pdfkit 0.19.1 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/.yarn/install-state.gz +0 -0
  2. package/CHANGELOG.md +25 -0
  3. package/README.md +97 -25
  4. package/js/output.cjs +53 -0
  5. package/js/output.mjs +50 -0
  6. package/js/pdfkit.browser.js +7524 -0
  7. package/js/pdfkit.browser.js.map +1 -0
  8. package/js/pdfkit.browser.mjs +7344 -0
  9. package/js/pdfkit.browser.mjs.map +1 -0
  10. package/js/pdfkit.browser.old.js +7517 -0
  11. package/js/pdfkit.browser.old.mjs +7342 -0
  12. package/js/pdfkit.js +1419 -487
  13. package/js/pdfkit.js.map +1 -1
  14. package/js/{pdfkit.es.js → pdfkit.node.mjs} +1410 -488
  15. package/js/pdfkit.node.mjs.map +1 -0
  16. package/js/pdfkit.old.js +7276 -0
  17. package/js/pdfkit.standalone.js +23432 -35943
  18. package/js/standard-fonts/Courier.cjs +17 -0
  19. package/js/standard-fonts/Courier.mjs +15 -0
  20. package/js/standard-fonts/CourierBold.cjs +17 -0
  21. package/js/standard-fonts/CourierBold.mjs +15 -0
  22. package/js/standard-fonts/CourierBoldOblique.cjs +17 -0
  23. package/js/standard-fonts/CourierBoldOblique.mjs +15 -0
  24. package/js/standard-fonts/CourierOblique.cjs +17 -0
  25. package/js/standard-fonts/CourierOblique.mjs +15 -0
  26. package/js/standard-fonts/Helvetica.cjs +17 -0
  27. package/js/standard-fonts/Helvetica.mjs +15 -0
  28. package/js/standard-fonts/HelveticaBold.cjs +17 -0
  29. package/js/standard-fonts/HelveticaBold.mjs +15 -0
  30. package/js/standard-fonts/HelveticaBoldOblique.cjs +17 -0
  31. package/js/standard-fonts/HelveticaBoldOblique.mjs +15 -0
  32. package/js/standard-fonts/HelveticaOblique.cjs +17 -0
  33. package/js/standard-fonts/HelveticaOblique.mjs +15 -0
  34. package/js/standard-fonts/Symbol.cjs +15 -0
  35. package/js/standard-fonts/Symbol.mjs +13 -0
  36. package/js/standard-fonts/TimesBold.cjs +17 -0
  37. package/js/standard-fonts/TimesBold.mjs +15 -0
  38. package/js/standard-fonts/TimesBoldItalic.cjs +17 -0
  39. package/js/standard-fonts/TimesBoldItalic.mjs +15 -0
  40. package/js/standard-fonts/TimesItalic.cjs +17 -0
  41. package/js/standard-fonts/TimesItalic.mjs +15 -0
  42. package/js/standard-fonts/TimesRoman.cjs +17 -0
  43. package/js/standard-fonts/TimesRoman.mjs +15 -0
  44. package/js/standard-fonts/ZapfDingbats.cjs +15 -0
  45. package/js/standard-fonts/ZapfDingbats.mjs +13 -0
  46. package/js/standard-fonts/chunks/standardGlyphNames-DNHAb7rp.cjs +5 -0
  47. package/js/standard-fonts/chunks/standardGlyphNames-w3QlG7PW.mjs +3 -0
  48. package/package.json +110 -28
  49. package/rollup.config.mjs +126 -57
  50. package/tools/README.md +124 -0
  51. package/tools/afm-converter.js +317 -0
  52. package/tools/asset-plugin.mjs +17 -0
  53. package/tools/binary-plugin.mjs +18 -0
  54. package/tools/convert-afm-parsed.js +8 -0
  55. package/tools/convert-afm-runtime.js +8 -0
  56. package/vitest.config.js +2 -0
  57. package/js/pdfkit.es.js.map +0 -1
  58. package/js/virtual-fs.js +0 -49
package/js/pdfkit.js CHANGED
@@ -1,16 +1,20 @@
1
1
  'use strict';
2
2
 
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var module$1 = require('module');
3
6
  var stream = require('stream');
4
- var zlib = require('zlib');
5
7
  var utils = require('@noble/hashes/utils');
6
- var md5 = require('js-md5');
7
- var sha2 = require('@noble/hashes/sha2');
8
+ var zlib$1 = require('zlib');
8
9
  var aes = require('@noble/ciphers/aes');
9
- var fs = require('fs');
10
+ var fs$1 = require('fs');
10
11
  var fontkit = require('fontkit');
11
12
  var LineBreaker = require('linebreak');
12
13
  var PNG = require('png-js');
13
14
 
15
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
16
+ var Readable = stream.Readable;
17
+
14
18
  class PDFAbstractReference {
15
19
  toString() {
16
20
  throw new Error('Must be implemented by subclasses');
@@ -28,17 +32,17 @@ class PDFTree {
28
32
  get(key) {
29
33
  return this._items[key];
30
34
  }
31
- toString() {
35
+ toString(encryptFn = null) {
32
36
  const sortedKeys = Object.keys(this._items).sort((a, b) => this._compareKeys(a, b));
33
37
  const out = ['<<'];
34
38
  if (this.limits && sortedKeys.length > 1) {
35
39
  const first = sortedKeys[0],
36
40
  last = sortedKeys[sortedKeys.length - 1];
37
- out.push(` /Limits ${PDFObject.convert([this._dataForKey(first), this._dataForKey(last)])}`);
41
+ out.push(` /Limits ${PDFObject.convert([this._dataForKey(first), this._dataForKey(last)], encryptFn)}`);
38
42
  }
39
43
  out.push(` /${this._keysName()} [`);
40
44
  for (let key of sortedKeys) {
41
- out.push(` ${PDFObject.convert(this._dataForKey(key))} ${PDFObject.convert(this._items[key])}`);
45
+ out.push(` ${PDFObject.convert(this._dataForKey(key), encryptFn)} ${PDFObject.convert(this._items[key], encryptFn)}`);
42
46
  }
43
47
  out.push(']');
44
48
  out.push('>>');
@@ -75,6 +79,57 @@ class SpotColor {
75
79
  }
76
80
  }
77
81
 
82
+ const toBinaryString = bytes => {
83
+ const chunkSize = 0x8000;
84
+ let out = '';
85
+ for (let i = 0; i < bytes.length; i += chunkSize) {
86
+ const end = Math.min(i + chunkSize, bytes.length);
87
+ out += String.fromCharCode.apply(null, bytes.subarray(i, end));
88
+ }
89
+ return out;
90
+ };
91
+ const fromBinaryString = str => {
92
+ const out = new Uint8Array(str.length);
93
+ for (let i = 0; i < str.length; i++) {
94
+ out[i] = str.charCodeAt(i) & 0xff;
95
+ }
96
+ return out;
97
+ };
98
+ const fromBase64 = b64 => {
99
+ const binary = atob(b64);
100
+ const out = new Uint8Array(binary.length);
101
+ for (let i = 0; i < binary.length; i++) {
102
+ out[i] = binary.charCodeAt(i);
103
+ }
104
+ return out;
105
+ };
106
+ const concat = chunks => {
107
+ let length = 0;
108
+ for (const chunk of chunks) length += chunk.length;
109
+ const out = new Uint8Array(length);
110
+ let offset = 0;
111
+ for (const chunk of chunks) {
112
+ out.set(chunk, offset);
113
+ offset += chunk.length;
114
+ }
115
+ return out;
116
+ };
117
+ const toUTF16BE = str => {
118
+ const out = new Uint8Array((str.length + 1) * 2);
119
+ out[0] = 0xfe;
120
+ out[1] = 0xff;
121
+ for (let i = 0; i < str.length; i++) {
122
+ const code = str.charCodeAt(i);
123
+ out[i * 2 + 2] = code >> 8;
124
+ out[i * 2 + 3] = code & 0xff;
125
+ }
126
+ return out;
127
+ };
128
+ const readUInt16BE = (bytes, offset = 0) => (bytes[offset] << 8 | bytes[offset + 1]) >>> 0;
129
+ const readUInt16LE = (bytes, offset = 0) => (bytes[offset + 1] << 8 | bytes[offset]) >>> 0;
130
+ const readUInt32BE = (bytes, offset = 0) => bytes[offset] * 0x1000000 + (bytes[offset + 1] << 16 | bytes[offset + 2] << 8 | bytes[offset + 3]) >>> 0;
131
+ const readUInt32LE = (bytes, offset = 0) => (bytes[offset] | bytes[offset + 1] << 8 | bytes[offset + 2] << 16) + bytes[offset + 3] * 0x1000000 >>> 0;
132
+
78
133
  const pad = (str, length) => (Array(length + 1).join('0') + str).slice(-length);
79
134
  const isSafeCharCode = code => {
80
135
  if (code > 0x7f) return true;
@@ -103,19 +158,6 @@ const escapeName = function (name) {
103
158
  }
104
159
  return escapedName;
105
160
  };
106
- const swapBytes = function (buff) {
107
- const l = buff.length;
108
- if (l & 0x01) {
109
- throw new Error('Buffer length must be even');
110
- } else {
111
- for (let i = 0, end = l - 1; i < end; i += 2) {
112
- const a = buff[i];
113
- buff[i] = buff[i + 1];
114
- buff[i + 1] = a;
115
- }
116
- }
117
- return buff;
118
- };
119
161
  class PDFObject {
120
162
  static convert(object, encryptFn = null) {
121
163
  if (typeof object === 'string') {
@@ -129,37 +171,43 @@ class PDFObject {
129
171
  break;
130
172
  }
131
173
  }
132
- let stringBuffer;
174
+ let stringBytes;
133
175
  if (isUnicode) {
134
- stringBuffer = swapBytes(Buffer.from(`\ufeff${string}`, 'utf16le'));
176
+ stringBytes = toUTF16BE(string.valueOf());
135
177
  } else {
136
- stringBuffer = Buffer.from(string.valueOf(), 'ascii');
178
+ stringBytes = fromBinaryString(string.valueOf());
137
179
  }
138
180
  if (encryptFn) {
139
- string = encryptFn(stringBuffer).toString('binary');
140
- } else {
141
- string = stringBuffer.toString('binary');
181
+ stringBytes = encryptFn(stringBytes);
142
182
  }
183
+ string = toBinaryString(stringBytes);
143
184
  string = string.replace(escapableRe, c => escapable[c]);
144
185
  return `(${string})`;
145
- } else if (Buffer.isBuffer(object)) {
146
- return `<${object.toString('hex')}>`;
147
- } else if (object instanceof PDFAbstractReference || object instanceof PDFTree || object instanceof SpotColor) {
186
+ } else if (object instanceof Uint8Array) {
187
+ return `<${utils.bytesToHex(object)}>`;
188
+ } else if (object instanceof PDFTree) {
189
+ return object.toString(encryptFn);
190
+ } else if (object instanceof PDFAbstractReference || object instanceof SpotColor) {
148
191
  return object.toString();
149
192
  } else if (object instanceof Date) {
150
193
  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';
151
194
  if (encryptFn) {
152
- string = encryptFn(Buffer.from(string, 'ascii')).toString('binary');
195
+ string = toBinaryString(encryptFn(fromBinaryString(string)));
153
196
  string = string.replace(escapableRe, c => escapable[c]);
154
197
  }
155
198
  return `(${string})`;
156
199
  } else if (Array.isArray(object)) {
157
- const items = object.map(e => PDFObject.convert(e, encryptFn)).join(' ');
158
- return `[${items}]`;
200
+ const items = [];
201
+ for (let i = 0; i < object.length; i++) {
202
+ const e = object[i];
203
+ items.push(PDFObject.convert(e === undefined ? null : e, encryptFn));
204
+ }
205
+ return `[${items.join(' ')}]`;
159
206
  } else if ({}.toString.call(object) === '[object Object]') {
160
207
  const out = ['<<'];
161
208
  for (let key in object) {
162
209
  const val = object[key];
210
+ if (val === undefined) continue;
163
211
  out.push(`/${key} ${PDFObject.convert(val, encryptFn)}`);
164
212
  }
165
213
  out.push('>>');
@@ -178,6 +226,10 @@ class PDFObject {
178
226
  }
179
227
  }
180
228
 
229
+ var zlib = {
230
+ deflateSync: data => zlib$1.deflateSync(data)
231
+ };
232
+
181
233
  class PDFReference extends PDFAbstractReference {
182
234
  constructor(document, id, data = {}) {
183
235
  super();
@@ -191,7 +243,7 @@ class PDFReference extends PDFAbstractReference {
191
243
  }
192
244
  write(chunk) {
193
245
  if (!(chunk instanceof Uint8Array)) {
194
- chunk = Buffer.from(chunk + '\n', 'binary');
246
+ chunk = fromBinaryString(chunk + '\n');
195
247
  }
196
248
  this.uncompressedLength += chunk.length;
197
249
  if (this.data.Length == null) {
@@ -213,7 +265,7 @@ class PDFReference extends PDFAbstractReference {
213
265
  this.offset = this.document._offset;
214
266
  const encryptFn = this.document._security ? this.document._security.getEncryptFn(this.id, this.gen) : null;
215
267
  if (this.buffer.length) {
216
- this.buffer = Buffer.concat(this.buffer);
268
+ this.buffer = concat(this.buffer);
217
269
  if (this.compress) {
218
270
  this.buffer = zlib.deflateSync(this.buffer);
219
271
  }
@@ -371,7 +423,7 @@ const SIZES = {
371
423
  TABLOID: [792.0, 1224.0]
372
424
  };
373
425
  class PDFPage {
374
- constructor(document, options = {}) {
426
+ constructor(document, options) {
375
427
  this.document = document;
376
428
  this._options = options;
377
429
  this.size = options.size || 'letter';
@@ -381,8 +433,6 @@ class PDFPage {
381
433
  this.width = dimensions[this.layout === 'portrait' ? 0 : 1];
382
434
  this.height = dimensions[this.layout === 'portrait' ? 1 : 0];
383
435
  this.content = this.document.ref();
384
- if (options.font) document.font(options.font, options.fontFamily);
385
- if (options.fontSize) document.fontSize(options.fontSize);
386
436
  this.margins = normalizeSides(options.margin ?? options.margins, DEFAULT_MARGINS, x => document.sizeToPoint(x, 0, this));
387
437
  this.resources = this.document.ref({
388
438
  ProcSet: ['PDF', 'Text', 'ImageB', 'ImageC', 'ImageI']
@@ -466,15 +516,837 @@ class PDFNameTree extends PDFTree {
466
516
  }
467
517
  }
468
518
 
519
+ function isBytes(a) {
520
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array';
521
+ }
522
+ function abytes(b, ...lengths) {
523
+ if (!isBytes(b)) throw new Error('Uint8Array expected');
524
+ if (lengths.length > 0 && !lengths.includes(b.length)) throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
525
+ }
526
+ function aexists(instance, checkFinished = true) {
527
+ if (instance.destroyed) throw new Error('Hash instance has been destroyed');
528
+ if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');
529
+ }
530
+ function aoutput(out, instance) {
531
+ abytes(out);
532
+ const min = instance.outputLen;
533
+ if (out.length < min) {
534
+ throw new Error('digestInto() expects output buffer of length at least ' + min);
535
+ }
536
+ }
537
+ function clean(...arrays) {
538
+ for (let i = 0; i < arrays.length; i++) {
539
+ arrays[i].fill(0);
540
+ }
541
+ }
542
+ function createView(arr) {
543
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
544
+ }
545
+ function rotr(word, shift) {
546
+ return word << 32 - shift | word >>> shift;
547
+ }
548
+ function rotl(word, shift) {
549
+ return word << shift | word >>> 32 - shift >>> 0;
550
+ }
551
+ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
552
+ (() => typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
553
+ Array.from({
554
+ length: 256
555
+ }, (_, i) => i.toString(16).padStart(2, '0'));
556
+ function utf8ToBytes(str) {
557
+ if (typeof str !== 'string') throw new Error('string expected');
558
+ return new Uint8Array(new TextEncoder().encode(str));
559
+ }
560
+ function toBytes(data) {
561
+ if (typeof data === 'string') data = utf8ToBytes(data);
562
+ abytes(data);
563
+ return data;
564
+ }
565
+ class Hash {}
566
+ function createHasher(hashCons) {
567
+ const hashC = msg => hashCons().update(toBytes(msg)).digest();
568
+ const tmp = hashCons();
569
+ hashC.outputLen = tmp.outputLen;
570
+ hashC.blockLen = tmp.blockLen;
571
+ hashC.create = () => hashCons();
572
+ return hashC;
573
+ }
574
+
575
+ function setBigUint64(view, byteOffset, value, isLE) {
576
+ if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);
577
+ const _32n = BigInt(32);
578
+ const _u32_max = BigInt(0xffffffff);
579
+ const wh = Number(value >> _32n & _u32_max);
580
+ const wl = Number(value & _u32_max);
581
+ const h = isLE ? 4 : 0;
582
+ const l = isLE ? 0 : 4;
583
+ view.setUint32(byteOffset + h, wh, isLE);
584
+ view.setUint32(byteOffset + l, wl, isLE);
585
+ }
586
+ function Chi(a, b, c) {
587
+ return a & b ^ ~a & c;
588
+ }
589
+ function Maj(a, b, c) {
590
+ return a & b ^ a & c ^ b & c;
591
+ }
592
+ class HashMD extends Hash {
593
+ constructor(blockLen, outputLen, padOffset, isLE) {
594
+ super();
595
+ this.finished = false;
596
+ this.length = 0;
597
+ this.pos = 0;
598
+ this.destroyed = false;
599
+ this.blockLen = blockLen;
600
+ this.outputLen = outputLen;
601
+ this.padOffset = padOffset;
602
+ this.isLE = isLE;
603
+ this.buffer = new Uint8Array(blockLen);
604
+ this.view = createView(this.buffer);
605
+ }
606
+ update(data) {
607
+ aexists(this);
608
+ data = toBytes(data);
609
+ abytes(data);
610
+ const {
611
+ view,
612
+ buffer,
613
+ blockLen
614
+ } = this;
615
+ const len = data.length;
616
+ for (let pos = 0; pos < len;) {
617
+ const take = Math.min(blockLen - this.pos, len - pos);
618
+ if (take === blockLen) {
619
+ const dataView = createView(data);
620
+ for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
621
+ continue;
622
+ }
623
+ buffer.set(data.subarray(pos, pos + take), this.pos);
624
+ this.pos += take;
625
+ pos += take;
626
+ if (this.pos === blockLen) {
627
+ this.process(view, 0);
628
+ this.pos = 0;
629
+ }
630
+ }
631
+ this.length += data.length;
632
+ this.roundClean();
633
+ return this;
634
+ }
635
+ digestInto(out) {
636
+ aexists(this);
637
+ aoutput(out, this);
638
+ this.finished = true;
639
+ const {
640
+ buffer,
641
+ view,
642
+ blockLen,
643
+ isLE
644
+ } = this;
645
+ let {
646
+ pos
647
+ } = this;
648
+ buffer[pos++] = 0b10000000;
649
+ clean(this.buffer.subarray(pos));
650
+ if (this.padOffset > blockLen - pos) {
651
+ this.process(view, 0);
652
+ pos = 0;
653
+ }
654
+ for (let i = pos; i < blockLen; i++) buffer[i] = 0;
655
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
656
+ this.process(view, 0);
657
+ const oview = createView(out);
658
+ const len = this.outputLen;
659
+ if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');
660
+ const outLen = len / 4;
661
+ const state = this.get();
662
+ if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');
663
+ for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);
664
+ }
665
+ digest() {
666
+ const {
667
+ buffer,
668
+ outputLen
669
+ } = this;
670
+ this.digestInto(buffer);
671
+ const res = buffer.slice(0, outputLen);
672
+ this.destroy();
673
+ return res;
674
+ }
675
+ _cloneInto(to) {
676
+ to || (to = new this.constructor());
677
+ to.set(...this.get());
678
+ const {
679
+ blockLen,
680
+ buffer,
681
+ length,
682
+ finished,
683
+ destroyed,
684
+ pos
685
+ } = this;
686
+ to.destroyed = destroyed;
687
+ to.finished = finished;
688
+ to.length = length;
689
+ to.pos = pos;
690
+ if (length % blockLen) to.buffer.set(buffer);
691
+ return to;
692
+ }
693
+ clone() {
694
+ return this._cloneInto();
695
+ }
696
+ }
697
+ const SHA256_IV = Uint32Array.from([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);
698
+ const SHA224_IV = Uint32Array.from([0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4]);
699
+ const SHA384_IV = Uint32Array.from([0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939, 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4]);
700
+ const SHA512_IV = Uint32Array.from([0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1, 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179]);
701
+
702
+ const SHA1_IV = Uint32Array.from([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]);
703
+ const SHA1_W = new Uint32Array(80);
704
+ class SHA1 extends HashMD {
705
+ constructor() {
706
+ super(64, 20, 8, false);
707
+ this.A = SHA1_IV[0] | 0;
708
+ this.B = SHA1_IV[1] | 0;
709
+ this.C = SHA1_IV[2] | 0;
710
+ this.D = SHA1_IV[3] | 0;
711
+ this.E = SHA1_IV[4] | 0;
712
+ }
713
+ get() {
714
+ const {
715
+ A,
716
+ B,
717
+ C,
718
+ D,
719
+ E
720
+ } = this;
721
+ return [A, B, C, D, E];
722
+ }
723
+ set(A, B, C, D, E) {
724
+ this.A = A | 0;
725
+ this.B = B | 0;
726
+ this.C = C | 0;
727
+ this.D = D | 0;
728
+ this.E = E | 0;
729
+ }
730
+ process(view, offset) {
731
+ for (let i = 0; i < 16; i++, offset += 4) SHA1_W[i] = view.getUint32(offset, false);
732
+ for (let i = 16; i < 80; i++) SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);
733
+ let {
734
+ A,
735
+ B,
736
+ C,
737
+ D,
738
+ E
739
+ } = this;
740
+ for (let i = 0; i < 80; i++) {
741
+ let F, K;
742
+ if (i < 20) {
743
+ F = Chi(B, C, D);
744
+ K = 0x5a827999;
745
+ } else if (i < 40) {
746
+ F = B ^ C ^ D;
747
+ K = 0x6ed9eba1;
748
+ } else if (i < 60) {
749
+ F = Maj(B, C, D);
750
+ K = 0x8f1bbcdc;
751
+ } else {
752
+ F = B ^ C ^ D;
753
+ K = 0xca62c1d6;
754
+ }
755
+ const T = rotl(A, 5) + F + E + K + SHA1_W[i] | 0;
756
+ E = D;
757
+ D = C;
758
+ C = rotl(B, 30);
759
+ B = A;
760
+ A = T;
761
+ }
762
+ A = A + this.A | 0;
763
+ B = B + this.B | 0;
764
+ C = C + this.C | 0;
765
+ D = D + this.D | 0;
766
+ E = E + this.E | 0;
767
+ this.set(A, B, C, D, E);
768
+ }
769
+ roundClean() {
770
+ clean(SHA1_W);
771
+ }
772
+ destroy() {
773
+ this.set(0, 0, 0, 0, 0);
774
+ clean(this.buffer);
775
+ }
776
+ }
777
+ createHasher(() => new SHA1());
778
+ const p32 = Math.pow(2, 32);
779
+ const K = Array.from({
780
+ length: 64
781
+ }, (_, i) => Math.floor(p32 * Math.abs(Math.sin(i + 1))));
782
+ const MD5_IV = SHA1_IV.slice(0, 4);
783
+ const MD5_W = new Uint32Array(16);
784
+ class MD5 extends HashMD {
785
+ constructor() {
786
+ super(64, 16, 8, true);
787
+ this.A = MD5_IV[0] | 0;
788
+ this.B = MD5_IV[1] | 0;
789
+ this.C = MD5_IV[2] | 0;
790
+ this.D = MD5_IV[3] | 0;
791
+ }
792
+ get() {
793
+ const {
794
+ A,
795
+ B,
796
+ C,
797
+ D
798
+ } = this;
799
+ return [A, B, C, D];
800
+ }
801
+ set(A, B, C, D) {
802
+ this.A = A | 0;
803
+ this.B = B | 0;
804
+ this.C = C | 0;
805
+ this.D = D | 0;
806
+ }
807
+ process(view, offset) {
808
+ for (let i = 0; i < 16; i++, offset += 4) MD5_W[i] = view.getUint32(offset, true);
809
+ let {
810
+ A,
811
+ B,
812
+ C,
813
+ D
814
+ } = this;
815
+ for (let i = 0; i < 64; i++) {
816
+ let F, g, s;
817
+ if (i < 16) {
818
+ F = Chi(B, C, D);
819
+ g = i;
820
+ s = [7, 12, 17, 22];
821
+ } else if (i < 32) {
822
+ F = Chi(D, B, C);
823
+ g = (5 * i + 1) % 16;
824
+ s = [5, 9, 14, 20];
825
+ } else if (i < 48) {
826
+ F = B ^ C ^ D;
827
+ g = (3 * i + 5) % 16;
828
+ s = [4, 11, 16, 23];
829
+ } else {
830
+ F = C ^ (B | ~D);
831
+ g = 7 * i % 16;
832
+ s = [6, 10, 15, 21];
833
+ }
834
+ F = F + A + K[i] + MD5_W[g];
835
+ A = D;
836
+ D = C;
837
+ C = B;
838
+ B = B + rotl(F, s[i % 4]);
839
+ }
840
+ A = A + this.A | 0;
841
+ B = B + this.B | 0;
842
+ C = C + this.C | 0;
843
+ D = D + this.D | 0;
844
+ this.set(A, B, C, D);
845
+ }
846
+ roundClean() {
847
+ clean(MD5_W);
848
+ }
849
+ destroy() {
850
+ this.set(0, 0, 0, 0);
851
+ clean(this.buffer);
852
+ }
853
+ }
854
+ const md5 = createHasher(() => new MD5());
855
+ const Rho160 = Uint8Array.from([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]);
856
+ const Id160 = (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();
857
+ const Pi160 = (() => Id160.map(i => (9 * i + 5) % 16))();
858
+ const idxLR = (() => {
859
+ const L = [Id160];
860
+ const R = [Pi160];
861
+ const res = [L, R];
862
+ for (let i = 0; i < 4; i++) for (let j of res) j.push(j[i].map(k => Rho160[k]));
863
+ return res;
864
+ })();
865
+ const idxL = (() => idxLR[0])();
866
+ const idxR = (() => idxLR[1])();
867
+ const shifts160 = [[11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5]].map(i => Uint8Array.from(i));
868
+ const shiftsL160 = idxL.map((idx, i) => idx.map(j => shifts160[i][j]));
869
+ const shiftsR160 = idxR.map((idx, i) => idx.map(j => shifts160[i][j]));
870
+ const Kl160 = Uint32Array.from([0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]);
871
+ const Kr160 = Uint32Array.from([0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]);
872
+ function ripemd_f(group, x, y, z) {
873
+ if (group === 0) return x ^ y ^ z;
874
+ if (group === 1) return x & y | ~x & z;
875
+ if (group === 2) return (x | ~y) ^ z;
876
+ if (group === 3) return x & z | y & ~z;
877
+ return x ^ (y | ~z);
878
+ }
879
+ const BUF_160 = new Uint32Array(16);
880
+ class RIPEMD160 extends HashMD {
881
+ constructor() {
882
+ super(64, 20, 8, true);
883
+ this.h0 = 0x67452301 | 0;
884
+ this.h1 = 0xefcdab89 | 0;
885
+ this.h2 = 0x98badcfe | 0;
886
+ this.h3 = 0x10325476 | 0;
887
+ this.h4 = 0xc3d2e1f0 | 0;
888
+ }
889
+ get() {
890
+ const {
891
+ h0,
892
+ h1,
893
+ h2,
894
+ h3,
895
+ h4
896
+ } = this;
897
+ return [h0, h1, h2, h3, h4];
898
+ }
899
+ set(h0, h1, h2, h3, h4) {
900
+ this.h0 = h0 | 0;
901
+ this.h1 = h1 | 0;
902
+ this.h2 = h2 | 0;
903
+ this.h3 = h3 | 0;
904
+ this.h4 = h4 | 0;
905
+ }
906
+ process(view, offset) {
907
+ for (let i = 0; i < 16; i++, offset += 4) BUF_160[i] = view.getUint32(offset, true);
908
+ let al = this.h0 | 0,
909
+ ar = al,
910
+ bl = this.h1 | 0,
911
+ br = bl,
912
+ cl = this.h2 | 0,
913
+ cr = cl,
914
+ dl = this.h3 | 0,
915
+ dr = dl,
916
+ el = this.h4 | 0,
917
+ er = el;
918
+ for (let group = 0; group < 5; group++) {
919
+ const rGroup = 4 - group;
920
+ const hbl = Kl160[group],
921
+ hbr = Kr160[group];
922
+ const rl = idxL[group],
923
+ rr = idxR[group];
924
+ const sl = shiftsL160[group],
925
+ sr = shiftsR160[group];
926
+ for (let i = 0; i < 16; i++) {
927
+ const tl = rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el | 0;
928
+ al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl;
929
+ }
930
+ for (let i = 0; i < 16; i++) {
931
+ const tr = rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er | 0;
932
+ ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr;
933
+ }
934
+ }
935
+ this.set(this.h1 + cl + dr | 0, this.h2 + dl + er | 0, this.h3 + el + ar | 0, this.h4 + al + br | 0, this.h0 + bl + cr | 0);
936
+ }
937
+ roundClean() {
938
+ clean(BUF_160);
939
+ }
940
+ destroy() {
941
+ this.destroyed = true;
942
+ clean(this.buffer);
943
+ this.set(0, 0, 0, 0, 0);
944
+ }
945
+ }
946
+ createHasher(() => new RIPEMD160());
947
+
469
948
  function md5Hash(data) {
470
- return new Uint8Array(md5.arrayBuffer(data));
949
+ return md5.create().update(data).digest();
471
950
  }
472
951
  function md5Hex(data) {
473
- return md5(data);
952
+ return utils.bytesToHex(md5Hash(data));
953
+ }
954
+
955
+ const U32_MASK64 = BigInt(2 ** 32 - 1);
956
+ const _32n = BigInt(32);
957
+ function fromBig(n, le = false) {
958
+ if (le) return {
959
+ h: Number(n & U32_MASK64),
960
+ l: Number(n >> _32n & U32_MASK64)
961
+ };
962
+ return {
963
+ h: Number(n >> _32n & U32_MASK64) | 0,
964
+ l: Number(n & U32_MASK64) | 0
965
+ };
966
+ }
967
+ function split(lst, le = false) {
968
+ const len = lst.length;
969
+ let Ah = new Uint32Array(len);
970
+ let Al = new Uint32Array(len);
971
+ for (let i = 0; i < len; i++) {
972
+ const {
973
+ h,
974
+ l
975
+ } = fromBig(lst[i], le);
976
+ [Ah[i], Al[i]] = [h, l];
977
+ }
978
+ return [Ah, Al];
979
+ }
980
+ const shrSH = (h, _l, s) => h >>> s;
981
+ const shrSL = (h, l, s) => h << 32 - s | l >>> s;
982
+ const rotrSH = (h, l, s) => h >>> s | l << 32 - s;
983
+ const rotrSL = (h, l, s) => h << 32 - s | l >>> s;
984
+ const rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
985
+ const rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
986
+ function add(Ah, Al, Bh, Bl) {
987
+ const l = (Al >>> 0) + (Bl >>> 0);
988
+ return {
989
+ h: Ah + Bh + (l / 2 ** 32 | 0) | 0,
990
+ l: l | 0
991
+ };
992
+ }
993
+ const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
994
+ const add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
995
+ const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
996
+ const add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
997
+ const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
998
+ const add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
999
+
1000
+ const SHA256_K = Uint32Array.from([0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]);
1001
+ const SHA256_W = new Uint32Array(64);
1002
+ class SHA256 extends HashMD {
1003
+ constructor(outputLen = 32) {
1004
+ super(64, outputLen, 8, false);
1005
+ this.A = SHA256_IV[0] | 0;
1006
+ this.B = SHA256_IV[1] | 0;
1007
+ this.C = SHA256_IV[2] | 0;
1008
+ this.D = SHA256_IV[3] | 0;
1009
+ this.E = SHA256_IV[4] | 0;
1010
+ this.F = SHA256_IV[5] | 0;
1011
+ this.G = SHA256_IV[6] | 0;
1012
+ this.H = SHA256_IV[7] | 0;
1013
+ }
1014
+ get() {
1015
+ const {
1016
+ A,
1017
+ B,
1018
+ C,
1019
+ D,
1020
+ E,
1021
+ F,
1022
+ G,
1023
+ H
1024
+ } = this;
1025
+ return [A, B, C, D, E, F, G, H];
1026
+ }
1027
+ set(A, B, C, D, E, F, G, H) {
1028
+ this.A = A | 0;
1029
+ this.B = B | 0;
1030
+ this.C = C | 0;
1031
+ this.D = D | 0;
1032
+ this.E = E | 0;
1033
+ this.F = F | 0;
1034
+ this.G = G | 0;
1035
+ this.H = H | 0;
1036
+ }
1037
+ process(view, offset) {
1038
+ for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);
1039
+ for (let i = 16; i < 64; i++) {
1040
+ const W15 = SHA256_W[i - 15];
1041
+ const W2 = SHA256_W[i - 2];
1042
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
1043
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
1044
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
1045
+ }
1046
+ let {
1047
+ A,
1048
+ B,
1049
+ C,
1050
+ D,
1051
+ E,
1052
+ F,
1053
+ G,
1054
+ H
1055
+ } = this;
1056
+ for (let i = 0; i < 64; i++) {
1057
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
1058
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
1059
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
1060
+ const T2 = sigma0 + Maj(A, B, C) | 0;
1061
+ H = G;
1062
+ G = F;
1063
+ F = E;
1064
+ E = D + T1 | 0;
1065
+ D = C;
1066
+ C = B;
1067
+ B = A;
1068
+ A = T1 + T2 | 0;
1069
+ }
1070
+ A = A + this.A | 0;
1071
+ B = B + this.B | 0;
1072
+ C = C + this.C | 0;
1073
+ D = D + this.D | 0;
1074
+ E = E + this.E | 0;
1075
+ F = F + this.F | 0;
1076
+ G = G + this.G | 0;
1077
+ H = H + this.H | 0;
1078
+ this.set(A, B, C, D, E, F, G, H);
1079
+ }
1080
+ roundClean() {
1081
+ clean(SHA256_W);
1082
+ }
1083
+ destroy() {
1084
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
1085
+ clean(this.buffer);
1086
+ }
1087
+ }
1088
+ class SHA224 extends SHA256 {
1089
+ constructor() {
1090
+ super(28);
1091
+ this.A = SHA224_IV[0] | 0;
1092
+ this.B = SHA224_IV[1] | 0;
1093
+ this.C = SHA224_IV[2] | 0;
1094
+ this.D = SHA224_IV[3] | 0;
1095
+ this.E = SHA224_IV[4] | 0;
1096
+ this.F = SHA224_IV[5] | 0;
1097
+ this.G = SHA224_IV[6] | 0;
1098
+ this.H = SHA224_IV[7] | 0;
1099
+ }
1100
+ }
1101
+ const K512 = (() => split(['0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'].map(n => BigInt(n))))();
1102
+ const SHA512_Kh = (() => K512[0])();
1103
+ const SHA512_Kl = (() => K512[1])();
1104
+ const SHA512_W_H = new Uint32Array(80);
1105
+ const SHA512_W_L = new Uint32Array(80);
1106
+ class SHA512 extends HashMD {
1107
+ constructor(outputLen = 64) {
1108
+ super(128, outputLen, 16, false);
1109
+ this.Ah = SHA512_IV[0] | 0;
1110
+ this.Al = SHA512_IV[1] | 0;
1111
+ this.Bh = SHA512_IV[2] | 0;
1112
+ this.Bl = SHA512_IV[3] | 0;
1113
+ this.Ch = SHA512_IV[4] | 0;
1114
+ this.Cl = SHA512_IV[5] | 0;
1115
+ this.Dh = SHA512_IV[6] | 0;
1116
+ this.Dl = SHA512_IV[7] | 0;
1117
+ this.Eh = SHA512_IV[8] | 0;
1118
+ this.El = SHA512_IV[9] | 0;
1119
+ this.Fh = SHA512_IV[10] | 0;
1120
+ this.Fl = SHA512_IV[11] | 0;
1121
+ this.Gh = SHA512_IV[12] | 0;
1122
+ this.Gl = SHA512_IV[13] | 0;
1123
+ this.Hh = SHA512_IV[14] | 0;
1124
+ this.Hl = SHA512_IV[15] | 0;
1125
+ }
1126
+ get() {
1127
+ const {
1128
+ Ah,
1129
+ Al,
1130
+ Bh,
1131
+ Bl,
1132
+ Ch,
1133
+ Cl,
1134
+ Dh,
1135
+ Dl,
1136
+ Eh,
1137
+ El,
1138
+ Fh,
1139
+ Fl,
1140
+ Gh,
1141
+ Gl,
1142
+ Hh,
1143
+ Hl
1144
+ } = this;
1145
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
1146
+ }
1147
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
1148
+ this.Ah = Ah | 0;
1149
+ this.Al = Al | 0;
1150
+ this.Bh = Bh | 0;
1151
+ this.Bl = Bl | 0;
1152
+ this.Ch = Ch | 0;
1153
+ this.Cl = Cl | 0;
1154
+ this.Dh = Dh | 0;
1155
+ this.Dl = Dl | 0;
1156
+ this.Eh = Eh | 0;
1157
+ this.El = El | 0;
1158
+ this.Fh = Fh | 0;
1159
+ this.Fl = Fl | 0;
1160
+ this.Gh = Gh | 0;
1161
+ this.Gl = Gl | 0;
1162
+ this.Hh = Hh | 0;
1163
+ this.Hl = Hl | 0;
1164
+ }
1165
+ process(view, offset) {
1166
+ for (let i = 0; i < 16; i++, offset += 4) {
1167
+ SHA512_W_H[i] = view.getUint32(offset);
1168
+ SHA512_W_L[i] = view.getUint32(offset += 4);
1169
+ }
1170
+ for (let i = 16; i < 80; i++) {
1171
+ const W15h = SHA512_W_H[i - 15] | 0;
1172
+ const W15l = SHA512_W_L[i - 15] | 0;
1173
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
1174
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
1175
+ const W2h = SHA512_W_H[i - 2] | 0;
1176
+ const W2l = SHA512_W_L[i - 2] | 0;
1177
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
1178
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
1179
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
1180
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
1181
+ SHA512_W_H[i] = SUMh | 0;
1182
+ SHA512_W_L[i] = SUMl | 0;
1183
+ }
1184
+ let {
1185
+ Ah,
1186
+ Al,
1187
+ Bh,
1188
+ Bl,
1189
+ Ch,
1190
+ Cl,
1191
+ Dh,
1192
+ Dl,
1193
+ Eh,
1194
+ El,
1195
+ Fh,
1196
+ Fl,
1197
+ Gh,
1198
+ Gl,
1199
+ Hh,
1200
+ Hl
1201
+ } = this;
1202
+ for (let i = 0; i < 80; i++) {
1203
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
1204
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
1205
+ const CHIh = Eh & Fh ^ ~Eh & Gh;
1206
+ const CHIl = El & Fl ^ ~El & Gl;
1207
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
1208
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
1209
+ const T1l = T1ll | 0;
1210
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
1211
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
1212
+ const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
1213
+ const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
1214
+ Hh = Gh | 0;
1215
+ Hl = Gl | 0;
1216
+ Gh = Fh | 0;
1217
+ Gl = Fl | 0;
1218
+ Fh = Eh | 0;
1219
+ Fl = El | 0;
1220
+ ({
1221
+ h: Eh,
1222
+ l: El
1223
+ } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
1224
+ Dh = Ch | 0;
1225
+ Dl = Cl | 0;
1226
+ Ch = Bh | 0;
1227
+ Cl = Bl | 0;
1228
+ Bh = Ah | 0;
1229
+ Bl = Al | 0;
1230
+ const All = add3L(T1l, sigma0l, MAJl);
1231
+ Ah = add3H(All, T1h, sigma0h, MAJh);
1232
+ Al = All | 0;
1233
+ }
1234
+ ({
1235
+ h: Ah,
1236
+ l: Al
1237
+ } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
1238
+ ({
1239
+ h: Bh,
1240
+ l: Bl
1241
+ } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
1242
+ ({
1243
+ h: Ch,
1244
+ l: Cl
1245
+ } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
1246
+ ({
1247
+ h: Dh,
1248
+ l: Dl
1249
+ } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
1250
+ ({
1251
+ h: Eh,
1252
+ l: El
1253
+ } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
1254
+ ({
1255
+ h: Fh,
1256
+ l: Fl
1257
+ } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
1258
+ ({
1259
+ h: Gh,
1260
+ l: Gl
1261
+ } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
1262
+ ({
1263
+ h: Hh,
1264
+ l: Hl
1265
+ } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
1266
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
1267
+ }
1268
+ roundClean() {
1269
+ clean(SHA512_W_H, SHA512_W_L);
1270
+ }
1271
+ destroy() {
1272
+ clean(this.buffer);
1273
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1274
+ }
1275
+ }
1276
+ class SHA384 extends SHA512 {
1277
+ constructor() {
1278
+ super(48);
1279
+ this.Ah = SHA384_IV[0] | 0;
1280
+ this.Al = SHA384_IV[1] | 0;
1281
+ this.Bh = SHA384_IV[2] | 0;
1282
+ this.Bl = SHA384_IV[3] | 0;
1283
+ this.Ch = SHA384_IV[4] | 0;
1284
+ this.Cl = SHA384_IV[5] | 0;
1285
+ this.Dh = SHA384_IV[6] | 0;
1286
+ this.Dl = SHA384_IV[7] | 0;
1287
+ this.Eh = SHA384_IV[8] | 0;
1288
+ this.El = SHA384_IV[9] | 0;
1289
+ this.Fh = SHA384_IV[10] | 0;
1290
+ this.Fl = SHA384_IV[11] | 0;
1291
+ this.Gh = SHA384_IV[12] | 0;
1292
+ this.Gl = SHA384_IV[13] | 0;
1293
+ this.Hh = SHA384_IV[14] | 0;
1294
+ this.Hl = SHA384_IV[15] | 0;
1295
+ }
1296
+ }
1297
+ const T224_IV = Uint32Array.from([0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf, 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1]);
1298
+ const T256_IV = Uint32Array.from([0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd, 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2]);
1299
+ class SHA512_224 extends SHA512 {
1300
+ constructor() {
1301
+ super(28);
1302
+ this.Ah = T224_IV[0] | 0;
1303
+ this.Al = T224_IV[1] | 0;
1304
+ this.Bh = T224_IV[2] | 0;
1305
+ this.Bl = T224_IV[3] | 0;
1306
+ this.Ch = T224_IV[4] | 0;
1307
+ this.Cl = T224_IV[5] | 0;
1308
+ this.Dh = T224_IV[6] | 0;
1309
+ this.Dl = T224_IV[7] | 0;
1310
+ this.Eh = T224_IV[8] | 0;
1311
+ this.El = T224_IV[9] | 0;
1312
+ this.Fh = T224_IV[10] | 0;
1313
+ this.Fl = T224_IV[11] | 0;
1314
+ this.Gh = T224_IV[12] | 0;
1315
+ this.Gl = T224_IV[13] | 0;
1316
+ this.Hh = T224_IV[14] | 0;
1317
+ this.Hl = T224_IV[15] | 0;
1318
+ }
1319
+ }
1320
+ class SHA512_256 extends SHA512 {
1321
+ constructor() {
1322
+ super(32);
1323
+ this.Ah = T256_IV[0] | 0;
1324
+ this.Al = T256_IV[1] | 0;
1325
+ this.Bh = T256_IV[2] | 0;
1326
+ this.Bl = T256_IV[3] | 0;
1327
+ this.Ch = T256_IV[4] | 0;
1328
+ this.Cl = T256_IV[5] | 0;
1329
+ this.Dh = T256_IV[6] | 0;
1330
+ this.Dl = T256_IV[7] | 0;
1331
+ this.Eh = T256_IV[8] | 0;
1332
+ this.El = T256_IV[9] | 0;
1333
+ this.Fh = T256_IV[10] | 0;
1334
+ this.Fl = T256_IV[11] | 0;
1335
+ this.Gh = T256_IV[12] | 0;
1336
+ this.Gl = T256_IV[13] | 0;
1337
+ this.Hh = T256_IV[14] | 0;
1338
+ this.Hl = T256_IV[15] | 0;
1339
+ }
474
1340
  }
1341
+ const sha256 = createHasher(() => new SHA256());
1342
+ createHasher(() => new SHA224());
1343
+ createHasher(() => new SHA512());
1344
+ createHasher(() => new SHA384());
1345
+ createHasher(() => new SHA512_256());
1346
+ createHasher(() => new SHA512_224());
475
1347
 
476
1348
  function sha256Hash(data) {
477
- return sha2.sha256(data);
1349
+ return sha256(data);
478
1350
  }
479
1351
 
480
1352
  function aesCbcEncrypt(data, key, iv, padding = true) {
@@ -612,7 +1484,7 @@ class PDFSecurity {
612
1484
  }
613
1485
  infoStr += `${key}: ${info[key].valueOf()}\n`;
614
1486
  }
615
- return Buffer.from(md5Hash(infoStr));
1487
+ return md5Hash(infoStr);
616
1488
  }
617
1489
  static generateRandomWordArray(bytes) {
618
1490
  return randomBytes(bytes);
@@ -707,8 +1579,8 @@ class PDFSecurity {
707
1579
  encDict.StrF = 'StdCF';
708
1580
  }
709
1581
  encDict.R = r;
710
- encDict.O = Buffer.from(ownerPasswordEntry);
711
- encDict.U = Buffer.from(userPasswordEntry);
1582
+ encDict.O = ownerPasswordEntry;
1583
+ encDict.U = userPasswordEntry;
712
1584
  encDict.P = permissions;
713
1585
  }
714
1586
  _setupEncryptionV5(encDict, options) {
@@ -736,12 +1608,12 @@ class PDFSecurity {
736
1608
  encDict.StmF = 'StdCF';
737
1609
  encDict.StrF = 'StdCF';
738
1610
  encDict.R = 5;
739
- encDict.O = Buffer.from(ownerPasswordEntry);
740
- encDict.OE = Buffer.from(ownerEncryptionKeyEntry);
741
- encDict.U = Buffer.from(userPasswordEntry);
742
- encDict.UE = Buffer.from(userEncryptionKeyEntry);
1611
+ encDict.O = ownerPasswordEntry;
1612
+ encDict.OE = ownerEncryptionKeyEntry;
1613
+ encDict.U = userPasswordEntry;
1614
+ encDict.UE = userEncryptionKeyEntry;
743
1615
  encDict.P = permissions;
744
- encDict.Perms = Buffer.from(permsEntry);
1616
+ encDict.Perms = permsEntry;
745
1617
  }
746
1618
  getEncryptFn(obj, gen) {
747
1619
  let digest;
@@ -753,7 +1625,7 @@ class PDFSecurity {
753
1625
  let key = md5Hash(digest);
754
1626
  const keyLen = Math.min(16, this.keyBits / 8 + 5);
755
1627
  key = key.slice(0, keyLen);
756
- return buffer => Buffer.from(rc4(new Uint8Array(buffer), key));
1628
+ return buffer => rc4(buffer, key);
757
1629
  }
758
1630
  let key;
759
1631
  if (this.version === 4) {
@@ -764,8 +1636,8 @@ class PDFSecurity {
764
1636
  }
765
1637
  const iv = PDFSecurity.generateRandomWordArray(16);
766
1638
  return buffer => {
767
- const encrypted = aesCbcEncrypt(new Uint8Array(buffer), key, iv, true);
768
- return Buffer.from(utils.concatBytes(iv, encrypted));
1639
+ const encrypted = aesCbcEncrypt(buffer, key, iv, true);
1640
+ return utils.concatBytes(iv, encrypted);
769
1641
  };
770
1642
  }
771
1643
  end() {
@@ -2221,6 +3093,60 @@ var VectorMixin = {
2221
3093
  }
2222
3094
  };
2223
3095
 
3096
+ const registeredFiles = new Map();
3097
+ const toNativePath = path => typeof path === 'string' && path.startsWith('file:') ? new URL(path) : path;
3098
+ const getTimestamp = (value, name, defaultValue) => {
3099
+ if (value === undefined) {
3100
+ return defaultValue;
3101
+ }
3102
+ if (!(value instanceof Date) || Number.isNaN(value.getTime())) {
3103
+ throw new TypeError(`Expected options.${name} to be a valid Date`);
3104
+ }
3105
+ return value.getTime();
3106
+ };
3107
+ function registerFile(path, data, options = {}) {
3108
+ if (typeof path !== 'string') {
3109
+ throw new TypeError(`Expected a string for path, got ${typeof path}`);
3110
+ }
3111
+ if (data === undefined) {
3112
+ registeredFiles.delete(path);
3113
+ return;
3114
+ }
3115
+ if (!(data instanceof Uint8Array)) {
3116
+ throw new TypeError(`Expected a Uint8Array or undefined for data, got ${typeof data}`);
3117
+ }
3118
+ if (options === null || typeof options !== 'object') {
3119
+ throw new TypeError(`Expected options to be an object`);
3120
+ }
3121
+ const registeredAt = Date.now();
3122
+ registeredFiles.set(path, {
3123
+ data,
3124
+ birthtime: getTimestamp(options.birthtime, 'birthtime', registeredAt),
3125
+ ctime: getTimestamp(options.ctime, 'ctime', registeredAt)
3126
+ });
3127
+ }
3128
+ var fs = {
3129
+ readFileSync(path) {
3130
+ if (registeredFiles.has(path)) {
3131
+ return registeredFiles.get(path).data;
3132
+ }
3133
+ return fs$1.readFileSync(toNativePath(path));
3134
+ },
3135
+ statSync(path) {
3136
+ if (registeredFiles.has(path)) {
3137
+ const {
3138
+ birthtime,
3139
+ ctime
3140
+ } = registeredFiles.get(path);
3141
+ return {
3142
+ birthtime: new Date(birthtime),
3143
+ ctime: new Date(ctime)
3144
+ };
3145
+ }
3146
+ return fs$1.statSync(toNativePath(path));
3147
+ }
3148
+ };
3149
+
2224
3150
  const WIN_ANSI_MAP = {
2225
3151
  402: 131,
2226
3152
  8211: 150,
@@ -2324,58 +3250,25 @@ oslash ugrave uacute ucircumflex
2324
3250
  udieresis yacute thorn ydieresis\
2325
3251
  `.split(/\s+/);
2326
3252
  class AFMFont {
2327
- constructor(contents) {
2328
- this.attributes = {};
2329
- this.glyphWidths = {};
2330
- this.boundingBoxes = {};
2331
- this.kernPairs = {};
2332
- this.parse(contents);
2333
- this.bbox = this.attributes['FontBBox'].split(/\s+/).map(e => +e);
2334
- this.ascender = +(this.attributes['Ascender'] || 0);
2335
- this.descender = +(this.attributes['Descender'] || 0);
2336
- this.xHeight = +(this.attributes['XHeight'] || 0);
2337
- this.capHeight = +(this.attributes['CapHeight'] || 0);
3253
+ constructor(data) {
3254
+ this.name = data.name;
3255
+ this.bbox = data.bbox.slice();
3256
+ this.ascender = data.ascender;
3257
+ this.descender = data.descender;
3258
+ this.xHeight = data.xHeight;
3259
+ this.capHeight = data.capHeight;
2338
3260
  this.lineGap = this.bbox[3] - this.bbox[1] - (this.ascender - this.descender);
2339
- }
2340
- parse(contents) {
2341
- let section = '';
2342
- for (let line of contents.split('\n')) {
2343
- var match;
2344
- var a;
2345
- if (match = line.match(/^Start(\w+)/)) {
2346
- section = match[1];
2347
- continue;
2348
- } else if (line.match(/^End(\w+)/)) {
2349
- section = '';
2350
- continue;
2351
- }
2352
- switch (section) {
2353
- case 'FontMetrics':
2354
- match = line.match(/(^\w+)\s+(.*)/);
2355
- var key = match[1];
2356
- var value = match[2];
2357
- if (a = this.attributes[key]) {
2358
- if (!Array.isArray(a)) {
2359
- a = this.attributes[key] = [a];
2360
- }
2361
- a.push(value);
2362
- } else {
2363
- this.attributes[key] = value;
2364
- }
2365
- break;
2366
- case 'CharMetrics':
2367
- if (!/^CH?\s/.test(line)) {
2368
- continue;
2369
- }
2370
- var name = line.match(/\bN\s+(\.?\w+)\s*;/)[1];
2371
- this.glyphWidths[name] = +line.match(/\bWX\s+(\d+)\s*;/)[1];
2372
- break;
2373
- case 'KernPairs':
2374
- match = line.match(/^KPX\s+(\.?\w+)\s+(\.?\w+)\s+(-?\d+)/);
2375
- if (match) {
2376
- this.kernPairs[match[1] + '\0' + match[2]] = parseInt(match[3]);
2377
- }
2378
- break;
3261
+ const glyphNames = data.glyphNames.split(' ');
3262
+ this.glyphWidths = Object.fromEntries(glyphNames.map((name, index) => [name, data.glyphWidths[index]]));
3263
+ this.kernPairs = {};
3264
+ for (let index = 0; index < data.kernPairs.length; index += 2) {
3265
+ const amount = data.kernPairs[index];
3266
+ let pairId = 0;
3267
+ for (const delta of data.kernPairs[index + 1]) {
3268
+ pairId += delta;
3269
+ const left = Math.floor(pairId / glyphNames.length);
3270
+ const right = pairId % glyphNames.length;
3271
+ this.kernPairs[`${glyphNames[left]}\0${glyphNames[right]}`] = amount;
2379
3272
  }
2380
3273
  }
2381
3274
  }
@@ -2443,57 +3336,13 @@ class PDFFont {
2443
3336
  }
2444
3337
  }
2445
3338
 
2446
- const STANDARD_FONTS = {
2447
- Courier() {
2448
- return fs.readFileSync(__dirname + '/data/Courier.afm', 'utf8');
2449
- },
2450
- 'Courier-Bold'() {
2451
- return fs.readFileSync(__dirname + '/data/Courier-Bold.afm', 'utf8');
2452
- },
2453
- 'Courier-Oblique'() {
2454
- return fs.readFileSync(__dirname + '/data/Courier-Oblique.afm', 'utf8');
2455
- },
2456
- 'Courier-BoldOblique'() {
2457
- return fs.readFileSync(__dirname + '/data/Courier-BoldOblique.afm', 'utf8');
2458
- },
2459
- Helvetica() {
2460
- return fs.readFileSync(__dirname + '/data/Helvetica.afm', 'utf8');
2461
- },
2462
- 'Helvetica-Bold'() {
2463
- return fs.readFileSync(__dirname + '/data/Helvetica-Bold.afm', 'utf8');
2464
- },
2465
- 'Helvetica-Oblique'() {
2466
- return fs.readFileSync(__dirname + '/data/Helvetica-Oblique.afm', 'utf8');
2467
- },
2468
- 'Helvetica-BoldOblique'() {
2469
- return fs.readFileSync(__dirname + '/data/Helvetica-BoldOblique.afm', 'utf8');
2470
- },
2471
- 'Times-Roman'() {
2472
- return fs.readFileSync(__dirname + '/data/Times-Roman.afm', 'utf8');
2473
- },
2474
- 'Times-Bold'() {
2475
- return fs.readFileSync(__dirname + '/data/Times-Bold.afm', 'utf8');
2476
- },
2477
- 'Times-Italic'() {
2478
- return fs.readFileSync(__dirname + '/data/Times-Italic.afm', 'utf8');
2479
- },
2480
- 'Times-BoldItalic'() {
2481
- return fs.readFileSync(__dirname + '/data/Times-BoldItalic.afm', 'utf8');
2482
- },
2483
- Symbol() {
2484
- return fs.readFileSync(__dirname + '/data/Symbol.afm', 'utf8');
2485
- },
2486
- ZapfDingbats() {
2487
- return fs.readFileSync(__dirname + '/data/ZapfDingbats.afm', 'utf8');
2488
- }
2489
- };
2490
3339
  class StandardFont extends PDFFont {
2491
- constructor(document, name, id) {
3340
+ constructor(document, fontData, id) {
2492
3341
  super();
2493
3342
  this.document = document;
2494
- this.name = name;
3343
+ this.name = fontData.name;
2495
3344
  this.id = id;
2496
- this.font = new AFMFont(STANDARD_FONTS[this.name]());
3345
+ this.font = new AFMFont(fontData);
2497
3346
  ({
2498
3347
  ascender: this.ascender,
2499
3348
  descender: this.descender,
@@ -2539,9 +3388,6 @@ class StandardFont extends PDFFont {
2539
3388
  const scale = size / 1000;
2540
3389
  return width * scale;
2541
3390
  }
2542
- static isStandardFont(name) {
2543
- return name in STANDARD_FONTS;
2544
- }
2545
3391
  }
2546
3392
 
2547
3393
  const toHex = function (num) {
@@ -2690,7 +3536,7 @@ class EmbeddedFont extends PDFFont {
2690
3536
  }
2691
3537
  if (this.document.subset && this.document.subset === 1) {
2692
3538
  const maxCID = this.widths.length - 1;
2693
- const cidSetBuffer = Buffer.alloc(Math.ceil((maxCID + 1) / 8), 0);
3539
+ const cidSetBuffer = new Uint8Array(Math.ceil((maxCID + 1) / 8));
2694
3540
  for (let cid = 0; cid <= maxCID; cid++) {
2695
3541
  if (this.widths[cid] != null) {
2696
3542
  cidSetBuffer[Math.floor(cid / 8)] |= 0x80 >> cid % 8;
@@ -2779,12 +3625,46 @@ end\
2779
3625
  }
2780
3626
  }
2781
3627
 
3628
+ const STANDARD_FONT_NAMES = ['Courier', 'Courier-Bold', 'Courier-BoldOblique', 'Courier-Oblique', 'Helvetica', 'Helvetica-Bold', 'Helvetica-BoldOblique', 'Helvetica-Oblique', 'Symbol', 'Times-Bold', 'Times-BoldItalic', 'Times-Italic', 'Times-Roman', 'ZapfDingbats'];
3629
+ const STANDARD_FONT_NAME_SET = new Set(STANDARD_FONT_NAMES);
3630
+ const validateFontData = (fontData, expectedName) => {
3631
+ if (fontData == null || typeof fontData !== 'object' || !STANDARD_FONT_NAME_SET.has(fontData.name) || expectedName != null && fontData.name !== expectedName) {
3632
+ throw new TypeError('Invalid standard font data.');
3633
+ }
3634
+ };
3635
+ const standardFonts = new Map();
3636
+ const isStandardFont = name => STANDARD_FONT_NAME_SET.has(name);
3637
+ const registerStdFontLoaders = loaders => {
3638
+ for (const [name, loader] of Object.entries(loaders)) {
3639
+ if (!STANDARD_FONT_NAME_SET.has(name) || typeof loader !== 'function') {
3640
+ throw new TypeError('Invalid standard font loader.');
3641
+ }
3642
+ standardFonts.set(name, loader);
3643
+ }
3644
+ };
3645
+ const getStandardFont = name => {
3646
+ if (!STANDARD_FONT_NAME_SET.has(name)) {
3647
+ return null;
3648
+ }
3649
+ const font = standardFonts.get(name);
3650
+ if (font == null) {
3651
+ throw new Error(`Standard font "${name}" is not registered. ` + 'Call registerStdFonts() before using it.');
3652
+ }
3653
+ if (typeof font !== 'function') {
3654
+ return font;
3655
+ }
3656
+ const data = font();
3657
+ validateFontData(data, name);
3658
+ standardFonts.set(name, data);
3659
+ return data;
3660
+ };
3661
+
2782
3662
  class PDFFontFactory {
2783
3663
  static open(document, src, family, id) {
2784
3664
  let font;
2785
3665
  if (typeof src === 'string') {
2786
- if (StandardFont.isStandardFont(src)) {
2787
- return new StandardFont(document, src, id);
3666
+ if (isStandardFont(src)) {
3667
+ return new StandardFont(document, getStandardFont(src), id);
2788
3668
  }
2789
3669
  src = fs.readFileSync(src);
2790
3670
  }
@@ -2792,6 +3672,8 @@ class PDFFontFactory {
2792
3672
  font = fontkit.create(src, family);
2793
3673
  } else if (src instanceof ArrayBuffer) {
2794
3674
  font = fontkit.create(new Uint8Array(src), family);
3675
+ } else if (typeof src?.layout === 'function') {
3676
+ font = src;
2795
3677
  }
2796
3678
  if (font == null) {
2797
3679
  throw new Error('Not a supported font format or standard PDF font.');
@@ -2941,11 +3823,42 @@ var FontsMixin = {
2941
3823
  }
2942
3824
  };
2943
3825
 
3826
+ class EventEmitter {
3827
+ constructor() {
3828
+ this._listeners = Object.create(null);
3829
+ }
3830
+ on(event, listener) {
3831
+ (this._listeners[event] || (this._listeners[event] = [])).push(listener);
3832
+ return this;
3833
+ }
3834
+ once(event, listener) {
3835
+ const wrapper = (...args) => {
3836
+ this.off(event, wrapper);
3837
+ listener(...args);
3838
+ };
3839
+ return this.on(event, wrapper);
3840
+ }
3841
+ off(event, listener) {
3842
+ const listeners = this._listeners[event];
3843
+ if (listeners) {
3844
+ const index = listeners.indexOf(listener);
3845
+ if (index !== -1) listeners.splice(index, 1);
3846
+ }
3847
+ return this;
3848
+ }
3849
+ emit(event, ...args) {
3850
+ const listeners = this._listeners[event];
3851
+ if (!listeners) return false;
3852
+ for (const listener of listeners.slice()) listener(...args);
3853
+ return listeners.length > 0;
3854
+ }
3855
+ }
3856
+
2944
3857
  const SOFT_HYPHEN = '\u00AD';
2945
3858
  const HYPHEN = '-';
2946
- class LineWrapper {
3859
+ class LineWrapper extends EventEmitter {
2947
3860
  constructor(document, options) {
2948
- this._listeners = Object.create(null);
3861
+ super();
2949
3862
  this.document = document;
2950
3863
  this.horizontalScaling = options.horizontalScaling || 100;
2951
3864
  this.indent = (options.indent || 0) * this.horizontalScaling / 100;
@@ -2961,6 +3874,7 @@ class LineWrapper {
2961
3874
  this.column = 1;
2962
3875
  this.ellipsis = options.ellipsis;
2963
3876
  this.continuedX = 0;
3877
+ this.indentApplied = false;
2964
3878
  this.features = options.features;
2965
3879
  if (options.height != null) {
2966
3880
  this.height = options.height;
@@ -2969,15 +3883,26 @@ class LineWrapper {
2969
3883
  this.maxY = PDFNumber(this.document.page.maxY());
2970
3884
  }
2971
3885
  this.on('firstLine', options => {
2972
- const indent = this.continuedX || this.indent;
2973
- this.document.x += indent;
2974
- this.lineWidth -= indent;
3886
+ const continuation = this.continuedX;
3887
+ const indent = continuation || this.indent;
3888
+ if (continuation || !this.indentApplied) {
3889
+ this.document.x += indent;
3890
+ this.lineWidth -= indent;
3891
+ this.indentApplied = true;
3892
+ }
2975
3893
  if (options.indentAllLines) {
3894
+ if (continuation) {
3895
+ this.once('line', () => {
3896
+ this.document.x -= continuation;
3897
+ this.lineWidth += continuation;
3898
+ });
3899
+ }
2976
3900
  return;
2977
3901
  }
2978
3902
  this.once('line', () => {
2979
3903
  this.document.x -= indent;
2980
3904
  this.lineWidth += indent;
3905
+ this.indentApplied = false;
2981
3906
  if (options.continued && !this.continuedX) {
2982
3907
  this.continuedX = this.indent;
2983
3908
  }
@@ -3001,22 +3926,6 @@ class LineWrapper {
3001
3926
  });
3002
3927
  });
3003
3928
  }
3004
- on(event, listener) {
3005
- (this._listeners[event] || (this._listeners[event] = [])).push(listener);
3006
- }
3007
- once(event, listener) {
3008
- const wrapper = (...args) => {
3009
- const listeners = this._listeners[event];
3010
- listeners.splice(listeners.indexOf(wrapper), 1);
3011
- listener(...args);
3012
- };
3013
- this.on(event, wrapper);
3014
- }
3015
- emit(event, ...args) {
3016
- const listeners = this._listeners[event];
3017
- if (!listeners) return;
3018
- for (const listener of listeners.slice()) listener(...args);
3019
- }
3020
3929
  wordWidth(word) {
3021
3930
  return PDFNumber(this.document.widthOfString(word, this) + this.characterSpacing + this.wordSpacing);
3022
3931
  }
@@ -3207,9 +4116,9 @@ class LineWrapper {
3207
4116
  this.startY = this.document.page.margins.top;
3208
4117
  this.maxY = this.document.page.maxY();
3209
4118
  if (this.indentAllLines) {
3210
- const indent = this.continuedX || this.indent;
3211
- this.document.x += indent;
3212
- this.lineWidth -= indent;
4119
+ if (this.indentApplied) {
4120
+ this.document.x += this.continuedX || this.indent;
4121
+ }
3213
4122
  } else {
3214
4123
  this.document.x = this.startX;
3215
4124
  }
@@ -3749,20 +4658,6 @@ var TextMixin = {
3749
4658
  }
3750
4659
  };
3751
4660
 
3752
- const toBinaryString = bytes => {
3753
- const chunkSize = 0x8000;
3754
- let out = '';
3755
- for (let i = 0; i < bytes.length; i += chunkSize) {
3756
- const end = Math.min(i + chunkSize, bytes.length);
3757
- out += String.fromCharCode.apply(null, bytes.subarray(i, end));
3758
- }
3759
- return out;
3760
- };
3761
- const readUInt16BE = (bytes, offset = 0) => (bytes[offset] << 8 | bytes[offset + 1]) >>> 0;
3762
- const readUInt16LE = (bytes, offset = 0) => (bytes[offset + 1] << 8 | bytes[offset]) >>> 0;
3763
- const readUInt32BE = (bytes, offset = 0) => bytes[offset] * 0x1000000 + (bytes[offset + 1] << 16 | bytes[offset + 2] << 8 | bytes[offset + 3]) >>> 0;
3764
- const readUInt32LE = (bytes, offset = 0) => (bytes[offset] | bytes[offset + 1] << 8 | bytes[offset + 2] << 16) + bytes[offset + 3] * 0x1000000 >>> 0;
3765
-
3766
4661
  const parseExifOrientation = data => {
3767
4662
  if (!data || data.length < 20) return null;
3768
4663
  let pos = 2;
@@ -3815,7 +4710,7 @@ class JPEG {
3815
4710
  let marker;
3816
4711
  this.data = data;
3817
4712
  this.label = label;
3818
- if (this.data.readUInt16BE(0) !== 0xffd8) {
4713
+ if (readUInt16BE(this.data, 0) !== 0xffd8) {
3819
4714
  throw 'SOI not found in JPEG';
3820
4715
  }
3821
4716
  this.orientation = parseExifOrientation(this.data) || 1;
@@ -3823,21 +4718,21 @@ class JPEG {
3823
4718
  while (pos < this.data.length) {
3824
4719
  while (pos < this.data.length && this.data[pos] !== 0xff) pos++;
3825
4720
  if (pos >= this.data.length) break;
3826
- marker = this.data.readUInt16BE(pos);
4721
+ marker = readUInt16BE(this.data, pos);
3827
4722
  pos += 2;
3828
4723
  if (MARKERS.includes(marker)) {
3829
4724
  break;
3830
4725
  }
3831
- pos += this.data.readUInt16BE(pos);
4726
+ pos += readUInt16BE(this.data, pos);
3832
4727
  }
3833
4728
  if (!MARKERS.includes(marker)) {
3834
4729
  throw 'Invalid JPEG.';
3835
4730
  }
3836
4731
  pos += 2;
3837
4732
  this.bits = this.data[pos++];
3838
- this.height = this.data.readUInt16BE(pos);
4733
+ this.height = readUInt16BE(this.data, pos);
3839
4734
  pos += 2;
3840
- this.width = this.data.readUInt16BE(pos);
4735
+ this.width = readUInt16BE(this.data, pos);
3841
4736
  pos += 2;
3842
4737
  const channels = this.data[pos];
3843
4738
  this.colorSpace = COLOR_SPACE_MAP[channels];
@@ -3907,7 +4802,7 @@ class PNGImage {
3907
4802
  obj.data['ColorSpace'] = image.colorSpace;
3908
4803
  } else {
3909
4804
  const palette = document.ref();
3910
- palette.end(Buffer.from(image.palette));
4805
+ palette.end(new Uint8Array(image.palette));
3911
4806
  obj.data['ColorSpace'] = ['Indexed', 'DeviceRGB', image.palette.length / 3 - 1, palette];
3912
4807
  }
3913
4808
  if (image.transparency.grayscale != null) {
@@ -3956,8 +4851,8 @@ class PNGImage {
3956
4851
  let a, p;
3957
4852
  const colorCount = this.image.colors;
3958
4853
  const pixelCount = this.width * this.height;
3959
- const imgData = Buffer.alloc(pixelCount * colorCount);
3960
- const alphaChannel = Buffer.alloc(pixelCount);
4854
+ const imgData = new Uint8Array(pixelCount * colorCount);
4855
+ const alphaChannel = new Uint8Array(pixelCount);
3961
4856
  let i = p = a = 0;
3962
4857
  const len = pixels.length;
3963
4858
  const skipByteCount = this.image.bits === 16 ? 1 : 0;
@@ -3978,13 +4873,13 @@ class PNGImage {
3978
4873
  const transparency = this.image.transparency.indexed;
3979
4874
  const isInterlaced = this.image.interlaceMethod === 1;
3980
4875
  return this.image.decodePixels(pixels => {
3981
- const alphaChannel = Buffer.alloc(this.width * this.height);
4876
+ const alphaChannel = new Uint8Array(this.width * this.height);
3982
4877
  let i = 0;
3983
4878
  for (let j = 0, end = pixels.length; j < end; j++) {
3984
4879
  alphaChannel[i++] = transparency[pixels[j]];
3985
4880
  }
3986
4881
  if (isInterlaced) {
3987
- this.imgData = zlib.deflateSync(Buffer.from(pixels));
4882
+ this.imgData = zlib.deflateSync(pixels);
3988
4883
  }
3989
4884
  this.alphaChannel = zlib.deflateSync(alphaChannel);
3990
4885
  return this.finalize();
@@ -4001,14 +4896,14 @@ class PNGImage {
4001
4896
  class PDFImage {
4002
4897
  static open(src, label) {
4003
4898
  let data;
4004
- if (Buffer.isBuffer(src)) {
4899
+ if (src instanceof Uint8Array) {
4005
4900
  data = src;
4006
4901
  } else if (src instanceof ArrayBuffer) {
4007
- data = Buffer.from(new Uint8Array(src));
4902
+ data = new Uint8Array(src);
4008
4903
  } else {
4009
4904
  const match = /^data:.+?;base64,(.*)$/.exec(src);
4010
4905
  if (match) {
4011
- data = Buffer.from(match[1], 'base64');
4906
+ data = fromBase64(match[1]);
4012
4907
  } else {
4013
4908
  data = fs.readFileSync(src);
4014
4909
  if (!data) {
@@ -4225,136 +5120,169 @@ class PDFAnnotationReference {
4225
5120
 
4226
5121
  var AnnotationsMixin = {
4227
5122
  annotate(x, y, w, h, options) {
4228
- options.Type = 'Annot';
4229
- options.Rect = this._convertRect(x, y, w, h);
4230
- options.Border = [0, 0, 0];
4231
- if (options.Subtype === 'Link' && typeof options.F === 'undefined') {
4232
- options.F = 1 << 2;
5123
+ const {
5124
+ structParent,
5125
+ color,
5126
+ ...annotations
5127
+ } = options;
5128
+ annotations.Type = 'Annot';
5129
+ annotations.Rect = this._convertRect(x, y, w, h);
5130
+ annotations.Border = [0, 0, 0];
5131
+ if (annotations.Subtype === 'Link' && typeof annotations.F === 'undefined') {
5132
+ annotations.F = 1 << 2;
4233
5133
  }
4234
- if (options.Subtype !== 'Link') {
4235
- if (options.C == null) {
4236
- options.C = this._normalizeColor(options.color || [0, 0, 0]);
5134
+ if (annotations.Subtype !== 'Link') {
5135
+ if (annotations.C == null) {
5136
+ annotations.C = this._normalizeColor(color || [0, 0, 0]);
4237
5137
  }
4238
5138
  }
4239
- delete options.color;
4240
- if (typeof options.Dest === 'string') {
4241
- options.Dest = new String(options.Dest);
5139
+ if (typeof annotations.Dest === 'string') {
5140
+ annotations.Dest = new String(annotations.Dest);
4242
5141
  }
4243
- const structParent = options.structParent;
4244
- delete options.structParent;
4245
- for (let key in options) {
4246
- const val = options[key];
4247
- options[key[0].toUpperCase() + key.slice(1)] = val;
4248
- }
4249
- const ref = this.ref(options);
5142
+ const ref = this.ref(annotations);
4250
5143
  this.page.annotations.push(ref);
4251
- if (structParent && typeof structParent.add === 'function') {
5144
+ if (typeof structParent?.add === 'function') {
4252
5145
  const annotRef = new PDFAnnotationReference(ref);
4253
5146
  structParent.add(annotRef);
4254
5147
  }
4255
5148
  ref.end();
4256
5149
  return this;
4257
5150
  },
4258
- note(x, y, w, h, contents, options = {}) {
4259
- options.Subtype = 'Text';
4260
- options.Contents = new String(contents);
4261
- if (options.Name == null) {
4262
- options.Name = 'Comment';
5151
+ note(x, y, w, h, contents, options) {
5152
+ const annotationOptions = {
5153
+ ...options,
5154
+ Subtype: 'Text',
5155
+ Contents: new String(contents)
5156
+ };
5157
+ if (annotationOptions.Name == null) {
5158
+ annotationOptions.Name = 'Comment';
4263
5159
  }
4264
- if (options.color == null) {
4265
- options.color = [243, 223, 92];
5160
+ if (annotationOptions.color == null) {
5161
+ annotationOptions.color = [243, 223, 92];
4266
5162
  }
4267
- return this.annotate(x, y, w, h, options);
5163
+ return this.annotate(x, y, w, h, annotationOptions);
4268
5164
  },
4269
- goTo(x, y, w, h, name, options = {}) {
4270
- options.Subtype = 'Link';
4271
- options.A = this.ref({
4272
- S: 'GoTo',
4273
- D: new String(name)
4274
- });
4275
- options.A.end();
4276
- return this.annotate(x, y, w, h, options);
5165
+ goTo(x, y, w, h, name, options) {
5166
+ const annotateOptions = {
5167
+ ...options,
5168
+ Subtype: 'Link',
5169
+ A: this.ref({
5170
+ S: 'GoTo',
5171
+ D: new String(name)
5172
+ })
5173
+ };
5174
+ annotateOptions.A.end();
5175
+ return this.annotate(x, y, w, h, annotateOptions);
4277
5176
  },
4278
- link(x, y, w, h, url, options = {}) {
4279
- options.Subtype = 'Link';
5177
+ link(x, y, w, h, url, options) {
5178
+ const annotateOptions = {
5179
+ ...options,
5180
+ Subtype: 'Link'
5181
+ };
4280
5182
  if (typeof url === 'number') {
4281
5183
  const pages = this._root.data.Pages.data;
4282
5184
  if (url >= 0 && url < pages.Kids.length) {
4283
- options.A = this.ref({
5185
+ annotateOptions.A = this.ref({
4284
5186
  S: 'GoTo',
4285
5187
  D: [pages.Kids[url], 'XYZ', null, null, null]
4286
5188
  });
4287
- options.A.end();
5189
+ annotateOptions.A.end();
4288
5190
  } else {
4289
5191
  throw new Error(`The document has no page ${url}`);
4290
5192
  }
4291
5193
  } else {
4292
- options.A = this.ref({
5194
+ annotateOptions.A = this.ref({
4293
5195
  S: 'URI',
4294
5196
  URI: new String(url)
4295
5197
  });
4296
- options.A.end();
5198
+ annotateOptions.A.end();
4297
5199
  }
4298
- if (options.structParent && !options.Contents) {
4299
- options.Contents = new String('');
5200
+ if (annotateOptions.structParent && !annotateOptions.Contents) {
5201
+ annotateOptions.Contents = new String('');
4300
5202
  }
4301
- return this.annotate(x, y, w, h, options);
5203
+ return this.annotate(x, y, w, h, annotateOptions);
4302
5204
  },
4303
- _markup(x, y, w, h, options = {}) {
5205
+ _markup(x, y, w, h, options) {
4304
5206
  const [x1, y1, x2, y2] = this._convertRect(x, y, w, h);
4305
- options.QuadPoints = [x1, y2, x2, y2, x1, y1, x2, y1];
4306
- options.Contents = new String();
4307
- return this.annotate(x, y, w, h, options);
4308
- },
4309
- highlight(x, y, w, h, options = {}) {
4310
- options.Subtype = 'Highlight';
4311
- if (options.color == null) {
4312
- options.color = [241, 238, 148];
4313
- }
4314
- return this._markup(x, y, w, h, options);
4315
- },
4316
- underline(x, y, w, h, options = {}) {
4317
- options.Subtype = 'Underline';
4318
- return this._markup(x, y, w, h, options);
4319
- },
4320
- strike(x, y, w, h, options = {}) {
4321
- options.Subtype = 'StrikeOut';
4322
- return this._markup(x, y, w, h, options);
4323
- },
4324
- lineAnnotation(x1, y1, x2, y2, options = {}) {
4325
- options.Subtype = 'Line';
4326
- options.Contents = new String();
4327
- options.L = [x1, this.page.height - y1, x2, this.page.height - y2];
4328
- return this.annotate(x1, y1, x2, y2, options);
4329
- },
4330
- rectAnnotation(x, y, w, h, options = {}) {
4331
- options.Subtype = 'Square';
4332
- options.Contents = new String();
4333
- return this.annotate(x, y, w, h, options);
4334
- },
4335
- ellipseAnnotation(x, y, w, h, options = {}) {
4336
- options.Subtype = 'Circle';
4337
- options.Contents = new String();
4338
- return this.annotate(x, y, w, h, options);
4339
- },
4340
- textAnnotation(x, y, w, h, text, options = {}) {
4341
- options.Subtype = 'FreeText';
4342
- options.Contents = new String(text);
4343
- options.DA = new String();
4344
- return this.annotate(x, y, w, h, options);
4345
- },
4346
- fileAnnotation(x, y, w, h, file = {}, options = {}) {
5207
+ return this.annotate(x, y, w, h, {
5208
+ ...options,
5209
+ QuadPoints: [x1, y2, x2, y2, x1, y1, x2, y1],
5210
+ Contents: new String()
5211
+ });
5212
+ },
5213
+ highlight(x, y, w, h, options) {
5214
+ const annotationOptions = {
5215
+ ...options,
5216
+ Subtype: 'Highlight'
5217
+ };
5218
+ if (annotationOptions.color == null) {
5219
+ annotationOptions.color = [241, 238, 148];
5220
+ }
5221
+ return this._markup(x, y, w, h, annotationOptions);
5222
+ },
5223
+ underline(x, y, w, h, options) {
5224
+ const annotationOptions = {
5225
+ ...options,
5226
+ Subtype: 'Underline'
5227
+ };
5228
+ return this._markup(x, y, w, h, annotationOptions);
5229
+ },
5230
+ strike(x, y, w, h, options) {
5231
+ const annotationOptions = {
5232
+ ...options,
5233
+ Subtype: 'StrikeOut'
5234
+ };
5235
+ return this._markup(x, y, w, h, annotationOptions);
5236
+ },
5237
+ lineAnnotation(x1, y1, x2, y2, options) {
5238
+ const annotationOptions = {
5239
+ ...options,
5240
+ Subtype: 'Line',
5241
+ Contents: new String(),
5242
+ L: [x1, this.page.height - y1, x2, this.page.height - y2]
5243
+ };
5244
+ return this.annotate(x1, y1, x2, y2, annotationOptions);
5245
+ },
5246
+ rectAnnotation(x, y, w, h, options) {
5247
+ const annotationOptions = {
5248
+ ...options,
5249
+ Subtype: 'Square',
5250
+ Contents: new String()
5251
+ };
5252
+ return this.annotate(x, y, w, h, annotationOptions);
5253
+ },
5254
+ ellipseAnnotation(x, y, w, h, options) {
5255
+ const annotationOptions = {
5256
+ ...options,
5257
+ Subtype: 'Circle',
5258
+ Contents: new String()
5259
+ };
5260
+ return this.annotate(x, y, w, h, annotationOptions);
5261
+ },
5262
+ textAnnotation(x, y, w, h, text, options) {
5263
+ const annotationOptions = {
5264
+ ...options,
5265
+ Subtype: 'FreeText',
5266
+ Contents: new String(text),
5267
+ DA: new String()
5268
+ };
5269
+ return this.annotate(x, y, w, h, annotationOptions);
5270
+ },
5271
+ fileAnnotation(x, y, w, h, file = {}, options) {
4347
5272
  const filespec = this.file(file.src, Object.assign({
4348
5273
  hidden: true
4349
5274
  }, file));
4350
- options.Subtype = 'FileAttachment';
4351
- options.FS = filespec;
4352
- if (options.Contents) {
4353
- options.Contents = new String(options.Contents);
5275
+ const annotationOptions = {
5276
+ ...options,
5277
+ Subtype: 'FileAttachment',
5278
+ FS: filespec
5279
+ };
5280
+ if (annotationOptions.Contents) {
5281
+ annotationOptions.Contents = new String(annotationOptions.Contents);
4354
5282
  } else if (filespec.data.Desc) {
4355
- options.Contents = filespec.data.Desc;
5283
+ annotationOptions.Contents = new String(filespec.data.Desc);
4356
5284
  }
4357
- return this.annotate(x, y, w, h, options);
5285
+ return this.annotate(x, y, w, h, annotationOptions);
4358
5286
  },
4359
5287
  _convertRect(x1, y1, w, h) {
4360
5288
  let y2 = y1;
@@ -4875,6 +5803,105 @@ const FORMAT_DEFAULT = {
4875
5803
  sepComma: false
4876
5804
  }
4877
5805
  };
5806
+ function mapTypeAndFlags(type, userOptions, pdfObject) {
5807
+ let flags = userOptions.Ff ?? 0;
5808
+ if (type === 'text') {
5809
+ pdfObject.FT = 'Tx';
5810
+ } else if (type === 'pushButton') {
5811
+ pdfObject.FT = 'Btn';
5812
+ flags |= FIELD_FLAGS.pushButton;
5813
+ } else if (type === 'radioButton') {
5814
+ pdfObject.FT = 'Btn';
5815
+ flags |= FIELD_FLAGS.radioButton;
5816
+ } else if (type === 'checkbox') {
5817
+ pdfObject.FT = 'Btn';
5818
+ } else if (type === 'combo') {
5819
+ pdfObject.FT = 'Ch';
5820
+ flags |= FIELD_FLAGS.combo;
5821
+ } else if (type === 'list') {
5822
+ pdfObject.FT = 'Ch';
5823
+ } else if (type) {
5824
+ throw new Error(`Invalid form annotation type '${type}'`);
5825
+ }
5826
+ Object.keys(userOptions).forEach(key => {
5827
+ if (FIELD_FLAGS[key] && userOptions[key]) {
5828
+ flags |= FIELD_FLAGS[key];
5829
+ }
5830
+ });
5831
+ if (flags !== 0) {
5832
+ pdfObject.Ff = flags;
5833
+ }
5834
+ }
5835
+ function mapJustify(userOptions, pdfObject) {
5836
+ const result = FIELD_JUSTIFY[userOptions.align];
5837
+ if (typeof result === 'number' && result !== 0) {
5838
+ pdfObject.Q = result;
5839
+ }
5840
+ }
5841
+ function mapStrings(options, pdfObject) {
5842
+ if (Array.isArray(options.select) && options.select.length) {
5843
+ pdfObject.Opt = options.select.map(s => {
5844
+ if (typeof s === 'string') {
5845
+ return new String(s);
5846
+ }
5847
+ return s;
5848
+ });
5849
+ }
5850
+ Object.keys(VALUE_MAP).forEach(key => {
5851
+ if (key in options) {
5852
+ const value = options[key] ?? '';
5853
+ pdfObject[VALUE_MAP[key]] = typeof value === 'string' ? new String(value) : value;
5854
+ }
5855
+ });
5856
+ if (options.MK?.CA) {
5857
+ pdfObject.MK = {
5858
+ CA: new String(options.MK.CA)
5859
+ };
5860
+ }
5861
+ if (options.label) {
5862
+ pdfObject.MK = options.MK ?? {};
5863
+ pdfObject.MK.CA = new String(options.label);
5864
+ }
5865
+ }
5866
+ function mapFormat(options, pdfObject) {
5867
+ const f = options.format;
5868
+ if (f?.type) {
5869
+ let fnKeystroke;
5870
+ let fnFormat;
5871
+ let params = '';
5872
+ if (FORMAT_SPECIAL[f.type] !== undefined) {
5873
+ fnKeystroke = `AFSpecial_Keystroke`;
5874
+ fnFormat = `AFSpecial_Format`;
5875
+ params = FORMAT_SPECIAL[f.type];
5876
+ } else {
5877
+ let format = f.type.charAt(0).toUpperCase() + f.type.slice(1);
5878
+ fnKeystroke = `AF${format}_Keystroke`;
5879
+ fnFormat = `AF${format}_Format`;
5880
+ if (f.type === 'date') {
5881
+ fnKeystroke += 'Ex';
5882
+ fnFormat += 'Ex';
5883
+ params = '"' + String(f.param) + '"';
5884
+ } else if (f.type === 'time') {
5885
+ params = String(f.param);
5886
+ } else if (f.type === 'number') {
5887
+ let p = Object.assign({}, FORMAT_DEFAULT.number, f);
5888
+ params = String([String(p.nDec), p.sepComma ? '0' : '1', '"' + p.negStyle + '"', 'null', '"' + p.currency + '"', String(p.currencyPrepend)].join(','));
5889
+ } else if (f.type === 'percent') {
5890
+ let p = Object.assign({}, FORMAT_DEFAULT.percent, f);
5891
+ params = String([String(p.nDec), p.sepComma ? '0' : '1'].join(','));
5892
+ }
5893
+ }
5894
+ pdfObject.AA = options.AA ?? {};
5895
+ pdfObject.AA.K = {
5896
+ S: 'JavaScript',
5897
+ JS: new String(`${fnKeystroke}(${params});`)
5898
+ };
5899
+ pdfObject.AA.F = {
5900
+ S: 'JavaScript',
5901
+ JS: new String(`${fnFormat}(${params});`)
5902
+ };
5903
+ }
5904
+ }
4878
5905
  var AcroFormMixin = {
4879
5906
  initForm() {
4880
5907
  if (!this._font) {
@@ -4973,187 +6000,49 @@ var AcroFormMixin = {
4973
6000
  if (!this._acroform) {
4974
6001
  throw new Error('Call document.initForm() method before adding form elements to document');
4975
6002
  }
4976
- let opts = Object.assign({}, options);
4977
- if (type !== null) {
4978
- opts = this._resolveType(type, options);
4979
- }
4980
- opts = this._resolveFlags(opts);
4981
- opts = this._resolveJustify(opts);
4982
- opts = this._resolveFont(opts);
4983
- opts = this._resolveStrings(opts);
4984
- opts = this._resolveColors(opts);
4985
- opts = this._resolveFormat(opts);
4986
- opts.T = new String(name);
4987
- if (opts.parent) {
4988
- opts.Parent = opts.parent;
4989
- delete opts.parent;
4990
- }
4991
- return opts;
4992
- },
4993
- _resolveType(type, opts) {
4994
- if (type === 'text') {
4995
- opts.FT = 'Tx';
4996
- } else if (type === 'pushButton') {
4997
- opts.FT = 'Btn';
4998
- opts.pushButton = true;
4999
- } else if (type === 'radioButton') {
5000
- opts.FT = 'Btn';
5001
- opts.radioButton = true;
5002
- } else if (type === 'checkbox') {
5003
- opts.FT = 'Btn';
5004
- } else if (type === 'combo') {
5005
- opts.FT = 'Ch';
5006
- opts.combo = true;
5007
- } else if (type === 'list') {
5008
- opts.FT = 'Ch';
5009
- } else {
5010
- throw new Error(`Invalid form annotation type '${type}'`);
5011
- }
5012
- return opts;
5013
- },
5014
- _resolveFormat(opts) {
5015
- const f = opts.format;
5016
- if (f && f.type) {
5017
- let fnKeystroke;
5018
- let fnFormat;
5019
- let params = '';
5020
- if (FORMAT_SPECIAL[f.type] !== undefined) {
5021
- fnKeystroke = `AFSpecial_Keystroke`;
5022
- fnFormat = `AFSpecial_Format`;
5023
- params = FORMAT_SPECIAL[f.type];
5024
- } else {
5025
- let format = f.type.charAt(0).toUpperCase() + f.type.slice(1);
5026
- fnKeystroke = `AF${format}_Keystroke`;
5027
- fnFormat = `AF${format}_Format`;
5028
- if (f.type === 'date') {
5029
- fnKeystroke += 'Ex';
5030
- params = String(f.param);
5031
- } else if (f.type === 'time') {
5032
- params = String(f.param);
5033
- } else if (f.type === 'number') {
5034
- let p = Object.assign({}, FORMAT_DEFAULT.number, f);
5035
- params = String([String(p.nDec), p.sepComma ? '0' : '1', '"' + p.negStyle + '"', 'null', '"' + p.currency + '"', String(p.currencyPrepend)].join(','));
5036
- } else if (f.type === 'percent') {
5037
- let p = Object.assign({}, FORMAT_DEFAULT.percent, f);
5038
- params = String([String(p.nDec), p.sepComma ? '0' : '1'].join(','));
5039
- }
5040
- }
5041
- opts.AA = opts.AA ? opts.AA : {};
5042
- opts.AA.K = {
5043
- S: 'JavaScript',
5044
- JS: new String(`${fnKeystroke}(${params});`)
5045
- };
5046
- opts.AA.F = {
5047
- S: 'JavaScript',
5048
- JS: new String(`${fnFormat}(${params});`)
5049
- };
5050
- }
5051
- delete opts.format;
5052
- return opts;
5053
- },
5054
- _resolveColors(opts) {
5055
- let color = this._normalizeColor(opts.backgroundColor);
6003
+ const pdfObject = {};
6004
+ mapTypeAndFlags(type, options, pdfObject);
6005
+ mapJustify(options, pdfObject);
6006
+ this._mapFont(options, pdfObject);
6007
+ mapStrings(options, pdfObject);
6008
+ this._mapColors(options, pdfObject);
6009
+ mapFormat(options, pdfObject);
6010
+ pdfObject.T = new String(name);
6011
+ if (options.parent) {
6012
+ pdfObject.Parent = options.parent;
6013
+ }
6014
+ return pdfObject;
6015
+ },
6016
+ _mapColors(options, pdfObject) {
6017
+ let color = this._normalizeColor(options.backgroundColor);
5056
6018
  if (color) {
5057
- if (!opts.MK) {
5058
- opts.MK = {};
5059
- }
5060
- opts.MK.BG = color;
6019
+ pdfObject.MK = pdfObject.MK ? pdfObject.MK : {};
6020
+ pdfObject.MK.BG = color;
5061
6021
  }
5062
- color = this._normalizeColor(opts.borderColor);
6022
+ color = this._normalizeColor(options.borderColor);
5063
6023
  if (color) {
5064
- if (!opts.MK) {
5065
- opts.MK = {};
5066
- }
5067
- opts.MK.BC = color;
5068
- }
5069
- delete opts.backgroundColor;
5070
- delete opts.borderColor;
5071
- return opts;
5072
- },
5073
- _resolveFlags(options) {
5074
- let result = 0;
5075
- Object.keys(options).forEach(key => {
5076
- if (FIELD_FLAGS[key]) {
5077
- if (options[key]) {
5078
- result |= FIELD_FLAGS[key];
5079
- }
5080
- delete options[key];
5081
- }
5082
- });
5083
- if (result !== 0) {
5084
- options.Ff = options.Ff ? options.Ff : 0;
5085
- options.Ff |= result;
5086
- }
5087
- return options;
5088
- },
5089
- _resolveJustify(options) {
5090
- let result = 0;
5091
- if (options.align !== undefined) {
5092
- if (typeof FIELD_JUSTIFY[options.align] === 'number') {
5093
- result = FIELD_JUSTIFY[options.align];
6024
+ if (!pdfObject.MK) {
6025
+ pdfObject.MK = {};
5094
6026
  }
5095
- delete options.align;
5096
- }
5097
- if (result !== 0) {
5098
- options.Q = result;
6027
+ pdfObject.MK.BC = color;
5099
6028
  }
5100
- return options;
5101
6029
  },
5102
- _resolveFont(options) {
5103
- if (this._acroform.fonts[this._font.id] == null) {
5104
- this._acroform.fonts[this._font.id] = this._font.ref();
6030
+ _mapFont(options, pdfObject) {
6031
+ const {
6032
+ _acroform,
6033
+ _font
6034
+ } = this;
6035
+ if (_acroform.fonts[_font.id] == null) {
6036
+ _acroform.fonts[_font.id] = _font.ref();
5105
6037
  }
5106
- if (this._acroform.defaultFont !== this._font.name) {
5107
- options.DR = {
6038
+ if (_acroform.defaultFont !== _font.name) {
6039
+ pdfObject.DR = {
5108
6040
  Font: {}
5109
6041
  };
5110
6042
  const fontSize = options.fontSize || 0;
5111
- options.DR.Font[this._font.id] = this._font.ref();
5112
- options.DA = new String(`/${this._font.id} ${fontSize} Tf 0 g`);
5113
- }
5114
- return options;
5115
- },
5116
- _resolveStrings(options) {
5117
- let select = [];
5118
- function appendChoices(a) {
5119
- if (Array.isArray(a)) {
5120
- for (let idx = 0; idx < a.length; idx++) {
5121
- if (typeof a[idx] === 'string') {
5122
- select.push(new String(a[idx]));
5123
- } else {
5124
- select.push(a[idx]);
5125
- }
5126
- }
5127
- }
6043
+ pdfObject.DR.Font[_font.id] = _font.ref();
6044
+ pdfObject.DA = new String(`/${_font.id} ${fontSize} Tf 0 g`);
5128
6045
  }
5129
- appendChoices(options.Opt);
5130
- if (options.select) {
5131
- appendChoices(options.select);
5132
- delete options.select;
5133
- }
5134
- if (select.length) {
5135
- options.Opt = select;
5136
- }
5137
- Object.keys(VALUE_MAP).forEach(key => {
5138
- if (options[key] !== undefined) {
5139
- options[VALUE_MAP[key]] = options[key];
5140
- delete options[key];
5141
- }
5142
- });
5143
- ['V', 'DV'].forEach(key => {
5144
- if (typeof options[key] === 'string') {
5145
- options[key] = new String(options[key]);
5146
- }
5147
- });
5148
- if (options.MK && options.MK.CA) {
5149
- options.MK.CA = new String(options.MK.CA);
5150
- }
5151
- if (options.label) {
5152
- options.MK = options.MK ? options.MK : {};
5153
- options.MK.CA = new String(options.label);
5154
- delete options.label;
5155
- }
5156
- return options;
5157
6046
  }
5158
6047
  };
5159
6048
 
@@ -5169,17 +6058,17 @@ var AttachmentsMixin = {
5169
6058
  if (!src) {
5170
6059
  throw new Error('No src specified');
5171
6060
  }
5172
- if (Buffer.isBuffer(src)) {
6061
+ if (src instanceof Uint8Array) {
5173
6062
  data = src;
5174
6063
  } else if (src instanceof ArrayBuffer) {
5175
- data = Buffer.from(new Uint8Array(src));
6064
+ data = new Uint8Array(src);
5176
6065
  } else {
5177
6066
  const match = /^data:(.*?);base64,(.*)$/.exec(src);
5178
6067
  if (match) {
5179
6068
  if (match[1]) {
5180
6069
  refBody.Subtype = escapeName(match[1]);
5181
6070
  }
5182
- data = Buffer.from(match[2], 'base64');
6071
+ data = fromBase64(match[2]);
5183
6072
  } else {
5184
6073
  data = fs.readFileSync(src);
5185
6074
  if (!data) {
@@ -5247,6 +6136,8 @@ function isEqual(a, b) {
5247
6136
  return a.Subtype === b.Subtype && a.Params.CheckSum.toString() === b.Params.CheckSum.toString() && a.Params.Size === b.Params.Size && a.Params.CreationDate.getTime() === b.Params.CreationDate.getTime() && (a.Params.ModDate === undefined && b.Params.ModDate === undefined || a.Params.ModDate.getTime() === b.Params.ModDate.getTime());
5248
6137
  }
5249
6138
 
6139
+ const ICC_PROFILE_PATH = new URL('./data/sRGB_IEC61966_2_1.icc', (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('pdfkit.js', document.baseURI).href))).href;
6140
+ let iccProfile;
5250
6141
  var PDFA = {
5251
6142
  initPDFA(pSubset) {
5252
6143
  if (pSubset.charAt(pSubset.length - 3) === '-') {
@@ -5262,7 +6153,9 @@ var PDFA = {
5262
6153
  this._addColorOutputIntent();
5263
6154
  },
5264
6155
  _addColorOutputIntent() {
5265
- const iccProfile = fs.readFileSync(`${__dirname}/data/sRGB_IEC61966_2_1.icc`);
6156
+ if (!iccProfile) {
6157
+ iccProfile = fs.readFileSync(ICC_PROFILE_PATH);
6158
+ }
5266
6159
  const colorProfileRef = this.ref({
5267
6160
  Length: iccProfile.length,
5268
6161
  N: 3
@@ -5496,7 +6389,17 @@ function normalizeText(text) {
5496
6389
  function normalizeCell(cell, rowIndex, colIndex) {
5497
6390
  const colStyle = this._colStyle(colIndex);
5498
6391
  let rowStyle = this._rowStyle(rowIndex);
5499
- const font = deepMerge({}, colStyle.font, rowStyle.font, cell.font);
6392
+ const font = {};
6393
+ for (const level of [colStyle.font, rowStyle.font, cell.font]) {
6394
+ if (level == null) continue;
6395
+ if (level.src != null) {
6396
+ font.src = level.src;
6397
+ font.family = level.family;
6398
+ } else if (level.family != null) {
6399
+ font.family = level.family;
6400
+ }
6401
+ if (level.size != null) font.size = level.size;
6402
+ }
5500
6403
  const customFont = Object.values(font).filter(v => v != null).length > 0;
5501
6404
  const doc = this.document;
5502
6405
  const rollbackFont = doc._fontSource;
@@ -6074,14 +6977,14 @@ var MetadataMixin = {
6074
6977
  Subtype: 'XML'
6075
6978
  });
6076
6979
  this.metadataRef.compress = false;
6077
- this.metadataRef.write(Buffer.from(this.metadata.getXML(), 'utf-8'));
6980
+ this.metadataRef.write(new TextEncoder().encode(this.metadata.getXML()));
6078
6981
  this.metadataRef.end();
6079
6982
  this._root.data.Metadata = this.metadataRef;
6080
6983
  }
6081
6984
  }
6082
6985
  };
6083
6986
 
6084
- class PDFDocument extends stream.Readable {
6987
+ class PDFDocument extends Readable {
6085
6988
  constructor(options = {}) {
6086
6989
  super(options);
6087
6990
  this.options = options;
@@ -6166,15 +7069,17 @@ class PDFDocument extends stream.Readable {
6166
7069
  }
6167
7070
  }
6168
7071
  addPage(options) {
6169
- if (options == null) {
6170
- ({
6171
- options
6172
- } = this);
6173
- }
6174
- if (!this.options.bufferPages) {
7072
+ const documentOptions = this.options;
7073
+ if (!documentOptions.bufferPages) {
6175
7074
  this.flushPages();
6176
7075
  }
6177
- this.page = new PDFPage(this, options);
7076
+ const font = options?.font;
7077
+ if (font) {
7078
+ this.font(font, options.fontFamily);
7079
+ }
7080
+ const fontSize = options?.fontSize;
7081
+ if (fontSize) this.fontSize(fontSize);
7082
+ this.page = new PDFPage(this, options || documentOptions);
6178
7083
  this._pageBuffer.push(this.page);
6179
7084
  const pages = this._root.data.Pages.data;
6180
7085
  pages.Kids.push(this.page.dictionary);
@@ -6225,6 +7130,9 @@ class PDFDocument extends stream.Readable {
6225
7130
  this._root.data.Names.data.Dests.add(name, args);
6226
7131
  }
6227
7132
  addNamedEmbeddedFile(name, ref) {
7133
+ if (!ref) {
7134
+ throw new Error(`No ref specified for embedded file ${name}`);
7135
+ }
6228
7136
  if (!this._root.data.Names.data.EmbeddedFiles) {
6229
7137
  this._root.data.Names.data.EmbeddedFiles = new PDFNameTree({
6230
7138
  limits: false
@@ -6250,8 +7158,8 @@ class PDFDocument extends stream.Readable {
6250
7158
  }
6251
7159
  _read() {}
6252
7160
  _write(data) {
6253
- if (!Buffer.isBuffer(data)) {
6254
- data = Buffer.from(data + '\n', 'binary');
7161
+ if (!(data instanceof Uint8Array)) {
7162
+ data = fromBinaryString(data + '\n');
6255
7163
  }
6256
7164
  this.push(data);
6257
7165
  this._offset += data.length;
@@ -6351,7 +7259,31 @@ mixin(AcroFormMixin);
6351
7259
  mixin(AttachmentsMixin);
6352
7260
  mixin(SubsetMixin);
6353
7261
  mixin(TableMixin);
6354
- PDFDocument.LineWrapper = LineWrapper;
6355
7262
 
6356
- module.exports = PDFDocument;
7263
+ const require$1 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('pdfkit.js', document.baseURI).href)));
7264
+ registerStdFontLoaders({
7265
+ Courier: () => require$1('#standard-fonts/Courier'),
7266
+ 'Courier-Bold': () => require$1('#standard-fonts/CourierBold'),
7267
+ 'Courier-BoldOblique': () => require$1('#standard-fonts/CourierBoldOblique'),
7268
+ 'Courier-Oblique': () => require$1('#standard-fonts/CourierOblique'),
7269
+ Helvetica: () => require$1('#standard-fonts/Helvetica'),
7270
+ 'Helvetica-Bold': () => require$1('#standard-fonts/HelveticaBold'),
7271
+ 'Helvetica-BoldOblique': () => require$1('#standard-fonts/HelveticaBoldOblique'),
7272
+ 'Helvetica-Oblique': () => require$1('#standard-fonts/HelveticaOblique'),
7273
+ Symbol: () => require$1('#standard-fonts/Symbol'),
7274
+ 'Times-Bold': () => require$1('#standard-fonts/TimesBold'),
7275
+ 'Times-BoldItalic': () => require$1('#standard-fonts/TimesBoldItalic'),
7276
+ 'Times-Italic': () => require$1('#standard-fonts/TimesItalic'),
7277
+ 'Times-Roman': () => require$1('#standard-fonts/TimesRoman'),
7278
+ ZapfDingbats: () => require$1('#standard-fonts/ZapfDingbats')
7279
+ });
7280
+
7281
+ exports.LineWrapper = LineWrapper;
7282
+ exports.PDFDocument = PDFDocument;
7283
+ exports.default = PDFDocument;
7284
+ exports.registerFile = registerFile;
7285
+ module.exports = exports.default;
7286
+ module.exports.PDFDocument = exports.PDFDocument;
7287
+ module.exports.LineWrapper = exports.LineWrapper;
7288
+ module.exports.registerFile = exports.registerFile;
6357
7289
  //# sourceMappingURL=pdfkit.js.map