123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963 |
- const {
- AnnotationLayer,
- AnnotationMode,
- createPromiseCapability,
- getDocument,
- GlobalWorkerOptions,
- PixelsPerInch,
- renderTextLayer,
- shadow,
- XfaLayer,
- } = pdfjsLib;
- const { GenericL10n, NullL10n, parseQueryString, SimpleLinkService } =
- pdfjsViewer;
- const WAITING_TIME = 100;
- const CMAP_URL = "/build/generic/web/cmaps/";
- const CMAP_PACKED = true;
- const STANDARD_FONT_DATA_URL = "/build/generic/web/standard_fonts/";
- const IMAGE_RESOURCES_PATH = "/web/images/";
- const VIEWER_CSS = "../build/components/pdf_viewer.css";
- const VIEWER_LOCALE = "en-US";
- const WORKER_SRC = "../build/generic/build/pdf.worker.js";
- const RENDER_TASK_ON_CONTINUE_DELAY = 5;
- const SVG_NS = "http://www.w3.org/2000/svg";
- const md5FileMap = new Map();
- function loadStyles(styles) {
- const promises = [];
- for (const file of styles) {
- promises.push(
- fetch(file)
- .then(response => {
- if (!response.ok) {
- throw new Error(response.statusText);
- }
- return response.text();
- })
- .catch(reason => {
- throw new Error(`Error fetching style (${file}): ${reason}`);
- })
- );
- }
- return Promise.all(promises);
- }
- function writeSVG(svgElement, ctx) {
-
- const svg_xml = unescape(
- encodeURIComponent(new XMLSerializer().serializeToString(svgElement))
- );
- return new Promise((resolve, reject) => {
- const img = new Image();
- img.src = "data:image/svg+xml;base64," + btoa(svg_xml);
- img.onload = function () {
- ctx.drawImage(img, 0, 0);
- resolve();
- };
- img.onerror = function (e) {
- reject(new Error(`Error rasterizing SVG: ${e}`));
- };
- });
- }
- async function inlineImages(node, silentErrors = false) {
- const promises = [];
- for (const image of node.getElementsByTagName("img")) {
- const url = image.src;
- promises.push(
- fetch(url)
- .then(response => {
- if (!response.ok) {
- throw new Error(response.statusText);
- }
- return response.blob();
- })
- .then(blob => {
- return new Promise((resolve, reject) => {
- const reader = new FileReader();
- reader.onload = () => {
- resolve(reader.result);
- };
- reader.onerror = reject;
- reader.readAsDataURL(blob);
- });
- })
- .then(dataUrl => {
- return new Promise((resolve, reject) => {
- image.onload = resolve;
- image.onerror = evt => {
- if (silentErrors) {
- resolve();
- return;
- }
- reject(evt);
- };
- image.src = dataUrl;
- });
- })
- .catch(reason => {
- throw new Error(`Error inlining image (${url}): ${reason}`);
- })
- );
- }
- await Promise.all(promises);
- }
- async function convertCanvasesToImages(annotationCanvasMap, outputScale) {
- const results = new Map();
- const promises = [];
- for (const [key, canvas] of annotationCanvasMap) {
- promises.push(
- new Promise(resolve => {
- canvas.toBlob(blob => {
- const image = document.createElement("img");
- image.onload = function () {
- image.style.width = Math.floor(image.width / outputScale) + "px";
- resolve();
- };
- results.set(key, image);
- image.src = URL.createObjectURL(blob);
- });
- })
- );
- }
- await Promise.all(promises);
- return results;
- }
- class Rasterize {
-
- static get annotationStylePromise() {
- const styles = [VIEWER_CSS, "./annotation_layer_builder_overrides.css"];
- return shadow(this, "annotationStylePromise", loadStyles(styles));
- }
- static get textStylePromise() {
- const styles = [VIEWER_CSS, "./text_layer_test.css"];
- return shadow(this, "textStylePromise", loadStyles(styles));
- }
- static get xfaStylePromise() {
- const styles = [VIEWER_CSS, "./xfa_layer_builder_overrides.css"];
- return shadow(this, "xfaStylePromise", loadStyles(styles));
- }
- static createContainer(viewport) {
- const svg = document.createElementNS(SVG_NS, "svg:svg");
- svg.setAttribute("width", `${viewport.width}px`);
- svg.setAttribute("height", `${viewport.height}px`);
- const foreignObject = document.createElementNS(SVG_NS, "svg:foreignObject");
- foreignObject.setAttribute("x", "0");
- foreignObject.setAttribute("y", "0");
- foreignObject.setAttribute("width", `${viewport.width}px`);
- foreignObject.setAttribute("height", `${viewport.height}px`);
- const style = document.createElement("style");
- foreignObject.append(style);
- const div = document.createElement("div");
- foreignObject.append(div);
- return { svg, foreignObject, style, div };
- }
- static async annotationLayer(
- ctx,
- viewport,
- outputScale,
- annotations,
- annotationCanvasMap,
- page,
- imageResourcesPath,
- renderForms = false,
- l10n = NullL10n
- ) {
- try {
- const { svg, foreignObject, style, div } = this.createContainer(viewport);
- div.className = "annotationLayer";
- const [common, overrides] = await this.annotationStylePromise;
- style.textContent =
- `${common}\n${overrides}\n` +
- `:root { --scale-factor: ${viewport.scale} }`;
- const annotationViewport = viewport.clone({ dontFlip: true });
- const annotationImageMap = await convertCanvasesToImages(
- annotationCanvasMap,
- outputScale
- );
-
- const parameters = {
- viewport: annotationViewport,
- div,
- annotations,
- page,
- linkService: new SimpleLinkService(),
- imageResourcesPath,
- renderForms,
- annotationCanvasMap: annotationImageMap,
- };
- AnnotationLayer.render(parameters);
- await l10n.translate(div);
-
- await inlineImages(div);
- foreignObject.append(div);
- svg.append(foreignObject);
- await writeSVG(svg, ctx);
- } catch (reason) {
- throw new Error(`Rasterize.annotationLayer: "${reason?.message}".`);
- }
- }
- static async textLayer(ctx, viewport, textContent) {
- try {
- const { svg, foreignObject, style, div } = this.createContainer(viewport);
- div.className = "textLayer";
-
- svg.setAttribute("font-size", 1);
- const [common, overrides] = await this.textStylePromise;
- style.textContent =
- `${common}\n${overrides}\n` +
- `:root { --scale-factor: ${viewport.scale} }`;
-
- const task = renderTextLayer({
- textContentSource: textContent,
- container: div,
- viewport,
- });
- await task.promise;
- svg.append(foreignObject);
- await writeSVG(svg, ctx);
- } catch (reason) {
- throw new Error(`Rasterize.textLayer: "${reason?.message}".`);
- }
- }
- static async xfaLayer(
- ctx,
- viewport,
- xfaHtml,
- fontRules,
- annotationStorage,
- isPrint
- ) {
- try {
- const { svg, foreignObject, style, div } = this.createContainer(viewport);
- const [common, overrides] = await this.xfaStylePromise;
- style.textContent = `${common}\n${overrides}\n${fontRules}`;
-
- XfaLayer.render({
- viewport: viewport.clone({ dontFlip: true }),
- div,
- xfaHtml,
- annotationStorage,
- linkService: new SimpleLinkService(),
- intent: isPrint ? "print" : "display",
- });
-
- await inlineImages(div, true);
- svg.append(foreignObject);
- await writeSVG(svg, ctx);
- } catch (reason) {
- throw new Error(`Rasterize.xfaLayer: "${reason?.message}".`);
- }
- }
- }
- class Driver {
-
- constructor(options) {
-
- GlobalWorkerOptions.workerSrc = WORKER_SRC;
- this._l10n = new GenericL10n(VIEWER_LOCALE);
-
- this.inflight = options.inflight;
- this.disableScrolling = options.disableScrolling;
- this.output = options.output;
- this.end = options.end;
-
- const params = parseQueryString(window.location.search.substring(1));
- this.browser = params.get("browser");
- this.manifestFile = params.get("manifestfile");
- this.delay = params.get("delay") | 0;
- this.inFlightRequests = 0;
- this.testFilter = JSON.parse(params.get("testfilter") || "[]");
- this.xfaOnly = params.get("xfaonly") === "true";
-
- this.canvas = document.createElement("canvas");
- }
- run() {
- window.onerror = (message, source, line, column, error) => {
- this._info(
- "Error: " +
- message +
- " Script: " +
- source +
- " Line: " +
- line +
- " Column: " +
- column +
- " StackTrace: " +
- error
- );
- };
- this._info("User agent: " + navigator.userAgent);
- this._log(`Harness thinks this browser is ${this.browser}\n`);
- this._log('Fetching manifest "' + this.manifestFile + '"... ');
- if (this.delay > 0) {
- this._log("\nDelaying for " + this.delay + " ms...\n");
- }
-
-
- setTimeout(async () => {
- const response = await fetch(this.manifestFile);
- if (!response.ok) {
- throw new Error(response.statusText);
- }
- this._log("done\n");
- this.manifest = await response.json();
- if (this.testFilter?.length || this.xfaOnly) {
- this.manifest = this.manifest.filter(item => {
- if (this.testFilter.includes(item.id)) {
- return true;
- }
- if (this.xfaOnly && item.enableXfa) {
- return true;
- }
- return false;
- });
- }
- this.currentTask = 0;
- this._nextTask();
- }, this.delay);
- }
-
- log(msg) {
- let id = this.browser;
- const task = this.manifest[this.currentTask];
- if (task) {
- id += `-${task.id}`;
- }
- this._info(`${id}: ${msg}`);
- }
- _nextTask() {
- let failure = "";
- this._cleanup().then(() => {
- if (this.currentTask === this.manifest.length) {
- this._done();
- return;
- }
- const task = this.manifest[this.currentTask];
- task.round = 0;
- task.pageNum = task.firstPage || 1;
- task.stats = { times: [] };
- task.enableXfa = task.enableXfa === true;
- const prevFile = md5FileMap.get(task.md5);
- if (prevFile) {
- if (task.file !== prevFile) {
- this._nextPage(
- task,
- `The "${task.file}" file is identical to the previously used "${prevFile}" file.`
- );
- return;
- }
- } else {
- md5FileMap.set(task.md5, task.file);
- }
-
-
- if (task.type === "other") {
- this._log(`Skipping file "${task.file}"\n`);
- if (!task.link) {
- this._nextPage(task, 'Expected "other" test-case to be linked.');
- return;
- }
- this.currentTask++;
- this._nextTask();
- return;
- }
- this._log('Loading file "' + task.file + '"\n');
- const absoluteUrl = new URL(task.file, window.location).href;
- try {
- let xfaStyleElement = null;
- if (task.enableXfa) {
-
-
-
- xfaStyleElement = document.createElement("style");
- document.documentElement
- .getElementsByTagName("head")[0]
- .append(xfaStyleElement);
- }
- const loadingTask = getDocument({
- url: absoluteUrl,
- password: task.password,
- cMapUrl: CMAP_URL,
- cMapPacked: CMAP_PACKED,
- standardFontDataUrl: STANDARD_FONT_DATA_URL,
- disableRange: task.disableRange,
- disableAutoFetch: !task.enableAutoFetch,
- pdfBug: true,
- useSystemFonts: task.useSystemFonts,
- useWorkerFetch: task.useWorkerFetch,
- enableXfa: task.enableXfa,
- styleElement: xfaStyleElement,
- });
- let promise = loadingTask.promise;
- if (task.save) {
- if (!task.annotationStorage) {
- promise = Promise.reject(
- new Error("Missing `annotationStorage` entry.")
- );
- } else {
- promise = loadingTask.promise.then(async doc => {
- for (const [key, value] of Object.entries(
- task.annotationStorage
- )) {
- doc.annotationStorage.setValue(key, value);
- }
- const data = await doc.saveDocument();
- await loadingTask.destroy();
- delete task.annotationStorage;
- return getDocument(data).promise;
- });
- }
- }
- promise.then(
- async doc => {
- if (task.enableXfa) {
- task.fontRules = "";
- for (const rule of xfaStyleElement.sheet.cssRules) {
- task.fontRules += rule.cssText + "\n";
- }
- }
- task.pdfDoc = doc;
- task.optionalContentConfigPromise = doc.getOptionalContentConfig();
- if (task.optionalContent) {
- const entries = Object.entries(task.optionalContent),
- optionalContentConfig = await task.optionalContentConfigPromise;
- for (const [id, visible] of entries) {
- optionalContentConfig.setVisibility(id, visible);
- }
- }
- this._nextPage(task, failure);
- },
- err => {
- failure = "Loading PDF document: " + err;
- this._nextPage(task, failure);
- }
- );
- return;
- } catch (e) {
- failure = "Loading PDF document: " + this._exceptionToString(e);
- }
- this._nextPage(task, failure);
- });
- }
- _cleanup() {
-
- while (document.styleSheets.length > 0) {
- const styleSheet = document.styleSheets[0];
- while (styleSheet.cssRules.length > 0) {
- styleSheet.deleteRule(0);
- }
- styleSheet.ownerNode.remove();
- }
- const body = document.body;
- while (body.lastChild !== this.end) {
- body.lastChild.remove();
- }
- const destroyedPromises = [];
-
- for (let i = 0; i < this.manifest.length; i++) {
- if (this.manifest[i].pdfDoc) {
- destroyedPromises.push(this.manifest[i].pdfDoc.destroy());
- delete this.manifest[i].pdfDoc;
- }
- }
- return Promise.all(destroyedPromises);
- }
- _exceptionToString(e) {
- if (typeof e !== "object") {
- return String(e);
- }
- if (!("message" in e)) {
- return JSON.stringify(e);
- }
- return e.message + ("stack" in e ? " at " + e.stack.split("\n")[0] : "");
- }
- _getLastPageNumber(task) {
- if (!task.pdfDoc) {
- return task.firstPage || 1;
- }
- return task.lastPage || task.pdfDoc.numPages;
- }
- _nextPage(task, loadError) {
- let failure = loadError || "";
- let ctx;
- if (!task.pdfDoc) {
- const dataUrl = this.canvas.toDataURL("image/png");
- this._sendResult(dataUrl, task, failure).then(() => {
- this._log(
- "done" + (failure ? " (failed !: " + failure + ")" : "") + "\n"
- );
- this.currentTask++;
- this._nextTask();
- });
- return;
- }
- if (task.pageNum > this._getLastPageNumber(task)) {
- if (++task.round < task.rounds) {
- this._log(" Round " + (1 + task.round) + "\n");
- task.pageNum = task.firstPage || 1;
- } else {
- this.currentTask++;
- this._nextTask();
- return;
- }
- }
- if (task.skipPages && task.skipPages.includes(task.pageNum)) {
- this._log(
- " Skipping page " + task.pageNum + "/" + task.pdfDoc.numPages + "...\n"
- );
- task.pageNum++;
- this._nextPage(task);
- return;
- }
- if (!failure) {
- try {
- this._log(
- " Loading page " + task.pageNum + "/" + task.pdfDoc.numPages + "... "
- );
- ctx = this.canvas.getContext("2d", { alpha: false });
- task.pdfDoc.getPage(task.pageNum).then(
- page => {
-
-
- const outputScale = task.outputScale || window.devicePixelRatio;
- let viewport = page.getViewport({
- scale: PixelsPerInch.PDF_TO_CSS_UNITS,
- });
-
- const MAX_CANVAS_PIXEL_DIMENSION = 4096;
- const largestDimension = Math.max(viewport.width, viewport.height);
- if (
- Math.floor(largestDimension * outputScale) >
- MAX_CANVAS_PIXEL_DIMENSION
- ) {
- const rescale = MAX_CANVAS_PIXEL_DIMENSION / largestDimension;
- viewport = viewport.clone({
- scale: PixelsPerInch.PDF_TO_CSS_UNITS * rescale,
- });
- }
- const pixelWidth = Math.floor(viewport.width * outputScale);
- const pixelHeight = Math.floor(viewport.height * outputScale);
- task.viewportWidth = Math.floor(viewport.width);
- task.viewportHeight = Math.floor(viewport.height);
- task.outputScale = outputScale;
- this.canvas.width = pixelWidth;
- this.canvas.height = pixelHeight;
- this.canvas.style.width = Math.floor(viewport.width) + "px";
- this.canvas.style.height = Math.floor(viewport.height) + "px";
- this._clearCanvas();
- const transform =
- outputScale !== 1 ? [outputScale, 0, 0, outputScale, 0, 0] : null;
-
- let renderAnnotations = false,
- renderForms = false,
- renderPrint = false,
- renderXfa = false,
- annotationCanvasMap = null,
- pageColors = null;
- if (task.annotationStorage) {
- const entries = Object.entries(task.annotationStorage),
- docAnnotationStorage = task.pdfDoc.annotationStorage;
- for (const [key, value] of entries) {
- docAnnotationStorage.setValue(key, value);
- }
- }
- let textLayerCanvas, annotationLayerCanvas, annotationLayerContext;
- let initPromise;
- if (task.type === "text") {
-
- textLayerCanvas = this.textLayerCanvas;
- if (!textLayerCanvas) {
- textLayerCanvas = document.createElement("canvas");
- this.textLayerCanvas = textLayerCanvas;
- }
- textLayerCanvas.width = pixelWidth;
- textLayerCanvas.height = pixelHeight;
- const textLayerContext = textLayerCanvas.getContext("2d");
- textLayerContext.clearRect(
- 0,
- 0,
- textLayerCanvas.width,
- textLayerCanvas.height
- );
- textLayerContext.scale(outputScale, outputScale);
-
- initPromise = page
- .getTextContent({
- includeMarkedContent: true,
- })
- .then(function (textContent) {
- return Rasterize.textLayer(
- textLayerContext,
- viewport,
- textContent
- );
- });
- } else {
- textLayerCanvas = null;
-
-
- renderAnnotations = !!task.annotations;
- renderForms = !!task.forms;
- renderPrint = !!task.print;
- renderXfa = !!task.enableXfa;
- pageColors = task.pageColors || null;
-
- if (renderAnnotations || renderForms || renderXfa) {
-
- annotationLayerCanvas = this.annotationLayerCanvas;
- if (!annotationLayerCanvas) {
- annotationLayerCanvas = document.createElement("canvas");
- this.annotationLayerCanvas = annotationLayerCanvas;
- }
- annotationLayerCanvas.width = pixelWidth;
- annotationLayerCanvas.height = pixelHeight;
- annotationLayerContext = annotationLayerCanvas.getContext("2d");
- annotationLayerContext.clearRect(
- 0,
- 0,
- annotationLayerCanvas.width,
- annotationLayerCanvas.height
- );
- annotationLayerContext.scale(outputScale, outputScale);
- if (!renderXfa) {
-
-
- initPromise = page.getAnnotations({ intent: "display" });
- annotationCanvasMap = new Map();
- } else {
- initPromise = page.getXfa().then(function (xfaHtml) {
- return Rasterize.xfaLayer(
- annotationLayerContext,
- viewport,
- xfaHtml,
- task.fontRules,
- task.pdfDoc.annotationStorage,
- task.renderPrint
- );
- });
- }
- } else {
- annotationLayerCanvas = null;
- initPromise = Promise.resolve();
- }
- }
- const renderContext = {
- canvasContext: ctx,
- viewport,
- optionalContentConfigPromise: task.optionalContentConfigPromise,
- annotationCanvasMap,
- pageColors,
- transform,
- };
- if (renderForms) {
- renderContext.annotationMode = task.annotationStorage
- ? AnnotationMode.ENABLE_STORAGE
- : AnnotationMode.ENABLE_FORMS;
- } else if (renderPrint) {
- if (task.annotationStorage) {
- renderContext.annotationMode = AnnotationMode.ENABLE_STORAGE;
- }
- renderContext.intent = "print";
- }
- const completeRender = error => {
-
- if (textLayerCanvas) {
- ctx.save();
- ctx.globalCompositeOperation = "screen";
- ctx.fillStyle = "rgb(128, 255, 128)";
- ctx.fillRect(0, 0, pixelWidth, pixelHeight);
- ctx.restore();
- ctx.drawImage(textLayerCanvas, 0, 0);
- }
-
- if (annotationLayerCanvas) {
- ctx.drawImage(annotationLayerCanvas, 0, 0);
- }
- if (page.stats) {
-
- task.stats = page.stats;
- }
- page.cleanup( true);
- this._snapshot(task, error);
- };
- initPromise
- .then(data => {
- const renderTask = page.render(renderContext);
- if (task.renderTaskOnContinue) {
- renderTask.onContinue = function (cont) {
-
- setTimeout(cont, RENDER_TASK_ON_CONTINUE_DELAY);
- };
- }
- return renderTask.promise.then(() => {
- if (annotationCanvasMap) {
- Rasterize.annotationLayer(
- annotationLayerContext,
- viewport,
- outputScale,
- data,
- annotationCanvasMap,
- page,
- IMAGE_RESOURCES_PATH,
- renderForms,
- this._l10n
- ).then(() => {
- completeRender(false);
- });
- } else {
- completeRender(false);
- }
- });
- })
- .catch(function (error) {
- completeRender("render : " + error);
- });
- },
- error => {
- this._snapshot(task, "render : " + error);
- }
- );
- } catch (e) {
- failure = "page setup : " + this._exceptionToString(e);
- this._snapshot(task, failure);
- }
- }
- }
- _clearCanvas() {
- const ctx = this.canvas.getContext("2d", { alpha: false });
- ctx.beginPath();
- ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
- }
- _snapshot(task, failure) {
- this._log("Snapshotting... ");
- const dataUrl = this.canvas.toDataURL("image/png");
- this._sendResult(dataUrl, task, failure).then(() => {
- this._log(
- "done" + (failure ? " (failed !: " + failure + ")" : "") + "\n"
- );
- task.pageNum++;
- this._nextPage(task);
- });
- }
- _quit() {
- this._log("Done !");
- this.end.textContent = "Tests finished. Close this window!";
-
- fetch(`/tellMeToQuit?browser=${escape(this.browser)}`, {
- method: "POST",
- });
- }
- _info(message) {
- this._send(
- "/info",
- JSON.stringify({
- browser: this.browser,
- message,
- })
- );
- }
- _log(message) {
-
-
- if (this.output.insertAdjacentHTML) {
-
- this.output.insertAdjacentHTML("BeforeEnd", message);
- } else {
- this.output.textContent += message;
- }
- if (message.lastIndexOf("\n") >= 0 && !this.disableScrolling.checked) {
-
- this.output.scrollTop = this.output.scrollHeight;
- }
- }
- _done() {
- if (this.inFlightRequests > 0) {
- this.inflight.textContent = this.inFlightRequests;
- setTimeout(this._done.bind(this), WAITING_TIME);
- } else {
- setTimeout(this._quit.bind(this), WAITING_TIME);
- }
- }
- _sendResult(snapshot, task, failure) {
- const result = JSON.stringify({
- browser: this.browser,
- id: task.id,
- numPages: task.pdfDoc ? task.lastPage || task.pdfDoc.numPages : 0,
- lastPageNum: this._getLastPageNumber(task),
- failure,
- file: task.file,
- round: task.round,
- page: task.pageNum,
- snapshot,
- stats: task.stats.times,
- viewportWidth: task.viewportWidth,
- viewportHeight: task.viewportHeight,
- outputScale: task.outputScale,
- });
- return this._send("/submit_task_results", result);
- }
- _send(url, message) {
- const capability = createPromiseCapability();
- this.inflight.textContent = this.inFlightRequests++;
- fetch(url, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: message,
- })
- .then(response => {
-
- if (!response.ok || response.status !== 200) {
- throw new Error(response.statusText);
- }
- this.inFlightRequests--;
- capability.resolve();
- })
- .catch(reason => {
- console.warn(`Driver._send failed (${url}): ${reason}`);
- this.inFlightRequests--;
- capability.resolve();
- this._send(url, message);
- });
- return capability.promise;
- }
- }
- export { Driver };
|