diff --git a/.prettierrc b/.prettierrc index f5289b11c..f1c81e8d5 100644 --- a/.prettierrc +++ b/.prettierrc @@ -1,4 +1,5 @@ { + "arrowParens": "avoid", "endOfLine": "lf", "printWidth": 80, "semi": true, diff --git a/examples/acroforms/acroforms.js b/examples/acroforms/acroforms.js index bcf4dae3f..ef64248be 100644 --- a/examples/acroforms/acroforms.js +++ b/examples/acroforms/acroforms.js @@ -27,14 +27,14 @@ var eventBus = new pdfjsViewer.EventBus(); // Fetch the PDF document from the URL using promises. var loadingTask = pdfjsLib.getDocument(DEFAULT_URL); -loadingTask.promise.then(function(doc) { +loadingTask.promise.then(function (doc) { // Use a promise to fetch and render the next page. var promise = Promise.resolve(); for (var i = 1; i <= doc.numPages; i++) { promise = promise.then( - function(pageNum) { - return doc.getPage(pageNum).then(function(pdfPage) { + function (pageNum) { + return doc.getPage(pageNum).then(function (pdfPage) { // Create the page view. var pdfPageView = new pdfjsViewer.PDFPageView({ container: container, diff --git a/examples/browserify/gulpfile.js b/examples/browserify/gulpfile.js index 241f97f43..7d836e78f 100644 --- a/examples/browserify/gulpfile.js +++ b/examples/browserify/gulpfile.js @@ -8,7 +8,7 @@ var source = require("vinyl-source-stream"); var OUTPUT_PATH = "../../build/browserify"; var TMP_FILE_PREFIX = "../../build/browserify_"; -gulp.task("build-bundle", function() { +gulp.task("build-bundle", function () { return browserify("main.js", { output: TMP_FILE_PREFIX + "main.tmp" }) .ignore(require.resolve("pdfjs-dist/build/pdf.worker")) // Reducing size .bundle() @@ -18,7 +18,7 @@ gulp.task("build-bundle", function() { .pipe(gulp.dest(OUTPUT_PATH)); }); -gulp.task("build-worker", function() { +gulp.task("build-worker", function () { // We can create our own viewer (see worker.js) or use already defined one. var workerSrc = require.resolve("pdfjs-dist/build/pdf.worker.entry"); return browserify(workerSrc, { output: TMP_FILE_PREFIX + "worker.tmp" }) diff --git a/examples/browserify/main.js b/examples/browserify/main.js index 644a10140..eb515077d 100644 --- a/examples/browserify/main.js +++ b/examples/browserify/main.js @@ -14,9 +14,9 @@ pdfjsLib.GlobalWorkerOptions.workerSrc = // Loading a document. var loadingTask = pdfjsLib.getDocument(pdfPath); loadingTask.promise - .then(function(pdfDocument) { + .then(function (pdfDocument) { // Request a first page - return pdfDocument.getPage(1).then(function(pdfPage) { + return pdfDocument.getPage(1).then(function (pdfPage) { // Display page on the existing canvas with 100% scale. var viewport = pdfPage.getViewport({ scale: 1.0 }); var canvas = document.getElementById("theCanvas"); @@ -30,6 +30,6 @@ loadingTask.promise return renderTask.promise; }); }) - .catch(function(reason) { + .catch(function (reason) { console.error("Error: " + reason); }); diff --git a/examples/components/pageviewer.js b/examples/components/pageviewer.js index fd8297990..74791faf8 100644 --- a/examples/components/pageviewer.js +++ b/examples/components/pageviewer.js @@ -43,9 +43,9 @@ var loadingTask = pdfjsLib.getDocument({ cMapUrl: CMAP_URL, cMapPacked: CMAP_PACKED, }); -loadingTask.promise.then(function(pdfDocument) { +loadingTask.promise.then(function (pdfDocument) { // Document loaded, retrieving the page. - return pdfDocument.getPage(PAGE_TO_VIEW).then(function(pdfPage) { + return pdfDocument.getPage(PAGE_TO_VIEW).then(function (pdfPage) { // Creating the page view with default parameters. var pdfPageView = new pdfjsViewer.PDFPageView({ container: container, diff --git a/examples/components/simpleviewer.js b/examples/components/simpleviewer.js index 290a4f8cb..daec1c6e0 100644 --- a/examples/components/simpleviewer.js +++ b/examples/components/simpleviewer.js @@ -55,7 +55,7 @@ var pdfViewer = new pdfjsViewer.PDFViewer({ }); pdfLinkService.setViewer(pdfViewer); -eventBus.on("pagesinit", function() { +eventBus.on("pagesinit", function () { // We can use pdfViewer now, e.g. let's change default scale. pdfViewer.currentScaleValue = "page-width"; @@ -71,7 +71,7 @@ var loadingTask = pdfjsLib.getDocument({ cMapUrl: CMAP_URL, cMapPacked: CMAP_PACKED, }); -loadingTask.promise.then(function(pdfDocument) { +loadingTask.promise.then(function (pdfDocument) { // Document loaded, specifying document for the viewer and // the (optional) linkService. pdfViewer.setDocument(pdfDocument); diff --git a/examples/components/singlepageviewer.js b/examples/components/singlepageviewer.js index ff6460553..8d12380ca 100644 --- a/examples/components/singlepageviewer.js +++ b/examples/components/singlepageviewer.js @@ -55,7 +55,7 @@ var pdfSinglePageViewer = new pdfjsViewer.PDFSinglePageViewer({ }); pdfLinkService.setViewer(pdfSinglePageViewer); -eventBus.on("pagesinit", function() { +eventBus.on("pagesinit", function () { // We can use pdfSinglePageViewer now, e.g. let's change default scale. pdfSinglePageViewer.currentScaleValue = "page-width"; @@ -71,7 +71,7 @@ var loadingTask = pdfjsLib.getDocument({ cMapUrl: CMAP_URL, cMapPacked: CMAP_PACKED, }); -loadingTask.promise.then(function(pdfDocument) { +loadingTask.promise.then(function (pdfDocument) { // Document loaded, specifying document for the viewer and // the (optional) linkService. pdfSinglePageViewer.setDocument(pdfDocument); diff --git a/examples/mobile-viewer/viewer.js b/examples/mobile-viewer/viewer.js index befe718f6..e90210ec3 100644 --- a/examples/mobile-viewer/viewer.js +++ b/examples/mobile-viewer/viewer.js @@ -47,11 +47,11 @@ var PDFViewerApplication = { * @returns {Promise} - Returns the promise, which is resolved when document * is opened. */ - open: function(params) { + open: function (params) { if (this.pdfLoadingTask) { // We need to destroy already opened document return this.close().then( - function() { + function () { // ... and repeat the open() call. return this.open(params); }.bind(this) @@ -71,12 +71,12 @@ var PDFViewerApplication = { }); this.pdfLoadingTask = loadingTask; - loadingTask.onProgress = function(progressData) { + loadingTask.onProgress = function (progressData) { self.progress(progressData.loaded / progressData.total); }; return loadingTask.promise.then( - function(pdfDocument) { + function (pdfDocument) { // Document loaded, specifying document for the viewer. self.pdfDocument = pdfDocument; self.pdfViewer.setDocument(pdfDocument); @@ -86,7 +86,7 @@ var PDFViewerApplication = { self.loadingBar.hide(); self.setTitleUsingMetadata(pdfDocument); }, - function(exception) { + function (exception) { var message = exception && exception.message; var l10n = self.l10n; var loadingErrorMessage; @@ -119,7 +119,7 @@ var PDFViewerApplication = { ); } - loadingErrorMessage.then(function(msg) { + loadingErrorMessage.then(function (msg) { self.error(msg, { message: message }); }); self.loadingBar.hide(); @@ -132,7 +132,7 @@ var PDFViewerApplication = { * @returns {Promise} - Returns the promise, which is resolved when all * destruction is completed. */ - close: function() { + close: function () { var errorWrapper = document.getElementById("errorWrapper"); errorWrapper.setAttribute("hidden", "true"); @@ -175,9 +175,9 @@ var PDFViewerApplication = { this.setTitle(title); }, - setTitleUsingMetadata: function(pdfDocument) { + setTitleUsingMetadata: function (pdfDocument) { var self = this; - pdfDocument.getMetadata().then(function(data) { + pdfDocument.getMetadata().then(function (data) { var info = data.info, metadata = data.metadata; self.documentInfo = info; @@ -275,27 +275,27 @@ var PDFViewerApplication = { errorMessage.textContent = message; var closeButton = document.getElementById("errorClose"); - closeButton.onclick = function() { + closeButton.onclick = function () { errorWrapper.setAttribute("hidden", "true"); }; var errorMoreInfo = document.getElementById("errorMoreInfo"); var moreInfoButton = document.getElementById("errorShowMore"); var lessInfoButton = document.getElementById("errorShowLess"); - moreInfoButton.onclick = function() { + moreInfoButton.onclick = function () { errorMoreInfo.removeAttribute("hidden"); moreInfoButton.setAttribute("hidden", "true"); lessInfoButton.removeAttribute("hidden"); errorMoreInfo.style.height = errorMoreInfo.scrollHeight + "px"; }; - lessInfoButton.onclick = function() { + lessInfoButton.onclick = function () { errorMoreInfo.setAttribute("hidden", "true"); moreInfoButton.removeAttribute("hidden"); lessInfoButton.setAttribute("hidden", "true"); }; moreInfoButton.removeAttribute("hidden"); lessInfoButton.setAttribute("hidden", "true"); - Promise.all(moreInfoText).then(function(parts) { + Promise.all(moreInfoText).then(function (parts) { errorMoreInfo.value = parts.join("\n"); }); }, @@ -369,29 +369,31 @@ var PDFViewerApplication = { }); linkService.setHistory(this.pdfHistory); - document.getElementById("previous").addEventListener("click", function() { + document.getElementById("previous").addEventListener("click", function () { PDFViewerApplication.page--; }); - document.getElementById("next").addEventListener("click", function() { + document.getElementById("next").addEventListener("click", function () { PDFViewerApplication.page++; }); - document.getElementById("zoomIn").addEventListener("click", function() { + document.getElementById("zoomIn").addEventListener("click", function () { PDFViewerApplication.zoomIn(); }); - document.getElementById("zoomOut").addEventListener("click", function() { + document.getElementById("zoomOut").addEventListener("click", function () { PDFViewerApplication.zoomOut(); }); - document.getElementById("pageNumber").addEventListener("click", function() { - this.select(); - }); - document .getElementById("pageNumber") - .addEventListener("change", function() { + .addEventListener("click", function () { + this.select(); + }); + + document + .getElementById("pageNumber") + .addEventListener("change", function () { PDFViewerApplication.page = this.value | 0; // Ensure that the page number input displays the correct value, @@ -402,14 +404,14 @@ var PDFViewerApplication = { } }); - eventBus.on("pagesinit", function() { + eventBus.on("pagesinit", function () { // We can use pdfViewer now, e.g. let's change default scale. pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE; }); eventBus.on( "pagechanging", - function(evt) { + function (evt) { var page = evt.pageNumber; var numPages = PDFViewerApplication.pagesCount; @@ -424,7 +426,7 @@ var PDFViewerApplication = { document.addEventListener( "DOMContentLoaded", - function() { + function () { PDFViewerApplication.initUI(); }, true @@ -433,13 +435,15 @@ document.addEventListener( (function animationStartedClosure() { // The offsetParent is not set until the PDF.js iframe or object is visible. // Waiting for first animation. - PDFViewerApplication.animationStartedPromise = new Promise(function(resolve) { + PDFViewerApplication.animationStartedPromise = new Promise(function ( + resolve + ) { window.requestAnimationFrame(resolve); }); })(); // We need to delay opening until all HTML is loaded. -PDFViewerApplication.animationStartedPromise.then(function() { +PDFViewerApplication.animationStartedPromise.then(function () { PDFViewerApplication.open({ url: DEFAULT_URL, }); diff --git a/examples/node/domstubs.js b/examples/node/domstubs.js index dcf1720fc..3fdd02fd1 100644 --- a/examples/node/domstubs.js +++ b/examples/node/domstubs.js @@ -58,7 +58,7 @@ function DOMElement(name) { if (name === "style") { this.sheet = { cssRules: [], - insertRule: function(rule) { + insertRule: function (rule) { this.cssRules.push(rule); }, }; @@ -226,16 +226,16 @@ const document = { return this; }, - createElementNS: function(NS, element) { + createElementNS: function (NS, element) { var elObject = new DOMElement(element); return elObject; }, - createElement: function(element) { + createElement: function (element) { return this.createElementNS("", element); }, - getElementsByTagName: function(element) { + getElementsByTagName: function (element) { if (element === "head") { return [this.head || (this.head = new DOMElement("head"))]; } @@ -264,14 +264,14 @@ exports.Image = Image; var exported_symbols = Object.keys(exports); -exports.setStubs = function(namespace) { - exported_symbols.forEach(function(key) { +exports.setStubs = function (namespace) { + exported_symbols.forEach(function (key) { console.assert(!(key in namespace), "property should not be set: " + key); namespace[key] = exports[key]; }); }; -exports.unsetStubs = function(namespace) { - exported_symbols.forEach(function(key) { +exports.unsetStubs = function (namespace) { + exported_symbols.forEach(function (key) { console.assert(key in namespace, "property should be set: " + key); delete namespace[key]; }); diff --git a/examples/node/getinfo.js b/examples/node/getinfo.js index 31db3da19..f58bb02b8 100644 --- a/examples/node/getinfo.js +++ b/examples/node/getinfo.js @@ -17,14 +17,14 @@ var pdfPath = process.argv[2] || "../../web/compressed.tracemonkey-pldi-09.pdf"; // callback. var loadingTask = pdfjsLib.getDocument(pdfPath); loadingTask.promise - .then(function(doc) { + .then(function (doc) { var numPages = doc.numPages; console.log("# Document Loaded"); console.log("Number of Pages: " + numPages); console.log(); var lastPromise; // will be used to chain promises - lastPromise = doc.getMetadata().then(function(data) { + lastPromise = doc.getMetadata().then(function (data) { console.log("# Metadata Is Loaded"); console.log("## Info"); console.log(JSON.stringify(data.info, null, 2)); @@ -36,24 +36,24 @@ loadingTask.promise } }); - var loadPage = function(pageNum) { - return doc.getPage(pageNum).then(function(page) { + var loadPage = function (pageNum) { + return doc.getPage(pageNum).then(function (page) { console.log("# Page " + pageNum); var viewport = page.getViewport({ scale: 1.0 }); console.log("Size: " + viewport.width + "x" + viewport.height); console.log(); return page .getTextContent() - .then(function(content) { + .then(function (content) { // Content contains lots of information about the text layout and // styles, but we need only strings at the moment - var strings = content.items.map(function(item) { + var strings = content.items.map(function (item) { return item.str; }); console.log("## Text Content"); console.log(strings.join(" ")); }) - .then(function() { + .then(function () { console.log(); }); }); @@ -66,10 +66,10 @@ loadingTask.promise return lastPromise; }) .then( - function() { + function () { console.log("# End of Document"); }, - function(err) { + function (err) { console.error("Error: " + err); } ); diff --git a/examples/node/pdf2png/pdf2png.js b/examples/node/pdf2png/pdf2png.js index 9b84ddfbe..421a8a834 100644 --- a/examples/node/pdf2png/pdf2png.js +++ b/examples/node/pdf2png/pdf2png.js @@ -59,11 +59,11 @@ var rawData = new Uint8Array(fs.readFileSync(pdfURL)); // Load the PDF file. var loadingTask = pdfjsLib.getDocument(rawData); loadingTask.promise - .then(function(pdfDocument) { + .then(function (pdfDocument) { console.log("# PDF document loaded."); // Get the first page. - pdfDocument.getPage(1).then(function(page) { + pdfDocument.getPage(1).then(function (page) { // Render the page on a Node canvas with 100% scale. var viewport = page.getViewport({ scale: 1.0 }); var canvasFactory = new NodeCanvasFactory(); @@ -78,10 +78,10 @@ loadingTask.promise }; var renderTask = page.render(renderContext); - renderTask.promise.then(function() { + renderTask.promise.then(function () { // Convert the canvas to an image buffer. var image = canvasAndContext.canvas.toBuffer(); - fs.writeFile("output.png", image, function(error) { + fs.writeFile("output.png", image, function (error) { if (error) { console.error("Error: " + error); } else { @@ -93,6 +93,6 @@ loadingTask.promise }); }); }) - .catch(function(reason) { + .catch(function (reason) { console.log(reason); }); diff --git a/examples/node/pdf2svg.js b/examples/node/pdf2svg.js index 404b47601..472ebba69 100644 --- a/examples/node/pdf2svg.js +++ b/examples/node/pdf2svg.js @@ -54,7 +54,7 @@ function ReadableSVGStream(options) { } util.inherits(ReadableSVGStream, stream.Readable); // Implements https://nodejs.org/api/stream.html#stream_readable_read_size_1 -ReadableSVGStream.prototype._read = function() { +ReadableSVGStream.prototype._read = function () { var chunk; while ((chunk = this.serializer.getNext()) !== null) { if (!this.push(chunk)) { @@ -70,12 +70,12 @@ function writeSvgToFile(svgElement, filePath) { svgElement: svgElement, }); var writableStream = fs.createWriteStream(filePath); - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { readableSvgStream.once("error", reject); writableStream.once("error", reject); writableStream.once("finish", resolve); readableSvgStream.pipe(writableStream); - }).catch(function(err) { + }).catch(function (err) { readableSvgStream = null; // Explicitly null because of v8 bug 6512. writableStream.end(); throw err; @@ -91,29 +91,29 @@ var loadingTask = pdfjsLib.getDocument({ nativeImageDecoderSupport: pdfjsLib.NativeImageDecoding.DISPLAY, }); loadingTask.promise - .then(function(doc) { + .then(function (doc) { var numPages = doc.numPages; console.log("# Document Loaded"); console.log("Number of Pages: " + numPages); console.log(); var lastPromise = Promise.resolve(); // will be used to chain promises - var loadPage = function(pageNum) { - return doc.getPage(pageNum).then(function(page) { + var loadPage = function (pageNum) { + return doc.getPage(pageNum).then(function (page) { console.log("# Page " + pageNum); var viewport = page.getViewport({ scale: 1.0 }); console.log("Size: " + viewport.width + "x" + viewport.height); console.log(); - return page.getOperatorList().then(function(opList) { + return page.getOperatorList().then(function (opList) { var svgGfx = new pdfjsLib.SVGGraphics(page.commonObjs, page.objs); svgGfx.embedFonts = true; - return svgGfx.getSVG(opList, viewport).then(function(svg) { + return svgGfx.getSVG(opList, viewport).then(function (svg) { return writeSvgToFile(svg, getFilePathForPage(pageNum)).then( - function() { + function () { console.log("Page: " + pageNum); }, - function(err) { + function (err) { console.log("Error: " + err); } ); @@ -128,10 +128,10 @@ loadingTask.promise return lastPromise; }) .then( - function() { + function () { console.log("# End of Document"); }, - function(err) { + function (err) { console.error("Error: " + err); } ); diff --git a/examples/svgviewer/viewer.js b/examples/svgviewer/viewer.js index b7dec1e28..0ec51c29d 100644 --- a/examples/svgviewer/viewer.js +++ b/examples/svgviewer/viewer.js @@ -49,7 +49,7 @@ var pdfViewer = new pdfjsViewer.PDFViewer({ }); pdfLinkService.setViewer(pdfViewer); -eventBus.on("pagesinit", function() { +eventBus.on("pagesinit", function () { // We can use pdfViewer now, e.g. let's change default scale. pdfViewer.currentScaleValue = "page-width"; }); @@ -60,7 +60,7 @@ var loadingTask = pdfjsLib.getDocument({ cMapUrl: CMAP_URL, cMapPacked: CMAP_PACKED, }); -loadingTask.promise.then(function(pdfDocument) { +loadingTask.promise.then(function (pdfDocument) { // Document loaded, specifying document for the viewer and // the (optional) linkService. pdfViewer.setDocument(pdfDocument); diff --git a/examples/text-only/pdf2svg.js b/examples/text-only/pdf2svg.js index 51bfd2cd7..fd6e372fa 100644 --- a/examples/text-only/pdf2svg.js +++ b/examples/text-only/pdf2svg.js @@ -30,7 +30,7 @@ function buildSVG(viewport, textContent) { svg.setAttribute("font-size", 1); // processing all items - textContent.items.forEach(function(textItem) { + textContent.items.forEach(function (textItem) { // we have to take in account viewport transform, which includes scale, // rotation and Y-axis flip, and not forgetting to flip text. var tx = pdfjsLib.Util.transform( @@ -51,10 +51,10 @@ function buildSVG(viewport, textContent) { function pageLoaded() { // Loading document and page text content var loadingTask = pdfjsLib.getDocument({ url: PDF_PATH }); - loadingTask.promise.then(function(pdfDocument) { - pdfDocument.getPage(PAGE_NUMBER).then(function(page) { + loadingTask.promise.then(function (pdfDocument) { + pdfDocument.getPage(PAGE_NUMBER).then(function (page) { var viewport = page.getViewport({ scale: PAGE_SCALE }); - page.getTextContent().then(function(textContent) { + page.getTextContent().then(function (textContent) { // building SVG and adding that to the DOM var svg = buildSVG(viewport, textContent); document.getElementById("pageContainer").appendChild(svg); @@ -63,7 +63,7 @@ function pageLoaded() { }); } -document.addEventListener("DOMContentLoaded", function() { +document.addEventListener("DOMContentLoaded", function () { if (typeof pdfjsLib === "undefined") { alert( "Built version of PDF.js was not found.\n" + diff --git a/examples/webpack/main.js b/examples/webpack/main.js index 053bea8a0..942693c10 100644 --- a/examples/webpack/main.js +++ b/examples/webpack/main.js @@ -14,9 +14,9 @@ pdfjsLib.GlobalWorkerOptions.workerSrc = // Loading a document. var loadingTask = pdfjsLib.getDocument(pdfPath); loadingTask.promise - .then(function(pdfDocument) { + .then(function (pdfDocument) { // Request a first page - return pdfDocument.getPage(1).then(function(pdfPage) { + return pdfDocument.getPage(1).then(function (pdfPage) { // Display page on the existing canvas with 100% scale. var viewport = pdfPage.getViewport({ scale: 1.0 }); var canvas = document.getElementById("theCanvas"); @@ -30,6 +30,6 @@ loadingTask.promise return renderTask.promise; }); }) - .catch(function(reason) { + .catch(function (reason) { console.error("Error: " + reason); }); diff --git a/extensions/chromium/extension-router.js b/extensions/chromium/extension-router.js index 25aad2e48..c0ca26f1e 100644 --- a/extensions/chromium/extension-router.js +++ b/extensions/chromium/extension-router.js @@ -61,7 +61,7 @@ limitations under the License. // (or rewrite the query string parser in viewer.js to get it to // recognize the non-URL-encoded PDF URL.) chrome.webRequest.onBeforeRequest.addListener( - function(details) { + function (details) { // This listener converts chrome-extension://.../http://...pdf to // chrome-extension://.../content/web/viewer.html?file=http%3A%2F%2F...pdf var url = parseExtensionURL(details.url); @@ -78,7 +78,7 @@ limitations under the License. }, { types: ["main_frame", "sub_frame"], - urls: schemes.map(function(scheme) { + urls: schemes.map(function (scheme) { // Format: "chrome-extension://[EXTENSIONID]/*" return CRX_BASE_URL + scheme + "*"; }), @@ -94,7 +94,7 @@ limitations under the License. { url: CRX_BASE_URL + "*:*", }, - function(tabsFromLastSession) { + function (tabsFromLastSession) { for (var i = 0; i < tabsFromLastSession.length; ++i) { chrome.tabs.reload(tabsFromLastSession[i].id); } @@ -102,7 +102,7 @@ limitations under the License. ); console.log("Set up extension URL router."); - Object.keys(localStorage).forEach(function(key) { + Object.keys(localStorage).forEach(function (key) { // The localStorage item is set upon unload by chromecom.js. var parsedKey = /^unload-(\d+)-(true|false)-(.+)/.exec(key); if (parsedKey) { diff --git a/extensions/chromium/options/migration.js b/extensions/chromium/options/migration.js index 55700a519..25f660714 100644 --- a/extensions/chromium/options/migration.js +++ b/extensions/chromium/options/migration.js @@ -15,7 +15,7 @@ limitations under the License. */ /* eslint strict: ["error", "function"] */ -(function() { +(function () { "use strict"; var storageLocal = chrome.storage.local; var storageSync = chrome.storage.sync; @@ -25,8 +25,8 @@ limitations under the License. return; } - getStorageNames(function(storageKeys) { - storageLocal.get(storageKeys, function(values) { + getStorageNames(function (storageKeys) { + storageLocal.get(storageKeys, function (values) { if (!values || !Object.keys(values).length) { // No local storage - nothing to migrate. // ... except possibly for a renamed preference name. @@ -41,7 +41,7 @@ limitations under the License. var x = new XMLHttpRequest(); var schema_location = chrome.runtime.getManifest().storage.managed_schema; x.open("get", chrome.runtime.getURL(schema_location)); - x.onload = function() { + x.onload = function () { var storageKeys = Object.keys(x.response.properties); callback(storageKeys); }; @@ -52,7 +52,7 @@ limitations under the License. // Save |values| to storage.sync and delete the values with that key from // storage.local. function migrateToSyncStorage(values) { - storageSync.set(values, function() { + storageSync.set(values, function () { if (chrome.runtime.lastError) { console.error( "Failed to migrate settings due to an error: " + @@ -61,7 +61,7 @@ limitations under the License. return; } // Migration successful. Delete local settings. - storageLocal.remove(Object.keys(values), function() { + storageLocal.remove(Object.keys(values), function () { // In theory remove() could fail (e.g. if the browser's storage // backend is corrupt), but since storageSync.set succeeded, consider // the migration successful. @@ -89,7 +89,7 @@ limitations under the License. "disablePageMode", "viewOnLoad", ], - function(items) { + function (items) { // Migration code for https://github.com/mozilla/pdf.js/pull/7635. if (typeof items.enableHandToolOnLoad === "boolean") { if (items.enableHandToolOnLoad) { @@ -97,7 +97,7 @@ limitations under the License. { cursorToolOnLoad: 1, }, - function() { + function () { if (!chrome.runtime.lastError) { storageSync.remove("enableHandToolOnLoad"); } @@ -121,7 +121,7 @@ limitations under the License. { textLayerMode: textLayerMode, }, - function() { + function () { if (!chrome.runtime.lastError) { storageSync.remove([ "disableTextLayer", @@ -141,7 +141,7 @@ limitations under the License. { viewOnLoad: 1, }, - function() { + function () { if (!chrome.runtime.lastError) { storageSync.remove([ "showPreviousViewOnLoad", diff --git a/extensions/chromium/options/options.js b/extensions/chromium/options/options.js index 318ce89b8..27df162d5 100644 --- a/extensions/chromium/options/options.js +++ b/extensions/chromium/options/options.js @@ -25,13 +25,13 @@ Promise.all([ return; } // Get preferences as set by the system administrator. - chrome.storage.managed.get(null, function(prefs) { + chrome.storage.managed.get(null, function (prefs) { // Managed storage may be disabled, e.g. in Opera. resolve(prefs || {}); }); }), new Promise(function getUserPrefs(resolve) { - storageArea.get(null, function(prefs) { + storageArea.get(null, function (prefs) { resolve(prefs || {}); }); }), @@ -40,14 +40,14 @@ Promise.all([ var x = new XMLHttpRequest(); var schema_location = chrome.runtime.getManifest().storage.managed_schema; x.open("get", chrome.runtime.getURL(schema_location)); - x.onload = function() { + x.onload = function () { resolve(x.response.properties); }; x.responseType = "json"; x.send(); }), ]) - .then(function(values) { + .then(function (values) { var managedPrefs = values[0]; var userPrefs = values[1]; var schema = values[2]; @@ -62,7 +62,7 @@ Promise.all([ var prefNames = Object.keys(schema); var renderPreferenceFunctions = {}; // Render options - prefNames.forEach(function(prefName) { + prefNames.forEach(function (prefName) { var prefSchema = schema[prefName]; if (!prefSchema.title) { // Don't show preferences if the title is missing. @@ -102,17 +102,17 @@ Promise.all([ var renderedPrefNames = Object.keys(renderPreferenceFunctions); // Reset button to restore default settings. - document.getElementById("reset-button").onclick = function() { + document.getElementById("reset-button").onclick = function () { userPrefs = {}; - storageArea.remove(prefNames, function() { - renderedPrefNames.forEach(function(prefName) { + storageArea.remove(prefNames, function () { + renderedPrefNames.forEach(function (prefName) { renderPreferenceFunctions[prefName](getPrefValue(prefName)); }); }); }; // Automatically update the UI when the preferences were changed elsewhere. - chrome.storage.onChanged.addListener(function(changes, areaName) { + chrome.storage.onChanged.addListener(function (changes, areaName) { var prefs = null; if (areaName === storageAreaName) { prefs = userPrefs; @@ -120,7 +120,7 @@ Promise.all([ prefs = managedPrefs; } if (prefs) { - renderedPrefNames.forEach(function(prefName) { + renderedPrefNames.forEach(function (prefName) { var prefChanges = changes[prefName]; if (prefChanges) { if ("newValue" in prefChanges) { @@ -149,7 +149,7 @@ function renderBooleanPref(shortDescription, description, prefName) { wrapper.title = description; var checkbox = wrapper.querySelector('input[type="checkbox"]'); - checkbox.onchange = function() { + checkbox.onchange = function () { var pref = {}; pref[prefName] = this.checked; storageArea.set(pref); @@ -166,7 +166,7 @@ function renderBooleanPref(shortDescription, description, prefName) { function renderEnumPref(shortDescription, prefName) { var wrapper = importTemplate(prefName + "-template"); var select = wrapper.querySelector("select"); - select.onchange = function() { + select.onchange = function () { var pref = {}; pref[prefName] = parseInt(this.value); storageArea.set(pref); @@ -183,7 +183,7 @@ function renderEnumPref(shortDescription, prefName) { function renderDefaultZoomValue(shortDescription) { var wrapper = importTemplate("defaultZoomValue-template"); var select = wrapper.querySelector("select"); - select.onchange = function() { + select.onchange = function () { storageArea.set({ defaultZoomValue: this.value, }); diff --git a/extensions/chromium/pageAction/background.js b/extensions/chromium/pageAction/background.js index 38766ae38..ab9b259db 100644 --- a/extensions/chromium/pageAction/background.js +++ b/extensions/chromium/pageAction/background.js @@ -37,7 +37,7 @@ limitations under the License. } } - chrome.runtime.onMessage.addListener(function(message, sender) { + chrome.runtime.onMessage.addListener(function (message, sender) { if (message === "showPageAction" && sender.tab) { showPageAction(sender.tab.id, sender.tab.url); } diff --git a/extensions/chromium/pdfHandler-vcros.js b/extensions/chromium/pdfHandler-vcros.js index b09065bfa..1fe3102d2 100644 --- a/extensions/chromium/pdfHandler-vcros.js +++ b/extensions/chromium/pdfHandler-vcros.js @@ -16,7 +16,7 @@ limitations under the License. /* eslint strict: ["error", "function"] */ /* import-globals-from pdfHandler.js */ -(function() { +(function () { "use strict"; if (!chrome.fileBrowserHandler) { @@ -41,12 +41,12 @@ limitations under the License. // the other Chrome APIs that use "tabId" (http://crbug.com/179767) var tabId = details.tab_id || details.tabId; if (tabId > 0) { - chrome.tabs.get(tabId, function(tab) { + chrome.tabs.get(tabId, function (tab) { openViewer(tab && tab.windowId, fileEntries); }); } else { // Re-use existing window, if available. - chrome.windows.getLastFocused(function(chromeWindow) { + chrome.windows.getLastFocused(function (chromeWindow) { var windowId = chromeWindow && chromeWindow.id; if (windowId) { chrome.windows.update(windowId, { focused: true }); @@ -82,7 +82,7 @@ limitations under the License. active: true, url: url, }, - function() { + function () { openViewer(windowId, fileEntries); } ); @@ -93,7 +93,7 @@ limitations under the License. focused: true, url: url, }, - function(chromeWindow) { + function (chromeWindow) { openViewer(chromeWindow.id, fileEntries); } ); diff --git a/extensions/chromium/pdfHandler.js b/extensions/chromium/pdfHandler.js index 6eefcbe2c..22d819e80 100644 --- a/extensions/chromium/pdfHandler.js +++ b/extensions/chromium/pdfHandler.js @@ -73,10 +73,7 @@ function getHeaderFromHeaders(headers, headerName) { function isPdfFile(details) { var header = getHeaderFromHeaders(details.responseHeaders, "content-type"); if (header) { - var headerValue = header.value - .toLowerCase() - .split(";", 1)[0] - .trim(); + var headerValue = header.value.toLowerCase().split(";", 1)[0].trim(); if (headerValue === "application/pdf") { return true; } @@ -120,7 +117,7 @@ function getHeadersWithContentDispositionAttachment(details) { } chrome.webRequest.onHeadersReceived.addListener( - function(details) { + function (details) { if (details.method !== "GET") { // Don't intercept POST requests until http://crbug.com/104058 is fixed. return undefined; @@ -148,7 +145,7 @@ chrome.webRequest.onHeadersReceived.addListener( ); chrome.webRequest.onBeforeRequest.addListener( - function(details) { + function (details) { if (isPdfDownloadable(details)) { return undefined; } @@ -176,7 +173,7 @@ chrome.webRequest.onBeforeRequest.addListener( ["blocking"] ); -chrome.extension.isAllowedFileSchemeAccess(function(isAllowedAccess) { +chrome.extension.isAllowedFileSchemeAccess(function (isAllowedAccess) { if (isAllowedAccess) { return; } @@ -186,7 +183,7 @@ chrome.extension.isAllowedFileSchemeAccess(function(isAllowedAccess) { // The viewer will detect that it has no access to file:-URLs, and prompt the // user to activate file permissions. chrome.webNavigation.onBeforeNavigate.addListener( - function(details) { + function (details) { if (details.frameId === 0 && !isPdfDownloadable(details)) { chrome.tabs.update(details.tabId, { url: getViewerURL(details.url), @@ -208,7 +205,7 @@ chrome.extension.isAllowedFileSchemeAccess(function(isAllowedAccess) { ); }); -chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) { +chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) { if (message && message.action === "getParentOrigin") { // getParentOrigin is used to determine whether it is safe to embed a // sensitive (local) file in a frame. diff --git a/extensions/chromium/preserve-referer.js b/extensions/chromium/preserve-referer.js index 4a5ac8b0a..aff414852 100644 --- a/extensions/chromium/preserve-referer.js +++ b/extensions/chromium/preserve-referer.js @@ -43,7 +43,7 @@ var g_referrers = {}; var extraInfoSpecWithHeaders; // = ['requestHeaders', 'extraHeaders'] -(function() { +(function () { var requestFilter = { urls: ["*://*/*"], types: ["main_frame", "sub_frame"], @@ -52,7 +52,7 @@ var extraInfoSpecWithHeaders; // = ['requestHeaders', 'extraHeaders'] extraInfoSpecWithHeaders = extraInfoSpec; // May throw if the given extraInfoSpec is unsupported. chrome.webRequest.onSendHeaders.addListener( - function(details) { + function (details) { g_requestHeaders[details.requestId] = details.requestHeaders; }, requestFilter, @@ -87,7 +87,7 @@ function saveReferer(details) { g_referrers[details.tabId][details.frameId] = referer; } -chrome.tabs.onRemoved.addListener(function(tabId) { +chrome.tabs.onRemoved.addListener(function (tabId) { delete g_referrers[tabId]; }); @@ -108,7 +108,7 @@ chrome.runtime.onConnect.addListener(function onReceivePort(port) { // If the PDF is viewed for the first time, then the referer will be set here. var referer = (g_referrers[tabId] && g_referrers[tabId][frameId]) || ""; - port.onMessage.addListener(function(data) { + port.onMessage.addListener(function (data) { // If the viewer was opened directly (without opening a PDF URL first), then // the background script does not know about g_referrers, but the viewer may // know about the referer if stored in the history state (see chromecom.js). @@ -133,7 +133,7 @@ chrome.runtime.onConnect.addListener(function onReceivePort(port) { }); // The port is only disconnected when the other end reloads. - port.onDisconnect.addListener(function() { + port.onDisconnect.addListener(function () { if (g_referrers[tabId]) { delete g_referrers[tabId][frameId]; } diff --git a/extensions/chromium/suppress-update.js b/extensions/chromium/suppress-update.js index 79398b457..009651d9e 100644 --- a/extensions/chromium/suppress-update.js +++ b/extensions/chromium/suppress-update.js @@ -19,7 +19,7 @@ limitations under the License. // Do not reload the extension when an update becomes available, UNLESS the PDF // viewer is not displaying any PDF files. Otherwise the tabs would close, which // is quite disruptive (crbug.com/511670). -chrome.runtime.onUpdateAvailable.addListener(function() { +chrome.runtime.onUpdateAvailable.addListener(function () { if (chrome.extension.getViews({ type: "tab" }).length === 0) { chrome.runtime.reload(); } diff --git a/extensions/chromium/telemetry.js b/extensions/chromium/telemetry.js index 2328bb22f..d6fe1c0a4 100644 --- a/extensions/chromium/telemetry.js +++ b/extensions/chromium/telemetry.js @@ -15,7 +15,7 @@ limitations under the License. */ /* eslint strict: ["error", "function"] */ -(function() { +(function () { "use strict"; // This module sends the browser and extension version to a server, to // determine whether it is safe to drop support for old Chrome versions in @@ -46,7 +46,7 @@ limitations under the License. setInterval(maybeSendPing, 36e5); function maybeSendPing() { - getLoggingPref(function(didOptOut) { + getLoggingPref(function (didOptOut) { if (didOptOut) { // Respect the user's decision to not send statistics. return; @@ -154,7 +154,7 @@ limitations under the License. return; } - chrome.storage[storageAreaName].get("disableTelemetry", function(items) { + chrome.storage[storageAreaName].get("disableTelemetry", function (items) { next(items && items.disableTelemetry); }); } diff --git a/extensions/firefox/tools/l10n.js b/extensions/firefox/tools/l10n.js index 5e0d56fab..383764512 100644 --- a/extensions/firefox/tools/l10n.js +++ b/extensions/firefox/tools/l10n.js @@ -1,7 +1,7 @@ "use strict"; // Small subset of the webL10n API by Fabien Cazenave for PDF.js extension. -(function(window) { +(function (window) { var gLanguage = ""; var gExternalLocalizerServices = null; var gReadyState = "loading"; @@ -21,7 +21,7 @@ if (!args) { return text; } - return text.replace(/\{\{\s*(\w+)\s*\}\}/g, function(all, name) { + return text.replace(/\{\{\s*(\w+)\s*\}\}/g, function (all, name) { return name in args ? args[name] : "{{" + name + "}}"; }); } diff --git a/external/builder/builder.js b/external/builder/builder.js index e11d883e0..a2d37a365 100644 --- a/external/builder/builder.js +++ b/external/builder/builder.js @@ -34,10 +34,7 @@ var fs = require("fs"), */ function preprocess(inFilename, outFilename, defines) { // TODO make this really read line by line. - var lines = fs - .readFileSync(inFilename) - .toString() - .split("\n"); + var lines = fs.readFileSync(inFilename).toString().split("\n"); var totalLines = lines.length; var out = ""; var i = 0; @@ -50,7 +47,7 @@ function preprocess(inFilename, outFilename, defines) { var writeLine = typeof outFilename === "function" ? outFilename - : function(line) { + : function (line) { out += line + "\n"; }; function evaluateCondition(code) { @@ -95,7 +92,7 @@ function preprocess(inFilename, outFilename, defines) { } } function expand(line) { - line = line.replace(/__[\w]+__/g, function(variable) { + line = line.replace(/__[\w]+__/g, function (variable) { variable = variable.substring(2, variable.length - 2); if (variable in defines) { return defines[variable]; @@ -122,7 +119,7 @@ function preprocess(inFilename, outFilename, defines) { var stack = []; var control = /^(?:\/\/|)?$)?/; var lineNumber = 0; - var loc = function() { + var loc = function () { return fs.realpathSync(inFilename) + ":" + lineNumber; }; while ((line = readLine()) !== null) { @@ -215,7 +212,7 @@ function preprocessCSS(mode, source, destination) { } function expandImports(content, baseUrl) { - return content.replace(/^\s*@import\s+url\(([^\)]+)\);\s*$/gm, function( + return content.replace(/^\s*@import\s+url\(([^\)]+)\);\s*$/gm, function ( all, url ) { diff --git a/external/builder/preprocessor2.js b/external/builder/preprocessor2.js index 699f48df1..9be29c8b3 100644 --- a/external/builder/preprocessor2.js +++ b/external/builder/preprocessor2.js @@ -294,7 +294,7 @@ function traverseTree(ctx, node) { node[i] = result; } } else if (Array.isArray(child)) { - child.forEach(function(childItem, index) { + child.forEach(function (childItem, index) { if ( typeof childItem === "object" && childItem !== null && diff --git a/external/builder/test-fixtures.js b/external/builder/test-fixtures.js index d1c151f09..f23480abf 100644 --- a/external/builder/test-fixtures.js +++ b/external/builder/test-fixtures.js @@ -9,13 +9,13 @@ var errors = 0; var baseDir = path.join(__dirname, "fixtures"); var files = fs .readdirSync(baseDir) - .filter(function(name) { + .filter(function (name) { return /-expected\./.test(name); }) - .map(function(name) { + .map(function (name) { return path.join(baseDir, name); }); -files.forEach(function(expectationFilename) { +files.forEach(function (expectationFilename) { var inFilename = expectationFilename.replace("-expected", ""); var expectation = fs .readFileSync(expectationFilename) @@ -24,7 +24,7 @@ files.forEach(function(expectationFilename) { .replace(/__filename/g, fs.realpathSync(inFilename)); var outLines = []; - var outFilename = function(line) { + var outFilename = function (line) { outLines.push(line); }; var defines = { diff --git a/external/builder/test-fixtures_esprima.js b/external/builder/test-fixtures_esprima.js index c4ccdf9c0..3f8523038 100644 --- a/external/builder/test-fixtures_esprima.js +++ b/external/builder/test-fixtures_esprima.js @@ -9,13 +9,13 @@ var errors = 0; var baseDir = path.join(__dirname, "fixtures_esprima"); var files = fs .readdirSync(baseDir) - .filter(function(name) { + .filter(function (name) { return /-expected\./.test(name); }) - .map(function(name) { + .map(function (name) { return path.join(baseDir, name); }); -files.forEach(function(expectationFilename) { +files.forEach(function (expectationFilename) { var inFilename = expectationFilename.replace("-expected", ""); var expectation = fs .readFileSync(expectationFilename) diff --git a/external/importL10n/locales.js b/external/importL10n/locales.js index a05d1584a..a54d19d54 100644 --- a/external/importL10n/locales.js +++ b/external/importL10n/locales.js @@ -36,15 +36,15 @@ function downloadLanguageCodes() { var ALL_LOCALES = "https://hg.mozilla.org/mozilla-central/raw-file/tip/browser/locales/all-locales"; - return new Promise(function(resolve) { - https.get(ALL_LOCALES, function(response) { + return new Promise(function (resolve) { + https.get(ALL_LOCALES, function (response) { if (response.statusCode === 200) { var content = ""; response.setEncoding("utf8"); - response.on("data", function(chunk) { + response.on("data", function (chunk) { content += chunk; }); - response.on("end", function() { + response.on("end", function () { content = content.trim(); // Remove any leading/trailing white-space. var langCodes = normalizeText(content).split("\n"); // Remove all locales that we don't want to download below. @@ -80,22 +80,22 @@ function downloadLanguageFiles(root, langCode) { fs.mkdirSync(outputDir); } - return new Promise(function(resolve) { + return new Promise(function (resolve) { // Download the necessary files for this language. - files.forEach(function(fileName) { + files.forEach(function (fileName) { var outputPath = path.join(outputDir, fileName); var url = MOZ_CENTRAL_ROOT + langCode + MOZ_CENTRAL_PDFJS_DIR + fileName; - https.get(url, function(response) { + https.get(url, function (response) { // Not all files exist for each language. Files without translations // have been removed (https://bugzilla.mozilla.org/show_bug.cgi?id=1443175). if (response.statusCode === 200) { var content = ""; response.setEncoding("utf8"); - response.on("data", function(chunk) { + response.on("data", function (chunk) { content += chunk; }); - response.on("end", function() { + response.on("end", function () { fs.writeFileSync(outputPath, normalizeText(content), "utf8"); if (--downloadsLeft === 0) { resolve(); diff --git a/external/systemjs/plugin-babel-cached.js b/external/systemjs/plugin-babel-cached.js index 170a7f446..622ebd47e 100644 --- a/external/systemjs/plugin-babel-cached.js +++ b/external/systemjs/plugin-babel-cached.js @@ -22,17 +22,17 @@ var dbPromise; function getDb() { if (!dbPromise) { - dbPromise = new Promise(function(resolve, reject) { + dbPromise = new Promise(function (resolve, reject) { var request = indexedDB.open(dbName, dbVersion); - request.onupgradeneeded = function() { + request.onupgradeneeded = function () { var db = request.result; db.createObjectStore(dbCacheTable, { keyPath: "address" }); }; - request.onsuccess = function() { + request.onsuccess = function () { var db = request.result; resolve(db); }; - request.onerror = function() { + request.onerror = function () { console.warn("getDb: " + request.error); reject(request.error); }; @@ -42,7 +42,7 @@ function getDb() { } function storeCache(address, hashCode, translated, format) { - return getDb().then(function(db) { + return getDb().then(function (db) { var tx = db.transaction(dbCacheTable, "readwrite"); var store = tx.objectStore(dbCacheTable); store.put({ @@ -52,11 +52,11 @@ function storeCache(address, hashCode, translated, format) { expires: Date.now() + cacheExpiration, format: format, }); - return new Promise(function(resolve, reject) { - tx.oncomplete = function() { + return new Promise(function (resolve, reject) { + tx.oncomplete = function () { resolve(); }; - tx.onerror = function() { + tx.onerror = function () { resolve(); }; }); @@ -64,12 +64,12 @@ function storeCache(address, hashCode, translated, format) { } function loadCache(address, hashCode) { - return getDb().then(function(db) { + return getDb().then(function (db) { var tx = db.transaction(dbCacheTable, "readonly"); var store = tx.objectStore(dbCacheTable); var getAddress = store.get(address); - return new Promise(function(resolve, reject) { - tx.oncomplete = function() { + return new Promise(function (resolve, reject) { + tx.oncomplete = function () { var found = getAddress.result; var isValid = found && found.hashCode === hashCode && Date.now() < found.expires; @@ -82,7 +82,7 @@ function loadCache(address, hashCode) { : null ); }; - tx.onerror = function() { + tx.onerror = function () { resolve(null); }; }); @@ -92,7 +92,7 @@ function loadCache(address, hashCode) { var encoder = new TextEncoder("utf-8"); function sha256(str) { var buffer = encoder.encode(str); - return crypto.subtle.digest("SHA-256", buffer).then(function(hash) { + return crypto.subtle.digest("SHA-256", buffer).then(function (hash) { var data = new Int32Array(hash); return ( data[0].toString(36) + @@ -106,38 +106,38 @@ function sha256(str) { }); } -exports.translate = function(load, opt) { +exports.translate = function (load, opt) { var savedHashCode, babelTranslateError; return sha256(load.source) - .then(function(hashCode) { + .then(function (hashCode) { savedHashCode = hashCode; return loadCache(load.address, hashCode); }) .then( - function(cache) { + function (cache) { if (cache) { load.metadata.format = cache.format; return cache.translated; } return babel.translate.call(this, load, opt).then( - function(translated) { + function (translated) { return storeCache( load.address, savedHashCode, translated, load.metadata.format - ).then(function() { + ).then(function () { return translated; }); }, - function(reason) { + function (reason) { throw (babelTranslateError = reason); } ); }.bind(this) ) .catch( - function(reason) { + function (reason) { if (babelTranslateError) { throw babelTranslateError; } diff --git a/external/webpack/pdfjsdev-loader.js b/external/webpack/pdfjsdev-loader.js index 7434b5f0a..1bbcacf71 100644 --- a/external/webpack/pdfjsdev-loader.js +++ b/external/webpack/pdfjsdev-loader.js @@ -19,7 +19,7 @@ var preprocessor2 = require("../builder/preprocessor2.js"); var path = require("path"); -module.exports = function(source) { +module.exports = function (source) { // Options must be specified, ignoring request if not. if (!this.query || typeof this.query !== "object") { return source; @@ -28,10 +28,7 @@ module.exports = function(source) { var filePath = this.resourcePath; var context = this.rootContext; - var sourcePath = path - .relative(context, filePath) - .split(path.sep) - .join("/"); + var sourcePath = path.relative(context, filePath).split(path.sep).join("/"); var ctx = Object.create(this.query); ctx.sourceMap = true; diff --git a/gulpfile.js b/gulpfile.js index 45cee3646..cea77ecef 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -105,7 +105,7 @@ var DEFINES = { }; function transform(charEncoding, transformFunction) { - return through.obj(function(vinylFile, enc, done) { + return through.obj(function (vinylFile, enc, done) { var transformedFile = vinylFile.clone(); transformedFile.contents = Buffer.from( transformFunction(transformedFile.contents), @@ -154,7 +154,7 @@ function startNode(args, options) { function createStringSource(filename, content) { var source = stream.Readable({ objectMode: true }); - source._read = function() { + source._read = function () { this.push( new Vinyl({ path: filename, @@ -253,7 +253,7 @@ function getVersionJSON() { function checkChromePreferencesFile(chromePrefsPath, webPrefsPath) { var chromePrefs = JSON.parse(fs.readFileSync(chromePrefsPath).toString()); var chromePrefsKeys = Object.keys(chromePrefs.properties); - chromePrefsKeys = chromePrefsKeys.filter(function(key) { + chromePrefsKeys = chromePrefsKeys.filter(function (key) { var description = chromePrefs.properties[key].description; // Deprecated keys are allowed in the managed preferences file. // The code maintained is responsible for adding migration logic to @@ -274,7 +274,7 @@ function checkChromePreferencesFile(chromePrefsPath, webPrefsPath) { if (webPrefsKeys.length !== chromePrefsKeys.length) { return false; } - return webPrefsKeys.every(function(value, index) { + return webPrefsKeys.every(function (value, index) { return ( chromePrefsKeys[index] === value && chromePrefs.properties[value].default === webPrefs[value] @@ -402,9 +402,7 @@ function replaceInFile(filePath, find, replacement) { function getTempFile(prefix, suffix) { mkdirp.sync(BUILD_DIR + "tmp/"); - var bytes = require("crypto") - .randomBytes(6) - .toString("hex"); + var bytes = require("crypto").randomBytes(6).toString("hex"); var filePath = BUILD_DIR + "tmp/" + prefix + bytes + suffix; fs.writeFileSync(filePath, ""); return filePath; @@ -412,7 +410,7 @@ function getTempFile(prefix, suffix) { function createTestSource(testsName, bot) { var source = stream.Readable({ objectMode: true }); - source._read = function() { + source._read = function () { console.log(); console.log("### Running " + testsName + " tests"); @@ -456,7 +454,7 @@ function createTestSource(testsName, bot) { } var testProcess = startNode(args, { cwd: TEST_DIR, stdio: "inherit" }); - testProcess.on("close", function(code) { + testProcess.on("close", function (code) { source.push(null); }); return undefined; @@ -489,26 +487,26 @@ function makeRef(done, bot) { } args.push("--browserManifestFile=" + PDF_BROWSERS); var testProcess = startNode(args, { cwd: TEST_DIR, stdio: "inherit" }); - testProcess.on("close", function(code) { + testProcess.on("close", function (code) { done(); }); } -gulp.task("default", function(done) { +gulp.task("default", function (done) { console.log("Available tasks:"); var tasks = Object.keys(gulp.registry().tasks()); tasks.sort(); - tasks.forEach(function(taskName) { + tasks.forEach(function (taskName) { console.log(" " + taskName); }); done(); }); -gulp.task("buildnumber", function(done) { +gulp.task("buildnumber", function (done) { console.log(); console.log("### Getting extension build number"); - exec("git log --format=oneline " + config.baseVersion + "..", function( + exec("git log --format=oneline " + config.baseVersion + "..", function ( err, stdout, stderr @@ -525,7 +523,7 @@ gulp.task("buildnumber", function(done) { var version = config.versionPrefix + buildNumber; - exec('git log --format="%h" -n 1', function(err2, stdout2, stderr2) { + exec('git log --format="%h" -n 1', function (err2, stdout2, stderr2) { var buildCommit = ""; if (!err2) { buildCommit = stdout2.replace("\n", ""); @@ -549,7 +547,7 @@ gulp.task("buildnumber", function(done) { }); }); -gulp.task("default_preferences-pre", function() { +gulp.task("default_preferences-pre", function () { console.log(); console.log("### Building `default_preferences.json`"); @@ -610,7 +608,7 @@ gulp.task("default_preferences-pre", function() { gulp.task( "default_preferences", - gulp.series("default_preferences-pre", function(done) { + gulp.series("default_preferences-pre", function (done) { var AppOptionsLib = require("./" + DEFAULT_PREFERENCES_DIR + "lib/web/app_options.js"); @@ -626,7 +624,7 @@ gulp.task( }) ); -gulp.task("locale", function() { +gulp.task("locale", function () { var VIEWER_LOCALE_OUTPUT = "web/locale/"; console.log(); @@ -677,7 +675,7 @@ gulp.task("locale", function() { ]); }); -gulp.task("cmaps", function(done) { +gulp.task("cmaps", function (done) { var CMAP_INPUT = "external/cmaps"; var VIEWER_CMAP_OUTPUT = "external/bcmaps"; @@ -692,7 +690,7 @@ gulp.task("cmaps", function(done) { } // Remove old bcmap files. - fs.readdirSync(VIEWER_CMAP_OUTPUT).forEach(function(file) { + fs.readdirSync(VIEWER_CMAP_OUTPUT).forEach(function (file) { if (/\.bcmap$/i.test(file)) { fs.unlinkSync(VIEWER_CMAP_OUTPUT + "/" + file); } @@ -706,7 +704,7 @@ gulp.task("cmaps", function(done) { gulp.task( "bundle", - gulp.series("buildnumber", function() { + gulp.series("buildnumber", function () { return createBundle(DEFINES).pipe(gulp.dest(BUILD_DIR)); }) ); @@ -775,7 +773,7 @@ function buildGeneric(defines, dir) { // HTML5 browsers, which implement modern ECMAScript features. gulp.task( "generic", - gulp.series("buildnumber", "default_preferences", "locale", function() { + gulp.series("buildnumber", "default_preferences", "locale", function () { console.log(); console.log("### Creating generic viewer"); var defines = builder.merge(DEFINES, { GENERIC: true }); @@ -788,7 +786,7 @@ gulp.task( // older HTML5 browsers. gulp.task( "generic-es5", - gulp.series("buildnumber", "default_preferences", "locale", function() { + gulp.series("buildnumber", "default_preferences", "locale", function () { console.log(); console.log("### Creating generic (ES5) viewer"); var defines = builder.merge(DEFINES, { GENERIC: true, SKIP_BABEL: false }); @@ -824,7 +822,7 @@ function buildComponents(defines, dir) { gulp.task( "components", - gulp.series("buildnumber", function() { + gulp.series("buildnumber", function () { console.log(); console.log("### Creating generic components"); var defines = builder.merge(DEFINES, { COMPONENTS: true, GENERIC: true }); @@ -835,7 +833,7 @@ gulp.task( gulp.task( "components-es5", - gulp.series("buildnumber", function() { + gulp.series("buildnumber", function () { console.log(); console.log("### Creating generic (ES5) components"); var defines = builder.merge(DEFINES, { @@ -850,7 +848,7 @@ gulp.task( gulp.task( "image_decoders", - gulp.series("buildnumber", function() { + gulp.series("buildnumber", function () { console.log(); console.log("### Creating image decoders"); var defines = builder.merge(DEFINES, { @@ -866,7 +864,7 @@ gulp.task( gulp.task( "minified-pre", - gulp.series("buildnumber", "default_preferences", "locale", function() { + gulp.series("buildnumber", "default_preferences", "locale", function () { console.log(); console.log("### Creating minified viewer"); var defines = builder.merge(DEFINES, { MINIFIED: true, GENERIC: true }); @@ -916,7 +914,7 @@ gulp.task( gulp.task( "minified-post", - gulp.series("minified-pre", function(done) { + gulp.series("minified-pre", function (done) { var pdfFile = fs.readFileSync(MINIFIED_DIR + "/build/pdf.js").toString(); var pdfWorkerFile = fs .readFileSync(MINIFIED_DIR + "/build/pdf.worker.js") @@ -1008,7 +1006,7 @@ function preprocessDefaultPreferences(content) { gulp.task( "mozcentral-pre", - gulp.series("buildnumber", "default_preferences", function() { + gulp.series("buildnumber", "default_preferences", function () { console.log(); console.log("### Building mozilla-central extension"); var defines = builder.merge(DEFINES, { MOZCENTRAL: true }); @@ -1075,7 +1073,7 @@ gulp.task("mozcentral", gulp.series("mozcentral-pre")); gulp.task( "chromium-pre", - gulp.series("buildnumber", "default_preferences", "locale", function() { + gulp.series("buildnumber", "default_preferences", "locale", function () { console.log(); console.log("### Building Chromium extension"); var defines = builder.merge(DEFINES, { CHROME: true, SKIP_BABEL: false }); @@ -1138,14 +1136,14 @@ gulp.task( gulp.task("chromium", gulp.series("chromium-pre")); -gulp.task("jsdoc", function(done) { +gulp.task("jsdoc", function (done) { console.log(); console.log("### Generating documentation (JSDoc)"); var JSDOC_FILES = ["src/doc_helper.js", "src/display/api.js"]; - rimraf(JSDOC_BUILD_DIR, function() { - mkdirp(JSDOC_BUILD_DIR).then(function() { + rimraf(JSDOC_BUILD_DIR, function () { + mkdirp(JSDOC_BUILD_DIR).then(function () { var command = '"node_modules/.bin/jsdoc" -d ' + JSDOC_BUILD_DIR + @@ -1238,7 +1236,7 @@ function buildLib(defines, dir) { gulp.task( "lib", - gulp.series("buildnumber", "default_preferences", function() { + gulp.series("buildnumber", "default_preferences", function () { var defines = builder.merge(DEFINES, { GENERIC: true, LIB: true }); return buildLib(defines, "build/lib/"); @@ -1247,7 +1245,7 @@ gulp.task( gulp.task( "lib-es5", - gulp.series("buildnumber", "default_preferences", function() { + gulp.series("buildnumber", "default_preferences", function () { var defines = builder.merge(DEFINES, { GENERIC: true, LIB: true, @@ -1263,14 +1261,14 @@ function compressPublish(targetName, dir) { .src(dir + "**") .pipe(zip(targetName)) .pipe(gulp.dest(BUILD_DIR)) - .on("end", function() { + .on("end", function () { console.log("Built distribution file: " + targetName); }); } gulp.task( "publish", - gulp.series("generic", "generic-es5", function(done) { + gulp.series("generic", "generic-es5", function (done) { var version = JSON.parse( fs.readFileSync(BUILD_DIR + "version.json").toString() ).version; @@ -1288,14 +1286,14 @@ gulp.task( }) ); -gulp.task("testing-pre", function(done) { +gulp.task("testing-pre", function (done) { process.env["TESTING"] = "true"; done(); }); gulp.task( "test", - gulp.series("testing-pre", "generic", "components", function() { + gulp.series("testing-pre", "generic", "components", function () { return streamqueue( { objectMode: true }, createTestSource("unit"), @@ -1306,7 +1304,7 @@ gulp.task( gulp.task( "bottest", - gulp.series("testing-pre", "generic", "components", function() { + gulp.series("testing-pre", "generic", "components", function () { return streamqueue( { objectMode: true }, createTestSource("unit", true), @@ -1318,40 +1316,40 @@ gulp.task( gulp.task( "browsertest", - gulp.series("testing-pre", "generic", "components", function() { + gulp.series("testing-pre", "generic", "components", function () { return createTestSource("browser"); }) ); gulp.task( "unittest", - gulp.series("testing-pre", "generic", "components", function() { + gulp.series("testing-pre", "generic", "components", function () { return createTestSource("unit"); }) ); gulp.task( "fonttest", - gulp.series("testing-pre", function() { + gulp.series("testing-pre", function () { return createTestSource("font"); }) ); gulp.task( "makeref", - gulp.series("testing-pre", "generic", "components", function(done) { + gulp.series("testing-pre", "generic", "components", function (done) { makeRef(done); }) ); gulp.task( "botmakeref", - gulp.series("testing-pre", "generic", "components", function(done) { + gulp.series("testing-pre", "generic", "components", function (done) { makeRef(done, true); }) ); -gulp.task("baseline", function(done) { +gulp.task("baseline", function (done) { console.log(); console.log("### Creating baseline environment"); @@ -1368,13 +1366,13 @@ gulp.task("baseline", function(done) { } var workingDirectory = path.resolve(process.cwd(), BASELINE_DIR); - exec(initializeCommand, { cwd: workingDirectory }, function(error) { + exec(initializeCommand, { cwd: workingDirectory }, function (error) { if (error) { done(new Error("Baseline clone/fetch failed.")); return; } - exec("git checkout " + baselineCommit, { cwd: workingDirectory }, function( + exec("git checkout " + baselineCommit, { cwd: workingDirectory }, function ( error2 ) { if (error2) { @@ -1390,13 +1388,13 @@ gulp.task("baseline", function(done) { gulp.task( "unittestcli", - gulp.series("testing-pre", "lib-es5", function(done) { + gulp.series("testing-pre", "lib-es5", function (done) { var options = [ "node_modules/jasmine/bin/jasmine", "JASMINE_CONFIG_PATH=test/unit/clitests.json", ]; var jasmineProcess = startNode(options, { stdio: "inherit" }); - jasmineProcess.on("close", function(code) { + jasmineProcess.on("close", function (code) { if (code !== 0) { done(new Error("Unit tests failed.")); return; @@ -1406,7 +1404,7 @@ gulp.task( }) ); -gulp.task("lint", function(done) { +gulp.task("lint", function (done) { console.log(); console.log("### Linting JS files"); @@ -1422,7 +1420,7 @@ gulp.task("lint", function(done) { options.push("--fix"); } var esLintProcess = startNode(options, { stdio: "inherit" }); - esLintProcess.on("close", function(code) { + esLintProcess.on("close", function (code) { if (code !== 0) { done(new Error("ESLint failed.")); return; @@ -1434,7 +1432,7 @@ gulp.task("lint", function(done) { gulp.task( "lint-chromium", - gulp.series("default_preferences", function(done) { + gulp.series("default_preferences", function (done) { console.log(); console.log("### Checking supplemental Chromium files"); @@ -1451,7 +1449,7 @@ gulp.task( }) ); -gulp.task("server", function() { +gulp.task("server", function () { console.log(); console.log("### Starting local server"); @@ -1461,14 +1459,14 @@ gulp.task("server", function() { server.start(); }); -gulp.task("clean", function(done) { +gulp.task("clean", function (done) { console.log(); console.log("### Cleaning up project builds"); rimraf(BUILD_DIR, done); }); -gulp.task("makefile", function() { +gulp.task("makefile", function () { var makefileContent = "help:\n\tgulp\n\n"; var targetsNames = []; for (var i in target) { @@ -1479,7 +1477,7 @@ gulp.task("makefile", function() { return createStringSource("Makefile", makefileContent).pipe(gulp.dest(".")); }); -gulp.task("importl10n", function(done) { +gulp.task("importl10n", function (done) { var locales = require("./external/importL10n/locales.js"); console.log(); @@ -1491,7 +1489,7 @@ gulp.task("importl10n", function(done) { locales.downloadL10n(L10N_DIR, done); }); -gulp.task("gh-pages-prepare", function() { +gulp.task("gh-pages-prepare", function () { console.log(); console.log("### Creating web site"); @@ -1514,10 +1512,10 @@ gulp.task("gh-pages-prepare", function() { ]); }); -gulp.task("wintersmith", function(done) { +gulp.task("wintersmith", function (done) { var wintersmith = require("wintersmith"); var env = wintersmith("docs/config.json"); - env.build(GH_PAGES_DIR, function(error) { + env.build(GH_PAGES_DIR, function (error) { if (error) { done(error); return; @@ -1552,7 +1550,7 @@ gulp.task("wintersmith", function(done) { }); }); -gulp.task("gh-pages-git", function(done) { +gulp.task("gh-pages-git", function (done) { var VERSION = getVersionJSON().version; var reason = process.env["PDFJS_UPDATE_REASON"]; @@ -1601,7 +1599,7 @@ gulp.task( "image_decoders", "lib", "minified", - function() { + function () { var VERSION = getVersionJSON().version; console.log(); @@ -1719,7 +1717,7 @@ gulp.task( gulp.task( "dist-install", - gulp.series("dist-pre", function(done) { + gulp.series("dist-pre", function (done) { var distPath = DIST_DIR; var opts = {}; var installPath = process.env["PDFJS_INSTALL_PATH"]; @@ -1734,7 +1732,7 @@ gulp.task( gulp.task( "dist-repo-git", - gulp.series("dist-pre", function(done) { + gulp.series("dist-pre", function (done) { var VERSION = getVersionJSON().version; console.log(); @@ -1777,7 +1775,7 @@ gulp.task("dist", gulp.series("dist-repo-git")); gulp.task( "mozcentralbaseline", - gulp.series("baseline", function(done) { + gulp.series("baseline", function (done) { console.log(); console.log("### Creating mozcentral baseline environment"); @@ -1798,7 +1796,7 @@ gulp.task( gulp .src([BASELINE_DIR + BUILD_DIR + "mozcentral/**/*"]) .pipe(gulp.dest(MOZCENTRAL_BASELINE_DIR)) - .on("end", function() { + .on("end", function () { // Commit the mozcentral baseline. safeSpawnSync("git", ["init"], { cwd: MOZCENTRAL_BASELINE_DIR }); safeSpawnSync("git", ["add", "."], { cwd: MOZCENTRAL_BASELINE_DIR }); @@ -1812,7 +1810,7 @@ gulp.task( gulp.task( "mozcentraldiff", - gulp.series("mozcentral", "mozcentralbaseline", function(done) { + gulp.series("mozcentral", "mozcentralbaseline", function (done) { console.log(); console.log("### Creating mozcentral diff"); @@ -1826,7 +1824,7 @@ gulp.task( gulp .src([BUILD_DIR + "mozcentral/**/*"]) .pipe(gulp.dest(MOZCENTRAL_BASELINE_DIR)) - .on("end", function() { + .on("end", function () { safeSpawnSync("git", ["add", "-A"], { cwd: MOZCENTRAL_BASELINE_DIR }); var diff = safeSpawnSync( "git", @@ -1836,7 +1834,7 @@ gulp.task( createStringSource(MOZCENTRAL_DIFF_FILE, diff) .pipe(gulp.dest(BUILD_DIR)) - .on("end", function() { + .on("end", function () { console.log( "Result diff can be found at " + BUILD_DIR + MOZCENTRAL_DIFF_FILE ); @@ -1846,7 +1844,7 @@ gulp.task( }) ); -gulp.task("externaltest", function(done) { +gulp.task("externaltest", function (done) { fancylog("Running test-fixtures.js"); safeSpawnSync("node", ["external/builder/test-fixtures.js"], { stdio: "inherit", diff --git a/package-lock.json b/package-lock.json index f4c128f2b..497243456 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11310,9 +11310,9 @@ "dev": true }, "prettier": { - "version": "1.19.1", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.19.1.tgz", - "integrity": "sha512-s7PoyDv/II1ObgQunCbB9PdLmUcBZcnWOcxDh7O0N/UwDEsHyqkW+Qh28jW+mVuCdx7gLB0BotYI1Y6uI9iyew==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.0.4.tgz", + "integrity": "sha512-SVJIQ51spzFDvh4fIbCLvciiDMCrRhlN3mbZvv/+ycjvmF5E73bKdGfU8QDLNmjYJf+lsGnDBC4UUnvTe5OO0w==", "dev": true }, "prettier-linter-helpers": { diff --git a/package.json b/package.json index 8107b7334..7fc2ac6e1 100644 --- a/package.json +++ b/package.json @@ -37,7 +37,7 @@ "mkdirp": "^1.0.3", "postcss-calc": "^7.0.2", "postcss-css-variables": "^0.14.0", - "prettier": "^1.19.1", + "prettier": "^2.0.4", "rimraf": "^2.7.1", "streamqueue": "^1.1.2", "systemjs": "^0.21.6", diff --git a/src/core/annotation.js b/src/core/annotation.js index f1dd0146e..ab31be32f 100644 --- a/src/core/annotation.js +++ b/src/core/annotation.js @@ -503,7 +503,7 @@ class Annotation { } const objectLoader = new ObjectLoader(resources, keys, resources.xref); - return objectLoader.load().then(function() { + return objectLoader.load().then(function () { return resources; }); }); @@ -941,7 +941,7 @@ class TextWidgetAnnotation extends WidgetAnnotation { resources: this.fieldResources, operatorList, }) - .then(function() { + .then(function () { return operatorList; }); } diff --git a/src/core/ccitt_stream.js b/src/core/ccitt_stream.js index 4140a30fd..bef561e0e 100644 --- a/src/core/ccitt_stream.js +++ b/src/core/ccitt_stream.js @@ -47,7 +47,7 @@ var CCITTFaxStream = (function CCITTFaxStreamClosure() { CCITTFaxStream.prototype = Object.create(DecodeStream.prototype); - CCITTFaxStream.prototype.readBlock = function() { + CCITTFaxStream.prototype.readBlock = function () { while (!this.eof) { const c = this.ccittFaxDecoder.readNextChar(); if (c === -1) { diff --git a/src/core/chunked_stream.js b/src/core/chunked_stream.js index 7cd136994..7da4bd3c9 100644 --- a/src/core/chunked_stream.js +++ b/src/core/chunked_stream.js @@ -280,7 +280,7 @@ class ChunkedStream { function ChunkedStreamSubstream() {} ChunkedStreamSubstream.prototype = Object.create(this); - ChunkedStreamSubstream.prototype.getMissingChunks = function() { + ChunkedStreamSubstream.prototype.getMissingChunks = function () { const chunkSize = this.chunkSize; const beginChunk = Math.floor(this.start / chunkSize); const endChunk = Math.floor((this.end - 1) / chunkSize) + 1; @@ -292,7 +292,7 @@ class ChunkedStream { } return missingChunks; }; - ChunkedStreamSubstream.prototype.allChunksLoaded = function() { + ChunkedStreamSubstream.prototype.allChunksLoaded = function () { if (this.numChunksLoaded === this.numChunks) { return true; } @@ -454,7 +454,7 @@ class ChunkedStreamManager { } } - chunksToRequest.sort(function(a, b) { + chunksToRequest.sort(function (a, b) { return a - b; }); return this._requestChunks(chunksToRequest); diff --git a/src/core/cmap.js b/src/core/cmap.js index 6a663fcc4..608fb8fb1 100644 --- a/src/core/cmap.js +++ b/src/core/cmap.js @@ -530,7 +530,7 @@ var BinaryCMapReader = (function BinaryCMapReaderClosure() { }; function processBinaryCMap(data, cMap, extend) { - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { var stream = new BinaryCMapStream(data); var header = stream.readByte(); cMap.vertical = !!(header & 1); @@ -934,7 +934,9 @@ var CMapFactory = (function CMapFactoryClosure() { } function extendCMap(cMap, fetchBuiltInCMap, useCMap) { - return createBuiltInCMap(useCMap, fetchBuiltInCMap).then(function(newCMap) { + return createBuiltInCMap(useCMap, fetchBuiltInCMap).then(function ( + newCMap + ) { cMap.useCMap = newCMap; // If there aren't any code space ranges defined clone all the parent ones // into this cMap. @@ -947,7 +949,7 @@ var CMapFactory = (function CMapFactoryClosure() { } // Merge the map into the current one, making sure not to override // any previously defined entries. - cMap.useCMap.forEach(function(key, value) { + cMap.useCMap.forEach(function (key, value) { if (!cMap.contains(key)) { cMap.mapOne(key, cMap.useCMap.lookup(key)); } @@ -972,13 +974,13 @@ var CMapFactory = (function CMapFactoryClosure() { ); } - return fetchBuiltInCMap(name).then(function(data) { + return fetchBuiltInCMap(name).then(function (data) { var cMapData = data.cMapData, compressionType = data.compressionType; var cMap = new CMap(true); if (compressionType === CMapCompressionType.BINARY) { - return new BinaryCMapReader().process(cMapData, cMap, function( + return new BinaryCMapReader().process(cMapData, cMap, function ( useCMap ) { return extendCMap(cMap, fetchBuiltInCMap, useCMap); @@ -1007,7 +1009,7 @@ var CMapFactory = (function CMapFactoryClosure() { } else if (isStream(encoding)) { var cMap = new CMap(); var lexer = new Lexer(encoding); - return parseCMap(cMap, lexer, fetchBuiltInCMap, useCMap).then(function( + return parseCMap(cMap, lexer, fetchBuiltInCMap, useCMap).then(function ( parsedCMap ) { if (parsedCMap.isIdentityCMap) { diff --git a/src/core/core_utils.js b/src/core/core_utils.js index dd20bf006..71c992d3f 100644 --- a/src/core/core_utils.js +++ b/src/core/core_utils.js @@ -18,7 +18,7 @@ import { assert, BaseException, warn } from "../shared/util.js"; function getLookupTableFactory(initializer) { let lookup; - return function() { + return function () { if (initializer) { lookup = Object.create(null); initializer(lookup); diff --git a/src/core/document.js b/src/core/document.js index 42532db16..e5dacd31c 100644 --- a/src/core/document.js +++ b/src/core/document.js @@ -282,7 +282,7 @@ class Page { resources: this.resources, operatorList: opList, }) - .then(function() { + .then(function () { return opList; }); }); @@ -290,7 +290,7 @@ class Page { // Fetch the page's annotations and add their operator lists to the // page's operator list to render them. return Promise.all([pageListPromise, this._parsedAnnotations]).then( - function([pageOpList, annotations]) { + function ([pageOpList, annotations]) { if (annotations.length === 0) { pageOpList.flush(true); return { length: pageOpList.totalLength }; @@ -311,7 +311,7 @@ class Page { } } - return Promise.all(opListPromises).then(function(opLists) { + return Promise.all(opListPromises).then(function (opLists) { pageOpList.addOp(OPS.beginAnnotations, []); for (const opList of opLists) { pageOpList.addOpList(opList); @@ -366,7 +366,7 @@ class Page { } getAnnotationsData(intent) { - return this._parsedAnnotations.then(function(annotations) { + return this._parsedAnnotations.then(function (annotations) { const annotationsData = []; for (let i = 0, ii = annotations.length; i < ii; i++) { if (!intent || isAnnotationRenderable(annotations[i], intent)) { @@ -403,12 +403,12 @@ class Page { } return Promise.all(annotationPromises).then( - function(annotations) { + function (annotations) { return annotations.filter(function isDefined(annotation) { return !!annotation; }); }, - function(reason) { + function (reason) { warn(`_parsedAnnotations: "${reason}".`); return []; } diff --git a/src/core/evaluator.js b/src/core/evaluator.js index a39bc2055..df5b10225 100644 --- a/src/core/evaluator.js +++ b/src/core/evaluator.js @@ -127,9 +127,9 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { }); const reader = readableStream.getReader(); - const data = await new Promise(function(resolve, reject) { + const data = await new Promise(function (resolve, reject) { function pump() { - reader.read().then(function({ value, done }) { + reader.read().then(function ({ value, done }) { if (done) { return; } @@ -432,7 +432,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { resources: dict.get("Resources") || resources, operatorList, initialState, - }).then(function() { + }).then(function () { operatorList.addOp(OPS.paintFormXObjectEnd, []); if (group) { @@ -566,7 +566,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { image.getIR(this.options.forceDataSchema), ]) .then( - function() { + function () { // Only add the dependency once we know that the native JPEG // decoding succeeded, to ensure that rendering will always // complete. @@ -738,7 +738,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { resources: patternResources, operatorList: tilingOpList, }) - .then(function() { + .then(function () { return getTilingPatternIR( { fnArray: tilingOpList.fnArray, @@ -749,7 +749,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { ); }) .then( - function(tilingPatternIR) { + function (tilingPatternIR) { // Add the dependencies to the parent operator list so they are // resolved before the sub operator list is executed synchronously. operatorList.addDependencies(tilingOpList.dependencies); @@ -795,7 +795,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { } return translated .loadType3Data(this, resources, operatorList, task) - .then(function() { + .then(function () { return translated; }) .catch(reason => { @@ -896,7 +896,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { operatorList, task, stateManager.state - ).then(function(loadedName) { + ).then(function (loadedName) { operatorList.addDependency(loadedName); gStateObj.push([key, [loadedName, value[1]]]); }); @@ -950,7 +950,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { break; } } - return promise.then(function() { + return promise.then(function () { if (gStateObj.length > 0) { operatorList.addOp(OPS.setGState, [gStateObj]); } @@ -985,8 +985,9 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { } } if (!fontRef) { - const partialMsg = `Font "${fontName || - (font && font.toString())}" is not available`; + const partialMsg = `Font "${ + fontName || (font && font.toString()) + }" is not available`; if (!this.options.ignoreErrors && !this.parsingType3Font) { warn(`${partialMsg}.`); @@ -1275,8 +1276,8 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { } return new Promise(function promiseBody(resolve, reject) { - const next = function(promise) { - Promise.all([promise, operatorList.ready]).then(function() { + const next = function (promise) { + Promise.all([promise, operatorList.ready]).then(function () { try { promiseBody(resolve, reject); } catch (ex) { @@ -1314,7 +1315,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { } next( - new Promise(function(resolveXObject, rejectXObject) { + new Promise(function (resolveXObject, rejectXObject) { if (!name) { throw new FormatError( "XObject must be referred to by name." @@ -1347,7 +1348,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { task, stateManager.state.clone() ) - .then(function() { + .then(function () { stateManager.restore(); resolveXObject(); }, rejectXObject); @@ -1373,7 +1374,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { ); } resolveXObject(); - }).catch(function(reason) { + }).catch(function (reason) { if (reason instanceof AbortException) { return; } @@ -1403,7 +1404,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { task, stateManager.state ) - .then(function(loadedName) { + .then(function (loadedName) { operatorList.addDependency(loadedName); operatorList.addOp(OPS.setFont, [loadedName, fontSize]); }) @@ -1497,7 +1498,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { cs: args[0], resources, }) - .then(function(colorSpace) { + .then(function (colorSpace) { if (colorSpace) { stateManager.state.fillColorSpace = colorSpace; } @@ -1511,7 +1512,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { cs: args[0], resources, }) - .then(function(colorSpace) { + .then(function (colorSpace) { if (colorSpace) { stateManager.state.strokeColorSpace = colorSpace; } @@ -1875,7 +1876,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { function handleSetFont(fontName, fontRef) { return self .loadFont(fontName, fontRef, resources) - .then(function(translated) { + .then(function (translated) { textState.font = translated.font; textState.fontMatrix = translated.font.fontMatrix || FONT_IDENTITY_MATRIX; @@ -1983,9 +1984,9 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { var timeSlotManager = new TimeSlotManager(); return new Promise(function promiseBody(resolve, reject) { - const next = function(promise) { + const next = function (promise) { enqueueChunk(); - Promise.all([promise, sink.ready]).then(function() { + Promise.all([promise, sink.ready]).then(function () { try { promiseBody(resolve, reject); } catch (ex) { @@ -2236,7 +2237,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { } next( - new Promise(function(resolveXObject, rejectXObject) { + new Promise(function (resolveXObject, rejectXObject) { if (!name) { throw new FormatError( "XObject must be referred to by name." @@ -2307,13 +2308,13 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { sink: sinkWrapper, seenStyles, }) - .then(function() { + .then(function () { if (!sinkWrapper.enqueueInvoked) { skipEmptyXObjs[name] = true; } resolveXObject(); }, rejectXObject); - }).catch(function(reason) { + }).catch(function (reason) { if (reason instanceof AbortException) { return; } @@ -2673,10 +2674,10 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { encoding: ucs2CMapName, fetchBuiltInCMap: this.fetchBuiltInCMap, useCMap: null, - }).then(function(ucs2CMap) { + }).then(function (ucs2CMap) { const cMap = properties.cMap; const toUnicode = []; - cMap.forEach(function(charcode, cid) { + cMap.forEach(function (charcode, cid) { if (cid > 0xffff) { throw new FormatError("Max size of CID is 65,535"); } @@ -2706,7 +2707,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { encoding: cmapObj, fetchBuiltInCMap: this.fetchBuiltInCMap, useCMap: null, - }).then(function(cmap) { + }).then(function (cmap) { if (cmap instanceof IdentityCMap) { return new IdentityToUnicodeMap(0, 0xffff); } @@ -2718,7 +2719,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { fetchBuiltInCMap: this.fetchBuiltInCMap, useCMap: null, }).then( - function(cmap) { + function (cmap) { if (cmap instanceof IdentityCMap) { return new IdentityToUnicodeMap(0, 0xffff); } @@ -2726,7 +2727,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { // Convert UTF-16BE // NOTE: cmap can be a sparse array, so use forEach instead of // `for(;;)` to iterate over all keys. - cmap.forEach(function(charCode, token) { + cmap.forEach(function (charCode, token) { var str = []; for (var k = 0; k < token.length; k += 2) { var w1 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1); @@ -3212,7 +3213,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { encoding: cidEncoding, fetchBuiltInCMap: this.fetchBuiltInCMap, useCMap: null, - }).then(function(cMap) { + }).then(function (cMap) { properties.cMap = cMap; properties.vertical = properties.cMap.vertical; }); @@ -3235,7 +3236,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { }, }; - PartialEvaluator.buildFontPaths = function(font, glyphs, handler) { + PartialEvaluator.buildFontPaths = function (font, glyphs, handler) { function buildPath(fontChar) { if (font.renderer.hasBuiltPath(fontChar)) { return; @@ -3261,7 +3262,7 @@ var PartialEvaluator = (function PartialEvaluatorClosure() { // TODO: Change this to a `static` getter, using shadowing, once // `PartialEvaluator` is converted to a proper class. - PartialEvaluator.getFallbackFontDict = function() { + PartialEvaluator.getFallbackFontDict = function () { if (this._fallbackFontDict) { return this._fallbackFontDict; } @@ -3346,7 +3347,7 @@ class TranslatedFont { for (var i = 0, n = charProcKeys.length; i < n; ++i) { const key = charProcKeys[i]; - loadCharProcsPromise = loadCharProcsPromise.then(function() { + loadCharProcsPromise = loadCharProcsPromise.then(function () { var glyphStream = charProcs.get(key); var operatorList = new OperatorList(); return type3Evaluator @@ -3356,21 +3357,21 @@ class TranslatedFont { resources: fontResources, operatorList, }) - .then(function() { + .then(function () { charProcOperatorList[key] = operatorList.getIR(); // Add the dependencies to the parent operator list so they are // resolved before sub operator list is executed synchronously. parentOperatorList.addDependencies(operatorList.dependencies); }) - .catch(function(reason) { + .catch(function (reason) { warn(`Type3 font resource "${key}" is not available.`); const dummyOperatorList = new OperatorList(); charProcOperatorList[key] = dummyOperatorList.getIR(); }); }); } - this.type3Loaded = loadCharProcsPromise.then(function() { + this.type3Loaded = loadCharProcsPromise.then(function () { translatedFont.charProcOperatorList = charProcOperatorList; }); return this.type3Loaded; @@ -3530,7 +3531,7 @@ var EvaluatorPreprocessor = (function EvaluatorPreprocessorClosure() { // // If variableArgs === true: [0, `numArgs`] expected // If variableArgs === false: exactly `numArgs` expected - var getOPMap = getLookupTableFactory(function(t) { + var getOPMap = getLookupTableFactory(function (t) { // Graphic state t["w"] = { id: OPS.setLineWidth, numArgs: 1, variableArgs: false }; t["J"] = { id: OPS.setLineCap, numArgs: 1, variableArgs: false }; diff --git a/src/core/fonts.js b/src/core/fonts.js index 2580b18ee..f50c838d3 100644 --- a/src/core/fonts.js +++ b/src/core/fonts.js @@ -283,7 +283,7 @@ var Glyph = (function GlyphClosure() { this.isInFont = isInFont; } - Glyph.prototype.matchesForCache = function( + Glyph.prototype.matchesForCache = function ( fontChar, unicode, accent, @@ -694,7 +694,7 @@ var Font = (function FontClosure() { this.seacMap = properties.seacMap; } - Font.getFontID = (function() { + Font.getFontID = (function () { var ID = 1; return function Font_getFontID() { return String(ID++); @@ -1367,7 +1367,7 @@ var Font = (function FontClosure() { var isIdentityUnicode = this.toUnicode instanceof IdentityToUnicodeMap; if (!isIdentityUnicode) { - this.toUnicode.forEach(function(charCode, unicodeCharCode) { + this.toUnicode.forEach(function (charCode, unicodeCharCode) { map[+charCode] = unicodeCharCode; }); } @@ -1775,7 +1775,7 @@ var Font = (function FontClosure() { } // removing duplicate entries - mappings.sort(function(a, b) { + mappings.sort(function (a, b) { return a.charCode - b.charCode; }); for (i = 1; i < mappings.length; i++) { @@ -2764,7 +2764,7 @@ var Font = (function FontClosure() { var cidToGidMap = properties.cidToGidMap || []; var isCidToGidMapEmpty = cidToGidMap.length === 0; - properties.cMap.forEach(function(charCode, cid) { + properties.cMap.forEach(function (charCode, cid) { if (cid > 0xffff) { throw new FormatError("Max size of CID is 65,535"); } diff --git a/src/core/function.js b/src/core/function.js index a54395524..e6f264a2c 100644 --- a/src/core/function.js +++ b/src/core/function.js @@ -159,7 +159,7 @@ var PDFFunction = (function PDFFunctionClosure() { this.parse({ xref, isEvalSupported, fn: xref.fetchIfRef(fnObj[j]) }) ); } - return function(src, srcOffset, dest, destOffset) { + return function (src, srcOffset, dest, destOffset) { for (var i = 0, ii = fnArray.length; i < ii; i++) { fnArray[i](src, srcOffset, dest, destOffset + i); } @@ -873,7 +873,7 @@ var PostScriptCompiler = (function PostScriptCompilerClosure() { function AstNode(type) { this.type = type; } - AstNode.prototype.visit = function(visitor) { + AstNode.prototype.visit = function (visitor) { unreachable("abstract method"); }; @@ -884,7 +884,7 @@ var PostScriptCompiler = (function PostScriptCompilerClosure() { this.max = max; } AstArgument.prototype = Object.create(AstNode.prototype); - AstArgument.prototype.visit = function(visitor) { + AstArgument.prototype.visit = function (visitor) { visitor.visitArgument(this); }; @@ -895,7 +895,7 @@ var PostScriptCompiler = (function PostScriptCompilerClosure() { this.max = number; } AstLiteral.prototype = Object.create(AstNode.prototype); - AstLiteral.prototype.visit = function(visitor) { + AstLiteral.prototype.visit = function (visitor) { visitor.visitLiteral(this); }; @@ -908,7 +908,7 @@ var PostScriptCompiler = (function PostScriptCompilerClosure() { this.max = max; } AstBinaryOperation.prototype = Object.create(AstNode.prototype); - AstBinaryOperation.prototype.visit = function(visitor) { + AstBinaryOperation.prototype.visit = function (visitor) { visitor.visitBinaryOperation(this); }; @@ -919,7 +919,7 @@ var PostScriptCompiler = (function PostScriptCompilerClosure() { this.max = max; } AstMin.prototype = Object.create(AstNode.prototype); - AstMin.prototype.visit = function(visitor) { + AstMin.prototype.visit = function (visitor) { visitor.visitMin(this); }; @@ -930,7 +930,7 @@ var PostScriptCompiler = (function PostScriptCompilerClosure() { this.max = max; } AstVariable.prototype = Object.create(AstNode.prototype); - AstVariable.prototype.visit = function(visitor) { + AstVariable.prototype.visit = function (visitor) { visitor.visitVariable(this); }; @@ -940,7 +940,7 @@ var PostScriptCompiler = (function PostScriptCompilerClosure() { this.arg = arg; } AstVariableDefinition.prototype = Object.create(AstNode.prototype); - AstVariableDefinition.prototype.visit = function(visitor) { + AstVariableDefinition.prototype.visit = function (visitor) { visitor.visitVariableDefinition(this); }; @@ -1245,12 +1245,12 @@ var PostScriptCompiler = (function PostScriptCompilerClosure() { } var result = []; - instructions.forEach(function(instruction) { + instructions.forEach(function (instruction) { var statementBuilder = new ExpressionBuilderVisitor(); instruction.visit(statementBuilder); result.push(statementBuilder.toString()); }); - stack.forEach(function(expr, i) { + stack.forEach(function (expr, i) { var statementBuilder = new ExpressionBuilderVisitor(); expr.visit(statementBuilder); var min = range[i * 2], diff --git a/src/core/glyphlist.js b/src/core/glyphlist.js index f9b6c58ab..307880d04 100644 --- a/src/core/glyphlist.js +++ b/src/core/glyphlist.js @@ -16,7 +16,7 @@ var getLookupTableFactory = require("./core_utils.js").getLookupTableFactory; -var getGlyphsUnicode = getLookupTableFactory(function(t) { +var getGlyphsUnicode = getLookupTableFactory(function (t) { t["A"] = 0x0041; t["AE"] = 0x00c6; t["AEacute"] = 0x01fc; @@ -4343,7 +4343,7 @@ var getGlyphsUnicode = getLookupTableFactory(function(t) { t["vextendsingle"] = 0x2223; }); -var getDingbatsGlyphsUnicode = getLookupTableFactory(function(t) { +var getDingbatsGlyphsUnicode = getLookupTableFactory(function (t) { t["space"] = 0x0020; t["a1"] = 0x2701; t["a2"] = 0x2702; diff --git a/src/core/image.js b/src/core/image.js index 6e87e7bf0..d0cecd766 100644 --- a/src/core/image.js +++ b/src/core/image.js @@ -265,7 +265,7 @@ var PDFImage = (function PDFImageClosure() { * Handles processing of image data and returns the Promise that is resolved * with a PDFImage when the image is ready to be used. */ - PDFImage.buildImage = function({ + PDFImage.buildImage = function ({ handler, xref, res, @@ -300,7 +300,7 @@ var PDFImage = (function PDFImageClosure() { } } return Promise.all([imagePromise, smaskPromise, maskPromise]).then( - function([imageData, smaskData, maskData]) { + function ([imageData, smaskData, maskData]) { return new PDFImage({ xref, res, @@ -314,7 +314,7 @@ var PDFImage = (function PDFImageClosure() { ); }; - PDFImage.createMask = function({ + PDFImage.createMask = function ({ imgArray, width, height, diff --git a/src/core/image_utils.js b/src/core/image_utils.js index 294ec14a2..6fddb543d 100644 --- a/src/core/image_utils.js +++ b/src/core/image_utils.js @@ -62,7 +62,7 @@ class NativeImageDecoder { image.getIR(this.forceDataSchema), colorSpace.numComps, ]) - .then(function({ data, width, height }) { + .then(function ({ data, width, height }) { return new Stream(data, 0, data.length, dict); }); } diff --git a/src/core/jbig2.js b/src/core/jbig2.js index aeaed334d..31e05ab19 100644 --- a/src/core/jbig2.js +++ b/src/core/jbig2.js @@ -371,7 +371,7 @@ var Jbig2Image = (function Jbig2ImageClosure() { // Sorting is non-standard, and it is not required. But sorting increases // the number of template bits that can be reused from the previous // contextLabel in the main loop. - template.sort(function(a, b) { + template.sort(function (a, b) { return a.y - b.y || a.x - b.x; }); diff --git a/src/core/jbig2_stream.js b/src/core/jbig2_stream.js index ac0490bc3..5d5af33d1 100644 --- a/src/core/jbig2_stream.js +++ b/src/core/jbig2_stream.js @@ -43,12 +43,12 @@ const Jbig2Stream = (function Jbig2StreamClosure() { configurable: true, }); - Jbig2Stream.prototype.ensureBuffer = function(requested) { + Jbig2Stream.prototype.ensureBuffer = function (requested) { // No-op, since `this.readBlock` will always parse the entire image and // directly insert all of its data into `this.buffer`. }; - Jbig2Stream.prototype.readBlock = function() { + Jbig2Stream.prototype.readBlock = function () { if (this.eof) { return; } diff --git a/src/core/jpeg_stream.js b/src/core/jpeg_stream.js index 66638ea13..eb8e9a5f7 100644 --- a/src/core/jpeg_stream.js +++ b/src/core/jpeg_stream.js @@ -56,12 +56,12 @@ const JpegStream = (function JpegStreamClosure() { configurable: true, }); - JpegStream.prototype.ensureBuffer = function(requested) { + JpegStream.prototype.ensureBuffer = function (requested) { // No-op, since `this.readBlock` will always parse the entire image and // directly insert all of its data into `this.buffer`. }; - JpegStream.prototype.readBlock = function() { + JpegStream.prototype.readBlock = function () { if (this.eof) { return; } @@ -250,7 +250,7 @@ const JpegStream = (function JpegStreamClosure() { configurable: true, }); - JpegStream.prototype.getIR = function(forceDataSchema = false) { + JpegStream.prototype.getIR = function (forceDataSchema = false) { return createObjectURL(this.bytes, "image/jpeg", forceDataSchema); }; diff --git a/src/core/jpx_stream.js b/src/core/jpx_stream.js index 0c2c04fc2..300bb9118 100644 --- a/src/core/jpx_stream.js +++ b/src/core/jpx_stream.js @@ -42,12 +42,12 @@ const JpxStream = (function JpxStreamClosure() { configurable: true, }); - JpxStream.prototype.ensureBuffer = function(requested) { + JpxStream.prototype.ensureBuffer = function (requested) { // No-op, since `this.readBlock` will always parse the entire image and // directly insert all of its data into `this.buffer`. }; - JpxStream.prototype.readBlock = function() { + JpxStream.prototype.readBlock = function () { if (this.eof) { return; } diff --git a/src/core/metrics.js b/src/core/metrics.js index 51b3da815..1eb148f99 100644 --- a/src/core/metrics.js +++ b/src/core/metrics.js @@ -18,13 +18,13 @@ import { getLookupTableFactory } from "./core_utils.js"; // The Metrics object contains glyph widths (in glyph space units). // As per PDF spec, for most fonts (Type 3 being an exception) a glyph // space unit corresponds to 1/1000th of text space unit. -var getMetrics = getLookupTableFactory(function(t) { +var getMetrics = getLookupTableFactory(function (t) { t["Courier"] = 600; t["Courier-Bold"] = 600; t["Courier-BoldOblique"] = 600; t["Courier-Oblique"] = 600; // eslint-disable-next-line no-shadow - t["Helvetica"] = getLookupTableFactory(function(t) { + t["Helvetica"] = getLookupTableFactory(function (t) { t["space"] = 278; t["exclam"] = 278; t["quotedbl"] = 355; @@ -342,7 +342,7 @@ var getMetrics = getLookupTableFactory(function(t) { t["Euro"] = 556; }); // eslint-disable-next-line no-shadow - t["Helvetica-Bold"] = getLookupTableFactory(function(t) { + t["Helvetica-Bold"] = getLookupTableFactory(function (t) { t["space"] = 278; t["exclam"] = 333; t["quotedbl"] = 474; @@ -660,7 +660,7 @@ var getMetrics = getLookupTableFactory(function(t) { t["Euro"] = 556; }); // eslint-disable-next-line no-shadow - t["Helvetica-BoldOblique"] = getLookupTableFactory(function(t) { + t["Helvetica-BoldOblique"] = getLookupTableFactory(function (t) { t["space"] = 278; t["exclam"] = 333; t["quotedbl"] = 474; @@ -978,7 +978,7 @@ var getMetrics = getLookupTableFactory(function(t) { t["Euro"] = 556; }); // eslint-disable-next-line no-shadow - t["Helvetica-Oblique"] = getLookupTableFactory(function(t) { + t["Helvetica-Oblique"] = getLookupTableFactory(function (t) { t["space"] = 278; t["exclam"] = 278; t["quotedbl"] = 355; @@ -1296,7 +1296,7 @@ var getMetrics = getLookupTableFactory(function(t) { t["Euro"] = 556; }); // eslint-disable-next-line no-shadow - t["Symbol"] = getLookupTableFactory(function(t) { + t["Symbol"] = getLookupTableFactory(function (t) { t["space"] = 250; t["exclam"] = 333; t["universal"] = 713; @@ -1489,7 +1489,7 @@ var getMetrics = getLookupTableFactory(function(t) { t["apple"] = 790; }); // eslint-disable-next-line no-shadow - t["Times-Roman"] = getLookupTableFactory(function(t) { + t["Times-Roman"] = getLookupTableFactory(function (t) { t["space"] = 250; t["exclam"] = 333; t["quotedbl"] = 408; @@ -1807,7 +1807,7 @@ var getMetrics = getLookupTableFactory(function(t) { t["Euro"] = 500; }); // eslint-disable-next-line no-shadow - t["Times-Bold"] = getLookupTableFactory(function(t) { + t["Times-Bold"] = getLookupTableFactory(function (t) { t["space"] = 250; t["exclam"] = 333; t["quotedbl"] = 555; @@ -2125,7 +2125,7 @@ var getMetrics = getLookupTableFactory(function(t) { t["Euro"] = 500; }); // eslint-disable-next-line no-shadow - t["Times-BoldItalic"] = getLookupTableFactory(function(t) { + t["Times-BoldItalic"] = getLookupTableFactory(function (t) { t["space"] = 250; t["exclam"] = 389; t["quotedbl"] = 555; @@ -2443,7 +2443,7 @@ var getMetrics = getLookupTableFactory(function(t) { t["Euro"] = 500; }); // eslint-disable-next-line no-shadow - t["Times-Italic"] = getLookupTableFactory(function(t) { + t["Times-Italic"] = getLookupTableFactory(function (t) { t["space"] = 250; t["exclam"] = 333; t["quotedbl"] = 420; @@ -2761,7 +2761,7 @@ var getMetrics = getLookupTableFactory(function(t) { t["Euro"] = 500; }); // eslint-disable-next-line no-shadow - t["ZapfDingbats"] = getLookupTableFactory(function(t) { + t["ZapfDingbats"] = getLookupTableFactory(function (t) { t["space"] = 278; t["a1"] = 974; t["a2"] = 961; diff --git a/src/core/obj.js b/src/core/obj.js index f8a820b62..10469f05b 100644 --- a/src/core/obj.js +++ b/src/core/obj.js @@ -271,7 +271,7 @@ class Catalog { dests[name] = fetchDestination(names[name]); } } else if (obj instanceof Dict) { - obj.forEach(function(key, value) { + obj.forEach(function (key, value) { if (value) { dests[key] = fetchDestination(value); } @@ -693,7 +693,7 @@ class Catalog { fontFallback(id, handler) { const promises = []; - this.fontCache.forEach(function(promise) { + this.fontCache.forEach(function (promise) { promises.push(promise); }); @@ -712,7 +712,7 @@ class Catalog { this.pageKidsCountCache.clear(); const promises = []; - this.fontCache.forEach(function(promise) { + this.fontCache.forEach(function (promise) { promises.push(promise); }); @@ -754,7 +754,7 @@ class Catalog { } visitedNodes.put(currentNode); - xref.fetchAsync(currentNode).then(function(obj) { + xref.fetchAsync(currentNode).then(function (obj) { if (isDict(obj, "Page") || (isDict(obj) && !obj.has("Kids"))) { if (pageIndex === currentPageIndex) { // Cache the Page reference, since it can *greatly* improve @@ -849,7 +849,7 @@ class Catalog { return xref .fetchAsync(kidRef) - .then(function(node) { + .then(function (node) { if ( isRefsEqual(kidRef, pageRef) && !isDict(node, "Page") && @@ -868,7 +868,7 @@ class Catalog { parentRef = node.getRaw("Parent"); return node.getAsync("Parent"); }) - .then(function(parent) { + .then(function (parent) { if (!parent) { return null; } @@ -877,7 +877,7 @@ class Catalog { } return parent.getAsync("Kids"); }) - .then(function(kids) { + .then(function (kids) { if (!kids) { return null; } @@ -894,7 +894,7 @@ class Catalog { break; } kidPromises.push( - xref.fetchAsync(kid).then(function(obj) { + xref.fetchAsync(kid).then(function (obj) { if (!isDict(obj)) { throw new FormatError("Kid node must be a dictionary."); } @@ -910,7 +910,7 @@ class Catalog { if (!found) { throw new FormatError("Kid reference not found in parent's kids."); } - return Promise.all(kidPromises).then(function() { + return Promise.all(kidPromises).then(function () { return [total, parentRef]; }); }); @@ -918,7 +918,7 @@ class Catalog { let total = 0; function next(ref) { - return pagesBeforeRef(ref).then(function(args) { + return pagesBeforeRef(ref).then(function (args) { if (!args) { return total; } @@ -1069,9 +1069,7 @@ class Catalog { const URL_OPEN_METHODS = ["app.launchURL", "window.open"]; const regex = new RegExp( "^\\s*(" + - URL_OPEN_METHODS.join("|") - .split(".") - .join("\\.") + + URL_OPEN_METHODS.join("|").split(".").join("\\.") + ")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))", "i" ); @@ -2186,7 +2184,7 @@ var FileSpec = (function FileSpecClosure() { * that have references to the catalog or other pages since that will cause the * entire PDF document object graph to be traversed. */ -const ObjectLoader = (function() { +const ObjectLoader = (function () { function mayHaveChildren(value) { return ( value instanceof Ref || diff --git a/src/core/operator_list.js b/src/core/operator_list.js index 385e35190..a086ffad8 100644 --- a/src/core/operator_list.js +++ b/src/core/operator_list.js @@ -304,7 +304,7 @@ var QueueOptimizer = (function QueueOptimizerClosure() { addState( InitialState, [OPS.save, OPS.transform, OPS.paintImageXObject, OPS.restore], - function(context) { + function (context) { var argsArray = context.argsArray; var iFirstTransform = context.iCurr - 2; return ( @@ -351,7 +351,7 @@ var QueueOptimizer = (function QueueOptimizerClosure() { } throw new Error(`iterateImageGroup - invalid pos: ${pos}`); }, - function(context, i) { + function (context, i) { var MIN_IMAGES_IN_BLOCK = 3; var MAX_IMAGES_IN_BLOCK = 1000; @@ -436,7 +436,7 @@ var QueueOptimizer = (function QueueOptimizerClosure() { } throw new Error(`iterateShowTextGroup - invalid pos: ${pos}`); }, - function(context, i) { + function (context, i) { var MIN_CHARS_IN_BLOCK = 3; var MAX_CHARS_IN_BLOCK = 1000; diff --git a/src/core/pattern.js b/src/core/pattern.js index a2d752f5c..c380adf0b 100644 --- a/src/core/pattern.js +++ b/src/core/pattern.js @@ -51,7 +51,7 @@ var Pattern = (function PatternClosure() { }, }; - Pattern.parseShading = function( + Pattern.parseShading = function ( shading, matrix, xref, diff --git a/src/core/primitives.js b/src/core/primitives.js index a0e8d62c3..8c8727260 100644 --- a/src/core/primitives.js +++ b/src/core/primitives.js @@ -34,7 +34,7 @@ var Name = (function NameClosure() { return nameValue ? nameValue : (nameCache[name] = new Name(name)); }; - Name._clearCache = function() { + Name._clearCache = function () { nameCache = Object.create(null); }; @@ -57,7 +57,7 @@ var Cmd = (function CmdClosure() { return cmdValue ? cmdValue : (cmdCache[cmd] = new Cmd(cmd)); }; - Cmd._clearCache = function() { + Cmd._clearCache = function () { cmdCache = Object.create(null); }; @@ -164,7 +164,7 @@ var Dict = (function DictClosure() { Dict.empty = new Dict(null); - Dict.merge = function(xref, dictArray) { + Dict.merge = function (xref, dictArray) { const mergedDict = new Dict(xref); for (let i = 0, ii = dictArray.length; i < ii; i++) { @@ -205,14 +205,14 @@ var Ref = (function RefClosure() { }, }; - Ref.get = function(num, gen) { + Ref.get = function (num, gen) { const key = gen === 0 ? `${num}R` : `${num}R${gen}`; const refValue = refCache[key]; // eslint-disable-next-line no-restricted-syntax return refValue ? refValue : (refCache[key] = new Ref(num, gen)); }; - Ref._clearCache = function() { + Ref._clearCache = function () { refCache = Object.create(null); }; diff --git a/src/core/standard_fonts.js b/src/core/standard_fonts.js index dfd16282c..b1a4ec85e 100644 --- a/src/core/standard_fonts.js +++ b/src/core/standard_fonts.js @@ -20,7 +20,7 @@ import { getLookupTableFactory } from "./core_utils.js"; * Hold a map of decoded fonts and of the standard fourteen Type1 * fonts and their acronyms. */ -const getStdFontMap = getLookupTableFactory(function(t) { +const getStdFontMap = getLookupTableFactory(function (t) { t["ArialNarrow"] = "Helvetica"; t["ArialNarrow-Bold"] = "Helvetica-Bold"; t["ArialNarrow-BoldItalic"] = "Helvetica-BoldOblique"; @@ -82,7 +82,7 @@ const getStdFontMap = getLookupTableFactory(function(t) { * Holds the map of the non-standard fonts that might be included as * a standard fonts without glyph data. */ -const getNonStdFontMap = getLookupTableFactory(function(t) { +const getNonStdFontMap = getLookupTableFactory(function (t) { t["Calibri"] = "Helvetica"; t["Calibri-Bold"] = "Helvetica-Bold"; t["Calibri-BoldItalic"] = "Helvetica-BoldOblique"; @@ -122,7 +122,7 @@ const getNonStdFontMap = getLookupTableFactory(function(t) { t["Wingdings-Regular"] = "ZapfDingbats"; }); -const getSerifFonts = getLookupTableFactory(function(t) { +const getSerifFonts = getLookupTableFactory(function (t) { t["Adobe Jenson"] = true; t["Adobe Text"] = true; t["Albertus"] = true; @@ -258,7 +258,7 @@ const getSerifFonts = getLookupTableFactory(function(t) { t["XITS"] = true; }); -const getSymbolsFonts = getLookupTableFactory(function(t) { +const getSymbolsFonts = getLookupTableFactory(function (t) { t["Dingbats"] = true; t["Symbol"] = true; t["ZapfDingbats"] = true; @@ -267,7 +267,7 @@ const getSymbolsFonts = getLookupTableFactory(function(t) { // Glyph map for well-known standard fonts. Sometimes Ghostscript uses CID // fonts, but does not embed the CID to GID mapping. The mapping is incomplete // for all glyphs, but common for some set of the standard fonts. -const getGlyphMapForStandardFonts = getLookupTableFactory(function(t) { +const getGlyphMapForStandardFonts = getLookupTableFactory(function (t) { t[2] = 10; t[3] = 32; t[4] = 33; @@ -666,7 +666,9 @@ const getGlyphMapForStandardFonts = getLookupTableFactory(function(t) { // The glyph map for ArialBlack differs slightly from the glyph map used for // other well-known standard fonts. Hence we use this (incomplete) CID to GID // mapping to adjust the glyph map for non-embedded ArialBlack fonts. -const getSupplementalGlyphMapForArialBlack = getLookupTableFactory(function(t) { +const getSupplementalGlyphMapForArialBlack = getLookupTableFactory(function ( + t +) { t[227] = 322; t[264] = 261; t[291] = 346; @@ -675,7 +677,7 @@ const getSupplementalGlyphMapForArialBlack = getLookupTableFactory(function(t) { // The glyph map for Calibri (a Windows font) differs from the glyph map used // in the standard fonts. Hence we use this (incomplete) CID to GID mapping to // adjust the glyph map for non-embedded Calibri fonts. -const getSupplementalGlyphMapForCalibri = getLookupTableFactory(function(t) { +const getSupplementalGlyphMapForCalibri = getLookupTableFactory(function (t) { t[1] = 32; t[4] = 65; t[17] = 66; diff --git a/src/core/unicode.js b/src/core/unicode.js index e97e87388..57b8ed676 100644 --- a/src/core/unicode.js +++ b/src/core/unicode.js @@ -19,7 +19,7 @@ var getLookupTableFactory = require("./core_utils.js").getLookupTableFactory; // Some characters, e.g. copyrightserif, are mapped to the private use area // and might not be displayed using standard fonts. Mapping/hacking well-known // chars to the similar equivalents in the normal characters range. -var getSpecialPUASymbols = getLookupTableFactory(function(t) { +var getSpecialPUASymbols = getLookupTableFactory(function (t) { t[63721] = 0x00a9; // copyrightsans (0xF8E9) => copyright t[63193] = 0x00a9; // copyrightserif (0xF6D9) => copyright t[63720] = 0x00ae; // registersans (0xF8E8) => registered @@ -241,7 +241,7 @@ function isRTLRangeFor(value) { // The normalization table is obtained by filtering the Unicode characters // database with entries. -var getNormalizedUnicodes = getLookupTableFactory(function(t) { +var getNormalizedUnicodes = getLookupTableFactory(function (t) { t["\u00A8"] = "\u0020\u0308"; t["\u00AF"] = "\u0020\u0304"; t["\u00B4"] = "\u0020\u0301"; diff --git a/src/core/worker.js b/src/core/worker.js index 74f4af1c5..2e21d52e2 100644 --- a/src/core/worker.js +++ b/src/core/worker.js @@ -230,7 +230,7 @@ var WorkerMessageHandler = { var fullRequest = pdfStream.getFullReader(); fullRequest.headersReady - .then(function() { + .then(function () { if (!fullRequest.isRangeSupported) { return; } @@ -262,13 +262,13 @@ var WorkerMessageHandler = { pdfManagerCapability.resolve(newPdfManager); cancelXHRs = null; }) - .catch(function(reason) { + .catch(function (reason) { pdfManagerCapability.reject(reason); cancelXHRs = null; }); var loaded = 0; - var flushChunks = function() { + var flushChunks = function () { var pdfFile = arraysToBytes(cachedChunks); if (source.length && pdfFile.length !== source.length) { warn("reported HTTP length is different from actual"); @@ -288,8 +288,8 @@ var WorkerMessageHandler = { } cachedChunks = []; }; - var readPromise = new Promise(function(resolve, reject) { - var readChunk = function({ value, done }) { + var readPromise = new Promise(function (resolve, reject) { + var readChunk = function ({ value, done }) { try { ensureNotTerminated(); if (done) { @@ -321,12 +321,12 @@ var WorkerMessageHandler = { }; fullRequest.read().then(readChunk, reject); }); - readPromise.catch(function(e) { + readPromise.catch(function (e) { pdfManagerCapability.reject(e); cancelXHRs = null; }); - cancelXHRs = function(reason) { + cancelXHRs = function (reason) { pdfStream.cancelAllRequests(reason); }; @@ -348,12 +348,12 @@ var WorkerMessageHandler = { handler .sendWithPromise("PasswordRequest", ex) - .then(function({ password }) { + .then(function ({ password }) { finishWorkerTask(task); pdfManager.updatePassword(password); pdfManagerReady(); }) - .catch(function() { + .catch(function () { finishWorkerTask(task); handler.send("DocException", ex); }); @@ -386,7 +386,7 @@ var WorkerMessageHandler = { return; } pdfManager.requestLoadedStream(); - pdfManager.onLoadedStream().then(function() { + pdfManager.onLoadedStream().then(function () { ensureNotTerminated(); loadDocument(true).then(onSuccess, onFailure); @@ -409,7 +409,7 @@ var WorkerMessageHandler = { }; getPdfManager(data, evaluatorOptions) - .then(function(newPdfManager) { + .then(function (newPdfManager) { if (terminated) { // We were in a process of setting up the manager, but it got // terminated in the middle. @@ -420,7 +420,7 @@ var WorkerMessageHandler = { } pdfManager = newPdfManager; - pdfManager.onLoadedStream().then(function(stream) { + pdfManager.onLoadedStream().then(function (stream) { handler.send("DataLoaded", { length: stream.bytes.byteLength }); }); }) @@ -428,13 +428,13 @@ var WorkerMessageHandler = { } handler.on("GetPage", function wphSetupGetPage(data) { - return pdfManager.getPage(data.pageIndex).then(function(page) { + return pdfManager.getPage(data.pageIndex).then(function (page) { return Promise.all([ pdfManager.ensure(page, "rotate"), pdfManager.ensure(page, "ref"), pdfManager.ensure(page, "userUnit"), pdfManager.ensure(page, "view"), - ]).then(function([rotate, ref, userUnit, view]) { + ]).then(function ([rotate, ref, userUnit, view]) { return { rotate, ref, @@ -471,11 +471,11 @@ var WorkerMessageHandler = { return pdfManager.ensureCatalog("pageMode"); }); - handler.on("GetViewerPreferences", function(data) { + handler.on("GetViewerPreferences", function (data) { return pdfManager.ensureCatalog("viewerPreferences"); }); - handler.on("GetOpenAction", function(data) { + handler.on("GetOpenAction", function (data) { return pdfManager.ensureCatalog("openAction"); }); @@ -491,7 +491,7 @@ var WorkerMessageHandler = { return pdfManager.ensureCatalog("documentOutline"); }); - handler.on("GetPermissions", function(data) { + handler.on("GetPermissions", function (data) { return pdfManager.ensureCatalog("permissions"); }); @@ -504,7 +504,7 @@ var WorkerMessageHandler = { handler.on("GetData", function wphSetupGetData(data) { pdfManager.requestLoadedStream(); - return pdfManager.onLoadedStream().then(function(stream) { + return pdfManager.onLoadedStream().then(function (stream) { return stream.bytes; }); }); @@ -513,8 +513,8 @@ var WorkerMessageHandler = { return pdfManager.pdfDocument.xref.stats; }); - handler.on("GetAnnotations", function({ pageIndex, intent }) { - return pdfManager.getPage(pageIndex).then(function(page) { + handler.on("GetAnnotations", function ({ pageIndex, intent }) { + return pdfManager.getPage(pageIndex).then(function (page) { return page.getAnnotationsData(intent); }); }); @@ -523,7 +523,7 @@ var WorkerMessageHandler = { "GetOperatorList", function wphSetupRenderPage(data, sink) { var pageIndex = data.pageIndex; - pdfManager.getPage(pageIndex).then(function(page) { + pdfManager.getPage(pageIndex).then(function (page) { var task = new WorkerTask(`GetOperatorList: page ${pageIndex}`); startWorkerTask(task); @@ -540,7 +540,7 @@ var WorkerMessageHandler = { renderInteractiveForms: data.renderInteractiveForms, }) .then( - function(operatorListInfo) { + function (operatorListInfo) { finishWorkerTask(task); if (start) { @@ -551,7 +551,7 @@ var WorkerMessageHandler = { } sink.close(); }, - function(reason) { + function (reason) { finishWorkerTask(task); if (task.terminated) { return; // ignoring errors from the terminated thread @@ -576,10 +576,10 @@ var WorkerMessageHandler = { handler.on("GetTextContent", function wphExtractText(data, sink) { var pageIndex = data.pageIndex; - sink.onPull = function(desiredSize) {}; - sink.onCancel = function(reason) {}; + sink.onPull = function (desiredSize) {}; + sink.onCancel = function (reason) {}; - pdfManager.getPage(pageIndex).then(function(page) { + pdfManager.getPage(pageIndex).then(function (page) { var task = new WorkerTask("GetTextContent: page " + pageIndex); startWorkerTask(task); @@ -595,7 +595,7 @@ var WorkerMessageHandler = { combineTextItems: data.combineTextItems, }) .then( - function() { + function () { finishWorkerTask(task); if (start) { @@ -606,7 +606,7 @@ var WorkerMessageHandler = { } sink.close(); }, - function(reason) { + function (reason) { finishWorkerTask(task); if (task.terminated) { return; // ignoring errors from the terminated thread @@ -620,7 +620,7 @@ var WorkerMessageHandler = { }); }); - handler.on("FontFallback", function(data) { + handler.on("FontFallback", function (data) { return pdfManager.fontFallback(data.id, handler); }); @@ -646,12 +646,12 @@ var WorkerMessageHandler = { cancelXHRs(new AbortException("Worker was terminated.")); } - WorkerTasks.forEach(function(task) { + WorkerTasks.forEach(function (task) { waitOn.push(task.finished); task.terminate(); }); - return Promise.all(waitOn).then(function() { + return Promise.all(waitOn).then(function () { // Notice that even if we destroying handler, resolved response promise // must be sent back. handler.destroy(); diff --git a/src/core/worker_stream.js b/src/core/worker_stream.js index 3f0922a21..f1f21d4c3 100644 --- a/src/core/worker_stream.js +++ b/src/core/worker_stream.js @@ -42,7 +42,7 @@ class PDFWorkerStream { this._fullRequestReader.cancel(reason); } const readers = this._rangeRequestReaders.slice(0); - readers.forEach(function(reader) { + readers.forEach(function (reader) { reader.cancel(reason); }); } diff --git a/src/display/api.js b/src/display/api.js index 8921cc690..028bcff4d 100644 --- a/src/display/api.js +++ b/src/display/api.js @@ -309,12 +309,12 @@ function getDocument(src) { } const docId = task.docId; worker.promise - .then(function() { + .then(function () { if (task.destroyed) { throw new Error("Loading aborted"); } return _fetchDocument(worker, params, rangeTransport, docId).then( - function(workerId) { + function (workerId) { if (task.destroyed) { throw new Error("Loading aborted"); } @@ -411,7 +411,7 @@ function _fetchDocument(worker, source, pdfDataRangeTransport, docId) { isEvalSupported: source.isEvalSupported, fontExtraProperties: source.fontExtraProperties, }) - .then(function(workerId) { + .then(function (workerId) { if (worker.destroyed) { throw new Error("Worker was destroyed"); } @@ -679,7 +679,7 @@ class PDFDocumentProxy { getOpenActionDestination() { deprecated("getOpenActionDestination, use getOpenAction instead."); - return this.getOpenAction().then(function(openAction) { + return this.getOpenAction().then(function (openAction) { return openAction && openAction.dest ? openAction.dest : null; }); } @@ -1214,9 +1214,9 @@ class PDFPageProxy { getTextContent(params = {}) { const readableStream = this.streamTextContent(params); - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { function pump() { - reader.read().then(function({ value, done }) { + reader.read().then(function ({ value, done }) { if (done) { resolve(textContent); return; @@ -1257,9 +1257,9 @@ class PDFPageProxy { // Avoid errors below, since the renderTasks are just stubs. return; } - intentState.renderTasks.forEach(function(renderTask) { + intentState.renderTasks.forEach(function (renderTask) { const renderCompleted = renderTask.capability.promise.catch( - function() {} + function () {} ); // ignoring failures waitOn.push(renderCompleted); renderTask.cancel(); @@ -1629,7 +1629,7 @@ const PDFWorker = (function PDFWorkerClosure() { } fakeWorkerCapability = createPromiseCapability(); - const loader = async function() { + const loader = async function () { const mainWorkerMessageHandler = getMainThreadWorkerMessageHandler(); if (mainWorkerMessageHandler) { @@ -1734,7 +1734,7 @@ const PDFWorker = (function PDFWorkerClosure() { _initializeFromPort(port) { this._port = port; this._messageHandler = new MessageHandler("main", "worker", port); - this._messageHandler.on("ready", function() { + this._messageHandler.on("ready", function () { // Ignoring 'ready' event -- MessageHandler shall be already initialized // and ready to accept the messages. }); @@ -1991,7 +1991,7 @@ class WorkerTransport { const waitOn = []; // We need to wait for all renderings to be completed, e.g. // timeout/rAF can take a long time. - this.pageCache.forEach(function(page) { + this.pageCache.forEach(function (page) { if (page) { waitOn.push(page._destroy()); } @@ -2033,7 +2033,7 @@ class WorkerTransport { sink.onPull = () => { this._fullReader .read() - .then(function({ value, done }) { + .then(function ({ value, done }) { if (done) { sink.close(); return; @@ -2108,7 +2108,7 @@ class WorkerTransport { sink.onPull = () => { rangeReader .read() - .then(function({ value, done }) { + .then(function ({ value, done }) { if (done) { sink.close(); return; @@ -2131,7 +2131,7 @@ class WorkerTransport { loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this)); }); - messageHandler.on("DocException", function(ex) { + messageHandler.on("DocException", function (ex) { let reason; switch (ex.name) { case "PasswordException": @@ -2283,10 +2283,10 @@ class WorkerTransport { case "JpegStream": return new Promise((resolve, reject) => { const img = new Image(); - img.onload = function() { + img.onload = function () { resolve(img); }; - img.onerror = function() { + img.onerror = function () { // Note that when the browser image loading/decoding fails, // we'll fallback to the built-in PDF.js JPEG decoder; see // `PartialEvaluator.buildPaintImageXObject` in the @@ -2354,9 +2354,9 @@ class WorkerTransport { ); } - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { const img = new Image(); - img.onload = function() { + img.onload = function () { const { width, height } = img; const size = width * height; const rgbaLength = size * 4; @@ -2390,7 +2390,7 @@ class WorkerTransport { tmpCanvas = null; tmpCtx = null; }; - img.onerror = function() { + img.onerror = function () { reject(new Error("JpegDecode failed to load image")); // Always remember to release the image data if errors occurred. @@ -2415,10 +2415,10 @@ class WorkerTransport { fetched = true; this.CMapReaderFactory.fetch(data) - .then(function(builtInCMap) { + .then(function (builtInCMap) { sink.enqueue(builtInCMap, 1, [builtInCMap.cMapData.buffer]); }) - .catch(function(reason) { + .catch(function (reason) { sink.error(reason); }); }; @@ -2477,7 +2477,7 @@ class WorkerTransport { .sendWithPromise("GetPageIndex", { ref, }) - .catch(function(reason) { + .catch(function (reason) { return Promise.reject(new Error(reason)); }); } @@ -2856,9 +2856,7 @@ const InternalRenderTask = (function InternalRenderTaskClosure() { this._nextBound().catch(this.cancel.bind(this)); }); } else { - Promise.resolve() - .then(this._nextBound) - .catch(this.cancel.bind(this)); + Promise.resolve().then(this._nextBound).catch(this.cancel.bind(this)); } } diff --git a/src/display/canvas.js b/src/display/canvas.js index 89345ae58..5ce5be839 100644 --- a/src/display/canvas.js +++ b/src/display/canvas.js @@ -362,7 +362,7 @@ function compileType3Glyph(imgData) { --i; } - var drawOutline = function(c) { + var drawOutline = function (c) { c.save(); // the path shall be painted in [0..1]x[0..1] space c.scale(1 / width, -1 / height); diff --git a/src/display/content_disposition.js b/src/display/content_disposition.js index 5a732a524..7375361c2 100644 --- a/src/display/content_disposition.js +++ b/src/display/content_disposition.js @@ -85,7 +85,7 @@ function getFilenameFromContentDispositionHeader(contentDisposition) { } try { const decoder = new TextDecoder(encoding, { fatal: true }); - const bytes = Array.from(value, function(ch) { + const bytes = Array.from(value, function (ch) { return ch.charCodeAt(0) & 0xff; }); value = decoder.decode(new Uint8Array(bytes)); @@ -205,11 +205,11 @@ function getFilenameFromContentDispositionHeader(contentDisposition) { // ... but Firefox permits ? and space. return value.replace( /=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, - function(matches, charset, encoding, text) { + function (matches, charset, encoding, text) { if (encoding === "q" || encoding === "Q") { // RFC 2047 section 4.2. text = text.replace(/_/g, " "); - text = text.replace(/=([0-9a-fA-F]{2})/g, function(match, hex) { + text = text.replace(/=([0-9a-fA-F]{2})/g, function (match, hex) { return String.fromCharCode(parseInt(hex, 16)); }); return textdecode(charset, text); diff --git a/src/display/display_utils.js b/src/display/display_utils.js index 279f89ba8..f8cfd5b69 100644 --- a/src/display/display_utils.js +++ b/src/display/display_utils.js @@ -502,7 +502,7 @@ function loadScript(src) { script.src = src; script.onload = resolve; - script.onerror = function() { + script.onerror = function () { reject(new Error(`Cannot load script at: ${script.src}`)); }; (document.head || document.documentElement).appendChild(script); diff --git a/src/display/fetch_stream.js b/src/display/fetch_stream.js index 1a88294ba..fc35effc7 100644 --- a/src/display/fetch_stream.js +++ b/src/display/fetch_stream.js @@ -84,7 +84,7 @@ class PDFFetchStream { this._fullRequestReader.cancel(reason); } const readers = this._rangeRequestReaders.slice(0); - readers.forEach(function(reader) { + readers.forEach(function (reader) { reader.cancel(reason); }); } diff --git a/src/display/font_loader.js b/src/display/font_loader.js index e1f385a98..5de7302fa 100644 --- a/src/display/font_loader.js +++ b/src/display/font_loader.js @@ -56,7 +56,7 @@ class BaseFontLoader { } clear() { - this.nativeFontFaces.forEach(function(nativeFontFace) { + this.nativeFontFaces.forEach(function (nativeFontFace) { document.fonts.delete(nativeFontFace); }); this.nativeFontFaces.length = 0; @@ -198,7 +198,7 @@ if (typeof PDFJSDev !== "undefined" && PDFJSDev.test("MOZCENTRAL")) { } get _loadTestFont() { - const getLoadTestFont = function() { + const getLoadTestFont = function () { // This is a CFF font with 1 glyph for '.' that fills its entire width // and height. return atob( @@ -328,7 +328,7 @@ if (typeof PDFJSDev !== "undefined" && PDFJSDev.test("MOZCENTRAL")) { } document.body.appendChild(div); - isFontReady(loadTestFontId, function() { + isFontReady(loadTestFontId, function () { document.body.removeChild(div); request.complete(); }); @@ -404,7 +404,7 @@ class FontFaceObject { } warn(`getPathGenerator - ignoring character: "${ex}".`); - return (this.compiledGlyphs[character] = function(c, size) { + return (this.compiledGlyphs[character] = function (c, size) { // No-op function, to allow rendering to continue. }); } @@ -428,7 +428,7 @@ class FontFaceObject { } // ... but fall back on using Function.prototype.apply() if we're // blocked from using eval() for whatever reason (like CSP policies). - return (this.compiledGlyphs[character] = function(c, size) { + return (this.compiledGlyphs[character] = function (c, size) { for (let i = 0, ii = cmds.length; i < ii; i++) { current = cmds[i]; diff --git a/src/display/metadata.js b/src/display/metadata.js index edd1f5935..3ce5bdbd3 100644 --- a/src/display/metadata.js +++ b/src/display/metadata.js @@ -38,12 +38,12 @@ class Metadata { // Start by removing any "junk" before the first tag (see issue 10395). return data .replace(/^[^<]+/, "") - .replace(/>\\376\\377([^<]+)/g, function(all, codes) { + .replace(/>\\376\\377([^<]+)/g, function (all, codes) { const bytes = codes - .replace(/\\([0-3])([0-7])([0-7])/g, function(code, d1, d2, d3) { + .replace(/\\([0-3])([0-7])([0-7])/g, function (code, d1, d2, d3) { return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1); }) - .replace(/&(amp|apos|gt|lt|quot);/g, function(str, name) { + .replace(/&(amp|apos|gt|lt|quot);/g, function (str, name) { switch (name) { case "amp": return "&"; diff --git a/src/display/network.js b/src/display/network.js index f24ee1f92..048785c75 100644 --- a/src/display/network.js +++ b/src/display/network.js @@ -100,7 +100,7 @@ class NetworkManager { xhr.responseType = "arraybuffer"; if (args.onError) { - xhr.onerror = function(evt) { + xhr.onerror = function (evt) { args.onError(xhr.status); }; } @@ -271,7 +271,7 @@ class PDFNetworkStream { this._fullRequestReader.cancel(reason); } const readers = this._rangeRequestReaders.slice(0); - readers.forEach(function(reader) { + readers.forEach(function (reader) { reader.cancel(reason); }); } @@ -359,7 +359,7 @@ class PDFNetworkStreamFullRequestReader { if (this._cachedChunks.length > 0) { return; } - this._requests.forEach(function(requestCapability) { + this._requests.forEach(function (requestCapability) { requestCapability.resolve({ value: undefined, done: true }); }); this._requests = []; @@ -370,7 +370,7 @@ class PDFNetworkStreamFullRequestReader { const exception = createResponseStatusError(status, url); this._storedError = exception; this._headersReceivedCapability.reject(exception); - this._requests.forEach(function(requestCapability) { + this._requests.forEach(function (requestCapability) { requestCapability.reject(exception); }); this._requests = []; @@ -425,7 +425,7 @@ class PDFNetworkStreamFullRequestReader { cancel(reason) { this._done = true; this._headersReceivedCapability.reject(reason); - this._requests.forEach(function(requestCapability) { + this._requests.forEach(function (requestCapability) { requestCapability.resolve({ value: undefined, done: true }); }); this._requests = []; @@ -468,7 +468,7 @@ class PDFNetworkStreamRangeRequestReader { this._queuedChunk = chunk; } this._done = true; - this._requests.forEach(function(requestCapability) { + this._requests.forEach(function (requestCapability) { requestCapability.resolve({ value: undefined, done: true }); }); this._requests = []; @@ -503,7 +503,7 @@ class PDFNetworkStreamRangeRequestReader { cancel(reason) { this._done = true; - this._requests.forEach(function(requestCapability) { + this._requests.forEach(function (requestCapability) { requestCapability.resolve({ value: undefined, done: true }); }); this._requests = []; diff --git a/src/display/node_stream.js b/src/display/node_stream.js index ce0bd1a18..f370f8a90 100644 --- a/src/display/node_stream.js +++ b/src/display/node_stream.js @@ -91,7 +91,7 @@ class PDFNodeStream { } const readers = this._rangeRequestReaders.slice(0); - readers.forEach(function(reader) { + readers.forEach(function (reader) { reader.cancel(reason); }); } diff --git a/src/display/svg.js b/src/display/svg.js index e605d7054..0afd55ca3 100644 --- a/src/display/svg.js +++ b/src/display/svg.js @@ -29,7 +29,7 @@ import { import { DOMSVGFactory } from "./display_utils.js"; import { isNodeJS } from "../shared/is_node.js"; -let SVGGraphics = function() { +let SVGGraphics = function () { throw new Error("Not implemented: SVGGraphics"); }; @@ -44,7 +44,7 @@ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) { const LINE_CAP_STYLES = ["butt", "round", "square"]; const LINE_JOIN_STYLES = ["miter", "round", "bevel"]; - const convertImgDataToPng = (function() { + const convertImgDataToPng = (function () { const PNG_HEADER = new Uint8Array([ 0x89, 0x50, @@ -1327,7 +1327,7 @@ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) { // The previous clipping group content can go out of order -- resetting // cached clipGroups. current.clipGroup = null; - this.extraStack.forEach(function(prev) { + this.extraStack.forEach(function (prev) { prev.clipGroup = null; }); // Intersect with the previous clipping path. @@ -1439,7 +1439,7 @@ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) { const current = this.current; let dashArray = current.dashArray; if (lineWidthScale !== 1 && dashArray.length > 0) { - dashArray = dashArray.map(function(value) { + dashArray = dashArray.map(function (value) { return lineWidthScale * value; }); } diff --git a/src/display/text_layer.js b/src/display/text_layer.js index f8308a4e3..ecf29efd3 100644 --- a/src/display/text_layer.js +++ b/src/display/text_layer.js @@ -234,7 +234,7 @@ var renderTextLayer = (function renderTextLayerClosure() { // Finding intersections with expanded box. var points = [[0, 0], [0, b.size[1]], [b.size[0], 0], b.size]; var ts = new Float64Array(64); - points.forEach(function(p, j) { + points.forEach(function (p, j) { var t = Util.applyTransform(p, m); ts[j + 0] = c && (e.left - t[0]) / c; ts[j + 4] = s && (e.top - t[1]) / s; @@ -268,7 +268,7 @@ var renderTextLayer = (function renderTextLayerClosure() { } function expandBounds(width, height, boxes) { - var bounds = boxes.map(function(box, i) { + var bounds = boxes.map(function (box, i) { return { x1: box.left, y1: box.top, @@ -281,7 +281,7 @@ var renderTextLayer = (function renderTextLayerClosure() { }); expandBoundsLTR(width, bounds); var expanded = new Array(boxes.length); - bounds.forEach(function(b) { + bounds.forEach(function (b) { var i = b.index; expanded[i] = { left: b.x1New, @@ -293,7 +293,7 @@ var renderTextLayer = (function renderTextLayerClosure() { // Rotating on 90 degrees and extending extended boxes. Reusing the bounds // array and objects. - boxes.map(function(box, i) { + boxes.map(function (box, i) { var e = expanded[i], b = bounds[i]; b.x1 = box.top; @@ -306,7 +306,7 @@ var renderTextLayer = (function renderTextLayerClosure() { }); expandBoundsLTR(height, bounds); - bounds.forEach(function(b) { + bounds.forEach(function (b) { var i = b.index; expanded[i].top = b.x1New; expanded[i].bottom = b.x2New; @@ -316,7 +316,7 @@ var renderTextLayer = (function renderTextLayerClosure() { function expandBoundsLTR(width, bounds) { // Sorting by x1 coordinate and walk by the bounds in the same order. - bounds.sort(function(a, b) { + bounds.sort(function (a, b) { return a.x1 - b.x1 || a.index - b.index; }); @@ -338,7 +338,7 @@ var renderTextLayer = (function renderTextLayerClosure() { }, ]; - bounds.forEach(function(boundary) { + bounds.forEach(function (boundary) { // Searching for the affected part of horizon. // TODO red-black tree or simple binary search var i = 0; @@ -480,7 +480,7 @@ var renderTextLayer = (function renderTextLayerClosure() { }); // Set new x2 for all unset boundaries. - horizon.forEach(function(horizonPart) { + horizon.forEach(function (horizonPart) { var affectedBoundary = horizonPart.boundary; if (affectedBoundary.x2New === undefined) { affectedBoundary.x2New = Math.max(width, affectedBoundary.x2); diff --git a/src/display/transport_stream.js b/src/display/transport_stream.js index 2226f6d1b..e1355ff7d 100644 --- a/src/display/transport_stream.js +++ b/src/display/transport_stream.js @@ -66,7 +66,7 @@ class PDFDataTransportStream { this._queuedChunks.push(buffer); } } else { - const found = this._rangeReaders.some(function(rangeReader) { + const found = this._rangeReaders.some(function (rangeReader) { if (rangeReader._begin !== args.begin) { return false; } @@ -136,7 +136,7 @@ class PDFDataTransportStream { this._fullRequestReader.cancel(reason); } const readers = this._rangeReaders.slice(0); - readers.forEach(function(rangeReader) { + readers.forEach(function (rangeReader) { rangeReader.cancel(reason); }); this._pdfDataRangeTransport.abort(); @@ -209,7 +209,7 @@ class PDFDataTransportStreamReader { cancel(reason) { this._done = true; - this._requests.forEach(function(requestCapability) { + this._requests.forEach(function (requestCapability) { requestCapability.resolve({ value: undefined, done: true }); }); this._requests = []; @@ -245,7 +245,7 @@ class PDFDataTransportStreamRangeReader { } else { const requestsCapability = this._requests.shift(); requestsCapability.resolve({ value: chunk, done: false }); - this._requests.forEach(function(requestCapability) { + this._requests.forEach(function (requestCapability) { requestCapability.resolve({ value: undefined, done: true }); }); this._requests = []; @@ -274,7 +274,7 @@ class PDFDataTransportStreamRangeReader { cancel(reason) { this._done = true; - this._requests.forEach(function(requestCapability) { + this._requests.forEach(function (requestCapability) { requestCapability.resolve({ value: undefined, done: true }); }); this._requests = []; diff --git a/src/display/xml_parser.js b/src/display/xml_parser.js index 77a6d8548..6401a76c7 100644 --- a/src/display/xml_parser.js +++ b/src/display/xml_parser.js @@ -317,7 +317,7 @@ class SimpleDOMNode { return this.nodeValue || ""; } return this.childNodes - .map(function(child) { + .map(function (child) { return child.textContent; }) .join(""); diff --git a/src/pdf.js b/src/pdf.js index 1d1252171..2233f3438 100644 --- a/src/pdf.js +++ b/src/pdf.js @@ -56,7 +56,7 @@ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) { } else if (PDFJSDev.test("CHROME")) { const PDFNetworkStream = require("./display/network.js").PDFNetworkStream; let PDFFetchStream; - const isChromeWithFetchCredentials = function() { + const isChromeWithFetchCredentials = function () { // fetch does not include credentials until Chrome 61.0.3138.0 and later. // https://chromium.googlesource.com/chromium/src/+/2e231cf052ca5e68e22baf0008ac9e5e29121707 try { diff --git a/src/shared/compatibility.js b/src/shared/compatibility.js index 7cd219fba..6c3c6e50a 100644 --- a/src/shared/compatibility.js +++ b/src/shared/compatibility.js @@ -39,7 +39,7 @@ if ( if (globalThis.btoa || !isNodeJS) { return; } - globalThis.btoa = function(chars) { + globalThis.btoa = function (chars) { // eslint-disable-next-line no-undef return Buffer.from(chars, "binary").toString("base64"); }; @@ -50,7 +50,7 @@ if ( if (globalThis.atob || !isNodeJS) { return; } - globalThis.atob = function(input) { + globalThis.atob = function (input) { // eslint-disable-next-line no-undef return Buffer.from(input, "base64").toString("binary"); }; @@ -65,7 +65,7 @@ if ( if (typeof Element.prototype.remove !== "undefined") { return; } - Element.prototype.remove = function() { + Element.prototype.remove = function () { if (this.parentNode) { // eslint-disable-next-line mozilla/avoid-removeChild this.parentNode.removeChild(this); @@ -92,12 +92,12 @@ if ( const OriginalDOMTokenListAdd = DOMTokenList.prototype.add; const OriginalDOMTokenListRemove = DOMTokenList.prototype.remove; - DOMTokenList.prototype.add = function(...tokens) { + DOMTokenList.prototype.add = function (...tokens) { for (const token of tokens) { OriginalDOMTokenListAdd.call(this, token); } }; - DOMTokenList.prototype.remove = function(...tokens) { + DOMTokenList.prototype.remove = function (...tokens) { for (const token of tokens) { OriginalDOMTokenListRemove.call(this, token); } @@ -116,7 +116,7 @@ if ( return; } - DOMTokenList.prototype.toggle = function(token) { + DOMTokenList.prototype.toggle = function (token) { const force = arguments.length > 1 ? !!arguments[1] : !this.contains(token); return this[force ? "add" : "remove"](token), force; @@ -133,11 +133,11 @@ if ( const OriginalPushState = window.history.pushState; const OriginalReplaceState = window.history.replaceState; - window.history.pushState = function(state, title, url) { + window.history.pushState = function (state, title, url) { const args = url === undefined ? [state, title] : [state, title, url]; OriginalPushState.apply(this, args); }; - window.history.replaceState = function(state, title, url) { + window.history.replaceState = function (state, title, url) { const args = url === undefined ? [state, title] : [state, title, url]; OriginalReplaceState.apply(this, args); }; diff --git a/src/shared/message_handler.js b/src/shared/message_handler.js index 5bcd1f65d..0be2961ec 100644 --- a/src/shared/message_handler.js +++ b/src/shared/message_handler.js @@ -116,10 +116,10 @@ class MessageHandler { if (data.callbackId) { const cbSourceName = this.sourceName; const cbTargetName = data.sourceName; - new Promise(function(resolve) { + new Promise(function (resolve) { resolve(action(data.data)); }).then( - function(result) { + function (result) { comObj.postMessage({ sourceName: cbSourceName, targetName: cbTargetName, @@ -128,7 +128,7 @@ class MessageHandler { data: result, }); }, - function(reason) { + function (reason) { comObj.postMessage({ sourceName: cbSourceName, targetName: cbTargetName, @@ -367,10 +367,10 @@ class MessageHandler { streamSink.sinkCapability.resolve(); streamSink.ready = streamSink.sinkCapability.promise; this.streamSinks[streamId] = streamSink; - new Promise(function(resolve) { + new Promise(function (resolve) { resolve(action(data.data, streamSink)); }).then( - function() { + function () { comObj.postMessage({ sourceName, targetName, @@ -379,7 +379,7 @@ class MessageHandler { success: true, }); }, - function(reason) { + function (reason) { comObj.postMessage({ sourceName, targetName, @@ -443,10 +443,10 @@ class MessageHandler { // Reset desiredSize property of sink on every pull. this.streamSinks[streamId].desiredSize = data.desiredSize; const { onPull } = this.streamSinks[data.streamId]; - new Promise(function(resolve) { + new Promise(function (resolve) { resolve(onPull && onPull()); }).then( - function() { + function () { comObj.postMessage({ sourceName, targetName, @@ -455,7 +455,7 @@ class MessageHandler { success: true, }); }, - function(reason) { + function (reason) { comObj.postMessage({ sourceName, targetName, @@ -513,10 +513,10 @@ class MessageHandler { break; } const { onCancel } = this.streamSinks[data.streamId]; - new Promise(function(resolve) { + new Promise(function (resolve) { resolve(onCancel && onCancel(wrapReason(data.reason))); }).then( - function() { + function () { comObj.postMessage({ sourceName, targetName, @@ -525,7 +525,7 @@ class MessageHandler { success: true, }); }, - function(reason) { + function (reason) { comObj.postMessage({ sourceName, targetName, @@ -557,7 +557,7 @@ class MessageHandler { this.streamControllers[streamId].startCall, this.streamControllers[streamId].pullCall, this.streamControllers[streamId].cancelCall, - ].map(function(capability) { + ].map(function (capability) { return capability && capability.promise; }) ); diff --git a/src/shared/util.js b/src/shared/util.js index dc4a4a2d8..f8d39116e 100644 --- a/src/shared/util.js +++ b/src/shared/util.js @@ -812,7 +812,7 @@ function isArrayEqual(arr1, arr2) { if (arr1.length !== arr2.length) { return false; } - return arr1.every(function(element, index) { + return arr1.every(function (element, index) { return element === arr2[index]; }); } @@ -842,12 +842,12 @@ function createPromiseCapability() { return isSettled; }, }); - capability.promise = new Promise(function(resolve, reject) { - capability.resolve = function(data) { + capability.promise = new Promise(function (resolve, reject) { + capability.resolve = function (data) { isSettled = true; resolve(data); }; - capability.reject = function(reason) { + capability.reject = function (reason) { isSettled = true; reject(reason); }; diff --git a/src/worker_loader.js b/src/worker_loader.js index 05f55c711..12b807a44 100644 --- a/src/worker_loader.js +++ b/src/worker_loader.js @@ -17,9 +17,9 @@ // Patch importScripts to work around a bug in WebKit and Chrome 48-. // See https://crbug.com/572225 and https://webkit.org/b/153317. -self.importScripts = (function(importScripts) { - return function() { - setTimeout(function() {}, 0); +self.importScripts = (function (importScripts) { + return function () { + setTimeout(function () {}, 0); return importScripts.apply(this, arguments); }; })(importScripts); @@ -27,6 +27,6 @@ self.importScripts = (function(importScripts) { importScripts("../node_modules/systemjs/dist/system.js"); importScripts("../systemjs.config.js"); -SystemJS.import("pdfjs/core/worker.js").then(function() { +SystemJS.import("pdfjs/core/worker.js").then(function () { // Worker is loaded at this point. }); diff --git a/systemjs.config.js b/systemjs.config.js index 5572b60e9..be9199781 100644 --- a/systemjs.config.js +++ b/systemjs.config.js @@ -15,7 +15,7 @@ "use strict"; -(function() { +(function () { var baseLocation; if (typeof document !== "undefined") { baseLocation = new URL("./", document.currentScript.src); diff --git a/test/add_test.js b/test/add_test.js index 9a2117960..1f3cd55e9 100644 --- a/test/add_test.js +++ b/test/add_test.js @@ -25,13 +25,13 @@ if (!fs.existsSync(file)) { function calculateMD5(pdfFile, callback) { var hash = crypto.createHash("md5"); var stream = fs.createReadStream(pdfFile); - stream.on("data", function(data) { + stream.on("data", function (data) { hash.update(data); }); - stream.on("error", function(err) { + stream.on("error", function (err) { callback(err); }); - stream.on("end", function() { + stream.on("end", function () { var result = hash.digest("hex"); callback(null, result); }); diff --git a/test/chromium/test-telemetry.js b/test/chromium/test-telemetry.js index c4a53f895..cd2f2c522 100755 --- a/test/chromium/test-telemetry.js +++ b/test/chromium/test-telemetry.js @@ -45,13 +45,13 @@ function createExtensionGlobal() { window.chrome.extension.inIncognitoContext = false; window.chrome.runtime = {}; window.chrome.runtime.id = "oemmndcbldboiebfnladdacbdfmadadm"; - window.chrome.runtime.getManifest = function() { + window.chrome.runtime.getManifest = function () { return { version: "1.0.0" }; }; function createStorageAPI() { var storageArea = {}; - storageArea.get = function(key, callback) { + storageArea.get = function (key, callback) { assert.equal(key, "disableTelemetry"); // chrome.storage.*. is async, but we make it synchronous to ease testing. callback(storageArea.mock_data); @@ -73,7 +73,7 @@ function createExtensionGlobal() { var getRandomValues_state = 0; window.crypto = {}; - window.crypto.getRandomValues = function(buf) { + window.crypto.getRandomValues = function (buf) { var state = getRandomValues_state++; for (var i = 0; i < buf.length; ++i) { // Totally random byte ;) @@ -89,38 +89,38 @@ function createExtensionGlobal() { throw new TypeError("Illegal invocation"); }, }; - window.fetch = function(url, options) { + window.fetch = function (url, options) { assert.equal(url, LOG_URL); assert.equal(options.method, "POST"); assert.equal(options.mode, "cors"); assert.ok(!options.body); test_requests.push(options.headers); }; - window.Headers = function(headers) { + window.Headers = function (headers) { headers = JSON.parse(JSON.stringify(headers)); // Clone. - Object.keys(headers).forEach(function(k) { + Object.keys(headers).forEach(function (k) { headers[k] = String(headers[k]); }); return headers; }; - window.XMLHttpRequest = function() { + window.XMLHttpRequest = function () { var invoked = { open: false, send: false, }; var headers = {}; return { - open: function(method, url) { + open: function (method, url) { assert.equal(invoked.open, false); invoked.open = true; assert.equal(method, "POST"); assert.equal(url, LOG_URL); }, - setRequestHeader: function(k, v) { + setRequestHeader: function (k, v) { assert.equal(invoked.open, true); headers[k] = String(v); }, - send: function(body) { + send: function (body) { assert.equal(invoked.open, true); assert.equal(invoked.send, false); invoked.send = true; @@ -132,19 +132,19 @@ function createExtensionGlobal() { // Time-related logic. var timers = []; - window.setInterval = function(callback, ms) { + window.setInterval = function (callback, ms) { assert.equal(typeof callback, "function"); timers.push(callback); }; window.Date = { test_now_value: Date.now(), - now: function() { + now: function () { return window.Date.test_now_value; }, }; - window.test_fireTimers = function() { + window.test_fireTimers = function () { assert.ok(timers.length); - timers.forEach(function(timer) { + timers.forEach(function (timer) { timer(); }); }; @@ -156,7 +156,7 @@ function createExtensionGlobal() { function updateBrowser(window) { window.navigator.userAgent = window.navigator.userAgent.replace( /Chrome\/(\d+)/, - function(_, v) { + function (_, v) { return "Chrome/" + (parseInt(v) + 1); } ); @@ -351,7 +351,7 @@ var tests = [ function test_extension_update() { var window = createExtensionGlobal(); telemetryScript.runInNewContext(window); - window.chrome.runtime.getManifest = function() { + window.chrome.runtime.getManifest = function () { return { version: "1.0.1" }; }; window.Date.test_now_value += 12 * 36e5; @@ -373,7 +373,7 @@ var tests = [ var window = createExtensionGlobal(); var didWarn = false; window.console = {}; - window.console.warn = function() { + window.console.warn = function () { didWarn = true; }; window.chrome.runtime.id = "abcdefghijklmnopabcdefghijklmnop"; @@ -413,7 +413,7 @@ var tests = [ function test_fetch_mode_not_supported() { var window = createExtensionGlobal(); delete window.Request.prototype.mode; - window.fetch = function() { + window.fetch = function () { throw new Error("Unexpected call to fetch!"); }; telemetryScript.runInNewContext(window); diff --git a/test/downloadutils.js b/test/downloadutils.js index 3f77a6821..eecbcaf89 100644 --- a/test/downloadutils.js +++ b/test/downloadutils.js @@ -40,7 +40,7 @@ function downloadFile(file, url, callback, redirects) { var completed = false; var protocol = /^https:\/\//.test(url) ? https : http; protocol - .get(url, function(response) { + .get(url, function (response) { var redirectTo; if ( response.statusCode === 301 || @@ -71,14 +71,14 @@ function downloadFile(file, url, callback, redirects) { return; } var stream = fs.createWriteStream(file); - stream.on("error", function(err) { + stream.on("error", function (err) { if (!completed) { completed = true; callback(err); } }); response.pipe(stream); - stream.on("finish", function() { + stream.on("finish", function () { stream.end(); if (!completed) { completed = true; @@ -86,7 +86,7 @@ function downloadFile(file, url, callback, redirects) { } }); }) - .on("error", function(err) { + .on("error", function (err) { if (!completed) { if ( typeof err === "object" && @@ -113,7 +113,7 @@ function downloadManifestFiles(manifest, callback) { var file = links[i].file; var url = links[i].url; console.log("Downloading " + url + " to " + file + "..."); - downloadFile(file, url, function(err) { + downloadFile(file, url, function (err) { if (err) { console.error("Error during downloading of " + url + ": " + err); fs.writeFileSync(file, ""); // making it empty file @@ -125,10 +125,10 @@ function downloadManifestFiles(manifest, callback) { } var links = manifest - .filter(function(item) { + .filter(function (item) { return item.link && !fs.existsSync(item.file); }) - .map(function(item) { + .map(function (item) { var file = item.file; var linkfile = file + ".link"; var url = fs.readFileSync(linkfile).toString(); @@ -143,13 +143,13 @@ function downloadManifestFiles(manifest, callback) { function calculateMD5(file, callback) { var hash = crypto.createHash("md5"); var stream = fs.createReadStream(file); - stream.on("data", function(data) { + stream.on("data", function (data) { hash.update(data); }); - stream.on("error", function(err) { + stream.on("error", function (err) { callback(err); }); - stream.on("end", function() { + stream.on("end", function () { var result = hash.digest("hex"); callback(null, result); }); @@ -171,7 +171,7 @@ function verifyManifestFiles(manifest, callback) { verifyNext(); return; } - calculateMD5(item.file, function(err, md5) { + calculateMD5(item.file, function (err, md5) { if (err) { console.log('WARNING: Unable to open file for reading "' + err + '".'); error = true; diff --git a/test/driver.js b/test/driver.js index 15f44a4a5..f86db197d 100644 --- a/test/driver.js +++ b/test/driver.js @@ -34,10 +34,10 @@ var rasterizeTextLayer = (function rasterizeTextLayerClosure() { if (textLayerStylePromise) { return textLayerStylePromise; } - textLayerStylePromise = new Promise(function(resolve) { + textLayerStylePromise = new Promise(function (resolve) { var xhr = new XMLHttpRequest(); xhr.open("GET", "./text_layer_test.css"); - xhr.onload = function() { + xhr.onload = function () { resolve(xhr.responseText); }; xhr.send(null); @@ -52,7 +52,7 @@ var rasterizeTextLayer = (function rasterizeTextLayerClosure() { textContent, enhanceTextSelection ) { - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { // Building SVG with size of the viewport. var svg = document.createElementNS(SVG_NS, "svg:svg"); svg.setAttribute("width", viewport.width + "px"); @@ -80,7 +80,7 @@ var rasterizeTextLayer = (function rasterizeTextLayerClosure() { viewport, enhanceTextSelection, }); - Promise.all([stylePromise, task.promise]).then(function(results) { + Promise.all([stylePromise, task.promise]).then(function (results) { task.expandTextDivs(true); style.textContent = results[0]; svg.appendChild(foreignObject); @@ -91,11 +91,11 @@ var rasterizeTextLayer = (function rasterizeTextLayerClosure() { ); var img = new Image(); img.src = "data:image/svg+xml;base64," + btoa(svg_xml); - img.onload = function() { + img.onload = function () { ctx.drawImage(img, 0, 0); resolve(); }; - img.onerror = function(e) { + img.onerror = function (e) { reject(new Error("Error rasterizing text layer " + e)); }; }); @@ -139,13 +139,13 @@ var rasterizeAnnotationLayer = (function rasterizeAnnotationLayerClosure() { // Load the style files and cache the results. for (const key in styles) { - styles[key].promise = new Promise(function(resolve, reject) { + styles[key].promise = new Promise(function (resolve, reject) { const xhr = new XMLHttpRequest(); xhr.open("GET", styles[key].file); - xhr.onload = function() { + xhr.onload = function () { resolve(xhr.responseText); }; - xhr.onerror = function(e) { + xhr.onerror = function (e) { reject(new Error("Error fetching annotation style " + e)); }; xhr.send(null); @@ -158,17 +158,17 @@ var rasterizeAnnotationLayer = (function rasterizeAnnotationLayerClosure() { function inlineAnnotationImages(images) { var imagePromises = []; for (var i = 0, ii = images.length; i < ii; i++) { - var imagePromise = new Promise(function(resolve, reject) { + var imagePromise = new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest(); xhr.responseType = "blob"; - xhr.onload = function() { + xhr.onload = function () { var reader = new FileReader(); - reader.onloadend = function() { + reader.onloadend = function () { resolve(reader.result); }; reader.readAsDataURL(xhr.response); }; - xhr.onerror = function(e) { + xhr.onerror = function (e) { reject(new Error("Error fetching inline annotation image " + e)); }; xhr.open("GET", images[i].src); @@ -188,7 +188,7 @@ var rasterizeAnnotationLayer = (function rasterizeAnnotationLayerClosure() { imageResourcesPath, renderInteractiveForms ) { - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { // Building SVG with size of the viewport. var svg = document.createElementNS(SVG_NS, "svg:svg"); svg.setAttribute("width", viewport.width + "px"); @@ -207,7 +207,7 @@ var rasterizeAnnotationLayer = (function rasterizeAnnotationLayerClosure() { div.className = "annotationLayer"; // Rendering annotation layer as HTML. - stylePromise.then(function(common, overrides) { + stylePromise.then(function (common, overrides) { style.textContent = common + overrides; var annotation_viewport = viewport.clone({ dontFlip: true }); @@ -225,14 +225,14 @@ var rasterizeAnnotationLayer = (function rasterizeAnnotationLayerClosure() { // Inline SVG images from text annotations. var images = div.getElementsByTagName("img"); var imagePromises = inlineAnnotationImages(images); - var converted = Promise.all(imagePromises).then(function(data) { + var converted = Promise.all(imagePromises).then(function (data) { var loadedPromises = []; for (var i = 0, ii = data.length; i < ii; i++) { images[i].src = data[i]; loadedPromises.push( - new Promise(function(resolveImage, rejectImage) { + new Promise(function (resolveImage, rejectImage) { images[i].onload = resolveImage; - images[i].onerror = function(e) { + images[i].onerror = function (e) { rejectImage(new Error("Error loading image " + e)); }; }) @@ -245,17 +245,17 @@ var rasterizeAnnotationLayer = (function rasterizeAnnotationLayerClosure() { svg.appendChild(foreignObject); // We need to have UTF-8 encoded XML. - converted.then(function() { + converted.then(function () { var svg_xml = unescape( encodeURIComponent(new XMLSerializer().serializeToString(svg)) ); var img = new Image(); img.src = "data:image/svg+xml;base64," + btoa(svg_xml); - img.onload = function() { + img.onload = function () { ctx.drawImage(img, 0, 0); resolve(); }; - img.onerror = function(e) { + img.onerror = function (e) { reject(new Error("Error rasterizing annotation layer " + e)); }; }); @@ -325,7 +325,7 @@ var Driver = (function DriverClosure() { run: function Driver_run() { var self = this; - window.onerror = function(message, source, line, column, error) { + window.onerror = function (message, source, line, column, error) { self._info( "Error: " + message + @@ -351,12 +351,12 @@ var Driver = (function DriverClosure() { var r = new XMLHttpRequest(); r.open("GET", this.manifestFile, false); - r.onreadystatechange = function() { + r.onreadystatechange = function () { if (r.readyState === 4) { self._log("done\n"); self.manifest = JSON.parse(r.responseText); if (self.testFilter && self.testFilter.length) { - self.manifest = self.manifest.filter(function(item) { + self.manifest = self.manifest.filter(function (item) { return self.testFilter.includes(item.id); }); } @@ -369,7 +369,7 @@ var Driver = (function DriverClosure() { } // When gathering the stats the numbers seem to be more reliable // if the browser is given more time to start. - setTimeout(function() { + setTimeout(function () { r.send(null); }, this.delay); }, @@ -472,7 +472,7 @@ var Driver = (function DriverClosure() { if (!task.pdfDoc) { var dataUrl = this.canvas.toDataURL("image/png"); - this._sendResult(dataUrl, task, failure, function() { + this._sendResult(dataUrl, task, failure, function () { self._log( "done" + (failure ? " (failed !: " + failure + ")" : "") + "\n" ); @@ -518,7 +518,7 @@ var Driver = (function DriverClosure() { this.canvas.mozOpaque = true; ctx = this.canvas.getContext("2d", { alpha: false }); task.pdfDoc.getPage(task.pageNum).then( - function(page) { + function (page) { var viewport = page.getViewport({ scale: PDF_TO_CSS_UNITS }); self.canvas.width = viewport.width; self.canvas.height = viewport.height; @@ -552,7 +552,7 @@ var Driver = (function DriverClosure() { .getTextContent({ normalizeWhitespace: true, }) - .then(function(textContent) { + .then(function (textContent) { return rasterizeTextLayer( textLayerContext, viewport, @@ -590,7 +590,7 @@ var Driver = (function DriverClosure() { // The annotation builder will draw its content on the canvas. initPromise = page .getAnnotations({ intent: "display" }) - .then(function(annotations) { + .then(function (annotations) { return rasterizeAnnotationLayer( annotationLayerContext, viewport, @@ -611,7 +611,7 @@ var Driver = (function DriverClosure() { viewport, renderInteractiveForms: renderForms, }; - var completeRender = function(error) { + var completeRender = function (error) { // if text layer is present, compose it on top of the page if (textLayerCanvas) { ctx.save(); @@ -633,16 +633,16 @@ var Driver = (function DriverClosure() { self._snapshot(task, error); }; initPromise - .then(function() { - return page.render(renderContext).promise.then(function() { + .then(function () { + return page.render(renderContext).promise.then(function () { completeRender(false); }); }) - .catch(function(error) { + .catch(function (error) { completeRender("render : " + error); }); }, - function(error) { + function (error) { self._snapshot(task, "render : " + error); } ); @@ -664,7 +664,7 @@ var Driver = (function DriverClosure() { this._log("Snapshotting... "); var dataUrl = this.canvas.toDataURL("image/png"); - this._sendResult(dataUrl, task, failure, function() { + this._sendResult(dataUrl, task, failure, function () { self._log( "done" + (failure ? " (failed !: " + failure + ")" : "") + "\n" ); @@ -680,7 +680,7 @@ var Driver = (function DriverClosure() { // Send the quit request var r = new XMLHttpRequest(); r.open("POST", "/tellMeToQuit?path=" + escape(this.appPath), false); - r.onreadystatechange = function(e) { + r.onreadystatechange = function (e) { if (r.readyState === 4) { window.close(); } @@ -744,13 +744,13 @@ var Driver = (function DriverClosure() { var r = new XMLHttpRequest(); r.open("POST", url, true); r.setRequestHeader("Content-Type", "application/json"); - r.onreadystatechange = function(e) { + r.onreadystatechange = function (e) { if (r.readyState === 4) { self.inFlightRequests--; // Retry until successful if (r.status !== 200) { - setTimeout(function() { + setTimeout(function () { self._send(url, message); }); } diff --git a/test/font/jasmine-boot.js b/test/font/jasmine-boot.js index 0325383dc..6b20acef9 100644 --- a/test/font/jasmine-boot.js +++ b/test/font/jasmine-boot.js @@ -46,7 +46,7 @@ function initializePDFJS(callback) { SystemJS.import("pdfjs/core/stream.js"), SystemJS.import("pdfjs/core/primitives.js"), SystemJS.import("pdfjs/core/cmap.js"), - ]).then(function(modules) { + ]).then(function (modules) { var fonts = modules[0], stream = modules[1], primitives = modules[2], @@ -62,7 +62,7 @@ function initializePDFJS(callback) { }); } -(function() { +(function () { window.jasmine = jasmineRequire.core(jasmineRequire); jasmineRequire.html(jasmine); @@ -134,7 +134,7 @@ function initializePDFJS(callback) { }, }); - config.specFilter = function(spec) { + config.specFilter = function (spec) { return specFilter.matches(spec.getFullName()); }; @@ -148,12 +148,12 @@ function initializePDFJS(callback) { // instance and then executing the loaded Jasmine environment. var currentWindowOnload = window.onload; - window.onload = function() { + window.onload = function () { if (currentWindowOnload) { currentWindowOnload(); } - initializePDFJS(function() { + initializePDFJS(function () { htmlReporter.initialize(); env.execute(); }); diff --git a/test/font/ttxdriver.js b/test/font/ttxdriver.js index 61c3275f2..52d46f6a6 100644 --- a/test/font/ttxdriver.js +++ b/test/font/ttxdriver.js @@ -25,9 +25,9 @@ var ttxResourcesHome = path.join(__dirname, "..", "ttx"); var nextTTXTaskId = Date.now(); function runTtx(ttxResourcesHomePath, fontPath, registerOnCancel, callback) { - fs.realpath(ttxResourcesHomePath, function(error, realTtxResourcesHomePath) { + fs.realpath(ttxResourcesHomePath, function (error, realTtxResourcesHomePath) { var fontToolsHome = path.join(realTtxResourcesHomePath, "fonttools-code"); - fs.realpath(fontPath, function(errorFontPath, realFontPath) { + fs.realpath(fontPath, function (errorFontPath, realFontPath) { var ttxPath = path.join("Tools", "ttx"); if (!fs.existsSync(path.join(fontToolsHome, ttxPath))) { callback("TTX was not found, please checkout PDF.js submodules"); @@ -44,16 +44,16 @@ function runTtx(ttxResourcesHomePath, fontPath, registerOnCancel, callback) { env: ttxEnv, }); var ttxRunError; - registerOnCancel(function(reason) { + registerOnCancel(function (reason) { ttxRunError = reason; callback(reason); ttx.kill(); }); - ttx.on("error", function(errorTtx) { + ttx.on("error", function (errorTtx) { ttxRunError = errorTtx; callback("Unable to execute ttx"); }); - ttx.on("close", function(code) { + ttx.on("close", function (code) { if (ttxRunError) { return; } @@ -74,7 +74,7 @@ exports.translateFont = function translateFont( var resultPath = path.join(ttxResourcesHome, taskId + ".ttx"); fs.writeFileSync(fontPath, buffer); - runTtx(ttxResourcesHome, fontPath, registerOnCancel, function(err) { + runTtx(ttxResourcesHome, fontPath, registerOnCancel, function (err) { fs.unlinkSync(fontPath); if (err) { console.error(err); diff --git a/test/stats/statcmp.js b/test/stats/statcmp.js index e7b7204f4..056b3381e 100644 --- a/test/stats/statcmp.js +++ b/test/stats/statcmp.js @@ -57,8 +57,8 @@ function group(stats, groupBy) { */ function flatten(stats) { var rows = []; - stats.forEach(function(curStat) { - curStat["stats"].forEach(function(s) { + stats.forEach(function (curStat) { + curStat["stats"].forEach(function (s) { rows.push({ browser: curStat["browser"], page: curStat["page"], @@ -71,7 +71,7 @@ function flatten(stats) { }); // Use only overall results if not grouped by 'stat' if (!options.groupBy.includes("stat")) { - rows = rows.filter(function(s) { + rows = rows.filter(function (s) { return s.stat === "Overall"; }); } @@ -138,7 +138,7 @@ function stat(baseline, current) { row, rows = []; // collect rows and measure column widths - var width = labels.map(function(s) { + var width = labels.map(function (s) { return s.length; }); rows.push(labels); @@ -172,7 +172,7 @@ function stat(baseline, current) { } // add horizontal line - var hline = width.map(function(w) { + var hline = width.map(function (w) { return new Array(w + 1).join("-"); }); rows.splice(1, 0, hline); diff --git a/test/test.js b/test/test.js index 5cc7bbf29..4f1d59a34 100644 --- a/test/test.js +++ b/test/test.js @@ -27,7 +27,7 @@ var testUtils = require("./testutils.js"); function parseOptions() { function describeCheck(fn, text) { - fn.toString = function() { + fn.toString = function () { return text; }; return fn; @@ -102,7 +102,7 @@ function parseOptions() { ) .default("statsDelay", 0) .check( - describeCheck(function(argv) { + describeCheck(function (argv) { return ( +argv.reftest + argv.unitTest + argv.fontTest + argv.masterMode <= 1 ); @@ -110,18 +110,18 @@ function parseOptions() { "specified at the same time.") ) .check( - describeCheck(function(argv) { + describeCheck(function (argv) { return !argv.noDownload || !argv.downloadOnly; }, "--noDownload and --downloadOnly cannot be used together.") ) .check( - describeCheck(function(argv) { + describeCheck(function (argv) { return !argv.masterMode || argv.manifestFile === "test_manifest.json"; }, "when --masterMode is specified --manifestFile shall be equal " + "test_manifest.json") ) .check( - describeCheck(function(argv) { + describeCheck(function (argv) { return !argv.browser || !argv.browserManifestFile; }, "--browser and --browserManifestFile must not be specified at the " + "same time.") @@ -151,7 +151,7 @@ function monitorBrowserTimeout(session, onTimeout) { session.timeoutMonitor = null; return; } - session.timeoutMonitor = setTimeout(function() { + session.timeoutMonitor = setTimeout(function () { onTimeout(session); }, browserTimeout * 1000); } @@ -172,7 +172,7 @@ function updateRefImages() { } testUtils.confirm( "Would you like to update the master copy in ref/? [yn] ", - function(confirmed) { + function (confirmed) { if (confirmed) { sync(true); } else { @@ -203,7 +203,7 @@ function startRefTest(masterMode, showRefImages) { var numFBFFailures = 0; var numEqFailures = 0; var numEqNoSnapshot = 0; - sessions.forEach(function(session) { + sessions.forEach(function (session) { numErrors += session.numErrors; numFBFFailures += session.numFBFFailures; numEqFailures += session.numEqFailures; @@ -274,12 +274,12 @@ function startRefTest(masterMode, showRefImages) { server.hooks["POST"].push(refTestPostHandler); onAllSessionsClosed = finalize; - startBrowsers("/test/test_slave.html", function(session) { + startBrowsers("/test/test_slave.html", function (session) { session.masterMode = masterMode; session.taskResults = {}; session.tasks = {}; session.remaining = manifest.length; - manifest.forEach(function(item) { + manifest.forEach(function (item) { var rounds = item.rounds || 1; var roundsResults = []; roundsResults.length = rounds; @@ -304,7 +304,7 @@ function startRefTest(masterMode, showRefImages) { console.log("tmp/ can be removed if it has nothing you need."); testUtils.confirm( "SHOULD THIS SCRIPT REMOVE tmp/? THINK CAREFULLY [yn] ", - function(confirmed) { + function (confirmed) { if (confirmed) { testUtils.removeDirSync(refsTmpDir); } @@ -350,7 +350,7 @@ function getTestManifest() { var testFilter = options.testfilter.slice(0); if (testFilter.length) { - manifest = manifest.filter(function(item) { + manifest = manifest.filter(function (item) { var i = testFilter.indexOf(item.id); if (i !== -1) { testFilter.splice(i, 1); @@ -533,8 +533,8 @@ function checkRefTestResults(browser, id, results) { var failed = false; var session = getSession(browser); var task = session.tasks[id]; - results.forEach(function(roundResults, round) { - roundResults.forEach(function(pageResult, page) { + results.forEach(function (roundResults, round) { + roundResults.forEach(function (pageResult, page) { if (!pageResult) { return; // no results } @@ -589,8 +589,8 @@ function checkRefTestResults(browser, id, results) { throw new Error("Unknown test type"); } // clear memory - results.forEach(function(roundResults, round) { - roundResults.forEach(function(pageResult, page) { + results.forEach(function (roundResults, round) { + roundResults.forEach(function (pageResult, page) { pageResult.snapshot = null; }); }); @@ -608,10 +608,10 @@ function refTestPostHandler(req, res) { } var body = ""; - req.on("data", function(data) { + req.on("data", function (data) { body += data; }); - req.on("end", function() { + req.on("end", function () { res.writeHead(200, { "Content-Type": "text/plain" }); res.end(); @@ -619,7 +619,7 @@ function refTestPostHandler(req, res) { if (pathname === "/tellMeToQuit") { // finding by path var browserPath = parsedUrl.query.path; - session = sessions.filter(function(curSession) { + session = sessions.filter(function (curSession) { return curSession.config.path === browserPath; })[0]; monitorBrowserTimeout(session, null); @@ -693,11 +693,11 @@ function startUnitTest(testUrl, name) { var startTime = Date.now(); startServer(); server.hooks["POST"].push(unitTestPostHandler); - onAllSessionsClosed = function() { + onAllSessionsClosed = function () { stopServer(); var numRuns = 0, numErrors = 0; - sessions.forEach(function(session) { + sessions.forEach(function (session) { numRuns += session.numRuns; numErrors += session.numErrors; }); @@ -712,7 +712,7 @@ function startUnitTest(testUrl, name) { var runtime = (Date.now() - startTime) / 1000; console.log(name + " tests runtime was " + runtime.toFixed(1) + " seconds"); }; - startBrowsers(testUrl, function(session) { + startBrowsers(testUrl, function (session) { session.numRuns = 0; session.numErrors = 0; }); @@ -731,25 +731,25 @@ function unitTestPostHandler(req, res) { } var body = ""; - req.on("data", function(data) { + req.on("data", function (data) { body += data; }); - req.on("end", function() { + req.on("end", function () { if (pathname === "/ttx") { var translateFont = require("./font/ttxdriver.js").translateFont; var onCancel = null, ttxTimeout = 10000; - var timeoutId = setTimeout(function() { + var timeoutId = setTimeout(function () { if (onCancel) { onCancel("TTX timeout"); } }, ttxTimeout); translateFont( body, - function(fn) { + function (fn) { onCancel = fn; }, - function(err, xml) { + function (err, xml) { clearTimeout(timeoutId); res.writeHead(200, { "Content-Type": "text/xml" }); res.end(err ? "" + err + "" : xml); @@ -797,7 +797,7 @@ function startBrowsers(testUrl, initSessionCallback) { process.exit(1); } sessions = []; - browsers.forEach(function(b) { + browsers.forEach(function (b) { var browser = WebBrowser.create(b); var startUrl = getServerBaseAddress() + @@ -846,7 +846,7 @@ function stopServer() { } function getSession(browser) { - return sessions.filter(function(session) { + return sessions.filter(function (session) { return session.name === browser; })[0]; } @@ -858,9 +858,9 @@ function closeSession(browser) { } if (i < sessions.length) { var session = sessions[i]; - session.browser.stop(function() { + session.browser.stop(function () { session.closed = true; - var allClosed = sessions.every(function(s) { + var allClosed = sessions.every(function (s) { return s.closed; }); if (allClosed && onAllSessionsClosed) { @@ -873,8 +873,8 @@ function closeSession(browser) { function ensurePDFsDownloaded(callback) { var downloadUtils = require("./downloadutils.js"); var manifest = getTestManifest(); - downloadUtils.downloadManifestFiles(manifest, function() { - downloadUtils.verifyManifestFiles(manifest, function(hasErrors) { + downloadUtils.downloadManifestFiles(manifest, function () { + downloadUtils.verifyManifestFiles(manifest, function (hasErrors) { if (hasErrors) { console.log( "Unable to verify the checksum for the files that are " + @@ -899,12 +899,12 @@ function main() { } if (options.downloadOnly) { - ensurePDFsDownloaded(function() {}); + ensurePDFsDownloaded(function () {}); } else if (!options.browser && !options.browserManifestFile) { startServer(); } else if (options.unitTest) { // Allows linked PDF files in unit-tests as well. - ensurePDFsDownloaded(function() { + ensurePDFsDownloaded(function () { startUnitTest("/test/unit/unit_test.html", "unit"); }); } else if (options.fontTest) { diff --git a/test/testutils.js b/test/testutils.js index 99e824d7b..8113d949f 100644 --- a/test/testutils.js +++ b/test/testutils.js @@ -32,7 +32,7 @@ exports.copySubtreeSync = function copySubtreeSync(src, dest) { if (!fs.existsSync(dest)) { fs.mkdirSync(dest); } - files.forEach(function(filename) { + files.forEach(function (filename) { var srcFile = path.join(src, filename); var file = path.join(dest, filename); var stats = fs.statSync(srcFile); @@ -99,12 +99,12 @@ function handleStdinBuffer() { function initStdin() { process.stdin.setEncoding("utf8"); - process.stdin.on("data", function(chunk) { + process.stdin.on("data", function (chunk) { stdinBuffer += chunk; handleStdinBuffer(); }); - process.stdin.on("end", function() { + process.stdin.on("end", function () { endOfStdin = true; handleStdinBuffer(); }); @@ -125,7 +125,7 @@ exports.prompt = function prompt(message, callback) { }; exports.confirm = function confirm(message, callback) { - exports.prompt(message, function(answer) { + exports.prompt(message, function (answer) { if (answer === undefined) { callback(); return; diff --git a/test/unit/annotation_spec.js b/test/unit/annotation_spec.js index 1a5a37707..100ca9dbb 100644 --- a/test/unit/annotation_spec.js +++ b/test/unit/annotation_spec.js @@ -33,14 +33,14 @@ import { Dict, Name, Ref } from "../../src/core/primitives.js"; import { Lexer, Parser } from "../../src/core/parser.js"; import { StringStream } from "../../src/core/stream.js"; -describe("annotation", function() { +describe("annotation", function () { class PDFManagerMock { constructor(params) { this.docBaseUrl = params.docBaseUrl || null; } ensure(obj, prop, args) { - return new Promise(function(resolve) { + return new Promise(function (resolve) { const value = obj[prop]; if (typeof value === "function") { resolve(value.apply(obj, args)); @@ -53,7 +53,7 @@ describe("annotation", function() { let pdfManagerMock, idFactoryMock; - beforeAll(function(done) { + beforeAll(function (done) { pdfManagerMock = new PDFManagerMock({ docBaseUrl: null, }); @@ -61,13 +61,13 @@ describe("annotation", function() { done(); }); - afterAll(function() { + afterAll(function () { pdfManagerMock = null; idFactoryMock = null; }); - describe("AnnotationFactory", function() { - it("should get id for annotation", function(done) { + describe("AnnotationFactory", function () { + it("should get id for annotation", function (done) { const annotationDict = new Dict(); annotationDict.set("Type", Name.get("Annot")); annotationDict.set("Subtype", Name.get("Link")); @@ -90,7 +90,7 @@ describe("annotation", function() { it( "should handle, and get fallback IDs for, annotations that are not " + "indirect objects (issue 7569)", - function(done) { + function (done) { const annotationDict = new Dict(); annotationDict.set("Type", Name.get("Annot")); annotationDict.set("Subtype", Name.get("Link")); @@ -122,7 +122,7 @@ describe("annotation", function() { } ); - it("should handle missing /Subtype", function(done) { + it("should handle missing /Subtype", function (done) { const annotationDict = new Dict(); annotationDict.set("Type", Name.get("Annot")); @@ -141,35 +141,35 @@ describe("annotation", function() { }); }); - describe("getQuadPoints", function() { + describe("getQuadPoints", function () { let dict, rect; - beforeEach(function(done) { + beforeEach(function (done) { dict = new Dict(); rect = []; done(); }); - afterEach(function() { + afterEach(function () { dict = null; rect = null; }); - it("should ignore missing quadpoints", function() { + it("should ignore missing quadpoints", function () { expect(getQuadPoints(dict, rect)).toEqual(null); }); - it("should ignore non-array values", function() { + it("should ignore non-array values", function () { dict.set("QuadPoints", "foo"); expect(getQuadPoints(dict, rect)).toEqual(null); }); - it("should ignore arrays where the length is not a multiple of eight", function() { + it("should ignore arrays where the length is not a multiple of eight", function () { dict.set("QuadPoints", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); expect(getQuadPoints(dict, rect)).toEqual(null); }); - it("should ignore quadpoints if one coordinate lies outside the rectangle", function() { + it("should ignore quadpoints if one coordinate lies outside the rectangle", function () { rect = [10, 10, 20, 20]; const inputs = [ [11, 11, 12, 12, 9, 13, 14, 14], // Smaller than lower x coordinate. @@ -183,7 +183,7 @@ describe("annotation", function() { } }); - it("should process valid quadpoints arrays", function() { + it("should process valid quadpoints arrays", function () { rect = [10, 10, 20, 20]; dict.set("QuadPoints", [ 11, @@ -220,48 +220,48 @@ describe("annotation", function() { }); }); - describe("Annotation", function() { + describe("Annotation", function () { let dict, ref; - beforeAll(function(done) { + beforeAll(function (done) { dict = new Dict(); ref = Ref.get(1, 0); done(); }); - afterAll(function() { + afterAll(function () { dict = ref = null; }); - it("should set and get valid contents", function() { + it("should set and get valid contents", function () { const annotation = new Annotation({ dict, ref }); annotation.setContents("Foo bar baz"); expect(annotation.contents).toEqual("Foo bar baz"); }); - it("should not set and get invalid contents", function() { + it("should not set and get invalid contents", function () { const annotation = new Annotation({ dict, ref }); annotation.setContents(undefined); expect(annotation.contents).toEqual(""); }); - it("should set and get a valid modification date", function() { + it("should set and get a valid modification date", function () { const annotation = new Annotation({ dict, ref }); annotation.setModificationDate("D:20190422"); expect(annotation.modificationDate).toEqual("D:20190422"); }); - it("should not set and get an invalid modification date", function() { + it("should not set and get an invalid modification date", function () { const annotation = new Annotation({ dict, ref }); annotation.setModificationDate(undefined); expect(annotation.modificationDate).toEqual(null); }); - it("should set and get flags", function() { + it("should set and get flags", function () { const annotation = new Annotation({ dict, ref }); annotation.setFlags(13); @@ -271,63 +271,63 @@ describe("annotation", function() { expect(annotation.hasFlag(AnnotationFlag.READONLY)).toEqual(false); }); - it("should be viewable and not printable by default", function() { + it("should be viewable and not printable by default", function () { const annotation = new Annotation({ dict, ref }); expect(annotation.viewable).toEqual(true); expect(annotation.printable).toEqual(false); }); - it("should set and get a valid rectangle", function() { + it("should set and get a valid rectangle", function () { const annotation = new Annotation({ dict, ref }); annotation.setRectangle([117, 694, 164.298, 720]); expect(annotation.rectangle).toEqual([117, 694, 164.298, 720]); }); - it("should not set and get an invalid rectangle", function() { + it("should not set and get an invalid rectangle", function () { const annotation = new Annotation({ dict, ref }); annotation.setRectangle([117, 694, 164.298]); expect(annotation.rectangle).toEqual([0, 0, 0, 0]); }); - it("should reject a color if it is not an array", function() { + it("should reject a color if it is not an array", function () { const annotation = new Annotation({ dict, ref }); annotation.setColor("red"); expect(annotation.color).toEqual(new Uint8ClampedArray([0, 0, 0])); }); - it("should set and get a transparent color", function() { + it("should set and get a transparent color", function () { const annotation = new Annotation({ dict, ref }); annotation.setColor([]); expect(annotation.color).toEqual(null); }); - it("should set and get a grayscale color", function() { + it("should set and get a grayscale color", function () { const annotation = new Annotation({ dict, ref }); annotation.setColor([0.4]); expect(annotation.color).toEqual(new Uint8ClampedArray([102, 102, 102])); }); - it("should set and get an RGB color", function() { + it("should set and get an RGB color", function () { const annotation = new Annotation({ dict, ref }); annotation.setColor([0, 0, 1]); expect(annotation.color).toEqual(new Uint8ClampedArray([0, 0, 255])); }); - it("should set and get a CMYK color", function() { + it("should set and get a CMYK color", function () { const annotation = new Annotation({ dict, ref }); annotation.setColor([0.1, 0.92, 0.84, 0.02]); expect(annotation.color).toEqual(new Uint8ClampedArray([234, 59, 48])); }); - it("should not set and get an invalid color", function() { + it("should not set and get an invalid color", function () { const annotation = new Annotation({ dict, ref }); annotation.setColor([0.4, 0.6]); @@ -335,22 +335,22 @@ describe("annotation", function() { }); }); - describe("AnnotationBorderStyle", function() { - it("should set and get a valid width", function() { + describe("AnnotationBorderStyle", function () { + it("should set and get a valid width", function () { const borderStyle = new AnnotationBorderStyle(); borderStyle.setWidth(3); expect(borderStyle.width).toEqual(3); }); - it("should not set and get an invalid width", function() { + it("should not set and get an invalid width", function () { const borderStyle = new AnnotationBorderStyle(); borderStyle.setWidth("three"); expect(borderStyle.width).toEqual(1); }); - it("should set the width to zero, when the input is a `Name` (issue 10385)", function() { + it("should set the width to zero, when the input is a `Name` (issue 10385)", function () { const borderStyleZero = new AnnotationBorderStyle(); borderStyleZero.setWidth(Name.get("0")); const borderStyleFive = new AnnotationBorderStyle(); @@ -360,56 +360,56 @@ describe("annotation", function() { expect(borderStyleFive.width).toEqual(0); }); - it("should set and get a valid style", function() { + it("should set and get a valid style", function () { const borderStyle = new AnnotationBorderStyle(); borderStyle.setStyle(Name.get("D")); expect(borderStyle.style).toEqual(AnnotationBorderStyleType.DASHED); }); - it("should not set and get an invalid style", function() { + it("should not set and get an invalid style", function () { const borderStyle = new AnnotationBorderStyle(); borderStyle.setStyle("Dashed"); expect(borderStyle.style).toEqual(AnnotationBorderStyleType.SOLID); }); - it("should set and get a valid dash array", function() { + it("should set and get a valid dash array", function () { const borderStyle = new AnnotationBorderStyle(); borderStyle.setDashArray([1, 2, 3]); expect(borderStyle.dashArray).toEqual([1, 2, 3]); }); - it("should not set and get an invalid dash array", function() { + it("should not set and get an invalid dash array", function () { const borderStyle = new AnnotationBorderStyle(); borderStyle.setDashArray([0, 0]); expect(borderStyle.dashArray).toEqual([3]); }); - it("should set and get a valid horizontal corner radius", function() { + it("should set and get a valid horizontal corner radius", function () { const borderStyle = new AnnotationBorderStyle(); borderStyle.setHorizontalCornerRadius(3); expect(borderStyle.horizontalCornerRadius).toEqual(3); }); - it("should not set and get an invalid horizontal corner radius", function() { + it("should not set and get an invalid horizontal corner radius", function () { const borderStyle = new AnnotationBorderStyle(); borderStyle.setHorizontalCornerRadius("three"); expect(borderStyle.horizontalCornerRadius).toEqual(0); }); - it("should set and get a valid vertical corner radius", function() { + it("should set and get a valid vertical corner radius", function () { const borderStyle = new AnnotationBorderStyle(); borderStyle.setVerticalCornerRadius(3); expect(borderStyle.verticalCornerRadius).toEqual(3); }); - it("should not set and get an invalid vertical corner radius", function() { + it("should not set and get an invalid vertical corner radius", function () { const borderStyle = new AnnotationBorderStyle(); borderStyle.setVerticalCornerRadius("three"); @@ -417,34 +417,34 @@ describe("annotation", function() { }); }); - describe("MarkupAnnotation", function() { + describe("MarkupAnnotation", function () { let dict, ref; - beforeAll(function(done) { + beforeAll(function (done) { dict = new Dict(); ref = Ref.get(1, 0); done(); }); - afterAll(function() { + afterAll(function () { dict = ref = null; }); - it("should set and get a valid creation date", function() { + it("should set and get a valid creation date", function () { const markupAnnotation = new MarkupAnnotation({ dict, ref }); markupAnnotation.setCreationDate("D:20190422"); expect(markupAnnotation.creationDate).toEqual("D:20190422"); }); - it("should not set and get an invalid creation date", function() { + it("should not set and get an invalid creation date", function () { const markupAnnotation = new MarkupAnnotation({ dict, ref }); markupAnnotation.setCreationDate(undefined); expect(markupAnnotation.creationDate).toEqual(null); }); - it("should not parse IRT/RT when not defined", function(done) { + it("should not parse IRT/RT when not defined", function (done) { dict.set("Type", Name.get("Annot")); dict.set("Subtype", Name.get("Text")); @@ -460,7 +460,7 @@ describe("annotation", function() { ); }); - it("should parse IRT and set default RT when not defined.", function(done) { + it("should parse IRT and set default RT when not defined.", function (done) { const annotationRef = Ref.get(819, 0); const annotationDict = new Dict(); annotationDict.set("Type", Name.get("Annot")); @@ -491,7 +491,7 @@ describe("annotation", function() { }, done.fail); }); - it("should parse IRT/RT for a group type", function(done) { + it("should parse IRT/RT for a group type", function (done) { const annotationRef = Ref.get(819, 0); const annotationDict = new Dict(); annotationDict.set("Type", Name.get("Annot")); @@ -548,7 +548,7 @@ describe("annotation", function() { }, done.fail); }); - it("should parse IRT/RT for a reply type", function(done) { + it("should parse IRT/RT for a reply type", function (done) { const annotationRef = Ref.get(819, 0); const annotationDict = new Dict(); annotationDict.set("Type", Name.get("Annot")); @@ -606,8 +606,8 @@ describe("annotation", function() { }); }); - describe("TextAnnotation", function() { - it("should not parse state model and state when not defined", function(done) { + describe("TextAnnotation", function () { + it("should not parse state model and state when not defined", function (done) { const annotationRef = Ref.get(819, 0); const annotationDict = new Dict(); annotationDict.set("Type", Name.get("Annot")); @@ -641,7 +641,7 @@ describe("annotation", function() { }, done.fail); }); - it("should correctly parse state model and state when defined", function(done) { + it("should correctly parse state model and state when defined", function (done) { const annotationRef = Ref.get(819, 0); const annotationDict = new Dict(); annotationDict.set("Type", Name.get("Annot")); @@ -676,8 +676,8 @@ describe("annotation", function() { }); }); - describe("LinkAnnotation", function() { - it("should correctly parse a URI action", function(done) { + describe("LinkAnnotation", function () { + it("should correctly parse a URI action", function (done) { const actionDict = new Dict(); actionDict.set("Type", Name.get("Action")); actionDict.set("S", Name.get("URI")); @@ -710,7 +710,7 @@ describe("annotation", function() { it( "should correctly parse a URI action, where the URI entry " + "is missing a protocol", - function(done) { + function (done) { const actionDict = new Dict(); actionDict.set("Type", Name.get("Action")); actionDict.set("S", Name.get("URI")); @@ -744,7 +744,7 @@ describe("annotation", function() { it( "should correctly parse a URI action, where the URI entry " + "has an incorrect encoding (bug 1122280)", - function(done) { + function (done) { const actionStream = new StringStream( "<<\n" + "/Type /Action\n" + @@ -793,7 +793,7 @@ describe("annotation", function() { } ); - it("should correctly parse a GoTo action", function(done) { + it("should correctly parse a GoTo action", function (done) { const actionDict = new Dict(); actionDict.set("Type", Name.get("Action")); actionDict.set("S", Name.get("GoTo")); @@ -824,7 +824,7 @@ describe("annotation", function() { it( "should correctly parse a GoToR action, where the FileSpec entry " + "is a string containing a relative URL", - function(done) { + function (done) { const actionDict = new Dict(); actionDict.set("Type", Name.get("Action")); actionDict.set("S", Name.get("GoToR")); @@ -861,7 +861,7 @@ describe("annotation", function() { it( "should correctly parse a GoToR action, containing a relative URL, " + 'with the "docBaseUrl" parameter specified', - function(done) { + function (done) { const actionDict = new Dict(); actionDict.set("Type", Name.get("Action")); actionDict.set("S", Name.get("GoToR")); @@ -898,7 +898,7 @@ describe("annotation", function() { } ); - it("should correctly parse a GoToR action, with named destination", function(done) { + it("should correctly parse a GoToR action, with named destination", function (done) { const actionDict = new Dict(); actionDict.set("Type", Name.get("Action")); actionDict.set("S", Name.get("GoToR")); @@ -928,7 +928,7 @@ describe("annotation", function() { }, done.fail); }); - it("should correctly parse a GoToR action, with explicit destination array", function(done) { + it("should correctly parse a GoToR action, with explicit destination array", function (done) { const actionDict = new Dict(); actionDict.set("Type", Name.get("Action")); actionDict.set("S", Name.get("GoToR")); @@ -969,7 +969,7 @@ describe("annotation", function() { it( "should correctly parse a Launch action, where the FileSpec dict " + 'contains a relative URL, with the "docBaseUrl" parameter specified', - function(done) { + function (done) { const fileSpecDict = new Dict(); fileSpecDict.set("Type", Name.get("FileSpec")); fileSpecDict.set("F", "Part II/Part II.pdf"); @@ -1015,7 +1015,7 @@ describe("annotation", function() { it( "should recover valid URLs from JavaScript actions having certain " + "white-listed formats", - function(done) { + function (done) { function checkJsAction(params) { const jsEntry = params.jsEntry; const expectedUrl = params.expectedUrl; @@ -1084,7 +1084,7 @@ describe("annotation", function() { } ); - it("should correctly parse a Named action", function(done) { + it("should correctly parse a Named action", function (done) { const actionDict = new Dict(); actionDict.set("Type", Name.get("Action")); actionDict.set("S", Name.get("Named")); @@ -1112,7 +1112,7 @@ describe("annotation", function() { }, done.fail); }); - it("should correctly parse a simple Dest", function(done) { + it("should correctly parse a simple Dest", function (done) { const annotationDict = new Dict(); annotationDict.set("Type", Name.get("Annot")); annotationDict.set("Subtype", Name.get("Link")); @@ -1135,7 +1135,7 @@ describe("annotation", function() { }, done.fail); }); - it("should correctly parse a simple Dest, with explicit destination array", function(done) { + it("should correctly parse a simple Dest, with explicit destination array", function (done) { const annotationDict = new Dict(); annotationDict.set("Type", Name.get("Annot")); annotationDict.set("Subtype", Name.get("Link")); @@ -1173,7 +1173,7 @@ describe("annotation", function() { it( "should correctly parse a Dest, which violates the specification " + "by containing a dictionary", - function(done) { + function (done) { const destDict = new Dict(); destDict.set("Type", Name.get("Action")); destDict.set("S", Name.get("GoTo")); @@ -1206,7 +1206,7 @@ describe("annotation", function() { } ); - it("should not set quadpoints if not defined", function(done) { + it("should not set quadpoints if not defined", function (done) { const annotationDict = new Dict(); annotationDict.set("Type", Name.get("Annot")); annotationDict.set("Subtype", Name.get("Link")); @@ -1226,7 +1226,7 @@ describe("annotation", function() { }, done.fail); }); - it("should set quadpoints if defined", function(done) { + it("should set quadpoints if defined", function (done) { const annotationDict = new Dict(); annotationDict.set("Type", Name.get("Annot")); annotationDict.set("Subtype", Name.get("Link")); @@ -1256,21 +1256,21 @@ describe("annotation", function() { }); }); - describe("WidgetAnnotation", function() { + describe("WidgetAnnotation", function () { let widgetDict; - beforeEach(function(done) { + beforeEach(function (done) { widgetDict = new Dict(); widgetDict.set("Type", Name.get("Annot")); widgetDict.set("Subtype", Name.get("Widget")); done(); }); - afterEach(function() { + afterEach(function () { widgetDict = null; }); - it("should handle unknown field names", function(done) { + it("should handle unknown field names", function (done) { const widgetRef = Ref.get(20, 0); const xref = new XRefMock([{ ref: widgetRef, data: widgetDict }]); @@ -1286,7 +1286,7 @@ describe("annotation", function() { }, done.fail); }); - it("should construct the field name when there are no ancestors", function(done) { + it("should construct the field name when there are no ancestors", function (done) { widgetDict.set("T", "foo"); const widgetRef = Ref.get(21, 0); @@ -1304,7 +1304,7 @@ describe("annotation", function() { }, done.fail); }); - it("should construct the field name when there are ancestors", function(done) { + it("should construct the field name when there are ancestors", function (done) { const firstParent = new Dict(); firstParent.set("T", "foo"); @@ -1333,7 +1333,7 @@ describe("annotation", function() { it( "should construct the field name if a parent is not a dictionary " + "(issue 8143)", - function(done) { + function (done) { const parentDict = new Dict(); parentDict.set("Parent", null); parentDict.set("T", "foo"); @@ -1358,10 +1358,10 @@ describe("annotation", function() { ); }); - describe("TextWidgetAnnotation", function() { + describe("TextWidgetAnnotation", function () { let textWidgetDict; - beforeEach(function(done) { + beforeEach(function (done) { textWidgetDict = new Dict(); textWidgetDict.set("Type", Name.get("Annot")); textWidgetDict.set("Subtype", Name.get("Widget")); @@ -1369,11 +1369,11 @@ describe("annotation", function() { done(); }); - afterEach(function() { + afterEach(function () { textWidgetDict = null; }); - it("should handle unknown text alignment, maximum length and flags", function(done) { + it("should handle unknown text alignment, maximum length and flags", function (done) { const textWidgetRef = Ref.get(124, 0); const xref = new XRefMock([{ ref: textWidgetRef, data: textWidgetDict }]); @@ -1393,7 +1393,7 @@ describe("annotation", function() { }, done.fail); }); - it("should not set invalid text alignment, maximum length and flags", function(done) { + it("should not set invalid text alignment, maximum length and flags", function (done) { textWidgetDict.set("Q", "center"); textWidgetDict.set("MaxLen", "five"); textWidgetDict.set("Ff", "readonly"); @@ -1417,7 +1417,7 @@ describe("annotation", function() { }, done.fail); }); - it("should set valid text alignment, maximum length and flags", function(done) { + it("should set valid text alignment, maximum length and flags", function (done) { textWidgetDict.set("Q", 1); textWidgetDict.set("MaxLen", 20); textWidgetDict.set( @@ -1443,7 +1443,7 @@ describe("annotation", function() { }, done.fail); }); - it("should reject comb fields without a maximum length", function(done) { + it("should reject comb fields without a maximum length", function (done) { textWidgetDict.set("Ff", AnnotationFieldFlag.COMB); const textWidgetRef = Ref.get(46, 0); @@ -1461,7 +1461,7 @@ describe("annotation", function() { }, done.fail); }); - it("should accept comb fields with a maximum length", function(done) { + it("should accept comb fields with a maximum length", function (done) { textWidgetDict.set("MaxLen", 20); textWidgetDict.set("Ff", AnnotationFieldFlag.COMB); @@ -1480,7 +1480,7 @@ describe("annotation", function() { }, done.fail); }); - it("should only accept comb fields when the flags are valid", function(done) { + it("should only accept comb fields when the flags are valid", function (done) { const invalidFieldFlags = [ AnnotationFieldFlag.MULTILINE, AnnotationFieldFlag.PASSWORD, @@ -1528,10 +1528,10 @@ describe("annotation", function() { }); }); - describe("ButtonWidgetAnnotation", function() { + describe("ButtonWidgetAnnotation", function () { let buttonWidgetDict; - beforeEach(function(done) { + beforeEach(function (done) { buttonWidgetDict = new Dict(); buttonWidgetDict.set("Type", Name.get("Annot")); buttonWidgetDict.set("Subtype", Name.get("Widget")); @@ -1539,11 +1539,11 @@ describe("annotation", function() { done(); }); - afterEach(function() { + afterEach(function () { buttonWidgetDict = null; }); - it("should handle checkboxes with export value", function(done) { + it("should handle checkboxes with export value", function (done) { buttonWidgetDict.set("V", Name.get("1")); const appearanceStatesDict = new Dict(); @@ -1574,7 +1574,7 @@ describe("annotation", function() { }, done.fail); }); - it("should handle checkboxes without export value", function(done) { + it("should handle checkboxes without export value", function (done) { buttonWidgetDict.set("V", Name.get("1")); const buttonWidgetRef = Ref.get(124, 0); @@ -1596,7 +1596,7 @@ describe("annotation", function() { }, done.fail); }); - it("should handle radio buttons with a field value", function(done) { + it("should handle radio buttons with a field value", function (done) { const parentDict = new Dict(); parentDict.set("V", Name.get("1")); @@ -1630,7 +1630,7 @@ describe("annotation", function() { }, done.fail); }); - it("should handle radio buttons without a field value", function(done) { + it("should handle radio buttons without a field value", function (done) { const normalAppearanceStateDict = new Dict(); normalAppearanceStateDict.set("2", null); @@ -1661,10 +1661,10 @@ describe("annotation", function() { }); }); - describe("ChoiceWidgetAnnotation", function() { + describe("ChoiceWidgetAnnotation", function () { let choiceWidgetDict; - beforeEach(function(done) { + beforeEach(function (done) { choiceWidgetDict = new Dict(); choiceWidgetDict.set("Type", Name.get("Annot")); choiceWidgetDict.set("Subtype", Name.get("Widget")); @@ -1672,11 +1672,11 @@ describe("annotation", function() { done(); }); - afterEach(function() { + afterEach(function () { choiceWidgetDict = null; }); - it("should handle missing option arrays", function(done) { + it("should handle missing option arrays", function (done) { const choiceWidgetRef = Ref.get(122, 0); const xref = new XRefMock([ { ref: choiceWidgetRef, data: choiceWidgetDict }, @@ -1694,7 +1694,7 @@ describe("annotation", function() { }, done.fail); }); - it("should handle option arrays with array elements", function(done) { + it("should handle option arrays with array elements", function (done) { const optionBarRef = Ref.get(20, 0); const optionBarStr = "Bar"; const optionOneRef = Ref.get(10, 0); @@ -1727,7 +1727,7 @@ describe("annotation", function() { }, done.fail); }); - it("should handle option arrays with string elements", function(done) { + it("should handle option arrays with string elements", function (done) { const optionBarRef = Ref.get(10, 0); const optionBarStr = "Bar"; @@ -1757,7 +1757,7 @@ describe("annotation", function() { }, done.fail); }); - it("should handle inherited option arrays (issue 8094)", function(done) { + it("should handle inherited option arrays (issue 8094)", function (done) { const options = [ ["Value1", "Description1"], ["Value2", "Description2"], @@ -1789,7 +1789,7 @@ describe("annotation", function() { }, done.fail); }); - it("should sanitize display values in option arrays (issue 8947)", function(done) { + it("should sanitize display values in option arrays (issue 8947)", function (done) { // The option value is a UTF-16BE string. The display value should be // sanitized, but the export value should remain the same since that // may be used as a unique identifier when exporting form values. @@ -1817,7 +1817,7 @@ describe("annotation", function() { }, done.fail); }); - it("should handle array field values", function(done) { + it("should handle array field values", function (done) { const fieldValue = ["Foo", "Bar"]; choiceWidgetDict.set("V", fieldValue); @@ -1839,7 +1839,7 @@ describe("annotation", function() { }, done.fail); }); - it("should handle string field values", function(done) { + it("should handle string field values", function (done) { const fieldValue = "Foo"; choiceWidgetDict.set("V", fieldValue); @@ -1861,7 +1861,7 @@ describe("annotation", function() { }, done.fail); }); - it("should handle unknown flags", function(done) { + it("should handle unknown flags", function (done) { const choiceWidgetRef = Ref.get(166, 0); const xref = new XRefMock([ { ref: choiceWidgetRef, data: choiceWidgetDict }, @@ -1881,7 +1881,7 @@ describe("annotation", function() { }, done.fail); }); - it("should not set invalid flags", function(done) { + it("should not set invalid flags", function (done) { choiceWidgetDict.set("Ff", "readonly"); const choiceWidgetRef = Ref.get(165, 0); @@ -1903,7 +1903,7 @@ describe("annotation", function() { }, done.fail); }); - it("should set valid flags", function(done) { + it("should set valid flags", function (done) { choiceWidgetDict.set( "Ff", AnnotationFieldFlag.READONLY + @@ -1931,8 +1931,8 @@ describe("annotation", function() { }); }); - describe("LineAnnotation", function() { - it("should set the line coordinates", function(done) { + describe("LineAnnotation", function () { + it("should set the line coordinates", function (done) { const lineDict = new Dict(); lineDict.set("Type", Name.get("Annot")); lineDict.set("Subtype", Name.get("Line")); @@ -1954,8 +1954,8 @@ describe("annotation", function() { }); }); - describe("FileAttachmentAnnotation", function() { - it("should correctly parse a file attachment", function(done) { + describe("FileAttachmentAnnotation", function () { + it("should correctly parse a file attachment", function (done) { const fileStream = new StringStream( "<<\n" + "/Type /EmbeddedFile\n" + @@ -2015,8 +2015,8 @@ describe("annotation", function() { }); }); - describe("PopupAnnotation", function() { - it("should inherit properties from its parent", function(done) { + describe("PopupAnnotation", function () { + it("should inherit properties from its parent", function (done) { const parentDict = new Dict(); parentDict.set("Type", Name.get("Annot")); parentDict.set("Subtype", Name.get("Text")); @@ -2044,7 +2044,7 @@ describe("annotation", function() { }, done.fail); }); - it("should handle missing parent properties", function(done) { + it("should handle missing parent properties", function (done) { const parentDict = new Dict(); parentDict.set("Type", Name.get("Annot")); parentDict.set("Subtype", Name.get("Text")); @@ -2073,7 +2073,7 @@ describe("annotation", function() { it( "should inherit the parent flags when the Popup is not viewable, " + "but the parent is (PR 7352)", - function(done) { + function (done) { const parentDict = new Dict(); parentDict.set("Type", Name.get("Annot")); parentDict.set("Subtype", Name.get("Text")); @@ -2108,7 +2108,7 @@ describe("annotation", function() { it( "should correctly inherit Contents from group-master annotation " + "if parent has ReplyType == Group", - function(done) { + function (done) { const annotationRef = Ref.get(819, 0); const annotationDict = new Dict(); annotationDict.set("Type", Name.get("Annot")); @@ -2165,8 +2165,8 @@ describe("annotation", function() { ); }); - describe("InkAnnotation", function() { - it("should handle a single ink list", function(done) { + describe("InkAnnotation", function () { + it("should handle a single ink list", function (done) { const inkDict = new Dict(); inkDict.set("Type", Name.get("Annot")); inkDict.set("Subtype", Name.get("Ink")); @@ -2193,7 +2193,7 @@ describe("annotation", function() { }, done.fail); }); - it("should handle multiple ink lists", function(done) { + it("should handle multiple ink lists", function (done) { const inkDict = new Dict(); inkDict.set("Type", Name.get("Annot")); inkDict.set("Subtype", Name.get("Ink")); @@ -2226,8 +2226,8 @@ describe("annotation", function() { }); }); - describe("HightlightAnnotation", function() { - it("should not set quadpoints if not defined", function(done) { + describe("HightlightAnnotation", function () { + it("should not set quadpoints if not defined", function (done) { const highlightDict = new Dict(); highlightDict.set("Type", Name.get("Annot")); highlightDict.set("Subtype", Name.get("Highlight")); @@ -2247,7 +2247,7 @@ describe("annotation", function() { }, done.fail); }); - it("should set quadpoints if defined", function(done) { + it("should set quadpoints if defined", function (done) { const highlightDict = new Dict(); highlightDict.set("Type", Name.get("Annot")); highlightDict.set("Subtype", Name.get("Highlight")); @@ -2277,8 +2277,8 @@ describe("annotation", function() { }); }); - describe("UnderlineAnnotation", function() { - it("should not set quadpoints if not defined", function(done) { + describe("UnderlineAnnotation", function () { + it("should not set quadpoints if not defined", function (done) { const underlineDict = new Dict(); underlineDict.set("Type", Name.get("Annot")); underlineDict.set("Subtype", Name.get("Underline")); @@ -2298,7 +2298,7 @@ describe("annotation", function() { }, done.fail); }); - it("should set quadpoints if defined", function(done) { + it("should set quadpoints if defined", function (done) { const underlineDict = new Dict(); underlineDict.set("Type", Name.get("Annot")); underlineDict.set("Subtype", Name.get("Underline")); @@ -2328,8 +2328,8 @@ describe("annotation", function() { }); }); - describe("SquigglyAnnotation", function() { - it("should not set quadpoints if not defined", function(done) { + describe("SquigglyAnnotation", function () { + it("should not set quadpoints if not defined", function (done) { const squigglyDict = new Dict(); squigglyDict.set("Type", Name.get("Annot")); squigglyDict.set("Subtype", Name.get("Squiggly")); @@ -2349,7 +2349,7 @@ describe("annotation", function() { }, done.fail); }); - it("should set quadpoints if defined", function(done) { + it("should set quadpoints if defined", function (done) { const squigglyDict = new Dict(); squigglyDict.set("Type", Name.get("Annot")); squigglyDict.set("Subtype", Name.get("Squiggly")); @@ -2379,8 +2379,8 @@ describe("annotation", function() { }); }); - describe("StrikeOutAnnotation", function() { - it("should not set quadpoints if not defined", function(done) { + describe("StrikeOutAnnotation", function () { + it("should not set quadpoints if not defined", function (done) { const strikeOutDict = new Dict(); strikeOutDict.set("Type", Name.get("Annot")); strikeOutDict.set("Subtype", Name.get("StrikeOut")); @@ -2400,7 +2400,7 @@ describe("annotation", function() { }, done.fail); }); - it("should set quadpoints if defined", function(done) { + it("should set quadpoints if defined", function (done) { const strikeOutDict = new Dict(); strikeOutDict.set("Type", Name.get("Annot")); strikeOutDict.set("Subtype", Name.get("StrikeOut")); diff --git a/test/unit/api_spec.js b/test/unit/api_spec.js index 3c7b64904..2cda2eecd 100644 --- a/test/unit/api_spec.js +++ b/test/unit/api_spec.js @@ -49,14 +49,14 @@ import { GlobalWorkerOptions } from "../../src/display/worker_options.js"; import { isNodeJS } from "../../src/shared/is_node.js"; import { Metadata } from "../../src/display/metadata.js"; -describe("api", function() { +describe("api", function () { const basicApiFileName = "basicapi.pdf"; const basicApiFileLength = 105779; // bytes const basicApiGetDocumentParams = buildGetDocumentParams(basicApiFileName); let CanvasFactory; - beforeAll(function(done) { + beforeAll(function (done) { if (isNodeJS) { CanvasFactory = new NodeCanvasFactory(); } else { @@ -65,26 +65,26 @@ describe("api", function() { done(); }); - afterAll(function(done) { + afterAll(function (done) { CanvasFactory = null; done(); }); function waitSome(callback) { var WAIT_TIMEOUT = 10; - setTimeout(function() { + setTimeout(function () { callback(); }, WAIT_TIMEOUT); } - describe("getDocument", function() { - it("creates pdf doc from URL", function(done) { + describe("getDocument", function () { + it("creates pdf doc from URL", function (done) { var loadingTask = getDocument(basicApiGetDocumentParams); var progressReportedCapability = createPromiseCapability(); // Attach the callback that is used to report loading progress; // similarly to how viewer.js works. - loadingTask.onProgress = function(progressData) { + loadingTask.onProgress = function (progressData) { if (!progressReportedCapability.settled) { progressReportedCapability.resolve(progressData); } @@ -92,7 +92,7 @@ describe("api", function() { var promises = [progressReportedCapability.promise, loadingTask.promise]; Promise.all(promises) - .then(function(data) { + .then(function (data) { expect(data[0].loaded / data[0].total >= 0).toEqual(true); expect(data[1] instanceof PDFDocumentProxy).toEqual(true); expect(loadingTask).toEqual(data[1].loadingTask); @@ -100,34 +100,34 @@ describe("api", function() { }) .catch(done.fail); }); - it("creates pdf doc from URL and aborts before worker initialized", function(done) { + it("creates pdf doc from URL and aborts before worker initialized", function (done) { var loadingTask = getDocument(basicApiGetDocumentParams); const destroyed = loadingTask.destroy(); loadingTask.promise - .then(function(reason) { + .then(function (reason) { done.fail("shall fail loading"); }) - .catch(function(reason) { + .catch(function (reason) { expect(true).toEqual(true); destroyed.then(done); }); }); - it("creates pdf doc from URL and aborts loading after worker initialized", function(done) { + it("creates pdf doc from URL and aborts loading after worker initialized", function (done) { var loadingTask = getDocument(basicApiGetDocumentParams); // This can be somewhat random -- we cannot guarantee perfect // 'Terminate' message to the worker before/after setting up pdfManager. - var destroyed = loadingTask._worker.promise.then(function() { + var destroyed = loadingTask._worker.promise.then(function () { return loadingTask.destroy(); }); destroyed - .then(function(data) { + .then(function (data) { expect(true).toEqual(true); done(); }) .catch(done.fail); }); - it("creates pdf doc from typed array", function(done) { + it("creates pdf doc from typed array", function (done) { let typedArrayPdfPromise; if (isNodeJS) { typedArrayPdfPromise = NodeFileReaderFactory.fetch({ @@ -147,14 +147,14 @@ describe("api", function() { const loadingTask = getDocument(typedArrayPdf); const progressReportedCapability = createPromiseCapability(); - loadingTask.onProgress = function(data) { + loadingTask.onProgress = function (data) { progressReportedCapability.resolve(data); }; return Promise.all([ loadingTask.promise, progressReportedCapability.promise, - ]).then(function(data) { + ]).then(function (data) { expect(data[0] instanceof PDFDocumentProxy).toEqual(true); expect(data[1].loaded / data[1].total).toEqual(1); @@ -163,39 +163,39 @@ describe("api", function() { }) .catch(done.fail); }); - it("creates pdf doc from invalid PDF file", function(done) { + it("creates pdf doc from invalid PDF file", function (done) { // A severely corrupt PDF file (even Adobe Reader fails to open it). var loadingTask = getDocument(buildGetDocumentParams("bug1020226.pdf")); loadingTask.promise - .then(function() { + .then(function () { done.fail("shall fail loading"); }) - .catch(function(reason) { + .catch(function (reason) { expect(reason instanceof InvalidPDFException).toEqual(true); expect(reason.message).toEqual("Invalid PDF structure."); loadingTask.destroy().then(done); }); }); - it("creates pdf doc from non-existent URL", function(done) { + it("creates pdf doc from non-existent URL", function (done) { var loadingTask = getDocument(buildGetDocumentParams("non-existent.pdf")); loadingTask.promise - .then(function(error) { + .then(function (error) { done.fail("shall fail loading"); }) - .catch(function(error) { + .catch(function (error) { expect(error instanceof MissingPDFException).toEqual(true); loadingTask.destroy().then(done); }); }); - it("creates pdf doc from PDF file protected with user and owner password", function(done) { + it("creates pdf doc from PDF file protected with user and owner password", function (done) { var loadingTask = getDocument(buildGetDocumentParams("pr6531_1.pdf")); var passwordNeededCapability = createPromiseCapability(); var passwordIncorrectCapability = createPromiseCapability(); // Attach the callback that is used to request a password; // similarly to how viewer.js handles passwords. - loadingTask.onPassword = function(updatePassword, reason) { + loadingTask.onPassword = function (updatePassword, reason) { if ( reason === PasswordResponses.NEED_PASSWORD && !passwordNeededCapability.settled @@ -224,13 +224,13 @@ describe("api", function() { loadingTask.promise, ]; Promise.all(promises) - .then(function(data) { + .then(function (data) { expect(data[2] instanceof PDFDocumentProxy).toEqual(true); loadingTask.destroy().then(done); }) .catch(done.fail); }); - it("creates pdf doc from PDF file protected with only a user password", function(done) { + it("creates pdf doc from PDF file protected with only a user password", function (done) { var filename = "pr6531_2.pdf"; var passwordNeededLoadingTask = getDocument( @@ -239,11 +239,11 @@ describe("api", function() { }) ); var result1 = passwordNeededLoadingTask.promise.then( - function() { + function () { done.fail("shall fail with no password"); return Promise.reject(new Error("loadingTask should be rejected")); }, - function(data) { + function (data) { expect(data instanceof PasswordException).toEqual(true); expect(data.code).toEqual(PasswordResponses.NEED_PASSWORD); return passwordNeededLoadingTask.destroy(); @@ -256,11 +256,11 @@ describe("api", function() { }) ); var result2 = passwordIncorrectLoadingTask.promise.then( - function() { + function () { done.fail("shall fail with wrong password"); return Promise.reject(new Error("loadingTask should be rejected")); }, - function(data) { + function (data) { expect(data instanceof PasswordException).toEqual(true); expect(data.code).toEqual(PasswordResponses.INCORRECT_PASSWORD); return passwordIncorrectLoadingTask.destroy(); @@ -272,12 +272,12 @@ describe("api", function() { password: "asdfasdf", }) ); - var result3 = passwordAcceptedLoadingTask.promise.then(function(data) { + var result3 = passwordAcceptedLoadingTask.promise.then(function (data) { expect(data instanceof PDFDocumentProxy).toEqual(true); return passwordAcceptedLoadingTask.destroy(); }); Promise.all([result1, result2, result3]) - .then(function() { + .then(function () { done(); }) .catch(done.fail); @@ -286,7 +286,7 @@ describe("api", function() { it( "creates pdf doc from password protected PDF file and aborts/throws " + "in the onPassword callback (issue 7806)", - function(done) { + function (done) { var filename = "issue3371.pdf"; var passwordNeededLoadingTask = getDocument( @@ -299,7 +299,7 @@ describe("api", function() { ); let passwordNeededDestroyed; - passwordNeededLoadingTask.onPassword = function(callback, reason) { + passwordNeededLoadingTask.onPassword = function (callback, reason) { if (reason === PasswordResponses.NEED_PASSWORD) { passwordNeededDestroyed = passwordNeededLoadingTask.destroy(); return; @@ -308,18 +308,18 @@ describe("api", function() { expect(false).toEqual(true); }; var result1 = passwordNeededLoadingTask.promise.then( - function() { + function () { done.fail("shall fail since the loadingTask should be destroyed"); return Promise.reject(new Error("loadingTask should be rejected")); }, - function(reason) { + function (reason) { expect(reason instanceof PasswordException).toEqual(true); expect(reason.code).toEqual(PasswordResponses.NEED_PASSWORD); return passwordNeededDestroyed; } ); - passwordIncorrectLoadingTask.onPassword = function(callback, reason) { + passwordIncorrectLoadingTask.onPassword = function (callback, reason) { if (reason === PasswordResponses.INCORRECT_PASSWORD) { throw new Error("Incorrect password"); } @@ -327,11 +327,11 @@ describe("api", function() { expect(false).toEqual(true); }; var result2 = passwordIncorrectLoadingTask.promise.then( - function() { + function () { done.fail("shall fail since the onPassword callback should throw"); return Promise.reject(new Error("loadingTask should be rejected")); }, - function(reason) { + function (reason) { expect(reason instanceof PasswordException).toEqual(true); expect(reason.code).toEqual(PasswordResponses.INCORRECT_PASSWORD); return passwordIncorrectLoadingTask.destroy(); @@ -339,21 +339,21 @@ describe("api", function() { ); Promise.all([result1, result2]) - .then(function() { + .then(function () { done(); }) .catch(done.fail); } ); - it("creates pdf doc from empty typed array", function(done) { + it("creates pdf doc from empty typed array", function (done) { const loadingTask = getDocument(new Uint8Array(0)); loadingTask.promise.then( - function() { + function () { done.fail("shall not open empty file"); }, - function(reason) { + function (reason) { expect(reason instanceof InvalidPDFException); expect(reason.message).toEqual( "The PDF file is empty, i.e. its size is zero bytes." @@ -365,15 +365,15 @@ describe("api", function() { }); }); - describe("PDFWorker", function() { - it("worker created or destroyed", function(done) { + describe("PDFWorker", function () { + it("worker created or destroyed", function (done) { if (isNodeJS) { pending("Worker is not supported in Node.js."); } var worker = new PDFWorker({ name: "test1" }); worker.promise - .then(function() { + .then(function () { expect(worker.name).toEqual("test1"); expect(!!worker.port).toEqual(true); expect(worker.destroyed).toEqual(false); @@ -387,23 +387,23 @@ describe("api", function() { }) .catch(done.fail); }); - it("worker created or destroyed by getDocument", function(done) { + it("worker created or destroyed by getDocument", function (done) { if (isNodeJS) { pending("Worker is not supported in Node.js."); } var loadingTask = getDocument(basicApiGetDocumentParams); var worker; - loadingTask.promise.then(function() { + loadingTask.promise.then(function () { worker = loadingTask._worker; expect(!!worker).toEqual(true); }); - var destroyPromise = loadingTask.promise.then(function() { + var destroyPromise = loadingTask.promise.then(function () { return loadingTask.destroy(); }); destroyPromise - .then(function() { + .then(function () { var destroyedWorker = loadingTask._worker; expect(!!destroyedWorker).toEqual(false); expect(worker.destroyed).toEqual(true); @@ -411,7 +411,7 @@ describe("api", function() { }) .catch(done.fail); }); - it("worker created and can be used in getDocument", function(done) { + it("worker created and can be used in getDocument", function (done) { if (isNodeJS) { pending("Worker is not supported in Node.js."); } @@ -422,7 +422,7 @@ describe("api", function() { worker, }) ); - loadingTask.promise.then(function() { + loadingTask.promise.then(function () { var docWorker = loadingTask._worker; expect(!!docWorker).toEqual(false); // checking is the same port is used in the MessageHandler @@ -430,18 +430,18 @@ describe("api", function() { expect(messageHandlerPort === worker.port).toEqual(true); }); - var destroyPromise = loadingTask.promise.then(function() { + var destroyPromise = loadingTask.promise.then(function () { return loadingTask.destroy(); }); destroyPromise - .then(function() { + .then(function () { expect(worker.destroyed).toEqual(false); worker.destroy(); done(); }) .catch(done.fail); }); - it("creates more than one worker", function(done) { + it("creates more than one worker", function (done) { if (isNodeJS) { pending("Worker is not supported in Node.js."); } @@ -455,7 +455,7 @@ describe("api", function() { worker3.promise, ]); ready - .then(function() { + .then(function () { expect( worker1.port !== worker2.port && worker1.port !== worker3.port && @@ -468,7 +468,7 @@ describe("api", function() { }) .catch(done.fail); }); - it("gets current workerSrc", function() { + it("gets current workerSrc", function () { if (isNodeJS) { pending("Worker is not supported in Node.js."); } @@ -478,99 +478,99 @@ describe("api", function() { expect(workerSrc).toEqual(GlobalWorkerOptions.workerSrc); }); }); - describe("PDFDocument", function() { + describe("PDFDocument", function () { let pdfLoadingTask, pdfDocument; - beforeAll(function(done) { + beforeAll(function (done) { pdfLoadingTask = getDocument(basicApiGetDocumentParams); - pdfLoadingTask.promise.then(function(data) { + pdfLoadingTask.promise.then(function (data) { pdfDocument = data; done(); }); }); - afterAll(function(done) { + afterAll(function (done) { pdfLoadingTask.destroy().then(done); }); - it("gets number of pages", function() { + it("gets number of pages", function () { expect(pdfDocument.numPages).toEqual(3); }); - it("gets fingerprint", function() { + it("gets fingerprint", function () { expect(pdfDocument.fingerprint).toEqual( "ea8b35919d6279a369e835bde778611b" ); }); - it("gets page", function(done) { + it("gets page", function (done) { var promise = pdfDocument.getPage(1); promise - .then(function(data) { + .then(function (data) { expect(data instanceof PDFPageProxy).toEqual(true); expect(data.pageNumber).toEqual(1); done(); }) .catch(done.fail); }); - it("gets non-existent page", function(done) { + it("gets non-existent page", function (done) { var outOfRangePromise = pdfDocument.getPage(100); var nonIntegerPromise = pdfDocument.getPage(2.5); var nonNumberPromise = pdfDocument.getPage("1"); outOfRangePromise = outOfRangePromise.then( - function() { + function () { throw new Error("shall fail for out-of-range pageNumber parameter"); }, - function(reason) { + function (reason) { expect(reason instanceof Error).toEqual(true); } ); nonIntegerPromise = nonIntegerPromise.then( - function() { + function () { throw new Error("shall fail for non-integer pageNumber parameter"); }, - function(reason) { + function (reason) { expect(reason instanceof Error).toEqual(true); } ); nonNumberPromise = nonNumberPromise.then( - function() { + function () { throw new Error("shall fail for non-number pageNumber parameter"); }, - function(reason) { + function (reason) { expect(reason instanceof Error).toEqual(true); } ); Promise.all([outOfRangePromise, nonIntegerPromise, nonNumberPromise]) - .then(function() { + .then(function () { done(); }) .catch(done.fail); }); - it("gets page, from /Pages tree with circular reference", function(done) { + it("gets page, from /Pages tree with circular reference", function (done) { const loadingTask = getDocument( buildGetDocumentParams("Pages-tree-refs.pdf") ); - const page1 = loadingTask.promise.then(function(pdfDoc) { + const page1 = loadingTask.promise.then(function (pdfDoc) { return pdfDoc.getPage(1).then( - function(pdfPage) { + function (pdfPage) { expect(pdfPage instanceof PDFPageProxy).toEqual(true); expect(pdfPage.ref).toEqual({ num: 6, gen: 0 }); }, - function(reason) { + function (reason) { throw new Error("shall not fail for valid page"); } ); }); - const page2 = loadingTask.promise.then(function(pdfDoc) { + const page2 = loadingTask.promise.then(function (pdfDoc) { return pdfDoc.getPage(2).then( - function(pdfPage) { + function (pdfPage) { throw new Error("shall fail for invalid page"); }, - function(reason) { + function (reason) { expect(reason instanceof Error).toEqual(true); expect(reason.message).toEqual( "Pages tree contains circular reference." @@ -579,39 +579,39 @@ describe("api", function() { ); }); - Promise.all([page1, page2]).then(function() { + Promise.all([page1, page2]).then(function () { loadingTask.destroy().then(done); }, done.fail); }); - it("gets page index", function(done) { + it("gets page index", function (done) { // reference to second page var ref = { num: 17, gen: 0 }; var promise = pdfDocument.getPageIndex(ref); promise - .then(function(pageIndex) { + .then(function (pageIndex) { expect(pageIndex).toEqual(1); done(); }) .catch(done.fail); }); - it("gets invalid page index", function(done) { + it("gets invalid page index", function (done) { var ref = { num: 3, gen: 0 }; // Reference to a font dictionary. var promise = pdfDocument.getPageIndex(ref); promise - .then(function() { + .then(function () { done.fail("shall fail for invalid page reference."); }) - .catch(function(reason) { + .catch(function (reason) { expect(reason instanceof Error).toEqual(true); done(); }); }); - it("gets destinations, from /Dests dictionary", function(done) { + it("gets destinations, from /Dests dictionary", function (done) { var promise = pdfDocument.getDestinations(); promise - .then(function(data) { + .then(function (data) { expect(data).toEqual({ chapter1: [{ gen: 0, num: 17 }, { name: "XYZ" }, 0, 841.89, null], }); @@ -619,10 +619,10 @@ describe("api", function() { }) .catch(done.fail); }); - it("gets a destination, from /Dests dictionary", function(done) { + it("gets a destination, from /Dests dictionary", function (done) { var promise = pdfDocument.getDestination("chapter1"); promise - .then(function(data) { + .then(function (data) { expect(data).toEqual([ { gen: 0, num: 17 }, { name: "XYZ" }, @@ -634,25 +634,25 @@ describe("api", function() { }) .catch(done.fail); }); - it("gets a non-existent destination, from /Dests dictionary", function(done) { + it("gets a non-existent destination, from /Dests dictionary", function (done) { var promise = pdfDocument.getDestination( "non-existent-named-destination" ); promise - .then(function(data) { + .then(function (data) { expect(data).toEqual(null); done(); }) .catch(done.fail); }); - it("gets destinations, from /Names (NameTree) dictionary", function(done) { + it("gets destinations, from /Names (NameTree) dictionary", function (done) { var loadingTask = getDocument(buildGetDocumentParams("issue6204.pdf")); - var promise = loadingTask.promise.then(function(pdfDoc) { + var promise = loadingTask.promise.then(function (pdfDoc) { return pdfDoc.getDestinations(); }); promise - .then(function(destinations) { + .then(function (destinations) { expect(destinations).toEqual({ "Page.1": [{ num: 1, gen: 0 }, { name: "XYZ" }, 0, 375, null], "Page.2": [{ num: 6, gen: 0 }, { name: "XYZ" }, 0, 375, null], @@ -662,13 +662,13 @@ describe("api", function() { }) .catch(done.fail); }); - it("gets a destination, from /Names (NameTree) dictionary", function(done) { + it("gets a destination, from /Names (NameTree) dictionary", function (done) { var loadingTask = getDocument(buildGetDocumentParams("issue6204.pdf")); - var promise = loadingTask.promise.then(function(pdfDoc) { + var promise = loadingTask.promise.then(function (pdfDoc) { return pdfDoc.getDestination("Page.1"); }); promise - .then(function(destination) { + .then(function (destination) { expect(destination).toEqual([ { num: 1, gen: 0 }, { name: "XYZ" }, @@ -681,13 +681,13 @@ describe("api", function() { }) .catch(done.fail); }); - it("gets a non-existent destination, from /Names (NameTree) dictionary", function(done) { + it("gets a non-existent destination, from /Names (NameTree) dictionary", function (done) { var loadingTask = getDocument(buildGetDocumentParams("issue6204.pdf")); - var promise = loadingTask.promise.then(function(pdfDoc) { + var promise = loadingTask.promise.then(function (pdfDoc) { return pdfDoc.getDestination("non-existent-named-destination"); }); promise - .then(function(destination) { + .then(function (destination) { expect(destination).toEqual(null); loadingTask.destroy().then(done); @@ -695,7 +695,7 @@ describe("api", function() { .catch(done.fail); }); - it("gets non-string destination", function(done) { + it("gets non-string destination", function (done) { let numberPromise = pdfDocument.getDestination(4.3); let booleanPromise = pdfDocument.getDestination(true); let arrayPromise = pdfDocument.getDestination([ @@ -707,26 +707,26 @@ describe("api", function() { ]); numberPromise = numberPromise.then( - function() { + function () { throw new Error("shall fail for non-string destination."); }, - function(reason) { + function (reason) { expect(reason instanceof Error).toEqual(true); } ); booleanPromise = booleanPromise.then( - function() { + function () { throw new Error("shall fail for non-string destination."); }, - function(reason) { + function (reason) { expect(reason instanceof Error).toEqual(true); } ); arrayPromise = arrayPromise.then( - function() { + function () { throw new Error("shall fail for non-string destination."); }, - function(reason) { + function (reason) { expect(reason instanceof Error).toEqual(true); } ); @@ -737,31 +737,31 @@ describe("api", function() { ); }); - it("gets non-existent page labels", function(done) { + it("gets non-existent page labels", function (done) { var promise = pdfDocument.getPageLabels(); promise - .then(function(data) { + .then(function (data) { expect(data).toEqual(null); done(); }) .catch(done.fail); }); - it("gets page labels", function(done) { + it("gets page labels", function (done) { // PageLabels with Roman/Arabic numerals. var loadingTask0 = getDocument(buildGetDocumentParams("bug793632.pdf")); - var promise0 = loadingTask0.promise.then(function(pdfDoc) { + var promise0 = loadingTask0.promise.then(function (pdfDoc) { return pdfDoc.getPageLabels(); }); // PageLabels with only a label prefix. var loadingTask1 = getDocument(buildGetDocumentParams("issue1453.pdf")); - var promise1 = loadingTask1.promise.then(function(pdfDoc) { + var promise1 = loadingTask1.promise.then(function (pdfDoc) { return pdfDoc.getPageLabels(); }); // PageLabels identical to standard page numbering. var loadingTask2 = getDocument(buildGetDocumentParams("rotation.pdf")); - var promise2 = loadingTask2.promise.then(function(pdfDoc) { + var promise2 = loadingTask2.promise.then(function (pdfDoc) { return pdfDoc.getPageLabels(); }); @@ -769,12 +769,12 @@ describe("api", function() { var loadingTask3 = getDocument( buildGetDocumentParams("bad-PageLabels.pdf") ); - var promise3 = loadingTask3.promise.then(function(pdfDoc) { + var promise3 = loadingTask3.promise.then(function (pdfDoc) { return pdfDoc.getPageLabels(); }); Promise.all([promise0, promise1, promise2, promise3]) - .then(function(pageLabels) { + .then(function (pageLabels) { expect(pageLabels[0]).toEqual(["i", "ii", "iii", "1"]); expect(pageLabels[1]).toEqual(["Front Page1"]); expect(pageLabels[2]).toEqual(["1", "2"]); @@ -790,62 +790,62 @@ describe("api", function() { .catch(done.fail); }); - it("gets default page layout", function(done) { + it("gets default page layout", function (done) { var loadingTask = getDocument(buildGetDocumentParams("tracemonkey.pdf")); loadingTask.promise - .then(function(pdfDoc) { + .then(function (pdfDoc) { return pdfDoc.getPageLayout(); }) - .then(function(mode) { + .then(function (mode) { expect(mode).toEqual(""); loadingTask.destroy().then(done); }) .catch(done.fail); }); - it("gets non-default page layout", function(done) { + it("gets non-default page layout", function (done) { pdfDocument .getPageLayout() - .then(function(mode) { + .then(function (mode) { expect(mode).toEqual("SinglePage"); done(); }) .catch(done.fail); }); - it("gets default page mode", function(done) { + it("gets default page mode", function (done) { var loadingTask = getDocument(buildGetDocumentParams("tracemonkey.pdf")); loadingTask.promise - .then(function(pdfDoc) { + .then(function (pdfDoc) { return pdfDoc.getPageMode(); }) - .then(function(mode) { + .then(function (mode) { expect(mode).toEqual("UseNone"); loadingTask.destroy().then(done); }) .catch(done.fail); }); - it("gets non-default page mode", function(done) { + it("gets non-default page mode", function (done) { pdfDocument .getPageMode() - .then(function(mode) { + .then(function (mode) { expect(mode).toEqual("UseOutlines"); done(); }) .catch(done.fail); }); - it("gets default viewer preferences", function(done) { + it("gets default viewer preferences", function (done) { var loadingTask = getDocument(buildGetDocumentParams("tracemonkey.pdf")); loadingTask.promise - .then(function(pdfDoc) { + .then(function (pdfDoc) { return pdfDoc.getViewerPreferences(); }) - .then(function(prefs) { + .then(function (prefs) { expect( typeof prefs === "object" && prefs !== null && isEmptyObj(prefs) ).toEqual(true); @@ -854,10 +854,10 @@ describe("api", function() { }) .catch(done.fail); }); - it("gets non-default viewer preferences", function(done) { + it("gets non-default viewer preferences", function (done) { pdfDocument .getViewerPreferences() - .then(function(prefs) { + .then(function (prefs) { expect(prefs).toEqual({ Direction: "L2R", }); @@ -866,24 +866,24 @@ describe("api", function() { .catch(done.fail); }); - it("gets default open action", function(done) { + it("gets default open action", function (done) { var loadingTask = getDocument(buildGetDocumentParams("tracemonkey.pdf")); loadingTask.promise - .then(function(pdfDoc) { + .then(function (pdfDoc) { return pdfDoc.getOpenAction(); }) - .then(function(openAction) { + .then(function (openAction) { expect(openAction).toEqual(null); loadingTask.destroy().then(done); }) .catch(done.fail); }); - it("gets non-default open action (with destination)", function(done) { + it("gets non-default open action (with destination)", function (done) { pdfDocument .getOpenAction() - .then(function(openAction) { + .then(function (openAction) { expect(openAction.dest).toEqual([ { num: 15, gen: 0 }, { name: "FitH" }, @@ -895,7 +895,7 @@ describe("api", function() { }) .catch(done.fail); }); - it("gets non-default open action (with Print action)", function(done) { + it("gets non-default open action (with Print action)", function (done) { // PDF document with "Print" Named action in the OpenAction dictionary. const loadingTask1 = getDocument( buildGetDocumentParams("bug1001080.pdf") @@ -907,20 +907,20 @@ describe("api", function() { ); const promise1 = loadingTask1.promise - .then(function(pdfDoc) { + .then(function (pdfDoc) { return pdfDoc.getOpenAction(); }) - .then(function(openAction) { + .then(function (openAction) { expect(openAction.dest).toBeUndefined(); expect(openAction.action).toEqual("Print"); return loadingTask1.destroy(); }); const promise2 = loadingTask2.promise - .then(function(pdfDoc) { + .then(function (pdfDoc) { return pdfDoc.getOpenAction(); }) - .then(function(openAction) { + .then(function (openAction) { expect(openAction.dest).toBeUndefined(); expect(openAction.action).toEqual("Print"); @@ -930,22 +930,22 @@ describe("api", function() { Promise.all([promise1, promise2]).then(done, done.fail); }); - it("gets non-existent attachments", function(done) { + it("gets non-existent attachments", function (done) { var promise = pdfDocument.getAttachments(); promise - .then(function(data) { + .then(function (data) { expect(data).toEqual(null); done(); }) .catch(done.fail); }); - it("gets attachments", function(done) { + it("gets attachments", function (done) { var loadingTask = getDocument(buildGetDocumentParams("attachment.pdf")); - var promise = loadingTask.promise.then(function(pdfDoc) { + var promise = loadingTask.promise.then(function (pdfDoc) { return pdfDoc.getAttachments(); }); promise - .then(function(data) { + .then(function (data) { var attachment = data["foo.txt"]; expect(attachment.filename).toEqual("foo.txt"); expect(attachment.content).toEqual( @@ -957,23 +957,23 @@ describe("api", function() { .catch(done.fail); }); - it("gets javascript", function(done) { + it("gets javascript", function (done) { var promise = pdfDocument.getJavaScript(); promise - .then(function(data) { + .then(function (data) { expect(data).toEqual(null); done(); }) .catch(done.fail); }); - it("gets javascript with printing instructions (JS action)", function(done) { + it("gets javascript with printing instructions (JS action)", function (done) { // PDF document with "JavaScript" action in the OpenAction dictionary. var loadingTask = getDocument(buildGetDocumentParams("issue6106.pdf")); - var promise = loadingTask.promise.then(function(pdfDoc) { + var promise = loadingTask.promise.then(function (pdfDoc) { return pdfDoc.getJavaScript(); }); promise - .then(function(data) { + .then(function (data) { expect(data).toEqual([ "this.print({bUI:true,bSilent:false,bShrinkToFit:true});", ]); @@ -983,24 +983,24 @@ describe("api", function() { .catch(done.fail); }); - it("gets non-existent outline", function(done) { + it("gets non-existent outline", function (done) { var loadingTask = getDocument(buildGetDocumentParams("tracemonkey.pdf")); - var promise = loadingTask.promise.then(function(pdfDoc) { + var promise = loadingTask.promise.then(function (pdfDoc) { return pdfDoc.getOutline(); }); promise - .then(function(outline) { + .then(function (outline) { expect(outline).toEqual(null); loadingTask.destroy().then(done); }) .catch(done.fail); }); - it("gets outline", function(done) { + it("gets outline", function (done) { var promise = pdfDocument.getOutline(); promise - .then(function(outline) { + .then(function (outline) { // Two top level entries. expect(Array.isArray(outline)).toEqual(true); expect(outline.length).toEqual(2); @@ -1024,12 +1024,12 @@ describe("api", function() { }) .catch(done.fail); }); - it("gets outline containing a url", function(done) { + it("gets outline containing a url", function (done) { var loadingTask = getDocument(buildGetDocumentParams("issue3214.pdf")); loadingTask.promise - .then(function(pdfDoc) { - pdfDoc.getOutline().then(function(outline) { + .then(function (pdfDoc) { + pdfDoc.getOutline().then(function (outline) { expect(Array.isArray(outline)).toEqual(true); expect(outline.length).toEqual(5); @@ -1053,10 +1053,10 @@ describe("api", function() { .catch(done.fail); }); - it("gets non-existent permissions", function(done) { + it("gets non-existent permissions", function (done) { pdfDocument .getPermissions() - .then(function(permissions) { + .then(function (permissions) { expect(permissions).toEqual(null); done(); @@ -1064,12 +1064,12 @@ describe("api", function() { .catch(done.fail); }); - it("gets permissions", function(done) { + it("gets permissions", function (done) { // Editing not allowed. const loadingTask0 = getDocument( buildGetDocumentParams("issue9972-1.pdf") ); - const promise0 = loadingTask0.promise.then(function(pdfDoc) { + const promise0 = loadingTask0.promise.then(function (pdfDoc) { return pdfDoc.getPermissions(); }); @@ -1077,7 +1077,7 @@ describe("api", function() { const loadingTask1 = getDocument( buildGetDocumentParams("issue9972-2.pdf") ); - const promise1 = loadingTask1.promise.then(function(pdfDoc) { + const promise1 = loadingTask1.promise.then(function (pdfDoc) { return pdfDoc.getPermissions(); }); @@ -1085,13 +1085,13 @@ describe("api", function() { const loadingTask2 = getDocument( buildGetDocumentParams("issue9972-3.pdf") ); - const promise2 = loadingTask2.promise.then(function(pdfDoc) { + const promise2 = loadingTask2.promise.then(function (pdfDoc) { return pdfDoc.getPermissions(); }); const totalPermissionCount = Object.keys(PermissionFlag).length; Promise.all([promise0, promise1, promise2]) - .then(function(permissions) { + .then(function (permissions) { expect(permissions[0].length).toEqual(totalPermissionCount - 1); expect( permissions[0].includes(PermissionFlag.MODIFY_CONTENTS) @@ -1115,10 +1115,10 @@ describe("api", function() { .catch(done.fail); }); - it("gets metadata", function(done) { + it("gets metadata", function (done) { var promise = pdfDocument.getMetadata(); promise - .then(function({ info, metadata, contentDispositionFilename }) { + .then(function ({ info, metadata, contentDispositionFilename }) { expect(info["Title"]).toEqual("Basic API Test"); // Custom, non-standard, information dictionary entries. expect(info["Custom"]).toEqual(undefined); @@ -1137,14 +1137,14 @@ describe("api", function() { }) .catch(done.fail); }); - it("gets metadata, with custom info dict entries", function(done) { + it("gets metadata, with custom info dict entries", function (done) { var loadingTask = getDocument(buildGetDocumentParams("tracemonkey.pdf")); loadingTask.promise - .then(function(pdfDoc) { + .then(function (pdfDoc) { return pdfDoc.getMetadata(); }) - .then(function({ info, metadata, contentDispositionFilename }) { + .then(function ({ info, metadata, contentDispositionFilename }) { expect(info["Creator"]).toEqual("TeX"); expect(info["Producer"]).toEqual("pdfeTeX-1.21a"); expect(info["CreationDate"]).toEqual("D:20090401163925-07'00'"); @@ -1170,14 +1170,14 @@ describe("api", function() { }) .catch(done.fail); }); - it("gets metadata, with missing PDF header (bug 1606566)", function(done) { + it("gets metadata, with missing PDF header (bug 1606566)", function (done) { const loadingTask = getDocument(buildGetDocumentParams("bug1606566.pdf")); loadingTask.promise - .then(function(pdfDoc) { + .then(function (pdfDoc) { return pdfDoc.getMetadata(); }) - .then(function({ info, metadata, contentDispositionFilename }) { + .then(function ({ info, metadata, contentDispositionFilename }) { // The following are PDF.js specific, non-standard, properties. expect(info["PDFFormatVersion"]).toEqual(null); expect(info["IsLinearized"]).toEqual(false); @@ -1193,51 +1193,51 @@ describe("api", function() { .catch(done.fail); }); - it("gets data", function(done) { + it("gets data", function (done) { var promise = pdfDocument.getData(); promise - .then(function(data) { + .then(function (data) { expect(data instanceof Uint8Array).toEqual(true); expect(data.length).toEqual(basicApiFileLength); done(); }) .catch(done.fail); }); - it("gets download info", function(done) { + it("gets download info", function (done) { var promise = pdfDocument.getDownloadInfo(); promise - .then(function(data) { + .then(function (data) { expect(data).toEqual({ length: basicApiFileLength }); done(); }) .catch(done.fail); }); - it("gets document stats", function(done) { + it("gets document stats", function (done) { var promise = pdfDocument.getStats(); promise - .then(function(stats) { + .then(function (stats) { expect(stats).toEqual({ streamTypes: {}, fontTypes: {} }); done(); }) .catch(done.fail); }); - it("cleans up document resources", function(done) { + it("cleans up document resources", function (done) { const promise = pdfDocument.cleanup(); - promise.then(function() { + promise.then(function () { expect(true).toEqual(true); done(); }, done.fail); }); - it("checks that fingerprints are unique", function(done) { + it("checks that fingerprints are unique", function (done) { const loadingTask1 = getDocument( buildGetDocumentParams("issue4436r.pdf") ); const loadingTask2 = getDocument(buildGetDocumentParams("issue4575.pdf")); Promise.all([loadingTask1.promise, loadingTask2.promise]) - .then(function(data) { + .then(function (data) { const fingerprint1 = data[0].fingerprint; const fingerprint2 = data[1].fingerprint; @@ -1253,7 +1253,7 @@ describe("api", function() { .catch(done.fail); }); - describe("Cross-origin", function() { + describe("Cross-origin", function () { var loadingTask; function _checkCanLoad(expectSuccess, filename, options) { if (isNodeJS) { @@ -1271,14 +1271,14 @@ describe("api", function() { params.url = url.href; loadingTask = getDocument(params); return loadingTask.promise - .then(function(pdf) { + .then(function (pdf) { return pdf.destroy(); }) .then( - function() { + function () { expect(expectSuccess).toEqual(true); }, - function(error) { + function (error) { if (expectSuccess) { // For ease of debugging. expect(error).toEqual("There should not be any error"); @@ -1293,35 +1293,35 @@ describe("api", function() { function testCannotLoad(filename, options) { return _checkCanLoad(false, filename, options); } - afterEach(function(done) { + afterEach(function (done) { if (loadingTask && !loadingTask.destroyed) { loadingTask.destroy().then(done); } else { done(); } }); - it("server disallows cors", function(done) { + it("server disallows cors", function (done) { testCannotLoad("basicapi.pdf").then(done); }); - it("server allows cors without credentials, default withCredentials", function(done) { + it("server allows cors without credentials, default withCredentials", function (done) { testCanLoad("basicapi.pdf?cors=withoutCredentials").then(done); }); - it("server allows cors without credentials, and withCredentials=false", function(done) { + it("server allows cors without credentials, and withCredentials=false", function (done) { testCanLoad("basicapi.pdf?cors=withoutCredentials", { withCredentials: false, }).then(done); }); - it("server allows cors without credentials, but withCredentials=true", function(done) { + it("server allows cors without credentials, but withCredentials=true", function (done) { testCannotLoad("basicapi.pdf?cors=withoutCredentials", { withCredentials: true, }).then(done); }); - it("server allows cors with credentials, and withCredentials=true", function(done) { + it("server allows cors with credentials, and withCredentials=true", function (done) { testCanLoad("basicapi.pdf?cors=withCredentials", { withCredentials: true, }).then(done); }); - it("server allows cors with credentials, and withCredentials=false", function(done) { + it("server allows cors with credentials, and withCredentials=false", function (done) { // The server supports even more than we need, so if the previous tests // pass, then this should pass for sure. // The only case where this test fails is when the server does not reply @@ -1332,15 +1332,15 @@ describe("api", function() { }); }); }); - describe("Page", function() { + describe("Page", function () { let pdfLoadingTask, pdfDocument, page; - beforeAll(function(done) { + beforeAll(function (done) { pdfLoadingTask = getDocument(basicApiGetDocumentParams); pdfLoadingTask.promise - .then(function(doc) { + .then(function (doc) { pdfDocument = doc; - pdfDocument.getPage(1).then(function(data) { + pdfDocument.getPage(1).then(function (data) { page = data; done(); }); @@ -1348,27 +1348,27 @@ describe("api", function() { .catch(done.fail); }); - afterAll(function(done) { + afterAll(function (done) { pdfLoadingTask.destroy().then(done); }); - it("gets page number", function() { + it("gets page number", function () { expect(page.pageNumber).toEqual(1); }); - it("gets rotate", function() { + it("gets rotate", function () { expect(page.rotate).toEqual(0); }); - it("gets ref", function() { + it("gets ref", function () { expect(page.ref).toEqual({ num: 15, gen: 0 }); }); - it("gets userUnit", function() { + it("gets userUnit", function () { expect(page.userUnit).toEqual(1.0); }); - it("gets view", function() { + it("gets view", function () { expect(page.view).toEqual([0, 0, 595.28, 841.89]); }); - it("gets view, with empty/invalid bounding boxes", function(done) { + it("gets view, with empty/invalid bounding boxes", function (done) { const viewLoadingTask = getDocument( buildGetDocumentParams("boundingBox_invalid.pdf") ); @@ -1396,7 +1396,7 @@ describe("api", function() { .catch(done.fail); }); - it("gets viewport", function() { + it("gets viewport", function () { var viewport = page.getViewport({ scale: 1.5, rotation: 90 }); expect(viewport.viewBox).toEqual(page.view); expect(viewport.scale).toEqual(1.5); @@ -1405,7 +1405,7 @@ describe("api", function() { expect(viewport.width).toEqual(1262.835); expect(viewport.height).toEqual(892.92); }); - it('gets viewport with "offsetX/offsetY" arguments', function() { + it('gets viewport with "offsetX/offsetY" arguments', function () { const viewport = page.getViewport({ scale: 1, rotation: 0, @@ -1414,7 +1414,7 @@ describe("api", function() { }); expect(viewport.transform).toEqual([1, 0, 0, -1, 100, 741.89]); }); - it('gets viewport respecting "dontFlip" argument', function() { + it('gets viewport respecting "dontFlip" argument', function () { const scale = 1, rotation = 0; const viewport = page.getViewport({ scale, rotation }); @@ -1430,35 +1430,35 @@ describe("api", function() { expect(viewport.transform).toEqual([1, 0, 0, -1, 0, 841.89]); expect(dontFlipViewport.transform).toEqual([1, 0, -0, 1, 0, 0]); }); - it("gets annotations", function(done) { - var defaultPromise = page.getAnnotations().then(function(data) { + it("gets annotations", function (done) { + var defaultPromise = page.getAnnotations().then(function (data) { expect(data.length).toEqual(4); }); var displayPromise = page .getAnnotations({ intent: "display" }) - .then(function(data) { + .then(function (data) { expect(data.length).toEqual(4); }); var printPromise = page .getAnnotations({ intent: "print" }) - .then(function(data) { + .then(function (data) { expect(data.length).toEqual(4); }); Promise.all([defaultPromise, displayPromise, printPromise]) - .then(function() { + .then(function () { done(); }) .catch(done.fail); }); - it("gets annotations containing relative URLs (bug 766086)", function(done) { + it("gets annotations containing relative URLs (bug 766086)", function (done) { var filename = "bug766086.pdf"; var defaultLoadingTask = getDocument(buildGetDocumentParams(filename)); - var defaultPromise = defaultLoadingTask.promise.then(function(pdfDoc) { - return pdfDoc.getPage(1).then(function(pdfPage) { + var defaultPromise = defaultLoadingTask.promise.then(function (pdfDoc) { + return pdfDoc.getPage(1).then(function (pdfPage) { return pdfPage.getAnnotations(); }); }); @@ -1468,10 +1468,10 @@ describe("api", function() { docBaseUrl: "http://www.example.com/test/pdfs/qwerty.pdf", }) ); - var docBaseUrlPromise = docBaseUrlLoadingTask.promise.then(function( + var docBaseUrlPromise = docBaseUrlLoadingTask.promise.then(function ( pdfDoc ) { - return pdfDoc.getPage(1).then(function(pdfPage) { + return pdfDoc.getPage(1).then(function (pdfPage) { return pdfPage.getAnnotations(); }); }); @@ -1482,15 +1482,15 @@ describe("api", function() { }) ); var invalidDocBaseUrlPromise = invalidDocBaseUrlLoadingTask.promise.then( - function(pdfDoc) { - return pdfDoc.getPage(1).then(function(pdfPage) { + function (pdfDoc) { + return pdfDoc.getPage(1).then(function (pdfPage) { return pdfPage.getAnnotations(); }); } ); Promise.all([defaultPromise, docBaseUrlPromise, invalidDocBaseUrlPromise]) - .then(function(data) { + .then(function (data) { var defaultAnnotations = data[0]; var docBaseUrlAnnotations = data[1]; var invalidDocBaseUrlAnnotations = data[2]; @@ -1521,7 +1521,7 @@ describe("api", function() { .catch(done.fail); }); - it("gets text content", function(done) { + it("gets text content", function (done) { var defaultPromise = page.getTextContent(); var parametersPromise = page.getTextContent({ normalizeWhitespace: true, @@ -1530,7 +1530,7 @@ describe("api", function() { var promises = [defaultPromise, parametersPromise]; Promise.all(promises) - .then(function(data) { + .then(function (data) { expect(!!data[0].items).toEqual(true); expect(data[0].items.length).toEqual(7); expect(!!data[0].styles).toEqual(true); @@ -1542,7 +1542,7 @@ describe("api", function() { .catch(done.fail); }); - it("gets text content, with correct properties (issue 8276)", function(done) { + it("gets text content, with correct properties (issue 8276)", function (done) { const loadingTask = getDocument( buildGetDocumentParams("issue8276_reduced.pdf") ); @@ -1576,10 +1576,10 @@ describe("api", function() { .catch(done.fail); }); - it("gets operator list", function(done) { + it("gets operator list", function (done) { var promise = page.getOperatorList(); promise - .then(function(oplist) { + .then(function (oplist) { expect(!!oplist.fnArray).toEqual(true); expect(!!oplist.argsArray).toEqual(true); expect(oplist.lastChunk).toEqual(true); @@ -1588,7 +1588,7 @@ describe("api", function() { .catch(done.fail); }); - it("gets operatorList with JPEG image (issue 4888)", function(done) { + it("gets operatorList with JPEG image (issue 4888)", function (done) { const loadingTask = getDocument(buildGetDocumentParams("cmykjpeg.pdf")); loadingTask.promise @@ -1612,7 +1612,7 @@ describe("api", function() { it( "gets operatorList, from corrupt PDF file (issue 8702), " + "with/without `stopAtErrors` set", - function(done) { + function (done) { const loadingTask1 = getDocument( buildGetDocumentParams("issue8702.pdf", { stopAtErrors: false, // The default value. @@ -1652,8 +1652,8 @@ describe("api", function() { } ); - it("gets document stats after parsing page", function(done) { - var promise = page.getOperatorList().then(function() { + it("gets document stats after parsing page", function (done) { + var promise = page.getOperatorList().then(function () { return pdfDocument.getStats(); }); var expectedStreamTypes = {}; @@ -1663,7 +1663,7 @@ describe("api", function() { expectedFontTypes[FontType.CIDFONTTYPE2] = true; promise - .then(function(stats) { + .then(function (stats) { expect(stats).toEqual({ streamTypes: expectedStreamTypes, fontTypes: expectedFontTypes, @@ -1673,7 +1673,7 @@ describe("api", function() { .catch(done.fail); }); - it("gets page stats after parsing page, without `pdfBug` set", function(done) { + it("gets page stats after parsing page, without `pdfBug` set", function (done) { page .getOperatorList() .then(opList => { @@ -1684,7 +1684,7 @@ describe("api", function() { done(); }, done.fail); }); - it("gets page stats after parsing page, with `pdfBug` set", function(done) { + it("gets page stats after parsing page, with `pdfBug` set", function (done) { const loadingTask = getDocument( buildGetDocumentParams(basicApiFileName, { pdfBug: true }) ); @@ -1708,7 +1708,7 @@ describe("api", function() { loadingTask.destroy().then(done); }, done.fail); }); - it("gets page stats after rendering page, with `pdfBug` set", function(done) { + it("gets page stats after rendering page, with `pdfBug` set", function (done) { const loadingTask = getDocument( buildGetDocumentParams(basicApiFileName, { pdfBug: true }) ); @@ -1754,7 +1754,7 @@ describe("api", function() { }, done.fail); }); - it("cancels rendering of page", function(done) { + it("cancels rendering of page", function (done) { var viewport = page.getViewport({ scale: 1 }); var canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height); @@ -1766,10 +1766,10 @@ describe("api", function() { renderTask.cancel(); renderTask.promise - .then(function() { + .then(function () { done.fail("shall cancel rendering"); }) - .catch(function(error) { + .catch(function (error) { expect(error instanceof RenderingCancelledException).toEqual(true); expect(error.message).toEqual("Rendering cancelled, page 1"); expect(error.type).toEqual("canvas"); @@ -1779,7 +1779,7 @@ describe("api", function() { }); }); - it("re-render page, using the same canvas, after cancelling rendering", function(done) { + it("re-render page, using the same canvas, after cancelling rendering", function (done) { const viewport = page.getViewport({ scale: 1 }); const canvasAndCtx = CanvasFactory.create( viewport.width, @@ -1816,7 +1816,7 @@ describe("api", function() { }, done.fail); }); - it("multiple render() on the same canvas", function(done) { + it("multiple render() on the same canvas", function (done) { var viewport = page.getViewport({ scale: 1 }); var canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height); @@ -1845,7 +1845,7 @@ describe("api", function() { ]).then(done); }); - it("cleans up document resources after rendering of page", function(done) { + it("cleans up document resources after rendering of page", function (done) { const loadingTask = getDocument(buildGetDocumentParams(basicApiFileName)); let canvasAndCtx; @@ -1876,7 +1876,7 @@ describe("api", function() { }, done.fail); }); - it("cleans up document resources during rendering of page", function(done) { + it("cleans up document resources during rendering of page", function (done) { const loadingTask = getDocument( buildGetDocumentParams("tracemonkey.pdf") ); @@ -1922,7 +1922,7 @@ describe("api", function() { .catch(done.fail); }); }); - describe("Multiple `getDocument` instances", function() { + describe("Multiple `getDocument` instances", function () { // Regression test for https://github.com/mozilla/pdf.js/issues/6205 // A PDF using the Helvetica font. var pdf1 = buildGetDocumentParams("tracemonkey.pdf"); @@ -1955,28 +1955,28 @@ describe("api", function() { return data; } - afterEach(function(done) { + afterEach(function (done) { // Issue 6205 reported an issue with font rendering, so clear the loaded // fonts so that we can see whether loading PDFs in parallel does not // cause any issues with the rendered fonts. - const destroyPromises = loadingTasks.map(function(loadingTask) { + const destroyPromises = loadingTasks.map(function (loadingTask) { return loadingTask.destroy(); }); Promise.all(destroyPromises).then(done); }); - it("should correctly render PDFs in parallel", function(done) { + it("should correctly render PDFs in parallel", function (done) { var baseline1, baseline2, baseline3; var promiseDone = renderPDF(pdf1) - .then(function(data1) { + .then(function (data1) { baseline1 = data1; return renderPDF(pdf2); }) - .then(function(data2) { + .then(function (data2) { baseline2 = data2; return renderPDF(pdf3); }) - .then(function(data3) { + .then(function (data3) { baseline3 = data3; return Promise.all([ renderPDF(pdf1), @@ -1984,24 +1984,24 @@ describe("api", function() { renderPDF(pdf3), ]); }) - .then(function(dataUrls) { + .then(function (dataUrls) { expect(dataUrls[0]).toEqual(baseline1); expect(dataUrls[1]).toEqual(baseline2); expect(dataUrls[2]).toEqual(baseline3); return true; }); promiseDone - .then(function() { + .then(function () { done(); }) .catch(done.fail); }); }); - describe("PDFDataRangeTransport", function() { + describe("PDFDataRangeTransport", function () { let dataPromise; - beforeAll(function(done) { + beforeAll(function (done) { const fileName = "tracemonkey.pdf"; if (isNodeJS) { dataPromise = NodeFileReaderFactory.fetch({ @@ -2015,22 +2015,22 @@ describe("api", function() { done(); }); - afterAll(function() { + afterAll(function () { dataPromise = null; }); - it("should fetch document info and page using ranges", function(done) { + it("should fetch document info and page using ranges", function (done) { const initialDataLength = 4000; let fetches = 0, loadingTask; dataPromise - .then(function(data) { + .then(function (data) { const initialData = data.subarray(0, initialDataLength); const transport = new PDFDataRangeTransport(data.length, initialData); - transport.requestDataRange = function(begin, end) { + transport.requestDataRange = function (begin, end) { fetches++; - waitSome(function() { + waitSome(function () { transport.onDataProgress(4000); transport.onDataRange(begin, data.subarray(begin, end)); }); @@ -2038,12 +2038,12 @@ describe("api", function() { loadingTask = getDocument(transport); return loadingTask.promise; }) - .then(function(pdfDocument) { + .then(function (pdfDocument) { expect(pdfDocument.numPages).toEqual(14); return pdfDocument.getPage(10); }) - .then(function(pdfPage) { + .then(function (pdfPage) { expect(pdfPage.rotate).toEqual(0); expect(fetches).toBeGreaterThan(2); @@ -2052,38 +2052,38 @@ describe("api", function() { .catch(done.fail); }); - it("should fetch document info and page using range and streaming", function(done) { + it("should fetch document info and page using range and streaming", function (done) { const initialDataLength = 4000; let fetches = 0, loadingTask; dataPromise - .then(function(data) { + .then(function (data) { const initialData = data.subarray(0, initialDataLength); const transport = new PDFDataRangeTransport(data.length, initialData); - transport.requestDataRange = function(begin, end) { + transport.requestDataRange = function (begin, end) { fetches++; if (fetches === 1) { // Send rest of the data on first range request. transport.onDataProgressiveRead(data.subarray(initialDataLength)); } - waitSome(function() { + waitSome(function () { transport.onDataRange(begin, data.subarray(begin, end)); }); }; loadingTask = getDocument(transport); return loadingTask.promise; }) - .then(function(pdfDocument) { + .then(function (pdfDocument) { expect(pdfDocument.numPages).toEqual(14); return pdfDocument.getPage(10); }) - .then(function(pdfPage) { + .then(function (pdfPage) { expect(pdfPage.rotate).toEqual(0); expect(fetches).toEqual(1); - waitSome(function() { + waitSome(function () { loadingTask.destroy().then(done); }); }) @@ -2093,29 +2093,29 @@ describe("api", function() { it( "should fetch document info and page, without range, " + "using complete initialData", - function(done) { + function (done) { let fetches = 0, loadingTask; dataPromise - .then(function(data) { + .then(function (data) { const transport = new PDFDataRangeTransport( data.length, data, /* progressiveDone = */ true ); - transport.requestDataRange = function(begin, end) { + transport.requestDataRange = function (begin, end) { fetches++; }; loadingTask = getDocument({ disableRange: true, range: transport }); return loadingTask.promise; }) - .then(function(pdfDocument) { + .then(function (pdfDocument) { expect(pdfDocument.numPages).toEqual(14); return pdfDocument.getPage(10); }) - .then(function(pdfPage) { + .then(function (pdfPage) { expect(pdfPage.rotate).toEqual(0); expect(fetches).toEqual(0); diff --git a/test/unit/bidi_spec.js b/test/unit/bidi_spec.js index be2122ce7..e6dfe3d0a 100644 --- a/test/unit/bidi_spec.js +++ b/test/unit/bidi_spec.js @@ -15,8 +15,8 @@ import { bidi } from "../../src/core/bidi.js"; -describe("bidi", function() { - it("should mark text as RTL if more than 30% of text is RTL", function() { +describe("bidi", function () { + it("should mark text as RTL if more than 30% of text is RTL", function () { // 33% of test text are RTL characters var test = "\u0645\u0635\u0631 Egypt"; var result = "Egypt \u0631\u0635\u0645"; @@ -26,7 +26,7 @@ describe("bidi", function() { expect(bidiText.dir).toEqual("rtl"); }); - it("should mark text as LTR if less than 30% of text is RTL", function() { + it("should mark text as LTR if less than 30% of text is RTL", function () { var test = "Egypt is known as \u0645\u0635\u0631 in Arabic."; var result = "Egypt is known as \u0631\u0635\u0645 in Arabic."; var bidiText = bidi(test, -1, false); diff --git a/test/unit/cff_parser_spec.js b/test/unit/cff_parser_spec.js index aa340bfca..16df3270c 100644 --- a/test/unit/cff_parser_spec.js +++ b/test/unit/cff_parser_spec.js @@ -23,7 +23,7 @@ import { import { SEAC_ANALYSIS_ENABLED } from "../../src/core/fonts.js"; import { Stream } from "../../src/core/stream.js"; -describe("CFFParser", function() { +describe("CFFParser", function () { function createWithNullProto(obj) { var result = Object.create(null); for (var i in obj) { @@ -41,7 +41,7 @@ describe("CFFParser", function() { var fontData, parser, cff; - beforeAll(function(done) { + beforeAll(function (done) { // This example font comes from the CFF spec: // http://www.adobe.com/content/dam/Adobe/en/devnet/font/pdfs/5176.CFF.pdf var exampleFont = @@ -64,22 +64,22 @@ describe("CFFParser", function() { done(); }); - afterAll(function() { + afterAll(function () { fontData = null; }); - beforeEach(function(done) { + beforeEach(function (done) { parser = new CFFParser(fontData, {}, SEAC_ANALYSIS_ENABLED); cff = parser.parse(); done(); }); - afterEach(function(done) { + afterEach(function (done) { parser = cff = null; done(); }); - it("parses header", function() { + it("parses header", function () { var header = cff.header; expect(header.major).toEqual(1); expect(header.minor).toEqual(0); @@ -87,20 +87,20 @@ describe("CFFParser", function() { expect(header.offSize).toEqual(1); }); - it("parses name index", function() { + it("parses name index", function () { var names = cff.names; expect(names.length).toEqual(1); expect(names[0]).toEqual("ABCDEF+Times-Roman"); }); - it("parses string index", function() { + it("parses string index", function () { var strings = cff.strings; expect(strings.count).toEqual(3); expect(strings.get(0)).toEqual(".notdef"); expect(strings.get(391)).toEqual("001.007"); }); - it("parses top dict", function() { + it("parses top dict", function () { var topDict = cff.topDict; // 391 version 392 FullName 393 FamilyName 389 Weight 28416 UniqueID // -168 -218 1000 898 FontBBox 94 CharStrings 45 102 Private @@ -114,7 +114,7 @@ describe("CFFParser", function() { expect(topDict.getByName("Private")).toEqual([45, 102]); }); - it("refuses to add topDict key with invalid value (bug 1068432)", function() { + it("refuses to add topDict key with invalid value (bug 1068432)", function () { var topDict = cff.topDict; var defaultValue = topDict.getByName("UnderlinePosition"); @@ -125,7 +125,7 @@ describe("CFFParser", function() { it( "ignores reserved commands in parseDict, and refuses to add privateDict " + "keys with invalid values (bug 1308536)", - function() { + function () { // prettier-ignore var bytes = new Uint8Array([ 64, 39, 31, 30, 252, 114, 137, 115, 79, 30, 197, 119, 2, 99, 127, 6 @@ -134,7 +134,7 @@ describe("CFFParser", function() { var topDict = cff.topDict; topDict.setByName("Private", [bytes.length, 0]); - var parsePrivateDict = function() { + var parsePrivateDict = function () { parser.parsePrivateDict(topDict); }; expect(parsePrivateDict).not.toThrow(); @@ -144,7 +144,7 @@ describe("CFFParser", function() { } ); - it("parses a CharString having cntrmask", function() { + it("parses a CharString having cntrmask", function () { // prettier-ignore var bytes = new Uint8Array([0, 1, // count 1, // offsetSize @@ -171,7 +171,7 @@ describe("CFFParser", function() { expect(charStrings.get(0).length).toEqual(38); }); - it("parses a CharString endchar with 4 args w/seac enabled", function() { + it("parses a CharString endchar with 4 args w/seac enabled", function () { const cffParser = new CFFParser( fontData, {}, @@ -200,7 +200,7 @@ describe("CFFParser", function() { expect(result.seacs[0][3]).toEqual(194); }); - it("parses a CharString endchar with 4 args w/seac disabled", function() { + it("parses a CharString endchar with 4 args w/seac disabled", function () { const cffParser = new CFFParser( fontData, {}, @@ -224,7 +224,7 @@ describe("CFFParser", function() { expect(result.seacs.length).toEqual(0); }); - it("parses a CharString endchar no args", function() { + it("parses a CharString endchar no args", function () { // prettier-ignore var bytes = new Uint8Array([0, 1, // count 1, // offsetSize @@ -241,12 +241,12 @@ describe("CFFParser", function() { expect(result.seacs.length).toEqual(0); }); - it("parses predefined charsets", function() { + it("parses predefined charsets", function () { var charset = parser.parseCharsets(0, 0, null, true); expect(charset.predefined).toEqual(true); }); - it("parses charset format 0", function() { + it("parses charset format 0", function () { // The first three bytes make the offset large enough to skip predefined. // prettier-ignore var bytes = new Uint8Array([0x00, 0x00, 0x00, @@ -262,7 +262,7 @@ describe("CFFParser", function() { expect(charset.charset[1]).toEqual(2); }); - it("parses charset format 1", function() { + it("parses charset format 1", function () { // The first three bytes make the offset large enough to skip predefined. // prettier-ignore var bytes = new Uint8Array([0x00, 0x00, 0x00, @@ -279,7 +279,7 @@ describe("CFFParser", function() { expect(charset.charset).toEqual([0, 8, 9]); }); - it("parses charset format 2", function() { + it("parses charset format 2", function () { // format 2 is the same as format 1 but the left is card16 // The first three bytes make the offset large enough to skip predefined. // prettier-ignore @@ -297,7 +297,7 @@ describe("CFFParser", function() { expect(charset.charset).toEqual([0, 8, 9]); }); - it("parses encoding format 0", function() { + it("parses encoding format 0", function () { // The first two bytes make the offset large enough to skip predefined. // prettier-ignore var bytes = new Uint8Array([0x00, 0x00, @@ -310,7 +310,7 @@ describe("CFFParser", function() { expect(encoding.encoding).toEqual(createWithNullProto({ 0x8: 1 })); }); - it("parses encoding format 1", function() { + it("parses encoding format 1", function () { // The first two bytes make the offset large enough to skip predefined. // prettier-ignore var bytes = new Uint8Array([0x00, 0x00, @@ -326,7 +326,7 @@ describe("CFFParser", function() { ); }); - it("parses fdselect format 0", function() { + it("parses fdselect format 0", function () { // prettier-ignore var bytes = new Uint8Array([0x00, // format 0x00, // gid: 0 fd: 0 @@ -339,7 +339,7 @@ describe("CFFParser", function() { expect(fdSelect.format).toEqual(0); }); - it("parses fdselect format 3", function() { + it("parses fdselect format 3", function () { // prettier-ignore var bytes = new Uint8Array([0x03, // format 0x00, 0x02, // range count @@ -356,7 +356,7 @@ describe("CFFParser", function() { expect(fdSelect.format).toEqual(3); }); - it("parses invalid fdselect format 3 (bug 1146106)", function() { + it("parses invalid fdselect format 3 (bug 1146106)", function () { // prettier-ignore var bytes = new Uint8Array([0x03, // format 0x00, 0x02, // range count @@ -376,7 +376,7 @@ describe("CFFParser", function() { // TODO fdArray }); -describe("CFFCompiler", function() { +describe("CFFCompiler", function () { function testParser(bytes) { bytes = new Uint8Array(bytes); return new CFFParser( @@ -390,7 +390,7 @@ describe("CFFCompiler", function() { ); } - it("encodes integers", function() { + it("encodes integers", function () { var c = new CFFCompiler(); // all the examples from the spec expect(c.encodeInteger(0)).toEqual([0x8b]); @@ -404,13 +404,13 @@ describe("CFFCompiler", function() { expect(c.encodeInteger(-100000)).toEqual([0x1d, 0xff, 0xfe, 0x79, 0x60]); }); - it("encodes floats", function() { + it("encodes floats", function () { var c = new CFFCompiler(); expect(c.encodeFloat(-2.25)).toEqual([0x1e, 0xe2, 0xa2, 0x5f]); expect(c.encodeFloat(5e-11)).toEqual([0x1e, 0x5c, 0x11, 0xff]); }); - it("sanitizes name index", function() { + it("sanitizes name index", function () { var c = new CFFCompiler(); var nameIndexCompiled = c.compileNameIndex(["[a"]); var parser = testParser(nameIndexCompiled); @@ -429,7 +429,7 @@ describe("CFFCompiler", function() { expect(names[0].length).toEqual(127); }); - it("compiles fdselect format 0", function() { + it("compiles fdselect format 0", function () { var fdSelect = new CFFFDSelect(0, [3, 2, 1]); var c = new CFFCompiler(); var out = c.compileFDSelect(fdSelect); @@ -441,7 +441,7 @@ describe("CFFCompiler", function() { ]); }); - it("compiles fdselect format 3", function() { + it("compiles fdselect format 3", function () { var fdSelect = new CFFFDSelect(3, [0, 0, 1, 1]); var c = new CFFCompiler(); var out = c.compileFDSelect(fdSelect); @@ -460,7 +460,7 @@ describe("CFFCompiler", function() { ]); }); - it("compiles fdselect format 3, single range", function() { + it("compiles fdselect format 3, single range", function () { var fdSelect = new CFFFDSelect(3, [0, 0]); var c = new CFFCompiler(); var out = c.compileFDSelect(fdSelect); @@ -476,7 +476,7 @@ describe("CFFCompiler", function() { ]); }); - it("compiles charset of CID font", function() { + it("compiles charset of CID font", function () { var charset = new CFFCharset(); var c = new CFFCompiler(); var numGlyphs = 7; @@ -491,7 +491,7 @@ describe("CFFCompiler", function() { ]); }); - it("compiles charset of non CID font", function() { + it("compiles charset of non CID font", function () { var charset = new CFFCharset(false, 0, ["space", "exclam"]); var c = new CFFCompiler(); var numGlyphs = 3; diff --git a/test/unit/clitests_helper.js b/test/unit/clitests_helper.js index a57ef74a7..679316afd 100644 --- a/test/unit/clitests_helper.js +++ b/test/unit/clitests_helper.js @@ -31,6 +31,6 @@ if (!isNodeJS) { setVerbosityLevel(VerbosityLevel.ERRORS); // Set the network stream factory for the unit-tests. -setPDFNetworkStreamFactory(function(params) { +setPDFNetworkStreamFactory(function (params) { return new PDFNodeStream(params); }); diff --git a/test/unit/cmap_spec.js b/test/unit/cmap_spec.js index 193a8dcc1..553a0b21e 100644 --- a/test/unit/cmap_spec.js +++ b/test/unit/cmap_spec.js @@ -26,10 +26,10 @@ var cMapUrl = { }; var cMapPacked = true; -describe("cmap", function() { +describe("cmap", function () { var fetchBuiltInCMap; - beforeAll(function(done) { + beforeAll(function (done) { // Allow CMap testing in Node.js, e.g. for Travis. var CMapReaderFactory; if (isNodeJS) { @@ -44,7 +44,7 @@ describe("cmap", function() { }); } - fetchBuiltInCMap = function(name) { + fetchBuiltInCMap = function (name) { return CMapReaderFactory.fetch({ name, }); @@ -52,11 +52,11 @@ describe("cmap", function() { done(); }); - afterAll(function() { + afterAll(function () { fetchBuiltInCMap = null; }); - it("parses beginbfchar", function(done) { + it("parses beginbfchar", function (done) { // prettier-ignore var str = "2 beginbfchar\n" + "<03> <00>\n" + @@ -65,17 +65,17 @@ describe("cmap", function() { var stream = new StringStream(str); var cmapPromise = CMapFactory.create({ encoding: stream }); cmapPromise - .then(function(cmap) { + .then(function (cmap) { expect(cmap.lookup(0x03)).toEqual(String.fromCharCode(0x00)); expect(cmap.lookup(0x04)).toEqual(String.fromCharCode(0x01)); expect(cmap.lookup(0x05)).toBeUndefined(); done(); }) - .catch(function(reason) { + .catch(function (reason) { done.fail(reason); }); }); - it("parses beginbfrange with range", function(done) { + it("parses beginbfrange with range", function (done) { // prettier-ignore var str = "1 beginbfrange\n" + "<06> <0B> 0\n" + @@ -83,18 +83,18 @@ describe("cmap", function() { var stream = new StringStream(str); var cmapPromise = CMapFactory.create({ encoding: stream }); cmapPromise - .then(function(cmap) { + .then(function (cmap) { expect(cmap.lookup(0x05)).toBeUndefined(); expect(cmap.lookup(0x06)).toEqual(String.fromCharCode(0x00)); expect(cmap.lookup(0x0b)).toEqual(String.fromCharCode(0x05)); expect(cmap.lookup(0x0c)).toBeUndefined(); done(); }) - .catch(function(reason) { + .catch(function (reason) { done.fail(reason); }); }); - it("parses beginbfrange with array", function(done) { + it("parses beginbfrange with array", function (done) { // prettier-ignore var str = "1 beginbfrange\n" + "<0D> <12> [ 0 1 2 3 4 5 ]\n" + @@ -102,18 +102,18 @@ describe("cmap", function() { var stream = new StringStream(str); var cmapPromise = CMapFactory.create({ encoding: stream }); cmapPromise - .then(function(cmap) { + .then(function (cmap) { expect(cmap.lookup(0x0c)).toBeUndefined(); expect(cmap.lookup(0x0d)).toEqual(0x00); expect(cmap.lookup(0x12)).toEqual(0x05); expect(cmap.lookup(0x13)).toBeUndefined(); done(); }) - .catch(function(reason) { + .catch(function (reason) { done.fail(reason); }); }); - it("parses begincidchar", function(done) { + it("parses begincidchar", function (done) { // prettier-ignore var str = "1 begincidchar\n" + "<14> 0\n" + @@ -121,16 +121,16 @@ describe("cmap", function() { var stream = new StringStream(str); var cmapPromise = CMapFactory.create({ encoding: stream }); cmapPromise - .then(function(cmap) { + .then(function (cmap) { expect(cmap.lookup(0x14)).toEqual(0x00); expect(cmap.lookup(0x15)).toBeUndefined(); done(); }) - .catch(function(reason) { + .catch(function (reason) { done.fail(reason); }); }); - it("parses begincidrange", function(done) { + it("parses begincidrange", function (done) { // prettier-ignore var str = "1 begincidrange\n" + "<0016> <001B> 0\n" + @@ -138,18 +138,18 @@ describe("cmap", function() { var stream = new StringStream(str); var cmapPromise = CMapFactory.create({ encoding: stream }); cmapPromise - .then(function(cmap) { + .then(function (cmap) { expect(cmap.lookup(0x15)).toBeUndefined(); expect(cmap.lookup(0x16)).toEqual(0x00); expect(cmap.lookup(0x1b)).toEqual(0x05); expect(cmap.lookup(0x1c)).toBeUndefined(); done(); }) - .catch(function(reason) { + .catch(function (reason) { done.fail(reason); }); }); - it("decodes codespace ranges", function(done) { + it("decodes codespace ranges", function (done) { // prettier-ignore var str = "1 begincodespacerange\n" + "<01> <02>\n" + @@ -158,7 +158,7 @@ describe("cmap", function() { var stream = new StringStream(str); var cmapPromise = CMapFactory.create({ encoding: stream }); cmapPromise - .then(function(cmap) { + .then(function (cmap) { var c = {}; cmap.readCharCode(String.fromCharCode(1), 0, c); expect(c.charcode).toEqual(1); @@ -168,11 +168,11 @@ describe("cmap", function() { expect(c.length).toEqual(4); done(); }) - .catch(function(reason) { + .catch(function (reason) { done.fail(reason); }); }); - it("decodes 4 byte codespace ranges", function(done) { + it("decodes 4 byte codespace ranges", function (done) { // prettier-ignore var str = "1 begincodespacerange\n" + "<8EA1A1A1> <8EA1FEFE>\n" + @@ -180,18 +180,18 @@ describe("cmap", function() { var stream = new StringStream(str); var cmapPromise = CMapFactory.create({ encoding: stream }); cmapPromise - .then(function(cmap) { + .then(function (cmap) { var c = {}; cmap.readCharCode(String.fromCharCode(0x8e, 0xa1, 0xa1, 0xa1), 0, c); expect(c.charcode).toEqual(0x8ea1a1a1); expect(c.length).toEqual(4); done(); }) - .catch(function(reason) { + .catch(function (reason) { done.fail(reason); }); }); - it("read usecmap", function(done) { + it("read usecmap", function (done) { var str = "/Adobe-Japan1-1 usecmap\n"; var stream = new StringStream(str); var cmapPromise = CMapFactory.create({ @@ -200,7 +200,7 @@ describe("cmap", function() { useCMap: null, }); cmapPromise - .then(function(cmap) { + .then(function (cmap) { expect(cmap instanceof CMap).toEqual(true); expect(cmap.useCMap).not.toBeNull(); expect(cmap.builtInCMap).toBeFalsy(); @@ -208,44 +208,44 @@ describe("cmap", function() { expect(cmap.isIdentityCMap).toEqual(false); done(); }) - .catch(function(reason) { + .catch(function (reason) { done.fail(reason); }); }); - it("parses cmapname", function(done) { + it("parses cmapname", function (done) { var str = "/CMapName /Identity-H def\n"; var stream = new StringStream(str); var cmapPromise = CMapFactory.create({ encoding: stream }); cmapPromise - .then(function(cmap) { + .then(function (cmap) { expect(cmap.name).toEqual("Identity-H"); done(); }) - .catch(function(reason) { + .catch(function (reason) { done.fail(reason); }); }); - it("parses wmode", function(done) { + it("parses wmode", function (done) { var str = "/WMode 1 def\n"; var stream = new StringStream(str); var cmapPromise = CMapFactory.create({ encoding: stream }); cmapPromise - .then(function(cmap) { + .then(function (cmap) { expect(cmap.vertical).toEqual(true); done(); }) - .catch(function(reason) { + .catch(function (reason) { done.fail(reason); }); }); - it("loads built in cmap", function(done) { + it("loads built in cmap", function (done) { var cmapPromise = CMapFactory.create({ encoding: Name.get("Adobe-Japan1-1"), fetchBuiltInCMap, useCMap: null, }); cmapPromise - .then(function(cmap) { + .then(function (cmap) { expect(cmap instanceof CMap).toEqual(true); expect(cmap.useCMap).toBeNull(); expect(cmap.builtInCMap).toBeTruthy(); @@ -253,42 +253,42 @@ describe("cmap", function() { expect(cmap.isIdentityCMap).toEqual(false); done(); }) - .catch(function(reason) { + .catch(function (reason) { done.fail(reason); }); }); - it("loads built in identity cmap", function(done) { + it("loads built in identity cmap", function (done) { var cmapPromise = CMapFactory.create({ encoding: Name.get("Identity-H"), fetchBuiltInCMap, useCMap: null, }); cmapPromise - .then(function(cmap) { + .then(function (cmap) { expect(cmap instanceof IdentityCMap).toEqual(true); expect(cmap.vertical).toEqual(false); expect(cmap.length).toEqual(0x10000); - expect(function() { + expect(function () { return cmap.isIdentityCMap; }).toThrow(new Error("should not access .isIdentityCMap")); done(); }) - .catch(function(reason) { + .catch(function (reason) { done.fail(reason); }); }); - it("attempts to load a non-existent built-in CMap", function(done) { + it("attempts to load a non-existent built-in CMap", function (done) { var cmapPromise = CMapFactory.create({ encoding: Name.get("null"), fetchBuiltInCMap, useCMap: null, }); cmapPromise.then( - function() { + function () { done.fail("No CMap should be loaded"); }, - function(reason) { + function (reason) { expect(reason instanceof Error).toEqual(true); expect(reason.message).toEqual("Unknown CMap name: null"); done(); @@ -296,7 +296,7 @@ describe("cmap", function() { ); }); - it("attempts to load a built-in CMap without the necessary API parameters", function(done) { + it("attempts to load a built-in CMap without the necessary API parameters", function (done) { function tmpFetchBuiltInCMap(name) { var CMapReaderFactory = isNodeJS ? new NodeCMapReaderFactory({}) @@ -312,10 +312,10 @@ describe("cmap", function() { useCMap: null, }); cmapPromise.then( - function() { + function () { done.fail("No CMap should be loaded"); }, - function(reason) { + function (reason) { expect(reason instanceof Error).toEqual(true); expect(reason.message).toEqual( 'The CMap "baseUrl" parameter must be specified, ensure that ' + @@ -326,7 +326,7 @@ describe("cmap", function() { ); }); - it("attempts to load a built-in CMap with inconsistent API parameters", function(done) { + it("attempts to load a built-in CMap with inconsistent API parameters", function (done) { function tmpFetchBuiltInCMap(name) { let CMapReaderFactory; if (isNodeJS) { @@ -351,10 +351,10 @@ describe("cmap", function() { useCMap: null, }); cmapPromise.then( - function() { + function () { done.fail("No CMap should be loaded"); }, - function(reason) { + function (reason) { expect(reason instanceof Error).toEqual(true); const message = reason.message; expect(message.startsWith("Unable to load CMap at: ")).toEqual(true); diff --git a/test/unit/colorspace_spec.js b/test/unit/colorspace_spec.js index 4478987c7..47fd40659 100644 --- a/test/unit/colorspace_spec.js +++ b/test/unit/colorspace_spec.js @@ -19,16 +19,16 @@ import { ColorSpace } from "../../src/core/colorspace.js"; import { PDFFunctionFactory } from "../../src/core/function.js"; import { XRefMock } from "./test_utils.js"; -describe("colorspace", function() { - describe("ColorSpace", function() { - it("should be true if decode is not an array", function() { +describe("colorspace", function () { + describe("ColorSpace", function () { + it("should be true if decode is not an array", function () { expect(ColorSpace.isDefaultDecode("string", 0)).toBeTruthy(); }); - it("should be true if length of decode array is not correct", function() { + it("should be true if length of decode array is not correct", function () { expect(ColorSpace.isDefaultDecode([0], 1)).toBeTruthy(); expect(ColorSpace.isDefaultDecode([0, 1, 0], 1)).toBeTruthy(); }); - it("should be true if decode map matches the default decode map", function() { + it("should be true if decode map matches the default decode map", function () { expect(ColorSpace.isDefaultDecode([], 0)).toBeTruthy(); expect(ColorSpace.isDefaultDecode([0, 0], 1)).toBeFalsy(); @@ -46,8 +46,8 @@ describe("colorspace", function() { }); }); - describe("DeviceGrayCS", function() { - it("should handle the case when cs is a Name object", function() { + describe("DeviceGrayCS", function () { + it("should handle the case when cs is a Name object", function () { const cs = Name.get("DeviceGray"); const xref = new XRefMock([ { @@ -92,7 +92,7 @@ describe("colorspace", function() { expect(colorSpace.isPassthrough(8)).toBeFalsy(); expect(testDest).toEqual(expectedDest); }); - it("should handle the case when cs is an indirect object", function() { + it("should handle the case when cs is an indirect object", function () { const cs = Ref.get(10, 0); const xref = new XRefMock([ { @@ -132,8 +132,8 @@ describe("colorspace", function() { }); }); - describe("DeviceRgbCS", function() { - it("should handle the case when cs is a Name object", function() { + describe("DeviceRgbCS", function () { + it("should handle the case when cs is a Name object", function () { const cs = Name.get("DeviceRGB"); const xref = new XRefMock([ { @@ -184,7 +184,7 @@ describe("colorspace", function() { expect(colorSpace.isPassthrough(8)).toBeTruthy(); expect(testDest).toEqual(expectedDest); }); - it("should handle the case when cs is an indirect object", function() { + it("should handle the case when cs is an indirect object", function () { const cs = Ref.get(10, 0); const xref = new XRefMock([ { @@ -230,8 +230,8 @@ describe("colorspace", function() { }); }); - describe("DeviceCmykCS", function() { - it("should handle the case when cs is a Name object", function() { + describe("DeviceCmykCS", function () { + it("should handle the case when cs is a Name object", function () { const cs = Name.get("DeviceCMYK"); const xref = new XRefMock([ { @@ -282,7 +282,7 @@ describe("colorspace", function() { expect(colorSpace.isPassthrough(8)).toBeFalsy(); expect(testDest).toEqual(expectedDest); }); - it("should handle the case when cs is an indirect object", function() { + it("should handle the case when cs is an indirect object", function () { const cs = Ref.get(10, 0); const xref = new XRefMock([ { @@ -328,8 +328,8 @@ describe("colorspace", function() { }); }); - describe("CalGrayCS", function() { - it("should handle the case when cs is an array", function() { + describe("CalGrayCS", function () { + it("should handle the case when cs is an array", function () { const params = new Dict(); params.set("WhitePoint", [1, 1, 1]); params.set("BlackPoint", [0, 0, 0]); @@ -381,8 +381,8 @@ describe("colorspace", function() { }); }); - describe("CalRGBCS", function() { - it("should handle the case when cs is an array", function() { + describe("CalRGBCS", function () { + it("should handle the case when cs is an array", function () { const params = new Dict(); params.set("WhitePoint", [1, 1, 1]); params.set("BlackPoint", [0, 0, 0]); @@ -434,8 +434,8 @@ describe("colorspace", function() { }); }); - describe("LabCS", function() { - it("should handle the case when cs is an array", function() { + describe("LabCS", function () { + it("should handle the case when cs is an array", function () { const params = new Dict(); params.set("WhitePoint", [1, 1, 1]); params.set("BlackPoint", [0, 0, 0]); @@ -487,8 +487,8 @@ describe("colorspace", function() { }); }); - describe("IndexedCS", function() { - it("should handle the case when cs is an array", function() { + describe("IndexedCS", function () { + it("should handle the case when cs is an array", function () { // prettier-ignore const lookup = new Uint8Array([ 23, 155, 35, @@ -534,8 +534,8 @@ describe("colorspace", function() { }); }); - describe("AlternateCS", function() { - it("should handle the case when cs is an array", function() { + describe("AlternateCS", function () { + it("should handle the case when cs is an array", function () { const fnDict = new Dict(); fnDict.set("FunctionType", 4); fnDict.set("Domain", [0.0, 1.0]); diff --git a/test/unit/core_utils_spec.js b/test/unit/core_utils_spec.js index 3d13f12e8..315ab28aa 100644 --- a/test/unit/core_utils_spec.js +++ b/test/unit/core_utils_spec.js @@ -22,9 +22,9 @@ import { } from "../../src/core/core_utils.js"; import { XRefMock } from "./test_utils.js"; -describe("core_utils", function() { - describe("getInheritableProperty", function() { - it("handles non-dictionary arguments", function() { +describe("core_utils", function () { + describe("getInheritableProperty", function () { + it("handles non-dictionary arguments", function () { expect(getInheritableProperty({ dict: null, key: "foo" })).toEqual( undefined ); @@ -33,7 +33,7 @@ describe("core_utils", function() { ); }); - it("handles dictionaries that do not contain the property", function() { + it("handles dictionaries that do not contain the property", function () { // Empty dictionary. const emptyDict = new Dict(); expect(getInheritableProperty({ dict: emptyDict, key: "foo" })).toEqual( @@ -48,7 +48,7 @@ describe("core_utils", function() { ); }); - it("fetches the property if it is not inherited", function() { + it("fetches the property if it is not inherited", function () { const ref = Ref.get(10, 0); const xref = new XRefMock([{ ref, data: "quux" }]); const dict = new Dict(xref); @@ -64,7 +64,7 @@ describe("core_utils", function() { ).toEqual(["qux", "quux"]); }); - it("fetches the property if it is inherited and present on one level", function() { + it("fetches the property if it is inherited and present on one level", function () { const ref = Ref.get(10, 0); const xref = new XRefMock([{ ref, data: "quux" }]); const firstDict = new Dict(xref); @@ -84,7 +84,7 @@ describe("core_utils", function() { ).toEqual(["qux", "quux"]); }); - it("fetches the property if it is inherited and present on multiple levels", function() { + it("fetches the property if it is inherited and present on multiple levels", function () { const ref = Ref.get(10, 0); const xref = new XRefMock([{ ref, data: "quux" }]); const firstDict = new Dict(xref); @@ -122,7 +122,7 @@ describe("core_utils", function() { ]); }); - it("stops searching when the loop limit is reached", function() { + it("stops searching when the loop limit is reached", function () { const dict = new Dict(); let currentDict = dict; let parentDict = null; @@ -147,16 +147,16 @@ describe("core_utils", function() { }); }); - describe("toRomanNumerals", function() { - it("handles invalid arguments", function() { + describe("toRomanNumerals", function () { + it("handles invalid arguments", function () { for (const input of ["foo", -1, 0]) { - expect(function() { + expect(function () { toRomanNumerals(input); }).toThrow(new Error("The number should be a positive integer.")); } }); - it("converts numbers to uppercase Roman numerals", function() { + it("converts numbers to uppercase Roman numerals", function () { expect(toRomanNumerals(1)).toEqual("I"); expect(toRomanNumerals(6)).toEqual("VI"); expect(toRomanNumerals(7)).toEqual("VII"); @@ -169,7 +169,7 @@ describe("core_utils", function() { expect(toRomanNumerals(2019)).toEqual("MMXIX"); }); - it("converts numbers to lowercase Roman numerals", function() { + it("converts numbers to lowercase Roman numerals", function () { expect(toRomanNumerals(1, /* lowercase = */ true)).toEqual("i"); expect(toRomanNumerals(6, /* lowercase = */ true)).toEqual("vi"); expect(toRomanNumerals(7, /* lowercase = */ true)).toEqual("vii"); @@ -183,13 +183,13 @@ describe("core_utils", function() { }); }); - describe("log2", function() { - it("handles values smaller than/equal to zero", function() { + describe("log2", function () { + it("handles values smaller than/equal to zero", function () { expect(log2(0)).toEqual(0); expect(log2(-1)).toEqual(0); }); - it("handles values larger than zero", function() { + it("handles values larger than zero", function () { expect(log2(1)).toEqual(0); expect(log2(2)).toEqual(1); expect(log2(3)).toEqual(2); @@ -197,15 +197,15 @@ describe("core_utils", function() { }); }); - describe("isWhiteSpace", function() { - it("handles space characters", function() { + describe("isWhiteSpace", function () { + it("handles space characters", function () { expect(isWhiteSpace(0x20)).toEqual(true); expect(isWhiteSpace(0x09)).toEqual(true); expect(isWhiteSpace(0x0d)).toEqual(true); expect(isWhiteSpace(0x0a)).toEqual(true); }); - it("handles non-space characters", function() { + it("handles non-space characters", function () { expect(isWhiteSpace(0x0b)).toEqual(false); expect(isWhiteSpace(null)).toEqual(false); expect(isWhiteSpace(undefined)).toEqual(false); diff --git a/test/unit/crypto_spec.js b/test/unit/crypto_spec.js index 03cd1c63e..cf4533ab9 100644 --- a/test/unit/crypto_spec.js +++ b/test/unit/crypto_spec.js @@ -32,7 +32,7 @@ import { stringToBytes, } from "../../src/shared/util.js"; -describe("crypto", function() { +describe("crypto", function () { function hex2binary(s) { var digits = "0123456789ABCDEF"; s = s.toUpperCase(); @@ -50,43 +50,43 @@ describe("crypto", function() { } // RFC 1321, A.5 Test suite - describe("calculateMD5", function() { - it("should pass RFC 1321 test #1", function() { + describe("calculateMD5", function () { + it("should pass RFC 1321 test #1", function () { var input, result, expected; input = stringToBytes(""); result = calculateMD5(input, 0, input.length); expected = hex2binary("d41d8cd98f00b204e9800998ecf8427e"); expect(result).toEqual(expected); }); - it("should pass RFC 1321 test #2", function() { + it("should pass RFC 1321 test #2", function () { var input, result, expected; input = stringToBytes("a"); result = calculateMD5(input, 0, input.length); expected = hex2binary("0cc175b9c0f1b6a831c399e269772661"); expect(result).toEqual(expected); }); - it("should pass RFC 1321 test #3", function() { + it("should pass RFC 1321 test #3", function () { var input, result, expected; input = stringToBytes("abc"); result = calculateMD5(input, 0, input.length); expected = hex2binary("900150983cd24fb0d6963f7d28e17f72"); expect(result).toEqual(expected); }); - it("should pass RFC 1321 test #4", function() { + it("should pass RFC 1321 test #4", function () { var input, result, expected; input = stringToBytes("message digest"); result = calculateMD5(input, 0, input.length); expected = hex2binary("f96b697d7cb7938d525a2f31aaf161d0"); expect(result).toEqual(expected); }); - it("should pass RFC 1321 test #5", function() { + it("should pass RFC 1321 test #5", function () { var input, result, expected; input = stringToBytes("abcdefghijklmnopqrstuvwxyz"); result = calculateMD5(input, 0, input.length); expected = hex2binary("c3fcd3d76192e4007dfb496cca67e13b"); expect(result).toEqual(expected); }); - it("should pass RFC 1321 test #6", function() { + it("should pass RFC 1321 test #6", function () { var input, result, expected; input = stringToBytes( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" @@ -95,7 +95,7 @@ describe("crypto", function() { expected = hex2binary("d174ab98d277d9f5a5611c2c9f419d9f"); expect(result).toEqual(expected); }); - it("should pass RFC 1321 test #7", function() { + it("should pass RFC 1321 test #7", function () { var input, result, expected; input = stringToBytes( "123456789012345678901234567890123456789012345678" + @@ -108,8 +108,8 @@ describe("crypto", function() { }); // http://www.freemedialibrary.com/index.php/RC4_test_vectors are used - describe("ARCFourCipher", function() { - it("should pass test #1", function() { + describe("ARCFourCipher", function () { + it("should pass test #1", function () { var key, input, result, expected, cipher; key = hex2binary("0123456789abcdef"); input = hex2binary("0123456789abcdef"); @@ -118,7 +118,7 @@ describe("crypto", function() { expected = hex2binary("75b7878099e0c596"); expect(result).toEqual(expected); }); - it("should pass test #2", function() { + it("should pass test #2", function () { var key, input, result, expected, cipher; key = hex2binary("0123456789abcdef"); input = hex2binary("0000000000000000"); @@ -127,7 +127,7 @@ describe("crypto", function() { expected = hex2binary("7494c2e7104b0879"); expect(result).toEqual(expected); }); - it("should pass test #3", function() { + it("should pass test #3", function () { var key, input, result, expected, cipher; key = hex2binary("0000000000000000"); input = hex2binary("0000000000000000"); @@ -136,7 +136,7 @@ describe("crypto", function() { expected = hex2binary("de188941a3375d3a"); expect(result).toEqual(expected); }); - it("should pass test #4", function() { + it("should pass test #4", function () { var key, input, result, expected, cipher; key = hex2binary("ef012345"); input = hex2binary("00000000000000000000"); @@ -145,7 +145,7 @@ describe("crypto", function() { expected = hex2binary("d6a141a7ec3c38dfbd61"); expect(result).toEqual(expected); }); - it("should pass test #5", function() { + it("should pass test #5", function () { var key, input, result, expected, cipher; key = hex2binary("0123456789abcdef"); input = hex2binary( @@ -188,7 +188,7 @@ describe("crypto", function() { ); expect(result).toEqual(expected); }); - it("should pass test #6", function() { + it("should pass test #6", function () { var key, input, result, expected, cipher; key = hex2binary("fb029e3031323334"); input = hex2binary( @@ -205,7 +205,7 @@ describe("crypto", function() { ); expect(result).toEqual(expected); }); - it("should pass test #7", function() { + it("should pass test #7", function () { var key, input, result, expected, cipher; key = hex2binary("0123456789abcdef"); input = hex2binary( @@ -220,8 +220,8 @@ describe("crypto", function() { }); }); - describe("calculateSHA256", function() { - it("should properly hash abc", function() { + describe("calculateSHA256", function () { + it("should properly hash abc", function () { var input, result, expected; input = stringToBytes("abc"); result = calculateSHA256(input, 0, input.length); @@ -230,7 +230,7 @@ describe("crypto", function() { ); expect(result).toEqual(expected); }); - it("should properly hash a multiblock input", function() { + it("should properly hash a multiblock input", function () { var input, result, expected; input = stringToBytes( "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" @@ -243,8 +243,8 @@ describe("crypto", function() { }); }); - describe("calculateSHA384", function() { - it("should properly hash abc", function() { + describe("calculateSHA384", function () { + it("should properly hash abc", function () { var input, result, expected; input = stringToBytes("abc"); result = calculateSHA384(input, 0, input.length); @@ -254,7 +254,7 @@ describe("crypto", function() { ); expect(result).toEqual(expected); }); - it("should properly hash a multiblock input", function() { + it("should properly hash a multiblock input", function () { var input, result, expected; input = stringToBytes( "abcdefghbcdefghicdefghijdefghijkefghijklfghijklm" + @@ -270,8 +270,8 @@ describe("crypto", function() { }); }); - describe("calculateSHA512", function() { - it("should properly hash abc", function() { + describe("calculateSHA512", function () { + it("should properly hash abc", function () { var input, result, expected; input = stringToBytes("abc"); result = calculateSHA512(input, 0, input.length); @@ -282,7 +282,7 @@ describe("crypto", function() { ); expect(result).toEqual(expected); }); - it("should properly hash a multiblock input", function() { + it("should properly hash a multiblock input", function () { var input, result, expected; input = stringToBytes( "abcdefghbcdefghicdefghijdefghijkefghijklfghijklm" + @@ -299,9 +299,9 @@ describe("crypto", function() { }); }); - describe("AES128", function() { - describe("Encryption", function() { - it("should be able to encrypt a block", function() { + describe("AES128", function () { + describe("Encryption", function () { + it("should be able to encrypt a block", function () { var input, key, result, expected, iv, cipher; input = hex2binary("00112233445566778899aabbccddeeff"); key = hex2binary("000102030405060708090a0b0c0d0e0f"); @@ -313,8 +313,8 @@ describe("crypto", function() { }); }); - describe("Decryption", function() { - it("should be able to decrypt a block with IV in stream", function() { + describe("Decryption", function () { + it("should be able to decrypt a block with IV in stream", function () { var input, key, result, expected, cipher; input = hex2binary( "0000000000000000000000000000000069c4e0d86a7b0430d" + @@ -329,9 +329,9 @@ describe("crypto", function() { }); }); - describe("AES256", function() { - describe("Encryption", function() { - it("should be able to encrypt a block", function() { + describe("AES256", function () { + describe("Encryption", function () { + it("should be able to encrypt a block", function () { var input, key, result, expected, iv, cipher; input = hex2binary("00112233445566778899aabbccddeeff"); key = hex2binary( @@ -346,8 +346,8 @@ describe("crypto", function() { }); }); - describe("Decryption", function() { - it("should be able to decrypt a block with specified iv", function() { + describe("Decryption", function () { + it("should be able to decrypt a block with specified iv", function () { var input, key, result, expected, cipher, iv; input = hex2binary("8ea2b7ca516745bfeafc49904b496089"); key = hex2binary( @@ -360,7 +360,7 @@ describe("crypto", function() { expected = hex2binary("00112233445566778899aabbccddeeff"); expect(result).toEqual(expected); }); - it("should be able to decrypt a block with IV in stream", function() { + it("should be able to decrypt a block with IV in stream", function () { var input, key, result, expected, cipher; input = hex2binary( "000000000000000000000000000000008ea2b7ca516745bf" + @@ -378,8 +378,8 @@ describe("crypto", function() { }); }); - describe("PDF17Algorithm", function() { - it("should correctly check a user key", function() { + describe("PDF17Algorithm", function () { + it("should correctly check a user key", function () { var password, userValidation, userPassword, alg, result; alg = new PDF17(); password = new Uint8Array([117, 115, 101, 114]); @@ -393,7 +393,7 @@ describe("crypto", function() { expect(result).toEqual(true); }); - it("should correctly check an owner key", function() { + it("should correctly check an owner key", function () { var password, ownerValidation, ownerPassword, alg, result, uBytes; alg = new PDF17(); password = new Uint8Array([111, 119, 110, 101, 114]); @@ -418,7 +418,7 @@ describe("crypto", function() { expect(result).toEqual(true); }); - it("should generate a file encryption key from the user key", function() { + it("should generate a file encryption key from the user key", function () { var password, userKeySalt, expected, alg, result, userEncryption; alg = new PDF17(); password = new Uint8Array([117, 115, 101, 114]); @@ -437,7 +437,7 @@ describe("crypto", function() { expect(result).toEqual(expected); }); - it("should generate a file encryption key from the owner key", function() { + it("should generate a file encryption key from the owner key", function () { var password, ownerKeySalt, expected, alg, result, ownerEncryption; var uBytes; alg = new PDF17(); @@ -464,8 +464,8 @@ describe("crypto", function() { }); }); - describe("PDF20Algorithm", function() { - it("should correctly check a user key", function() { + describe("PDF20Algorithm", function () { + it("should correctly check a user key", function () { var password, userValidation, userPassword, alg, result; alg = new PDF20(); password = new Uint8Array([117, 115, 101, 114]); @@ -479,7 +479,7 @@ describe("crypto", function() { expect(result).toEqual(true); }); - it("should correctly check an owner key", function() { + it("should correctly check an owner key", function () { var password, ownerValidation, ownerPassword, alg, result, uBytes; alg = new PDF20(); password = new Uint8Array([111, 119, 110, 101, 114]); @@ -504,7 +504,7 @@ describe("crypto", function() { expect(result).toEqual(true); }); - it("should generate a file encryption key from the user key", function() { + it("should generate a file encryption key from the user key", function () { var password, userKeySalt, expected, alg, result, userEncryption; alg = new PDF20(); password = new Uint8Array([117, 115, 101, 114]); @@ -523,7 +523,7 @@ describe("crypto", function() { expect(result).toEqual(expected); }); - it("should generate a file encryption key from the owner key", function() { + it("should generate a file encryption key from the owner key", function () { var password, ownerKeySalt, expected, alg, result, ownerEncryption; var uBytes; alg = new PDF20(); @@ -551,7 +551,7 @@ describe("crypto", function() { }); }); -describe("CipherTransformFactory", function() { +describe("CipherTransformFactory", function () { function buildDict(map) { var dict = new Dict(); for (var key in map) { @@ -602,7 +602,7 @@ describe("CipherTransformFactory", function() { var fileId1, fileId2, dict1, dict2; var aes256Dict, aes256IsoDict, aes256BlankDict, aes256IsoBlankDict; - beforeAll(function(done) { + beforeAll(function (done) { fileId1 = unescape("%F6%C6%AF%17%F3rR%8DRM%9A%80%D1%EF%DF%18"); fileId2 = unescape("%3CL_%3AD%96%AF@%9A%9D%B3%3Cx%1Cv%AC"); @@ -741,61 +741,61 @@ describe("CipherTransformFactory", function() { done(); }); - afterAll(function() { + afterAll(function () { fileId1 = fileId2 = dict1 = dict2 = null; aes256Dict = aes256IsoDict = aes256BlankDict = aes256IsoBlankDict = null; }); - describe("#ctor", function() { - describe("AES256 Revision 5", function() { - it("should accept user password", function(done) { + describe("#ctor", function () { + describe("AES256 Revision 5", function () { + it("should accept user password", function (done) { ensurePasswordCorrect(done, aes256Dict, fileId1, "user"); }); - it("should accept owner password", function(done) { + it("should accept owner password", function (done) { ensurePasswordCorrect(done, aes256Dict, fileId1, "owner"); }); - it("should not accept blank password", function(done) { + it("should not accept blank password", function (done) { ensurePasswordNeeded(done, aes256Dict, fileId1); }); - it("should not accept wrong password", function(done) { + it("should not accept wrong password", function (done) { ensurePasswordIncorrect(done, aes256Dict, fileId1, "wrong"); }); - it("should accept blank password", function(done) { + it("should accept blank password", function (done) { ensurePasswordCorrect(done, aes256BlankDict, fileId1); }); }); - describe("AES256 Revision 6", function() { - it("should accept user password", function(done) { + describe("AES256 Revision 6", function () { + it("should accept user password", function (done) { ensurePasswordCorrect(done, aes256IsoDict, fileId1, "user"); }); - it("should accept owner password", function(done) { + it("should accept owner password", function (done) { ensurePasswordCorrect(done, aes256IsoDict, fileId1, "owner"); }); - it("should not accept blank password", function(done) { + it("should not accept blank password", function (done) { ensurePasswordNeeded(done, aes256IsoDict, fileId1); }); - it("should not accept wrong password", function(done) { + it("should not accept wrong password", function (done) { ensurePasswordIncorrect(done, aes256IsoDict, fileId1, "wrong"); }); - it("should accept blank password", function(done) { + it("should accept blank password", function (done) { ensurePasswordCorrect(done, aes256IsoBlankDict, fileId1); }); }); - it("should accept user password", function(done) { + it("should accept user password", function (done) { ensurePasswordCorrect(done, dict1, fileId1, "123456"); }); - it("should accept owner password", function(done) { + it("should accept owner password", function (done) { ensurePasswordCorrect(done, dict1, fileId1, "654321"); }); - it("should not accept blank password", function(done) { + it("should not accept blank password", function (done) { ensurePasswordNeeded(done, dict1, fileId1); }); - it("should not accept wrong password", function(done) { + it("should not accept wrong password", function (done) { ensurePasswordIncorrect(done, dict1, fileId1, "wrong"); }); - it("should accept blank password", function(done) { + it("should accept blank password", function (done) { ensurePasswordCorrect(done, dict2, fileId2); }); }); diff --git a/test/unit/custom_spec.js b/test/unit/custom_spec.js index b422c0277..75cca0154 100644 --- a/test/unit/custom_spec.js +++ b/test/unit/custom_spec.js @@ -28,7 +28,7 @@ function getTopLeftPixel(canvasContext) { }; } -describe("custom canvas rendering", function() { +describe("custom canvas rendering", function () { const transparentGetDocumentParams = buildGetDocumentParams( "transparent.pdf" ); @@ -37,7 +37,7 @@ describe("custom canvas rendering", function() { let loadingTask; let page; - beforeAll(function(done) { + beforeAll(function (done) { if (isNodeJS) { CanvasFactory = new NodeCanvasFactory(); } else { @@ -45,23 +45,23 @@ describe("custom canvas rendering", function() { } loadingTask = getDocument(transparentGetDocumentParams); loadingTask.promise - .then(function(doc) { + .then(function (doc) { return doc.getPage(1); }) - .then(function(data) { + .then(function (data) { page = data; done(); }) .catch(done.fail); }); - afterAll(function(done) { + afterAll(function (done) { CanvasFactory = null; page = null; loadingTask.destroy().then(done); }); - it("renders to canvas with a default white background", function(done) { + it("renders to canvas with a default white background", function (done) { var viewport = page.getViewport({ scale: 1 }); var canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height); @@ -70,7 +70,7 @@ describe("custom canvas rendering", function() { viewport, }); renderTask.promise - .then(function() { + .then(function () { expect(getTopLeftPixel(canvasAndCtx.context)).toEqual({ r: 255, g: 255, @@ -83,7 +83,7 @@ describe("custom canvas rendering", function() { .catch(done.fail); }); - it("renders to canvas with a custom background", function(done) { + it("renders to canvas with a custom background", function (done) { var viewport = page.getViewport({ scale: 1 }); var canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height); @@ -93,7 +93,7 @@ describe("custom canvas rendering", function() { background: "rgba(255,0,0,1.0)", }); renderTask.promise - .then(function() { + .then(function () { expect(getTopLeftPixel(canvasAndCtx.context)).toEqual({ r: 255, g: 0, diff --git a/test/unit/display_svg_spec.js b/test/unit/display_svg_spec.js index b8475e72e..0dce86043 100644 --- a/test/unit/display_svg_spec.js +++ b/test/unit/display_svg_spec.js @@ -58,37 +58,37 @@ function withZlib(isZlibRequired, callback) { return promise; } -describe("SVGGraphics", function() { +describe("SVGGraphics", function () { var loadingTask; var page; - beforeAll(function(done) { + beforeAll(function (done) { loadingTask = getDocument( buildGetDocumentParams("xobject-image.pdf", { nativeImageDecoderSupport: NativeImageDecoding.DISPLAY, }) ); - loadingTask.promise.then(function(doc) { - doc.getPage(1).then(function(firstPage) { + loadingTask.promise.then(function (doc) { + doc.getPage(1).then(function (firstPage) { page = firstPage; done(); }); }); }); - afterAll(function(done) { + afterAll(function (done) { loadingTask.destroy().then(done); }); - describe("paintImageXObject", function() { + describe("paintImageXObject", function () { function getSVGImage() { var svgGfx; return page .getOperatorList() - .then(function(opList) { + .then(function (opList) { var forceDataSchema = true; svgGfx = new SVGGraphics(page.commonObjs, page.objs, forceDataSchema); return svgGfx.loadDependencies(opList); }) - .then(function() { + .then(function () { var svgImg; // A mock to steal the svg:image element from paintInlineImageXObject. var elementContainer = { @@ -114,7 +114,7 @@ describe("SVGGraphics", function() { }); } - it('should fail require("zlib") unless in Node.js', function() { + it('should fail require("zlib") unless in Node.js', function () { function testFunc() { __non_webpack_require__("zlib"); } @@ -129,12 +129,12 @@ describe("SVGGraphics", function() { } }); - it("should produce a reasonably small svg:image", function(done) { + it("should produce a reasonably small svg:image", function (done) { if (!isNodeJS) { pending("zlib.deflateSync is not supported in non-Node environments."); } withZlib(true, getSVGImage) - .then(function(svgImg) { + .then(function (svgImg) { expect(svgImg.nodeName).toBe("svg:image"); expect(svgImg.getAttributeNS(null, "width")).toBe("200px"); expect(svgImg.getAttributeNS(null, "height")).toBe("100px"); @@ -150,9 +150,9 @@ describe("SVGGraphics", function() { .then(done, done.fail); }); - it("should be able to produce a svg:image without zlib", function(done) { + it("should be able to produce a svg:image without zlib", function (done) { withZlib(false, getSVGImage) - .then(function(svgImg) { + .then(function (svgImg) { expect(svgImg.nodeName).toBe("svg:image"); expect(svgImg.getAttributeNS(null, "width")).toBe("200px"); expect(svgImg.getAttributeNS(null, "height")).toBe("100px"); diff --git a/test/unit/display_utils_spec.js b/test/unit/display_utils_spec.js index c44c4e330..ee1e42f67 100644 --- a/test/unit/display_utils_spec.js +++ b/test/unit/display_utils_spec.js @@ -23,32 +23,32 @@ import { } from "../../src/display/display_utils.js"; import { isNodeJS } from "../../src/shared/is_node.js"; -describe("display_utils", function() { - describe("DOMCanvasFactory", function() { +describe("display_utils", function () { + describe("DOMCanvasFactory", function () { let canvasFactory; - beforeAll(function(done) { + beforeAll(function (done) { canvasFactory = new DOMCanvasFactory(); done(); }); - afterAll(function() { + afterAll(function () { canvasFactory = null; }); - it("`create` should throw an error if the dimensions are invalid", function() { + it("`create` should throw an error if the dimensions are invalid", function () { // Invalid width. - expect(function() { + expect(function () { return canvasFactory.create(-1, 1); }).toThrow(new Error("Invalid canvas size")); // Invalid height. - expect(function() { + expect(function () { return canvasFactory.create(1, -1); }).toThrow(new Error("Invalid canvas size")); }); - it("`create` should return a canvas if the dimensions are valid", function() { + it("`create` should return a canvas if the dimensions are valid", function () { if (isNodeJS) { pending("Document is not supported in Node.js."); } @@ -60,29 +60,29 @@ describe("display_utils", function() { expect(canvas.height).toBe(40); }); - it("`reset` should throw an error if no canvas is provided", function() { + it("`reset` should throw an error if no canvas is provided", function () { const canvasAndContext = { canvas: null, context: null }; - expect(function() { + expect(function () { return canvasFactory.reset(canvasAndContext, 20, 40); }).toThrow(new Error("Canvas is not specified")); }); - it("`reset` should throw an error if the dimensions are invalid", function() { + it("`reset` should throw an error if the dimensions are invalid", function () { const canvasAndContext = { canvas: "foo", context: "bar" }; // Invalid width. - expect(function() { + expect(function () { return canvasFactory.reset(canvasAndContext, -1, 1); }).toThrow(new Error("Invalid canvas size")); // Invalid height. - expect(function() { + expect(function () { return canvasFactory.reset(canvasAndContext, 1, -1); }).toThrow(new Error("Invalid canvas size")); }); - it("`reset` should alter the canvas/context if the dimensions are valid", function() { + it("`reset` should alter the canvas/context if the dimensions are valid", function () { if (isNodeJS) { pending("Document is not supported in Node.js."); } @@ -97,13 +97,13 @@ describe("display_utils", function() { expect(canvas.height).toBe(80); }); - it("`destroy` should throw an error if no canvas is provided", function() { - expect(function() { + it("`destroy` should throw an error if no canvas is provided", function () { + expect(function () { return canvasFactory.destroy({}); }).toThrow(new Error("Canvas is not specified")); }); - it("`destroy` should clear the canvas/context", function() { + it("`destroy` should clear the canvas/context", function () { if (isNodeJS) { pending("Document is not supported in Node.js."); } @@ -117,31 +117,31 @@ describe("display_utils", function() { }); }); - describe("DOMSVGFactory", function() { + describe("DOMSVGFactory", function () { let svgFactory; - beforeAll(function(done) { + beforeAll(function (done) { svgFactory = new DOMSVGFactory(); done(); }); - afterAll(function() { + afterAll(function () { svgFactory = null; }); - it("`create` should throw an error if the dimensions are invalid", function() { + it("`create` should throw an error if the dimensions are invalid", function () { // Invalid width. - expect(function() { + expect(function () { return svgFactory.create(-1, 0); }).toThrow(new Error("Invalid SVG dimensions")); // Invalid height. - expect(function() { + expect(function () { return svgFactory.create(0, -1); }).toThrow(new Error("Invalid SVG dimensions")); }); - it("`create` should return an SVG element if the dimensions are valid", function() { + it("`create` should return an SVG element if the dimensions are valid", function () { if (isNodeJS) { pending("Document is not supported in Node.js."); } @@ -155,13 +155,13 @@ describe("display_utils", function() { expect(svg.getAttribute("viewBox")).toBe("0 0 20 40"); }); - it("`createElement` should throw an error if the type is not a string", function() { - expect(function() { + it("`createElement` should throw an error if the type is not a string", function () { + expect(function () { return svgFactory.createElement(true); }).toThrow(new Error("Invalid SVG element type")); }); - it("`createElement` should return an SVG element if the type is valid", function() { + it("`createElement` should return an SVG element if the type is valid", function () { if (isNodeJS) { pending("Document is not supported in Node.js."); } @@ -171,55 +171,55 @@ describe("display_utils", function() { }); }); - describe("getFilenameFromUrl", function() { - it("should get the filename from an absolute URL", function() { + describe("getFilenameFromUrl", function () { + it("should get the filename from an absolute URL", function () { const url = "https://server.org/filename.pdf"; expect(getFilenameFromUrl(url)).toEqual("filename.pdf"); }); - it("should get the filename from a relative URL", function() { + it("should get the filename from a relative URL", function () { const url = "../../filename.pdf"; expect(getFilenameFromUrl(url)).toEqual("filename.pdf"); }); - it("should get the filename from a URL with an anchor", function() { + it("should get the filename from a URL with an anchor", function () { const url = "https://server.org/filename.pdf#foo"; expect(getFilenameFromUrl(url)).toEqual("filename.pdf"); }); - it("should get the filename from a URL with query parameters", function() { + it("should get the filename from a URL with query parameters", function () { const url = "https://server.org/filename.pdf?foo=bar"; expect(getFilenameFromUrl(url)).toEqual("filename.pdf"); }); }); - describe("isValidFetchUrl", function() { - it("handles invalid Fetch URLs", function() { + describe("isValidFetchUrl", function () { + it("handles invalid Fetch URLs", function () { expect(isValidFetchUrl(null)).toEqual(false); expect(isValidFetchUrl(100)).toEqual(false); expect(isValidFetchUrl("foo")).toEqual(false); expect(isValidFetchUrl("/foo", 100)).toEqual(false); }); - it("handles relative Fetch URLs", function() { + it("handles relative Fetch URLs", function () { expect(isValidFetchUrl("/foo", "file://www.example.com")).toEqual(false); expect(isValidFetchUrl("/foo", "http://www.example.com")).toEqual(true); }); - it("handles unsupported Fetch protocols", function() { + it("handles unsupported Fetch protocols", function () { expect(isValidFetchUrl("file://www.example.com")).toEqual(false); expect(isValidFetchUrl("ftp://www.example.com")).toEqual(false); }); - it("handles supported Fetch protocols", function() { + it("handles supported Fetch protocols", function () { expect(isValidFetchUrl("http://www.example.com")).toEqual(true); expect(isValidFetchUrl("https://www.example.com")).toEqual(true); }); }); - describe("PDFDateString", function() { - describe("toDateObject", function() { - it("converts PDF date strings to JavaScript `Date` objects", function() { + describe("PDFDateString", function () { + describe("toDateObject", function () { + it("converts PDF date strings to JavaScript `Date` objects", function () { const expectations = { undefined: null, null: null, diff --git a/test/unit/document_spec.js b/test/unit/document_spec.js index bf18a8482..f021490f6 100644 --- a/test/unit/document_spec.js +++ b/test/unit/document_spec.js @@ -15,9 +15,9 @@ import { createIdFactory } from "./test_utils.js"; -describe("document", function() { - describe("Page", function() { - it("should create correct objId using the idFactory", function() { +describe("document", function () { + describe("Page", function () { + it("should create correct objId using the idFactory", function () { const idFactory1 = createIdFactory(/* pageIndex = */ 0); const idFactory2 = createIdFactory(/* pageIndex = */ 1); diff --git a/test/unit/encodings_spec.js b/test/unit/encodings_spec.js index 85f10e45d..e3b04a0bd 100644 --- a/test/unit/encodings_spec.js +++ b/test/unit/encodings_spec.js @@ -15,9 +15,9 @@ import { getEncoding } from "../../src/core/encodings.js"; -describe("encodings", function() { - describe("getEncoding", function() { - it("fetches a valid array for known encoding names", function() { +describe("encodings", function () { + describe("getEncoding", function () { + it("fetches a valid array for known encoding names", function () { const knownEncodingNames = [ "ExpertEncoding", "MacExpertEncoding", @@ -39,7 +39,7 @@ describe("encodings", function() { } }); - it("fetches `null` for unknown encoding names", function() { + it("fetches `null` for unknown encoding names", function () { expect(getEncoding("FooBarEncoding")).toEqual(null); }); }); diff --git a/test/unit/evaluator_spec.js b/test/unit/evaluator_spec.js index c1a0ee629..82087eb57 100644 --- a/test/unit/evaluator_spec.js +++ b/test/unit/evaluator_spec.js @@ -21,7 +21,7 @@ import { OperatorList } from "../../src/core/operator_list.js"; import { PartialEvaluator } from "../../src/core/evaluator.js"; import { WorkerTask } from "../../src/core/worker.js"; -describe("evaluator", function() { +describe("evaluator", function () { function HandlerMock() { this.inputs = []; } @@ -48,10 +48,10 @@ describe("evaluator", function() { operatorList: result, }) .then( - function() { + function () { callback(result); }, - function(reason) { + function (reason) { callback(reason); } ); @@ -59,7 +59,7 @@ describe("evaluator", function() { var partialEvaluator; - beforeAll(function(done) { + beforeAll(function (done) { partialEvaluator = new PartialEvaluator({ xref: new XRefMock(), handler: new HandlerMock(), @@ -69,18 +69,18 @@ describe("evaluator", function() { done(); }); - afterAll(function() { + afterAll(function () { partialEvaluator = null; }); - describe("splitCombinedOperations", function() { - it("should reject unknown operations", function(done) { + describe("splitCombinedOperations", function () { + it("should reject unknown operations", function (done) { var stream = new StringStream("fTT"); runOperatorListCheck( partialEvaluator, stream, new ResourcesMock(), - function(result) { + function (result) { expect(!!result.fnArray && !!result.argsArray).toEqual(true); expect(result.fnArray.length).toEqual(1); expect(result.fnArray[0]).toEqual(OPS.fill); @@ -90,13 +90,13 @@ describe("evaluator", function() { ); }); - it("should handle one operation", function(done) { + it("should handle one operation", function (done) { var stream = new StringStream("Q"); runOperatorListCheck( partialEvaluator, stream, new ResourcesMock(), - function(result) { + function (result) { expect(!!result.fnArray && !!result.argsArray).toEqual(true); expect(result.fnArray.length).toEqual(1); expect(result.fnArray[0]).toEqual(OPS.restore); @@ -105,11 +105,11 @@ describe("evaluator", function() { ); }); - it("should handle two glued operations", function(done) { + it("should handle two glued operations", function (done) { var resources = new ResourcesMock(); resources.Res1 = {}; var stream = new StringStream("/Res1 DoQ"); - runOperatorListCheck(partialEvaluator, stream, resources, function( + runOperatorListCheck(partialEvaluator, stream, resources, function ( result ) { expect(!!result.fnArray && !!result.argsArray).toEqual(true); @@ -120,13 +120,13 @@ describe("evaluator", function() { }); }); - it("should handle three glued operations", function(done) { + it("should handle three glued operations", function (done) { var stream = new StringStream("fff"); runOperatorListCheck( partialEvaluator, stream, new ResourcesMock(), - function(result) { + function (result) { expect(!!result.fnArray && !!result.argsArray).toEqual(true); expect(result.fnArray.length).toEqual(3); expect(result.fnArray[0]).toEqual(OPS.fill); @@ -137,11 +137,11 @@ describe("evaluator", function() { ); }); - it("should handle three glued operations #2", function(done) { + it("should handle three glued operations #2", function (done) { var resources = new ResourcesMock(); resources.Res1 = {}; var stream = new StringStream("B*Bf*"); - runOperatorListCheck(partialEvaluator, stream, resources, function( + runOperatorListCheck(partialEvaluator, stream, resources, function ( result ) { expect(!!result.fnArray && !!result.argsArray).toEqual(true); @@ -153,13 +153,13 @@ describe("evaluator", function() { }); }); - it("should handle glued operations and operands", function(done) { + it("should handle glued operations and operands", function (done) { var stream = new StringStream("f5 Ts"); runOperatorListCheck( partialEvaluator, stream, new ResourcesMock(), - function(result) { + function (result) { expect(!!result.fnArray && !!result.argsArray).toEqual(true); expect(result.fnArray.length).toEqual(2); expect(result.fnArray[0]).toEqual(OPS.fill); @@ -172,13 +172,13 @@ describe("evaluator", function() { ); }); - it("should handle glued operations and literals", function(done) { + it("should handle glued operations and literals", function (done) { var stream = new StringStream("trueifalserinulln"); runOperatorListCheck( partialEvaluator, stream, new ResourcesMock(), - function(result) { + function (result) { expect(!!result.fnArray && !!result.argsArray).toEqual(true); expect(result.fnArray.length).toEqual(3); expect(result.fnArray[0]).toEqual(OPS.setFlatness); @@ -196,14 +196,14 @@ describe("evaluator", function() { }); }); - describe("validateNumberOfArgs", function() { - it("should execute if correct number of arguments", function(done) { + describe("validateNumberOfArgs", function () { + it("should execute if correct number of arguments", function (done) { var stream = new StringStream("5 1 d0"); runOperatorListCheck( partialEvaluator, stream, new ResourcesMock(), - function(result) { + function (result) { expect(result.argsArray[0][0]).toEqual(5); expect(result.argsArray[0][1]).toEqual(1); expect(result.fnArray[0]).toEqual(OPS.setCharWidth); @@ -211,13 +211,13 @@ describe("evaluator", function() { } ); }); - it("should execute if too many arguments", function(done) { + it("should execute if too many arguments", function (done) { var stream = new StringStream("5 1 4 d0"); runOperatorListCheck( partialEvaluator, stream, new ResourcesMock(), - function(result) { + function (result) { expect(result.argsArray[0][0]).toEqual(1); expect(result.argsArray[0][1]).toEqual(4); expect(result.fnArray[0]).toEqual(OPS.setCharWidth); @@ -225,13 +225,13 @@ describe("evaluator", function() { } ); }); - it("should execute if nested commands", function(done) { + it("should execute if nested commands", function (done) { var stream = new StringStream("/F2 /GS2 gs 5.711 Tf"); runOperatorListCheck( partialEvaluator, stream, new ResourcesMock(), - function(result) { + function (result) { expect(result.fnArray.length).toEqual(3); expect(result.fnArray[0]).toEqual(OPS.setGState); expect(result.fnArray[1]).toEqual(OPS.dependency); @@ -244,13 +244,13 @@ describe("evaluator", function() { } ); }); - it("should skip if too few arguments", function(done) { + it("should skip if too few arguments", function (done) { var stream = new StringStream("5 d0"); runOperatorListCheck( partialEvaluator, stream, new ResourcesMock(), - function(result) { + function (result) { expect(result.argsArray).toEqual([]); expect(result.fnArray).toEqual([]); done(); @@ -261,7 +261,7 @@ describe("evaluator", function() { it( "should error if (many) path operators have too few arguments " + "(bug 1443140)", - function(done) { + function (done) { const NUM_INVALID_OPS = 25; const tempArr = new Array(NUM_INVALID_OPS + 1); @@ -272,7 +272,7 @@ describe("evaluator", function() { partialEvaluator, moveTextStream, new ResourcesMock(), - function(result) { + function (result) { expect(result.argsArray).toEqual([]); expect(result.fnArray).toEqual([]); done(); @@ -286,7 +286,7 @@ describe("evaluator", function() { partialEvaluator, lineToStream, new ResourcesMock(), - function(error) { + function (error) { expect(error instanceof FormatError).toEqual(true); expect(error.message).toEqual( "Invalid command l: expected 2 args, but received 1 args." @@ -297,13 +297,13 @@ describe("evaluator", function() { } ); - it("should close opened saves", function(done) { + it("should close opened saves", function (done) { var stream = new StringStream("qq"); runOperatorListCheck( partialEvaluator, stream, new ResourcesMock(), - function(result) { + function (result) { expect(!!result.fnArray && !!result.argsArray).toEqual(true); expect(result.fnArray.length).toEqual(4); expect(result.fnArray[0]).toEqual(OPS.save); @@ -314,13 +314,13 @@ describe("evaluator", function() { } ); }); - it("should error on paintXObject if name is missing", function(done) { + it("should error on paintXObject if name is missing", function (done) { var stream = new StringStream("/ Do"); runOperatorListCheck( partialEvaluator, stream, new ResourcesMock(), - function(result) { + function (result) { expect(result instanceof FormatError).toEqual(true); expect(result.message).toEqual( "XObject must be referred to by name." @@ -329,7 +329,7 @@ describe("evaluator", function() { } ); }); - it("should skip paintXObject if subtype is PS", function(done) { + it("should skip paintXObject if subtype is PS", function (done) { var xobjStreamDict = new Dict(); xobjStreamDict.set("Subtype", Name.get("PS")); var xobjStream = new Stream([], 0, 0, xobjStreamDict); @@ -341,7 +341,7 @@ describe("evaluator", function() { resources.set("XObject", xobjs); var stream = new StringStream("/Res1 Do"); - runOperatorListCheck(partialEvaluator, stream, resources, function( + runOperatorListCheck(partialEvaluator, stream, resources, function ( result ) { expect(result.argsArray).toEqual([]); @@ -351,8 +351,8 @@ describe("evaluator", function() { }); }); - describe("thread control", function() { - it("should abort operator list parsing", function(done) { + describe("thread control", function () { + it("should abort operator list parsing", function (done) { var stream = new StringStream("qqQQ"); var resources = new ResourcesMock(); var result = new OperatorList(); @@ -365,13 +365,13 @@ describe("evaluator", function() { resources, operatorList: result, }) - .catch(function() { + .catch(function () { expect(!!result.fnArray && !!result.argsArray).toEqual(true); expect(result.fnArray.length).toEqual(0); done(); }); }); - it("should abort text parsing parsing", function(done) { + it("should abort text parsing parsing", function (done) { var resources = new ResourcesMock(); var stream = new StringStream("qqQQ"); var task = new WorkerTask("TextContentAbort"); @@ -382,19 +382,19 @@ describe("evaluator", function() { task, resources, }) - .catch(function() { + .catch(function () { expect(true).toEqual(true); done(); }); }); }); - describe("operator list", function() { + describe("operator list", function () { class StreamSinkMock { enqueue() {} } - it("should get correct total length after flushing", function() { + it("should get correct total length after flushing", function () { var operatorList = new OperatorList(null, new StreamSinkMock()); operatorList.addOp(OPS.save, null); operatorList.addOp(OPS.restore, null); diff --git a/test/unit/fetch_stream_spec.js b/test/unit/fetch_stream_spec.js index 49a06cbea..3a4477b22 100644 --- a/test/unit/fetch_stream_spec.js +++ b/test/unit/fetch_stream_spec.js @@ -17,11 +17,11 @@ import { AbortException } from "../../src/shared/util.js"; import { PDFFetchStream } from "../../src/display/fetch_stream.js"; -describe("fetch_stream", function() { +describe("fetch_stream", function () { const pdfUrl = new URL("../pdfs/tracemonkey.pdf", window.location).href; const pdfLength = 1016315; - it("read with streaming", function(done) { + it("read with streaming", function (done) { const stream = new PDFFetchStream({ url: pdfUrl, disableStream: false, @@ -31,14 +31,14 @@ describe("fetch_stream", function() { const fullReader = stream.getFullReader(); let isStreamingSupported, isRangeSupported; - const promise = fullReader.headersReady.then(function() { + const promise = fullReader.headersReady.then(function () { isStreamingSupported = fullReader.isStreamingSupported; isRangeSupported = fullReader.isRangeSupported; }); let len = 0; - const read = function() { - return fullReader.read().then(function(result) { + const read = function () { + return fullReader.read().then(function (result) { if (result.done) { return undefined; } @@ -50,7 +50,7 @@ describe("fetch_stream", function() { const readPromise = Promise.all([read(), promise]); readPromise - .then(function() { + .then(function () { expect(len).toEqual(pdfLength); expect(isStreamingSupported).toEqual(true); expect(isRangeSupported).toEqual(false); @@ -59,7 +59,7 @@ describe("fetch_stream", function() { .catch(done.fail); }); - it("read ranges with streaming", function(done) { + it("read ranges with streaming", function (done) { const rangeSize = 32768; const stream = new PDFFetchStream({ url: pdfUrl, @@ -71,7 +71,7 @@ describe("fetch_stream", function() { const fullReader = stream.getFullReader(); let isStreamingSupported, isRangeSupported, fullReaderCancelled; - const promise = fullReader.headersReady.then(function() { + const promise = fullReader.headersReady.then(function () { isStreamingSupported = fullReader.isStreamingSupported; isRangeSupported = fullReader.isRangeSupported; // We shall be able to close full reader without any issue. @@ -88,8 +88,8 @@ describe("fetch_stream", function() { const result1 = { value: 0 }, result2 = { value: 0 }; - const read = function(reader, lenResult) { - return reader.read().then(function(result) { + const read = function (reader, lenResult) { + return reader.read().then(function (result) { if (result.done) { return undefined; } @@ -105,7 +105,7 @@ describe("fetch_stream", function() { promise, ]); readPromise - .then(function() { + .then(function () { expect(isStreamingSupported).toEqual(true); expect(isRangeSupported).toEqual(true); expect(fullReaderCancelled).toEqual(true); diff --git a/test/unit/function_spec.js b/test/unit/function_spec.js index 952600576..b08b3294a 100644 --- a/test/unit/function_spec.js +++ b/test/unit/function_spec.js @@ -20,8 +20,8 @@ import { import { PostScriptLexer, PostScriptParser } from "../../src/core/ps_parser.js"; import { StringStream } from "../../src/core/stream.js"; -describe("function", function() { - beforeEach(function() { +describe("function", function () { + beforeEach(function () { jasmine.addMatchers({ toMatchArray(util, customEqualityTesters) { return { @@ -67,55 +67,55 @@ describe("function", function() { }); }); - describe("PostScriptParser", function() { + describe("PostScriptParser", function () { function parse(program) { var stream = new StringStream(program); var parser = new PostScriptParser(new PostScriptLexer(stream)); return parser.parse(); } - it("parses empty programs", function() { + it("parses empty programs", function () { var output = parse("{}"); expect(output.length).toEqual(0); }); - it("parses positive numbers", function() { + it("parses positive numbers", function () { var number = 999; var program = parse("{ " + number + " }"); var expectedProgram = [number]; expect(program).toMatchArray(expectedProgram); }); - it("parses negative numbers", function() { + it("parses negative numbers", function () { var number = -999; var program = parse("{ " + number + " }"); var expectedProgram = [number]; expect(program).toMatchArray(expectedProgram); }); - it("parses negative floats", function() { + it("parses negative floats", function () { var number = 3.3; var program = parse("{ " + number + " }"); var expectedProgram = [number]; expect(program).toMatchArray(expectedProgram); }); - it("parses operators", function() { + it("parses operators", function () { var program = parse("{ sub }"); var expectedProgram = ["sub"]; expect(program).toMatchArray(expectedProgram); }); - it("parses if statements", function() { + it("parses if statements", function () { var program = parse("{ { 99 } if }"); var expectedProgram = [3, "jz", 99]; expect(program).toMatchArray(expectedProgram); }); - it("parses ifelse statements", function() { + it("parses ifelse statements", function () { var program = parse("{ { 99 } { 44 } ifelse }"); var expectedProgram = [5, "jz", 99, 6, "j", 44]; expect(program).toMatchArray(expectedProgram); }); - it("handles missing brackets", function() { - expect(function() { + it("handles missing brackets", function () { + expect(function () { parse("{"); }).toThrow(new Error("Unexpected symbol: found undefined expected 1.")); }); - it("handles junk after the end", function() { + it("handles junk after the end", function () { var number = 3.3; var program = parse("{ " + number + " }#"); var expectedProgram = [number]; @@ -123,7 +123,7 @@ describe("function", function() { }); }); - describe("PostScriptEvaluator", function() { + describe("PostScriptEvaluator", function () { function evaluate(program) { var stream = new StringStream(program); var parser = new PostScriptParser(new PostScriptLexer(stream)); @@ -133,320 +133,320 @@ describe("function", function() { return output; } - it("pushes stack", function() { + it("pushes stack", function () { var stack = evaluate("{ 99 }"); var expectedStack = [99]; expect(stack).toMatchArray(expectedStack); }); - it("handles if with true", function() { + it("handles if with true", function () { var stack = evaluate("{ 1 {99} if }"); var expectedStack = [99]; expect(stack).toMatchArray(expectedStack); }); - it("handles if with false", function() { + it("handles if with false", function () { var stack = evaluate("{ 0 {99} if }"); var expectedStack = []; expect(stack).toMatchArray(expectedStack); }); - it("handles ifelse with true", function() { + it("handles ifelse with true", function () { var stack = evaluate("{ 1 {99} {77} ifelse }"); var expectedStack = [99]; expect(stack).toMatchArray(expectedStack); }); - it("handles ifelse with false", function() { + it("handles ifelse with false", function () { var stack = evaluate("{ 0 {99} {77} ifelse }"); var expectedStack = [77]; expect(stack).toMatchArray(expectedStack); }); - it("handles nested if", function() { + it("handles nested if", function () { var stack = evaluate("{ 1 {1 {77} if} if }"); var expectedStack = [77]; expect(stack).toMatchArray(expectedStack); }); - it("abs", function() { + it("abs", function () { var stack = evaluate("{ -2 abs }"); var expectedStack = [2]; expect(stack).toMatchArray(expectedStack); }); - it("adds", function() { + it("adds", function () { var stack = evaluate("{ 1 2 add }"); var expectedStack = [3]; expect(stack).toMatchArray(expectedStack); }); - it("boolean and", function() { + it("boolean and", function () { var stack = evaluate("{ true false and }"); var expectedStack = [false]; expect(stack).toMatchArray(expectedStack); }); - it("bitwise and", function() { + it("bitwise and", function () { var stack = evaluate("{ 254 1 and }"); var expectedStack = [254 & 1]; expect(stack).toMatchArray(expectedStack); }); - it("calculates the inverse tangent of a number", function() { + it("calculates the inverse tangent of a number", function () { var stack = evaluate("{ 90 atan }"); var expectedStack = [Math.atan(90)]; expect(stack).toMatchArray(expectedStack); }); - it("handles bitshifting ", function() { + it("handles bitshifting ", function () { var stack = evaluate("{ 50 2 bitshift }"); var expectedStack = [200]; expect(stack).toMatchArray(expectedStack); }); - it("calculates the ceiling value", function() { + it("calculates the ceiling value", function () { var stack = evaluate("{ 9.9 ceiling }"); var expectedStack = [10]; expect(stack).toMatchArray(expectedStack); }); - it("copies", function() { + it("copies", function () { var stack = evaluate("{ 99 98 2 copy }"); var expectedStack = [99, 98, 99, 98]; expect(stack).toMatchArray(expectedStack); }); - it("calculates the cosine of a number", function() { + it("calculates the cosine of a number", function () { var stack = evaluate("{ 90 cos }"); var expectedStack = [Math.cos(90)]; expect(stack).toMatchArray(expectedStack); }); - it("converts to int", function() { + it("converts to int", function () { var stack = evaluate("{ 9.9 cvi }"); var expectedStack = [9]; expect(stack).toMatchArray(expectedStack); }); - it("converts negatives to int", function() { + it("converts negatives to int", function () { var stack = evaluate("{ -9.9 cvi }"); var expectedStack = [-9]; expect(stack).toMatchArray(expectedStack); }); - it("converts to real", function() { + it("converts to real", function () { var stack = evaluate("{ 55.34 cvr }"); var expectedStack = [55.34]; expect(stack).toMatchArray(expectedStack); }); - it("divides", function() { + it("divides", function () { var stack = evaluate("{ 6 5 div }"); var expectedStack = [1.2]; expect(stack).toMatchArray(expectedStack); }); - it("maps division by zero to infinity", function() { + it("maps division by zero to infinity", function () { var stack = evaluate("{ 6 0 div }"); var expectedStack = [Infinity]; expect(stack).toMatchArray(expectedStack); }); - it("duplicates", function() { + it("duplicates", function () { var stack = evaluate("{ 99 dup }"); var expectedStack = [99, 99]; expect(stack).toMatchArray(expectedStack); }); - it("accepts an equality", function() { + it("accepts an equality", function () { var stack = evaluate("{ 9 9 eq }"); var expectedStack = [true]; expect(stack).toMatchArray(expectedStack); }); - it("rejects an inequality", function() { + it("rejects an inequality", function () { var stack = evaluate("{ 9 8 eq }"); var expectedStack = [false]; expect(stack).toMatchArray(expectedStack); }); - it("exchanges", function() { + it("exchanges", function () { var stack = evaluate("{ 44 99 exch }"); var expectedStack = [99, 44]; expect(stack).toMatchArray(expectedStack); }); - it("handles exponentiation", function() { + it("handles exponentiation", function () { var stack = evaluate("{ 10 2 exp }"); var expectedStack = [100]; expect(stack).toMatchArray(expectedStack); }); - it("pushes false onto the stack", function() { + it("pushes false onto the stack", function () { var stack = evaluate("{ false }"); var expectedStack = [false]; expect(stack).toMatchArray(expectedStack); }); - it("calculates the floor value", function() { + it("calculates the floor value", function () { var stack = evaluate("{ 9.9 floor }"); var expectedStack = [9]; expect(stack).toMatchArray(expectedStack); }); - it("handles greater than or equal to", function() { + it("handles greater than or equal to", function () { var stack = evaluate("{ 10 9 ge }"); var expectedStack = [true]; expect(stack).toMatchArray(expectedStack); }); - it("rejects less than for greater than or equal to", function() { + it("rejects less than for greater than or equal to", function () { var stack = evaluate("{ 8 9 ge }"); var expectedStack = [false]; expect(stack).toMatchArray(expectedStack); }); - it("handles greater than", function() { + it("handles greater than", function () { var stack = evaluate("{ 10 9 gt }"); var expectedStack = [true]; expect(stack).toMatchArray(expectedStack); }); - it("rejects less than or equal for greater than", function() { + it("rejects less than or equal for greater than", function () { var stack = evaluate("{ 9 9 gt }"); var expectedStack = [false]; expect(stack).toMatchArray(expectedStack); }); - it("divides to integer", function() { + it("divides to integer", function () { var stack = evaluate("{ 2 3 idiv }"); var expectedStack = [0]; expect(stack).toMatchArray(expectedStack); }); - it("divides to negative integer", function() { + it("divides to negative integer", function () { var stack = evaluate("{ -2 3 idiv }"); var expectedStack = [0]; expect(stack).toMatchArray(expectedStack); }); - it("duplicates index", function() { + it("duplicates index", function () { var stack = evaluate("{ 4 3 2 1 2 index }"); var expectedStack = [4, 3, 2, 1, 3]; expect(stack).toMatchArray(expectedStack); }); - it("handles less than or equal to", function() { + it("handles less than or equal to", function () { var stack = evaluate("{ 9 10 le }"); var expectedStack = [true]; expect(stack).toMatchArray(expectedStack); }); - it("rejects greater than for less than or equal to", function() { + it("rejects greater than for less than or equal to", function () { var stack = evaluate("{ 10 9 le }"); var expectedStack = [false]; expect(stack).toMatchArray(expectedStack); }); - it("calculates the natural logarithm", function() { + it("calculates the natural logarithm", function () { var stack = evaluate("{ 10 ln }"); var expectedStack = [Math.log(10)]; expect(stack).toMatchArray(expectedStack); }); - it("calculates the base 10 logarithm", function() { + it("calculates the base 10 logarithm", function () { var stack = evaluate("{ 100 log }"); var expectedStack = [2]; expect(stack).toMatchArray(expectedStack); }); - it("handles less than", function() { + it("handles less than", function () { var stack = evaluate("{ 9 10 lt }"); var expectedStack = [true]; expect(stack).toMatchArray(expectedStack); }); - it("rejects greater than or equal to for less than", function() { + it("rejects greater than or equal to for less than", function () { var stack = evaluate("{ 10 9 lt }"); var expectedStack = [false]; expect(stack).toMatchArray(expectedStack); }); - it("performs the modulo operation", function() { + it("performs the modulo operation", function () { var stack = evaluate("{ 4 3 mod }"); var expectedStack = [1]; expect(stack).toMatchArray(expectedStack); }); - it("multiplies two numbers (positive result)", function() { + it("multiplies two numbers (positive result)", function () { var stack = evaluate("{ 9 8 mul }"); var expectedStack = [72]; expect(stack).toMatchArray(expectedStack); }); - it("multiplies two numbers (negative result)", function() { + it("multiplies two numbers (negative result)", function () { var stack = evaluate("{ 9 -8 mul }"); var expectedStack = [-72]; expect(stack).toMatchArray(expectedStack); }); - it("accepts an inequality", function() { + it("accepts an inequality", function () { var stack = evaluate("{ 9 8 ne }"); var expectedStack = [true]; expect(stack).toMatchArray(expectedStack); }); - it("rejects an equality", function() { + it("rejects an equality", function () { var stack = evaluate("{ 9 9 ne }"); var expectedStack = [false]; expect(stack).toMatchArray(expectedStack); }); - it("negates", function() { + it("negates", function () { var stack = evaluate("{ 4.5 neg }"); var expectedStack = [-4.5]; expect(stack).toMatchArray(expectedStack); }); - it("boolean not", function() { + it("boolean not", function () { var stack = evaluate("{ true not }"); var expectedStack = [false]; expect(stack).toMatchArray(expectedStack); }); - it("bitwise not", function() { + it("bitwise not", function () { var stack = evaluate("{ 12 not }"); var expectedStack = [-13]; expect(stack).toMatchArray(expectedStack); }); - it("boolean or", function() { + it("boolean or", function () { var stack = evaluate("{ true false or }"); var expectedStack = [true]; expect(stack).toMatchArray(expectedStack); }); - it("bitwise or", function() { + it("bitwise or", function () { var stack = evaluate("{ 254 1 or }"); var expectedStack = [254 | 1]; expect(stack).toMatchArray(expectedStack); }); - it("pops stack", function() { + it("pops stack", function () { var stack = evaluate("{ 1 2 pop }"); var expectedStack = [1]; expect(stack).toMatchArray(expectedStack); }); - it("rolls stack right", function() { + it("rolls stack right", function () { var stack = evaluate("{ 1 3 2 2 4 1 roll }"); var expectedStack = [2, 1, 3, 2]; expect(stack).toMatchArray(expectedStack); }); - it("rolls stack left", function() { + it("rolls stack left", function () { var stack = evaluate("{ 1 3 2 2 4 -1 roll }"); var expectedStack = [3, 2, 2, 1]; expect(stack).toMatchArray(expectedStack); }); - it("rounds a number", function() { + it("rounds a number", function () { var stack = evaluate("{ 9.52 round }"); var expectedStack = [10]; expect(stack).toMatchArray(expectedStack); }); - it("calculates the sine of a number", function() { + it("calculates the sine of a number", function () { var stack = evaluate("{ 90 sin }"); var expectedStack = [Math.sin(90)]; expect(stack).toMatchArray(expectedStack); }); - it("calculates a square root (integer)", function() { + it("calculates a square root (integer)", function () { var stack = evaluate("{ 100 sqrt }"); var expectedStack = [10]; expect(stack).toMatchArray(expectedStack); }); - it("calculates a square root (float)", function() { + it("calculates a square root (float)", function () { var stack = evaluate("{ 99 sqrt }"); var expectedStack = [Math.sqrt(99)]; expect(stack).toMatchArray(expectedStack); }); - it("subtracts (positive result)", function() { + it("subtracts (positive result)", function () { var stack = evaluate("{ 6 4 sub }"); var expectedStack = [2]; expect(stack).toMatchArray(expectedStack); }); - it("subtracts (negative result)", function() { + it("subtracts (negative result)", function () { var stack = evaluate("{ 4 6 sub }"); var expectedStack = [-2]; expect(stack).toMatchArray(expectedStack); }); - it("pushes true onto the stack", function() { + it("pushes true onto the stack", function () { var stack = evaluate("{ true }"); var expectedStack = [true]; expect(stack).toMatchArray(expectedStack); }); - it("truncates a number", function() { + it("truncates a number", function () { var stack = evaluate("{ 35.004 truncate }"); var expectedStack = [35]; expect(stack).toMatchArray(expectedStack); }); - it("calculates an exclusive or value", function() { + it("calculates an exclusive or value", function () { var stack = evaluate("{ 3 9 xor }"); var expectedStack = [10]; expect(stack).toMatchArray(expectedStack); }); }); - describe("PostScriptCompiler", function() { + describe("PostScriptCompiler", function () { function check(code, domain, range, samples) { var compiler = new PostScriptCompiler(); var compiledCode = compiler.compile(code, domain, range); @@ -472,7 +472,7 @@ describe("function", function() { } } - it("check compiled add", function() { + it("check compiled add", function () { check([0.25, 0.5, "add"], [], [0, 1], [{ input: [], output: [0.75] }]); check([0, "add"], [0, 1], [0, 1], [{ input: [0.25], output: [0.25] }]); check([0.5, "add"], [0, 1], [0, 1], [{ input: [0.25], output: [0.75] }]); @@ -496,7 +496,7 @@ describe("function", function() { ); check(["add"], [0, 1], [0, 1], null); }); - it("check compiled sub", function() { + it("check compiled sub", function () { check([0.5, 0.25, "sub"], [], [0, 1], [{ input: [], output: [0.25] }]); check([0, "sub"], [0, 1], [0, 1], [{ input: [0.25], output: [0.25] }]); check([0.5, "sub"], [0, 1], [0, 1], [{ input: [0.75], output: [0.25] }]); @@ -527,7 +527,7 @@ describe("function", function() { [{ input: [0.75], output: [0.75] }] ); }); - it("check compiled mul", function() { + it("check compiled mul", function () { check([0.25, 0.5, "mul"], [], [0, 1], [{ input: [], output: [0.125] }]); check([0, "mul"], [0, 1], [0, 1], [{ input: [0.25], output: [0] }]); check([0.5, "mul"], [0, 1], [0, 1], [{ input: [0.25], output: [0.125] }]); @@ -558,7 +558,7 @@ describe("function", function() { ); check(["mul"], [0, 1], [0, 1], null); }); - it("check compiled max", function() { + it("check compiled max", function () { check( ["dup", 0.75, "gt", 7, "jz", "pop", 0.75], [0, 1], @@ -573,7 +573,7 @@ describe("function", function() { ); check(["dup", 0.75, "gt", 5, "jz", "pop", 0.75], [0, 1], [0, 1], null); }); - it("check pop/roll/index", function() { + it("check pop/roll/index", function () { check([1, "pop"], [0, 1], [0, 1], [{ input: [0.5], output: [0.5] }]); check( [1, 3, -1, "roll"], @@ -597,7 +597,7 @@ describe("function", function() { check([1, 3, "index", "pop"], [0, 1], [0, 1], null); check([1, 0.5, "index", "pop"], [0, 1], [0, 1], null); }); - it("check input boundaries", function() { + it("check input boundaries", function () { check([], [0, 0.5], [0, 1], [{ input: [1], output: [0.5] }]); check([], [0.5, 1], [0, 1], [{ input: [0], output: [0.5] }]); check( @@ -608,7 +608,7 @@ describe("function", function() { ); check([], [100, 1001], [0, 10000], [{ input: [1000], output: [1000] }]); }); - it("check output boundaries", function() { + it("check output boundaries", function () { check([], [0, 1], [0, 0.5], [{ input: [1], output: [0.5] }]); check([], [0, 1], [0.5, 1], [{ input: [0], output: [0.5] }]); check( @@ -619,7 +619,7 @@ describe("function", function() { ); check([], [0, 10000], [100, 1001], [{ input: [1000], output: [1000] }]); }); - it("compile optimized", function() { + it("compile optimized", function () { var compiler = new PostScriptCompiler(); var code = [0, "add", 1, 1, 3, -1, "roll", "sub", "sub", 1, "mul"]; var compiledCode = compiler.compile(code, [0, 1], [0, 1]); diff --git a/test/unit/jasmine-boot.js b/test/unit/jasmine-boot.js index 24389822b..c414ba1fb 100644 --- a/test/unit/jasmine-boot.js +++ b/test/unit/jasmine-boot.js @@ -79,11 +79,11 @@ function initializePDFJS(callback) { "pdfjs-test/unit/ui_utils_spec.js", "pdfjs-test/unit/unicode_spec.js", "pdfjs-test/unit/util_spec.js", - ].map(function(moduleName) { + ].map(function (moduleName) { // eslint-disable-next-line no-unsanitized/method return SystemJS.import(moduleName); }) - ).then(function(modules) { + ).then(function (modules) { const displayApi = modules[0]; const { GlobalWorkerOptions } = modules[1]; const { PDFNetworkStream } = modules[2]; @@ -102,11 +102,11 @@ function initializePDFJS(callback) { "body" in Response.prototype && typeof ReadableStream !== "undefined" ) { - displayApi.setPDFNetworkStreamFactory(function(params) { + displayApi.setPDFNetworkStreamFactory(function (params) { return new PDFFetchStream(params); }); } else { - displayApi.setPDFNetworkStreamFactory(function(params) { + displayApi.setPDFNetworkStreamFactory(function (params) { return new PDFNetworkStream(params); }); } @@ -118,7 +118,7 @@ function initializePDFJS(callback) { }); } -(function() { +(function () { window.jasmine = jasmineRequire.core(jasmineRequire); jasmineRequire.html(jasmine); @@ -190,7 +190,7 @@ function initializePDFJS(callback) { }, }); - config.specFilter = function(spec) { + config.specFilter = function (spec) { return specFilter.matches(spec.getFullName()); }; @@ -204,12 +204,12 @@ function initializePDFJS(callback) { // instance and then executing the loaded Jasmine environment. var currentWindowOnload = window.onload; - window.onload = function() { + window.onload = function () { if (currentWindowOnload) { currentWindowOnload(); } - initializePDFJS(function() { + initializePDFJS(function () { htmlReporter.initialize(); env.execute(); }); diff --git a/test/unit/message_handler_spec.js b/test/unit/message_handler_spec.js index 76ab3e6f0..4ad7f4fdc 100644 --- a/test/unit/message_handler_spec.js +++ b/test/unit/message_handler_spec.js @@ -21,7 +21,7 @@ import { import { LoopbackPort } from "../../src/display/api.js"; import { MessageHandler } from "../../src/shared/message_handler.js"; -describe("message_handler", function() { +describe("message_handler", function () { // Sleep function to wait for sometime, similar to setTimeout but faster. function sleep(ticks) { return Promise.resolve().then(() => { @@ -29,8 +29,8 @@ describe("message_handler", function() { }); } - describe("sendWithStream", function() { - it("should return a ReadableStream", function() { + describe("sendWithStream", function () { + it("should return a ReadableStream", function () { const port = new LoopbackPort(); const messageHandler1 = new MessageHandler("main", "worker", port); const readable = messageHandler1.sendWithStream("fakeHandler"); @@ -39,16 +39,16 @@ describe("message_handler", function() { expect(typeof readable.getReader).toEqual("function"); }); - it("should read using a reader", function(done) { + it("should read using a reader", function (done) { let log = ""; const port = new LoopbackPort(); const messageHandler1 = new MessageHandler("main", "worker", port); const messageHandler2 = new MessageHandler("worker", "main", port); messageHandler2.on("fakeHandler", (data, sink) => { - sink.onPull = function() { + sink.onPull = function () { log += "p"; }; - sink.onCancel = function(reason) { + sink.onCancel = function (reason) { log += "c"; }; sink.ready @@ -93,15 +93,15 @@ describe("message_handler", function() { }); }); - it("should not read any data when cancelled", function(done) { + it("should not read any data when cancelled", function (done) { let log = ""; const port = new LoopbackPort(); const messageHandler2 = new MessageHandler("worker", "main", port); messageHandler2.on("fakeHandler", (data, sink) => { - sink.onPull = function() { + sink.onPull = function () { log += "p"; }; - sink.onCancel = function(reason) { + sink.onCancel = function (reason) { log += "c"; }; log += "0"; @@ -159,15 +159,15 @@ describe("message_handler", function() { }); }); - it("should not read when errored", function(done) { + it("should not read when errored", function (done) { let log = ""; const port = new LoopbackPort(); const messageHandler2 = new MessageHandler("worker", "main", port); messageHandler2.on("fakeHandler", (data, sink) => { - sink.onPull = function() { + sink.onPull = function () { log += "p"; }; - sink.onCancel = function(reason) { + sink.onCancel = function (reason) { log += "c"; }; log += "0"; @@ -214,15 +214,15 @@ describe("message_handler", function() { }); }); - it("should read data with blocking promise", function(done) { + it("should read data with blocking promise", function (done) { let log = ""; const port = new LoopbackPort(); const messageHandler2 = new MessageHandler("worker", "main", port); messageHandler2.on("fakeHandler", (data, sink) => { - sink.onPull = function() { + sink.onPull = function () { log += "p"; }; - sink.onCancel = function(reason) { + sink.onCancel = function (reason) { log += "c"; }; log += "0"; @@ -290,15 +290,15 @@ describe("message_handler", function() { it( "should read data with blocking promise and buffer whole data" + " into stream", - function(done) { + function (done) { let log = ""; const port = new LoopbackPort(); const messageHandler2 = new MessageHandler("worker", "main", port); messageHandler2.on("fakeHandler", (data, sink) => { - sink.onPull = function() { + sink.onPull = function () { log += "p"; }; - sink.onCancel = function(reason) { + sink.onCancel = function (reason) { log += "c"; }; log += "0"; @@ -364,16 +364,16 @@ describe("message_handler", function() { } ); - it("should ignore any pull after close is called", function(done) { + it("should ignore any pull after close is called", function (done) { let log = ""; const port = new LoopbackPort(); const capability = createPromiseCapability(); const messageHandler2 = new MessageHandler("worker", "main", port); messageHandler2.on("fakeHandler", (data, sink) => { - sink.onPull = function() { + sink.onPull = function () { log += "p"; }; - sink.onCancel = function(reason) { + sink.onCancel = function (reason) { log += "c"; }; log += "0"; diff --git a/test/unit/metadata_spec.js b/test/unit/metadata_spec.js index 1b92847d8..710a8fdb7 100644 --- a/test/unit/metadata_spec.js +++ b/test/unit/metadata_spec.js @@ -16,8 +16,8 @@ import { isEmptyObj } from "../../src/shared/util.js"; import { Metadata } from "../../src/display/metadata.js"; -describe("metadata", function() { - it("should handle valid metadata", function() { +describe("metadata", function () { + it("should handle valid metadata", function () { const data = "" + "" + @@ -35,7 +35,7 @@ describe("metadata", function() { expect(metadata.getAll()).toEqual({ "dc:title": "Foo bar baz" }); }); - it("should repair and handle invalid metadata", function() { + it("should repair and handle invalid metadata", function () { const data = "" + "" + @@ -53,7 +53,7 @@ describe("metadata", function() { expect(metadata.getAll()).toEqual({ "dc:title": "PDF&" }); }); - it("should repair and handle invalid metadata (bug 1424938)", function() { + it("should repair and handle invalid metadata (bug 1424938)", function () { const data = "" + @@ -102,7 +102,7 @@ describe("metadata", function() { }); }); - it("should gracefully handle incomplete tags (issue 8884)", function() { + it("should gracefully handle incomplete tags (issue 8884)", function () { const data = '' + @@ -133,7 +133,7 @@ describe("metadata", function() { expect(isEmptyObj(metadata.getAll())).toEqual(true); }); - it('should gracefully handle "junk" before the actual metadata (issue 10395)', function() { + it('should gracefully handle "junk" before the actual metadata (issue 10395)', function () { const data = '' + '" + @@ -202,7 +202,7 @@ describe("metadata", function() { expect(metadata.getAll()).toEqual({ "dc:title": "'Foo bar baz'" }); }); - it("should gracefully handle unbalanced end tags (issue 10410)", function() { + it("should gracefully handle unbalanced end tags (issue 10410)", function () { const data = '' + '' + @@ -225,7 +225,7 @@ describe("metadata", function() { expect(isEmptyObj(metadata.getAll())).toEqual(true); }); - it("should not be vulnerable to the billion laughs attack", function() { + it("should not be vulnerable to the billion laughs attack", function () { const data = '' + " { if (headerName === "Content-Disposition") { @@ -212,7 +212,7 @@ describe("network_utils", function() { ).toBeNull(); }); - it("gets the filename from the response header", function() { + it("gets the filename from the response header", function () { expect( extractFilenameFromHeader(headerName => { if (headerName === "Content-Disposition") { @@ -295,7 +295,7 @@ describe("network_utils", function() { ).toEqual("100%.pdf"); }); - it("gets the filename from the response header (RFC 6266)", function() { + it("gets the filename from the response header (RFC 6266)", function () { expect( extractFilenameFromHeader(headerName => { if (headerName === "Content-Disposition") { @@ -342,7 +342,7 @@ describe("network_utils", function() { ).toEqual("filename.pdf"); }); - it("gets the filename from the response header (RFC 2231)", function() { + it("gets the filename from the response header (RFC 2231)", function () { // Tests continuations (RFC 2231 section 3, via RFC 5987 section 3.1). expect( extractFilenameFromHeader(headerName => { @@ -354,7 +354,7 @@ describe("network_utils", function() { ).toEqual("filename.pdf"); }); - it("only extracts filename with pdf extension", function() { + it("only extracts filename with pdf extension", function () { expect( extractFilenameFromHeader(headerName => { if (headerName === "Content-Disposition") { @@ -365,7 +365,7 @@ describe("network_utils", function() { ).toBeNull(); }); - it("extension validation is case insensitive", function() { + it("extension validation is case insensitive", function () { expect( extractFilenameFromHeader(headerName => { if (headerName === "Content-Disposition") { @@ -377,8 +377,8 @@ describe("network_utils", function() { }); }); - describe("createResponseStatusError", function() { - it("handles missing PDF file responses", function() { + describe("createResponseStatusError", function () { + it("handles missing PDF file responses", function () { expect(createResponseStatusError(404, "https://foo.com/bar.pdf")).toEqual( new MissingPDFException('Missing PDF "https://foo.com/bar.pdf".') ); @@ -388,7 +388,7 @@ describe("network_utils", function() { ); }); - it("handles unexpected responses", function() { + it("handles unexpected responses", function () { expect(createResponseStatusError(302, "https://foo.com/bar.pdf")).toEqual( new UnexpectedResponseException( "Unexpected server response (302) while retrieving PDF " + @@ -405,13 +405,13 @@ describe("network_utils", function() { }); }); - describe("validateResponseStatus", function() { - it("accepts valid response statuses", function() { + describe("validateResponseStatus", function () { + it("accepts valid response statuses", function () { expect(validateResponseStatus(200)).toEqual(true); expect(validateResponseStatus(206)).toEqual(true); }); - it("rejects invalid response statuses", function() { + it("rejects invalid response statuses", function () { expect(validateResponseStatus(302)).toEqual(false); expect(validateResponseStatus(404)).toEqual(false); expect(validateResponseStatus(null)).toEqual(false); diff --git a/test/unit/node_stream_spec.js b/test/unit/node_stream_spec.js index e46c44743..730a62e3c 100644 --- a/test/unit/node_stream_spec.js +++ b/test/unit/node_stream_spec.js @@ -26,7 +26,7 @@ const url = __non_webpack_require__("url"); const http = __non_webpack_require__("http"); const fs = __non_webpack_require__("fs"); -describe("node_stream", function() { +describe("node_stream", function () { let server = null; let port = null; const pdf = url.parse( @@ -82,7 +82,7 @@ describe("node_stream", function() { done(); }); - it("read both http(s) and filesystem pdf files", function(done) { + it("read both http(s) and filesystem pdf files", function (done) { const stream1 = new PDFNodeStream({ url: `http://127.0.0.1:${port}/tracemonkey.pdf`, rangeChunkSize: 65536, @@ -114,8 +114,8 @@ describe("node_stream", function() { let len1 = 0, len2 = 0; - const read1 = function() { - return fullReader1.read().then(function(result) { + const read1 = function () { + return fullReader1.read().then(function (result) { if (result.done) { return undefined; } @@ -123,8 +123,8 @@ describe("node_stream", function() { return read1(); }); }; - const read2 = function() { - return fullReader2.read().then(function(result) { + const read2 = function () { + return fullReader2.read().then(function (result) { if (result.done) { return undefined; } @@ -149,7 +149,7 @@ describe("node_stream", function() { }); }); - it("read custom ranges for both http(s) and filesystem urls", function(done) { + it("read custom ranges for both http(s) and filesystem urls", function (done) { const rangeSize = 32768; const stream1 = new PDFNodeStream({ url: `http://127.0.0.1:${port}/tracemonkey.pdf`, @@ -172,7 +172,7 @@ describe("node_stream", function() { let isStreamingSupported1, isRangeSupported1, fullReaderCancelled1; let isStreamingSupported2, isRangeSupported2, fullReaderCancelled2; - const promise1 = fullReader1.headersReady.then(function() { + const promise1 = fullReader1.headersReady.then(function () { isStreamingSupported1 = fullReader1.isStreamingSupported; isRangeSupported1 = fullReader1.isRangeSupported; // we shall be able to close the full reader without issues @@ -180,7 +180,7 @@ describe("node_stream", function() { fullReaderCancelled1 = true; }); - const promise2 = fullReader2.headersReady.then(function() { + const promise2 = fullReader2.headersReady.then(function () { isStreamingSupported2 = fullReader2.isStreamingSupported; isRangeSupported2 = fullReader2.isRangeSupported; fullReader2.cancel(new AbortException("Don't need fullReader2.")); @@ -213,8 +213,8 @@ describe("node_stream", function() { const result21 = { value: 0 }, result22 = { value: 0 }; - const read = function(reader, lenResult) { - return reader.read().then(function(result) { + const read = function (reader, lenResult) { + return reader.read().then(function (result) { if (result.done) { return undefined; } @@ -233,7 +233,7 @@ describe("node_stream", function() { ]); readPromises - .then(function() { + .then(function () { expect(result11.value).toEqual(rangeSize); expect(result12.value).toEqual(tailSize); expect(result21.value).toEqual(rangeSize); @@ -246,7 +246,7 @@ describe("node_stream", function() { expect(fullReaderCancelled2).toEqual(true); done(); }) - .catch(function(reason) { + .catch(function (reason) { done.fail(reason); }); }); diff --git a/test/unit/parser_spec.js b/test/unit/parser_spec.js index 9e767db83..98f2e4365 100644 --- a/test/unit/parser_spec.js +++ b/test/unit/parser_spec.js @@ -19,10 +19,10 @@ import { FormatError } from "../../src/shared/util.js"; import { Name } from "../../src/core/primitives.js"; import { StringStream } from "../../src/core/stream.js"; -describe("parser", function() { - describe("Parser", function() { - describe("inlineStreamSkipEI", function() { - it("should skip over the EI marker if it is found", function() { +describe("parser", function () { + describe("Parser", function () { + describe("inlineStreamSkipEI", function () { + it("should skip over the EI marker if it is found", function () { const string = "q 1 0 0 1 0 0 cm BI /W 10 /H 10 /BPC 1 " + "/F /A85 ID abc123~> EI Q"; @@ -38,7 +38,7 @@ describe("parser", function() { expect(input.peekByte()).toEqual(0x51); // 'Q' }); - it("should skip to the end of stream if the EI marker is not found", function() { + it("should skip to the end of stream if the EI marker is not found", function () { const string = "q 1 0 0 1 0 0 cm BI /W 10 /H 10 /BPC 1 /F /A85 ID abc123~> Q"; const input = new StringStream(string); @@ -55,16 +55,16 @@ describe("parser", function() { }); }); - describe("Lexer", function() { - describe("nextChar", function() { - it("should return and set -1 when the end of the stream is reached", function() { + describe("Lexer", function () { + describe("nextChar", function () { + it("should return and set -1 when the end of the stream is reached", function () { const input = new StringStream(""); const lexer = new Lexer(input); expect(lexer.nextChar()).toEqual(-1); expect(lexer.currentChar).toEqual(-1); }); - it("should return and set the character after the current position", function() { + it("should return and set the character after the current position", function () { const input = new StringStream("123"); const lexer = new Lexer(input); expect(lexer.nextChar()).toEqual(0x32); // '2' @@ -72,15 +72,15 @@ describe("parser", function() { }); }); - describe("peekChar", function() { - it("should only return -1 when the end of the stream is reached", function() { + describe("peekChar", function () { + it("should only return -1 when the end of the stream is reached", function () { const input = new StringStream(""); const lexer = new Lexer(input); expect(lexer.peekChar()).toEqual(-1); expect(lexer.currentChar).toEqual(-1); }); - it("should only return the character after the current position", function() { + it("should only return the character after the current position", function () { const input = new StringStream("123"); const lexer = new Lexer(input); expect(lexer.peekChar()).toEqual(0x32); // '2' @@ -88,14 +88,14 @@ describe("parser", function() { }); }); - describe("getNumber", function() { - it("should stop parsing numbers at the end of stream", function() { + describe("getNumber", function () { + it("should stop parsing numbers at the end of stream", function () { const input = new StringStream("11.234"); const lexer = new Lexer(input); expect(lexer.getNumber()).toEqual(11.234); }); - it("should parse PostScript numbers", function() { + it("should parse PostScript numbers", function () { const numbers = [ "-.002", "34.5", @@ -130,19 +130,19 @@ describe("parser", function() { } }); - it("should ignore double negative before number", function() { + it("should ignore double negative before number", function () { const input = new StringStream("--205.88"); const lexer = new Lexer(input); expect(lexer.getNumber()).toEqual(-205.88); }); - it("should ignore minus signs in the middle of number", function() { + it("should ignore minus signs in the middle of number", function () { const input = new StringStream("205--.88"); const lexer = new Lexer(input); expect(lexer.getNumber()).toEqual(205.88); }); - it("should ignore line-breaks between operator and digit in number", function() { + it("should ignore line-breaks between operator and digit in number", function () { const minusInput = new StringStream("-\r\n205.88"); const minusLexer = new Lexer(minusInput); expect(minusLexer.getNumber()).toEqual(-205.88); @@ -152,7 +152,7 @@ describe("parser", function() { expect(plusLexer.getNumber()).toEqual(205.88); }); - it("should treat a single decimal point as zero", function() { + it("should treat a single decimal point as zero", function () { const input = new StringStream("."); const lexer = new Lexer(input); expect(lexer.getNumber()).toEqual(0); @@ -162,13 +162,13 @@ describe("parser", function() { const invalidInput = new StringStream(number); const invalidLexer = new Lexer(invalidInput); - expect(function() { + expect(function () { return invalidLexer.getNumber(); }).toThrowError(FormatError, /^Invalid number:\s/); } }); - it("should handle glued numbers and operators", function() { + it("should handle glued numbers and operators", function () { const input = new StringStream("123ET"); const lexer = new Lexer(input); expect(lexer.getNumber()).toEqual(123); @@ -177,10 +177,10 @@ describe("parser", function() { }); }); - describe("getString", function() { - it("should stop parsing strings at the end of stream", function() { + describe("getString", function () { + it("should stop parsing strings at the end of stream", function () { const input = new StringStream("(1$4)"); - input.getByte = function(super_getByte) { + input.getByte = function (super_getByte) { // Simulating end of file using null (see issue 2766). const ch = super_getByte.call(input); return ch === 0x24 /* '$' */ ? -1 : ch; @@ -189,7 +189,7 @@ describe("parser", function() { expect(lexer.getString()).toEqual("1"); }); - it("should ignore escaped CR and LF", function() { + it("should ignore escaped CR and LF", function () { // '(\101\\102)' should be parsed as 'AB'. const input = new StringStream("(\\101\\\r\n\\102\\\r\\103\\\n\\104)"); const lexer = new Lexer(input); @@ -197,8 +197,8 @@ describe("parser", function() { }); }); - describe("getHexString", function() { - it("should not throw exception on bad input", function() { + describe("getHexString", function () { + it("should not throw exception on bad input", function () { // '7 0 2 15 5 2 2 2 4 3 2 4' should be parsed as '70 21 55 22 24 32'. const input = new StringStream("<7 0 2 15 5 2 2 2 4 3 2 4>"); const lexer = new Lexer(input); @@ -206,8 +206,8 @@ describe("parser", function() { }); }); - describe("getName", function() { - it("should handle Names with invalid usage of NUMBER SIGN (#)", function() { + describe("getName", function () { + it("should handle Names with invalid usage of NUMBER SIGN (#)", function () { const inputNames = ["/# 680 0 R", "/#AQwerty", "/#A<>\n" + "endobj" ); - expect(function() { + expect(function () { return Linearization.create(stream1); }).toThrow( new Error( @@ -316,7 +316,7 @@ describe("parser", function() { ">>\n" + "endobj" ); - expect(function() { + expect(function () { return Linearization.create(stream2); }).toThrow( new Error( @@ -339,7 +339,7 @@ describe("parser", function() { ">>\n" + "endobj" ); - expect(function() { + expect(function () { return Linearization.create(stream3); }).toThrow( new Error( @@ -349,7 +349,7 @@ describe("parser", function() { } ); - it("should reject a linearization dictionary with invalid hint parameters", function() { + it("should reject a linearization dictionary with invalid hint parameters", function () { // The /H parameter should be an array. // prettier-ignore const stream1 = new StringStream( @@ -365,7 +365,7 @@ describe("parser", function() { ">>\n" + "endobj" ); - expect(function() { + expect(function () { return Linearization.create(stream1); }).toThrow( new Error("Hint array in the linearization dictionary is invalid.") @@ -386,7 +386,7 @@ describe("parser", function() { ">>\n" + "endobj" ); - expect(function() { + expect(function () { return Linearization.create(stream2); }).toThrow( new Error("Hint array in the linearization dictionary is invalid.") @@ -407,7 +407,7 @@ describe("parser", function() { ">>\n" + "endobj" ); - expect(function() { + expect(function () { return Linearization.create(stream3); }).toThrow( new Error("Hint (2) in the linearization dictionary is invalid.") diff --git a/test/unit/pdf_find_controller_spec.js b/test/unit/pdf_find_controller_spec.js index 165b73f42..aef775e97 100644 --- a/test/unit/pdf_find_controller_spec.js +++ b/test/unit/pdf_find_controller_spec.js @@ -44,13 +44,13 @@ class MockLinkService extends SimpleLinkService { } } -describe("pdf_find_controller", function() { +describe("pdf_find_controller", function () { let eventBus; let pdfFindController; - beforeEach(function(done) { + beforeEach(function (done) { const loadingTask = getDocument(buildGetDocumentParams("tracemonkey.pdf")); - loadingTask.promise.then(function(pdfDocument) { + loadingTask.promise.then(function (pdfDocument) { eventBus = new EventBus(); const linkService = new MockLinkService(); @@ -66,13 +66,13 @@ describe("pdf_find_controller", function() { }); }); - afterEach(function() { + afterEach(function () { eventBus = null; pdfFindController = null; }); function testSearch({ parameters, matchesPerPage, selectedMatch }) { - return new Promise(function(resolve) { + return new Promise(function (resolve) { pdfFindController.executeCommand("find", parameters); // The `updatefindmatchescount` event is only emitted if the page contains @@ -124,7 +124,7 @@ describe("pdf_find_controller", function() { }); } - it("performs a normal search", function(done) { + it("performs a normal search", function (done) { testSearch({ parameters: { query: "Dynamic", @@ -141,7 +141,7 @@ describe("pdf_find_controller", function() { }).then(done); }); - it("performs a normal search and finds the previous result", function(done) { + it("performs a normal search and finds the previous result", function (done) { // Page 14 (with page index 13) contains five results. By default, the // first result (match index 0) is selected, so the previous result // should be the fifth result (match index 4). @@ -161,7 +161,7 @@ describe("pdf_find_controller", function() { }).then(done); }); - it("performs a case sensitive search", function(done) { + it("performs a case sensitive search", function (done) { testSearch({ parameters: { query: "Dynamic", @@ -178,7 +178,7 @@ describe("pdf_find_controller", function() { }).then(done); }); - it("performs an entire word search", function(done) { + it("performs an entire word search", function (done) { // Page 13 contains both 'Government' and 'Governmental', so the latter // should not be found with entire word search. testSearch({ @@ -197,7 +197,7 @@ describe("pdf_find_controller", function() { }).then(done); }); - it("performs a multiple term (no phrase) search", function(done) { + it("performs a multiple term (no phrase) search", function (done) { // Page 9 contains 'alternate' and pages 6 and 9 contain 'solution'. // Both should be found for multiple term (no phrase) search. testSearch({ diff --git a/test/unit/pdf_find_utils_spec.js b/test/unit/pdf_find_utils_spec.js index f05f14204..b54b21b54 100644 --- a/test/unit/pdf_find_utils_spec.js +++ b/test/unit/pdf_find_utils_spec.js @@ -15,9 +15,9 @@ import { CharacterType, getCharacterType } from "../../web/pdf_find_utils.js"; -describe("pdf_find_utils", function() { - describe("getCharacterType", function() { - it("gets expected character types", function() { +describe("pdf_find_utils", function () { + describe("getCharacterType", function () { + it("gets expected character types", function () { const characters = { A: CharacterType.ALPHA_LETTER, a: CharacterType.ALPHA_LETTER, diff --git a/test/unit/pdf_history_spec.js b/test/unit/pdf_history_spec.js index a29cec9d2..4dc90661c 100644 --- a/test/unit/pdf_history_spec.js +++ b/test/unit/pdf_history_spec.js @@ -15,9 +15,9 @@ import { isDestArraysEqual, isDestHashesEqual } from "../../web/pdf_history.js"; -describe("pdf_history", function() { - describe("isDestHashesEqual", function() { - it("should reject non-equal destination hashes", function() { +describe("pdf_history", function () { + describe("isDestHashesEqual", function () { + it("should reject non-equal destination hashes", function () { expect(isDestHashesEqual(null, "page.157")).toEqual(false); expect(isDestHashesEqual("title.0", "page.157")).toEqual(false); expect(isDestHashesEqual("page=1&zoom=auto", "page.157")).toEqual(false); @@ -40,7 +40,7 @@ describe("pdf_history", function() { expect(isDestHashesEqual("page.157", destArrayString)).toEqual(false); }); - it("should accept equal destination hashes", function() { + it("should accept equal destination hashes", function () { expect(isDestHashesEqual("page.157", "page.157")).toEqual(true); expect(isDestHashesEqual("nameddest=page.157", "page.157")).toEqual(true); @@ -50,14 +50,14 @@ describe("pdf_history", function() { }); }); - describe("isDestArraysEqual", function() { + describe("isDestArraysEqual", function () { const firstDest = [{ num: 1, gen: 0 }, { name: "XYZ" }, 0, 375, null]; const secondDest = [{ num: 5, gen: 0 }, { name: "XYZ" }, 0, 375, null]; const thirdDest = [{ num: 1, gen: 0 }, { name: "XYZ" }, 750, 0, null]; const fourthDest = [{ num: 1, gen: 0 }, { name: "XYZ" }, 0, 375, 1.0]; const fifthDest = [{ gen: 0, num: 1 }, { name: "XYZ" }, 0, 375, null]; - it("should reject non-equal destination arrays", function() { + it("should reject non-equal destination arrays", function () { expect(isDestArraysEqual(firstDest, undefined)).toEqual(false); expect(isDestArraysEqual(firstDest, [1, 2, 3, 4, 5])).toEqual(false); @@ -66,7 +66,7 @@ describe("pdf_history", function() { expect(isDestArraysEqual(firstDest, fourthDest)).toEqual(false); }); - it("should accept equal destination arrays", function() { + it("should accept equal destination arrays", function () { expect(isDestArraysEqual(firstDest, firstDest)).toEqual(true); expect(isDestArraysEqual(firstDest, fifthDest)).toEqual(true); diff --git a/test/unit/primitives_spec.js b/test/unit/primitives_spec.js index 219a81129..19bd7274d 100644 --- a/test/unit/primitives_spec.js +++ b/test/unit/primitives_spec.js @@ -27,15 +27,15 @@ import { } from "../../src/core/primitives.js"; import { XRefMock } from "./test_utils.js"; -describe("primitives", function() { - describe("Name", function() { - it("should retain the given name", function() { +describe("primitives", function () { + describe("Name", function () { + it("should retain the given name", function () { var givenName = "Font"; var name = Name.get(givenName); expect(name.name).toEqual(givenName); }); - it("should create only one object for a name and cache it", function() { + it("should create only one object for a name and cache it", function () { var firstFont = Name.get("Font"); var secondFont = Name.get("Font"); var firstSubtype = Name.get("Subtype"); @@ -47,14 +47,14 @@ describe("primitives", function() { }); }); - describe("Cmd", function() { - it("should retain the given cmd name", function() { + describe("Cmd", function () { + it("should retain the given cmd name", function () { var givenCmd = "BT"; var cmd = Cmd.get(givenCmd); expect(cmd.cmd).toEqual(givenCmd); }); - it("should create only one object for a command and cache it", function() { + it("should create only one object for a command and cache it", function () { var firstBT = Cmd.get("BT"); var secondBT = Cmd.get("BT"); var firstET = Cmd.get("ET"); @@ -66,13 +66,13 @@ describe("primitives", function() { }); }); - describe("Dict", function() { - var checkInvalidHasValues = function(dict) { + describe("Dict", function () { + var checkInvalidHasValues = function (dict) { expect(dict.has()).toBeFalsy(); expect(dict.has("Prev")).toBeFalsy(); }; - var checkInvalidKeyValues = function(dict) { + var checkInvalidKeyValues = function (dict) { expect(dict.get()).toBeUndefined(); expect(dict.get("Prev")).toBeUndefined(); expect(dict.get("Decode", "D")).toBeUndefined(); @@ -85,7 +85,7 @@ describe("primitives", function() { var testFontFile2 = "file2"; var testFontFile3 = "file3"; - beforeAll(function(done) { + beforeAll(function (done) { emptyDict = new Dict(); dictWithSizeKey = new Dict(); @@ -99,16 +99,16 @@ describe("primitives", function() { done(); }); - afterAll(function() { + afterAll(function () { emptyDict = dictWithSizeKey = dictWithManyKeys = null; }); - it("should return invalid values for unknown keys", function() { + it("should return invalid values for unknown keys", function () { checkInvalidHasValues(emptyDict); checkInvalidKeyValues(emptyDict); }); - it("should return correct value for stored Size key", function() { + it("should return correct value for stored Size key", function () { expect(dictWithSizeKey.has("Size")).toBeTruthy(); expect(dictWithSizeKey.get("Size")).toEqual(storedSize); @@ -116,14 +116,14 @@ describe("primitives", function() { expect(dictWithSizeKey.get("Prev", "Root", "Size")).toEqual(storedSize); }); - it("should return invalid values for unknown keys when Size key is stored", function() { + it("should return invalid values for unknown keys when Size key is stored", function () { checkInvalidHasValues(dictWithSizeKey); checkInvalidKeyValues(dictWithSizeKey); }); - it("should not accept to set a key with an undefined value", function() { + it("should not accept to set a key with an undefined value", function () { const dict = new Dict(); - expect(function() { + expect(function () { dict.set("Size"); }).toThrow(new Error('Dict.set: The "value" cannot be undefined.')); @@ -132,7 +132,7 @@ describe("primitives", function() { checkInvalidKeyValues(dict); }); - it("should return correct values for multiple stored keys", function() { + it("should return correct values for multiple stored keys", function () { expect(dictWithManyKeys.has("FontFile")).toBeTruthy(); expect(dictWithManyKeys.has("FontFile2")).toBeTruthy(); expect(dictWithManyKeys.has("FontFile3")).toBeTruthy(); @@ -146,24 +146,24 @@ describe("primitives", function() { ).toEqual(testFontFile); }); - it("should asynchronously fetch unknown keys", function(done) { + it("should asynchronously fetch unknown keys", function (done) { var keyPromises = [ dictWithManyKeys.getAsync("Size"), dictWithSizeKey.getAsync("FontFile", "FontFile2", "FontFile3"), ]; Promise.all(keyPromises) - .then(function(values) { + .then(function (values) { expect(values[0]).toBeUndefined(); expect(values[1]).toBeUndefined(); done(); }) - .catch(function(reason) { + .catch(function (reason) { done.fail(reason); }); }); - it("should asynchronously fetch correct values for multiple stored keys", function(done) { + it("should asynchronously fetch correct values for multiple stored keys", function (done) { var keyPromises = [ dictWithManyKeys.getAsync("FontFile3"), dictWithManyKeys.getAsync("FontFile2", "FontFile3"), @@ -171,18 +171,18 @@ describe("primitives", function() { ]; Promise.all(keyPromises) - .then(function(values) { + .then(function (values) { expect(values[0]).toEqual(testFontFile3); expect(values[1]).toEqual(testFontFile2); expect(values[2]).toEqual(testFontFile); done(); }) - .catch(function(reason) { + .catch(function (reason) { done.fail(reason); }); }); - it("should callback for each stored key", function() { + it("should callback for each stored key", function () { var callbackSpy = jasmine.createSpy("spy on callback in dictionary"); dictWithManyKeys.forEach(callbackSpy); @@ -195,7 +195,7 @@ describe("primitives", function() { expect(callbackSpyCalls.count()).toEqual(3); }); - it("should handle keys pointing to indirect objects, both sync and async", function(done) { + it("should handle keys pointing to indirect objects, both sync and async", function (done) { var fontRef = Ref.get(1, 0); var xref = new XRefMock([{ ref: fontRef, data: testFontFile }]); var fontDict = new Dict(xref); @@ -208,16 +208,16 @@ describe("primitives", function() { fontDict .getAsync("FontFile", "FontFile2", "FontFile3") - .then(function(value) { + .then(function (value) { expect(value).toEqual(testFontFile); done(); }) - .catch(function(reason) { + .catch(function (reason) { done.fail(reason); }); }); - it("should handle arrays containing indirect objects", function() { + it("should handle arrays containing indirect objects", function () { var minCoordRef = Ref.get(1, 0), maxCoordRef = Ref.get(2, 0); var minCoord = 0, @@ -243,14 +243,14 @@ describe("primitives", function() { ]); }); - it("should get all key names", function() { + it("should get all key names", function () { var expectedKeys = ["FontFile", "FontFile2", "FontFile3"]; var keys = dictWithManyKeys.getKeys(); expect(keys.sort()).toEqual(expectedKeys); }); - it("should create only one object for Dict.empty", function() { + it("should create only one object for Dict.empty", function () { var firstDictEmpty = Dict.empty; var secondDictEmpty = Dict.empty; @@ -258,7 +258,7 @@ describe("primitives", function() { expect(firstDictEmpty).not.toBe(emptyDict); }); - it("should correctly merge dictionaries", function() { + it("should correctly merge dictionaries", function () { var expectedKeys = ["FontFile", "FontFile2", "FontFile3", "Size"]; var fontFileDict = new Dict(); @@ -275,8 +275,8 @@ describe("primitives", function() { }); }); - describe("Ref", function() { - it("should retain the stored values", function() { + describe("Ref", function () { + it("should retain the stored values", function () { var storedNum = 4; var storedGen = 2; var ref = Ref.get(storedNum, storedGen); @@ -285,14 +285,14 @@ describe("primitives", function() { }); }); - describe("RefSet", function() { - it("should have a stored value", function() { + describe("RefSet", function () { + it("should have a stored value", function () { var ref = Ref.get(4, 2); var refset = new RefSet(); refset.put(ref); expect(refset.has(ref)).toBeTruthy(); }); - it("should not have an unknown value", function() { + it("should not have an unknown value", function () { var ref = Ref.get(4, 2); var refset = new RefSet(); expect(refset.has(ref)).toBeFalsy(); @@ -303,55 +303,55 @@ describe("primitives", function() { }); }); - describe("isName", function() { - it("handles non-names", function() { + describe("isName", function () { + it("handles non-names", function () { var nonName = {}; expect(isName(nonName)).toEqual(false); }); - it("handles names", function() { + it("handles names", function () { var name = Name.get("Font"); expect(isName(name)).toEqual(true); }); - it("handles names with name check", function() { + it("handles names with name check", function () { var name = Name.get("Font"); expect(isName(name, "Font")).toEqual(true); expect(isName(name, "Subtype")).toEqual(false); }); }); - describe("isCmd", function() { - it("handles non-commands", function() { + describe("isCmd", function () { + it("handles non-commands", function () { var nonCmd = {}; expect(isCmd(nonCmd)).toEqual(false); }); - it("handles commands", function() { + it("handles commands", function () { var cmd = Cmd.get("BT"); expect(isCmd(cmd)).toEqual(true); }); - it("handles commands with cmd check", function() { + it("handles commands with cmd check", function () { var cmd = Cmd.get("BT"); expect(isCmd(cmd, "BT")).toEqual(true); expect(isCmd(cmd, "ET")).toEqual(false); }); }); - describe("isDict", function() { - it("handles non-dictionaries", function() { + describe("isDict", function () { + it("handles non-dictionaries", function () { var nonDict = {}; expect(isDict(nonDict)).toEqual(false); }); - it("handles empty dictionaries with type check", function() { + it("handles empty dictionaries with type check", function () { var dict = Dict.empty; expect(isDict(dict)).toEqual(true); expect(isDict(dict, "Page")).toEqual(false); }); - it("handles dictionaries with type check", function() { + it("handles dictionaries with type check", function () { var dict = new Dict(); dict.set("Type", Name.get("Page")); expect(isDict(dict, "Page")).toEqual(true); @@ -359,26 +359,26 @@ describe("primitives", function() { }); }); - describe("isRef", function() { - it("handles non-refs", function() { + describe("isRef", function () { + it("handles non-refs", function () { var nonRef = {}; expect(isRef(nonRef)).toEqual(false); }); - it("handles refs", function() { + it("handles refs", function () { var ref = Ref.get(1, 0); expect(isRef(ref)).toEqual(true); }); }); - describe("isRefsEqual", function() { - it("should handle Refs pointing to the same object", function() { + describe("isRefsEqual", function () { + it("should handle Refs pointing to the same object", function () { var ref1 = Ref.get(1, 0); var ref2 = Ref.get(1, 0); expect(isRefsEqual(ref1, ref2)).toEqual(true); }); - it("should handle Refs pointing to different objects", function() { + it("should handle Refs pointing to different objects", function () { var ref1 = Ref.get(1, 0); var ref2 = Ref.get(2, 0); expect(isRefsEqual(ref1, ref2)).toEqual(false); diff --git a/test/unit/stream_spec.js b/test/unit/stream_spec.js index 2e58cd3ef..c14a73cf7 100644 --- a/test/unit/stream_spec.js +++ b/test/unit/stream_spec.js @@ -16,8 +16,8 @@ import { PredictorStream, Stream } from "../../src/core/stream.js"; import { Dict } from "../../src/core/primitives.js"; -describe("stream", function() { - beforeEach(function() { +describe("stream", function () { + beforeEach(function () { jasmine.addMatchers({ toMatchTypedArray(util, customEqualityTesters) { return { @@ -47,8 +47,8 @@ describe("stream", function() { }, }); }); - describe("PredictorStream", function() { - it("should decode simple predictor data", function() { + describe("PredictorStream", function () { + it("should decode simple predictor data", function () { var dict = new Dict(); dict.set("Predictor", 12); dict.set("Colors", 1); diff --git a/test/unit/testreporter.js b/test/unit/testreporter.js index f852c6417..a1f8c9f90 100644 --- a/test/unit/testreporter.js +++ b/test/unit/testreporter.js @@ -1,7 +1,7 @@ "use strict"; // eslint-disable-next-line no-unused-vars -var TestReporter = function(browser, appPath) { +var TestReporter = function (browser, appPath) { function send(action, json, cb) { var r = new XMLHttpRequest(); // (The POST URI is ignored atm.) @@ -42,20 +42,20 @@ var TestReporter = function(browser, appPath) { send("/tellMeToQuit?path=" + escape(appPath), {}); } - this.now = function() { + this.now = function () { return new Date().getTime(); }; - this.jasmineStarted = function(suiteInfo) { + this.jasmineStarted = function (suiteInfo) { this.runnerStartTime = this.now(); sendInfo("Started tests for " + browser + "."); }; - this.suiteStarted = function(result) {}; + this.suiteStarted = function (result) {}; - this.specStarted = function(result) {}; + this.specStarted = function (result) {}; - this.specDone = function(result) { + this.specDone = function (result) { if (result.failedExpectations.length === 0) { sendResult("TEST-PASSED", result.description); } else { @@ -68,9 +68,9 @@ var TestReporter = function(browser, appPath) { } }; - this.suiteDone = function(result) {}; + this.suiteDone = function (result) {}; - this.jasmineDone = function() { + this.jasmineDone = function () { // Give the test.py some time process any queued up requests setTimeout(sendQuitRequest, 500); }; diff --git a/test/unit/type1_parser_spec.js b/test/unit/type1_parser_spec.js index 2426b1bd4..f6d2f28a7 100644 --- a/test/unit/type1_parser_spec.js +++ b/test/unit/type1_parser_spec.js @@ -17,8 +17,8 @@ import { SEAC_ANALYSIS_ENABLED } from "../../src/core/fonts.js"; import { StringStream } from "../../src/core/stream.js"; import { Type1Parser } from "../../src/core/type1_parser.js"; -describe("Type1Parser", function() { - it("splits tokens", function() { +describe("Type1Parser", function () { + it("splits tokens", function () { var stream = new StringStream("/BlueValues[-17 0]noaccess def"); var parser = new Type1Parser(stream, false, SEAC_ANALYSIS_ENABLED); expect(parser.getToken()).toEqual("/"); @@ -32,7 +32,7 @@ describe("Type1Parser", function() { expect(parser.getToken()).toEqual(null); }); - it("handles glued tokens", function() { + it("handles glued tokens", function () { var stream = new StringStream("dup/CharStrings"); var parser = new Type1Parser(stream, false, SEAC_ANALYSIS_ENABLED); expect(parser.getToken()).toEqual("dup"); @@ -40,27 +40,27 @@ describe("Type1Parser", function() { expect(parser.getToken()).toEqual("CharStrings"); }); - it("ignores whitespace", function() { + it("ignores whitespace", function () { var stream = new StringStream("\nab c\t"); var parser = new Type1Parser(stream, false, SEAC_ANALYSIS_ENABLED); expect(parser.getToken()).toEqual("ab"); expect(parser.getToken()).toEqual("c"); }); - it("parses numbers", function() { + it("parses numbers", function () { var stream = new StringStream("123"); var parser = new Type1Parser(stream, false, SEAC_ANALYSIS_ENABLED); expect(parser.readNumber()).toEqual(123); }); - it("parses booleans", function() { + it("parses booleans", function () { var stream = new StringStream("true false"); var parser = new Type1Parser(stream, false, SEAC_ANALYSIS_ENABLED); expect(parser.readBoolean()).toEqual(1); expect(parser.readBoolean()).toEqual(0); }); - it("parses number arrays", function() { + it("parses number arrays", function () { var stream = new StringStream("[1 2]"); var parser = new Type1Parser(stream, false, SEAC_ANALYSIS_ENABLED); expect(parser.readNumberArray()).toEqual([1, 2]); @@ -70,7 +70,7 @@ describe("Type1Parser", function() { expect(parser.readNumberArray()).toEqual([1, 2]); }); - it("skips comments", function() { + it("skips comments", function () { var stream = new StringStream( "%!PS-AdobeFont-1.0: CMSY10 003.002\n" + "%%Title: CMSY10\n" + @@ -81,7 +81,7 @@ describe("Type1Parser", function() { expect(parser.getToken()).toEqual("FontDirectory"); }); - it("parses font program", function() { + it("parses font program", function () { var stream = new StringStream( "/ExpansionFactor 99\n" + "/Subrs 1 array\n" + @@ -97,7 +97,7 @@ describe("Type1Parser", function() { expect(program.properties.privateData.ExpansionFactor).toEqual(99); }); - it("parses font header font matrix", function() { + it("parses font header font matrix", function () { var stream = new StringStream( "/FontMatrix [0.001 0 0 0.001 0 0 ]readonly def\n" ); @@ -107,7 +107,7 @@ describe("Type1Parser", function() { expect(props.fontMatrix).toEqual([0.001, 0, 0, 0.001, 0, 0]); }); - it("parses font header encoding", function() { + it("parses font header encoding", function () { var stream = new StringStream( "/Encoding 256 array\n" + "0 1 255 {1 index exch /.notdef put} for\n" + diff --git a/test/unit/ui_utils_spec.js b/test/unit/ui_utils_spec.js index 132aa3b72..ef2a08502 100644 --- a/test/unit/ui_utils_spec.js +++ b/test/unit/ui_utils_spec.js @@ -29,8 +29,8 @@ import { import { createObjectURL } from "../../src/shared/util.js"; import { isNodeJS } from "../../src/shared/is_node.js"; -describe("ui_utils", function() { - describe("binary search", function() { +describe("ui_utils", function () { + describe("binary search", function () { function isTrue(boolean) { return boolean; } @@ -38,28 +38,28 @@ describe("ui_utils", function() { return number > 3; } - it("empty array", function() { + it("empty array", function () { expect(binarySearchFirstItem([], isTrue)).toEqual(0); }); - it("single boolean entry", function() { + it("single boolean entry", function () { expect(binarySearchFirstItem([false], isTrue)).toEqual(1); expect(binarySearchFirstItem([true], isTrue)).toEqual(0); }); - it("three boolean entries", function() { + it("three boolean entries", function () { expect(binarySearchFirstItem([true, true, true], isTrue)).toEqual(0); expect(binarySearchFirstItem([false, true, true], isTrue)).toEqual(1); expect(binarySearchFirstItem([false, false, true], isTrue)).toEqual(2); expect(binarySearchFirstItem([false, false, false], isTrue)).toEqual(3); }); - it("three numeric entries", function() { + it("three numeric entries", function () { expect(binarySearchFirstItem([0, 1, 2], isGreater3)).toEqual(3); expect(binarySearchFirstItem([2, 3, 4], isGreater3)).toEqual(2); expect(binarySearchFirstItem([4, 5, 6], isGreater3)).toEqual(0); }); }); - describe("getPDFFileNameFromURL", function() { - it("gets PDF filename", function() { + describe("getPDFFileNameFromURL", function () { + it("gets PDF filename", function () { // Relative URL expect(getPDFFileNameFromURL("/pdfs/file1.pdf")).toEqual("file1.pdf"); // Absolute URL @@ -68,7 +68,7 @@ describe("ui_utils", function() { ).toEqual("file2.pdf"); }); - it("gets fallback filename", function() { + it("gets fallback filename", function () { // Relative URL expect(getPDFFileNameFromURL("/pdfs/file1.txt")).toEqual("document.pdf"); // Absolute URL @@ -77,7 +77,7 @@ describe("ui_utils", function() { ).toEqual("document.pdf"); }); - it("gets custom fallback filename", function() { + it("gets custom fallback filename", function () { // Relative URL expect(getPDFFileNameFromURL("/pdfs/file1.txt", "qwerty1.pdf")).toEqual( "qwerty1.pdf" @@ -94,13 +94,13 @@ describe("ui_utils", function() { expect(getPDFFileNameFromURL("/pdfs/file3.txt", "")).toEqual(""); }); - it("gets fallback filename when url is not a string", function() { + it("gets fallback filename when url is not a string", function () { expect(getPDFFileNameFromURL(null)).toEqual("document.pdf"); expect(getPDFFileNameFromURL(null, "file.pdf")).toEqual("file.pdf"); }); - it("gets PDF filename from URL containing leading/trailing whitespace", function() { + it("gets PDF filename from URL containing leading/trailing whitespace", function () { // Relative URL expect(getPDFFileNameFromURL(" /pdfs/file1.pdf ")).toEqual( "file1.pdf" @@ -111,7 +111,7 @@ describe("ui_utils", function() { ).toEqual("file2.pdf"); }); - it("gets PDF filename from query string", function() { + it("gets PDF filename from query string", function () { // Relative URL expect(getPDFFileNameFromURL("/pdfs/pdfs.html?name=file1.pdf")).toEqual( "file1.pdf" @@ -122,7 +122,7 @@ describe("ui_utils", function() { ).toEqual("file2.pdf"); }); - it("gets PDF filename from hash string", function() { + it("gets PDF filename from hash string", function () { // Relative URL expect(getPDFFileNameFromURL("/pdfs/pdfs.html#name=file1.pdf")).toEqual( "file1.pdf" @@ -133,7 +133,7 @@ describe("ui_utils", function() { ).toEqual("file2.pdf"); }); - it("gets correct PDF filename when multiple ones are present", function() { + it("gets correct PDF filename when multiple ones are present", function () { // Relative URL expect(getPDFFileNameFromURL("/pdfs/file1.pdf?name=file.pdf")).toEqual( "file1.pdf" @@ -144,7 +144,7 @@ describe("ui_utils", function() { ).toEqual("file2.pdf"); }); - it("gets PDF filename from URI-encoded data", function() { + it("gets PDF filename from URI-encoded data", function () { var encodedUrl = encodeURIComponent( "http://www.example.com/pdfs/file1.pdf" ); @@ -156,13 +156,13 @@ describe("ui_utils", function() { expect(getPDFFileNameFromURL(encodedUrlWithQuery)).toEqual("file2.pdf"); }); - it("gets PDF filename from data mistaken for URI-encoded", function() { + it("gets PDF filename from data mistaken for URI-encoded", function () { expect(getPDFFileNameFromURL("/pdfs/%AA.pdf")).toEqual("%AA.pdf"); expect(getPDFFileNameFromURL("/pdfs/%2F.pdf")).toEqual("%2F.pdf"); }); - it("gets PDF filename from (some) standard protocols", function() { + it("gets PDF filename from (some) standard protocols", function () { // HTTP expect(getPDFFileNameFromURL("http://www.example.com/file1.pdf")).toEqual( "file1.pdf" @@ -181,7 +181,7 @@ describe("ui_utils", function() { ); }); - it('gets PDF filename from query string appended to "blob:" URL', function() { + it('gets PDF filename from query string appended to "blob:" URL', function () { if (isNodeJS) { pending("Blob in not supported in Node.js."); } @@ -193,7 +193,7 @@ describe("ui_utils", function() { expect(getPDFFileNameFromURL(blobUrl + "?file.pdf")).toEqual("file.pdf"); }); - it('gets fallback filename from query string appended to "data:" URL', function() { + it('gets fallback filename from query string appended to "data:" URL', function () { var typedArray = new Uint8Array([1, 2, 3, 4, 5]); var dataUrl = createObjectURL( typedArray, @@ -214,21 +214,21 @@ describe("ui_utils", function() { }); }); - describe("EventBus", function() { - it("dispatch event", function() { + describe("EventBus", function () { + it("dispatch event", function () { var eventBus = new EventBus(); var count = 0; - eventBus.on("test", function(evt) { + eventBus.on("test", function (evt) { expect(evt).toEqual(undefined); count++; }); eventBus.dispatch("test"); expect(count).toEqual(1); }); - it("dispatch event with arguments", function() { + it("dispatch event with arguments", function () { const eventBus = new EventBus(); let count = 0; - eventBus.on("test", function(evt) { + eventBus.on("test", function (evt) { expect(evt).toEqual({ abc: 123 }); count++; }); @@ -237,42 +237,42 @@ describe("ui_utils", function() { }); expect(count).toEqual(1); }); - it("dispatch different event", function() { + it("dispatch different event", function () { var eventBus = new EventBus(); var count = 0; - eventBus.on("test", function() { + eventBus.on("test", function () { count++; }); eventBus.dispatch("nottest"); expect(count).toEqual(0); }); - it("dispatch event multiple times", function() { + it("dispatch event multiple times", function () { var eventBus = new EventBus(); var count = 0; eventBus.dispatch("test"); - eventBus.on("test", function() { + eventBus.on("test", function () { count++; }); eventBus.dispatch("test"); eventBus.dispatch("test"); expect(count).toEqual(2); }); - it("dispatch event to multiple handlers", function() { + it("dispatch event to multiple handlers", function () { var eventBus = new EventBus(); var count = 0; - eventBus.on("test", function() { + eventBus.on("test", function () { count++; }); - eventBus.on("test", function() { + eventBus.on("test", function () { count++; }); eventBus.dispatch("test"); expect(count).toEqual(2); }); - it("dispatch to detached", function() { + it("dispatch to detached", function () { var eventBus = new EventBus(); var count = 0; - var listener = function() { + var listener = function () { count++; }; eventBus.on("test", listener); @@ -281,27 +281,27 @@ describe("ui_utils", function() { eventBus.dispatch("test"); expect(count).toEqual(1); }); - it("dispatch to wrong detached", function() { + it("dispatch to wrong detached", function () { var eventBus = new EventBus(); var count = 0; - eventBus.on("test", function() { + eventBus.on("test", function () { count++; }); eventBus.dispatch("test"); - eventBus.off("test", function() { + eventBus.off("test", function () { count++; }); eventBus.dispatch("test"); expect(count).toEqual(2); }); - it("dispatch to detached during handling", function() { + it("dispatch to detached during handling", function () { var eventBus = new EventBus(); var count = 0; - var listener1 = function() { + var listener1 = function () { eventBus.off("test", listener2); count++; }; - var listener2 = function() { + var listener2 = function () { eventBus.off("test", listener1); count++; }; @@ -312,13 +312,13 @@ describe("ui_utils", function() { expect(count).toEqual(2); }); - it("should not re-dispatch to DOM", function(done) { + it("should not re-dispatch to DOM", function (done) { if (isNodeJS) { pending("Document in not supported in Node.js."); } const eventBus = new EventBus(); let count = 0; - eventBus.on("test", function(evt) { + eventBus.on("test", function (evt) { expect(evt).toEqual(undefined); count++; }); @@ -338,8 +338,8 @@ describe("ui_utils", function() { }); }); - describe("isValidRotation", function() { - it("should reject non-integer angles", function() { + describe("isValidRotation", function () { + it("should reject non-integer angles", function () { expect(isValidRotation()).toEqual(false); expect(isValidRotation(null)).toEqual(false); expect(isValidRotation(NaN)).toEqual(false); @@ -348,12 +348,12 @@ describe("ui_utils", function() { expect(isValidRotation(90.5)).toEqual(false); }); - it("should reject non-multiple of 90 degree angles", function() { + it("should reject non-multiple of 90 degree angles", function () { expect(isValidRotation(45)).toEqual(false); expect(isValidRotation(-123)).toEqual(false); }); - it("should accept valid angles", function() { + it("should accept valid angles", function () { expect(isValidRotation(0)).toEqual(true); expect(isValidRotation(90)).toEqual(true); expect(isValidRotation(-270)).toEqual(true); @@ -361,8 +361,8 @@ describe("ui_utils", function() { }); }); - describe("isPortraitOrientation", function() { - it("should be portrait orientation", function() { + describe("isPortraitOrientation", function () { + it("should be portrait orientation", function () { expect( isPortraitOrientation({ width: 200, @@ -378,7 +378,7 @@ describe("ui_utils", function() { ).toEqual(true); }); - it("should be landscape orientation", function() { + it("should be landscape orientation", function () { expect( isPortraitOrientation({ width: 600, @@ -388,27 +388,27 @@ describe("ui_utils", function() { }); }); - describe("waitOnEventOrTimeout", function() { + describe("waitOnEventOrTimeout", function () { let eventBus; - beforeAll(function(done) { + beforeAll(function (done) { eventBus = new EventBus(); done(); }); - afterAll(function() { + afterAll(function () { eventBus = null; }); - it("should reject invalid parameters", function(done) { + it("should reject invalid parameters", function (done) { const invalidTarget = waitOnEventOrTimeout({ target: "window", name: "DOMContentLoaded", }).then( - function() { + function () { throw new Error("Should reject invalid parameters."); }, - function(reason) { + function (reason) { expect(reason instanceof Error).toEqual(true); } ); @@ -417,10 +417,10 @@ describe("ui_utils", function() { target: eventBus, name: "", }).then( - function() { + function () { throw new Error("Should reject invalid parameters."); }, - function(reason) { + function (reason) { expect(reason instanceof Error).toEqual(true); } ); @@ -430,10 +430,10 @@ describe("ui_utils", function() { name: "pagerendered", delay: -1000, }).then( - function() { + function () { throw new Error("Should reject invalid parameters."); }, - function(reason) { + function (reason) { expect(reason instanceof Error).toEqual(true); } ); @@ -444,7 +444,7 @@ describe("ui_utils", function() { ); }); - it("should resolve on event, using the DOM", function(done) { + it("should resolve on event, using the DOM", function (done) { if (isNodeJS) { pending("Document in not supported in Node.js."); } @@ -458,13 +458,13 @@ describe("ui_utils", function() { // Immediately dispatch the expected event. button.click(); - buttonClicked.then(function(type) { + buttonClicked.then(function (type) { expect(type).toEqual(WaitOnType.EVENT); done(); }, done.fail); }); - it("should resolve on timeout, using the DOM", function(done) { + it("should resolve on timeout, using the DOM", function (done) { if (isNodeJS) { pending("Document in not supported in Node.js."); } @@ -477,13 +477,13 @@ describe("ui_utils", function() { }); // Do *not* dispatch the event, and wait for the timeout. - buttonClicked.then(function(type) { + buttonClicked.then(function (type) { expect(type).toEqual(WaitOnType.TIMEOUT); done(); }, done.fail); }); - it("should resolve on event, using the EventBus", function(done) { + it("should resolve on event, using the EventBus", function (done) { const pageRendered = waitOnEventOrTimeout({ target: eventBus, name: "pagerendered", @@ -492,13 +492,13 @@ describe("ui_utils", function() { // Immediately dispatch the expected event. eventBus.dispatch("pagerendered"); - pageRendered.then(function(type) { + pageRendered.then(function (type) { expect(type).toEqual(WaitOnType.EVENT); done(); }, done.fail); }); - it("should resolve on timeout, using the EventBus", function(done) { + it("should resolve on timeout, using the EventBus", function (done) { const pageRendered = waitOnEventOrTimeout({ target: eventBus, name: "pagerendered", @@ -506,15 +506,15 @@ describe("ui_utils", function() { }); // Do *not* dispatch the event, and wait for the timeout. - pageRendered.then(function(type) { + pageRendered.then(function (type) { expect(type).toEqual(WaitOnType.TIMEOUT); done(); }, done.fail); }); }); - describe("getPageSizeInches", function() { - it("gets page size (in inches)", function() { + describe("getPageSizeInches", function () { + it("gets page size (in inches)", function () { const page = { view: [0, 0, 595.28, 841.89], userUnit: 1.0, @@ -526,7 +526,7 @@ describe("ui_utils", function() { expect(+height.toPrecision(4)).toEqual(11.69); }); - it("gets page size (in inches), for non-default /Rotate entry", function() { + it("gets page size (in inches), for non-default /Rotate entry", function () { const pdfPage1 = { view: [0, 0, 612, 792], userUnit: 1, rotate: 0 }; const { width: width1, height: height1 } = getPageSizeInches(pdfPage1); @@ -541,7 +541,7 @@ describe("ui_utils", function() { }); }); - describe("getVisibleElements", function() { + describe("getVisibleElements", function () { // These values are based on margin/border values in the CSS, but there // isn't any real need for them to be; they just need to take *some* value. const BORDER_WIDTH = 9; @@ -576,7 +576,7 @@ describe("ui_utils", function() { let lineTop = 0, id = 0; for (const line of lines) { - const lineHeight = line.reduce(function(maxHeight, pair) { + const lineHeight = line.reduce(function (maxHeight, pair) { return Math.max(maxHeight, pair[1]); }, 0); let offsetLeft = -BORDER_WIDTH; @@ -640,7 +640,7 @@ describe("ui_utils", function() { // test to the slower implementation above, for a range of scroll viewport // sizes and positions. function scrollOverDocument(pages, horizontally = false) { - const size = pages.reduce(function(max, { div }) { + const size = pages.reduce(function (max, { div }) { return Math.max( max, horizontally @@ -677,7 +677,7 @@ describe("ui_utils", function() { } } - it("with pages of varying height", function() { + it("with pages of varying height", function () { const pages = makePages([ [ [50, 20], @@ -699,7 +699,7 @@ describe("ui_utils", function() { scrollOverDocument(pages); }); - it("widescreen challenge", function() { + it("widescreen challenge", function () { const pages = makePages([ [ [10, 50], @@ -726,7 +726,7 @@ describe("ui_utils", function() { scrollOverDocument(pages); }); - it("works with horizontal scrolling", function() { + it("works with horizontal scrolling", function () { const pages = makePages([ [ [10, 50], @@ -737,7 +737,7 @@ describe("ui_utils", function() { scrollOverDocument(pages, true); }); - it("handles `sortByVisibility` correctly", function() { + it("handles `sortByVisibility` correctly", function () { const scrollEl = { scrollTop: 75, scrollLeft: 0, @@ -765,7 +765,7 @@ describe("ui_utils", function() { expect(viewsSortedOrder).toEqual([1, 2, 0]); }); - it("handles views being empty", function() { + it("handles views being empty", function () { const scrollEl = { scrollTop: 10, scrollLeft: 0, @@ -781,7 +781,7 @@ describe("ui_utils", function() { }); }); - it("handles all views being hidden (without errors)", function() { + it("handles all views being hidden (without errors)", function () { const scrollEl = { scrollTop: 100000, scrollLeft: 0, @@ -799,7 +799,7 @@ describe("ui_utils", function() { // This sub-suite is for a notionally internal helper function for // getVisibleElements. - describe("backtrackBeforeAllVisibleElements", function() { + describe("backtrackBeforeAllVisibleElements", function () { // Layout elements common to all tests const tallPage = [10, 50]; const shortPage = [10, 10]; @@ -821,7 +821,7 @@ describe("ui_utils", function() { // These tests refer to cases enumerated in the comments of // backtrackBeforeAllVisibleElements. - it("handles case 1", function() { + it("handles case 1", function () { const pages = makePages([ [ [10, 20], @@ -851,7 +851,7 @@ describe("ui_utils", function() { ).toEqual(4); }); - it("handles case 2", function() { + it("handles case 2", function () { const pages = makePages([ [ [10, 20], @@ -880,7 +880,7 @@ describe("ui_utils", function() { ).toEqual(4); }); - it("handles case 3", function() { + it("handles case 3", function () { const pages = makePages([ [ [10, 20], @@ -909,7 +909,7 @@ describe("ui_utils", function() { ).toEqual(4); }); - it("handles case 4", function() { + it("handles case 4", function () { const pages = makePages([ [ [10, 20], @@ -940,40 +940,40 @@ describe("ui_utils", function() { }); }); - describe("moveToEndOfArray", function() { - it("works on empty arrays", function() { + describe("moveToEndOfArray", function () { + it("works on empty arrays", function () { const data = []; - moveToEndOfArray(data, function() {}); + moveToEndOfArray(data, function () {}); expect(data).toEqual([]); }); - it("works when moving everything", function() { + it("works when moving everything", function () { const data = [1, 2, 3, 4, 5]; - moveToEndOfArray(data, function() { + moveToEndOfArray(data, function () { return true; }); expect(data).toEqual([1, 2, 3, 4, 5]); }); - it("works when moving some things", function() { + it("works when moving some things", function () { const data = [1, 2, 3, 4, 5]; - moveToEndOfArray(data, function(x) { + moveToEndOfArray(data, function (x) { return x % 2 === 0; }); expect(data).toEqual([1, 3, 5, 2, 4]); }); - it("works when moving one thing", function() { + it("works when moving one thing", function () { const data = [1, 2, 3, 4, 5]; - moveToEndOfArray(data, function(x) { + moveToEndOfArray(data, function (x) { return x === 1; }); expect(data).toEqual([2, 3, 4, 5, 1]); }); - it("works when moving nothing", function() { + it("works when moving nothing", function () { const data = [1, 2, 3, 4, 5]; - moveToEndOfArray(data, function(x) { + moveToEndOfArray(data, function (x) { return x === 0; }); expect(data).toEqual([1, 2, 3, 4, 5]); diff --git a/test/unit/unicode_spec.js b/test/unit/unicode_spec.js index fa8a45aea..72054a970 100644 --- a/test/unit/unicode_spec.js +++ b/test/unit/unicode_spec.js @@ -25,16 +25,16 @@ import { reverseIfRtl, } from "../../src/core/unicode.js"; -describe("unicode", function() { - describe("mapSpecialUnicodeValues", function() { - it("should not re-map normal Unicode values", function() { +describe("unicode", function () { + describe("mapSpecialUnicodeValues", function () { + it("should not re-map normal Unicode values", function () { // A expect(mapSpecialUnicodeValues(0x0041)).toEqual(0x0041); // fi expect(mapSpecialUnicodeValues(0xfb01)).toEqual(0xfb01); }); - it("should re-map special Unicode values", function() { + it("should re-map special Unicode values", function () { // copyrightsans => copyright expect(mapSpecialUnicodeValues(0xf8e9)).toEqual(0x00a9); // Private Use Area characters @@ -42,25 +42,25 @@ describe("unicode", function() { }); }); - describe("getUnicodeForGlyph", function() { + describe("getUnicodeForGlyph", function () { var standardMap, dingbatsMap; - beforeAll(function(done) { + beforeAll(function (done) { standardMap = getGlyphsUnicode(); dingbatsMap = getDingbatsGlyphsUnicode(); done(); }); - afterAll(function() { + afterAll(function () { standardMap = dingbatsMap = null; }); - it("should get Unicode values for valid glyph names", function() { + it("should get Unicode values for valid glyph names", function () { expect(getUnicodeForGlyph("A", standardMap)).toEqual(0x0041); expect(getUnicodeForGlyph("a1", dingbatsMap)).toEqual(0x2701); }); - it("should recover Unicode values from uniXXXX/uXXXX{XX} glyph names", function() { + it("should recover Unicode values from uniXXXX/uXXXX{XX} glyph names", function () { expect(getUnicodeForGlyph("uni0041", standardMap)).toEqual(0x0041); expect(getUnicodeForGlyph("u0041", standardMap)).toEqual(0x0041); @@ -68,50 +68,50 @@ describe("unicode", function() { expect(getUnicodeForGlyph("u2701", dingbatsMap)).toEqual(0x2701); }); - it("should not get Unicode values for invalid glyph names", function() { + it("should not get Unicode values for invalid glyph names", function () { expect(getUnicodeForGlyph("Qwerty", standardMap)).toEqual(-1); expect(getUnicodeForGlyph("Qwerty", dingbatsMap)).toEqual(-1); }); }); - describe("getUnicodeRangeFor", function() { - it("should get correct Unicode range", function() { + describe("getUnicodeRangeFor", function () { + it("should get correct Unicode range", function () { // A (Basic Latin) expect(getUnicodeRangeFor(0x0041)).toEqual(0); // fi (Alphabetic Presentation Forms) expect(getUnicodeRangeFor(0xfb01)).toEqual(62); }); - it("should not get a Unicode range", function() { + it("should not get a Unicode range", function () { expect(getUnicodeRangeFor(0x05ff)).toEqual(-1); }); }); - describe("getNormalizedUnicodes", function() { + describe("getNormalizedUnicodes", function () { var NormalizedUnicodes; - beforeAll(function(done) { + beforeAll(function (done) { NormalizedUnicodes = getNormalizedUnicodes(); done(); }); - afterAll(function() { + afterAll(function () { NormalizedUnicodes = null; }); - it("should get normalized Unicode values for ligatures", function() { + it("should get normalized Unicode values for ligatures", function () { // fi => f + i expect(NormalizedUnicodes["\uFB01"]).toEqual("fi"); // Arabic expect(NormalizedUnicodes["\u0675"]).toEqual("\u0627\u0674"); }); - it("should not normalize standard characters", function() { + it("should not normalize standard characters", function () { expect(NormalizedUnicodes["A"]).toEqual(undefined); }); }); - describe("reverseIfRtl", function() { + describe("reverseIfRtl", function () { var NormalizedUnicodes; function getGlyphUnicode(char) { @@ -121,16 +121,16 @@ describe("unicode", function() { return char; } - beforeAll(function(done) { + beforeAll(function (done) { NormalizedUnicodes = getNormalizedUnicodes(); done(); }); - afterAll(function() { + afterAll(function () { NormalizedUnicodes = null; }); - it("should not reverse LTR characters", function() { + it("should not reverse LTR characters", function () { var A = getGlyphUnicode("A"); expect(reverseIfRtl(A)).toEqual("A"); @@ -138,7 +138,7 @@ describe("unicode", function() { expect(reverseIfRtl(fi)).toEqual("fi"); }); - it("should reverse RTL characters", function() { + it("should reverse RTL characters", function () { // Hebrew (no-op, since it's not a combined character) var heAlef = getGlyphUnicode("\u05D0"); expect(reverseIfRtl(heAlef)).toEqual("\u05D0"); diff --git a/test/unit/util_spec.js b/test/unit/util_spec.js index 99fb3fe97..eca89e41f 100644 --- a/test/unit/util_spec.js +++ b/test/unit/util_spec.js @@ -29,20 +29,20 @@ import { stringToPDFString, } from "../../src/shared/util.js"; -describe("util", function() { - describe("bytesToString", function() { - it("handles non-array arguments", function() { - expect(function() { +describe("util", function () { + describe("bytesToString", function () { + it("handles non-array arguments", function () { + expect(function () { bytesToString(null); }).toThrow(new Error("Invalid argument for bytesToString")); }); - it("handles array arguments with a length not exceeding the maximum", function() { + it("handles array arguments with a length not exceeding the maximum", function () { expect(bytesToString(new Uint8Array([]))).toEqual(""); expect(bytesToString(new Uint8Array([102, 111, 111]))).toEqual("foo"); }); - it("handles array arguments with a length exceeding the maximum", function() { + it("handles array arguments with a length exceeding the maximum", function () { const length = 10000; // Larger than MAX_ARGUMENT_COUNT = 8192. // Create an array with `length` 'a' character codes. @@ -59,13 +59,13 @@ describe("util", function() { }); }); - describe("isArrayBuffer", function() { - it("handles array buffer values", function() { + describe("isArrayBuffer", function () { + it("handles array buffer values", function () { expect(isArrayBuffer(new ArrayBuffer(0))).toEqual(true); expect(isArrayBuffer(new Uint8Array(0))).toEqual(true); }); - it("handles non-array buffer values", function() { + it("handles non-array buffer values", function () { expect(isArrayBuffer("true")).toEqual(false); expect(isArrayBuffer(1)).toEqual(false); expect(isArrayBuffer(null)).toEqual(false); @@ -73,13 +73,13 @@ describe("util", function() { }); }); - describe("isBool", function() { - it("handles boolean values", function() { + describe("isBool", function () { + it("handles boolean values", function () { expect(isBool(true)).toEqual(true); expect(isBool(false)).toEqual(true); }); - it("handles non-boolean values", function() { + it("handles non-boolean values", function () { expect(isBool("true")).toEqual(false); expect(isBool("false")).toEqual(false); expect(isBool(1)).toEqual(false); @@ -89,18 +89,18 @@ describe("util", function() { }); }); - describe("isEmptyObj", function() { - it("handles empty objects", function() { + describe("isEmptyObj", function () { + it("handles empty objects", function () { expect(isEmptyObj({})).toEqual(true); }); - it("handles non-empty objects", function() { + it("handles non-empty objects", function () { expect(isEmptyObj({ foo: "bar" })).toEqual(false); }); }); - describe("isNum", function() { - it("handles numeric values", function() { + describe("isNum", function () { + it("handles numeric values", function () { expect(isNum(1)).toEqual(true); expect(isNum(0)).toEqual(true); expect(isNum(-1)).toEqual(true); @@ -108,7 +108,7 @@ describe("util", function() { expect(isNum(12.34)).toEqual(true); }); - it("handles non-numeric values", function() { + it("handles non-numeric values", function () { expect(isNum("true")).toEqual(false); expect(isNum(true)).toEqual(false); expect(isNum(null)).toEqual(false); @@ -116,13 +116,13 @@ describe("util", function() { }); }); - describe("isString", function() { - it("handles string values", function() { + describe("isString", function () { + it("handles string values", function () { expect(isString("foo")).toEqual(true); expect(isString("")).toEqual(true); }); - it("handles non-string values", function() { + it("handles non-string values", function () { expect(isString(true)).toEqual(false); expect(isString(1)).toEqual(false); expect(isString(null)).toEqual(false); @@ -130,44 +130,44 @@ describe("util", function() { }); }); - describe("string32", function() { - it("converts unsigned 32-bit integers to strings", function() { + describe("string32", function () { + it("converts unsigned 32-bit integers to strings", function () { expect(string32(0x74727565)).toEqual("true"); expect(string32(0x74797031)).toEqual("typ1"); expect(string32(0x4f54544f)).toEqual("OTTO"); }); }); - describe("stringToBytes", function() { - it("handles non-string arguments", function() { - expect(function() { + describe("stringToBytes", function () { + it("handles non-string arguments", function () { + expect(function () { stringToBytes(null); }).toThrow(new Error("Invalid argument for stringToBytes")); }); - it("handles string arguments", function() { + it("handles string arguments", function () { expect(stringToBytes("")).toEqual(new Uint8Array([])); expect(stringToBytes("foo")).toEqual(new Uint8Array([102, 111, 111])); }); }); - describe("stringToPDFString", function() { - it("handles ISO Latin 1 strings", function() { + describe("stringToPDFString", function () { + it("handles ISO Latin 1 strings", function () { const str = "\x8Dstring\x8E"; expect(stringToPDFString(str)).toEqual("\u201Cstring\u201D"); }); - it("handles UTF-16 big-endian strings", function() { + it("handles UTF-16 big-endian strings", function () { const str = "\xFE\xFF\x00\x73\x00\x74\x00\x72\x00\x69\x00\x6E\x00\x67"; expect(stringToPDFString(str)).toEqual("string"); }); - it("handles UTF-16 little-endian strings", function() { + it("handles UTF-16 little-endian strings", function () { const str = "\xFF\xFE\x73\x00\x74\x00\x72\x00\x69\x00\x6E\x00\x67\x00"; expect(stringToPDFString(str)).toEqual("string"); }); - it("handles empty strings", function() { + it("handles empty strings", function () { // ISO Latin 1 const str1 = ""; expect(stringToPDFString(str1)).toEqual(""); @@ -182,44 +182,44 @@ describe("util", function() { }); }); - describe("removeNullCharacters", function() { - it("should not modify string without null characters", function() { + describe("removeNullCharacters", function () { + it("should not modify string without null characters", function () { const str = "string without null chars"; expect(removeNullCharacters(str)).toEqual("string without null chars"); }); - it("should modify string with null characters", function() { + it("should modify string with null characters", function () { const str = "string\x00With\x00Null\x00Chars"; expect(removeNullCharacters(str)).toEqual("stringWithNullChars"); }); }); - describe("ReadableStream", function() { - it("should return an Object", function() { + describe("ReadableStream", function () { + it("should return an Object", function () { const readable = new ReadableStream(); expect(typeof readable).toEqual("object"); }); - it("should have property getReader", function() { + it("should have property getReader", function () { const readable = new ReadableStream(); expect(typeof readable.getReader).toEqual("function"); }); }); - describe("URL", function() { - it("should return an Object", function() { + describe("URL", function () { + it("should return an Object", function () { const url = new URL("https://example.com"); expect(typeof url).toEqual("object"); }); - it("should have property `href`", function() { + it("should have property `href`", function () { const url = new URL("https://example.com"); expect(typeof url.href).toEqual("string"); }); }); - describe("isSameOrigin", function() { - it("handles invalid base URLs", function() { + describe("isSameOrigin", function () { + it("handles invalid base URLs", function () { // The base URL is not valid. expect(isSameOrigin("/foo", "/bar")).toEqual(false); @@ -227,7 +227,7 @@ describe("util", function() { expect(isSameOrigin("blob:foo", "/bar")).toEqual(false); }); - it("correctly checks if the origin of both URLs matches", function() { + it("correctly checks if the origin of both URLs matches", function () { expect( isSameOrigin( "https://www.mozilla.org/foo", @@ -243,18 +243,18 @@ describe("util", function() { }); }); - describe("createValidAbsoluteUrl", function() { - it("handles invalid URLs", function() { + describe("createValidAbsoluteUrl", function () { + it("handles invalid URLs", function () { expect(createValidAbsoluteUrl(undefined, undefined)).toEqual(null); expect(createValidAbsoluteUrl(null, null)).toEqual(null); expect(createValidAbsoluteUrl("/foo", "/bar")).toEqual(null); }); - it("handles URLs that do not use a whitelisted protocol", function() { + it("handles URLs that do not use a whitelisted protocol", function () { expect(createValidAbsoluteUrl("magnet:?foo", null)).toEqual(null); }); - it("correctly creates a valid URL for whitelisted protocols", function() { + it("correctly creates a valid URL for whitelisted protocols", function () { // `http` protocol expect( createValidAbsoluteUrl("http://www.mozilla.org/foo", null) @@ -295,14 +295,14 @@ describe("util", function() { }); }); - describe("createPromiseCapability", function() { - it("should resolve with correct data", function(done) { + describe("createPromiseCapability", function () { + it("should resolve with correct data", function (done) { const promiseCapability = createPromiseCapability(); expect(promiseCapability.settled).toEqual(false); promiseCapability.resolve({ test: "abc" }); - promiseCapability.promise.then(function(data) { + promiseCapability.promise.then(function (data) { expect(promiseCapability.settled).toEqual(true); expect(data).toEqual({ test: "abc" }); @@ -310,13 +310,13 @@ describe("util", function() { }, done.fail); }); - it("should reject with correct reason", function(done) { + it("should reject with correct reason", function (done) { const promiseCapability = createPromiseCapability(); expect(promiseCapability.settled).toEqual(false); promiseCapability.reject(new Error("reason")); - promiseCapability.promise.then(done.fail, function(reason) { + promiseCapability.promise.then(done.fail, function (reason) { expect(promiseCapability.settled).toEqual(true); expect(reason instanceof Error).toEqual(true); diff --git a/test/webbrowser.js b/test/webbrowser.js index cc03732be..97de33619 100644 --- a/test/webbrowser.js +++ b/test/webbrowser.js @@ -41,14 +41,14 @@ function WebBrowser(name, execPath, headless) { this.uniqStringId = "webbrowser" + crypto.randomBytes(32).toString("hex"); } WebBrowser.prototype = { - start: function(url) { + start: function (url) { this.tmpDir = path.join(os.tmpdir(), tempDirPrefix + this.name); if (!fs.existsSync(this.tmpDir)) { fs.mkdirSync(this.tmpDir); } this.startProcess(url); }, - getProfileDir: function() { + getProfileDir: function () { if (!this.profileDir) { var profileDir = path.join(this.tmpDir, "profile"); if (fs.existsSync(profileDir)) { @@ -60,11 +60,11 @@ WebBrowser.prototype = { } return this.profileDir; }, - buildArguments: function(url) { + buildArguments: function (url) { return [url]; }, - setupProfileDir: function(dir) {}, - startProcess: function(url) { + setupProfileDir: function (dir) {}, + startProcess: function (url) { console.assert(!this.process, "startProcess may be called only once"); var args = this.buildArguments(url); @@ -76,7 +76,7 @@ WebBrowser.prototype = { this.process.on( "exit", - function(code, signal) { + function (code, signal) { this.process = null; var exitInfo = code !== null @@ -93,7 +93,7 @@ WebBrowser.prototype = { }.bind(this) ); }, - cleanup: function() { + cleanup: function () { console.assert( this.requestedExit, "cleanup should only be called after an explicit stop() request" @@ -123,7 +123,7 @@ WebBrowser.prototype = { this.log("Clean-up finished. Going to call callback..."); this.callback(); }, - stop: function(callback) { + stop: function (callback) { console.assert(this.tmpDir, ".start() must be called before stop()"); // Require the callback to ensure that callers do not make any assumptions // on the state of this browser instance until the callback is called. @@ -145,7 +145,7 @@ WebBrowser.prototype = { this.killProcessUnknownPid(this.cleanup.bind(this)); } }, - killProcessUnknownPid: function(callback) { + killProcessUnknownPid: function (callback) { this.log("pid unknown, killing processes matching " + this.uniqStringId); var cmdKillAll, cmdCheckAllKilled, isAllKilled; @@ -168,13 +168,13 @@ WebBrowser.prototype = { file: "wmic", args: wmicPrefix.concat(["get", "CommandLine"]), }; - isAllKilled = function(exitCode, stdout) { + isAllKilled = function (exitCode, stdout) { return !stdout.includes(this.uniqStringId); }.bind(this); } else { cmdKillAll = { file: "pkill", args: ["-f", this.uniqStringId] }; cmdCheckAllKilled = { file: "pgrep", args: ["-f", this.uniqStringId] }; - isAllKilled = function(pgrepStatus) { + isAllKilled = function (pgrepStatus) { return pgrepStatus === 1; // "No process matched.", per man pgrep. }; } @@ -200,7 +200,7 @@ WebBrowser.prototype = { function checkAlive(firstExitCode, firstStdout) { execAsyncNoStdin( cmdCheckAllKilled, - function(exitCode, stdout) { + function (exitCode, stdout) { if (isAllKilled(exitCode, stdout)) { callback(); } else if (Date.now() - killDateStart > 10000) { @@ -220,7 +220,7 @@ WebBrowser.prototype = { }.bind(this) ); }, - log: function(msg) { + log: function (msg) { console.log("[" + this.name + "] " + msg); }, }; @@ -237,7 +237,7 @@ function FirefoxBrowser(name, execPath, headless) { WebBrowser.call(this, name, execPath, headless); } FirefoxBrowser.prototype = Object.create(WebBrowser.prototype); -FirefoxBrowser.prototype.buildArguments = function(url) { +FirefoxBrowser.prototype.buildArguments = function (url) { var profileDir = this.getProfileDir(); var args = []; if (os.platform() === "darwin") { @@ -249,7 +249,7 @@ FirefoxBrowser.prototype.buildArguments = function(url) { args.push("-no-remote", "-profile", profileDir, url); return args; }; -FirefoxBrowser.prototype.setupProfileDir = function(dir) { +FirefoxBrowser.prototype.setupProfileDir = function (dir) { testUtils.copySubtreeSync(firefoxResourceDir, dir); }; @@ -263,7 +263,7 @@ function ChromiumBrowser(name, execPath, headless) { WebBrowser.call(this, name, execPath, headless); } ChromiumBrowser.prototype = Object.create(WebBrowser.prototype); -ChromiumBrowser.prototype.buildArguments = function(url) { +ChromiumBrowser.prototype.buildArguments = function (url) { var profileDir = this.getProfileDir(); var crashDumpsDir = path.join(this.tmpDir, "crash_dumps"); var args = [ @@ -288,7 +288,7 @@ ChromiumBrowser.prototype.buildArguments = function(url) { return args; }; -WebBrowser.create = function(desc) { +WebBrowser.create = function (desc) { var name = desc.name; var execPath = fs.realpathSync(desc.path); if (!execPath) { diff --git a/test/webserver.js b/test/webserver.js index 54f69e26e..9e73faf0c 100644 --- a/test/webserver.js +++ b/test/webserver.js @@ -53,7 +53,7 @@ function WebServer() { }; } WebServer.prototype = { - start: function(callback) { + start: function (callback) { this._ensureNonZeroPort(); this.server = http.createServer(this._handler.bind(this)); this.server.listen(this.port, this.host, callback); @@ -61,11 +61,11 @@ WebServer.prototype = { "Server running at http://" + this.host + ":" + this.port + "/" ); }, - stop: function(callback) { + stop: function (callback) { this.server.close(callback); this.server = null; }, - _ensureNonZeroPort: function() { + _ensureNonZeroPort: function () { if (!this.port) { // If port is 0, a random port will be chosen instead. Do not set a host // name to make sure that the port is synchronously set by .listen(). @@ -78,7 +78,7 @@ WebServer.prototype = { server.close(); } }, - _handler: function(req, res) { + _handler: function (req, res) { var url = req.url.replace(/\/\//g, "/"); var urlParts = /([^?]*)((?:\?(.*))?)/.exec(url); try { @@ -107,7 +107,7 @@ WebServer.prototype = { res.end("Unsupported request method", "utf8"); return; } - var handled = methodHooks.some(function(hook) { + var handled = methodHooks.some(function (hook) { return hook(req, res); }); if (handled) { @@ -218,7 +218,7 @@ WebServer.prototype = { return; } var all = queryPart === "all"; - fs.readdir(dir, function(err, files) { + fs.readdir(dir, function (err, files) { if (err) { res.end(); return; @@ -232,7 +232,7 @@ WebServer.prototype = { if (pathPart !== "/") { res.write('..
\n'); } - files.forEach(function(file) { + files.forEach(function (file) { var stat; var item = pathPart + file; var href = ""; @@ -286,7 +286,7 @@ WebServer.prototype = { function serveRequestedFile(reqFilePath) { var stream = fs.createReadStream(reqFilePath, { flags: "rs" }); - stream.on("error", function(error) { + stream.on("error", function (error) { res.writeHead(500); res.end(); }); @@ -316,7 +316,7 @@ WebServer.prototype = { end: end - 1, }); - stream.on("error", function(error) { + stream.on("error", function (error) { res.writeHead(500); res.end(); }); diff --git a/web/app.js b/web/app.js index d4cf74c11..504baaa98 100644 --- a/web/app.js +++ b/web/app.js @@ -855,7 +855,7 @@ const PDFViewerApplication = { this.pdfDocument .getData() - .then(function(data) { + .then(function (data) { const blob = new Blob([data], { type: "application/pdf" }); downloadManager.download(blob, url, filename); }) @@ -950,20 +950,20 @@ const PDFViewerApplication = { errorMessage.textContent = message; const closeButton = errorWrapperConfig.closeButton; - closeButton.onclick = function() { + closeButton.onclick = function () { errorWrapper.setAttribute("hidden", "true"); }; const errorMoreInfo = errorWrapperConfig.errorMoreInfo; const moreInfoButton = errorWrapperConfig.moreInfoButton; const lessInfoButton = errorWrapperConfig.lessInfoButton; - moreInfoButton.onclick = function() { + moreInfoButton.onclick = function () { errorMoreInfo.removeAttribute("hidden"); moreInfoButton.setAttribute("hidden", "true"); lessInfoButton.removeAttribute("hidden"); errorMoreInfo.style.height = errorMoreInfo.scrollHeight + "px"; }; - lessInfoButton.onclick = function() { + lessInfoButton.onclick = function () { errorMoreInfo.setAttribute("hidden", "true"); moreInfoButton.removeAttribute("hidden"); lessInfoButton.setAttribute("hidden", "true"); @@ -1036,13 +1036,13 @@ const PDFViewerApplication = { // Since the `setInitialView` call below depends on this being resolved, // fetch it early to avoid delaying initial rendering of the PDF document. - const pageLayoutPromise = pdfDocument.getPageLayout().catch(function() { + const pageLayoutPromise = pdfDocument.getPageLayout().catch(function () { /* Avoid breaking initial rendering; ignoring errors. */ }); - const pageModePromise = pdfDocument.getPageMode().catch(function() { + const pageModePromise = pdfDocument.getPageMode().catch(function () { /* Avoid breaking initial rendering; ignoring errors. */ }); - const openActionPromise = pdfDocument.getOpenAction().catch(function() { + const openActionPromise = pdfDocument.getOpenAction().catch(function () { /* Avoid breaking initial rendering; ignoring errors. */ }); @@ -1185,7 +1185,7 @@ const PDFViewerApplication = { // even if there are any errors thrown above. this.setInitialView(); }) - .then(function() { + .then(function () { // At this point, rendering of the initial page(s) should always have // started (and may even have completed). // To prevent any future issues, e.g. the document being completely @@ -1254,7 +1254,7 @@ const PDFViewerApplication = { return; } if (triggerAutoPrint) { - setTimeout(function() { + setTimeout(function () { window.print(); }); } @@ -1377,7 +1377,7 @@ const PDFViewerApplication = { ]; if (info.Producer) { const producer = info.Producer.toLowerCase(); - KNOWN_GENERATORS.some(function(generator) { + KNOWN_GENERATORS.some(function (generator) { if (!producer.includes(generator)) { return false; } @@ -1795,7 +1795,7 @@ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) { "http://mozilla.github.io", "https://mozilla.github.io", ]; - validateFileURL = function(file) { + validateFileURL = function (file) { if (file === undefined) { return; } @@ -1843,7 +1843,7 @@ async function loadFakeWorker() { function loadAndEnablePDFBug(enabledTabs) { const appConfig = PDFViewerApplication.appConfig; - return loadScript(appConfig.debuggerScriptPath).then(function() { + return loadScript(appConfig.debuggerScriptPath).then(function () { PDFBug.enable(enabledTabs); PDFBug.init({ OPS }, appConfig.mainContainer); }); @@ -1883,7 +1883,7 @@ function webViewerInitialized() { fileInput.value = null; } - fileInput.addEventListener("change", function(evt) { + fileInput.addEventListener("change", function (evt) { const files = evt.target.files; if (!files || files.length === 0) { return; @@ -1895,12 +1895,12 @@ function webViewerInitialized() { }); // Enable dragging-and-dropping a new PDF file onto the viewerContainer. - appConfig.mainContainer.addEventListener("dragover", function(evt) { + appConfig.mainContainer.addEventListener("dragover", function (evt) { evt.preventDefault(); evt.dataTransfer.dropEffect = "move"; }); - appConfig.mainContainer.addEventListener("drop", function(evt) { + appConfig.mainContainer.addEventListener("drop", function (evt) { evt.preventDefault(); const files = evt.dataTransfer.files; @@ -1950,7 +1950,7 @@ function webViewerInitialized() { appConfig.mainContainer.addEventListener( "transitionend", - function(evt) { + function (evt) { if (evt.target === /* mainContainer */ this) { PDFViewerApplication.eventBus.dispatch("resize", { source: this }); } @@ -1971,14 +1971,14 @@ function webViewerInitialized() { let webViewerOpenFileViaURL; if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) { - webViewerOpenFileViaURL = function(file) { + webViewerOpenFileViaURL = function (file) { if (file && file.lastIndexOf("file:", 0) === 0) { // file:-scheme. Load the contents in the main thread because QtWebKit // cannot load file:-URLs in a Web Worker. file:-URLs are usually loaded // very quickly, so there is no need to set up progress event listeners. PDFViewerApplication.setTitleUsingUrl(file); const xhr = new XMLHttpRequest(); - xhr.onload = function() { + xhr.onload = function () { PDFViewerApplication.open(new Uint8Array(xhr.response)); }; xhr.open("GET", file); @@ -1992,12 +1992,12 @@ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) { } }; } else if (PDFJSDev.test("MOZCENTRAL || CHROME")) { - webViewerOpenFileViaURL = function(file) { + webViewerOpenFileViaURL = function (file) { PDFViewerApplication.setTitleUsingUrl(file); PDFViewerApplication.initPassiveLoading(); }; } else { - webViewerOpenFileViaURL = function(file) { + webViewerOpenFileViaURL = function (file) { if (file) { throw new Error("Not implemented: webViewerOpenFileViaURL"); } @@ -2063,7 +2063,7 @@ function webViewerPageRendered(evt) { timestamp: evt.timestamp, }); // It is a good time to report stream and font types. - PDFViewerApplication.pdfDocument.getStats().then(function(stats) { + PDFViewerApplication.pdfDocument.getStats().then(function (stats) { PDFViewerApplication.externalServices.reportTelemetry({ type: "documentStats", stats, @@ -2130,7 +2130,7 @@ function webViewerSidebarViewChanged(evt) { const store = PDFViewerApplication.store; if (store && PDFViewerApplication.isInitialViewSet) { // Only update the storage when the document has been loaded *and* rendered. - store.set("sidebarView", evt.view).catch(function() {}); + store.set("sidebarView", evt.view).catch(function () {}); } } @@ -2147,7 +2147,7 @@ function webViewerUpdateViewarea(evt) { scrollTop: location.top, rotation: location.rotation, }) - .catch(function() { + .catch(function () { /* unable to write to storage */ }); } @@ -2169,7 +2169,7 @@ function webViewerScrollModeChanged(evt) { const store = PDFViewerApplication.store; if (store && PDFViewerApplication.isInitialViewSet) { // Only update the storage when the document has been loaded *and* rendered. - store.set("scrollMode", evt.mode).catch(function() {}); + store.set("scrollMode", evt.mode).catch(function () {}); } } @@ -2177,7 +2177,7 @@ function webViewerSpreadModeChanged(evt) { const store = PDFViewerApplication.store; if (store && PDFViewerApplication.isInitialViewSet) { // Only update the storage when the document has been loaded *and* rendered. - store.set("spreadMode", evt.mode).catch(function() {}); + store.set("spreadMode", evt.mode).catch(function () {}); } } @@ -2212,7 +2212,7 @@ function webViewerHashchange(evt) { let webViewerFileInputChange, webViewerOpenFile; if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) { - webViewerFileInputChange = function(evt) { + webViewerFileInputChange = function (evt) { if ( PDFViewerApplication.pdfViewer && PDFViewerApplication.pdfViewer.isInPresentationMode @@ -2249,7 +2249,7 @@ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) { appConfig.secondaryToolbar.downloadButton.setAttribute("hidden", "true"); }; - webViewerOpenFile = function(evt) { + webViewerOpenFile = function (evt) { const openFileInputName = PDFViewerApplication.appConfig.openFileInputName; document.getElementById(openFileInputName).click(); }; @@ -2415,7 +2415,7 @@ function setZoomDisabledTimeout() { if (zoomDisabledTimeout) { clearTimeout(zoomDisabledTimeout); } - zoomDisabledTimeout = setTimeout(function() { + zoomDisabledTimeout = setTimeout(function () { zoomDisabledTimeout = null; }, WHEEL_ZOOM_DISABLED_TIMEOUT); } @@ -2549,7 +2549,7 @@ function webViewerKeyDown(evt) { case 96: // '0' on Numpad of Swedish keyboard if (!isViewerInPresentationMode) { // keeping it unhandled (to restore page zoom to 100%) - setTimeout(function() { + setTimeout(function () { // ... and resetting the scale after browser adjusts its scale PDFViewerApplication.zoomReset(); }); diff --git a/web/app_options.js b/web/app_options.js index d1e1abd3c..66c478739 100644 --- a/web/app_options.js +++ b/web/app_options.js @@ -162,9 +162,9 @@ const defaultOptions = { cMapUrl: { /** @type {string} */ value: - (typeof PDFJSDev === "undefined" || !PDFJSDev.test("PRODUCTION") + typeof PDFJSDev === "undefined" || !PDFJSDev.test("PRODUCTION") ? "../external/bcmaps/" - : "../web/cmaps/"), + : "../web/cmaps/", kind: OptionKind.API, }, disableAutoFetch: { @@ -232,9 +232,9 @@ const defaultOptions = { workerSrc: { /** @type {string} */ value: - (typeof PDFJSDev === "undefined" || !PDFJSDev.test("PRODUCTION") + typeof PDFJSDev === "undefined" || !PDFJSDev.test("PRODUCTION") ? "../src/worker_loader.js" - : "../build/pdf.worker.js"), + : "../build/pdf.worker.js", kind: OptionKind.WORKER, }, }; @@ -249,7 +249,7 @@ if ( }; defaultOptions.locale = { /** @type {string} */ - value: (typeof navigator !== "undefined" ? navigator.language : "en-US"), + value: typeof navigator !== "undefined" ? navigator.language : "en-US", kind: OptionKind.VIEWER, }; defaultOptions.printResolution = { diff --git a/web/base_viewer.js b/web/base_viewer.js index 09257ac5a..a4af7a084 100644 --- a/web/base_viewer.js +++ b/web/base_viewer.js @@ -82,7 +82,7 @@ const DEFAULT_CACHE_SIZE = 10; function PDFPageViewBuffer(size) { const data = []; - this.push = function(view) { + this.push = function (view) { const i = data.indexOf(view); if (i >= 0) { data.splice(i, 1); @@ -99,14 +99,14 @@ function PDFPageViewBuffer(size) { * impact on the final size of the buffer; if pagesToKeep has length larger * than newSize, some of those pages will be destroyed anyway. */ - this.resize = function(newSize, pagesToKeep) { + this.resize = function (newSize, pagesToKeep) { size = newSize; if (pagesToKeep) { const pageIdsToKeep = new Set(); for (let i = 0, iMax = pagesToKeep.length; i < iMax; ++i) { pageIdsToKeep.add(pagesToKeep[i].id); } - moveToEndOfArray(data, function(page) { + moveToEndOfArray(data, function (page) { return pageIdsToKeep.has(page.id); }); } @@ -202,7 +202,7 @@ class BaseViewer { } // Prevent printing errors when 'disableAutoFetch' is set, by ensuring // that *all* pages have in fact been completely loaded. - return this._pages.every(function(pageView) { + return this._pages.every(function (pageView) { return pageView && pageView.pdfPage; }); } @@ -1042,7 +1042,7 @@ class BaseViewer { ); return false; } - return this._getVisiblePages().views.some(function(view) { + return this._getVisiblePages().views.some(function (view) { return view.id === pageNumber; }); } @@ -1195,7 +1195,7 @@ class BaseViewer { * @returns {Array} Array of objects with width/height/rotation fields. */ getPagesOverview() { - const pagesOverview = this._pages.map(function(pageView) { + const pagesOverview = this._pages.map(function (pageView) { const viewport = pageView.pdfPage.getViewport({ scale: 1 }); return { width: viewport.width, @@ -1207,7 +1207,7 @@ class BaseViewer { return pagesOverview; } const isFirstPagePortrait = isPortraitOrientation(pagesOverview[0]); - return pagesOverview.map(function(size) { + return pagesOverview.map(function (size) { if (isFirstPagePortrait === isPortraitOrientation(size)) { return size; } diff --git a/web/chromecom.js b/web/chromecom.js index 2853c8ccb..b160bdf74 100644 --- a/web/chromecom.js +++ b/web/chromecom.js @@ -72,13 +72,13 @@ const ChromeCom = { // Assumption: The file being opened is the file that was requested. // There is no UI to input a different URL, so this assumption will hold // for now. - setReferer(file, function() { + setReferer(file, function () { callback(file); }); return; } if (/^file?:/.test(file)) { - getEmbedderOrigin(function(origin) { + getEmbedderOrigin(function (origin) { // If the origin cannot be determined, let Chrome decide whether to // allow embedding files. Otherwise, only allow local files to be // embedded from local files or Chrome extensions. @@ -95,7 +95,7 @@ const ChromeCom = { ); return; } - isAllowedFileSchemeAccess(function(isAllowedAccess) { + isAllowedFileSchemeAccess(function (isAllowedAccess) { if (isAllowedAccess) { callback(file); } else { @@ -156,7 +156,7 @@ function requestAccessToLocalFile(fileUrl, overlayManager, callback) { // for detecting unload of the top-level frame. Should this ever change // (crbug.com/511670), then the user can just reload the tab. window.addEventListener("focus", reloadIfRuntimeIsUnavailable); - onCloseOverlay = function() { + onCloseOverlay = function () { window.removeEventListener("focus", reloadIfRuntimeIsUnavailable); reloadIfRuntimeIsUnavailable(); overlayManager.close("chromeFileAccessOverlay"); @@ -170,7 +170,7 @@ function requestAccessToLocalFile(fileUrl, overlayManager, callback) { true ); } - chromeFileAccessOverlayPromise.then(function() { + chromeFileAccessOverlayPromise.then(function () { const iconPath = chrome.runtime.getManifest().icons[48]; document.getElementById("chrome-pdfjs-logo-bg").style.backgroundImage = "url(" + chrome.runtime.getURL(iconPath) + ")"; @@ -190,7 +190,7 @@ function requestAccessToLocalFile(fileUrl, overlayManager, callback) { const link = document.getElementById("chrome-link-to-extensions-page"); link.href = "chrome://extensions/?id=" + chrome.runtime.id; - link.onclick = function(e) { + link.onclick = function (e) { // Direct navigation to chrome:// URLs is blocked by Chrome, so we // have to ask the background page to open chrome://extensions/?id=... e.preventDefault(); @@ -206,7 +206,7 @@ function requestAccessToLocalFile(fileUrl, overlayManager, callback) { // why this permission request is shown. document.getElementById("chrome-url-of-local-file").textContent = fileUrl; - document.getElementById("chrome-file-fallback").onchange = function() { + document.getElementById("chrome-file-fallback").onchange = function () { const file = this.files[0]; if (file) { const originalFilename = decodeURIComponent(fileUrl.split("/").pop()); @@ -242,7 +242,7 @@ if (window === top) { // localStorage and restored by extension-router.js. // Unfortunately, the window and tab index are not restored. And if it was // the only tab in an incognito window, then the tab is not restored either. - addEventListener("unload", function() { + addEventListener("unload", function () { // If the runtime is still available, the unload is most likely a normal // tab closure. Otherwise it is most likely an extension reload. if (!isRuntimeAvailable()) { @@ -318,11 +318,11 @@ class ChromePreferences extends BasePreferences { const keysToRemove = Object.keys(this.defaults); // If the storage is reset, remove the keys so that the values from // managed storage are applied again. - storageArea.remove(keysToRemove, function() { + storageArea.remove(keysToRemove, function () { resolve(); }); } else { - storageArea.set(prefObj, function() { + storageArea.set(prefObj, function () { resolve(); }); } @@ -336,7 +336,7 @@ class ChromePreferences extends BasePreferences { // Managed storage not supported, e.g. in Opera. defaultPrefs = this.defaults; } - storageArea.get(defaultPrefs, function(readPrefs) { + storageArea.get(defaultPrefs, function (readPrefs) { resolve(readPrefs); }); }; @@ -360,7 +360,7 @@ class ChromePreferences extends BasePreferences { this.defaults ); - chrome.storage.managed.get(defaultManagedPrefs, function(items) { + chrome.storage.managed.get(defaultManagedPrefs, function (items) { items = items || defaultManagedPrefs; // Migration logic for deprecated preferences: If the new preference // is not defined by an administrator (i.e. the value is the same as @@ -410,7 +410,7 @@ class ChromeExternalServices extends DefaultExternalServices { ChromeCom.resolvePDFFile( AppOptions.get("defaultUrl"), PDFViewerApplication.overlayManager, - function(url, length, originalUrl) { + function (url, length, originalUrl) { callbacks.onOpenWithURL(url, length, originalUrl); } ); diff --git a/web/debugger.js b/web/debugger.js index ed7ee5a54..500522d84 100644 --- a/web/debugger.js +++ b/web/debugger.js @@ -126,14 +126,14 @@ var FontInspector = (function FontInspectorClosure() { var logIt = document.createElement("a"); logIt.href = ""; logIt.textContent = "Log"; - logIt.addEventListener("click", function(event) { + logIt.addEventListener("click", function (event) { event.preventDefault(); console.log(fontObj); }); const select = document.createElement("input"); select.setAttribute("type", "checkbox"); select.dataset.fontName = fontName; - select.addEventListener("click", function() { + select.addEventListener("click", function () { selectFont(fontName, select.checked); }); font.appendChild(select); @@ -174,7 +174,7 @@ var StepperManager = (function StepperManagerClosure() { var self = this; stepperControls = document.createElement("div"); stepperChooser = document.createElement("select"); - stepperChooser.addEventListener("change", function(event) { + stepperChooser.addEventListener("change", function (event) { self.selectStepper(this.value); }); stepperControls.appendChild(stepperChooser); @@ -390,7 +390,7 @@ var Stepper = (function StepperClosure() { this.table.appendChild(chunk); }, getNextBreakPoint: function getNextBreakPoint() { - this.breakPoints.sort(function(a, b) { + this.breakPoints.sort(function (a, b) { return a - b; }); for (var i = 0; i < this.breakPoints.length; i++) { @@ -405,7 +405,7 @@ var Stepper = (function StepperClosure() { var self = this; var dom = document; self.currentIdx = idx; - var listener = function(e) { + var listener = function (e) { switch (e.keyCode) { case 83: // step dom.removeEventListener("keydown", listener); @@ -486,7 +486,7 @@ var Stats = (function Stats() { wrapper.appendChild(title); wrapper.appendChild(statsDiv); stats.push({ pageNumber, div: wrapper }); - stats.sort(function(a, b) { + stats.sort(function (a, b) { return a.pageNumber - b.pageNumber; }); clear(this.panel); @@ -523,7 +523,7 @@ window.PDFBug = (function PDFBugClosure() { } if (!all) { // Sort the tools by the order they are enabled. - tools.sort(function(a, b) { + tools.sort(function (a, b) { var indexA = ids.indexOf(a.id); indexA = indexA < 0 ? tools.length : indexA; var indexB = ids.indexOf(b.id); @@ -566,8 +566,8 @@ window.PDFBug = (function PDFBugClosure() { panelButton.textContent = tool.name; panelButton.addEventListener( "click", - (function(selected) { - return function(event) { + (function (selected) { + return function (event) { event.preventDefault(); self.selectPanel(selected); }; diff --git a/web/firefox_print_service.js b/web/firefox_print_service.js index 4e6be15ac..312a05427 100644 --- a/web/firefox_print_service.js +++ b/web/firefox_print_service.js @@ -36,7 +36,7 @@ function composePage(pdfDocument, pageNumber, size, printContainer) { canvasWrapper.appendChild(canvas); printContainer.appendChild(canvasWrapper); - canvas.mozPrintCallback = function(obj) { + canvas.mozPrintCallback = function (obj) { // Printing/rendering the page. const ctx = obj.context; @@ -47,7 +47,7 @@ function composePage(pdfDocument, pageNumber, size, printContainer) { pdfDocument .getPage(pageNumber) - .then(function(pdfPage) { + .then(function (pdfPage) { const renderContext = { canvasContext: ctx, transform: [PRINT_UNITS, 0, 0, PRINT_UNITS, 0, 0], @@ -57,11 +57,11 @@ function composePage(pdfDocument, pageNumber, size, printContainer) { return pdfPage.render(renderContext).promise; }) .then( - function() { + function () { // Tell the printEngine that rendering this canvas/page has finished. obj.done(); }, - function(error) { + function (error) { console.error(error); // Tell the printEngine that rendering this canvas/page has failed. // This will make the print process stop. diff --git a/web/firefoxcom.js b/web/firefoxcom.js index d0167f888..64514c9eb 100644 --- a/web/firefoxcom.js +++ b/web/firefoxcom.js @@ -133,14 +133,14 @@ class DownloadManager { class FirefoxPreferences extends BasePreferences { async _writeToStorage(prefObj) { - return new Promise(function(resolve) { + return new Promise(function (resolve) { FirefoxCom.request("setPreferences", prefObj, resolve); }); } async _readFromStorage(prefObj) { - return new Promise(function(resolve) { - FirefoxCom.request("getPreferences", prefObj, function(prefStr) { + return new Promise(function (resolve) { + FirefoxCom.request("getPreferences", prefObj, function (prefStr) { const readPrefs = JSON.parse(prefStr); resolve(readPrefs); }); @@ -179,7 +179,7 @@ class MozL10n { "findentirewordchange", "findbarclose", ]; - const handleEvent = function({ type, detail }) { + const handleEvent = function ({ type, detail }) { if (!PDFViewerApplication.initialized) { return; } @@ -206,7 +206,7 @@ class MozL10n { (function listenZoomEvents() { const events = ["zoomin", "zoomout", "zoomreset"]; - const handleEvent = function({ type, detail }) { + const handleEvent = function ({ type, detail }) { if (!PDFViewerApplication.initialized) { return; } diff --git a/web/grab_to_pan.js b/web/grab_to_pan.js index 9533df4e0..bedd77b13 100644 --- a/web/grab_to_pan.js +++ b/web/grab_to_pan.js @@ -180,7 +180,7 @@ GrabToPan.prototype = { // Get the correct (vendor-prefixed) name of the matches method. let matchesSelector; -["webkitM", "mozM", "msM", "oM", "m"].some(function(prefix) { +["webkitM", "mozM", "msM", "oM", "m"].some(function (prefix) { let name = prefix + "atches"; if (name in document.documentElement) { matchesSelector = name; diff --git a/web/pdf_attachment_viewer.js b/web/pdf_attachment_viewer.js index 5df8703bf..d3ab20216 100644 --- a/web/pdf_attachment_viewer.js +++ b/web/pdf_attachment_viewer.js @@ -84,7 +84,7 @@ class PDFAttachmentViewer { ); } let blobUrl; - button.onclick = function() { + button.onclick = function () { if (!blobUrl) { blobUrl = createObjectURL(content, "application/pdf"); } @@ -135,7 +135,7 @@ class PDFAttachmentViewer { return; } - const names = Object.keys(attachments).sort(function(a, b) { + const names = Object.keys(attachments).sort(function (a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()); }); attachmentsCount = names.length; diff --git a/web/pdf_find_controller.js b/web/pdf_find_controller.js index 2068de152..36f4e042a 100644 --- a/web/pdf_find_controller.js +++ b/web/pdf_find_controller.js @@ -49,7 +49,7 @@ function normalize(text) { const replace = Object.keys(CHARACTERS_TO_NORMALIZE).join(""); normalizationRegex = new RegExp(`[${replace}]`, "g"); } - return text.replace(normalizationRegex, function(ch) { + return text.replace(normalizationRegex, function (ch) { return CHARACTERS_TO_NORMALIZE[ch]; }); } @@ -312,7 +312,7 @@ class PDFFindController { // Sort the array of `{ match: , matchLength: }` // objects on increasing index first and on the length otherwise. - matchesWithLength.sort(function(a, b) { + matchesWithLength.sort(function (a, b) { return a.match === b.match ? a.matchLength - b.matchLength : a.match - b.match; diff --git a/web/pdf_page_view.js b/web/pdf_page_view.js index 710e316cc..ecf0326f8 100644 --- a/web/pdf_page_view.js +++ b/web/pdf_page_view.js @@ -512,8 +512,8 @@ class PDFPageView { this.paintTask = paintTask; const resultPromise = paintTask.promise.then( - function() { - return finishPaintTask(null).then(function() { + function () { + return finishPaintTask(null).then(function () { if (textLayer) { const readableStream = pdfPage.streamTextContent({ normalizeWhitespace: true, @@ -523,7 +523,7 @@ class PDFPageView { } }); }, - function(reason) { + function (reason) { return finishPaintTask(reason); } ); @@ -573,7 +573,7 @@ class PDFPageView { // is complete when `!this.renderingQueue`, to prevent black flickering. canvas.setAttribute("hidden", "hidden"); let isCanvasHidden = true; - const showCanvas = function() { + const showCanvas = function () { if (isCanvasHidden) { canvas.removeAttribute("hidden"); isCanvasHidden = false; @@ -637,7 +637,7 @@ class PDFPageView { renderInteractiveForms: this.renderInteractiveForms, }; const renderTask = this.pdfPage.render(renderContext); - renderTask.onContinue = function(cont) { + renderTask.onContinue = function (cont) { showCanvas(); if (result.onRenderContinue) { result.onRenderContinue(cont); @@ -647,11 +647,11 @@ class PDFPageView { }; renderTask.promise.then( - function() { + function () { showCanvas(); renderCapability.resolve(undefined); }, - function(error) { + function (error) { showCanvas(); renderCapability.reject(error); } diff --git a/web/pdf_print_service.js b/web/pdf_print_service.js index 3c3bf0660..84ed4a547 100644 --- a/web/pdf_print_service.js +++ b/web/pdf_print_service.js @@ -43,7 +43,7 @@ function renderPage(activeServiceOnEntry, pdfDocument, pageNumber, size) { return pdfDocument .getPage(pageNumber) - .then(function(pdfPage) { + .then(function (pdfPage) { const renderContext = { canvasContext: ctx, transform: [PRINT_UNITS, 0, 0, PRINT_UNITS, 0, 0], @@ -52,7 +52,7 @@ function renderPage(activeServiceOnEntry, pdfDocument, pageNumber, size) { }; return pdfPage.render(renderContext).promise; }) - .then(function() { + .then(function () { return { width, height, @@ -79,7 +79,7 @@ PDFPrintService.prototype = { const body = document.querySelector("body"); body.setAttribute("data-pdfjsprinting", true); - const hasEqualPageSizes = this.pagesOverview.every(function(size) { + const hasEqualPageSizes = this.pagesOverview.every(function (size) { return ( size.width === this.pagesOverview[0].width && size.height === this.pagesOverview[0].height @@ -135,7 +135,7 @@ PDFPrintService.prototype = { this.scratchCanvas.width = this.scratchCanvas.height = 0; this.scratchCanvas = null; activeService = null; - ensureOverlay().then(function() { + ensureOverlay().then(function () { if (overlayManager.active !== "printServiceOverlay") { return; // overlay was already closed } @@ -156,7 +156,7 @@ PDFPrintService.prototype = { renderProgress(index, pageCount, this.l10n); renderPage(this, this.pdfDocument, index + 1, this.pagesOverview[index]) .then(this.useRenderedPage.bind(this)) - .then(function() { + .then(function () { renderNextPage(resolve, reject); }, reject); }; @@ -171,7 +171,7 @@ PDFPrintService.prototype = { const scratchCanvas = this.scratchCanvas; if ("toBlob" in scratchCanvas && !this.disableCreateObjectURL) { - scratchCanvas.toBlob(function(blob) { + scratchCanvas.toBlob(function (blob) { img.src = URL.createObjectURL(blob); }); } else { @@ -182,7 +182,7 @@ PDFPrintService.prototype = { wrapper.appendChild(img); this.printContainer.appendChild(wrapper); - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { img.onload = resolve; img.onerror = reject; }); @@ -218,12 +218,12 @@ PDFPrintService.prototype = { }; const print = window.print; -window.print = function() { +window.print = function () { if (activeService) { console.warn("Ignored window.print() because of a pending print job."); return; } - ensureOverlay().then(function() { + ensureOverlay().then(function () { if (activeService) { overlayManager.open("printServiceOverlay"); } @@ -234,7 +234,7 @@ window.print = function() { } finally { if (!activeService) { console.error("Expected print service to be initialized."); - ensureOverlay().then(function() { + ensureOverlay().then(function () { if (overlayManager.active === "printServiceOverlay") { overlayManager.close("printServiceOverlay"); } @@ -244,13 +244,13 @@ window.print = function() { const activeServiceOnEntry = activeService; activeService .renderPages() - .then(function() { + .then(function () { return activeServiceOnEntry.performPrint(); }) - .catch(function() { + .catch(function () { // Ignore any error messages. }) - .then(function() { + .then(function () { // aborts acts on the "active" print request, so we need to check // whether the print request (activeServiceOnEntry) is still active. // Without the check, an unrelated print request (created after aborting @@ -289,7 +289,7 @@ function renderProgress(index, total, l10n) { window.addEventListener( "keydown", - function(event) { + function (event) { // Intercept Cmd/Ctrl + P in all browsers. // Also intercept Cmd/Ctrl + Shift + P in Chrome and Opera if ( @@ -316,7 +316,7 @@ window.addEventListener( if ("onbeforeprint" in window) { // Do not propagate before/afterprint events when they are not triggered // from within this polyfill. (FF /IE / Chrome 63+). - const stopPropagationIfNeeded = function(event) { + const stopPropagationIfNeeded = function (event) { if (event.detail !== "custom" && event.stopImmediatePropagation) { event.stopImmediatePropagation(); } diff --git a/web/pdf_thumbnail_view.js b/web/pdf_thumbnail_view.js index 785f15bfd..81b7c36d4 100644 --- a/web/pdf_thumbnail_view.js +++ b/web/pdf_thumbnail_view.js @@ -128,7 +128,7 @@ class PDFThumbnailView { this._thumbPageTitle.then(msg => { anchor.title = msg; }); - anchor.onclick = function() { + anchor.onclick = function () { linkService.page = id; return false; }; @@ -350,10 +350,10 @@ class PDFThumbnailView { renderTask.onContinue = renderContinueCallback; renderTask.promise.then( - function() { + function () { finishRenderTask(null); }, - function(error) { + function (error) { finishRenderTask(error); } ); diff --git a/web/pdf_thumbnail_viewer.js b/web/pdf_thumbnail_viewer.js index b26255e59..70be7b05e 100644 --- a/web/pdf_thumbnail_viewer.js +++ b/web/pdf_thumbnail_viewer.js @@ -102,7 +102,7 @@ class PDFThumbnailViewer { if (pageNumber <= first || pageNumber >= last) { shouldScroll = true; } else { - visibleThumbs.views.some(function(view) { + visibleThumbs.views.some(function (view) { if (view.id !== pageNumber) { return false; } diff --git a/web/preferences.js b/web/preferences.js index 17a072afa..f917cdfce 100644 --- a/web/preferences.js +++ b/web/preferences.js @@ -21,13 +21,13 @@ function getDefaultPreferences() { PDFJSDev.json("$ROOT/build/default_preferences.json") ); } else { - defaultPreferences = new Promise(function(resolve, reject) { + defaultPreferences = new Promise(function (resolve, reject) { if (typeof SystemJS === "object") { SystemJS.import("./app_options.js").then(resolve, reject); } else { reject(new Error("SystemJS must be used to load AppOptions.")); } - }).then(function({ AppOptions, OptionKind }) { + }).then(function ({ AppOptions, OptionKind }) { return AppOptions.getAll(OptionKind.PREFERENCE); }); } diff --git a/web/secondary_toolbar.js b/web/secondary_toolbar.js index 0dd75f815..edd002e94 100644 --- a/web/secondary_toolbar.js +++ b/web/secondary_toolbar.js @@ -233,7 +233,7 @@ class SecondaryToolbar { } _bindCursorToolsListener(buttons) { - this.eventBus._on("cursortoolchanged", function({ tool }) { + this.eventBus._on("cursortoolchanged", function ({ tool }) { buttons.cursorSelectToolButton.classList.toggle( "toggled", tool === CursorTool.SELECT @@ -340,8 +340,9 @@ class SecondaryToolbar { if (this.containerHeight === this.previousContainerHeight) { return; } - this.toolbarButtonContainer.style.maxHeight = `${this.containerHeight - - SCROLLBAR_PADDING}px`; + this.toolbarButtonContainer.style.maxHeight = `${ + this.containerHeight - SCROLLBAR_PADDING + }px`; this.previousContainerHeight = this.containerHeight; } diff --git a/web/text_layer_builder.js b/web/text_layer_builder.js index 715135da0..763de86dd 100644 --- a/web/text_layer_builder.js +++ b/web/text_layer_builder.js @@ -111,7 +111,7 @@ class TextLayerBuilder { this._finishRendering(); this._updateMatches(); }, - function(reason) { + function (reason) { // Cancelled or failed to render text layer; skipping errors. } ); diff --git a/web/toolbar.js b/web/toolbar.js index 1937292ee..77b729f35 100644 --- a/web/toolbar.js +++ b/web/toolbar.js @@ -137,17 +137,17 @@ class Toolbar { }); } // The non-button elements within the toolbar. - pageNumber.addEventListener("click", function() { + pageNumber.addEventListener("click", function () { this.select(); }); - pageNumber.addEventListener("change", function() { + pageNumber.addEventListener("change", function () { self.eventBus.dispatch("pagenumberchanged", { source: self, value: this.value, }); }); - scaleSelect.addEventListener("change", function() { + scaleSelect.addEventListener("change", function () { if (this.value === "custom") { return; } diff --git a/web/ui_utils.js b/web/ui_utils.js index 5ea91834a..74ac2c633 100644 --- a/web/ui_utils.js +++ b/web/ui_utils.js @@ -164,7 +164,7 @@ function scrollIntoView(element, spot, skipOverflowHiddenElements = false) { * PDF.js friendly one: with scroll debounce and scroll direction. */ function watchScroll(viewAreaElement, callback) { - const debounceScroll = function(evt) { + const debounceScroll = function (evt) { if (rAF) { return; } @@ -564,7 +564,7 @@ function getVisibleElements( last = visible[visible.length - 1]; if (sortByVisibility) { - visible.sort(function(a, b) { + visible.sort(function (a, b) { const pc = a.percent - b.percent; if (Math.abs(pc) > 0.001) { return -pc; @@ -705,7 +705,7 @@ const WaitOnType = { * @returns {Promise} A promise that is resolved with a {WaitOnType} value. */ function waitOnEventOrTimeout({ target, name, delay = 0 }) { - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { if ( typeof target !== "object" || !(name && typeof name === "string") || @@ -742,7 +742,7 @@ function waitOnEventOrTimeout({ target, name, delay = 0 }) { /** * Promise that is resolved when DOM window becomes visible. */ -const animationStarted = new Promise(function(resolve) { +const animationStarted = new Promise(function (resolve) { if ( typeof PDFJSDev !== "undefined" && PDFJSDev.test("LIB && TESTING") && @@ -828,7 +828,7 @@ class EventBus { let externalListeners; // Making copy of the listeners array in case if it will be modified // during dispatch. - eventListeners.slice(0).forEach(function({ listener, external }) { + eventListeners.slice(0).forEach(function ({ listener, external }) { if (external) { if (!externalListeners) { externalListeners = []; @@ -841,7 +841,7 @@ class EventBus { // Dispatch any "external" listeners *after* the internal ones, to give the // viewer components time to handle events and update their state first. if (externalListeners) { - externalListeners.forEach(function(listener) { + externalListeners.forEach(function (listener) { listener.apply(null, args); }); externalListeners = null; diff --git a/web/viewer.js b/web/viewer.js index 35d919b80..6b6cccd4a 100644 --- a/web/viewer.js +++ b/web/viewer.js @@ -193,7 +193,7 @@ function webViewerLoad() { SystemJS.import("pdfjs-web/app_options.js"), SystemJS.import("pdfjs-web/genericcom.js"), SystemJS.import("pdfjs-web/pdf_print_service.js"), - ]).then(function([app, appOptions, ...otherModules]) { + ]).then(function ([app, appOptions, ...otherModules]) { window.PDFViewerApplication = app.PDFViewerApplication; window.PDFViewerApplicationOptions = appOptions.AppOptions; app.PDFViewerApplication.run(config);