Socket
Socket
Sign inDemoInstall

pdfjs-dist

Package Overview
Dependencies
0
Maintainers
3
Versions
1538
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 2.5.207 to 2.6.347

es5/build/pdf.min.js

2

bower.json
{
"name": "pdfjs-dist",
"version": "2.5.207",
"version": "2.6.347",
"main": [

@@ -5,0 +5,0 @@ "build/pdf.js",

@@ -44,8 +44,12 @@ /**

var _writer = require("./writer.js");
class AnnotationFactory {
static create(xref, ref, pdfManager, idFactory) {
return pdfManager.ensure(this, "_create", [xref, ref, pdfManager, idFactory]);
return pdfManager.ensureCatalog("acroForm").then(acroForm => {
return pdfManager.ensure(this, "_create", [xref, ref, pdfManager, idFactory, acroForm]);
});
}
static _create(xref, ref, pdfManager, idFactory) {
static _create(xref, ref, pdfManager, idFactory, acroForm) {
const dict = xref.fetchIfRef(ref);

@@ -62,6 +66,8 @@

xref,
ref,
dict,
subtype,
id,
pdfManager
pdfManager,
acroForm: acroForm instanceof _primitives.Dict ? acroForm : _primitives.Dict.empty
};

@@ -389,3 +395,3 @@

getOperatorList(evaluator, task, renderForms) {
getOperatorList(evaluator, task, renderForms, annotationStorage) {
if (!this.appearance) {

@@ -395,4 +401,5 @@ return Promise.resolve(new _operator_list.OperatorList());

const appearance = this.appearance;
const data = this.data;
const appearanceDict = this.appearance.dict;
const appearanceDict = appearance.dict;
const resourcesPromise = this.loadResources(["ExtGState", "ColorSpace", "Pattern", "Shading", "XObject", "Font"]);

@@ -406,3 +413,3 @@ const bbox = appearanceDict.getArray("BBox") || [0, 0, 1, 1];

return evaluator.getOperatorList({
stream: this.appearance,
stream: appearance,
task,

@@ -413,3 +420,3 @@ resources,

opList.addOp(_util.OPS.endAnnotation, []);
this.appearance.reset();
appearance.reset();
return opList;

@@ -420,2 +427,6 @@ });

async save(evaluator, task, annotationStorage) {
return null;
}
}

@@ -593,5 +604,6 @@

const data = this.data;
this.ref = params.ref;
data.annotationType = _util.AnnotationType.WIDGET;
data.fieldName = this._constructFieldName(dict);
data.fieldValue = (0, _core_utils.getInheritableProperty)({
const fieldValue = (0, _core_utils.getInheritableProperty)({
dict,

@@ -601,2 +613,3 @@ key: "V",

});
data.fieldValue = this._decodeFormValue(fieldValue);
data.alternativeText = (0, _util.stringToPDFString)(dict.get("TU") || "");

@@ -606,3 +619,3 @@ data.defaultAppearance = (0, _core_utils.getInheritableProperty)({

key: "DA"
}) || "";
}) || params.acroForm.get("DA") || "";
const fieldType = (0, _core_utils.getInheritableProperty)({

@@ -616,3 +629,3 @@ dict,

key: "DR"
}) || _primitives.Dict.empty;
}) || params.acroForm.get("DR") || _primitives.Dict.empty;
data.fieldFlags = (0, _core_utils.getInheritableProperty)({

@@ -668,2 +681,14 @@ dict,

_decodeFormValue(formValue) {
if (Array.isArray(formValue)) {
return formValue.filter(item => (0, _util.isString)(item)).map(item => (0, _util.stringToPDFString)(item));
} else if ((0, _primitives.isName)(formValue)) {
return (0, _util.stringToPDFString)(formValue.name);
} else if ((0, _util.isString)(formValue)) {
return (0, _util.stringToPDFString)(formValue);
}
return null;
}
hasFieldFlag(flag) {

@@ -673,3 +698,3 @@ return !!(this.data.fieldFlags & flag);

getOperatorList(evaluator, task, renderForms) {
getOperatorList(evaluator, task, renderForms, annotationStorage) {
if (renderForms) {

@@ -679,5 +704,202 @@ return Promise.resolve(new _operator_list.OperatorList());

return super.getOperatorList(evaluator, task, renderForms);
if (!this._hasText) {
return super.getOperatorList(evaluator, task, renderForms, annotationStorage);
}
return this._getAppearance(evaluator, task, annotationStorage).then(content => {
if (this.appearance && content === null) {
return super.getOperatorList(evaluator, task, renderForms, annotationStorage);
}
const operatorList = new _operator_list.OperatorList();
if (!this.data.defaultAppearance || content === null) {
return operatorList;
}
const matrix = [1, 0, 0, 1, 0, 0];
const bbox = [0, 0, this.data.rect[2] - this.data.rect[0], this.data.rect[3] - this.data.rect[1]];
const transform = getTransformMatrix(this.data.rect, bbox, matrix);
operatorList.addOp(_util.OPS.beginAnnotation, [this.data.rect, transform, matrix]);
const stream = new _stream.StringStream(content);
return evaluator.getOperatorList({
stream,
task,
resources: this.fieldResources,
operatorList
}).then(function () {
operatorList.addOp(_util.OPS.endAnnotation, []);
return operatorList;
});
});
}
async save(evaluator, task, annotationStorage) {
if (this.data.fieldValue === annotationStorage[this.data.id]) {
return null;
}
let appearance = await this._getAppearance(evaluator, task, annotationStorage);
if (appearance === null) {
return null;
}
const dict = evaluator.xref.fetchIfRef(this.ref);
if (!(0, _primitives.isDict)(dict)) {
return null;
}
const bbox = [0, 0, this.data.rect[2] - this.data.rect[0], this.data.rect[3] - this.data.rect[1]];
const newRef = evaluator.xref.getNewRef();
const AP = new _primitives.Dict(evaluator.xref);
AP.set("N", newRef);
const value = annotationStorage[this.data.id];
const encrypt = evaluator.xref.encrypt;
let originalTransform = null;
let newTransform = null;
if (encrypt) {
originalTransform = encrypt.createCipherTransform(this.ref.num, this.ref.gen);
newTransform = encrypt.createCipherTransform(newRef.num, newRef.gen);
appearance = newTransform.encryptString(appearance);
}
dict.set("V", value);
dict.set("AP", AP);
dict.set("M", `D:${(0, _util.getModificationDate)()}`);
const appearanceDict = new _primitives.Dict(evaluator.xref);
appearanceDict.set("Length", appearance.length);
appearanceDict.set("Subtype", _primitives.Name.get("Form"));
appearanceDict.set("Resources", this.fieldResources);
appearanceDict.set("BBox", bbox);
const bufferOriginal = [`${this.ref.num} ${this.ref.gen} obj\n`];
(0, _writer.writeDict)(dict, bufferOriginal, originalTransform);
bufferOriginal.push("\nendobj\n");
const bufferNew = [`${newRef.num} ${newRef.gen} obj\n`];
(0, _writer.writeDict)(appearanceDict, bufferNew, newTransform);
bufferNew.push(" stream\n");
bufferNew.push(appearance);
bufferNew.push("\nendstream\nendobj\n");
return [{
ref: this.ref,
data: bufferOriginal.join("")
}, {
ref: newRef,
data: bufferNew.join("")
}];
}
async _getAppearance(evaluator, task, annotationStorage) {
const isPassword = this.hasFieldFlag(_util.AnnotationFieldFlag.PASSWORD);
if (!annotationStorage || isPassword) {
return null;
}
const value = annotationStorage[this.data.id];
if (value === "") {
return "";
}
const defaultPadding = 2;
const hPadding = defaultPadding;
const totalHeight = this.data.rect[3] - this.data.rect[1];
const totalWidth = this.data.rect[2] - this.data.rect[0];
const fontInfo = await this._getFontData(evaluator, task);
const [font, fontName] = fontInfo;
let fontSize = fontInfo[2];
fontSize = this._computeFontSize(font, fontName, fontSize, totalHeight);
let descent = font.descent;
if (isNaN(descent)) {
descent = 0;
}
const vPadding = defaultPadding + Math.abs(descent) * fontSize;
const defaultAppearance = this.data.defaultAppearance;
const alignment = this.data.textAlignment;
if (this.data.comb) {
return this._getCombAppearance(defaultAppearance, value, totalWidth, hPadding, vPadding);
}
if (this.data.multiLine) {
return this._getMultilineAppearance(defaultAppearance, value, font, fontSize, totalWidth, totalHeight, alignment, hPadding, vPadding);
}
if (alignment === 0 || alignment > 2) {
return "/Tx BMC q BT " + defaultAppearance + ` 1 0 0 1 ${hPadding} ${vPadding} Tm (${(0, _util.escapeString)(value)}) Tj` + " ET Q EMC";
}
const renderedText = this._renderText(value, font, fontSize, totalWidth, alignment, hPadding, vPadding);
return "/Tx BMC q BT " + defaultAppearance + ` 1 0 0 1 0 0 Tm ${renderedText}` + " ET Q EMC";
}
async _getFontData(evaluator, task) {
const operatorList = new _operator_list.OperatorList();
const initialState = {
fontSize: 0,
font: null,
fontName: null,
clone() {
return this;
}
};
await evaluator.getOperatorList({
stream: new _stream.StringStream(this.data.defaultAppearance),
task,
resources: this.fieldResources,
operatorList,
initialState
});
return [initialState.font, initialState.fontName, initialState.fontSize];
}
_computeFontSize(font, fontName, fontSize, height) {
if (fontSize === null || fontSize === 0) {
const em = font.charsToGlyphs("M", true)[0].width / 1000;
const capHeight = 0.7 * em;
fontSize = Math.max(1, Math.floor(height / (1.5 * capHeight)));
let fontRegex = new RegExp(`/${fontName}\\s+[0-9\.]+\\s+Tf`);
if (this.data.defaultAppearance.search(fontRegex) === -1) {
fontRegex = new RegExp(`/${fontName}\\s+Tf`);
}
this.data.defaultAppearance = this.data.defaultAppearance.replace(fontRegex, `/${fontName} ${fontSize} Tf`);
}
return fontSize;
}
_renderText(text, font, fontSize, totalWidth, alignment, hPadding, vPadding) {
const glyphs = font.charsToGlyphs(text);
const scale = fontSize / 1000;
let width = 0;
for (const glyph of glyphs) {
width += glyph.width * scale;
}
let shift;
if (alignment === 1) {
shift = (totalWidth - width) / 2;
} else if (alignment === 2) {
shift = totalWidth - width - hPadding;
} else {
shift = hPadding;
}
shift = shift.toFixed(2);
vPadding = vPadding.toFixed(2);
return `${shift} ${vPadding} Td (${(0, _util.escapeString)(text)}) Tj`;
}
}

@@ -688,4 +910,9 @@

super(params);
this._hasText = true;
const dict = params.dict;
this.data.fieldValue = (0, _util.stringToPDFString)(this.data.fieldValue || "");
if (!(0, _util.isString)(this.data.fieldValue)) {
this.data.fieldValue = "";
}
let alignment = (0, _core_utils.getInheritableProperty)({

@@ -715,24 +942,84 @@ dict,

getOperatorList(evaluator, task, renderForms) {
if (renderForms || this.appearance) {
return super.getOperatorList(evaluator, task, renderForms);
_getCombAppearance(defaultAppearance, text, width, hPadding, vPadding) {
const combWidth = (width / this.data.maxLen).toFixed(2);
const buf = [];
for (const character of text) {
buf.push(`(${(0, _util.escapeString)(character)}) Tj`);
}
const operatorList = new _operator_list.OperatorList();
const renderedComb = buf.join(` ${combWidth} 0 Td `);
return "/Tx BMC q BT " + defaultAppearance + ` 1 0 0 1 ${hPadding} ${vPadding} Tm ${renderedComb}` + " ET Q EMC";
}
if (!this.data.defaultAppearance) {
return Promise.resolve(operatorList);
_getMultilineAppearance(defaultAppearance, text, font, fontSize, width, height, alignment, hPadding, vPadding) {
const lines = text.split(/\r\n|\r|\n/);
const buf = [];
const totalWidth = width - 2 * hPadding;
for (const line of lines) {
const chunks = this._splitLine(line, font, fontSize, totalWidth);
for (const chunk of chunks) {
const padding = buf.length === 0 ? hPadding : 0;
buf.push(this._renderText(chunk, font, fontSize, width, alignment, padding, -fontSize));
}
}
const stream = new _stream.Stream((0, _util.stringToBytes)(this.data.defaultAppearance));
return evaluator.getOperatorList({
stream,
task,
resources: this.fieldResources,
operatorList
}).then(function () {
return operatorList;
});
const renderedText = buf.join("\n");
return "/Tx BMC q BT " + defaultAppearance + ` 1 0 0 1 0 ${height} Tm ${renderedText}` + " ET Q EMC";
}
_splitLine(line, font, fontSize, width) {
if (line.length <= 1) {
return [line];
}
const scale = fontSize / 1000;
const whitespace = font.charsToGlyphs(" ", true)[0].width * scale;
const chunks = [];
let lastSpacePos = -1,
startChunk = 0,
currentWidth = 0;
for (let i = 0, ii = line.length; i < ii; i++) {
const character = line.charAt(i);
if (character === " ") {
if (currentWidth + whitespace > width) {
chunks.push(line.substring(startChunk, i));
startChunk = i;
currentWidth = whitespace;
lastSpacePos = -1;
} else {
currentWidth += whitespace;
lastSpacePos = i;
}
} else {
const charWidth = font.charsToGlyphs(character, false)[0].width * scale;
if (currentWidth + charWidth > width) {
if (lastSpacePos !== -1) {
chunks.push(line.substring(startChunk, lastSpacePos + 1));
startChunk = i = lastSpacePos + 1;
lastSpacePos = -1;
currentWidth = 0;
} else {
chunks.push(line.substring(startChunk, i));
startChunk = i;
currentWidth = charWidth;
}
} else {
currentWidth += charWidth;
}
}
}
if (startChunk < line.length) {
chunks.push(line.substring(startChunk, line.length));
}
return chunks;
}
}

@@ -743,2 +1030,4 @@

super(params);
this.checkedAppearance = null;
this.uncheckedAppearance = null;
this.data.checkBox = !this.hasFieldFlag(_util.AnnotationFieldFlag.RADIO) && !this.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);

@@ -759,7 +1048,142 @@ this.data.radioButton = this.hasFieldFlag(_util.AnnotationFieldFlag.RADIO) && !this.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);

_processCheckBox(params) {
if ((0, _primitives.isName)(this.data.fieldValue)) {
this.data.fieldValue = this.data.fieldValue.name;
getOperatorList(evaluator, task, renderForms, annotationStorage) {
if (this.data.pushButton) {
return super.getOperatorList(evaluator, task, false, annotationStorage);
}
if (annotationStorage) {
const value = annotationStorage[this.data.id] || false;
let appearance;
if (value) {
appearance = this.checkedAppearance;
} else {
appearance = this.uncheckedAppearance;
}
if (appearance) {
const savedAppearance = this.appearance;
this.appearance = appearance;
const operatorList = super.getOperatorList(evaluator, task, renderForms, annotationStorage);
this.appearance = savedAppearance;
return operatorList;
}
return Promise.resolve(new _operator_list.OperatorList());
}
return super.getOperatorList(evaluator, task, renderForms, annotationStorage);
}
async save(evaluator, task, annotationStorage) {
if (this.data.checkBox) {
return this._saveCheckbox(evaluator, task, annotationStorage);
}
if (this.data.radioButton) {
return this._saveRadioButton(evaluator, task, annotationStorage);
}
return super.save(evaluator, task, annotationStorage);
}
async _saveCheckbox(evaluator, task, annotationStorage) {
const defaultValue = this.data.fieldValue && this.data.fieldValue !== "Off";
const value = annotationStorage[this.data.id];
if (defaultValue === value) {
return null;
}
const dict = evaluator.xref.fetchIfRef(this.ref);
if (!(0, _primitives.isDict)(dict)) {
return null;
}
const name = _primitives.Name.get(value ? this.data.exportValue : "Off");
dict.set("V", name);
dict.set("AS", name);
dict.set("M", `D:${(0, _util.getModificationDate)()}`);
const encrypt = evaluator.xref.encrypt;
let originalTransform = null;
if (encrypt) {
originalTransform = encrypt.createCipherTransform(this.ref.num, this.ref.gen);
}
const buffer = [`${this.ref.num} ${this.ref.gen} obj\n`];
(0, _writer.writeDict)(dict, buffer, originalTransform);
buffer.push("\nendobj\n");
return [{
ref: this.ref,
data: buffer.join("")
}];
}
async _saveRadioButton(evaluator, task, annotationStorage) {
const defaultValue = this.data.fieldValue === this.data.buttonValue;
const value = annotationStorage[this.data.id];
if (defaultValue === value) {
return null;
}
const dict = evaluator.xref.fetchIfRef(this.ref);
if (!(0, _primitives.isDict)(dict)) {
return null;
}
const name = _primitives.Name.get(value ? this.data.buttonValue : "Off");
let parentBuffer = null;
const encrypt = evaluator.xref.encrypt;
if (value) {
if ((0, _primitives.isRef)(this.parent)) {
const parent = evaluator.xref.fetch(this.parent);
let parentTransform = null;
if (encrypt) {
parentTransform = encrypt.createCipherTransform(this.parent.num, this.parent.gen);
}
parent.set("V", name);
parentBuffer = [`${this.parent.num} ${this.parent.gen} obj\n`];
(0, _writer.writeDict)(parent, parentBuffer, parentTransform);
parentBuffer.push("\nendobj\n");
} else if ((0, _primitives.isDict)(this.parent)) {
this.parent.set("V", name);
}
}
dict.set("AS", name);
dict.set("M", `D:${(0, _util.getModificationDate)()}`);
let originalTransform = null;
if (encrypt) {
originalTransform = encrypt.createCipherTransform(this.ref.num, this.ref.gen);
}
const buffer = [`${this.ref.num} ${this.ref.gen} obj\n`];
(0, _writer.writeDict)(dict, buffer, originalTransform);
buffer.push("\nendobj\n");
const newRefs = [{
ref: this.ref,
data: buffer.join("")
}];
if (parentBuffer !== null) {
newRefs.push({
ref: this.parent,
data: parentBuffer.join("")
});
}
return newRefs;
}
_processCheckBox(params) {
const customAppearance = params.dict.get("AP");

@@ -771,12 +1195,15 @@

const exportValueOptionsDict = customAppearance.get("D");
const normalAppearance = customAppearance.get("N");
if (!(0, _primitives.isDict)(exportValueOptionsDict)) {
if (!(0, _primitives.isDict)(normalAppearance)) {
return;
}
const exportValues = exportValueOptionsDict.getKeys();
const hasCorrectOptionCount = exportValues.length === 2;
const exportValues = normalAppearance.getKeys();
if (!hasCorrectOptionCount) {
if (!exportValues.includes("Off")) {
exportValues.push("Off");
}
if (exportValues.length !== 2) {
return;

@@ -786,2 +1213,4 @@ }

this.data.exportValue = exportValues[0] === "Off" ? exportValues[1] : exportValues[0];
this.checkedAppearance = normalAppearance.get(this.data.exportValue);
this.uncheckedAppearance = normalAppearance.get("Off") || null;
}

@@ -797,3 +1226,4 @@

if ((0, _primitives.isName)(fieldParentValue)) {
this.data.fieldValue = fieldParentValue.name;
this.parent = params.dict.getRaw("Parent");
this.data.fieldValue = this._decodeFormValue(fieldParentValue);
}

@@ -808,9 +1238,9 @@ }

const normalAppearanceState = appearanceStates.get("N");
const normalAppearance = appearanceStates.get("N");
if (!(0, _primitives.isDict)(normalAppearanceState)) {
if (!(0, _primitives.isDict)(normalAppearance)) {
return;
}
for (const key of normalAppearanceState.getKeys()) {
for (const key of normalAppearance.getKeys()) {
if (key !== "Off") {

@@ -821,2 +1251,5 @@ this.data.buttonValue = key;

}
this.checkedAppearance = normalAppearance.get(this.data.buttonValue);
this.uncheckedAppearance = normalAppearance.get("Off") || null;
}

@@ -855,4 +1288,4 @@

this.data.options[i] = {
exportValue: isOptionArray ? xref.fetchIfRef(option[0]) : option,
displayValue: (0, _util.stringToPDFString)(isOptionArray ? xref.fetchIfRef(option[1]) : option)
exportValue: this._decodeFormValue(isOptionArray ? xref.fetchIfRef(option[0]) : option),
displayValue: this._decodeFormValue(isOptionArray ? xref.fetchIfRef(option[1]) : option)
};

@@ -862,4 +1295,6 @@ }

if (!Array.isArray(this.data.fieldValue)) {
if ((0, _util.isString)(this.data.fieldValue)) {
this.data.fieldValue = [this.data.fieldValue];
} else if (!this.data.fieldValue) {
this.data.fieldValue = [];
}

@@ -869,2 +1304,3 @@

this.data.multiSelect = this.hasFieldFlag(_util.AnnotationFieldFlag.MULTISELECT);
this._hasText = true;
}

@@ -871,0 +1307,0 @@

@@ -251,10 +251,10 @@ /**

function CFFParser(file, properties, seacAnalysisEnabled) {
this.bytes = file.getBytes();
this.properties = properties;
this.seacAnalysisEnabled = !!seacAnalysisEnabled;
}
class CFFParser {
constructor(file, properties, seacAnalysisEnabled) {
this.bytes = file.getBytes();
this.properties = properties;
this.seacAnalysisEnabled = !!seacAnalysisEnabled;
}
CFFParser.prototype = {
parse: function CFFParser_parse() {
parse() {
var properties = this.properties;

@@ -327,4 +327,5 @@ var cff = new CFF();

return cff;
},
parseHeader: function CFFParser_parseHeader() {
}
parseHeader() {
var bytes = this.bytes;

@@ -357,4 +358,5 @@ var bytesLength = bytes.length;

};
},
parseDict: function CFFParser_parseDict(dict) {
}
parseDict(dict) {
var pos = 0;

@@ -438,4 +440,5 @@

return entries;
},
parseIndex: function CFFParser_parseIndex(pos) {
}
parseIndex(pos) {
var cffIndex = new CFFIndex();

@@ -476,4 +479,5 @@ var bytes = this.bytes;

};
},
parseNameIndex: function CFFParser_parseNameIndex(index) {
}
parseNameIndex(index) {
var names = [];

@@ -487,4 +491,5 @@

return names;
},
parseStringIndex: function CFFParser_parseStringIndex(index) {
}
parseStringIndex(index) {
var strings = new CFFStrings();

@@ -498,4 +503,5 @@

return strings;
},
createDict: function CFFParser_createDict(Type, dict, strings) {
}
createDict(Type, dict, strings) {
var cffDict = new Type(strings);

@@ -511,4 +517,5 @@

return cffDict;
},
parseCharString: function CFFParser_parseCharString(state, data, localSubrIndex, globalSubrIndex) {
}
parseCharString(state, data, localSubrIndex, globalSubrIndex) {
if (!data || state.callDepth > MAX_SUBR_NESTING) {

@@ -671,3 +678,3 @@ return false;

return true;
},
}

@@ -750,10 +757,11 @@ parseCharStrings({

};
},
}
emptyPrivateDictionary: function CFFParser_emptyPrivateDictionary(parentDict) {
emptyPrivateDictionary(parentDict) {
var privateDict = this.createDict(CFFPrivateDict, [], parentDict.strings);
parentDict.setByKey(18, [0, 0]);
parentDict.privateDict = privateDict;
},
parsePrivateDict: function CFFParser_parsePrivateDict(parentDict) {
}
parsePrivateDict(parentDict) {
if (!parentDict.hasName("Private")) {

@@ -799,4 +807,5 @@ this.emptyPrivateDictionary(parentDict);

privateDict.subrsIndex = subrsIndex.obj;
},
parseCharsets: function CFFParser_parseCharsets(pos, length, strings, cid) {
}
parseCharsets(pos, length, strings, cid) {
if (pos === 0) {

@@ -857,4 +866,5 @@ return new CFFCharset(true, CFFCharsetPredefinedTypes.ISO_ADOBE, _charsets.ISOAdobeCharset);

return new CFFCharset(false, format, charset, raw);
},
parseEncoding: function CFFParser_parseEncoding(pos, properties, strings, charset) {
}
parseEncoding(pos, properties, strings, charset) {
var encoding = Object.create(null);

@@ -933,4 +943,5 @@ var bytes = this.bytes;

return new CFFEncoding(predefined, format, encoding, raw);
},
parseFDSelect: function CFFParser_parseFDSelect(pos, length) {
}
parseFDSelect(pos, length) {
var bytes = this.bytes;

@@ -982,3 +993,5 @@ var format = bytes[pos++];

}
};
}
return CFFParser;

@@ -989,4 +1002,4 @@ }();

var CFF = function CFFClosure() {
function CFF() {
class CFF {
constructor() {
this.header = null;

@@ -1005,32 +1018,31 @@ this.names = [];

CFF.prototype = {
duplicateFirstGlyph: function CFF_duplicateFirstGlyph() {
if (this.charStrings.count >= 65535) {
(0, _util.warn)("Not enough space in charstrings to duplicate first glyph.");
return;
}
duplicateFirstGlyph() {
if (this.charStrings.count >= 65535) {
(0, _util.warn)("Not enough space in charstrings to duplicate first glyph.");
return;
}
var glyphZero = this.charStrings.get(0);
this.charStrings.add(glyphZero);
var glyphZero = this.charStrings.get(0);
this.charStrings.add(glyphZero);
if (this.isCIDFont) {
this.fdSelect.fdSelect.push(this.fdSelect.fdSelect[0]);
}
},
hasGlyphId: function CFF_hasGlyphID(id) {
if (id < 0 || id >= this.charStrings.count) {
return false;
}
if (this.isCIDFont) {
this.fdSelect.fdSelect.push(this.fdSelect.fdSelect[0]);
}
}
var glyph = this.charStrings.get(id);
return glyph.length > 0;
hasGlyphId(id) {
if (id < 0 || id >= this.charStrings.count) {
return false;
}
};
return CFF;
}();
var glyph = this.charStrings.get(id);
return glyph.length > 0;
}
}
exports.CFF = CFF;
var CFFHeader = function CFFHeaderClosure() {
function CFFHeader(major, minor, hdrSize, offSize) {
class CFFHeader {
constructor(major, minor, hdrSize, offSize) {
this.major = major;

@@ -1042,55 +1054,53 @@ this.minor = minor;

return CFFHeader;
}();
}
exports.CFFHeader = CFFHeader;
var CFFStrings = function CFFStringsClosure() {
function CFFStrings() {
class CFFStrings {
constructor() {
this.strings = [];
}
CFFStrings.prototype = {
get: function CFFStrings_get(index) {
if (index >= 0 && index <= NUM_STANDARD_CFF_STRINGS - 1) {
return CFFStandardStrings[index];
}
get(index) {
if (index >= 0 && index <= NUM_STANDARD_CFF_STRINGS - 1) {
return CFFStandardStrings[index];
}
if (index - NUM_STANDARD_CFF_STRINGS <= this.strings.length) {
return this.strings[index - NUM_STANDARD_CFF_STRINGS];
}
if (index - NUM_STANDARD_CFF_STRINGS <= this.strings.length) {
return this.strings[index - NUM_STANDARD_CFF_STRINGS];
}
return CFFStandardStrings[0];
},
getSID: function CFFStrings_getSID(str) {
let index = CFFStandardStrings.indexOf(str);
return CFFStandardStrings[0];
}
if (index !== -1) {
return index;
}
getSID(str) {
let index = CFFStandardStrings.indexOf(str);
index = this.strings.indexOf(str);
if (index !== -1) {
return index;
}
if (index !== -1) {
return index + NUM_STANDARD_CFF_STRINGS;
}
index = this.strings.indexOf(str);
return -1;
},
add: function CFFStrings_add(value) {
this.strings.push(value);
},
get count() {
return this.strings.length;
if (index !== -1) {
return index + NUM_STANDARD_CFF_STRINGS;
}
};
return CFFStrings;
}();
return -1;
}
add(value) {
this.strings.push(value);
}
get count() {
return this.strings.length;
}
}
exports.CFFStrings = CFFStrings;
var CFFIndex = function CFFIndexClosure() {
function CFFIndex() {
class CFFIndex {
constructor() {
this.objects = [];

@@ -1100,27 +1110,26 @@ this.length = 0;

CFFIndex.prototype = {
add: function CFFIndex_add(data) {
this.length += data.length;
this.objects.push(data);
},
set: function CFFIndex_set(index, data) {
this.length += data.length - this.objects[index].length;
this.objects[index] = data;
},
get: function CFFIndex_get(index) {
return this.objects[index];
},
add(data) {
this.length += data.length;
this.objects.push(data);
}
get count() {
return this.objects.length;
}
set(index, data) {
this.length += data.length - this.objects[index].length;
this.objects[index] = data;
}
};
return CFFIndex;
}();
get(index) {
return this.objects[index];
}
get count() {
return this.objects.length;
}
}
exports.CFFIndex = CFFIndex;
var CFFDict = function CFFDictClosure() {
function CFFDict(tables, strings) {
class CFFDict {
constructor(tables, strings) {
this.keyToNameMap = tables.keyToNameMap;

@@ -1136,59 +1145,61 @@ this.nameToKeyMap = tables.nameToKeyMap;

CFFDict.prototype = {
setByKey: function CFFDict_setByKey(key, value) {
if (!(key in this.keyToNameMap)) {
return false;
}
setByKey(key, value) {
if (!(key in this.keyToNameMap)) {
return false;
}
var valueLength = value.length;
var valueLength = value.length;
if (valueLength === 0) {
if (valueLength === 0) {
return true;
}
for (var i = 0; i < valueLength; i++) {
if (isNaN(value[i])) {
(0, _util.warn)('Invalid CFFDict value: "' + value + '" for key "' + key + '".');
return true;
}
}
for (var i = 0; i < valueLength; i++) {
if (isNaN(value[i])) {
(0, _util.warn)('Invalid CFFDict value: "' + value + '" for key "' + key + '".');
return true;
}
}
var type = this.types[key];
var type = this.types[key];
if (type === "num" || type === "sid" || type === "offset") {
value = value[0];
}
if (type === "num" || type === "sid" || type === "offset") {
value = value[0];
}
this.values[key] = value;
return true;
}
this.values[key] = value;
return true;
},
setByName: function CFFDict_setByName(name, value) {
if (!(name in this.nameToKeyMap)) {
throw new _util.FormatError(`Invalid dictionary name "${name}"`);
}
setByName(name, value) {
if (!(name in this.nameToKeyMap)) {
throw new _util.FormatError(`Invalid dictionary name "${name}"`);
}
this.values[this.nameToKeyMap[name]] = value;
},
hasName: function CFFDict_hasName(name) {
return this.nameToKeyMap[name] in this.values;
},
getByName: function CFFDict_getByName(name) {
if (!(name in this.nameToKeyMap)) {
throw new _util.FormatError(`Invalid dictionary name ${name}"`);
}
this.values[this.nameToKeyMap[name]] = value;
}
var key = this.nameToKeyMap[name];
hasName(name) {
return this.nameToKeyMap[name] in this.values;
}
if (!(key in this.values)) {
return this.defaults[key];
}
getByName(name) {
if (!(name in this.nameToKeyMap)) {
throw new _util.FormatError(`Invalid dictionary name ${name}"`);
}
return this.values[key];
},
removeByName: function CFFDict_removeByName(name) {
delete this.values[this.nameToKeyMap[name]];
var key = this.nameToKeyMap[name];
if (!(key in this.values)) {
return this.defaults[key];
}
};
CFFDict.createTables = function CFFDict_createTables(layout) {
return this.values[key];
}
removeByName(name) {
delete this.values[this.nameToKeyMap[name]];
}
static createTables(layout) {
var tables = {

@@ -1215,6 +1226,5 @@ keyToNameMap: {},

return tables;
};
}
return CFFDict;
}();
}

@@ -1225,12 +1235,14 @@ var CFFTopDict = function CFFTopDictClosure() {

function CFFTopDict(strings) {
if (tables === null) {
tables = CFFDict.createTables(layout);
class CFFTopDict extends CFFDict {
constructor(strings) {
if (tables === null) {
tables = CFFDict.createTables(layout);
}
super(tables, strings);
this.privateDict = null;
}
CFFDict.call(this, tables, strings);
this.privateDict = null;
}
CFFTopDict.prototype = Object.create(CFFDict.prototype);
return CFFTopDict;

@@ -1245,12 +1257,14 @@ }();

function CFFPrivateDict(strings) {
if (tables === null) {
tables = CFFDict.createTables(layout);
class CFFPrivateDict extends CFFDict {
constructor(strings) {
if (tables === null) {
tables = CFFDict.createTables(layout);
}
super(tables, strings);
this.subrsIndex = null;
}
CFFDict.call(this, tables, strings);
this.subrsIndex = null;
}
CFFPrivateDict.prototype = Object.create(CFFDict.prototype);
return CFFPrivateDict;

@@ -1266,4 +1280,4 @@ }();

var CFFCharset = function CFFCharsetClosure() {
function CFFCharset(predefined, format, charset, raw) {
class CFFCharset {
constructor(predefined, format, charset, raw) {
this.predefined = predefined;

@@ -1275,9 +1289,8 @@ this.format = format;

return CFFCharset;
}();
}
exports.CFFCharset = CFFCharset;
var CFFEncoding = function CFFEncodingClosure() {
function CFFEncoding(predefined, format, encoding, raw) {
class CFFEncoding {
constructor(predefined, format, encoding, raw) {
this.predefined = predefined;

@@ -1289,7 +1302,6 @@ this.format = format;

return CFFEncoding;
}();
}
var CFFFDSelect = function CFFFDSelectClosure() {
function CFFFDSelect(format, fdSelect) {
class CFFFDSelect {
constructor(format, fdSelect) {
this.format = format;

@@ -1299,546 +1311,562 @@ this.fdSelect = fdSelect;

CFFFDSelect.prototype = {
getFDIndex: function CFFFDSelect_get(glyphIndex) {
if (glyphIndex < 0 || glyphIndex >= this.fdSelect.length) {
return -1;
}
return this.fdSelect[glyphIndex];
getFDIndex(glyphIndex) {
if (glyphIndex < 0 || glyphIndex >= this.fdSelect.length) {
return -1;
}
};
return CFFFDSelect;
}();
return this.fdSelect[glyphIndex];
}
}
exports.CFFFDSelect = CFFFDSelect;
var CFFOffsetTracker = function CFFOffsetTrackerClosure() {
function CFFOffsetTracker() {
class CFFOffsetTracker {
constructor() {
this.offsets = Object.create(null);
}
CFFOffsetTracker.prototype = {
isTracking: function CFFOffsetTracker_isTracking(key) {
return key in this.offsets;
},
track: function CFFOffsetTracker_track(key, location) {
if (key in this.offsets) {
throw new _util.FormatError(`Already tracking location of ${key}`);
}
isTracking(key) {
return key in this.offsets;
}
this.offsets[key] = location;
},
offset: function CFFOffsetTracker_offset(value) {
for (var key in this.offsets) {
this.offsets[key] += value;
}
},
setEntryLocation: function CFFOffsetTracker_setEntryLocation(key, values, output) {
if (!(key in this.offsets)) {
throw new _util.FormatError(`Not tracking location of ${key}`);
}
track(key, location) {
if (key in this.offsets) {
throw new _util.FormatError(`Already tracking location of ${key}`);
}
var data = output.data;
var dataOffset = this.offsets[key];
var size = 5;
this.offsets[key] = location;
}
for (var i = 0, ii = values.length; i < ii; ++i) {
var offset0 = i * size + dataOffset;
var offset1 = offset0 + 1;
var offset2 = offset0 + 2;
var offset3 = offset0 + 3;
var offset4 = offset0 + 4;
offset(value) {
for (var key in this.offsets) {
this.offsets[key] += value;
}
}
if (data[offset0] !== 0x1d || data[offset1] !== 0 || data[offset2] !== 0 || data[offset3] !== 0 || data[offset4] !== 0) {
throw new _util.FormatError("writing to an offset that is not empty");
}
setEntryLocation(key, values, output) {
if (!(key in this.offsets)) {
throw new _util.FormatError(`Not tracking location of ${key}`);
}
var value = values[i];
data[offset0] = 0x1d;
data[offset1] = value >> 24 & 0xff;
data[offset2] = value >> 16 & 0xff;
data[offset3] = value >> 8 & 0xff;
data[offset4] = value & 0xff;
var data = output.data;
var dataOffset = this.offsets[key];
var size = 5;
for (var i = 0, ii = values.length; i < ii; ++i) {
var offset0 = i * size + dataOffset;
var offset1 = offset0 + 1;
var offset2 = offset0 + 2;
var offset3 = offset0 + 3;
var offset4 = offset0 + 4;
if (data[offset0] !== 0x1d || data[offset1] !== 0 || data[offset2] !== 0 || data[offset3] !== 0 || data[offset4] !== 0) {
throw new _util.FormatError("writing to an offset that is not empty");
}
var value = values[i];
data[offset0] = 0x1d;
data[offset1] = value >> 24 & 0xff;
data[offset2] = value >> 16 & 0xff;
data[offset3] = value >> 8 & 0xff;
data[offset4] = value & 0xff;
}
};
return CFFOffsetTracker;
}();
}
var CFFCompiler = function CFFCompilerClosure() {
function CFFCompiler(cff) {
}
class CFFCompiler {
constructor(cff) {
this.cff = cff;
}
CFFCompiler.prototype = {
compile: function CFFCompiler_compile() {
var cff = this.cff;
var output = {
data: [],
length: 0,
add: function CFFCompiler_add(data) {
this.data = this.data.concat(data);
this.length = this.data.length;
}
};
var header = this.compileHeader(cff.header);
output.add(header);
var nameIndex = this.compileNameIndex(cff.names);
output.add(nameIndex);
compile() {
var cff = this.cff;
var output = {
data: [],
length: 0,
add: function CFFCompiler_add(data) {
this.data = this.data.concat(data);
this.length = this.data.length;
}
};
var header = this.compileHeader(cff.header);
output.add(header);
var nameIndex = this.compileNameIndex(cff.names);
output.add(nameIndex);
if (cff.isCIDFont) {
if (cff.topDict.hasName("FontMatrix")) {
var base = cff.topDict.getByName("FontMatrix");
cff.topDict.removeByName("FontMatrix");
if (cff.isCIDFont) {
if (cff.topDict.hasName("FontMatrix")) {
var base = cff.topDict.getByName("FontMatrix");
cff.topDict.removeByName("FontMatrix");
for (var i = 0, ii = cff.fdArray.length; i < ii; i++) {
var subDict = cff.fdArray[i];
var matrix = base.slice(0);
for (var i = 0, ii = cff.fdArray.length; i < ii; i++) {
var subDict = cff.fdArray[i];
var matrix = base.slice(0);
if (subDict.hasName("FontMatrix")) {
matrix = _util.Util.transform(matrix, subDict.getByName("FontMatrix"));
}
if (subDict.hasName("FontMatrix")) {
matrix = _util.Util.transform(matrix, subDict.getByName("FontMatrix"));
}
subDict.setByName("FontMatrix", matrix);
}
subDict.setByName("FontMatrix", matrix);
}
}
}
cff.topDict.setByName("charset", 0);
var compiled = this.compileTopDicts([cff.topDict], output.length, cff.isCIDFont);
output.add(compiled.output);
var topDictTracker = compiled.trackers[0];
var stringIndex = this.compileStringIndex(cff.strings.strings);
output.add(stringIndex);
var globalSubrIndex = this.compileIndex(cff.globalSubrIndex);
output.add(globalSubrIndex);
cff.topDict.setByName("charset", 0);
var compiled = this.compileTopDicts([cff.topDict], output.length, cff.isCIDFont);
output.add(compiled.output);
var topDictTracker = compiled.trackers[0];
var stringIndex = this.compileStringIndex(cff.strings.strings);
output.add(stringIndex);
var globalSubrIndex = this.compileIndex(cff.globalSubrIndex);
output.add(globalSubrIndex);
if (cff.encoding && cff.topDict.hasName("Encoding")) {
if (cff.encoding.predefined) {
topDictTracker.setEntryLocation("Encoding", [cff.encoding.format], output);
} else {
var encoding = this.compileEncoding(cff.encoding);
topDictTracker.setEntryLocation("Encoding", [output.length], output);
output.add(encoding);
}
if (cff.encoding && cff.topDict.hasName("Encoding")) {
if (cff.encoding.predefined) {
topDictTracker.setEntryLocation("Encoding", [cff.encoding.format], output);
} else {
var encoding = this.compileEncoding(cff.encoding);
topDictTracker.setEntryLocation("Encoding", [output.length], output);
output.add(encoding);
}
}
var charset = this.compileCharset(cff.charset, cff.charStrings.count, cff.strings, cff.isCIDFont);
topDictTracker.setEntryLocation("charset", [output.length], output);
output.add(charset);
var charStrings = this.compileCharStrings(cff.charStrings);
topDictTracker.setEntryLocation("CharStrings", [output.length], output);
output.add(charStrings);
var charset = this.compileCharset(cff.charset, cff.charStrings.count, cff.strings, cff.isCIDFont);
topDictTracker.setEntryLocation("charset", [output.length], output);
output.add(charset);
var charStrings = this.compileCharStrings(cff.charStrings);
topDictTracker.setEntryLocation("CharStrings", [output.length], output);
output.add(charStrings);
if (cff.isCIDFont) {
topDictTracker.setEntryLocation("FDSelect", [output.length], output);
var fdSelect = this.compileFDSelect(cff.fdSelect);
output.add(fdSelect);
compiled = this.compileTopDicts(cff.fdArray, output.length, true);
topDictTracker.setEntryLocation("FDArray", [output.length], output);
output.add(compiled.output);
var fontDictTrackers = compiled.trackers;
this.compilePrivateDicts(cff.fdArray, fontDictTrackers, output);
}
if (cff.isCIDFont) {
topDictTracker.setEntryLocation("FDSelect", [output.length], output);
var fdSelect = this.compileFDSelect(cff.fdSelect);
output.add(fdSelect);
compiled = this.compileTopDicts(cff.fdArray, output.length, true);
topDictTracker.setEntryLocation("FDArray", [output.length], output);
output.add(compiled.output);
var fontDictTrackers = compiled.trackers;
this.compilePrivateDicts(cff.fdArray, fontDictTrackers, output);
}
this.compilePrivateDicts([cff.topDict], [topDictTracker], output);
output.add([0]);
return output.data;
},
encodeNumber: function CFFCompiler_encodeNumber(value) {
if (parseFloat(value) === parseInt(value, 10) && !isNaN(value)) {
return this.encodeInteger(value);
}
this.compilePrivateDicts([cff.topDict], [topDictTracker], output);
output.add([0]);
return output.data;
}
return this.encodeFloat(value);
},
encodeFloat: function CFFCompiler_encodeFloat(num) {
var value = num.toString();
var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value);
encodeNumber(value) {
if (Number.isInteger(value)) {
return this.encodeInteger(value);
}
if (m) {
var epsilon = parseFloat("1e" + ((m[2] ? +m[2] : 0) + m[1].length));
value = (Math.round(num * epsilon) / epsilon).toString();
}
return this.encodeFloat(value);
}
var nibbles = "";
var i, ii;
static get EncodeFloatRegExp() {
return (0, _util.shadow)(this, "EncodeFloatRegExp", /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/);
}
for (i = 0, ii = value.length; i < ii; ++i) {
var a = value[i];
encodeFloat(num) {
var value = num.toString();
var m = CFFCompiler.EncodeFloatRegExp.exec(value);
if (a === "e") {
nibbles += value[++i] === "-" ? "c" : "b";
} else if (a === ".") {
nibbles += "a";
} else if (a === "-") {
nibbles += "e";
} else {
nibbles += a;
}
}
if (m) {
var epsilon = parseFloat("1e" + ((m[2] ? +m[2] : 0) + m[1].length));
value = (Math.round(num * epsilon) / epsilon).toString();
}
nibbles += nibbles.length & 1 ? "f" : "ff";
var out = [30];
var nibbles = "";
var i, ii;
for (i = 0, ii = nibbles.length; i < ii; i += 2) {
out.push(parseInt(nibbles.substring(i, i + 2), 16));
}
for (i = 0, ii = value.length; i < ii; ++i) {
var a = value[i];
return out;
},
encodeInteger: function CFFCompiler_encodeInteger(value) {
var code;
if (value >= -107 && value <= 107) {
code = [value + 139];
} else if (value >= 108 && value <= 1131) {
value = value - 108;
code = [(value >> 8) + 247, value & 0xff];
} else if (value >= -1131 && value <= -108) {
value = -value - 108;
code = [(value >> 8) + 251, value & 0xff];
} else if (value >= -32768 && value <= 32767) {
code = [0x1c, value >> 8 & 0xff, value & 0xff];
if (a === "e") {
nibbles += value[++i] === "-" ? "c" : "b";
} else if (a === ".") {
nibbles += "a";
} else if (a === "-") {
nibbles += "e";
} else {
code = [0x1d, value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff];
nibbles += a;
}
}
return code;
},
compileHeader: function CFFCompiler_compileHeader(header) {
return [header.major, header.minor, header.hdrSize, header.offSize];
},
compileNameIndex: function CFFCompiler_compileNameIndex(names) {
var nameIndex = new CFFIndex();
nibbles += nibbles.length & 1 ? "f" : "ff";
var out = [30];
for (var i = 0, ii = names.length; i < ii; ++i) {
var name = names[i];
var length = Math.min(name.length, 127);
var sanitizedName = new Array(length);
for (i = 0, ii = nibbles.length; i < ii; i += 2) {
out.push(parseInt(nibbles.substring(i, i + 2), 16));
}
for (var j = 0; j < length; j++) {
var char = name[j];
return out;
}
if (char < "!" || char > "~" || char === "[" || char === "]" || char === "(" || char === ")" || char === "{" || char === "}" || char === "<" || char === ">" || char === "/" || char === "%") {
char = "_";
}
encodeInteger(value) {
var code;
sanitizedName[j] = char;
}
if (value >= -107 && value <= 107) {
code = [value + 139];
} else if (value >= 108 && value <= 1131) {
value = value - 108;
code = [(value >> 8) + 247, value & 0xff];
} else if (value >= -1131 && value <= -108) {
value = -value - 108;
code = [(value >> 8) + 251, value & 0xff];
} else if (value >= -32768 && value <= 32767) {
code = [0x1c, value >> 8 & 0xff, value & 0xff];
} else {
code = [0x1d, value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff];
}
sanitizedName = sanitizedName.join("");
return code;
}
if (sanitizedName === "") {
sanitizedName = "Bad_Font_Name";
compileHeader(header) {
return [header.major, header.minor, header.hdrSize, header.offSize];
}
compileNameIndex(names) {
var nameIndex = new CFFIndex();
for (var i = 0, ii = names.length; i < ii; ++i) {
var name = names[i];
var length = Math.min(name.length, 127);
var sanitizedName = new Array(length);
for (var j = 0; j < length; j++) {
var char = name[j];
if (char < "!" || char > "~" || char === "[" || char === "]" || char === "(" || char === ")" || char === "{" || char === "}" || char === "<" || char === ">" || char === "/" || char === "%") {
char = "_";
}
nameIndex.add((0, _util.stringToBytes)(sanitizedName));
sanitizedName[j] = char;
}
return this.compileIndex(nameIndex);
},
compileTopDicts: function CFFCompiler_compileTopDicts(dicts, length, removeCidKeys) {
var fontDictTrackers = [];
var fdArrayIndex = new CFFIndex();
sanitizedName = sanitizedName.join("");
for (var i = 0, ii = dicts.length; i < ii; ++i) {
var fontDict = dicts[i];
if (sanitizedName === "") {
sanitizedName = "Bad_Font_Name";
}
if (removeCidKeys) {
fontDict.removeByName("CIDFontVersion");
fontDict.removeByName("CIDFontRevision");
fontDict.removeByName("CIDFontType");
fontDict.removeByName("CIDCount");
fontDict.removeByName("UIDBase");
}
nameIndex.add((0, _util.stringToBytes)(sanitizedName));
}
var fontDictTracker = new CFFOffsetTracker();
var fontDictData = this.compileDict(fontDict, fontDictTracker);
fontDictTrackers.push(fontDictTracker);
fdArrayIndex.add(fontDictData);
fontDictTracker.offset(length);
return this.compileIndex(nameIndex);
}
compileTopDicts(dicts, length, removeCidKeys) {
var fontDictTrackers = [];
var fdArrayIndex = new CFFIndex();
for (var i = 0, ii = dicts.length; i < ii; ++i) {
var fontDict = dicts[i];
if (removeCidKeys) {
fontDict.removeByName("CIDFontVersion");
fontDict.removeByName("CIDFontRevision");
fontDict.removeByName("CIDFontType");
fontDict.removeByName("CIDCount");
fontDict.removeByName("UIDBase");
}
fdArrayIndex = this.compileIndex(fdArrayIndex, fontDictTrackers);
return {
trackers: fontDictTrackers,
output: fdArrayIndex
};
},
compilePrivateDicts: function CFFCompiler_compilePrivateDicts(dicts, trackers, output) {
for (var i = 0, ii = dicts.length; i < ii; ++i) {
var fontDict = dicts[i];
var privateDict = fontDict.privateDict;
var fontDictTracker = new CFFOffsetTracker();
var fontDictData = this.compileDict(fontDict, fontDictTracker);
fontDictTrackers.push(fontDictTracker);
fdArrayIndex.add(fontDictData);
fontDictTracker.offset(length);
}
if (!privateDict || !fontDict.hasName("Private")) {
throw new _util.FormatError("There must be a private dictionary.");
}
fdArrayIndex = this.compileIndex(fdArrayIndex, fontDictTrackers);
return {
trackers: fontDictTrackers,
output: fdArrayIndex
};
}
var privateDictTracker = new CFFOffsetTracker();
var privateDictData = this.compileDict(privateDict, privateDictTracker);
var outputLength = output.length;
privateDictTracker.offset(outputLength);
compilePrivateDicts(dicts, trackers, output) {
for (var i = 0, ii = dicts.length; i < ii; ++i) {
var fontDict = dicts[i];
var privateDict = fontDict.privateDict;
if (!privateDictData.length) {
outputLength = 0;
}
if (!privateDict || !fontDict.hasName("Private")) {
throw new _util.FormatError("There must be a private dictionary.");
}
trackers[i].setEntryLocation("Private", [privateDictData.length, outputLength], output);
output.add(privateDictData);
var privateDictTracker = new CFFOffsetTracker();
var privateDictData = this.compileDict(privateDict, privateDictTracker);
var outputLength = output.length;
privateDictTracker.offset(outputLength);
if (privateDict.subrsIndex && privateDict.hasName("Subrs")) {
var subrs = this.compileIndex(privateDict.subrsIndex);
privateDictTracker.setEntryLocation("Subrs", [privateDictData.length], output);
output.add(subrs);
}
if (!privateDictData.length) {
outputLength = 0;
}
},
compileDict: function CFFCompiler_compileDict(dict, offsetTracker) {
var out = [];
var order = dict.order;
for (var i = 0; i < order.length; ++i) {
var key = order[i];
trackers[i].setEntryLocation("Private", [privateDictData.length, outputLength], output);
output.add(privateDictData);
if (!(key in dict.values)) {
continue;
}
if (privateDict.subrsIndex && privateDict.hasName("Subrs")) {
var subrs = this.compileIndex(privateDict.subrsIndex);
privateDictTracker.setEntryLocation("Subrs", [privateDictData.length], output);
output.add(subrs);
}
}
}
var values = dict.values[key];
var types = dict.types[key];
compileDict(dict, offsetTracker) {
var out = [];
var order = dict.order;
if (!Array.isArray(types)) {
types = [types];
}
for (var i = 0; i < order.length; ++i) {
var key = order[i];
if (!Array.isArray(values)) {
values = [values];
}
if (!(key in dict.values)) {
continue;
}
if (values.length === 0) {
continue;
}
var values = dict.values[key];
var types = dict.types[key];
for (var j = 0, jj = types.length; j < jj; ++j) {
var type = types[j];
var value = values[j];
if (!Array.isArray(types)) {
types = [types];
}
switch (type) {
case "num":
case "sid":
out = out.concat(this.encodeNumber(value));
break;
if (!Array.isArray(values)) {
values = [values];
}
case "offset":
var name = dict.keyToNameMap[key];
if (values.length === 0) {
continue;
}
if (!offsetTracker.isTracking(name)) {
offsetTracker.track(name, out.length);
}
for (var j = 0, jj = types.length; j < jj; ++j) {
var type = types[j];
var value = values[j];
out = out.concat([0x1d, 0, 0, 0, 0]);
break;
switch (type) {
case "num":
case "sid":
out = out.concat(this.encodeNumber(value));
break;
case "array":
case "delta":
out = out.concat(this.encodeNumber(value));
case "offset":
var name = dict.keyToNameMap[key];
for (var k = 1, kk = values.length; k < kk; ++k) {
out = out.concat(this.encodeNumber(values[k]));
}
if (!offsetTracker.isTracking(name)) {
offsetTracker.track(name, out.length);
}
break;
out = out.concat([0x1d, 0, 0, 0, 0]);
break;
default:
throw new _util.FormatError(`Unknown data type of ${type}`);
}
}
case "array":
case "delta":
out = out.concat(this.encodeNumber(value));
out = out.concat(dict.opcodes[key]);
}
for (var k = 1, kk = values.length; k < kk; ++k) {
out = out.concat(this.encodeNumber(values[k]));
}
return out;
},
compileStringIndex: function CFFCompiler_compileStringIndex(strings) {
var stringIndex = new CFFIndex();
break;
for (var i = 0, ii = strings.length; i < ii; ++i) {
stringIndex.add((0, _util.stringToBytes)(strings[i]));
default:
throw new _util.FormatError(`Unknown data type of ${type}`);
}
}
return this.compileIndex(stringIndex);
},
compileGlobalSubrIndex: function CFFCompiler_compileGlobalSubrIndex() {
var globalSubrIndex = this.cff.globalSubrIndex;
this.out.writeByteArray(this.compileIndex(globalSubrIndex));
},
compileCharStrings: function CFFCompiler_compileCharStrings(charStrings) {
var charStringsIndex = new CFFIndex();
out = out.concat(dict.opcodes[key]);
}
for (var i = 0; i < charStrings.count; i++) {
var glyph = charStrings.get(i);
return out;
}
if (glyph.length === 0) {
charStringsIndex.add(new Uint8Array([0x8b, 0x0e]));
continue;
}
compileStringIndex(strings) {
var stringIndex = new CFFIndex();
charStringsIndex.add(glyph);
for (var i = 0, ii = strings.length; i < ii; ++i) {
stringIndex.add((0, _util.stringToBytes)(strings[i]));
}
return this.compileIndex(stringIndex);
}
compileGlobalSubrIndex() {
var globalSubrIndex = this.cff.globalSubrIndex;
this.out.writeByteArray(this.compileIndex(globalSubrIndex));
}
compileCharStrings(charStrings) {
var charStringsIndex = new CFFIndex();
for (var i = 0; i < charStrings.count; i++) {
var glyph = charStrings.get(i);
if (glyph.length === 0) {
charStringsIndex.add(new Uint8Array([0x8b, 0x0e]));
continue;
}
return this.compileIndex(charStringsIndex);
},
compileCharset: function CFFCompiler_compileCharset(charset, numGlyphs, strings, isCIDFont) {
let out;
const numGlyphsLessNotDef = numGlyphs - 1;
charStringsIndex.add(glyph);
}
if (isCIDFont) {
out = new Uint8Array([2, 0, 0, numGlyphsLessNotDef >> 8 & 0xff, numGlyphsLessNotDef & 0xff]);
} else {
const length = 1 + numGlyphsLessNotDef * 2;
out = new Uint8Array(length);
out[0] = 0;
let charsetIndex = 0;
const numCharsets = charset.charset.length;
let warned = false;
return this.compileIndex(charStringsIndex);
}
for (let i = 1; i < out.length; i += 2) {
let sid = 0;
compileCharset(charset, numGlyphs, strings, isCIDFont) {
let out;
const numGlyphsLessNotDef = numGlyphs - 1;
if (charsetIndex < numCharsets) {
const name = charset.charset[charsetIndex++];
sid = strings.getSID(name);
if (isCIDFont) {
out = new Uint8Array([2, 0, 0, numGlyphsLessNotDef >> 8 & 0xff, numGlyphsLessNotDef & 0xff]);
} else {
const length = 1 + numGlyphsLessNotDef * 2;
out = new Uint8Array(length);
out[0] = 0;
let charsetIndex = 0;
const numCharsets = charset.charset.length;
let warned = false;
if (sid === -1) {
sid = 0;
for (let i = 1; i < out.length; i += 2) {
let sid = 0;
if (!warned) {
warned = true;
(0, _util.warn)(`Couldn't find ${name} in CFF strings`);
}
if (charsetIndex < numCharsets) {
const name = charset.charset[charsetIndex++];
sid = strings.getSID(name);
if (sid === -1) {
sid = 0;
if (!warned) {
warned = true;
(0, _util.warn)(`Couldn't find ${name} in CFF strings`);
}
}
}
out[i] = sid >> 8 & 0xff;
out[i + 1] = sid & 0xff;
}
out[i] = sid >> 8 & 0xff;
out[i + 1] = sid & 0xff;
}
}
return this.compileTypedArray(out);
},
compileEncoding: function CFFCompiler_compileEncoding(encoding) {
return this.compileTypedArray(encoding.raw);
},
compileFDSelect: function CFFCompiler_compileFDSelect(fdSelect) {
const format = fdSelect.format;
let out, i;
return this.compileTypedArray(out);
}
switch (format) {
case 0:
out = new Uint8Array(1 + fdSelect.fdSelect.length);
out[0] = format;
compileEncoding(encoding) {
return this.compileTypedArray(encoding.raw);
}
for (i = 0; i < fdSelect.fdSelect.length; i++) {
out[i + 1] = fdSelect.fdSelect[i];
}
compileFDSelect(fdSelect) {
const format = fdSelect.format;
let out, i;
break;
switch (format) {
case 0:
out = new Uint8Array(1 + fdSelect.fdSelect.length);
out[0] = format;
case 3:
const start = 0;
let lastFD = fdSelect.fdSelect[0];
const ranges = [format, 0, 0, start >> 8 & 0xff, start & 0xff, lastFD];
for (i = 0; i < fdSelect.fdSelect.length; i++) {
out[i + 1] = fdSelect.fdSelect[i];
}
for (i = 1; i < fdSelect.fdSelect.length; i++) {
const currentFD = fdSelect.fdSelect[i];
break;
if (currentFD !== lastFD) {
ranges.push(i >> 8 & 0xff, i & 0xff, currentFD);
lastFD = currentFD;
}
case 3:
const start = 0;
let lastFD = fdSelect.fdSelect[0];
const ranges = [format, 0, 0, start >> 8 & 0xff, start & 0xff, lastFD];
for (i = 1; i < fdSelect.fdSelect.length; i++) {
const currentFD = fdSelect.fdSelect[i];
if (currentFD !== lastFD) {
ranges.push(i >> 8 & 0xff, i & 0xff, currentFD);
lastFD = currentFD;
}
}
const numRanges = (ranges.length - 3) / 3;
ranges[1] = numRanges >> 8 & 0xff;
ranges[2] = numRanges & 0xff;
ranges.push(i >> 8 & 0xff, i & 0xff);
out = new Uint8Array(ranges);
break;
}
const numRanges = (ranges.length - 3) / 3;
ranges[1] = numRanges >> 8 & 0xff;
ranges[2] = numRanges & 0xff;
ranges.push(i >> 8 & 0xff, i & 0xff);
out = new Uint8Array(ranges);
break;
}
return this.compileTypedArray(out);
},
compileTypedArray: function CFFCompiler_compileTypedArray(data) {
var out = [];
return this.compileTypedArray(out);
}
for (var i = 0, ii = data.length; i < ii; ++i) {
out[i] = data[i];
}
compileTypedArray(data) {
var out = [];
return out;
},
compileIndex: function CFFCompiler_compileIndex(index, trackers) {
trackers = trackers || [];
var objects = index.objects;
var count = objects.length;
for (var i = 0, ii = data.length; i < ii; ++i) {
out[i] = data[i];
}
if (count === 0) {
return [0, 0, 0];
}
return out;
}
var data = [count >> 8 & 0xff, count & 0xff];
var lastOffset = 1,
i;
compileIndex(index, trackers = []) {
var objects = index.objects;
var count = objects.length;
for (i = 0; i < count; ++i) {
lastOffset += objects[i].length;
}
if (count === 0) {
return [0, 0, 0];
}
var offsetSize;
var data = [count >> 8 & 0xff, count & 0xff];
var lastOffset = 1,
i;
if (lastOffset < 0x100) {
offsetSize = 1;
} else if (lastOffset < 0x10000) {
offsetSize = 2;
} else if (lastOffset < 0x1000000) {
offsetSize = 3;
} else {
offsetSize = 4;
}
for (i = 0; i < count; ++i) {
lastOffset += objects[i].length;
}
data.push(offsetSize);
var relativeOffset = 1;
var offsetSize;
for (i = 0; i < count + 1; i++) {
if (offsetSize === 1) {
data.push(relativeOffset & 0xff);
} else if (offsetSize === 2) {
data.push(relativeOffset >> 8 & 0xff, relativeOffset & 0xff);
} else if (offsetSize === 3) {
data.push(relativeOffset >> 16 & 0xff, relativeOffset >> 8 & 0xff, relativeOffset & 0xff);
} else {
data.push(relativeOffset >>> 24 & 0xff, relativeOffset >> 16 & 0xff, relativeOffset >> 8 & 0xff, relativeOffset & 0xff);
}
if (lastOffset < 0x100) {
offsetSize = 1;
} else if (lastOffset < 0x10000) {
offsetSize = 2;
} else if (lastOffset < 0x1000000) {
offsetSize = 3;
} else {
offsetSize = 4;
}
if (objects[i]) {
relativeOffset += objects[i].length;
}
data.push(offsetSize);
var relativeOffset = 1;
for (i = 0; i < count + 1; i++) {
if (offsetSize === 1) {
data.push(relativeOffset & 0xff);
} else if (offsetSize === 2) {
data.push(relativeOffset >> 8 & 0xff, relativeOffset & 0xff);
} else if (offsetSize === 3) {
data.push(relativeOffset >> 16 & 0xff, relativeOffset >> 8 & 0xff, relativeOffset & 0xff);
} else {
data.push(relativeOffset >>> 24 & 0xff, relativeOffset >> 16 & 0xff, relativeOffset >> 8 & 0xff, relativeOffset & 0xff);
}
for (i = 0; i < count; i++) {
if (trackers[i]) {
trackers[i].offset(data.length);
}
if (objects[i]) {
relativeOffset += objects[i].length;
}
}
for (var j = 0, jj = objects[i].length; j < jj; j++) {
data.push(objects[i][j]);
}
for (i = 0; i < count; i++) {
if (trackers[i]) {
trackers[i].offset(data.length);
}
return data;
for (var j = 0, jj = objects[i].length; j < jj; j++) {
data.push(objects[i][j]);
}
}
};
return CFFCompiler;
}();
return data;
}
}
exports.CFFCompiler = CFFCompiler;

@@ -40,4 +40,3 @@ /**

this.chunkSize = chunkSize;
this.loadedChunks = [];
this.numChunksLoaded = 0;
this._loadedChunks = new Set();
this.numChunks = Math.ceil(length / chunkSize);

@@ -53,3 +52,3 @@ this.manager = manager;

for (let chunk = 0, n = this.numChunks; chunk < n; ++chunk) {
if (!this.loadedChunks[chunk]) {
if (!this._loadedChunks.has(chunk)) {
chunks.push(chunk);

@@ -66,2 +65,6 @@ }

get numChunksLoaded() {
return this._loadedChunks.size;
}
allChunksLoaded() {

@@ -89,6 +92,3 @@ return this.numChunksLoaded === this.numChunks;

for (let curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
if (!this.loadedChunks[curChunk]) {
this.loadedChunks[curChunk] = true;
++this.numChunksLoaded;
}
this._loadedChunks.add(curChunk);
}

@@ -106,6 +106,3 @@ }

for (let curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
if (!this.loadedChunks[curChunk]) {
this.loadedChunks[curChunk] = true;
++this.numChunksLoaded;
}
this._loadedChunks.add(curChunk);
}

@@ -125,3 +122,3 @@ }

if (!this.loadedChunks[chunk]) {
if (!this._loadedChunks.has(chunk)) {
throw new _core_utils.MissingDataException(pos, pos + 1);

@@ -147,3 +144,3 @@ }

for (let chunk = beginChunk; chunk < endChunk; ++chunk) {
if (!this.loadedChunks[chunk]) {
if (!this._loadedChunks.has(chunk)) {
throw new _core_utils.MissingDataException(begin, end);

@@ -160,3 +157,3 @@ }

if (!this.loadedChunks[chunk]) {
if (!this._loadedChunks.has(chunk)) {
return chunk;

@@ -170,3 +167,3 @@ }

hasChunk(chunk) {
return !!this.loadedChunks[chunk];
return this._loadedChunks.has(chunk);
}

@@ -314,3 +311,3 @@

for (let chunk = beginChunk; chunk < endChunk; ++chunk) {
if (!this.loadedChunks[chunk]) {
if (!this._loadedChunks.has(chunk)) {
missingChunks.push(chunk);

@@ -351,5 +348,5 @@ }

this.currRequestId = 0;
this.chunksNeededByRequest = Object.create(null);
this.requestsByChunk = Object.create(null);
this.promisesByRequest = Object.create(null);
this._chunksNeededByRequest = new Map();
this._requestsByChunk = new Map();
this._promisesByRequest = new Map();
this.progressiveDataLength = 0;

@@ -423,12 +420,13 @@ this.aborted = false;

const requestId = this.currRequestId++;
const chunksNeeded = Object.create(null);
this.chunksNeededByRequest[requestId] = chunksNeeded;
const chunksNeeded = new Set();
this._chunksNeededByRequest.set(requestId, chunksNeeded);
for (const chunk of chunks) {
if (!this.stream.hasChunk(chunk)) {
chunksNeeded[chunk] = true;
chunksNeeded.add(chunk);
}
}
if ((0, _util.isEmptyObj)(chunksNeeded)) {
if (chunksNeeded.size === 0) {
return Promise.resolve();

@@ -438,29 +436,38 @@ }

const capability = (0, _util.createPromiseCapability)();
this.promisesByRequest[requestId] = capability;
this._promisesByRequest.set(requestId, capability);
const chunksToRequest = [];
for (let chunk in chunksNeeded) {
chunk = chunk | 0;
for (const chunk of chunksNeeded) {
let requestIds = this._requestsByChunk.get(chunk);
if (!(chunk in this.requestsByChunk)) {
this.requestsByChunk[chunk] = [];
if (!requestIds) {
requestIds = [];
this._requestsByChunk.set(chunk, requestIds);
chunksToRequest.push(chunk);
}
this.requestsByChunk[chunk].push(requestId);
requestIds.push(requestId);
}
if (!chunksToRequest.length) {
return capability.promise;
if (chunksToRequest.length > 0) {
const groupedChunksToRequest = this.groupChunks(chunksToRequest);
for (const groupedChunk of groupedChunksToRequest) {
const begin = groupedChunk.beginChunk * this.chunkSize;
const end = Math.min(groupedChunk.endChunk * this.chunkSize, this.length);
this.sendRequest(begin, end);
}
}
const groupedChunksToRequest = this.groupChunks(chunksToRequest);
return capability.promise.catch(reason => {
if (this.aborted) {
return;
}
for (const groupedChunk of groupedChunksToRequest) {
const begin = groupedChunk.beginChunk * this.chunkSize;
const end = Math.min(groupedChunk.endChunk * this.chunkSize, this.length);
this.sendRequest(begin, end);
}
return capability.promise;
throw reason;
});
}

@@ -567,13 +574,18 @@

for (let curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
const requestIds = this.requestsByChunk[curChunk] || [];
delete this.requestsByChunk[curChunk];
const requestIds = this._requestsByChunk.get(curChunk);
if (!requestIds) {
continue;
}
this._requestsByChunk.delete(curChunk);
for (const requestId of requestIds) {
const chunksNeeded = this.chunksNeededByRequest[requestId];
const chunksNeeded = this._chunksNeededByRequest.get(requestId);
if (curChunk in chunksNeeded) {
delete chunksNeeded[curChunk];
if (chunksNeeded.has(curChunk)) {
chunksNeeded.delete(curChunk);
}
if (!(0, _util.isEmptyObj)(chunksNeeded)) {
if (chunksNeeded.size > 0) {
continue;

@@ -586,3 +598,3 @@ }

if (!this.disableAutoFetch && (0, _util.isEmptyObj)(this.requestsByChunk)) {
if (!this.disableAutoFetch && this._requestsByChunk.size === 0) {
let nextEmptyChunk;

@@ -606,4 +618,6 @@

for (const requestId of loadedRequests) {
const capability = this.promisesByRequest[requestId];
delete this.promisesByRequest[requestId];
const capability = this._promisesByRequest.get(requestId);
this._promisesByRequest.delete(requestId);
capability.resolve();

@@ -637,4 +651,4 @@ }

for (const requestId in this.promisesByRequest) {
this.promisesByRequest[requestId].reject(reason);
for (const capability of this._promisesByRequest.values()) {
capability.reject(reason);
}

@@ -641,0 +655,0 @@ }

@@ -33,2 +33,4 @@ /**

var _core_utils = require("./core_utils.js");
function resizeRgbImage(src, dest, w1, h1, w2, h2, alpha01) {

@@ -166,67 +168,94 @@ const COMPONENTS = 3;

static parse(cs, xref, res, pdfFunctionFactory) {
const IR = this.parseToIR(cs, xref, res, pdfFunctionFactory);
return this.fromIR(IR);
}
static _cache(cacheKey, xref, localColorSpaceCache, parsedColorSpace) {
if (!localColorSpaceCache) {
throw new Error('ColorSpace._cache - expected "localColorSpaceCache" argument.');
}
static fromIR(IR) {
const name = Array.isArray(IR) ? IR[0] : IR;
let whitePoint, blackPoint, gamma;
if (!parsedColorSpace) {
throw new Error('ColorSpace._cache - expected "parsedColorSpace" argument.');
}
switch (name) {
case "DeviceGrayCS":
return this.singletons.gray;
let csName, csRef;
case "DeviceRgbCS":
return this.singletons.rgb;
if (cacheKey instanceof _primitives.Ref) {
csRef = cacheKey;
cacheKey = xref.fetch(cacheKey);
}
case "DeviceCmykCS":
return this.singletons.cmyk;
if (cacheKey instanceof _primitives.Name) {
csName = cacheKey.name;
}
case "CalGrayCS":
whitePoint = IR[1];
blackPoint = IR[2];
gamma = IR[3];
return new CalGrayCS(whitePoint, blackPoint, gamma);
if (csName || csRef) {
localColorSpaceCache.set(csName, csRef, parsedColorSpace);
}
}
case "CalRGBCS":
whitePoint = IR[1];
blackPoint = IR[2];
gamma = IR[3];
const matrix = IR[4];
return new CalRGBCS(whitePoint, blackPoint, gamma, matrix);
static getCached(cacheKey, xref, localColorSpaceCache) {
if (!localColorSpaceCache) {
throw new Error('ColorSpace.getCached - expected "localColorSpaceCache" argument.');
}
case "PatternCS":
let basePatternCS = IR[1];
if (cacheKey instanceof _primitives.Ref) {
const localColorSpace = localColorSpaceCache.getByRef(cacheKey);
if (basePatternCS) {
basePatternCS = this.fromIR(basePatternCS);
if (localColorSpace) {
return localColorSpace;
}
try {
cacheKey = xref.fetch(cacheKey);
} catch (ex) {
if (ex instanceof _core_utils.MissingDataException) {
throw ex;
}
}
}
return new PatternCS(basePatternCS);
if (cacheKey instanceof _primitives.Name) {
const localColorSpace = localColorSpaceCache.getByName(cacheKey.name);
case "IndexedCS":
const baseIndexedCS = IR[1];
const hiVal = IR[2];
const lookup = IR[3];
return new IndexedCS(this.fromIR(baseIndexedCS), hiVal, lookup);
if (localColorSpace) {
return localColorSpace;
}
}
case "AlternateCS":
const numComps = IR[1];
const alt = IR[2];
const tintFn = IR[3];
return new AlternateCS(numComps, this.fromIR(alt), tintFn);
return null;
}
case "LabCS":
whitePoint = IR[1];
blackPoint = IR[2];
const range = IR[3];
return new LabCS(whitePoint, blackPoint, range);
static async parseAsync({
cs,
xref,
resources = null,
pdfFunctionFactory,
localColorSpaceCache
}) {
const parsedColorSpace = this._parse(cs, xref, resources, pdfFunctionFactory);
default:
throw new _util.FormatError(`Unknown colorspace name: ${name}`);
this._cache(cs, xref, localColorSpaceCache, parsedColorSpace);
return parsedColorSpace;
}
static parse({
cs,
xref,
resources = null,
pdfFunctionFactory,
localColorSpaceCache
}) {
const cachedColorSpace = this.getCached(cs, xref, localColorSpaceCache);
if (cachedColorSpace) {
return cachedColorSpace;
}
const parsedColorSpace = this._parse(cs, xref, resources, pdfFunctionFactory);
this._cache(cs, xref, localColorSpaceCache, parsedColorSpace);
return parsedColorSpace;
}
static parseToIR(cs, xref, res = null, pdfFunctionFactory) {
static _parse(cs, xref, resources = null, pdfFunctionFactory) {
cs = xref.fetchIfRef(cs);

@@ -238,28 +267,28 @@

case "G":
return "DeviceGrayCS";
return this.singletons.gray;
case "DeviceRGB":
case "RGB":
return "DeviceRgbCS";
return this.singletons.rgb;
case "DeviceCMYK":
case "CMYK":
return "DeviceCmykCS";
return this.singletons.cmyk;
case "Pattern":
return ["PatternCS", null];
return new PatternCS(null);
default:
if ((0, _primitives.isDict)(res)) {
const colorSpaces = res.get("ColorSpace");
if ((0, _primitives.isDict)(resources)) {
const colorSpaces = resources.get("ColorSpace");
if ((0, _primitives.isDict)(colorSpaces)) {
const resCS = colorSpaces.get(cs.name);
const resourcesCS = colorSpaces.get(cs.name);
if (resCS) {
if ((0, _primitives.isName)(resCS)) {
return this.parseToIR(resCS, xref, res, pdfFunctionFactory);
if (resourcesCS) {
if ((0, _primitives.isName)(resourcesCS)) {
return this._parse(resourcesCS, xref, resources, pdfFunctionFactory);
}
cs = resCS;
cs = resourcesCS;
break;

@@ -270,3 +299,3 @@ }

throw new _util.FormatError(`unrecognized colorspace ${cs.name}`);
throw new _util.FormatError(`Unrecognized ColorSpace: ${cs.name}`);
}

@@ -277,3 +306,3 @@ }

const mode = xref.fetchIfRef(cs[0]).name;
let numComps, params, alt, whitePoint, blackPoint, gamma;
let params, numComps, baseCS, whitePoint, blackPoint, gamma;

@@ -283,11 +312,11 @@ switch (mode) {

case "G":
return "DeviceGrayCS";
return this.singletons.gray;
case "DeviceRGB":
case "RGB":
return "DeviceRgbCS";
return this.singletons.rgb;
case "DeviceCMYK":
case "CMYK":
return "DeviceCmykCS";
return this.singletons.cmyk;

@@ -299,3 +328,3 @@ case "CalGray":

gamma = params.get("Gamma");
return ["CalGrayCS", whitePoint, blackPoint, gamma];
return new CalGrayCS(whitePoint, blackPoint, gamma);

@@ -308,3 +337,3 @@ case "CalRGB":

const matrix = params.getArray("Matrix");
return ["CalRGBCS", whitePoint, blackPoint, gamma, matrix];
return new CalRGBCS(whitePoint, blackPoint, gamma, matrix);

@@ -315,10 +344,9 @@ case "ICCBased":

numComps = dict.get("N");
alt = dict.get("Alternate");
const alt = dict.get("Alternate");
if (alt) {
const altIR = this.parseToIR(alt, xref, res, pdfFunctionFactory);
const altCS = this.fromIR(altIR, pdfFunctionFactory);
const altCS = this._parse(alt, xref, resources, pdfFunctionFactory);
if (altCS.numComps === numComps) {
return altIR;
return altCS;
}

@@ -330,7 +358,7 @@

if (numComps === 1) {
return "DeviceGrayCS";
return this.singletons.gray;
} else if (numComps === 3) {
return "DeviceRgbCS";
return this.singletons.rgb;
} else if (numComps === 4) {
return "DeviceCmykCS";
return this.singletons.cmyk;
}

@@ -341,22 +369,17 @@

case "Pattern":
let basePatternCS = cs[1] || null;
baseCS = cs[1] || null;
if (basePatternCS) {
basePatternCS = this.parseToIR(basePatternCS, xref, res, pdfFunctionFactory);
if (baseCS) {
baseCS = this._parse(baseCS, xref, resources, pdfFunctionFactory);
}
return ["PatternCS", basePatternCS];
return new PatternCS(baseCS);
case "Indexed":
case "I":
const baseIndexedCS = this.parseToIR(cs[1], xref, res, pdfFunctionFactory);
baseCS = this._parse(cs[1], xref, resources, pdfFunctionFactory);
const hiVal = xref.fetchIfRef(cs[2]) + 1;
let lookup = xref.fetchIfRef(cs[3]);
const lookup = xref.fetchIfRef(cs[3]);
return new IndexedCS(baseCS, hiVal, lookup);
if ((0, _primitives.isStream)(lookup)) {
lookup = lookup.getBytes();
}
return ["IndexedCS", baseIndexedCS, hiVal, lookup];
case "Separation":

@@ -366,5 +389,5 @@ case "DeviceN":

numComps = Array.isArray(name) ? name.length : 1;
alt = this.parseToIR(cs[2], xref, res, pdfFunctionFactory);
const tintFn = pdfFunctionFactory.create(xref.fetchIfRef(cs[3]));
return ["AlternateCS", numComps, alt, tintFn];
baseCS = this._parse(cs[2], xref, resources, pdfFunctionFactory);
const tintFn = pdfFunctionFactory.create(cs[3]);
return new AlternateCS(numComps, baseCS, tintFn);

@@ -376,10 +399,10 @@ case "Lab":

const range = params.getArray("Range");
return ["LabCS", whitePoint, blackPoint, range];
return new LabCS(whitePoint, blackPoint, range);
default:
throw new _util.FormatError(`unimplemented color space object "${mode}"`);
throw new _util.FormatError(`Unimplemented ColorSpace object: ${mode}`);
}
}
throw new _util.FormatError(`unrecognized color space object: "${cs}"`);
throw new _util.FormatError(`Unrecognized ColorSpace object: ${cs}`);
}

@@ -500,19 +523,14 @@

this.highVal = highVal;
const baseNumComps = base.numComps;
const length = baseNumComps * highVal;
const length = base.numComps * highVal;
this.lookup = new Uint8Array(length);
if ((0, _primitives.isStream)(lookup)) {
this.lookup = new Uint8Array(length);
const bytes = lookup.getBytes(length);
this.lookup.set(bytes);
} else if ((0, _util.isString)(lookup)) {
this.lookup = new Uint8Array(length);
} else if (typeof lookup === "string") {
for (let i = 0; i < length; ++i) {
this.lookup[i] = lookup.charCodeAt(i);
this.lookup[i] = lookup.charCodeAt(i) & 0xff;
}
} else if (lookup instanceof Uint8Array) {
this.lookup = lookup;
} else {
throw new _util.FormatError(`Unrecognized lookup table: ${lookup}`);
throw new _util.FormatError(`IndexedCS - unrecognized lookup table: ${lookup}`);
}

@@ -779,2 +797,6 @@ }

if (color >= 0.99554525) {
return 1;
}
return adjustToRange(0, 1, (1 + 0.055) * color ** (1 / 2.4) - 0.055);

@@ -852,5 +874,5 @@ }

const C = adjustToRange(0, 1, src[srcOffset + 2] * scale);
const AGR = A ** cs.GR;
const BGG = B ** cs.GG;
const CGB = C ** cs.GB;
const AGR = A === 1 ? 1 : A ** cs.GR;
const BGG = B === 1 ? 1 : B ** cs.GG;
const CGB = C === 1 ? 1 : C ** cs.GB;
const X = cs.MXA * AGR + cs.MXB * BGG + cs.MXC * CGB;

@@ -857,0 +879,0 @@ const Y = cs.MYA * AGR + cs.MYB * BGG + cs.MYC * CGB;

@@ -86,2 +86,3 @@ /**

ARCFourCipher.prototype.decryptBlock = ARCFourCipher.prototype.encryptBlock;
ARCFourCipher.prototype.encrypt = ARCFourCipher.prototype.encryptBlock;
return ARCFourCipher;

@@ -626,2 +627,5 @@ }();

return data;
},
encrypt: function NullCipher_encrypt(data) {
return data;
}

@@ -1240,2 +1244,35 @@ };

return (0, _util.bytesToString)(data);
},
encryptString: function CipherTransform_encryptString(s) {
const cipher = new this.StringCipherConstructor();
if (cipher instanceof AESBaseCipher) {
const strLen = s.length;
const pad = 16 - strLen % 16;
if (pad !== 16) {
s = s.padEnd(16 * Math.ceil(strLen / 16), String.fromCharCode(pad));
}
const iv = new Uint8Array(16);
if (typeof crypto !== "undefined") {
crypto.getRandomValues(iv);
} else {
for (let i = 0; i < 16; i++) {
iv[i] = Math.floor(256 * Math.random());
}
}
let data = (0, _util.stringToBytes)(s);
data = cipher.encrypt(data, iv);
const buf = new Uint8Array(16 + data.length);
buf.set(iv);
buf.set(data, 16);
return (0, _util.bytesToString)(buf);
}
let data = (0, _util.stringToBytes)(s);
data = cipher.encrypt(data);
return (0, _util.bytesToString)(data);
}

@@ -1242,0 +1279,0 @@ };

@@ -49,4 +49,2 @@ /**

var _function = require("./function.js");
const DEFAULT_USER_UNIT = 1.0;

@@ -66,6 +64,6 @@ const LETTER_SIZE_MEDIABOX = [0, 0, 612, 792];

ref,
globalIdFactory,
fontCache,
builtInCMapCache,
globalImageCache,
pdfFunctionFactory
globalImageCache
}) {

@@ -80,3 +78,2 @@ this.pdfManager = pdfManager;

this.globalImageCache = globalImageCache;
this.pdfFunctionFactory = pdfFunctionFactory;
this.evaluatorOptions = pdfManager.evaluatorOptions;

@@ -87,9 +84,5 @@ this.resourcesPromise = null;

};
this.idFactory = {
createObjId() {
this._localIdFactory = class extends globalIdFactory {
static createObjId() {
return `p${pageIndex}_${++idCounters.obj}`;
},
getDocId() {
return `g_${pdfManager.docId}`;
}

@@ -116,3 +109,6 @@

return _primitives.Dict.merge(this.xref, value);
return _primitives.Dict.merge({
xref: this.xref,
dictArray: value
});
}

@@ -218,2 +214,31 @@

save(handler, task, annotationStorage) {
const partialEvaluator = new _evaluator.PartialEvaluator({
xref: this.xref,
handler,
pageIndex: this.pageIndex,
idFactory: this._localIdFactory,
fontCache: this.fontCache,
builtInCMapCache: this.builtInCMapCache,
globalImageCache: this.globalImageCache,
options: this.evaluatorOptions
});
return this._parsedAnnotations.then(function (annotations) {
const newRefsPromises = [];
for (const annotation of annotations) {
if (!isAnnotationRenderable(annotation, "print")) {
continue;
}
newRefsPromises.push(annotation.save(partialEvaluator, task, annotationStorage).catch(function (reason) {
(0, _util.warn)("save - ignoring annotation data during " + `"${task.name}" task: "${reason}".`);
return null;
}));
}
return Promise.all(newRefsPromises);
});
}
loadResources(keys) {

@@ -235,3 +260,4 @@ if (!this.resourcesPromise) {

intent,
renderInteractiveForms
renderInteractiveForms,
annotationStorage
}) {

@@ -244,12 +270,11 @@ const contentStreamPromise = this.pdfManager.ensure(this, "getContentStream");

pageIndex: this.pageIndex,
idFactory: this.idFactory,
idFactory: this._localIdFactory,
fontCache: this.fontCache,
builtInCMapCache: this.builtInCMapCache,
globalImageCache: this.globalImageCache,
options: this.evaluatorOptions,
pdfFunctionFactory: this.pdfFunctionFactory
options: this.evaluatorOptions
});
const dataPromises = Promise.all([contentStreamPromise, resourcesPromise]);
const pageListPromise = dataPromises.then(([contentStream]) => {
const opList = new _operator_list.OperatorList(intent, sink, this.pageIndex);
const opList = new _operator_list.OperatorList(intent, sink);
handler.send("StartRenderPage", {

@@ -281,3 +306,3 @@ transparency: partialEvaluator.hasBlendModes(this.resources),

if (isAnnotationRenderable(annotation, intent)) {
opListPromises.push(annotation.getOperatorList(partialEvaluator, task, renderInteractiveForms).catch(function (reason) {
opListPromises.push(annotation.getOperatorList(partialEvaluator, task, renderInteractiveForms, annotationStorage).catch(function (reason) {
(0, _util.warn)("getOperatorList - ignoring annotation data during " + `"${task.name}" task: "${reason}".`);

@@ -320,8 +345,7 @@ return null;

pageIndex: this.pageIndex,
idFactory: this.idFactory,
idFactory: this._localIdFactory,
fontCache: this.fontCache,
builtInCMapCache: this.builtInCMapCache,
globalImageCache: this.globalImageCache,
options: this.evaluatorOptions,
pdfFunctionFactory: this.pdfFunctionFactory
options: this.evaluatorOptions
});

@@ -362,3 +386,3 @@ return partialEvaluator.getTextContent({

for (const annotationRef of this.annotations) {
annotationPromises.push(_annotation.AnnotationFactory.create(this.xref, annotationRef, this.pdfManager, this.idFactory).catch(function (reason) {
annotationPromises.push(_annotation.AnnotationFactory.create(this.xref, annotationRef, this.pdfManager, this._localIdFactory).catch(function (reason) {
(0, _util.warn)(`_parsedAnnotations: "${reason}".`);

@@ -454,49 +478,29 @@ return null;

this.xref = new _obj.XRef(stream, pdfManager);
this.pdfFunctionFactory = new _function.PDFFunctionFactory({
xref: this.xref,
isEvalSupported: pdfManager.evaluatorOptions.isEvalSupported
});
this._pagePromises = [];
}
this._version = null;
const idCounters = {
font: 0
};
this._globalIdFactory = class {
static getDocId() {
return `g_${pdfManager.docId}`;
}
parse(recoveryMode) {
this.setup(recoveryMode);
const version = this.catalog.catDict.get("Version");
static createFontId() {
return `f${++idCounters.font}`;
}
if ((0, _primitives.isName)(version)) {
this.pdfFormatVersion = version.name;
}
try {
this.acroForm = this.catalog.catDict.get("AcroForm");
if (this.acroForm) {
this.xfa = this.acroForm.get("XFA");
const fields = this.acroForm.get("Fields");
if ((!Array.isArray(fields) || fields.length === 0) && !this.xfa) {
this.acroForm = null;
}
static createObjId() {
(0, _util.unreachable)("Abstract method `createObjId` called.");
}
} catch (ex) {
if (ex instanceof _core_utils.MissingDataException) {
throw ex;
}
(0, _util.info)("Cannot fetch AcroForm entry; assuming no AcroForms are present");
this.acroForm = null;
}
};
}
try {
const collection = this.catalog.catDict.get("Collection");
parse(recoveryMode) {
this.xref.parse(recoveryMode);
this.catalog = new _obj.Catalog(this.pdfManager, this.xref);
if ((0, _primitives.isDict)(collection) && collection.getKeys().length > 0) {
this.collection = collection;
}
} catch (ex) {
if (ex instanceof _core_utils.MissingDataException) {
throw ex;
}
(0, _util.info)("Cannot fetch Collection dictionary.");
if (this.catalog.version) {
this._version = this.catalog.version;
}

@@ -595,4 +599,4 @@ }

if (!this.pdfFormatVersion) {
this.pdfFormatVersion = version.substring(5);
if (!this._version) {
this._version = version.substring(5);
}

@@ -605,7 +609,2 @@ }

setup(recoveryMode) {
this.xref.parse(recoveryMode);
this.catalog = new _obj.Catalog(this.pdfManager, this.xref);
}
get numPages() {

@@ -617,2 +616,56 @@ const linearization = this.linearization;

_hasOnlyDocumentSignatures(fields, recursionDepth = 0) {
const RECURSION_LIMIT = 10;
return fields.every(field => {
field = this.xref.fetchIfRef(field);
if (field.has("Kids")) {
if (++recursionDepth > RECURSION_LIMIT) {
(0, _util.warn)("_hasOnlyDocumentSignatures: maximum recursion depth reached");
return false;
}
return this._hasOnlyDocumentSignatures(field.get("Kids"), recursionDepth);
}
const isSignature = (0, _primitives.isName)(field.get("FT"), "Sig");
const rectangle = field.get("Rect");
const isInvisible = Array.isArray(rectangle) && rectangle.every(value => value === 0);
return isSignature && isInvisible;
});
}
get formInfo() {
const formInfo = {
hasAcroForm: false,
hasXfa: false
};
const acroForm = this.catalog.acroForm;
if (!acroForm) {
return (0, _util.shadow)(this, "formInfo", formInfo);
}
try {
const xfa = acroForm.get("XFA");
const hasXfa = Array.isArray(xfa) && xfa.length > 0 || (0, _primitives.isStream)(xfa) && !xfa.isEmpty;
formInfo.hasXfa = hasXfa;
const fields = acroForm.get("Fields");
const hasFields = Array.isArray(fields) && fields.length > 0;
const sigFlags = acroForm.get("SigFlags");
const hasOnlyDocumentSignatures = !!(sigFlags & 0x1) && this._hasOnlyDocumentSignatures(fields);
formInfo.hasAcroForm = hasFields && !hasOnlyDocumentSignatures;
} catch (ex) {
if (ex instanceof _core_utils.MissingDataException) {
throw ex;
}
(0, _util.info)("Cannot fetch form information.");
}
return (0, _util.shadow)(this, "formInfo", formInfo);
}
get documentInfo() {

@@ -630,3 +683,3 @@ const DocumentInfoValidators = {

};
let version = this.pdfFormatVersion;
let version = this._version;

@@ -641,5 +694,5 @@ if (typeof version !== "string" || !PDF_HEADER_VERSION_REGEXP.test(version)) {

IsLinearized: !!this.linearization,
IsAcroFormPresent: !!this.acroForm,
IsXFAPresent: !!this.xfa,
IsCollectionPresent: !!this.collection
IsAcroFormPresent: this.formInfo.hasAcroForm,
IsXFAPresent: this.formInfo.hasXfa,
IsCollectionPresent: !!this.catalog.collection
};

@@ -753,6 +806,6 @@ let infoDict;

ref,
globalIdFactory: this._globalIdFactory,
fontCache: catalog.fontCache,
builtInCMapCache: catalog.builtInCMapCache,
globalImageCache: catalog.globalImageCache,
pdfFunctionFactory: this.pdfFunctionFactory
globalImageCache: catalog.globalImageCache
});

@@ -759,0 +812,0 @@ });

@@ -30,8 +30,10 @@ /**

var _primitives = require("./primitives.js");
var _util = require("../shared/util.js");
var _primitives = require("./primitives.js");
var _ps_parser = require("./ps_parser.js");
var _image_utils = require("./image_utils.js");
class PDFFunctionFactory {

@@ -44,20 +46,91 @@ constructor({

this.isEvalSupported = isEvalSupported !== false;
this._localFunctionCache = null;
}
create(fn) {
return PDFFunction.parse({
const cachedFunction = this.getCached(fn);
if (cachedFunction) {
return cachedFunction;
}
const parsedFunction = PDFFunction.parse({
xref: this.xref,
isEvalSupported: this.isEvalSupported,
fn
fn: fn instanceof _primitives.Ref ? this.xref.fetch(fn) : fn
});
this._cache(fn, parsedFunction);
return parsedFunction;
}
createFromArray(fnObj) {
return PDFFunction.parseArray({
const cachedFunction = this.getCached(fnObj);
if (cachedFunction) {
return cachedFunction;
}
const parsedFunction = PDFFunction.parseArray({
xref: this.xref,
isEvalSupported: this.isEvalSupported,
fnObj
fnObj: fnObj instanceof _primitives.Ref ? this.xref.fetch(fnObj) : fnObj
});
this._cache(fnObj, parsedFunction);
return parsedFunction;
}
getCached(cacheKey) {
let fnRef;
if (cacheKey instanceof _primitives.Ref) {
fnRef = cacheKey;
} else if (cacheKey instanceof _primitives.Dict) {
fnRef = cacheKey.objId;
} else if ((0, _primitives.isStream)(cacheKey)) {
fnRef = cacheKey.dict && cacheKey.dict.objId;
}
if (fnRef) {
if (!this._localFunctionCache) {
this._localFunctionCache = new _image_utils.LocalFunctionCache();
}
const localFunction = this._localFunctionCache.getByRef(fnRef);
if (localFunction) {
return localFunction;
}
}
return null;
}
_cache(cacheKey, parsedFunction) {
if (!parsedFunction) {
throw new Error('PDFFunctionFactory._cache - expected "parsedFunction" argument.');
}
let fnRef;
if (cacheKey instanceof _primitives.Ref) {
fnRef = cacheKey;
} else if (cacheKey instanceof _primitives.Dict) {
fnRef = cacheKey.objId;
} else if ((0, _primitives.isStream)(cacheKey)) {
fnRef = cacheKey.dict && cacheKey.dict.objId;
}
if (fnRef) {
if (!this._localFunctionCache) {
this._localFunctionCache = new _image_utils.LocalFunctionCache();
}
this._localFunctionCache.set(null, fnRef, parsedFunction);
}
}
}

@@ -64,0 +137,0 @@

@@ -27,3 +27,3 @@ /**

});
exports.GlobalImageCache = exports.LocalImageCache = void 0;
exports.GlobalImageCache = exports.LocalGStateCache = exports.LocalFunctionCache = exports.LocalColorSpaceCache = exports.LocalImageCache = void 0;

@@ -34,6 +34,13 @@ var _util = require("../shared/util.js");

class LocalImageCache {
constructor() {
this._nameRefMap = new Map();
this._imageMap = new Map();
class BaseLocalCache {
constructor(options) {
if (this.constructor === BaseLocalCache) {
(0, _util.unreachable)("Cannot initialize BaseLocalCache.");
}
if (!options || !options.onlyRefs) {
this._nameRefMap = new Map();
this._imageMap = new Map();
}
this._imageCache = new _primitives.RefSetCache();

@@ -56,2 +63,9 @@ }

set(name, ref, data) {
(0, _util.unreachable)("Abstract method `set` called.");
}
}
class LocalImageCache extends BaseLocalCache {
set(name, ref = null, data) {

@@ -85,2 +99,89 @@ if (!name) {

class LocalColorSpaceCache extends BaseLocalCache {
set(name = null, ref = null, data) {
if (!name && !ref) {
throw new Error('LocalColorSpaceCache.set - expected "name" and/or "ref" argument.');
}
if (ref) {
if (this._imageCache.has(ref)) {
return;
}
if (name) {
this._nameRefMap.set(name, ref);
}
this._imageCache.put(ref, data);
return;
}
if (this._imageMap.has(name)) {
return;
}
this._imageMap.set(name, data);
}
}
exports.LocalColorSpaceCache = LocalColorSpaceCache;
class LocalFunctionCache extends BaseLocalCache {
constructor(options) {
super({
onlyRefs: true
});
}
getByName(name) {
(0, _util.unreachable)("Should not call `getByName` method.");
}
set(name = null, ref, data) {
if (!ref) {
throw new Error('LocalFunctionCache.set - expected "ref" argument.');
}
if (this._imageCache.has(ref)) {
return;
}
this._imageCache.put(ref, data);
}
}
exports.LocalFunctionCache = LocalFunctionCache;
class LocalGStateCache extends BaseLocalCache {
set(name, ref = null, data) {
if (!name) {
throw new Error('LocalGStateCache.set - expected "name" argument.');
}
if (ref) {
if (this._imageCache.has(ref)) {
return;
}
this._nameRefMap.set(name, ref);
this._imageCache.put(ref, data);
return;
}
if (this._imageMap.has(name)) {
return;
}
this._imageMap.set(name, data);
}
}
exports.LocalGStateCache = LocalGStateCache;
class GlobalImageCache {

@@ -129,8 +230,8 @@ static get NUM_PAGES_THRESHOLD() {

getData(ref, pageIndex) {
if (!this._refCache.has(ref)) {
const pageIndexSet = this._refCache.get(ref);
if (!pageIndexSet) {
return null;
}
const pageIndexSet = this._refCache.get(ref);
if (pageIndexSet.size < GlobalImageCache.NUM_PAGES_THRESHOLD) {

@@ -137,0 +238,0 @@ return null;

@@ -41,54 +41,54 @@ /**

var PDFImage = function PDFImageClosure() {
function decodeAndClamp(value, addend, coefficient, max) {
value = addend + value * coefficient;
function decodeAndClamp(value, addend, coefficient, max) {
value = addend + value * coefficient;
if (value < 0) {
value = 0;
} else if (value > max) {
value = max;
}
return value;
if (value < 0) {
value = 0;
} else if (value > max) {
value = max;
}
function resizeImageMask(src, bpc, w1, h1, w2, h2) {
var length = w2 * h2;
let dest;
return value;
}
if (bpc <= 8) {
dest = new Uint8Array(length);
} else if (bpc <= 16) {
dest = new Uint16Array(length);
} else {
dest = new Uint32Array(length);
}
function resizeImageMask(src, bpc, w1, h1, w2, h2) {
var length = w2 * h2;
let dest;
var xRatio = w1 / w2;
var yRatio = h1 / h2;
var i,
j,
py,
newIndex = 0,
oldIndex;
var xScaled = new Uint16Array(w2);
var w1Scanline = w1;
if (bpc <= 8) {
dest = new Uint8Array(length);
} else if (bpc <= 16) {
dest = new Uint16Array(length);
} else {
dest = new Uint32Array(length);
}
for (i = 0; i < w2; i++) {
xScaled[i] = Math.floor(i * xRatio);
}
var xRatio = w1 / w2;
var yRatio = h1 / h2;
var i,
j,
py,
newIndex = 0,
oldIndex;
var xScaled = new Uint16Array(w2);
var w1Scanline = w1;
for (i = 0; i < h2; i++) {
py = Math.floor(i * yRatio) * w1Scanline;
for (i = 0; i < w2; i++) {
xScaled[i] = Math.floor(i * xRatio);
}
for (j = 0; j < w2; j++) {
oldIndex = py + xScaled[j];
dest[newIndex++] = src[oldIndex];
}
for (i = 0; i < h2; i++) {
py = Math.floor(i * yRatio) * w1Scanline;
for (j = 0; j < w2; j++) {
oldIndex = py + xScaled[j];
dest[newIndex++] = src[oldIndex];
}
return dest;
}
function PDFImage({
return dest;
}
class PDFImage {
constructor({
xref,

@@ -101,3 +101,4 @@ res,

isMask = false,
pdfFunctionFactory
pdfFunctionFactory,
localColorSpaceCache
}) {

@@ -162,3 +163,3 @@ this.image = image;

if (!this.imageMask) {
var colorSpace = dict.get("ColorSpace", "CS");
let colorSpace = dict.getRaw("ColorSpace") || dict.getRaw("CS");

@@ -186,4 +187,9 @@ if (!colorSpace) {

const resources = isInline ? res : null;
this.colorSpace = _colorspace.ColorSpace.parse(colorSpace, xref, resources, pdfFunctionFactory);
this.colorSpace = _colorspace.ColorSpace.parse({
cs: colorSpace,
xref,
resources: isInline ? res : null,
pdfFunctionFactory,
localColorSpaceCache
});
this.numComps = this.colorSpace.numComps;

@@ -216,3 +222,4 @@ }

isInline,
pdfFunctionFactory
pdfFunctionFactory,
localColorSpaceCache
});

@@ -233,3 +240,4 @@ } else if (mask) {

isMask: true,
pdfFunctionFactory
pdfFunctionFactory,
localColorSpaceCache
});

@@ -243,3 +251,3 @@ }

PDFImage.buildImage = function ({
static async buildImage({
xref,

@@ -249,3 +257,4 @@ res,

isInline = false,
pdfFunctionFactory
pdfFunctionFactory,
localColorSpaceCache
}) {

@@ -268,3 +277,3 @@ const imageData = image;

return Promise.resolve(new PDFImage({
return new PDFImage({
xref,

@@ -276,7 +285,8 @@ res,

mask: maskData,
pdfFunctionFactory
}));
};
pdfFunctionFactory,
localColorSpaceCache
});
}
PDFImage.createMask = function ({
static createMask({
imgArray,

@@ -318,376 +328,373 @@ width,

};
};
}
PDFImage.prototype = {
get drawWidth() {
return Math.max(this.width, this.smask && this.smask.width || 0, this.mask && this.mask.width || 0);
},
get drawWidth() {
return Math.max(this.width, this.smask && this.smask.width || 0, this.mask && this.mask.width || 0);
}
get drawHeight() {
return Math.max(this.height, this.smask && this.smask.height || 0, this.mask && this.mask.height || 0);
},
get drawHeight() {
return Math.max(this.height, this.smask && this.smask.height || 0, this.mask && this.mask.height || 0);
}
decodeBuffer(buffer) {
var bpc = this.bpc;
var numComps = this.numComps;
var decodeAddends = this.decodeAddends;
var decodeCoefficients = this.decodeCoefficients;
var max = (1 << bpc) - 1;
var i, ii;
decodeBuffer(buffer) {
var bpc = this.bpc;
var numComps = this.numComps;
var decodeAddends = this.decodeAddends;
var decodeCoefficients = this.decodeCoefficients;
var max = (1 << bpc) - 1;
var i, ii;
if (bpc === 1) {
for (i = 0, ii = buffer.length; i < ii; i++) {
buffer[i] = +!buffer[i];
}
return;
if (bpc === 1) {
for (i = 0, ii = buffer.length; i < ii; i++) {
buffer[i] = +!buffer[i];
}
var index = 0;
return;
}
for (i = 0, ii = this.width * this.height; i < ii; i++) {
for (var j = 0; j < numComps; j++) {
buffer[index] = decodeAndClamp(buffer[index], decodeAddends[j], decodeCoefficients[j], max);
index++;
}
var index = 0;
for (i = 0, ii = this.width * this.height; i < ii; i++) {
for (var j = 0; j < numComps; j++) {
buffer[index] = decodeAndClamp(buffer[index], decodeAddends[j], decodeCoefficients[j], max);
index++;
}
},
}
}
getComponents(buffer) {
var bpc = this.bpc;
getComponents(buffer) {
var bpc = this.bpc;
if (bpc === 8) {
return buffer;
}
if (bpc === 8) {
return buffer;
}
var width = this.width;
var height = this.height;
var numComps = this.numComps;
var length = width * height * numComps;
var bufferPos = 0;
let output;
var width = this.width;
var height = this.height;
var numComps = this.numComps;
var length = width * height * numComps;
var bufferPos = 0;
let output;
if (bpc <= 8) {
output = new Uint8Array(length);
} else if (bpc <= 16) {
output = new Uint16Array(length);
} else {
output = new Uint32Array(length);
}
if (bpc <= 8) {
output = new Uint8Array(length);
} else if (bpc <= 16) {
output = new Uint16Array(length);
} else {
output = new Uint32Array(length);
}
var rowComps = width * numComps;
var max = (1 << bpc) - 1;
var i = 0,
ii,
buf;
var rowComps = width * numComps;
var max = (1 << bpc) - 1;
var i = 0,
ii,
buf;
if (bpc === 1) {
var mask, loop1End, loop2End;
if (bpc === 1) {
var mask, loop1End, loop2End;
for (var j = 0; j < height; j++) {
loop1End = i + (rowComps & ~7);
loop2End = i + rowComps;
for (var j = 0; j < height; j++) {
loop1End = i + (rowComps & ~7);
loop2End = i + rowComps;
while (i < loop1End) {
buf = buffer[bufferPos++];
output[i] = buf >> 7 & 1;
output[i + 1] = buf >> 6 & 1;
output[i + 2] = buf >> 5 & 1;
output[i + 3] = buf >> 4 & 1;
output[i + 4] = buf >> 3 & 1;
output[i + 5] = buf >> 2 & 1;
output[i + 6] = buf >> 1 & 1;
output[i + 7] = buf & 1;
i += 8;
}
while (i < loop1End) {
buf = buffer[bufferPos++];
output[i] = buf >> 7 & 1;
output[i + 1] = buf >> 6 & 1;
output[i + 2] = buf >> 5 & 1;
output[i + 3] = buf >> 4 & 1;
output[i + 4] = buf >> 3 & 1;
output[i + 5] = buf >> 2 & 1;
output[i + 6] = buf >> 1 & 1;
output[i + 7] = buf & 1;
i += 8;
}
if (i < loop2End) {
buf = buffer[bufferPos++];
mask = 128;
if (i < loop2End) {
buf = buffer[bufferPos++];
mask = 128;
while (i < loop2End) {
output[i++] = +!!(buf & mask);
mask >>= 1;
}
while (i < loop2End) {
output[i++] = +!!(buf & mask);
mask >>= 1;
}
}
} else {
var bits = 0;
buf = 0;
}
} else {
var bits = 0;
buf = 0;
for (i = 0, ii = length; i < ii; ++i) {
if (i % rowComps === 0) {
buf = 0;
bits = 0;
}
for (i = 0, ii = length; i < ii; ++i) {
if (i % rowComps === 0) {
buf = 0;
bits = 0;
}
while (bits < bpc) {
buf = buf << 8 | buffer[bufferPos++];
bits += 8;
}
while (bits < bpc) {
buf = buf << 8 | buffer[bufferPos++];
bits += 8;
}
var remainingBits = bits - bpc;
let value = buf >> remainingBits;
var remainingBits = bits - bpc;
let value = buf >> remainingBits;
if (value < 0) {
value = 0;
} else if (value > max) {
value = max;
}
if (value < 0) {
value = 0;
} else if (value > max) {
value = max;
}
output[i] = value;
buf = buf & (1 << remainingBits) - 1;
bits = remainingBits;
}
output[i] = value;
buf = buf & (1 << remainingBits) - 1;
bits = remainingBits;
}
}
return output;
},
return output;
}
fillOpacity(rgbaBuf, width, height, actualHeight, image) {
var smask = this.smask;
var mask = this.mask;
var alphaBuf, sw, sh, i, ii, j;
fillOpacity(rgbaBuf, width, height, actualHeight, image) {
var smask = this.smask;
var mask = this.mask;
var alphaBuf, sw, sh, i, ii, j;
if (smask) {
sw = smask.width;
sh = smask.height;
if (smask) {
sw = smask.width;
sh = smask.height;
alphaBuf = new Uint8ClampedArray(sw * sh);
smask.fillGrayBuffer(alphaBuf);
if (sw !== width || sh !== height) {
alphaBuf = resizeImageMask(alphaBuf, smask.bpc, sw, sh, width, height);
}
} else if (mask) {
if (mask instanceof PDFImage) {
sw = mask.width;
sh = mask.height;
alphaBuf = new Uint8ClampedArray(sw * sh);
smask.fillGrayBuffer(alphaBuf);
mask.numComps = 1;
mask.fillGrayBuffer(alphaBuf);
for (i = 0, ii = sw * sh; i < ii; ++i) {
alphaBuf[i] = 255 - alphaBuf[i];
}
if (sw !== width || sh !== height) {
alphaBuf = resizeImageMask(alphaBuf, smask.bpc, sw, sh, width, height);
alphaBuf = resizeImageMask(alphaBuf, mask.bpc, sw, sh, width, height);
}
} else if (mask) {
if (mask instanceof PDFImage) {
sw = mask.width;
sh = mask.height;
alphaBuf = new Uint8ClampedArray(sw * sh);
mask.numComps = 1;
mask.fillGrayBuffer(alphaBuf);
} else if (Array.isArray(mask)) {
alphaBuf = new Uint8ClampedArray(width * height);
var numComps = this.numComps;
for (i = 0, ii = sw * sh; i < ii; ++i) {
alphaBuf[i] = 255 - alphaBuf[i];
}
for (i = 0, ii = width * height; i < ii; ++i) {
var opacity = 0;
var imageOffset = i * numComps;
if (sw !== width || sh !== height) {
alphaBuf = resizeImageMask(alphaBuf, mask.bpc, sw, sh, width, height);
}
} else if (Array.isArray(mask)) {
alphaBuf = new Uint8ClampedArray(width * height);
var numComps = this.numComps;
for (j = 0; j < numComps; ++j) {
var color = image[imageOffset + j];
var maskOffset = j * 2;
for (i = 0, ii = width * height; i < ii; ++i) {
var opacity = 0;
var imageOffset = i * numComps;
for (j = 0; j < numComps; ++j) {
var color = image[imageOffset + j];
var maskOffset = j * 2;
if (color < mask[maskOffset] || color > mask[maskOffset + 1]) {
opacity = 255;
break;
}
if (color < mask[maskOffset] || color > mask[maskOffset + 1]) {
opacity = 255;
break;
}
alphaBuf[i] = opacity;
}
} else {
throw new _util.FormatError("Unknown mask format.");
}
}
if (alphaBuf) {
for (i = 0, j = 3, ii = width * actualHeight; i < ii; ++i, j += 4) {
rgbaBuf[j] = alphaBuf[i];
alphaBuf[i] = opacity;
}
} else {
for (i = 0, j = 3, ii = width * actualHeight; i < ii; ++i, j += 4) {
rgbaBuf[j] = 255;
}
throw new _util.FormatError("Unknown mask format.");
}
},
}
undoPreblend(buffer, width, height) {
var matte = this.smask && this.smask.matte;
if (!matte) {
return;
if (alphaBuf) {
for (i = 0, j = 3, ii = width * actualHeight; i < ii; ++i, j += 4) {
rgbaBuf[j] = alphaBuf[i];
}
} else {
for (i = 0, j = 3, ii = width * actualHeight; i < ii; ++i, j += 4) {
rgbaBuf[j] = 255;
}
}
}
var matteRgb = this.colorSpace.getRgb(matte, 0);
var matteR = matteRgb[0];
var matteG = matteRgb[1];
var matteB = matteRgb[2];
var length = width * height * 4;
undoPreblend(buffer, width, height) {
var matte = this.smask && this.smask.matte;
for (var i = 0; i < length; i += 4) {
var alpha = buffer[i + 3];
if (!matte) {
return;
}
if (alpha === 0) {
buffer[i] = 255;
buffer[i + 1] = 255;
buffer[i + 2] = 255;
continue;
}
var matteRgb = this.colorSpace.getRgb(matte, 0);
var matteR = matteRgb[0];
var matteG = matteRgb[1];
var matteB = matteRgb[2];
var length = width * height * 4;
var k = 255 / alpha;
buffer[i] = (buffer[i] - matteR) * k + matteR;
buffer[i + 1] = (buffer[i + 1] - matteG) * k + matteG;
buffer[i + 2] = (buffer[i + 2] - matteB) * k + matteB;
for (var i = 0; i < length; i += 4) {
var alpha = buffer[i + 3];
if (alpha === 0) {
buffer[i] = 255;
buffer[i + 1] = 255;
buffer[i + 2] = 255;
continue;
}
},
createImageData(forceRGBA = false) {
var drawWidth = this.drawWidth;
var drawHeight = this.drawHeight;
var imgData = {
width: drawWidth,
height: drawHeight,
kind: 0,
data: null
};
var numComps = this.numComps;
var originalWidth = this.width;
var originalHeight = this.height;
var bpc = this.bpc;
var rowBytes = originalWidth * numComps * bpc + 7 >> 3;
var imgArray;
var k = 255 / alpha;
buffer[i] = (buffer[i] - matteR) * k + matteR;
buffer[i + 1] = (buffer[i + 1] - matteG) * k + matteG;
buffer[i + 2] = (buffer[i + 2] - matteB) * k + matteB;
}
}
if (!forceRGBA) {
var kind;
createImageData(forceRGBA = false) {
var drawWidth = this.drawWidth;
var drawHeight = this.drawHeight;
var imgData = {
width: drawWidth,
height: drawHeight,
kind: 0,
data: null
};
var numComps = this.numComps;
var originalWidth = this.width;
var originalHeight = this.height;
var bpc = this.bpc;
var rowBytes = originalWidth * numComps * bpc + 7 >> 3;
var imgArray;
if (this.colorSpace.name === "DeviceGray" && bpc === 1) {
kind = _util.ImageKind.GRAYSCALE_1BPP;
} else if (this.colorSpace.name === "DeviceRGB" && bpc === 8 && !this.needsDecode) {
kind = _util.ImageKind.RGB_24BPP;
}
if (!forceRGBA) {
var kind;
if (kind && !this.smask && !this.mask && drawWidth === originalWidth && drawHeight === originalHeight) {
imgData.kind = kind;
imgArray = this.getImageBytes(originalHeight * rowBytes);
if (this.colorSpace.name === "DeviceGray" && bpc === 1) {
kind = _util.ImageKind.GRAYSCALE_1BPP;
} else if (this.colorSpace.name === "DeviceRGB" && bpc === 8 && !this.needsDecode) {
kind = _util.ImageKind.RGB_24BPP;
}
if (this.image instanceof _stream.DecodeStream) {
imgData.data = imgArray;
} else {
var newArray = new Uint8ClampedArray(imgArray.length);
newArray.set(imgArray);
imgData.data = newArray;
}
if (kind && !this.smask && !this.mask && drawWidth === originalWidth && drawHeight === originalHeight) {
imgData.kind = kind;
imgArray = this.getImageBytes(originalHeight * rowBytes);
if (this.needsDecode) {
(0, _util.assert)(kind === _util.ImageKind.GRAYSCALE_1BPP, "PDFImage.createImageData: The image must be grayscale.");
var buffer = imgData.data;
for (var i = 0, ii = buffer.length; i < ii; i++) {
buffer[i] ^= 0xff;
}
}
return imgData;
if (this.image instanceof _stream.DecodeStream) {
imgData.data = imgArray;
} else {
var newArray = new Uint8ClampedArray(imgArray.length);
newArray.set(imgArray);
imgData.data = newArray;
}
if (this.image instanceof _jpeg_stream.JpegStream && !this.smask && !this.mask) {
let imageLength = originalHeight * rowBytes;
if (this.needsDecode) {
(0, _util.assert)(kind === _util.ImageKind.GRAYSCALE_1BPP, "PDFImage.createImageData: The image must be grayscale.");
var buffer = imgData.data;
switch (this.colorSpace.name) {
case "DeviceGray":
imageLength *= 3;
case "DeviceRGB":
case "DeviceCMYK":
imgData.kind = _util.ImageKind.RGB_24BPP;
imgData.data = this.getImageBytes(imageLength, drawWidth, drawHeight, true);
return imgData;
for (var i = 0, ii = buffer.length; i < ii; i++) {
buffer[i] ^= 0xff;
}
}
return imgData;
}
imgArray = this.getImageBytes(originalHeight * rowBytes);
var actualHeight = 0 | imgArray.length / rowBytes * drawHeight / originalHeight;
var comps = this.getComponents(imgArray);
var alpha01, maybeUndoPreblend;
if (this.image instanceof _jpeg_stream.JpegStream && !this.smask && !this.mask) {
let imageLength = originalHeight * rowBytes;
if (!forceRGBA && !this.smask && !this.mask) {
imgData.kind = _util.ImageKind.RGB_24BPP;
imgData.data = new Uint8ClampedArray(drawWidth * drawHeight * 3);
alpha01 = 0;
maybeUndoPreblend = false;
} else {
imgData.kind = _util.ImageKind.RGBA_32BPP;
imgData.data = new Uint8ClampedArray(drawWidth * drawHeight * 4);
alpha01 = 1;
maybeUndoPreblend = true;
this.fillOpacity(imgData.data, drawWidth, drawHeight, actualHeight, comps);
}
switch (this.colorSpace.name) {
case "DeviceGray":
imageLength *= 3;
if (this.needsDecode) {
this.decodeBuffer(comps);
case "DeviceRGB":
case "DeviceCMYK":
imgData.kind = _util.ImageKind.RGB_24BPP;
imgData.data = this.getImageBytes(imageLength, drawWidth, drawHeight, true);
return imgData;
}
}
}
this.colorSpace.fillRgb(imgData.data, originalWidth, originalHeight, drawWidth, drawHeight, actualHeight, bpc, comps, alpha01);
imgArray = this.getImageBytes(originalHeight * rowBytes);
var actualHeight = 0 | imgArray.length / rowBytes * drawHeight / originalHeight;
var comps = this.getComponents(imgArray);
var alpha01, maybeUndoPreblend;
if (maybeUndoPreblend) {
this.undoPreblend(imgData.data, drawWidth, actualHeight);
}
if (!forceRGBA && !this.smask && !this.mask) {
imgData.kind = _util.ImageKind.RGB_24BPP;
imgData.data = new Uint8ClampedArray(drawWidth * drawHeight * 3);
alpha01 = 0;
maybeUndoPreblend = false;
} else {
imgData.kind = _util.ImageKind.RGBA_32BPP;
imgData.data = new Uint8ClampedArray(drawWidth * drawHeight * 4);
alpha01 = 1;
maybeUndoPreblend = true;
this.fillOpacity(imgData.data, drawWidth, drawHeight, actualHeight, comps);
}
return imgData;
},
if (this.needsDecode) {
this.decodeBuffer(comps);
}
fillGrayBuffer(buffer) {
var numComps = this.numComps;
this.colorSpace.fillRgb(imgData.data, originalWidth, originalHeight, drawWidth, drawHeight, actualHeight, bpc, comps, alpha01);
if (numComps !== 1) {
throw new _util.FormatError(`Reading gray scale from a color image: ${numComps}`);
}
if (maybeUndoPreblend) {
this.undoPreblend(imgData.data, drawWidth, actualHeight);
}
var width = this.width;
var height = this.height;
var bpc = this.bpc;
var rowBytes = width * numComps * bpc + 7 >> 3;
var imgArray = this.getImageBytes(height * rowBytes);
var comps = this.getComponents(imgArray);
var i, length;
return imgData;
}
if (bpc === 1) {
length = width * height;
fillGrayBuffer(buffer) {
var numComps = this.numComps;
if (this.needsDecode) {
for (i = 0; i < length; ++i) {
buffer[i] = comps[i] - 1 & 255;
}
} else {
for (i = 0; i < length; ++i) {
buffer[i] = -comps[i] & 255;
}
}
if (numComps !== 1) {
throw new _util.FormatError(`Reading gray scale from a color image: ${numComps}`);
}
return;
}
var width = this.width;
var height = this.height;
var bpc = this.bpc;
var rowBytes = width * numComps * bpc + 7 >> 3;
var imgArray = this.getImageBytes(height * rowBytes);
var comps = this.getComponents(imgArray);
var i, length;
if (bpc === 1) {
length = width * height;
if (this.needsDecode) {
this.decodeBuffer(comps);
for (i = 0; i < length; ++i) {
buffer[i] = comps[i] - 1 & 255;
}
} else {
for (i = 0; i < length; ++i) {
buffer[i] = -comps[i] & 255;
}
}
length = width * height;
var scale = 255 / ((1 << bpc) - 1);
return;
}
for (i = 0; i < length; ++i) {
buffer[i] = scale * comps[i];
}
},
if (this.needsDecode) {
this.decodeBuffer(comps);
}
getImageBytes(length, drawWidth, drawHeight, forceRGB = false) {
this.image.reset();
this.image.drawWidth = drawWidth || this.width;
this.image.drawHeight = drawHeight || this.height;
this.image.forceRGB = !!forceRGB;
return this.image.getBytes(length, true);
length = width * height;
var scale = 255 / ((1 << bpc) - 1);
for (i = 0; i < length; ++i) {
buffer[i] = scale * comps[i];
}
}
};
return PDFImage;
}();
getImageBytes(length, drawWidth, drawHeight, forceRGB = false) {
this.image.reset();
this.image.drawWidth = drawWidth || this.width;
this.image.drawHeight = drawHeight || this.height;
this.image.forceRGB = !!forceRGB;
return this.image.getBytes(length, true);
}
}
exports.PDFImage = PDFImage;

@@ -157,5 +157,5 @@ /**

if (parseDNLMarker) {
const maybeScanLines = blockRow * 8;
const maybeScanLines = blockRow * (frame.precision === 8 ? 8 : 0);
if (maybeScanLines > 0 && maybeScanLines < frame.scanLines / 10) {
if (maybeScanLines > 0 && Math.round(frame.scanLines / maybeScanLines) >= 10) {
throw new DNLMarkerError("Found EOI marker (0xFFD9) while parsing scan data, " + "possibly caused by incorrect `scanLines` parameter", maybeScanLines);

@@ -980,4 +980,6 @@ }

for (i = 0; i < selectorsCount; i++) {
var componentIndex = frame.componentIds[data[offset++]];
const index = data[offset++];
var componentIndex = frame.componentIds[index];
component = frame.components[componentIndex];
component.index = index;
var tableSpec = data[offset++];

@@ -1059,2 +1061,3 @@ component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4];

this.components.push({
index: component.index,
output: buildComponentData(frame, component),

@@ -1140,2 +1143,4 @@ scaleX: component.h / frame.maxH,

return false;
} else if (this.components[0].index === 0x52 && this.components[1].index === 0x47 && this.components[2].index === 0x42) {
return false;
}

@@ -1142,0 +1147,0 @@

@@ -215,7 +215,9 @@ /**

var firstPIMXOArg0 = argsArray[iFirstPIMXO][0];
const firstTransformArg0 = argsArray[iFirstTransform][0],
firstTransformArg1 = argsArray[iFirstTransform][1],
firstTransformArg2 = argsArray[iFirstTransform][2],
firstTransformArg3 = argsArray[iFirstTransform][3];
if (argsArray[iFirstTransform][1] === 0 && argsArray[iFirstTransform][2] === 0) {
if (firstTransformArg1 === firstTransformArg2) {
isSameImage = true;
var firstTransformArg0 = argsArray[iFirstTransform][0];
var firstTransformArg3 = argsArray[iFirstTransform][3];
iTransform = iFirstTransform + 4;

@@ -227,3 +229,3 @@ var iPIMXO = iFirstPIMXO + 4;

if (argsArray[iPIMXO][0] !== firstPIMXOArg0 || transformArgs[0] !== firstTransformArg0 || transformArgs[1] !== 0 || transformArgs[2] !== 0 || transformArgs[3] !== firstTransformArg3) {
if (argsArray[iPIMXO][0] !== firstPIMXOArg0 || transformArgs[0] !== firstTransformArg0 || transformArgs[1] !== firstTransformArg1 || transformArgs[2] !== firstTransformArg2 || transformArgs[3] !== firstTransformArg3) {
if (q < MIN_IMAGES_IN_MASKS_BLOCK) {

@@ -252,3 +254,3 @@ isSameImage = false;

fnArray.splice(iFirstSave, count * 4, _util.OPS.paintImageMaskXObjectRepeat);
argsArray.splice(iFirstSave, count * 4, [firstPIMXOArg0, firstTransformArg0, firstTransformArg3, positions]);
argsArray.splice(iFirstSave, count * 4, [firstPIMXOArg0, firstTransformArg0, firstTransformArg1, firstTransformArg2, firstTransformArg3, positions]);
} else {

@@ -549,3 +551,3 @@ count = Math.min(count, MAX_IMAGES_IN_MASKS_BLOCK);

function OperatorList(intent, streamSink, pageIndex) {
function OperatorList(intent, streamSink) {
this._streamSink = streamSink;

@@ -561,6 +563,4 @@ this.fnArray = [];

this.dependencies = Object.create(null);
this.dependencies = new Set();
this._totalLength = 0;
this.pageIndex = pageIndex;
this.intent = intent;
this.weight = 0;

@@ -597,7 +597,7 @@ this._resolved = streamSink ? null : Promise.resolve();

addDependency(dependency) {
if (dependency in this.dependencies) {
if (this.dependencies.has(dependency)) {
return;
}
this.dependencies[dependency] = true;
this.dependencies.add(dependency);
this.addOp(_util.OPS.dependency, [dependency]);

@@ -607,4 +607,4 @@ },

addDependencies(dependencies) {
for (var key in dependencies) {
this.addDependency(key);
for (const dependency of dependencies) {
this.addDependency(dependency);
}

@@ -619,3 +619,5 @@ },

Object.assign(this.dependencies, opList.dependencies);
for (const dependency of opList.dependencies) {
this.dependencies.add(dependency);
}

@@ -674,3 +676,3 @@ for (var i = 0, ii = opList.length; i < ii; i++) {

this.dependencies = Object.create(null);
this.dependencies.clear();
this.fnArray.length = 0;

@@ -677,0 +679,0 @@ this.argsArray.length = 0;

@@ -199,6 +199,7 @@ /**

LF = 0xa,
CR = 0xd;
const n = 10,
CR = 0xd,
NUL = 0x0;
const startPos = stream.pos;
const lexer = this.lexer,
startPos = stream.pos,
n = 10;
let state = 0,

@@ -233,2 +234,16 @@ ch,

if (state !== 2) {
continue;
}
if (lexer.knownCommands) {
const nextObj = lexer.peekObj();
if (nextObj instanceof _primitives.Cmd && !lexer.knownCommands[nextObj.cmd]) {
state = 0;
}
} else {
(0, _util.warn)("findDefaultInlineStreamEnd - `lexer.knownCommands` is undefined.");
}
if (state === 2) {

@@ -1239,2 +1254,24 @@ break;

peekObj() {
const streamPos = this.stream.pos,
currentChar = this.currentChar,
beginInlineImagePos = this.beginInlineImagePos;
let nextObj;
try {
nextObj = this.getObj();
} catch (ex) {
if (ex instanceof _core_utils.MissingDataException) {
throw ex;
}
(0, _util.warn)(`peekObj: ${ex}`);
}
this.stream.pos = streamPos;
this.currentChar = currentChar;
this.beginInlineImagePos = beginInlineImagePos;
return nextObj;
}
skipToNextLine() {

@@ -1241,0 +1278,0 @@ let ch = this.currentChar;

@@ -59,3 +59,3 @@ /**

Pattern.parseShading = function (shading, matrix, xref, res, handler, pdfFunctionFactory) {
Pattern.parseShading = function (shading, matrix, xref, res, handler, pdfFunctionFactory, localColorSpaceCache) {
var dict = (0, _primitives.isStream)(shading) ? shading.dict : shading;

@@ -68,3 +68,3 @@ var type = dict.get("ShadingType");

case ShadingType.RADIAL:
return new Shadings.RadialAxial(dict, matrix, xref, res, pdfFunctionFactory);
return new Shadings.RadialAxial(dict, matrix, xref, res, pdfFunctionFactory, localColorSpaceCache);

@@ -75,3 +75,3 @@ case ShadingType.FREE_FORM_MESH:

case ShadingType.TENSOR_PATCH_MESH:
return new Shadings.Mesh(shading, matrix, xref, res, pdfFunctionFactory);
return new Shadings.Mesh(shading, matrix, xref, res, pdfFunctionFactory, localColorSpaceCache);

@@ -102,3 +102,3 @@ default:

Shadings.RadialAxial = function RadialAxialClosure() {
function RadialAxial(dict, matrix, xref, res, pdfFunctionFactory) {
function RadialAxial(dict, matrix, xref, resources, pdfFunctionFactory, localColorSpaceCache) {
this.matrix = matrix;

@@ -108,4 +108,11 @@ this.coordsArr = dict.getArray("Coords");

this.type = "Pattern";
var cs = dict.get("ColorSpace", "CS");
cs = _colorspace.ColorSpace.parse(cs, xref, res, pdfFunctionFactory);
const cs = _colorspace.ColorSpace.parse({
cs: dict.getRaw("ColorSpace") || dict.getRaw("CS"),
xref,
resources,
pdfFunctionFactory,
localColorSpaceCache
});
this.cs = cs;

@@ -154,3 +161,3 @@ const bbox = dict.getArray("BBox");

this.extendEnd = extendEnd;
var fnObj = dict.get("Function");
var fnObj = dict.getRaw("Function");
var fn = pdfFunctionFactory.createFromArray(fnObj);

@@ -844,3 +851,3 @@ const NUMBER_OF_SAMPLES = 10;

function Mesh(stream, matrix, xref, res, pdfFunctionFactory) {
function Mesh(stream, matrix, xref, resources, pdfFunctionFactory, localColorSpaceCache) {
if (!(0, _primitives.isStream)(stream)) {

@@ -862,7 +869,13 @@ throw new _util.FormatError("Mesh data is not a stream");

var cs = dict.get("ColorSpace", "CS");
cs = _colorspace.ColorSpace.parse(cs, xref, res, pdfFunctionFactory);
const cs = _colorspace.ColorSpace.parse({
cs: dict.getRaw("ColorSpace") || dict.getRaw("CS"),
xref,
resources,
pdfFunctionFactory,
localColorSpaceCache
});
this.cs = cs;
this.background = dict.has("Background") ? cs.getRgb(dict.get("Background"), 0) : null;
var fnObj = dict.get("Function");
var fnObj = dict.getRaw("Function");
var fn = fnObj ? pdfFunctionFactory.createFromArray(fnObj) : null;

@@ -869,0 +882,0 @@ this.coords = [];

@@ -106,2 +106,6 @@ /**

get size() {
return Object.keys(this._map).length;
},
get(key1, key2, key3) {

@@ -169,2 +173,5 @@ let value = this._map[key1];

},
getRawValues: function Dict_getRawValues() {
return Object.values(this._map);
},
set: function Dict_set(key, value) {

@@ -184,22 +191,71 @@ this._map[key] = value;

Dict.merge = function (xref, dictArray) {
Dict.merge = function ({
xref,
dictArray,
mergeSubDicts = false
}) {
const mergedDict = new Dict(xref);
for (let i = 0, ii = dictArray.length; i < ii; i++) {
const dict = dictArray[i];
if (!mergeSubDicts) {
for (const dict of dictArray) {
if (!(dict instanceof Dict)) {
continue;
}
if (!isDict(dict)) {
for (const [key, value] of Object.entries(dict._map)) {
if (mergedDict._map[key] === undefined) {
mergedDict._map[key] = value;
}
}
}
return mergedDict.size > 0 ? mergedDict : Dict.empty;
}
const properties = new Map();
for (const dict of dictArray) {
if (!(dict instanceof Dict)) {
continue;
}
for (const keyName in dict._map) {
if (mergedDict._map[keyName] !== undefined) {
for (const [key, value] of Object.entries(dict._map)) {
let property = properties.get(key);
if (property === undefined) {
property = [];
properties.set(key, property);
}
property.push(value);
}
}
for (const [name, values] of properties) {
if (values.length === 1 || !(values[0] instanceof Dict)) {
mergedDict._map[name] = values[0];
continue;
}
const subDict = new Dict(xref);
for (const dict of values) {
if (!(dict instanceof Dict)) {
continue;
}
mergedDict._map[keyName] = dict._map[keyName];
for (const [key, value] of Object.entries(dict._map)) {
if (subDict._map[key] === undefined) {
subDict._map[key] = value;
}
}
}
if (subDict.size > 0) {
mergedDict._map[name] = subDict;
}
}
return mergedDict;
properties.clear();
return mergedDict.size > 0 ? mergedDict : Dict.empty;
};

@@ -245,57 +301,60 @@

var RefSet = function RefSetClosure() {
function RefSet() {
this.dict = Object.create(null);
class RefSet {
constructor() {
this._set = new Set();
}
RefSet.prototype = {
has: function RefSet_has(ref) {
return ref.toString() in this.dict;
},
put: function RefSet_put(ref) {
this.dict[ref.toString()] = true;
},
remove: function RefSet_remove(ref) {
delete this.dict[ref.toString()];
}
};
return RefSet;
}();
has(ref) {
return this._set.has(ref.toString());
}
put(ref) {
this._set.add(ref.toString());
}
remove(ref) {
this._set.delete(ref.toString());
}
}
exports.RefSet = RefSet;
var RefSetCache = function RefSetCacheClosure() {
function RefSetCache() {
this.dict = Object.create(null);
class RefSetCache {
constructor() {
this._map = new Map();
}
RefSetCache.prototype = {
get size() {
return Object.keys(this.dict).length;
},
get size() {
return this._map.size;
}
get: function RefSetCache_get(ref) {
return this.dict[ref.toString()];
},
has: function RefSetCache_has(ref) {
return ref.toString() in this.dict;
},
put: function RefSetCache_put(ref, obj) {
this.dict[ref.toString()] = obj;
},
putAlias: function RefSetCache_putAlias(ref, aliasRef) {
this.dict[ref.toString()] = this.get(aliasRef);
},
forEach: function RefSetCache_forEach(callback) {
for (const i in this.dict) {
callback(this.dict[i]);
}
},
clear: function RefSetCache_clear() {
this.dict = Object.create(null);
get(ref) {
return this._map.get(ref.toString());
}
has(ref) {
return this._map.has(ref.toString());
}
put(ref, obj) {
this._map.set(ref.toString(), obj);
}
putAlias(ref, aliasRef) {
this._map.set(ref.toString(), this.get(aliasRef));
}
forEach(callback) {
for (const value of this._map.values()) {
callback(value);
}
};
return RefSetCache;
}();
}
clear() {
this._map.clear();
}
}
exports.RefSetCache = RefSetCache;

@@ -302,0 +361,0 @@

@@ -220,3 +220,5 @@ /**

if (seacAnalysisEnabled) {
const asb = this.stack[this.stack.length - 5];
this.seac = this.stack.splice(-4, 4);
this.seac[0] += this.lsb - asb;
error = this.executeCommand(0, COMMAND_MAP.endchar);

@@ -223,0 +225,0 @@ } else {

@@ -35,2 +35,4 @@ /**

var _writer = require("./writer.js");
var _is_node = require("../shared/is_node.js");

@@ -44,4 +46,4 @@

var WorkerTask = function WorkerTaskClosure() {
function WorkerTask(name) {
class WorkerTask {
constructor(name) {
this.name = name;

@@ -52,28 +54,26 @@ this.terminated = false;

WorkerTask.prototype = {
get finished() {
return this._capability.promise;
},
get finished() {
return this._capability.promise;
}
finish() {
this._capability.resolve();
},
finish() {
this._capability.resolve();
}
terminate() {
this.terminated = true;
},
terminate() {
this.terminated = true;
}
ensureNotTerminated() {
if (this.terminated) {
throw new Error("Worker task was terminated");
}
ensureNotTerminated() {
if (this.terminated) {
throw new Error("Worker task was terminated");
}
}
};
return WorkerTask;
}();
}
exports.WorkerTask = WorkerTask;
var WorkerMessageHandler = {
setup(handler, port) {
class WorkerMessageHandler {
static setup(handler, port) {
var testMessageProcessed = false;

@@ -104,5 +104,5 @@ handler.on("test", function wphSetupTest(data) {

});
},
}
createDocumentHandler(docParams, port) {
static createDocumentHandler(docParams, port) {
var pdfManager;

@@ -114,3 +114,3 @@ var terminated = false;

const apiVersion = docParams.apiVersion;
const workerVersion = '2.5.207';
const workerVersion = '2.6.347';

@@ -329,7 +329,7 @@ if (apiVersion !== workerVersion) {

ensureNotTerminated();
loadDocument(false).then(onSuccess, function loadFailure(ex) {
loadDocument(false).then(onSuccess, function (reason) {
ensureNotTerminated();
if (!(ex instanceof _core_utils.XRefParseException)) {
onFailure(ex);
if (!(reason instanceof _core_utils.XRefParseException)) {
onFailure(reason);
return;

@@ -343,3 +343,3 @@ }

});
}, onFailure);
});
}

@@ -382,7 +382,8 @@

});
handler.on("GetPageIndex", function wphSetupGetPageIndex(data) {
var ref = _primitives.Ref.get(data.ref.num, data.ref.gen);
handler.on("GetPageIndex", function wphSetupGetPageIndex({
ref
}) {
const pageRef = _primitives.Ref.get(ref.num, ref.gen);
var catalog = pdfManager.pdfDocument.catalog;
return catalog.getPageIndex(ref);
return pdfManager.ensureCatalog("getPageIndex", [pageRef]);
});

@@ -419,2 +420,5 @@ handler.on("GetDestinations", function wphSetupGetDestinations(data) {

});
handler.on("GetOptionalContentConfig", function (data) {
return pdfManager.ensureCatalog("optionalContentConfig");
});
handler.on("GetPermissions", function (data) {

@@ -433,3 +437,3 @@ return pdfManager.ensureCatalog("permissions");

handler.on("GetStats", function wphSetupGetStats(data) {
return pdfManager.pdfDocument.xref.stats;
return pdfManager.ensureXRef("stats");
});

@@ -444,2 +448,61 @@ handler.on("GetAnnotations", function ({

});
handler.on("SaveDocument", function ({
numPages,
annotationStorage,
filename
}) {
pdfManager.requestLoadedStream();
const promises = [pdfManager.onLoadedStream()];
const document = pdfManager.pdfDocument;
for (let pageIndex = 0; pageIndex < numPages; pageIndex++) {
promises.push(pdfManager.getPage(pageIndex).then(function (page) {
const task = new WorkerTask(`Save: page ${pageIndex}`);
return page.save(handler, task, annotationStorage);
}));
}
return Promise.all(promises).then(([stream, ...refs]) => {
let newRefs = [];
for (const ref of refs) {
newRefs = ref.filter(x => x !== null).reduce((a, b) => a.concat(b), newRefs);
}
if (newRefs.length === 0) {
return stream.bytes;
}
const xref = document.xref;
let newXrefInfo = Object.create(null);
if (xref.trailer) {
const _info = Object.create(null);
const xrefInfo = xref.trailer.get("Info") || null;
if (xrefInfo) {
xrefInfo.forEach((key, value) => {
if ((0, _util.isString)(key) && (0, _util.isString)(value)) {
_info[key] = (0, _util.stringToPDFString)(value);
}
});
}
newXrefInfo = {
rootRef: xref.trailer.getRaw("Root") || null,
encrypt: xref.trailer.getRaw("Encrypt") || null,
newRef: xref.getNewRef(),
infoRef: xref.trailer.getRaw("Info") || null,
info: _info,
fileIds: xref.trailer.getRaw("ID") || null,
startXRef: document.startXRef,
filename
};
}
xref.resetNewRef();
return (0, _writer.incrementalUpdate)(stream.bytes, newXrefInfo, newRefs);
});
});
handler.on("GetOperatorList", function wphSetupRenderPage(data, sink) {

@@ -456,3 +519,4 @@ var pageIndex = data.pageIndex;

intent: data.intent,
renderInteractiveForms: data.renderInteractiveForms
renderInteractiveForms: data.renderInteractiveForms,
annotationStorage: data.annotationStorage
}).then(function (operatorListInfo) {

@@ -553,5 +617,5 @@ finishWorkerTask(task);

return workerHandlerName;
},
}
initializeFromPort(port) {
static initializeFromPort(port) {
var handler = new _message_handler.MessageHandler("worker", "main", port);

@@ -562,3 +626,4 @@ WorkerMessageHandler.setup(handler, port);

};
}
exports.WorkerMessageHandler = WorkerMessageHandler;

@@ -565,0 +630,0 @@

@@ -33,2 +33,4 @@ /**

var _annotation_storage = require("./annotation_storage.js");
class AnnotationElementFactory {

@@ -131,2 +133,3 @@ static create(parameters) {

this.svgFactory = parameters.svgFactory;
this.annotationStorage = parameters.annotationStorage;

@@ -338,2 +341,4 @@ if (isRenderable) {

const TEXT_ALIGNMENT = ["left", "center", "right"];
const storage = this.annotationStorage;
const id = this.data.id;
this.container.className = "textWidgetAnnotation";

@@ -343,11 +348,16 @@ let element = null;

if (this.renderInteractiveForms) {
const textContent = storage.getOrCreateValue(id, this.data.fieldValue);
if (this.data.multiLine) {
element = document.createElement("textarea");
element.textContent = this.data.fieldValue;
element.textContent = textContent;
} else {
element = document.createElement("input");
element.type = "text";
element.setAttribute("value", this.data.fieldValue);
element.setAttribute("value", textContent);
}
element.addEventListener("input", function (event) {
storage.setValue(id, event.target.value);
});
element.disabled = this.data.readOnly;

@@ -420,12 +430,19 @@ element.name = this.data.fieldName;

render() {
const storage = this.annotationStorage;
const data = this.data;
const id = data.id;
const value = storage.getOrCreateValue(id, data.fieldValue && data.fieldValue !== "Off");
this.container.className = "buttonWidgetAnnotation checkBox";
const element = document.createElement("input");
element.disabled = this.data.readOnly;
element.disabled = data.readOnly;
element.type = "checkbox";
element.name = this.data.fieldName;
if (this.data.fieldValue && this.data.fieldValue !== "Off") {
if (value) {
element.setAttribute("checked", true);
}
element.addEventListener("change", function (event) {
storage.setValue(id, event.target.checked);
});
this.container.appendChild(element);

@@ -444,11 +461,26 @@ return this.container;

this.container.className = "buttonWidgetAnnotation radioButton";
const storage = this.annotationStorage;
const data = this.data;
const id = data.id;
const value = storage.getOrCreateValue(id, data.fieldValue === data.buttonValue);
const element = document.createElement("input");
element.disabled = this.data.readOnly;
element.disabled = data.readOnly;
element.type = "radio";
element.name = this.data.fieldName;
element.name = data.fieldName;
if (this.data.fieldValue === this.data.buttonValue) {
if (value) {
element.setAttribute("checked", true);
}
element.addEventListener("change", function (event) {
const name = event.target.name;
for (const radio of document.getElementsByName(name)) {
if (radio !== event.target) {
storage.setValue(radio.parentNode.getAttribute("data-annotation-id"), false);
}
}
storage.setValue(id, event.target.checked);
});
this.container.appendChild(element);

@@ -476,2 +508,5 @@ return this.container;

this.container.className = "choiceWidgetAnnotation";
const storage = this.annotationStorage;
const id = this.data.id;
storage.getOrCreateValue(id, this.data.fieldValue.length > 0 ? this.data.fieldValue[0] : null);
const selectElement = document.createElement("select");

@@ -494,3 +529,3 @@ selectElement.disabled = this.data.readOnly;

if (this.data.fieldValue.includes(option.displayValue)) {
if (this.data.fieldValue.includes(option.exportValue)) {
optionElement.setAttribute("selected", true);

@@ -502,2 +537,7 @@ }

selectElement.addEventListener("input", function (event) {
const options = event.target.options;
const value = options[options.selectedIndex].value;
storage.setValue(id, value);
});
this.container.appendChild(selectElement);

@@ -1036,4 +1076,5 @@ return this.container;

imageResourcesPath: parameters.imageResourcesPath || "",
renderInteractiveForms: parameters.renderInteractiveForms || false,
svgFactory: new _display_utils.DOMSVGFactory()
renderInteractiveForms: typeof parameters.renderInteractiveForms === "boolean" ? parameters.renderInteractiveForms : true,
svgFactory: new _display_utils.DOMSVGFactory(),
annotationStorage: parameters.annotationStorage || new _annotation_storage.AnnotationStorage()
});

@@ -1040,0 +1081,0 @@

@@ -37,2 +37,6 @@ /**

var _node_utils = require("./node_utils.js");
var _annotation_storage = require("./annotation_storage.js");
var _api_compatibility = require("./api_compatibility.js");

@@ -50,2 +54,4 @@

var _optional_content_config = require("./optional_content_config.js");
var _transport_stream = require("./transport_stream.js");

@@ -57,2 +63,4 @@

const RENDERING_CANCELLED_TIMEOUT = 100;
const DefaultCanvasFactory = _is_node.isNodeJS ? _node_utils.NodeCanvasFactory : _display_utils.DOMCanvasFactory;
const DefaultCMapReaderFactory = _is_node.isNodeJS ? _node_utils.NodeCMapReaderFactory : _display_utils.DOMCMapReaderFactory;
let createPDFNetworkStream;

@@ -126,3 +134,3 @@

params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
params.CMapReaderFactory = params.CMapReaderFactory || _display_utils.DOMCMapReaderFactory;
params.CMapReaderFactory = params.CMapReaderFactory || DefaultCMapReaderFactory;
params.ignoreErrors = params.stopAtErrors !== true;

@@ -144,2 +152,6 @@ params.fontExtraProperties = params.fontExtraProperties === true;

if (typeof params.ownerDocument === "undefined") {
params.ownerDocument = globalThis.document;
}
if (typeof params.disableRange !== "boolean") {

@@ -229,3 +241,3 @@ params.disableRange = false;

docId,
apiVersion: '2.5.207',
apiVersion: '2.6.347',
source: {

@@ -371,2 +383,6 @@ data: source.data,

get annotationStorage() {
return (0, _util.shadow)(this, "annotationStorage", new _annotation_storage.AnnotationStorage());
}
get numPages() {

@@ -416,9 +432,2 @@ return this._pdfInfo.numPages;

getOpenActionDestination() {
(0, _display_utils.deprecated)("getOpenActionDestination, use getOpenAction instead.");
return this.getOpenAction().then(function (openAction) {
return openAction && openAction.dest ? openAction.dest : null;
});
}
getAttachments() {

@@ -436,2 +445,6 @@ return this._transport.getAttachments();

getOptionalContentConfig() {
return this._transport.getOptionalContentConfig();
}
getPermissions() {

@@ -473,2 +486,6 @@ return this._transport.getPermissions();

saveDocument(annotationStorage) {
return this._transport.saveDocument(annotationStorage);
}
}

@@ -479,5 +496,6 @@

class PDFPageProxy {
constructor(pageIndex, pageInfo, transport, pdfBug = false) {
constructor(pageIndex, pageInfo, transport, ownerDocument, pdfBug = false) {
this._pageIndex = pageIndex;
this._pageInfo = pageInfo;
this._ownerDocument = ownerDocument;
this._transport = transport;

@@ -490,3 +508,3 @@ this._stats = pdfBug ? new _display_utils.StatTimer() : null;

this.pendingCleanup = false;
this.intentStates = Object.create(null);
this._intentStates = new Map();
this.destroyed = false;

@@ -552,3 +570,5 @@ }

canvasFactory = null,
background = null
background = null,
annotationStorage = null,
optionalContentConfigPromise = null
}) {

@@ -562,8 +582,14 @@ if (this._stats) {

if (!this.intentStates[renderingIntent]) {
this.intentStates[renderingIntent] = Object.create(null);
if (!optionalContentConfigPromise) {
optionalContentConfigPromise = this._transport.getOptionalContentConfig();
}
const intentState = this.intentStates[renderingIntent];
let intentState = this._intentStates.get(renderingIntent);
if (!intentState) {
intentState = Object.create(null);
this._intentStates.set(renderingIntent, intentState);
}
if (intentState.streamReaderCancelTimeout) {

@@ -574,3 +600,5 @@ clearTimeout(intentState.streamReaderCancelTimeout);

const canvasFactoryInstance = canvasFactory || new _display_utils.DOMCanvasFactory();
const canvasFactoryInstance = canvasFactory || new DefaultCanvasFactory({
ownerDocument: this._ownerDocument
});
const webGLContext = new _webgl.WebGLContext({

@@ -595,3 +623,4 @@ enable: enableWebGL

intent: renderingIntent,
renderInteractiveForms: renderInteractiveForms === true
renderInteractiveForms: renderInteractiveForms === true,
annotationStorage: annotationStorage && annotationStorage.getAll() || null
});

@@ -656,3 +685,3 @@ }

const renderTask = internalRenderTask.task;
intentState.displayReadyCapability.promise.then(transparency => {
Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
if (this.pendingCleanup) {

@@ -667,3 +696,6 @@ complete();

internalRenderTask.initializeGraphics(transparency);
internalRenderTask.initializeGraphics({
transparency,
optionalContentConfig
});
internalRenderTask.operatorListChanged();

@@ -688,11 +720,14 @@ }).catch(complete);

if (!this.intentStates[renderingIntent]) {
this.intentStates[renderingIntent] = Object.create(null);
let intentState = this._intentStates.get(renderingIntent);
if (!intentState) {
intentState = Object.create(null);
this._intentStates.set(renderingIntent, intentState);
}
const intentState = this.intentStates[renderingIntent];
let opListTask;
if (!intentState.opListReadCapability) {
opListTask = {};
opListTask = Object.create(null);
opListTask.operatorListChanged = operatorListChanged;

@@ -772,5 +807,4 @@ intentState.opListReadCapability = (0, _util.createPromiseCapability)();

const waitOn = [];
Object.keys(this.intentStates).forEach(intent => {
const intentState = this.intentStates[intent];
for (const [intent, intentState] of this._intentStates) {
this._abortOperatorList({

@@ -783,11 +817,11 @@ intentState,

if (intent === "oplist") {
return;
continue;
}
intentState.renderTasks.forEach(function (renderTask) {
const renderCompleted = renderTask.capability.promise.catch(function () {});
waitOn.push(renderCompleted);
renderTask.cancel();
});
});
for (const internalRenderTask of intentState.renderTasks) {
waitOn.push(internalRenderTask.completed);
internalRenderTask.cancel();
}
}
this.objs.clear();

@@ -805,12 +839,17 @@ this.annotationsPromise = null;

_tryCleanup(resetStats = false) {
if (!this.pendingCleanup || Object.keys(this.intentStates).some(intent => {
const intentState = this.intentStates[intent];
return intentState.renderTasks.length !== 0 || !intentState.operatorList.lastChunk;
})) {
if (!this.pendingCleanup) {
return false;
}
Object.keys(this.intentStates).forEach(intent => {
delete this.intentStates[intent];
});
for (const {
renderTasks,
operatorList
} of this._intentStates.values()) {
if (renderTasks.length !== 0 || !operatorList.lastChunk) {
return false;
}
}
this._intentStates.clear();
this.objs.clear();

@@ -828,3 +867,3 @@ this.annotationsPromise = null;

_startRenderPage(transparency, intent) {
const intentState = this.intentStates[intent];
const intentState = this._intentStates.get(intent);

@@ -867,3 +906,5 @@ if (!intentState) {

const reader = readableStream.getReader();
const intentState = this.intentStates[args.intent];
const intentState = this._intentStates.get(args.intent);
intentState.streamReader = reader;

@@ -955,10 +996,10 @@

Object.keys(this.intentStates).some(intent => {
if (this.intentStates[intent] === intentState) {
delete this.intentStates[intent];
return true;
for (const [intent, curIntentState] of this._intentStates) {
if (curIntentState === intentState) {
this._intentStates.delete(intent);
break;
}
}
return false;
});
this.cleanup();

@@ -1380,3 +1421,4 @@ }

docId: loadingTask.docId,
onUnsupportedFeature: this._onUnsupportedFeature.bind(this)
onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
ownerDocument: params.ownerDocument
});

@@ -1474,2 +1516,10 @@ this._params = params;

this._fullReader.cancel(reason);
sink.ready.catch(readyReason => {
if (this.destroyed) {
return;
}
throw readyReason;
});
};

@@ -1533,2 +1583,9 @@ });

rangeReader.cancel(reason);
sink.ready.catch(readyReason => {
if (this.destroyed) {
return;
}
throw readyReason;
});
};

@@ -1568,2 +1625,7 @@ });

if (!(reason instanceof Error)) {
const msg = "DocException - expected a valid Error.";
(0, _util.warn)(msg);
}
loadingTask._capability.reject(reason);

@@ -1665,3 +1727,2 @@ });

case "FontPath":
case "FontType3Res":
case "Image":

@@ -1775,3 +1836,3 @@ this.commonObjs.resolve(id, exportedData);

const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.pdfBug);
const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.ownerDocument, this._params.pdfBug);
this.pageCache[pageIndex] = page;

@@ -1799,2 +1860,14 @@ return page;

saveDocument(annotationStorage) {
return this.messageHandler.sendWithPromise("SaveDocument", {
numPages: this._numPages,
annotationStorage: annotationStorage && annotationStorage.getAll() || null,
filename: this._fullReader ? this._fullReader.filename : null
}).finally(() => {
if (annotationStorage) {
annotationStorage.resetModified();
}
});
}
getDestinations() {

@@ -1846,2 +1919,8 @@ return this.messageHandler.sendWithPromise("GetDestinations", null);

getOptionalContentConfig() {
return this.messageHandler.sendWithPromise("GetOptionalContentConfig", null).then(results => {
return new _optional_content_config.OptionalContentConfig(results);
});
}
getPermissions() {

@@ -2001,3 +2080,10 @@ return this.messageHandler.sendWithPromise("GetPermissions", null);

initializeGraphics(transparency = false) {
get completed() {
return this.capability.promise.catch(function () {});
}
initializeGraphics({
transparency = false,
optionalContentConfig
}) {
if (this.cancelled) {

@@ -2028,3 +2114,3 @@ return;

} = this.params;
this.gfx = new _canvas.CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, this.webGLContext, imageLayer);
this.gfx = new _canvas.CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, this.webGLContext, imageLayer, optionalContentConfig);
this.gfx.beginDrawing({

@@ -2130,5 +2216,5 @@ transform,

const version = '2.5.207';
const version = '2.6.347';
exports.version = version;
const build = '0974d605';
const build = '3be9c65f';
exports.build = build;

@@ -33,3 +33,3 @@ /**

exports.deprecated = deprecated;
exports.PDFDateString = exports.StatTimer = exports.DOMSVGFactory = exports.DOMCMapReaderFactory = exports.DOMCanvasFactory = exports.DEFAULT_LINK_REL = exports.LinkTarget = exports.RenderingCancelledException = exports.PageViewport = void 0;
exports.PDFDateString = exports.StatTimer = exports.DOMSVGFactory = exports.DOMCMapReaderFactory = exports.BaseCMapReaderFactory = exports.DOMCanvasFactory = exports.BaseCanvasFactory = exports.DEFAULT_LINK_REL = exports.LinkTarget = exports.RenderingCancelledException = exports.PageViewport = void 0;

@@ -42,16 +42,11 @@ var _util = require("../shared/util.js");

class DOMCanvasFactory {
create(width, height) {
if (width <= 0 || height <= 0) {
throw new Error("Invalid canvas size");
class BaseCanvasFactory {
constructor() {
if (this.constructor === BaseCanvasFactory) {
(0, _util.unreachable)("Cannot initialize BaseCanvasFactory.");
}
}
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;
return {
canvas,
context
};
create(width, height) {
(0, _util.unreachable)("Abstract method `create` called.");
}

@@ -85,5 +80,33 @@

exports.BaseCanvasFactory = BaseCanvasFactory;
class DOMCanvasFactory extends BaseCanvasFactory {
constructor({
ownerDocument = globalThis.document
} = {}) {
super();
this._document = ownerDocument;
}
create(width, height) {
if (width <= 0 || height <= 0) {
throw new Error("Invalid canvas size");
}
const canvas = this._document.createElement("canvas");
const context = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;
return {
canvas,
context
};
}
}
exports.DOMCanvasFactory = DOMCanvasFactory;
class DOMCMapReaderFactory {
class BaseCMapReaderFactory {
constructor({

@@ -93,2 +116,6 @@ baseUrl = null,

}) {
if (this.constructor === BaseCMapReaderFactory) {
(0, _util.unreachable)("Cannot initialize BaseCMapReaderFactory.");
}
this.baseUrl = baseUrl;

@@ -111,3 +138,17 @@ this.isCompressed = isCompressed;

const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
return this._fetchData(url, compressionType).catch(reason => {
throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
});
}
_fetchData(url, compressionType) {
(0, _util.unreachable)("Abstract method `_fetchData` called.");
}
}
exports.BaseCMapReaderFactory = BaseCMapReaderFactory;
class DOMCMapReaderFactory extends BaseCMapReaderFactory {
_fetchData(url, compressionType) {
if (isFetchSupported() && isValidFetchUrl(url, document.baseURI)) {

@@ -131,4 +172,2 @@ return fetch(url).then(async response => {

};
}).catch(reason => {
throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}` + `CMap at: ${url}`);
});

@@ -172,4 +211,2 @@ }

request.send(null);
}).catch(reason => {
throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}` + `CMap at: ${url}`);
});

@@ -176,0 +213,0 @@ }

@@ -256,2 +256,8 @@ /**

this._reader = response.body.getReader();
}).catch(reason => {
if (reason && reason.name === "AbortError") {
return;
}
throw reason;
});

@@ -258,0 +264,0 @@ this.onProgress = null;

@@ -34,3 +34,4 @@ /**

docId,
onUnsupportedFeature
onUnsupportedFeature,
ownerDocument = globalThis.document
}) {

@@ -43,2 +44,3 @@ if (this.constructor === BaseFontLoader) {

this._onUnsupportedFeature = onUnsupportedFeature;
this._document = ownerDocument;
this.nativeFontFaces = [];

@@ -50,3 +52,4 @@ this.styleElement = null;

this.nativeFontFaces.push(nativeFontFace);
document.fonts.add(nativeFontFace);
this._document.fonts.add(nativeFontFace);
}

@@ -58,5 +61,6 @@

if (!styleElement) {
styleElement = this.styleElement = document.createElement("style");
styleElement = this.styleElement = this._document.createElement("style");
styleElement.id = `PDFJS_FONT_STYLE_TAG_${this.docId}`;
document.documentElement.getElementsByTagName("head")[0].appendChild(styleElement);
this._document.documentElement.getElementsByTagName("head")[0].appendChild(styleElement);
}

@@ -69,4 +73,4 @@

clear() {
this.nativeFontFaces.forEach(function (nativeFontFace) {
document.fonts.delete(nativeFontFace);
this.nativeFontFaces.forEach(nativeFontFace => {
this._document.fonts.delete(nativeFontFace);
});

@@ -132,3 +136,3 @@ this.nativeFontFaces.length = 0;

get isFontLoadingAPISupported() {
const supported = typeof document !== "undefined" && !!document.fonts;
const supported = typeof this._document !== "undefined" && !!this._document.fonts;
return (0, _util.shadow)(this, "isFontLoadingAPISupported", supported);

@@ -155,4 +159,4 @@ }

exports.FontLoader = FontLoader = class GenericFontLoader extends BaseFontLoader {
constructor(docId) {
super(docId);
constructor(params) {
super(params);
this.loadingContext = {

@@ -223,3 +227,5 @@ requests: [],

let i, ii;
const canvas = document.createElement("canvas");
const canvas = this._document.createElement("canvas");
canvas.width = 1;

@@ -278,3 +284,5 @@ canvas.height = 1;

names.push(loadTestFontId);
const div = document.createElement("div");
const div = this._document.createElement("div");
div.style.visibility = "hidden";

@@ -286,3 +294,4 @@ div.style.width = div.style.height = "10px";

for (i = 0, ii = names.length; i < ii; ++i) {
const span = document.createElement("span");
const span = this._document.createElement("span");
span.textContent = "Hi";

@@ -293,5 +302,7 @@ span.style.fontFamily = names[i];

document.body.appendChild(div);
isFontReady(loadTestFontId, function () {
document.body.removeChild(div);
this._document.body.appendChild(div);
isFontReady(loadTestFontId, () => {
this._document.body.removeChild(div);
request.complete();

@@ -298,0 +309,0 @@ });

@@ -128,9 +128,3 @@ /**

getAll() {
const obj = Object.create(null);
for (const [key, value] of this._metadataMap) {
obj[key] = value;
}
return obj;
return Object.fromEntries(this._metadataMap);
}

@@ -137,0 +131,0 @@

@@ -199,10 +199,2 @@ /**

hasPendingRequests() {
for (const xhrId in this.pendingRequests) {
return true;
}
return false;
}
getRequestXhr(xhrId) {

@@ -216,8 +208,2 @@ return this.pendingRequests[xhrId].xhr;

abortAllRequests() {
for (const xhrId in this.pendingRequests) {
this.abortRequest(xhrId | 0);
}
}
abortRequest(xhrId) {

@@ -224,0 +210,0 @@ const xhr = this.pendingRequests[xhrId].xhr;

@@ -1423,3 +1423,3 @@ /**

paintImageXObject(objId) {
const imgData = this.objs.get(objId);
const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId);

@@ -1426,0 +1426,0 @@ if (!imgData) {

@@ -465,2 +465,3 @@ /**

this._container = container;
this._document = container.ownerDocument;
this._viewport = viewport;

@@ -572,3 +573,5 @@ this._textDivs = textDivs || [];

let styleCache = Object.create(null);
const canvas = document.createElement("canvas");
const canvas = this._document.createElement("canvas");
canvas.mozOpaque = true;

@@ -575,0 +578,0 @@ this._layoutTextCtx = canvas.getContext("2d", {

@@ -236,4 +236,4 @@ /**

const pdfjsVersion = '2.5.207';
const pdfjsBuild = '0974d605';
const pdfjsVersion = '2.6.347';
const pdfjsBuild = '3be9c65f';
{

@@ -240,0 +240,0 @@ const {

@@ -36,3 +36,3 @@ /**

const pdfjsVersion = '2.5.207';
const pdfjsBuild = '0974d605';
const pdfjsVersion = '2.6.347';
const pdfjsBuild = '3be9c65f';

@@ -28,3 +28,3 @@ /**

exports.isNodeJS = void 0;
const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !process.versions.electron;
const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
exports.isNodeJS = isNodeJS;

@@ -32,2 +32,4 @@ /**

exports.createPromiseCapability = createPromiseCapability;
exports.escapeString = escapeString;
exports.getModificationDate = getModificationDate;
exports.getVerbosityLevel = getVerbosityLevel;

@@ -38,3 +40,2 @@ exports.info = info;

exports.isBool = isBool;
exports.isEmptyObj = isEmptyObj;
exports.isNum = isNum;

@@ -338,3 +339,4 @@ exports.isString = isString;

errorFontLoadNative: "errorFontLoadNative",
errorFontGetPath: "errorFontGetPath"
errorFontGetPath: "errorFontGetPath",
errorMarkedContent: "errorMarkedContent"
};

@@ -754,2 +756,6 @@ exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;

function escapeString(str) {
return str.replace(/([\(\)\\])/g, "\\$1");
}
function stringToUTF8String(str) {

@@ -763,10 +769,2 @@ return decodeURIComponent(escape(str));

function isEmptyObj(obj) {
for (const key in obj) {
return false;
}
return true;
}
function isBool(v) {

@@ -798,2 +796,7 @@ return typeof v === "boolean";

function getModificationDate(date = new Date(Date.now())) {
const buffer = [date.getUTCFullYear().toString(), (date.getUTCMonth() + 1).toString().padStart(2, "0"), (date.getUTCDate() + 1).toString().padStart(2, "0"), date.getUTCHours().toString().padStart(2, "0"), date.getUTCMinutes().toString().padStart(2, "0"), date.getUTCSeconds().toString().padStart(2, "0")];
return buffer.join("");
}
function createPromiseCapability() {

@@ -800,0 +803,0 @@ const capability = Object.create(null);

@@ -32,3 +32,3 @@ /**

var _test_utils = require("./test_utils.js");
var _node_utils = require("../../display/node_utils.js");

@@ -48,3 +48,3 @@ var _stream = require("../../core/stream.js");

if (_is_node.isNodeJS) {
CMapReaderFactory = new _test_utils.NodeCMapReaderFactory({
CMapReaderFactory = new _node_utils.NodeCMapReaderFactory({
baseUrl: cMapUrl.node,

@@ -302,3 +302,3 @@ isCompressed: cMapPacked

function tmpFetchBuiltInCMap(name) {
var CMapReaderFactory = _is_node.isNodeJS ? new _test_utils.NodeCMapReaderFactory({}) : new _display_utils.DOMCMapReaderFactory({});
var CMapReaderFactory = _is_node.isNodeJS ? new _node_utils.NodeCMapReaderFactory({}) : new _display_utils.DOMCMapReaderFactory({});
return CMapReaderFactory.fetch({

@@ -328,3 +328,3 @@ name

if (_is_node.isNodeJS) {
CMapReaderFactory = new _test_utils.NodeCMapReaderFactory({
CMapReaderFactory = new _node_utils.NodeCMapReaderFactory({
baseUrl: cMapUrl.node,

@@ -331,0 +331,0 @@ isCompressed: false

@@ -30,2 +30,4 @@ /**

var _image_utils = require("../../core/image_utils.js");
var _function = require("../../core/function.js");

@@ -36,3 +38,3 @@

describe("colorspace", function () {
describe("ColorSpace", function () {
describe("ColorSpace.isDefaultDecode", function () {
it("should be true if decode is not an array", function () {

@@ -55,2 +57,126 @@ expect(_colorspace.ColorSpace.isDefaultDecode("string", 0)).toBeTruthy();

});
describe("ColorSpace caching", function () {
let localColorSpaceCache = null;
beforeAll(function (done) {
localColorSpaceCache = new _image_utils.LocalColorSpaceCache();
done();
});
afterAll(function (done) {
localColorSpaceCache = null;
done();
});
it("caching by Name", function () {
const xref = new _test_utils.XRefMock();
const pdfFunctionFactory = new _function.PDFFunctionFactory({
xref
});
const colorSpace1 = _colorspace.ColorSpace.parse({
cs: _primitives.Name.get("Pattern"),
xref,
resources: null,
pdfFunctionFactory,
localColorSpaceCache
});
expect(colorSpace1.name).toEqual("Pattern");
const colorSpace2 = _colorspace.ColorSpace.parse({
cs: _primitives.Name.get("Pattern"),
xref,
resources: null,
pdfFunctionFactory,
localColorSpaceCache
});
expect(colorSpace2.name).toEqual("Pattern");
const colorSpaceNonCached = _colorspace.ColorSpace.parse({
cs: _primitives.Name.get("Pattern"),
xref,
resources: null,
pdfFunctionFactory,
localColorSpaceCache: new _image_utils.LocalColorSpaceCache()
});
expect(colorSpaceNonCached.name).toEqual("Pattern");
const colorSpaceOther = _colorspace.ColorSpace.parse({
cs: _primitives.Name.get("RGB"),
xref,
resources: null,
pdfFunctionFactory,
localColorSpaceCache
});
expect(colorSpaceOther.name).toEqual("DeviceRGB");
expect(colorSpace1).toBe(colorSpace2);
expect(colorSpace1).not.toBe(colorSpaceNonCached);
expect(colorSpace1).not.toBe(colorSpaceOther);
});
it("caching by Ref", function () {
const paramsCalGray = new _primitives.Dict();
paramsCalGray.set("WhitePoint", [1, 1, 1]);
paramsCalGray.set("BlackPoint", [0, 0, 0]);
paramsCalGray.set("Gamma", 2.0);
const paramsCalRGB = new _primitives.Dict();
paramsCalRGB.set("WhitePoint", [1, 1, 1]);
paramsCalRGB.set("BlackPoint", [0, 0, 0]);
paramsCalRGB.set("Gamma", [1, 1, 1]);
paramsCalRGB.set("Matrix", [1, 0, 0, 0, 1, 0, 0, 0, 1]);
const xref = new _test_utils.XRefMock([{
ref: _primitives.Ref.get(50, 0),
data: [_primitives.Name.get("CalGray"), paramsCalGray]
}, {
ref: _primitives.Ref.get(100, 0),
data: [_primitives.Name.get("CalRGB"), paramsCalRGB]
}]);
const pdfFunctionFactory = new _function.PDFFunctionFactory({
xref
});
const colorSpace1 = _colorspace.ColorSpace.parse({
cs: _primitives.Ref.get(50, 0),
xref,
resources: null,
pdfFunctionFactory,
localColorSpaceCache
});
expect(colorSpace1.name).toEqual("CalGray");
const colorSpace2 = _colorspace.ColorSpace.parse({
cs: _primitives.Ref.get(50, 0),
xref,
resources: null,
pdfFunctionFactory,
localColorSpaceCache
});
expect(colorSpace2.name).toEqual("CalGray");
const colorSpaceNonCached = _colorspace.ColorSpace.parse({
cs: _primitives.Ref.get(50, 0),
xref,
resources: null,
pdfFunctionFactory,
localColorSpaceCache: new _image_utils.LocalColorSpaceCache()
});
expect(colorSpaceNonCached.name).toEqual("CalGray");
const colorSpaceOther = _colorspace.ColorSpace.parse({
cs: _primitives.Ref.get(100, 0),
xref,
resources: null,
pdfFunctionFactory,
localColorSpaceCache
});
expect(colorSpaceOther.name).toEqual("CalRGB");
expect(colorSpace1).toBe(colorSpace2);
expect(colorSpace1).not.toBe(colorSpaceNonCached);
expect(colorSpace1).not.toBe(colorSpaceOther);
});
});
describe("DeviceGrayCS", function () {

@@ -64,3 +190,3 @@ it("should handle the case when cs is a Name object", function () {

}]);
const res = new _primitives.Dict();
const resources = new _primitives.Dict();
const pdfFunctionFactory = new _function.PDFFunctionFactory({

@@ -70,3 +196,9 @@ xref

const colorSpace = _colorspace.ColorSpace.parse(cs, xref, res, pdfFunctionFactory);
const colorSpace = _colorspace.ColorSpace.parse({
cs,
xref,
resources,
pdfFunctionFactory,
localColorSpaceCache: new _image_utils.LocalColorSpaceCache()
});

@@ -89,3 +221,3 @@ const testSrc = new Uint8Array([27, 125, 250, 131]);

}]);
const res = new _primitives.Dict();
const resources = new _primitives.Dict();
const pdfFunctionFactory = new _function.PDFFunctionFactory({

@@ -95,3 +227,9 @@ xref

const colorSpace = _colorspace.ColorSpace.parse(cs, xref, res, pdfFunctionFactory);
const colorSpace = _colorspace.ColorSpace.parse({
cs,
xref,
resources,
pdfFunctionFactory,
localColorSpaceCache: new _image_utils.LocalColorSpaceCache()
});

@@ -116,3 +254,3 @@ const testSrc = new Uint8Array([27, 125, 250, 131]);

}]);
const res = new _primitives.Dict();
const resources = new _primitives.Dict();
const pdfFunctionFactory = new _function.PDFFunctionFactory({

@@ -122,3 +260,9 @@ xref

const colorSpace = _colorspace.ColorSpace.parse(cs, xref, res, pdfFunctionFactory);
const colorSpace = _colorspace.ColorSpace.parse({
cs,
xref,
resources,
pdfFunctionFactory,
localColorSpaceCache: new _image_utils.LocalColorSpaceCache()
});

@@ -141,3 +285,3 @@ const testSrc = new Uint8Array([27, 125, 250, 131, 139, 140, 111, 25, 198, 21, 147, 255]);

}]);
const res = new _primitives.Dict();
const resources = new _primitives.Dict();
const pdfFunctionFactory = new _function.PDFFunctionFactory({

@@ -147,3 +291,9 @@ xref

const colorSpace = _colorspace.ColorSpace.parse(cs, xref, res, pdfFunctionFactory);
const colorSpace = _colorspace.ColorSpace.parse({
cs,
xref,
resources,
pdfFunctionFactory,
localColorSpaceCache: new _image_utils.LocalColorSpaceCache()
});

@@ -168,3 +318,3 @@ const testSrc = new Uint8Array([27, 125, 250, 131, 139, 140, 111, 25, 198, 21, 147, 255]);

}]);
const res = new _primitives.Dict();
const resources = new _primitives.Dict();
const pdfFunctionFactory = new _function.PDFFunctionFactory({

@@ -174,3 +324,9 @@ xref

const colorSpace = _colorspace.ColorSpace.parse(cs, xref, res, pdfFunctionFactory);
const colorSpace = _colorspace.ColorSpace.parse({
cs,
xref,
resources,
pdfFunctionFactory,
localColorSpaceCache: new _image_utils.LocalColorSpaceCache()
});

@@ -193,3 +349,3 @@ const testSrc = new Uint8Array([27, 125, 250, 128, 131, 139, 140, 45, 111, 25, 198, 78, 21, 147, 255, 69]);

}]);
const res = new _primitives.Dict();
const resources = new _primitives.Dict();
const pdfFunctionFactory = new _function.PDFFunctionFactory({

@@ -199,3 +355,9 @@ xref

const colorSpace = _colorspace.ColorSpace.parse(cs, xref, res, pdfFunctionFactory);
const colorSpace = _colorspace.ColorSpace.parse({
cs,
xref,
resources,
pdfFunctionFactory,
localColorSpaceCache: new _image_utils.LocalColorSpaceCache()
});

@@ -223,3 +385,3 @@ const testSrc = new Uint8Array([27, 125, 250, 128, 131, 139, 140, 45, 111, 25, 198, 78, 21, 147, 255, 69]);

}]);
const res = new _primitives.Dict();
const resources = new _primitives.Dict();
const pdfFunctionFactory = new _function.PDFFunctionFactory({

@@ -229,3 +391,9 @@ xref

const colorSpace = _colorspace.ColorSpace.parse(cs, xref, res, pdfFunctionFactory);
const colorSpace = _colorspace.ColorSpace.parse({
cs,
xref,
resources,
pdfFunctionFactory,
localColorSpaceCache: new _image_utils.LocalColorSpaceCache()
});

@@ -254,3 +422,3 @@ const testSrc = new Uint8Array([27, 125, 250, 131]);

}]);
const res = new _primitives.Dict();
const resources = new _primitives.Dict();
const pdfFunctionFactory = new _function.PDFFunctionFactory({

@@ -260,3 +428,9 @@ xref

const colorSpace = _colorspace.ColorSpace.parse(cs, xref, res, pdfFunctionFactory);
const colorSpace = _colorspace.ColorSpace.parse({
cs,
xref,
resources,
pdfFunctionFactory,
localColorSpaceCache: new _image_utils.LocalColorSpaceCache()
});

@@ -284,3 +458,3 @@ const testSrc = new Uint8Array([27, 125, 250, 131, 139, 140, 111, 25, 198, 21, 147, 255]);

}]);
const res = new _primitives.Dict();
const resources = new _primitives.Dict();
const pdfFunctionFactory = new _function.PDFFunctionFactory({

@@ -290,3 +464,9 @@ xref

const colorSpace = _colorspace.ColorSpace.parse(cs, xref, res, pdfFunctionFactory);
const colorSpace = _colorspace.ColorSpace.parse({
cs,
xref,
resources,
pdfFunctionFactory,
localColorSpaceCache: new _image_utils.LocalColorSpaceCache()
});

@@ -306,3 +486,3 @@ const testSrc = new Uint8Array([27, 25, 50, 31, 19, 40, 11, 25, 98, 21, 47, 55]);

it("should handle the case when cs is an array", function () {
const lookup = new Uint8Array([23, 155, 35, 147, 69, 93, 255, 109, 70]);
const lookup = new _stream.Stream(new Uint8Array([23, 155, 35, 147, 69, 93, 255, 109, 70]));
const cs = [_primitives.Name.get("Indexed"), _primitives.Name.get("DeviceRGB"), 2, lookup];

@@ -313,3 +493,3 @@ const xref = new _test_utils.XRefMock([{

}]);
const res = new _primitives.Dict();
const resources = new _primitives.Dict();
const pdfFunctionFactory = new _function.PDFFunctionFactory({

@@ -319,3 +499,9 @@ xref

const colorSpace = _colorspace.ColorSpace.parse(cs, xref, res, pdfFunctionFactory);
const colorSpace = _colorspace.ColorSpace.parse({
cs,
xref,
resources,
pdfFunctionFactory,
localColorSpaceCache: new _image_utils.LocalColorSpaceCache()
});

@@ -349,3 +535,3 @@ const testSrc = new Uint8Array([2, 2, 0, 1]);

}]);
const res = new _primitives.Dict();
const resources = new _primitives.Dict();
const pdfFunctionFactory = new _function.PDFFunctionFactory({

@@ -355,3 +541,9 @@ xref

const colorSpace = _colorspace.ColorSpace.parse(cs, xref, res, pdfFunctionFactory);
const colorSpace = _colorspace.ColorSpace.parse({
cs,
xref,
resources,
pdfFunctionFactory,
localColorSpaceCache: new _image_utils.LocalColorSpaceCache()
});

@@ -358,0 +550,0 @@ const testSrc = new Uint8Array([27, 25, 50, 31]);

@@ -409,3 +409,11 @@ /**

var fileId1, fileId2, dict1, dict2;
function ensureEncryptDecryptIsIdentity(dict, fileId, password, string) {
const factory = new _crypto.CipherTransformFactory(dict, fileId, password);
const cipher = factory.createCipherTransform(123, 0);
const encrypted = cipher.encryptString(string);
const decrypted = cipher.decryptString(encrypted);
expect(string).toEqual(decrypted);
}
var fileId1, fileId2, dict1, dict2, dict3;
var aes256Dict, aes256IsoDict, aes256BlankDict, aes256IsoBlankDict;

@@ -433,3 +441,3 @@ beforeAll(function (done) {

});
aes256Dict = buildDict({
dict3 = {
Filter: _primitives.Name.get("Standard"),

@@ -445,3 +453,4 @@ V: 5,

R: 5
});
};
aes256Dict = buildDict(dict3);
aes256IsoDict = buildDict({

@@ -486,3 +495,3 @@ Filter: _primitives.Name.get("Standard"),

afterAll(function () {
fileId1 = fileId2 = dict1 = dict2 = null;
fileId1 = fileId2 = dict1 = dict2 = dict3 = null;
aes256Dict = aes256IsoDict = aes256BlankDict = aes256IsoBlankDict = null;

@@ -541,2 +550,40 @@ });

});
describe("Encrypt and decrypt", function () {
it("should encrypt and decrypt using ARCFour", function (done) {
dict3.CF = buildDict({
Identity: buildDict({
CFM: _primitives.Name.get("V2")
})
});
const dict = buildDict(dict3);
ensureEncryptDecryptIsIdentity(dict, fileId1, "user", "hello world");
done();
});
it("should encrypt and decrypt using AES128", function (done) {
dict3.CF = buildDict({
Identity: buildDict({
CFM: _primitives.Name.get("AESV2")
})
});
const dict = buildDict(dict3);
ensureEncryptDecryptIsIdentity(dict, fileId1, "user", "a");
ensureEncryptDecryptIsIdentity(dict, fileId1, "user", "aa");
ensureEncryptDecryptIsIdentity(dict, fileId1, "user", "aaaaaaaaaaaaaaaa");
ensureEncryptDecryptIsIdentity(dict, fileId1, "user", "aaaaaaaaaaaaaaaaaaa");
done();
});
it("should encrypt and decrypt using AES256", function (done) {
dict3.CF = buildDict({
Identity: buildDict({
CFM: _primitives.Name.get("AESV3")
})
});
const dict = buildDict(dict3);
ensureEncryptDecryptIsIdentity(dict, fileId1, "user", "aaaa");
ensureEncryptDecryptIsIdentity(dict, fileId1, "user", "aaaaa");
ensureEncryptDecryptIsIdentity(dict, fileId1, "user", "aaaaaaaaaaaaaaaa");
ensureEncryptDecryptIsIdentity(dict, fileId1, "user", "aaaaaaaaaaaaaaaaaaaaaa");
done();
});
});
});

@@ -32,2 +32,4 @@ /**

var _node_utils = require("../../display/node_utils.js");
function getTopLeftPixel(canvasContext) {

@@ -50,3 +52,3 @@ const imgData = canvasContext.getImageData(0, 0, 1, 1);

if (_is_node.isNodeJS) {
CanvasFactory = new _test_utils.NodeCanvasFactory();
CanvasFactory = new _node_utils.NodeCanvasFactory();
} else {

@@ -110,2 +112,128 @@ CanvasFactory = new _display_utils.DOMCanvasFactory();

});
});
describe("custom ownerDocument", function () {
const FontFace = globalThis.FontFace;
const checkFont = font => /g_d\d+_f1/.test(font.family);
const checkFontFaceRule = rule => /^@font-face {font-family:"g_d\d+_f1";src:/.test(rule);
beforeEach(() => {
globalThis.FontFace = function MockFontFace(name) {
this.family = name;
};
});
afterEach(() => {
globalThis.FontFace = FontFace;
});
function getMocks() {
const elements = [];
const createElement = name => {
let element = typeof document !== "undefined" && document.createElement(name);
if (name === "style") {
element = {
tagName: name,
sheet: {
cssRules: [],
insertRule(rule) {
this.cssRules.push(rule);
}
}
};
Object.assign(element, {
remove() {
this.remove.called = true;
}
});
}
elements.push(element);
return element;
};
const ownerDocument = {
fonts: new Set(),
createElement,
documentElement: {
getElementsByTagName: () => [{
appendChild: () => {}
}]
}
};
const CanvasFactory = _is_node.isNodeJS ? new _node_utils.NodeCanvasFactory() : new _display_utils.DOMCanvasFactory({
ownerDocument
});
return {
elements,
ownerDocument,
CanvasFactory
};
}
it("should use given document for loading fonts (with Font Loading API)", async function () {
const {
ownerDocument,
elements,
CanvasFactory
} = getMocks();
const getDocumentParams = (0, _test_utils.buildGetDocumentParams)("TrueType_without_cmap.pdf", {
disableFontFace: false,
ownerDocument
});
const loadingTask = (0, _api.getDocument)(getDocumentParams);
const doc = await loadingTask.promise;
const page = await doc.getPage(1);
const viewport = page.getViewport({
scale: 1
});
const canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height);
await page.render({
canvasContext: canvasAndCtx.context,
viewport
}).promise;
const style = elements.find(element => element.tagName === "style");
expect(style).toBeFalsy();
expect(ownerDocument.fonts.size).toBeGreaterThanOrEqual(1);
expect(Array.from(ownerDocument.fonts).find(checkFont)).toBeTruthy();
await doc.destroy();
await loadingTask.destroy();
CanvasFactory.destroy(canvasAndCtx);
expect(ownerDocument.fonts.size).toBe(0);
});
it("should use given document for loading fonts (with CSS rules)", async function () {
const {
ownerDocument,
elements,
CanvasFactory
} = getMocks();
ownerDocument.fonts = null;
const getDocumentParams = (0, _test_utils.buildGetDocumentParams)("TrueType_without_cmap.pdf", {
disableFontFace: false,
ownerDocument
});
const loadingTask = (0, _api.getDocument)(getDocumentParams);
const doc = await loadingTask.promise;
const page = await doc.getPage(1);
const viewport = page.getViewport({
scale: 1
});
const canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height);
await page.render({
canvasContext: canvasAndCtx.context,
viewport
}).promise;
const style = elements.find(element => element.tagName === "style");
expect(style.sheet.cssRules.length).toBeGreaterThanOrEqual(1);
expect(style.sheet.cssRules.find(checkFontFaceRule)).toBeTruthy();
await doc.destroy();
await loadingTask.destroy();
CanvasFactory.destroy(canvasAndCtx);
expect(style.remove.called).toBe(true);
});
});

@@ -26,5 +26,11 @@ /**

var _primitives = require("../../core/primitives.js");
var _document = require("../../core/document.js");
var _stream = require("../../core/stream.js");
describe("document", function () {
describe("Page", function () {
it("should create correct objId using the idFactory", function () {
it("should create correct objId/fontId using the idFactory", function () {
const idFactory1 = (0, _test_utils.createIdFactory)(0);

@@ -34,11 +40,116 @@ const idFactory2 = (0, _test_utils.createIdFactory)(1);

expect(idFactory1.createObjId()).toEqual("p0_2");
expect(idFactory1.createFontId()).toEqual("f1");
expect(idFactory1.createFontId()).toEqual("f2");
expect(idFactory1.getDocId()).toEqual("g_d0");
expect(idFactory2.createObjId()).toEqual("p1_1");
expect(idFactory2.createObjId()).toEqual("p1_2");
expect(idFactory2.createFontId()).toEqual("f1");
expect(idFactory2.createFontId()).toEqual("f2");
expect(idFactory2.getDocId()).toEqual("g_d0");
expect(idFactory1.createObjId()).toEqual("p0_3");
expect(idFactory1.createObjId()).toEqual("p0_4");
expect(idFactory1.createFontId()).toEqual("f3");
expect(idFactory1.createFontId()).toEqual("f4");
expect(idFactory1.getDocId()).toEqual("g_d0");
});
});
describe("PDFDocument", function () {
const pdfManager = {
get docId() {
return "d0";
}
};
const stream = new _stream.StringStream("Dummy_PDF_data");
function getDocument(acroForm) {
const pdfDocument = new _document.PDFDocument(pdfManager, stream);
pdfDocument.catalog = {
acroForm
};
return pdfDocument;
}
it("should get form info when no form data is present", function () {
const pdfDocument = getDocument(null);
expect(pdfDocument.formInfo).toEqual({
hasAcroForm: false,
hasXfa: false
});
});
it("should get form info when XFA is present", function () {
const acroForm = new _primitives.Dict();
acroForm.set("XFA", []);
let pdfDocument = getDocument(acroForm);
expect(pdfDocument.formInfo).toEqual({
hasAcroForm: false,
hasXfa: false
});
acroForm.set("XFA", ["foo", "bar"]);
pdfDocument = getDocument(acroForm);
expect(pdfDocument.formInfo).toEqual({
hasAcroForm: false,
hasXfa: true
});
acroForm.set("XFA", new _stream.StringStream(""));
pdfDocument = getDocument(acroForm);
expect(pdfDocument.formInfo).toEqual({
hasAcroForm: false,
hasXfa: false
});
acroForm.set("XFA", new _stream.StringStream("non-empty"));
pdfDocument = getDocument(acroForm);
expect(pdfDocument.formInfo).toEqual({
hasAcroForm: false,
hasXfa: true
});
});
it("should get form info when AcroForm is present", function () {
const acroForm = new _primitives.Dict();
acroForm.set("Fields", []);
let pdfDocument = getDocument(acroForm);
expect(pdfDocument.formInfo).toEqual({
hasAcroForm: false,
hasXfa: false
});
acroForm.set("Fields", ["foo", "bar"]);
pdfDocument = getDocument(acroForm);
expect(pdfDocument.formInfo).toEqual({
hasAcroForm: true,
hasXfa: false
});
acroForm.set("Fields", ["foo", "bar"]);
acroForm.set("SigFlags", 2);
pdfDocument = getDocument(acroForm);
expect(pdfDocument.formInfo).toEqual({
hasAcroForm: true,
hasXfa: false
});
const annotationDict = new _primitives.Dict();
annotationDict.set("FT", _primitives.Name.get("Sig"));
annotationDict.set("Rect", [0, 0, 0, 0]);
const annotationRef = _primitives.Ref.get(11, 0);
const kidsDict = new _primitives.Dict();
kidsDict.set("Kids", [annotationRef]);
const kidsRef = _primitives.Ref.get(10, 0);
pdfDocument.xref = new _test_utils.XRefMock([{
ref: annotationRef,
data: annotationDict
}, {
ref: kidsRef,
data: kidsDict
}]);
acroForm.set("Fields", [kidsRef]);
acroForm.set("SigFlags", 3);
pdfDocument = getDocument(acroForm);
expect(pdfDocument.formInfo).toEqual({
hasAcroForm: false,
hasXfa: false
});
});
});
});

@@ -111,10 +111,22 @@ /**

it("should handle two glued operations", function (done) {
var resources = new ResourcesMock();
resources.Res1 = {};
const imgDict = new _primitives.Dict();
imgDict.set("Subtype", _primitives.Name.get("Image"));
imgDict.set("Width", 1);
imgDict.set("Height", 1);
const imgStream = new _stream.Stream([0]);
imgStream.dict = imgDict;
const xObject = new _primitives.Dict();
xObject.set("Res1", imgStream);
const resources = new ResourcesMock();
resources.XObject = xObject;
var stream = new _stream.StringStream("/Res1 DoQ");
runOperatorListCheck(partialEvaluator, stream, resources, function (result) {
expect(!!result.fnArray && !!result.argsArray).toEqual(true);
expect(result.fnArray.length).toEqual(2);
expect(result.fnArray[0]).toEqual(_util.OPS.paintXObject);
expect(result.fnArray[1]).toEqual(_util.OPS.restore);
expect(result.fnArray.length).toEqual(3);
expect(result.fnArray[0]).toEqual(_util.OPS.dependency);
expect(result.fnArray[1]).toEqual(_util.OPS.paintImageXObject);
expect(result.fnArray[2]).toEqual(_util.OPS.restore);
expect(result.argsArray.length).toEqual(3);
expect(result.argsArray[0]).toEqual(["img_p0_1"]);
expect(result.argsArray[1]).toEqual(["img_p0_1", 1, 1]);
expect(result.argsArray[2]).toEqual(null);
done();

@@ -198,4 +210,11 @@ });

it("should execute if nested commands", function (done) {
const gState = new _primitives.Dict();
gState.set("LW", 2);
gState.set("CA", 0.5);
const extGState = new _primitives.Dict();
extGState.set("GS2", gState);
const resources = new ResourcesMock();
resources.ExtGState = extGState;
var stream = new _stream.StringStream("/F2 /GS2 gs 5.711 Tf");
runOperatorListCheck(partialEvaluator, stream, new ResourcesMock(), function (result) {
runOperatorListCheck(partialEvaluator, stream, resources, function (result) {
expect(result.fnArray.length).toEqual(3);

@@ -206,5 +225,5 @@ expect(result.fnArray[0]).toEqual(_util.OPS.setGState);

expect(result.argsArray.length).toEqual(3);
expect(result.argsArray[0].length).toEqual(1);
expect(result.argsArray[1].length).toEqual(1);
expect(result.argsArray[2].length).toEqual(2);
expect(result.argsArray[0]).toEqual([[["LW", 2], ["CA", 0.5]]]);
expect(result.argsArray[1]).toEqual(["g_font_error"]);
expect(result.argsArray[2]).toEqual(["g_font_error", 5.711]);
done();

@@ -211,0 +230,0 @@ });

@@ -25,3 +25,3 @@ /**

function initializePDFJS(callback) {
Promise.all(["pdfjs/display/api.js", "pdfjs/display/worker_options.js", "pdfjs/display/network.js", "pdfjs/display/fetch_stream.js", "pdfjs/shared/is_node.js", "pdfjs-test/unit/annotation_spec.js", "pdfjs-test/unit/api_spec.js", "pdfjs-test/unit/bidi_spec.js", "pdfjs-test/unit/cff_parser_spec.js", "pdfjs-test/unit/cmap_spec.js", "pdfjs-test/unit/colorspace_spec.js", "pdfjs-test/unit/core_utils_spec.js", "pdfjs-test/unit/crypto_spec.js", "pdfjs-test/unit/custom_spec.js", "pdfjs-test/unit/display_svg_spec.js", "pdfjs-test/unit/display_utils_spec.js", "pdfjs-test/unit/document_spec.js", "pdfjs-test/unit/encodings_spec.js", "pdfjs-test/unit/evaluator_spec.js", "pdfjs-test/unit/function_spec.js", "pdfjs-test/unit/fetch_stream_spec.js", "pdfjs-test/unit/message_handler_spec.js", "pdfjs-test/unit/metadata_spec.js", "pdfjs-test/unit/murmurhash3_spec.js", "pdfjs-test/unit/network_spec.js", "pdfjs-test/unit/network_utils_spec.js", "pdfjs-test/unit/parser_spec.js", "pdfjs-test/unit/pdf_find_controller_spec.js", "pdfjs-test/unit/pdf_find_utils_spec.js", "pdfjs-test/unit/pdf_history_spec.js", "pdfjs-test/unit/primitives_spec.js", "pdfjs-test/unit/stream_spec.js", "pdfjs-test/unit/type1_parser_spec.js", "pdfjs-test/unit/ui_utils_spec.js", "pdfjs-test/unit/unicode_spec.js", "pdfjs-test/unit/util_spec.js"].map(function (moduleName) {
Promise.all(["pdfjs/display/api.js", "pdfjs/display/worker_options.js", "pdfjs/display/network.js", "pdfjs/display/fetch_stream.js", "pdfjs/shared/is_node.js", "pdfjs-test/unit/annotation_spec.js", "pdfjs-test/unit/annotation_storage_spec.js", "pdfjs-test/unit/api_spec.js", "pdfjs-test/unit/bidi_spec.js", "pdfjs-test/unit/cff_parser_spec.js", "pdfjs-test/unit/cmap_spec.js", "pdfjs-test/unit/colorspace_spec.js", "pdfjs-test/unit/core_utils_spec.js", "pdfjs-test/unit/crypto_spec.js", "pdfjs-test/unit/custom_spec.js", "pdfjs-test/unit/display_svg_spec.js", "pdfjs-test/unit/display_utils_spec.js", "pdfjs-test/unit/document_spec.js", "pdfjs-test/unit/encodings_spec.js", "pdfjs-test/unit/evaluator_spec.js", "pdfjs-test/unit/function_spec.js", "pdfjs-test/unit/fetch_stream_spec.js", "pdfjs-test/unit/message_handler_spec.js", "pdfjs-test/unit/metadata_spec.js", "pdfjs-test/unit/murmurhash3_spec.js", "pdfjs-test/unit/network_spec.js", "pdfjs-test/unit/network_utils_spec.js", "pdfjs-test/unit/parser_spec.js", "pdfjs-test/unit/pdf_find_controller_spec.js", "pdfjs-test/unit/pdf_find_utils_spec.js", "pdfjs-test/unit/pdf_history_spec.js", "pdfjs-test/unit/primitives_spec.js", "pdfjs-test/unit/stream_spec.js", "pdfjs-test/unit/type1_parser_spec.js", "pdfjs-test/unit/ui_utils_spec.js", "pdfjs-test/unit/unicode_spec.js", "pdfjs-test/unit/util_spec.js", "pdfjs-test/unit/writer_spec.js"].map(function (moduleName) {
return SystemJS.import(moduleName);

@@ -28,0 +28,0 @@ })).then(function (modules) {

@@ -24,3 +24,3 @@ /**

var _util = require("../../shared/util.js");
var _test_utils = require("./test_utils.js");

@@ -68,3 +68,3 @@ var _metadata = require("../../display/metadata.js");

const metadata = new _metadata.Metadata(data);
expect((0, _util.isEmptyObj)(metadata.getAll())).toEqual(true);
expect((0, _test_utils.isEmptyObj)(metadata.getAll())).toEqual(true);
});

@@ -107,3 +107,3 @@ it('should gracefully handle "junk" before the actual metadata (issue 10395)', function () {

const metadata = new _metadata.Metadata(data);
expect((0, _util.isEmptyObj)(metadata.getAll())).toEqual(true);
expect((0, _test_utils.isEmptyObj)(metadata.getAll())).toEqual(true);
});

@@ -110,0 +110,0 @@ it("should not be vulnerable to the billion laughs attack", function () {

@@ -26,2 +26,4 @@ /**

var _stream = require("../../core/stream.js");
var _test_utils = require("./test_utils.js");

@@ -32,5 +34,5 @@

it("should retain the given name", function () {
var givenName = "Font";
const givenName = "Font";
var name = _primitives.Name.get(givenName);
const name = _primitives.Name.get(givenName);

@@ -40,9 +42,9 @@ expect(name.name).toEqual(givenName);

it("should create only one object for a name and cache it", function () {
var firstFont = _primitives.Name.get("Font");
const firstFont = _primitives.Name.get("Font");
var secondFont = _primitives.Name.get("Font");
const secondFont = _primitives.Name.get("Font");
var firstSubtype = _primitives.Name.get("Subtype");
const firstSubtype = _primitives.Name.get("Subtype");
var secondSubtype = _primitives.Name.get("Subtype");
const secondSubtype = _primitives.Name.get("Subtype");

@@ -56,5 +58,5 @@ expect(firstFont).toBe(secondFont);

it("should retain the given cmd name", function () {
var givenCmd = "BT";
const givenCmd = "BT";
var cmd = _primitives.Cmd.get(givenCmd);
const cmd = _primitives.Cmd.get(givenCmd);

@@ -64,9 +66,9 @@ expect(cmd.cmd).toEqual(givenCmd);

it("should create only one object for a command and cache it", function () {
var firstBT = _primitives.Cmd.get("BT");
const firstBT = _primitives.Cmd.get("BT");
var secondBT = _primitives.Cmd.get("BT");
const secondBT = _primitives.Cmd.get("BT");
var firstET = _primitives.Cmd.get("ET");
const firstET = _primitives.Cmd.get("ET");
var secondET = _primitives.Cmd.get("ET");
const secondET = _primitives.Cmd.get("ET");

@@ -79,3 +81,3 @@ expect(firstBT).toBe(secondBT);

describe("Dict", function () {
var checkInvalidHasValues = function (dict) {
const checkInvalidHasValues = function (dict) {
expect(dict.has()).toBeFalsy();

@@ -85,3 +87,3 @@ expect(dict.has("Prev")).toBeFalsy();

var checkInvalidKeyValues = function (dict) {
const checkInvalidKeyValues = function (dict) {
expect(dict.get()).toBeUndefined();

@@ -93,7 +95,7 @@ expect(dict.get("Prev")).toBeUndefined();

var emptyDict, dictWithSizeKey, dictWithManyKeys;
var storedSize = 42;
var testFontFile = "file1";
var testFontFile2 = "file2";
var testFontFile3 = "file3";
let emptyDict, dictWithSizeKey, dictWithManyKeys;
const storedSize = 42;
const testFontFile = "file1";
const testFontFile2 = "file2";
const testFontFile3 = "file3";
beforeAll(function (done) {

@@ -112,2 +114,17 @@ emptyDict = new _primitives.Dict();

});
it("should allow assigning an XRef table after creation", function () {
const dict = new _primitives.Dict(null);
expect(dict.xref).toEqual(null);
const xref = new _test_utils.XRefMock([]);
dict.assignXref(xref);
expect(dict.xref).toEqual(xref);
});
it("should return correct size", function () {
const dict = new _primitives.Dict(null);
expect(dict.size).toEqual(0);
dict.set("Type", _primitives.Name.get("Page"));
expect(dict.size).toEqual(1);
dict.set("Contents", _primitives.Ref.get(10, 0));
expect(dict.size).toEqual(2);
});
it("should return invalid values for unknown keys", function () {

@@ -144,3 +161,3 @@ checkInvalidHasValues(emptyDict);

it("should asynchronously fetch unknown keys", function (done) {
var keyPromises = [dictWithManyKeys.getAsync("Size"), dictWithSizeKey.getAsync("FontFile", "FontFile2", "FontFile3")];
const keyPromises = [dictWithManyKeys.getAsync("Size"), dictWithSizeKey.getAsync("FontFile", "FontFile2", "FontFile3")];
Promise.all(keyPromises).then(function (values) {

@@ -155,3 +172,3 @@ expect(values[0]).toBeUndefined();

it("should asynchronously fetch correct values for multiple stored keys", function (done) {
var keyPromises = [dictWithManyKeys.getAsync("FontFile3"), dictWithManyKeys.getAsync("FontFile2", "FontFile3"), dictWithManyKeys.getAsync("FontFile", "FontFile2", "FontFile3")];
const keyPromises = [dictWithManyKeys.getAsync("FontFile3"), dictWithManyKeys.getAsync("FontFile2", "FontFile3"), dictWithManyKeys.getAsync("FontFile", "FontFile2", "FontFile3")];
Promise.all(keyPromises).then(function (values) {

@@ -167,6 +184,6 @@ expect(values[0]).toEqual(testFontFile3);

it("should callback for each stored key", function () {
var callbackSpy = jasmine.createSpy("spy on callback in dictionary");
const callbackSpy = jasmine.createSpy("spy on callback in dictionary");
dictWithManyKeys.forEach(callbackSpy);
expect(callbackSpy).toHaveBeenCalled();
var callbackSpyCalls = callbackSpy.calls;
const callbackSpyCalls = callbackSpy.calls;
expect(callbackSpyCalls.argsFor(0)).toEqual(["FontFile", testFontFile]);

@@ -178,9 +195,9 @@ expect(callbackSpyCalls.argsFor(1)).toEqual(["FontFile2", testFontFile2]);

it("should handle keys pointing to indirect objects, both sync and async", function (done) {
var fontRef = _primitives.Ref.get(1, 0);
const fontRef = _primitives.Ref.get(1, 0);
var xref = new _test_utils.XRefMock([{
const xref = new _test_utils.XRefMock([{
ref: fontRef,
data: testFontFile
}]);
var fontDict = new _primitives.Dict(xref);
const fontDict = new _primitives.Dict(xref);
fontDict.set("FontFile", fontRef);

@@ -197,8 +214,9 @@ expect(fontDict.getRaw("FontFile")).toEqual(fontRef);

it("should handle arrays containing indirect objects", function () {
var minCoordRef = _primitives.Ref.get(1, 0),
maxCoordRef = _primitives.Ref.get(2, 0);
const minCoordRef = _primitives.Ref.get(1, 0);
var minCoord = 0,
maxCoord = 1;
var xref = new _test_utils.XRefMock([{
const maxCoordRef = _primitives.Ref.get(2, 0);
const minCoord = 0;
const maxCoord = 1;
const xref = new _test_utils.XRefMock([{
ref: minCoordRef,

@@ -210,3 +228,3 @@ data: minCoord

}]);
var xObjectDict = new _primitives.Dict(xref);
const xObjectDict = new _primitives.Dict(xref);
xObjectDict.set("BBox", [minCoord, maxCoord, minCoordRef, maxCoordRef]);

@@ -217,9 +235,37 @@ expect(xObjectDict.get("BBox")).toEqual([minCoord, maxCoord, minCoordRef, maxCoordRef]);

it("should get all key names", function () {
var expectedKeys = ["FontFile", "FontFile2", "FontFile3"];
var keys = dictWithManyKeys.getKeys();
const expectedKeys = ["FontFile", "FontFile2", "FontFile3"];
const keys = dictWithManyKeys.getKeys();
expect(keys.sort()).toEqual(expectedKeys);
});
it("should get all raw values", function () {
const expectedRawValues1 = [testFontFile, testFontFile2, testFontFile3];
const rawValues1 = dictWithManyKeys.getRawValues();
expect(rawValues1.sort()).toEqual(expectedRawValues1);
const typeName = _primitives.Name.get("Page");
const resources = new _primitives.Dict(null),
resourcesRef = _primitives.Ref.get(5, 0);
const contents = new _stream.StringStream("data"),
contentsRef = _primitives.Ref.get(10, 0);
const xref = new _test_utils.XRefMock([{
ref: resourcesRef,
data: resources
}, {
ref: contentsRef,
data: contents
}]);
const dict = new _primitives.Dict(xref);
dict.set("Type", typeName);
dict.set("Resources", resourcesRef);
dict.set("Contents", contentsRef);
const expectedRawValues2 = [contentsRef, resourcesRef, typeName];
const rawValues2 = dict.getRawValues();
expect(rawValues2.sort()).toEqual(expectedRawValues2);
});
it("should create only one object for Dict.empty", function () {
var firstDictEmpty = _primitives.Dict.empty;
var secondDictEmpty = _primitives.Dict.empty;
const firstDictEmpty = _primitives.Dict.empty;
const secondDictEmpty = _primitives.Dict.empty;
expect(firstDictEmpty).toBe(secondDictEmpty);

@@ -229,19 +275,67 @@ expect(firstDictEmpty).not.toBe(emptyDict);

it("should correctly merge dictionaries", function () {
var expectedKeys = ["FontFile", "FontFile2", "FontFile3", "Size"];
var fontFileDict = new _primitives.Dict();
const expectedKeys = ["FontFile", "FontFile2", "FontFile3", "Size"];
const fontFileDict = new _primitives.Dict();
fontFileDict.set("FontFile", "Type1 font file");
var mergedDict = _primitives.Dict.merge(null, [dictWithManyKeys, dictWithSizeKey, fontFileDict]);
const mergedDict = _primitives.Dict.merge({
xref: null,
dictArray: [dictWithManyKeys, dictWithSizeKey, fontFileDict]
});
var mergedKeys = mergedDict.getKeys();
const mergedKeys = mergedDict.getKeys();
expect(mergedKeys.sort()).toEqual(expectedKeys);
expect(mergedDict.get("FontFile")).toEqual(testFontFile);
});
it("should correctly merge sub-dictionaries", function () {
const localFontDict = new _primitives.Dict();
localFontDict.set("F1", "Local font one");
const globalFontDict = new _primitives.Dict();
globalFontDict.set("F1", "Global font one");
globalFontDict.set("F2", "Global font two");
globalFontDict.set("F3", "Global font three");
const localDict = new _primitives.Dict();
localDict.set("Font", localFontDict);
const globalDict = new _primitives.Dict();
globalDict.set("Font", globalFontDict);
const mergedDict = _primitives.Dict.merge({
xref: null,
dictArray: [localDict, globalDict]
});
const mergedSubDict = _primitives.Dict.merge({
xref: null,
dictArray: [localDict, globalDict],
mergeSubDicts: true
});
const mergedFontDict = mergedDict.get("Font");
const mergedSubFontDict = mergedSubDict.get("Font");
expect(mergedFontDict instanceof _primitives.Dict).toEqual(true);
expect(mergedSubFontDict instanceof _primitives.Dict).toEqual(true);
const mergedFontDictKeys = mergedFontDict.getKeys();
const mergedSubFontDictKeys = mergedSubFontDict.getKeys();
expect(mergedFontDictKeys).toEqual(["F1"]);
expect(mergedSubFontDictKeys).toEqual(["F1", "F2", "F3"]);
const mergedFontDictValues = mergedFontDict.getRawValues();
const mergedSubFontDictValues = mergedSubFontDict.getRawValues();
expect(mergedFontDictValues).toEqual(["Local font one"]);
expect(mergedSubFontDictValues).toEqual(["Local font one", "Global font two", "Global font three"]);
});
});
describe("Ref", function () {
it("should get a string representation", function () {
const nonZeroRef = _primitives.Ref.get(4, 2);
expect(nonZeroRef.toString()).toEqual("4R2");
const zeroRef = _primitives.Ref.get(4, 0);
expect(zeroRef.toString()).toEqual("4R");
});
it("should retain the stored values", function () {
var storedNum = 4;
var storedGen = 2;
const storedNum = 4;
const storedGen = 2;
var ref = _primitives.Ref.get(storedNum, storedGen);
const ref = _primitives.Ref.get(storedNum, storedGen);

@@ -251,8 +345,21 @@ expect(ref.num).toEqual(storedNum);

});
it("should create only one object for a reference and cache it", function () {
const firstRef = _primitives.Ref.get(4, 2);
const secondRef = _primitives.Ref.get(4, 2);
const firstOtherRef = _primitives.Ref.get(5, 2);
const secondOtherRef = _primitives.Ref.get(5, 2);
expect(firstRef).toBe(secondRef);
expect(firstOtherRef).toBe(secondOtherRef);
expect(firstRef).not.toBe(firstOtherRef);
});
});
describe("RefSet", function () {
it("should have a stored value", function () {
var ref = _primitives.Ref.get(4, 2);
const ref = _primitives.Ref.get(4, 2);
var refset = new _primitives.RefSet();
const refset = new _primitives.RefSet();
refset.put(ref);

@@ -262,9 +369,9 @@ expect(refset.has(ref)).toBeTruthy();

it("should not have an unknown value", function () {
var ref = _primitives.Ref.get(4, 2);
const ref = _primitives.Ref.get(4, 2);
var refset = new _primitives.RefSet();
const refset = new _primitives.RefSet();
expect(refset.has(ref)).toBeFalsy();
refset.put(ref);
var anotherRef = _primitives.Ref.get(2, 4);
const anotherRef = _primitives.Ref.get(2, 4);

@@ -274,9 +381,71 @@ expect(refset.has(anotherRef)).toBeFalsy();

});
describe("RefSetCache", function () {
const ref1 = _primitives.Ref.get(4, 2);
const ref2 = _primitives.Ref.get(5, 2);
const obj1 = _primitives.Name.get("foo");
const obj2 = _primitives.Name.get("bar");
let cache;
beforeEach(function (done) {
cache = new _primitives.RefSetCache();
done();
});
afterEach(function () {
cache = null;
});
it("should put, have and get a value", function () {
cache.put(ref1, obj1);
expect(cache.has(ref1)).toBeTruthy();
expect(cache.has(ref2)).toBeFalsy();
expect(cache.get(ref1)).toBe(obj1);
});
it("should put, have and get a value by alias", function () {
cache.put(ref1, obj1);
cache.putAlias(ref2, ref1);
expect(cache.has(ref1)).toBeTruthy();
expect(cache.has(ref2)).toBeTruthy();
expect(cache.get(ref1)).toBe(obj1);
expect(cache.get(ref2)).toBe(obj1);
});
it("should report the size of the cache", function () {
cache.put(ref1, obj1);
expect(cache.size).toEqual(1);
cache.put(ref2, obj2);
expect(cache.size).toEqual(2);
});
it("should clear the cache", function () {
cache.put(ref1, obj1);
expect(cache.size).toEqual(1);
cache.clear();
expect(cache.size).toEqual(0);
});
it("should support iteration", function () {
cache.put(ref1, obj1);
cache.put(ref2, obj2);
const values = [];
cache.forEach(function (value) {
values.push(value);
});
expect(values).toEqual([obj1, obj2]);
});
});
describe("isEOF", function () {
it("handles non-EOF", function () {
const nonEOF = "foo";
expect((0, _primitives.isEOF)(nonEOF)).toEqual(false);
});
it("handles EOF", function () {
expect((0, _primitives.isEOF)(_primitives.EOF)).toEqual(true);
});
});
describe("isName", function () {
it("handles non-names", function () {
var nonName = {};
const nonName = {};
expect((0, _primitives.isName)(nonName)).toEqual(false);
});
it("handles names", function () {
var name = _primitives.Name.get("Font");
const name = _primitives.Name.get("Font");

@@ -286,3 +455,3 @@ expect((0, _primitives.isName)(name)).toEqual(true);

it("handles names with name check", function () {
var name = _primitives.Name.get("Font");
const name = _primitives.Name.get("Font");

@@ -295,7 +464,7 @@ expect((0, _primitives.isName)(name, "Font")).toEqual(true);

it("handles non-commands", function () {
var nonCmd = {};
const nonCmd = {};
expect((0, _primitives.isCmd)(nonCmd)).toEqual(false);
});
it("handles commands", function () {
var cmd = _primitives.Cmd.get("BT");
const cmd = _primitives.Cmd.get("BT");

@@ -305,3 +474,3 @@ expect((0, _primitives.isCmd)(cmd)).toEqual(true);

it("handles commands with cmd check", function () {
var cmd = _primitives.Cmd.get("BT");
const cmd = _primitives.Cmd.get("BT");

@@ -314,7 +483,7 @@ expect((0, _primitives.isCmd)(cmd, "BT")).toEqual(true);

it("handles non-dictionaries", function () {
var nonDict = {};
const nonDict = {};
expect((0, _primitives.isDict)(nonDict)).toEqual(false);
});
it("handles empty dictionaries with type check", function () {
var dict = _primitives.Dict.empty;
const dict = _primitives.Dict.empty;
expect((0, _primitives.isDict)(dict)).toEqual(true);

@@ -324,3 +493,3 @@ expect((0, _primitives.isDict)(dict, "Page")).toEqual(false);

it("handles dictionaries with type check", function () {
var dict = new _primitives.Dict();
const dict = new _primitives.Dict();
dict.set("Type", _primitives.Name.get("Page"));

@@ -333,7 +502,7 @@ expect((0, _primitives.isDict)(dict, "Page")).toEqual(true);

it("handles non-refs", function () {
var nonRef = {};
const nonRef = {};
expect((0, _primitives.isRef)(nonRef)).toEqual(false);
});
it("handles refs", function () {
var ref = _primitives.Ref.get(1, 0);
const ref = _primitives.Ref.get(1, 0);

@@ -345,5 +514,5 @@ expect((0, _primitives.isRef)(ref)).toEqual(true);

it("should handle Refs pointing to the same object", function () {
var ref1 = _primitives.Ref.get(1, 0);
const ref1 = _primitives.Ref.get(1, 0);
var ref2 = _primitives.Ref.get(1, 0);
const ref2 = _primitives.Ref.get(1, 0);

@@ -353,5 +522,5 @@ expect((0, _primitives.isRefsEqual)(ref1, ref2)).toEqual(true);

it("should handle Refs pointing to different objects", function () {
var ref1 = _primitives.Ref.get(1, 0);
const ref1 = _primitives.Ref.get(1, 0);
var ref2 = _primitives.Ref.get(2, 0);
const ref2 = _primitives.Ref.get(2, 0);

@@ -361,2 +530,12 @@ expect((0, _primitives.isRefsEqual)(ref1, ref2)).toEqual(false);

});
describe("isStream", function () {
it("handles non-streams", function () {
const nonStream = {};
expect((0, _primitives.isStream)(nonStream)).toEqual(false);
});
it("handles streams", function () {
const stream = new _stream.StringStream("foo");
expect((0, _primitives.isStream)(stream)).toEqual(true);
});
});
});

@@ -29,4 +29,9 @@ /**

exports.createIdFactory = createIdFactory;
exports.TEST_PDFS_PATH = exports.XRefMock = exports.NodeCMapReaderFactory = exports.NodeCanvasFactory = exports.NodeFileReaderFactory = exports.DOMFileReaderFactory = void 0;
exports.isEmptyObj = isEmptyObj;
exports.TEST_PDFS_PATH = exports.XRefMock = exports.NodeFileReaderFactory = exports.DOMFileReaderFactory = void 0;
var _primitives = require("../../core/primitives.js");
var _document = require("../../core/document.js");
var _util = require("../../shared/util.js");

@@ -36,6 +41,4 @@

var _primitives = require("../../core/primitives.js");
var _stream = require("../../core/stream.js");
var _document = require("../../core/document.js");
class DOMFileReaderFactory {

@@ -97,82 +100,10 @@ static async fetch(params) {

class NodeCanvasFactory {
create(width, height) {
(0, _util.assert)(width > 0 && height > 0, "Invalid canvas size");
const Canvas = require("canvas");
const canvas = Canvas.createCanvas(width, height);
return {
canvas,
context: canvas.getContext("2d")
};
}
reset(canvasAndContext, width, height) {
(0, _util.assert)(canvasAndContext.canvas, "Canvas is not specified");
(0, _util.assert)(width > 0 && height > 0, "Invalid canvas size");
canvasAndContext.canvas.width = width;
canvasAndContext.canvas.height = height;
}
destroy(canvasAndContext) {
(0, _util.assert)(canvasAndContext.canvas, "Canvas is not specified");
canvasAndContext.canvas.width = 0;
canvasAndContext.canvas.height = 0;
canvasAndContext.canvas = null;
canvasAndContext.context = null;
}
}
exports.NodeCanvasFactory = NodeCanvasFactory;
class NodeCMapReaderFactory {
constructor({
baseUrl = null,
isCompressed = false
}) {
this.baseUrl = baseUrl;
this.isCompressed = isCompressed;
}
async fetch({
name
}) {
if (!this.baseUrl) {
throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
}
if (!name) {
throw new Error("CMap name must be specified.");
}
const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
return new Promise((resolve, reject) => {
const fs = require("fs");
fs.readFile(url, (error, data) => {
if (error || !data) {
reject(new Error(error));
return;
}
resolve({
cMapData: new Uint8Array(data),
compressionType
});
});
}).catch(reason => {
throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}` + `CMap at: ${url}`);
});
}
}
exports.NodeCMapReaderFactory = NodeCMapReaderFactory;
class XRefMock {
constructor(array) {
this._map = Object.create(null);
this.stats = {
streamTypes: Object.create(null),
fontTypes: Object.create(null)
};
this._newRefNum = null;

@@ -185,2 +116,14 @@ for (const key in array) {

getNewRef() {
if (this._newRefNum === null) {
this._newRefNum = Object.keys(this._map).length;
}
return _primitives.Ref.get(this._newRefNum++, 0);
}
resetNewRef() {
this.newRef = null;
}
fetch(ref) {

@@ -211,12 +154,22 @@ return this._map[ref.toString()];

function createIdFactory(pageIndex) {
const pdfManager = {
get docId() {
return "d0";
}
};
const stream = new _stream.StringStream("Dummy_PDF_data");
const pdfDocument = new _document.PDFDocument(pdfManager, stream);
const page = new _document.Page({
pdfManager: {
get docId() {
return "d0";
}
pdfManager: pdfDocument.pdfManager,
xref: pdfDocument.xref,
pageIndex,
globalIdFactory: pdfDocument._globalIdFactory
});
return page._localIdFactory;
}
},
pageIndex
});
return page.idFactory;
function isEmptyObj(obj) {
(0, _util.assert)(typeof obj === "object" && obj !== null, "isEmptyObj - invalid argument.");
return Object.keys(obj).length === 0;
}

@@ -75,7 +75,19 @@ /**

this.runnerStartTime = this.now();
sendInfo("Started tests for " + browser + ".");
const total = suiteInfo.totalSpecsDefined;
const seed = suiteInfo.order.seed;
sendInfo(`Started ${total} tests for ${browser} with seed ${seed}.`);
};
this.suiteStarted = function (result) {};
this.suiteStarted = function (result) {
if (result.failedExpectations.length > 0) {
let failedMessages = "";
for (const item of result.failedExpectations) {
failedMessages += `${item.message} `;
}
sendResult("TEST-UNEXPECTED-FAIL", result.description, failedMessages);
}
};
this.specStarted = function (result) {};

@@ -87,7 +99,6 @@

} else {
var failedMessages = "";
var items = result.failedExpectations;
let failedMessages = "";
for (var i = 0, ii = items.length; i < ii; i++) {
failedMessages += items[i].message + " ";
for (const item of result.failedExpectations) {
failedMessages += `${item.message} `;
}

@@ -94,0 +105,0 @@

@@ -75,12 +75,2 @@ /**

});
describe("isEmptyObj", function () {
it("handles empty objects", function () {
expect((0, _util.isEmptyObj)({})).toEqual(true);
});
it("handles non-empty objects", function () {
expect((0, _util.isEmptyObj)({
foo: "bar"
})).toEqual(false);
});
});
describe("isNum", function () {

@@ -199,6 +189,6 @@ it("handles numeric values", function () {

});
it("handles URLs that do not use a whitelisted protocol", function () {
it("handles URLs that do not use an allowed protocol", function () {
expect((0, _util.createValidAbsoluteUrl)("magnet:?foo", null)).toEqual(null);
});
it("correctly creates a valid URL for whitelisted protocols", function () {
it("correctly creates a valid URL for allowed protocols", function () {
expect((0, _util.createValidAbsoluteUrl)("http://www.mozilla.org/foo", null)).toEqual(new URL("http://www.mozilla.org/foo"));

@@ -243,2 +233,13 @@ expect((0, _util.createValidAbsoluteUrl)("/foo", "http://www.mozilla.org")).toEqual(new URL("http://www.mozilla.org/foo"));

});
describe("escapeString", function () {
it("should escape (, ) and \\", function () {
expect((0, _util.escapeString)("((a\\a))(b(b\\b)b)")).toEqual("\\(\\(a\\\\a\\)\\)\\(b\\(b\\\\b\\)b\\)");
});
});
describe("getModificationDate", function () {
it("should get a correctly formatted date", function () {
const date = new Date(Date.UTC(3141, 5, 9, 2, 6, 53));
expect((0, _util.getModificationDate)(date)).toEqual("31410610020653");
});
});
});

@@ -41,4 +41,5 @@ /**

downloadManager,
annotationStorage = null,
imageResourcesPath = "",
renderInteractiveForms = false,
renderInteractiveForms = true,
l10n = _ui_utils.NullL10n

@@ -53,2 +54,3 @@ }) {

this.l10n = l10n;
this.annotationStorage = annotationStorage;
this.div = null;

@@ -59,3 +61,3 @@ this._cancelled = false;

render(viewport, intent = "display") {
this.pdfPage.getAnnotations({
return this.pdfPage.getAnnotations({
intent

@@ -67,2 +69,6 @@ }).then(annotations => {

if (annotations.length === 0) {
return;
}
const parameters = {

@@ -78,3 +84,4 @@ viewport: viewport.clone({

linkService: this.linkService,
downloadManager: this.downloadManager
downloadManager: this.downloadManager,
annotationStorage: this.annotationStorage
};

@@ -85,6 +92,2 @@

} else {
if (annotations.length === 0) {
return;
}
this.div = document.createElement("div");

@@ -119,3 +122,3 @@ this.div.className = "annotationLayer";

class DefaultAnnotationLayerFactory {
createAnnotationLayerBuilder(pageDiv, pdfPage, imageResourcesPath = "", renderInteractiveForms = false, l10n = _ui_utils.NullL10n) {
createAnnotationLayerBuilder(pageDiv, pdfPage, annotationStorage = null, imageResourcesPath = "", renderInteractiveForms = true, l10n = _ui_utils.NullL10n) {
return new AnnotationLayerBuilder({

@@ -127,3 +130,4 @@ pageDiv,

linkService: new _pdf_link_service.SimpleLinkService(),
l10n
l10n,
annotationStorage
});

@@ -130,0 +134,0 @@ }

@@ -51,7 +51,2 @@ /**

},
disableCreateObjectURL: {
value: false,
compatibility: _viewer_compatibility.viewerCompatibilityParams.disableCreateObjectURL,
kind: OptionKind.VIEWER
},
disableHistory: {

@@ -115,3 +110,3 @@ value: false,

renderInteractiveForms: {
value: false,
value: true,
kind: OptionKind.VIEWER + OptionKind.PREFERENCE

@@ -118,0 +113,0 @@ },

@@ -104,2 +104,7 @@ /**

this.viewer = options.viewer || options.container.firstElementChild;
if (!(this.container instanceof HTMLDivElement && this.viewer instanceof HTMLDivElement)) {
throw new Error("Invalid `container` and/or `viewer` option.");
}
this.eventBus = options.eventBus;

@@ -112,3 +117,3 @@ this.linkService = options.linkService || new _pdf_link_service.SimpleLinkService();

this.imageResourcesPath = options.imageResourcesPath || "";
this.renderInteractiveForms = options.renderInteractiveForms || false;
this.renderInteractiveForms = typeof options.renderInteractiveForms === "boolean" ? options.renderInteractiveForms : true;
this.enablePrintAutoRotate = options.enablePrintAutoRotate || false;

@@ -344,2 +349,4 @@ this.renderer = options.renderer || _ui_utils.RendererType.CANVAS;

const firstPagePromise = pdfDocument.getPage(1);
const annotationStorage = pdfDocument.annotationStorage;
const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig();

@@ -382,2 +389,3 @@ this._pagesCapability.promise.then(() => {

this._optionalContentConfigPromise = optionalContentConfigPromise;
const scale = this.currentScale;

@@ -396,2 +404,4 @@ const viewport = firstPdfPage.getViewport({

defaultViewport: viewport.clone(),
annotationStorage,
optionalContentConfigPromise,
renderingQueue: this.renderingQueue,

@@ -508,2 +518,3 @@ textLayerFactory,

this._pagesRotation = 0;
this._optionalContentConfigPromise = null;
this._pagesRequests = new WeakMap();

@@ -980,6 +991,7 @@ this._firstPageCapability = (0, _pdf.createPromiseCapability)();

createAnnotationLayerBuilder(pageDiv, pdfPage, imageResourcesPath = "", renderInteractiveForms = false, l10n = _ui_utils.NullL10n) {
createAnnotationLayerBuilder(pageDiv, pdfPage, annotationStorage = null, imageResourcesPath = "", renderInteractiveForms = false, l10n = _ui_utils.NullL10n) {
return new _annotation_layer_builder.AnnotationLayerBuilder({
pageDiv,
pdfPage,
annotationStorage,
imageResourcesPath,

@@ -1023,5 +1035,4 @@ renderInteractiveForms,

const isFirstPagePortrait = (0, _ui_utils.isPortraitOrientation)(pagesOverview[0]);
return pagesOverview.map(function (size) {
if (isFirstPagePortrait === (0, _ui_utils.isPortraitOrientation)(size)) {
if ((0, _ui_utils.isPortraitOrientation)(size)) {
return size;

@@ -1038,2 +1049,40 @@ }

get optionalContentConfigPromise() {
if (!this.pdfDocument) {
return Promise.resolve(null);
}
if (!this._optionalContentConfigPromise) {
return this.pdfDocument.getOptionalContentConfig();
}
return this._optionalContentConfigPromise;
}
set optionalContentConfigPromise(promise) {
if (!(promise instanceof Promise)) {
throw new Error(`Invalid optionalContentConfigPromise: ${promise}`);
}
if (!this.pdfDocument) {
return;
}
if (!this._optionalContentConfigPromise) {
return;
}
this._optionalContentConfigPromise = promise;
for (const pageView of this._pages) {
pageView.update(pageView.scale, pageView.rotation, promise);
}
this.update();
this.eventBus.dispatch("optionalcontentconfigchanged", {
source: this,
promise
});
}
get scrollMode() {

@@ -1040,0 +1089,0 @@ return this._scrollMode;

@@ -34,3 +34,2 @@ /**

;
const DISABLE_CREATE_OBJECT_URL = _viewer_compatibility.viewerCompatibilityParams.disableCreateObjectURL || false;

@@ -57,8 +56,2 @@ function download(blobUrl, filename) {

class DownloadManager {
constructor({
disableCreateObjectURL = DISABLE_CREATE_OBJECT_URL
}) {
this.disableCreateObjectURL = disableCreateObjectURL;
}
downloadUrl(url, filename) {

@@ -80,7 +73,7 @@ if (!(0, _pdf.createValidAbsoluteUrl)(url, "http://example.com")) {

const blobUrl = (0, _pdf.createObjectURL)(data, contentType, this.disableCreateObjectURL);
const blobUrl = (0, _pdf.createObjectURL)(data, contentType, _viewer_compatibility.viewerCompatibilityParams.disableCreateObjectURL);
download(blobUrl, filename);
}
download(blob, url, filename) {
download(blob, url, filename, sourceEventType = "download") {
if (navigator.msSaveBlob) {

@@ -94,3 +87,3 @@ if (!navigator.msSaveBlob(blob, filename)) {

if (this.disableCreateObjectURL) {
if (_viewer_compatibility.viewerCompatibilityParams.disableCreateObjectURL) {
this.downloadUrl(url, filename);

@@ -97,0 +90,0 @@ return;

@@ -29,4 +29,2 @@ /**

var _app_options = require("./app_options.js");
var _ui_utils = require("./ui_utils.js");

@@ -38,6 +36,5 @@

function composePage(pdfDocument, pageNumber, size, printContainer) {
function composePage(pdfDocument, pageNumber, size, printContainer, printResolution, optionalContentConfigPromise) {
const canvas = document.createElement("canvas");
const PRINT_RESOLUTION = _app_options.AppOptions.get("printResolution") || 150;
const PRINT_UNITS = PRINT_RESOLUTION / 72.0;
const PRINT_UNITS = printResolution / 72.0;
canvas.width = Math.floor(size.width * PRINT_UNITS);

@@ -50,2 +47,3 @@ canvas.height = Math.floor(size.height * PRINT_UNITS);

printContainer.appendChild(canvasWrapper);
let currentRenderTask = null;

@@ -58,3 +56,9 @@ canvas.mozPrintCallback = function (obj) {

ctx.restore();
let thisRenderTask = null;
pdfDocument.getPage(pageNumber).then(function (pdfPage) {
if (currentRenderTask) {
currentRenderTask.cancel();
currentRenderTask = null;
}
const renderContext = {

@@ -67,6 +71,13 @@ canvasContext: ctx,

}),
intent: "print"
intent: "print",
annotationStorage: pdfDocument.annotationStorage,
optionalContentConfigPromise
};
return pdfPage.render(renderContext).promise;
currentRenderTask = thisRenderTask = pdfPage.render(renderContext);
return thisRenderTask.promise;
}).then(function () {
if (currentRenderTask === thisRenderTask) {
currentRenderTask = null;
}
obj.done();

@@ -76,2 +87,7 @@ }, function (error) {

if (currentRenderTask === thisRenderTask) {
currentRenderTask.cancel();
currentRenderTask = null;
}
if ("abort" in obj) {

@@ -86,6 +102,8 @@ obj.abort();

function FirefoxPrintService(pdfDocument, pagesOverview, printContainer) {
function FirefoxPrintService(pdfDocument, pagesOverview, printContainer, printResolution, optionalContentConfigPromise = null) {
this.pdfDocument = pdfDocument;
this.pagesOverview = pagesOverview;
this.printContainer = printContainer;
this._printResolution = printResolution || 150;
this._optionalContentConfigPromise = optionalContentConfigPromise || pdfDocument.getOptionalContentConfig();
}

@@ -98,3 +116,5 @@

pagesOverview,
printContainer
printContainer,
_printResolution,
_optionalContentConfigPromise
} = this;

@@ -105,3 +125,3 @@ const body = document.querySelector("body");

for (let i = 0, ii = pagesOverview.length; i < ii; ++i) {
composePage(pdfDocument, i + 1, pagesOverview[i], printContainer);
composePage(pdfDocument, i + 1, pagesOverview[i], printContainer, _printResolution, _optionalContentConfigPromise);
}

@@ -124,6 +144,6 @@ },

createPrintService(pdfDocument, pagesOverview, printContainer) {
return new FirefoxPrintService(pdfDocument, pagesOverview, printContainer);
createPrintService(pdfDocument, pagesOverview, printContainer, printResolution, optionalContentConfigPromise) {
return new FirefoxPrintService(pdfDocument, pagesOverview, printContainer, printResolution, optionalContentConfigPromise);
}
};

@@ -90,6 +90,2 @@ /**

class DownloadManager {
constructor(options) {
this.disableCreateObjectURL = false;
}
downloadUrl(url, filename) {

@@ -119,3 +115,3 @@ FirefoxCom.request("download", {

download(blob, url, filename) {
download(blob, url, filename, sourceEventType = "download") {
const blobUrl = URL.createObjectURL(blob);

@@ -134,3 +130,4 @@

originalUrl: url,
filename
filename,
sourceEventType
}, onResponse);

@@ -245,2 +242,19 @@ }

(function listenSaveEvent() {
const handleEvent = function ({
type,
detail
}) {
if (!_app.PDFViewerApplication.initialized) {
return;
}
_app.PDFViewerApplication.eventBus.dispatch(type, {
source: window
});
};
window.addEventListener("save", handleEvent);
})();
class FirefoxComDataRangeTransport extends _pdf.PDFDataRangeTransport {

@@ -247,0 +261,0 @@ requestDataRange(begin, end) {

@@ -108,3 +108,3 @@ /**

class IPDFAnnotationLayerFactory {
createAnnotationLayerBuilder(pageDiv, pdfPage, imageResourcesPath = "", renderInteractiveForms = false, l10n = undefined) {}
createAnnotationLayerBuilder(pageDiv, pdfPage, annotationStorage = null, imageResourcesPath = "", renderInteractiveForms = true, l10n = undefined) {}

@@ -111,0 +111,0 @@ }

@@ -31,13 +31,13 @@ /**

class PDFAttachmentViewer {
constructor({
container,
eventBus,
downloadManager
}) {
this.container = container;
this.eventBus = eventBus;
this.downloadManager = downloadManager;
this.reset();
var _base_tree_viewer = require("./base_tree_viewer.js");
var _viewer_compatibility = require("./viewer_compatibility.js");
const PdfFileRegExp = /\.pdf$/i;
class PDFAttachmentViewer extends _base_tree_viewer.BaseTreeViewer {
constructor(options) {
super(options);
this.downloadManager = options.downloadManager;
this.eventBus._on("fileattachmentannotation", this._appendAttachment.bind(this));

@@ -47,4 +47,4 @@ }

reset(keepRenderedCapability = false) {
this.attachments = null;
this.container.textContent = "";
super.reset();
this._attachments = null;

@@ -54,2 +54,8 @@ if (!keepRenderedCapability) {

}
if (this._pendingDispatchEvent) {
clearTimeout(this._pendingDispatchEvent);
}
this._pendingDispatchEvent = null;
}

@@ -60,2 +66,18 @@

if (this._pendingDispatchEvent) {
clearTimeout(this._pendingDispatchEvent);
this._pendingDispatchEvent = null;
}
if (attachmentsCount === 0) {
this._pendingDispatchEvent = setTimeout(() => {
this.eventBus.dispatch("attachmentsloaded", {
source: this,
attachmentsCount: 0
});
this._pendingDispatchEvent = null;
});
return;
}
this.eventBus.dispatch("attachmentsloaded", {

@@ -67,6 +89,9 @@ source: this,

_bindPdfLink(button, content, filename) {
_bindPdfLink(element, {
content,
filename
}) {
let blobUrl;
button.onclick = () => {
element.onclick = () => {
if (!blobUrl) {

@@ -94,5 +119,9 @@ blobUrl = URL.createObjectURL(new Blob([content], {

_bindLink(button, content, filename) {
button.onclick = () => {
this.downloadManager.downloadData(content, filename, "");
_bindLink(element, {
content,
filename
}) {
element.onclick = () => {
const contentType = PdfFileRegExp.test(filename) ? "application/pdf" : "";
this.downloadManager.downloadData(content, filename, contentType);
return false;

@@ -106,12 +135,10 @@ };

}) {
let attachmentsCount = 0;
if (this.attachments) {
this.reset(keepRenderedCapability === true);
if (this._attachments) {
this.reset(keepRenderedCapability);
}
this.attachments = attachments || null;
this._attachments = attachments || null;
if (!attachments) {
this._dispatchEvent(attachmentsCount);
this._dispatchEvent(0);

@@ -124,22 +151,32 @@ return;

});
attachmentsCount = names.length;
const fragment = document.createDocumentFragment();
let attachmentsCount = 0;
for (let i = 0; i < attachmentsCount; i++) {
const item = attachments[names[i]];
const filename = (0, _pdf.removeNullCharacters)((0, _pdf.getFilenameFromUrl)(item.filename));
for (const name of names) {
const item = attachments[name];
const filename = (0, _pdf.getFilenameFromUrl)(item.filename);
const div = document.createElement("div");
div.className = "attachmentsItem";
const button = document.createElement("button");
button.textContent = filename;
div.className = "treeItem";
const element = document.createElement("a");
if (/\.pdf$/i.test(filename) && !this.downloadManager.disableCreateObjectURL) {
this._bindPdfLink(button, item.content, filename);
if (PdfFileRegExp.test(filename) && !_viewer_compatibility.viewerCompatibilityParams.disableCreateObjectURL) {
this._bindPdfLink(element, {
content: item.content,
filename
});
} else {
this._bindLink(button, item.content, filename);
this._bindLink(element, {
content: item.content,
filename
});
}
div.appendChild(button);
this.container.appendChild(div);
element.textContent = this._normalizeTextContent(filename);
div.appendChild(element);
fragment.appendChild(div);
attachmentsCount++;
}
this.container.appendChild(fragment);
this._dispatchEvent(attachmentsCount);

@@ -153,5 +190,10 @@ }

}) {
this._renderedCapability.promise.then(() => {
let attachments = this.attachments;
const renderedPromise = this._renderedCapability.promise;
renderedPromise.then(() => {
if (renderedPromise !== this._renderedCapability.promise) {
return;
}
let attachments = this._attachments;
if (!attachments) {

@@ -158,0 +200,0 @@ attachments = Object.create(null);

@@ -690,3 +690,4 @@ /**

previous,
matchesCount: this._requestMatchesCount()
matchesCount: this._requestMatchesCount(),
rawQuery: this._state ? this._state.query : null
});

@@ -693,0 +694,0 @@ }

@@ -31,23 +31,15 @@ /**

const DEFAULT_TITLE = "\u2013";
var _base_tree_viewer = require("./base_tree_viewer.js");
class PDFOutlineViewer {
constructor({
container,
linkService,
eventBus
}) {
this.container = container;
this.linkService = linkService;
this.eventBus = eventBus;
this.reset();
class PDFOutlineViewer extends _base_tree_viewer.BaseTreeViewer {
constructor(options) {
super(options);
this.linkService = options.linkService;
eventBus._on("toggleoutlinetree", this.toggleOutlineTree.bind(this));
this.eventBus._on("toggleoutlinetree", this._toggleAllTreeItems.bind(this));
}
reset() {
this.outline = null;
this.lastToggleIsShow = true;
this.container.textContent = "";
this.container.classList.remove("outlineWithDeepNesting");
super.reset();
this._outline = null;
}

@@ -109,37 +101,13 @@

}) {
const toggler = document.createElement("div");
toggler.className = "outlineItemToggler";
const hidden = count < 0 && Math.abs(count) === items.length;
if (count < 0 && Math.abs(count) === items.length) {
toggler.classList.add("outlineItemsHidden");
}
toggler.onclick = evt => {
evt.stopPropagation();
toggler.classList.toggle("outlineItemsHidden");
if (evt.shiftKey) {
const shouldShowAll = !toggler.classList.contains("outlineItemsHidden");
this._toggleOutlineItem(div, shouldShowAll);
}
};
div.insertBefore(toggler, div.firstChild);
super._addToggleButton(div, hidden);
}
_toggleOutlineItem(root, show = false) {
this.lastToggleIsShow = show;
for (const toggler of root.querySelectorAll(".outlineItemToggler")) {
toggler.classList.toggle("outlineItemsHidden", !show);
}
}
toggleOutlineTree() {
if (!this.outline) {
_toggleAllTreeItems() {
if (!this._outline) {
return;
}
this._toggleOutlineItem(this.container, !this.lastToggleIsShow);
super._toggleAllTreeItems();
}

@@ -150,12 +118,10 @@

}) {
let outlineCount = 0;
if (this.outline) {
if (this._outline) {
this.reset();
}
this.outline = outline || null;
this._outline = outline || null;
if (!outline) {
this._dispatchEvent(outlineCount);
this._dispatchEvent(0);

@@ -168,5 +134,6 @@ return;

parent: fragment,
items: this.outline
items: outline
}];
let hasAnyNesting = false;
let outlineCount = 0,
hasAnyNesting = false;

@@ -178,3 +145,3 @@ while (queue.length > 0) {

const div = document.createElement("div");
div.className = "outlineItem";
div.className = "treeItem";
const element = document.createElement("a");

@@ -186,3 +153,3 @@

element.textContent = (0, _pdf.removeNullCharacters)(item.title) || DEFAULT_TITLE;
element.textContent = this._normalizeTextContent(item.title);
div.appendChild(element);

@@ -196,3 +163,3 @@

const itemsDiv = document.createElement("div");
itemsDiv.className = "outlineItems";
itemsDiv.className = "treeItems";
div.appendChild(itemsDiv);

@@ -211,4 +178,4 @@ queue.push({

if (hasAnyNesting) {
this.container.classList.add("outlineWithDeepNesting");
this.lastToggleIsShow = fragment.querySelectorAll(".outlineItemsHidden").length === 0;
this.container.classList.add("treeWithDeepNesting");
this._lastToggleIsShow = fragment.querySelectorAll(".treeItemsHidden").length === 0;
}

@@ -215,0 +182,0 @@

@@ -51,6 +51,8 @@ /**

this.pdfPageRotate = defaultViewport.rotation;
this._annotationStorage = options.annotationStorage || null;
this._optionalContentConfigPromise = options.optionalContentConfigPromise || null;
this.hasRestrictedScaling = false;
this.textLayerMode = Number.isInteger(options.textLayerMode) ? options.textLayerMode : _ui_utils.TextLayerMode.ENABLE;
this.imageResourcesPath = options.imageResourcesPath || "";
this.renderInteractiveForms = options.renderInteractiveForms || false;
this.renderInteractiveForms = typeof options.renderInteractiveForms === "boolean" ? options.renderInteractiveForms : true;
this.useOnlyCssZoom = options.useOnlyCssZoom || false;

@@ -102,2 +104,18 @@ this.maxCanvasPixels = options.maxCanvasPixels || MAX_CANVAS_PIXELS;

async _renderAnnotationLayer() {
let error = null;
try {
await this.annotationLayer.render(this.viewport, "display");
} catch (ex) {
error = ex;
} finally {
this.eventBus.dispatch("annotationlayerrendered", {
source: this,
pageNumber: this.id,
error
});
}
}
_resetZoomLayer(removeFromDOM = false) {

@@ -170,3 +188,3 @@ if (!this.zoomLayer) {

update(scale, rotation) {
update(scale, rotation, optionalContentConfigPromise = null) {
this.scale = scale || this.scale;

@@ -178,2 +196,6 @@

if (optionalContentConfigPromise instanceof Promise) {
this._optionalContentConfigPromise = optionalContentConfigPromise;
}
const totalRotation = (this.rotation + this.pdfPageRotate) % 360;

@@ -312,3 +334,3 @@ this.viewport = this.viewport.clone({

if (redrawAnnotations && this.annotationLayer) {
this.annotationLayer.render(this.viewport, "display");
this._renderAnnotationLayer();
}

@@ -452,6 +474,6 @@ }

if (!this.annotationLayer) {
this.annotationLayer = this.annotationLayerFactory.createAnnotationLayerBuilder(div, pdfPage, this.imageResourcesPath, this.renderInteractiveForms, this.l10n);
this.annotationLayer = this.annotationLayerFactory.createAnnotationLayerBuilder(div, pdfPage, this._annotationStorage, this.imageResourcesPath, this.renderInteractiveForms, this.l10n);
}
this.annotationLayer.render(this.viewport, "display");
this._renderAnnotationLayer();
}

@@ -543,3 +565,4 @@

enableWebGL: this.enableWebGL,
renderInteractiveForms: this.renderInteractiveForms
renderInteractiveForms: this.renderInteractiveForms,
optionalContentConfigPromise: this._optionalContentConfigPromise
};

@@ -546,0 +569,0 @@ const renderTask = this.pdfPage.render(renderContext);

@@ -33,3 +33,3 @@ /**

var _app_options = require("./app_options.js");
var _viewer_compatibility = require("./viewer_compatibility.js");

@@ -39,6 +39,5 @@ let activeService = null;

function renderPage(activeServiceOnEntry, pdfDocument, pageNumber, size) {
function renderPage(activeServiceOnEntry, pdfDocument, pageNumber, size, printResolution, optionalContentConfigPromise) {
const scratchCanvas = activeService.scratchCanvas;
const PRINT_RESOLUTION = _app_options.AppOptions.get("printResolution") || 150;
const PRINT_UNITS = PRINT_RESOLUTION / 72.0;
const PRINT_UNITS = printResolution / 72.0;
scratchCanvas.width = Math.floor(size.width * PRINT_UNITS);

@@ -61,3 +60,5 @@ scratchCanvas.height = Math.floor(size.height * PRINT_UNITS);

}),
intent: "print"
intent: "print",
annotationStorage: pdfDocument.annotationStorage,
optionalContentConfigPromise
};

@@ -73,8 +74,9 @@ return pdfPage.render(renderContext).promise;

function PDFPrintService(pdfDocument, pagesOverview, printContainer, l10n) {
function PDFPrintService(pdfDocument, pagesOverview, printContainer, printResolution, optionalContentConfigPromise = null, l10n) {
this.pdfDocument = pdfDocument;
this.pagesOverview = pagesOverview;
this.printContainer = printContainer;
this._printResolution = printResolution || 150;
this._optionalContentConfigPromise = optionalContentConfigPromise || pdfDocument.getOptionalContentConfig();
this.l10n = l10n || _ui_utils.NullL10n;
this.disableCreateObjectURL = _app_options.AppOptions.get("disableCreateObjectURL");
this.currentPage = -1;

@@ -143,3 +145,3 @@ this.scratchCanvas = document.createElement("canvas");

renderProgress(index, pageCount, this.l10n);
renderPage(this, this.pdfDocument, index + 1, this.pagesOverview[index]).then(this.useRenderedPage.bind(this)).then(function () {
renderPage(this, this.pdfDocument, index + 1, this.pagesOverview[index], this._printResolution, this._optionalContentConfigPromise).then(this.useRenderedPage.bind(this)).then(function () {
renderNextPage(resolve, reject);

@@ -159,3 +161,3 @@ }, reject);

if ("toBlob" in scratchCanvas && !this.disableCreateObjectURL) {
if ("toBlob" in scratchCanvas && !_viewer_compatibility.viewerCompatibilityParams.disableCreateObjectURL) {
scratchCanvas.toBlob(function (blob) {

@@ -311,3 +313,3 @@ img.src = URL.createObjectURL(blob);

createPrintService(pdfDocument, pagesOverview, printContainer, l10n) {
createPrintService(pdfDocument, pagesOverview, printContainer, printResolution, optionalContentConfigPromise, l10n) {
if (activeService) {

@@ -317,3 +319,3 @@ throw new Error("The print service is created and active.");

activeService = new PDFPrintService(pdfDocument, pagesOverview, printContainer, l10n);
activeService = new PDFPrintService(pdfDocument, pagesOverview, printContainer, printResolution, optionalContentConfigPromise, l10n);
return activeService;

@@ -320,0 +322,0 @@ }

@@ -65,5 +65,7 @@ /**

this.attachmentsButton = elements.attachmentsButton;
this.layersButton = elements.layersButton;
this.thumbnailView = elements.thumbnailView;
this.outlineView = elements.outlineView;
this.attachmentsView = elements.attachmentsView;
this.layersView = elements.layersView;
this.eventBus = eventBus;

@@ -84,2 +86,3 @@ this.l10n = l10n;

this.attachmentsButton.disabled = false;
this.layersButton.disabled = false;
}

@@ -103,2 +106,6 @@

get isLayersViewVisible() {
return this.isOpen && this.active === SidebarView.LAYERS;
}
setInitialView(view = SidebarView.NONE) {

@@ -160,2 +167,9 @@ if (this.isInitialViewSet) {

case SidebarView.LAYERS:
if (this.layersButton.disabled) {
return false;
}
break;
default:

@@ -170,5 +184,7 @@ console.error(`PDFSidebar._switchView: "${view}" is not a valid view.`);

this.attachmentsButton.classList.toggle("toggled", view === SidebarView.ATTACHMENTS);
this.layersButton.classList.toggle("toggled", view === SidebarView.LAYERS);
this.thumbnailView.classList.toggle("hidden", view !== SidebarView.THUMBS);
this.outlineView.classList.toggle("hidden", view !== SidebarView.OUTLINE);
this.attachmentsView.classList.toggle("hidden", view !== SidebarView.ATTACHMENTS);
this.layersView.classList.toggle("hidden", view !== SidebarView.LAYERS);

@@ -278,3 +294,3 @@ if (forceOpen && !this.isOpen) {

this.l10n.get("toggle_sidebar_notification.title", null, "Toggle Sidebar (document contains outline/attachments)").then(msg => {
this.l10n.get("toggle_sidebar_notification2.title", null, "Toggle Sidebar (document contains outline/attachments/layers)").then(msg => {
this.toggleButton.title = msg;

@@ -297,2 +313,6 @@ });

break;
case SidebarView.LAYERS:
this.layersButton.classList.add(UI_NOTIFICATION_CLASS);
break;
}

@@ -315,2 +335,6 @@ }

break;
case SidebarView.LAYERS:
this.layersButton.classList.remove(UI_NOTIFICATION_CLASS);
break;
}

@@ -362,34 +386,31 @@ };

});
this.layersButton.addEventListener("click", () => {
this.switchView(SidebarView.LAYERS);
});
this.layersButton.addEventListener("dblclick", () => {
this.eventBus.dispatch("resetlayers", {
source: this
});
});
this.eventBus._on("outlineloaded", evt => {
const outlineCount = evt.outlineCount;
this.outlineButton.disabled = !outlineCount;
const onTreeLoaded = (count, button, view) => {
button.disabled = !count;
if (outlineCount) {
this._showUINotification(SidebarView.OUTLINE);
} else if (this.active === SidebarView.OUTLINE) {
if (count) {
this._showUINotification(view);
} else if (this.active === view) {
this.switchView(SidebarView.THUMBS);
}
};
this.eventBus._on("outlineloaded", evt => {
onTreeLoaded(evt.outlineCount, this.outlineButton, SidebarView.OUTLINE);
});
this.eventBus._on("attachmentsloaded", evt => {
if (evt.attachmentsCount) {
this.attachmentsButton.disabled = false;
onTreeLoaded(evt.attachmentsCount, this.attachmentsButton, SidebarView.ATTACHMENTS);
});
this._showUINotification(SidebarView.ATTACHMENTS);
return;
}
Promise.resolve().then(() => {
if (this.attachmentsView.hasChildNodes()) {
return;
}
this.attachmentsButton.disabled = true;
if (this.active === SidebarView.ATTACHMENTS) {
this.switchView(SidebarView.THUMBS);
}
});
this.eventBus._on("layersloaded", evt => {
onTreeLoaded(evt.layersCount, this.layersButton, SidebarView.LAYERS);
});

@@ -396,0 +417,0 @@

@@ -82,4 +82,6 @@ /**

defaultViewport,
optionalContentConfigPromise,
linkService,
renderingQueue,
checkSetImageDisabled,
disableCanvasToImageConversion = false,

@@ -95,2 +97,3 @@ l10n = _ui_utils.NullL10n

this.pdfPageRotate = defaultViewport.rotation;
this._optionalContentConfigPromise = optionalContentConfigPromise || null;
this.linkService = linkService;

@@ -101,2 +104,7 @@ this.renderingQueue = renderingQueue;

this.resume = null;
this._checkSetImageDisabled = checkSetImageDisabled || function () {
return false;
};
this.disableCanvasToImageConversion = disableCanvasToImageConversion;

@@ -326,3 +334,4 @@ this.pageWidth = this.viewport.width;

canvasContext: ctx,
viewport: drawViewport
viewport: drawViewport,
optionalContentConfigPromise: this._optionalContentConfigPromise
};

@@ -340,2 +349,6 @@ const renderTask = this.renderTask = pdfPage.render(renderContext);

setImage(pageView) {
if (this._checkSetImageDisabled()) {
return;
}
if (this.renderingState !== _pdf_rendering_queue.RenderingStates.INITIAL) {

@@ -394,3 +407,3 @@ return;

return this.l10n.get("thumb_page_title", {
page: this.pageLabel !== null ? this.pageLabel : this.id
page: this.pageLabel ?? this.id
}, "Page {{page}}");

@@ -401,3 +414,3 @@ }

return this.l10n.get("thumb_page_canvas", {
page: this.pageLabel !== null ? this.pageLabel : this.id
page: this.pageLabel ?? this.id
}, "Thumbnail of Page {{page}}");

@@ -404,0 +417,0 @@ }

@@ -39,2 +39,3 @@ /**

container,
eventBus,
linkService,

@@ -51,2 +52,6 @@ renderingQueue,

this._resetView();
eventBus._on("optionalcontentconfigchanged", () => {
this._setImageDisabled = true;
});
}

@@ -149,3 +154,5 @@

this._pagesRotation = 0;
this._optionalContentConfigPromise = null;
this._pagesRequests = new WeakMap();
this._setImageDisabled = false;
this.container.textContent = "";

@@ -167,3 +174,6 @@ }

pdfDocument.getPage(1).then(firstPdfPage => {
const firstPagePromise = pdfDocument.getPage(1);
const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig();
firstPagePromise.then(firstPdfPage => {
this._optionalContentConfigPromise = optionalContentConfigPromise;
const pagesCount = pdfDocument.numPages;

@@ -174,2 +184,6 @@ const viewport = firstPdfPage.getViewport({

const checkSetImageDisabled = () => {
return this._setImageDisabled;
};
for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) {

@@ -180,4 +194,6 @@ const thumbnail = new _pdf_thumbnail_view.PDFThumbnailView({

defaultViewport: viewport.clone(),
optionalContentConfigPromise,
linkService: this.linkService,
renderingQueue: this.renderingQueue,
checkSetImageDisabled,
disableCanvasToImageConversion: false,

@@ -184,0 +200,0 @@ l10n: this.l10n

@@ -146,3 +146,3 @@ /**

const pdfjsVersion = '2.5.207';
const pdfjsBuild = '0974d605';
const pdfjsVersion = '2.6.347';
const pdfjsBuild = '3be9c65f';

@@ -47,3 +47,3 @@ /**

"renderer": "canvas",
"renderInteractiveForms": false,
"renderInteractiveForms": true,
"sidebarViewOnLoad": -1,

@@ -50,0 +50,0 @@ "scrollModeOnLoad": -1,

@@ -271,3 +271,3 @@ /**

const overflow = SCALE_SELECT_WIDTH - SCALE_SELECT_CONTAINER_WIDTH;
maxWidth += 1.5 * overflow;
maxWidth += 2 * overflow;

@@ -274,0 +274,0 @@ if (maxWidth > SCALE_SELECT_CONTAINER_WIDTH) {

@@ -44,2 +44,3 @@ /**

exports.binarySearchFirstItem = binarySearchFirstItem;
exports.normalizeWheelEventDirection = normalizeWheelEventDirection;
exports.normalizeWheelEventDelta = normalizeWheelEventDelta;

@@ -482,3 +483,3 @@ exports.waitOnEventOrTimeout = waitOnEventOrTimeout;

function normalizeWheelEventDelta(evt) {
function normalizeWheelEventDirection(evt) {
let delta = Math.sqrt(evt.deltaX * evt.deltaX + evt.deltaY * evt.deltaY);

@@ -491,2 +492,7 @@ const angle = Math.atan2(evt.deltaY, evt.deltaX);

return delta;
}
function normalizeWheelEventDelta(evt) {
let delta = normalizeWheelEventDirection(evt);
const MOUSE_DOM_DELTA_PIXEL_MODE = 0;

@@ -493,0 +499,0 @@ const MOUSE_DOM_DELTA_LINE_MODE = 1;

{
"name": "pdfjs-dist",
"version": "2.5.207",
"version": "2.6.347",
"main": "build/pdf.js",
"types": "types/pdf.d.ts",
"description": "Generic build of Mozilla's PDF.js library.",

@@ -15,2 +16,3 @@ "keywords": [

"browser": {
"canvas": false,
"fs": false,

@@ -17,0 +19,0 @@ "http": false,

@@ -18,12 +18,4 @@ /* Copyright 2020 Mozilla Foundation

try {
require.resolve("worker-loader");
} catch (ex) {
throw new Error(
"Cannot find the `worker-loader` package, please make sure that it's correctly installed."
);
}
var pdfjs = require("./build/pdf.js");
var PdfjsWorker = require("worker-loader!./build/pdf.worker.js");
var PdfjsWorker = require("worker-loader?esModule=false!./build/pdf.worker.js");

@@ -30,0 +22,0 @@ if (typeof window !== "undefined" && "Worker" in window) {

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc