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