pdfkit 0.19.1 → 0.20.0

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