From 6a6e2a5ea1ab5f8eeaae70561ff40a002055b8a5 Mon Sep 17 00:00:00 2001 From: Peter Njeim Date: Fri, 12 Mar 2021 19:35:41 -0400 Subject: [PATCH 1/3] fix: packages and unnecessary if statement --- dist/main.js | 13016 +++++++++++++++++++++++---------------- src/cli.ts | 3 +- src/librescore-link.ts | 4 +- src/mscz.ts | 2 +- 4 files changed, 7772 insertions(+), 5253 deletions(-) diff --git a/dist/main.js b/dist/main.js index 3b58434..1a1ea24 100644 --- a/dist/main.js +++ b/dist/main.js @@ -1,78 +1,78 @@ -// ==UserScript== -// @name musescore-downloader -// @namespace https://www.xmader.com/ -// @homepageURL https://github.com/Xmader/musescore-downloader/ -// @supportURL https://github.com/Xmader/musescore-downloader/issues -// @updateURL https://msdl.librescore.org/install.user.js -// @downloadURL https://msdl.librescore.org/install.user.js -// @version 0.23.9 -// @description download sheet music from musescore.com for free, no login or Musescore Pro required | 免登录、免 Musescore Pro,免费下载 musescore.com 上的曲谱 -// @author Xmader -// @match https://musescore.com/*/* -// @match https://s.musescore.com/*/* -// @license MIT -// @copyright Copyright (c) 2019-2021 Xmader -// @grant unsafeWindow -// @grant GM.registerMenuCommand -// @grant GM.addElement -// @grant GM.openInTab -// @run-at document-start -// ==/UserScript== +// ==UserScript== +// @name musescore-downloader +// @namespace https://www.xmader.com/ +// @homepageURL https://github.com/Xmader/musescore-downloader/ +// @supportURL https://github.com/Xmader/musescore-downloader/issues +// @updateURL https://msdl.librescore.org/install.user.js +// @downloadURL https://msdl.librescore.org/install.user.js +// @version 0.23.9 +// @description download sheet music from musescore.com for free, no login or Musescore Pro required | 免登录、免 Musescore Pro,免费下载 musescore.com 上的曲谱 +// @author Xmader +// @match https://musescore.com/*/* +// @match https://s.musescore.com/*/* +// @license MIT +// @copyright Copyright (c) 2019-2021 Xmader +// @grant unsafeWindow +// @grant GM.registerMenuCommand +// @grant GM.addElement +// @grant GM.openInTab +// @run-at document-start +// ==/UserScript== (function () { 'use strict'; - /* eslint-disable */ - const w = typeof unsafeWindow == 'object' ? unsafeWindow : window; - - // GM APIs glue - const _GM = typeof GM == 'object' ? GM : undefined; - const gmId = '' + Math.random(); - w[gmId] = _GM; - - if (_GM && _GM.registerMenuCommand && _GM.openInTab) { - // add buttons to the userscript manager menu - _GM.registerMenuCommand( - `** Version: ${_GM.info.script.version} **`, - () => _GM.openInTab("https://github.com/Xmader/musescore-downloader/releases", { active: true }) - ) - - _GM.registerMenuCommand( - '** Source Code **', - () => _GM.openInTab(_GM.info.script.homepage, { active: true }) - ) - - _GM.registerMenuCommand( - '** Discord **', - () => _GM.openInTab("https://discord.gg/DKu7cUZ4XQ", { active: true }) - ) - } - - function getRandL () { - return String.fromCharCode(97 + Math.floor(Math.random() * 26)) - } - - // script loader - new Promise(resolve => { - const id = '' + Math.random(); - w[id] = resolve; - - const stackN = 9 - let loaderIntro = '' - for (let i = 0; i < stackN; i++) { - loaderIntro += `(function ${getRandL()}(){` - } - const loaderOutro = '})()'.repeat(stackN) - const mockUrl = "https://c.amazon-adsystem.com/aax2/apstag.js" - - setTimeout(`${loaderIntro}const d=new Image();window['${id}'](d);delete window['${id}'];document.body.prepend(d)${loaderOutro}//# sourceURL=${mockUrl}`) - }).then(d => { - d.style.display = 'none'; - d.src = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='; - d.once = false; - d.setAttribute('onload', `if(this.once)return;this.once=true;this.remove();const GM=window['${gmId}'];delete window['${gmId}'];(` + function a () { - /** script code here */ - + /* eslint-disable */ + const w = typeof unsafeWindow == 'object' ? unsafeWindow : window; + + // GM APIs glue + const _GM = typeof GM == 'object' ? GM : undefined; + const gmId = '' + Math.random(); + w[gmId] = _GM; + + if (_GM && _GM.registerMenuCommand && _GM.openInTab) { + // add buttons to the userscript manager menu + _GM.registerMenuCommand( + `** Version: ${_GM.info.script.version} **`, + () => _GM.openInTab("https://github.com/Xmader/musescore-downloader/releases", { active: true }) + ) + + _GM.registerMenuCommand( + '** Source Code **', + () => _GM.openInTab(_GM.info.script.homepage, { active: true }) + ) + + _GM.registerMenuCommand( + '** Discord **', + () => _GM.openInTab("https://discord.gg/DKu7cUZ4XQ", { active: true }) + ) + } + + function getRandL () { + return String.fromCharCode(97 + Math.floor(Math.random() * 26)) + } + + // script loader + new Promise(resolve => { + const id = '' + Math.random(); + w[id] = resolve; + + const stackN = 9 + let loaderIntro = '' + for (let i = 0; i < stackN; i++) { + loaderIntro += `(function ${getRandL()}(){` + } + const loaderOutro = '})()'.repeat(stackN) + const mockUrl = "https://c.amazon-adsystem.com/aax2/apstag.js" + + setTimeout(`${loaderIntro}const d=new Image();window['${id}'](d);delete window['${id}'];document.body.prepend(d)${loaderOutro}//# sourceURL=${mockUrl}`) + }).then(d => { + d.style.display = 'none'; + d.src = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='; + d.once = false; + d.setAttribute('onload', `if(this.once)return;this.once=true;this.remove();const GM=window['${gmId}'];delete window['${gmId}'];(` + function a () { + /** script code here */ + function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } @@ -323,7 +323,7 @@ }; // Only Node.JS has a process variable that is of [[Class]] process - var detectNode = Object.prototype.toString.call(typeof process$1 !== 'undefined' ? process$1 : 0) === '[object process]'; + var C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_detectNode = Object.prototype.toString.call(typeof process$1 !== 'undefined' ? process$1 : 0) === '[object process]'; const _GM = (typeof GM === 'object' ? GM : undefined); const isGmAvailable = (requiredMethod = 'info') => { @@ -339,7 +339,7 @@ 'Accept-Language': 'en-US,en;q=0.8', }; const getFetch = () => { - if (!detectNode) { + if (!C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_detectNode) { return fetch; } else { @@ -3533,6 +3533,1766 @@ return Object.prototype.hasOwnProperty.call(obj, prop); } + var INSPECT_MAX_BYTES$1 = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer$1.TYPED_ARRAY_SUPPORT = global$1$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1$1.TYPED_ARRAY_SUPPORT + : true; + + function kMaxLength$1 () { + return Buffer$1.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer$1 (that, length) { + if (kMaxLength$1() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer$1.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer$1(length); + } + that.length = length; + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer$1 (arg, encodingOrOffset, length) { + if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) { + return new Buffer$1(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe$1(this, arg) + } + return from$1(this, arg, encodingOrOffset, length) + } + + Buffer$1.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer$1._augment = function (arr) { + arr.__proto__ = Buffer$1.prototype; + return arr + }; + + function from$1 (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer$1(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString$1(that, value, encodingOrOffset) + } + + return fromObject$1(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer$1.from = function (value, encodingOrOffset, length) { + return from$1(null, value, encodingOrOffset, length) + }; + + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + Buffer$1.prototype.__proto__ = Uint8Array.prototype; + Buffer$1.__proto__ = Uint8Array; + } + + function assertSize$1 (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc$1 (that, size, fill, encoding) { + assertSize$1(size); + if (size <= 0) { + return createBuffer$1(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer$1(that, size).fill(fill, encoding) + : createBuffer$1(that, size).fill(fill) + } + return createBuffer$1(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer$1.alloc = function (size, fill, encoding) { + return alloc$1(null, size, fill, encoding) + }; + + function allocUnsafe$1 (that, size) { + assertSize$1(size); + that = createBuffer$1(that, size < 0 ? 0 : checked$1(size) | 0); + if (!Buffer$1.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer$1.allocUnsafe = function (size) { + return allocUnsafe$1(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer$1.allocUnsafeSlow = function (size) { + return allocUnsafe$1(null, size) + }; + + function fromString$1 (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer$1.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength$1(string, encoding) | 0; + that = createBuffer$1(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike$1 (that, array) { + var length = array.length < 0 ? 0 : checked$1(array.length) | 0; + that = createBuffer$1(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer$1 (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer$1.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike$1(that, array); + } + return that + } + + function fromObject$1 (that, obj) { + if (internalIsBuffer$1(obj)) { + var len = checked$1(obj.length) | 0; + that = createBuffer$1(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan$1(obj.length)) { + return createBuffer$1(that, 0) + } + return fromArrayLike$1(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike$1(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked$1 (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength$1()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength$1().toString(16) + ' bytes') + } + return length | 0 + } + Buffer$1.isBuffer = isBuffer$1; + function internalIsBuffer$1 (b) { + return !!(b != null && b._isBuffer) + } + + Buffer$1.compare = function compare (a, b) { + if (!internalIsBuffer$1(a) || !internalIsBuffer$1(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer$1.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer$1.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer$1.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer$1.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer$1(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength$1 (string, encoding) { + if (internalIsBuffer$1(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes$1(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes$1(string).length + default: + if (loweredCase) return utf8ToBytes$1(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer$1.byteLength = byteLength$1; + + function slowToString$1 (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice$1(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice$1(this, start, end) + + case 'ascii': + return asciiSlice$1(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice$1(this, start, end) + + case 'base64': + return base64Slice$1(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice$1(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer$1.prototype._isBuffer = true; + + function swap$1 (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer$1.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap$1(this, i, i + 1); + } + return this + }; + + Buffer$1.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap$1(this, i, i + 3); + swap$1(this, i + 1, i + 2); + } + return this + }; + + Buffer$1.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap$1(this, i, i + 7); + swap$1(this, i + 1, i + 6); + swap$1(this, i + 2, i + 5); + swap$1(this, i + 3, i + 4); + } + return this + }; + + Buffer$1.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice$1(this, 0, length) + return slowToString$1.apply(this, arguments) + }; + + Buffer$1.prototype.equals = function equals (b) { + if (!internalIsBuffer$1(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer$1.compare(this, b) === 0 + }; + + Buffer$1.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES$1; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer$1.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer$1(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf$1 (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer$1.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer$1(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf$1(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer$1.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf$1(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf$1 (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer$1.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer$1.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf$1(this, val, byteOffset, encoding, true) + }; + + Buffer$1.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf$1(this, val, byteOffset, encoding, false) + }; + + function hexWrite$1 (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write$1 (buf, string, offset, length) { + return blitBuffer$1(utf8ToBytes$1(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite$1 (buf, string, offset, length) { + return blitBuffer$1(asciiToBytes$1(string), buf, offset, length) + } + + function latin1Write$1 (buf, string, offset, length) { + return asciiWrite$1(buf, string, offset, length) + } + + function base64Write$1 (buf, string, offset, length) { + return blitBuffer$1(base64ToBytes$1(string), buf, offset, length) + } + + function ucs2Write$1 (buf, string, offset, length) { + return blitBuffer$1(utf16leToBytes$1(string, buf.length - offset), buf, offset, length) + } + + Buffer$1.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite$1(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write$1(this, string, offset, length) + + case 'ascii': + return asciiWrite$1(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write$1(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write$1(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write$1(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer$1.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice$1 (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice$1 (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray$1(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH$1 = 0x1000; + + function decodeCodePointsArray$1 (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH$1) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH$1) + ); + } + return res + } + + function asciiSlice$1 (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice$1 (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice$1 (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex$1(buf[i]); + } + return out + } + + function utf16leSlice$1 (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer$1.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer$1.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer$1(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset$1 (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer$1.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset$1(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer$1.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset$1(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer$1.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 1, this.length); + return this[offset] + }; + + Buffer$1.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer$1.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer$1.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer$1.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer$1.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset$1(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer$1.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset$1(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer$1.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer$1.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer$1.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer$1.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer$1.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer$1.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 4, this.length); + return read(this, offset, true, 23, 4) + }; + + Buffer$1.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 4, this.length); + return read(this, offset, false, 23, 4) + }; + + Buffer$1.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 8, this.length); + return read(this, offset, true, 52, 8) + }; + + Buffer$1.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 8, this.length); + return read(this, offset, false, 52, 8) + }; + + function checkInt$1 (buf, value, offset, ext, max, min) { + if (!internalIsBuffer$1(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer$1.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt$1(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer$1.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt$1(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer$1.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt$1(this, value, offset, 1, 0xff, 0); + if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16$1 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer$1.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt$1(this, value, offset, 2, 0xffff, 0); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16$1(this, value, offset, true); + } + return offset + 2 + }; + + Buffer$1.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt$1(this, value, offset, 2, 0xffff, 0); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16$1(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32$1 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer$1.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt$1(this, value, offset, 4, 0xffffffff, 0); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32$1(this, value, offset, true); + } + return offset + 4 + }; + + Buffer$1.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt$1(this, value, offset, 4, 0xffffffff, 0); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32$1(this, value, offset, false); + } + return offset + 4 + }; + + Buffer$1.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt$1(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer$1.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt$1(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer$1.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt$1(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer$1.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt$1(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16$1(this, value, offset, true); + } + return offset + 2 + }; + + Buffer$1.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt$1(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16$1(this, value, offset, false); + } + return offset + 2 + }; + + Buffer$1.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt$1(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32$1(this, value, offset, true); + } + return offset + 4 + }; + + Buffer$1.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt$1(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32$1(this, value, offset, false); + } + return offset + 4 + }; + + function checkIEEE754$1 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat$1 (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754$1(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer$1.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat$1(this, value, offset, true, noAssert) + }; + + Buffer$1.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat$1(this, value, offset, false, noAssert) + }; + + function writeDouble$1 (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754$1(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer$1.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble$1(this, value, offset, true, noAssert) + }; + + Buffer$1.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble$1(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer$1.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer$1.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer$1.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer$1.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer$1(val) + ? val + : utf8ToBytes$1(new Buffer$1(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE$1 = /[^+\/0-9A-Za-z-_]/g; + + function base64clean$1 (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim$1(str).replace(INVALID_BASE64_RE$1, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function stringtrim$1 (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex$1 (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes$1 (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes$1 (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes$1 (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + + function base64ToBytes$1 (str) { + return toByteArray(base64clean$1(str)) + } + + function blitBuffer$1 (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan$1 (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer$1(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer$1(obj) || isSlowBuffer$1(obj)) + } + + function isFastBuffer$1 (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer$1 (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer$1(obj.slice(0, 0)) + } + function BufferList() { this.head = null; this.tail = null; @@ -3576,9 +5336,9 @@ }; BufferList.prototype.concat = function (n) { - if (this.length === 0) return Buffer.alloc(0); + if (this.length === 0) return Buffer$1.alloc(0); if (this.length === 1) return this.head.data; - var ret = Buffer.allocUnsafe(n >>> 0); + var ret = Buffer$1.allocUnsafe(n >>> 0); var p = this.head; var i = 0; while (p) { @@ -3590,7 +5350,7 @@ }; // Copyright Joyent, Inc. and other Node contributors. - var isBufferEncoding = Buffer.isEncoding + var isBufferEncoding = Buffer$1.isEncoding || function(encoding) { switch (encoding && encoding.toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; @@ -3639,7 +5399,7 @@ // Enough space to store all bytes of a single character. UTF-8 needs 4 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer(6); + this.charBuffer = new Buffer$1(6); // Number of bytes received for the current incomplete multi-byte character. this.charReceived = 0; // Number of bytes expected for the current incomplete multi-byte character. @@ -4840,7 +6600,7 @@ // if it is not a buffer, string, or undefined. if (chunk === null) { er = new TypeError('May not write null values to stream'); - } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + } else if (!Buffer$1.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } if (er) { @@ -4860,7 +6620,7 @@ encoding = null; } - if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (Buffer$1.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; if (typeof cb !== 'function') cb = nop; @@ -4898,7 +6658,7 @@ function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); + chunk = Buffer$1.from(chunk, encoding); } return chunk; } @@ -4909,7 +6669,7 @@ function writeOrBuffer(stream, state, chunk, encoding, cb) { chunk = decodeChunk(state, chunk, encoding); - if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + if (Buffer$1.isBuffer(chunk)) encoding = 'buffer'; var len = state.objectMode ? 1 : chunk.length; state.length += len; @@ -5427,172 +7187,316 @@ var fs = {}; - /* - PDFAbstractReference - abstract class for PDF reference - */ - - class PDFAbstractReference { - toString() { - throw new Error('Must be implemented by subclasses'); - } + /* + PDFAbstractReference - abstract class for PDF reference + */ + + class PDFAbstractReference { + toString() { + throw new Error('Must be implemented by subclasses'); + } } - /* - PDFNameTree - represents a name tree object - */ - - class PDFNameTree { - - constructor() { - this._items = {}; - } - - add(key, val) { - return this._items[key] = val; - } - - get(key) { - return this._items[key]; - } - - toString() { - // Needs to be sorted by key - const sortedKeys = (Object.keys(this._items)).sort((a, b) => a.localeCompare(b)); - - const out = ['<<']; - if (sortedKeys.length > 1) { - const first = sortedKeys[0], last = sortedKeys[sortedKeys.length - 1]; - out.push(` /Limits ${PDFObject.convert([new String(first), new String(last)])}`); - } - out.push(' /Names ['); - for (let key of sortedKeys) { - out.push(` ${PDFObject.convert(new String(key))} ${PDFObject.convert(this._items[key])}`); - } - out.push(']'); - out.push('>>'); - return out.join('\n'); - } + /* + PDFNameTree - represents a name tree object + */ + + class PDFNameTree { + + constructor() { + this._items = {}; + } + + add(key, val) { + return this._items[key] = val; + } + + get(key) { + return this._items[key]; + } + + toString() { + // Needs to be sorted by key + const sortedKeys = (Object.keys(this._items)).sort((a, b) => a.localeCompare(b)); + + const out = ['<<']; + if (sortedKeys.length > 1) { + const first = sortedKeys[0], last = sortedKeys[sortedKeys.length - 1]; + out.push(` /Limits ${PDFObject.convert([new String(first), new String(last)])}`); + } + out.push(' /Names ['); + for (let key of sortedKeys) { + out.push(` ${PDFObject.convert(new String(key))} ${PDFObject.convert(this._items[key])}`); + } + out.push(']'); + out.push('>>'); + return out.join('\n'); + } } - const pad = (str, length) => (Array(length + 1).join('0') + str).slice(-length); + const pad = (str, length) => (Array(length + 1).join('0') + str).slice(-length); + + const escapableRe = /[\n\r\t\b\f\(\)\\]/g; + const escapable = { + '\n': '\\n', + '\r': '\\r', + '\t': '\\t', + '\b': '\\b', + '\f': '\\f', + '\\': '\\\\', + '(': '\\(', + ')': '\\)' + }; + + // Convert little endian UTF-16 to big endian + const swapBytes = function(buff) { + const l = buff.length; + if (l & 0x01) { + throw new Error('Buffer length must be even'); + } else { + for (let i = 0, end = l - 1; i < end; i += 2) { + const a = buff[i]; + buff[i] = buff[i + 1]; + buff[i + 1] = a; + } + } + + return buff; + }; + + class PDFObject { + static convert(object, encryptFn = null) { + // String literals are converted to the PDF name type + if (typeof object === 'string') { + return `/${object}`; + + // String objects are converted to PDF strings (UTF-16) + } else if (object instanceof String) { + let string = object; + // Detect if this is a unicode string + let isUnicode = false; + for (let i = 0, end = string.length; i < end; i++) { + if (string.charCodeAt(i) > 0x7f) { + isUnicode = true; + break; + } + } + + // If so, encode it as big endian UTF-16 + let stringBuffer; + if (isUnicode) { + stringBuffer = swapBytes(Buffer.from(`\ufeff${string}`, 'utf16le')); + } else { + stringBuffer = Buffer.from(string.valueOf(), 'ascii'); + } + + // Encrypt the string when necessary + if (encryptFn) { + string = encryptFn(stringBuffer).toString('binary'); + } else { + string = stringBuffer.toString('binary'); + } + + // Escape characters as required by the spec + string = string.replace(escapableRe, c => escapable[c]); + + return `(${string})`; + + // Buffers are converted to PDF hex strings + } else if (isBuffer(object)) { + return `<${object.toString('hex')}>`; + } else if (object instanceof PDFAbstractReference || object instanceof PDFNameTree) { + return object.toString(); + } else if (object instanceof Date) { + let string = + `D:${pad(object.getUTCFullYear(), 4)}` + + pad(object.getUTCMonth() + 1, 2) + + pad(object.getUTCDate(), 2) + + pad(object.getUTCHours(), 2) + + pad(object.getUTCMinutes(), 2) + + pad(object.getUTCSeconds(), 2) + + 'Z'; + + // Encrypt the string when necessary + if (encryptFn) { + string = encryptFn(new Buffer(string, 'ascii')).toString('binary'); + + // Escape characters as required by the spec + string = string.replace(escapableRe, c => escapable[c]); + } + + return `(${string})`; + } else if (Array.isArray(object)) { + const items = object.map(e => PDFObject.convert(e, encryptFn)).join(' '); + return `[${items}]`; + } else if ({}.toString.call(object) === '[object Object]') { + const out = ['<<']; + for (let key in object) { + const val = object[key]; + out.push(`/${key} ${PDFObject.convert(val, encryptFn)}`); + } + + out.push('>>'); + return out.join('\n'); + } else if (typeof object === 'number') { + return PDFObject.number(object); + } else { + return `${object}`; + } + } + + static number(n) { + if (n > -1e21 && n < 1e21) { + return Math.round(n * 1e6) / 1e6; + } + + throw new Error(`unsupported number: ${n}`); + } + } - const escapableRe = /[\n\r\t\b\f\(\)\\]/g; - const escapable = { - '\n': '\\n', - '\r': '\\r', - '\t': '\\t', - '\b': '\\b', - '\f': '\\f', - '\\': '\\\\', - '(': '\\(', - ')': '\\)' - }; + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js - // Convert little endian UTF-16 to big endian - const swapBytes = function(buff) { - const l = buff.length; - if (l & 0x01) { - throw new Error('Buffer length must be even'); - } else { - for (let i = 0, end = l - 1; i < end; i += 2) { - const a = buff[i]; - buff[i] = buff[i + 1]; - buff[i + 1] = a; + function defaultSetTimout$1() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout$1 () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout$1 = defaultSetTimout$1; + var cachedClearTimeout$1 = defaultClearTimeout$1; + if (typeof global$1$1.setTimeout === 'function') { + cachedSetTimeout$1 = setTimeout; + } + if (typeof global$1$1.clearTimeout === 'function') { + cachedClearTimeout$1 = clearTimeout; + } + + function runTimeout$1(fun) { + if (cachedSetTimeout$1 === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); } - } - - return buff; - }; - - class PDFObject { - static convert(object, encryptFn = null) { - // String literals are converted to the PDF name type - if (typeof object === 'string') { - return `/${object}`; - - // String objects are converted to PDF strings (UTF-16) - } else if (object instanceof String) { - let string = object; - // Detect if this is a unicode string - let isUnicode = false; - for (let i = 0, end = string.length; i < end; i++) { - if (string.charCodeAt(i) > 0x7f) { - isUnicode = true; - break; + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout$1 === defaultSetTimout$1 || !cachedSetTimeout$1) && setTimeout) { + cachedSetTimeout$1 = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout$1(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout$1.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout$1.call(this, fun, 0); } - } - - // If so, encode it as big endian UTF-16 - let stringBuffer; - if (isUnicode) { - stringBuffer = swapBytes(Buffer.from(`\ufeff${string}`, 'utf16le')); - } else { - stringBuffer = Buffer.from(string.valueOf(), 'ascii'); - } - - // Encrypt the string when necessary - if (encryptFn) { - string = encryptFn(stringBuffer).toString('binary'); - } else { - string = stringBuffer.toString('binary'); - } - - // Escape characters as required by the spec - string = string.replace(escapableRe, c => escapable[c]); - - return `(${string})`; - - // Buffers are converted to PDF hex strings - } else if (isBuffer(object)) { - return `<${object.toString('hex')}>`; - } else if (object instanceof PDFAbstractReference || object instanceof PDFNameTree) { - return object.toString(); - } else if (object instanceof Date) { - let string = - `D:${pad(object.getUTCFullYear(), 4)}` + - pad(object.getUTCMonth() + 1, 2) + - pad(object.getUTCDate(), 2) + - pad(object.getUTCHours(), 2) + - pad(object.getUTCMinutes(), 2) + - pad(object.getUTCSeconds(), 2) + - 'Z'; - - // Encrypt the string when necessary - if (encryptFn) { - string = encryptFn(new Buffer(string, 'ascii')).toString('binary'); - - // Escape characters as required by the spec - string = string.replace(escapableRe, c => escapable[c]); - } - - return `(${string})`; - } else if (Array.isArray(object)) { - const items = object.map(e => PDFObject.convert(e, encryptFn)).join(' '); - return `[${items}]`; - } else if ({}.toString.call(object) === '[object Object]') { - const out = ['<<']; - for (let key in object) { - const val = object[key]; - out.push(`/${key} ${PDFObject.convert(val, encryptFn)}`); - } - - out.push('>>'); - return out.join('\n'); - } else if (typeof object === 'number') { - return PDFObject.number(object); - } else { - return `${object}`; - } - } - - static number(n) { - if (n > -1e21 && n < 1e21) { - return Math.round(n * 1e6) / 1e6; } - throw new Error(`unsupported number: ${n}`); - } + } + function runClearTimeout$1(marker) { + if (cachedClearTimeout$1 === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout$1 === defaultClearTimeout$1 || !cachedClearTimeout$1) && clearTimeout) { + cachedClearTimeout$1 = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout$1(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout$1.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout$1.call(this, marker); + } + } + + + + } + var queue$1 = []; + var draining$1 = false; + var currentQueue$1; + var queueIndex$1 = -1; + + function cleanUpNextTick$1() { + if (!draining$1 || !currentQueue$1) { + return; + } + draining$1 = false; + if (currentQueue$1.length) { + queue$1 = currentQueue$1.concat(queue$1); + } else { + queueIndex$1 = -1; + } + if (queue$1.length) { + drainQueue$1(); + } + } + + function drainQueue$1() { + if (draining$1) { + return; + } + var timeout = runTimeout$1(cleanUpNextTick$1); + draining$1 = true; + + var len = queue$1.length; + while(len) { + currentQueue$1 = queue$1; + queue$1 = []; + while (++queueIndex$1 < len) { + if (currentQueue$1) { + currentQueue$1[queueIndex$1].run(); + } + } + queueIndex$1 = -1; + len = queue$1.length; + } + currentQueue$1 = null; + draining$1 = false; + runClearTimeout$1(timeout); + } + function nextTick$1(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue$1.push(new Item$1(fun, args)); + if (queue$1.length === 1 && !draining$1) { + runTimeout$1(drainQueue$1); + } + } + // v8 likes predictible objects + function Item$1(fun, array) { + this.fun = fun; + this.array = array; + } + Item$1.prototype.run = function () { + this.fun.apply(null, this.array); + }; + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance$1 = global$1$1.performance || {}; + var performanceNow$1 = + performance$1.now || + performance$1.mozNow || + performance$1.msNow || + performance$1.oNow || + performance$1.webkitNow || + function(){ return (new Date()).getTime() }; var msg = { 2: 'need dictionary', /* Z_NEED_DICT 2 */ @@ -11044,7 +12948,7 @@ this.write_in_progress = true; var self = this; - nextTick(function() { + nextTick$1(function() { self.write_in_progress = false; var res = self._write(flush, input, in_off, in_len, out, out_off, out_len); self.callback(res[0], res[1]); @@ -11588,7 +13492,7 @@ } }); } else { - nextTick(callback); + nextTick$1(callback); } }; @@ -11612,7 +13516,7 @@ if (ws.ended) { if (callback) - nextTick(callback); + nextTick$1(callback); } else if (ws.ending) { if (callback) this.once('end', callback); @@ -11629,7 +13533,7 @@ Zlib$1.prototype.close = function(callback) { if (callback) - nextTick(callback); + nextTick$1(callback); if (this._closed) return; @@ -11639,7 +13543,7 @@ this._binding.close(); var self = this; - nextTick(function() { + nextTick$1(function() { self.emit('close'); }); }; @@ -11817,228 +13721,228 @@ Zlib: Zlib$1 }; - class PDFReference extends PDFAbstractReference { - constructor(document, id, data = {}) { - super(); - this.document = document; - this.id = id; - this.data = data; - this.gen = 0; - this.compress = this.document.compress && !this.data.Filter; - this.uncompressedLength = 0; - this.buffer = []; - } - - write(chunk) { - if (!isBuffer(chunk)) { - chunk = new Buffer(chunk + '\n', 'binary'); - } - - this.uncompressedLength += chunk.length; - if (this.data.Length == null) { - this.data.Length = 0; - } - this.buffer.push(chunk); - this.data.Length += chunk.length; - if (this.compress) { - return (this.data.Filter = 'FlateDecode'); - } - } - - end(chunk) { - if (chunk) { - this.write(chunk); - } - return this.finalize(); - } - - finalize() { - this.offset = this.document._offset; - - const encryptFn = this.document._security - ? this.document._security.getEncryptFn(this.id, this.gen) - : null; - - if (this.buffer.length) { - this.buffer = Buffer.concat(this.buffer); - if (this.compress) { - this.buffer = zlib.deflateSync(this.buffer); - } - - if (encryptFn) { - this.buffer = encryptFn(this.buffer); - } - - this.data.Length = this.buffer.length; - } - - this.document._write(`${this.id} ${this.gen} obj`); - this.document._write(PDFObject.convert(this.data, encryptFn)); - - if (this.buffer.length) { - this.document._write('stream'); - this.document._write(this.buffer); - - this.buffer = []; // free up memory - this.document._write('\nendstream'); - } - - this.document._write('endobj'); - this.document._refEnd(this); - } - toString() { - return `${this.id} ${this.gen} R`; - } + class PDFReference extends PDFAbstractReference { + constructor(document, id, data = {}) { + super(); + this.document = document; + this.id = id; + this.data = data; + this.gen = 0; + this.compress = this.document.compress && !this.data.Filter; + this.uncompressedLength = 0; + this.buffer = []; + } + + write(chunk) { + if (!isBuffer(chunk)) { + chunk = new Buffer(chunk + '\n', 'binary'); + } + + this.uncompressedLength += chunk.length; + if (this.data.Length == null) { + this.data.Length = 0; + } + this.buffer.push(chunk); + this.data.Length += chunk.length; + if (this.compress) { + return (this.data.Filter = 'FlateDecode'); + } + } + + end(chunk) { + if (chunk) { + this.write(chunk); + } + return this.finalize(); + } + + finalize() { + this.offset = this.document._offset; + + const encryptFn = this.document._security + ? this.document._security.getEncryptFn(this.id, this.gen) + : null; + + if (this.buffer.length) { + this.buffer = Buffer.concat(this.buffer); + if (this.compress) { + this.buffer = zlib.deflateSync(this.buffer); + } + + if (encryptFn) { + this.buffer = encryptFn(this.buffer); + } + + this.data.Length = this.buffer.length; + } + + this.document._write(`${this.id} ${this.gen} obj`); + this.document._write(PDFObject.convert(this.data, encryptFn)); + + if (this.buffer.length) { + this.document._write('stream'); + this.document._write(this.buffer); + + this.buffer = []; // free up memory + this.document._write('\nendstream'); + } + + this.document._write('endobj'); + this.document._refEnd(this); + } + toString() { + return `${this.id} ${this.gen} R`; + } } - /* - PDFPage - represents a single page in the PDF document - By Devon Govett - */ - - const DEFAULT_MARGINS = { - top: 72, - left: 72, - bottom: 72, - right: 72 - }; - - const SIZES = { - '4A0': [4767.87, 6740.79], - '2A0': [3370.39, 4767.87], - A0: [2383.94, 3370.39], - A1: [1683.78, 2383.94], - A2: [1190.55, 1683.78], - A3: [841.89, 1190.55], - A4: [595.28, 841.89], - A5: [419.53, 595.28], - A6: [297.64, 419.53], - A7: [209.76, 297.64], - A8: [147.4, 209.76], - A9: [104.88, 147.4], - A10: [73.7, 104.88], - B0: [2834.65, 4008.19], - B1: [2004.09, 2834.65], - B2: [1417.32, 2004.09], - B3: [1000.63, 1417.32], - B4: [708.66, 1000.63], - B5: [498.9, 708.66], - B6: [354.33, 498.9], - B7: [249.45, 354.33], - B8: [175.75, 249.45], - B9: [124.72, 175.75], - B10: [87.87, 124.72], - C0: [2599.37, 3676.54], - C1: [1836.85, 2599.37], - C2: [1298.27, 1836.85], - C3: [918.43, 1298.27], - C4: [649.13, 918.43], - C5: [459.21, 649.13], - C6: [323.15, 459.21], - C7: [229.61, 323.15], - C8: [161.57, 229.61], - C9: [113.39, 161.57], - C10: [79.37, 113.39], - RA0: [2437.8, 3458.27], - RA1: [1729.13, 2437.8], - RA2: [1218.9, 1729.13], - RA3: [864.57, 1218.9], - RA4: [609.45, 864.57], - SRA0: [2551.18, 3628.35], - SRA1: [1814.17, 2551.18], - SRA2: [1275.59, 1814.17], - SRA3: [907.09, 1275.59], - SRA4: [637.8, 907.09], - EXECUTIVE: [521.86, 756.0], - FOLIO: [612.0, 936.0], - LEGAL: [612.0, 1008.0], - LETTER: [612.0, 792.0], - TABLOID: [792.0, 1224.0] - }; - - class PDFPage { - constructor(document, options = {}) { - this.document = document; - this.size = options.size || 'letter'; - this.layout = options.layout || 'portrait'; - - // process margins - if (typeof options.margin === 'number') { - this.margins = { - top: options.margin, - left: options.margin, - bottom: options.margin, - right: options.margin - }; - - // default to 1 inch margins - } else { - this.margins = options.margins || DEFAULT_MARGINS; - } - - // calculate page dimensions - const dimensions = Array.isArray(this.size) - ? this.size - : SIZES[this.size.toUpperCase()]; - this.width = dimensions[this.layout === 'portrait' ? 0 : 1]; - this.height = dimensions[this.layout === 'portrait' ? 1 : 0]; - - this.content = this.document.ref(); - - // Initialize the Font, XObject, and ExtGState dictionaries - this.resources = this.document.ref({ - ProcSet: ['PDF', 'Text', 'ImageB', 'ImageC', 'ImageI'] - }); - - // The page dictionary - this.dictionary = this.document.ref({ - Type: 'Page', - Parent: this.document._root.data.Pages, - MediaBox: [0, 0, this.width, this.height], - Contents: this.content, - Resources: this.resources - }); - } - - // Lazily create these dictionaries - get fonts() { - const data = this.resources.data; - return data.Font != null ? data.Font : (data.Font = {}); - } - - get xobjects() { - const data = this.resources.data; - return data.XObject != null ? data.XObject : (data.XObject = {}); - } - - get ext_gstates() { - const data = this.resources.data; - return data.ExtGState != null ? data.ExtGState : (data.ExtGState = {}); - } - - get patterns() { - const data = this.resources.data; - return data.Pattern != null ? data.Pattern : (data.Pattern = {}); - } - - get annotations() { - const data = this.dictionary.data; - return data.Annots != null ? data.Annots : (data.Annots = []); - } - - maxY() { - return this.height - this.margins.bottom; - } - - write(chunk) { - return this.content.write(chunk); - } - - end() { - this.dictionary.end(); - this.resources.end(); - return this.content.end(); - } + /* + PDFPage - represents a single page in the PDF document + By Devon Govett + */ + + const DEFAULT_MARGINS = { + top: 72, + left: 72, + bottom: 72, + right: 72 + }; + + const SIZES = { + '4A0': [4767.87, 6740.79], + '2A0': [3370.39, 4767.87], + A0: [2383.94, 3370.39], + A1: [1683.78, 2383.94], + A2: [1190.55, 1683.78], + A3: [841.89, 1190.55], + A4: [595.28, 841.89], + A5: [419.53, 595.28], + A6: [297.64, 419.53], + A7: [209.76, 297.64], + A8: [147.4, 209.76], + A9: [104.88, 147.4], + A10: [73.7, 104.88], + B0: [2834.65, 4008.19], + B1: [2004.09, 2834.65], + B2: [1417.32, 2004.09], + B3: [1000.63, 1417.32], + B4: [708.66, 1000.63], + B5: [498.9, 708.66], + B6: [354.33, 498.9], + B7: [249.45, 354.33], + B8: [175.75, 249.45], + B9: [124.72, 175.75], + B10: [87.87, 124.72], + C0: [2599.37, 3676.54], + C1: [1836.85, 2599.37], + C2: [1298.27, 1836.85], + C3: [918.43, 1298.27], + C4: [649.13, 918.43], + C5: [459.21, 649.13], + C6: [323.15, 459.21], + C7: [229.61, 323.15], + C8: [161.57, 229.61], + C9: [113.39, 161.57], + C10: [79.37, 113.39], + RA0: [2437.8, 3458.27], + RA1: [1729.13, 2437.8], + RA2: [1218.9, 1729.13], + RA3: [864.57, 1218.9], + RA4: [609.45, 864.57], + SRA0: [2551.18, 3628.35], + SRA1: [1814.17, 2551.18], + SRA2: [1275.59, 1814.17], + SRA3: [907.09, 1275.59], + SRA4: [637.8, 907.09], + EXECUTIVE: [521.86, 756.0], + FOLIO: [612.0, 936.0], + LEGAL: [612.0, 1008.0], + LETTER: [612.0, 792.0], + TABLOID: [792.0, 1224.0] + }; + + class PDFPage { + constructor(document, options = {}) { + this.document = document; + this.size = options.size || 'letter'; + this.layout = options.layout || 'portrait'; + + // process margins + if (typeof options.margin === 'number') { + this.margins = { + top: options.margin, + left: options.margin, + bottom: options.margin, + right: options.margin + }; + + // default to 1 inch margins + } else { + this.margins = options.margins || DEFAULT_MARGINS; + } + + // calculate page dimensions + const dimensions = Array.isArray(this.size) + ? this.size + : SIZES[this.size.toUpperCase()]; + this.width = dimensions[this.layout === 'portrait' ? 0 : 1]; + this.height = dimensions[this.layout === 'portrait' ? 1 : 0]; + + this.content = this.document.ref(); + + // Initialize the Font, XObject, and ExtGState dictionaries + this.resources = this.document.ref({ + ProcSet: ['PDF', 'Text', 'ImageB', 'ImageC', 'ImageI'] + }); + + // The page dictionary + this.dictionary = this.document.ref({ + Type: 'Page', + Parent: this.document._root.data.Pages, + MediaBox: [0, 0, this.width, this.height], + Contents: this.content, + Resources: this.resources + }); + } + + // Lazily create these dictionaries + get fonts() { + const data = this.resources.data; + return data.Font != null ? data.Font : (data.Font = {}); + } + + get xobjects() { + const data = this.resources.data; + return data.XObject != null ? data.XObject : (data.XObject = {}); + } + + get ext_gstates() { + const data = this.resources.data; + return data.ExtGState != null ? data.ExtGState : (data.ExtGState = {}); + } + + get patterns() { + const data = this.resources.data; + return data.Pattern != null ? data.Pattern : (data.Pattern = {}); + } + + get annotations() { + const data = this.dictionary.data; + return data.Annots != null ? data.Annots : (data.Annots = []); + } + + maxY() { + return this.height - this.margins.bottom; + } + + write(chunk) { + return this.content.write(chunk); + } + + end() { + this.dictionary.end(); + this.resources.end(); + return this.content.end(); + } } var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global$1 !== 'undefined' ? global$1 : typeof self !== 'undefined' ? self : {}; @@ -18440,7 +20344,7 @@ })); }); - var cryptoJs = createCommonjsModule(function (module, exports) { + var C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs = createCommonjsModule(function (module, exports) { (function (root, factory, undef) { { // CommonJS @@ -18453,4057 +20357,4671 @@ })); }); - /** - * Check if value is in a range group. - * @param {number} value - * @param {number[]} rangeGroup - * @returns {boolean} - */ - function inRange(value, rangeGroup) { - if (value < rangeGroup[0]) return false; - let startRange = 0; - let endRange = rangeGroup.length / 2; - while (startRange <= endRange) { - const middleRange = Math.floor((startRange + endRange) / 2); - - // actual array index - const arrayIndex = middleRange * 2; - - // Check if value is in range pointed by actual index - if ( - value >= rangeGroup[arrayIndex] && - value <= rangeGroup[arrayIndex + 1] - ) { - return true; - } - - if (value > rangeGroup[arrayIndex + 1]) { - // Search Right Side Of Array - startRange = middleRange + 1; - } else { - // Search Left Side Of Array - endRange = middleRange - 1; - } - } - return false; + /** + * Check if value is in a range group. + * @param {number} value + * @param {number[]} rangeGroup + * @returns {boolean} + */ + function inRange(value, rangeGroup) { + if (value < rangeGroup[0]) return false; + let startRange = 0; + let endRange = rangeGroup.length / 2; + while (startRange <= endRange) { + const middleRange = Math.floor((startRange + endRange) / 2); + + // actual array index + const arrayIndex = middleRange * 2; + + // Check if value is in range pointed by actual index + if ( + value >= rangeGroup[arrayIndex] && + value <= rangeGroup[arrayIndex + 1] + ) { + return true; + } + + if (value > rangeGroup[arrayIndex + 1]) { + // Search Right Side Of Array + startRange = middleRange + 1; + } else { + // Search Left Side Of Array + endRange = middleRange - 1; + } + } + return false; } - /* eslint-disable prettier/prettier */ - /** - * A.1 Unassigned code points in Unicode 3.2 - * @link https://tools.ietf.org/html/rfc3454#appendix-A.1 - */ - const unassigned_code_points = [ - 0x0221, - 0x0221, - 0x0234, - 0x024f, - 0x02ae, - 0x02af, - 0x02ef, - 0x02ff, - 0x0350, - 0x035f, - 0x0370, - 0x0373, - 0x0376, - 0x0379, - 0x037b, - 0x037d, - 0x037f, - 0x0383, - 0x038b, - 0x038b, - 0x038d, - 0x038d, - 0x03a2, - 0x03a2, - 0x03cf, - 0x03cf, - 0x03f7, - 0x03ff, - 0x0487, - 0x0487, - 0x04cf, - 0x04cf, - 0x04f6, - 0x04f7, - 0x04fa, - 0x04ff, - 0x0510, - 0x0530, - 0x0557, - 0x0558, - 0x0560, - 0x0560, - 0x0588, - 0x0588, - 0x058b, - 0x0590, - 0x05a2, - 0x05a2, - 0x05ba, - 0x05ba, - 0x05c5, - 0x05cf, - 0x05eb, - 0x05ef, - 0x05f5, - 0x060b, - 0x060d, - 0x061a, - 0x061c, - 0x061e, - 0x0620, - 0x0620, - 0x063b, - 0x063f, - 0x0656, - 0x065f, - 0x06ee, - 0x06ef, - 0x06ff, - 0x06ff, - 0x070e, - 0x070e, - 0x072d, - 0x072f, - 0x074b, - 0x077f, - 0x07b2, - 0x0900, - 0x0904, - 0x0904, - 0x093a, - 0x093b, - 0x094e, - 0x094f, - 0x0955, - 0x0957, - 0x0971, - 0x0980, - 0x0984, - 0x0984, - 0x098d, - 0x098e, - 0x0991, - 0x0992, - 0x09a9, - 0x09a9, - 0x09b1, - 0x09b1, - 0x09b3, - 0x09b5, - 0x09ba, - 0x09bb, - 0x09bd, - 0x09bd, - 0x09c5, - 0x09c6, - 0x09c9, - 0x09ca, - 0x09ce, - 0x09d6, - 0x09d8, - 0x09db, - 0x09de, - 0x09de, - 0x09e4, - 0x09e5, - 0x09fb, - 0x0a01, - 0x0a03, - 0x0a04, - 0x0a0b, - 0x0a0e, - 0x0a11, - 0x0a12, - 0x0a29, - 0x0a29, - 0x0a31, - 0x0a31, - 0x0a34, - 0x0a34, - 0x0a37, - 0x0a37, - 0x0a3a, - 0x0a3b, - 0x0a3d, - 0x0a3d, - 0x0a43, - 0x0a46, - 0x0a49, - 0x0a4a, - 0x0a4e, - 0x0a58, - 0x0a5d, - 0x0a5d, - 0x0a5f, - 0x0a65, - 0x0a75, - 0x0a80, - 0x0a84, - 0x0a84, - 0x0a8c, - 0x0a8c, - 0x0a8e, - 0x0a8e, - 0x0a92, - 0x0a92, - 0x0aa9, - 0x0aa9, - 0x0ab1, - 0x0ab1, - 0x0ab4, - 0x0ab4, - 0x0aba, - 0x0abb, - 0x0ac6, - 0x0ac6, - 0x0aca, - 0x0aca, - 0x0ace, - 0x0acf, - 0x0ad1, - 0x0adf, - 0x0ae1, - 0x0ae5, - 0x0af0, - 0x0b00, - 0x0b04, - 0x0b04, - 0x0b0d, - 0x0b0e, - 0x0b11, - 0x0b12, - 0x0b29, - 0x0b29, - 0x0b31, - 0x0b31, - 0x0b34, - 0x0b35, - 0x0b3a, - 0x0b3b, - 0x0b44, - 0x0b46, - 0x0b49, - 0x0b4a, - 0x0b4e, - 0x0b55, - 0x0b58, - 0x0b5b, - 0x0b5e, - 0x0b5e, - 0x0b62, - 0x0b65, - 0x0b71, - 0x0b81, - 0x0b84, - 0x0b84, - 0x0b8b, - 0x0b8d, - 0x0b91, - 0x0b91, - 0x0b96, - 0x0b98, - 0x0b9b, - 0x0b9b, - 0x0b9d, - 0x0b9d, - 0x0ba0, - 0x0ba2, - 0x0ba5, - 0x0ba7, - 0x0bab, - 0x0bad, - 0x0bb6, - 0x0bb6, - 0x0bba, - 0x0bbd, - 0x0bc3, - 0x0bc5, - 0x0bc9, - 0x0bc9, - 0x0bce, - 0x0bd6, - 0x0bd8, - 0x0be6, - 0x0bf3, - 0x0c00, - 0x0c04, - 0x0c04, - 0x0c0d, - 0x0c0d, - 0x0c11, - 0x0c11, - 0x0c29, - 0x0c29, - 0x0c34, - 0x0c34, - 0x0c3a, - 0x0c3d, - 0x0c45, - 0x0c45, - 0x0c49, - 0x0c49, - 0x0c4e, - 0x0c54, - 0x0c57, - 0x0c5f, - 0x0c62, - 0x0c65, - 0x0c70, - 0x0c81, - 0x0c84, - 0x0c84, - 0x0c8d, - 0x0c8d, - 0x0c91, - 0x0c91, - 0x0ca9, - 0x0ca9, - 0x0cb4, - 0x0cb4, - 0x0cba, - 0x0cbd, - 0x0cc5, - 0x0cc5, - 0x0cc9, - 0x0cc9, - 0x0cce, - 0x0cd4, - 0x0cd7, - 0x0cdd, - 0x0cdf, - 0x0cdf, - 0x0ce2, - 0x0ce5, - 0x0cf0, - 0x0d01, - 0x0d04, - 0x0d04, - 0x0d0d, - 0x0d0d, - 0x0d11, - 0x0d11, - 0x0d29, - 0x0d29, - 0x0d3a, - 0x0d3d, - 0x0d44, - 0x0d45, - 0x0d49, - 0x0d49, - 0x0d4e, - 0x0d56, - 0x0d58, - 0x0d5f, - 0x0d62, - 0x0d65, - 0x0d70, - 0x0d81, - 0x0d84, - 0x0d84, - 0x0d97, - 0x0d99, - 0x0db2, - 0x0db2, - 0x0dbc, - 0x0dbc, - 0x0dbe, - 0x0dbf, - 0x0dc7, - 0x0dc9, - 0x0dcb, - 0x0dce, - 0x0dd5, - 0x0dd5, - 0x0dd7, - 0x0dd7, - 0x0de0, - 0x0df1, - 0x0df5, - 0x0e00, - 0x0e3b, - 0x0e3e, - 0x0e5c, - 0x0e80, - 0x0e83, - 0x0e83, - 0x0e85, - 0x0e86, - 0x0e89, - 0x0e89, - 0x0e8b, - 0x0e8c, - 0x0e8e, - 0x0e93, - 0x0e98, - 0x0e98, - 0x0ea0, - 0x0ea0, - 0x0ea4, - 0x0ea4, - 0x0ea6, - 0x0ea6, - 0x0ea8, - 0x0ea9, - 0x0eac, - 0x0eac, - 0x0eba, - 0x0eba, - 0x0ebe, - 0x0ebf, - 0x0ec5, - 0x0ec5, - 0x0ec7, - 0x0ec7, - 0x0ece, - 0x0ecf, - 0x0eda, - 0x0edb, - 0x0ede, - 0x0eff, - 0x0f48, - 0x0f48, - 0x0f6b, - 0x0f70, - 0x0f8c, - 0x0f8f, - 0x0f98, - 0x0f98, - 0x0fbd, - 0x0fbd, - 0x0fcd, - 0x0fce, - 0x0fd0, - 0x0fff, - 0x1022, - 0x1022, - 0x1028, - 0x1028, - 0x102b, - 0x102b, - 0x1033, - 0x1035, - 0x103a, - 0x103f, - 0x105a, - 0x109f, - 0x10c6, - 0x10cf, - 0x10f9, - 0x10fa, - 0x10fc, - 0x10ff, - 0x115a, - 0x115e, - 0x11a3, - 0x11a7, - 0x11fa, - 0x11ff, - 0x1207, - 0x1207, - 0x1247, - 0x1247, - 0x1249, - 0x1249, - 0x124e, - 0x124f, - 0x1257, - 0x1257, - 0x1259, - 0x1259, - 0x125e, - 0x125f, - 0x1287, - 0x1287, - 0x1289, - 0x1289, - 0x128e, - 0x128f, - 0x12af, - 0x12af, - 0x12b1, - 0x12b1, - 0x12b6, - 0x12b7, - 0x12bf, - 0x12bf, - 0x12c1, - 0x12c1, - 0x12c6, - 0x12c7, - 0x12cf, - 0x12cf, - 0x12d7, - 0x12d7, - 0x12ef, - 0x12ef, - 0x130f, - 0x130f, - 0x1311, - 0x1311, - 0x1316, - 0x1317, - 0x131f, - 0x131f, - 0x1347, - 0x1347, - 0x135b, - 0x1360, - 0x137d, - 0x139f, - 0x13f5, - 0x1400, - 0x1677, - 0x167f, - 0x169d, - 0x169f, - 0x16f1, - 0x16ff, - 0x170d, - 0x170d, - 0x1715, - 0x171f, - 0x1737, - 0x173f, - 0x1754, - 0x175f, - 0x176d, - 0x176d, - 0x1771, - 0x1771, - 0x1774, - 0x177f, - 0x17dd, - 0x17df, - 0x17ea, - 0x17ff, - 0x180f, - 0x180f, - 0x181a, - 0x181f, - 0x1878, - 0x187f, - 0x18aa, - 0x1dff, - 0x1e9c, - 0x1e9f, - 0x1efa, - 0x1eff, - 0x1f16, - 0x1f17, - 0x1f1e, - 0x1f1f, - 0x1f46, - 0x1f47, - 0x1f4e, - 0x1f4f, - 0x1f58, - 0x1f58, - 0x1f5a, - 0x1f5a, - 0x1f5c, - 0x1f5c, - 0x1f5e, - 0x1f5e, - 0x1f7e, - 0x1f7f, - 0x1fb5, - 0x1fb5, - 0x1fc5, - 0x1fc5, - 0x1fd4, - 0x1fd5, - 0x1fdc, - 0x1fdc, - 0x1ff0, - 0x1ff1, - 0x1ff5, - 0x1ff5, - 0x1fff, - 0x1fff, - 0x2053, - 0x2056, - 0x2058, - 0x205e, - 0x2064, - 0x2069, - 0x2072, - 0x2073, - 0x208f, - 0x209f, - 0x20b2, - 0x20cf, - 0x20eb, - 0x20ff, - 0x213b, - 0x213c, - 0x214c, - 0x2152, - 0x2184, - 0x218f, - 0x23cf, - 0x23ff, - 0x2427, - 0x243f, - 0x244b, - 0x245f, - 0x24ff, - 0x24ff, - 0x2614, - 0x2615, - 0x2618, - 0x2618, - 0x267e, - 0x267f, - 0x268a, - 0x2700, - 0x2705, - 0x2705, - 0x270a, - 0x270b, - 0x2728, - 0x2728, - 0x274c, - 0x274c, - 0x274e, - 0x274e, - 0x2753, - 0x2755, - 0x2757, - 0x2757, - 0x275f, - 0x2760, - 0x2795, - 0x2797, - 0x27b0, - 0x27b0, - 0x27bf, - 0x27cf, - 0x27ec, - 0x27ef, - 0x2b00, - 0x2e7f, - 0x2e9a, - 0x2e9a, - 0x2ef4, - 0x2eff, - 0x2fd6, - 0x2fef, - 0x2ffc, - 0x2fff, - 0x3040, - 0x3040, - 0x3097, - 0x3098, - 0x3100, - 0x3104, - 0x312d, - 0x3130, - 0x318f, - 0x318f, - 0x31b8, - 0x31ef, - 0x321d, - 0x321f, - 0x3244, - 0x3250, - 0x327c, - 0x327e, - 0x32cc, - 0x32cf, - 0x32ff, - 0x32ff, - 0x3377, - 0x337a, - 0x33de, - 0x33df, - 0x33ff, - 0x33ff, - 0x4db6, - 0x4dff, - 0x9fa6, - 0x9fff, - 0xa48d, - 0xa48f, - 0xa4c7, - 0xabff, - 0xd7a4, - 0xd7ff, - 0xfa2e, - 0xfa2f, - 0xfa6b, - 0xfaff, - 0xfb07, - 0xfb12, - 0xfb18, - 0xfb1c, - 0xfb37, - 0xfb37, - 0xfb3d, - 0xfb3d, - 0xfb3f, - 0xfb3f, - 0xfb42, - 0xfb42, - 0xfb45, - 0xfb45, - 0xfbb2, - 0xfbd2, - 0xfd40, - 0xfd4f, - 0xfd90, - 0xfd91, - 0xfdc8, - 0xfdcf, - 0xfdfd, - 0xfdff, - 0xfe10, - 0xfe1f, - 0xfe24, - 0xfe2f, - 0xfe47, - 0xfe48, - 0xfe53, - 0xfe53, - 0xfe67, - 0xfe67, - 0xfe6c, - 0xfe6f, - 0xfe75, - 0xfe75, - 0xfefd, - 0xfefe, - 0xff00, - 0xff00, - 0xffbf, - 0xffc1, - 0xffc8, - 0xffc9, - 0xffd0, - 0xffd1, - 0xffd8, - 0xffd9, - 0xffdd, - 0xffdf, - 0xffe7, - 0xffe7, - 0xffef, - 0xfff8, - 0x10000, - 0x102ff, - 0x1031f, - 0x1031f, - 0x10324, - 0x1032f, - 0x1034b, - 0x103ff, - 0x10426, - 0x10427, - 0x1044e, - 0x1cfff, - 0x1d0f6, - 0x1d0ff, - 0x1d127, - 0x1d129, - 0x1d1de, - 0x1d3ff, - 0x1d455, - 0x1d455, - 0x1d49d, - 0x1d49d, - 0x1d4a0, - 0x1d4a1, - 0x1d4a3, - 0x1d4a4, - 0x1d4a7, - 0x1d4a8, - 0x1d4ad, - 0x1d4ad, - 0x1d4ba, - 0x1d4ba, - 0x1d4bc, - 0x1d4bc, - 0x1d4c1, - 0x1d4c1, - 0x1d4c4, - 0x1d4c4, - 0x1d506, - 0x1d506, - 0x1d50b, - 0x1d50c, - 0x1d515, - 0x1d515, - 0x1d51d, - 0x1d51d, - 0x1d53a, - 0x1d53a, - 0x1d53f, - 0x1d53f, - 0x1d545, - 0x1d545, - 0x1d547, - 0x1d549, - 0x1d551, - 0x1d551, - 0x1d6a4, - 0x1d6a7, - 0x1d7ca, - 0x1d7cd, - 0x1d800, - 0x1fffd, - 0x2a6d7, - 0x2f7ff, - 0x2fa1e, - 0x2fffd, - 0x30000, - 0x3fffd, - 0x40000, - 0x4fffd, - 0x50000, - 0x5fffd, - 0x60000, - 0x6fffd, - 0x70000, - 0x7fffd, - 0x80000, - 0x8fffd, - 0x90000, - 0x9fffd, - 0xa0000, - 0xafffd, - 0xb0000, - 0xbfffd, - 0xc0000, - 0xcfffd, - 0xd0000, - 0xdfffd, - 0xe0000, - 0xe0000, - 0xe0002, - 0xe001f, - 0xe0080, - 0xefffd - ]; - /* eslint-enable */ - - const isUnassignedCodePoint = character => - inRange(character, unassigned_code_points); - - /* eslint-disable prettier/prettier */ - /** - * B.1 Commonly mapped to nothing - * @link https://tools.ietf.org/html/rfc3454#appendix-B.1 - */ - const commonly_mapped_to_nothing = [ - 0x00ad, - 0x00ad, - 0x034f, - 0x034f, - 0x1806, - 0x1806, - 0x180b, - 0x180b, - 0x180c, - 0x180c, - 0x180d, - 0x180d, - 0x200b, - 0x200b, - 0x200c, - 0x200c, - 0x200d, - 0x200d, - 0x2060, - 0x2060, - 0xfe00, - 0xfe00, - 0xfe01, - 0xfe01, - 0xfe02, - 0xfe02, - 0xfe03, - 0xfe03, - 0xfe04, - 0xfe04, - 0xfe05, - 0xfe05, - 0xfe06, - 0xfe06, - 0xfe07, - 0xfe07, - 0xfe08, - 0xfe08, - 0xfe09, - 0xfe09, - 0xfe0a, - 0xfe0a, - 0xfe0b, - 0xfe0b, - 0xfe0c, - 0xfe0c, - 0xfe0d, - 0xfe0d, - 0xfe0e, - 0xfe0e, - 0xfe0f, - 0xfe0f, - 0xfeff, - 0xfeff - ]; - /* eslint-enable */ - - const isCommonlyMappedToNothing = character => - inRange(character, commonly_mapped_to_nothing); - - /* eslint-disable prettier/prettier */ - /** - * C.1.2 Non-ASCII space characters - * @link https://tools.ietf.org/html/rfc3454#appendix-C.1.2 - */ - const non_ASCII_space_characters = [ - 0x00a0, - 0x00a0 /* NO-BREAK SPACE */, - 0x1680, - 0x1680 /* OGHAM SPACE MARK */, - 0x2000, - 0x2000 /* EN QUAD */, - 0x2001, - 0x2001 /* EM QUAD */, - 0x2002, - 0x2002 /* EN SPACE */, - 0x2003, - 0x2003 /* EM SPACE */, - 0x2004, - 0x2004 /* THREE-PER-EM SPACE */, - 0x2005, - 0x2005 /* FOUR-PER-EM SPACE */, - 0x2006, - 0x2006 /* SIX-PER-EM SPACE */, - 0x2007, - 0x2007 /* FIGURE SPACE */, - 0x2008, - 0x2008 /* PUNCTUATION SPACE */, - 0x2009, - 0x2009 /* THIN SPACE */, - 0x200a, - 0x200a /* HAIR SPACE */, - 0x200b, - 0x200b /* ZERO WIDTH SPACE */, - 0x202f, - 0x202f /* NARROW NO-BREAK SPACE */, - 0x205f, - 0x205f /* MEDIUM MATHEMATICAL SPACE */, - 0x3000, - 0x3000 /* IDEOGRAPHIC SPACE */ - ]; - /* eslint-enable */ - - const isNonASCIISpaceCharacter = character => - inRange(character, non_ASCII_space_characters); - - /* eslint-disable prettier/prettier */ - const non_ASCII_controls_characters = [ - /** - * C.2.2 Non-ASCII control characters - * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.2 - */ - 0x0080, - 0x009f /* [CONTROL CHARACTERS] */, - 0x06dd, - 0x06dd /* ARABIC END OF AYAH */, - 0x070f, - 0x070f /* SYRIAC ABBREVIATION MARK */, - 0x180e, - 0x180e /* MONGOLIAN VOWEL SEPARATOR */, - 0x200c, - 0x200c /* ZERO WIDTH NON-JOINER */, - 0x200d, - 0x200d /* ZERO WIDTH JOINER */, - 0x2028, - 0x2028 /* LINE SEPARATOR */, - 0x2029, - 0x2029 /* PARAGRAPH SEPARATOR */, - 0x2060, - 0x2060 /* WORD JOINER */, - 0x2061, - 0x2061 /* FUNCTION APPLICATION */, - 0x2062, - 0x2062 /* INVISIBLE TIMES */, - 0x2063, - 0x2063 /* INVISIBLE SEPARATOR */, - 0x206a, - 0x206f /* [CONTROL CHARACTERS] */, - 0xfeff, - 0xfeff /* ZERO WIDTH NO-BREAK SPACE */, - 0xfff9, - 0xfffc /* [CONTROL CHARACTERS] */, - 0x1d173, - 0x1d17a /* [MUSICAL CONTROL CHARACTERS] */ - ]; - - const non_character_codepoints = [ - /** - * C.4 Non-character code points - * @link https://tools.ietf.org/html/rfc3454#appendix-C.4 - */ - 0xfdd0, - 0xfdef /* [NONCHARACTER CODE POINTS] */, - 0xfffe, - 0xffff /* [NONCHARACTER CODE POINTS] */, - 0x1fffe, - 0x1ffff /* [NONCHARACTER CODE POINTS] */, - 0x2fffe, - 0x2ffff /* [NONCHARACTER CODE POINTS] */, - 0x3fffe, - 0x3ffff /* [NONCHARACTER CODE POINTS] */, - 0x4fffe, - 0x4ffff /* [NONCHARACTER CODE POINTS] */, - 0x5fffe, - 0x5ffff /* [NONCHARACTER CODE POINTS] */, - 0x6fffe, - 0x6ffff /* [NONCHARACTER CODE POINTS] */, - 0x7fffe, - 0x7ffff /* [NONCHARACTER CODE POINTS] */, - 0x8fffe, - 0x8ffff /* [NONCHARACTER CODE POINTS] */, - 0x9fffe, - 0x9ffff /* [NONCHARACTER CODE POINTS] */, - 0xafffe, - 0xaffff /* [NONCHARACTER CODE POINTS] */, - 0xbfffe, - 0xbffff /* [NONCHARACTER CODE POINTS] */, - 0xcfffe, - 0xcffff /* [NONCHARACTER CODE POINTS] */, - 0xdfffe, - 0xdffff /* [NONCHARACTER CODE POINTS] */, - 0xefffe, - 0xeffff /* [NONCHARACTER CODE POINTS] */, - 0x10fffe, - 0x10ffff /* [NONCHARACTER CODE POINTS] */ - ]; - - /** - * 2.3. Prohibited Output - */ - const prohibited_characters = [ - /** - * C.2.1 ASCII control characters - * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.1 - */ - 0, - 0x001f /* [CONTROL CHARACTERS] */, - 0x007f, - 0x007f /* DELETE */, - - /** - * C.8 Change display properties or are deprecated - * @link https://tools.ietf.org/html/rfc3454#appendix-C.8 - */ - 0x0340, - 0x0340 /* COMBINING GRAVE TONE MARK */, - 0x0341, - 0x0341 /* COMBINING ACUTE TONE MARK */, - 0x200e, - 0x200e /* LEFT-TO-RIGHT MARK */, - 0x200f, - 0x200f /* RIGHT-TO-LEFT MARK */, - 0x202a, - 0x202a /* LEFT-TO-RIGHT EMBEDDING */, - 0x202b, - 0x202b /* RIGHT-TO-LEFT EMBEDDING */, - 0x202c, - 0x202c /* POP DIRECTIONAL FORMATTING */, - 0x202d, - 0x202d /* LEFT-TO-RIGHT OVERRIDE */, - 0x202e, - 0x202e /* RIGHT-TO-LEFT OVERRIDE */, - 0x206a, - 0x206a /* INHIBIT SYMMETRIC SWAPPING */, - 0x206b, - 0x206b /* ACTIVATE SYMMETRIC SWAPPING */, - 0x206c, - 0x206c /* INHIBIT ARABIC FORM SHAPING */, - 0x206d, - 0x206d /* ACTIVATE ARABIC FORM SHAPING */, - 0x206e, - 0x206e /* NATIONAL DIGIT SHAPES */, - 0x206f, - 0x206f /* NOMINAL DIGIT SHAPES */, - - /** - * C.7 Inappropriate for canonical representation - * @link https://tools.ietf.org/html/rfc3454#appendix-C.7 - */ - 0x2ff0, - 0x2ffb /* [IDEOGRAPHIC DESCRIPTION CHARACTERS] */, - - /** - * C.5 Surrogate codes - * @link https://tools.ietf.org/html/rfc3454#appendix-C.5 - */ - 0xd800, - 0xdfff, - - /** - * C.3 Private use - * @link https://tools.ietf.org/html/rfc3454#appendix-C.3 - */ - 0xe000, - 0xf8ff /* [PRIVATE USE, PLANE 0] */, - - /** - * C.6 Inappropriate for plain text - * @link https://tools.ietf.org/html/rfc3454#appendix-C.6 - */ - 0xfff9, - 0xfff9 /* INTERLINEAR ANNOTATION ANCHOR */, - 0xfffa, - 0xfffa /* INTERLINEAR ANNOTATION SEPARATOR */, - 0xfffb, - 0xfffb /* INTERLINEAR ANNOTATION TERMINATOR */, - 0xfffc, - 0xfffc /* OBJECT REPLACEMENT CHARACTER */, - 0xfffd, - 0xfffd /* REPLACEMENT CHARACTER */, - - /** - * C.9 Tagging characters - * @link https://tools.ietf.org/html/rfc3454#appendix-C.9 - */ - 0xe0001, - 0xe0001 /* LANGUAGE TAG */, - 0xe0020, - 0xe007f /* [TAGGING CHARACTERS] */, - - /** - * C.3 Private use - * @link https://tools.ietf.org/html/rfc3454#appendix-C.3 - */ - - 0xf0000, - 0xffffd /* [PRIVATE USE, PLANE 15] */, - 0x100000, - 0x10fffd /* [PRIVATE USE, PLANE 16] */ - ]; - /* eslint-enable */ - - const isProhibitedCharacter = character => - inRange(character, non_ASCII_space_characters) || - inRange(character, prohibited_characters) || - inRange(character, non_ASCII_controls_characters) || - inRange(character, non_character_codepoints); - - /* eslint-disable prettier/prettier */ - /** - * D.1 Characters with bidirectional property "R" or "AL" - * @link https://tools.ietf.org/html/rfc3454#appendix-D.1 - */ - const bidirectional_r_al = [ - 0x05be, - 0x05be, - 0x05c0, - 0x05c0, - 0x05c3, - 0x05c3, - 0x05d0, - 0x05ea, - 0x05f0, - 0x05f4, - 0x061b, - 0x061b, - 0x061f, - 0x061f, - 0x0621, - 0x063a, - 0x0640, - 0x064a, - 0x066d, - 0x066f, - 0x0671, - 0x06d5, - 0x06dd, - 0x06dd, - 0x06e5, - 0x06e6, - 0x06fa, - 0x06fe, - 0x0700, - 0x070d, - 0x0710, - 0x0710, - 0x0712, - 0x072c, - 0x0780, - 0x07a5, - 0x07b1, - 0x07b1, - 0x200f, - 0x200f, - 0xfb1d, - 0xfb1d, - 0xfb1f, - 0xfb28, - 0xfb2a, - 0xfb36, - 0xfb38, - 0xfb3c, - 0xfb3e, - 0xfb3e, - 0xfb40, - 0xfb41, - 0xfb43, - 0xfb44, - 0xfb46, - 0xfbb1, - 0xfbd3, - 0xfd3d, - 0xfd50, - 0xfd8f, - 0xfd92, - 0xfdc7, - 0xfdf0, - 0xfdfc, - 0xfe70, - 0xfe74, - 0xfe76, - 0xfefc - ]; - /* eslint-enable */ - - const isBidirectionalRAL = character => inRange(character, bidirectional_r_al); - - /* eslint-disable prettier/prettier */ - /** - * D.2 Characters with bidirectional property "L" - * @link https://tools.ietf.org/html/rfc3454#appendix-D.2 - */ - const bidirectional_l = [ - 0x0041, - 0x005a, - 0x0061, - 0x007a, - 0x00aa, - 0x00aa, - 0x00b5, - 0x00b5, - 0x00ba, - 0x00ba, - 0x00c0, - 0x00d6, - 0x00d8, - 0x00f6, - 0x00f8, - 0x0220, - 0x0222, - 0x0233, - 0x0250, - 0x02ad, - 0x02b0, - 0x02b8, - 0x02bb, - 0x02c1, - 0x02d0, - 0x02d1, - 0x02e0, - 0x02e4, - 0x02ee, - 0x02ee, - 0x037a, - 0x037a, - 0x0386, - 0x0386, - 0x0388, - 0x038a, - 0x038c, - 0x038c, - 0x038e, - 0x03a1, - 0x03a3, - 0x03ce, - 0x03d0, - 0x03f5, - 0x0400, - 0x0482, - 0x048a, - 0x04ce, - 0x04d0, - 0x04f5, - 0x04f8, - 0x04f9, - 0x0500, - 0x050f, - 0x0531, - 0x0556, - 0x0559, - 0x055f, - 0x0561, - 0x0587, - 0x0589, - 0x0589, - 0x0903, - 0x0903, - 0x0905, - 0x0939, - 0x093d, - 0x0940, - 0x0949, - 0x094c, - 0x0950, - 0x0950, - 0x0958, - 0x0961, - 0x0964, - 0x0970, - 0x0982, - 0x0983, - 0x0985, - 0x098c, - 0x098f, - 0x0990, - 0x0993, - 0x09a8, - 0x09aa, - 0x09b0, - 0x09b2, - 0x09b2, - 0x09b6, - 0x09b9, - 0x09be, - 0x09c0, - 0x09c7, - 0x09c8, - 0x09cb, - 0x09cc, - 0x09d7, - 0x09d7, - 0x09dc, - 0x09dd, - 0x09df, - 0x09e1, - 0x09e6, - 0x09f1, - 0x09f4, - 0x09fa, - 0x0a05, - 0x0a0a, - 0x0a0f, - 0x0a10, - 0x0a13, - 0x0a28, - 0x0a2a, - 0x0a30, - 0x0a32, - 0x0a33, - 0x0a35, - 0x0a36, - 0x0a38, - 0x0a39, - 0x0a3e, - 0x0a40, - 0x0a59, - 0x0a5c, - 0x0a5e, - 0x0a5e, - 0x0a66, - 0x0a6f, - 0x0a72, - 0x0a74, - 0x0a83, - 0x0a83, - 0x0a85, - 0x0a8b, - 0x0a8d, - 0x0a8d, - 0x0a8f, - 0x0a91, - 0x0a93, - 0x0aa8, - 0x0aaa, - 0x0ab0, - 0x0ab2, - 0x0ab3, - 0x0ab5, - 0x0ab9, - 0x0abd, - 0x0ac0, - 0x0ac9, - 0x0ac9, - 0x0acb, - 0x0acc, - 0x0ad0, - 0x0ad0, - 0x0ae0, - 0x0ae0, - 0x0ae6, - 0x0aef, - 0x0b02, - 0x0b03, - 0x0b05, - 0x0b0c, - 0x0b0f, - 0x0b10, - 0x0b13, - 0x0b28, - 0x0b2a, - 0x0b30, - 0x0b32, - 0x0b33, - 0x0b36, - 0x0b39, - 0x0b3d, - 0x0b3e, - 0x0b40, - 0x0b40, - 0x0b47, - 0x0b48, - 0x0b4b, - 0x0b4c, - 0x0b57, - 0x0b57, - 0x0b5c, - 0x0b5d, - 0x0b5f, - 0x0b61, - 0x0b66, - 0x0b70, - 0x0b83, - 0x0b83, - 0x0b85, - 0x0b8a, - 0x0b8e, - 0x0b90, - 0x0b92, - 0x0b95, - 0x0b99, - 0x0b9a, - 0x0b9c, - 0x0b9c, - 0x0b9e, - 0x0b9f, - 0x0ba3, - 0x0ba4, - 0x0ba8, - 0x0baa, - 0x0bae, - 0x0bb5, - 0x0bb7, - 0x0bb9, - 0x0bbe, - 0x0bbf, - 0x0bc1, - 0x0bc2, - 0x0bc6, - 0x0bc8, - 0x0bca, - 0x0bcc, - 0x0bd7, - 0x0bd7, - 0x0be7, - 0x0bf2, - 0x0c01, - 0x0c03, - 0x0c05, - 0x0c0c, - 0x0c0e, - 0x0c10, - 0x0c12, - 0x0c28, - 0x0c2a, - 0x0c33, - 0x0c35, - 0x0c39, - 0x0c41, - 0x0c44, - 0x0c60, - 0x0c61, - 0x0c66, - 0x0c6f, - 0x0c82, - 0x0c83, - 0x0c85, - 0x0c8c, - 0x0c8e, - 0x0c90, - 0x0c92, - 0x0ca8, - 0x0caa, - 0x0cb3, - 0x0cb5, - 0x0cb9, - 0x0cbe, - 0x0cbe, - 0x0cc0, - 0x0cc4, - 0x0cc7, - 0x0cc8, - 0x0cca, - 0x0ccb, - 0x0cd5, - 0x0cd6, - 0x0cde, - 0x0cde, - 0x0ce0, - 0x0ce1, - 0x0ce6, - 0x0cef, - 0x0d02, - 0x0d03, - 0x0d05, - 0x0d0c, - 0x0d0e, - 0x0d10, - 0x0d12, - 0x0d28, - 0x0d2a, - 0x0d39, - 0x0d3e, - 0x0d40, - 0x0d46, - 0x0d48, - 0x0d4a, - 0x0d4c, - 0x0d57, - 0x0d57, - 0x0d60, - 0x0d61, - 0x0d66, - 0x0d6f, - 0x0d82, - 0x0d83, - 0x0d85, - 0x0d96, - 0x0d9a, - 0x0db1, - 0x0db3, - 0x0dbb, - 0x0dbd, - 0x0dbd, - 0x0dc0, - 0x0dc6, - 0x0dcf, - 0x0dd1, - 0x0dd8, - 0x0ddf, - 0x0df2, - 0x0df4, - 0x0e01, - 0x0e30, - 0x0e32, - 0x0e33, - 0x0e40, - 0x0e46, - 0x0e4f, - 0x0e5b, - 0x0e81, - 0x0e82, - 0x0e84, - 0x0e84, - 0x0e87, - 0x0e88, - 0x0e8a, - 0x0e8a, - 0x0e8d, - 0x0e8d, - 0x0e94, - 0x0e97, - 0x0e99, - 0x0e9f, - 0x0ea1, - 0x0ea3, - 0x0ea5, - 0x0ea5, - 0x0ea7, - 0x0ea7, - 0x0eaa, - 0x0eab, - 0x0ead, - 0x0eb0, - 0x0eb2, - 0x0eb3, - 0x0ebd, - 0x0ebd, - 0x0ec0, - 0x0ec4, - 0x0ec6, - 0x0ec6, - 0x0ed0, - 0x0ed9, - 0x0edc, - 0x0edd, - 0x0f00, - 0x0f17, - 0x0f1a, - 0x0f34, - 0x0f36, - 0x0f36, - 0x0f38, - 0x0f38, - 0x0f3e, - 0x0f47, - 0x0f49, - 0x0f6a, - 0x0f7f, - 0x0f7f, - 0x0f85, - 0x0f85, - 0x0f88, - 0x0f8b, - 0x0fbe, - 0x0fc5, - 0x0fc7, - 0x0fcc, - 0x0fcf, - 0x0fcf, - 0x1000, - 0x1021, - 0x1023, - 0x1027, - 0x1029, - 0x102a, - 0x102c, - 0x102c, - 0x1031, - 0x1031, - 0x1038, - 0x1038, - 0x1040, - 0x1057, - 0x10a0, - 0x10c5, - 0x10d0, - 0x10f8, - 0x10fb, - 0x10fb, - 0x1100, - 0x1159, - 0x115f, - 0x11a2, - 0x11a8, - 0x11f9, - 0x1200, - 0x1206, - 0x1208, - 0x1246, - 0x1248, - 0x1248, - 0x124a, - 0x124d, - 0x1250, - 0x1256, - 0x1258, - 0x1258, - 0x125a, - 0x125d, - 0x1260, - 0x1286, - 0x1288, - 0x1288, - 0x128a, - 0x128d, - 0x1290, - 0x12ae, - 0x12b0, - 0x12b0, - 0x12b2, - 0x12b5, - 0x12b8, - 0x12be, - 0x12c0, - 0x12c0, - 0x12c2, - 0x12c5, - 0x12c8, - 0x12ce, - 0x12d0, - 0x12d6, - 0x12d8, - 0x12ee, - 0x12f0, - 0x130e, - 0x1310, - 0x1310, - 0x1312, - 0x1315, - 0x1318, - 0x131e, - 0x1320, - 0x1346, - 0x1348, - 0x135a, - 0x1361, - 0x137c, - 0x13a0, - 0x13f4, - 0x1401, - 0x1676, - 0x1681, - 0x169a, - 0x16a0, - 0x16f0, - 0x1700, - 0x170c, - 0x170e, - 0x1711, - 0x1720, - 0x1731, - 0x1735, - 0x1736, - 0x1740, - 0x1751, - 0x1760, - 0x176c, - 0x176e, - 0x1770, - 0x1780, - 0x17b6, - 0x17be, - 0x17c5, - 0x17c7, - 0x17c8, - 0x17d4, - 0x17da, - 0x17dc, - 0x17dc, - 0x17e0, - 0x17e9, - 0x1810, - 0x1819, - 0x1820, - 0x1877, - 0x1880, - 0x18a8, - 0x1e00, - 0x1e9b, - 0x1ea0, - 0x1ef9, - 0x1f00, - 0x1f15, - 0x1f18, - 0x1f1d, - 0x1f20, - 0x1f45, - 0x1f48, - 0x1f4d, - 0x1f50, - 0x1f57, - 0x1f59, - 0x1f59, - 0x1f5b, - 0x1f5b, - 0x1f5d, - 0x1f5d, - 0x1f5f, - 0x1f7d, - 0x1f80, - 0x1fb4, - 0x1fb6, - 0x1fbc, - 0x1fbe, - 0x1fbe, - 0x1fc2, - 0x1fc4, - 0x1fc6, - 0x1fcc, - 0x1fd0, - 0x1fd3, - 0x1fd6, - 0x1fdb, - 0x1fe0, - 0x1fec, - 0x1ff2, - 0x1ff4, - 0x1ff6, - 0x1ffc, - 0x200e, - 0x200e, - 0x2071, - 0x2071, - 0x207f, - 0x207f, - 0x2102, - 0x2102, - 0x2107, - 0x2107, - 0x210a, - 0x2113, - 0x2115, - 0x2115, - 0x2119, - 0x211d, - 0x2124, - 0x2124, - 0x2126, - 0x2126, - 0x2128, - 0x2128, - 0x212a, - 0x212d, - 0x212f, - 0x2131, - 0x2133, - 0x2139, - 0x213d, - 0x213f, - 0x2145, - 0x2149, - 0x2160, - 0x2183, - 0x2336, - 0x237a, - 0x2395, - 0x2395, - 0x249c, - 0x24e9, - 0x3005, - 0x3007, - 0x3021, - 0x3029, - 0x3031, - 0x3035, - 0x3038, - 0x303c, - 0x3041, - 0x3096, - 0x309d, - 0x309f, - 0x30a1, - 0x30fa, - 0x30fc, - 0x30ff, - 0x3105, - 0x312c, - 0x3131, - 0x318e, - 0x3190, - 0x31b7, - 0x31f0, - 0x321c, - 0x3220, - 0x3243, - 0x3260, - 0x327b, - 0x327f, - 0x32b0, - 0x32c0, - 0x32cb, - 0x32d0, - 0x32fe, - 0x3300, - 0x3376, - 0x337b, - 0x33dd, - 0x33e0, - 0x33fe, - 0x3400, - 0x4db5, - 0x4e00, - 0x9fa5, - 0xa000, - 0xa48c, - 0xac00, - 0xd7a3, - 0xd800, - 0xfa2d, - 0xfa30, - 0xfa6a, - 0xfb00, - 0xfb06, - 0xfb13, - 0xfb17, - 0xff21, - 0xff3a, - 0xff41, - 0xff5a, - 0xff66, - 0xffbe, - 0xffc2, - 0xffc7, - 0xffca, - 0xffcf, - 0xffd2, - 0xffd7, - 0xffda, - 0xffdc, - 0x10300, - 0x1031e, - 0x10320, - 0x10323, - 0x10330, - 0x1034a, - 0x10400, - 0x10425, - 0x10428, - 0x1044d, - 0x1d000, - 0x1d0f5, - 0x1d100, - 0x1d126, - 0x1d12a, - 0x1d166, - 0x1d16a, - 0x1d172, - 0x1d183, - 0x1d184, - 0x1d18c, - 0x1d1a9, - 0x1d1ae, - 0x1d1dd, - 0x1d400, - 0x1d454, - 0x1d456, - 0x1d49c, - 0x1d49e, - 0x1d49f, - 0x1d4a2, - 0x1d4a2, - 0x1d4a5, - 0x1d4a6, - 0x1d4a9, - 0x1d4ac, - 0x1d4ae, - 0x1d4b9, - 0x1d4bb, - 0x1d4bb, - 0x1d4bd, - 0x1d4c0, - 0x1d4c2, - 0x1d4c3, - 0x1d4c5, - 0x1d505, - 0x1d507, - 0x1d50a, - 0x1d50d, - 0x1d514, - 0x1d516, - 0x1d51c, - 0x1d51e, - 0x1d539, - 0x1d53b, - 0x1d53e, - 0x1d540, - 0x1d544, - 0x1d546, - 0x1d546, - 0x1d54a, - 0x1d550, - 0x1d552, - 0x1d6a3, - 0x1d6a8, - 0x1d7c9, - 0x20000, - 0x2a6d6, - 0x2f800, - 0x2fa1d, - 0xf0000, - 0xffffd, - 0x100000, - 0x10fffd - ]; - /* eslint-enable */ - + /* eslint-disable prettier/prettier */ + /** + * A.1 Unassigned code points in Unicode 3.2 + * @link https://tools.ietf.org/html/rfc3454#appendix-A.1 + */ + const unassigned_code_points = [ + 0x0221, + 0x0221, + 0x0234, + 0x024f, + 0x02ae, + 0x02af, + 0x02ef, + 0x02ff, + 0x0350, + 0x035f, + 0x0370, + 0x0373, + 0x0376, + 0x0379, + 0x037b, + 0x037d, + 0x037f, + 0x0383, + 0x038b, + 0x038b, + 0x038d, + 0x038d, + 0x03a2, + 0x03a2, + 0x03cf, + 0x03cf, + 0x03f7, + 0x03ff, + 0x0487, + 0x0487, + 0x04cf, + 0x04cf, + 0x04f6, + 0x04f7, + 0x04fa, + 0x04ff, + 0x0510, + 0x0530, + 0x0557, + 0x0558, + 0x0560, + 0x0560, + 0x0588, + 0x0588, + 0x058b, + 0x0590, + 0x05a2, + 0x05a2, + 0x05ba, + 0x05ba, + 0x05c5, + 0x05cf, + 0x05eb, + 0x05ef, + 0x05f5, + 0x060b, + 0x060d, + 0x061a, + 0x061c, + 0x061e, + 0x0620, + 0x0620, + 0x063b, + 0x063f, + 0x0656, + 0x065f, + 0x06ee, + 0x06ef, + 0x06ff, + 0x06ff, + 0x070e, + 0x070e, + 0x072d, + 0x072f, + 0x074b, + 0x077f, + 0x07b2, + 0x0900, + 0x0904, + 0x0904, + 0x093a, + 0x093b, + 0x094e, + 0x094f, + 0x0955, + 0x0957, + 0x0971, + 0x0980, + 0x0984, + 0x0984, + 0x098d, + 0x098e, + 0x0991, + 0x0992, + 0x09a9, + 0x09a9, + 0x09b1, + 0x09b1, + 0x09b3, + 0x09b5, + 0x09ba, + 0x09bb, + 0x09bd, + 0x09bd, + 0x09c5, + 0x09c6, + 0x09c9, + 0x09ca, + 0x09ce, + 0x09d6, + 0x09d8, + 0x09db, + 0x09de, + 0x09de, + 0x09e4, + 0x09e5, + 0x09fb, + 0x0a01, + 0x0a03, + 0x0a04, + 0x0a0b, + 0x0a0e, + 0x0a11, + 0x0a12, + 0x0a29, + 0x0a29, + 0x0a31, + 0x0a31, + 0x0a34, + 0x0a34, + 0x0a37, + 0x0a37, + 0x0a3a, + 0x0a3b, + 0x0a3d, + 0x0a3d, + 0x0a43, + 0x0a46, + 0x0a49, + 0x0a4a, + 0x0a4e, + 0x0a58, + 0x0a5d, + 0x0a5d, + 0x0a5f, + 0x0a65, + 0x0a75, + 0x0a80, + 0x0a84, + 0x0a84, + 0x0a8c, + 0x0a8c, + 0x0a8e, + 0x0a8e, + 0x0a92, + 0x0a92, + 0x0aa9, + 0x0aa9, + 0x0ab1, + 0x0ab1, + 0x0ab4, + 0x0ab4, + 0x0aba, + 0x0abb, + 0x0ac6, + 0x0ac6, + 0x0aca, + 0x0aca, + 0x0ace, + 0x0acf, + 0x0ad1, + 0x0adf, + 0x0ae1, + 0x0ae5, + 0x0af0, + 0x0b00, + 0x0b04, + 0x0b04, + 0x0b0d, + 0x0b0e, + 0x0b11, + 0x0b12, + 0x0b29, + 0x0b29, + 0x0b31, + 0x0b31, + 0x0b34, + 0x0b35, + 0x0b3a, + 0x0b3b, + 0x0b44, + 0x0b46, + 0x0b49, + 0x0b4a, + 0x0b4e, + 0x0b55, + 0x0b58, + 0x0b5b, + 0x0b5e, + 0x0b5e, + 0x0b62, + 0x0b65, + 0x0b71, + 0x0b81, + 0x0b84, + 0x0b84, + 0x0b8b, + 0x0b8d, + 0x0b91, + 0x0b91, + 0x0b96, + 0x0b98, + 0x0b9b, + 0x0b9b, + 0x0b9d, + 0x0b9d, + 0x0ba0, + 0x0ba2, + 0x0ba5, + 0x0ba7, + 0x0bab, + 0x0bad, + 0x0bb6, + 0x0bb6, + 0x0bba, + 0x0bbd, + 0x0bc3, + 0x0bc5, + 0x0bc9, + 0x0bc9, + 0x0bce, + 0x0bd6, + 0x0bd8, + 0x0be6, + 0x0bf3, + 0x0c00, + 0x0c04, + 0x0c04, + 0x0c0d, + 0x0c0d, + 0x0c11, + 0x0c11, + 0x0c29, + 0x0c29, + 0x0c34, + 0x0c34, + 0x0c3a, + 0x0c3d, + 0x0c45, + 0x0c45, + 0x0c49, + 0x0c49, + 0x0c4e, + 0x0c54, + 0x0c57, + 0x0c5f, + 0x0c62, + 0x0c65, + 0x0c70, + 0x0c81, + 0x0c84, + 0x0c84, + 0x0c8d, + 0x0c8d, + 0x0c91, + 0x0c91, + 0x0ca9, + 0x0ca9, + 0x0cb4, + 0x0cb4, + 0x0cba, + 0x0cbd, + 0x0cc5, + 0x0cc5, + 0x0cc9, + 0x0cc9, + 0x0cce, + 0x0cd4, + 0x0cd7, + 0x0cdd, + 0x0cdf, + 0x0cdf, + 0x0ce2, + 0x0ce5, + 0x0cf0, + 0x0d01, + 0x0d04, + 0x0d04, + 0x0d0d, + 0x0d0d, + 0x0d11, + 0x0d11, + 0x0d29, + 0x0d29, + 0x0d3a, + 0x0d3d, + 0x0d44, + 0x0d45, + 0x0d49, + 0x0d49, + 0x0d4e, + 0x0d56, + 0x0d58, + 0x0d5f, + 0x0d62, + 0x0d65, + 0x0d70, + 0x0d81, + 0x0d84, + 0x0d84, + 0x0d97, + 0x0d99, + 0x0db2, + 0x0db2, + 0x0dbc, + 0x0dbc, + 0x0dbe, + 0x0dbf, + 0x0dc7, + 0x0dc9, + 0x0dcb, + 0x0dce, + 0x0dd5, + 0x0dd5, + 0x0dd7, + 0x0dd7, + 0x0de0, + 0x0df1, + 0x0df5, + 0x0e00, + 0x0e3b, + 0x0e3e, + 0x0e5c, + 0x0e80, + 0x0e83, + 0x0e83, + 0x0e85, + 0x0e86, + 0x0e89, + 0x0e89, + 0x0e8b, + 0x0e8c, + 0x0e8e, + 0x0e93, + 0x0e98, + 0x0e98, + 0x0ea0, + 0x0ea0, + 0x0ea4, + 0x0ea4, + 0x0ea6, + 0x0ea6, + 0x0ea8, + 0x0ea9, + 0x0eac, + 0x0eac, + 0x0eba, + 0x0eba, + 0x0ebe, + 0x0ebf, + 0x0ec5, + 0x0ec5, + 0x0ec7, + 0x0ec7, + 0x0ece, + 0x0ecf, + 0x0eda, + 0x0edb, + 0x0ede, + 0x0eff, + 0x0f48, + 0x0f48, + 0x0f6b, + 0x0f70, + 0x0f8c, + 0x0f8f, + 0x0f98, + 0x0f98, + 0x0fbd, + 0x0fbd, + 0x0fcd, + 0x0fce, + 0x0fd0, + 0x0fff, + 0x1022, + 0x1022, + 0x1028, + 0x1028, + 0x102b, + 0x102b, + 0x1033, + 0x1035, + 0x103a, + 0x103f, + 0x105a, + 0x109f, + 0x10c6, + 0x10cf, + 0x10f9, + 0x10fa, + 0x10fc, + 0x10ff, + 0x115a, + 0x115e, + 0x11a3, + 0x11a7, + 0x11fa, + 0x11ff, + 0x1207, + 0x1207, + 0x1247, + 0x1247, + 0x1249, + 0x1249, + 0x124e, + 0x124f, + 0x1257, + 0x1257, + 0x1259, + 0x1259, + 0x125e, + 0x125f, + 0x1287, + 0x1287, + 0x1289, + 0x1289, + 0x128e, + 0x128f, + 0x12af, + 0x12af, + 0x12b1, + 0x12b1, + 0x12b6, + 0x12b7, + 0x12bf, + 0x12bf, + 0x12c1, + 0x12c1, + 0x12c6, + 0x12c7, + 0x12cf, + 0x12cf, + 0x12d7, + 0x12d7, + 0x12ef, + 0x12ef, + 0x130f, + 0x130f, + 0x1311, + 0x1311, + 0x1316, + 0x1317, + 0x131f, + 0x131f, + 0x1347, + 0x1347, + 0x135b, + 0x1360, + 0x137d, + 0x139f, + 0x13f5, + 0x1400, + 0x1677, + 0x167f, + 0x169d, + 0x169f, + 0x16f1, + 0x16ff, + 0x170d, + 0x170d, + 0x1715, + 0x171f, + 0x1737, + 0x173f, + 0x1754, + 0x175f, + 0x176d, + 0x176d, + 0x1771, + 0x1771, + 0x1774, + 0x177f, + 0x17dd, + 0x17df, + 0x17ea, + 0x17ff, + 0x180f, + 0x180f, + 0x181a, + 0x181f, + 0x1878, + 0x187f, + 0x18aa, + 0x1dff, + 0x1e9c, + 0x1e9f, + 0x1efa, + 0x1eff, + 0x1f16, + 0x1f17, + 0x1f1e, + 0x1f1f, + 0x1f46, + 0x1f47, + 0x1f4e, + 0x1f4f, + 0x1f58, + 0x1f58, + 0x1f5a, + 0x1f5a, + 0x1f5c, + 0x1f5c, + 0x1f5e, + 0x1f5e, + 0x1f7e, + 0x1f7f, + 0x1fb5, + 0x1fb5, + 0x1fc5, + 0x1fc5, + 0x1fd4, + 0x1fd5, + 0x1fdc, + 0x1fdc, + 0x1ff0, + 0x1ff1, + 0x1ff5, + 0x1ff5, + 0x1fff, + 0x1fff, + 0x2053, + 0x2056, + 0x2058, + 0x205e, + 0x2064, + 0x2069, + 0x2072, + 0x2073, + 0x208f, + 0x209f, + 0x20b2, + 0x20cf, + 0x20eb, + 0x20ff, + 0x213b, + 0x213c, + 0x214c, + 0x2152, + 0x2184, + 0x218f, + 0x23cf, + 0x23ff, + 0x2427, + 0x243f, + 0x244b, + 0x245f, + 0x24ff, + 0x24ff, + 0x2614, + 0x2615, + 0x2618, + 0x2618, + 0x267e, + 0x267f, + 0x268a, + 0x2700, + 0x2705, + 0x2705, + 0x270a, + 0x270b, + 0x2728, + 0x2728, + 0x274c, + 0x274c, + 0x274e, + 0x274e, + 0x2753, + 0x2755, + 0x2757, + 0x2757, + 0x275f, + 0x2760, + 0x2795, + 0x2797, + 0x27b0, + 0x27b0, + 0x27bf, + 0x27cf, + 0x27ec, + 0x27ef, + 0x2b00, + 0x2e7f, + 0x2e9a, + 0x2e9a, + 0x2ef4, + 0x2eff, + 0x2fd6, + 0x2fef, + 0x2ffc, + 0x2fff, + 0x3040, + 0x3040, + 0x3097, + 0x3098, + 0x3100, + 0x3104, + 0x312d, + 0x3130, + 0x318f, + 0x318f, + 0x31b8, + 0x31ef, + 0x321d, + 0x321f, + 0x3244, + 0x3250, + 0x327c, + 0x327e, + 0x32cc, + 0x32cf, + 0x32ff, + 0x32ff, + 0x3377, + 0x337a, + 0x33de, + 0x33df, + 0x33ff, + 0x33ff, + 0x4db6, + 0x4dff, + 0x9fa6, + 0x9fff, + 0xa48d, + 0xa48f, + 0xa4c7, + 0xabff, + 0xd7a4, + 0xd7ff, + 0xfa2e, + 0xfa2f, + 0xfa6b, + 0xfaff, + 0xfb07, + 0xfb12, + 0xfb18, + 0xfb1c, + 0xfb37, + 0xfb37, + 0xfb3d, + 0xfb3d, + 0xfb3f, + 0xfb3f, + 0xfb42, + 0xfb42, + 0xfb45, + 0xfb45, + 0xfbb2, + 0xfbd2, + 0xfd40, + 0xfd4f, + 0xfd90, + 0xfd91, + 0xfdc8, + 0xfdcf, + 0xfdfd, + 0xfdff, + 0xfe10, + 0xfe1f, + 0xfe24, + 0xfe2f, + 0xfe47, + 0xfe48, + 0xfe53, + 0xfe53, + 0xfe67, + 0xfe67, + 0xfe6c, + 0xfe6f, + 0xfe75, + 0xfe75, + 0xfefd, + 0xfefe, + 0xff00, + 0xff00, + 0xffbf, + 0xffc1, + 0xffc8, + 0xffc9, + 0xffd0, + 0xffd1, + 0xffd8, + 0xffd9, + 0xffdd, + 0xffdf, + 0xffe7, + 0xffe7, + 0xffef, + 0xfff8, + 0x10000, + 0x102ff, + 0x1031f, + 0x1031f, + 0x10324, + 0x1032f, + 0x1034b, + 0x103ff, + 0x10426, + 0x10427, + 0x1044e, + 0x1cfff, + 0x1d0f6, + 0x1d0ff, + 0x1d127, + 0x1d129, + 0x1d1de, + 0x1d3ff, + 0x1d455, + 0x1d455, + 0x1d49d, + 0x1d49d, + 0x1d4a0, + 0x1d4a1, + 0x1d4a3, + 0x1d4a4, + 0x1d4a7, + 0x1d4a8, + 0x1d4ad, + 0x1d4ad, + 0x1d4ba, + 0x1d4ba, + 0x1d4bc, + 0x1d4bc, + 0x1d4c1, + 0x1d4c1, + 0x1d4c4, + 0x1d4c4, + 0x1d506, + 0x1d506, + 0x1d50b, + 0x1d50c, + 0x1d515, + 0x1d515, + 0x1d51d, + 0x1d51d, + 0x1d53a, + 0x1d53a, + 0x1d53f, + 0x1d53f, + 0x1d545, + 0x1d545, + 0x1d547, + 0x1d549, + 0x1d551, + 0x1d551, + 0x1d6a4, + 0x1d6a7, + 0x1d7ca, + 0x1d7cd, + 0x1d800, + 0x1fffd, + 0x2a6d7, + 0x2f7ff, + 0x2fa1e, + 0x2fffd, + 0x30000, + 0x3fffd, + 0x40000, + 0x4fffd, + 0x50000, + 0x5fffd, + 0x60000, + 0x6fffd, + 0x70000, + 0x7fffd, + 0x80000, + 0x8fffd, + 0x90000, + 0x9fffd, + 0xa0000, + 0xafffd, + 0xb0000, + 0xbfffd, + 0xc0000, + 0xcfffd, + 0xd0000, + 0xdfffd, + 0xe0000, + 0xe0000, + 0xe0002, + 0xe001f, + 0xe0080, + 0xefffd + ]; + /* eslint-enable */ + + const isUnassignedCodePoint = character => + inRange(character, unassigned_code_points); + + /* eslint-disable prettier/prettier */ + /** + * B.1 Commonly mapped to nothing + * @link https://tools.ietf.org/html/rfc3454#appendix-B.1 + */ + const commonly_mapped_to_nothing = [ + 0x00ad, + 0x00ad, + 0x034f, + 0x034f, + 0x1806, + 0x1806, + 0x180b, + 0x180b, + 0x180c, + 0x180c, + 0x180d, + 0x180d, + 0x200b, + 0x200b, + 0x200c, + 0x200c, + 0x200d, + 0x200d, + 0x2060, + 0x2060, + 0xfe00, + 0xfe00, + 0xfe01, + 0xfe01, + 0xfe02, + 0xfe02, + 0xfe03, + 0xfe03, + 0xfe04, + 0xfe04, + 0xfe05, + 0xfe05, + 0xfe06, + 0xfe06, + 0xfe07, + 0xfe07, + 0xfe08, + 0xfe08, + 0xfe09, + 0xfe09, + 0xfe0a, + 0xfe0a, + 0xfe0b, + 0xfe0b, + 0xfe0c, + 0xfe0c, + 0xfe0d, + 0xfe0d, + 0xfe0e, + 0xfe0e, + 0xfe0f, + 0xfe0f, + 0xfeff, + 0xfeff + ]; + /* eslint-enable */ + + const isCommonlyMappedToNothing = character => + inRange(character, commonly_mapped_to_nothing); + + /* eslint-disable prettier/prettier */ + /** + * C.1.2 Non-ASCII space characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.1.2 + */ + const non_ASCII_space_characters = [ + 0x00a0, + 0x00a0 /* NO-BREAK SPACE */, + 0x1680, + 0x1680 /* OGHAM SPACE MARK */, + 0x2000, + 0x2000 /* EN QUAD */, + 0x2001, + 0x2001 /* EM QUAD */, + 0x2002, + 0x2002 /* EN SPACE */, + 0x2003, + 0x2003 /* EM SPACE */, + 0x2004, + 0x2004 /* THREE-PER-EM SPACE */, + 0x2005, + 0x2005 /* FOUR-PER-EM SPACE */, + 0x2006, + 0x2006 /* SIX-PER-EM SPACE */, + 0x2007, + 0x2007 /* FIGURE SPACE */, + 0x2008, + 0x2008 /* PUNCTUATION SPACE */, + 0x2009, + 0x2009 /* THIN SPACE */, + 0x200a, + 0x200a /* HAIR SPACE */, + 0x200b, + 0x200b /* ZERO WIDTH SPACE */, + 0x202f, + 0x202f /* NARROW NO-BREAK SPACE */, + 0x205f, + 0x205f /* MEDIUM MATHEMATICAL SPACE */, + 0x3000, + 0x3000 /* IDEOGRAPHIC SPACE */ + ]; + /* eslint-enable */ + + const isNonASCIISpaceCharacter = character => + inRange(character, non_ASCII_space_characters); + + /* eslint-disable prettier/prettier */ + const non_ASCII_controls_characters = [ + /** + * C.2.2 Non-ASCII control characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.2 + */ + 0x0080, + 0x009f /* [CONTROL CHARACTERS] */, + 0x06dd, + 0x06dd /* ARABIC END OF AYAH */, + 0x070f, + 0x070f /* SYRIAC ABBREVIATION MARK */, + 0x180e, + 0x180e /* MONGOLIAN VOWEL SEPARATOR */, + 0x200c, + 0x200c /* ZERO WIDTH NON-JOINER */, + 0x200d, + 0x200d /* ZERO WIDTH JOINER */, + 0x2028, + 0x2028 /* LINE SEPARATOR */, + 0x2029, + 0x2029 /* PARAGRAPH SEPARATOR */, + 0x2060, + 0x2060 /* WORD JOINER */, + 0x2061, + 0x2061 /* FUNCTION APPLICATION */, + 0x2062, + 0x2062 /* INVISIBLE TIMES */, + 0x2063, + 0x2063 /* INVISIBLE SEPARATOR */, + 0x206a, + 0x206f /* [CONTROL CHARACTERS] */, + 0xfeff, + 0xfeff /* ZERO WIDTH NO-BREAK SPACE */, + 0xfff9, + 0xfffc /* [CONTROL CHARACTERS] */, + 0x1d173, + 0x1d17a /* [MUSICAL CONTROL CHARACTERS] */ + ]; + + const non_character_codepoints = [ + /** + * C.4 Non-character code points + * @link https://tools.ietf.org/html/rfc3454#appendix-C.4 + */ + 0xfdd0, + 0xfdef /* [NONCHARACTER CODE POINTS] */, + 0xfffe, + 0xffff /* [NONCHARACTER CODE POINTS] */, + 0x1fffe, + 0x1ffff /* [NONCHARACTER CODE POINTS] */, + 0x2fffe, + 0x2ffff /* [NONCHARACTER CODE POINTS] */, + 0x3fffe, + 0x3ffff /* [NONCHARACTER CODE POINTS] */, + 0x4fffe, + 0x4ffff /* [NONCHARACTER CODE POINTS] */, + 0x5fffe, + 0x5ffff /* [NONCHARACTER CODE POINTS] */, + 0x6fffe, + 0x6ffff /* [NONCHARACTER CODE POINTS] */, + 0x7fffe, + 0x7ffff /* [NONCHARACTER CODE POINTS] */, + 0x8fffe, + 0x8ffff /* [NONCHARACTER CODE POINTS] */, + 0x9fffe, + 0x9ffff /* [NONCHARACTER CODE POINTS] */, + 0xafffe, + 0xaffff /* [NONCHARACTER CODE POINTS] */, + 0xbfffe, + 0xbffff /* [NONCHARACTER CODE POINTS] */, + 0xcfffe, + 0xcffff /* [NONCHARACTER CODE POINTS] */, + 0xdfffe, + 0xdffff /* [NONCHARACTER CODE POINTS] */, + 0xefffe, + 0xeffff /* [NONCHARACTER CODE POINTS] */, + 0x10fffe, + 0x10ffff /* [NONCHARACTER CODE POINTS] */ + ]; + + /** + * 2.3. Prohibited Output + */ + const prohibited_characters = [ + /** + * C.2.1 ASCII control characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.1 + */ + 0, + 0x001f /* [CONTROL CHARACTERS] */, + 0x007f, + 0x007f /* DELETE */, + + /** + * C.8 Change display properties or are deprecated + * @link https://tools.ietf.org/html/rfc3454#appendix-C.8 + */ + 0x0340, + 0x0340 /* COMBINING GRAVE TONE MARK */, + 0x0341, + 0x0341 /* COMBINING ACUTE TONE MARK */, + 0x200e, + 0x200e /* LEFT-TO-RIGHT MARK */, + 0x200f, + 0x200f /* RIGHT-TO-LEFT MARK */, + 0x202a, + 0x202a /* LEFT-TO-RIGHT EMBEDDING */, + 0x202b, + 0x202b /* RIGHT-TO-LEFT EMBEDDING */, + 0x202c, + 0x202c /* POP DIRECTIONAL FORMATTING */, + 0x202d, + 0x202d /* LEFT-TO-RIGHT OVERRIDE */, + 0x202e, + 0x202e /* RIGHT-TO-LEFT OVERRIDE */, + 0x206a, + 0x206a /* INHIBIT SYMMETRIC SWAPPING */, + 0x206b, + 0x206b /* ACTIVATE SYMMETRIC SWAPPING */, + 0x206c, + 0x206c /* INHIBIT ARABIC FORM SHAPING */, + 0x206d, + 0x206d /* ACTIVATE ARABIC FORM SHAPING */, + 0x206e, + 0x206e /* NATIONAL DIGIT SHAPES */, + 0x206f, + 0x206f /* NOMINAL DIGIT SHAPES */, + + /** + * C.7 Inappropriate for canonical representation + * @link https://tools.ietf.org/html/rfc3454#appendix-C.7 + */ + 0x2ff0, + 0x2ffb /* [IDEOGRAPHIC DESCRIPTION CHARACTERS] */, + + /** + * C.5 Surrogate codes + * @link https://tools.ietf.org/html/rfc3454#appendix-C.5 + */ + 0xd800, + 0xdfff, + + /** + * C.3 Private use + * @link https://tools.ietf.org/html/rfc3454#appendix-C.3 + */ + 0xe000, + 0xf8ff /* [PRIVATE USE, PLANE 0] */, + + /** + * C.6 Inappropriate for plain text + * @link https://tools.ietf.org/html/rfc3454#appendix-C.6 + */ + 0xfff9, + 0xfff9 /* INTERLINEAR ANNOTATION ANCHOR */, + 0xfffa, + 0xfffa /* INTERLINEAR ANNOTATION SEPARATOR */, + 0xfffb, + 0xfffb /* INTERLINEAR ANNOTATION TERMINATOR */, + 0xfffc, + 0xfffc /* OBJECT REPLACEMENT CHARACTER */, + 0xfffd, + 0xfffd /* REPLACEMENT CHARACTER */, + + /** + * C.9 Tagging characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.9 + */ + 0xe0001, + 0xe0001 /* LANGUAGE TAG */, + 0xe0020, + 0xe007f /* [TAGGING CHARACTERS] */, + + /** + * C.3 Private use + * @link https://tools.ietf.org/html/rfc3454#appendix-C.3 + */ + + 0xf0000, + 0xffffd /* [PRIVATE USE, PLANE 15] */, + 0x100000, + 0x10fffd /* [PRIVATE USE, PLANE 16] */ + ]; + /* eslint-enable */ + + const isProhibitedCharacter = character => + inRange(character, non_ASCII_space_characters) || + inRange(character, prohibited_characters) || + inRange(character, non_ASCII_controls_characters) || + inRange(character, non_character_codepoints); + + /* eslint-disable prettier/prettier */ + /** + * D.1 Characters with bidirectional property "R" or "AL" + * @link https://tools.ietf.org/html/rfc3454#appendix-D.1 + */ + const bidirectional_r_al = [ + 0x05be, + 0x05be, + 0x05c0, + 0x05c0, + 0x05c3, + 0x05c3, + 0x05d0, + 0x05ea, + 0x05f0, + 0x05f4, + 0x061b, + 0x061b, + 0x061f, + 0x061f, + 0x0621, + 0x063a, + 0x0640, + 0x064a, + 0x066d, + 0x066f, + 0x0671, + 0x06d5, + 0x06dd, + 0x06dd, + 0x06e5, + 0x06e6, + 0x06fa, + 0x06fe, + 0x0700, + 0x070d, + 0x0710, + 0x0710, + 0x0712, + 0x072c, + 0x0780, + 0x07a5, + 0x07b1, + 0x07b1, + 0x200f, + 0x200f, + 0xfb1d, + 0xfb1d, + 0xfb1f, + 0xfb28, + 0xfb2a, + 0xfb36, + 0xfb38, + 0xfb3c, + 0xfb3e, + 0xfb3e, + 0xfb40, + 0xfb41, + 0xfb43, + 0xfb44, + 0xfb46, + 0xfbb1, + 0xfbd3, + 0xfd3d, + 0xfd50, + 0xfd8f, + 0xfd92, + 0xfdc7, + 0xfdf0, + 0xfdfc, + 0xfe70, + 0xfe74, + 0xfe76, + 0xfefc + ]; + /* eslint-enable */ + + const isBidirectionalRAL = character => inRange(character, bidirectional_r_al); + + /* eslint-disable prettier/prettier */ + /** + * D.2 Characters with bidirectional property "L" + * @link https://tools.ietf.org/html/rfc3454#appendix-D.2 + */ + const bidirectional_l = [ + 0x0041, + 0x005a, + 0x0061, + 0x007a, + 0x00aa, + 0x00aa, + 0x00b5, + 0x00b5, + 0x00ba, + 0x00ba, + 0x00c0, + 0x00d6, + 0x00d8, + 0x00f6, + 0x00f8, + 0x0220, + 0x0222, + 0x0233, + 0x0250, + 0x02ad, + 0x02b0, + 0x02b8, + 0x02bb, + 0x02c1, + 0x02d0, + 0x02d1, + 0x02e0, + 0x02e4, + 0x02ee, + 0x02ee, + 0x037a, + 0x037a, + 0x0386, + 0x0386, + 0x0388, + 0x038a, + 0x038c, + 0x038c, + 0x038e, + 0x03a1, + 0x03a3, + 0x03ce, + 0x03d0, + 0x03f5, + 0x0400, + 0x0482, + 0x048a, + 0x04ce, + 0x04d0, + 0x04f5, + 0x04f8, + 0x04f9, + 0x0500, + 0x050f, + 0x0531, + 0x0556, + 0x0559, + 0x055f, + 0x0561, + 0x0587, + 0x0589, + 0x0589, + 0x0903, + 0x0903, + 0x0905, + 0x0939, + 0x093d, + 0x0940, + 0x0949, + 0x094c, + 0x0950, + 0x0950, + 0x0958, + 0x0961, + 0x0964, + 0x0970, + 0x0982, + 0x0983, + 0x0985, + 0x098c, + 0x098f, + 0x0990, + 0x0993, + 0x09a8, + 0x09aa, + 0x09b0, + 0x09b2, + 0x09b2, + 0x09b6, + 0x09b9, + 0x09be, + 0x09c0, + 0x09c7, + 0x09c8, + 0x09cb, + 0x09cc, + 0x09d7, + 0x09d7, + 0x09dc, + 0x09dd, + 0x09df, + 0x09e1, + 0x09e6, + 0x09f1, + 0x09f4, + 0x09fa, + 0x0a05, + 0x0a0a, + 0x0a0f, + 0x0a10, + 0x0a13, + 0x0a28, + 0x0a2a, + 0x0a30, + 0x0a32, + 0x0a33, + 0x0a35, + 0x0a36, + 0x0a38, + 0x0a39, + 0x0a3e, + 0x0a40, + 0x0a59, + 0x0a5c, + 0x0a5e, + 0x0a5e, + 0x0a66, + 0x0a6f, + 0x0a72, + 0x0a74, + 0x0a83, + 0x0a83, + 0x0a85, + 0x0a8b, + 0x0a8d, + 0x0a8d, + 0x0a8f, + 0x0a91, + 0x0a93, + 0x0aa8, + 0x0aaa, + 0x0ab0, + 0x0ab2, + 0x0ab3, + 0x0ab5, + 0x0ab9, + 0x0abd, + 0x0ac0, + 0x0ac9, + 0x0ac9, + 0x0acb, + 0x0acc, + 0x0ad0, + 0x0ad0, + 0x0ae0, + 0x0ae0, + 0x0ae6, + 0x0aef, + 0x0b02, + 0x0b03, + 0x0b05, + 0x0b0c, + 0x0b0f, + 0x0b10, + 0x0b13, + 0x0b28, + 0x0b2a, + 0x0b30, + 0x0b32, + 0x0b33, + 0x0b36, + 0x0b39, + 0x0b3d, + 0x0b3e, + 0x0b40, + 0x0b40, + 0x0b47, + 0x0b48, + 0x0b4b, + 0x0b4c, + 0x0b57, + 0x0b57, + 0x0b5c, + 0x0b5d, + 0x0b5f, + 0x0b61, + 0x0b66, + 0x0b70, + 0x0b83, + 0x0b83, + 0x0b85, + 0x0b8a, + 0x0b8e, + 0x0b90, + 0x0b92, + 0x0b95, + 0x0b99, + 0x0b9a, + 0x0b9c, + 0x0b9c, + 0x0b9e, + 0x0b9f, + 0x0ba3, + 0x0ba4, + 0x0ba8, + 0x0baa, + 0x0bae, + 0x0bb5, + 0x0bb7, + 0x0bb9, + 0x0bbe, + 0x0bbf, + 0x0bc1, + 0x0bc2, + 0x0bc6, + 0x0bc8, + 0x0bca, + 0x0bcc, + 0x0bd7, + 0x0bd7, + 0x0be7, + 0x0bf2, + 0x0c01, + 0x0c03, + 0x0c05, + 0x0c0c, + 0x0c0e, + 0x0c10, + 0x0c12, + 0x0c28, + 0x0c2a, + 0x0c33, + 0x0c35, + 0x0c39, + 0x0c41, + 0x0c44, + 0x0c60, + 0x0c61, + 0x0c66, + 0x0c6f, + 0x0c82, + 0x0c83, + 0x0c85, + 0x0c8c, + 0x0c8e, + 0x0c90, + 0x0c92, + 0x0ca8, + 0x0caa, + 0x0cb3, + 0x0cb5, + 0x0cb9, + 0x0cbe, + 0x0cbe, + 0x0cc0, + 0x0cc4, + 0x0cc7, + 0x0cc8, + 0x0cca, + 0x0ccb, + 0x0cd5, + 0x0cd6, + 0x0cde, + 0x0cde, + 0x0ce0, + 0x0ce1, + 0x0ce6, + 0x0cef, + 0x0d02, + 0x0d03, + 0x0d05, + 0x0d0c, + 0x0d0e, + 0x0d10, + 0x0d12, + 0x0d28, + 0x0d2a, + 0x0d39, + 0x0d3e, + 0x0d40, + 0x0d46, + 0x0d48, + 0x0d4a, + 0x0d4c, + 0x0d57, + 0x0d57, + 0x0d60, + 0x0d61, + 0x0d66, + 0x0d6f, + 0x0d82, + 0x0d83, + 0x0d85, + 0x0d96, + 0x0d9a, + 0x0db1, + 0x0db3, + 0x0dbb, + 0x0dbd, + 0x0dbd, + 0x0dc0, + 0x0dc6, + 0x0dcf, + 0x0dd1, + 0x0dd8, + 0x0ddf, + 0x0df2, + 0x0df4, + 0x0e01, + 0x0e30, + 0x0e32, + 0x0e33, + 0x0e40, + 0x0e46, + 0x0e4f, + 0x0e5b, + 0x0e81, + 0x0e82, + 0x0e84, + 0x0e84, + 0x0e87, + 0x0e88, + 0x0e8a, + 0x0e8a, + 0x0e8d, + 0x0e8d, + 0x0e94, + 0x0e97, + 0x0e99, + 0x0e9f, + 0x0ea1, + 0x0ea3, + 0x0ea5, + 0x0ea5, + 0x0ea7, + 0x0ea7, + 0x0eaa, + 0x0eab, + 0x0ead, + 0x0eb0, + 0x0eb2, + 0x0eb3, + 0x0ebd, + 0x0ebd, + 0x0ec0, + 0x0ec4, + 0x0ec6, + 0x0ec6, + 0x0ed0, + 0x0ed9, + 0x0edc, + 0x0edd, + 0x0f00, + 0x0f17, + 0x0f1a, + 0x0f34, + 0x0f36, + 0x0f36, + 0x0f38, + 0x0f38, + 0x0f3e, + 0x0f47, + 0x0f49, + 0x0f6a, + 0x0f7f, + 0x0f7f, + 0x0f85, + 0x0f85, + 0x0f88, + 0x0f8b, + 0x0fbe, + 0x0fc5, + 0x0fc7, + 0x0fcc, + 0x0fcf, + 0x0fcf, + 0x1000, + 0x1021, + 0x1023, + 0x1027, + 0x1029, + 0x102a, + 0x102c, + 0x102c, + 0x1031, + 0x1031, + 0x1038, + 0x1038, + 0x1040, + 0x1057, + 0x10a0, + 0x10c5, + 0x10d0, + 0x10f8, + 0x10fb, + 0x10fb, + 0x1100, + 0x1159, + 0x115f, + 0x11a2, + 0x11a8, + 0x11f9, + 0x1200, + 0x1206, + 0x1208, + 0x1246, + 0x1248, + 0x1248, + 0x124a, + 0x124d, + 0x1250, + 0x1256, + 0x1258, + 0x1258, + 0x125a, + 0x125d, + 0x1260, + 0x1286, + 0x1288, + 0x1288, + 0x128a, + 0x128d, + 0x1290, + 0x12ae, + 0x12b0, + 0x12b0, + 0x12b2, + 0x12b5, + 0x12b8, + 0x12be, + 0x12c0, + 0x12c0, + 0x12c2, + 0x12c5, + 0x12c8, + 0x12ce, + 0x12d0, + 0x12d6, + 0x12d8, + 0x12ee, + 0x12f0, + 0x130e, + 0x1310, + 0x1310, + 0x1312, + 0x1315, + 0x1318, + 0x131e, + 0x1320, + 0x1346, + 0x1348, + 0x135a, + 0x1361, + 0x137c, + 0x13a0, + 0x13f4, + 0x1401, + 0x1676, + 0x1681, + 0x169a, + 0x16a0, + 0x16f0, + 0x1700, + 0x170c, + 0x170e, + 0x1711, + 0x1720, + 0x1731, + 0x1735, + 0x1736, + 0x1740, + 0x1751, + 0x1760, + 0x176c, + 0x176e, + 0x1770, + 0x1780, + 0x17b6, + 0x17be, + 0x17c5, + 0x17c7, + 0x17c8, + 0x17d4, + 0x17da, + 0x17dc, + 0x17dc, + 0x17e0, + 0x17e9, + 0x1810, + 0x1819, + 0x1820, + 0x1877, + 0x1880, + 0x18a8, + 0x1e00, + 0x1e9b, + 0x1ea0, + 0x1ef9, + 0x1f00, + 0x1f15, + 0x1f18, + 0x1f1d, + 0x1f20, + 0x1f45, + 0x1f48, + 0x1f4d, + 0x1f50, + 0x1f57, + 0x1f59, + 0x1f59, + 0x1f5b, + 0x1f5b, + 0x1f5d, + 0x1f5d, + 0x1f5f, + 0x1f7d, + 0x1f80, + 0x1fb4, + 0x1fb6, + 0x1fbc, + 0x1fbe, + 0x1fbe, + 0x1fc2, + 0x1fc4, + 0x1fc6, + 0x1fcc, + 0x1fd0, + 0x1fd3, + 0x1fd6, + 0x1fdb, + 0x1fe0, + 0x1fec, + 0x1ff2, + 0x1ff4, + 0x1ff6, + 0x1ffc, + 0x200e, + 0x200e, + 0x2071, + 0x2071, + 0x207f, + 0x207f, + 0x2102, + 0x2102, + 0x2107, + 0x2107, + 0x210a, + 0x2113, + 0x2115, + 0x2115, + 0x2119, + 0x211d, + 0x2124, + 0x2124, + 0x2126, + 0x2126, + 0x2128, + 0x2128, + 0x212a, + 0x212d, + 0x212f, + 0x2131, + 0x2133, + 0x2139, + 0x213d, + 0x213f, + 0x2145, + 0x2149, + 0x2160, + 0x2183, + 0x2336, + 0x237a, + 0x2395, + 0x2395, + 0x249c, + 0x24e9, + 0x3005, + 0x3007, + 0x3021, + 0x3029, + 0x3031, + 0x3035, + 0x3038, + 0x303c, + 0x3041, + 0x3096, + 0x309d, + 0x309f, + 0x30a1, + 0x30fa, + 0x30fc, + 0x30ff, + 0x3105, + 0x312c, + 0x3131, + 0x318e, + 0x3190, + 0x31b7, + 0x31f0, + 0x321c, + 0x3220, + 0x3243, + 0x3260, + 0x327b, + 0x327f, + 0x32b0, + 0x32c0, + 0x32cb, + 0x32d0, + 0x32fe, + 0x3300, + 0x3376, + 0x337b, + 0x33dd, + 0x33e0, + 0x33fe, + 0x3400, + 0x4db5, + 0x4e00, + 0x9fa5, + 0xa000, + 0xa48c, + 0xac00, + 0xd7a3, + 0xd800, + 0xfa2d, + 0xfa30, + 0xfa6a, + 0xfb00, + 0xfb06, + 0xfb13, + 0xfb17, + 0xff21, + 0xff3a, + 0xff41, + 0xff5a, + 0xff66, + 0xffbe, + 0xffc2, + 0xffc7, + 0xffca, + 0xffcf, + 0xffd2, + 0xffd7, + 0xffda, + 0xffdc, + 0x10300, + 0x1031e, + 0x10320, + 0x10323, + 0x10330, + 0x1034a, + 0x10400, + 0x10425, + 0x10428, + 0x1044d, + 0x1d000, + 0x1d0f5, + 0x1d100, + 0x1d126, + 0x1d12a, + 0x1d166, + 0x1d16a, + 0x1d172, + 0x1d183, + 0x1d184, + 0x1d18c, + 0x1d1a9, + 0x1d1ae, + 0x1d1dd, + 0x1d400, + 0x1d454, + 0x1d456, + 0x1d49c, + 0x1d49e, + 0x1d49f, + 0x1d4a2, + 0x1d4a2, + 0x1d4a5, + 0x1d4a6, + 0x1d4a9, + 0x1d4ac, + 0x1d4ae, + 0x1d4b9, + 0x1d4bb, + 0x1d4bb, + 0x1d4bd, + 0x1d4c0, + 0x1d4c2, + 0x1d4c3, + 0x1d4c5, + 0x1d505, + 0x1d507, + 0x1d50a, + 0x1d50d, + 0x1d514, + 0x1d516, + 0x1d51c, + 0x1d51e, + 0x1d539, + 0x1d53b, + 0x1d53e, + 0x1d540, + 0x1d544, + 0x1d546, + 0x1d546, + 0x1d54a, + 0x1d550, + 0x1d552, + 0x1d6a3, + 0x1d6a8, + 0x1d7c9, + 0x20000, + 0x2a6d6, + 0x2f800, + 0x2fa1d, + 0xf0000, + 0xffffd, + 0x100000, + 0x10fffd + ]; + /* eslint-enable */ + const isBidirectionalL = character => inRange(character, bidirectional_l); - // 2.1. Mapping - - /** - * non-ASCII space characters [StringPrep, C.1.2] that can be - * mapped to SPACE (U+0020) - */ - const mapping2space = isNonASCIISpaceCharacter; - - /** - * the "commonly mapped to nothing" characters [StringPrep, B.1] - * that can be mapped to nothing. - */ - const mapping2nothing = isCommonlyMappedToNothing; - - // utils - const getCodePoint = character => character.codePointAt(0); - const first = x => x[0]; - const last = x => x[x.length - 1]; - - /** - * Convert provided string into an array of Unicode Code Points. - * Based on https://stackoverflow.com/a/21409165/1556249 - * and https://www.npmjs.com/package/code-point-at. - * @param {string} input - * @returns {number[]} - */ - function toCodePoints(input) { - const codepoints = []; - const size = input.length; - - for (let i = 0; i < size; i += 1) { - const before = input.charCodeAt(i); - - if (before >= 0xd800 && before <= 0xdbff && size > i + 1) { - const next = input.charCodeAt(i + 1); - - if (next >= 0xdc00 && next <= 0xdfff) { - codepoints.push((before - 0xd800) * 0x400 + next - 0xdc00 + 0x10000); - i += 1; - continue; - } - } - - codepoints.push(before); - } - - return codepoints; + // 2.1. Mapping + + /** + * non-ASCII space characters [StringPrep, C.1.2] that can be + * mapped to SPACE (U+0020) + */ + const mapping2space = isNonASCIISpaceCharacter; + + /** + * the "commonly mapped to nothing" characters [StringPrep, B.1] + * that can be mapped to nothing. + */ + const mapping2nothing = isCommonlyMappedToNothing; + + // utils + const getCodePoint = character => character.codePointAt(0); + const first = x => x[0]; + const last = x => x[x.length - 1]; + + /** + * Convert provided string into an array of Unicode Code Points. + * Based on https://stackoverflow.com/a/21409165/1556249 + * and https://www.npmjs.com/package/code-point-at. + * @param {string} input + * @returns {number[]} + */ + function toCodePoints(input) { + const codepoints = []; + const size = input.length; + + for (let i = 0; i < size; i += 1) { + const before = input.charCodeAt(i); + + if (before >= 0xd800 && before <= 0xdbff && size > i + 1) { + const next = input.charCodeAt(i + 1); + + if (next >= 0xdc00 && next <= 0xdfff) { + codepoints.push((before - 0xd800) * 0x400 + next - 0xdc00 + 0x10000); + i += 1; + continue; + } + } + + codepoints.push(before); + } + + return codepoints; + } + + /** + * SASLprep. + * @param {string} input + * @param {Object} opts + * @param {boolean} opts.allowUnassigned + * @returns {string} + */ + function saslprep(input, opts = {}) { + if (typeof input !== 'string') { + throw new TypeError('Expected string.'); + } + + if (input.length === 0) { + return ''; + } + + // 1. Map + const mapped_input = toCodePoints(input) + // 1.1 mapping to space + .map(character => (mapping2space(character) ? 0x20 : character)) + // 1.2 mapping to nothing + .filter(character => !mapping2nothing(character)); + + // 2. Normalize + const normalized_input = String.fromCodePoint + .apply(null, mapped_input) + .normalize('NFKC'); + + const normalized_map = toCodePoints(normalized_input); + + // 3. Prohibit + const hasProhibited = normalized_map.some(isProhibitedCharacter); + + if (hasProhibited) { + throw new Error( + 'Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3' + ); + } + + // Unassigned Code Points + if (opts.allowUnassigned !== true) { + const hasUnassigned = normalized_map.some(isUnassignedCodePoint); + + if (hasUnassigned) { + throw new Error( + 'Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5' + ); + } + } + + // 4. check bidi + + const hasBidiRAL = normalized_map.some(isBidirectionalRAL); + + const hasBidiL = normalized_map.some(isBidirectionalL); + + // 4.1 If a string contains any RandALCat character, the string MUST NOT + // contain any LCat character. + if (hasBidiRAL && hasBidiL) { + throw new Error( + 'String must not contain RandALCat and LCat at the same time,' + + ' see https://tools.ietf.org/html/rfc3454#section-6' + ); + } + + /** + * 4.2 If a string contains any RandALCat character, a RandALCat + * character MUST be the first character of the string, and a + * RandALCat character MUST be the last character of the string. + */ + + const isFirstBidiRAL = isBidirectionalRAL( + getCodePoint(first(normalized_input)) + ); + const isLastBidiRAL = isBidirectionalRAL( + getCodePoint(last(normalized_input)) + ); + + if (hasBidiRAL && !(isFirstBidiRAL && isLastBidiRAL)) { + throw new Error( + 'Bidirectional RandALCat character must be the first and the last' + + ' character of the string, see https://tools.ietf.org/html/rfc3454#section-6' + ); + } + + return normalized_input; } - /** - * SASLprep. - * @param {string} input - * @param {Object} opts - * @param {boolean} opts.allowUnassigned - * @returns {string} - */ - function saslprep(input, opts = {}) { - if (typeof input !== 'string') { - throw new TypeError('Expected string.'); - } - - if (input.length === 0) { - return ''; - } - - // 1. Map - const mapped_input = toCodePoints(input) - // 1.1 mapping to space - .map(character => (mapping2space(character) ? 0x20 : character)) - // 1.2 mapping to nothing - .filter(character => !mapping2nothing(character)); - - // 2. Normalize - const normalized_input = String.fromCodePoint - .apply(null, mapped_input) - .normalize('NFKC'); - - const normalized_map = toCodePoints(normalized_input); - - // 3. Prohibit - const hasProhibited = normalized_map.some(isProhibitedCharacter); - - if (hasProhibited) { - throw new Error( - 'Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3' - ); - } - - // Unassigned Code Points - if (opts.allowUnassigned !== true) { - const hasUnassigned = normalized_map.some(isUnassignedCodePoint); - - if (hasUnassigned) { - throw new Error( - 'Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5' - ); - } - } - - // 4. check bidi - - const hasBidiRAL = normalized_map.some(isBidirectionalRAL); - - const hasBidiL = normalized_map.some(isBidirectionalL); - - // 4.1 If a string contains any RandALCat character, the string MUST NOT - // contain any LCat character. - if (hasBidiRAL && hasBidiL) { - throw new Error( - 'String must not contain RandALCat and LCat at the same time,' + - ' see https://tools.ietf.org/html/rfc3454#section-6' - ); - } - - /** - * 4.2 If a string contains any RandALCat character, a RandALCat - * character MUST be the first character of the string, and a - * RandALCat character MUST be the last character of the string. - */ - - const isFirstBidiRAL = isBidirectionalRAL( - getCodePoint(first(normalized_input)) - ); - const isLastBidiRAL = isBidirectionalRAL( - getCodePoint(last(normalized_input)) - ); - - if (hasBidiRAL && !(isFirstBidiRAL && isLastBidiRAL)) { - throw new Error( - 'Bidirectional RandALCat character must be the first and the last' + - ' character of the string, see https://tools.ietf.org/html/rfc3454#section-6' - ); - } - - return normalized_input; - } - - class PDFSecurity { - static generateFileID(info = {}) { - let infoStr = `${info.CreationDate.getTime()}\n`; - - for (let key in info) { - if (!info.hasOwnProperty(key)) { - continue; - } - infoStr += `${key}: ${info[key]}\n`; - } - - return wordArrayToBuffer(cryptoJs.MD5(infoStr)); - } - - static generateRandomWordArray(bytes) { - return cryptoJs.lib.WordArray.random(bytes); - } - - static create(document, options = {}) { - if (!options.ownerPassword && !options.userPassword) { - return null; - } - return new PDFSecurity(document, options); - } - - constructor(document, options = {}) { - if (!options.ownerPassword && !options.userPassword) { - throw new Error('None of owner password and user password is defined.'); - } - - this.document = document; - this._setupEncryption(options); - } - - _setupEncryption(options) { - switch (options.pdfVersion) { - case '1.4': - case '1.5': - this.version = 2; - break; - case '1.6': - case '1.7': - this.version = 4; - break; - case '1.7ext3': - this.version = 5; - break; - default: - this.version = 1; - break; - } - - const encDict = { - Filter: 'Standard' - }; - - switch (this.version) { - case 1: - case 2: - case 4: - this._setupEncryptionV1V2V4(this.version, encDict, options); - break; - case 5: - this._setupEncryptionV5(encDict, options); - break; - } - - this.dictionary = this.document.ref(encDict); - } - - _setupEncryptionV1V2V4(v, encDict, options) { - let r, permissions; - switch (v) { - case 1: - r = 2; - this.keyBits = 40; - permissions = getPermissionsR2(options.permissions); - break; - case 2: - r = 3; - this.keyBits = 128; - permissions = getPermissionsR3(options.permissions); - break; - case 4: - r = 4; - this.keyBits = 128; - permissions = getPermissionsR3(options.permissions); - break; - } - - const paddedUserPassword = processPasswordR2R3R4(options.userPassword); - const paddedOwnerPassword = options.ownerPassword - ? processPasswordR2R3R4(options.ownerPassword) - : paddedUserPassword; - - const ownerPasswordEntry = getOwnerPasswordR2R3R4( - r, - this.keyBits, - paddedUserPassword, - paddedOwnerPassword - ); - this.encryptionKey = getEncryptionKeyR2R3R4( - r, - this.keyBits, - this.document._id, - paddedUserPassword, - ownerPasswordEntry, - permissions - ); - let userPasswordEntry; - if (r === 2) { - userPasswordEntry = getUserPasswordR2(this.encryptionKey); - } else { - userPasswordEntry = getUserPasswordR3R4( - this.document._id, - this.encryptionKey - ); - } - - encDict.V = v; - if (v >= 2) { - encDict.Length = this.keyBits; - } - if (v === 4) { - encDict.CF = { - StdCF: { - AuthEvent: 'DocOpen', - CFM: 'AESV2', - Length: this.keyBits / 8 - } - }; - encDict.StmF = 'StdCF'; - encDict.StrF = 'StdCF'; - } - encDict.R = r; - encDict.O = wordArrayToBuffer(ownerPasswordEntry); - encDict.U = wordArrayToBuffer(userPasswordEntry); - encDict.P = permissions; - } - - _setupEncryptionV5(encDict, options) { - this.keyBits = 256; - const permissions = getPermissionsR3(options); - - const processedUserPassword = processPasswordR5(options.userPassword); - const processedOwnerPassword = options.ownerPassword - ? processPasswordR5(options.ownerPassword) - : processedUserPassword; - - this.encryptionKey = getEncryptionKeyR5( - PDFSecurity.generateRandomWordArray - ); - const userPasswordEntry = getUserPasswordR5( - processedUserPassword, - PDFSecurity.generateRandomWordArray - ); - const userKeySalt = cryptoJs.lib.WordArray.create( - userPasswordEntry.words.slice(10, 12), - 8 - ); - const userEncryptionKeyEntry = getUserEncryptionKeyR5( - processedUserPassword, - userKeySalt, - this.encryptionKey - ); - const ownerPasswordEntry = getOwnerPasswordR5( - processedOwnerPassword, - userPasswordEntry, - PDFSecurity.generateRandomWordArray - ); - const ownerKeySalt = cryptoJs.lib.WordArray.create( - ownerPasswordEntry.words.slice(10, 12), - 8 - ); - const ownerEncryptionKeyEntry = getOwnerEncryptionKeyR5( - processedOwnerPassword, - ownerKeySalt, - userPasswordEntry, - this.encryptionKey - ); - const permsEntry = getEncryptedPermissionsR5( - permissions, - this.encryptionKey, - PDFSecurity.generateRandomWordArray - ); - - encDict.V = 5; - encDict.Length = this.keyBits; - encDict.CF = { - StdCF: { - AuthEvent: 'DocOpen', - CFM: 'AESV3', - Length: this.keyBits / 8 - } - }; - encDict.StmF = 'StdCF'; - encDict.StrF = 'StdCF'; - encDict.R = 5; - encDict.O = wordArrayToBuffer(ownerPasswordEntry); - encDict.OE = wordArrayToBuffer(ownerEncryptionKeyEntry); - encDict.U = wordArrayToBuffer(userPasswordEntry); - encDict.UE = wordArrayToBuffer(userEncryptionKeyEntry); - encDict.P = permissions; - encDict.Perms = wordArrayToBuffer(permsEntry); - } - - getEncryptFn(obj, gen) { - let digest; - if (this.version < 5) { - digest = this.encryptionKey - .clone() - .concat( - cryptoJs.lib.WordArray.create( - [ - ((obj & 0xff) << 24) | - ((obj & 0xff00) << 8) | - ((obj >> 8) & 0xff00) | - (gen & 0xff), - (gen & 0xff00) << 16 - ], - 5 - ) - ); - } - - if (this.version === 1 || this.version === 2) { - let key = cryptoJs.MD5(digest); - key.sigBytes = Math.min(16, this.keyBits / 8 + 5); - return buffer => - wordArrayToBuffer( - cryptoJs.RC4.encrypt(cryptoJs.lib.WordArray.create(buffer), key) - .ciphertext - ); - } - - let key; - if (this.version === 4) { - key = cryptoJs.MD5( - digest.concat(cryptoJs.lib.WordArray.create([0x73416c54], 4)) - ); - } else { - key = this.encryptionKey; - } - - const iv = PDFSecurity.generateRandomWordArray(16); - const options = { - mode: cryptoJs.mode.CBC, - padding: cryptoJs.pad.Pkcs7, - iv - }; - - return buffer => - wordArrayToBuffer( - iv - .clone() - .concat( - cryptoJs.AES.encrypt( - cryptoJs.lib.WordArray.create(buffer), - key, - options - ).ciphertext - ) - ); - } - - end() { - this.dictionary.end(); - } - } - - function getPermissionsR2(permissionObject = {}) { - let permissions = 0xffffffc0 >> 0; - if (permissionObject.printing) { - permissions |= 0b000000000100; - } - if (permissionObject.modifying) { - permissions |= 0b000000001000; - } - if (permissionObject.copying) { - permissions |= 0b000000010000; - } - if (permissionObject.annotating) { - permissions |= 0b000000100000; - } - return permissions; - } - - function getPermissionsR3(permissionObject = {}) { - let permissions = 0xfffff0c0 >> 0; - if (permissionObject.printing === 'lowResolution') { - permissions |= 0b000000000100; - } - if (permissionObject.printing === 'highResolution') { - permissions |= 0b100000000100; - } - if (permissionObject.modifying) { - permissions |= 0b000000001000; - } - if (permissionObject.copying) { - permissions |= 0b000000010000; - } - if (permissionObject.annotating) { - permissions |= 0b000000100000; - } - if (permissionObject.fillingForms) { - permissions |= 0b000100000000; - } - if (permissionObject.contentAccessibility) { - permissions |= 0b001000000000; - } - if (permissionObject.documentAssembly) { - permissions |= 0b010000000000; - } - return permissions; - } - - function getUserPasswordR2(encryptionKey) { - return cryptoJs.RC4.encrypt(processPasswordR2R3R4(), encryptionKey) - .ciphertext; - } - - function getUserPasswordR3R4(documentId, encryptionKey) { - const key = encryptionKey.clone(); - let cipher = cryptoJs.MD5( - processPasswordR2R3R4().concat(cryptoJs.lib.WordArray.create(documentId)) - ); - for (let i = 0; i < 20; i++) { - const xorRound = Math.ceil(key.sigBytes / 4); - for (let j = 0; j < xorRound; j++) { - key.words[j] = - encryptionKey.words[j] ^ (i | (i << 8) | (i << 16) | (i << 24)); - } - cipher = cryptoJs.RC4.encrypt(cipher, key).ciphertext; - } - return cipher.concat(cryptoJs.lib.WordArray.create(null, 16)); - } - - function getOwnerPasswordR2R3R4( - r, - keyBits, - paddedUserPassword, - paddedOwnerPassword - ) { - let digest = paddedOwnerPassword; - let round = r >= 3 ? 51 : 1; - for (let i = 0; i < round; i++) { - digest = cryptoJs.MD5(digest); - } - - const key = digest.clone(); - key.sigBytes = keyBits / 8; - let cipher = paddedUserPassword; - round = r >= 3 ? 20 : 1; - for (let i = 0; i < round; i++) { - const xorRound = Math.ceil(key.sigBytes / 4); - for (let j = 0; j < xorRound; j++) { - key.words[j] = digest.words[j] ^ (i | (i << 8) | (i << 16) | (i << 24)); - } - cipher = cryptoJs.RC4.encrypt(cipher, key).ciphertext; - } - return cipher; - } - - function getEncryptionKeyR2R3R4( - r, - keyBits, - documentId, - paddedUserPassword, - ownerPasswordEntry, - permissions - ) { - let key = paddedUserPassword - .clone() - .concat(ownerPasswordEntry) - .concat(cryptoJs.lib.WordArray.create([lsbFirstWord(permissions)], 4)) - .concat(cryptoJs.lib.WordArray.create(documentId)); - const round = r >= 3 ? 51 : 1; - for (let i = 0; i < round; i++) { - key = cryptoJs.MD5(key); - key.sigBytes = keyBits / 8; - } - return key; - } - - function getUserPasswordR5(processedUserPassword, generateRandomWordArray) { - const validationSalt = generateRandomWordArray(8); - const keySalt = generateRandomWordArray(8); - return cryptoJs.SHA256(processedUserPassword.clone().concat(validationSalt)) - .concat(validationSalt) - .concat(keySalt); - } - - function getUserEncryptionKeyR5( - processedUserPassword, - userKeySalt, - encryptionKey - ) { - const key = cryptoJs.SHA256( - processedUserPassword.clone().concat(userKeySalt) - ); - const options = { - mode: cryptoJs.mode.CBC, - padding: cryptoJs.pad.NoPadding, - iv: cryptoJs.lib.WordArray.create(null, 16) - }; - return cryptoJs.AES.encrypt(encryptionKey, key, options).ciphertext; - } - - function getOwnerPasswordR5( - processedOwnerPassword, - userPasswordEntry, - generateRandomWordArray - ) { - const validationSalt = generateRandomWordArray(8); - const keySalt = generateRandomWordArray(8); - return cryptoJs.SHA256( - processedOwnerPassword - .clone() - .concat(validationSalt) - .concat(userPasswordEntry) - ) - .concat(validationSalt) - .concat(keySalt); - } - - function getOwnerEncryptionKeyR5( - processedOwnerPassword, - ownerKeySalt, - userPasswordEntry, - encryptionKey - ) { - const key = cryptoJs.SHA256( - processedOwnerPassword - .clone() - .concat(ownerKeySalt) - .concat(userPasswordEntry) - ); - const options = { - mode: cryptoJs.mode.CBC, - padding: cryptoJs.pad.NoPadding, - iv: cryptoJs.lib.WordArray.create(null, 16) - }; - return cryptoJs.AES.encrypt(encryptionKey, key, options).ciphertext; - } - - function getEncryptionKeyR5(generateRandomWordArray) { - return generateRandomWordArray(32); - } - - function getEncryptedPermissionsR5( - permissions, - encryptionKey, - generateRandomWordArray - ) { - const cipher = cryptoJs.lib.WordArray.create( - [lsbFirstWord(permissions), 0xffffffff, 0x54616462], - 12 - ).concat(generateRandomWordArray(4)); - const options = { - mode: cryptoJs.mode.ECB, - padding: cryptoJs.pad.NoPadding - }; - return cryptoJs.AES.encrypt(cipher, encryptionKey, options).ciphertext; - } - - function processPasswordR2R3R4(password = '') { - const out = new Buffer(32); - const length = password.length; - let index = 0; - while (index < length && index < 32) { - const code = password.charCodeAt(index); - if (code > 0xff) { - throw new Error('Password contains one or more invalid characters.'); - } - out[index] = code; - index++; - } - while (index < 32) { - out[index] = PASSWORD_PADDING[index - length]; - index++; - } - return cryptoJs.lib.WordArray.create(out); - } - - function processPasswordR5(password = '') { - password = unescape(encodeURIComponent(saslprep(password))); - const length = Math.min(127, password.length); - const out = new Buffer(length); - - for (let i = 0; i < length; i++) { - out[i] = password.charCodeAt(i); - } - - return cryptoJs.lib.WordArray.create(out); - } - - function lsbFirstWord(data) { - return ( - ((data & 0xff) << 24) | - ((data & 0xff00) << 8) | - ((data >> 8) & 0xff00) | - ((data >> 24) & 0xff) - ); - } - - function wordArrayToBuffer(wordArray) { - const byteArray = []; - for (let i = 0; i < wordArray.sigBytes; i++) { - byteArray.push( - (wordArray.words[Math.floor(i / 4)] >> (8 * (3 - (i % 4)))) & 0xff - ); - } - return Buffer.from(byteArray); - } - - const PASSWORD_PADDING = [ - 0x28, - 0xbf, - 0x4e, - 0x5e, - 0x4e, - 0x75, - 0x8a, - 0x41, - 0x64, - 0x00, - 0x4e, - 0x56, - 0xff, - 0xfa, - 0x01, - 0x08, - 0x2e, - 0x2e, - 0x00, - 0xb6, - 0xd0, - 0x68, - 0x3e, - 0x80, - 0x2f, - 0x0c, - 0xa9, - 0xfe, - 0x64, - 0x53, - 0x69, - 0x7a + class PDFSecurity { + static generateFileID(info = {}) { + let infoStr = `${info.CreationDate.getTime()}\n`; + + for (let key in info) { + if (!info.hasOwnProperty(key)) { + continue; + } + infoStr += `${key}: ${info[key]}\n`; + } + + return wordArrayToBuffer(C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.MD5(infoStr)); + } + + static generateRandomWordArray(bytes) { + return C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.random(bytes); + } + + static create(document, options = {}) { + if (!options.ownerPassword && !options.userPassword) { + return null; + } + return new PDFSecurity(document, options); + } + + constructor(document, options = {}) { + if (!options.ownerPassword && !options.userPassword) { + throw new Error('None of owner password and user password is defined.'); + } + + this.document = document; + this._setupEncryption(options); + } + + _setupEncryption(options) { + switch (options.pdfVersion) { + case '1.4': + case '1.5': + this.version = 2; + break; + case '1.6': + case '1.7': + this.version = 4; + break; + case '1.7ext3': + this.version = 5; + break; + default: + this.version = 1; + break; + } + + const encDict = { + Filter: 'Standard' + }; + + switch (this.version) { + case 1: + case 2: + case 4: + this._setupEncryptionV1V2V4(this.version, encDict, options); + break; + case 5: + this._setupEncryptionV5(encDict, options); + break; + } + + this.dictionary = this.document.ref(encDict); + } + + _setupEncryptionV1V2V4(v, encDict, options) { + let r, permissions; + switch (v) { + case 1: + r = 2; + this.keyBits = 40; + permissions = getPermissionsR2(options.permissions); + break; + case 2: + r = 3; + this.keyBits = 128; + permissions = getPermissionsR3(options.permissions); + break; + case 4: + r = 4; + this.keyBits = 128; + permissions = getPermissionsR3(options.permissions); + break; + } + + const paddedUserPassword = processPasswordR2R3R4(options.userPassword); + const paddedOwnerPassword = options.ownerPassword + ? processPasswordR2R3R4(options.ownerPassword) + : paddedUserPassword; + + const ownerPasswordEntry = getOwnerPasswordR2R3R4( + r, + this.keyBits, + paddedUserPassword, + paddedOwnerPassword + ); + this.encryptionKey = getEncryptionKeyR2R3R4( + r, + this.keyBits, + this.document._id, + paddedUserPassword, + ownerPasswordEntry, + permissions + ); + let userPasswordEntry; + if (r === 2) { + userPasswordEntry = getUserPasswordR2(this.encryptionKey); + } else { + userPasswordEntry = getUserPasswordR3R4( + this.document._id, + this.encryptionKey + ); + } + + encDict.V = v; + if (v >= 2) { + encDict.Length = this.keyBits; + } + if (v === 4) { + encDict.CF = { + StdCF: { + AuthEvent: 'DocOpen', + CFM: 'AESV2', + Length: this.keyBits / 8 + } + }; + encDict.StmF = 'StdCF'; + encDict.StrF = 'StdCF'; + } + encDict.R = r; + encDict.O = wordArrayToBuffer(ownerPasswordEntry); + encDict.U = wordArrayToBuffer(userPasswordEntry); + encDict.P = permissions; + } + + _setupEncryptionV5(encDict, options) { + this.keyBits = 256; + const permissions = getPermissionsR3(options); + + const processedUserPassword = processPasswordR5(options.userPassword); + const processedOwnerPassword = options.ownerPassword + ? processPasswordR5(options.ownerPassword) + : processedUserPassword; + + this.encryptionKey = getEncryptionKeyR5( + PDFSecurity.generateRandomWordArray + ); + const userPasswordEntry = getUserPasswordR5( + processedUserPassword, + PDFSecurity.generateRandomWordArray + ); + const userKeySalt = C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create( + userPasswordEntry.words.slice(10, 12), + 8 + ); + const userEncryptionKeyEntry = getUserEncryptionKeyR5( + processedUserPassword, + userKeySalt, + this.encryptionKey + ); + const ownerPasswordEntry = getOwnerPasswordR5( + processedOwnerPassword, + userPasswordEntry, + PDFSecurity.generateRandomWordArray + ); + const ownerKeySalt = C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create( + ownerPasswordEntry.words.slice(10, 12), + 8 + ); + const ownerEncryptionKeyEntry = getOwnerEncryptionKeyR5( + processedOwnerPassword, + ownerKeySalt, + userPasswordEntry, + this.encryptionKey + ); + const permsEntry = getEncryptedPermissionsR5( + permissions, + this.encryptionKey, + PDFSecurity.generateRandomWordArray + ); + + encDict.V = 5; + encDict.Length = this.keyBits; + encDict.CF = { + StdCF: { + AuthEvent: 'DocOpen', + CFM: 'AESV3', + Length: this.keyBits / 8 + } + }; + encDict.StmF = 'StdCF'; + encDict.StrF = 'StdCF'; + encDict.R = 5; + encDict.O = wordArrayToBuffer(ownerPasswordEntry); + encDict.OE = wordArrayToBuffer(ownerEncryptionKeyEntry); + encDict.U = wordArrayToBuffer(userPasswordEntry); + encDict.UE = wordArrayToBuffer(userEncryptionKeyEntry); + encDict.P = permissions; + encDict.Perms = wordArrayToBuffer(permsEntry); + } + + getEncryptFn(obj, gen) { + let digest; + if (this.version < 5) { + digest = this.encryptionKey + .clone() + .concat( + C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create( + [ + ((obj & 0xff) << 24) | + ((obj & 0xff00) << 8) | + ((obj >> 8) & 0xff00) | + (gen & 0xff), + (gen & 0xff00) << 16 + ], + 5 + ) + ); + } + + if (this.version === 1 || this.version === 2) { + let key = C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.MD5(digest); + key.sigBytes = Math.min(16, this.keyBits / 8 + 5); + return buffer => + wordArrayToBuffer( + C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.RC4.encrypt(C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create(buffer), key) + .ciphertext + ); + } + + let key; + if (this.version === 4) { + key = C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.MD5( + digest.concat(C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create([0x73416c54], 4)) + ); + } else { + key = this.encryptionKey; + } + + const iv = PDFSecurity.generateRandomWordArray(16); + const options = { + mode: C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.mode.CBC, + padding: C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.pad.Pkcs7, + iv + }; + + return buffer => + wordArrayToBuffer( + iv + .clone() + .concat( + C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.AES.encrypt( + C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create(buffer), + key, + options + ).ciphertext + ) + ); + } + + end() { + this.dictionary.end(); + } + } + + function getPermissionsR2(permissionObject = {}) { + let permissions = 0xffffffc0 >> 0; + if (permissionObject.printing) { + permissions |= 0b000000000100; + } + if (permissionObject.modifying) { + permissions |= 0b000000001000; + } + if (permissionObject.copying) { + permissions |= 0b000000010000; + } + if (permissionObject.annotating) { + permissions |= 0b000000100000; + } + return permissions; + } + + function getPermissionsR3(permissionObject = {}) { + let permissions = 0xfffff0c0 >> 0; + if (permissionObject.printing === 'lowResolution') { + permissions |= 0b000000000100; + } + if (permissionObject.printing === 'highResolution') { + permissions |= 0b100000000100; + } + if (permissionObject.modifying) { + permissions |= 0b000000001000; + } + if (permissionObject.copying) { + permissions |= 0b000000010000; + } + if (permissionObject.annotating) { + permissions |= 0b000000100000; + } + if (permissionObject.fillingForms) { + permissions |= 0b000100000000; + } + if (permissionObject.contentAccessibility) { + permissions |= 0b001000000000; + } + if (permissionObject.documentAssembly) { + permissions |= 0b010000000000; + } + return permissions; + } + + function getUserPasswordR2(encryptionKey) { + return C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.RC4.encrypt(processPasswordR2R3R4(), encryptionKey) + .ciphertext; + } + + function getUserPasswordR3R4(documentId, encryptionKey) { + const key = encryptionKey.clone(); + let cipher = C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.MD5( + processPasswordR2R3R4().concat(C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create(documentId)) + ); + for (let i = 0; i < 20; i++) { + const xorRound = Math.ceil(key.sigBytes / 4); + for (let j = 0; j < xorRound; j++) { + key.words[j] = + encryptionKey.words[j] ^ (i | (i << 8) | (i << 16) | (i << 24)); + } + cipher = C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.RC4.encrypt(cipher, key).ciphertext; + } + return cipher.concat(C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create(null, 16)); + } + + function getOwnerPasswordR2R3R4( + r, + keyBits, + paddedUserPassword, + paddedOwnerPassword + ) { + let digest = paddedOwnerPassword; + let round = r >= 3 ? 51 : 1; + for (let i = 0; i < round; i++) { + digest = C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.MD5(digest); + } + + const key = digest.clone(); + key.sigBytes = keyBits / 8; + let cipher = paddedUserPassword; + round = r >= 3 ? 20 : 1; + for (let i = 0; i < round; i++) { + const xorRound = Math.ceil(key.sigBytes / 4); + for (let j = 0; j < xorRound; j++) { + key.words[j] = digest.words[j] ^ (i | (i << 8) | (i << 16) | (i << 24)); + } + cipher = C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.RC4.encrypt(cipher, key).ciphertext; + } + return cipher; + } + + function getEncryptionKeyR2R3R4( + r, + keyBits, + documentId, + paddedUserPassword, + ownerPasswordEntry, + permissions + ) { + let key = paddedUserPassword + .clone() + .concat(ownerPasswordEntry) + .concat(C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create([lsbFirstWord(permissions)], 4)) + .concat(C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create(documentId)); + const round = r >= 3 ? 51 : 1; + for (let i = 0; i < round; i++) { + key = C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.MD5(key); + key.sigBytes = keyBits / 8; + } + return key; + } + + function getUserPasswordR5(processedUserPassword, generateRandomWordArray) { + const validationSalt = generateRandomWordArray(8); + const keySalt = generateRandomWordArray(8); + return C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.SHA256(processedUserPassword.clone().concat(validationSalt)) + .concat(validationSalt) + .concat(keySalt); + } + + function getUserEncryptionKeyR5( + processedUserPassword, + userKeySalt, + encryptionKey + ) { + const key = C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.SHA256( + processedUserPassword.clone().concat(userKeySalt) + ); + const options = { + mode: C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.mode.CBC, + padding: C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.pad.NoPadding, + iv: C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create(null, 16) + }; + return C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.AES.encrypt(encryptionKey, key, options).ciphertext; + } + + function getOwnerPasswordR5( + processedOwnerPassword, + userPasswordEntry, + generateRandomWordArray + ) { + const validationSalt = generateRandomWordArray(8); + const keySalt = generateRandomWordArray(8); + return C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.SHA256( + processedOwnerPassword + .clone() + .concat(validationSalt) + .concat(userPasswordEntry) + ) + .concat(validationSalt) + .concat(keySalt); + } + + function getOwnerEncryptionKeyR5( + processedOwnerPassword, + ownerKeySalt, + userPasswordEntry, + encryptionKey + ) { + const key = C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.SHA256( + processedOwnerPassword + .clone() + .concat(ownerKeySalt) + .concat(userPasswordEntry) + ); + const options = { + mode: C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.mode.CBC, + padding: C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.pad.NoPadding, + iv: C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create(null, 16) + }; + return C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.AES.encrypt(encryptionKey, key, options).ciphertext; + } + + function getEncryptionKeyR5(generateRandomWordArray) { + return generateRandomWordArray(32); + } + + function getEncryptedPermissionsR5( + permissions, + encryptionKey, + generateRandomWordArray + ) { + const cipher = C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create( + [lsbFirstWord(permissions), 0xffffffff, 0x54616462], + 12 + ).concat(generateRandomWordArray(4)); + const options = { + mode: C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.mode.ECB, + padding: C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.pad.NoPadding + }; + return C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.AES.encrypt(cipher, encryptionKey, options).ciphertext; + } + + function processPasswordR2R3R4(password = '') { + const out = new Buffer(32); + const length = password.length; + let index = 0; + while (index < length && index < 32) { + const code = password.charCodeAt(index); + if (code > 0xff) { + throw new Error('Password contains one or more invalid characters.'); + } + out[index] = code; + index++; + } + while (index < 32) { + out[index] = PASSWORD_PADDING[index - length]; + index++; + } + return C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create(out); + } + + function processPasswordR5(password = '') { + password = unescape(encodeURIComponent(saslprep(password))); + const length = Math.min(127, password.length); + const out = new Buffer(length); + + for (let i = 0; i < length; i++) { + out[i] = password.charCodeAt(i); + } + + return C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create(out); + } + + function lsbFirstWord(data) { + return ( + ((data & 0xff) << 24) | + ((data & 0xff00) << 8) | + ((data >> 8) & 0xff00) | + ((data >> 24) & 0xff) + ); + } + + function wordArrayToBuffer(wordArray) { + const byteArray = []; + for (let i = 0; i < wordArray.sigBytes; i++) { + byteArray.push( + (wordArray.words[Math.floor(i / 4)] >> (8 * (3 - (i % 4)))) & 0xff + ); + } + return Buffer.from(byteArray); + } + + const PASSWORD_PADDING = [ + 0x28, + 0xbf, + 0x4e, + 0x5e, + 0x4e, + 0x75, + 0x8a, + 0x41, + 0x64, + 0x00, + 0x4e, + 0x56, + 0xff, + 0xfa, + 0x01, + 0x08, + 0x2e, + 0x2e, + 0x00, + 0xb6, + 0xd0, + 0x68, + 0x3e, + 0x80, + 0x2f, + 0x0c, + 0xa9, + 0xfe, + 0x64, + 0x53, + 0x69, + 0x7a ]; - const { number } = PDFObject; - - class PDFGradient { - constructor(doc) { - this.doc = doc; - this.stops = []; - this.embedded = false; - this.transform = [1, 0, 0, 1, 0, 0]; - } - - stop(pos, color, opacity) { - if (opacity == null) { - opacity = 1; - } - color = this.doc._normalizeColor(color); - - if (this.stops.length === 0) { - if (color.length === 3) { - this._colorSpace = 'DeviceRGB'; - } else if (color.length === 4) { - this._colorSpace = 'DeviceCMYK'; - } else if (color.length === 1) { - this._colorSpace = 'DeviceGray'; - } else { - throw new Error('Unknown color space'); - } - } else if ( - (this._colorSpace === 'DeviceRGB' && color.length !== 3) || - (this._colorSpace === 'DeviceCMYK' && color.length !== 4) || - (this._colorSpace === 'DeviceGray' && color.length !== 1) - ) { - throw new Error('All gradient stops must use the same color space'); - } - - opacity = Math.max(0, Math.min(1, opacity)); - this.stops.push([pos, color, opacity]); - return this; - } - - setTransform(m11, m12, m21, m22, dx, dy) { - this.transform = [m11, m12, m21, m22, dx, dy]; - return this; - } - - embed(m) { - let fn; - const stopsLength = this.stops.length; - if (stopsLength === 0) { - return; - } - this.embedded = true; - this.matrix = m; - - // if the last stop comes before 100%, add a copy at 100% - const last = this.stops[stopsLength - 1]; - if (last[0] < 1) { - this.stops.push([1, last[1], last[2]]); - } - - const bounds = []; - const encode = []; - const stops = []; - - for (let i = 0; i < stopsLength - 1; i++) { - encode.push(0, 1); - if (i + 2 !== stopsLength) { - bounds.push(this.stops[i + 1][0]); - } - - fn = this.doc.ref({ - FunctionType: 2, - Domain: [0, 1], - C0: this.stops[i + 0][1], - C1: this.stops[i + 1][1], - N: 1 - }); - - stops.push(fn); - fn.end(); - } - - // if there are only two stops, we don't need a stitching function - if (stopsLength === 1) { - fn = stops[0]; - } else { - fn = this.doc.ref({ - FunctionType: 3, // stitching function - Domain: [0, 1], - Functions: stops, - Bounds: bounds, - Encode: encode - }); - - fn.end(); - } - - this.id = `Sh${++this.doc._gradCount}`; - - const shader = this.shader(fn); - shader.end(); - - const pattern = this.doc.ref({ - Type: 'Pattern', - PatternType: 2, - Shading: shader, - Matrix: this.matrix.map(number) - }); - - pattern.end(); - - if (this.stops.some(stop => stop[2] < 1)) { - let grad = this.opacityGradient(); - grad._colorSpace = 'DeviceGray'; - - for (let stop of this.stops) { - grad.stop(stop[0], [stop[2]]); - } - - grad = grad.embed(this.matrix); - - const pageBBox = [0, 0, this.doc.page.width, this.doc.page.height]; - - const form = this.doc.ref({ - Type: 'XObject', - Subtype: 'Form', - FormType: 1, - BBox: pageBBox, - Group: { - Type: 'Group', - S: 'Transparency', - CS: 'DeviceGray' - }, - Resources: { - ProcSet: ['PDF', 'Text', 'ImageB', 'ImageC', 'ImageI'], - Pattern: { - Sh1: grad - } - } - }); - - form.write('/Pattern cs /Sh1 scn'); - form.end(`${pageBBox.join(' ')} re f`); - - const gstate = this.doc.ref({ - Type: 'ExtGState', - SMask: { - Type: 'Mask', - S: 'Luminosity', - G: form - } - }); - - gstate.end(); - - const opacityPattern = this.doc.ref({ - Type: 'Pattern', - PatternType: 1, - PaintType: 1, - TilingType: 2, - BBox: pageBBox, - XStep: pageBBox[2], - YStep: pageBBox[3], - Resources: { - ProcSet: ['PDF', 'Text', 'ImageB', 'ImageC', 'ImageI'], - Pattern: { - Sh1: pattern - }, - ExtGState: { - Gs1: gstate - } - } - }); - - opacityPattern.write('/Gs1 gs /Pattern cs /Sh1 scn'); - opacityPattern.end(`${pageBBox.join(' ')} re f`); - - this.doc.page.patterns[this.id] = opacityPattern; - } else { - this.doc.page.patterns[this.id] = pattern; - } - - return pattern; - } - - apply(op) { - // apply gradient transform to existing document ctm - const [m0, m1, m2, m3, m4, m5] = this.doc._ctm; - const [m11, m12, m21, m22, dx, dy] = this.transform; - const m = [ - m0 * m11 + m2 * m12, - m1 * m11 + m3 * m12, - m0 * m21 + m2 * m22, - m1 * m21 + m3 * m22, - m0 * dx + m2 * dy + m4, - m1 * dx + m3 * dy + m5 - ]; - - if (!this.embedded || m.join(' ') !== this.matrix.join(' ')) { - this.embed(m); - } - return this.doc.addContent(`/${this.id} ${op}`); - } - } - - class PDFLinearGradient extends PDFGradient { - constructor(doc, x1, y1, x2, y2) { - super(doc); - this.x1 = x1; - this.y1 = y1; - this.x2 = x2; - this.y2 = y2; - } - - shader(fn) { - return this.doc.ref({ - ShadingType: 2, - ColorSpace: this._colorSpace, - Coords: [this.x1, this.y1, this.x2, this.y2], - Function: fn, - Extend: [true, true] - }); - } - - opacityGradient() { - return new PDFLinearGradient(this.doc, this.x1, this.y1, this.x2, this.y2); - } - } - - class PDFRadialGradient extends PDFGradient { - constructor(doc, x1, y1, r1, x2, y2, r2) { - super(doc); - this.doc = doc; - this.x1 = x1; - this.y1 = y1; - this.r1 = r1; - this.x2 = x2; - this.y2 = y2; - this.r2 = r2; - } - - shader(fn) { - return this.doc.ref({ - ShadingType: 3, - ColorSpace: this._colorSpace, - Coords: [this.x1, this.y1, this.r1, this.x2, this.y2, this.r2], - Function: fn, - Extend: [true, true] - }); - } - - opacityGradient() { - return new PDFRadialGradient( - this.doc, - this.x1, - this.y1, - this.r1, - this.x2, - this.y2, - this.r2 - ); - } - } - + const { number } = PDFObject; + + class PDFGradient { + constructor(doc) { + this.doc = doc; + this.stops = []; + this.embedded = false; + this.transform = [1, 0, 0, 1, 0, 0]; + } + + stop(pos, color, opacity) { + if (opacity == null) { + opacity = 1; + } + color = this.doc._normalizeColor(color); + + if (this.stops.length === 0) { + if (color.length === 3) { + this._colorSpace = 'DeviceRGB'; + } else if (color.length === 4) { + this._colorSpace = 'DeviceCMYK'; + } else if (color.length === 1) { + this._colorSpace = 'DeviceGray'; + } else { + throw new Error('Unknown color space'); + } + } else if ( + (this._colorSpace === 'DeviceRGB' && color.length !== 3) || + (this._colorSpace === 'DeviceCMYK' && color.length !== 4) || + (this._colorSpace === 'DeviceGray' && color.length !== 1) + ) { + throw new Error('All gradient stops must use the same color space'); + } + + opacity = Math.max(0, Math.min(1, opacity)); + this.stops.push([pos, color, opacity]); + return this; + } + + setTransform(m11, m12, m21, m22, dx, dy) { + this.transform = [m11, m12, m21, m22, dx, dy]; + return this; + } + + embed(m) { + let fn; + const stopsLength = this.stops.length; + if (stopsLength === 0) { + return; + } + this.embedded = true; + this.matrix = m; + + // if the last stop comes before 100%, add a copy at 100% + const last = this.stops[stopsLength - 1]; + if (last[0] < 1) { + this.stops.push([1, last[1], last[2]]); + } + + const bounds = []; + const encode = []; + const stops = []; + + for (let i = 0; i < stopsLength - 1; i++) { + encode.push(0, 1); + if (i + 2 !== stopsLength) { + bounds.push(this.stops[i + 1][0]); + } + + fn = this.doc.ref({ + FunctionType: 2, + Domain: [0, 1], + C0: this.stops[i + 0][1], + C1: this.stops[i + 1][1], + N: 1 + }); + + stops.push(fn); + fn.end(); + } + + // if there are only two stops, we don't need a stitching function + if (stopsLength === 1) { + fn = stops[0]; + } else { + fn = this.doc.ref({ + FunctionType: 3, // stitching function + Domain: [0, 1], + Functions: stops, + Bounds: bounds, + Encode: encode + }); + + fn.end(); + } + + this.id = `Sh${++this.doc._gradCount}`; + + const shader = this.shader(fn); + shader.end(); + + const pattern = this.doc.ref({ + Type: 'Pattern', + PatternType: 2, + Shading: shader, + Matrix: this.matrix.map(number) + }); + + pattern.end(); + + if (this.stops.some(stop => stop[2] < 1)) { + let grad = this.opacityGradient(); + grad._colorSpace = 'DeviceGray'; + + for (let stop of this.stops) { + grad.stop(stop[0], [stop[2]]); + } + + grad = grad.embed(this.matrix); + + const pageBBox = [0, 0, this.doc.page.width, this.doc.page.height]; + + const form = this.doc.ref({ + Type: 'XObject', + Subtype: 'Form', + FormType: 1, + BBox: pageBBox, + Group: { + Type: 'Group', + S: 'Transparency', + CS: 'DeviceGray' + }, + Resources: { + ProcSet: ['PDF', 'Text', 'ImageB', 'ImageC', 'ImageI'], + Pattern: { + Sh1: grad + } + } + }); + + form.write('/Pattern cs /Sh1 scn'); + form.end(`${pageBBox.join(' ')} re f`); + + const gstate = this.doc.ref({ + Type: 'ExtGState', + SMask: { + Type: 'Mask', + S: 'Luminosity', + G: form + } + }); + + gstate.end(); + + const opacityPattern = this.doc.ref({ + Type: 'Pattern', + PatternType: 1, + PaintType: 1, + TilingType: 2, + BBox: pageBBox, + XStep: pageBBox[2], + YStep: pageBBox[3], + Resources: { + ProcSet: ['PDF', 'Text', 'ImageB', 'ImageC', 'ImageI'], + Pattern: { + Sh1: pattern + }, + ExtGState: { + Gs1: gstate + } + } + }); + + opacityPattern.write('/Gs1 gs /Pattern cs /Sh1 scn'); + opacityPattern.end(`${pageBBox.join(' ')} re f`); + + this.doc.page.patterns[this.id] = opacityPattern; + } else { + this.doc.page.patterns[this.id] = pattern; + } + + return pattern; + } + + apply(op) { + // apply gradient transform to existing document ctm + const [m0, m1, m2, m3, m4, m5] = this.doc._ctm; + const [m11, m12, m21, m22, dx, dy] = this.transform; + const m = [ + m0 * m11 + m2 * m12, + m1 * m11 + m3 * m12, + m0 * m21 + m2 * m22, + m1 * m21 + m3 * m22, + m0 * dx + m2 * dy + m4, + m1 * dx + m3 * dy + m5 + ]; + + if (!this.embedded || m.join(' ') !== this.matrix.join(' ')) { + this.embed(m); + } + return this.doc.addContent(`/${this.id} ${op}`); + } + } + + class PDFLinearGradient extends PDFGradient { + constructor(doc, x1, y1, x2, y2) { + super(doc); + this.x1 = x1; + this.y1 = y1; + this.x2 = x2; + this.y2 = y2; + } + + shader(fn) { + return this.doc.ref({ + ShadingType: 2, + ColorSpace: this._colorSpace, + Coords: [this.x1, this.y1, this.x2, this.y2], + Function: fn, + Extend: [true, true] + }); + } + + opacityGradient() { + return new PDFLinearGradient(this.doc, this.x1, this.y1, this.x2, this.y2); + } + } + + class PDFRadialGradient extends PDFGradient { + constructor(doc, x1, y1, r1, x2, y2, r2) { + super(doc); + this.doc = doc; + this.x1 = x1; + this.y1 = y1; + this.r1 = r1; + this.x2 = x2; + this.y2 = y2; + this.r2 = r2; + } + + shader(fn) { + return this.doc.ref({ + ShadingType: 3, + ColorSpace: this._colorSpace, + Coords: [this.x1, this.y1, this.r1, this.x2, this.y2, this.r2], + Function: fn, + Extend: [true, true] + }); + } + + opacityGradient() { + return new PDFRadialGradient( + this.doc, + this.x1, + this.y1, + this.r1, + this.x2, + this.y2, + this.r2 + ); + } + } + var Gradient = { PDFGradient, PDFLinearGradient, PDFRadialGradient }; - const { PDFGradient: PDFGradient$1, PDFLinearGradient: PDFLinearGradient$1, PDFRadialGradient: PDFRadialGradient$1 } = Gradient; - - var ColorMixin = { - initColor() { - // The opacity dictionaries - this._opacityRegistry = {}; - this._opacityCount = 0; - return (this._gradCount = 0); - }, - - _normalizeColor(color) { - if (color instanceof PDFGradient$1) { - return color; - } - - if (typeof color === 'string') { - if (color.charAt(0) === '#') { - if (color.length === 4) { - color = color.replace( - /#([0-9A-F])([0-9A-F])([0-9A-F])/i, - '#$1$1$2$2$3$3' - ); - } - const hex = parseInt(color.slice(1), 16); - color = [hex >> 16, (hex >> 8) & 0xff, hex & 0xff]; - } else if (namedColors[color]) { - color = namedColors[color]; - } - } - - if (Array.isArray(color)) { - // RGB - if (color.length === 3) { - color = color.map(part => part / 255); - // CMYK - } else if (color.length === 4) { - color = color.map(part => part / 100); - } - return color; - } - - return null; - }, - - _setColor(color, stroke) { - color = this._normalizeColor(color); - if (!color) { - return false; - } - - const op = stroke ? 'SCN' : 'scn'; - - if (color instanceof PDFGradient$1) { - this._setColorSpace('Pattern', stroke); - color.apply(op); - } else { - const space = color.length === 4 ? 'DeviceCMYK' : 'DeviceRGB'; - this._setColorSpace(space, stroke); - - color = color.join(' '); - this.addContent(`${color} ${op}`); - } - - return true; - }, - - _setColorSpace(space, stroke) { - const op = stroke ? 'CS' : 'cs'; - return this.addContent(`/${space} ${op}`); - }, - - fillColor(color, opacity) { - const set = this._setColor(color, false); - if (set) { - this.fillOpacity(opacity); - } - - // save this for text wrapper, which needs to reset - // the fill color on new pages - this._fillColor = [color, opacity]; - return this; - }, - - strokeColor(color, opacity) { - const set = this._setColor(color, true); - if (set) { - this.strokeOpacity(opacity); - } - return this; - }, - - opacity(opacity) { - this._doOpacity(opacity, opacity); - return this; - }, - - fillOpacity(opacity) { - this._doOpacity(opacity, null); - return this; - }, - - strokeOpacity(opacity) { - this._doOpacity(null, opacity); - return this; - }, - - _doOpacity(fillOpacity, strokeOpacity) { - let dictionary, name; - if (fillOpacity == null && strokeOpacity == null) { - return; - } - - if (fillOpacity != null) { - fillOpacity = Math.max(0, Math.min(1, fillOpacity)); - } - if (strokeOpacity != null) { - strokeOpacity = Math.max(0, Math.min(1, strokeOpacity)); - } - const key = `${fillOpacity}_${strokeOpacity}`; - - if (this._opacityRegistry[key]) { - [dictionary, name] = this._opacityRegistry[key]; - } else { - dictionary = { Type: 'ExtGState' }; - - if (fillOpacity != null) { - dictionary.ca = fillOpacity; - } - if (strokeOpacity != null) { - dictionary.CA = strokeOpacity; - } - - dictionary = this.ref(dictionary); - dictionary.end(); - const id = ++this._opacityCount; - name = `Gs${id}`; - this._opacityRegistry[key] = [dictionary, name]; - } - - this.page.ext_gstates[name] = dictionary; - return this.addContent(`/${name} gs`); - }, - - linearGradient(x1, y1, x2, y2) { - return new PDFLinearGradient$1(this, x1, y1, x2, y2); - }, - - radialGradient(x1, y1, r1, x2, y2, r2) { - return new PDFRadialGradient$1(this, x1, y1, r1, x2, y2, r2); - } + const { PDFGradient: PDFGradient$1, PDFLinearGradient: PDFLinearGradient$1, PDFRadialGradient: PDFRadialGradient$1 } = Gradient; + + var ColorMixin = { + initColor() { + // The opacity dictionaries + this._opacityRegistry = {}; + this._opacityCount = 0; + return (this._gradCount = 0); + }, + + _normalizeColor(color) { + if (color instanceof PDFGradient$1) { + return color; + } + + if (typeof color === 'string') { + if (color.charAt(0) === '#') { + if (color.length === 4) { + color = color.replace( + /#([0-9A-F])([0-9A-F])([0-9A-F])/i, + '#$1$1$2$2$3$3' + ); + } + const hex = parseInt(color.slice(1), 16); + color = [hex >> 16, (hex >> 8) & 0xff, hex & 0xff]; + } else if (namedColors[color]) { + color = namedColors[color]; + } + } + + if (Array.isArray(color)) { + // RGB + if (color.length === 3) { + color = color.map(part => part / 255); + // CMYK + } else if (color.length === 4) { + color = color.map(part => part / 100); + } + return color; + } + + return null; + }, + + _setColor(color, stroke) { + color = this._normalizeColor(color); + if (!color) { + return false; + } + + const op = stroke ? 'SCN' : 'scn'; + + if (color instanceof PDFGradient$1) { + this._setColorSpace('Pattern', stroke); + color.apply(op); + } else { + const space = color.length === 4 ? 'DeviceCMYK' : 'DeviceRGB'; + this._setColorSpace(space, stroke); + + color = color.join(' '); + this.addContent(`${color} ${op}`); + } + + return true; + }, + + _setColorSpace(space, stroke) { + const op = stroke ? 'CS' : 'cs'; + return this.addContent(`/${space} ${op}`); + }, + + fillColor(color, opacity) { + const set = this._setColor(color, false); + if (set) { + this.fillOpacity(opacity); + } + + // save this for text wrapper, which needs to reset + // the fill color on new pages + this._fillColor = [color, opacity]; + return this; + }, + + strokeColor(color, opacity) { + const set = this._setColor(color, true); + if (set) { + this.strokeOpacity(opacity); + } + return this; + }, + + opacity(opacity) { + this._doOpacity(opacity, opacity); + return this; + }, + + fillOpacity(opacity) { + this._doOpacity(opacity, null); + return this; + }, + + strokeOpacity(opacity) { + this._doOpacity(null, opacity); + return this; + }, + + _doOpacity(fillOpacity, strokeOpacity) { + let dictionary, name; + if (fillOpacity == null && strokeOpacity == null) { + return; + } + + if (fillOpacity != null) { + fillOpacity = Math.max(0, Math.min(1, fillOpacity)); + } + if (strokeOpacity != null) { + strokeOpacity = Math.max(0, Math.min(1, strokeOpacity)); + } + const key = `${fillOpacity}_${strokeOpacity}`; + + if (this._opacityRegistry[key]) { + [dictionary, name] = this._opacityRegistry[key]; + } else { + dictionary = { Type: 'ExtGState' }; + + if (fillOpacity != null) { + dictionary.ca = fillOpacity; + } + if (strokeOpacity != null) { + dictionary.CA = strokeOpacity; + } + + dictionary = this.ref(dictionary); + dictionary.end(); + const id = ++this._opacityCount; + name = `Gs${id}`; + this._opacityRegistry[key] = [dictionary, name]; + } + + this.page.ext_gstates[name] = dictionary; + return this.addContent(`/${name} gs`); + }, + + linearGradient(x1, y1, x2, y2) { + return new PDFLinearGradient$1(this, x1, y1, x2, y2); + }, + + radialGradient(x1, y1, r1, x2, y2, r2) { + return new PDFRadialGradient$1(this, x1, y1, r1, x2, y2, r2); + } + }; + + var namedColors = { + aliceblue: [240, 248, 255], + antiquewhite: [250, 235, 215], + aqua: [0, 255, 255], + aquamarine: [127, 255, 212], + azure: [240, 255, 255], + beige: [245, 245, 220], + bisque: [255, 228, 196], + black: [0, 0, 0], + blanchedalmond: [255, 235, 205], + blue: [0, 0, 255], + blueviolet: [138, 43, 226], + brown: [165, 42, 42], + burlywood: [222, 184, 135], + cadetblue: [95, 158, 160], + chartreuse: [127, 255, 0], + chocolate: [210, 105, 30], + coral: [255, 127, 80], + cornflowerblue: [100, 149, 237], + cornsilk: [255, 248, 220], + crimson: [220, 20, 60], + cyan: [0, 255, 255], + darkblue: [0, 0, 139], + darkcyan: [0, 139, 139], + darkgoldenrod: [184, 134, 11], + darkgray: [169, 169, 169], + darkgreen: [0, 100, 0], + darkgrey: [169, 169, 169], + darkkhaki: [189, 183, 107], + darkmagenta: [139, 0, 139], + darkolivegreen: [85, 107, 47], + darkorange: [255, 140, 0], + darkorchid: [153, 50, 204], + darkred: [139, 0, 0], + darksalmon: [233, 150, 122], + darkseagreen: [143, 188, 143], + darkslateblue: [72, 61, 139], + darkslategray: [47, 79, 79], + darkslategrey: [47, 79, 79], + darkturquoise: [0, 206, 209], + darkviolet: [148, 0, 211], + deeppink: [255, 20, 147], + deepskyblue: [0, 191, 255], + dimgray: [105, 105, 105], + dimgrey: [105, 105, 105], + dodgerblue: [30, 144, 255], + firebrick: [178, 34, 34], + floralwhite: [255, 250, 240], + forestgreen: [34, 139, 34], + fuchsia: [255, 0, 255], + gainsboro: [220, 220, 220], + ghostwhite: [248, 248, 255], + gold: [255, 215, 0], + goldenrod: [218, 165, 32], + gray: [128, 128, 128], + grey: [128, 128, 128], + green: [0, 128, 0], + greenyellow: [173, 255, 47], + honeydew: [240, 255, 240], + hotpink: [255, 105, 180], + indianred: [205, 92, 92], + indigo: [75, 0, 130], + ivory: [255, 255, 240], + khaki: [240, 230, 140], + lavender: [230, 230, 250], + lavenderblush: [255, 240, 245], + lawngreen: [124, 252, 0], + lemonchiffon: [255, 250, 205], + lightblue: [173, 216, 230], + lightcoral: [240, 128, 128], + lightcyan: [224, 255, 255], + lightgoldenrodyellow: [250, 250, 210], + lightgray: [211, 211, 211], + lightgreen: [144, 238, 144], + lightgrey: [211, 211, 211], + lightpink: [255, 182, 193], + lightsalmon: [255, 160, 122], + lightseagreen: [32, 178, 170], + lightskyblue: [135, 206, 250], + lightslategray: [119, 136, 153], + lightslategrey: [119, 136, 153], + lightsteelblue: [176, 196, 222], + lightyellow: [255, 255, 224], + lime: [0, 255, 0], + limegreen: [50, 205, 50], + linen: [250, 240, 230], + magenta: [255, 0, 255], + maroon: [128, 0, 0], + mediumaquamarine: [102, 205, 170], + mediumblue: [0, 0, 205], + mediumorchid: [186, 85, 211], + mediumpurple: [147, 112, 219], + mediumseagreen: [60, 179, 113], + mediumslateblue: [123, 104, 238], + mediumspringgreen: [0, 250, 154], + mediumturquoise: [72, 209, 204], + mediumvioletred: [199, 21, 133], + midnightblue: [25, 25, 112], + mintcream: [245, 255, 250], + mistyrose: [255, 228, 225], + moccasin: [255, 228, 181], + navajowhite: [255, 222, 173], + navy: [0, 0, 128], + oldlace: [253, 245, 230], + olive: [128, 128, 0], + olivedrab: [107, 142, 35], + orange: [255, 165, 0], + orangered: [255, 69, 0], + orchid: [218, 112, 214], + palegoldenrod: [238, 232, 170], + palegreen: [152, 251, 152], + paleturquoise: [175, 238, 238], + palevioletred: [219, 112, 147], + papayawhip: [255, 239, 213], + peachpuff: [255, 218, 185], + peru: [205, 133, 63], + pink: [255, 192, 203], + plum: [221, 160, 221], + powderblue: [176, 224, 230], + purple: [128, 0, 128], + red: [255, 0, 0], + rosybrown: [188, 143, 143], + royalblue: [65, 105, 225], + saddlebrown: [139, 69, 19], + salmon: [250, 128, 114], + sandybrown: [244, 164, 96], + seagreen: [46, 139, 87], + seashell: [255, 245, 238], + sienna: [160, 82, 45], + silver: [192, 192, 192], + skyblue: [135, 206, 235], + slateblue: [106, 90, 205], + slategray: [112, 128, 144], + slategrey: [112, 128, 144], + snow: [255, 250, 250], + springgreen: [0, 255, 127], + steelblue: [70, 130, 180], + tan: [210, 180, 140], + teal: [0, 128, 128], + thistle: [216, 191, 216], + tomato: [255, 99, 71], + turquoise: [64, 224, 208], + violet: [238, 130, 238], + wheat: [245, 222, 179], + white: [255, 255, 255], + whitesmoke: [245, 245, 245], + yellow: [255, 255, 0], + yellowgreen: [154, 205, 50] }; - var namedColors = { - aliceblue: [240, 248, 255], - antiquewhite: [250, 235, 215], - aqua: [0, 255, 255], - aquamarine: [127, 255, 212], - azure: [240, 255, 255], - beige: [245, 245, 220], - bisque: [255, 228, 196], - black: [0, 0, 0], - blanchedalmond: [255, 235, 205], - blue: [0, 0, 255], - blueviolet: [138, 43, 226], - brown: [165, 42, 42], - burlywood: [222, 184, 135], - cadetblue: [95, 158, 160], - chartreuse: [127, 255, 0], - chocolate: [210, 105, 30], - coral: [255, 127, 80], - cornflowerblue: [100, 149, 237], - cornsilk: [255, 248, 220], - crimson: [220, 20, 60], - cyan: [0, 255, 255], - darkblue: [0, 0, 139], - darkcyan: [0, 139, 139], - darkgoldenrod: [184, 134, 11], - darkgray: [169, 169, 169], - darkgreen: [0, 100, 0], - darkgrey: [169, 169, 169], - darkkhaki: [189, 183, 107], - darkmagenta: [139, 0, 139], - darkolivegreen: [85, 107, 47], - darkorange: [255, 140, 0], - darkorchid: [153, 50, 204], - darkred: [139, 0, 0], - darksalmon: [233, 150, 122], - darkseagreen: [143, 188, 143], - darkslateblue: [72, 61, 139], - darkslategray: [47, 79, 79], - darkslategrey: [47, 79, 79], - darkturquoise: [0, 206, 209], - darkviolet: [148, 0, 211], - deeppink: [255, 20, 147], - deepskyblue: [0, 191, 255], - dimgray: [105, 105, 105], - dimgrey: [105, 105, 105], - dodgerblue: [30, 144, 255], - firebrick: [178, 34, 34], - floralwhite: [255, 250, 240], - forestgreen: [34, 139, 34], - fuchsia: [255, 0, 255], - gainsboro: [220, 220, 220], - ghostwhite: [248, 248, 255], - gold: [255, 215, 0], - goldenrod: [218, 165, 32], - gray: [128, 128, 128], - grey: [128, 128, 128], - green: [0, 128, 0], - greenyellow: [173, 255, 47], - honeydew: [240, 255, 240], - hotpink: [255, 105, 180], - indianred: [205, 92, 92], - indigo: [75, 0, 130], - ivory: [255, 255, 240], - khaki: [240, 230, 140], - lavender: [230, 230, 250], - lavenderblush: [255, 240, 245], - lawngreen: [124, 252, 0], - lemonchiffon: [255, 250, 205], - lightblue: [173, 216, 230], - lightcoral: [240, 128, 128], - lightcyan: [224, 255, 255], - lightgoldenrodyellow: [250, 250, 210], - lightgray: [211, 211, 211], - lightgreen: [144, 238, 144], - lightgrey: [211, 211, 211], - lightpink: [255, 182, 193], - lightsalmon: [255, 160, 122], - lightseagreen: [32, 178, 170], - lightskyblue: [135, 206, 250], - lightslategray: [119, 136, 153], - lightslategrey: [119, 136, 153], - lightsteelblue: [176, 196, 222], - lightyellow: [255, 255, 224], - lime: [0, 255, 0], - limegreen: [50, 205, 50], - linen: [250, 240, 230], - magenta: [255, 0, 255], - maroon: [128, 0, 0], - mediumaquamarine: [102, 205, 170], - mediumblue: [0, 0, 205], - mediumorchid: [186, 85, 211], - mediumpurple: [147, 112, 219], - mediumseagreen: [60, 179, 113], - mediumslateblue: [123, 104, 238], - mediumspringgreen: [0, 250, 154], - mediumturquoise: [72, 209, 204], - mediumvioletred: [199, 21, 133], - midnightblue: [25, 25, 112], - mintcream: [245, 255, 250], - mistyrose: [255, 228, 225], - moccasin: [255, 228, 181], - navajowhite: [255, 222, 173], - navy: [0, 0, 128], - oldlace: [253, 245, 230], - olive: [128, 128, 0], - olivedrab: [107, 142, 35], - orange: [255, 165, 0], - orangered: [255, 69, 0], - orchid: [218, 112, 214], - palegoldenrod: [238, 232, 170], - palegreen: [152, 251, 152], - paleturquoise: [175, 238, 238], - palevioletred: [219, 112, 147], - papayawhip: [255, 239, 213], - peachpuff: [255, 218, 185], - peru: [205, 133, 63], - pink: [255, 192, 203], - plum: [221, 160, 221], - powderblue: [176, 224, 230], - purple: [128, 0, 128], - red: [255, 0, 0], - rosybrown: [188, 143, 143], - royalblue: [65, 105, 225], - saddlebrown: [139, 69, 19], - salmon: [250, 128, 114], - sandybrown: [244, 164, 96], - seagreen: [46, 139, 87], - seashell: [255, 245, 238], - sienna: [160, 82, 45], - silver: [192, 192, 192], - skyblue: [135, 206, 235], - slateblue: [106, 90, 205], - slategray: [112, 128, 144], - slategrey: [112, 128, 144], - snow: [255, 250, 250], - springgreen: [0, 255, 127], - steelblue: [70, 130, 180], - tan: [210, 180, 140], - teal: [0, 128, 128], - thistle: [216, 191, 216], - tomato: [255, 99, 71], - turquoise: [64, 224, 208], - violet: [238, 130, 238], - wheat: [245, 222, 179], - white: [255, 255, 255], - whitesmoke: [245, 245, 245], - yellow: [255, 255, 0], - yellowgreen: [154, 205, 50] + let cx, cy, px, py, sx, sy; + + cx = cy = px = py = sx = sy = 0; + + const parameters = { + A: 7, + a: 7, + C: 6, + c: 6, + H: 1, + h: 1, + L: 2, + l: 2, + M: 2, + m: 2, + Q: 4, + q: 4, + S: 4, + s: 4, + T: 2, + t: 2, + V: 1, + v: 1, + Z: 0, + z: 0 + }; + + const parse = function(path) { + let cmd; + const ret = []; + let args = []; + let curArg = ''; + let foundDecimal = false; + let params = 0; + + for (let c of path) { + if (parameters[c] != null) { + params = parameters[c]; + if (cmd) { + // save existing command + if (curArg.length > 0) { + args[args.length] = +curArg; + } + ret[ret.length] = { cmd, args }; + + args = []; + curArg = ''; + foundDecimal = false; + } + + cmd = c; + } else if ( + [' ', ','].includes(c) || + (c === '-' && curArg.length > 0 && curArg[curArg.length - 1] !== 'e') || + (c === '.' && foundDecimal) + ) { + if (curArg.length === 0) { + continue; + } + + if (args.length === params) { + // handle reused commands + ret[ret.length] = { cmd, args }; + args = [+curArg]; + + // handle assumed commands + if (cmd === 'M') { + cmd = 'L'; + } + if (cmd === 'm') { + cmd = 'l'; + } + } else { + args[args.length] = +curArg; + } + + foundDecimal = c === '.'; + + // fix for negative numbers or repeated decimals with no delimeter between commands + curArg = ['-', '.'].includes(c) ? c : ''; + } else { + curArg += c; + if (c === '.') { + foundDecimal = true; + } + } + } + + // add the last command + if (curArg.length > 0) { + if (args.length === params) { + // handle reused commands + ret[ret.length] = { cmd, args }; + args = [+curArg]; + + // handle assumed commands + if (cmd === 'M') { + cmd = 'L'; + } + if (cmd === 'm') { + cmd = 'l'; + } + } else { + args[args.length] = +curArg; + } + } + + ret[ret.length] = { cmd, args }; + + return ret; + }; + + const apply = function(commands, doc) { + // current point, control point, and subpath starting point + cx = cy = px = py = sx = sy = 0; + + // run the commands + for (let i = 0; i < commands.length; i++) { + const c = commands[i]; + if (typeof runners[c.cmd] === 'function') { + runners[c.cmd](doc, c.args); + } + } + }; + + const runners = { + M(doc, a) { + cx = a[0]; + cy = a[1]; + px = py = null; + sx = cx; + sy = cy; + return doc.moveTo(cx, cy); + }, + + m(doc, a) { + cx += a[0]; + cy += a[1]; + px = py = null; + sx = cx; + sy = cy; + return doc.moveTo(cx, cy); + }, + + C(doc, a) { + cx = a[4]; + cy = a[5]; + px = a[2]; + py = a[3]; + return doc.bezierCurveTo(...a); + }, + + c(doc, a) { + doc.bezierCurveTo( + a[0] + cx, + a[1] + cy, + a[2] + cx, + a[3] + cy, + a[4] + cx, + a[5] + cy + ); + px = cx + a[2]; + py = cy + a[3]; + cx += a[4]; + return (cy += a[5]); + }, + + S(doc, a) { + if (px === null) { + px = cx; + py = cy; + } + + doc.bezierCurveTo(cx - (px - cx), cy - (py - cy), a[0], a[1], a[2], a[3]); + px = a[0]; + py = a[1]; + cx = a[2]; + return (cy = a[3]); + }, + + s(doc, a) { + if (px === null) { + px = cx; + py = cy; + } + + doc.bezierCurveTo( + cx - (px - cx), + cy - (py - cy), + cx + a[0], + cy + a[1], + cx + a[2], + cy + a[3] + ); + px = cx + a[0]; + py = cy + a[1]; + cx += a[2]; + return (cy += a[3]); + }, + + Q(doc, a) { + px = a[0]; + py = a[1]; + cx = a[2]; + cy = a[3]; + return doc.quadraticCurveTo(a[0], a[1], cx, cy); + }, + + q(doc, a) { + doc.quadraticCurveTo(a[0] + cx, a[1] + cy, a[2] + cx, a[3] + cy); + px = cx + a[0]; + py = cy + a[1]; + cx += a[2]; + return (cy += a[3]); + }, + + T(doc, a) { + if (px === null) { + px = cx; + py = cy; + } else { + px = cx - (px - cx); + py = cy - (py - cy); + } + + doc.quadraticCurveTo(px, py, a[0], a[1]); + px = cx - (px - cx); + py = cy - (py - cy); + cx = a[0]; + return (cy = a[1]); + }, + + t(doc, a) { + if (px === null) { + px = cx; + py = cy; + } else { + px = cx - (px - cx); + py = cy - (py - cy); + } + + doc.quadraticCurveTo(px, py, cx + a[0], cy + a[1]); + cx += a[0]; + return (cy += a[1]); + }, + + A(doc, a) { + solveArc(doc, cx, cy, a); + cx = a[5]; + return (cy = a[6]); + }, + + a(doc, a) { + a[5] += cx; + a[6] += cy; + solveArc(doc, cx, cy, a); + cx = a[5]; + return (cy = a[6]); + }, + + L(doc, a) { + cx = a[0]; + cy = a[1]; + px = py = null; + return doc.lineTo(cx, cy); + }, + + l(doc, a) { + cx += a[0]; + cy += a[1]; + px = py = null; + return doc.lineTo(cx, cy); + }, + + H(doc, a) { + cx = a[0]; + px = py = null; + return doc.lineTo(cx, cy); + }, + + h(doc, a) { + cx += a[0]; + px = py = null; + return doc.lineTo(cx, cy); + }, + + V(doc, a) { + cy = a[0]; + px = py = null; + return doc.lineTo(cx, cy); + }, + + v(doc, a) { + cy += a[0]; + px = py = null; + return doc.lineTo(cx, cy); + }, + + Z(doc) { + doc.closePath(); + cx = sx; + return (cy = sy); + }, + + z(doc) { + doc.closePath(); + cx = sx; + return (cy = sy); + } + }; + + const solveArc = function(doc, x, y, coords) { + const [rx, ry, rot, large, sweep, ex, ey] = coords; + const segs = arcToSegments(ex, ey, rx, ry, large, sweep, rot, x, y); + + for (let seg of segs) { + const bez = segmentToBezier(...seg); + doc.bezierCurveTo(...bez); + } + }; + + // from Inkscape svgtopdf, thanks! + const arcToSegments = function(x, y, rx, ry, large, sweep, rotateX, ox, oy) { + const th = rotateX * (Math.PI / 180); + const sin_th = Math.sin(th); + const cos_th = Math.cos(th); + rx = Math.abs(rx); + ry = Math.abs(ry); + px = cos_th * (ox - x) * 0.5 + sin_th * (oy - y) * 0.5; + py = cos_th * (oy - y) * 0.5 - sin_th * (ox - x) * 0.5; + let pl = (px * px) / (rx * rx) + (py * py) / (ry * ry); + if (pl > 1) { + pl = Math.sqrt(pl); + rx *= pl; + ry *= pl; + } + + const a00 = cos_th / rx; + const a01 = sin_th / rx; + const a10 = -sin_th / ry; + const a11 = cos_th / ry; + const x0 = a00 * ox + a01 * oy; + const y0 = a10 * ox + a11 * oy; + const x1 = a00 * x + a01 * y; + const y1 = a10 * x + a11 * y; + + const d = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0); + let sfactor_sq = 1 / d - 0.25; + if (sfactor_sq < 0) { + sfactor_sq = 0; + } + let sfactor = Math.sqrt(sfactor_sq); + if (sweep === large) { + sfactor = -sfactor; + } + + const xc = 0.5 * (x0 + x1) - sfactor * (y1 - y0); + const yc = 0.5 * (y0 + y1) + sfactor * (x1 - x0); + + const th0 = Math.atan2(y0 - yc, x0 - xc); + const th1 = Math.atan2(y1 - yc, x1 - xc); + + let th_arc = th1 - th0; + if (th_arc < 0 && sweep === 1) { + th_arc += 2 * Math.PI; + } else if (th_arc > 0 && sweep === 0) { + th_arc -= 2 * Math.PI; + } + + const segments = Math.ceil(Math.abs(th_arc / (Math.PI * 0.5 + 0.001))); + const result = []; + + for (let i = 0; i < segments; i++) { + const th2 = th0 + (i * th_arc) / segments; + const th3 = th0 + ((i + 1) * th_arc) / segments; + result[i] = [xc, yc, th2, th3, rx, ry, sin_th, cos_th]; + } + + return result; + }; + + const segmentToBezier = function(cx, cy, th0, th1, rx, ry, sin_th, cos_th) { + const a00 = cos_th * rx; + const a01 = -sin_th * ry; + const a10 = sin_th * rx; + const a11 = cos_th * ry; + + const th_half = 0.5 * (th1 - th0); + const t = + ((8 / 3) * Math.sin(th_half * 0.5) * Math.sin(th_half * 0.5)) / + Math.sin(th_half); + const x1 = cx + Math.cos(th0) - t * Math.sin(th0); + const y1 = cy + Math.sin(th0) + t * Math.cos(th0); + const x3 = cx + Math.cos(th1); + const y3 = cy + Math.sin(th1); + const x2 = x3 + t * Math.sin(th1); + const y2 = y3 - t * Math.cos(th1); + + return [ + a00 * x1 + a01 * y1, + a10 * x1 + a11 * y1, + a00 * x2 + a01 * y2, + a10 * x2 + a11 * y2, + a00 * x3 + a01 * y3, + a10 * x3 + a11 * y3 + ]; + }; + + class SVGPath { + static apply(doc, path) { + const commands = parse(path); + apply(commands, doc); + } + } + + const { number: number$1 } = PDFObject; + + // This constant is used to approximate a symmetrical arc using a cubic + // Bezier curve. + const KAPPA = 4.0 * ((Math.sqrt(2) - 1.0) / 3.0); + var VectorMixin = { + initVector() { + this._ctm = [1, 0, 0, 1, 0, 0]; // current transformation matrix + return (this._ctmStack = []); + }, + + save() { + this._ctmStack.push(this._ctm.slice()); + // TODO: save/restore colorspace and styles so not setting it unnessesarily all the time? + return this.addContent('q'); + }, + + restore() { + this._ctm = this._ctmStack.pop() || [1, 0, 0, 1, 0, 0]; + return this.addContent('Q'); + }, + + closePath() { + return this.addContent('h'); + }, + + lineWidth(w) { + return this.addContent(`${number$1(w)} w`); + }, + + _CAP_STYLES: { + BUTT: 0, + ROUND: 1, + SQUARE: 2 + }, + + lineCap(c) { + if (typeof c === 'string') { + c = this._CAP_STYLES[c.toUpperCase()]; + } + return this.addContent(`${c} J`); + }, + + _JOIN_STYLES: { + MITER: 0, + ROUND: 1, + BEVEL: 2 + }, + + lineJoin(j) { + if (typeof j === 'string') { + j = this._JOIN_STYLES[j.toUpperCase()]; + } + return this.addContent(`${j} j`); + }, + + miterLimit(m) { + return this.addContent(`${number$1(m)} M`); + }, + + dash(length, options = {}) { + const originalLength = length; + if (!Array.isArray(length)) { + length = [length, options.space || length]; + } + + const valid = length.every(x => Number.isFinite(x) && x > 0); + if(!valid) { + throw new Error(`dash(${JSON.stringify(originalLength)}, ${JSON.stringify(options)}) invalid, lengths must be numeric and greater than zero`); + } + + length = length.map(number$1).join(' '); + return this.addContent(`[${length}] ${number$1(options.phase || 0)} d`); + }, + + undash() { + return this.addContent('[] 0 d'); + }, + + moveTo(x, y) { + return this.addContent(`${number$1(x)} ${number$1(y)} m`); + }, + + lineTo(x, y) { + return this.addContent(`${number$1(x)} ${number$1(y)} l`); + }, + + bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) { + return this.addContent( + `${number$1(cp1x)} ${number$1(cp1y)} ${number$1(cp2x)} ${number$1(cp2y)} ${number$1( + x + )} ${number$1(y)} c` + ); + }, + + quadraticCurveTo(cpx, cpy, x, y) { + return this.addContent( + `${number$1(cpx)} ${number$1(cpy)} ${number$1(x)} ${number$1(y)} v` + ); + }, + + rect(x, y, w, h) { + return this.addContent( + `${number$1(x)} ${number$1(y)} ${number$1(w)} ${number$1(h)} re` + ); + }, + + roundedRect(x, y, w, h, r) { + if (r == null) { + r = 0; + } + r = Math.min(r, 0.5 * w, 0.5 * h); + + // amount to inset control points from corners (see `ellipse`) + const c = r * (1.0 - KAPPA); + + this.moveTo(x + r, y); + this.lineTo(x + w - r, y); + this.bezierCurveTo(x + w - c, y, x + w, y + c, x + w, y + r); + this.lineTo(x + w, y + h - r); + this.bezierCurveTo(x + w, y + h - c, x + w - c, y + h, x + w - r, y + h); + this.lineTo(x + r, y + h); + this.bezierCurveTo(x + c, y + h, x, y + h - c, x, y + h - r); + this.lineTo(x, y + r); + this.bezierCurveTo(x, y + c, x + c, y, x + r, y); + return this.closePath(); + }, + + ellipse(x, y, r1, r2) { + // based on http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas/2173084#2173084 + if (r2 == null) { + r2 = r1; + } + x -= r1; + y -= r2; + const ox = r1 * KAPPA; + const oy = r2 * KAPPA; + const xe = x + r1 * 2; + const ye = y + r2 * 2; + const xm = x + r1; + const ym = y + r2; + + this.moveTo(x, ym); + this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + return this.closePath(); + }, + + circle(x, y, radius) { + return this.ellipse(x, y, radius); + }, + + arc(x, y, radius, startAngle, endAngle, anticlockwise) { + if (anticlockwise == null) { + anticlockwise = false; + } + const TWO_PI = 2.0 * Math.PI; + const HALF_PI = 0.5 * Math.PI; + + let deltaAng = endAngle - startAngle; + + if (Math.abs(deltaAng) > TWO_PI) { + // draw only full circle if more than that is specified + deltaAng = TWO_PI; + } else if (deltaAng !== 0 && anticlockwise !== deltaAng < 0) { + // necessary to flip direction of rendering + const dir = anticlockwise ? -1 : 1; + deltaAng = dir * TWO_PI + deltaAng; + } + + const numSegs = Math.ceil(Math.abs(deltaAng) / HALF_PI); + const segAng = deltaAng / numSegs; + const handleLen = (segAng / HALF_PI) * KAPPA * radius; + let curAng = startAngle; + + // component distances between anchor point and control point + let deltaCx = -Math.sin(curAng) * handleLen; + let deltaCy = Math.cos(curAng) * handleLen; + + // anchor point + let ax = x + Math.cos(curAng) * radius; + let ay = y + Math.sin(curAng) * radius; + + // calculate and render segments + this.moveTo(ax, ay); + + for (let segIdx = 0; segIdx < numSegs; segIdx++) { + // starting control point + const cp1x = ax + deltaCx; + const cp1y = ay + deltaCy; + + // step angle + curAng += segAng; + + // next anchor point + ax = x + Math.cos(curAng) * radius; + ay = y + Math.sin(curAng) * radius; + + // next control point delta + deltaCx = -Math.sin(curAng) * handleLen; + deltaCy = Math.cos(curAng) * handleLen; + + // ending control point + const cp2x = ax - deltaCx; + const cp2y = ay - deltaCy; + + // render segment + this.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, ax, ay); + } + + return this; + }, + + polygon(...points) { + this.moveTo(...(points.shift() || [])); + for (let point of points) { + this.lineTo(...(point || [])); + } + return this.closePath(); + }, + + path(path) { + SVGPath.apply(this, path); + return this; + }, + + _windingRule(rule) { + if (/even-?odd/.test(rule)) { + return '*'; + } + + return ''; + }, + + fill(color, rule) { + if (/(even-?odd)|(non-?zero)/.test(color)) { + rule = color; + color = null; + } + + if (color) { + this.fillColor(color); + } + return this.addContent(`f${this._windingRule(rule)}`); + }, + + stroke(color) { + if (color) { + this.strokeColor(color); + } + return this.addContent('S'); + }, + + fillAndStroke(fillColor, strokeColor, rule) { + if (strokeColor == null) { + strokeColor = fillColor; + } + const isFillRule = /(even-?odd)|(non-?zero)/; + if (isFillRule.test(fillColor)) { + rule = fillColor; + fillColor = null; + } + + if (isFillRule.test(strokeColor)) { + rule = strokeColor; + strokeColor = fillColor; + } + + if (fillColor) { + this.fillColor(fillColor); + this.strokeColor(strokeColor); + } + + return this.addContent(`B${this._windingRule(rule)}`); + }, + + clip(rule) { + return this.addContent(`W${this._windingRule(rule)} n`); + }, + + transform(m11, m12, m21, m22, dx, dy) { + // keep track of the current transformation matrix + const m = this._ctm; + const [m0, m1, m2, m3, m4, m5] = m; + m[0] = m0 * m11 + m2 * m12; + m[1] = m1 * m11 + m3 * m12; + m[2] = m0 * m21 + m2 * m22; + m[3] = m1 * m21 + m3 * m22; + m[4] = m0 * dx + m2 * dy + m4; + m[5] = m1 * dx + m3 * dy + m5; + + const values = [m11, m12, m21, m22, dx, dy].map(v => number$1(v)).join(' '); + return this.addContent(`${values} cm`); + }, + + translate(x, y) { + return this.transform(1, 0, 0, 1, x, y); + }, + + rotate(angle, options = {}) { + let y; + const rad = (angle * Math.PI) / 180; + const cos = Math.cos(rad); + const sin = Math.sin(rad); + let x = (y = 0); + + if (options.origin != null) { + [x, y] = options.origin; + const x1 = x * cos - y * sin; + const y1 = x * sin + y * cos; + x -= x1; + y -= y1; + } + + return this.transform(cos, sin, -sin, cos, x, y); + }, + + scale(xFactor, yFactor, options = {}) { + let y; + if (yFactor == null) { + yFactor = xFactor; + } + if (typeof yFactor === 'object') { + options = yFactor; + yFactor = xFactor; + } + + let x = (y = 0); + if (options.origin != null) { + [x, y] = options.origin; + x -= xFactor * x; + y -= yFactor * y; + } + + return this.transform(xFactor, 0, 0, yFactor, x, y); + } }; - let cx, cy, px, py, sx, sy; + const MARKERS = [ + 0xffc0, + 0xffc1, + 0xffc2, + 0xffc3, + 0xffc5, + 0xffc6, + 0xffc7, + 0xffc8, + 0xffc9, + 0xffca, + 0xffcb, + 0xffcc, + 0xffcd, + 0xffce, + 0xffcf + ]; + + const COLOR_SPACE_MAP = { + 1: 'DeviceGray', + 3: 'DeviceRGB', + 4: 'DeviceCMYK' + }; + + class JPEG { + constructor(data, label) { + let marker; + this.data = data; + this.label = label; + if (this.data.readUInt16BE(0) !== 0xffd8) { + throw 'SOI not found in JPEG'; + } + + let pos = 2; + while (pos < this.data.length) { + marker = this.data.readUInt16BE(pos); + pos += 2; + if (MARKERS.includes(marker)) { + break; + } + pos += this.data.readUInt16BE(pos); + } + + if (!MARKERS.includes(marker)) { + throw 'Invalid JPEG.'; + } + pos += 2; + + this.bits = this.data[pos++]; + this.height = this.data.readUInt16BE(pos); + pos += 2; + + this.width = this.data.readUInt16BE(pos); + pos += 2; + + const channels = this.data[pos++]; + this.colorSpace = COLOR_SPACE_MAP[channels]; + + this.obj = null; + } + + embed(document) { + if (this.obj) { + return; + } + + this.obj = document.ref({ + Type: 'XObject', + Subtype: 'Image', + BitsPerComponent: this.bits, + Width: this.width, + Height: this.height, + ColorSpace: this.colorSpace, + Filter: 'DCTDecode' + }); + + // add extra decode params for CMYK images. By swapping the + // min and max values from the default, we invert the colors. See + // section 4.8.4 of the spec. + if (this.colorSpace === 'DeviceCMYK') { + this.obj.data['Decode'] = [1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0]; + } + + this.obj.end(this.data); + + // free memory + return (this.data = null); + } + } - cx = cy = px = py = sx = sy = 0; + var fs$1 = {}; - const parameters = { - A: 7, - a: 7, - C: 6, - c: 6, - H: 1, - h: 1, - L: 2, - l: 2, - M: 2, - m: 2, - Q: 4, - q: 4, - S: 4, - s: 4, - T: 2, - t: 2, - V: 1, - v: 1, - Z: 0, - z: 0 + function assert$1 (a, msg) { + if (!a) { + throw new Error(msg); + } + } + var binding$1 = {}; + Object.keys(_binding).forEach(function (key) { + binding$1[key] = _binding[key]; + }); + // zlib doesn't provide these, so kludge them in following the same + // const naming scheme zlib uses. + binding$1.Z_MIN_WINDOWBITS = 8; + binding$1.Z_MAX_WINDOWBITS = 15; + binding$1.Z_DEFAULT_WINDOWBITS = 15; + + // fewer than 64 bytes per chunk is stupid. + // technically it could work with as few as 8, but even 64 bytes + // is absurdly low. Usually a MB or more is best. + binding$1.Z_MIN_CHUNK = 64; + binding$1.Z_MAX_CHUNK = Infinity; + binding$1.Z_DEFAULT_CHUNK = (16 * 1024); + + binding$1.Z_MIN_MEMLEVEL = 1; + binding$1.Z_MAX_MEMLEVEL = 9; + binding$1.Z_DEFAULT_MEMLEVEL = 8; + + binding$1.Z_MIN_LEVEL = -1; + binding$1.Z_MAX_LEVEL = 9; + binding$1.Z_DEFAULT_LEVEL = binding$1.Z_DEFAULT_COMPRESSION; + + + // translation table for return codes. + var codes$1 = { + Z_OK: binding$1.Z_OK, + Z_STREAM_END: binding$1.Z_STREAM_END, + Z_NEED_DICT: binding$1.Z_NEED_DICT, + Z_ERRNO: binding$1.Z_ERRNO, + Z_STREAM_ERROR: binding$1.Z_STREAM_ERROR, + Z_DATA_ERROR: binding$1.Z_DATA_ERROR, + Z_MEM_ERROR: binding$1.Z_MEM_ERROR, + Z_BUF_ERROR: binding$1.Z_BUF_ERROR, + Z_VERSION_ERROR: binding$1.Z_VERSION_ERROR }; - const parse = function(path) { - let cmd; - const ret = []; - let args = []; - let curArg = ''; - let foundDecimal = false; - let params = 0; + Object.keys(codes$1).forEach(function(k) { + codes$1[codes$1[k]] = k; + }); - for (let c of path) { - if (parameters[c] != null) { - params = parameters[c]; - if (cmd) { - // save existing command - if (curArg.length > 0) { - args[args.length] = +curArg; - } - ret[ret.length] = { cmd, args }; + function createDeflate$1(o) { + return new Deflate$1(o); + } - args = []; - curArg = ''; - foundDecimal = false; - } + function createInflate$1(o) { + return new Inflate$1(o); + } - cmd = c; - } else if ( - [' ', ','].includes(c) || - (c === '-' && curArg.length > 0 && curArg[curArg.length - 1] !== 'e') || - (c === '.' && foundDecimal) - ) { - if (curArg.length === 0) { - continue; - } + function createDeflateRaw$1(o) { + return new DeflateRaw$1(o); + } - if (args.length === params) { - // handle reused commands - ret[ret.length] = { cmd, args }; - args = [+curArg]; + function createInflateRaw$1(o) { + return new InflateRaw$1(o); + } - // handle assumed commands - if (cmd === 'M') { - cmd = 'L'; - } - if (cmd === 'm') { - cmd = 'l'; - } - } else { - args[args.length] = +curArg; - } + function createGzip$1(o) { + return new Gzip$1(o); + } - foundDecimal = c === '.'; + function createGunzip$1(o) { + return new Gunzip$1(o); + } - // fix for negative numbers or repeated decimals with no delimeter between commands - curArg = ['-', '.'].includes(c) ? c : ''; - } else { - curArg += c; - if (c === '.') { - foundDecimal = true; - } + function createUnzip$1(o) { + return new Unzip$1(o); + } + + + // Convenience methods. + // compress/decompress a string or buffer in one step. + function deflate$2(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer$1(new Deflate$1(opts), buffer, callback); + } + + function deflateSync$1(buffer, opts) { + return zlibBufferSync$1(new Deflate$1(opts), buffer); + } + + function gzip$1(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer$1(new Gzip$1(opts), buffer, callback); + } + + function gzipSync$1(buffer, opts) { + return zlibBufferSync$1(new Gzip$1(opts), buffer); + } + + function deflateRaw$1(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer$1(new DeflateRaw$1(opts), buffer, callback); + } + + function deflateRawSync$1(buffer, opts) { + return zlibBufferSync$1(new DeflateRaw$1(opts), buffer); + } + + function unzip$1(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer$1(new Unzip$1(opts), buffer, callback); + } + + function unzipSync$1(buffer, opts) { + return zlibBufferSync$1(new Unzip$1(opts), buffer); + } + + function inflate$2(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer$1(new Inflate$1(opts), buffer, callback); + } + + function inflateSync$1(buffer, opts) { + return zlibBufferSync$1(new Inflate$1(opts), buffer); + } + + function gunzip$1(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer$1(new Gunzip$1(opts), buffer, callback); + } + + function gunzipSync$1(buffer, opts) { + return zlibBufferSync$1(new Gunzip$1(opts), buffer); + } + + function inflateRaw$1(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer$1(new InflateRaw$1(opts), buffer, callback); + } + + function inflateRawSync$1(buffer, opts) { + return zlibBufferSync$1(new InflateRaw$1(opts), buffer); + } + + function zlibBuffer$1(engine, buffer, callback) { + var buffers = []; + var nread = 0; + + engine.on('error', onError); + engine.on('end', onEnd); + + engine.end(buffer); + flow(); + + function flow() { + var chunk; + while (null !== (chunk = engine.read())) { + buffers.push(chunk); + nread += chunk.length; } + engine.once('readable', flow); } - // add the last command - if (curArg.length > 0) { - if (args.length === params) { - // handle reused commands - ret[ret.length] = { cmd, args }; - args = [+curArg]; - - // handle assumed commands - if (cmd === 'M') { - cmd = 'L'; - } - if (cmd === 'm') { - cmd = 'l'; - } - } else { - args[args.length] = +curArg; - } + function onError(err) { + engine.removeListener('end', onEnd); + engine.removeListener('readable', flow); + callback(err); } - ret[ret.length] = { cmd, args }; - - return ret; - }; - - const apply = function(commands, doc) { - // current point, control point, and subpath starting point - cx = cy = px = py = sx = sy = 0; - - // run the commands - for (let i = 0; i < commands.length; i++) { - const c = commands[i]; - if (typeof runners[c.cmd] === 'function') { - runners[c.cmd](doc, c.args); - } - } - }; - - const runners = { - M(doc, a) { - cx = a[0]; - cy = a[1]; - px = py = null; - sx = cx; - sy = cy; - return doc.moveTo(cx, cy); - }, - - m(doc, a) { - cx += a[0]; - cy += a[1]; - px = py = null; - sx = cx; - sy = cy; - return doc.moveTo(cx, cy); - }, - - C(doc, a) { - cx = a[4]; - cy = a[5]; - px = a[2]; - py = a[3]; - return doc.bezierCurveTo(...a); - }, - - c(doc, a) { - doc.bezierCurveTo( - a[0] + cx, - a[1] + cy, - a[2] + cx, - a[3] + cy, - a[4] + cx, - a[5] + cy - ); - px = cx + a[2]; - py = cy + a[3]; - cx += a[4]; - return (cy += a[5]); - }, - - S(doc, a) { - if (px === null) { - px = cx; - py = cy; - } - - doc.bezierCurveTo(cx - (px - cx), cy - (py - cy), a[0], a[1], a[2], a[3]); - px = a[0]; - py = a[1]; - cx = a[2]; - return (cy = a[3]); - }, - - s(doc, a) { - if (px === null) { - px = cx; - py = cy; - } - - doc.bezierCurveTo( - cx - (px - cx), - cy - (py - cy), - cx + a[0], - cy + a[1], - cx + a[2], - cy + a[3] - ); - px = cx + a[0]; - py = cy + a[1]; - cx += a[2]; - return (cy += a[3]); - }, - - Q(doc, a) { - px = a[0]; - py = a[1]; - cx = a[2]; - cy = a[3]; - return doc.quadraticCurveTo(a[0], a[1], cx, cy); - }, - - q(doc, a) { - doc.quadraticCurveTo(a[0] + cx, a[1] + cy, a[2] + cx, a[3] + cy); - px = cx + a[0]; - py = cy + a[1]; - cx += a[2]; - return (cy += a[3]); - }, - - T(doc, a) { - if (px === null) { - px = cx; - py = cy; - } else { - px = cx - (px - cx); - py = cy - (py - cy); - } - - doc.quadraticCurveTo(px, py, a[0], a[1]); - px = cx - (px - cx); - py = cy - (py - cy); - cx = a[0]; - return (cy = a[1]); - }, - - t(doc, a) { - if (px === null) { - px = cx; - py = cy; - } else { - px = cx - (px - cx); - py = cy - (py - cy); - } - - doc.quadraticCurveTo(px, py, cx + a[0], cy + a[1]); - cx += a[0]; - return (cy += a[1]); - }, - - A(doc, a) { - solveArc(doc, cx, cy, a); - cx = a[5]; - return (cy = a[6]); - }, - - a(doc, a) { - a[5] += cx; - a[6] += cy; - solveArc(doc, cx, cy, a); - cx = a[5]; - return (cy = a[6]); - }, - - L(doc, a) { - cx = a[0]; - cy = a[1]; - px = py = null; - return doc.lineTo(cx, cy); - }, - - l(doc, a) { - cx += a[0]; - cy += a[1]; - px = py = null; - return doc.lineTo(cx, cy); - }, - - H(doc, a) { - cx = a[0]; - px = py = null; - return doc.lineTo(cx, cy); - }, - - h(doc, a) { - cx += a[0]; - px = py = null; - return doc.lineTo(cx, cy); - }, - - V(doc, a) { - cy = a[0]; - px = py = null; - return doc.lineTo(cx, cy); - }, - - v(doc, a) { - cy += a[0]; - px = py = null; - return doc.lineTo(cx, cy); - }, - - Z(doc) { - doc.closePath(); - cx = sx; - return (cy = sy); - }, - - z(doc) { - doc.closePath(); - cx = sx; - return (cy = sy); - } - }; - - const solveArc = function(doc, x, y, coords) { - const [rx, ry, rot, large, sweep, ex, ey] = coords; - const segs = arcToSegments(ex, ey, rx, ry, large, sweep, rot, x, y); - - for (let seg of segs) { - const bez = segmentToBezier(...seg); - doc.bezierCurveTo(...bez); - } - }; - - // from Inkscape svgtopdf, thanks! - const arcToSegments = function(x, y, rx, ry, large, sweep, rotateX, ox, oy) { - const th = rotateX * (Math.PI / 180); - const sin_th = Math.sin(th); - const cos_th = Math.cos(th); - rx = Math.abs(rx); - ry = Math.abs(ry); - px = cos_th * (ox - x) * 0.5 + sin_th * (oy - y) * 0.5; - py = cos_th * (oy - y) * 0.5 - sin_th * (ox - x) * 0.5; - let pl = (px * px) / (rx * rx) + (py * py) / (ry * ry); - if (pl > 1) { - pl = Math.sqrt(pl); - rx *= pl; - ry *= pl; - } - - const a00 = cos_th / rx; - const a01 = sin_th / rx; - const a10 = -sin_th / ry; - const a11 = cos_th / ry; - const x0 = a00 * ox + a01 * oy; - const y0 = a10 * ox + a11 * oy; - const x1 = a00 * x + a01 * y; - const y1 = a10 * x + a11 * y; - - const d = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0); - let sfactor_sq = 1 / d - 0.25; - if (sfactor_sq < 0) { - sfactor_sq = 0; - } - let sfactor = Math.sqrt(sfactor_sq); - if (sweep === large) { - sfactor = -sfactor; - } - - const xc = 0.5 * (x0 + x1) - sfactor * (y1 - y0); - const yc = 0.5 * (y0 + y1) + sfactor * (x1 - x0); - - const th0 = Math.atan2(y0 - yc, x0 - xc); - const th1 = Math.atan2(y1 - yc, x1 - xc); - - let th_arc = th1 - th0; - if (th_arc < 0 && sweep === 1) { - th_arc += 2 * Math.PI; - } else if (th_arc > 0 && sweep === 0) { - th_arc -= 2 * Math.PI; - } - - const segments = Math.ceil(Math.abs(th_arc / (Math.PI * 0.5 + 0.001))); - const result = []; - - for (let i = 0; i < segments; i++) { - const th2 = th0 + (i * th_arc) / segments; - const th3 = th0 + ((i + 1) * th_arc) / segments; - result[i] = [xc, yc, th2, th3, rx, ry, sin_th, cos_th]; - } - - return result; - }; - - const segmentToBezier = function(cx, cy, th0, th1, rx, ry, sin_th, cos_th) { - const a00 = cos_th * rx; - const a01 = -sin_th * ry; - const a10 = sin_th * rx; - const a11 = cos_th * ry; - - const th_half = 0.5 * (th1 - th0); - const t = - ((8 / 3) * Math.sin(th_half * 0.5) * Math.sin(th_half * 0.5)) / - Math.sin(th_half); - const x1 = cx + Math.cos(th0) - t * Math.sin(th0); - const y1 = cy + Math.sin(th0) + t * Math.cos(th0); - const x3 = cx + Math.cos(th1); - const y3 = cy + Math.sin(th1); - const x2 = x3 + t * Math.sin(th1); - const y2 = y3 - t * Math.cos(th1); - - return [ - a00 * x1 + a01 * y1, - a10 * x1 + a11 * y1, - a00 * x2 + a01 * y2, - a10 * x2 + a11 * y2, - a00 * x3 + a01 * y3, - a10 * x3 + a11 * y3 - ]; - }; - - class SVGPath { - static apply(doc, path) { - const commands = parse(path); - apply(commands, doc); + function onEnd() { + var buf = Buffer.concat(buffers, nread); + buffers = []; + callback(null, buf); + engine.close(); } } - const { number: number$1 } = PDFObject; + function zlibBufferSync$1(engine, buffer) { + if (typeof buffer === 'string') + buffer = new Buffer(buffer); + if (!isBuffer(buffer)) + throw new TypeError('Not a string or buffer'); - // This constant is used to approximate a symmetrical arc using a cubic - // Bezier curve. - const KAPPA = 4.0 * ((Math.sqrt(2) - 1.0) / 3.0); - var VectorMixin = { - initVector() { - this._ctm = [1, 0, 0, 1, 0, 0]; // current transformation matrix - return (this._ctmStack = []); - }, + var flushFlag = binding$1.Z_FINISH; - save() { - this._ctmStack.push(this._ctm.slice()); - // TODO: save/restore colorspace and styles so not setting it unnessesarily all the time? - return this.addContent('q'); - }, + return engine._processChunk(buffer, flushFlag); + } - restore() { - this._ctm = this._ctmStack.pop() || [1, 0, 0, 1, 0, 0]; - return this.addContent('Q'); - }, + // generic zlib + // minimal 2-byte header + function Deflate$1(opts) { + if (!(this instanceof Deflate$1)) return new Deflate$1(opts); + Zlib$2.call(this, opts, binding$1.DEFLATE); + } - closePath() { - return this.addContent('h'); - }, + function Inflate$1(opts) { + if (!(this instanceof Inflate$1)) return new Inflate$1(opts); + Zlib$2.call(this, opts, binding$1.INFLATE); + } - lineWidth(w) { - return this.addContent(`${number$1(w)} w`); - }, - _CAP_STYLES: { - BUTT: 0, - ROUND: 1, - SQUARE: 2 - }, - lineCap(c) { - if (typeof c === 'string') { - c = this._CAP_STYLES[c.toUpperCase()]; + // gzip - bigger header, same deflate compression + function Gzip$1(opts) { + if (!(this instanceof Gzip$1)) return new Gzip$1(opts); + Zlib$2.call(this, opts, binding$1.GZIP); + } + + function Gunzip$1(opts) { + if (!(this instanceof Gunzip$1)) return new Gunzip$1(opts); + Zlib$2.call(this, opts, binding$1.GUNZIP); + } + + + + // raw - no header + function DeflateRaw$1(opts) { + if (!(this instanceof DeflateRaw$1)) return new DeflateRaw$1(opts); + Zlib$2.call(this, opts, binding$1.DEFLATERAW); + } + + function InflateRaw$1(opts) { + if (!(this instanceof InflateRaw$1)) return new InflateRaw$1(opts); + Zlib$2.call(this, opts, binding$1.INFLATERAW); + } + + + // auto-detect header. + function Unzip$1(opts) { + if (!(this instanceof Unzip$1)) return new Unzip$1(opts); + Zlib$2.call(this, opts, binding$1.UNZIP); + } + + + // the Zlib class they all inherit from + // This thing manages the queue of requests, and returns + // true or false if there is anything in the queue when + // you call the .write() method. + + function Zlib$2(opts, mode) { + this._opts = opts = opts || {}; + this._chunkSize = opts.chunkSize || binding$1.Z_DEFAULT_CHUNK; + + Transform.call(this, opts); + + if (opts.flush) { + if (opts.flush !== binding$1.Z_NO_FLUSH && + opts.flush !== binding$1.Z_PARTIAL_FLUSH && + opts.flush !== binding$1.Z_SYNC_FLUSH && + opts.flush !== binding$1.Z_FULL_FLUSH && + opts.flush !== binding$1.Z_FINISH && + opts.flush !== binding$1.Z_BLOCK) { + throw new Error('Invalid flush flag: ' + opts.flush); } - return this.addContent(`${c} J`); - }, - - _JOIN_STYLES: { - MITER: 0, - ROUND: 1, - BEVEL: 2 - }, - - lineJoin(j) { - if (typeof j === 'string') { - j = this._JOIN_STYLES[j.toUpperCase()]; - } - return this.addContent(`${j} j`); - }, - - miterLimit(m) { - return this.addContent(`${number$1(m)} M`); - }, - - dash(length, options = {}) { - const originalLength = length; - if (!Array.isArray(length)) { - length = [length, options.space || length]; - } - - const valid = length.every(x => Number.isFinite(x) && x > 0); - if(!valid) { - throw new Error(`dash(${JSON.stringify(originalLength)}, ${JSON.stringify(options)}) invalid, lengths must be numeric and greater than zero`); - } - - length = length.map(number$1).join(' '); - return this.addContent(`[${length}] ${number$1(options.phase || 0)} d`); - }, - - undash() { - return this.addContent('[] 0 d'); - }, - - moveTo(x, y) { - return this.addContent(`${number$1(x)} ${number$1(y)} m`); - }, - - lineTo(x, y) { - return this.addContent(`${number$1(x)} ${number$1(y)} l`); - }, - - bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) { - return this.addContent( - `${number$1(cp1x)} ${number$1(cp1y)} ${number$1(cp2x)} ${number$1(cp2y)} ${number$1( - x - )} ${number$1(y)} c` - ); - }, - - quadraticCurveTo(cpx, cpy, x, y) { - return this.addContent( - `${number$1(cpx)} ${number$1(cpy)} ${number$1(x)} ${number$1(y)} v` - ); - }, - - rect(x, y, w, h) { - return this.addContent( - `${number$1(x)} ${number$1(y)} ${number$1(w)} ${number$1(h)} re` - ); - }, - - roundedRect(x, y, w, h, r) { - if (r == null) { - r = 0; - } - r = Math.min(r, 0.5 * w, 0.5 * h); - - // amount to inset control points from corners (see `ellipse`) - const c = r * (1.0 - KAPPA); - - this.moveTo(x + r, y); - this.lineTo(x + w - r, y); - this.bezierCurveTo(x + w - c, y, x + w, y + c, x + w, y + r); - this.lineTo(x + w, y + h - r); - this.bezierCurveTo(x + w, y + h - c, x + w - c, y + h, x + w - r, y + h); - this.lineTo(x + r, y + h); - this.bezierCurveTo(x + c, y + h, x, y + h - c, x, y + h - r); - this.lineTo(x, y + r); - this.bezierCurveTo(x, y + c, x + c, y, x + r, y); - return this.closePath(); - }, - - ellipse(x, y, r1, r2) { - // based on http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas/2173084#2173084 - if (r2 == null) { - r2 = r1; - } - x -= r1; - y -= r2; - const ox = r1 * KAPPA; - const oy = r2 * KAPPA; - const xe = x + r1 * 2; - const ye = y + r2 * 2; - const xm = x + r1; - const ym = y + r2; - - this.moveTo(x, ym); - this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); - this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); - this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); - this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); - return this.closePath(); - }, - - circle(x, y, radius) { - return this.ellipse(x, y, radius); - }, - - arc(x, y, radius, startAngle, endAngle, anticlockwise) { - if (anticlockwise == null) { - anticlockwise = false; - } - const TWO_PI = 2.0 * Math.PI; - const HALF_PI = 0.5 * Math.PI; - - let deltaAng = endAngle - startAngle; - - if (Math.abs(deltaAng) > TWO_PI) { - // draw only full circle if more than that is specified - deltaAng = TWO_PI; - } else if (deltaAng !== 0 && anticlockwise !== deltaAng < 0) { - // necessary to flip direction of rendering - const dir = anticlockwise ? -1 : 1; - deltaAng = dir * TWO_PI + deltaAng; - } - - const numSegs = Math.ceil(Math.abs(deltaAng) / HALF_PI); - const segAng = deltaAng / numSegs; - const handleLen = (segAng / HALF_PI) * KAPPA * radius; - let curAng = startAngle; - - // component distances between anchor point and control point - let deltaCx = -Math.sin(curAng) * handleLen; - let deltaCy = Math.cos(curAng) * handleLen; - - // anchor point - let ax = x + Math.cos(curAng) * radius; - let ay = y + Math.sin(curAng) * radius; - - // calculate and render segments - this.moveTo(ax, ay); - - for (let segIdx = 0; segIdx < numSegs; segIdx++) { - // starting control point - const cp1x = ax + deltaCx; - const cp1y = ay + deltaCy; - - // step angle - curAng += segAng; - - // next anchor point - ax = x + Math.cos(curAng) * radius; - ay = y + Math.sin(curAng) * radius; - - // next control point delta - deltaCx = -Math.sin(curAng) * handleLen; - deltaCy = Math.cos(curAng) * handleLen; - - // ending control point - const cp2x = ax - deltaCx; - const cp2y = ay - deltaCy; - - // render segment - this.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, ax, ay); - } - - return this; - }, - - polygon(...points) { - this.moveTo(...(points.shift() || [])); - for (let point of points) { - this.lineTo(...(point || [])); - } - return this.closePath(); - }, - - path(path) { - SVGPath.apply(this, path); - return this; - }, - - _windingRule(rule) { - if (/even-?odd/.test(rule)) { - return '*'; - } - - return ''; - }, - - fill(color, rule) { - if (/(even-?odd)|(non-?zero)/.test(color)) { - rule = color; - color = null; - } - - if (color) { - this.fillColor(color); - } - return this.addContent(`f${this._windingRule(rule)}`); - }, - - stroke(color) { - if (color) { - this.strokeColor(color); - } - return this.addContent('S'); - }, - - fillAndStroke(fillColor, strokeColor, rule) { - if (strokeColor == null) { - strokeColor = fillColor; - } - const isFillRule = /(even-?odd)|(non-?zero)/; - if (isFillRule.test(fillColor)) { - rule = fillColor; - fillColor = null; - } - - if (isFillRule.test(strokeColor)) { - rule = strokeColor; - strokeColor = fillColor; - } - - if (fillColor) { - this.fillColor(fillColor); - this.strokeColor(strokeColor); - } - - return this.addContent(`B${this._windingRule(rule)}`); - }, - - clip(rule) { - return this.addContent(`W${this._windingRule(rule)} n`); - }, - - transform(m11, m12, m21, m22, dx, dy) { - // keep track of the current transformation matrix - const m = this._ctm; - const [m0, m1, m2, m3, m4, m5] = m; - m[0] = m0 * m11 + m2 * m12; - m[1] = m1 * m11 + m3 * m12; - m[2] = m0 * m21 + m2 * m22; - m[3] = m1 * m21 + m3 * m22; - m[4] = m0 * dx + m2 * dy + m4; - m[5] = m1 * dx + m3 * dy + m5; - - const values = [m11, m12, m21, m22, dx, dy].map(v => number$1(v)).join(' '); - return this.addContent(`${values} cm`); - }, - - translate(x, y) { - return this.transform(1, 0, 0, 1, x, y); - }, - - rotate(angle, options = {}) { - let y; - const rad = (angle * Math.PI) / 180; - const cos = Math.cos(rad); - const sin = Math.sin(rad); - let x = (y = 0); - - if (options.origin != null) { - [x, y] = options.origin; - const x1 = x * cos - y * sin; - const y1 = x * sin + y * cos; - x -= x1; - y -= y1; - } - - return this.transform(cos, sin, -sin, cos, x, y); - }, - - scale(xFactor, yFactor, options = {}) { - let y; - if (yFactor == null) { - yFactor = xFactor; - } - if (typeof yFactor === 'object') { - options = yFactor; - yFactor = xFactor; - } - - let x = (y = 0); - if (options.origin != null) { - [x, y] = options.origin; - x -= xFactor * x; - y -= yFactor * y; - } - - return this.transform(xFactor, 0, 0, yFactor, x, y); } - }; + this._flushFlag = opts.flush || binding$1.Z_NO_FLUSH; - const MARKERS = [ - 0xffc0, - 0xffc1, - 0xffc2, - 0xffc3, - 0xffc5, - 0xffc6, - 0xffc7, - 0xffc8, - 0xffc9, - 0xffca, - 0xffcb, - 0xffcc, - 0xffcd, - 0xffce, - 0xffcf - ]; - - const COLOR_SPACE_MAP = { - 1: 'DeviceGray', - 3: 'DeviceRGB', - 4: 'DeviceCMYK' - }; - - class JPEG { - constructor(data, label) { - let marker; - this.data = data; - this.label = label; - if (this.data.readUInt16BE(0) !== 0xffd8) { - throw 'SOI not found in JPEG'; + if (opts.chunkSize) { + if (opts.chunkSize < binding$1.Z_MIN_CHUNK || + opts.chunkSize > binding$1.Z_MAX_CHUNK) { + throw new Error('Invalid chunk size: ' + opts.chunkSize); } + } - let pos = 2; - while (pos < this.data.length) { - marker = this.data.readUInt16BE(pos); - pos += 2; - if (MARKERS.includes(marker)) { - break; + if (opts.windowBits) { + if (opts.windowBits < binding$1.Z_MIN_WINDOWBITS || + opts.windowBits > binding$1.Z_MAX_WINDOWBITS) { + throw new Error('Invalid windowBits: ' + opts.windowBits); + } + } + + if (opts.level) { + if (opts.level < binding$1.Z_MIN_LEVEL || + opts.level > binding$1.Z_MAX_LEVEL) { + throw new Error('Invalid compression level: ' + opts.level); + } + } + + if (opts.memLevel) { + if (opts.memLevel < binding$1.Z_MIN_MEMLEVEL || + opts.memLevel > binding$1.Z_MAX_MEMLEVEL) { + throw new Error('Invalid memLevel: ' + opts.memLevel); + } + } + + if (opts.strategy) { + if (opts.strategy != binding$1.Z_FILTERED && + opts.strategy != binding$1.Z_HUFFMAN_ONLY && + opts.strategy != binding$1.Z_RLE && + opts.strategy != binding$1.Z_FIXED && + opts.strategy != binding$1.Z_DEFAULT_STRATEGY) { + throw new Error('Invalid strategy: ' + opts.strategy); + } + } + + if (opts.dictionary) { + if (!isBuffer(opts.dictionary)) { + throw new Error('Invalid dictionary: it should be a Buffer instance'); + } + } + + this._binding = new binding$1.Zlib(mode); + + var self = this; + this._hadError = false; + this._binding.onerror = function(message, errno) { + // there is no way to cleanly recover. + // continuing only obscures problems. + self._binding = null; + self._hadError = true; + + var error = new Error(message); + error.errno = errno; + error.code = binding$1.codes[errno]; + self.emit('error', error); + }; + + var level = binding$1.Z_DEFAULT_COMPRESSION; + if (typeof opts.level === 'number') level = opts.level; + + var strategy = binding$1.Z_DEFAULT_STRATEGY; + if (typeof opts.strategy === 'number') strategy = opts.strategy; + + this._binding.init(opts.windowBits || binding$1.Z_DEFAULT_WINDOWBITS, + level, + opts.memLevel || binding$1.Z_DEFAULT_MEMLEVEL, + strategy, + opts.dictionary); + + this._buffer = new Buffer(this._chunkSize); + this._offset = 0; + this._closed = false; + this._level = level; + this._strategy = strategy; + + this.once('end', this.close); + } + + inherits$1(Zlib$2, Transform); + + Zlib$2.prototype.params = function(level, strategy, callback) { + if (level < binding$1.Z_MIN_LEVEL || + level > binding$1.Z_MAX_LEVEL) { + throw new RangeError('Invalid compression level: ' + level); + } + if (strategy != binding$1.Z_FILTERED && + strategy != binding$1.Z_HUFFMAN_ONLY && + strategy != binding$1.Z_RLE && + strategy != binding$1.Z_FIXED && + strategy != binding$1.Z_DEFAULT_STRATEGY) { + throw new TypeError('Invalid strategy: ' + strategy); + } + + if (this._level !== level || this._strategy !== strategy) { + var self = this; + this.flush(binding$1.Z_SYNC_FLUSH, function() { + self._binding.params(level, strategy); + if (!self._hadError) { + self._level = level; + self._strategy = strategy; + if (callback) callback(); } - pos += this.data.readUInt16BE(pos); - } + }); + } else { + nextTick$1(callback); + } + }; - if (!MARKERS.includes(marker)) { - throw 'Invalid JPEG.'; - } - pos += 2; + Zlib$2.prototype.reset = function() { + return this._binding.reset(); + }; - this.bits = this.data[pos++]; - this.height = this.data.readUInt16BE(pos); - pos += 2; + // This is the _flush function called by the transform class, + // internally, when the last chunk has been written. + Zlib$2.prototype._flush = function(callback) { + this._transform(new Buffer(0), '', callback); + }; - this.width = this.data.readUInt16BE(pos); - pos += 2; + Zlib$2.prototype.flush = function(kind, callback) { + var ws = this._writableState; - const channels = this.data[pos++]; - this.colorSpace = COLOR_SPACE_MAP[channels]; - - this.obj = null; + if (typeof kind === 'function' || (kind === void 0 && !callback)) { + callback = kind; + kind = binding$1.Z_FULL_FLUSH; } - embed(document) { - if (this.obj) { - return; - } + if (ws.ended) { + if (callback) + nextTick$1(callback); + } else if (ws.ending) { + if (callback) + this.once('end', callback); + } else if (ws.needDrain) { + var self = this; + this.once('drain', function() { + self.flush(callback); + }); + } else { + this._flushFlag = kind; + this.write(new Buffer(0), '', callback); + } + }; - this.obj = document.ref({ - Type: 'XObject', - Subtype: 'Image', - BitsPerComponent: this.bits, - Width: this.width, - Height: this.height, - ColorSpace: this.colorSpace, - Filter: 'DCTDecode' + Zlib$2.prototype.close = function(callback) { + if (callback) + nextTick$1(callback); + + if (this._closed) + return; + + this._closed = true; + + this._binding.close(); + + var self = this; + nextTick$1(function() { + self.emit('close'); + }); + }; + + Zlib$2.prototype._transform = function(chunk, encoding, cb) { + var flushFlag; + var ws = this._writableState; + var ending = ws.ending || ws.ended; + var last = ending && (!chunk || ws.length === chunk.length); + + if (!chunk === null && !isBuffer(chunk)) + return cb(new Error('invalid input')); + + // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag. + // If it's explicitly flushing at some other time, then we use + // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression + // goodness. + if (last) + flushFlag = binding$1.Z_FINISH; + else { + flushFlag = this._flushFlag; + // once we've flushed the last of the queue, stop flushing and + // go back to the normal behavior. + if (chunk.length >= ws.length) { + this._flushFlag = this._opts.flush || binding$1.Z_NO_FLUSH; + } + } + + this._processChunk(chunk, flushFlag, cb); + }; + + Zlib$2.prototype._processChunk = function(chunk, flushFlag, cb) { + var availInBefore = chunk && chunk.length; + var availOutBefore = this._chunkSize - this._offset; + var inOff = 0; + + var self = this; + + var async = typeof cb === 'function'; + + if (!async) { + var buffers = []; + var nread = 0; + + var error; + this.on('error', function(er) { + error = er; }); - // add extra decode params for CMYK images. By swapping the - // min and max values from the default, we invert the colors. See - // section 4.8.4 of the spec. - if (this.colorSpace === 'DeviceCMYK') { - this.obj.data['Decode'] = [1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0]; + do { + var res = this._binding.writeSync(flushFlag, + chunk, // in + inOff, // in_off + availInBefore, // in_len + this._buffer, // out + this._offset, //out_off + availOutBefore); // out_len + } while (!this._hadError && callback(res[0], res[1])); + + if (this._hadError) { + throw error; } - this.obj.end(this.data); + var buf = Buffer.concat(buffers, nread); + this.close(); - // free memory - return (this.data = null); + return buf; } - } + + var req = this._binding.write(flushFlag, + chunk, // in + inOff, // in_off + availInBefore, // in_len + this._buffer, // out + this._offset, //out_off + availOutBefore); // out_len + + req.buffer = chunk; + req.callback = callback; + + function callback(availInAfter, availOutAfter) { + if (self._hadError) + return; + + var have = availOutBefore - availOutAfter; + assert$1(have >= 0, 'have should not go down'); + + if (have > 0) { + var out = self._buffer.slice(self._offset, self._offset + have); + self._offset += have; + // serve some output to the consumer. + if (async) { + self.push(out); + } else { + buffers.push(out); + nread += out.length; + } + } + + // exhausted the output buffer, or used all the input create a new one. + if (availOutAfter === 0 || self._offset >= self._chunkSize) { + availOutBefore = self._chunkSize; + self._offset = 0; + self._buffer = new Buffer(self._chunkSize); + } + + if (availOutAfter === 0) { + // Not actually done. Need to reprocess. + // Also, update the availInBefore to the availInAfter value, + // so that if we have to hit it a third (fourth, etc.) time, + // it'll have the correct byte counts. + inOff += (availInBefore - availInAfter); + availInBefore = availInAfter; + + if (!async) + return true; + + var newReq = self._binding.write(flushFlag, + chunk, + inOff, + availInBefore, + self._buffer, + self._offset, + self._chunkSize); + newReq.callback = callback; // this same function + newReq.buffer = chunk; + return; + } + + if (!async) + return false; + + // finished with the chunk. + cb(); + } + }; + + inherits$1(Deflate$1, Zlib$2); + inherits$1(Inflate$1, Zlib$2); + inherits$1(Gzip$1, Zlib$2); + inherits$1(Gunzip$1, Zlib$2); + inherits$1(DeflateRaw$1, Zlib$2); + inherits$1(InflateRaw$1, Zlib$2); + inherits$1(Unzip$1, Zlib$2); + var zlib$1 = { + codes: codes$1, + createDeflate: createDeflate$1, + createInflate: createInflate$1, + createDeflateRaw: createDeflateRaw$1, + createInflateRaw: createInflateRaw$1, + createGzip: createGzip$1, + createGunzip: createGunzip$1, + createUnzip: createUnzip$1, + deflate: deflate$2, + deflateSync: deflateSync$1, + gzip: gzip$1, + gzipSync: gzipSync$1, + deflateRaw: deflateRaw$1, + deflateRawSync: deflateRawSync$1, + unzip: unzip$1, + unzipSync: unzipSync$1, + inflate: inflate$2, + inflateSync: inflateSync$1, + gunzip: gunzip$1, + gunzipSync: gunzipSync$1, + inflateRaw: inflateRaw$1, + inflateRawSync: inflateRawSync$1, + Deflate: Deflate$1, + Inflate: Inflate$1, + Gzip: Gzip$1, + Gunzip: Gunzip$1, + DeflateRaw: DeflateRaw$1, + InflateRaw: InflateRaw$1, + Unzip: Unzip$1, + Zlib: Zlib$2 + }; /* * MIT LICENSE @@ -22530,14 +25048,14 @@ var pngNode = class PNG { static decode(path, fn) { - return fs.readFile(path, function(err, file) { + return fs$1.readFile(path, function(err, file) { const png = new PNG(file); return png.decode(pixels => fn(pixels)); }); } static load(path) { - const file = fs.readFileSync(path); + const file = fs$1.readFileSync(path); return new PNG(file); } @@ -22686,7 +25204,7 @@ } decodePixels(fn) { - return zlib.inflate(this.imgData, (err, data) => { + return zlib$1.inflate(this.imgData, (err, data) => { if (err) { throw err; } @@ -22907,393 +25425,393 @@ } }; - class PNGImage { - constructor(data, label) { - this.label = label; - this.image = new pngNode(data); - this.width = this.image.width; - this.height = this.image.height; - this.imgData = this.image.imgData; - this.obj = null; - } - - embed(document) { - let dataDecoded = false; - - this.document = document; - if (this.obj) { - return; - } - - const hasAlphaChannel = this.image.hasAlphaChannel; - const isInterlaced = this.image.interlaceMethod === 1; - - this.obj = this.document.ref({ - Type: 'XObject', - Subtype: 'Image', - BitsPerComponent: hasAlphaChannel ? 8 : this.image.bits, - Width: this.width, - Height: this.height, - Filter: 'FlateDecode' - }); - - if (!hasAlphaChannel) { - const params = this.document.ref({ - Predictor: isInterlaced ? 1 : 15, - Colors: this.image.colors, - BitsPerComponent: this.image.bits, - Columns: this.width - }); - - this.obj.data['DecodeParms'] = params; - params.end(); - } - - if (this.image.palette.length === 0) { - this.obj.data['ColorSpace'] = this.image.colorSpace; - } else { - // embed the color palette in the PDF as an object stream - const palette = this.document.ref(); - palette.end(new Buffer(this.image.palette)); - - // build the color space array for the image - this.obj.data['ColorSpace'] = [ - 'Indexed', - 'DeviceRGB', - this.image.palette.length / 3 - 1, - palette - ]; - } - - // For PNG color types 0, 2 and 3, the transparency data is stored in - // a dedicated PNG chunk. - if (this.image.transparency.grayscale != null) { - // Use Color Key Masking (spec section 4.8.5) - // An array with N elements, where N is two times the number of color components. - const val = this.image.transparency.grayscale; - this.obj.data['Mask'] = [val, val]; - } else if (this.image.transparency.rgb) { - // Use Color Key Masking (spec section 4.8.5) - // An array with N elements, where N is two times the number of color components. - const { rgb } = this.image.transparency; - const mask = []; - for (let x of rgb) { - mask.push(x, x); - } - - this.obj.data['Mask'] = mask; - } else if (this.image.transparency.indexed) { - // Create a transparency SMask for the image based on the data - // in the PLTE and tRNS sections. See below for details on SMasks. - dataDecoded = true; - return this.loadIndexedAlphaChannel(); - } else if (hasAlphaChannel) { - // For PNG color types 4 and 6, the transparency data is stored as a alpha - // channel mixed in with the main image data. Separate this data out into an - // SMask object and store it separately in the PDF. - dataDecoded = true; - return this.splitAlphaChannel(); - } - - if (isInterlaced && !dataDecoded) { - return this.decodeData(); - } - - this.finalize(); - } - - finalize() { - if (this.alphaChannel) { - const sMask = this.document.ref({ - Type: 'XObject', - Subtype: 'Image', - Height: this.height, - Width: this.width, - BitsPerComponent: 8, - Filter: 'FlateDecode', - ColorSpace: 'DeviceGray', - Decode: [0, 1] - }); - - sMask.end(this.alphaChannel); - this.obj.data['SMask'] = sMask; - } - - // add the actual image data - this.obj.end(this.imgData); - - // free memory - this.image = null; - return (this.imgData = null); - } - - splitAlphaChannel() { - return this.image.decodePixels(pixels => { - let a, p; - const colorCount = this.image.colors; - const pixelCount = this.width * this.height; - const imgData = new Buffer(pixelCount * colorCount); - const alphaChannel = new Buffer(pixelCount); - - let i = (p = a = 0); - const len = pixels.length; - // For 16bit images copy only most significant byte (MSB) - PNG data is always stored in network byte order (MSB first) - const skipByteCount = this.image.bits === 16 ? 1 : 0; - while (i < len) { - for (let colorIndex = 0; colorIndex < colorCount; colorIndex++) { - imgData[p++] = pixels[i++]; - i += skipByteCount; - } - alphaChannel[a++] = pixels[i++]; - i += skipByteCount; - } - - this.imgData = zlib.deflateSync(imgData); - this.alphaChannel = zlib.deflateSync(alphaChannel); - return this.finalize(); - }); - } - - loadIndexedAlphaChannel() { - const transparency = this.image.transparency.indexed; - return this.image.decodePixels(pixels => { - const alphaChannel = new Buffer(this.width * this.height); - - let i = 0; - for (let j = 0, end = pixels.length; j < end; j++) { - alphaChannel[i++] = transparency[pixels[j]]; - } - - this.alphaChannel = zlib.deflateSync(alphaChannel); - return this.finalize(); - }); - } - - decodeData() { - this.image.decodePixels(pixels => { - this.imgData = zlib.deflateSync(pixels); - this.finalize(); - }); - } + class PNGImage { + constructor(data, label) { + this.label = label; + this.image = new pngNode(data); + this.width = this.image.width; + this.height = this.image.height; + this.imgData = this.image.imgData; + this.obj = null; + } + + embed(document) { + let dataDecoded = false; + + this.document = document; + if (this.obj) { + return; + } + + const hasAlphaChannel = this.image.hasAlphaChannel; + const isInterlaced = this.image.interlaceMethod === 1; + + this.obj = this.document.ref({ + Type: 'XObject', + Subtype: 'Image', + BitsPerComponent: hasAlphaChannel ? 8 : this.image.bits, + Width: this.width, + Height: this.height, + Filter: 'FlateDecode' + }); + + if (!hasAlphaChannel) { + const params = this.document.ref({ + Predictor: isInterlaced ? 1 : 15, + Colors: this.image.colors, + BitsPerComponent: this.image.bits, + Columns: this.width + }); + + this.obj.data['DecodeParms'] = params; + params.end(); + } + + if (this.image.palette.length === 0) { + this.obj.data['ColorSpace'] = this.image.colorSpace; + } else { + // embed the color palette in the PDF as an object stream + const palette = this.document.ref(); + palette.end(new Buffer(this.image.palette)); + + // build the color space array for the image + this.obj.data['ColorSpace'] = [ + 'Indexed', + 'DeviceRGB', + this.image.palette.length / 3 - 1, + palette + ]; + } + + // For PNG color types 0, 2 and 3, the transparency data is stored in + // a dedicated PNG chunk. + if (this.image.transparency.grayscale != null) { + // Use Color Key Masking (spec section 4.8.5) + // An array with N elements, where N is two times the number of color components. + const val = this.image.transparency.grayscale; + this.obj.data['Mask'] = [val, val]; + } else if (this.image.transparency.rgb) { + // Use Color Key Masking (spec section 4.8.5) + // An array with N elements, where N is two times the number of color components. + const { rgb } = this.image.transparency; + const mask = []; + for (let x of rgb) { + mask.push(x, x); + } + + this.obj.data['Mask'] = mask; + } else if (this.image.transparency.indexed) { + // Create a transparency SMask for the image based on the data + // in the PLTE and tRNS sections. See below for details on SMasks. + dataDecoded = true; + return this.loadIndexedAlphaChannel(); + } else if (hasAlphaChannel) { + // For PNG color types 4 and 6, the transparency data is stored as a alpha + // channel mixed in with the main image data. Separate this data out into an + // SMask object and store it separately in the PDF. + dataDecoded = true; + return this.splitAlphaChannel(); + } + + if (isInterlaced && !dataDecoded) { + return this.decodeData(); + } + + this.finalize(); + } + + finalize() { + if (this.alphaChannel) { + const sMask = this.document.ref({ + Type: 'XObject', + Subtype: 'Image', + Height: this.height, + Width: this.width, + BitsPerComponent: 8, + Filter: 'FlateDecode', + ColorSpace: 'DeviceGray', + Decode: [0, 1] + }); + + sMask.end(this.alphaChannel); + this.obj.data['SMask'] = sMask; + } + + // add the actual image data + this.obj.end(this.imgData); + + // free memory + this.image = null; + return (this.imgData = null); + } + + splitAlphaChannel() { + return this.image.decodePixels(pixels => { + let a, p; + const colorCount = this.image.colors; + const pixelCount = this.width * this.height; + const imgData = new Buffer(pixelCount * colorCount); + const alphaChannel = new Buffer(pixelCount); + + let i = (p = a = 0); + const len = pixels.length; + // For 16bit images copy only most significant byte (MSB) - PNG data is always stored in network byte order (MSB first) + const skipByteCount = this.image.bits === 16 ? 1 : 0; + while (i < len) { + for (let colorIndex = 0; colorIndex < colorCount; colorIndex++) { + imgData[p++] = pixels[i++]; + i += skipByteCount; + } + alphaChannel[a++] = pixels[i++]; + i += skipByteCount; + } + + this.imgData = zlib.deflateSync(imgData); + this.alphaChannel = zlib.deflateSync(alphaChannel); + return this.finalize(); + }); + } + + loadIndexedAlphaChannel() { + const transparency = this.image.transparency.indexed; + return this.image.decodePixels(pixels => { + const alphaChannel = new Buffer(this.width * this.height); + + let i = 0; + for (let j = 0, end = pixels.length; j < end; j++) { + alphaChannel[i++] = transparency[pixels[j]]; + } + + this.alphaChannel = zlib.deflateSync(alphaChannel); + return this.finalize(); + }); + } + + decodeData() { + this.image.decodePixels(pixels => { + this.imgData = zlib.deflateSync(pixels); + this.finalize(); + }); + } } - class PDFImage { - static open(src, label) { - let data; - if (isBuffer(src)) { - data = src; - } else if (src instanceof ArrayBuffer) { - data = new Buffer(new Uint8Array(src)); - } else { - let match; - if ((match = /^data:.+;base64,(.*)$/.exec(src))) { - data = new Buffer(match[1], 'base64'); - } else { - data = fs.readFileSync(src); - if (!data) { - return; - } - } - } - - if (data[0] === 0xff && data[1] === 0xd8) { - return new JPEG(data, label); - } else if (data[0] === 0x89 && data.toString('ascii', 1, 4) === 'PNG') { - return new PNGImage(data, label); - } else { - throw new Error('Unknown image format.'); - } - } + class PDFImage { + static open(src, label) { + let data; + if (isBuffer(src)) { + data = src; + } else if (src instanceof ArrayBuffer) { + data = new Buffer(new Uint8Array(src)); + } else { + let match; + if ((match = /^data:.+;base64,(.*)$/.exec(src))) { + data = new Buffer(match[1], 'base64'); + } else { + data = fs.readFileSync(src); + if (!data) { + return; + } + } + } + + if (data[0] === 0xff && data[1] === 0xd8) { + return new JPEG(data, label); + } else if (data[0] === 0x89 && data.toString('ascii', 1, 4) === 'PNG') { + return new PNGImage(data, label); + } else { + throw new Error('Unknown image format.'); + } + } } - var ImagesMixin = { - initImages() { - this._imageRegistry = {}; - return (this._imageCount = 0); - }, - - image(src, x, y, options = {}) { - let bh, bp, bw, image, ip, left, left1; - if (typeof x === 'object') { - options = x; - x = null; - } - - x = (left = x != null ? x : options.x) != null ? left : this.x; - y = (left1 = y != null ? y : options.y) != null ? left1 : this.y; - - if (typeof src === 'string') { - image = this._imageRegistry[src]; - } - - if (!image) { - if (src.width && src.height) { - image = src; - } else { - image = this.openImage(src); - } - } - - if (!image.obj) { - image.embed(this); - } - - if (this.page.xobjects[image.label] == null) { - this.page.xobjects[image.label] = image.obj; - } - - let w = options.width || image.width; - let h = options.height || image.height; - - if (options.width && !options.height) { - const wp = w / image.width; - w = image.width * wp; - h = image.height * wp; - } else if (options.height && !options.width) { - const hp = h / image.height; - w = image.width * hp; - h = image.height * hp; - } else if (options.scale) { - w = image.width * options.scale; - h = image.height * options.scale; - } else if (options.fit) { - [bw, bh] = options.fit; - bp = bw / bh; - ip = image.width / image.height; - if (ip > bp) { - w = bw; - h = bw / ip; - } else { - h = bh; - w = bh * ip; - } - } else if (options.cover) { - [bw, bh] = options.cover; - bp = bw / bh; - ip = image.width / image.height; - if (ip > bp) { - h = bh; - w = bh * ip; - } else { - w = bw; - h = bw / ip; - } - } - - if (options.fit || options.cover) { - if (options.align === 'center') { - x = x + bw / 2 - w / 2; - } else if (options.align === 'right') { - x = x + bw - w; - } - - if (options.valign === 'center') { - y = y + bh / 2 - h / 2; - } else if (options.valign === 'bottom') { - y = y + bh - h; - } - } - - // create link annotations if the link option is given - if (options.link != null) { - this.link(x, y, w, h, options.link); - } - if (options.goTo != null) { - this.goTo(x, y, w, h, options.goTo); - } - if (options.destination != null) { - this.addNamedDestination(options.destination, 'XYZ', x, y, null); - } - - // Set the current y position to below the image if it is in the document flow - if (this.y === y) { - this.y += h; - } - - this.save(); - this.transform(w, 0, 0, -h, x, y + h); - this.addContent(`/${image.label} Do`); - this.restore(); - - return this; - }, - - openImage(src) { - let image; - if (typeof src === 'string') { - image = this._imageRegistry[src]; - } - - if (!image) { - image = PDFImage.open(src, `I${++this._imageCount}`); - if (typeof src === 'string') { - this._imageRegistry[src] = image; - } - } - - return image; - } + var ImagesMixin = { + initImages() { + this._imageRegistry = {}; + return (this._imageCount = 0); + }, + + image(src, x, y, options = {}) { + let bh, bp, bw, image, ip, left, left1; + if (typeof x === 'object') { + options = x; + x = null; + } + + x = (left = x != null ? x : options.x) != null ? left : this.x; + y = (left1 = y != null ? y : options.y) != null ? left1 : this.y; + + if (typeof src === 'string') { + image = this._imageRegistry[src]; + } + + if (!image) { + if (src.width && src.height) { + image = src; + } else { + image = this.openImage(src); + } + } + + if (!image.obj) { + image.embed(this); + } + + if (this.page.xobjects[image.label] == null) { + this.page.xobjects[image.label] = image.obj; + } + + let w = options.width || image.width; + let h = options.height || image.height; + + if (options.width && !options.height) { + const wp = w / image.width; + w = image.width * wp; + h = image.height * wp; + } else if (options.height && !options.width) { + const hp = h / image.height; + w = image.width * hp; + h = image.height * hp; + } else if (options.scale) { + w = image.width * options.scale; + h = image.height * options.scale; + } else if (options.fit) { + [bw, bh] = options.fit; + bp = bw / bh; + ip = image.width / image.height; + if (ip > bp) { + w = bw; + h = bw / ip; + } else { + h = bh; + w = bh * ip; + } + } else if (options.cover) { + [bw, bh] = options.cover; + bp = bw / bh; + ip = image.width / image.height; + if (ip > bp) { + h = bh; + w = bh * ip; + } else { + w = bw; + h = bw / ip; + } + } + + if (options.fit || options.cover) { + if (options.align === 'center') { + x = x + bw / 2 - w / 2; + } else if (options.align === 'right') { + x = x + bw - w; + } + + if (options.valign === 'center') { + y = y + bh / 2 - h / 2; + } else if (options.valign === 'bottom') { + y = y + bh - h; + } + } + + // create link annotations if the link option is given + if (options.link != null) { + this.link(x, y, w, h, options.link); + } + if (options.goTo != null) { + this.goTo(x, y, w, h, options.goTo); + } + if (options.destination != null) { + this.addNamedDestination(options.destination, 'XYZ', x, y, null); + } + + // Set the current y position to below the image if it is in the document flow + if (this.y === y) { + this.y += h; + } + + this.save(); + this.transform(w, 0, 0, -h, x, y + h); + this.addContent(`/${image.label} Do`); + this.restore(); + + return this; + }, + + openImage(src) { + let image; + if (typeof src === 'string') { + image = this._imageRegistry[src]; + } + + if (!image) { + image = PDFImage.open(src, `I${++this._imageCount}`); + if (typeof src === 'string') { + this._imageRegistry[src] = image; + } + } + + return image; + } }; - const bufferSize = 9007199254740991; - - var OutputDocument = { - - getStream() { - return this; - }, - - /** - * @returns {Promise} - */ - getBuffer() { - return new Promise((resolve, reject) => { - try { - let chunks = []; - let result; - this.getStream().on('readable', () => { - let chunk; - while ((chunk = this.getStream().read(bufferSize)) !== null) { - chunks.push(chunk); - } - }); - this.getStream().on('end', () => { - result = Buffer.concat(chunks); - resolve(result); - }); - this.getStream().end(); - } catch (e) { - reject(e); - } - }); - }, - - /** - * @returns {Promise} - */ - getBase64() { - return new Promise((resolve, reject) => { - this.getBuffer().then(buffer => { - resolve(buffer.toString('base64')); - }, result => { - reject(result); - }); - }); - }, - - /** - * @returns {Promise} - */ - getDataUrl() { - return new Promise((resolve, reject) => { - this.getBase64().then(data => { - resolve('data:application/pdf;base64,' + data); - }, result => { - reject(result); - }); - }); - }, - + const bufferSize = 9007199254740991; + + var OutputDocument = { + + getStream() { + return this; + }, + + /** + * @returns {Promise} + */ + getBuffer() { + return new Promise((resolve, reject) => { + try { + let chunks = []; + let result; + this.getStream().on('readable', () => { + let chunk; + while ((chunk = this.getStream().read(bufferSize)) !== null) { + chunks.push(chunk); + } + }); + this.getStream().on('end', () => { + result = Buffer.concat(chunks); + resolve(result); + }); + this.getStream().end(); + } catch (e) { + reject(e); + } + }); + }, + + /** + * @returns {Promise} + */ + getBase64() { + return new Promise((resolve, reject) => { + this.getBuffer().then(buffer => { + resolve(buffer.toString('base64')); + }, result => { + reject(result); + }); + }); + }, + + /** + * @returns {Promise} + */ + getDataUrl() { + return new Promise((resolve, reject) => { + this.getBase64().then(data => { + resolve('data:application/pdf;base64,' + data); + }, result => { + reject(result); + }); + }); + }, + }; var FileSaver = createCommonjsModule(function (module, exports) { @@ -23478,411 +25996,411 @@ }); }); - const bufferToBlob = buffer => { - let blob; - try { - blob = new Blob([buffer], { type: 'application/pdf' }); - } catch (e) { - // Old browser which can't handle it without making it an byte array (ie10) - if (e.name === 'InvalidStateError') { - let byteArray = new Uint8Array(buffer); - blob = new Blob([byteArray.buffer], { type: 'application/pdf' }); - } - } - - if (!blob) { - throw new Error('Could not generate blob'); - } - - return blob; - }; - - const openWindow = () => { - // we have to open the window immediately and store the reference - // otherwise popup blockers will stop us - let win = window.open('', '_blank'); - if (win === null) { - throw new Error('Open PDF in new window blocked by browser'); - } - - return win; - }; - - const OutputDocumentBrowser = Object.assign({}, OutputDocument, { - - /** - * @returns {Promise} - */ - getBlob() { - return new Promise((resolve, reject) => { - this.getBuffer().then(buffer => { - let blob = bufferToBlob(buffer); - resolve(blob); - }, result => { - reject(result); - }); - }); - }, - - /** - * @param {string} filename - * @returns {Promise} - */ - download(filename = 'file.pdf') { - return new Promise((resolve, reject) => { - this.getBlob().then(blob => { - FileSaver(blob, filename); - resolve(); - }, result => { - reject(result); - }); - }); - }, - - /** - * @param {Window} win - * @returns {Promise} - */ - open(win = null) { - return new Promise((resolve, reject) => { - if (!win) { - win = openWindow(); - } - this.getBlob().then(blob => { - try { - let urlCreator = window.URL || window.webkitURL; - let pdfUrl = urlCreator.createObjectURL(blob); - win.location.href = pdfUrl; - - // - resolve(); - /* temporarily disabled - if (win === window) { - resolve(); - } else { - setTimeout(() => { - if (win.window === null) { // is closed by AdBlock - window.location.href = pdfUrl; // open in actual window - } - resolve(); - }, 500); - } - */ - } catch (e) { - win.close(); - throw e; - } - }, result => { - reject(result); - }); - }); - }, - - /** - * @param {Window} win - * @returns {Promise} - */ - print(win = null) { - this.getStream().setOpenActionAsPrint(); - return this.open(win); - }, - + const bufferToBlob = buffer => { + let blob; + try { + blob = new Blob([buffer], { type: 'application/pdf' }); + } catch (e) { + // Old browser which can't handle it without making it an byte array (ie10) + if (e.name === 'InvalidStateError') { + let byteArray = new Uint8Array(buffer); + blob = new Blob([byteArray.buffer], { type: 'application/pdf' }); + } + } + + if (!blob) { + throw new Error('Could not generate blob'); + } + + return blob; + }; + + const openWindow = () => { + // we have to open the window immediately and store the reference + // otherwise popup blockers will stop us + let win = window.open('', '_blank'); + if (win === null) { + throw new Error('Open PDF in new window blocked by browser'); + } + + return win; + }; + + const OutputDocumentBrowser = Object.assign({}, OutputDocument, { + + /** + * @returns {Promise} + */ + getBlob() { + return new Promise((resolve, reject) => { + this.getBuffer().then(buffer => { + let blob = bufferToBlob(buffer); + resolve(blob); + }, result => { + reject(result); + }); + }); + }, + + /** + * @param {string} filename + * @returns {Promise} + */ + download(filename = 'file.pdf') { + return new Promise((resolve, reject) => { + this.getBlob().then(blob => { + FileSaver(blob, filename); + resolve(); + }, result => { + reject(result); + }); + }); + }, + + /** + * @param {Window} win + * @returns {Promise} + */ + open(win = null) { + return new Promise((resolve, reject) => { + if (!win) { + win = openWindow(); + } + this.getBlob().then(blob => { + try { + let urlCreator = window.URL || window.webkitURL; + let pdfUrl = urlCreator.createObjectURL(blob); + win.location.href = pdfUrl; + + // + resolve(); + /* temporarily disabled + if (win === window) { + resolve(); + } else { + setTimeout(() => { + if (win.window === null) { // is closed by AdBlock + window.location.href = pdfUrl; // open in actual window + } + resolve(); + }, 500); + } + */ + } catch (e) { + win.close(); + throw e; + } + }, result => { + reject(result); + }); + }); + }, + + /** + * @param {Window} win + * @returns {Promise} + */ + print(win = null) { + this.getStream().setOpenActionAsPrint(); + return this.open(win); + }, + }); - class PDFDocument extends Stream.Readable { - constructor(options = {}) { - super(options); - this.options = options; - - // PDF version - switch (options.pdfVersion) { - case '1.4': - this.version = 1.4; - break; - case '1.5': - this.version = 1.5; - break; - case '1.6': - this.version = 1.6; - break; - case '1.7': - case '1.7ext3': - this.version = 1.7; - break; - default: - this.version = 1.3; - break; - } - - // Whether streams should be compressed - this.compress = - this.options.compress != null ? this.options.compress : true; - - this._pageBuffer = []; - this._pageBufferStart = 0; - - // The PDF object store - this._offsets = []; - this._waiting = 0; - this._ended = false; - this._offset = 0; - const Pages = this.ref({ - Type: 'Pages', - Count: 0, - Kids: [] - }); - - const Names = this.ref({ - Dests: new PDFNameTree() - }); - - this._root = this.ref({ - Type: 'Catalog', - Pages, - Names - }); - - // The current page - this.page = null; - - // Initialize mixins - this.initColor(); - this.initVector(); - this.initImages(); - - // Initialize the metadata - this.info = { - Producer: 'PDFKit', - Creator: 'PDFKit', - CreationDate: new Date() - }; - - if (this.options.info) { - for (let key in this.options.info) { - const val = this.options.info[key]; - this.info[key] = val; - } - } - - // Generate file ID - this._id = PDFSecurity.generateFileID(this.info); - - // Initialize security settings - this._security = PDFSecurity.create(this, options); - - // Write the header - // PDF version - this._write(`%PDF-${this.version}`); - - // 4 binary chars, as recommended by the spec - this._write('%\xFF\xFF\xFF\xFF'); - - // Add the first page - if (this.options.autoFirstPage !== false) { - this.addPage(); - } - } - - addPage(options) { - // end the current page if needed - if (options == null) { - ({ options } = this); - } - if (!this.options.bufferPages) { - this.flushPages(); - } - - // create a page object - this.page = new PDFPage(this, options); - this._pageBuffer.push(this.page); - - // add the page to the object store - const pages = this._root.data.Pages.data; - pages.Kids.push(this.page.dictionary); - pages.Count++; - - // reset x and y coordinates - this.x = this.page.margins.left; - this.y = this.page.margins.top; - - // flip PDF coordinate system so that the origin is in - // the top left rather than the bottom left - this._ctm = [1, 0, 0, 1, 0, 0]; - this.transform(1, 0, 0, -1, 0, this.page.height); - - this.emit('pageAdded'); - - return this; - } - - bufferedPageRange() { - return { start: this._pageBufferStart, count: this._pageBuffer.length }; - } - - switchToPage(n) { - let page; - if (!(page = this._pageBuffer[n - this._pageBufferStart])) { - throw new Error( - `switchToPage(${n}) out of bounds, current buffer covers pages ${ - this._pageBufferStart - } to ${this._pageBufferStart + this._pageBuffer.length - 1}` - ); - } - - return (this.page = page); - } - - flushPages() { - // this local variable exists so we're future-proof against - // reentrant calls to flushPages. - const pages = this._pageBuffer; - this._pageBuffer = []; - this._pageBufferStart += pages.length; - for (let page of pages) { - page.end(); - } - } - - addNamedDestination(name, ...args) { - if (args.length === 0) { - args = ['XYZ', null, null, null]; - } - if (args[0] === 'XYZ' && args[2] !== null) { - args[2] = this.page.height - args[2]; - } - args.unshift(this.page.dictionary); - this._root.data.Names.data.Dests.add(name, args); - } - - ref(data) { - const ref = new PDFReference(this, this._offsets.length + 1, data); - this._offsets.push(null); // placeholder for this object's offset once it is finalized - this._waiting++; - return ref; - } - - _read() {} - // do nothing, but this method is required by node - - _write(data) { - if (!isBuffer(data)) { - data = new Buffer(data + '\n', 'binary'); - } - - this.push(data); - return (this._offset += data.length); - } - - addContent(data) { - this.page.write(data); - return this; - } - - _refEnd(ref) { - this._offsets[ref.id - 1] = ref.offset; - if (--this._waiting === 0 && this._ended) { - this._finalize(); - return (this._ended = false); - } - } - - write(filename, fn) { - // print a deprecation warning with a stacktrace - const err = new Error(`\ -PDFDocument#write is deprecated, and will be removed in a future version of PDFKit. \ -Please pipe the document into a Node stream.\ -`); - - console.warn(err.stack); - - this.pipe(fs.createWriteStream(filename)); - this.end(); - return this.once('end', fn); - } - - end() { - this.flushPages(); - this._info = this.ref(); - for (let key in this.info) { - let val = this.info[key]; - if (typeof val === 'string') { - val = new String(val); - } - - let entry = this.ref(val); - entry.end(); - - this._info.data[key] = entry; - } - - this._info.end(); - - for (let name in this._fontFamilies) { - const font = this._fontFamilies[name]; - font.finalize(); - } - - this._root.end(); - this._root.data.Pages.end(); - this._root.data.Names.end(); - - if (this._security) { - this._security.end(); - } - - if (this._waiting === 0) { - return this._finalize(); - } else { - return (this._ended = true); - } - } - - _finalize(fn) { - // generate xref - const xRefOffset = this._offset; - this._write('xref'); - this._write(`0 ${this._offsets.length + 1}`); - this._write('0000000000 65535 f '); - - for (let offset of this._offsets) { - offset = `0000000000${offset}`.slice(-10); - this._write(offset + ' 00000 n '); - } - - // trailer - const trailer = { - Size: this._offsets.length + 1, - Root: this._root, - Info: this._info, - ID: [this._id, this._id] - }; - if (this._security) { - trailer.Encrypt = this._security.dictionary; - } - - this._write('trailer'); - this._write(PDFObject.convert(trailer)); - - this._write('startxref'); - this._write(`${xRefOffset}`); - this._write('%%EOF'); - - // end the stream - return this.push(null); - } - - toString() { - return '[object PDFDocument]'; - } - } - - const mixin = methods => { - Object.assign(PDFDocument.prototype, methods); - }; - - mixin(ColorMixin); - mixin(VectorMixin); - mixin(ImagesMixin); + class PDFDocument extends Stream.Readable { + constructor(options = {}) { + super(options); + this.options = options; + + // PDF version + switch (options.pdfVersion) { + case '1.4': + this.version = 1.4; + break; + case '1.5': + this.version = 1.5; + break; + case '1.6': + this.version = 1.6; + break; + case '1.7': + case '1.7ext3': + this.version = 1.7; + break; + default: + this.version = 1.3; + break; + } + + // Whether streams should be compressed + this.compress = + this.options.compress != null ? this.options.compress : true; + + this._pageBuffer = []; + this._pageBufferStart = 0; + + // The PDF object store + this._offsets = []; + this._waiting = 0; + this._ended = false; + this._offset = 0; + const Pages = this.ref({ + Type: 'Pages', + Count: 0, + Kids: [] + }); + + const Names = this.ref({ + Dests: new PDFNameTree() + }); + + this._root = this.ref({ + Type: 'Catalog', + Pages, + Names + }); + + // The current page + this.page = null; + + // Initialize mixins + this.initColor(); + this.initVector(); + this.initImages(); + + // Initialize the metadata + this.info = { + Producer: 'PDFKit', + Creator: 'PDFKit', + CreationDate: new Date() + }; + + if (this.options.info) { + for (let key in this.options.info) { + const val = this.options.info[key]; + this.info[key] = val; + } + } + + // Generate file ID + this._id = PDFSecurity.generateFileID(this.info); + + // Initialize security settings + this._security = PDFSecurity.create(this, options); + + // Write the header + // PDF version + this._write(`%PDF-${this.version}`); + + // 4 binary chars, as recommended by the spec + this._write('%\xFF\xFF\xFF\xFF'); + + // Add the first page + if (this.options.autoFirstPage !== false) { + this.addPage(); + } + } + + addPage(options) { + // end the current page if needed + if (options == null) { + ({ options } = this); + } + if (!this.options.bufferPages) { + this.flushPages(); + } + + // create a page object + this.page = new PDFPage(this, options); + this._pageBuffer.push(this.page); + + // add the page to the object store + const pages = this._root.data.Pages.data; + pages.Kids.push(this.page.dictionary); + pages.Count++; + + // reset x and y coordinates + this.x = this.page.margins.left; + this.y = this.page.margins.top; + + // flip PDF coordinate system so that the origin is in + // the top left rather than the bottom left + this._ctm = [1, 0, 0, 1, 0, 0]; + this.transform(1, 0, 0, -1, 0, this.page.height); + + this.emit('pageAdded'); + + return this; + } + + bufferedPageRange() { + return { start: this._pageBufferStart, count: this._pageBuffer.length }; + } + + switchToPage(n) { + let page; + if (!(page = this._pageBuffer[n - this._pageBufferStart])) { + throw new Error( + `switchToPage(${n}) out of bounds, current buffer covers pages ${ + this._pageBufferStart + } to ${this._pageBufferStart + this._pageBuffer.length - 1}` + ); + } + + return (this.page = page); + } + + flushPages() { + // this local variable exists so we're future-proof against + // reentrant calls to flushPages. + const pages = this._pageBuffer; + this._pageBuffer = []; + this._pageBufferStart += pages.length; + for (let page of pages) { + page.end(); + } + } + + addNamedDestination(name, ...args) { + if (args.length === 0) { + args = ['XYZ', null, null, null]; + } + if (args[0] === 'XYZ' && args[2] !== null) { + args[2] = this.page.height - args[2]; + } + args.unshift(this.page.dictionary); + this._root.data.Names.data.Dests.add(name, args); + } + + ref(data) { + const ref = new PDFReference(this, this._offsets.length + 1, data); + this._offsets.push(null); // placeholder for this object's offset once it is finalized + this._waiting++; + return ref; + } + + _read() {} + // do nothing, but this method is required by node + + _write(data) { + if (!isBuffer(data)) { + data = new Buffer(data + '\n', 'binary'); + } + + this.push(data); + return (this._offset += data.length); + } + + addContent(data) { + this.page.write(data); + return this; + } + + _refEnd(ref) { + this._offsets[ref.id - 1] = ref.offset; + if (--this._waiting === 0 && this._ended) { + this._finalize(); + return (this._ended = false); + } + } + + write(filename, fn) { + // print a deprecation warning with a stacktrace + const err = new Error(`\ +PDFDocument#write is deprecated, and will be removed in a future version of PDFKit. \ +Please pipe the document into a Node stream.\ +`); + + console.warn(err.stack); + + this.pipe(fs.createWriteStream(filename)); + this.end(); + return this.once('end', fn); + } + + end() { + this.flushPages(); + this._info = this.ref(); + for (let key in this.info) { + let val = this.info[key]; + if (typeof val === 'string') { + val = new String(val); + } + + let entry = this.ref(val); + entry.end(); + + this._info.data[key] = entry; + } + + this._info.end(); + + for (let name in this._fontFamilies) { + const font = this._fontFamilies[name]; + font.finalize(); + } + + this._root.end(); + this._root.data.Pages.end(); + this._root.data.Names.end(); + + if (this._security) { + this._security.end(); + } + + if (this._waiting === 0) { + return this._finalize(); + } else { + return (this._ended = true); + } + } + + _finalize(fn) { + // generate xref + const xRefOffset = this._offset; + this._write('xref'); + this._write(`0 ${this._offsets.length + 1}`); + this._write('0000000000 65535 f '); + + for (let offset of this._offsets) { + offset = `0000000000${offset}`.slice(-10); + this._write(offset + ' 00000 n '); + } + + // trailer + const trailer = { + Size: this._offsets.length + 1, + Root: this._root, + Info: this._info, + ID: [this._id, this._id] + }; + if (this._security) { + trailer.Encrypt = this._security.dictionary; + } + + this._write('trailer'); + this._write(PDFObject.convert(trailer)); + + this._write('startxref'); + this._write(`${xRefOffset}`); + this._write('%%EOF'); + + // end the stream + return this.push(null); + } + + toString() { + return '[object PDFDocument]'; + } + } + + const mixin = methods => { + Object.assign(PDFDocument.prototype, methods); + }; + + mixin(ColorMixin); + mixin(VectorMixin); + mixin(ImagesMixin); mixin(OutputDocumentBrowser); var source = createCommonjsModule(function (module) { @@ -26734,7 +29252,7 @@ Please pipe the document into a Node stream.\ // read further error msg const err = cidRes.Message; if (err.includes('no link named')) { // file not found - throw new Error('score not in dataset'); + throw new Error('Score not in dataset'); } else { throw new Error(err); @@ -26900,7 +29418,7 @@ Please pipe the document into a Node stream.\ // detect browser language const lang = (() => { let userLangs; - if (!detectNode) { + if (!C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_detectNode) { userLangs = navigator.languages; } else { @@ -26939,7 +29457,7 @@ Please pipe the document into a Node stream.\ const SF3_URL = `https://cdn.jsdelivr.net/npm/@librescore/sf3@${dependencies['@librescore/sf3']}/FluidR3Mono_GM.sf3`; const SOUND_FONT_LOADED = Symbol('SoundFont loaded'); const initMscore = (w) => __awaiter(void 0, void 0, void 0, function* () { - if (!detectNode) { // attached to a page + if (!C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_detectNode) { // attached to a page if (!w['WebMscore']) { // init webmscore (https://github.com/LibreScore/webmscore) const script = w.document.createElement('script'); @@ -26958,7 +29476,7 @@ Please pipe the document into a Node stream.\ // load CJK fonts // CJK (East Asian) characters will be rendered as "tofu" if there is no font if (!fonts) { - if (detectNode) { + if (C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_detectNode) { // module.exports.CN = ..., module.exports.KR = ... const FONTS = Object.values(require('@librescore/fonts')); const fs = require('fs'); @@ -26973,7 +29491,7 @@ Please pipe the document into a Node stream.\ if (!score[SOUND_FONT_LOADED]) { const loadPromise = (() => __awaiter(void 0, void 0, void 0, function* () { let data; - if (detectNode) { + if (C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_detectNode) { // module.exports.FluidR3Mono = ... const SF3 = Object.values(require('@librescore/sf3'))[0]; const fs = require('fs'); @@ -27038,7 +29556,7 @@ Please pipe the document into a Node stream.\ const _getLink = (scorepack) => { return `https://librescore.org/score/${scorepack}`; }; - const getLibreScoreLink = (scoreinfo, _fetch = getFetch()) => __awaiter(void 0, void 0, void 0, function* () { + const getLibreScoreLink = (scoreinfo, isMsdl, _fetch = getFetch()) => __awaiter(void 0, void 0, void 0, function* () { const mainCid = yield getMainCid(scoreinfo, _fetch); const ref = scoreinfo.getScorepackRef(mainCid); const url = `https://ipfs.infura.io:5001/api/v0/dag/get?arg=${ref}`; @@ -27047,14 +29565,14 @@ Please pipe the document into a Node stream.\ assertRes(r0); } const res = yield r0.json(); - if (typeof res !== 'string') { + if (typeof res !== 'string' && !isMsdl) { // read further error msg throw new Error(res.Message); } return _getLink(res); }); - var btnListCss = "div {\n width: 422px;\n right: 0;\n margin: 0 18px 18px 0;\n\n text-align: center;\n align-items: center;\n font-family: 'Open Sans', 'Roboto', 'Helvetica neue', Helvetica, sans-serif;\n position: absolute;\n z-index: 9999;\n background: #f6f6f6;\n min-width: 230px;\n\n /* pass the scroll event through the btns background */\n pointer-events: none;\n}\n\n@media screen and (max-width: 950px) {\n div {\n width: auto !important;\n }\n}\n\nbutton {\n width: 205px !important;\n min-width: 205px;\n height: 38px;\n\n color: #fff;\n background: #1f74bd;\n\n cursor: pointer;\n pointer-events: auto;\n\n margin-bottom: 4px;\n margin-right: 4px;\n padding: 4px 12px;\n\n justify-content: start;\n align-self: center;\n\n font-size: 16px;\n border-radius: 2px;\n border: 0;\n\n display: inline-flex;\n position: relative;\n\n font-family: inherit;\n}\n\n/* fix `View in LibreScore` button text overflow */\nbutton:last-of-type {\n width: unset !important;\n}\n\nsvg {\n display: inline-block;\n margin-right: 5px;\n width: 20px;\n height: 20px;\n margin-top: auto;\n margin-bottom: auto;\n}\n\nspan {\n margin-top: auto;\n margin-bottom: auto;\n}"; + var btnListCss = "div {\r\n width: 422px;\r\n right: 0;\r\n margin: 0 18px 18px 0;\r\n\r\n text-align: center;\r\n align-items: center;\r\n font-family: 'Open Sans', 'Roboto', 'Helvetica neue', Helvetica, sans-serif;\r\n position: absolute;\r\n z-index: 9999;\r\n background: #f6f6f6;\r\n min-width: 230px;\r\n\r\n /* pass the scroll event through the btns background */\r\n pointer-events: none;\r\n}\r\n\r\n@media screen and (max-width: 950px) {\r\n div {\r\n width: auto !important;\r\n }\r\n}\r\n\r\nbutton {\r\n width: 205px !important;\r\n min-width: 205px;\r\n height: 38px;\r\n\r\n color: #fff;\r\n background: #1f74bd;\r\n\r\n cursor: pointer;\r\n pointer-events: auto;\r\n\r\n margin-bottom: 4px;\r\n margin-right: 4px;\r\n padding: 4px 12px;\r\n\r\n justify-content: start;\r\n align-self: center;\r\n\r\n font-size: 16px;\r\n border-radius: 2px;\r\n border: 0;\r\n\r\n display: inline-flex;\r\n position: relative;\r\n\r\n font-family: inherit;\r\n}\r\n\r\n/* fix `View in LibreScore` button text overflow */\r\nbutton:last-of-type {\r\n width: unset !important;\r\n}\r\n\r\nsvg {\r\n display: inline-block;\r\n margin-right: 5px;\r\n width: 20px;\r\n height: 20px;\r\n margin-top: auto;\r\n margin-bottom: auto;\r\n}\r\n\r\nspan {\r\n margin-top: auto;\r\n margin-bottom: auto;\r\n}"; var ICON; (function (ICON) { diff --git a/src/cli.ts b/src/cli.ts index fc60273..e4c58b7 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -88,7 +88,7 @@ void (async () => { if (!confirmed) return // initiate LibreScore link request - librescoreLink = getLibreScoreLink(scoreinfo) + librescoreLink = getLibreScoreLink(scoreinfo, true) // print a blank line to the terminal console.log() @@ -133,6 +133,7 @@ void (async () => { spinner.info('Score loaded by webmscore') } catch (err) { spinner.fail(err.message) + spinner.info('Send your URL to the #dataset-bugs channel in the LibreScore Community Discord server'); return } spinner.succeed('OK\n') diff --git a/src/librescore-link.ts b/src/librescore-link.ts index 04d8044..4b06c3c 100644 --- a/src/librescore-link.ts +++ b/src/librescore-link.ts @@ -6,7 +6,7 @@ const _getLink = (scorepack: string) => { return `https://librescore.org/score/${scorepack}` } -export const getLibreScoreLink = async (scoreinfo: ScoreInfo, _fetch = getFetch()): Promise => { +export const getLibreScoreLink = async (scoreinfo: ScoreInfo, isMsdl: Boolean, _fetch = getFetch()): Promise => { const mainCid = await getMainCid(scoreinfo, _fetch) const ref = scoreinfo.getScorepackRef(mainCid) const url = `https://ipfs.infura.io:5001/api/v0/dag/get?arg=${ref}` @@ -16,7 +16,7 @@ export const getLibreScoreLink = async (scoreinfo: ScoreInfo, _fetch = getFetch( assertRes(r0) } const res: { Message: string } | string = await r0.json() - if (typeof res !== 'string') { + if (typeof res !== 'string' && !isMsdl) { // read further error msg throw new Error(res.Message) } diff --git a/src/mscz.ts b/src/mscz.ts index a2e43e5..7234162 100644 --- a/src/mscz.ts +++ b/src/mscz.ts @@ -48,7 +48,7 @@ export const loadMsczUrl = async (scoreinfo: ScoreInfo, _fetch = getFetch()): Pr // read further error msg const err = cidRes.Message if (err.includes('no link named')) { // file not found - throw new Error('score not in dataset') + throw new Error('Score not in dataset') } else { throw new Error(err) } From 4494e155405aa82bd224f2631ca5158e4ce1fe98 Mon Sep 17 00:00:00 2001 From: Peter Njeim Date: Fri, 12 Mar 2021 20:10:50 -0400 Subject: [PATCH 2/3] feat: include discord link in message, npm audit fixes, and typescript handbook standards --- package-lock.json | 26 +++++++++++++++++--------- src/cli.ts | 3 ++- src/librescore-link.ts | 2 +- 3 files changed, 20 insertions(+), 11 deletions(-) diff --git a/package-lock.json b/package-lock.json index b8b6b8c..8625880 100644 --- a/package-lock.json +++ b/package-lock.json @@ -709,18 +709,26 @@ } }, "elliptic": { - "version": "6.5.3", - "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.3.tgz", - "integrity": "sha512-IMqzv5wNQf+E6aHeIqATs0tOLeOTwj1QKbRcS3jBbYkl5oLAserA8yJTT7/VyHUYG91PRmPyeQDObKLPpeS4dw==", + "version": "6.5.4", + "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.4.tgz", + "integrity": "sha512-iLhC6ULemrljPZb+QutR5TQGB+pdW6KGD5RSegS+8sorOZT+rdQFbsQFJgvN3eRqNALqJer4oQ16YvJHlU8hzQ==", "dev": true, "requires": { - "bn.js": "^4.4.0", - "brorand": "^1.0.1", + "bn.js": "^4.11.9", + "brorand": "^1.1.0", "hash.js": "^1.0.0", - "hmac-drbg": "^1.0.0", - "inherits": "^2.0.1", - "minimalistic-assert": "^1.0.0", - "minimalistic-crypto-utils": "^1.0.0" + "hmac-drbg": "^1.0.1", + "inherits": "^2.0.4", + "minimalistic-assert": "^1.0.1", + "minimalistic-crypto-utils": "^1.0.1" + }, + "dependencies": { + "bn.js": { + "version": "4.12.0", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", + "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==", + "dev": true + } } }, "emoji-regex": { diff --git a/src/cli.ts b/src/cli.ts index e4c58b7..3a1b98e 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -133,7 +133,8 @@ void (async () => { spinner.info('Score loaded by webmscore') } catch (err) { spinner.fail(err.message) - spinner.info('Send your URL to the #dataset-bugs channel in the LibreScore Community Discord server'); + spinner.info( + "Send your URL to the #dataset-bugs channel in the LibreScore Community Discord server:\n https://discord.gg/kTyx6nUjMv"); return } spinner.succeed('OK\n') diff --git a/src/librescore-link.ts b/src/librescore-link.ts index 4b06c3c..bdcc5cf 100644 --- a/src/librescore-link.ts +++ b/src/librescore-link.ts @@ -6,7 +6,7 @@ const _getLink = (scorepack: string) => { return `https://librescore.org/score/${scorepack}` } -export const getLibreScoreLink = async (scoreinfo: ScoreInfo, isMsdl: Boolean, _fetch = getFetch()): Promise => { +export const getLibreScoreLink = async (scoreinfo: ScoreInfo, isMsdl: boolean, _fetch = getFetch()): Promise => { const mainCid = await getMainCid(scoreinfo, _fetch) const ref = scoreinfo.getScorepackRef(mainCid) const url = `https://ipfs.infura.io:5001/api/v0/dag/get?arg=${ref}` From ec15d44811aef1e7103c5babab1fa352d42d9339 Mon Sep 17 00:00:00 2001 From: Peter Njeim Date: Fri, 12 Mar 2021 20:20:27 -0400 Subject: [PATCH 3/3] revert: dist/main.js --- dist/main.js | 13098 ++++++++++++++++++++----------------------------- 1 file changed, 5290 insertions(+), 7808 deletions(-) diff --git a/dist/main.js b/dist/main.js index 1a1ea24..3b58434 100644 --- a/dist/main.js +++ b/dist/main.js @@ -1,78 +1,78 @@ -// ==UserScript== -// @name musescore-downloader -// @namespace https://www.xmader.com/ -// @homepageURL https://github.com/Xmader/musescore-downloader/ -// @supportURL https://github.com/Xmader/musescore-downloader/issues -// @updateURL https://msdl.librescore.org/install.user.js -// @downloadURL https://msdl.librescore.org/install.user.js -// @version 0.23.9 -// @description download sheet music from musescore.com for free, no login or Musescore Pro required | 免登录、免 Musescore Pro,免费下载 musescore.com 上的曲谱 -// @author Xmader -// @match https://musescore.com/*/* -// @match https://s.musescore.com/*/* -// @license MIT -// @copyright Copyright (c) 2019-2021 Xmader -// @grant unsafeWindow -// @grant GM.registerMenuCommand -// @grant GM.addElement -// @grant GM.openInTab -// @run-at document-start -// ==/UserScript== +// ==UserScript== +// @name musescore-downloader +// @namespace https://www.xmader.com/ +// @homepageURL https://github.com/Xmader/musescore-downloader/ +// @supportURL https://github.com/Xmader/musescore-downloader/issues +// @updateURL https://msdl.librescore.org/install.user.js +// @downloadURL https://msdl.librescore.org/install.user.js +// @version 0.23.9 +// @description download sheet music from musescore.com for free, no login or Musescore Pro required | 免登录、免 Musescore Pro,免费下载 musescore.com 上的曲谱 +// @author Xmader +// @match https://musescore.com/*/* +// @match https://s.musescore.com/*/* +// @license MIT +// @copyright Copyright (c) 2019-2021 Xmader +// @grant unsafeWindow +// @grant GM.registerMenuCommand +// @grant GM.addElement +// @grant GM.openInTab +// @run-at document-start +// ==/UserScript== (function () { 'use strict'; - /* eslint-disable */ - const w = typeof unsafeWindow == 'object' ? unsafeWindow : window; - - // GM APIs glue - const _GM = typeof GM == 'object' ? GM : undefined; - const gmId = '' + Math.random(); - w[gmId] = _GM; - - if (_GM && _GM.registerMenuCommand && _GM.openInTab) { - // add buttons to the userscript manager menu - _GM.registerMenuCommand( - `** Version: ${_GM.info.script.version} **`, - () => _GM.openInTab("https://github.com/Xmader/musescore-downloader/releases", { active: true }) - ) - - _GM.registerMenuCommand( - '** Source Code **', - () => _GM.openInTab(_GM.info.script.homepage, { active: true }) - ) - - _GM.registerMenuCommand( - '** Discord **', - () => _GM.openInTab("https://discord.gg/DKu7cUZ4XQ", { active: true }) - ) - } - - function getRandL () { - return String.fromCharCode(97 + Math.floor(Math.random() * 26)) - } - - // script loader - new Promise(resolve => { - const id = '' + Math.random(); - w[id] = resolve; - - const stackN = 9 - let loaderIntro = '' - for (let i = 0; i < stackN; i++) { - loaderIntro += `(function ${getRandL()}(){` - } - const loaderOutro = '})()'.repeat(stackN) - const mockUrl = "https://c.amazon-adsystem.com/aax2/apstag.js" - - setTimeout(`${loaderIntro}const d=new Image();window['${id}'](d);delete window['${id}'];document.body.prepend(d)${loaderOutro}//# sourceURL=${mockUrl}`) - }).then(d => { - d.style.display = 'none'; - d.src = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='; - d.once = false; - d.setAttribute('onload', `if(this.once)return;this.once=true;this.remove();const GM=window['${gmId}'];delete window['${gmId}'];(` + function a () { - /** script code here */ - + /* eslint-disable */ + const w = typeof unsafeWindow == 'object' ? unsafeWindow : window; + + // GM APIs glue + const _GM = typeof GM == 'object' ? GM : undefined; + const gmId = '' + Math.random(); + w[gmId] = _GM; + + if (_GM && _GM.registerMenuCommand && _GM.openInTab) { + // add buttons to the userscript manager menu + _GM.registerMenuCommand( + `** Version: ${_GM.info.script.version} **`, + () => _GM.openInTab("https://github.com/Xmader/musescore-downloader/releases", { active: true }) + ) + + _GM.registerMenuCommand( + '** Source Code **', + () => _GM.openInTab(_GM.info.script.homepage, { active: true }) + ) + + _GM.registerMenuCommand( + '** Discord **', + () => _GM.openInTab("https://discord.gg/DKu7cUZ4XQ", { active: true }) + ) + } + + function getRandL () { + return String.fromCharCode(97 + Math.floor(Math.random() * 26)) + } + + // script loader + new Promise(resolve => { + const id = '' + Math.random(); + w[id] = resolve; + + const stackN = 9 + let loaderIntro = '' + for (let i = 0; i < stackN; i++) { + loaderIntro += `(function ${getRandL()}(){` + } + const loaderOutro = '})()'.repeat(stackN) + const mockUrl = "https://c.amazon-adsystem.com/aax2/apstag.js" + + setTimeout(`${loaderIntro}const d=new Image();window['${id}'](d);delete window['${id}'];document.body.prepend(d)${loaderOutro}//# sourceURL=${mockUrl}`) + }).then(d => { + d.style.display = 'none'; + d.src = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='; + d.once = false; + d.setAttribute('onload', `if(this.once)return;this.once=true;this.remove();const GM=window['${gmId}'];delete window['${gmId}'];(` + function a () { + /** script code here */ + function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } @@ -323,7 +323,7 @@ }; // Only Node.JS has a process variable that is of [[Class]] process - var C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_detectNode = Object.prototype.toString.call(typeof process$1 !== 'undefined' ? process$1 : 0) === '[object process]'; + var detectNode = Object.prototype.toString.call(typeof process$1 !== 'undefined' ? process$1 : 0) === '[object process]'; const _GM = (typeof GM === 'object' ? GM : undefined); const isGmAvailable = (requiredMethod = 'info') => { @@ -339,7 +339,7 @@ 'Accept-Language': 'en-US,en;q=0.8', }; const getFetch = () => { - if (!C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_detectNode) { + if (!detectNode) { return fetch; } else { @@ -3533,1766 +3533,6 @@ return Object.prototype.hasOwnProperty.call(obj, prop); } - var INSPECT_MAX_BYTES$1 = 50; - - /** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ - Buffer$1.TYPED_ARRAY_SUPPORT = global$1$1.TYPED_ARRAY_SUPPORT !== undefined - ? global$1$1.TYPED_ARRAY_SUPPORT - : true; - - function kMaxLength$1 () { - return Buffer$1.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff - } - - function createBuffer$1 (that, length) { - if (kMaxLength$1() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length); - that.__proto__ = Buffer$1.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer$1(length); - } - that.length = length; - } - - return that - } - - /** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - - function Buffer$1 (arg, encodingOrOffset, length) { - if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) { - return new Buffer$1(arg, encodingOrOffset, length) - } - - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe$1(this, arg) - } - return from$1(this, arg, encodingOrOffset, length) - } - - Buffer$1.poolSize = 8192; // not used by this implementation - - // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer$1._augment = function (arr) { - arr.__proto__ = Buffer$1.prototype; - return arr - }; - - function from$1 (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } - - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer$1(that, value, encodingOrOffset, length) - } - - if (typeof value === 'string') { - return fromString$1(that, value, encodingOrOffset) - } - - return fromObject$1(that, value) - } - - /** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ - Buffer$1.from = function (value, encodingOrOffset, length) { - return from$1(null, value, encodingOrOffset, length) - }; - - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - Buffer$1.prototype.__proto__ = Uint8Array.prototype; - Buffer$1.__proto__ = Uint8Array; - } - - function assertSize$1 (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } - } - - function alloc$1 (that, size, fill, encoding) { - assertSize$1(size); - if (size <= 0) { - return createBuffer$1(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer$1(that, size).fill(fill, encoding) - : createBuffer$1(that, size).fill(fill) - } - return createBuffer$1(that, size) - } - - /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ - Buffer$1.alloc = function (size, fill, encoding) { - return alloc$1(null, size, fill, encoding) - }; - - function allocUnsafe$1 (that, size) { - assertSize$1(size); - that = createBuffer$1(that, size < 0 ? 0 : checked$1(size) | 0); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0; - } - } - return that - } - - /** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ - Buffer$1.allocUnsafe = function (size) { - return allocUnsafe$1(null, size) - }; - /** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ - Buffer$1.allocUnsafeSlow = function (size) { - return allocUnsafe$1(null, size) - }; - - function fromString$1 (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8'; - } - - if (!Buffer$1.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } - - var length = byteLength$1(string, encoding) | 0; - that = createBuffer$1(that, length); - - var actual = that.write(string, encoding); - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual); - } - - return that - } - - function fromArrayLike$1 (that, array) { - var length = array.length < 0 ? 0 : checked$1(array.length) | 0; - that = createBuffer$1(that, length); - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255; - } - return that - } - - function fromArrayBuffer$1 (that, array, byteOffset, length) { - array.byteLength; // this throws if `array` is not a valid ArrayBuffer - - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } - - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array); - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset); - } else { - array = new Uint8Array(array, byteOffset, length); - } - - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array; - that.__proto__ = Buffer$1.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike$1(that, array); - } - return that - } - - function fromObject$1 (that, obj) { - if (internalIsBuffer$1(obj)) { - var len = checked$1(obj.length) | 0; - that = createBuffer$1(that, len); - - if (that.length === 0) { - return that - } - - obj.copy(that, 0, 0, len); - return that - } - - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan$1(obj.length)) { - return createBuffer$1(that, 0) - } - return fromArrayLike$1(that, obj) - } - - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike$1(that, obj.data) - } - } - - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') - } - - function checked$1 (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength$1()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength$1().toString(16) + ' bytes') - } - return length | 0 - } - Buffer$1.isBuffer = isBuffer$1; - function internalIsBuffer$1 (b) { - return !!(b != null && b._isBuffer) - } - - Buffer$1.compare = function compare (a, b) { - if (!internalIsBuffer$1(a) || !internalIsBuffer$1(b)) { - throw new TypeError('Arguments must be Buffers') - } - - if (a === b) return 0 - - var x = a.length; - var y = b.length; - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 - }; - - Buffer$1.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } - }; - - Buffer$1.concat = function concat (list, length) { - if (!isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer$1.alloc(0) - } - - var i; - if (length === undefined) { - length = 0; - for (i = 0; i < list.length; ++i) { - length += list[i].length; - } - } - - var buffer = Buffer$1.allocUnsafe(length); - var pos = 0; - for (i = 0; i < list.length; ++i) { - var buf = list[i]; - if (!internalIsBuffer$1(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos); - pos += buf.length; - } - return buffer - }; - - function byteLength$1 (string, encoding) { - if (internalIsBuffer$1(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string; - } - - var len = string.length; - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false; - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes$1(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes$1(string).length - default: - if (loweredCase) return utf8ToBytes$1(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } - } - Buffer$1.byteLength = byteLength$1; - - function slowToString$1 (encoding, start, end) { - var loweredCase = false; - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0; - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length; - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0; - start >>>= 0; - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8'; - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice$1(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice$1(this, start, end) - - case 'ascii': - return asciiSlice$1(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice$1(this, start, end) - - case 'base64': - return base64Slice$1(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice$1(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase(); - loweredCase = true; - } - } - } - - // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect - // Buffer instances. - Buffer$1.prototype._isBuffer = true; - - function swap$1 (b, n, m) { - var i = b[n]; - b[n] = b[m]; - b[m] = i; - } - - Buffer$1.prototype.swap16 = function swap16 () { - var len = this.length; - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap$1(this, i, i + 1); - } - return this - }; - - Buffer$1.prototype.swap32 = function swap32 () { - var len = this.length; - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap$1(this, i, i + 3); - swap$1(this, i + 1, i + 2); - } - return this - }; - - Buffer$1.prototype.swap64 = function swap64 () { - var len = this.length; - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap$1(this, i, i + 7); - swap$1(this, i + 1, i + 6); - swap$1(this, i + 2, i + 5); - swap$1(this, i + 3, i + 4); - } - return this - }; - - Buffer$1.prototype.toString = function toString () { - var length = this.length | 0; - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice$1(this, 0, length) - return slowToString$1.apply(this, arguments) - }; - - Buffer$1.prototype.equals = function equals (b) { - if (!internalIsBuffer$1(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer$1.compare(this, b) === 0 - }; - - Buffer$1.prototype.inspect = function inspect () { - var str = ''; - var max = INSPECT_MAX_BYTES$1; - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); - if (this.length > max) str += ' ... '; - } - return '' - }; - - Buffer$1.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!internalIsBuffer$1(target)) { - throw new TypeError('Argument must be a Buffer') - } - - if (start === undefined) { - start = 0; - } - if (end === undefined) { - end = target ? target.length : 0; - } - if (thisStart === undefined) { - thisStart = 0; - } - if (thisEnd === undefined) { - thisEnd = this.length; - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; - - if (this === target) return 0 - - var x = thisEnd - thisStart; - var y = end - start; - var len = Math.min(x, y); - - var thisCopy = this.slice(thisStart, thisEnd); - var targetCopy = target.slice(start, end); - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i]; - y = targetCopy[i]; - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 - }; - - // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, - // OR the last index of `val` in `buffer` at offset <= `byteOffset`. - // - // Arguments: - // - buffer - a Buffer to search - // - val - a string, Buffer, or number - // - byteOffset - an index into `buffer`; will be clamped to an int32 - // - encoding - an optional encoding, relevant is val is a string - // - dir - true for indexOf, false for lastIndexOf - function bidirectionalIndexOf$1 (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset; - byteOffset = 0; - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff; - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000; - } - byteOffset = +byteOffset; // Coerce to Number. - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1); - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset; - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1; - } else if (byteOffset < 0) { - if (dir) byteOffset = 0; - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer$1.from(val, encoding); - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (internalIsBuffer$1(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf$1(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF; // Search for a byte value [0-255] - if (Buffer$1.TYPED_ARRAY_SUPPORT && - typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf$1(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') - } - - function arrayIndexOf$1 (arr, val, byteOffset, encoding, dir) { - var indexSize = 1; - var arrLength = arr.length; - var valLength = val.length; - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase(); - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2; - arrLength /= 2; - valLength /= 2; - byteOffset /= 2; - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i; - if (dir) { - var foundIndex = -1; - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i; - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex; - foundIndex = -1; - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; - for (i = byteOffset; i >= 0; i--) { - var found = true; - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false; - break - } - } - if (found) return i - } - } - - return -1 - } - - Buffer$1.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 - }; - - Buffer$1.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf$1(this, val, byteOffset, encoding, true) - }; - - Buffer$1.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf$1(this, val, byteOffset, encoding, false) - }; - - function hexWrite$1 (buf, string, offset, length) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - if (!length) { - length = remaining; - } else { - length = Number(length); - if (length > remaining) { - length = remaining; - } - } - - // must be an even number of digits - var strLen = string.length; - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') - - if (length > strLen / 2) { - length = strLen / 2; - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16); - if (isNaN(parsed)) return i - buf[offset + i] = parsed; - } - return i - } - - function utf8Write$1 (buf, string, offset, length) { - return blitBuffer$1(utf8ToBytes$1(string, buf.length - offset), buf, offset, length) - } - - function asciiWrite$1 (buf, string, offset, length) { - return blitBuffer$1(asciiToBytes$1(string), buf, offset, length) - } - - function latin1Write$1 (buf, string, offset, length) { - return asciiWrite$1(buf, string, offset, length) - } - - function base64Write$1 (buf, string, offset, length) { - return blitBuffer$1(base64ToBytes$1(string), buf, offset, length) - } - - function ucs2Write$1 (buf, string, offset, length) { - return blitBuffer$1(utf16leToBytes$1(string, buf.length - offset), buf, offset, length) - } - - Buffer$1.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8'; - length = this.length; - offset = 0; - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset; - length = this.length; - offset = 0; - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0; - if (isFinite(length)) { - length = length | 0; - if (encoding === undefined) encoding = 'utf8'; - } else { - encoding = length; - length = undefined; - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset; - if (length === undefined || length > remaining) length = remaining; - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8'; - - var loweredCase = false; - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite$1(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write$1(this, string, offset, length) - - case 'ascii': - return asciiWrite$1(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write$1(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write$1(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write$1(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } - }; - - Buffer$1.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } - }; - - function base64Slice$1 (buf, start, end) { - if (start === 0 && end === buf.length) { - return fromByteArray(buf) - } else { - return fromByteArray(buf.slice(start, end)) - } - } - - function utf8Slice$1 (buf, start, end) { - end = Math.min(buf.length, end); - var res = []; - - var i = start; - while (i < end) { - var firstByte = buf[i]; - var codePoint = null; - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1; - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint; - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte; - } - break - case 2: - secondByte = buf[i + 1]; - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint; - } - } - break - case 3: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint; - } - } - break - case 4: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - fourthByte = buf[i + 3]; - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint; - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD; - bytesPerSequence = 1; - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000; - res.push(codePoint >>> 10 & 0x3FF | 0xD800); - codePoint = 0xDC00 | codePoint & 0x3FF; - } - - res.push(codePoint); - i += bytesPerSequence; - } - - return decodeCodePointsArray$1(res) - } - - // Based on http://stackoverflow.com/a/22747272/680742, the browser with - // the lowest limit is Chrome, with 0x10000 args. - // We go 1 magnitude less, for safety - var MAX_ARGUMENTS_LENGTH$1 = 0x1000; - - function decodeCodePointsArray$1 (codePoints) { - var len = codePoints.length; - if (len <= MAX_ARGUMENTS_LENGTH$1) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = ''; - var i = 0; - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH$1) - ); - } - return res - } - - function asciiSlice$1 (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F); - } - return ret - } - - function latin1Slice$1 (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); - } - return ret - } - - function hexSlice$1 (buf, start, end) { - var len = buf.length; - - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; - - var out = ''; - for (var i = start; i < end; ++i) { - out += toHex$1(buf[i]); - } - return out - } - - function utf16leSlice$1 (buf, start, end) { - var bytes = buf.slice(start, end); - var res = ''; - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); - } - return res - } - - Buffer$1.prototype.slice = function slice (start, end) { - var len = this.length; - start = ~~start; - end = end === undefined ? len : ~~end; - - if (start < 0) { - start += len; - if (start < 0) start = 0; - } else if (start > len) { - start = len; - } - - if (end < 0) { - end += len; - if (end < 0) end = 0; - } else if (end > len) { - end = len; - } - - if (end < start) end = start; - - var newBuf; - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer$1.prototype; - } else { - var sliceLen = end - start; - newBuf = new Buffer$1(sliceLen, undefined); - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start]; - } - } - - return newBuf - }; - - /* - * Need to make sure that buffer isn't trying to write out of bounds. - */ - function checkOffset$1 (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') - } - - Buffer$1.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset$1(offset, byteLength, this.length); - - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - - return val - }; - - Buffer$1.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - checkOffset$1(offset, byteLength, this.length); - } - - var val = this[offset + --byteLength]; - var mul = 1; - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul; - } - - return val - }; - - Buffer$1.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 1, this.length); - return this[offset] - }; - - Buffer$1.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 2, this.length); - return this[offset] | (this[offset + 1] << 8) - }; - - Buffer$1.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 2, this.length); - return (this[offset] << 8) | this[offset + 1] - }; - - Buffer$1.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 4, this.length); - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) - }; - - Buffer$1.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 4, this.length); - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) - }; - - Buffer$1.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset$1(offset, byteLength, this.length); - - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - mul *= 0x80; - - if (val >= mul) val -= Math.pow(2, 8 * byteLength); - - return val - }; - - Buffer$1.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset$1(offset, byteLength, this.length); - - var i = byteLength; - var mul = 1; - var val = this[offset + --i]; - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul; - } - mul *= 0x80; - - if (val >= mul) val -= Math.pow(2, 8 * byteLength); - - return val - }; - - Buffer$1.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 1, this.length); - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) - }; - - Buffer$1.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 2, this.length); - var val = this[offset] | (this[offset + 1] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val - }; - - Buffer$1.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 2, this.length); - var val = this[offset + 1] | (this[offset] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val - }; - - Buffer$1.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 4, this.length); - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) - }; - - Buffer$1.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 4, this.length); - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) - }; - - Buffer$1.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 4, this.length); - return read(this, offset, true, 23, 4) - }; - - Buffer$1.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 4, this.length); - return read(this, offset, false, 23, 4) - }; - - Buffer$1.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 8, this.length); - return read(this, offset, true, 52, 8) - }; - - Buffer$1.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 8, this.length); - return read(this, offset, false, 52, 8) - }; - - function checkInt$1 (buf, value, offset, ext, max, min) { - if (!internalIsBuffer$1(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') - } - - Buffer$1.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt$1(this, value, offset, byteLength, maxBytes, 0); - } - - var mul = 1; - var i = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; - } - - return offset + byteLength - }; - - Buffer$1.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt$1(this, value, offset, byteLength, maxBytes, 0); - } - - var i = byteLength - 1; - var mul = 1; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; - } - - return offset + byteLength - }; - - Buffer$1.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt$1(this, value, offset, 1, 0xff, 0); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - this[offset] = (value & 0xff); - return offset + 1 - }; - - function objectWriteUInt16$1 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8; - } - } - - Buffer$1.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt$1(this, value, offset, 2, 0xffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16$1(this, value, offset, true); - } - return offset + 2 - }; - - Buffer$1.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt$1(this, value, offset, 2, 0xffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16$1(this, value, offset, false); - } - return offset + 2 - }; - - function objectWriteUInt32$1 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; - } - } - - Buffer$1.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt$1(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24); - this[offset + 2] = (value >>> 16); - this[offset + 1] = (value >>> 8); - this[offset] = (value & 0xff); - } else { - objectWriteUInt32$1(this, value, offset, true); - } - return offset + 4 - }; - - Buffer$1.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt$1(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); - } else { - objectWriteUInt32$1(this, value, offset, false); - } - return offset + 4 - }; - - Buffer$1.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); - - checkInt$1(this, value, offset, byteLength, limit - 1, -limit); - } - - var i = 0; - var mul = 1; - var sub = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1; - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; - } - - return offset + byteLength - }; - - Buffer$1.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); - - checkInt$1(this, value, offset, byteLength, limit - 1, -limit); - } - - var i = byteLength - 1; - var mul = 1; - var sub = 0; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1; - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; - } - - return offset + byteLength - }; - - Buffer$1.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt$1(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - if (value < 0) value = 0xff + value + 1; - this[offset] = (value & 0xff); - return offset + 1 - }; - - Buffer$1.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt$1(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16$1(this, value, offset, true); - } - return offset + 2 - }; - - Buffer$1.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt$1(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16$1(this, value, offset, false); - } - return offset + 2 - }; - - Buffer$1.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt$1(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - this[offset + 2] = (value >>> 16); - this[offset + 3] = (value >>> 24); - } else { - objectWriteUInt32$1(this, value, offset, true); - } - return offset + 4 - }; - - Buffer$1.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt$1(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (value < 0) value = 0xffffffff + value + 1; - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); - } else { - objectWriteUInt32$1(this, value, offset, false); - } - return offset + 4 - }; - - function checkIEEE754$1 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') - } - - function writeFloat$1 (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754$1(buf, value, offset, 4); - } - write(buf, value, offset, littleEndian, 23, 4); - return offset + 4 - } - - Buffer$1.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat$1(this, value, offset, true, noAssert) - }; - - Buffer$1.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat$1(this, value, offset, false, noAssert) - }; - - function writeDouble$1 (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754$1(buf, value, offset, 8); - } - write(buf, value, offset, littleEndian, 52, 8); - return offset + 8 - } - - Buffer$1.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble$1(this, value, offset, true, noAssert) - }; - - Buffer$1.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble$1(this, value, offset, false, noAssert) - }; - - // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer$1.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0; - if (!end && end !== 0) end = this.length; - if (targetStart >= target.length) targetStart = target.length; - if (!targetStart) targetStart = 0; - if (end > 0 && end < start) end = start; - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length; - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; - } - - var len = end - start; - var i; - - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start]; - } - } else if (len < 1000 || !Buffer$1.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start]; - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ); - } - - return len - }; - - // Usage: - // buffer.fill(number[, offset[, end]]) - // buffer.fill(buffer[, offset[, end]]) - // buffer.fill(string[, offset[, end]][, encoding]) - Buffer$1.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start; - start = 0; - end = this.length; - } else if (typeof end === 'string') { - encoding = end; - end = this.length; - } - if (val.length === 1) { - var code = val.charCodeAt(0); - if (code < 256) { - val = code; - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer$1.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255; - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0; - end = end === undefined ? this.length : end >>> 0; - - if (!val) val = 0; - - var i; - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val; - } - } else { - var bytes = internalIsBuffer$1(val) - ? val - : utf8ToBytes$1(new Buffer$1(val, encoding).toString()); - var len = bytes.length; - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len]; - } - } - - return this - }; - - // HELPER FUNCTIONS - // ================ - - var INVALID_BASE64_RE$1 = /[^+\/0-9A-Za-z-_]/g; - - function base64clean$1 (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim$1(str).replace(INVALID_BASE64_RE$1, ''); - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '='; - } - return str - } - - function stringtrim$1 (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') - } - - function toHex$1 (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) - } - - function utf8ToBytes$1 (string, units) { - units = units || Infinity; - var codePoint; - var length = string.length; - var leadSurrogate = null; - var bytes = []; - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i); - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue - } - - // valid lead - leadSurrogate = codePoint; - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - leadSurrogate = codePoint; - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - } - - leadSurrogate = null; - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint); - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ); - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ); - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ); - } else { - throw new Error('Invalid code point') - } - } - - return bytes - } - - function asciiToBytes$1 (str) { - var byteArray = []; - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF); - } - return byteArray - } - - function utf16leToBytes$1 (str, units) { - var c, hi, lo; - var byteArray = []; - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i); - hi = c >> 8; - lo = c % 256; - byteArray.push(lo); - byteArray.push(hi); - } - - return byteArray - } - - - function base64ToBytes$1 (str) { - return toByteArray(base64clean$1(str)) - } - - function blitBuffer$1 (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i]; - } - return i - } - - function isnan$1 (val) { - return val !== val // eslint-disable-line no-self-compare - } - - - // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence - // The _isBuffer check is for Safari 5-7 support, because it's missing - // Object.prototype.constructor. Remove this eventually - function isBuffer$1(obj) { - return obj != null && (!!obj._isBuffer || isFastBuffer$1(obj) || isSlowBuffer$1(obj)) - } - - function isFastBuffer$1 (obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) - } - - // For Node v0.10 support. Remove this eventually. - function isSlowBuffer$1 (obj) { - return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer$1(obj.slice(0, 0)) - } - function BufferList() { this.head = null; this.tail = null; @@ -5336,9 +3576,9 @@ }; BufferList.prototype.concat = function (n) { - if (this.length === 0) return Buffer$1.alloc(0); + if (this.length === 0) return Buffer.alloc(0); if (this.length === 1) return this.head.data; - var ret = Buffer$1.allocUnsafe(n >>> 0); + var ret = Buffer.allocUnsafe(n >>> 0); var p = this.head; var i = 0; while (p) { @@ -5350,7 +3590,7 @@ }; // Copyright Joyent, Inc. and other Node contributors. - var isBufferEncoding = Buffer$1.isEncoding + var isBufferEncoding = Buffer.isEncoding || function(encoding) { switch (encoding && encoding.toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; @@ -5399,7 +3639,7 @@ // Enough space to store all bytes of a single character. UTF-8 needs 4 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer$1(6); + this.charBuffer = new Buffer(6); // Number of bytes received for the current incomplete multi-byte character. this.charReceived = 0; // Number of bytes expected for the current incomplete multi-byte character. @@ -6600,7 +4840,7 @@ // if it is not a buffer, string, or undefined. if (chunk === null) { er = new TypeError('May not write null values to stream'); - } else if (!Buffer$1.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } if (er) { @@ -6620,7 +4860,7 @@ encoding = null; } - if (Buffer$1.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; if (typeof cb !== 'function') cb = nop; @@ -6658,7 +4898,7 @@ function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer$1.from(chunk, encoding); + chunk = Buffer.from(chunk, encoding); } return chunk; } @@ -6669,7 +4909,7 @@ function writeOrBuffer(stream, state, chunk, encoding, cb) { chunk = decodeChunk(state, chunk, encoding); - if (Buffer$1.isBuffer(chunk)) encoding = 'buffer'; + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; var len = state.objectMode ? 1 : chunk.length; state.length += len; @@ -7187,316 +5427,172 @@ var fs = {}; - /* - PDFAbstractReference - abstract class for PDF reference - */ - - class PDFAbstractReference { - toString() { - throw new Error('Must be implemented by subclasses'); - } + /* + PDFAbstractReference - abstract class for PDF reference + */ + + class PDFAbstractReference { + toString() { + throw new Error('Must be implemented by subclasses'); + } } - /* - PDFNameTree - represents a name tree object - */ - - class PDFNameTree { - - constructor() { - this._items = {}; - } - - add(key, val) { - return this._items[key] = val; - } - - get(key) { - return this._items[key]; - } - - toString() { - // Needs to be sorted by key - const sortedKeys = (Object.keys(this._items)).sort((a, b) => a.localeCompare(b)); - - const out = ['<<']; - if (sortedKeys.length > 1) { - const first = sortedKeys[0], last = sortedKeys[sortedKeys.length - 1]; - out.push(` /Limits ${PDFObject.convert([new String(first), new String(last)])}`); - } - out.push(' /Names ['); - for (let key of sortedKeys) { - out.push(` ${PDFObject.convert(new String(key))} ${PDFObject.convert(this._items[key])}`); - } - out.push(']'); - out.push('>>'); - return out.join('\n'); - } + /* + PDFNameTree - represents a name tree object + */ + + class PDFNameTree { + + constructor() { + this._items = {}; + } + + add(key, val) { + return this._items[key] = val; + } + + get(key) { + return this._items[key]; + } + + toString() { + // Needs to be sorted by key + const sortedKeys = (Object.keys(this._items)).sort((a, b) => a.localeCompare(b)); + + const out = ['<<']; + if (sortedKeys.length > 1) { + const first = sortedKeys[0], last = sortedKeys[sortedKeys.length - 1]; + out.push(` /Limits ${PDFObject.convert([new String(first), new String(last)])}`); + } + out.push(' /Names ['); + for (let key of sortedKeys) { + out.push(` ${PDFObject.convert(new String(key))} ${PDFObject.convert(this._items[key])}`); + } + out.push(']'); + out.push('>>'); + return out.join('\n'); + } } - const pad = (str, length) => (Array(length + 1).join('0') + str).slice(-length); - - const escapableRe = /[\n\r\t\b\f\(\)\\]/g; - const escapable = { - '\n': '\\n', - '\r': '\\r', - '\t': '\\t', - '\b': '\\b', - '\f': '\\f', - '\\': '\\\\', - '(': '\\(', - ')': '\\)' - }; - - // Convert little endian UTF-16 to big endian - const swapBytes = function(buff) { - const l = buff.length; - if (l & 0x01) { - throw new Error('Buffer length must be even'); - } else { - for (let i = 0, end = l - 1; i < end; i += 2) { - const a = buff[i]; - buff[i] = buff[i + 1]; - buff[i + 1] = a; - } - } - - return buff; - }; - - class PDFObject { - static convert(object, encryptFn = null) { - // String literals are converted to the PDF name type - if (typeof object === 'string') { - return `/${object}`; - - // String objects are converted to PDF strings (UTF-16) - } else if (object instanceof String) { - let string = object; - // Detect if this is a unicode string - let isUnicode = false; - for (let i = 0, end = string.length; i < end; i++) { - if (string.charCodeAt(i) > 0x7f) { - isUnicode = true; - break; - } - } - - // If so, encode it as big endian UTF-16 - let stringBuffer; - if (isUnicode) { - stringBuffer = swapBytes(Buffer.from(`\ufeff${string}`, 'utf16le')); - } else { - stringBuffer = Buffer.from(string.valueOf(), 'ascii'); - } - - // Encrypt the string when necessary - if (encryptFn) { - string = encryptFn(stringBuffer).toString('binary'); - } else { - string = stringBuffer.toString('binary'); - } - - // Escape characters as required by the spec - string = string.replace(escapableRe, c => escapable[c]); - - return `(${string})`; - - // Buffers are converted to PDF hex strings - } else if (isBuffer(object)) { - return `<${object.toString('hex')}>`; - } else if (object instanceof PDFAbstractReference || object instanceof PDFNameTree) { - return object.toString(); - } else if (object instanceof Date) { - let string = - `D:${pad(object.getUTCFullYear(), 4)}` + - pad(object.getUTCMonth() + 1, 2) + - pad(object.getUTCDate(), 2) + - pad(object.getUTCHours(), 2) + - pad(object.getUTCMinutes(), 2) + - pad(object.getUTCSeconds(), 2) + - 'Z'; - - // Encrypt the string when necessary - if (encryptFn) { - string = encryptFn(new Buffer(string, 'ascii')).toString('binary'); - - // Escape characters as required by the spec - string = string.replace(escapableRe, c => escapable[c]); - } - - return `(${string})`; - } else if (Array.isArray(object)) { - const items = object.map(e => PDFObject.convert(e, encryptFn)).join(' '); - return `[${items}]`; - } else if ({}.toString.call(object) === '[object Object]') { - const out = ['<<']; - for (let key in object) { - const val = object[key]; - out.push(`/${key} ${PDFObject.convert(val, encryptFn)}`); - } - - out.push('>>'); - return out.join('\n'); - } else if (typeof object === 'number') { - return PDFObject.number(object); - } else { - return `${object}`; - } - } - - static number(n) { - if (n > -1e21 && n < 1e21) { - return Math.round(n * 1e6) / 1e6; - } - - throw new Error(`unsupported number: ${n}`); - } - } + const pad = (str, length) => (Array(length + 1).join('0') + str).slice(-length); - // shim for using process in browser - // based off https://github.com/defunctzombie/node-process/blob/master/browser.js - - function defaultSetTimout$1() { - throw new Error('setTimeout has not been defined'); - } - function defaultClearTimeout$1 () { - throw new Error('clearTimeout has not been defined'); - } - var cachedSetTimeout$1 = defaultSetTimout$1; - var cachedClearTimeout$1 = defaultClearTimeout$1; - if (typeof global$1$1.setTimeout === 'function') { - cachedSetTimeout$1 = setTimeout; - } - if (typeof global$1$1.clearTimeout === 'function') { - cachedClearTimeout$1 = clearTimeout; - } - - function runTimeout$1(fun) { - if (cachedSetTimeout$1 === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout$1 === defaultSetTimout$1 || !cachedSetTimeout$1) && setTimeout) { - cachedSetTimeout$1 = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout$1(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout$1.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout$1.call(this, fun, 0); - } - } - - - } - function runClearTimeout$1(marker) { - if (cachedClearTimeout$1 === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout$1 === defaultClearTimeout$1 || !cachedClearTimeout$1) && clearTimeout) { - cachedClearTimeout$1 = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout$1(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout$1.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout$1.call(this, marker); - } - } - - - - } - var queue$1 = []; - var draining$1 = false; - var currentQueue$1; - var queueIndex$1 = -1; - - function cleanUpNextTick$1() { - if (!draining$1 || !currentQueue$1) { - return; - } - draining$1 = false; - if (currentQueue$1.length) { - queue$1 = currentQueue$1.concat(queue$1); - } else { - queueIndex$1 = -1; - } - if (queue$1.length) { - drainQueue$1(); - } - } - - function drainQueue$1() { - if (draining$1) { - return; - } - var timeout = runTimeout$1(cleanUpNextTick$1); - draining$1 = true; - - var len = queue$1.length; - while(len) { - currentQueue$1 = queue$1; - queue$1 = []; - while (++queueIndex$1 < len) { - if (currentQueue$1) { - currentQueue$1[queueIndex$1].run(); - } - } - queueIndex$1 = -1; - len = queue$1.length; - } - currentQueue$1 = null; - draining$1 = false; - runClearTimeout$1(timeout); - } - function nextTick$1(fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue$1.push(new Item$1(fun, args)); - if (queue$1.length === 1 && !draining$1) { - runTimeout$1(drainQueue$1); - } - } - // v8 likes predictible objects - function Item$1(fun, array) { - this.fun = fun; - this.array = array; - } - Item$1.prototype.run = function () { - this.fun.apply(null, this.array); + const escapableRe = /[\n\r\t\b\f\(\)\\]/g; + const escapable = { + '\n': '\\n', + '\r': '\\r', + '\t': '\\t', + '\b': '\\b', + '\f': '\\f', + '\\': '\\\\', + '(': '\\(', + ')': '\\)' }; - // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js - var performance$1 = global$1$1.performance || {}; - var performanceNow$1 = - performance$1.now || - performance$1.mozNow || - performance$1.msNow || - performance$1.oNow || - performance$1.webkitNow || - function(){ return (new Date()).getTime() }; + // Convert little endian UTF-16 to big endian + const swapBytes = function(buff) { + const l = buff.length; + if (l & 0x01) { + throw new Error('Buffer length must be even'); + } else { + for (let i = 0, end = l - 1; i < end; i += 2) { + const a = buff[i]; + buff[i] = buff[i + 1]; + buff[i + 1] = a; + } + } + + return buff; + }; + + class PDFObject { + static convert(object, encryptFn = null) { + // String literals are converted to the PDF name type + if (typeof object === 'string') { + return `/${object}`; + + // String objects are converted to PDF strings (UTF-16) + } else if (object instanceof String) { + let string = object; + // Detect if this is a unicode string + let isUnicode = false; + for (let i = 0, end = string.length; i < end; i++) { + if (string.charCodeAt(i) > 0x7f) { + isUnicode = true; + break; + } + } + + // If so, encode it as big endian UTF-16 + let stringBuffer; + if (isUnicode) { + stringBuffer = swapBytes(Buffer.from(`\ufeff${string}`, 'utf16le')); + } else { + stringBuffer = Buffer.from(string.valueOf(), 'ascii'); + } + + // Encrypt the string when necessary + if (encryptFn) { + string = encryptFn(stringBuffer).toString('binary'); + } else { + string = stringBuffer.toString('binary'); + } + + // Escape characters as required by the spec + string = string.replace(escapableRe, c => escapable[c]); + + return `(${string})`; + + // Buffers are converted to PDF hex strings + } else if (isBuffer(object)) { + return `<${object.toString('hex')}>`; + } else if (object instanceof PDFAbstractReference || object instanceof PDFNameTree) { + return object.toString(); + } else if (object instanceof Date) { + let string = + `D:${pad(object.getUTCFullYear(), 4)}` + + pad(object.getUTCMonth() + 1, 2) + + pad(object.getUTCDate(), 2) + + pad(object.getUTCHours(), 2) + + pad(object.getUTCMinutes(), 2) + + pad(object.getUTCSeconds(), 2) + + 'Z'; + + // Encrypt the string when necessary + if (encryptFn) { + string = encryptFn(new Buffer(string, 'ascii')).toString('binary'); + + // Escape characters as required by the spec + string = string.replace(escapableRe, c => escapable[c]); + } + + return `(${string})`; + } else if (Array.isArray(object)) { + const items = object.map(e => PDFObject.convert(e, encryptFn)).join(' '); + return `[${items}]`; + } else if ({}.toString.call(object) === '[object Object]') { + const out = ['<<']; + for (let key in object) { + const val = object[key]; + out.push(`/${key} ${PDFObject.convert(val, encryptFn)}`); + } + + out.push('>>'); + return out.join('\n'); + } else if (typeof object === 'number') { + return PDFObject.number(object); + } else { + return `${object}`; + } + } + + static number(n) { + if (n > -1e21 && n < 1e21) { + return Math.round(n * 1e6) / 1e6; + } + + throw new Error(`unsupported number: ${n}`); + } + } var msg = { 2: 'need dictionary', /* Z_NEED_DICT 2 */ @@ -12948,7 +11044,7 @@ this.write_in_progress = true; var self = this; - nextTick$1(function() { + nextTick(function() { self.write_in_progress = false; var res = self._write(flush, input, in_off, in_len, out, out_off, out_len); self.callback(res[0], res[1]); @@ -13492,7 +11588,7 @@ } }); } else { - nextTick$1(callback); + nextTick(callback); } }; @@ -13516,7 +11612,7 @@ if (ws.ended) { if (callback) - nextTick$1(callback); + nextTick(callback); } else if (ws.ending) { if (callback) this.once('end', callback); @@ -13533,7 +11629,7 @@ Zlib$1.prototype.close = function(callback) { if (callback) - nextTick$1(callback); + nextTick(callback); if (this._closed) return; @@ -13543,7 +11639,7 @@ this._binding.close(); var self = this; - nextTick$1(function() { + nextTick(function() { self.emit('close'); }); }; @@ -13721,228 +11817,228 @@ Zlib: Zlib$1 }; - class PDFReference extends PDFAbstractReference { - constructor(document, id, data = {}) { - super(); - this.document = document; - this.id = id; - this.data = data; - this.gen = 0; - this.compress = this.document.compress && !this.data.Filter; - this.uncompressedLength = 0; - this.buffer = []; - } - - write(chunk) { - if (!isBuffer(chunk)) { - chunk = new Buffer(chunk + '\n', 'binary'); - } - - this.uncompressedLength += chunk.length; - if (this.data.Length == null) { - this.data.Length = 0; - } - this.buffer.push(chunk); - this.data.Length += chunk.length; - if (this.compress) { - return (this.data.Filter = 'FlateDecode'); - } - } - - end(chunk) { - if (chunk) { - this.write(chunk); - } - return this.finalize(); - } - - finalize() { - this.offset = this.document._offset; - - const encryptFn = this.document._security - ? this.document._security.getEncryptFn(this.id, this.gen) - : null; - - if (this.buffer.length) { - this.buffer = Buffer.concat(this.buffer); - if (this.compress) { - this.buffer = zlib.deflateSync(this.buffer); - } - - if (encryptFn) { - this.buffer = encryptFn(this.buffer); - } - - this.data.Length = this.buffer.length; - } - - this.document._write(`${this.id} ${this.gen} obj`); - this.document._write(PDFObject.convert(this.data, encryptFn)); - - if (this.buffer.length) { - this.document._write('stream'); - this.document._write(this.buffer); - - this.buffer = []; // free up memory - this.document._write('\nendstream'); - } - - this.document._write('endobj'); - this.document._refEnd(this); - } - toString() { - return `${this.id} ${this.gen} R`; - } + class PDFReference extends PDFAbstractReference { + constructor(document, id, data = {}) { + super(); + this.document = document; + this.id = id; + this.data = data; + this.gen = 0; + this.compress = this.document.compress && !this.data.Filter; + this.uncompressedLength = 0; + this.buffer = []; + } + + write(chunk) { + if (!isBuffer(chunk)) { + chunk = new Buffer(chunk + '\n', 'binary'); + } + + this.uncompressedLength += chunk.length; + if (this.data.Length == null) { + this.data.Length = 0; + } + this.buffer.push(chunk); + this.data.Length += chunk.length; + if (this.compress) { + return (this.data.Filter = 'FlateDecode'); + } + } + + end(chunk) { + if (chunk) { + this.write(chunk); + } + return this.finalize(); + } + + finalize() { + this.offset = this.document._offset; + + const encryptFn = this.document._security + ? this.document._security.getEncryptFn(this.id, this.gen) + : null; + + if (this.buffer.length) { + this.buffer = Buffer.concat(this.buffer); + if (this.compress) { + this.buffer = zlib.deflateSync(this.buffer); + } + + if (encryptFn) { + this.buffer = encryptFn(this.buffer); + } + + this.data.Length = this.buffer.length; + } + + this.document._write(`${this.id} ${this.gen} obj`); + this.document._write(PDFObject.convert(this.data, encryptFn)); + + if (this.buffer.length) { + this.document._write('stream'); + this.document._write(this.buffer); + + this.buffer = []; // free up memory + this.document._write('\nendstream'); + } + + this.document._write('endobj'); + this.document._refEnd(this); + } + toString() { + return `${this.id} ${this.gen} R`; + } } - /* - PDFPage - represents a single page in the PDF document - By Devon Govett - */ - - const DEFAULT_MARGINS = { - top: 72, - left: 72, - bottom: 72, - right: 72 - }; - - const SIZES = { - '4A0': [4767.87, 6740.79], - '2A0': [3370.39, 4767.87], - A0: [2383.94, 3370.39], - A1: [1683.78, 2383.94], - A2: [1190.55, 1683.78], - A3: [841.89, 1190.55], - A4: [595.28, 841.89], - A5: [419.53, 595.28], - A6: [297.64, 419.53], - A7: [209.76, 297.64], - A8: [147.4, 209.76], - A9: [104.88, 147.4], - A10: [73.7, 104.88], - B0: [2834.65, 4008.19], - B1: [2004.09, 2834.65], - B2: [1417.32, 2004.09], - B3: [1000.63, 1417.32], - B4: [708.66, 1000.63], - B5: [498.9, 708.66], - B6: [354.33, 498.9], - B7: [249.45, 354.33], - B8: [175.75, 249.45], - B9: [124.72, 175.75], - B10: [87.87, 124.72], - C0: [2599.37, 3676.54], - C1: [1836.85, 2599.37], - C2: [1298.27, 1836.85], - C3: [918.43, 1298.27], - C4: [649.13, 918.43], - C5: [459.21, 649.13], - C6: [323.15, 459.21], - C7: [229.61, 323.15], - C8: [161.57, 229.61], - C9: [113.39, 161.57], - C10: [79.37, 113.39], - RA0: [2437.8, 3458.27], - RA1: [1729.13, 2437.8], - RA2: [1218.9, 1729.13], - RA3: [864.57, 1218.9], - RA4: [609.45, 864.57], - SRA0: [2551.18, 3628.35], - SRA1: [1814.17, 2551.18], - SRA2: [1275.59, 1814.17], - SRA3: [907.09, 1275.59], - SRA4: [637.8, 907.09], - EXECUTIVE: [521.86, 756.0], - FOLIO: [612.0, 936.0], - LEGAL: [612.0, 1008.0], - LETTER: [612.0, 792.0], - TABLOID: [792.0, 1224.0] - }; - - class PDFPage { - constructor(document, options = {}) { - this.document = document; - this.size = options.size || 'letter'; - this.layout = options.layout || 'portrait'; - - // process margins - if (typeof options.margin === 'number') { - this.margins = { - top: options.margin, - left: options.margin, - bottom: options.margin, - right: options.margin - }; - - // default to 1 inch margins - } else { - this.margins = options.margins || DEFAULT_MARGINS; - } - - // calculate page dimensions - const dimensions = Array.isArray(this.size) - ? this.size - : SIZES[this.size.toUpperCase()]; - this.width = dimensions[this.layout === 'portrait' ? 0 : 1]; - this.height = dimensions[this.layout === 'portrait' ? 1 : 0]; - - this.content = this.document.ref(); - - // Initialize the Font, XObject, and ExtGState dictionaries - this.resources = this.document.ref({ - ProcSet: ['PDF', 'Text', 'ImageB', 'ImageC', 'ImageI'] - }); - - // The page dictionary - this.dictionary = this.document.ref({ - Type: 'Page', - Parent: this.document._root.data.Pages, - MediaBox: [0, 0, this.width, this.height], - Contents: this.content, - Resources: this.resources - }); - } - - // Lazily create these dictionaries - get fonts() { - const data = this.resources.data; - return data.Font != null ? data.Font : (data.Font = {}); - } - - get xobjects() { - const data = this.resources.data; - return data.XObject != null ? data.XObject : (data.XObject = {}); - } - - get ext_gstates() { - const data = this.resources.data; - return data.ExtGState != null ? data.ExtGState : (data.ExtGState = {}); - } - - get patterns() { - const data = this.resources.data; - return data.Pattern != null ? data.Pattern : (data.Pattern = {}); - } - - get annotations() { - const data = this.dictionary.data; - return data.Annots != null ? data.Annots : (data.Annots = []); - } - - maxY() { - return this.height - this.margins.bottom; - } - - write(chunk) { - return this.content.write(chunk); - } - - end() { - this.dictionary.end(); - this.resources.end(); - return this.content.end(); - } + /* + PDFPage - represents a single page in the PDF document + By Devon Govett + */ + + const DEFAULT_MARGINS = { + top: 72, + left: 72, + bottom: 72, + right: 72 + }; + + const SIZES = { + '4A0': [4767.87, 6740.79], + '2A0': [3370.39, 4767.87], + A0: [2383.94, 3370.39], + A1: [1683.78, 2383.94], + A2: [1190.55, 1683.78], + A3: [841.89, 1190.55], + A4: [595.28, 841.89], + A5: [419.53, 595.28], + A6: [297.64, 419.53], + A7: [209.76, 297.64], + A8: [147.4, 209.76], + A9: [104.88, 147.4], + A10: [73.7, 104.88], + B0: [2834.65, 4008.19], + B1: [2004.09, 2834.65], + B2: [1417.32, 2004.09], + B3: [1000.63, 1417.32], + B4: [708.66, 1000.63], + B5: [498.9, 708.66], + B6: [354.33, 498.9], + B7: [249.45, 354.33], + B8: [175.75, 249.45], + B9: [124.72, 175.75], + B10: [87.87, 124.72], + C0: [2599.37, 3676.54], + C1: [1836.85, 2599.37], + C2: [1298.27, 1836.85], + C3: [918.43, 1298.27], + C4: [649.13, 918.43], + C5: [459.21, 649.13], + C6: [323.15, 459.21], + C7: [229.61, 323.15], + C8: [161.57, 229.61], + C9: [113.39, 161.57], + C10: [79.37, 113.39], + RA0: [2437.8, 3458.27], + RA1: [1729.13, 2437.8], + RA2: [1218.9, 1729.13], + RA3: [864.57, 1218.9], + RA4: [609.45, 864.57], + SRA0: [2551.18, 3628.35], + SRA1: [1814.17, 2551.18], + SRA2: [1275.59, 1814.17], + SRA3: [907.09, 1275.59], + SRA4: [637.8, 907.09], + EXECUTIVE: [521.86, 756.0], + FOLIO: [612.0, 936.0], + LEGAL: [612.0, 1008.0], + LETTER: [612.0, 792.0], + TABLOID: [792.0, 1224.0] + }; + + class PDFPage { + constructor(document, options = {}) { + this.document = document; + this.size = options.size || 'letter'; + this.layout = options.layout || 'portrait'; + + // process margins + if (typeof options.margin === 'number') { + this.margins = { + top: options.margin, + left: options.margin, + bottom: options.margin, + right: options.margin + }; + + // default to 1 inch margins + } else { + this.margins = options.margins || DEFAULT_MARGINS; + } + + // calculate page dimensions + const dimensions = Array.isArray(this.size) + ? this.size + : SIZES[this.size.toUpperCase()]; + this.width = dimensions[this.layout === 'portrait' ? 0 : 1]; + this.height = dimensions[this.layout === 'portrait' ? 1 : 0]; + + this.content = this.document.ref(); + + // Initialize the Font, XObject, and ExtGState dictionaries + this.resources = this.document.ref({ + ProcSet: ['PDF', 'Text', 'ImageB', 'ImageC', 'ImageI'] + }); + + // The page dictionary + this.dictionary = this.document.ref({ + Type: 'Page', + Parent: this.document._root.data.Pages, + MediaBox: [0, 0, this.width, this.height], + Contents: this.content, + Resources: this.resources + }); + } + + // Lazily create these dictionaries + get fonts() { + const data = this.resources.data; + return data.Font != null ? data.Font : (data.Font = {}); + } + + get xobjects() { + const data = this.resources.data; + return data.XObject != null ? data.XObject : (data.XObject = {}); + } + + get ext_gstates() { + const data = this.resources.data; + return data.ExtGState != null ? data.ExtGState : (data.ExtGState = {}); + } + + get patterns() { + const data = this.resources.data; + return data.Pattern != null ? data.Pattern : (data.Pattern = {}); + } + + get annotations() { + const data = this.dictionary.data; + return data.Annots != null ? data.Annots : (data.Annots = []); + } + + maxY() { + return this.height - this.margins.bottom; + } + + write(chunk) { + return this.content.write(chunk); + } + + end() { + this.dictionary.end(); + this.resources.end(); + return this.content.end(); + } } var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global$1 !== 'undefined' ? global$1 : typeof self !== 'undefined' ? self : {}; @@ -20344,7 +18440,7 @@ })); }); - var C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs = createCommonjsModule(function (module, exports) { + var cryptoJs = createCommonjsModule(function (module, exports) { (function (root, factory, undef) { { // CommonJS @@ -20357,4672 +18453,4058 @@ })); }); - /** - * Check if value is in a range group. - * @param {number} value - * @param {number[]} rangeGroup - * @returns {boolean} - */ - function inRange(value, rangeGroup) { - if (value < rangeGroup[0]) return false; - let startRange = 0; - let endRange = rangeGroup.length / 2; - while (startRange <= endRange) { - const middleRange = Math.floor((startRange + endRange) / 2); - - // actual array index - const arrayIndex = middleRange * 2; - - // Check if value is in range pointed by actual index - if ( - value >= rangeGroup[arrayIndex] && - value <= rangeGroup[arrayIndex + 1] - ) { - return true; - } - - if (value > rangeGroup[arrayIndex + 1]) { - // Search Right Side Of Array - startRange = middleRange + 1; - } else { - // Search Left Side Of Array - endRange = middleRange - 1; - } - } - return false; + /** + * Check if value is in a range group. + * @param {number} value + * @param {number[]} rangeGroup + * @returns {boolean} + */ + function inRange(value, rangeGroup) { + if (value < rangeGroup[0]) return false; + let startRange = 0; + let endRange = rangeGroup.length / 2; + while (startRange <= endRange) { + const middleRange = Math.floor((startRange + endRange) / 2); + + // actual array index + const arrayIndex = middleRange * 2; + + // Check if value is in range pointed by actual index + if ( + value >= rangeGroup[arrayIndex] && + value <= rangeGroup[arrayIndex + 1] + ) { + return true; + } + + if (value > rangeGroup[arrayIndex + 1]) { + // Search Right Side Of Array + startRange = middleRange + 1; + } else { + // Search Left Side Of Array + endRange = middleRange - 1; + } + } + return false; } - /* eslint-disable prettier/prettier */ - /** - * A.1 Unassigned code points in Unicode 3.2 - * @link https://tools.ietf.org/html/rfc3454#appendix-A.1 - */ - const unassigned_code_points = [ - 0x0221, - 0x0221, - 0x0234, - 0x024f, - 0x02ae, - 0x02af, - 0x02ef, - 0x02ff, - 0x0350, - 0x035f, - 0x0370, - 0x0373, - 0x0376, - 0x0379, - 0x037b, - 0x037d, - 0x037f, - 0x0383, - 0x038b, - 0x038b, - 0x038d, - 0x038d, - 0x03a2, - 0x03a2, - 0x03cf, - 0x03cf, - 0x03f7, - 0x03ff, - 0x0487, - 0x0487, - 0x04cf, - 0x04cf, - 0x04f6, - 0x04f7, - 0x04fa, - 0x04ff, - 0x0510, - 0x0530, - 0x0557, - 0x0558, - 0x0560, - 0x0560, - 0x0588, - 0x0588, - 0x058b, - 0x0590, - 0x05a2, - 0x05a2, - 0x05ba, - 0x05ba, - 0x05c5, - 0x05cf, - 0x05eb, - 0x05ef, - 0x05f5, - 0x060b, - 0x060d, - 0x061a, - 0x061c, - 0x061e, - 0x0620, - 0x0620, - 0x063b, - 0x063f, - 0x0656, - 0x065f, - 0x06ee, - 0x06ef, - 0x06ff, - 0x06ff, - 0x070e, - 0x070e, - 0x072d, - 0x072f, - 0x074b, - 0x077f, - 0x07b2, - 0x0900, - 0x0904, - 0x0904, - 0x093a, - 0x093b, - 0x094e, - 0x094f, - 0x0955, - 0x0957, - 0x0971, - 0x0980, - 0x0984, - 0x0984, - 0x098d, - 0x098e, - 0x0991, - 0x0992, - 0x09a9, - 0x09a9, - 0x09b1, - 0x09b1, - 0x09b3, - 0x09b5, - 0x09ba, - 0x09bb, - 0x09bd, - 0x09bd, - 0x09c5, - 0x09c6, - 0x09c9, - 0x09ca, - 0x09ce, - 0x09d6, - 0x09d8, - 0x09db, - 0x09de, - 0x09de, - 0x09e4, - 0x09e5, - 0x09fb, - 0x0a01, - 0x0a03, - 0x0a04, - 0x0a0b, - 0x0a0e, - 0x0a11, - 0x0a12, - 0x0a29, - 0x0a29, - 0x0a31, - 0x0a31, - 0x0a34, - 0x0a34, - 0x0a37, - 0x0a37, - 0x0a3a, - 0x0a3b, - 0x0a3d, - 0x0a3d, - 0x0a43, - 0x0a46, - 0x0a49, - 0x0a4a, - 0x0a4e, - 0x0a58, - 0x0a5d, - 0x0a5d, - 0x0a5f, - 0x0a65, - 0x0a75, - 0x0a80, - 0x0a84, - 0x0a84, - 0x0a8c, - 0x0a8c, - 0x0a8e, - 0x0a8e, - 0x0a92, - 0x0a92, - 0x0aa9, - 0x0aa9, - 0x0ab1, - 0x0ab1, - 0x0ab4, - 0x0ab4, - 0x0aba, - 0x0abb, - 0x0ac6, - 0x0ac6, - 0x0aca, - 0x0aca, - 0x0ace, - 0x0acf, - 0x0ad1, - 0x0adf, - 0x0ae1, - 0x0ae5, - 0x0af0, - 0x0b00, - 0x0b04, - 0x0b04, - 0x0b0d, - 0x0b0e, - 0x0b11, - 0x0b12, - 0x0b29, - 0x0b29, - 0x0b31, - 0x0b31, - 0x0b34, - 0x0b35, - 0x0b3a, - 0x0b3b, - 0x0b44, - 0x0b46, - 0x0b49, - 0x0b4a, - 0x0b4e, - 0x0b55, - 0x0b58, - 0x0b5b, - 0x0b5e, - 0x0b5e, - 0x0b62, - 0x0b65, - 0x0b71, - 0x0b81, - 0x0b84, - 0x0b84, - 0x0b8b, - 0x0b8d, - 0x0b91, - 0x0b91, - 0x0b96, - 0x0b98, - 0x0b9b, - 0x0b9b, - 0x0b9d, - 0x0b9d, - 0x0ba0, - 0x0ba2, - 0x0ba5, - 0x0ba7, - 0x0bab, - 0x0bad, - 0x0bb6, - 0x0bb6, - 0x0bba, - 0x0bbd, - 0x0bc3, - 0x0bc5, - 0x0bc9, - 0x0bc9, - 0x0bce, - 0x0bd6, - 0x0bd8, - 0x0be6, - 0x0bf3, - 0x0c00, - 0x0c04, - 0x0c04, - 0x0c0d, - 0x0c0d, - 0x0c11, - 0x0c11, - 0x0c29, - 0x0c29, - 0x0c34, - 0x0c34, - 0x0c3a, - 0x0c3d, - 0x0c45, - 0x0c45, - 0x0c49, - 0x0c49, - 0x0c4e, - 0x0c54, - 0x0c57, - 0x0c5f, - 0x0c62, - 0x0c65, - 0x0c70, - 0x0c81, - 0x0c84, - 0x0c84, - 0x0c8d, - 0x0c8d, - 0x0c91, - 0x0c91, - 0x0ca9, - 0x0ca9, - 0x0cb4, - 0x0cb4, - 0x0cba, - 0x0cbd, - 0x0cc5, - 0x0cc5, - 0x0cc9, - 0x0cc9, - 0x0cce, - 0x0cd4, - 0x0cd7, - 0x0cdd, - 0x0cdf, - 0x0cdf, - 0x0ce2, - 0x0ce5, - 0x0cf0, - 0x0d01, - 0x0d04, - 0x0d04, - 0x0d0d, - 0x0d0d, - 0x0d11, - 0x0d11, - 0x0d29, - 0x0d29, - 0x0d3a, - 0x0d3d, - 0x0d44, - 0x0d45, - 0x0d49, - 0x0d49, - 0x0d4e, - 0x0d56, - 0x0d58, - 0x0d5f, - 0x0d62, - 0x0d65, - 0x0d70, - 0x0d81, - 0x0d84, - 0x0d84, - 0x0d97, - 0x0d99, - 0x0db2, - 0x0db2, - 0x0dbc, - 0x0dbc, - 0x0dbe, - 0x0dbf, - 0x0dc7, - 0x0dc9, - 0x0dcb, - 0x0dce, - 0x0dd5, - 0x0dd5, - 0x0dd7, - 0x0dd7, - 0x0de0, - 0x0df1, - 0x0df5, - 0x0e00, - 0x0e3b, - 0x0e3e, - 0x0e5c, - 0x0e80, - 0x0e83, - 0x0e83, - 0x0e85, - 0x0e86, - 0x0e89, - 0x0e89, - 0x0e8b, - 0x0e8c, - 0x0e8e, - 0x0e93, - 0x0e98, - 0x0e98, - 0x0ea0, - 0x0ea0, - 0x0ea4, - 0x0ea4, - 0x0ea6, - 0x0ea6, - 0x0ea8, - 0x0ea9, - 0x0eac, - 0x0eac, - 0x0eba, - 0x0eba, - 0x0ebe, - 0x0ebf, - 0x0ec5, - 0x0ec5, - 0x0ec7, - 0x0ec7, - 0x0ece, - 0x0ecf, - 0x0eda, - 0x0edb, - 0x0ede, - 0x0eff, - 0x0f48, - 0x0f48, - 0x0f6b, - 0x0f70, - 0x0f8c, - 0x0f8f, - 0x0f98, - 0x0f98, - 0x0fbd, - 0x0fbd, - 0x0fcd, - 0x0fce, - 0x0fd0, - 0x0fff, - 0x1022, - 0x1022, - 0x1028, - 0x1028, - 0x102b, - 0x102b, - 0x1033, - 0x1035, - 0x103a, - 0x103f, - 0x105a, - 0x109f, - 0x10c6, - 0x10cf, - 0x10f9, - 0x10fa, - 0x10fc, - 0x10ff, - 0x115a, - 0x115e, - 0x11a3, - 0x11a7, - 0x11fa, - 0x11ff, - 0x1207, - 0x1207, - 0x1247, - 0x1247, - 0x1249, - 0x1249, - 0x124e, - 0x124f, - 0x1257, - 0x1257, - 0x1259, - 0x1259, - 0x125e, - 0x125f, - 0x1287, - 0x1287, - 0x1289, - 0x1289, - 0x128e, - 0x128f, - 0x12af, - 0x12af, - 0x12b1, - 0x12b1, - 0x12b6, - 0x12b7, - 0x12bf, - 0x12bf, - 0x12c1, - 0x12c1, - 0x12c6, - 0x12c7, - 0x12cf, - 0x12cf, - 0x12d7, - 0x12d7, - 0x12ef, - 0x12ef, - 0x130f, - 0x130f, - 0x1311, - 0x1311, - 0x1316, - 0x1317, - 0x131f, - 0x131f, - 0x1347, - 0x1347, - 0x135b, - 0x1360, - 0x137d, - 0x139f, - 0x13f5, - 0x1400, - 0x1677, - 0x167f, - 0x169d, - 0x169f, - 0x16f1, - 0x16ff, - 0x170d, - 0x170d, - 0x1715, - 0x171f, - 0x1737, - 0x173f, - 0x1754, - 0x175f, - 0x176d, - 0x176d, - 0x1771, - 0x1771, - 0x1774, - 0x177f, - 0x17dd, - 0x17df, - 0x17ea, - 0x17ff, - 0x180f, - 0x180f, - 0x181a, - 0x181f, - 0x1878, - 0x187f, - 0x18aa, - 0x1dff, - 0x1e9c, - 0x1e9f, - 0x1efa, - 0x1eff, - 0x1f16, - 0x1f17, - 0x1f1e, - 0x1f1f, - 0x1f46, - 0x1f47, - 0x1f4e, - 0x1f4f, - 0x1f58, - 0x1f58, - 0x1f5a, - 0x1f5a, - 0x1f5c, - 0x1f5c, - 0x1f5e, - 0x1f5e, - 0x1f7e, - 0x1f7f, - 0x1fb5, - 0x1fb5, - 0x1fc5, - 0x1fc5, - 0x1fd4, - 0x1fd5, - 0x1fdc, - 0x1fdc, - 0x1ff0, - 0x1ff1, - 0x1ff5, - 0x1ff5, - 0x1fff, - 0x1fff, - 0x2053, - 0x2056, - 0x2058, - 0x205e, - 0x2064, - 0x2069, - 0x2072, - 0x2073, - 0x208f, - 0x209f, - 0x20b2, - 0x20cf, - 0x20eb, - 0x20ff, - 0x213b, - 0x213c, - 0x214c, - 0x2152, - 0x2184, - 0x218f, - 0x23cf, - 0x23ff, - 0x2427, - 0x243f, - 0x244b, - 0x245f, - 0x24ff, - 0x24ff, - 0x2614, - 0x2615, - 0x2618, - 0x2618, - 0x267e, - 0x267f, - 0x268a, - 0x2700, - 0x2705, - 0x2705, - 0x270a, - 0x270b, - 0x2728, - 0x2728, - 0x274c, - 0x274c, - 0x274e, - 0x274e, - 0x2753, - 0x2755, - 0x2757, - 0x2757, - 0x275f, - 0x2760, - 0x2795, - 0x2797, - 0x27b0, - 0x27b0, - 0x27bf, - 0x27cf, - 0x27ec, - 0x27ef, - 0x2b00, - 0x2e7f, - 0x2e9a, - 0x2e9a, - 0x2ef4, - 0x2eff, - 0x2fd6, - 0x2fef, - 0x2ffc, - 0x2fff, - 0x3040, - 0x3040, - 0x3097, - 0x3098, - 0x3100, - 0x3104, - 0x312d, - 0x3130, - 0x318f, - 0x318f, - 0x31b8, - 0x31ef, - 0x321d, - 0x321f, - 0x3244, - 0x3250, - 0x327c, - 0x327e, - 0x32cc, - 0x32cf, - 0x32ff, - 0x32ff, - 0x3377, - 0x337a, - 0x33de, - 0x33df, - 0x33ff, - 0x33ff, - 0x4db6, - 0x4dff, - 0x9fa6, - 0x9fff, - 0xa48d, - 0xa48f, - 0xa4c7, - 0xabff, - 0xd7a4, - 0xd7ff, - 0xfa2e, - 0xfa2f, - 0xfa6b, - 0xfaff, - 0xfb07, - 0xfb12, - 0xfb18, - 0xfb1c, - 0xfb37, - 0xfb37, - 0xfb3d, - 0xfb3d, - 0xfb3f, - 0xfb3f, - 0xfb42, - 0xfb42, - 0xfb45, - 0xfb45, - 0xfbb2, - 0xfbd2, - 0xfd40, - 0xfd4f, - 0xfd90, - 0xfd91, - 0xfdc8, - 0xfdcf, - 0xfdfd, - 0xfdff, - 0xfe10, - 0xfe1f, - 0xfe24, - 0xfe2f, - 0xfe47, - 0xfe48, - 0xfe53, - 0xfe53, - 0xfe67, - 0xfe67, - 0xfe6c, - 0xfe6f, - 0xfe75, - 0xfe75, - 0xfefd, - 0xfefe, - 0xff00, - 0xff00, - 0xffbf, - 0xffc1, - 0xffc8, - 0xffc9, - 0xffd0, - 0xffd1, - 0xffd8, - 0xffd9, - 0xffdd, - 0xffdf, - 0xffe7, - 0xffe7, - 0xffef, - 0xfff8, - 0x10000, - 0x102ff, - 0x1031f, - 0x1031f, - 0x10324, - 0x1032f, - 0x1034b, - 0x103ff, - 0x10426, - 0x10427, - 0x1044e, - 0x1cfff, - 0x1d0f6, - 0x1d0ff, - 0x1d127, - 0x1d129, - 0x1d1de, - 0x1d3ff, - 0x1d455, - 0x1d455, - 0x1d49d, - 0x1d49d, - 0x1d4a0, - 0x1d4a1, - 0x1d4a3, - 0x1d4a4, - 0x1d4a7, - 0x1d4a8, - 0x1d4ad, - 0x1d4ad, - 0x1d4ba, - 0x1d4ba, - 0x1d4bc, - 0x1d4bc, - 0x1d4c1, - 0x1d4c1, - 0x1d4c4, - 0x1d4c4, - 0x1d506, - 0x1d506, - 0x1d50b, - 0x1d50c, - 0x1d515, - 0x1d515, - 0x1d51d, - 0x1d51d, - 0x1d53a, - 0x1d53a, - 0x1d53f, - 0x1d53f, - 0x1d545, - 0x1d545, - 0x1d547, - 0x1d549, - 0x1d551, - 0x1d551, - 0x1d6a4, - 0x1d6a7, - 0x1d7ca, - 0x1d7cd, - 0x1d800, - 0x1fffd, - 0x2a6d7, - 0x2f7ff, - 0x2fa1e, - 0x2fffd, - 0x30000, - 0x3fffd, - 0x40000, - 0x4fffd, - 0x50000, - 0x5fffd, - 0x60000, - 0x6fffd, - 0x70000, - 0x7fffd, - 0x80000, - 0x8fffd, - 0x90000, - 0x9fffd, - 0xa0000, - 0xafffd, - 0xb0000, - 0xbfffd, - 0xc0000, - 0xcfffd, - 0xd0000, - 0xdfffd, - 0xe0000, - 0xe0000, - 0xe0002, - 0xe001f, - 0xe0080, - 0xefffd - ]; - /* eslint-enable */ - - const isUnassignedCodePoint = character => - inRange(character, unassigned_code_points); - - /* eslint-disable prettier/prettier */ - /** - * B.1 Commonly mapped to nothing - * @link https://tools.ietf.org/html/rfc3454#appendix-B.1 - */ - const commonly_mapped_to_nothing = [ - 0x00ad, - 0x00ad, - 0x034f, - 0x034f, - 0x1806, - 0x1806, - 0x180b, - 0x180b, - 0x180c, - 0x180c, - 0x180d, - 0x180d, - 0x200b, - 0x200b, - 0x200c, - 0x200c, - 0x200d, - 0x200d, - 0x2060, - 0x2060, - 0xfe00, - 0xfe00, - 0xfe01, - 0xfe01, - 0xfe02, - 0xfe02, - 0xfe03, - 0xfe03, - 0xfe04, - 0xfe04, - 0xfe05, - 0xfe05, - 0xfe06, - 0xfe06, - 0xfe07, - 0xfe07, - 0xfe08, - 0xfe08, - 0xfe09, - 0xfe09, - 0xfe0a, - 0xfe0a, - 0xfe0b, - 0xfe0b, - 0xfe0c, - 0xfe0c, - 0xfe0d, - 0xfe0d, - 0xfe0e, - 0xfe0e, - 0xfe0f, - 0xfe0f, - 0xfeff, - 0xfeff - ]; - /* eslint-enable */ - - const isCommonlyMappedToNothing = character => - inRange(character, commonly_mapped_to_nothing); - - /* eslint-disable prettier/prettier */ - /** - * C.1.2 Non-ASCII space characters - * @link https://tools.ietf.org/html/rfc3454#appendix-C.1.2 - */ - const non_ASCII_space_characters = [ - 0x00a0, - 0x00a0 /* NO-BREAK SPACE */, - 0x1680, - 0x1680 /* OGHAM SPACE MARK */, - 0x2000, - 0x2000 /* EN QUAD */, - 0x2001, - 0x2001 /* EM QUAD */, - 0x2002, - 0x2002 /* EN SPACE */, - 0x2003, - 0x2003 /* EM SPACE */, - 0x2004, - 0x2004 /* THREE-PER-EM SPACE */, - 0x2005, - 0x2005 /* FOUR-PER-EM SPACE */, - 0x2006, - 0x2006 /* SIX-PER-EM SPACE */, - 0x2007, - 0x2007 /* FIGURE SPACE */, - 0x2008, - 0x2008 /* PUNCTUATION SPACE */, - 0x2009, - 0x2009 /* THIN SPACE */, - 0x200a, - 0x200a /* HAIR SPACE */, - 0x200b, - 0x200b /* ZERO WIDTH SPACE */, - 0x202f, - 0x202f /* NARROW NO-BREAK SPACE */, - 0x205f, - 0x205f /* MEDIUM MATHEMATICAL SPACE */, - 0x3000, - 0x3000 /* IDEOGRAPHIC SPACE */ - ]; - /* eslint-enable */ - - const isNonASCIISpaceCharacter = character => - inRange(character, non_ASCII_space_characters); - - /* eslint-disable prettier/prettier */ - const non_ASCII_controls_characters = [ - /** - * C.2.2 Non-ASCII control characters - * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.2 - */ - 0x0080, - 0x009f /* [CONTROL CHARACTERS] */, - 0x06dd, - 0x06dd /* ARABIC END OF AYAH */, - 0x070f, - 0x070f /* SYRIAC ABBREVIATION MARK */, - 0x180e, - 0x180e /* MONGOLIAN VOWEL SEPARATOR */, - 0x200c, - 0x200c /* ZERO WIDTH NON-JOINER */, - 0x200d, - 0x200d /* ZERO WIDTH JOINER */, - 0x2028, - 0x2028 /* LINE SEPARATOR */, - 0x2029, - 0x2029 /* PARAGRAPH SEPARATOR */, - 0x2060, - 0x2060 /* WORD JOINER */, - 0x2061, - 0x2061 /* FUNCTION APPLICATION */, - 0x2062, - 0x2062 /* INVISIBLE TIMES */, - 0x2063, - 0x2063 /* INVISIBLE SEPARATOR */, - 0x206a, - 0x206f /* [CONTROL CHARACTERS] */, - 0xfeff, - 0xfeff /* ZERO WIDTH NO-BREAK SPACE */, - 0xfff9, - 0xfffc /* [CONTROL CHARACTERS] */, - 0x1d173, - 0x1d17a /* [MUSICAL CONTROL CHARACTERS] */ - ]; - - const non_character_codepoints = [ - /** - * C.4 Non-character code points - * @link https://tools.ietf.org/html/rfc3454#appendix-C.4 - */ - 0xfdd0, - 0xfdef /* [NONCHARACTER CODE POINTS] */, - 0xfffe, - 0xffff /* [NONCHARACTER CODE POINTS] */, - 0x1fffe, - 0x1ffff /* [NONCHARACTER CODE POINTS] */, - 0x2fffe, - 0x2ffff /* [NONCHARACTER CODE POINTS] */, - 0x3fffe, - 0x3ffff /* [NONCHARACTER CODE POINTS] */, - 0x4fffe, - 0x4ffff /* [NONCHARACTER CODE POINTS] */, - 0x5fffe, - 0x5ffff /* [NONCHARACTER CODE POINTS] */, - 0x6fffe, - 0x6ffff /* [NONCHARACTER CODE POINTS] */, - 0x7fffe, - 0x7ffff /* [NONCHARACTER CODE POINTS] */, - 0x8fffe, - 0x8ffff /* [NONCHARACTER CODE POINTS] */, - 0x9fffe, - 0x9ffff /* [NONCHARACTER CODE POINTS] */, - 0xafffe, - 0xaffff /* [NONCHARACTER CODE POINTS] */, - 0xbfffe, - 0xbffff /* [NONCHARACTER CODE POINTS] */, - 0xcfffe, - 0xcffff /* [NONCHARACTER CODE POINTS] */, - 0xdfffe, - 0xdffff /* [NONCHARACTER CODE POINTS] */, - 0xefffe, - 0xeffff /* [NONCHARACTER CODE POINTS] */, - 0x10fffe, - 0x10ffff /* [NONCHARACTER CODE POINTS] */ - ]; - - /** - * 2.3. Prohibited Output - */ - const prohibited_characters = [ - /** - * C.2.1 ASCII control characters - * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.1 - */ - 0, - 0x001f /* [CONTROL CHARACTERS] */, - 0x007f, - 0x007f /* DELETE */, - - /** - * C.8 Change display properties or are deprecated - * @link https://tools.ietf.org/html/rfc3454#appendix-C.8 - */ - 0x0340, - 0x0340 /* COMBINING GRAVE TONE MARK */, - 0x0341, - 0x0341 /* COMBINING ACUTE TONE MARK */, - 0x200e, - 0x200e /* LEFT-TO-RIGHT MARK */, - 0x200f, - 0x200f /* RIGHT-TO-LEFT MARK */, - 0x202a, - 0x202a /* LEFT-TO-RIGHT EMBEDDING */, - 0x202b, - 0x202b /* RIGHT-TO-LEFT EMBEDDING */, - 0x202c, - 0x202c /* POP DIRECTIONAL FORMATTING */, - 0x202d, - 0x202d /* LEFT-TO-RIGHT OVERRIDE */, - 0x202e, - 0x202e /* RIGHT-TO-LEFT OVERRIDE */, - 0x206a, - 0x206a /* INHIBIT SYMMETRIC SWAPPING */, - 0x206b, - 0x206b /* ACTIVATE SYMMETRIC SWAPPING */, - 0x206c, - 0x206c /* INHIBIT ARABIC FORM SHAPING */, - 0x206d, - 0x206d /* ACTIVATE ARABIC FORM SHAPING */, - 0x206e, - 0x206e /* NATIONAL DIGIT SHAPES */, - 0x206f, - 0x206f /* NOMINAL DIGIT SHAPES */, - - /** - * C.7 Inappropriate for canonical representation - * @link https://tools.ietf.org/html/rfc3454#appendix-C.7 - */ - 0x2ff0, - 0x2ffb /* [IDEOGRAPHIC DESCRIPTION CHARACTERS] */, - - /** - * C.5 Surrogate codes - * @link https://tools.ietf.org/html/rfc3454#appendix-C.5 - */ - 0xd800, - 0xdfff, - - /** - * C.3 Private use - * @link https://tools.ietf.org/html/rfc3454#appendix-C.3 - */ - 0xe000, - 0xf8ff /* [PRIVATE USE, PLANE 0] */, - - /** - * C.6 Inappropriate for plain text - * @link https://tools.ietf.org/html/rfc3454#appendix-C.6 - */ - 0xfff9, - 0xfff9 /* INTERLINEAR ANNOTATION ANCHOR */, - 0xfffa, - 0xfffa /* INTERLINEAR ANNOTATION SEPARATOR */, - 0xfffb, - 0xfffb /* INTERLINEAR ANNOTATION TERMINATOR */, - 0xfffc, - 0xfffc /* OBJECT REPLACEMENT CHARACTER */, - 0xfffd, - 0xfffd /* REPLACEMENT CHARACTER */, - - /** - * C.9 Tagging characters - * @link https://tools.ietf.org/html/rfc3454#appendix-C.9 - */ - 0xe0001, - 0xe0001 /* LANGUAGE TAG */, - 0xe0020, - 0xe007f /* [TAGGING CHARACTERS] */, - - /** - * C.3 Private use - * @link https://tools.ietf.org/html/rfc3454#appendix-C.3 - */ - - 0xf0000, - 0xffffd /* [PRIVATE USE, PLANE 15] */, - 0x100000, - 0x10fffd /* [PRIVATE USE, PLANE 16] */ - ]; - /* eslint-enable */ - - const isProhibitedCharacter = character => - inRange(character, non_ASCII_space_characters) || - inRange(character, prohibited_characters) || - inRange(character, non_ASCII_controls_characters) || - inRange(character, non_character_codepoints); - - /* eslint-disable prettier/prettier */ - /** - * D.1 Characters with bidirectional property "R" or "AL" - * @link https://tools.ietf.org/html/rfc3454#appendix-D.1 - */ - const bidirectional_r_al = [ - 0x05be, - 0x05be, - 0x05c0, - 0x05c0, - 0x05c3, - 0x05c3, - 0x05d0, - 0x05ea, - 0x05f0, - 0x05f4, - 0x061b, - 0x061b, - 0x061f, - 0x061f, - 0x0621, - 0x063a, - 0x0640, - 0x064a, - 0x066d, - 0x066f, - 0x0671, - 0x06d5, - 0x06dd, - 0x06dd, - 0x06e5, - 0x06e6, - 0x06fa, - 0x06fe, - 0x0700, - 0x070d, - 0x0710, - 0x0710, - 0x0712, - 0x072c, - 0x0780, - 0x07a5, - 0x07b1, - 0x07b1, - 0x200f, - 0x200f, - 0xfb1d, - 0xfb1d, - 0xfb1f, - 0xfb28, - 0xfb2a, - 0xfb36, - 0xfb38, - 0xfb3c, - 0xfb3e, - 0xfb3e, - 0xfb40, - 0xfb41, - 0xfb43, - 0xfb44, - 0xfb46, - 0xfbb1, - 0xfbd3, - 0xfd3d, - 0xfd50, - 0xfd8f, - 0xfd92, - 0xfdc7, - 0xfdf0, - 0xfdfc, - 0xfe70, - 0xfe74, - 0xfe76, - 0xfefc - ]; - /* eslint-enable */ - - const isBidirectionalRAL = character => inRange(character, bidirectional_r_al); - - /* eslint-disable prettier/prettier */ - /** - * D.2 Characters with bidirectional property "L" - * @link https://tools.ietf.org/html/rfc3454#appendix-D.2 - */ - const bidirectional_l = [ - 0x0041, - 0x005a, - 0x0061, - 0x007a, - 0x00aa, - 0x00aa, - 0x00b5, - 0x00b5, - 0x00ba, - 0x00ba, - 0x00c0, - 0x00d6, - 0x00d8, - 0x00f6, - 0x00f8, - 0x0220, - 0x0222, - 0x0233, - 0x0250, - 0x02ad, - 0x02b0, - 0x02b8, - 0x02bb, - 0x02c1, - 0x02d0, - 0x02d1, - 0x02e0, - 0x02e4, - 0x02ee, - 0x02ee, - 0x037a, - 0x037a, - 0x0386, - 0x0386, - 0x0388, - 0x038a, - 0x038c, - 0x038c, - 0x038e, - 0x03a1, - 0x03a3, - 0x03ce, - 0x03d0, - 0x03f5, - 0x0400, - 0x0482, - 0x048a, - 0x04ce, - 0x04d0, - 0x04f5, - 0x04f8, - 0x04f9, - 0x0500, - 0x050f, - 0x0531, - 0x0556, - 0x0559, - 0x055f, - 0x0561, - 0x0587, - 0x0589, - 0x0589, - 0x0903, - 0x0903, - 0x0905, - 0x0939, - 0x093d, - 0x0940, - 0x0949, - 0x094c, - 0x0950, - 0x0950, - 0x0958, - 0x0961, - 0x0964, - 0x0970, - 0x0982, - 0x0983, - 0x0985, - 0x098c, - 0x098f, - 0x0990, - 0x0993, - 0x09a8, - 0x09aa, - 0x09b0, - 0x09b2, - 0x09b2, - 0x09b6, - 0x09b9, - 0x09be, - 0x09c0, - 0x09c7, - 0x09c8, - 0x09cb, - 0x09cc, - 0x09d7, - 0x09d7, - 0x09dc, - 0x09dd, - 0x09df, - 0x09e1, - 0x09e6, - 0x09f1, - 0x09f4, - 0x09fa, - 0x0a05, - 0x0a0a, - 0x0a0f, - 0x0a10, - 0x0a13, - 0x0a28, - 0x0a2a, - 0x0a30, - 0x0a32, - 0x0a33, - 0x0a35, - 0x0a36, - 0x0a38, - 0x0a39, - 0x0a3e, - 0x0a40, - 0x0a59, - 0x0a5c, - 0x0a5e, - 0x0a5e, - 0x0a66, - 0x0a6f, - 0x0a72, - 0x0a74, - 0x0a83, - 0x0a83, - 0x0a85, - 0x0a8b, - 0x0a8d, - 0x0a8d, - 0x0a8f, - 0x0a91, - 0x0a93, - 0x0aa8, - 0x0aaa, - 0x0ab0, - 0x0ab2, - 0x0ab3, - 0x0ab5, - 0x0ab9, - 0x0abd, - 0x0ac0, - 0x0ac9, - 0x0ac9, - 0x0acb, - 0x0acc, - 0x0ad0, - 0x0ad0, - 0x0ae0, - 0x0ae0, - 0x0ae6, - 0x0aef, - 0x0b02, - 0x0b03, - 0x0b05, - 0x0b0c, - 0x0b0f, - 0x0b10, - 0x0b13, - 0x0b28, - 0x0b2a, - 0x0b30, - 0x0b32, - 0x0b33, - 0x0b36, - 0x0b39, - 0x0b3d, - 0x0b3e, - 0x0b40, - 0x0b40, - 0x0b47, - 0x0b48, - 0x0b4b, - 0x0b4c, - 0x0b57, - 0x0b57, - 0x0b5c, - 0x0b5d, - 0x0b5f, - 0x0b61, - 0x0b66, - 0x0b70, - 0x0b83, - 0x0b83, - 0x0b85, - 0x0b8a, - 0x0b8e, - 0x0b90, - 0x0b92, - 0x0b95, - 0x0b99, - 0x0b9a, - 0x0b9c, - 0x0b9c, - 0x0b9e, - 0x0b9f, - 0x0ba3, - 0x0ba4, - 0x0ba8, - 0x0baa, - 0x0bae, - 0x0bb5, - 0x0bb7, - 0x0bb9, - 0x0bbe, - 0x0bbf, - 0x0bc1, - 0x0bc2, - 0x0bc6, - 0x0bc8, - 0x0bca, - 0x0bcc, - 0x0bd7, - 0x0bd7, - 0x0be7, - 0x0bf2, - 0x0c01, - 0x0c03, - 0x0c05, - 0x0c0c, - 0x0c0e, - 0x0c10, - 0x0c12, - 0x0c28, - 0x0c2a, - 0x0c33, - 0x0c35, - 0x0c39, - 0x0c41, - 0x0c44, - 0x0c60, - 0x0c61, - 0x0c66, - 0x0c6f, - 0x0c82, - 0x0c83, - 0x0c85, - 0x0c8c, - 0x0c8e, - 0x0c90, - 0x0c92, - 0x0ca8, - 0x0caa, - 0x0cb3, - 0x0cb5, - 0x0cb9, - 0x0cbe, - 0x0cbe, - 0x0cc0, - 0x0cc4, - 0x0cc7, - 0x0cc8, - 0x0cca, - 0x0ccb, - 0x0cd5, - 0x0cd6, - 0x0cde, - 0x0cde, - 0x0ce0, - 0x0ce1, - 0x0ce6, - 0x0cef, - 0x0d02, - 0x0d03, - 0x0d05, - 0x0d0c, - 0x0d0e, - 0x0d10, - 0x0d12, - 0x0d28, - 0x0d2a, - 0x0d39, - 0x0d3e, - 0x0d40, - 0x0d46, - 0x0d48, - 0x0d4a, - 0x0d4c, - 0x0d57, - 0x0d57, - 0x0d60, - 0x0d61, - 0x0d66, - 0x0d6f, - 0x0d82, - 0x0d83, - 0x0d85, - 0x0d96, - 0x0d9a, - 0x0db1, - 0x0db3, - 0x0dbb, - 0x0dbd, - 0x0dbd, - 0x0dc0, - 0x0dc6, - 0x0dcf, - 0x0dd1, - 0x0dd8, - 0x0ddf, - 0x0df2, - 0x0df4, - 0x0e01, - 0x0e30, - 0x0e32, - 0x0e33, - 0x0e40, - 0x0e46, - 0x0e4f, - 0x0e5b, - 0x0e81, - 0x0e82, - 0x0e84, - 0x0e84, - 0x0e87, - 0x0e88, - 0x0e8a, - 0x0e8a, - 0x0e8d, - 0x0e8d, - 0x0e94, - 0x0e97, - 0x0e99, - 0x0e9f, - 0x0ea1, - 0x0ea3, - 0x0ea5, - 0x0ea5, - 0x0ea7, - 0x0ea7, - 0x0eaa, - 0x0eab, - 0x0ead, - 0x0eb0, - 0x0eb2, - 0x0eb3, - 0x0ebd, - 0x0ebd, - 0x0ec0, - 0x0ec4, - 0x0ec6, - 0x0ec6, - 0x0ed0, - 0x0ed9, - 0x0edc, - 0x0edd, - 0x0f00, - 0x0f17, - 0x0f1a, - 0x0f34, - 0x0f36, - 0x0f36, - 0x0f38, - 0x0f38, - 0x0f3e, - 0x0f47, - 0x0f49, - 0x0f6a, - 0x0f7f, - 0x0f7f, - 0x0f85, - 0x0f85, - 0x0f88, - 0x0f8b, - 0x0fbe, - 0x0fc5, - 0x0fc7, - 0x0fcc, - 0x0fcf, - 0x0fcf, - 0x1000, - 0x1021, - 0x1023, - 0x1027, - 0x1029, - 0x102a, - 0x102c, - 0x102c, - 0x1031, - 0x1031, - 0x1038, - 0x1038, - 0x1040, - 0x1057, - 0x10a0, - 0x10c5, - 0x10d0, - 0x10f8, - 0x10fb, - 0x10fb, - 0x1100, - 0x1159, - 0x115f, - 0x11a2, - 0x11a8, - 0x11f9, - 0x1200, - 0x1206, - 0x1208, - 0x1246, - 0x1248, - 0x1248, - 0x124a, - 0x124d, - 0x1250, - 0x1256, - 0x1258, - 0x1258, - 0x125a, - 0x125d, - 0x1260, - 0x1286, - 0x1288, - 0x1288, - 0x128a, - 0x128d, - 0x1290, - 0x12ae, - 0x12b0, - 0x12b0, - 0x12b2, - 0x12b5, - 0x12b8, - 0x12be, - 0x12c0, - 0x12c0, - 0x12c2, - 0x12c5, - 0x12c8, - 0x12ce, - 0x12d0, - 0x12d6, - 0x12d8, - 0x12ee, - 0x12f0, - 0x130e, - 0x1310, - 0x1310, - 0x1312, - 0x1315, - 0x1318, - 0x131e, - 0x1320, - 0x1346, - 0x1348, - 0x135a, - 0x1361, - 0x137c, - 0x13a0, - 0x13f4, - 0x1401, - 0x1676, - 0x1681, - 0x169a, - 0x16a0, - 0x16f0, - 0x1700, - 0x170c, - 0x170e, - 0x1711, - 0x1720, - 0x1731, - 0x1735, - 0x1736, - 0x1740, - 0x1751, - 0x1760, - 0x176c, - 0x176e, - 0x1770, - 0x1780, - 0x17b6, - 0x17be, - 0x17c5, - 0x17c7, - 0x17c8, - 0x17d4, - 0x17da, - 0x17dc, - 0x17dc, - 0x17e0, - 0x17e9, - 0x1810, - 0x1819, - 0x1820, - 0x1877, - 0x1880, - 0x18a8, - 0x1e00, - 0x1e9b, - 0x1ea0, - 0x1ef9, - 0x1f00, - 0x1f15, - 0x1f18, - 0x1f1d, - 0x1f20, - 0x1f45, - 0x1f48, - 0x1f4d, - 0x1f50, - 0x1f57, - 0x1f59, - 0x1f59, - 0x1f5b, - 0x1f5b, - 0x1f5d, - 0x1f5d, - 0x1f5f, - 0x1f7d, - 0x1f80, - 0x1fb4, - 0x1fb6, - 0x1fbc, - 0x1fbe, - 0x1fbe, - 0x1fc2, - 0x1fc4, - 0x1fc6, - 0x1fcc, - 0x1fd0, - 0x1fd3, - 0x1fd6, - 0x1fdb, - 0x1fe0, - 0x1fec, - 0x1ff2, - 0x1ff4, - 0x1ff6, - 0x1ffc, - 0x200e, - 0x200e, - 0x2071, - 0x2071, - 0x207f, - 0x207f, - 0x2102, - 0x2102, - 0x2107, - 0x2107, - 0x210a, - 0x2113, - 0x2115, - 0x2115, - 0x2119, - 0x211d, - 0x2124, - 0x2124, - 0x2126, - 0x2126, - 0x2128, - 0x2128, - 0x212a, - 0x212d, - 0x212f, - 0x2131, - 0x2133, - 0x2139, - 0x213d, - 0x213f, - 0x2145, - 0x2149, - 0x2160, - 0x2183, - 0x2336, - 0x237a, - 0x2395, - 0x2395, - 0x249c, - 0x24e9, - 0x3005, - 0x3007, - 0x3021, - 0x3029, - 0x3031, - 0x3035, - 0x3038, - 0x303c, - 0x3041, - 0x3096, - 0x309d, - 0x309f, - 0x30a1, - 0x30fa, - 0x30fc, - 0x30ff, - 0x3105, - 0x312c, - 0x3131, - 0x318e, - 0x3190, - 0x31b7, - 0x31f0, - 0x321c, - 0x3220, - 0x3243, - 0x3260, - 0x327b, - 0x327f, - 0x32b0, - 0x32c0, - 0x32cb, - 0x32d0, - 0x32fe, - 0x3300, - 0x3376, - 0x337b, - 0x33dd, - 0x33e0, - 0x33fe, - 0x3400, - 0x4db5, - 0x4e00, - 0x9fa5, - 0xa000, - 0xa48c, - 0xac00, - 0xd7a3, - 0xd800, - 0xfa2d, - 0xfa30, - 0xfa6a, - 0xfb00, - 0xfb06, - 0xfb13, - 0xfb17, - 0xff21, - 0xff3a, - 0xff41, - 0xff5a, - 0xff66, - 0xffbe, - 0xffc2, - 0xffc7, - 0xffca, - 0xffcf, - 0xffd2, - 0xffd7, - 0xffda, - 0xffdc, - 0x10300, - 0x1031e, - 0x10320, - 0x10323, - 0x10330, - 0x1034a, - 0x10400, - 0x10425, - 0x10428, - 0x1044d, - 0x1d000, - 0x1d0f5, - 0x1d100, - 0x1d126, - 0x1d12a, - 0x1d166, - 0x1d16a, - 0x1d172, - 0x1d183, - 0x1d184, - 0x1d18c, - 0x1d1a9, - 0x1d1ae, - 0x1d1dd, - 0x1d400, - 0x1d454, - 0x1d456, - 0x1d49c, - 0x1d49e, - 0x1d49f, - 0x1d4a2, - 0x1d4a2, - 0x1d4a5, - 0x1d4a6, - 0x1d4a9, - 0x1d4ac, - 0x1d4ae, - 0x1d4b9, - 0x1d4bb, - 0x1d4bb, - 0x1d4bd, - 0x1d4c0, - 0x1d4c2, - 0x1d4c3, - 0x1d4c5, - 0x1d505, - 0x1d507, - 0x1d50a, - 0x1d50d, - 0x1d514, - 0x1d516, - 0x1d51c, - 0x1d51e, - 0x1d539, - 0x1d53b, - 0x1d53e, - 0x1d540, - 0x1d544, - 0x1d546, - 0x1d546, - 0x1d54a, - 0x1d550, - 0x1d552, - 0x1d6a3, - 0x1d6a8, - 0x1d7c9, - 0x20000, - 0x2a6d6, - 0x2f800, - 0x2fa1d, - 0xf0000, - 0xffffd, - 0x100000, - 0x10fffd - ]; - /* eslint-enable */ - - const isBidirectionalL = character => inRange(character, bidirectional_l); + /* eslint-disable prettier/prettier */ + /** + * A.1 Unassigned code points in Unicode 3.2 + * @link https://tools.ietf.org/html/rfc3454#appendix-A.1 + */ + const unassigned_code_points = [ + 0x0221, + 0x0221, + 0x0234, + 0x024f, + 0x02ae, + 0x02af, + 0x02ef, + 0x02ff, + 0x0350, + 0x035f, + 0x0370, + 0x0373, + 0x0376, + 0x0379, + 0x037b, + 0x037d, + 0x037f, + 0x0383, + 0x038b, + 0x038b, + 0x038d, + 0x038d, + 0x03a2, + 0x03a2, + 0x03cf, + 0x03cf, + 0x03f7, + 0x03ff, + 0x0487, + 0x0487, + 0x04cf, + 0x04cf, + 0x04f6, + 0x04f7, + 0x04fa, + 0x04ff, + 0x0510, + 0x0530, + 0x0557, + 0x0558, + 0x0560, + 0x0560, + 0x0588, + 0x0588, + 0x058b, + 0x0590, + 0x05a2, + 0x05a2, + 0x05ba, + 0x05ba, + 0x05c5, + 0x05cf, + 0x05eb, + 0x05ef, + 0x05f5, + 0x060b, + 0x060d, + 0x061a, + 0x061c, + 0x061e, + 0x0620, + 0x0620, + 0x063b, + 0x063f, + 0x0656, + 0x065f, + 0x06ee, + 0x06ef, + 0x06ff, + 0x06ff, + 0x070e, + 0x070e, + 0x072d, + 0x072f, + 0x074b, + 0x077f, + 0x07b2, + 0x0900, + 0x0904, + 0x0904, + 0x093a, + 0x093b, + 0x094e, + 0x094f, + 0x0955, + 0x0957, + 0x0971, + 0x0980, + 0x0984, + 0x0984, + 0x098d, + 0x098e, + 0x0991, + 0x0992, + 0x09a9, + 0x09a9, + 0x09b1, + 0x09b1, + 0x09b3, + 0x09b5, + 0x09ba, + 0x09bb, + 0x09bd, + 0x09bd, + 0x09c5, + 0x09c6, + 0x09c9, + 0x09ca, + 0x09ce, + 0x09d6, + 0x09d8, + 0x09db, + 0x09de, + 0x09de, + 0x09e4, + 0x09e5, + 0x09fb, + 0x0a01, + 0x0a03, + 0x0a04, + 0x0a0b, + 0x0a0e, + 0x0a11, + 0x0a12, + 0x0a29, + 0x0a29, + 0x0a31, + 0x0a31, + 0x0a34, + 0x0a34, + 0x0a37, + 0x0a37, + 0x0a3a, + 0x0a3b, + 0x0a3d, + 0x0a3d, + 0x0a43, + 0x0a46, + 0x0a49, + 0x0a4a, + 0x0a4e, + 0x0a58, + 0x0a5d, + 0x0a5d, + 0x0a5f, + 0x0a65, + 0x0a75, + 0x0a80, + 0x0a84, + 0x0a84, + 0x0a8c, + 0x0a8c, + 0x0a8e, + 0x0a8e, + 0x0a92, + 0x0a92, + 0x0aa9, + 0x0aa9, + 0x0ab1, + 0x0ab1, + 0x0ab4, + 0x0ab4, + 0x0aba, + 0x0abb, + 0x0ac6, + 0x0ac6, + 0x0aca, + 0x0aca, + 0x0ace, + 0x0acf, + 0x0ad1, + 0x0adf, + 0x0ae1, + 0x0ae5, + 0x0af0, + 0x0b00, + 0x0b04, + 0x0b04, + 0x0b0d, + 0x0b0e, + 0x0b11, + 0x0b12, + 0x0b29, + 0x0b29, + 0x0b31, + 0x0b31, + 0x0b34, + 0x0b35, + 0x0b3a, + 0x0b3b, + 0x0b44, + 0x0b46, + 0x0b49, + 0x0b4a, + 0x0b4e, + 0x0b55, + 0x0b58, + 0x0b5b, + 0x0b5e, + 0x0b5e, + 0x0b62, + 0x0b65, + 0x0b71, + 0x0b81, + 0x0b84, + 0x0b84, + 0x0b8b, + 0x0b8d, + 0x0b91, + 0x0b91, + 0x0b96, + 0x0b98, + 0x0b9b, + 0x0b9b, + 0x0b9d, + 0x0b9d, + 0x0ba0, + 0x0ba2, + 0x0ba5, + 0x0ba7, + 0x0bab, + 0x0bad, + 0x0bb6, + 0x0bb6, + 0x0bba, + 0x0bbd, + 0x0bc3, + 0x0bc5, + 0x0bc9, + 0x0bc9, + 0x0bce, + 0x0bd6, + 0x0bd8, + 0x0be6, + 0x0bf3, + 0x0c00, + 0x0c04, + 0x0c04, + 0x0c0d, + 0x0c0d, + 0x0c11, + 0x0c11, + 0x0c29, + 0x0c29, + 0x0c34, + 0x0c34, + 0x0c3a, + 0x0c3d, + 0x0c45, + 0x0c45, + 0x0c49, + 0x0c49, + 0x0c4e, + 0x0c54, + 0x0c57, + 0x0c5f, + 0x0c62, + 0x0c65, + 0x0c70, + 0x0c81, + 0x0c84, + 0x0c84, + 0x0c8d, + 0x0c8d, + 0x0c91, + 0x0c91, + 0x0ca9, + 0x0ca9, + 0x0cb4, + 0x0cb4, + 0x0cba, + 0x0cbd, + 0x0cc5, + 0x0cc5, + 0x0cc9, + 0x0cc9, + 0x0cce, + 0x0cd4, + 0x0cd7, + 0x0cdd, + 0x0cdf, + 0x0cdf, + 0x0ce2, + 0x0ce5, + 0x0cf0, + 0x0d01, + 0x0d04, + 0x0d04, + 0x0d0d, + 0x0d0d, + 0x0d11, + 0x0d11, + 0x0d29, + 0x0d29, + 0x0d3a, + 0x0d3d, + 0x0d44, + 0x0d45, + 0x0d49, + 0x0d49, + 0x0d4e, + 0x0d56, + 0x0d58, + 0x0d5f, + 0x0d62, + 0x0d65, + 0x0d70, + 0x0d81, + 0x0d84, + 0x0d84, + 0x0d97, + 0x0d99, + 0x0db2, + 0x0db2, + 0x0dbc, + 0x0dbc, + 0x0dbe, + 0x0dbf, + 0x0dc7, + 0x0dc9, + 0x0dcb, + 0x0dce, + 0x0dd5, + 0x0dd5, + 0x0dd7, + 0x0dd7, + 0x0de0, + 0x0df1, + 0x0df5, + 0x0e00, + 0x0e3b, + 0x0e3e, + 0x0e5c, + 0x0e80, + 0x0e83, + 0x0e83, + 0x0e85, + 0x0e86, + 0x0e89, + 0x0e89, + 0x0e8b, + 0x0e8c, + 0x0e8e, + 0x0e93, + 0x0e98, + 0x0e98, + 0x0ea0, + 0x0ea0, + 0x0ea4, + 0x0ea4, + 0x0ea6, + 0x0ea6, + 0x0ea8, + 0x0ea9, + 0x0eac, + 0x0eac, + 0x0eba, + 0x0eba, + 0x0ebe, + 0x0ebf, + 0x0ec5, + 0x0ec5, + 0x0ec7, + 0x0ec7, + 0x0ece, + 0x0ecf, + 0x0eda, + 0x0edb, + 0x0ede, + 0x0eff, + 0x0f48, + 0x0f48, + 0x0f6b, + 0x0f70, + 0x0f8c, + 0x0f8f, + 0x0f98, + 0x0f98, + 0x0fbd, + 0x0fbd, + 0x0fcd, + 0x0fce, + 0x0fd0, + 0x0fff, + 0x1022, + 0x1022, + 0x1028, + 0x1028, + 0x102b, + 0x102b, + 0x1033, + 0x1035, + 0x103a, + 0x103f, + 0x105a, + 0x109f, + 0x10c6, + 0x10cf, + 0x10f9, + 0x10fa, + 0x10fc, + 0x10ff, + 0x115a, + 0x115e, + 0x11a3, + 0x11a7, + 0x11fa, + 0x11ff, + 0x1207, + 0x1207, + 0x1247, + 0x1247, + 0x1249, + 0x1249, + 0x124e, + 0x124f, + 0x1257, + 0x1257, + 0x1259, + 0x1259, + 0x125e, + 0x125f, + 0x1287, + 0x1287, + 0x1289, + 0x1289, + 0x128e, + 0x128f, + 0x12af, + 0x12af, + 0x12b1, + 0x12b1, + 0x12b6, + 0x12b7, + 0x12bf, + 0x12bf, + 0x12c1, + 0x12c1, + 0x12c6, + 0x12c7, + 0x12cf, + 0x12cf, + 0x12d7, + 0x12d7, + 0x12ef, + 0x12ef, + 0x130f, + 0x130f, + 0x1311, + 0x1311, + 0x1316, + 0x1317, + 0x131f, + 0x131f, + 0x1347, + 0x1347, + 0x135b, + 0x1360, + 0x137d, + 0x139f, + 0x13f5, + 0x1400, + 0x1677, + 0x167f, + 0x169d, + 0x169f, + 0x16f1, + 0x16ff, + 0x170d, + 0x170d, + 0x1715, + 0x171f, + 0x1737, + 0x173f, + 0x1754, + 0x175f, + 0x176d, + 0x176d, + 0x1771, + 0x1771, + 0x1774, + 0x177f, + 0x17dd, + 0x17df, + 0x17ea, + 0x17ff, + 0x180f, + 0x180f, + 0x181a, + 0x181f, + 0x1878, + 0x187f, + 0x18aa, + 0x1dff, + 0x1e9c, + 0x1e9f, + 0x1efa, + 0x1eff, + 0x1f16, + 0x1f17, + 0x1f1e, + 0x1f1f, + 0x1f46, + 0x1f47, + 0x1f4e, + 0x1f4f, + 0x1f58, + 0x1f58, + 0x1f5a, + 0x1f5a, + 0x1f5c, + 0x1f5c, + 0x1f5e, + 0x1f5e, + 0x1f7e, + 0x1f7f, + 0x1fb5, + 0x1fb5, + 0x1fc5, + 0x1fc5, + 0x1fd4, + 0x1fd5, + 0x1fdc, + 0x1fdc, + 0x1ff0, + 0x1ff1, + 0x1ff5, + 0x1ff5, + 0x1fff, + 0x1fff, + 0x2053, + 0x2056, + 0x2058, + 0x205e, + 0x2064, + 0x2069, + 0x2072, + 0x2073, + 0x208f, + 0x209f, + 0x20b2, + 0x20cf, + 0x20eb, + 0x20ff, + 0x213b, + 0x213c, + 0x214c, + 0x2152, + 0x2184, + 0x218f, + 0x23cf, + 0x23ff, + 0x2427, + 0x243f, + 0x244b, + 0x245f, + 0x24ff, + 0x24ff, + 0x2614, + 0x2615, + 0x2618, + 0x2618, + 0x267e, + 0x267f, + 0x268a, + 0x2700, + 0x2705, + 0x2705, + 0x270a, + 0x270b, + 0x2728, + 0x2728, + 0x274c, + 0x274c, + 0x274e, + 0x274e, + 0x2753, + 0x2755, + 0x2757, + 0x2757, + 0x275f, + 0x2760, + 0x2795, + 0x2797, + 0x27b0, + 0x27b0, + 0x27bf, + 0x27cf, + 0x27ec, + 0x27ef, + 0x2b00, + 0x2e7f, + 0x2e9a, + 0x2e9a, + 0x2ef4, + 0x2eff, + 0x2fd6, + 0x2fef, + 0x2ffc, + 0x2fff, + 0x3040, + 0x3040, + 0x3097, + 0x3098, + 0x3100, + 0x3104, + 0x312d, + 0x3130, + 0x318f, + 0x318f, + 0x31b8, + 0x31ef, + 0x321d, + 0x321f, + 0x3244, + 0x3250, + 0x327c, + 0x327e, + 0x32cc, + 0x32cf, + 0x32ff, + 0x32ff, + 0x3377, + 0x337a, + 0x33de, + 0x33df, + 0x33ff, + 0x33ff, + 0x4db6, + 0x4dff, + 0x9fa6, + 0x9fff, + 0xa48d, + 0xa48f, + 0xa4c7, + 0xabff, + 0xd7a4, + 0xd7ff, + 0xfa2e, + 0xfa2f, + 0xfa6b, + 0xfaff, + 0xfb07, + 0xfb12, + 0xfb18, + 0xfb1c, + 0xfb37, + 0xfb37, + 0xfb3d, + 0xfb3d, + 0xfb3f, + 0xfb3f, + 0xfb42, + 0xfb42, + 0xfb45, + 0xfb45, + 0xfbb2, + 0xfbd2, + 0xfd40, + 0xfd4f, + 0xfd90, + 0xfd91, + 0xfdc8, + 0xfdcf, + 0xfdfd, + 0xfdff, + 0xfe10, + 0xfe1f, + 0xfe24, + 0xfe2f, + 0xfe47, + 0xfe48, + 0xfe53, + 0xfe53, + 0xfe67, + 0xfe67, + 0xfe6c, + 0xfe6f, + 0xfe75, + 0xfe75, + 0xfefd, + 0xfefe, + 0xff00, + 0xff00, + 0xffbf, + 0xffc1, + 0xffc8, + 0xffc9, + 0xffd0, + 0xffd1, + 0xffd8, + 0xffd9, + 0xffdd, + 0xffdf, + 0xffe7, + 0xffe7, + 0xffef, + 0xfff8, + 0x10000, + 0x102ff, + 0x1031f, + 0x1031f, + 0x10324, + 0x1032f, + 0x1034b, + 0x103ff, + 0x10426, + 0x10427, + 0x1044e, + 0x1cfff, + 0x1d0f6, + 0x1d0ff, + 0x1d127, + 0x1d129, + 0x1d1de, + 0x1d3ff, + 0x1d455, + 0x1d455, + 0x1d49d, + 0x1d49d, + 0x1d4a0, + 0x1d4a1, + 0x1d4a3, + 0x1d4a4, + 0x1d4a7, + 0x1d4a8, + 0x1d4ad, + 0x1d4ad, + 0x1d4ba, + 0x1d4ba, + 0x1d4bc, + 0x1d4bc, + 0x1d4c1, + 0x1d4c1, + 0x1d4c4, + 0x1d4c4, + 0x1d506, + 0x1d506, + 0x1d50b, + 0x1d50c, + 0x1d515, + 0x1d515, + 0x1d51d, + 0x1d51d, + 0x1d53a, + 0x1d53a, + 0x1d53f, + 0x1d53f, + 0x1d545, + 0x1d545, + 0x1d547, + 0x1d549, + 0x1d551, + 0x1d551, + 0x1d6a4, + 0x1d6a7, + 0x1d7ca, + 0x1d7cd, + 0x1d800, + 0x1fffd, + 0x2a6d7, + 0x2f7ff, + 0x2fa1e, + 0x2fffd, + 0x30000, + 0x3fffd, + 0x40000, + 0x4fffd, + 0x50000, + 0x5fffd, + 0x60000, + 0x6fffd, + 0x70000, + 0x7fffd, + 0x80000, + 0x8fffd, + 0x90000, + 0x9fffd, + 0xa0000, + 0xafffd, + 0xb0000, + 0xbfffd, + 0xc0000, + 0xcfffd, + 0xd0000, + 0xdfffd, + 0xe0000, + 0xe0000, + 0xe0002, + 0xe001f, + 0xe0080, + 0xefffd + ]; + /* eslint-enable */ - // 2.1. Mapping - - /** - * non-ASCII space characters [StringPrep, C.1.2] that can be - * mapped to SPACE (U+0020) - */ - const mapping2space = isNonASCIISpaceCharacter; - - /** - * the "commonly mapped to nothing" characters [StringPrep, B.1] - * that can be mapped to nothing. - */ - const mapping2nothing = isCommonlyMappedToNothing; - - // utils - const getCodePoint = character => character.codePointAt(0); - const first = x => x[0]; - const last = x => x[x.length - 1]; - - /** - * Convert provided string into an array of Unicode Code Points. - * Based on https://stackoverflow.com/a/21409165/1556249 - * and https://www.npmjs.com/package/code-point-at. - * @param {string} input - * @returns {number[]} - */ - function toCodePoints(input) { - const codepoints = []; - const size = input.length; - - for (let i = 0; i < size; i += 1) { - const before = input.charCodeAt(i); - - if (before >= 0xd800 && before <= 0xdbff && size > i + 1) { - const next = input.charCodeAt(i + 1); - - if (next >= 0xdc00 && next <= 0xdfff) { - codepoints.push((before - 0xd800) * 0x400 + next - 0xdc00 + 0x10000); - i += 1; - continue; - } - } - - codepoints.push(before); - } - - return codepoints; - } - - /** - * SASLprep. - * @param {string} input - * @param {Object} opts - * @param {boolean} opts.allowUnassigned - * @returns {string} - */ - function saslprep(input, opts = {}) { - if (typeof input !== 'string') { - throw new TypeError('Expected string.'); - } - - if (input.length === 0) { - return ''; - } - - // 1. Map - const mapped_input = toCodePoints(input) - // 1.1 mapping to space - .map(character => (mapping2space(character) ? 0x20 : character)) - // 1.2 mapping to nothing - .filter(character => !mapping2nothing(character)); - - // 2. Normalize - const normalized_input = String.fromCodePoint - .apply(null, mapped_input) - .normalize('NFKC'); - - const normalized_map = toCodePoints(normalized_input); - - // 3. Prohibit - const hasProhibited = normalized_map.some(isProhibitedCharacter); - - if (hasProhibited) { - throw new Error( - 'Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3' - ); - } - - // Unassigned Code Points - if (opts.allowUnassigned !== true) { - const hasUnassigned = normalized_map.some(isUnassignedCodePoint); - - if (hasUnassigned) { - throw new Error( - 'Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5' - ); - } - } - - // 4. check bidi - - const hasBidiRAL = normalized_map.some(isBidirectionalRAL); - - const hasBidiL = normalized_map.some(isBidirectionalL); - - // 4.1 If a string contains any RandALCat character, the string MUST NOT - // contain any LCat character. - if (hasBidiRAL && hasBidiL) { - throw new Error( - 'String must not contain RandALCat and LCat at the same time,' + - ' see https://tools.ietf.org/html/rfc3454#section-6' - ); - } - - /** - * 4.2 If a string contains any RandALCat character, a RandALCat - * character MUST be the first character of the string, and a - * RandALCat character MUST be the last character of the string. - */ - - const isFirstBidiRAL = isBidirectionalRAL( - getCodePoint(first(normalized_input)) - ); - const isLastBidiRAL = isBidirectionalRAL( - getCodePoint(last(normalized_input)) - ); - - if (hasBidiRAL && !(isFirstBidiRAL && isLastBidiRAL)) { - throw new Error( - 'Bidirectional RandALCat character must be the first and the last' + - ' character of the string, see https://tools.ietf.org/html/rfc3454#section-6' - ); - } - - return normalized_input; - } + const isUnassignedCodePoint = character => + inRange(character, unassigned_code_points); - class PDFSecurity { - static generateFileID(info = {}) { - let infoStr = `${info.CreationDate.getTime()}\n`; - - for (let key in info) { - if (!info.hasOwnProperty(key)) { - continue; - } - infoStr += `${key}: ${info[key]}\n`; - } - - return wordArrayToBuffer(C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.MD5(infoStr)); - } - - static generateRandomWordArray(bytes) { - return C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.random(bytes); - } - - static create(document, options = {}) { - if (!options.ownerPassword && !options.userPassword) { - return null; - } - return new PDFSecurity(document, options); - } - - constructor(document, options = {}) { - if (!options.ownerPassword && !options.userPassword) { - throw new Error('None of owner password and user password is defined.'); - } - - this.document = document; - this._setupEncryption(options); - } - - _setupEncryption(options) { - switch (options.pdfVersion) { - case '1.4': - case '1.5': - this.version = 2; - break; - case '1.6': - case '1.7': - this.version = 4; - break; - case '1.7ext3': - this.version = 5; - break; - default: - this.version = 1; - break; - } - - const encDict = { - Filter: 'Standard' - }; - - switch (this.version) { - case 1: - case 2: - case 4: - this._setupEncryptionV1V2V4(this.version, encDict, options); - break; - case 5: - this._setupEncryptionV5(encDict, options); - break; - } - - this.dictionary = this.document.ref(encDict); - } - - _setupEncryptionV1V2V4(v, encDict, options) { - let r, permissions; - switch (v) { - case 1: - r = 2; - this.keyBits = 40; - permissions = getPermissionsR2(options.permissions); - break; - case 2: - r = 3; - this.keyBits = 128; - permissions = getPermissionsR3(options.permissions); - break; - case 4: - r = 4; - this.keyBits = 128; - permissions = getPermissionsR3(options.permissions); - break; - } - - const paddedUserPassword = processPasswordR2R3R4(options.userPassword); - const paddedOwnerPassword = options.ownerPassword - ? processPasswordR2R3R4(options.ownerPassword) - : paddedUserPassword; - - const ownerPasswordEntry = getOwnerPasswordR2R3R4( - r, - this.keyBits, - paddedUserPassword, - paddedOwnerPassword - ); - this.encryptionKey = getEncryptionKeyR2R3R4( - r, - this.keyBits, - this.document._id, - paddedUserPassword, - ownerPasswordEntry, - permissions - ); - let userPasswordEntry; - if (r === 2) { - userPasswordEntry = getUserPasswordR2(this.encryptionKey); - } else { - userPasswordEntry = getUserPasswordR3R4( - this.document._id, - this.encryptionKey - ); - } - - encDict.V = v; - if (v >= 2) { - encDict.Length = this.keyBits; - } - if (v === 4) { - encDict.CF = { - StdCF: { - AuthEvent: 'DocOpen', - CFM: 'AESV2', - Length: this.keyBits / 8 - } - }; - encDict.StmF = 'StdCF'; - encDict.StrF = 'StdCF'; - } - encDict.R = r; - encDict.O = wordArrayToBuffer(ownerPasswordEntry); - encDict.U = wordArrayToBuffer(userPasswordEntry); - encDict.P = permissions; - } - - _setupEncryptionV5(encDict, options) { - this.keyBits = 256; - const permissions = getPermissionsR3(options); - - const processedUserPassword = processPasswordR5(options.userPassword); - const processedOwnerPassword = options.ownerPassword - ? processPasswordR5(options.ownerPassword) - : processedUserPassword; - - this.encryptionKey = getEncryptionKeyR5( - PDFSecurity.generateRandomWordArray - ); - const userPasswordEntry = getUserPasswordR5( - processedUserPassword, - PDFSecurity.generateRandomWordArray - ); - const userKeySalt = C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create( - userPasswordEntry.words.slice(10, 12), - 8 - ); - const userEncryptionKeyEntry = getUserEncryptionKeyR5( - processedUserPassword, - userKeySalt, - this.encryptionKey - ); - const ownerPasswordEntry = getOwnerPasswordR5( - processedOwnerPassword, - userPasswordEntry, - PDFSecurity.generateRandomWordArray - ); - const ownerKeySalt = C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create( - ownerPasswordEntry.words.slice(10, 12), - 8 - ); - const ownerEncryptionKeyEntry = getOwnerEncryptionKeyR5( - processedOwnerPassword, - ownerKeySalt, - userPasswordEntry, - this.encryptionKey - ); - const permsEntry = getEncryptedPermissionsR5( - permissions, - this.encryptionKey, - PDFSecurity.generateRandomWordArray - ); - - encDict.V = 5; - encDict.Length = this.keyBits; - encDict.CF = { - StdCF: { - AuthEvent: 'DocOpen', - CFM: 'AESV3', - Length: this.keyBits / 8 - } - }; - encDict.StmF = 'StdCF'; - encDict.StrF = 'StdCF'; - encDict.R = 5; - encDict.O = wordArrayToBuffer(ownerPasswordEntry); - encDict.OE = wordArrayToBuffer(ownerEncryptionKeyEntry); - encDict.U = wordArrayToBuffer(userPasswordEntry); - encDict.UE = wordArrayToBuffer(userEncryptionKeyEntry); - encDict.P = permissions; - encDict.Perms = wordArrayToBuffer(permsEntry); - } - - getEncryptFn(obj, gen) { - let digest; - if (this.version < 5) { - digest = this.encryptionKey - .clone() - .concat( - C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create( - [ - ((obj & 0xff) << 24) | - ((obj & 0xff00) << 8) | - ((obj >> 8) & 0xff00) | - (gen & 0xff), - (gen & 0xff00) << 16 - ], - 5 - ) - ); - } - - if (this.version === 1 || this.version === 2) { - let key = C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.MD5(digest); - key.sigBytes = Math.min(16, this.keyBits / 8 + 5); - return buffer => - wordArrayToBuffer( - C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.RC4.encrypt(C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create(buffer), key) - .ciphertext - ); - } - - let key; - if (this.version === 4) { - key = C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.MD5( - digest.concat(C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create([0x73416c54], 4)) - ); - } else { - key = this.encryptionKey; - } - - const iv = PDFSecurity.generateRandomWordArray(16); - const options = { - mode: C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.mode.CBC, - padding: C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.pad.Pkcs7, - iv - }; - - return buffer => - wordArrayToBuffer( - iv - .clone() - .concat( - C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.AES.encrypt( - C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create(buffer), - key, - options - ).ciphertext - ) - ); - } - - end() { - this.dictionary.end(); - } - } - - function getPermissionsR2(permissionObject = {}) { - let permissions = 0xffffffc0 >> 0; - if (permissionObject.printing) { - permissions |= 0b000000000100; - } - if (permissionObject.modifying) { - permissions |= 0b000000001000; - } - if (permissionObject.copying) { - permissions |= 0b000000010000; - } - if (permissionObject.annotating) { - permissions |= 0b000000100000; - } - return permissions; - } - - function getPermissionsR3(permissionObject = {}) { - let permissions = 0xfffff0c0 >> 0; - if (permissionObject.printing === 'lowResolution') { - permissions |= 0b000000000100; - } - if (permissionObject.printing === 'highResolution') { - permissions |= 0b100000000100; - } - if (permissionObject.modifying) { - permissions |= 0b000000001000; - } - if (permissionObject.copying) { - permissions |= 0b000000010000; - } - if (permissionObject.annotating) { - permissions |= 0b000000100000; - } - if (permissionObject.fillingForms) { - permissions |= 0b000100000000; - } - if (permissionObject.contentAccessibility) { - permissions |= 0b001000000000; - } - if (permissionObject.documentAssembly) { - permissions |= 0b010000000000; - } - return permissions; - } - - function getUserPasswordR2(encryptionKey) { - return C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.RC4.encrypt(processPasswordR2R3R4(), encryptionKey) - .ciphertext; - } - - function getUserPasswordR3R4(documentId, encryptionKey) { - const key = encryptionKey.clone(); - let cipher = C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.MD5( - processPasswordR2R3R4().concat(C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create(documentId)) - ); - for (let i = 0; i < 20; i++) { - const xorRound = Math.ceil(key.sigBytes / 4); - for (let j = 0; j < xorRound; j++) { - key.words[j] = - encryptionKey.words[j] ^ (i | (i << 8) | (i << 16) | (i << 24)); - } - cipher = C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.RC4.encrypt(cipher, key).ciphertext; - } - return cipher.concat(C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create(null, 16)); - } - - function getOwnerPasswordR2R3R4( - r, - keyBits, - paddedUserPassword, - paddedOwnerPassword - ) { - let digest = paddedOwnerPassword; - let round = r >= 3 ? 51 : 1; - for (let i = 0; i < round; i++) { - digest = C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.MD5(digest); - } - - const key = digest.clone(); - key.sigBytes = keyBits / 8; - let cipher = paddedUserPassword; - round = r >= 3 ? 20 : 1; - for (let i = 0; i < round; i++) { - const xorRound = Math.ceil(key.sigBytes / 4); - for (let j = 0; j < xorRound; j++) { - key.words[j] = digest.words[j] ^ (i | (i << 8) | (i << 16) | (i << 24)); - } - cipher = C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.RC4.encrypt(cipher, key).ciphertext; - } - return cipher; - } - - function getEncryptionKeyR2R3R4( - r, - keyBits, - documentId, - paddedUserPassword, - ownerPasswordEntry, - permissions - ) { - let key = paddedUserPassword - .clone() - .concat(ownerPasswordEntry) - .concat(C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create([lsbFirstWord(permissions)], 4)) - .concat(C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create(documentId)); - const round = r >= 3 ? 51 : 1; - for (let i = 0; i < round; i++) { - key = C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.MD5(key); - key.sigBytes = keyBits / 8; - } - return key; - } - - function getUserPasswordR5(processedUserPassword, generateRandomWordArray) { - const validationSalt = generateRandomWordArray(8); - const keySalt = generateRandomWordArray(8); - return C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.SHA256(processedUserPassword.clone().concat(validationSalt)) - .concat(validationSalt) - .concat(keySalt); - } - - function getUserEncryptionKeyR5( - processedUserPassword, - userKeySalt, - encryptionKey - ) { - const key = C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.SHA256( - processedUserPassword.clone().concat(userKeySalt) - ); - const options = { - mode: C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.mode.CBC, - padding: C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.pad.NoPadding, - iv: C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create(null, 16) - }; - return C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.AES.encrypt(encryptionKey, key, options).ciphertext; - } - - function getOwnerPasswordR5( - processedOwnerPassword, - userPasswordEntry, - generateRandomWordArray - ) { - const validationSalt = generateRandomWordArray(8); - const keySalt = generateRandomWordArray(8); - return C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.SHA256( - processedOwnerPassword - .clone() - .concat(validationSalt) - .concat(userPasswordEntry) - ) - .concat(validationSalt) - .concat(keySalt); - } - - function getOwnerEncryptionKeyR5( - processedOwnerPassword, - ownerKeySalt, - userPasswordEntry, - encryptionKey - ) { - const key = C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.SHA256( - processedOwnerPassword - .clone() - .concat(ownerKeySalt) - .concat(userPasswordEntry) - ); - const options = { - mode: C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.mode.CBC, - padding: C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.pad.NoPadding, - iv: C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create(null, 16) - }; - return C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.AES.encrypt(encryptionKey, key, options).ciphertext; - } - - function getEncryptionKeyR5(generateRandomWordArray) { - return generateRandomWordArray(32); - } - - function getEncryptedPermissionsR5( - permissions, - encryptionKey, - generateRandomWordArray - ) { - const cipher = C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create( - [lsbFirstWord(permissions), 0xffffffff, 0x54616462], - 12 - ).concat(generateRandomWordArray(4)); - const options = { - mode: C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.mode.ECB, - padding: C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.pad.NoPadding - }; - return C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.AES.encrypt(cipher, encryptionKey, options).ciphertext; - } - - function processPasswordR2R3R4(password = '') { - const out = new Buffer(32); - const length = password.length; - let index = 0; - while (index < length && index < 32) { - const code = password.charCodeAt(index); - if (code > 0xff) { - throw new Error('Password contains one or more invalid characters.'); - } - out[index] = code; - index++; - } - while (index < 32) { - out[index] = PASSWORD_PADDING[index - length]; - index++; - } - return C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create(out); - } - - function processPasswordR5(password = '') { - password = unescape(encodeURIComponent(saslprep(password))); - const length = Math.min(127, password.length); - const out = new Buffer(length); - - for (let i = 0; i < length; i++) { - out[i] = password.charCodeAt(i); - } - - return C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_cryptoJs.lib.WordArray.create(out); - } - - function lsbFirstWord(data) { - return ( - ((data & 0xff) << 24) | - ((data & 0xff00) << 8) | - ((data >> 8) & 0xff00) | - ((data >> 24) & 0xff) - ); - } - - function wordArrayToBuffer(wordArray) { - const byteArray = []; - for (let i = 0; i < wordArray.sigBytes; i++) { - byteArray.push( - (wordArray.words[Math.floor(i / 4)] >> (8 * (3 - (i % 4)))) & 0xff - ); - } - return Buffer.from(byteArray); - } - - const PASSWORD_PADDING = [ - 0x28, - 0xbf, - 0x4e, - 0x5e, - 0x4e, - 0x75, - 0x8a, - 0x41, - 0x64, - 0x00, - 0x4e, - 0x56, - 0xff, - 0xfa, - 0x01, - 0x08, - 0x2e, - 0x2e, - 0x00, - 0xb6, - 0xd0, - 0x68, - 0x3e, - 0x80, - 0x2f, - 0x0c, - 0xa9, - 0xfe, - 0x64, - 0x53, - 0x69, - 0x7a + /* eslint-disable prettier/prettier */ + /** + * B.1 Commonly mapped to nothing + * @link https://tools.ietf.org/html/rfc3454#appendix-B.1 + */ + const commonly_mapped_to_nothing = [ + 0x00ad, + 0x00ad, + 0x034f, + 0x034f, + 0x1806, + 0x1806, + 0x180b, + 0x180b, + 0x180c, + 0x180c, + 0x180d, + 0x180d, + 0x200b, + 0x200b, + 0x200c, + 0x200c, + 0x200d, + 0x200d, + 0x2060, + 0x2060, + 0xfe00, + 0xfe00, + 0xfe01, + 0xfe01, + 0xfe02, + 0xfe02, + 0xfe03, + 0xfe03, + 0xfe04, + 0xfe04, + 0xfe05, + 0xfe05, + 0xfe06, + 0xfe06, + 0xfe07, + 0xfe07, + 0xfe08, + 0xfe08, + 0xfe09, + 0xfe09, + 0xfe0a, + 0xfe0a, + 0xfe0b, + 0xfe0b, + 0xfe0c, + 0xfe0c, + 0xfe0d, + 0xfe0d, + 0xfe0e, + 0xfe0e, + 0xfe0f, + 0xfe0f, + 0xfeff, + 0xfeff + ]; + /* eslint-enable */ + + const isCommonlyMappedToNothing = character => + inRange(character, commonly_mapped_to_nothing); + + /* eslint-disable prettier/prettier */ + /** + * C.1.2 Non-ASCII space characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.1.2 + */ + const non_ASCII_space_characters = [ + 0x00a0, + 0x00a0 /* NO-BREAK SPACE */, + 0x1680, + 0x1680 /* OGHAM SPACE MARK */, + 0x2000, + 0x2000 /* EN QUAD */, + 0x2001, + 0x2001 /* EM QUAD */, + 0x2002, + 0x2002 /* EN SPACE */, + 0x2003, + 0x2003 /* EM SPACE */, + 0x2004, + 0x2004 /* THREE-PER-EM SPACE */, + 0x2005, + 0x2005 /* FOUR-PER-EM SPACE */, + 0x2006, + 0x2006 /* SIX-PER-EM SPACE */, + 0x2007, + 0x2007 /* FIGURE SPACE */, + 0x2008, + 0x2008 /* PUNCTUATION SPACE */, + 0x2009, + 0x2009 /* THIN SPACE */, + 0x200a, + 0x200a /* HAIR SPACE */, + 0x200b, + 0x200b /* ZERO WIDTH SPACE */, + 0x202f, + 0x202f /* NARROW NO-BREAK SPACE */, + 0x205f, + 0x205f /* MEDIUM MATHEMATICAL SPACE */, + 0x3000, + 0x3000 /* IDEOGRAPHIC SPACE */ + ]; + /* eslint-enable */ + + const isNonASCIISpaceCharacter = character => + inRange(character, non_ASCII_space_characters); + + /* eslint-disable prettier/prettier */ + const non_ASCII_controls_characters = [ + /** + * C.2.2 Non-ASCII control characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.2 + */ + 0x0080, + 0x009f /* [CONTROL CHARACTERS] */, + 0x06dd, + 0x06dd /* ARABIC END OF AYAH */, + 0x070f, + 0x070f /* SYRIAC ABBREVIATION MARK */, + 0x180e, + 0x180e /* MONGOLIAN VOWEL SEPARATOR */, + 0x200c, + 0x200c /* ZERO WIDTH NON-JOINER */, + 0x200d, + 0x200d /* ZERO WIDTH JOINER */, + 0x2028, + 0x2028 /* LINE SEPARATOR */, + 0x2029, + 0x2029 /* PARAGRAPH SEPARATOR */, + 0x2060, + 0x2060 /* WORD JOINER */, + 0x2061, + 0x2061 /* FUNCTION APPLICATION */, + 0x2062, + 0x2062 /* INVISIBLE TIMES */, + 0x2063, + 0x2063 /* INVISIBLE SEPARATOR */, + 0x206a, + 0x206f /* [CONTROL CHARACTERS] */, + 0xfeff, + 0xfeff /* ZERO WIDTH NO-BREAK SPACE */, + 0xfff9, + 0xfffc /* [CONTROL CHARACTERS] */, + 0x1d173, + 0x1d17a /* [MUSICAL CONTROL CHARACTERS] */ ]; - const { number } = PDFObject; - - class PDFGradient { - constructor(doc) { - this.doc = doc; - this.stops = []; - this.embedded = false; - this.transform = [1, 0, 0, 1, 0, 0]; - } - - stop(pos, color, opacity) { - if (opacity == null) { - opacity = 1; - } - color = this.doc._normalizeColor(color); - - if (this.stops.length === 0) { - if (color.length === 3) { - this._colorSpace = 'DeviceRGB'; - } else if (color.length === 4) { - this._colorSpace = 'DeviceCMYK'; - } else if (color.length === 1) { - this._colorSpace = 'DeviceGray'; - } else { - throw new Error('Unknown color space'); - } - } else if ( - (this._colorSpace === 'DeviceRGB' && color.length !== 3) || - (this._colorSpace === 'DeviceCMYK' && color.length !== 4) || - (this._colorSpace === 'DeviceGray' && color.length !== 1) - ) { - throw new Error('All gradient stops must use the same color space'); - } - - opacity = Math.max(0, Math.min(1, opacity)); - this.stops.push([pos, color, opacity]); - return this; - } - - setTransform(m11, m12, m21, m22, dx, dy) { - this.transform = [m11, m12, m21, m22, dx, dy]; - return this; - } - - embed(m) { - let fn; - const stopsLength = this.stops.length; - if (stopsLength === 0) { - return; - } - this.embedded = true; - this.matrix = m; - - // if the last stop comes before 100%, add a copy at 100% - const last = this.stops[stopsLength - 1]; - if (last[0] < 1) { - this.stops.push([1, last[1], last[2]]); - } - - const bounds = []; - const encode = []; - const stops = []; - - for (let i = 0; i < stopsLength - 1; i++) { - encode.push(0, 1); - if (i + 2 !== stopsLength) { - bounds.push(this.stops[i + 1][0]); - } - - fn = this.doc.ref({ - FunctionType: 2, - Domain: [0, 1], - C0: this.stops[i + 0][1], - C1: this.stops[i + 1][1], - N: 1 - }); - - stops.push(fn); - fn.end(); - } - - // if there are only two stops, we don't need a stitching function - if (stopsLength === 1) { - fn = stops[0]; - } else { - fn = this.doc.ref({ - FunctionType: 3, // stitching function - Domain: [0, 1], - Functions: stops, - Bounds: bounds, - Encode: encode - }); - - fn.end(); - } - - this.id = `Sh${++this.doc._gradCount}`; - - const shader = this.shader(fn); - shader.end(); - - const pattern = this.doc.ref({ - Type: 'Pattern', - PatternType: 2, - Shading: shader, - Matrix: this.matrix.map(number) - }); - - pattern.end(); - - if (this.stops.some(stop => stop[2] < 1)) { - let grad = this.opacityGradient(); - grad._colorSpace = 'DeviceGray'; - - for (let stop of this.stops) { - grad.stop(stop[0], [stop[2]]); - } - - grad = grad.embed(this.matrix); - - const pageBBox = [0, 0, this.doc.page.width, this.doc.page.height]; - - const form = this.doc.ref({ - Type: 'XObject', - Subtype: 'Form', - FormType: 1, - BBox: pageBBox, - Group: { - Type: 'Group', - S: 'Transparency', - CS: 'DeviceGray' - }, - Resources: { - ProcSet: ['PDF', 'Text', 'ImageB', 'ImageC', 'ImageI'], - Pattern: { - Sh1: grad - } - } - }); - - form.write('/Pattern cs /Sh1 scn'); - form.end(`${pageBBox.join(' ')} re f`); - - const gstate = this.doc.ref({ - Type: 'ExtGState', - SMask: { - Type: 'Mask', - S: 'Luminosity', - G: form - } - }); - - gstate.end(); - - const opacityPattern = this.doc.ref({ - Type: 'Pattern', - PatternType: 1, - PaintType: 1, - TilingType: 2, - BBox: pageBBox, - XStep: pageBBox[2], - YStep: pageBBox[3], - Resources: { - ProcSet: ['PDF', 'Text', 'ImageB', 'ImageC', 'ImageI'], - Pattern: { - Sh1: pattern - }, - ExtGState: { - Gs1: gstate - } - } - }); - - opacityPattern.write('/Gs1 gs /Pattern cs /Sh1 scn'); - opacityPattern.end(`${pageBBox.join(' ')} re f`); - - this.doc.page.patterns[this.id] = opacityPattern; - } else { - this.doc.page.patterns[this.id] = pattern; - } - - return pattern; - } - - apply(op) { - // apply gradient transform to existing document ctm - const [m0, m1, m2, m3, m4, m5] = this.doc._ctm; - const [m11, m12, m21, m22, dx, dy] = this.transform; - const m = [ - m0 * m11 + m2 * m12, - m1 * m11 + m3 * m12, - m0 * m21 + m2 * m22, - m1 * m21 + m3 * m22, - m0 * dx + m2 * dy + m4, - m1 * dx + m3 * dy + m5 - ]; - - if (!this.embedded || m.join(' ') !== this.matrix.join(' ')) { - this.embed(m); - } - return this.doc.addContent(`/${this.id} ${op}`); - } - } - - class PDFLinearGradient extends PDFGradient { - constructor(doc, x1, y1, x2, y2) { - super(doc); - this.x1 = x1; - this.y1 = y1; - this.x2 = x2; - this.y2 = y2; - } - - shader(fn) { - return this.doc.ref({ - ShadingType: 2, - ColorSpace: this._colorSpace, - Coords: [this.x1, this.y1, this.x2, this.y2], - Function: fn, - Extend: [true, true] - }); - } - - opacityGradient() { - return new PDFLinearGradient(this.doc, this.x1, this.y1, this.x2, this.y2); - } - } - - class PDFRadialGradient extends PDFGradient { - constructor(doc, x1, y1, r1, x2, y2, r2) { - super(doc); - this.doc = doc; - this.x1 = x1; - this.y1 = y1; - this.r1 = r1; - this.x2 = x2; - this.y2 = y2; - this.r2 = r2; - } - - shader(fn) { - return this.doc.ref({ - ShadingType: 3, - ColorSpace: this._colorSpace, - Coords: [this.x1, this.y1, this.r1, this.x2, this.y2, this.r2], - Function: fn, - Extend: [true, true] - }); - } - - opacityGradient() { - return new PDFRadialGradient( - this.doc, - this.x1, - this.y1, - this.r1, - this.x2, - this.y2, - this.r2 - ); - } - } - + const non_character_codepoints = [ + /** + * C.4 Non-character code points + * @link https://tools.ietf.org/html/rfc3454#appendix-C.4 + */ + 0xfdd0, + 0xfdef /* [NONCHARACTER CODE POINTS] */, + 0xfffe, + 0xffff /* [NONCHARACTER CODE POINTS] */, + 0x1fffe, + 0x1ffff /* [NONCHARACTER CODE POINTS] */, + 0x2fffe, + 0x2ffff /* [NONCHARACTER CODE POINTS] */, + 0x3fffe, + 0x3ffff /* [NONCHARACTER CODE POINTS] */, + 0x4fffe, + 0x4ffff /* [NONCHARACTER CODE POINTS] */, + 0x5fffe, + 0x5ffff /* [NONCHARACTER CODE POINTS] */, + 0x6fffe, + 0x6ffff /* [NONCHARACTER CODE POINTS] */, + 0x7fffe, + 0x7ffff /* [NONCHARACTER CODE POINTS] */, + 0x8fffe, + 0x8ffff /* [NONCHARACTER CODE POINTS] */, + 0x9fffe, + 0x9ffff /* [NONCHARACTER CODE POINTS] */, + 0xafffe, + 0xaffff /* [NONCHARACTER CODE POINTS] */, + 0xbfffe, + 0xbffff /* [NONCHARACTER CODE POINTS] */, + 0xcfffe, + 0xcffff /* [NONCHARACTER CODE POINTS] */, + 0xdfffe, + 0xdffff /* [NONCHARACTER CODE POINTS] */, + 0xefffe, + 0xeffff /* [NONCHARACTER CODE POINTS] */, + 0x10fffe, + 0x10ffff /* [NONCHARACTER CODE POINTS] */ + ]; + + /** + * 2.3. Prohibited Output + */ + const prohibited_characters = [ + /** + * C.2.1 ASCII control characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.1 + */ + 0, + 0x001f /* [CONTROL CHARACTERS] */, + 0x007f, + 0x007f /* DELETE */, + + /** + * C.8 Change display properties or are deprecated + * @link https://tools.ietf.org/html/rfc3454#appendix-C.8 + */ + 0x0340, + 0x0340 /* COMBINING GRAVE TONE MARK */, + 0x0341, + 0x0341 /* COMBINING ACUTE TONE MARK */, + 0x200e, + 0x200e /* LEFT-TO-RIGHT MARK */, + 0x200f, + 0x200f /* RIGHT-TO-LEFT MARK */, + 0x202a, + 0x202a /* LEFT-TO-RIGHT EMBEDDING */, + 0x202b, + 0x202b /* RIGHT-TO-LEFT EMBEDDING */, + 0x202c, + 0x202c /* POP DIRECTIONAL FORMATTING */, + 0x202d, + 0x202d /* LEFT-TO-RIGHT OVERRIDE */, + 0x202e, + 0x202e /* RIGHT-TO-LEFT OVERRIDE */, + 0x206a, + 0x206a /* INHIBIT SYMMETRIC SWAPPING */, + 0x206b, + 0x206b /* ACTIVATE SYMMETRIC SWAPPING */, + 0x206c, + 0x206c /* INHIBIT ARABIC FORM SHAPING */, + 0x206d, + 0x206d /* ACTIVATE ARABIC FORM SHAPING */, + 0x206e, + 0x206e /* NATIONAL DIGIT SHAPES */, + 0x206f, + 0x206f /* NOMINAL DIGIT SHAPES */, + + /** + * C.7 Inappropriate for canonical representation + * @link https://tools.ietf.org/html/rfc3454#appendix-C.7 + */ + 0x2ff0, + 0x2ffb /* [IDEOGRAPHIC DESCRIPTION CHARACTERS] */, + + /** + * C.5 Surrogate codes + * @link https://tools.ietf.org/html/rfc3454#appendix-C.5 + */ + 0xd800, + 0xdfff, + + /** + * C.3 Private use + * @link https://tools.ietf.org/html/rfc3454#appendix-C.3 + */ + 0xe000, + 0xf8ff /* [PRIVATE USE, PLANE 0] */, + + /** + * C.6 Inappropriate for plain text + * @link https://tools.ietf.org/html/rfc3454#appendix-C.6 + */ + 0xfff9, + 0xfff9 /* INTERLINEAR ANNOTATION ANCHOR */, + 0xfffa, + 0xfffa /* INTERLINEAR ANNOTATION SEPARATOR */, + 0xfffb, + 0xfffb /* INTERLINEAR ANNOTATION TERMINATOR */, + 0xfffc, + 0xfffc /* OBJECT REPLACEMENT CHARACTER */, + 0xfffd, + 0xfffd /* REPLACEMENT CHARACTER */, + + /** + * C.9 Tagging characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.9 + */ + 0xe0001, + 0xe0001 /* LANGUAGE TAG */, + 0xe0020, + 0xe007f /* [TAGGING CHARACTERS] */, + + /** + * C.3 Private use + * @link https://tools.ietf.org/html/rfc3454#appendix-C.3 + */ + + 0xf0000, + 0xffffd /* [PRIVATE USE, PLANE 15] */, + 0x100000, + 0x10fffd /* [PRIVATE USE, PLANE 16] */ + ]; + /* eslint-enable */ + + const isProhibitedCharacter = character => + inRange(character, non_ASCII_space_characters) || + inRange(character, prohibited_characters) || + inRange(character, non_ASCII_controls_characters) || + inRange(character, non_character_codepoints); + + /* eslint-disable prettier/prettier */ + /** + * D.1 Characters with bidirectional property "R" or "AL" + * @link https://tools.ietf.org/html/rfc3454#appendix-D.1 + */ + const bidirectional_r_al = [ + 0x05be, + 0x05be, + 0x05c0, + 0x05c0, + 0x05c3, + 0x05c3, + 0x05d0, + 0x05ea, + 0x05f0, + 0x05f4, + 0x061b, + 0x061b, + 0x061f, + 0x061f, + 0x0621, + 0x063a, + 0x0640, + 0x064a, + 0x066d, + 0x066f, + 0x0671, + 0x06d5, + 0x06dd, + 0x06dd, + 0x06e5, + 0x06e6, + 0x06fa, + 0x06fe, + 0x0700, + 0x070d, + 0x0710, + 0x0710, + 0x0712, + 0x072c, + 0x0780, + 0x07a5, + 0x07b1, + 0x07b1, + 0x200f, + 0x200f, + 0xfb1d, + 0xfb1d, + 0xfb1f, + 0xfb28, + 0xfb2a, + 0xfb36, + 0xfb38, + 0xfb3c, + 0xfb3e, + 0xfb3e, + 0xfb40, + 0xfb41, + 0xfb43, + 0xfb44, + 0xfb46, + 0xfbb1, + 0xfbd3, + 0xfd3d, + 0xfd50, + 0xfd8f, + 0xfd92, + 0xfdc7, + 0xfdf0, + 0xfdfc, + 0xfe70, + 0xfe74, + 0xfe76, + 0xfefc + ]; + /* eslint-enable */ + + const isBidirectionalRAL = character => inRange(character, bidirectional_r_al); + + /* eslint-disable prettier/prettier */ + /** + * D.2 Characters with bidirectional property "L" + * @link https://tools.ietf.org/html/rfc3454#appendix-D.2 + */ + const bidirectional_l = [ + 0x0041, + 0x005a, + 0x0061, + 0x007a, + 0x00aa, + 0x00aa, + 0x00b5, + 0x00b5, + 0x00ba, + 0x00ba, + 0x00c0, + 0x00d6, + 0x00d8, + 0x00f6, + 0x00f8, + 0x0220, + 0x0222, + 0x0233, + 0x0250, + 0x02ad, + 0x02b0, + 0x02b8, + 0x02bb, + 0x02c1, + 0x02d0, + 0x02d1, + 0x02e0, + 0x02e4, + 0x02ee, + 0x02ee, + 0x037a, + 0x037a, + 0x0386, + 0x0386, + 0x0388, + 0x038a, + 0x038c, + 0x038c, + 0x038e, + 0x03a1, + 0x03a3, + 0x03ce, + 0x03d0, + 0x03f5, + 0x0400, + 0x0482, + 0x048a, + 0x04ce, + 0x04d0, + 0x04f5, + 0x04f8, + 0x04f9, + 0x0500, + 0x050f, + 0x0531, + 0x0556, + 0x0559, + 0x055f, + 0x0561, + 0x0587, + 0x0589, + 0x0589, + 0x0903, + 0x0903, + 0x0905, + 0x0939, + 0x093d, + 0x0940, + 0x0949, + 0x094c, + 0x0950, + 0x0950, + 0x0958, + 0x0961, + 0x0964, + 0x0970, + 0x0982, + 0x0983, + 0x0985, + 0x098c, + 0x098f, + 0x0990, + 0x0993, + 0x09a8, + 0x09aa, + 0x09b0, + 0x09b2, + 0x09b2, + 0x09b6, + 0x09b9, + 0x09be, + 0x09c0, + 0x09c7, + 0x09c8, + 0x09cb, + 0x09cc, + 0x09d7, + 0x09d7, + 0x09dc, + 0x09dd, + 0x09df, + 0x09e1, + 0x09e6, + 0x09f1, + 0x09f4, + 0x09fa, + 0x0a05, + 0x0a0a, + 0x0a0f, + 0x0a10, + 0x0a13, + 0x0a28, + 0x0a2a, + 0x0a30, + 0x0a32, + 0x0a33, + 0x0a35, + 0x0a36, + 0x0a38, + 0x0a39, + 0x0a3e, + 0x0a40, + 0x0a59, + 0x0a5c, + 0x0a5e, + 0x0a5e, + 0x0a66, + 0x0a6f, + 0x0a72, + 0x0a74, + 0x0a83, + 0x0a83, + 0x0a85, + 0x0a8b, + 0x0a8d, + 0x0a8d, + 0x0a8f, + 0x0a91, + 0x0a93, + 0x0aa8, + 0x0aaa, + 0x0ab0, + 0x0ab2, + 0x0ab3, + 0x0ab5, + 0x0ab9, + 0x0abd, + 0x0ac0, + 0x0ac9, + 0x0ac9, + 0x0acb, + 0x0acc, + 0x0ad0, + 0x0ad0, + 0x0ae0, + 0x0ae0, + 0x0ae6, + 0x0aef, + 0x0b02, + 0x0b03, + 0x0b05, + 0x0b0c, + 0x0b0f, + 0x0b10, + 0x0b13, + 0x0b28, + 0x0b2a, + 0x0b30, + 0x0b32, + 0x0b33, + 0x0b36, + 0x0b39, + 0x0b3d, + 0x0b3e, + 0x0b40, + 0x0b40, + 0x0b47, + 0x0b48, + 0x0b4b, + 0x0b4c, + 0x0b57, + 0x0b57, + 0x0b5c, + 0x0b5d, + 0x0b5f, + 0x0b61, + 0x0b66, + 0x0b70, + 0x0b83, + 0x0b83, + 0x0b85, + 0x0b8a, + 0x0b8e, + 0x0b90, + 0x0b92, + 0x0b95, + 0x0b99, + 0x0b9a, + 0x0b9c, + 0x0b9c, + 0x0b9e, + 0x0b9f, + 0x0ba3, + 0x0ba4, + 0x0ba8, + 0x0baa, + 0x0bae, + 0x0bb5, + 0x0bb7, + 0x0bb9, + 0x0bbe, + 0x0bbf, + 0x0bc1, + 0x0bc2, + 0x0bc6, + 0x0bc8, + 0x0bca, + 0x0bcc, + 0x0bd7, + 0x0bd7, + 0x0be7, + 0x0bf2, + 0x0c01, + 0x0c03, + 0x0c05, + 0x0c0c, + 0x0c0e, + 0x0c10, + 0x0c12, + 0x0c28, + 0x0c2a, + 0x0c33, + 0x0c35, + 0x0c39, + 0x0c41, + 0x0c44, + 0x0c60, + 0x0c61, + 0x0c66, + 0x0c6f, + 0x0c82, + 0x0c83, + 0x0c85, + 0x0c8c, + 0x0c8e, + 0x0c90, + 0x0c92, + 0x0ca8, + 0x0caa, + 0x0cb3, + 0x0cb5, + 0x0cb9, + 0x0cbe, + 0x0cbe, + 0x0cc0, + 0x0cc4, + 0x0cc7, + 0x0cc8, + 0x0cca, + 0x0ccb, + 0x0cd5, + 0x0cd6, + 0x0cde, + 0x0cde, + 0x0ce0, + 0x0ce1, + 0x0ce6, + 0x0cef, + 0x0d02, + 0x0d03, + 0x0d05, + 0x0d0c, + 0x0d0e, + 0x0d10, + 0x0d12, + 0x0d28, + 0x0d2a, + 0x0d39, + 0x0d3e, + 0x0d40, + 0x0d46, + 0x0d48, + 0x0d4a, + 0x0d4c, + 0x0d57, + 0x0d57, + 0x0d60, + 0x0d61, + 0x0d66, + 0x0d6f, + 0x0d82, + 0x0d83, + 0x0d85, + 0x0d96, + 0x0d9a, + 0x0db1, + 0x0db3, + 0x0dbb, + 0x0dbd, + 0x0dbd, + 0x0dc0, + 0x0dc6, + 0x0dcf, + 0x0dd1, + 0x0dd8, + 0x0ddf, + 0x0df2, + 0x0df4, + 0x0e01, + 0x0e30, + 0x0e32, + 0x0e33, + 0x0e40, + 0x0e46, + 0x0e4f, + 0x0e5b, + 0x0e81, + 0x0e82, + 0x0e84, + 0x0e84, + 0x0e87, + 0x0e88, + 0x0e8a, + 0x0e8a, + 0x0e8d, + 0x0e8d, + 0x0e94, + 0x0e97, + 0x0e99, + 0x0e9f, + 0x0ea1, + 0x0ea3, + 0x0ea5, + 0x0ea5, + 0x0ea7, + 0x0ea7, + 0x0eaa, + 0x0eab, + 0x0ead, + 0x0eb0, + 0x0eb2, + 0x0eb3, + 0x0ebd, + 0x0ebd, + 0x0ec0, + 0x0ec4, + 0x0ec6, + 0x0ec6, + 0x0ed0, + 0x0ed9, + 0x0edc, + 0x0edd, + 0x0f00, + 0x0f17, + 0x0f1a, + 0x0f34, + 0x0f36, + 0x0f36, + 0x0f38, + 0x0f38, + 0x0f3e, + 0x0f47, + 0x0f49, + 0x0f6a, + 0x0f7f, + 0x0f7f, + 0x0f85, + 0x0f85, + 0x0f88, + 0x0f8b, + 0x0fbe, + 0x0fc5, + 0x0fc7, + 0x0fcc, + 0x0fcf, + 0x0fcf, + 0x1000, + 0x1021, + 0x1023, + 0x1027, + 0x1029, + 0x102a, + 0x102c, + 0x102c, + 0x1031, + 0x1031, + 0x1038, + 0x1038, + 0x1040, + 0x1057, + 0x10a0, + 0x10c5, + 0x10d0, + 0x10f8, + 0x10fb, + 0x10fb, + 0x1100, + 0x1159, + 0x115f, + 0x11a2, + 0x11a8, + 0x11f9, + 0x1200, + 0x1206, + 0x1208, + 0x1246, + 0x1248, + 0x1248, + 0x124a, + 0x124d, + 0x1250, + 0x1256, + 0x1258, + 0x1258, + 0x125a, + 0x125d, + 0x1260, + 0x1286, + 0x1288, + 0x1288, + 0x128a, + 0x128d, + 0x1290, + 0x12ae, + 0x12b0, + 0x12b0, + 0x12b2, + 0x12b5, + 0x12b8, + 0x12be, + 0x12c0, + 0x12c0, + 0x12c2, + 0x12c5, + 0x12c8, + 0x12ce, + 0x12d0, + 0x12d6, + 0x12d8, + 0x12ee, + 0x12f0, + 0x130e, + 0x1310, + 0x1310, + 0x1312, + 0x1315, + 0x1318, + 0x131e, + 0x1320, + 0x1346, + 0x1348, + 0x135a, + 0x1361, + 0x137c, + 0x13a0, + 0x13f4, + 0x1401, + 0x1676, + 0x1681, + 0x169a, + 0x16a0, + 0x16f0, + 0x1700, + 0x170c, + 0x170e, + 0x1711, + 0x1720, + 0x1731, + 0x1735, + 0x1736, + 0x1740, + 0x1751, + 0x1760, + 0x176c, + 0x176e, + 0x1770, + 0x1780, + 0x17b6, + 0x17be, + 0x17c5, + 0x17c7, + 0x17c8, + 0x17d4, + 0x17da, + 0x17dc, + 0x17dc, + 0x17e0, + 0x17e9, + 0x1810, + 0x1819, + 0x1820, + 0x1877, + 0x1880, + 0x18a8, + 0x1e00, + 0x1e9b, + 0x1ea0, + 0x1ef9, + 0x1f00, + 0x1f15, + 0x1f18, + 0x1f1d, + 0x1f20, + 0x1f45, + 0x1f48, + 0x1f4d, + 0x1f50, + 0x1f57, + 0x1f59, + 0x1f59, + 0x1f5b, + 0x1f5b, + 0x1f5d, + 0x1f5d, + 0x1f5f, + 0x1f7d, + 0x1f80, + 0x1fb4, + 0x1fb6, + 0x1fbc, + 0x1fbe, + 0x1fbe, + 0x1fc2, + 0x1fc4, + 0x1fc6, + 0x1fcc, + 0x1fd0, + 0x1fd3, + 0x1fd6, + 0x1fdb, + 0x1fe0, + 0x1fec, + 0x1ff2, + 0x1ff4, + 0x1ff6, + 0x1ffc, + 0x200e, + 0x200e, + 0x2071, + 0x2071, + 0x207f, + 0x207f, + 0x2102, + 0x2102, + 0x2107, + 0x2107, + 0x210a, + 0x2113, + 0x2115, + 0x2115, + 0x2119, + 0x211d, + 0x2124, + 0x2124, + 0x2126, + 0x2126, + 0x2128, + 0x2128, + 0x212a, + 0x212d, + 0x212f, + 0x2131, + 0x2133, + 0x2139, + 0x213d, + 0x213f, + 0x2145, + 0x2149, + 0x2160, + 0x2183, + 0x2336, + 0x237a, + 0x2395, + 0x2395, + 0x249c, + 0x24e9, + 0x3005, + 0x3007, + 0x3021, + 0x3029, + 0x3031, + 0x3035, + 0x3038, + 0x303c, + 0x3041, + 0x3096, + 0x309d, + 0x309f, + 0x30a1, + 0x30fa, + 0x30fc, + 0x30ff, + 0x3105, + 0x312c, + 0x3131, + 0x318e, + 0x3190, + 0x31b7, + 0x31f0, + 0x321c, + 0x3220, + 0x3243, + 0x3260, + 0x327b, + 0x327f, + 0x32b0, + 0x32c0, + 0x32cb, + 0x32d0, + 0x32fe, + 0x3300, + 0x3376, + 0x337b, + 0x33dd, + 0x33e0, + 0x33fe, + 0x3400, + 0x4db5, + 0x4e00, + 0x9fa5, + 0xa000, + 0xa48c, + 0xac00, + 0xd7a3, + 0xd800, + 0xfa2d, + 0xfa30, + 0xfa6a, + 0xfb00, + 0xfb06, + 0xfb13, + 0xfb17, + 0xff21, + 0xff3a, + 0xff41, + 0xff5a, + 0xff66, + 0xffbe, + 0xffc2, + 0xffc7, + 0xffca, + 0xffcf, + 0xffd2, + 0xffd7, + 0xffda, + 0xffdc, + 0x10300, + 0x1031e, + 0x10320, + 0x10323, + 0x10330, + 0x1034a, + 0x10400, + 0x10425, + 0x10428, + 0x1044d, + 0x1d000, + 0x1d0f5, + 0x1d100, + 0x1d126, + 0x1d12a, + 0x1d166, + 0x1d16a, + 0x1d172, + 0x1d183, + 0x1d184, + 0x1d18c, + 0x1d1a9, + 0x1d1ae, + 0x1d1dd, + 0x1d400, + 0x1d454, + 0x1d456, + 0x1d49c, + 0x1d49e, + 0x1d49f, + 0x1d4a2, + 0x1d4a2, + 0x1d4a5, + 0x1d4a6, + 0x1d4a9, + 0x1d4ac, + 0x1d4ae, + 0x1d4b9, + 0x1d4bb, + 0x1d4bb, + 0x1d4bd, + 0x1d4c0, + 0x1d4c2, + 0x1d4c3, + 0x1d4c5, + 0x1d505, + 0x1d507, + 0x1d50a, + 0x1d50d, + 0x1d514, + 0x1d516, + 0x1d51c, + 0x1d51e, + 0x1d539, + 0x1d53b, + 0x1d53e, + 0x1d540, + 0x1d544, + 0x1d546, + 0x1d546, + 0x1d54a, + 0x1d550, + 0x1d552, + 0x1d6a3, + 0x1d6a8, + 0x1d7c9, + 0x20000, + 0x2a6d6, + 0x2f800, + 0x2fa1d, + 0xf0000, + 0xffffd, + 0x100000, + 0x10fffd + ]; + /* eslint-enable */ + + const isBidirectionalL = character => inRange(character, bidirectional_l); + + // 2.1. Mapping + + /** + * non-ASCII space characters [StringPrep, C.1.2] that can be + * mapped to SPACE (U+0020) + */ + const mapping2space = isNonASCIISpaceCharacter; + + /** + * the "commonly mapped to nothing" characters [StringPrep, B.1] + * that can be mapped to nothing. + */ + const mapping2nothing = isCommonlyMappedToNothing; + + // utils + const getCodePoint = character => character.codePointAt(0); + const first = x => x[0]; + const last = x => x[x.length - 1]; + + /** + * Convert provided string into an array of Unicode Code Points. + * Based on https://stackoverflow.com/a/21409165/1556249 + * and https://www.npmjs.com/package/code-point-at. + * @param {string} input + * @returns {number[]} + */ + function toCodePoints(input) { + const codepoints = []; + const size = input.length; + + for (let i = 0; i < size; i += 1) { + const before = input.charCodeAt(i); + + if (before >= 0xd800 && before <= 0xdbff && size > i + 1) { + const next = input.charCodeAt(i + 1); + + if (next >= 0xdc00 && next <= 0xdfff) { + codepoints.push((before - 0xd800) * 0x400 + next - 0xdc00 + 0x10000); + i += 1; + continue; + } + } + + codepoints.push(before); + } + + return codepoints; + } + + /** + * SASLprep. + * @param {string} input + * @param {Object} opts + * @param {boolean} opts.allowUnassigned + * @returns {string} + */ + function saslprep(input, opts = {}) { + if (typeof input !== 'string') { + throw new TypeError('Expected string.'); + } + + if (input.length === 0) { + return ''; + } + + // 1. Map + const mapped_input = toCodePoints(input) + // 1.1 mapping to space + .map(character => (mapping2space(character) ? 0x20 : character)) + // 1.2 mapping to nothing + .filter(character => !mapping2nothing(character)); + + // 2. Normalize + const normalized_input = String.fromCodePoint + .apply(null, mapped_input) + .normalize('NFKC'); + + const normalized_map = toCodePoints(normalized_input); + + // 3. Prohibit + const hasProhibited = normalized_map.some(isProhibitedCharacter); + + if (hasProhibited) { + throw new Error( + 'Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3' + ); + } + + // Unassigned Code Points + if (opts.allowUnassigned !== true) { + const hasUnassigned = normalized_map.some(isUnassignedCodePoint); + + if (hasUnassigned) { + throw new Error( + 'Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5' + ); + } + } + + // 4. check bidi + + const hasBidiRAL = normalized_map.some(isBidirectionalRAL); + + const hasBidiL = normalized_map.some(isBidirectionalL); + + // 4.1 If a string contains any RandALCat character, the string MUST NOT + // contain any LCat character. + if (hasBidiRAL && hasBidiL) { + throw new Error( + 'String must not contain RandALCat and LCat at the same time,' + + ' see https://tools.ietf.org/html/rfc3454#section-6' + ); + } + + /** + * 4.2 If a string contains any RandALCat character, a RandALCat + * character MUST be the first character of the string, and a + * RandALCat character MUST be the last character of the string. + */ + + const isFirstBidiRAL = isBidirectionalRAL( + getCodePoint(first(normalized_input)) + ); + const isLastBidiRAL = isBidirectionalRAL( + getCodePoint(last(normalized_input)) + ); + + if (hasBidiRAL && !(isFirstBidiRAL && isLastBidiRAL)) { + throw new Error( + 'Bidirectional RandALCat character must be the first and the last' + + ' character of the string, see https://tools.ietf.org/html/rfc3454#section-6' + ); + } + + return normalized_input; + } + + class PDFSecurity { + static generateFileID(info = {}) { + let infoStr = `${info.CreationDate.getTime()}\n`; + + for (let key in info) { + if (!info.hasOwnProperty(key)) { + continue; + } + infoStr += `${key}: ${info[key]}\n`; + } + + return wordArrayToBuffer(cryptoJs.MD5(infoStr)); + } + + static generateRandomWordArray(bytes) { + return cryptoJs.lib.WordArray.random(bytes); + } + + static create(document, options = {}) { + if (!options.ownerPassword && !options.userPassword) { + return null; + } + return new PDFSecurity(document, options); + } + + constructor(document, options = {}) { + if (!options.ownerPassword && !options.userPassword) { + throw new Error('None of owner password and user password is defined.'); + } + + this.document = document; + this._setupEncryption(options); + } + + _setupEncryption(options) { + switch (options.pdfVersion) { + case '1.4': + case '1.5': + this.version = 2; + break; + case '1.6': + case '1.7': + this.version = 4; + break; + case '1.7ext3': + this.version = 5; + break; + default: + this.version = 1; + break; + } + + const encDict = { + Filter: 'Standard' + }; + + switch (this.version) { + case 1: + case 2: + case 4: + this._setupEncryptionV1V2V4(this.version, encDict, options); + break; + case 5: + this._setupEncryptionV5(encDict, options); + break; + } + + this.dictionary = this.document.ref(encDict); + } + + _setupEncryptionV1V2V4(v, encDict, options) { + let r, permissions; + switch (v) { + case 1: + r = 2; + this.keyBits = 40; + permissions = getPermissionsR2(options.permissions); + break; + case 2: + r = 3; + this.keyBits = 128; + permissions = getPermissionsR3(options.permissions); + break; + case 4: + r = 4; + this.keyBits = 128; + permissions = getPermissionsR3(options.permissions); + break; + } + + const paddedUserPassword = processPasswordR2R3R4(options.userPassword); + const paddedOwnerPassword = options.ownerPassword + ? processPasswordR2R3R4(options.ownerPassword) + : paddedUserPassword; + + const ownerPasswordEntry = getOwnerPasswordR2R3R4( + r, + this.keyBits, + paddedUserPassword, + paddedOwnerPassword + ); + this.encryptionKey = getEncryptionKeyR2R3R4( + r, + this.keyBits, + this.document._id, + paddedUserPassword, + ownerPasswordEntry, + permissions + ); + let userPasswordEntry; + if (r === 2) { + userPasswordEntry = getUserPasswordR2(this.encryptionKey); + } else { + userPasswordEntry = getUserPasswordR3R4( + this.document._id, + this.encryptionKey + ); + } + + encDict.V = v; + if (v >= 2) { + encDict.Length = this.keyBits; + } + if (v === 4) { + encDict.CF = { + StdCF: { + AuthEvent: 'DocOpen', + CFM: 'AESV2', + Length: this.keyBits / 8 + } + }; + encDict.StmF = 'StdCF'; + encDict.StrF = 'StdCF'; + } + encDict.R = r; + encDict.O = wordArrayToBuffer(ownerPasswordEntry); + encDict.U = wordArrayToBuffer(userPasswordEntry); + encDict.P = permissions; + } + + _setupEncryptionV5(encDict, options) { + this.keyBits = 256; + const permissions = getPermissionsR3(options); + + const processedUserPassword = processPasswordR5(options.userPassword); + const processedOwnerPassword = options.ownerPassword + ? processPasswordR5(options.ownerPassword) + : processedUserPassword; + + this.encryptionKey = getEncryptionKeyR5( + PDFSecurity.generateRandomWordArray + ); + const userPasswordEntry = getUserPasswordR5( + processedUserPassword, + PDFSecurity.generateRandomWordArray + ); + const userKeySalt = cryptoJs.lib.WordArray.create( + userPasswordEntry.words.slice(10, 12), + 8 + ); + const userEncryptionKeyEntry = getUserEncryptionKeyR5( + processedUserPassword, + userKeySalt, + this.encryptionKey + ); + const ownerPasswordEntry = getOwnerPasswordR5( + processedOwnerPassword, + userPasswordEntry, + PDFSecurity.generateRandomWordArray + ); + const ownerKeySalt = cryptoJs.lib.WordArray.create( + ownerPasswordEntry.words.slice(10, 12), + 8 + ); + const ownerEncryptionKeyEntry = getOwnerEncryptionKeyR5( + processedOwnerPassword, + ownerKeySalt, + userPasswordEntry, + this.encryptionKey + ); + const permsEntry = getEncryptedPermissionsR5( + permissions, + this.encryptionKey, + PDFSecurity.generateRandomWordArray + ); + + encDict.V = 5; + encDict.Length = this.keyBits; + encDict.CF = { + StdCF: { + AuthEvent: 'DocOpen', + CFM: 'AESV3', + Length: this.keyBits / 8 + } + }; + encDict.StmF = 'StdCF'; + encDict.StrF = 'StdCF'; + encDict.R = 5; + encDict.O = wordArrayToBuffer(ownerPasswordEntry); + encDict.OE = wordArrayToBuffer(ownerEncryptionKeyEntry); + encDict.U = wordArrayToBuffer(userPasswordEntry); + encDict.UE = wordArrayToBuffer(userEncryptionKeyEntry); + encDict.P = permissions; + encDict.Perms = wordArrayToBuffer(permsEntry); + } + + getEncryptFn(obj, gen) { + let digest; + if (this.version < 5) { + digest = this.encryptionKey + .clone() + .concat( + cryptoJs.lib.WordArray.create( + [ + ((obj & 0xff) << 24) | + ((obj & 0xff00) << 8) | + ((obj >> 8) & 0xff00) | + (gen & 0xff), + (gen & 0xff00) << 16 + ], + 5 + ) + ); + } + + if (this.version === 1 || this.version === 2) { + let key = cryptoJs.MD5(digest); + key.sigBytes = Math.min(16, this.keyBits / 8 + 5); + return buffer => + wordArrayToBuffer( + cryptoJs.RC4.encrypt(cryptoJs.lib.WordArray.create(buffer), key) + .ciphertext + ); + } + + let key; + if (this.version === 4) { + key = cryptoJs.MD5( + digest.concat(cryptoJs.lib.WordArray.create([0x73416c54], 4)) + ); + } else { + key = this.encryptionKey; + } + + const iv = PDFSecurity.generateRandomWordArray(16); + const options = { + mode: cryptoJs.mode.CBC, + padding: cryptoJs.pad.Pkcs7, + iv + }; + + return buffer => + wordArrayToBuffer( + iv + .clone() + .concat( + cryptoJs.AES.encrypt( + cryptoJs.lib.WordArray.create(buffer), + key, + options + ).ciphertext + ) + ); + } + + end() { + this.dictionary.end(); + } + } + + function getPermissionsR2(permissionObject = {}) { + let permissions = 0xffffffc0 >> 0; + if (permissionObject.printing) { + permissions |= 0b000000000100; + } + if (permissionObject.modifying) { + permissions |= 0b000000001000; + } + if (permissionObject.copying) { + permissions |= 0b000000010000; + } + if (permissionObject.annotating) { + permissions |= 0b000000100000; + } + return permissions; + } + + function getPermissionsR3(permissionObject = {}) { + let permissions = 0xfffff0c0 >> 0; + if (permissionObject.printing === 'lowResolution') { + permissions |= 0b000000000100; + } + if (permissionObject.printing === 'highResolution') { + permissions |= 0b100000000100; + } + if (permissionObject.modifying) { + permissions |= 0b000000001000; + } + if (permissionObject.copying) { + permissions |= 0b000000010000; + } + if (permissionObject.annotating) { + permissions |= 0b000000100000; + } + if (permissionObject.fillingForms) { + permissions |= 0b000100000000; + } + if (permissionObject.contentAccessibility) { + permissions |= 0b001000000000; + } + if (permissionObject.documentAssembly) { + permissions |= 0b010000000000; + } + return permissions; + } + + function getUserPasswordR2(encryptionKey) { + return cryptoJs.RC4.encrypt(processPasswordR2R3R4(), encryptionKey) + .ciphertext; + } + + function getUserPasswordR3R4(documentId, encryptionKey) { + const key = encryptionKey.clone(); + let cipher = cryptoJs.MD5( + processPasswordR2R3R4().concat(cryptoJs.lib.WordArray.create(documentId)) + ); + for (let i = 0; i < 20; i++) { + const xorRound = Math.ceil(key.sigBytes / 4); + for (let j = 0; j < xorRound; j++) { + key.words[j] = + encryptionKey.words[j] ^ (i | (i << 8) | (i << 16) | (i << 24)); + } + cipher = cryptoJs.RC4.encrypt(cipher, key).ciphertext; + } + return cipher.concat(cryptoJs.lib.WordArray.create(null, 16)); + } + + function getOwnerPasswordR2R3R4( + r, + keyBits, + paddedUserPassword, + paddedOwnerPassword + ) { + let digest = paddedOwnerPassword; + let round = r >= 3 ? 51 : 1; + for (let i = 0; i < round; i++) { + digest = cryptoJs.MD5(digest); + } + + const key = digest.clone(); + key.sigBytes = keyBits / 8; + let cipher = paddedUserPassword; + round = r >= 3 ? 20 : 1; + for (let i = 0; i < round; i++) { + const xorRound = Math.ceil(key.sigBytes / 4); + for (let j = 0; j < xorRound; j++) { + key.words[j] = digest.words[j] ^ (i | (i << 8) | (i << 16) | (i << 24)); + } + cipher = cryptoJs.RC4.encrypt(cipher, key).ciphertext; + } + return cipher; + } + + function getEncryptionKeyR2R3R4( + r, + keyBits, + documentId, + paddedUserPassword, + ownerPasswordEntry, + permissions + ) { + let key = paddedUserPassword + .clone() + .concat(ownerPasswordEntry) + .concat(cryptoJs.lib.WordArray.create([lsbFirstWord(permissions)], 4)) + .concat(cryptoJs.lib.WordArray.create(documentId)); + const round = r >= 3 ? 51 : 1; + for (let i = 0; i < round; i++) { + key = cryptoJs.MD5(key); + key.sigBytes = keyBits / 8; + } + return key; + } + + function getUserPasswordR5(processedUserPassword, generateRandomWordArray) { + const validationSalt = generateRandomWordArray(8); + const keySalt = generateRandomWordArray(8); + return cryptoJs.SHA256(processedUserPassword.clone().concat(validationSalt)) + .concat(validationSalt) + .concat(keySalt); + } + + function getUserEncryptionKeyR5( + processedUserPassword, + userKeySalt, + encryptionKey + ) { + const key = cryptoJs.SHA256( + processedUserPassword.clone().concat(userKeySalt) + ); + const options = { + mode: cryptoJs.mode.CBC, + padding: cryptoJs.pad.NoPadding, + iv: cryptoJs.lib.WordArray.create(null, 16) + }; + return cryptoJs.AES.encrypt(encryptionKey, key, options).ciphertext; + } + + function getOwnerPasswordR5( + processedOwnerPassword, + userPasswordEntry, + generateRandomWordArray + ) { + const validationSalt = generateRandomWordArray(8); + const keySalt = generateRandomWordArray(8); + return cryptoJs.SHA256( + processedOwnerPassword + .clone() + .concat(validationSalt) + .concat(userPasswordEntry) + ) + .concat(validationSalt) + .concat(keySalt); + } + + function getOwnerEncryptionKeyR5( + processedOwnerPassword, + ownerKeySalt, + userPasswordEntry, + encryptionKey + ) { + const key = cryptoJs.SHA256( + processedOwnerPassword + .clone() + .concat(ownerKeySalt) + .concat(userPasswordEntry) + ); + const options = { + mode: cryptoJs.mode.CBC, + padding: cryptoJs.pad.NoPadding, + iv: cryptoJs.lib.WordArray.create(null, 16) + }; + return cryptoJs.AES.encrypt(encryptionKey, key, options).ciphertext; + } + + function getEncryptionKeyR5(generateRandomWordArray) { + return generateRandomWordArray(32); + } + + function getEncryptedPermissionsR5( + permissions, + encryptionKey, + generateRandomWordArray + ) { + const cipher = cryptoJs.lib.WordArray.create( + [lsbFirstWord(permissions), 0xffffffff, 0x54616462], + 12 + ).concat(generateRandomWordArray(4)); + const options = { + mode: cryptoJs.mode.ECB, + padding: cryptoJs.pad.NoPadding + }; + return cryptoJs.AES.encrypt(cipher, encryptionKey, options).ciphertext; + } + + function processPasswordR2R3R4(password = '') { + const out = new Buffer(32); + const length = password.length; + let index = 0; + while (index < length && index < 32) { + const code = password.charCodeAt(index); + if (code > 0xff) { + throw new Error('Password contains one or more invalid characters.'); + } + out[index] = code; + index++; + } + while (index < 32) { + out[index] = PASSWORD_PADDING[index - length]; + index++; + } + return cryptoJs.lib.WordArray.create(out); + } + + function processPasswordR5(password = '') { + password = unescape(encodeURIComponent(saslprep(password))); + const length = Math.min(127, password.length); + const out = new Buffer(length); + + for (let i = 0; i < length; i++) { + out[i] = password.charCodeAt(i); + } + + return cryptoJs.lib.WordArray.create(out); + } + + function lsbFirstWord(data) { + return ( + ((data & 0xff) << 24) | + ((data & 0xff00) << 8) | + ((data >> 8) & 0xff00) | + ((data >> 24) & 0xff) + ); + } + + function wordArrayToBuffer(wordArray) { + const byteArray = []; + for (let i = 0; i < wordArray.sigBytes; i++) { + byteArray.push( + (wordArray.words[Math.floor(i / 4)] >> (8 * (3 - (i % 4)))) & 0xff + ); + } + return Buffer.from(byteArray); + } + + const PASSWORD_PADDING = [ + 0x28, + 0xbf, + 0x4e, + 0x5e, + 0x4e, + 0x75, + 0x8a, + 0x41, + 0x64, + 0x00, + 0x4e, + 0x56, + 0xff, + 0xfa, + 0x01, + 0x08, + 0x2e, + 0x2e, + 0x00, + 0xb6, + 0xd0, + 0x68, + 0x3e, + 0x80, + 0x2f, + 0x0c, + 0xa9, + 0xfe, + 0x64, + 0x53, + 0x69, + 0x7a + ]; + + const { number } = PDFObject; + + class PDFGradient { + constructor(doc) { + this.doc = doc; + this.stops = []; + this.embedded = false; + this.transform = [1, 0, 0, 1, 0, 0]; + } + + stop(pos, color, opacity) { + if (opacity == null) { + opacity = 1; + } + color = this.doc._normalizeColor(color); + + if (this.stops.length === 0) { + if (color.length === 3) { + this._colorSpace = 'DeviceRGB'; + } else if (color.length === 4) { + this._colorSpace = 'DeviceCMYK'; + } else if (color.length === 1) { + this._colorSpace = 'DeviceGray'; + } else { + throw new Error('Unknown color space'); + } + } else if ( + (this._colorSpace === 'DeviceRGB' && color.length !== 3) || + (this._colorSpace === 'DeviceCMYK' && color.length !== 4) || + (this._colorSpace === 'DeviceGray' && color.length !== 1) + ) { + throw new Error('All gradient stops must use the same color space'); + } + + opacity = Math.max(0, Math.min(1, opacity)); + this.stops.push([pos, color, opacity]); + return this; + } + + setTransform(m11, m12, m21, m22, dx, dy) { + this.transform = [m11, m12, m21, m22, dx, dy]; + return this; + } + + embed(m) { + let fn; + const stopsLength = this.stops.length; + if (stopsLength === 0) { + return; + } + this.embedded = true; + this.matrix = m; + + // if the last stop comes before 100%, add a copy at 100% + const last = this.stops[stopsLength - 1]; + if (last[0] < 1) { + this.stops.push([1, last[1], last[2]]); + } + + const bounds = []; + const encode = []; + const stops = []; + + for (let i = 0; i < stopsLength - 1; i++) { + encode.push(0, 1); + if (i + 2 !== stopsLength) { + bounds.push(this.stops[i + 1][0]); + } + + fn = this.doc.ref({ + FunctionType: 2, + Domain: [0, 1], + C0: this.stops[i + 0][1], + C1: this.stops[i + 1][1], + N: 1 + }); + + stops.push(fn); + fn.end(); + } + + // if there are only two stops, we don't need a stitching function + if (stopsLength === 1) { + fn = stops[0]; + } else { + fn = this.doc.ref({ + FunctionType: 3, // stitching function + Domain: [0, 1], + Functions: stops, + Bounds: bounds, + Encode: encode + }); + + fn.end(); + } + + this.id = `Sh${++this.doc._gradCount}`; + + const shader = this.shader(fn); + shader.end(); + + const pattern = this.doc.ref({ + Type: 'Pattern', + PatternType: 2, + Shading: shader, + Matrix: this.matrix.map(number) + }); + + pattern.end(); + + if (this.stops.some(stop => stop[2] < 1)) { + let grad = this.opacityGradient(); + grad._colorSpace = 'DeviceGray'; + + for (let stop of this.stops) { + grad.stop(stop[0], [stop[2]]); + } + + grad = grad.embed(this.matrix); + + const pageBBox = [0, 0, this.doc.page.width, this.doc.page.height]; + + const form = this.doc.ref({ + Type: 'XObject', + Subtype: 'Form', + FormType: 1, + BBox: pageBBox, + Group: { + Type: 'Group', + S: 'Transparency', + CS: 'DeviceGray' + }, + Resources: { + ProcSet: ['PDF', 'Text', 'ImageB', 'ImageC', 'ImageI'], + Pattern: { + Sh1: grad + } + } + }); + + form.write('/Pattern cs /Sh1 scn'); + form.end(`${pageBBox.join(' ')} re f`); + + const gstate = this.doc.ref({ + Type: 'ExtGState', + SMask: { + Type: 'Mask', + S: 'Luminosity', + G: form + } + }); + + gstate.end(); + + const opacityPattern = this.doc.ref({ + Type: 'Pattern', + PatternType: 1, + PaintType: 1, + TilingType: 2, + BBox: pageBBox, + XStep: pageBBox[2], + YStep: pageBBox[3], + Resources: { + ProcSet: ['PDF', 'Text', 'ImageB', 'ImageC', 'ImageI'], + Pattern: { + Sh1: pattern + }, + ExtGState: { + Gs1: gstate + } + } + }); + + opacityPattern.write('/Gs1 gs /Pattern cs /Sh1 scn'); + opacityPattern.end(`${pageBBox.join(' ')} re f`); + + this.doc.page.patterns[this.id] = opacityPattern; + } else { + this.doc.page.patterns[this.id] = pattern; + } + + return pattern; + } + + apply(op) { + // apply gradient transform to existing document ctm + const [m0, m1, m2, m3, m4, m5] = this.doc._ctm; + const [m11, m12, m21, m22, dx, dy] = this.transform; + const m = [ + m0 * m11 + m2 * m12, + m1 * m11 + m3 * m12, + m0 * m21 + m2 * m22, + m1 * m21 + m3 * m22, + m0 * dx + m2 * dy + m4, + m1 * dx + m3 * dy + m5 + ]; + + if (!this.embedded || m.join(' ') !== this.matrix.join(' ')) { + this.embed(m); + } + return this.doc.addContent(`/${this.id} ${op}`); + } + } + + class PDFLinearGradient extends PDFGradient { + constructor(doc, x1, y1, x2, y2) { + super(doc); + this.x1 = x1; + this.y1 = y1; + this.x2 = x2; + this.y2 = y2; + } + + shader(fn) { + return this.doc.ref({ + ShadingType: 2, + ColorSpace: this._colorSpace, + Coords: [this.x1, this.y1, this.x2, this.y2], + Function: fn, + Extend: [true, true] + }); + } + + opacityGradient() { + return new PDFLinearGradient(this.doc, this.x1, this.y1, this.x2, this.y2); + } + } + + class PDFRadialGradient extends PDFGradient { + constructor(doc, x1, y1, r1, x2, y2, r2) { + super(doc); + this.doc = doc; + this.x1 = x1; + this.y1 = y1; + this.r1 = r1; + this.x2 = x2; + this.y2 = y2; + this.r2 = r2; + } + + shader(fn) { + return this.doc.ref({ + ShadingType: 3, + ColorSpace: this._colorSpace, + Coords: [this.x1, this.y1, this.r1, this.x2, this.y2, this.r2], + Function: fn, + Extend: [true, true] + }); + } + + opacityGradient() { + return new PDFRadialGradient( + this.doc, + this.x1, + this.y1, + this.r1, + this.x2, + this.y2, + this.r2 + ); + } + } + var Gradient = { PDFGradient, PDFLinearGradient, PDFRadialGradient }; - const { PDFGradient: PDFGradient$1, PDFLinearGradient: PDFLinearGradient$1, PDFRadialGradient: PDFRadialGradient$1 } = Gradient; - - var ColorMixin = { - initColor() { - // The opacity dictionaries - this._opacityRegistry = {}; - this._opacityCount = 0; - return (this._gradCount = 0); - }, - - _normalizeColor(color) { - if (color instanceof PDFGradient$1) { - return color; - } - - if (typeof color === 'string') { - if (color.charAt(0) === '#') { - if (color.length === 4) { - color = color.replace( - /#([0-9A-F])([0-9A-F])([0-9A-F])/i, - '#$1$1$2$2$3$3' - ); - } - const hex = parseInt(color.slice(1), 16); - color = [hex >> 16, (hex >> 8) & 0xff, hex & 0xff]; - } else if (namedColors[color]) { - color = namedColors[color]; - } - } - - if (Array.isArray(color)) { - // RGB - if (color.length === 3) { - color = color.map(part => part / 255); - // CMYK - } else if (color.length === 4) { - color = color.map(part => part / 100); - } - return color; - } - - return null; - }, - - _setColor(color, stroke) { - color = this._normalizeColor(color); - if (!color) { - return false; - } - - const op = stroke ? 'SCN' : 'scn'; - - if (color instanceof PDFGradient$1) { - this._setColorSpace('Pattern', stroke); - color.apply(op); - } else { - const space = color.length === 4 ? 'DeviceCMYK' : 'DeviceRGB'; - this._setColorSpace(space, stroke); - - color = color.join(' '); - this.addContent(`${color} ${op}`); - } - - return true; - }, - - _setColorSpace(space, stroke) { - const op = stroke ? 'CS' : 'cs'; - return this.addContent(`/${space} ${op}`); - }, - - fillColor(color, opacity) { - const set = this._setColor(color, false); - if (set) { - this.fillOpacity(opacity); - } - - // save this for text wrapper, which needs to reset - // the fill color on new pages - this._fillColor = [color, opacity]; - return this; - }, - - strokeColor(color, opacity) { - const set = this._setColor(color, true); - if (set) { - this.strokeOpacity(opacity); - } - return this; - }, - - opacity(opacity) { - this._doOpacity(opacity, opacity); - return this; - }, - - fillOpacity(opacity) { - this._doOpacity(opacity, null); - return this; - }, - - strokeOpacity(opacity) { - this._doOpacity(null, opacity); - return this; - }, - - _doOpacity(fillOpacity, strokeOpacity) { - let dictionary, name; - if (fillOpacity == null && strokeOpacity == null) { - return; - } - - if (fillOpacity != null) { - fillOpacity = Math.max(0, Math.min(1, fillOpacity)); - } - if (strokeOpacity != null) { - strokeOpacity = Math.max(0, Math.min(1, strokeOpacity)); - } - const key = `${fillOpacity}_${strokeOpacity}`; - - if (this._opacityRegistry[key]) { - [dictionary, name] = this._opacityRegistry[key]; - } else { - dictionary = { Type: 'ExtGState' }; - - if (fillOpacity != null) { - dictionary.ca = fillOpacity; - } - if (strokeOpacity != null) { - dictionary.CA = strokeOpacity; - } - - dictionary = this.ref(dictionary); - dictionary.end(); - const id = ++this._opacityCount; - name = `Gs${id}`; - this._opacityRegistry[key] = [dictionary, name]; - } - - this.page.ext_gstates[name] = dictionary; - return this.addContent(`/${name} gs`); - }, - - linearGradient(x1, y1, x2, y2) { - return new PDFLinearGradient$1(this, x1, y1, x2, y2); - }, - - radialGradient(x1, y1, r1, x2, y2, r2) { - return new PDFRadialGradient$1(this, x1, y1, r1, x2, y2, r2); - } - }; - - var namedColors = { - aliceblue: [240, 248, 255], - antiquewhite: [250, 235, 215], - aqua: [0, 255, 255], - aquamarine: [127, 255, 212], - azure: [240, 255, 255], - beige: [245, 245, 220], - bisque: [255, 228, 196], - black: [0, 0, 0], - blanchedalmond: [255, 235, 205], - blue: [0, 0, 255], - blueviolet: [138, 43, 226], - brown: [165, 42, 42], - burlywood: [222, 184, 135], - cadetblue: [95, 158, 160], - chartreuse: [127, 255, 0], - chocolate: [210, 105, 30], - coral: [255, 127, 80], - cornflowerblue: [100, 149, 237], - cornsilk: [255, 248, 220], - crimson: [220, 20, 60], - cyan: [0, 255, 255], - darkblue: [0, 0, 139], - darkcyan: [0, 139, 139], - darkgoldenrod: [184, 134, 11], - darkgray: [169, 169, 169], - darkgreen: [0, 100, 0], - darkgrey: [169, 169, 169], - darkkhaki: [189, 183, 107], - darkmagenta: [139, 0, 139], - darkolivegreen: [85, 107, 47], - darkorange: [255, 140, 0], - darkorchid: [153, 50, 204], - darkred: [139, 0, 0], - darksalmon: [233, 150, 122], - darkseagreen: [143, 188, 143], - darkslateblue: [72, 61, 139], - darkslategray: [47, 79, 79], - darkslategrey: [47, 79, 79], - darkturquoise: [0, 206, 209], - darkviolet: [148, 0, 211], - deeppink: [255, 20, 147], - deepskyblue: [0, 191, 255], - dimgray: [105, 105, 105], - dimgrey: [105, 105, 105], - dodgerblue: [30, 144, 255], - firebrick: [178, 34, 34], - floralwhite: [255, 250, 240], - forestgreen: [34, 139, 34], - fuchsia: [255, 0, 255], - gainsboro: [220, 220, 220], - ghostwhite: [248, 248, 255], - gold: [255, 215, 0], - goldenrod: [218, 165, 32], - gray: [128, 128, 128], - grey: [128, 128, 128], - green: [0, 128, 0], - greenyellow: [173, 255, 47], - honeydew: [240, 255, 240], - hotpink: [255, 105, 180], - indianred: [205, 92, 92], - indigo: [75, 0, 130], - ivory: [255, 255, 240], - khaki: [240, 230, 140], - lavender: [230, 230, 250], - lavenderblush: [255, 240, 245], - lawngreen: [124, 252, 0], - lemonchiffon: [255, 250, 205], - lightblue: [173, 216, 230], - lightcoral: [240, 128, 128], - lightcyan: [224, 255, 255], - lightgoldenrodyellow: [250, 250, 210], - lightgray: [211, 211, 211], - lightgreen: [144, 238, 144], - lightgrey: [211, 211, 211], - lightpink: [255, 182, 193], - lightsalmon: [255, 160, 122], - lightseagreen: [32, 178, 170], - lightskyblue: [135, 206, 250], - lightslategray: [119, 136, 153], - lightslategrey: [119, 136, 153], - lightsteelblue: [176, 196, 222], - lightyellow: [255, 255, 224], - lime: [0, 255, 0], - limegreen: [50, 205, 50], - linen: [250, 240, 230], - magenta: [255, 0, 255], - maroon: [128, 0, 0], - mediumaquamarine: [102, 205, 170], - mediumblue: [0, 0, 205], - mediumorchid: [186, 85, 211], - mediumpurple: [147, 112, 219], - mediumseagreen: [60, 179, 113], - mediumslateblue: [123, 104, 238], - mediumspringgreen: [0, 250, 154], - mediumturquoise: [72, 209, 204], - mediumvioletred: [199, 21, 133], - midnightblue: [25, 25, 112], - mintcream: [245, 255, 250], - mistyrose: [255, 228, 225], - moccasin: [255, 228, 181], - navajowhite: [255, 222, 173], - navy: [0, 0, 128], - oldlace: [253, 245, 230], - olive: [128, 128, 0], - olivedrab: [107, 142, 35], - orange: [255, 165, 0], - orangered: [255, 69, 0], - orchid: [218, 112, 214], - palegoldenrod: [238, 232, 170], - palegreen: [152, 251, 152], - paleturquoise: [175, 238, 238], - palevioletred: [219, 112, 147], - papayawhip: [255, 239, 213], - peachpuff: [255, 218, 185], - peru: [205, 133, 63], - pink: [255, 192, 203], - plum: [221, 160, 221], - powderblue: [176, 224, 230], - purple: [128, 0, 128], - red: [255, 0, 0], - rosybrown: [188, 143, 143], - royalblue: [65, 105, 225], - saddlebrown: [139, 69, 19], - salmon: [250, 128, 114], - sandybrown: [244, 164, 96], - seagreen: [46, 139, 87], - seashell: [255, 245, 238], - sienna: [160, 82, 45], - silver: [192, 192, 192], - skyblue: [135, 206, 235], - slateblue: [106, 90, 205], - slategray: [112, 128, 144], - slategrey: [112, 128, 144], - snow: [255, 250, 250], - springgreen: [0, 255, 127], - steelblue: [70, 130, 180], - tan: [210, 180, 140], - teal: [0, 128, 128], - thistle: [216, 191, 216], - tomato: [255, 99, 71], - turquoise: [64, 224, 208], - violet: [238, 130, 238], - wheat: [245, 222, 179], - white: [255, 255, 255], - whitesmoke: [245, 245, 245], - yellow: [255, 255, 0], - yellowgreen: [154, 205, 50] - }; - - let cx, cy, px, py, sx, sy; - - cx = cy = px = py = sx = sy = 0; - - const parameters = { - A: 7, - a: 7, - C: 6, - c: 6, - H: 1, - h: 1, - L: 2, - l: 2, - M: 2, - m: 2, - Q: 4, - q: 4, - S: 4, - s: 4, - T: 2, - t: 2, - V: 1, - v: 1, - Z: 0, - z: 0 - }; - - const parse = function(path) { - let cmd; - const ret = []; - let args = []; - let curArg = ''; - let foundDecimal = false; - let params = 0; - - for (let c of path) { - if (parameters[c] != null) { - params = parameters[c]; - if (cmd) { - // save existing command - if (curArg.length > 0) { - args[args.length] = +curArg; - } - ret[ret.length] = { cmd, args }; - - args = []; - curArg = ''; - foundDecimal = false; - } - - cmd = c; - } else if ( - [' ', ','].includes(c) || - (c === '-' && curArg.length > 0 && curArg[curArg.length - 1] !== 'e') || - (c === '.' && foundDecimal) - ) { - if (curArg.length === 0) { - continue; - } - - if (args.length === params) { - // handle reused commands - ret[ret.length] = { cmd, args }; - args = [+curArg]; - - // handle assumed commands - if (cmd === 'M') { - cmd = 'L'; - } - if (cmd === 'm') { - cmd = 'l'; - } - } else { - args[args.length] = +curArg; - } - - foundDecimal = c === '.'; - - // fix for negative numbers or repeated decimals with no delimeter between commands - curArg = ['-', '.'].includes(c) ? c : ''; - } else { - curArg += c; - if (c === '.') { - foundDecimal = true; - } - } - } - - // add the last command - if (curArg.length > 0) { - if (args.length === params) { - // handle reused commands - ret[ret.length] = { cmd, args }; - args = [+curArg]; - - // handle assumed commands - if (cmd === 'M') { - cmd = 'L'; - } - if (cmd === 'm') { - cmd = 'l'; - } - } else { - args[args.length] = +curArg; - } - } - - ret[ret.length] = { cmd, args }; - - return ret; - }; - - const apply = function(commands, doc) { - // current point, control point, and subpath starting point - cx = cy = px = py = sx = sy = 0; - - // run the commands - for (let i = 0; i < commands.length; i++) { - const c = commands[i]; - if (typeof runners[c.cmd] === 'function') { - runners[c.cmd](doc, c.args); - } - } - }; - - const runners = { - M(doc, a) { - cx = a[0]; - cy = a[1]; - px = py = null; - sx = cx; - sy = cy; - return doc.moveTo(cx, cy); - }, - - m(doc, a) { - cx += a[0]; - cy += a[1]; - px = py = null; - sx = cx; - sy = cy; - return doc.moveTo(cx, cy); - }, - - C(doc, a) { - cx = a[4]; - cy = a[5]; - px = a[2]; - py = a[3]; - return doc.bezierCurveTo(...a); - }, - - c(doc, a) { - doc.bezierCurveTo( - a[0] + cx, - a[1] + cy, - a[2] + cx, - a[3] + cy, - a[4] + cx, - a[5] + cy - ); - px = cx + a[2]; - py = cy + a[3]; - cx += a[4]; - return (cy += a[5]); - }, - - S(doc, a) { - if (px === null) { - px = cx; - py = cy; - } - - doc.bezierCurveTo(cx - (px - cx), cy - (py - cy), a[0], a[1], a[2], a[3]); - px = a[0]; - py = a[1]; - cx = a[2]; - return (cy = a[3]); - }, - - s(doc, a) { - if (px === null) { - px = cx; - py = cy; - } - - doc.bezierCurveTo( - cx - (px - cx), - cy - (py - cy), - cx + a[0], - cy + a[1], - cx + a[2], - cy + a[3] - ); - px = cx + a[0]; - py = cy + a[1]; - cx += a[2]; - return (cy += a[3]); - }, - - Q(doc, a) { - px = a[0]; - py = a[1]; - cx = a[2]; - cy = a[3]; - return doc.quadraticCurveTo(a[0], a[1], cx, cy); - }, - - q(doc, a) { - doc.quadraticCurveTo(a[0] + cx, a[1] + cy, a[2] + cx, a[3] + cy); - px = cx + a[0]; - py = cy + a[1]; - cx += a[2]; - return (cy += a[3]); - }, - - T(doc, a) { - if (px === null) { - px = cx; - py = cy; - } else { - px = cx - (px - cx); - py = cy - (py - cy); - } - - doc.quadraticCurveTo(px, py, a[0], a[1]); - px = cx - (px - cx); - py = cy - (py - cy); - cx = a[0]; - return (cy = a[1]); - }, - - t(doc, a) { - if (px === null) { - px = cx; - py = cy; - } else { - px = cx - (px - cx); - py = cy - (py - cy); - } - - doc.quadraticCurveTo(px, py, cx + a[0], cy + a[1]); - cx += a[0]; - return (cy += a[1]); - }, - - A(doc, a) { - solveArc(doc, cx, cy, a); - cx = a[5]; - return (cy = a[6]); - }, - - a(doc, a) { - a[5] += cx; - a[6] += cy; - solveArc(doc, cx, cy, a); - cx = a[5]; - return (cy = a[6]); - }, - - L(doc, a) { - cx = a[0]; - cy = a[1]; - px = py = null; - return doc.lineTo(cx, cy); - }, - - l(doc, a) { - cx += a[0]; - cy += a[1]; - px = py = null; - return doc.lineTo(cx, cy); - }, - - H(doc, a) { - cx = a[0]; - px = py = null; - return doc.lineTo(cx, cy); - }, - - h(doc, a) { - cx += a[0]; - px = py = null; - return doc.lineTo(cx, cy); - }, - - V(doc, a) { - cy = a[0]; - px = py = null; - return doc.lineTo(cx, cy); - }, - - v(doc, a) { - cy += a[0]; - px = py = null; - return doc.lineTo(cx, cy); - }, - - Z(doc) { - doc.closePath(); - cx = sx; - return (cy = sy); - }, - - z(doc) { - doc.closePath(); - cx = sx; - return (cy = sy); - } - }; - - const solveArc = function(doc, x, y, coords) { - const [rx, ry, rot, large, sweep, ex, ey] = coords; - const segs = arcToSegments(ex, ey, rx, ry, large, sweep, rot, x, y); - - for (let seg of segs) { - const bez = segmentToBezier(...seg); - doc.bezierCurveTo(...bez); - } - }; - - // from Inkscape svgtopdf, thanks! - const arcToSegments = function(x, y, rx, ry, large, sweep, rotateX, ox, oy) { - const th = rotateX * (Math.PI / 180); - const sin_th = Math.sin(th); - const cos_th = Math.cos(th); - rx = Math.abs(rx); - ry = Math.abs(ry); - px = cos_th * (ox - x) * 0.5 + sin_th * (oy - y) * 0.5; - py = cos_th * (oy - y) * 0.5 - sin_th * (ox - x) * 0.5; - let pl = (px * px) / (rx * rx) + (py * py) / (ry * ry); - if (pl > 1) { - pl = Math.sqrt(pl); - rx *= pl; - ry *= pl; - } - - const a00 = cos_th / rx; - const a01 = sin_th / rx; - const a10 = -sin_th / ry; - const a11 = cos_th / ry; - const x0 = a00 * ox + a01 * oy; - const y0 = a10 * ox + a11 * oy; - const x1 = a00 * x + a01 * y; - const y1 = a10 * x + a11 * y; - - const d = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0); - let sfactor_sq = 1 / d - 0.25; - if (sfactor_sq < 0) { - sfactor_sq = 0; - } - let sfactor = Math.sqrt(sfactor_sq); - if (sweep === large) { - sfactor = -sfactor; - } - - const xc = 0.5 * (x0 + x1) - sfactor * (y1 - y0); - const yc = 0.5 * (y0 + y1) + sfactor * (x1 - x0); - - const th0 = Math.atan2(y0 - yc, x0 - xc); - const th1 = Math.atan2(y1 - yc, x1 - xc); - - let th_arc = th1 - th0; - if (th_arc < 0 && sweep === 1) { - th_arc += 2 * Math.PI; - } else if (th_arc > 0 && sweep === 0) { - th_arc -= 2 * Math.PI; - } - - const segments = Math.ceil(Math.abs(th_arc / (Math.PI * 0.5 + 0.001))); - const result = []; - - for (let i = 0; i < segments; i++) { - const th2 = th0 + (i * th_arc) / segments; - const th3 = th0 + ((i + 1) * th_arc) / segments; - result[i] = [xc, yc, th2, th3, rx, ry, sin_th, cos_th]; - } - - return result; - }; - - const segmentToBezier = function(cx, cy, th0, th1, rx, ry, sin_th, cos_th) { - const a00 = cos_th * rx; - const a01 = -sin_th * ry; - const a10 = sin_th * rx; - const a11 = cos_th * ry; - - const th_half = 0.5 * (th1 - th0); - const t = - ((8 / 3) * Math.sin(th_half * 0.5) * Math.sin(th_half * 0.5)) / - Math.sin(th_half); - const x1 = cx + Math.cos(th0) - t * Math.sin(th0); - const y1 = cy + Math.sin(th0) + t * Math.cos(th0); - const x3 = cx + Math.cos(th1); - const y3 = cy + Math.sin(th1); - const x2 = x3 + t * Math.sin(th1); - const y2 = y3 - t * Math.cos(th1); - - return [ - a00 * x1 + a01 * y1, - a10 * x1 + a11 * y1, - a00 * x2 + a01 * y2, - a10 * x2 + a11 * y2, - a00 * x3 + a01 * y3, - a10 * x3 + a11 * y3 - ]; - }; - - class SVGPath { - static apply(doc, path) { - const commands = parse(path); - apply(commands, doc); - } - } - - const { number: number$1 } = PDFObject; - - // This constant is used to approximate a symmetrical arc using a cubic - // Bezier curve. - const KAPPA = 4.0 * ((Math.sqrt(2) - 1.0) / 3.0); - var VectorMixin = { - initVector() { - this._ctm = [1, 0, 0, 1, 0, 0]; // current transformation matrix - return (this._ctmStack = []); - }, - - save() { - this._ctmStack.push(this._ctm.slice()); - // TODO: save/restore colorspace and styles so not setting it unnessesarily all the time? - return this.addContent('q'); - }, - - restore() { - this._ctm = this._ctmStack.pop() || [1, 0, 0, 1, 0, 0]; - return this.addContent('Q'); - }, - - closePath() { - return this.addContent('h'); - }, - - lineWidth(w) { - return this.addContent(`${number$1(w)} w`); - }, - - _CAP_STYLES: { - BUTT: 0, - ROUND: 1, - SQUARE: 2 - }, - - lineCap(c) { - if (typeof c === 'string') { - c = this._CAP_STYLES[c.toUpperCase()]; - } - return this.addContent(`${c} J`); - }, - - _JOIN_STYLES: { - MITER: 0, - ROUND: 1, - BEVEL: 2 - }, - - lineJoin(j) { - if (typeof j === 'string') { - j = this._JOIN_STYLES[j.toUpperCase()]; - } - return this.addContent(`${j} j`); - }, - - miterLimit(m) { - return this.addContent(`${number$1(m)} M`); - }, - - dash(length, options = {}) { - const originalLength = length; - if (!Array.isArray(length)) { - length = [length, options.space || length]; - } - - const valid = length.every(x => Number.isFinite(x) && x > 0); - if(!valid) { - throw new Error(`dash(${JSON.stringify(originalLength)}, ${JSON.stringify(options)}) invalid, lengths must be numeric and greater than zero`); - } - - length = length.map(number$1).join(' '); - return this.addContent(`[${length}] ${number$1(options.phase || 0)} d`); - }, - - undash() { - return this.addContent('[] 0 d'); - }, - - moveTo(x, y) { - return this.addContent(`${number$1(x)} ${number$1(y)} m`); - }, - - lineTo(x, y) { - return this.addContent(`${number$1(x)} ${number$1(y)} l`); - }, - - bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) { - return this.addContent( - `${number$1(cp1x)} ${number$1(cp1y)} ${number$1(cp2x)} ${number$1(cp2y)} ${number$1( - x - )} ${number$1(y)} c` - ); - }, - - quadraticCurveTo(cpx, cpy, x, y) { - return this.addContent( - `${number$1(cpx)} ${number$1(cpy)} ${number$1(x)} ${number$1(y)} v` - ); - }, - - rect(x, y, w, h) { - return this.addContent( - `${number$1(x)} ${number$1(y)} ${number$1(w)} ${number$1(h)} re` - ); - }, - - roundedRect(x, y, w, h, r) { - if (r == null) { - r = 0; - } - r = Math.min(r, 0.5 * w, 0.5 * h); - - // amount to inset control points from corners (see `ellipse`) - const c = r * (1.0 - KAPPA); - - this.moveTo(x + r, y); - this.lineTo(x + w - r, y); - this.bezierCurveTo(x + w - c, y, x + w, y + c, x + w, y + r); - this.lineTo(x + w, y + h - r); - this.bezierCurveTo(x + w, y + h - c, x + w - c, y + h, x + w - r, y + h); - this.lineTo(x + r, y + h); - this.bezierCurveTo(x + c, y + h, x, y + h - c, x, y + h - r); - this.lineTo(x, y + r); - this.bezierCurveTo(x, y + c, x + c, y, x + r, y); - return this.closePath(); - }, - - ellipse(x, y, r1, r2) { - // based on http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas/2173084#2173084 - if (r2 == null) { - r2 = r1; - } - x -= r1; - y -= r2; - const ox = r1 * KAPPA; - const oy = r2 * KAPPA; - const xe = x + r1 * 2; - const ye = y + r2 * 2; - const xm = x + r1; - const ym = y + r2; - - this.moveTo(x, ym); - this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); - this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); - this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); - this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); - return this.closePath(); - }, - - circle(x, y, radius) { - return this.ellipse(x, y, radius); - }, - - arc(x, y, radius, startAngle, endAngle, anticlockwise) { - if (anticlockwise == null) { - anticlockwise = false; - } - const TWO_PI = 2.0 * Math.PI; - const HALF_PI = 0.5 * Math.PI; - - let deltaAng = endAngle - startAngle; - - if (Math.abs(deltaAng) > TWO_PI) { - // draw only full circle if more than that is specified - deltaAng = TWO_PI; - } else if (deltaAng !== 0 && anticlockwise !== deltaAng < 0) { - // necessary to flip direction of rendering - const dir = anticlockwise ? -1 : 1; - deltaAng = dir * TWO_PI + deltaAng; - } - - const numSegs = Math.ceil(Math.abs(deltaAng) / HALF_PI); - const segAng = deltaAng / numSegs; - const handleLen = (segAng / HALF_PI) * KAPPA * radius; - let curAng = startAngle; - - // component distances between anchor point and control point - let deltaCx = -Math.sin(curAng) * handleLen; - let deltaCy = Math.cos(curAng) * handleLen; - - // anchor point - let ax = x + Math.cos(curAng) * radius; - let ay = y + Math.sin(curAng) * radius; - - // calculate and render segments - this.moveTo(ax, ay); - - for (let segIdx = 0; segIdx < numSegs; segIdx++) { - // starting control point - const cp1x = ax + deltaCx; - const cp1y = ay + deltaCy; - - // step angle - curAng += segAng; - - // next anchor point - ax = x + Math.cos(curAng) * radius; - ay = y + Math.sin(curAng) * radius; - - // next control point delta - deltaCx = -Math.sin(curAng) * handleLen; - deltaCy = Math.cos(curAng) * handleLen; - - // ending control point - const cp2x = ax - deltaCx; - const cp2y = ay - deltaCy; - - // render segment - this.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, ax, ay); - } - - return this; - }, - - polygon(...points) { - this.moveTo(...(points.shift() || [])); - for (let point of points) { - this.lineTo(...(point || [])); - } - return this.closePath(); - }, - - path(path) { - SVGPath.apply(this, path); - return this; - }, - - _windingRule(rule) { - if (/even-?odd/.test(rule)) { - return '*'; - } - - return ''; - }, - - fill(color, rule) { - if (/(even-?odd)|(non-?zero)/.test(color)) { - rule = color; - color = null; - } - - if (color) { - this.fillColor(color); - } - return this.addContent(`f${this._windingRule(rule)}`); - }, - - stroke(color) { - if (color) { - this.strokeColor(color); - } - return this.addContent('S'); - }, - - fillAndStroke(fillColor, strokeColor, rule) { - if (strokeColor == null) { - strokeColor = fillColor; - } - const isFillRule = /(even-?odd)|(non-?zero)/; - if (isFillRule.test(fillColor)) { - rule = fillColor; - fillColor = null; - } - - if (isFillRule.test(strokeColor)) { - rule = strokeColor; - strokeColor = fillColor; - } - - if (fillColor) { - this.fillColor(fillColor); - this.strokeColor(strokeColor); - } - - return this.addContent(`B${this._windingRule(rule)}`); - }, - - clip(rule) { - return this.addContent(`W${this._windingRule(rule)} n`); - }, - - transform(m11, m12, m21, m22, dx, dy) { - // keep track of the current transformation matrix - const m = this._ctm; - const [m0, m1, m2, m3, m4, m5] = m; - m[0] = m0 * m11 + m2 * m12; - m[1] = m1 * m11 + m3 * m12; - m[2] = m0 * m21 + m2 * m22; - m[3] = m1 * m21 + m3 * m22; - m[4] = m0 * dx + m2 * dy + m4; - m[5] = m1 * dx + m3 * dy + m5; - - const values = [m11, m12, m21, m22, dx, dy].map(v => number$1(v)).join(' '); - return this.addContent(`${values} cm`); - }, - - translate(x, y) { - return this.transform(1, 0, 0, 1, x, y); - }, - - rotate(angle, options = {}) { - let y; - const rad = (angle * Math.PI) / 180; - const cos = Math.cos(rad); - const sin = Math.sin(rad); - let x = (y = 0); - - if (options.origin != null) { - [x, y] = options.origin; - const x1 = x * cos - y * sin; - const y1 = x * sin + y * cos; - x -= x1; - y -= y1; - } - - return this.transform(cos, sin, -sin, cos, x, y); - }, - - scale(xFactor, yFactor, options = {}) { - let y; - if (yFactor == null) { - yFactor = xFactor; - } - if (typeof yFactor === 'object') { - options = yFactor; - yFactor = xFactor; - } - - let x = (y = 0); - if (options.origin != null) { - [x, y] = options.origin; - x -= xFactor * x; - y -= yFactor * y; - } - - return this.transform(xFactor, 0, 0, yFactor, x, y); - } - }; - - const MARKERS = [ - 0xffc0, - 0xffc1, - 0xffc2, - 0xffc3, - 0xffc5, - 0xffc6, - 0xffc7, - 0xffc8, - 0xffc9, - 0xffca, - 0xffcb, - 0xffcc, - 0xffcd, - 0xffce, - 0xffcf - ]; - - const COLOR_SPACE_MAP = { - 1: 'DeviceGray', - 3: 'DeviceRGB', - 4: 'DeviceCMYK' - }; - - class JPEG { - constructor(data, label) { - let marker; - this.data = data; - this.label = label; - if (this.data.readUInt16BE(0) !== 0xffd8) { - throw 'SOI not found in JPEG'; - } - - let pos = 2; - while (pos < this.data.length) { - marker = this.data.readUInt16BE(pos); - pos += 2; - if (MARKERS.includes(marker)) { - break; - } - pos += this.data.readUInt16BE(pos); - } - - if (!MARKERS.includes(marker)) { - throw 'Invalid JPEG.'; - } - pos += 2; - - this.bits = this.data[pos++]; - this.height = this.data.readUInt16BE(pos); - pos += 2; - - this.width = this.data.readUInt16BE(pos); - pos += 2; - - const channels = this.data[pos++]; - this.colorSpace = COLOR_SPACE_MAP[channels]; - - this.obj = null; - } - - embed(document) { - if (this.obj) { - return; - } - - this.obj = document.ref({ - Type: 'XObject', - Subtype: 'Image', - BitsPerComponent: this.bits, - Width: this.width, - Height: this.height, - ColorSpace: this.colorSpace, - Filter: 'DCTDecode' - }); - - // add extra decode params for CMYK images. By swapping the - // min and max values from the default, we invert the colors. See - // section 4.8.4 of the spec. - if (this.colorSpace === 'DeviceCMYK') { - this.obj.data['Decode'] = [1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0]; - } - - this.obj.end(this.data); - - // free memory - return (this.data = null); - } - } - - var fs$1 = {}; - - function assert$1 (a, msg) { - if (!a) { - throw new Error(msg); - } - } - var binding$1 = {}; - Object.keys(_binding).forEach(function (key) { - binding$1[key] = _binding[key]; - }); - // zlib doesn't provide these, so kludge them in following the same - // const naming scheme zlib uses. - binding$1.Z_MIN_WINDOWBITS = 8; - binding$1.Z_MAX_WINDOWBITS = 15; - binding$1.Z_DEFAULT_WINDOWBITS = 15; - - // fewer than 64 bytes per chunk is stupid. - // technically it could work with as few as 8, but even 64 bytes - // is absurdly low. Usually a MB or more is best. - binding$1.Z_MIN_CHUNK = 64; - binding$1.Z_MAX_CHUNK = Infinity; - binding$1.Z_DEFAULT_CHUNK = (16 * 1024); - - binding$1.Z_MIN_MEMLEVEL = 1; - binding$1.Z_MAX_MEMLEVEL = 9; - binding$1.Z_DEFAULT_MEMLEVEL = 8; - - binding$1.Z_MIN_LEVEL = -1; - binding$1.Z_MAX_LEVEL = 9; - binding$1.Z_DEFAULT_LEVEL = binding$1.Z_DEFAULT_COMPRESSION; - - - // translation table for return codes. - var codes$1 = { - Z_OK: binding$1.Z_OK, - Z_STREAM_END: binding$1.Z_STREAM_END, - Z_NEED_DICT: binding$1.Z_NEED_DICT, - Z_ERRNO: binding$1.Z_ERRNO, - Z_STREAM_ERROR: binding$1.Z_STREAM_ERROR, - Z_DATA_ERROR: binding$1.Z_DATA_ERROR, - Z_MEM_ERROR: binding$1.Z_MEM_ERROR, - Z_BUF_ERROR: binding$1.Z_BUF_ERROR, - Z_VERSION_ERROR: binding$1.Z_VERSION_ERROR - }; - - Object.keys(codes$1).forEach(function(k) { - codes$1[codes$1[k]] = k; - }); - - function createDeflate$1(o) { - return new Deflate$1(o); - } - - function createInflate$1(o) { - return new Inflate$1(o); - } - - function createDeflateRaw$1(o) { - return new DeflateRaw$1(o); - } - - function createInflateRaw$1(o) { - return new InflateRaw$1(o); - } - - function createGzip$1(o) { - return new Gzip$1(o); - } - - function createGunzip$1(o) { - return new Gunzip$1(o); - } - - function createUnzip$1(o) { - return new Unzip$1(o); - } - - - // Convenience methods. - // compress/decompress a string or buffer in one step. - function deflate$2(buffer, opts, callback) { - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - return zlibBuffer$1(new Deflate$1(opts), buffer, callback); - } - - function deflateSync$1(buffer, opts) { - return zlibBufferSync$1(new Deflate$1(opts), buffer); - } - - function gzip$1(buffer, opts, callback) { - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - return zlibBuffer$1(new Gzip$1(opts), buffer, callback); - } - - function gzipSync$1(buffer, opts) { - return zlibBufferSync$1(new Gzip$1(opts), buffer); - } - - function deflateRaw$1(buffer, opts, callback) { - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - return zlibBuffer$1(new DeflateRaw$1(opts), buffer, callback); - } - - function deflateRawSync$1(buffer, opts) { - return zlibBufferSync$1(new DeflateRaw$1(opts), buffer); - } - - function unzip$1(buffer, opts, callback) { - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - return zlibBuffer$1(new Unzip$1(opts), buffer, callback); - } - - function unzipSync$1(buffer, opts) { - return zlibBufferSync$1(new Unzip$1(opts), buffer); - } - - function inflate$2(buffer, opts, callback) { - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - return zlibBuffer$1(new Inflate$1(opts), buffer, callback); - } - - function inflateSync$1(buffer, opts) { - return zlibBufferSync$1(new Inflate$1(opts), buffer); - } - - function gunzip$1(buffer, opts, callback) { - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - return zlibBuffer$1(new Gunzip$1(opts), buffer, callback); - } - - function gunzipSync$1(buffer, opts) { - return zlibBufferSync$1(new Gunzip$1(opts), buffer); - } - - function inflateRaw$1(buffer, opts, callback) { - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - return zlibBuffer$1(new InflateRaw$1(opts), buffer, callback); - } - - function inflateRawSync$1(buffer, opts) { - return zlibBufferSync$1(new InflateRaw$1(opts), buffer); - } - - function zlibBuffer$1(engine, buffer, callback) { - var buffers = []; - var nread = 0; - - engine.on('error', onError); - engine.on('end', onEnd); - - engine.end(buffer); - flow(); - - function flow() { - var chunk; - while (null !== (chunk = engine.read())) { - buffers.push(chunk); - nread += chunk.length; - } - engine.once('readable', flow); - } - - function onError(err) { - engine.removeListener('end', onEnd); - engine.removeListener('readable', flow); - callback(err); - } - - function onEnd() { - var buf = Buffer.concat(buffers, nread); - buffers = []; - callback(null, buf); - engine.close(); - } - } - - function zlibBufferSync$1(engine, buffer) { - if (typeof buffer === 'string') - buffer = new Buffer(buffer); - if (!isBuffer(buffer)) - throw new TypeError('Not a string or buffer'); - - var flushFlag = binding$1.Z_FINISH; - - return engine._processChunk(buffer, flushFlag); - } - - // generic zlib - // minimal 2-byte header - function Deflate$1(opts) { - if (!(this instanceof Deflate$1)) return new Deflate$1(opts); - Zlib$2.call(this, opts, binding$1.DEFLATE); - } - - function Inflate$1(opts) { - if (!(this instanceof Inflate$1)) return new Inflate$1(opts); - Zlib$2.call(this, opts, binding$1.INFLATE); - } - - - - // gzip - bigger header, same deflate compression - function Gzip$1(opts) { - if (!(this instanceof Gzip$1)) return new Gzip$1(opts); - Zlib$2.call(this, opts, binding$1.GZIP); - } - - function Gunzip$1(opts) { - if (!(this instanceof Gunzip$1)) return new Gunzip$1(opts); - Zlib$2.call(this, opts, binding$1.GUNZIP); - } - - - - // raw - no header - function DeflateRaw$1(opts) { - if (!(this instanceof DeflateRaw$1)) return new DeflateRaw$1(opts); - Zlib$2.call(this, opts, binding$1.DEFLATERAW); - } - - function InflateRaw$1(opts) { - if (!(this instanceof InflateRaw$1)) return new InflateRaw$1(opts); - Zlib$2.call(this, opts, binding$1.INFLATERAW); - } - - - // auto-detect header. - function Unzip$1(opts) { - if (!(this instanceof Unzip$1)) return new Unzip$1(opts); - Zlib$2.call(this, opts, binding$1.UNZIP); - } - - - // the Zlib class they all inherit from - // This thing manages the queue of requests, and returns - // true or false if there is anything in the queue when - // you call the .write() method. - - function Zlib$2(opts, mode) { - this._opts = opts = opts || {}; - this._chunkSize = opts.chunkSize || binding$1.Z_DEFAULT_CHUNK; - - Transform.call(this, opts); - - if (opts.flush) { - if (opts.flush !== binding$1.Z_NO_FLUSH && - opts.flush !== binding$1.Z_PARTIAL_FLUSH && - opts.flush !== binding$1.Z_SYNC_FLUSH && - opts.flush !== binding$1.Z_FULL_FLUSH && - opts.flush !== binding$1.Z_FINISH && - opts.flush !== binding$1.Z_BLOCK) { - throw new Error('Invalid flush flag: ' + opts.flush); - } - } - this._flushFlag = opts.flush || binding$1.Z_NO_FLUSH; - - if (opts.chunkSize) { - if (opts.chunkSize < binding$1.Z_MIN_CHUNK || - opts.chunkSize > binding$1.Z_MAX_CHUNK) { - throw new Error('Invalid chunk size: ' + opts.chunkSize); - } - } - - if (opts.windowBits) { - if (opts.windowBits < binding$1.Z_MIN_WINDOWBITS || - opts.windowBits > binding$1.Z_MAX_WINDOWBITS) { - throw new Error('Invalid windowBits: ' + opts.windowBits); - } - } - - if (opts.level) { - if (opts.level < binding$1.Z_MIN_LEVEL || - opts.level > binding$1.Z_MAX_LEVEL) { - throw new Error('Invalid compression level: ' + opts.level); - } - } - - if (opts.memLevel) { - if (opts.memLevel < binding$1.Z_MIN_MEMLEVEL || - opts.memLevel > binding$1.Z_MAX_MEMLEVEL) { - throw new Error('Invalid memLevel: ' + opts.memLevel); - } - } - - if (opts.strategy) { - if (opts.strategy != binding$1.Z_FILTERED && - opts.strategy != binding$1.Z_HUFFMAN_ONLY && - opts.strategy != binding$1.Z_RLE && - opts.strategy != binding$1.Z_FIXED && - opts.strategy != binding$1.Z_DEFAULT_STRATEGY) { - throw new Error('Invalid strategy: ' + opts.strategy); - } - } - - if (opts.dictionary) { - if (!isBuffer(opts.dictionary)) { - throw new Error('Invalid dictionary: it should be a Buffer instance'); - } - } - - this._binding = new binding$1.Zlib(mode); - - var self = this; - this._hadError = false; - this._binding.onerror = function(message, errno) { - // there is no way to cleanly recover. - // continuing only obscures problems. - self._binding = null; - self._hadError = true; - - var error = new Error(message); - error.errno = errno; - error.code = binding$1.codes[errno]; - self.emit('error', error); - }; - - var level = binding$1.Z_DEFAULT_COMPRESSION; - if (typeof opts.level === 'number') level = opts.level; - - var strategy = binding$1.Z_DEFAULT_STRATEGY; - if (typeof opts.strategy === 'number') strategy = opts.strategy; - - this._binding.init(opts.windowBits || binding$1.Z_DEFAULT_WINDOWBITS, - level, - opts.memLevel || binding$1.Z_DEFAULT_MEMLEVEL, - strategy, - opts.dictionary); - - this._buffer = new Buffer(this._chunkSize); - this._offset = 0; - this._closed = false; - this._level = level; - this._strategy = strategy; - - this.once('end', this.close); - } - - inherits$1(Zlib$2, Transform); - - Zlib$2.prototype.params = function(level, strategy, callback) { - if (level < binding$1.Z_MIN_LEVEL || - level > binding$1.Z_MAX_LEVEL) { - throw new RangeError('Invalid compression level: ' + level); - } - if (strategy != binding$1.Z_FILTERED && - strategy != binding$1.Z_HUFFMAN_ONLY && - strategy != binding$1.Z_RLE && - strategy != binding$1.Z_FIXED && - strategy != binding$1.Z_DEFAULT_STRATEGY) { - throw new TypeError('Invalid strategy: ' + strategy); - } - - if (this._level !== level || this._strategy !== strategy) { - var self = this; - this.flush(binding$1.Z_SYNC_FLUSH, function() { - self._binding.params(level, strategy); - if (!self._hadError) { - self._level = level; - self._strategy = strategy; - if (callback) callback(); - } - }); - } else { - nextTick$1(callback); - } - }; - - Zlib$2.prototype.reset = function() { - return this._binding.reset(); - }; - - // This is the _flush function called by the transform class, - // internally, when the last chunk has been written. - Zlib$2.prototype._flush = function(callback) { - this._transform(new Buffer(0), '', callback); - }; - - Zlib$2.prototype.flush = function(kind, callback) { - var ws = this._writableState; - - if (typeof kind === 'function' || (kind === void 0 && !callback)) { - callback = kind; - kind = binding$1.Z_FULL_FLUSH; - } - - if (ws.ended) { - if (callback) - nextTick$1(callback); - } else if (ws.ending) { - if (callback) - this.once('end', callback); - } else if (ws.needDrain) { - var self = this; - this.once('drain', function() { - self.flush(callback); - }); - } else { - this._flushFlag = kind; - this.write(new Buffer(0), '', callback); - } - }; - - Zlib$2.prototype.close = function(callback) { - if (callback) - nextTick$1(callback); - - if (this._closed) - return; - - this._closed = true; - - this._binding.close(); - - var self = this; - nextTick$1(function() { - self.emit('close'); - }); - }; - - Zlib$2.prototype._transform = function(chunk, encoding, cb) { - var flushFlag; - var ws = this._writableState; - var ending = ws.ending || ws.ended; - var last = ending && (!chunk || ws.length === chunk.length); - - if (!chunk === null && !isBuffer(chunk)) - return cb(new Error('invalid input')); - - // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag. - // If it's explicitly flushing at some other time, then we use - // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression - // goodness. - if (last) - flushFlag = binding$1.Z_FINISH; - else { - flushFlag = this._flushFlag; - // once we've flushed the last of the queue, stop flushing and - // go back to the normal behavior. - if (chunk.length >= ws.length) { - this._flushFlag = this._opts.flush || binding$1.Z_NO_FLUSH; - } - } - - this._processChunk(chunk, flushFlag, cb); - }; - - Zlib$2.prototype._processChunk = function(chunk, flushFlag, cb) { - var availInBefore = chunk && chunk.length; - var availOutBefore = this._chunkSize - this._offset; - var inOff = 0; - - var self = this; - - var async = typeof cb === 'function'; - - if (!async) { - var buffers = []; - var nread = 0; - - var error; - this.on('error', function(er) { - error = er; - }); - - do { - var res = this._binding.writeSync(flushFlag, - chunk, // in - inOff, // in_off - availInBefore, // in_len - this._buffer, // out - this._offset, //out_off - availOutBefore); // out_len - } while (!this._hadError && callback(res[0], res[1])); - - if (this._hadError) { - throw error; + const { PDFGradient: PDFGradient$1, PDFLinearGradient: PDFLinearGradient$1, PDFRadialGradient: PDFRadialGradient$1 } = Gradient; + + var ColorMixin = { + initColor() { + // The opacity dictionaries + this._opacityRegistry = {}; + this._opacityCount = 0; + return (this._gradCount = 0); + }, + + _normalizeColor(color) { + if (color instanceof PDFGradient$1) { + return color; } - var buf = Buffer.concat(buffers, nread); - this.close(); - - return buf; - } - - var req = this._binding.write(flushFlag, - chunk, // in - inOff, // in_off - availInBefore, // in_len - this._buffer, // out - this._offset, //out_off - availOutBefore); // out_len - - req.buffer = chunk; - req.callback = callback; - - function callback(availInAfter, availOutAfter) { - if (self._hadError) - return; - - var have = availOutBefore - availOutAfter; - assert$1(have >= 0, 'have should not go down'); - - if (have > 0) { - var out = self._buffer.slice(self._offset, self._offset + have); - self._offset += have; - // serve some output to the consumer. - if (async) { - self.push(out); - } else { - buffers.push(out); - nread += out.length; + if (typeof color === 'string') { + if (color.charAt(0) === '#') { + if (color.length === 4) { + color = color.replace( + /#([0-9A-F])([0-9A-F])([0-9A-F])/i, + '#$1$1$2$2$3$3' + ); + } + const hex = parseInt(color.slice(1), 16); + color = [hex >> 16, (hex >> 8) & 0xff, hex & 0xff]; + } else if (namedColors[color]) { + color = namedColors[color]; } } - // exhausted the output buffer, or used all the input create a new one. - if (availOutAfter === 0 || self._offset >= self._chunkSize) { - availOutBefore = self._chunkSize; - self._offset = 0; - self._buffer = new Buffer(self._chunkSize); + if (Array.isArray(color)) { + // RGB + if (color.length === 3) { + color = color.map(part => part / 255); + // CMYK + } else if (color.length === 4) { + color = color.map(part => part / 100); + } + return color; } - if (availOutAfter === 0) { - // Not actually done. Need to reprocess. - // Also, update the availInBefore to the availInAfter value, - // so that if we have to hit it a third (fourth, etc.) time, - // it'll have the correct byte counts. - inOff += (availInBefore - availInAfter); - availInBefore = availInAfter; + return null; + }, - if (!async) - return true; - - var newReq = self._binding.write(flushFlag, - chunk, - inOff, - availInBefore, - self._buffer, - self._offset, - self._chunkSize); - newReq.callback = callback; // this same function - newReq.buffer = chunk; - return; - } - - if (!async) + _setColor(color, stroke) { + color = this._normalizeColor(color); + if (!color) { return false; + } - // finished with the chunk. - cb(); + const op = stroke ? 'SCN' : 'scn'; + + if (color instanceof PDFGradient$1) { + this._setColorSpace('Pattern', stroke); + color.apply(op); + } else { + const space = color.length === 4 ? 'DeviceCMYK' : 'DeviceRGB'; + this._setColorSpace(space, stroke); + + color = color.join(' '); + this.addContent(`${color} ${op}`); + } + + return true; + }, + + _setColorSpace(space, stroke) { + const op = stroke ? 'CS' : 'cs'; + return this.addContent(`/${space} ${op}`); + }, + + fillColor(color, opacity) { + const set = this._setColor(color, false); + if (set) { + this.fillOpacity(opacity); + } + + // save this for text wrapper, which needs to reset + // the fill color on new pages + this._fillColor = [color, opacity]; + return this; + }, + + strokeColor(color, opacity) { + const set = this._setColor(color, true); + if (set) { + this.strokeOpacity(opacity); + } + return this; + }, + + opacity(opacity) { + this._doOpacity(opacity, opacity); + return this; + }, + + fillOpacity(opacity) { + this._doOpacity(opacity, null); + return this; + }, + + strokeOpacity(opacity) { + this._doOpacity(null, opacity); + return this; + }, + + _doOpacity(fillOpacity, strokeOpacity) { + let dictionary, name; + if (fillOpacity == null && strokeOpacity == null) { + return; + } + + if (fillOpacity != null) { + fillOpacity = Math.max(0, Math.min(1, fillOpacity)); + } + if (strokeOpacity != null) { + strokeOpacity = Math.max(0, Math.min(1, strokeOpacity)); + } + const key = `${fillOpacity}_${strokeOpacity}`; + + if (this._opacityRegistry[key]) { + [dictionary, name] = this._opacityRegistry[key]; + } else { + dictionary = { Type: 'ExtGState' }; + + if (fillOpacity != null) { + dictionary.ca = fillOpacity; + } + if (strokeOpacity != null) { + dictionary.CA = strokeOpacity; + } + + dictionary = this.ref(dictionary); + dictionary.end(); + const id = ++this._opacityCount; + name = `Gs${id}`; + this._opacityRegistry[key] = [dictionary, name]; + } + + this.page.ext_gstates[name] = dictionary; + return this.addContent(`/${name} gs`); + }, + + linearGradient(x1, y1, x2, y2) { + return new PDFLinearGradient$1(this, x1, y1, x2, y2); + }, + + radialGradient(x1, y1, r1, x2, y2, r2) { + return new PDFRadialGradient$1(this, x1, y1, r1, x2, y2, r2); } }; - inherits$1(Deflate$1, Zlib$2); - inherits$1(Inflate$1, Zlib$2); - inherits$1(Gzip$1, Zlib$2); - inherits$1(Gunzip$1, Zlib$2); - inherits$1(DeflateRaw$1, Zlib$2); - inherits$1(InflateRaw$1, Zlib$2); - inherits$1(Unzip$1, Zlib$2); - var zlib$1 = { - codes: codes$1, - createDeflate: createDeflate$1, - createInflate: createInflate$1, - createDeflateRaw: createDeflateRaw$1, - createInflateRaw: createInflateRaw$1, - createGzip: createGzip$1, - createGunzip: createGunzip$1, - createUnzip: createUnzip$1, - deflate: deflate$2, - deflateSync: deflateSync$1, - gzip: gzip$1, - gzipSync: gzipSync$1, - deflateRaw: deflateRaw$1, - deflateRawSync: deflateRawSync$1, - unzip: unzip$1, - unzipSync: unzipSync$1, - inflate: inflate$2, - inflateSync: inflateSync$1, - gunzip: gunzip$1, - gunzipSync: gunzipSync$1, - inflateRaw: inflateRaw$1, - inflateRawSync: inflateRawSync$1, - Deflate: Deflate$1, - Inflate: Inflate$1, - Gzip: Gzip$1, - Gunzip: Gunzip$1, - DeflateRaw: DeflateRaw$1, - InflateRaw: InflateRaw$1, - Unzip: Unzip$1, - Zlib: Zlib$2 + var namedColors = { + aliceblue: [240, 248, 255], + antiquewhite: [250, 235, 215], + aqua: [0, 255, 255], + aquamarine: [127, 255, 212], + azure: [240, 255, 255], + beige: [245, 245, 220], + bisque: [255, 228, 196], + black: [0, 0, 0], + blanchedalmond: [255, 235, 205], + blue: [0, 0, 255], + blueviolet: [138, 43, 226], + brown: [165, 42, 42], + burlywood: [222, 184, 135], + cadetblue: [95, 158, 160], + chartreuse: [127, 255, 0], + chocolate: [210, 105, 30], + coral: [255, 127, 80], + cornflowerblue: [100, 149, 237], + cornsilk: [255, 248, 220], + crimson: [220, 20, 60], + cyan: [0, 255, 255], + darkblue: [0, 0, 139], + darkcyan: [0, 139, 139], + darkgoldenrod: [184, 134, 11], + darkgray: [169, 169, 169], + darkgreen: [0, 100, 0], + darkgrey: [169, 169, 169], + darkkhaki: [189, 183, 107], + darkmagenta: [139, 0, 139], + darkolivegreen: [85, 107, 47], + darkorange: [255, 140, 0], + darkorchid: [153, 50, 204], + darkred: [139, 0, 0], + darksalmon: [233, 150, 122], + darkseagreen: [143, 188, 143], + darkslateblue: [72, 61, 139], + darkslategray: [47, 79, 79], + darkslategrey: [47, 79, 79], + darkturquoise: [0, 206, 209], + darkviolet: [148, 0, 211], + deeppink: [255, 20, 147], + deepskyblue: [0, 191, 255], + dimgray: [105, 105, 105], + dimgrey: [105, 105, 105], + dodgerblue: [30, 144, 255], + firebrick: [178, 34, 34], + floralwhite: [255, 250, 240], + forestgreen: [34, 139, 34], + fuchsia: [255, 0, 255], + gainsboro: [220, 220, 220], + ghostwhite: [248, 248, 255], + gold: [255, 215, 0], + goldenrod: [218, 165, 32], + gray: [128, 128, 128], + grey: [128, 128, 128], + green: [0, 128, 0], + greenyellow: [173, 255, 47], + honeydew: [240, 255, 240], + hotpink: [255, 105, 180], + indianred: [205, 92, 92], + indigo: [75, 0, 130], + ivory: [255, 255, 240], + khaki: [240, 230, 140], + lavender: [230, 230, 250], + lavenderblush: [255, 240, 245], + lawngreen: [124, 252, 0], + lemonchiffon: [255, 250, 205], + lightblue: [173, 216, 230], + lightcoral: [240, 128, 128], + lightcyan: [224, 255, 255], + lightgoldenrodyellow: [250, 250, 210], + lightgray: [211, 211, 211], + lightgreen: [144, 238, 144], + lightgrey: [211, 211, 211], + lightpink: [255, 182, 193], + lightsalmon: [255, 160, 122], + lightseagreen: [32, 178, 170], + lightskyblue: [135, 206, 250], + lightslategray: [119, 136, 153], + lightslategrey: [119, 136, 153], + lightsteelblue: [176, 196, 222], + lightyellow: [255, 255, 224], + lime: [0, 255, 0], + limegreen: [50, 205, 50], + linen: [250, 240, 230], + magenta: [255, 0, 255], + maroon: [128, 0, 0], + mediumaquamarine: [102, 205, 170], + mediumblue: [0, 0, 205], + mediumorchid: [186, 85, 211], + mediumpurple: [147, 112, 219], + mediumseagreen: [60, 179, 113], + mediumslateblue: [123, 104, 238], + mediumspringgreen: [0, 250, 154], + mediumturquoise: [72, 209, 204], + mediumvioletred: [199, 21, 133], + midnightblue: [25, 25, 112], + mintcream: [245, 255, 250], + mistyrose: [255, 228, 225], + moccasin: [255, 228, 181], + navajowhite: [255, 222, 173], + navy: [0, 0, 128], + oldlace: [253, 245, 230], + olive: [128, 128, 0], + olivedrab: [107, 142, 35], + orange: [255, 165, 0], + orangered: [255, 69, 0], + orchid: [218, 112, 214], + palegoldenrod: [238, 232, 170], + palegreen: [152, 251, 152], + paleturquoise: [175, 238, 238], + palevioletred: [219, 112, 147], + papayawhip: [255, 239, 213], + peachpuff: [255, 218, 185], + peru: [205, 133, 63], + pink: [255, 192, 203], + plum: [221, 160, 221], + powderblue: [176, 224, 230], + purple: [128, 0, 128], + red: [255, 0, 0], + rosybrown: [188, 143, 143], + royalblue: [65, 105, 225], + saddlebrown: [139, 69, 19], + salmon: [250, 128, 114], + sandybrown: [244, 164, 96], + seagreen: [46, 139, 87], + seashell: [255, 245, 238], + sienna: [160, 82, 45], + silver: [192, 192, 192], + skyblue: [135, 206, 235], + slateblue: [106, 90, 205], + slategray: [112, 128, 144], + slategrey: [112, 128, 144], + snow: [255, 250, 250], + springgreen: [0, 255, 127], + steelblue: [70, 130, 180], + tan: [210, 180, 140], + teal: [0, 128, 128], + thistle: [216, 191, 216], + tomato: [255, 99, 71], + turquoise: [64, 224, 208], + violet: [238, 130, 238], + wheat: [245, 222, 179], + white: [255, 255, 255], + whitesmoke: [245, 245, 245], + yellow: [255, 255, 0], + yellowgreen: [154, 205, 50] }; + let cx, cy, px, py, sx, sy; + + cx = cy = px = py = sx = sy = 0; + + const parameters = { + A: 7, + a: 7, + C: 6, + c: 6, + H: 1, + h: 1, + L: 2, + l: 2, + M: 2, + m: 2, + Q: 4, + q: 4, + S: 4, + s: 4, + T: 2, + t: 2, + V: 1, + v: 1, + Z: 0, + z: 0 + }; + + const parse = function(path) { + let cmd; + const ret = []; + let args = []; + let curArg = ''; + let foundDecimal = false; + let params = 0; + + for (let c of path) { + if (parameters[c] != null) { + params = parameters[c]; + if (cmd) { + // save existing command + if (curArg.length > 0) { + args[args.length] = +curArg; + } + ret[ret.length] = { cmd, args }; + + args = []; + curArg = ''; + foundDecimal = false; + } + + cmd = c; + } else if ( + [' ', ','].includes(c) || + (c === '-' && curArg.length > 0 && curArg[curArg.length - 1] !== 'e') || + (c === '.' && foundDecimal) + ) { + if (curArg.length === 0) { + continue; + } + + if (args.length === params) { + // handle reused commands + ret[ret.length] = { cmd, args }; + args = [+curArg]; + + // handle assumed commands + if (cmd === 'M') { + cmd = 'L'; + } + if (cmd === 'm') { + cmd = 'l'; + } + } else { + args[args.length] = +curArg; + } + + foundDecimal = c === '.'; + + // fix for negative numbers or repeated decimals with no delimeter between commands + curArg = ['-', '.'].includes(c) ? c : ''; + } else { + curArg += c; + if (c === '.') { + foundDecimal = true; + } + } + } + + // add the last command + if (curArg.length > 0) { + if (args.length === params) { + // handle reused commands + ret[ret.length] = { cmd, args }; + args = [+curArg]; + + // handle assumed commands + if (cmd === 'M') { + cmd = 'L'; + } + if (cmd === 'm') { + cmd = 'l'; + } + } else { + args[args.length] = +curArg; + } + } + + ret[ret.length] = { cmd, args }; + + return ret; + }; + + const apply = function(commands, doc) { + // current point, control point, and subpath starting point + cx = cy = px = py = sx = sy = 0; + + // run the commands + for (let i = 0; i < commands.length; i++) { + const c = commands[i]; + if (typeof runners[c.cmd] === 'function') { + runners[c.cmd](doc, c.args); + } + } + }; + + const runners = { + M(doc, a) { + cx = a[0]; + cy = a[1]; + px = py = null; + sx = cx; + sy = cy; + return doc.moveTo(cx, cy); + }, + + m(doc, a) { + cx += a[0]; + cy += a[1]; + px = py = null; + sx = cx; + sy = cy; + return doc.moveTo(cx, cy); + }, + + C(doc, a) { + cx = a[4]; + cy = a[5]; + px = a[2]; + py = a[3]; + return doc.bezierCurveTo(...a); + }, + + c(doc, a) { + doc.bezierCurveTo( + a[0] + cx, + a[1] + cy, + a[2] + cx, + a[3] + cy, + a[4] + cx, + a[5] + cy + ); + px = cx + a[2]; + py = cy + a[3]; + cx += a[4]; + return (cy += a[5]); + }, + + S(doc, a) { + if (px === null) { + px = cx; + py = cy; + } + + doc.bezierCurveTo(cx - (px - cx), cy - (py - cy), a[0], a[1], a[2], a[3]); + px = a[0]; + py = a[1]; + cx = a[2]; + return (cy = a[3]); + }, + + s(doc, a) { + if (px === null) { + px = cx; + py = cy; + } + + doc.bezierCurveTo( + cx - (px - cx), + cy - (py - cy), + cx + a[0], + cy + a[1], + cx + a[2], + cy + a[3] + ); + px = cx + a[0]; + py = cy + a[1]; + cx += a[2]; + return (cy += a[3]); + }, + + Q(doc, a) { + px = a[0]; + py = a[1]; + cx = a[2]; + cy = a[3]; + return doc.quadraticCurveTo(a[0], a[1], cx, cy); + }, + + q(doc, a) { + doc.quadraticCurveTo(a[0] + cx, a[1] + cy, a[2] + cx, a[3] + cy); + px = cx + a[0]; + py = cy + a[1]; + cx += a[2]; + return (cy += a[3]); + }, + + T(doc, a) { + if (px === null) { + px = cx; + py = cy; + } else { + px = cx - (px - cx); + py = cy - (py - cy); + } + + doc.quadraticCurveTo(px, py, a[0], a[1]); + px = cx - (px - cx); + py = cy - (py - cy); + cx = a[0]; + return (cy = a[1]); + }, + + t(doc, a) { + if (px === null) { + px = cx; + py = cy; + } else { + px = cx - (px - cx); + py = cy - (py - cy); + } + + doc.quadraticCurveTo(px, py, cx + a[0], cy + a[1]); + cx += a[0]; + return (cy += a[1]); + }, + + A(doc, a) { + solveArc(doc, cx, cy, a); + cx = a[5]; + return (cy = a[6]); + }, + + a(doc, a) { + a[5] += cx; + a[6] += cy; + solveArc(doc, cx, cy, a); + cx = a[5]; + return (cy = a[6]); + }, + + L(doc, a) { + cx = a[0]; + cy = a[1]; + px = py = null; + return doc.lineTo(cx, cy); + }, + + l(doc, a) { + cx += a[0]; + cy += a[1]; + px = py = null; + return doc.lineTo(cx, cy); + }, + + H(doc, a) { + cx = a[0]; + px = py = null; + return doc.lineTo(cx, cy); + }, + + h(doc, a) { + cx += a[0]; + px = py = null; + return doc.lineTo(cx, cy); + }, + + V(doc, a) { + cy = a[0]; + px = py = null; + return doc.lineTo(cx, cy); + }, + + v(doc, a) { + cy += a[0]; + px = py = null; + return doc.lineTo(cx, cy); + }, + + Z(doc) { + doc.closePath(); + cx = sx; + return (cy = sy); + }, + + z(doc) { + doc.closePath(); + cx = sx; + return (cy = sy); + } + }; + + const solveArc = function(doc, x, y, coords) { + const [rx, ry, rot, large, sweep, ex, ey] = coords; + const segs = arcToSegments(ex, ey, rx, ry, large, sweep, rot, x, y); + + for (let seg of segs) { + const bez = segmentToBezier(...seg); + doc.bezierCurveTo(...bez); + } + }; + + // from Inkscape svgtopdf, thanks! + const arcToSegments = function(x, y, rx, ry, large, sweep, rotateX, ox, oy) { + const th = rotateX * (Math.PI / 180); + const sin_th = Math.sin(th); + const cos_th = Math.cos(th); + rx = Math.abs(rx); + ry = Math.abs(ry); + px = cos_th * (ox - x) * 0.5 + sin_th * (oy - y) * 0.5; + py = cos_th * (oy - y) * 0.5 - sin_th * (ox - x) * 0.5; + let pl = (px * px) / (rx * rx) + (py * py) / (ry * ry); + if (pl > 1) { + pl = Math.sqrt(pl); + rx *= pl; + ry *= pl; + } + + const a00 = cos_th / rx; + const a01 = sin_th / rx; + const a10 = -sin_th / ry; + const a11 = cos_th / ry; + const x0 = a00 * ox + a01 * oy; + const y0 = a10 * ox + a11 * oy; + const x1 = a00 * x + a01 * y; + const y1 = a10 * x + a11 * y; + + const d = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0); + let sfactor_sq = 1 / d - 0.25; + if (sfactor_sq < 0) { + sfactor_sq = 0; + } + let sfactor = Math.sqrt(sfactor_sq); + if (sweep === large) { + sfactor = -sfactor; + } + + const xc = 0.5 * (x0 + x1) - sfactor * (y1 - y0); + const yc = 0.5 * (y0 + y1) + sfactor * (x1 - x0); + + const th0 = Math.atan2(y0 - yc, x0 - xc); + const th1 = Math.atan2(y1 - yc, x1 - xc); + + let th_arc = th1 - th0; + if (th_arc < 0 && sweep === 1) { + th_arc += 2 * Math.PI; + } else if (th_arc > 0 && sweep === 0) { + th_arc -= 2 * Math.PI; + } + + const segments = Math.ceil(Math.abs(th_arc / (Math.PI * 0.5 + 0.001))); + const result = []; + + for (let i = 0; i < segments; i++) { + const th2 = th0 + (i * th_arc) / segments; + const th3 = th0 + ((i + 1) * th_arc) / segments; + result[i] = [xc, yc, th2, th3, rx, ry, sin_th, cos_th]; + } + + return result; + }; + + const segmentToBezier = function(cx, cy, th0, th1, rx, ry, sin_th, cos_th) { + const a00 = cos_th * rx; + const a01 = -sin_th * ry; + const a10 = sin_th * rx; + const a11 = cos_th * ry; + + const th_half = 0.5 * (th1 - th0); + const t = + ((8 / 3) * Math.sin(th_half * 0.5) * Math.sin(th_half * 0.5)) / + Math.sin(th_half); + const x1 = cx + Math.cos(th0) - t * Math.sin(th0); + const y1 = cy + Math.sin(th0) + t * Math.cos(th0); + const x3 = cx + Math.cos(th1); + const y3 = cy + Math.sin(th1); + const x2 = x3 + t * Math.sin(th1); + const y2 = y3 - t * Math.cos(th1); + + return [ + a00 * x1 + a01 * y1, + a10 * x1 + a11 * y1, + a00 * x2 + a01 * y2, + a10 * x2 + a11 * y2, + a00 * x3 + a01 * y3, + a10 * x3 + a11 * y3 + ]; + }; + + class SVGPath { + static apply(doc, path) { + const commands = parse(path); + apply(commands, doc); + } + } + + const { number: number$1 } = PDFObject; + + // This constant is used to approximate a symmetrical arc using a cubic + // Bezier curve. + const KAPPA = 4.0 * ((Math.sqrt(2) - 1.0) / 3.0); + var VectorMixin = { + initVector() { + this._ctm = [1, 0, 0, 1, 0, 0]; // current transformation matrix + return (this._ctmStack = []); + }, + + save() { + this._ctmStack.push(this._ctm.slice()); + // TODO: save/restore colorspace and styles so not setting it unnessesarily all the time? + return this.addContent('q'); + }, + + restore() { + this._ctm = this._ctmStack.pop() || [1, 0, 0, 1, 0, 0]; + return this.addContent('Q'); + }, + + closePath() { + return this.addContent('h'); + }, + + lineWidth(w) { + return this.addContent(`${number$1(w)} w`); + }, + + _CAP_STYLES: { + BUTT: 0, + ROUND: 1, + SQUARE: 2 + }, + + lineCap(c) { + if (typeof c === 'string') { + c = this._CAP_STYLES[c.toUpperCase()]; + } + return this.addContent(`${c} J`); + }, + + _JOIN_STYLES: { + MITER: 0, + ROUND: 1, + BEVEL: 2 + }, + + lineJoin(j) { + if (typeof j === 'string') { + j = this._JOIN_STYLES[j.toUpperCase()]; + } + return this.addContent(`${j} j`); + }, + + miterLimit(m) { + return this.addContent(`${number$1(m)} M`); + }, + + dash(length, options = {}) { + const originalLength = length; + if (!Array.isArray(length)) { + length = [length, options.space || length]; + } + + const valid = length.every(x => Number.isFinite(x) && x > 0); + if(!valid) { + throw new Error(`dash(${JSON.stringify(originalLength)}, ${JSON.stringify(options)}) invalid, lengths must be numeric and greater than zero`); + } + + length = length.map(number$1).join(' '); + return this.addContent(`[${length}] ${number$1(options.phase || 0)} d`); + }, + + undash() { + return this.addContent('[] 0 d'); + }, + + moveTo(x, y) { + return this.addContent(`${number$1(x)} ${number$1(y)} m`); + }, + + lineTo(x, y) { + return this.addContent(`${number$1(x)} ${number$1(y)} l`); + }, + + bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) { + return this.addContent( + `${number$1(cp1x)} ${number$1(cp1y)} ${number$1(cp2x)} ${number$1(cp2y)} ${number$1( + x + )} ${number$1(y)} c` + ); + }, + + quadraticCurveTo(cpx, cpy, x, y) { + return this.addContent( + `${number$1(cpx)} ${number$1(cpy)} ${number$1(x)} ${number$1(y)} v` + ); + }, + + rect(x, y, w, h) { + return this.addContent( + `${number$1(x)} ${number$1(y)} ${number$1(w)} ${number$1(h)} re` + ); + }, + + roundedRect(x, y, w, h, r) { + if (r == null) { + r = 0; + } + r = Math.min(r, 0.5 * w, 0.5 * h); + + // amount to inset control points from corners (see `ellipse`) + const c = r * (1.0 - KAPPA); + + this.moveTo(x + r, y); + this.lineTo(x + w - r, y); + this.bezierCurveTo(x + w - c, y, x + w, y + c, x + w, y + r); + this.lineTo(x + w, y + h - r); + this.bezierCurveTo(x + w, y + h - c, x + w - c, y + h, x + w - r, y + h); + this.lineTo(x + r, y + h); + this.bezierCurveTo(x + c, y + h, x, y + h - c, x, y + h - r); + this.lineTo(x, y + r); + this.bezierCurveTo(x, y + c, x + c, y, x + r, y); + return this.closePath(); + }, + + ellipse(x, y, r1, r2) { + // based on http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas/2173084#2173084 + if (r2 == null) { + r2 = r1; + } + x -= r1; + y -= r2; + const ox = r1 * KAPPA; + const oy = r2 * KAPPA; + const xe = x + r1 * 2; + const ye = y + r2 * 2; + const xm = x + r1; + const ym = y + r2; + + this.moveTo(x, ym); + this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + return this.closePath(); + }, + + circle(x, y, radius) { + return this.ellipse(x, y, radius); + }, + + arc(x, y, radius, startAngle, endAngle, anticlockwise) { + if (anticlockwise == null) { + anticlockwise = false; + } + const TWO_PI = 2.0 * Math.PI; + const HALF_PI = 0.5 * Math.PI; + + let deltaAng = endAngle - startAngle; + + if (Math.abs(deltaAng) > TWO_PI) { + // draw only full circle if more than that is specified + deltaAng = TWO_PI; + } else if (deltaAng !== 0 && anticlockwise !== deltaAng < 0) { + // necessary to flip direction of rendering + const dir = anticlockwise ? -1 : 1; + deltaAng = dir * TWO_PI + deltaAng; + } + + const numSegs = Math.ceil(Math.abs(deltaAng) / HALF_PI); + const segAng = deltaAng / numSegs; + const handleLen = (segAng / HALF_PI) * KAPPA * radius; + let curAng = startAngle; + + // component distances between anchor point and control point + let deltaCx = -Math.sin(curAng) * handleLen; + let deltaCy = Math.cos(curAng) * handleLen; + + // anchor point + let ax = x + Math.cos(curAng) * radius; + let ay = y + Math.sin(curAng) * radius; + + // calculate and render segments + this.moveTo(ax, ay); + + for (let segIdx = 0; segIdx < numSegs; segIdx++) { + // starting control point + const cp1x = ax + deltaCx; + const cp1y = ay + deltaCy; + + // step angle + curAng += segAng; + + // next anchor point + ax = x + Math.cos(curAng) * radius; + ay = y + Math.sin(curAng) * radius; + + // next control point delta + deltaCx = -Math.sin(curAng) * handleLen; + deltaCy = Math.cos(curAng) * handleLen; + + // ending control point + const cp2x = ax - deltaCx; + const cp2y = ay - deltaCy; + + // render segment + this.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, ax, ay); + } + + return this; + }, + + polygon(...points) { + this.moveTo(...(points.shift() || [])); + for (let point of points) { + this.lineTo(...(point || [])); + } + return this.closePath(); + }, + + path(path) { + SVGPath.apply(this, path); + return this; + }, + + _windingRule(rule) { + if (/even-?odd/.test(rule)) { + return '*'; + } + + return ''; + }, + + fill(color, rule) { + if (/(even-?odd)|(non-?zero)/.test(color)) { + rule = color; + color = null; + } + + if (color) { + this.fillColor(color); + } + return this.addContent(`f${this._windingRule(rule)}`); + }, + + stroke(color) { + if (color) { + this.strokeColor(color); + } + return this.addContent('S'); + }, + + fillAndStroke(fillColor, strokeColor, rule) { + if (strokeColor == null) { + strokeColor = fillColor; + } + const isFillRule = /(even-?odd)|(non-?zero)/; + if (isFillRule.test(fillColor)) { + rule = fillColor; + fillColor = null; + } + + if (isFillRule.test(strokeColor)) { + rule = strokeColor; + strokeColor = fillColor; + } + + if (fillColor) { + this.fillColor(fillColor); + this.strokeColor(strokeColor); + } + + return this.addContent(`B${this._windingRule(rule)}`); + }, + + clip(rule) { + return this.addContent(`W${this._windingRule(rule)} n`); + }, + + transform(m11, m12, m21, m22, dx, dy) { + // keep track of the current transformation matrix + const m = this._ctm; + const [m0, m1, m2, m3, m4, m5] = m; + m[0] = m0 * m11 + m2 * m12; + m[1] = m1 * m11 + m3 * m12; + m[2] = m0 * m21 + m2 * m22; + m[3] = m1 * m21 + m3 * m22; + m[4] = m0 * dx + m2 * dy + m4; + m[5] = m1 * dx + m3 * dy + m5; + + const values = [m11, m12, m21, m22, dx, dy].map(v => number$1(v)).join(' '); + return this.addContent(`${values} cm`); + }, + + translate(x, y) { + return this.transform(1, 0, 0, 1, x, y); + }, + + rotate(angle, options = {}) { + let y; + const rad = (angle * Math.PI) / 180; + const cos = Math.cos(rad); + const sin = Math.sin(rad); + let x = (y = 0); + + if (options.origin != null) { + [x, y] = options.origin; + const x1 = x * cos - y * sin; + const y1 = x * sin + y * cos; + x -= x1; + y -= y1; + } + + return this.transform(cos, sin, -sin, cos, x, y); + }, + + scale(xFactor, yFactor, options = {}) { + let y; + if (yFactor == null) { + yFactor = xFactor; + } + if (typeof yFactor === 'object') { + options = yFactor; + yFactor = xFactor; + } + + let x = (y = 0); + if (options.origin != null) { + [x, y] = options.origin; + x -= xFactor * x; + y -= yFactor * y; + } + + return this.transform(xFactor, 0, 0, yFactor, x, y); + } + }; + + const MARKERS = [ + 0xffc0, + 0xffc1, + 0xffc2, + 0xffc3, + 0xffc5, + 0xffc6, + 0xffc7, + 0xffc8, + 0xffc9, + 0xffca, + 0xffcb, + 0xffcc, + 0xffcd, + 0xffce, + 0xffcf + ]; + + const COLOR_SPACE_MAP = { + 1: 'DeviceGray', + 3: 'DeviceRGB', + 4: 'DeviceCMYK' + }; + + class JPEG { + constructor(data, label) { + let marker; + this.data = data; + this.label = label; + if (this.data.readUInt16BE(0) !== 0xffd8) { + throw 'SOI not found in JPEG'; + } + + let pos = 2; + while (pos < this.data.length) { + marker = this.data.readUInt16BE(pos); + pos += 2; + if (MARKERS.includes(marker)) { + break; + } + pos += this.data.readUInt16BE(pos); + } + + if (!MARKERS.includes(marker)) { + throw 'Invalid JPEG.'; + } + pos += 2; + + this.bits = this.data[pos++]; + this.height = this.data.readUInt16BE(pos); + pos += 2; + + this.width = this.data.readUInt16BE(pos); + pos += 2; + + const channels = this.data[pos++]; + this.colorSpace = COLOR_SPACE_MAP[channels]; + + this.obj = null; + } + + embed(document) { + if (this.obj) { + return; + } + + this.obj = document.ref({ + Type: 'XObject', + Subtype: 'Image', + BitsPerComponent: this.bits, + Width: this.width, + Height: this.height, + ColorSpace: this.colorSpace, + Filter: 'DCTDecode' + }); + + // add extra decode params for CMYK images. By swapping the + // min and max values from the default, we invert the colors. See + // section 4.8.4 of the spec. + if (this.colorSpace === 'DeviceCMYK') { + this.obj.data['Decode'] = [1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0]; + } + + this.obj.end(this.data); + + // free memory + return (this.data = null); + } + } + /* * MIT LICENSE * Copyright (c) 2011 Devon Govett @@ -25048,14 +22530,14 @@ var pngNode = class PNG { static decode(path, fn) { - return fs$1.readFile(path, function(err, file) { + return fs.readFile(path, function(err, file) { const png = new PNG(file); return png.decode(pixels => fn(pixels)); }); } static load(path) { - const file = fs$1.readFileSync(path); + const file = fs.readFileSync(path); return new PNG(file); } @@ -25204,7 +22686,7 @@ } decodePixels(fn) { - return zlib$1.inflate(this.imgData, (err, data) => { + return zlib.inflate(this.imgData, (err, data) => { if (err) { throw err; } @@ -25425,393 +22907,393 @@ } }; - class PNGImage { - constructor(data, label) { - this.label = label; - this.image = new pngNode(data); - this.width = this.image.width; - this.height = this.image.height; - this.imgData = this.image.imgData; - this.obj = null; - } - - embed(document) { - let dataDecoded = false; - - this.document = document; - if (this.obj) { - return; - } - - const hasAlphaChannel = this.image.hasAlphaChannel; - const isInterlaced = this.image.interlaceMethod === 1; - - this.obj = this.document.ref({ - Type: 'XObject', - Subtype: 'Image', - BitsPerComponent: hasAlphaChannel ? 8 : this.image.bits, - Width: this.width, - Height: this.height, - Filter: 'FlateDecode' - }); - - if (!hasAlphaChannel) { - const params = this.document.ref({ - Predictor: isInterlaced ? 1 : 15, - Colors: this.image.colors, - BitsPerComponent: this.image.bits, - Columns: this.width - }); - - this.obj.data['DecodeParms'] = params; - params.end(); - } - - if (this.image.palette.length === 0) { - this.obj.data['ColorSpace'] = this.image.colorSpace; - } else { - // embed the color palette in the PDF as an object stream - const palette = this.document.ref(); - palette.end(new Buffer(this.image.palette)); - - // build the color space array for the image - this.obj.data['ColorSpace'] = [ - 'Indexed', - 'DeviceRGB', - this.image.palette.length / 3 - 1, - palette - ]; - } - - // For PNG color types 0, 2 and 3, the transparency data is stored in - // a dedicated PNG chunk. - if (this.image.transparency.grayscale != null) { - // Use Color Key Masking (spec section 4.8.5) - // An array with N elements, where N is two times the number of color components. - const val = this.image.transparency.grayscale; - this.obj.data['Mask'] = [val, val]; - } else if (this.image.transparency.rgb) { - // Use Color Key Masking (spec section 4.8.5) - // An array with N elements, where N is two times the number of color components. - const { rgb } = this.image.transparency; - const mask = []; - for (let x of rgb) { - mask.push(x, x); - } - - this.obj.data['Mask'] = mask; - } else if (this.image.transparency.indexed) { - // Create a transparency SMask for the image based on the data - // in the PLTE and tRNS sections. See below for details on SMasks. - dataDecoded = true; - return this.loadIndexedAlphaChannel(); - } else if (hasAlphaChannel) { - // For PNG color types 4 and 6, the transparency data is stored as a alpha - // channel mixed in with the main image data. Separate this data out into an - // SMask object and store it separately in the PDF. - dataDecoded = true; - return this.splitAlphaChannel(); - } - - if (isInterlaced && !dataDecoded) { - return this.decodeData(); - } - - this.finalize(); - } - - finalize() { - if (this.alphaChannel) { - const sMask = this.document.ref({ - Type: 'XObject', - Subtype: 'Image', - Height: this.height, - Width: this.width, - BitsPerComponent: 8, - Filter: 'FlateDecode', - ColorSpace: 'DeviceGray', - Decode: [0, 1] - }); - - sMask.end(this.alphaChannel); - this.obj.data['SMask'] = sMask; - } - - // add the actual image data - this.obj.end(this.imgData); - - // free memory - this.image = null; - return (this.imgData = null); - } - - splitAlphaChannel() { - return this.image.decodePixels(pixels => { - let a, p; - const colorCount = this.image.colors; - const pixelCount = this.width * this.height; - const imgData = new Buffer(pixelCount * colorCount); - const alphaChannel = new Buffer(pixelCount); - - let i = (p = a = 0); - const len = pixels.length; - // For 16bit images copy only most significant byte (MSB) - PNG data is always stored in network byte order (MSB first) - const skipByteCount = this.image.bits === 16 ? 1 : 0; - while (i < len) { - for (let colorIndex = 0; colorIndex < colorCount; colorIndex++) { - imgData[p++] = pixels[i++]; - i += skipByteCount; - } - alphaChannel[a++] = pixels[i++]; - i += skipByteCount; - } - - this.imgData = zlib.deflateSync(imgData); - this.alphaChannel = zlib.deflateSync(alphaChannel); - return this.finalize(); - }); - } - - loadIndexedAlphaChannel() { - const transparency = this.image.transparency.indexed; - return this.image.decodePixels(pixels => { - const alphaChannel = new Buffer(this.width * this.height); - - let i = 0; - for (let j = 0, end = pixels.length; j < end; j++) { - alphaChannel[i++] = transparency[pixels[j]]; - } - - this.alphaChannel = zlib.deflateSync(alphaChannel); - return this.finalize(); - }); - } - - decodeData() { - this.image.decodePixels(pixels => { - this.imgData = zlib.deflateSync(pixels); - this.finalize(); - }); - } + class PNGImage { + constructor(data, label) { + this.label = label; + this.image = new pngNode(data); + this.width = this.image.width; + this.height = this.image.height; + this.imgData = this.image.imgData; + this.obj = null; + } + + embed(document) { + let dataDecoded = false; + + this.document = document; + if (this.obj) { + return; + } + + const hasAlphaChannel = this.image.hasAlphaChannel; + const isInterlaced = this.image.interlaceMethod === 1; + + this.obj = this.document.ref({ + Type: 'XObject', + Subtype: 'Image', + BitsPerComponent: hasAlphaChannel ? 8 : this.image.bits, + Width: this.width, + Height: this.height, + Filter: 'FlateDecode' + }); + + if (!hasAlphaChannel) { + const params = this.document.ref({ + Predictor: isInterlaced ? 1 : 15, + Colors: this.image.colors, + BitsPerComponent: this.image.bits, + Columns: this.width + }); + + this.obj.data['DecodeParms'] = params; + params.end(); + } + + if (this.image.palette.length === 0) { + this.obj.data['ColorSpace'] = this.image.colorSpace; + } else { + // embed the color palette in the PDF as an object stream + const palette = this.document.ref(); + palette.end(new Buffer(this.image.palette)); + + // build the color space array for the image + this.obj.data['ColorSpace'] = [ + 'Indexed', + 'DeviceRGB', + this.image.palette.length / 3 - 1, + palette + ]; + } + + // For PNG color types 0, 2 and 3, the transparency data is stored in + // a dedicated PNG chunk. + if (this.image.transparency.grayscale != null) { + // Use Color Key Masking (spec section 4.8.5) + // An array with N elements, where N is two times the number of color components. + const val = this.image.transparency.grayscale; + this.obj.data['Mask'] = [val, val]; + } else if (this.image.transparency.rgb) { + // Use Color Key Masking (spec section 4.8.5) + // An array with N elements, where N is two times the number of color components. + const { rgb } = this.image.transparency; + const mask = []; + for (let x of rgb) { + mask.push(x, x); + } + + this.obj.data['Mask'] = mask; + } else if (this.image.transparency.indexed) { + // Create a transparency SMask for the image based on the data + // in the PLTE and tRNS sections. See below for details on SMasks. + dataDecoded = true; + return this.loadIndexedAlphaChannel(); + } else if (hasAlphaChannel) { + // For PNG color types 4 and 6, the transparency data is stored as a alpha + // channel mixed in with the main image data. Separate this data out into an + // SMask object and store it separately in the PDF. + dataDecoded = true; + return this.splitAlphaChannel(); + } + + if (isInterlaced && !dataDecoded) { + return this.decodeData(); + } + + this.finalize(); + } + + finalize() { + if (this.alphaChannel) { + const sMask = this.document.ref({ + Type: 'XObject', + Subtype: 'Image', + Height: this.height, + Width: this.width, + BitsPerComponent: 8, + Filter: 'FlateDecode', + ColorSpace: 'DeviceGray', + Decode: [0, 1] + }); + + sMask.end(this.alphaChannel); + this.obj.data['SMask'] = sMask; + } + + // add the actual image data + this.obj.end(this.imgData); + + // free memory + this.image = null; + return (this.imgData = null); + } + + splitAlphaChannel() { + return this.image.decodePixels(pixels => { + let a, p; + const colorCount = this.image.colors; + const pixelCount = this.width * this.height; + const imgData = new Buffer(pixelCount * colorCount); + const alphaChannel = new Buffer(pixelCount); + + let i = (p = a = 0); + const len = pixels.length; + // For 16bit images copy only most significant byte (MSB) - PNG data is always stored in network byte order (MSB first) + const skipByteCount = this.image.bits === 16 ? 1 : 0; + while (i < len) { + for (let colorIndex = 0; colorIndex < colorCount; colorIndex++) { + imgData[p++] = pixels[i++]; + i += skipByteCount; + } + alphaChannel[a++] = pixels[i++]; + i += skipByteCount; + } + + this.imgData = zlib.deflateSync(imgData); + this.alphaChannel = zlib.deflateSync(alphaChannel); + return this.finalize(); + }); + } + + loadIndexedAlphaChannel() { + const transparency = this.image.transparency.indexed; + return this.image.decodePixels(pixels => { + const alphaChannel = new Buffer(this.width * this.height); + + let i = 0; + for (let j = 0, end = pixels.length; j < end; j++) { + alphaChannel[i++] = transparency[pixels[j]]; + } + + this.alphaChannel = zlib.deflateSync(alphaChannel); + return this.finalize(); + }); + } + + decodeData() { + this.image.decodePixels(pixels => { + this.imgData = zlib.deflateSync(pixels); + this.finalize(); + }); + } } - class PDFImage { - static open(src, label) { - let data; - if (isBuffer(src)) { - data = src; - } else if (src instanceof ArrayBuffer) { - data = new Buffer(new Uint8Array(src)); - } else { - let match; - if ((match = /^data:.+;base64,(.*)$/.exec(src))) { - data = new Buffer(match[1], 'base64'); - } else { - data = fs.readFileSync(src); - if (!data) { - return; - } - } - } - - if (data[0] === 0xff && data[1] === 0xd8) { - return new JPEG(data, label); - } else if (data[0] === 0x89 && data.toString('ascii', 1, 4) === 'PNG') { - return new PNGImage(data, label); - } else { - throw new Error('Unknown image format.'); - } - } + class PDFImage { + static open(src, label) { + let data; + if (isBuffer(src)) { + data = src; + } else if (src instanceof ArrayBuffer) { + data = new Buffer(new Uint8Array(src)); + } else { + let match; + if ((match = /^data:.+;base64,(.*)$/.exec(src))) { + data = new Buffer(match[1], 'base64'); + } else { + data = fs.readFileSync(src); + if (!data) { + return; + } + } + } + + if (data[0] === 0xff && data[1] === 0xd8) { + return new JPEG(data, label); + } else if (data[0] === 0x89 && data.toString('ascii', 1, 4) === 'PNG') { + return new PNGImage(data, label); + } else { + throw new Error('Unknown image format.'); + } + } } - var ImagesMixin = { - initImages() { - this._imageRegistry = {}; - return (this._imageCount = 0); - }, - - image(src, x, y, options = {}) { - let bh, bp, bw, image, ip, left, left1; - if (typeof x === 'object') { - options = x; - x = null; - } - - x = (left = x != null ? x : options.x) != null ? left : this.x; - y = (left1 = y != null ? y : options.y) != null ? left1 : this.y; - - if (typeof src === 'string') { - image = this._imageRegistry[src]; - } - - if (!image) { - if (src.width && src.height) { - image = src; - } else { - image = this.openImage(src); - } - } - - if (!image.obj) { - image.embed(this); - } - - if (this.page.xobjects[image.label] == null) { - this.page.xobjects[image.label] = image.obj; - } - - let w = options.width || image.width; - let h = options.height || image.height; - - if (options.width && !options.height) { - const wp = w / image.width; - w = image.width * wp; - h = image.height * wp; - } else if (options.height && !options.width) { - const hp = h / image.height; - w = image.width * hp; - h = image.height * hp; - } else if (options.scale) { - w = image.width * options.scale; - h = image.height * options.scale; - } else if (options.fit) { - [bw, bh] = options.fit; - bp = bw / bh; - ip = image.width / image.height; - if (ip > bp) { - w = bw; - h = bw / ip; - } else { - h = bh; - w = bh * ip; - } - } else if (options.cover) { - [bw, bh] = options.cover; - bp = bw / bh; - ip = image.width / image.height; - if (ip > bp) { - h = bh; - w = bh * ip; - } else { - w = bw; - h = bw / ip; - } - } - - if (options.fit || options.cover) { - if (options.align === 'center') { - x = x + bw / 2 - w / 2; - } else if (options.align === 'right') { - x = x + bw - w; - } - - if (options.valign === 'center') { - y = y + bh / 2 - h / 2; - } else if (options.valign === 'bottom') { - y = y + bh - h; - } - } - - // create link annotations if the link option is given - if (options.link != null) { - this.link(x, y, w, h, options.link); - } - if (options.goTo != null) { - this.goTo(x, y, w, h, options.goTo); - } - if (options.destination != null) { - this.addNamedDestination(options.destination, 'XYZ', x, y, null); - } - - // Set the current y position to below the image if it is in the document flow - if (this.y === y) { - this.y += h; - } - - this.save(); - this.transform(w, 0, 0, -h, x, y + h); - this.addContent(`/${image.label} Do`); - this.restore(); - - return this; - }, - - openImage(src) { - let image; - if (typeof src === 'string') { - image = this._imageRegistry[src]; - } - - if (!image) { - image = PDFImage.open(src, `I${++this._imageCount}`); - if (typeof src === 'string') { - this._imageRegistry[src] = image; - } - } - - return image; - } + var ImagesMixin = { + initImages() { + this._imageRegistry = {}; + return (this._imageCount = 0); + }, + + image(src, x, y, options = {}) { + let bh, bp, bw, image, ip, left, left1; + if (typeof x === 'object') { + options = x; + x = null; + } + + x = (left = x != null ? x : options.x) != null ? left : this.x; + y = (left1 = y != null ? y : options.y) != null ? left1 : this.y; + + if (typeof src === 'string') { + image = this._imageRegistry[src]; + } + + if (!image) { + if (src.width && src.height) { + image = src; + } else { + image = this.openImage(src); + } + } + + if (!image.obj) { + image.embed(this); + } + + if (this.page.xobjects[image.label] == null) { + this.page.xobjects[image.label] = image.obj; + } + + let w = options.width || image.width; + let h = options.height || image.height; + + if (options.width && !options.height) { + const wp = w / image.width; + w = image.width * wp; + h = image.height * wp; + } else if (options.height && !options.width) { + const hp = h / image.height; + w = image.width * hp; + h = image.height * hp; + } else if (options.scale) { + w = image.width * options.scale; + h = image.height * options.scale; + } else if (options.fit) { + [bw, bh] = options.fit; + bp = bw / bh; + ip = image.width / image.height; + if (ip > bp) { + w = bw; + h = bw / ip; + } else { + h = bh; + w = bh * ip; + } + } else if (options.cover) { + [bw, bh] = options.cover; + bp = bw / bh; + ip = image.width / image.height; + if (ip > bp) { + h = bh; + w = bh * ip; + } else { + w = bw; + h = bw / ip; + } + } + + if (options.fit || options.cover) { + if (options.align === 'center') { + x = x + bw / 2 - w / 2; + } else if (options.align === 'right') { + x = x + bw - w; + } + + if (options.valign === 'center') { + y = y + bh / 2 - h / 2; + } else if (options.valign === 'bottom') { + y = y + bh - h; + } + } + + // create link annotations if the link option is given + if (options.link != null) { + this.link(x, y, w, h, options.link); + } + if (options.goTo != null) { + this.goTo(x, y, w, h, options.goTo); + } + if (options.destination != null) { + this.addNamedDestination(options.destination, 'XYZ', x, y, null); + } + + // Set the current y position to below the image if it is in the document flow + if (this.y === y) { + this.y += h; + } + + this.save(); + this.transform(w, 0, 0, -h, x, y + h); + this.addContent(`/${image.label} Do`); + this.restore(); + + return this; + }, + + openImage(src) { + let image; + if (typeof src === 'string') { + image = this._imageRegistry[src]; + } + + if (!image) { + image = PDFImage.open(src, `I${++this._imageCount}`); + if (typeof src === 'string') { + this._imageRegistry[src] = image; + } + } + + return image; + } }; - const bufferSize = 9007199254740991; - - var OutputDocument = { - - getStream() { - return this; - }, - - /** - * @returns {Promise} - */ - getBuffer() { - return new Promise((resolve, reject) => { - try { - let chunks = []; - let result; - this.getStream().on('readable', () => { - let chunk; - while ((chunk = this.getStream().read(bufferSize)) !== null) { - chunks.push(chunk); - } - }); - this.getStream().on('end', () => { - result = Buffer.concat(chunks); - resolve(result); - }); - this.getStream().end(); - } catch (e) { - reject(e); - } - }); - }, - - /** - * @returns {Promise} - */ - getBase64() { - return new Promise((resolve, reject) => { - this.getBuffer().then(buffer => { - resolve(buffer.toString('base64')); - }, result => { - reject(result); - }); - }); - }, - - /** - * @returns {Promise} - */ - getDataUrl() { - return new Promise((resolve, reject) => { - this.getBase64().then(data => { - resolve('data:application/pdf;base64,' + data); - }, result => { - reject(result); - }); - }); - }, - + const bufferSize = 9007199254740991; + + var OutputDocument = { + + getStream() { + return this; + }, + + /** + * @returns {Promise} + */ + getBuffer() { + return new Promise((resolve, reject) => { + try { + let chunks = []; + let result; + this.getStream().on('readable', () => { + let chunk; + while ((chunk = this.getStream().read(bufferSize)) !== null) { + chunks.push(chunk); + } + }); + this.getStream().on('end', () => { + result = Buffer.concat(chunks); + resolve(result); + }); + this.getStream().end(); + } catch (e) { + reject(e); + } + }); + }, + + /** + * @returns {Promise} + */ + getBase64() { + return new Promise((resolve, reject) => { + this.getBuffer().then(buffer => { + resolve(buffer.toString('base64')); + }, result => { + reject(result); + }); + }); + }, + + /** + * @returns {Promise} + */ + getDataUrl() { + return new Promise((resolve, reject) => { + this.getBase64().then(data => { + resolve('data:application/pdf;base64,' + data); + }, result => { + reject(result); + }); + }); + }, + }; var FileSaver = createCommonjsModule(function (module, exports) { @@ -25996,411 +23478,411 @@ }); }); - const bufferToBlob = buffer => { - let blob; - try { - blob = new Blob([buffer], { type: 'application/pdf' }); - } catch (e) { - // Old browser which can't handle it without making it an byte array (ie10) - if (e.name === 'InvalidStateError') { - let byteArray = new Uint8Array(buffer); - blob = new Blob([byteArray.buffer], { type: 'application/pdf' }); - } - } - - if (!blob) { - throw new Error('Could not generate blob'); - } - - return blob; - }; - - const openWindow = () => { - // we have to open the window immediately and store the reference - // otherwise popup blockers will stop us - let win = window.open('', '_blank'); - if (win === null) { - throw new Error('Open PDF in new window blocked by browser'); - } - - return win; - }; - - const OutputDocumentBrowser = Object.assign({}, OutputDocument, { - - /** - * @returns {Promise} - */ - getBlob() { - return new Promise((resolve, reject) => { - this.getBuffer().then(buffer => { - let blob = bufferToBlob(buffer); - resolve(blob); - }, result => { - reject(result); - }); - }); - }, - - /** - * @param {string} filename - * @returns {Promise} - */ - download(filename = 'file.pdf') { - return new Promise((resolve, reject) => { - this.getBlob().then(blob => { - FileSaver(blob, filename); - resolve(); - }, result => { - reject(result); - }); - }); - }, - - /** - * @param {Window} win - * @returns {Promise} - */ - open(win = null) { - return new Promise((resolve, reject) => { - if (!win) { - win = openWindow(); - } - this.getBlob().then(blob => { - try { - let urlCreator = window.URL || window.webkitURL; - let pdfUrl = urlCreator.createObjectURL(blob); - win.location.href = pdfUrl; - - // - resolve(); - /* temporarily disabled - if (win === window) { - resolve(); - } else { - setTimeout(() => { - if (win.window === null) { // is closed by AdBlock - window.location.href = pdfUrl; // open in actual window - } - resolve(); - }, 500); - } - */ - } catch (e) { - win.close(); - throw e; - } - }, result => { - reject(result); - }); - }); - }, - - /** - * @param {Window} win - * @returns {Promise} - */ - print(win = null) { - this.getStream().setOpenActionAsPrint(); - return this.open(win); - }, - + const bufferToBlob = buffer => { + let blob; + try { + blob = new Blob([buffer], { type: 'application/pdf' }); + } catch (e) { + // Old browser which can't handle it without making it an byte array (ie10) + if (e.name === 'InvalidStateError') { + let byteArray = new Uint8Array(buffer); + blob = new Blob([byteArray.buffer], { type: 'application/pdf' }); + } + } + + if (!blob) { + throw new Error('Could not generate blob'); + } + + return blob; + }; + + const openWindow = () => { + // we have to open the window immediately and store the reference + // otherwise popup blockers will stop us + let win = window.open('', '_blank'); + if (win === null) { + throw new Error('Open PDF in new window blocked by browser'); + } + + return win; + }; + + const OutputDocumentBrowser = Object.assign({}, OutputDocument, { + + /** + * @returns {Promise} + */ + getBlob() { + return new Promise((resolve, reject) => { + this.getBuffer().then(buffer => { + let blob = bufferToBlob(buffer); + resolve(blob); + }, result => { + reject(result); + }); + }); + }, + + /** + * @param {string} filename + * @returns {Promise} + */ + download(filename = 'file.pdf') { + return new Promise((resolve, reject) => { + this.getBlob().then(blob => { + FileSaver(blob, filename); + resolve(); + }, result => { + reject(result); + }); + }); + }, + + /** + * @param {Window} win + * @returns {Promise} + */ + open(win = null) { + return new Promise((resolve, reject) => { + if (!win) { + win = openWindow(); + } + this.getBlob().then(blob => { + try { + let urlCreator = window.URL || window.webkitURL; + let pdfUrl = urlCreator.createObjectURL(blob); + win.location.href = pdfUrl; + + // + resolve(); + /* temporarily disabled + if (win === window) { + resolve(); + } else { + setTimeout(() => { + if (win.window === null) { // is closed by AdBlock + window.location.href = pdfUrl; // open in actual window + } + resolve(); + }, 500); + } + */ + } catch (e) { + win.close(); + throw e; + } + }, result => { + reject(result); + }); + }); + }, + + /** + * @param {Window} win + * @returns {Promise} + */ + print(win = null) { + this.getStream().setOpenActionAsPrint(); + return this.open(win); + }, + }); - class PDFDocument extends Stream.Readable { - constructor(options = {}) { - super(options); - this.options = options; - - // PDF version - switch (options.pdfVersion) { - case '1.4': - this.version = 1.4; - break; - case '1.5': - this.version = 1.5; - break; - case '1.6': - this.version = 1.6; - break; - case '1.7': - case '1.7ext3': - this.version = 1.7; - break; - default: - this.version = 1.3; - break; - } - - // Whether streams should be compressed - this.compress = - this.options.compress != null ? this.options.compress : true; - - this._pageBuffer = []; - this._pageBufferStart = 0; - - // The PDF object store - this._offsets = []; - this._waiting = 0; - this._ended = false; - this._offset = 0; - const Pages = this.ref({ - Type: 'Pages', - Count: 0, - Kids: [] - }); - - const Names = this.ref({ - Dests: new PDFNameTree() - }); - - this._root = this.ref({ - Type: 'Catalog', - Pages, - Names - }); - - // The current page - this.page = null; - - // Initialize mixins - this.initColor(); - this.initVector(); - this.initImages(); - - // Initialize the metadata - this.info = { - Producer: 'PDFKit', - Creator: 'PDFKit', - CreationDate: new Date() - }; - - if (this.options.info) { - for (let key in this.options.info) { - const val = this.options.info[key]; - this.info[key] = val; - } - } - - // Generate file ID - this._id = PDFSecurity.generateFileID(this.info); - - // Initialize security settings - this._security = PDFSecurity.create(this, options); - - // Write the header - // PDF version - this._write(`%PDF-${this.version}`); - - // 4 binary chars, as recommended by the spec - this._write('%\xFF\xFF\xFF\xFF'); - - // Add the first page - if (this.options.autoFirstPage !== false) { - this.addPage(); - } - } - - addPage(options) { - // end the current page if needed - if (options == null) { - ({ options } = this); - } - if (!this.options.bufferPages) { - this.flushPages(); - } - - // create a page object - this.page = new PDFPage(this, options); - this._pageBuffer.push(this.page); - - // add the page to the object store - const pages = this._root.data.Pages.data; - pages.Kids.push(this.page.dictionary); - pages.Count++; - - // reset x and y coordinates - this.x = this.page.margins.left; - this.y = this.page.margins.top; - - // flip PDF coordinate system so that the origin is in - // the top left rather than the bottom left - this._ctm = [1, 0, 0, 1, 0, 0]; - this.transform(1, 0, 0, -1, 0, this.page.height); - - this.emit('pageAdded'); - - return this; - } - - bufferedPageRange() { - return { start: this._pageBufferStart, count: this._pageBuffer.length }; - } - - switchToPage(n) { - let page; - if (!(page = this._pageBuffer[n - this._pageBufferStart])) { - throw new Error( - `switchToPage(${n}) out of bounds, current buffer covers pages ${ - this._pageBufferStart - } to ${this._pageBufferStart + this._pageBuffer.length - 1}` - ); - } - - return (this.page = page); - } - - flushPages() { - // this local variable exists so we're future-proof against - // reentrant calls to flushPages. - const pages = this._pageBuffer; - this._pageBuffer = []; - this._pageBufferStart += pages.length; - for (let page of pages) { - page.end(); - } - } - - addNamedDestination(name, ...args) { - if (args.length === 0) { - args = ['XYZ', null, null, null]; - } - if (args[0] === 'XYZ' && args[2] !== null) { - args[2] = this.page.height - args[2]; - } - args.unshift(this.page.dictionary); - this._root.data.Names.data.Dests.add(name, args); - } - - ref(data) { - const ref = new PDFReference(this, this._offsets.length + 1, data); - this._offsets.push(null); // placeholder for this object's offset once it is finalized - this._waiting++; - return ref; - } - - _read() {} - // do nothing, but this method is required by node - - _write(data) { - if (!isBuffer(data)) { - data = new Buffer(data + '\n', 'binary'); - } - - this.push(data); - return (this._offset += data.length); - } - - addContent(data) { - this.page.write(data); - return this; - } - - _refEnd(ref) { - this._offsets[ref.id - 1] = ref.offset; - if (--this._waiting === 0 && this._ended) { - this._finalize(); - return (this._ended = false); - } - } - - write(filename, fn) { - // print a deprecation warning with a stacktrace - const err = new Error(`\ -PDFDocument#write is deprecated, and will be removed in a future version of PDFKit. \ -Please pipe the document into a Node stream.\ -`); - - console.warn(err.stack); - - this.pipe(fs.createWriteStream(filename)); - this.end(); - return this.once('end', fn); - } - - end() { - this.flushPages(); - this._info = this.ref(); - for (let key in this.info) { - let val = this.info[key]; - if (typeof val === 'string') { - val = new String(val); - } - - let entry = this.ref(val); - entry.end(); - - this._info.data[key] = entry; - } - - this._info.end(); - - for (let name in this._fontFamilies) { - const font = this._fontFamilies[name]; - font.finalize(); - } - - this._root.end(); - this._root.data.Pages.end(); - this._root.data.Names.end(); - - if (this._security) { - this._security.end(); - } - - if (this._waiting === 0) { - return this._finalize(); - } else { - return (this._ended = true); - } - } - - _finalize(fn) { - // generate xref - const xRefOffset = this._offset; - this._write('xref'); - this._write(`0 ${this._offsets.length + 1}`); - this._write('0000000000 65535 f '); - - for (let offset of this._offsets) { - offset = `0000000000${offset}`.slice(-10); - this._write(offset + ' 00000 n '); - } - - // trailer - const trailer = { - Size: this._offsets.length + 1, - Root: this._root, - Info: this._info, - ID: [this._id, this._id] - }; - if (this._security) { - trailer.Encrypt = this._security.dictionary; - } - - this._write('trailer'); - this._write(PDFObject.convert(trailer)); - - this._write('startxref'); - this._write(`${xRefOffset}`); - this._write('%%EOF'); - - // end the stream - return this.push(null); - } - - toString() { - return '[object PDFDocument]'; - } - } - - const mixin = methods => { - Object.assign(PDFDocument.prototype, methods); - }; - - mixin(ColorMixin); - mixin(VectorMixin); - mixin(ImagesMixin); + class PDFDocument extends Stream.Readable { + constructor(options = {}) { + super(options); + this.options = options; + + // PDF version + switch (options.pdfVersion) { + case '1.4': + this.version = 1.4; + break; + case '1.5': + this.version = 1.5; + break; + case '1.6': + this.version = 1.6; + break; + case '1.7': + case '1.7ext3': + this.version = 1.7; + break; + default: + this.version = 1.3; + break; + } + + // Whether streams should be compressed + this.compress = + this.options.compress != null ? this.options.compress : true; + + this._pageBuffer = []; + this._pageBufferStart = 0; + + // The PDF object store + this._offsets = []; + this._waiting = 0; + this._ended = false; + this._offset = 0; + const Pages = this.ref({ + Type: 'Pages', + Count: 0, + Kids: [] + }); + + const Names = this.ref({ + Dests: new PDFNameTree() + }); + + this._root = this.ref({ + Type: 'Catalog', + Pages, + Names + }); + + // The current page + this.page = null; + + // Initialize mixins + this.initColor(); + this.initVector(); + this.initImages(); + + // Initialize the metadata + this.info = { + Producer: 'PDFKit', + Creator: 'PDFKit', + CreationDate: new Date() + }; + + if (this.options.info) { + for (let key in this.options.info) { + const val = this.options.info[key]; + this.info[key] = val; + } + } + + // Generate file ID + this._id = PDFSecurity.generateFileID(this.info); + + // Initialize security settings + this._security = PDFSecurity.create(this, options); + + // Write the header + // PDF version + this._write(`%PDF-${this.version}`); + + // 4 binary chars, as recommended by the spec + this._write('%\xFF\xFF\xFF\xFF'); + + // Add the first page + if (this.options.autoFirstPage !== false) { + this.addPage(); + } + } + + addPage(options) { + // end the current page if needed + if (options == null) { + ({ options } = this); + } + if (!this.options.bufferPages) { + this.flushPages(); + } + + // create a page object + this.page = new PDFPage(this, options); + this._pageBuffer.push(this.page); + + // add the page to the object store + const pages = this._root.data.Pages.data; + pages.Kids.push(this.page.dictionary); + pages.Count++; + + // reset x and y coordinates + this.x = this.page.margins.left; + this.y = this.page.margins.top; + + // flip PDF coordinate system so that the origin is in + // the top left rather than the bottom left + this._ctm = [1, 0, 0, 1, 0, 0]; + this.transform(1, 0, 0, -1, 0, this.page.height); + + this.emit('pageAdded'); + + return this; + } + + bufferedPageRange() { + return { start: this._pageBufferStart, count: this._pageBuffer.length }; + } + + switchToPage(n) { + let page; + if (!(page = this._pageBuffer[n - this._pageBufferStart])) { + throw new Error( + `switchToPage(${n}) out of bounds, current buffer covers pages ${ + this._pageBufferStart + } to ${this._pageBufferStart + this._pageBuffer.length - 1}` + ); + } + + return (this.page = page); + } + + flushPages() { + // this local variable exists so we're future-proof against + // reentrant calls to flushPages. + const pages = this._pageBuffer; + this._pageBuffer = []; + this._pageBufferStart += pages.length; + for (let page of pages) { + page.end(); + } + } + + addNamedDestination(name, ...args) { + if (args.length === 0) { + args = ['XYZ', null, null, null]; + } + if (args[0] === 'XYZ' && args[2] !== null) { + args[2] = this.page.height - args[2]; + } + args.unshift(this.page.dictionary); + this._root.data.Names.data.Dests.add(name, args); + } + + ref(data) { + const ref = new PDFReference(this, this._offsets.length + 1, data); + this._offsets.push(null); // placeholder for this object's offset once it is finalized + this._waiting++; + return ref; + } + + _read() {} + // do nothing, but this method is required by node + + _write(data) { + if (!isBuffer(data)) { + data = new Buffer(data + '\n', 'binary'); + } + + this.push(data); + return (this._offset += data.length); + } + + addContent(data) { + this.page.write(data); + return this; + } + + _refEnd(ref) { + this._offsets[ref.id - 1] = ref.offset; + if (--this._waiting === 0 && this._ended) { + this._finalize(); + return (this._ended = false); + } + } + + write(filename, fn) { + // print a deprecation warning with a stacktrace + const err = new Error(`\ +PDFDocument#write is deprecated, and will be removed in a future version of PDFKit. \ +Please pipe the document into a Node stream.\ +`); + + console.warn(err.stack); + + this.pipe(fs.createWriteStream(filename)); + this.end(); + return this.once('end', fn); + } + + end() { + this.flushPages(); + this._info = this.ref(); + for (let key in this.info) { + let val = this.info[key]; + if (typeof val === 'string') { + val = new String(val); + } + + let entry = this.ref(val); + entry.end(); + + this._info.data[key] = entry; + } + + this._info.end(); + + for (let name in this._fontFamilies) { + const font = this._fontFamilies[name]; + font.finalize(); + } + + this._root.end(); + this._root.data.Pages.end(); + this._root.data.Names.end(); + + if (this._security) { + this._security.end(); + } + + if (this._waiting === 0) { + return this._finalize(); + } else { + return (this._ended = true); + } + } + + _finalize(fn) { + // generate xref + const xRefOffset = this._offset; + this._write('xref'); + this._write(`0 ${this._offsets.length + 1}`); + this._write('0000000000 65535 f '); + + for (let offset of this._offsets) { + offset = `0000000000${offset}`.slice(-10); + this._write(offset + ' 00000 n '); + } + + // trailer + const trailer = { + Size: this._offsets.length + 1, + Root: this._root, + Info: this._info, + ID: [this._id, this._id] + }; + if (this._security) { + trailer.Encrypt = this._security.dictionary; + } + + this._write('trailer'); + this._write(PDFObject.convert(trailer)); + + this._write('startxref'); + this._write(`${xRefOffset}`); + this._write('%%EOF'); + + // end the stream + return this.push(null); + } + + toString() { + return '[object PDFDocument]'; + } + } + + const mixin = methods => { + Object.assign(PDFDocument.prototype, methods); + }; + + mixin(ColorMixin); + mixin(VectorMixin); + mixin(ImagesMixin); mixin(OutputDocumentBrowser); var source = createCommonjsModule(function (module) { @@ -29252,7 +26734,7 @@ Please pipe the document into a Node stream.\ // read further error msg const err = cidRes.Message; if (err.includes('no link named')) { // file not found - throw new Error('Score not in dataset'); + throw new Error('score not in dataset'); } else { throw new Error(err); @@ -29418,7 +26900,7 @@ Please pipe the document into a Node stream.\ // detect browser language const lang = (() => { let userLangs; - if (!C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_detectNode) { + if (!detectNode) { userLangs = navigator.languages; } else { @@ -29457,7 +26939,7 @@ Please pipe the document into a Node stream.\ const SF3_URL = `https://cdn.jsdelivr.net/npm/@librescore/sf3@${dependencies['@librescore/sf3']}/FluidR3Mono_GM.sf3`; const SOUND_FONT_LOADED = Symbol('SoundFont loaded'); const initMscore = (w) => __awaiter(void 0, void 0, void 0, function* () { - if (!C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_detectNode) { // attached to a page + if (!detectNode) { // attached to a page if (!w['WebMscore']) { // init webmscore (https://github.com/LibreScore/webmscore) const script = w.document.createElement('script'); @@ -29476,7 +26958,7 @@ Please pipe the document into a Node stream.\ // load CJK fonts // CJK (East Asian) characters will be rendered as "tofu" if there is no font if (!fonts) { - if (C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_detectNode) { + if (detectNode) { // module.exports.CN = ..., module.exports.KR = ... const FONTS = Object.values(require('@librescore/fonts')); const fs = require('fs'); @@ -29491,7 +26973,7 @@ Please pipe the document into a Node stream.\ if (!score[SOUND_FONT_LOADED]) { const loadPromise = (() => __awaiter(void 0, void 0, void 0, function* () { let data; - if (C__Users_peter_Documents_source_repos_musescoreDownloader_node_modules_detectNode) { + if (detectNode) { // module.exports.FluidR3Mono = ... const SF3 = Object.values(require('@librescore/sf3'))[0]; const fs = require('fs'); @@ -29556,7 +27038,7 @@ Please pipe the document into a Node stream.\ const _getLink = (scorepack) => { return `https://librescore.org/score/${scorepack}`; }; - const getLibreScoreLink = (scoreinfo, isMsdl, _fetch = getFetch()) => __awaiter(void 0, void 0, void 0, function* () { + const getLibreScoreLink = (scoreinfo, _fetch = getFetch()) => __awaiter(void 0, void 0, void 0, function* () { const mainCid = yield getMainCid(scoreinfo, _fetch); const ref = scoreinfo.getScorepackRef(mainCid); const url = `https://ipfs.infura.io:5001/api/v0/dag/get?arg=${ref}`; @@ -29565,14 +27047,14 @@ Please pipe the document into a Node stream.\ assertRes(r0); } const res = yield r0.json(); - if (typeof res !== 'string' && !isMsdl) { + if (typeof res !== 'string') { // read further error msg throw new Error(res.Message); } return _getLink(res); }); - var btnListCss = "div {\r\n width: 422px;\r\n right: 0;\r\n margin: 0 18px 18px 0;\r\n\r\n text-align: center;\r\n align-items: center;\r\n font-family: 'Open Sans', 'Roboto', 'Helvetica neue', Helvetica, sans-serif;\r\n position: absolute;\r\n z-index: 9999;\r\n background: #f6f6f6;\r\n min-width: 230px;\r\n\r\n /* pass the scroll event through the btns background */\r\n pointer-events: none;\r\n}\r\n\r\n@media screen and (max-width: 950px) {\r\n div {\r\n width: auto !important;\r\n }\r\n}\r\n\r\nbutton {\r\n width: 205px !important;\r\n min-width: 205px;\r\n height: 38px;\r\n\r\n color: #fff;\r\n background: #1f74bd;\r\n\r\n cursor: pointer;\r\n pointer-events: auto;\r\n\r\n margin-bottom: 4px;\r\n margin-right: 4px;\r\n padding: 4px 12px;\r\n\r\n justify-content: start;\r\n align-self: center;\r\n\r\n font-size: 16px;\r\n border-radius: 2px;\r\n border: 0;\r\n\r\n display: inline-flex;\r\n position: relative;\r\n\r\n font-family: inherit;\r\n}\r\n\r\n/* fix `View in LibreScore` button text overflow */\r\nbutton:last-of-type {\r\n width: unset !important;\r\n}\r\n\r\nsvg {\r\n display: inline-block;\r\n margin-right: 5px;\r\n width: 20px;\r\n height: 20px;\r\n margin-top: auto;\r\n margin-bottom: auto;\r\n}\r\n\r\nspan {\r\n margin-top: auto;\r\n margin-bottom: auto;\r\n}"; + var btnListCss = "div {\n width: 422px;\n right: 0;\n margin: 0 18px 18px 0;\n\n text-align: center;\n align-items: center;\n font-family: 'Open Sans', 'Roboto', 'Helvetica neue', Helvetica, sans-serif;\n position: absolute;\n z-index: 9999;\n background: #f6f6f6;\n min-width: 230px;\n\n /* pass the scroll event through the btns background */\n pointer-events: none;\n}\n\n@media screen and (max-width: 950px) {\n div {\n width: auto !important;\n }\n}\n\nbutton {\n width: 205px !important;\n min-width: 205px;\n height: 38px;\n\n color: #fff;\n background: #1f74bd;\n\n cursor: pointer;\n pointer-events: auto;\n\n margin-bottom: 4px;\n margin-right: 4px;\n padding: 4px 12px;\n\n justify-content: start;\n align-self: center;\n\n font-size: 16px;\n border-radius: 2px;\n border: 0;\n\n display: inline-flex;\n position: relative;\n\n font-family: inherit;\n}\n\n/* fix `View in LibreScore` button text overflow */\nbutton:last-of-type {\n width: unset !important;\n}\n\nsvg {\n display: inline-block;\n margin-right: 5px;\n width: 20px;\n height: 20px;\n margin-top: auto;\n margin-bottom: auto;\n}\n\nspan {\n margin-top: auto;\n margin-bottom: auto;\n}"; var ICON; (function (ICON) {