This repository has been archived by the owner on Dec 10, 2023. It is now read-only.
/
EncodeToolsNative.ts
947 lines (876 loc) · 35.4 KB
/
EncodeToolsNative.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
import {Buffer} from 'buffer';
import EncodeTools, {
BinaryEncoding,
BinaryInputOutput,
CompressionFormat,
EncodingOptions as BaseEncodingOptions,
HashAlgorithm as HashAlgorithmBase,
IDFormat,
InvalidFormat,
SerializationFormat, SerializationFormatMimeTypes
} from './EncodeTools';
import * as cbor from 'cbor';
const ObjSorter = require('node-object-hash/dist/objectSorter');
import * as crypto from 'crypto';
import {CropDims, IEncodeTools, ImageMetadataBase} from "./IEncodeTools";
import * as bson from "bson";
import {ToPojoOptions} from "@thirdact/to-pojo";
export {
BinaryEncoding,
BinaryInputOutput,
EncodingOptions as BaseEncodingOptions,
InvalidFormat,
IDFormat,
SerializationFormat,
CompressionFormat,
EncodeToolsFormat,
EncodeToolsFunction,
SerializationFormatMimeTypes,
} from './EncodeTools';
export enum HashAlgorithm {
/**
* XXHash3
*/
xxhash3 = 'xxhash3',
crc32 = 'crc32',
/**
* Super fast non-cryptographic hashing algorithm.
*/
xxhash64 = 'xxhash64',
/**
* Super fast non-cryptographic hashing algorithm.
*/
xxhash32 = 'xxhash32',
/**
* Super fast non-cryptographic hashing algorithm.
*/
/**
* Insecure hashing algorithm, included for backwards compatibility.
*/
md5 = 'md5',
/**
* SHA2 hashing algorithm.
*/
sha1 = 'sha1',
/**
* SHA512 hashing algorithm.
*/
sha512 = 'sha512',
/**
* SHA2 hashing algorithm.
* @deprecated Use SHA512
*/
sha2 = 'sha2',
/**
* SHA3 hashing algorithm.
*/
sha3 = 'sha3',
/**
* BCrypt hashing algorithm
*/
bcrypt = 'bcrypt',
}
/**
* Format for converting images
*/
export enum ImageFormat {
/**
* PNG Format
*/
png = 'png',
/**
* JPEG Format
*/
jpeg = 'jpeg',
// bmp = 'bmp',
/**
* WEBP Format
*/
webp = 'webp',
/**
* AVIF Format
*/
avif = 'avif',
/**
* TIFF Format
*/
tiff = 'tiff',
/**
* GIF Format
*/
gif = 'gif'
/**
* Export to svg does not work
* @deprecated
*/
// svg = 'svg',
}
/**
* MIME Types for all image formats
*/
export const ImageFormatMimeTypes: Map<ImageFormat, string> = new Map<ImageFormat, string>([
[ ImageFormat.avif, 'image/avif' ],
[ ImageFormat.tiff, 'image/tiff' ],
[ ImageFormat.gif, 'image/gif' ],
[ ImageFormat.png, 'image/png' ],
[ ImageFormat.jpeg, 'image/jpeg' ],
[ ImageFormat.webp, 'image/webp' ]
]);
export interface ConfiguredEncodingOptions {
uniqueIdFormat: IDFormat;
serializationFormat: SerializationFormat;
hashAlgorithm: HashAlgorithm;
binaryEncoding: BinaryEncoding;
compressionFormat: CompressionFormat;
compressionLevel?: number;
imageFormat: ImageFormat;
toPojoOptions?: Partial<ToPojoOptions<unknown, unknown>>
useToPojoBeforeSerializing: boolean;
encodeBuffersWhenUsingToPojo?: boolean;
}
export const DEFAULT_ENCODE_TOOLS_NATIVE_OPTIONS: ConfiguredEncodingOptions = {
binaryEncoding: BinaryEncoding.base64,
hashAlgorithm: HashAlgorithm.xxhash64,
serializationFormat: SerializationFormat.json,
uniqueIdFormat: IDFormat.uuidv1String,
compressionFormat: CompressionFormat.lzma,
imageFormat: ImageFormat.png,
useToPojoBeforeSerializing: false,
encodeBuffersWhenUsingToPojo: false
};
export type EncodingOptions = Partial<ConfiguredEncodingOptions>;
export type ImageMetadata = ImageMetadataBase<ImageFormat>;
/**
* A `SerializationFormat` or `ImageFormat`
*/
export type ConvertableFormat = ImageFormat|SerializationFormat;
/**
* Combined map of all `SerializationFormat` and `ImageFormat` entries to their respective MIME Types
*/
export const ConvertableFormatMimeTypes: Map<ConvertableFormat, string> = new Map<ConvertableFormat, string>(
[
...Array.from(ImageFormatMimeTypes),
...Array.from(SerializationFormatMimeTypes),
]
);
/**
* Map of MIME Type to each `ImageFormat` or `SerializationFormat`.
*/
export const MimeTypesConvertableFormat: Map<string, ConvertableFormat> = new Map<string, ConvertableFormat>(
Array.from(ConvertableFormatMimeTypes.entries()).map(([a,b]) => [b,a])
);
/**
* Contains tools for encoding/decoding data in different circumstances.
*
* Will only attempt to use the native compiled npm libraries, returning an error if they aren't available.
* This class will not work in browsers.
*/
export class EncodeToolsNative extends EncodeTools implements IEncodeTools {
public options: ConfiguredEncodingOptions;
constructor(options?: EncodingOptions) {
super(options);
this.options = {
...super.options,
...DEFAULT_ENCODE_TOOLS_NATIVE_OPTIONS,
...options
};
}
/**
* Combined map of all `SerializationFormat` and `ImageFormat` entries to their respective MIME Types
*/
public get convertableFormatMimeTypes() { return ConvertableFormatMimeTypes; }
/**
* Map of MIME Type to each `ImageFormat` or `SerializationFormat`.
*/
public get mimeTypesConvertableFormat() { return MimeTypesConvertableFormat; }
/**
* Returns an instance of LZMA Native
*/
public static lzmaNative(): any {
if (typeof(require) === 'undefined')
return null;
return require('lzma-native');
}
/**
* Serializes an object as a CBOR-encoded Buffer
*
* @param obj Object to serialize
*/
public static objectToCbor<T>(obj: T): Buffer { return cbor.encode(obj); }
/**
* Deserializes a CBOR-encoded Buffer to an object
*
* @param data CBOR to deserialize
*/
public static cborToObject<T>(data: Buffer): T { return cbor.decode(data) as T; }
// /**
// * Returns an instance of node-zstd
// */
// public static async zstdNative(): Promise<any> {
// if (typeof(require) === 'undefined')
// return null;
// // @ts-ignore
// return require('@etomon/node-zstd');
// }
/**
* Returns an instance of the `bson` node module, using the native `bson-ext` if available.
*
*/
protected static get bson(): any {
let bson = EncodeTools.safeLoadModule('bson-ext');
if (!bson)
bson = require('bson');
return bson;
}
/**
* Returns an instance of XXHash Addon
*/
public static xxhashNative(): any {
if (typeof(require) === 'undefined')
return null;
return require('xxhash-addon');
}
/**
* Returns an instance of Sharp
*/
public static sharpNative(): any {
if (typeof(require) === 'undefined')
return null;
return require('sharp');
}
/**
* Returns an instance of the `ObjectId` constructor `bson` node module, using the native `bson-ext` if available.
*
*/
public static get ObjectId() {
return this.bson.ObjectId;
}
/**
* Hashes using XXHash-3 (https://zb.gy/l4kN), a fast, non-cryptographic,
* hashing function.
*
* Uses XXHash from npm:xxhash-addon
* @param buffer
* @param args
*/
public static async xxhash3(buffer: BinaryInputOutput, ...args: any[]): Promise<Buffer> {
const { XXHash3 } = EncodeToolsNative.xxhashNative();
const xxhash3 = new XXHash3(...args);
let hash = xxhash3.hash(EncodeToolsNative.ensureBuffer(buffer));
return Buffer.from(hash);
}
/**
* Serializes data as BSON, returning the result as a `Buffer`
*
* @param obj Object to serialize
*/
public static objectToBson<T>(obj: T): Buffer { return EncodeToolsNative.bson.serialize(obj); }
/**
* Deserializes a BSON encoded Buffer to an `object`
*
* @param bson BSON to deserialize
*/
public static bsonToObject<T>(bson: Buffer): T {
return EncodeToolsNative.bson.deserialize(bson) as T;
}
/**
* Hashes using XXHash-32 (https://zb.gy/l4kN), a fast, non-cryptographic,
* hashing function.
*
* Uses XXHash from npm:xxhash-addon
* @param buffer
* @param args
*/
public static async xxhash32(buffer: BinaryInputOutput, ...args: any[]): Promise<Buffer> {
const { XXHash32 } = EncodeToolsNative.xxhashNative();
const xxhash32 = new XXHash32(...args);
return Buffer.from(xxhash32.hash(EncodeToolsNative.ensureBuffer(buffer)));
}
/**
* Hashes using XXHash-64 (https://zb.gy/l4kN), a fast, non-cryptographic,
* hashing function.
*
* Uses XXHash from npm:xxhash-addon
* @param buffer
* @param args
*/
public static async xxhash64(buffer: BinaryInputOutput, ...args: any[]): Promise<Buffer> {
const { XXHash64 } = EncodeToolsNative.xxhashNative();
const xxhash64 = new XXHash64(...args);
return Buffer.from(xxhash64.hash(EncodeToolsNative.ensureBuffer(buffer)));
}
protected static nativeHash(buffer: BinaryInputOutput, algo: string): Buffer {
const hash = crypto.createHash(algo);
hash.update(EncodeToolsNative.ensureBuffer(buffer));
return hash.digest();
}
/**
* Uses the very popular, but UNSAFE, SHA-1 cryptographic algorithm.
* Use SHA3 for new projects.
*
* Uses SHA1 from node.js api
* @param buffer
* @param args
*/
public static async sha1(buffer: BinaryInputOutput): Promise<Buffer> {
return EncodeToolsNative.nativeHash(buffer, 'sha1');
}
/**
* Uses the popular, but UNSAFE, 512bit SHA-2 cryptographic algorithm.
* Use SHA3 for new projects.
*
* Uses 512bit SHA from node.js api
* @param buffer
* @param args
* @deprecated Use sha512
*/
public static async sha2(buffer: BinaryInputOutput): Promise<Buffer> {
return EncodeToolsNative.sha512(buffer);
}
/**
* Uses the popular, but UNSAFE, 512bit SHA- cryptographic algorithm.
* Use SHA3 for new projects.
*
* Uses 512bit SHA from node.js api
* @param buffer
* @param args
*/
public static async sha512(buffer: BinaryInputOutput): Promise<Buffer> {
return EncodeToolsNative.nativeHash(buffer, 'sha512');
}
/**
* Uses the very popular, but VERY VERY UNSAFE, MD5 cryptographic algorithm.
* Use SHA3 for new projects.
*
* Uses 512bit SHA from node.js api
* @param buffer
* @param args
*/
public static async md5(buffer: BinaryInputOutput): Promise<Buffer> {
return EncodeToolsNative.nativeHash(buffer, 'md5');
}
/**
* Returns an EncodeTools instance with the default properties
*/
public static get WithDefaults() {
return new EncodeToolsNative();
}
/**
* Compresses a buffer using LZMA
* @param buf - Buffer
* @param level - Compression level (1-9)
*/
public static async compressLZMA(buf: Buffer, level: number): Promise<Buffer> {
let lzma = EncodeToolsNative.lzmaNative();
return lzma.compress(buf, level);
}
/**
* Decompresses a buffer using LZMA
* @param buf - Buffer
* @param level - Compression level (1-9)
*/
public static async decompressLZMA(buf: Buffer): Promise<Buffer> {
let lzma = EncodeToolsNative.lzmaNative();
return new Promise<Buffer>((resolve, reject) => {
lzma.decompress(buf, (result: any, error: any) => {
if (error) reject(error);
else resolve(result);
});
});
}
// /**
// * Compresses a buffer using ZStd
// * @param buf - Buffer
// * @param level - Compression level (1-9)
// */
// public static async compressZStd(buf: Buffer, level: number): Promise<Buffer> {
// return (await EncodeToolsNative.cppzstNative()).compress(buf, level);
// }
//
// /**
// * Decompresses a buffer using ZStd
// * @param buf - Buffer
// * @param level - Compression level (1-9)
// */
// public static async decompressZStd(buf: Buffer): Promise<Buffer> {
// return (await EncodeToolsNative.cppzstNative()).decompress(buf);
// }
/**
* Serializes an object using one of the available algorithms, returning the result as a Buffer or a string
*
* @param obj Object to serialize
* @param serializationFormat - Algorithm to serialize with
* @param useToPojoBeforeSerializing Use `toPojo` on the object before serializing
* @param encodeBuffersWhenUsingToPojo If true, Buffers will be encoded with `this.encodeBuffer` when encountered.
*/
public serializeObject<T>(obj: T, serializationFormat?: SerializationFormat.json, useToPojoBeforeSerializing?: boolean, encodeBuffersWhenUsingToPojo?: boolean): string;
/**
* Serializes an object using one of the available algorithms, returning the result as a Buffer or a string
*
* @param obj Object to serialize
* @param serializationFormat - Algorithm to serialize with
* @param useToPojoBeforeSerializing Use `toPojo` on the object before serializing
* @param encodeBuffersWhenUsingToPojo If true, Buffers will be encoded with `this.encodeBuffer` when encountered.
*/
public serializeObject<T>(obj: T, serializationFormat?: SerializationFormat.json5, useToPojoBeforeSerializing?: boolean, encodeBuffersWhenUsingToPojo?: boolean): string;
/**
* Serializes an object using one of the available algorithms, returning the result as a Buffer or a string
*
* @param obj Object to serialize
* @param serializationFormat - Algorithm to serialize with
* @param useToPojoBeforeSerializing Use `toPojo` on the object before serializing
* @param encodeBuffersWhenUsingToPojo If true, Buffers will be encoded with `this.encodeBuffer` when encountered.
*/
public serializeObject<T>(obj: T, serializationFormat?: SerializationFormat.cbor, useToPojoBeforeSerializing?: boolean, encodeBuffersWhenUsingToPojo?: boolean): Buffer;
/**
* Serializes an object using one of the available algorithms, returning the result as a Buffer or a string
*
* @param obj Object to serialize
* @param serializationFormat - Algorithm to serialize with
* @param useToPojoBeforeSerializing Use `toPojo` on the object before serializing
* @param encodeBuffersWhenUsingToPojo If true, Buffers will be encoded with `this.encodeBuffer` when encountered.
*/
public serializeObject<T>(obj: T, serializationFormat?: SerializationFormat.msgpack, useToPojoBeforeSerializing?: boolean, encodeBuffersWhenUsingToPojo?: boolean): Buffer;
/**
* Serializes an object using one of the available algorithms, returning the result as a Buffer or a string
*
* @param obj Object to serialize
* @param serializationFormat - Algorithm to serialize with
* @param useToPojoBeforeSerializing Use `toPojo` on the object before serializing
* @param encodeBuffersWhenUsingToPojo If true, Buffers will be encoded with `this.encodeBuffer` when encountered.
*/
public serializeObject<T>(obj: T, serializationFormat?: SerializationFormat.bson, useToPojoBeforeSerializing?: boolean, encodeBuffersWhenUsingToPojo?: boolean): Buffer;
/**
* Serializes an object using one of the available algorithms, returning the result as a Buffer or a string
*
* @param obj Object to serialize
* @param serializationFormat - Algorithm to serialize with
* @param useToPojoBeforeSerializing Use `toPojo` on the object before serializing
* @param encodeBuffersWhenUsingToPojo If true, Buffers will be encoded with `this.encodeBuffer` when encountered.
*/
public serializeObject<T>(obj: T, serializationFormat?: SerializationFormat, useToPojoBeforeSerializing?: boolean, encodeBuffersWhenUsingToPojo?: boolean): Buffer;
/**
* Serializes an object using one of the available algorithms, returning the result as a Buffer or a string
*
* @param obj Object to serialize
* @param serializationFormat - Algorithm to serialize with
* @param useToPojoBeforeSerializing Use `toPojo` on the object before serializing
* @param encodeBuffersWhenUsingToPojo If true, Buffers will be encoded with `this.encodeBuffer` when encountered.
*/
public serializeObject<T>(obj: T, serializationFormat: SerializationFormat = this.options.serializationFormat, useToPojoBeforeSerializing: boolean|undefined = this.options.useToPojoBeforeSerializing, encodeBuffersWhenUsingToPojo: undefined|boolean = this.options.encodeBuffersWhenUsingToPojo): Buffer|string {
let convObj: any = obj;
if (useToPojoBeforeSerializing) {
const opts = encodeBuffersWhenUsingToPojo ? EncodeTools.createToPojoOptions(this, this.options.binaryEncoding, { ...this.toPojoInstance.DEFAULT_TO_POJO_OPTIONS, ... this.options.toPojoOptions }) : this.options.toPojoOptions;
convObj = this.toPojoInstance.toPojo(obj, opts);
}
if (serializationFormat === SerializationFormat.cbor) return EncodeToolsNative.objectToCbor<T>(convObj);
else if (serializationFormat === SerializationFormat.bson) return EncodeToolsNative.objectToBson<T>(convObj);
return super.serializeObject<T>(obj, serializationFormat, useToPojoBeforeSerializing);
}
/**
* Deserializes an object serialized using one of the available algorithms, returning the result as an object
*
* @param data Data to deserialize
* @param serializationFormat - Algorithm to deserialize with
*/
public deserializeObject<T>(data: Buffer|ArrayBuffer|string, serializationFormat?: SerializationFormat.json): T;
/**
* Deserializes an object serialized using one of the available algorithms, returning the result as an object
*
* @param data Data to deserialize
* @param serializationFormat - Algorithm to deserialize with
*/
public deserializeObject<T>(data: Buffer|ArrayBuffer|string, serializationFormat?: SerializationFormat.json5): T;
/**
* Deserializes an object serialized using one of the available algorithms, returning the result as an object
*
* @param data Data to deserialize
* @param serializationFormat - Algorithm to deserialize with
*/
public deserializeObject<T>(data: Buffer|ArrayBuffer, serializationFormat?: SerializationFormat.cbor): T;
/**
* Deserializes an object serialized using one of the available algorithms, returning the result as an object
*
* @param data Data to deserialize
* @param serializationFormat - Algorithm to deserialize with
*/
public deserializeObject<T>(data: Buffer|ArrayBuffer, serializationFormat?: SerializationFormat.msgpack): T;
/**
* Deserializes an object serialized using one of the available algorithms, returning the result as an object
*
* @param data Data to deserialize
* @param serializationFormat - Algorithm to deserialize with
*/
public deserializeObject<T>(data: Buffer|ArrayBuffer, serializationFormat?: SerializationFormat.bson): T;
/**
* Deserializes an object serialized using one of the available algorithms, returning the result as an object
*
* @param data Data to deserialize
* @param serializationFormat - Algorithm to deserialize with
*/
public deserializeObject<T>(data: Buffer|ArrayBuffer, serializationFormat?: SerializationFormat): T;
/**
* Deserializes an object serialized using one of the available algorithms, returning the result as an object
*
* @param data Data to deserialize
* @param serializationFormat - Algorithm to deserialize with
*/
public deserializeObject<T>(data: Buffer|ArrayBuffer|string, serializationFormat: SerializationFormat = this.options.serializationFormat): T {
if (serializationFormat === SerializationFormat.cbor) return EncodeToolsNative.cborToObject<T>(EncodeTools.ensureBuffer(data)) as T;
else if (serializationFormat === SerializationFormat.bson) return EncodeToolsNative.bsonToObject<T>(EncodeTools.ensureBuffer(data)) as T;
return super.deserializeObject<T>(data as Buffer|ArrayBuffer, serializationFormat);
}
/**
* Compresses arbitrary data using the provided format and any options
* @param data - Data to compress
* @param format - Format to use
* @param args - Options
*/
public async compress(data: Buffer|ArrayBuffer, format?: CompressionFormat.lzma, level?: number, ...args: any[]): Promise<Buffer>;
/**
* Compresses arbitrary data using the provided format and any options
* @param data - Data to compress
* @param format - Format to use
* @param args - Options
*/
public async compress(data: Buffer|ArrayBuffer, format?: CompressionFormat.zstd, level?: number, ...args: any[]): Promise<Buffer>;
/**
* Compresses arbitrary data using the provided format and any options
* @param data - Data to compress
* @param format - Format to use
* @param args - Options
*/
public async compress(data: BinaryInputOutput, format?: CompressionFormat, level?: number, ...args: any[]): Promise<Buffer>;
/**
* Compresses arbitrary data using the provided format and any options
* @param data - Data to compress
* @param format - Format to use
* @param args - Options
*/
public async compress(data: BinaryInputOutput, format: CompressionFormat = this.options.compressionFormat, level: number = this.options.compressionLevel, ...args: any[]): Promise<Buffer> {
if (format === CompressionFormat.lzma) {
return EncodeToolsNative.compressLZMA(EncodeToolsNative.ensureBuffer(data), level);
}
// else if (format === CompressionFormat.zstd) {
// return EncodeToolsNative.compressZStd(EncodeToolsNative.ensureBuffer(data), level);
// }
return super.compress(data, format, level);
}
/**
* Decompresses arbitrary data using the provided format and any options
* @param data - Data to decompress
* @param format - Format to use
*/
public async decompress(data: Buffer|ArrayBuffer, format: CompressionFormat.lzma, ...args: any[]): Promise<Buffer>;
/**
* Decompresses arbitrary data using the provided format and any options
* @param data - Data to decompress
* @param format - Format to use
*/
public async decompress(data: Buffer|ArrayBuffer, format: CompressionFormat.zstd, ...args: any[]): Promise<Buffer>;
/**
* Decompresses arbitrary data using the provided format and any options
* @param data - Data to decompress
* @param format - Format to use
*/
public async decompress(data: BinaryInputOutput, format: CompressionFormat, ...args: any[]): Promise<Buffer>;
/**
* Decompresses arbitrary data using the provided format and any options
* @param data - Data to decompress
* @param format - Format to use
*/
public async decompress(data: BinaryInputOutput, format: CompressionFormat = this.options.compressionFormat, ...args: any[]): Promise<Buffer> {
if (format === CompressionFormat.lzma) {
return EncodeToolsNative.decompressLZMA(EncodeToolsNative.ensureBuffer(data));
}
// else if (format === CompressionFormat.zstd) {
// return EncodeToolsNative.decompressZStd(EncodeToolsNative.ensureBuffer(data));
// }
return super.decompress(data, format);
}
/**
* Crops an image and returns a Buffer containing the result in the provided format
* @param buffer - Image
* @param dims - Height/Width to resize to
* @param format - Format to save result as
*/
public async cropImage(buffer: Buffer|ArrayBuffer, dims: CropDims, format?: ImageFormat.png): Promise<Buffer>;
/**
* Crops an image and returns a Buffer containing the result in the provided format
* @param buffer - Image
* @param dims - Height/Width to resize to
* @param format - Format to save result as
*/
public async cropImage(buffer: Buffer|ArrayBuffer, dims: CropDims, format?: ImageFormat.jpeg): Promise<Buffer>;
/**
* Crops an image and returns a Buffer containing the result in the provided format
* @param buffer - Image
* @param dims - Height/Width to resize to
* @param format - Format to save result as
*/
public async cropImage(buffer: Buffer|ArrayBuffer, dims: CropDims, format?: ImageFormat.webp): Promise<Buffer>;
/**
* Crops an image and returns a Buffer containing the result in the provided format
* @param buffer - Image
* @param dims - Height/Width to resize to
* @param format - Format to save result as
*/
public async cropImage(buffer: Buffer|ArrayBuffer, dims: CropDims, format?: ImageFormat.avif): Promise<Buffer>;
/**
* Crops an image and returns a Buffer containing the result in the provided format
* @param buffer - Image
* @param dims - Height/Width to resize to
* @param format - Format to save result as
*/
public async cropImage(buffer: Buffer|ArrayBuffer, dims: CropDims, format?: ImageFormat.tiff): Promise<Buffer>;
// public async cropImage(buffer: Buffer|ArrayBuffer|string, dims: CropDims, format?: ImageFormat.svg): Promise<Buffer>;
/**
* Crops an image and returns a Buffer containing the result in the provided format
* @param data - Image
* @param dims - Height/Width to resize to
* @param format - Format to save result as
*/
public async cropImage(data: BinaryInputOutput, dims: CropDims, format?: ImageFormat): Promise<Buffer>;
/**
* Crops an image and returns a Buffer containing the result in the provided format
* @param data - Image
* @param dims - Height/Width to resize to
* @param format - Format to save result as
*/
public async cropImage(data: BinaryInputOutput, dims: CropDims, format: ImageFormat = this.options.imageFormat): Promise<Buffer> {
// if (format === ImageFormat.bmp)
// return super.resizeImage(data, dims, format);
let sharp = EncodeToolsNative.sharpNative()(EncodeTools.ensureBuffer(data));
return await sharp.extract(dims).toFormat(format.toString()).toBuffer();
}
/**
* Resizes an image and returns a Buffer containing the result in the provided format
* @param buffer - Image
* @param dims - Height/Width to resize to
* @param format - Format to save result as
*/
public async resizeImage(buffer: Buffer|ArrayBuffer, dims: { height: number, width?: number }|{ height?: number, width: number }, format?: ImageFormat.png): Promise<Buffer>;
/**
* Resizes an image and returns a Buffer containing the result in the provided format
* @param buffer - Image
* @param dims - Height/Width to resize to
* @param format - Format to save result as
*/
public async resizeImage(buffer: Buffer|ArrayBuffer, dims: { height: number, width?: number }|{ height?: number, width: number }, format?: ImageFormat.jpeg): Promise<Buffer>;
/**
* Resizes an image and returns a Buffer containing the result in the provided format
* @param buffer - Image
* @param dims - Height/Width to resize to
* @param format - Format to save result as
*/
public async resizeImage(buffer: Buffer|ArrayBuffer, dims: { height: number, width?: number }|{ height?: number, width: number }, format?: ImageFormat.webp): Promise<Buffer>;
/**
* Resizes an image and returns a Buffer containing the result in the provided format
* @param buffer - Image
* @param dims - Height/Width to resize to
* @param format - Format to save result as
*/
public async resizeImage(buffer: Buffer|ArrayBuffer, dims: { height: number, width?: number }|{ height?: number, width: number }, format?: ImageFormat.avif): Promise<Buffer>;
/**
* Resizes an image and returns a Buffer containing the result in the provided format
* @param buffer - Image
* @param dims - Height/Width to resize to
* @param format - Format to save result as
*/
public async resizeImage(buffer: Buffer|ArrayBuffer, dims: { height: number, width?: number }|{ height?: number, width: number }, format?: ImageFormat.tiff): Promise<Buffer>;
// public async resizeImage(buffer: Buffer|ArrayBuffer|string, dims: { height: number, width?: number }|{ height?: number, width: number }, format?: ImageFormat.svg): Promise<Buffer>;
/**
* Resizes an image and returns a Buffer containing the result in the provided format
* @param data - Image
* @param dims - Height/Width to resize to
* @param format - Format to save result as
*/
public async resizeImage(data: BinaryInputOutput, dims: { height: number, width?: number }|{ height?: number, width: number }, format?: ImageFormat): Promise<Buffer>;
/**
* Resizes an image and returns a Buffer containing the result in the provided format
* @param data - Image
* @param dims - Height/Width to resize to
* @param format - Format to save result as
*/
public async resizeImage(data: BinaryInputOutput, dims: { height: number, width?: number }|{ height?: number, width: number }, format: ImageFormat = this.options.imageFormat): Promise<Buffer> {
// if (format === ImageFormat.bmp)
// return super.resizeImage(data, dims, format);
let sharp = EncodeToolsNative.sharpNative()(EncodeTools.ensureBuffer(data));
return await sharp.resize(dims).toFormat(format.toString()).toBuffer();
}
/**
* Saves an image in the provided format, performing no operations on the image
* @param data - Image
* @param format - Format to save result as
*/
public async convertImage(buffer: Buffer|ArrayBuffer, format?: ImageFormat.png): Promise<Buffer>;
/**
* Saves an image in the provided format, performing no operations on the image
* @param data - Image
* @param format - Format to save result as
*/
public async convertImage(buffer: Buffer|ArrayBuffer, format?: ImageFormat.jpeg): Promise<Buffer>;
/**
* Saves an image in the provided format, performing no operations on the image
* @param data - Image
* @param format - Format to save result as
*/
public async convertImage(buffer: Buffer|ArrayBuffer, format?: ImageFormat.webp): Promise<Buffer>;
/**
* Saves an image in the provided format, performing no operations on the image
* @param data - Image
* @param format - Format to save result as
*/
public async convertImage(buffer: Buffer|ArrayBuffer, format?: ImageFormat.avif): Promise<Buffer>;
/**
* Saves an image in the provided format, performing no operations on the image
* @param data - Image
* @param format - Format to save result as
*/
public async convertImage(buffer: Buffer|ArrayBuffer, format?: ImageFormat.tiff): Promise<Buffer>;
// public async convertImage(buffer: Buffer|ArrayBuffer|string, format?: ImageFormat.svg): Promise<Buffer>;
/**
* Saves an image in the provided format, performing no operations on the image
* @param data - Image
* @param format - Format to save result as
*/
public async convertImage(data: BinaryInputOutput, format?: ImageFormat): Promise<Buffer>;
/**
* Saves an image in the provided format, performing no operations on the image
* @param data - Image
* @param format - Format to save result as
*/
public async convertImage(data: BinaryInputOutput, format: ImageFormat = this.options.imageFormat): Promise<Buffer> {
// if (format === ImageFormat.bmp)
// return super.resizeImage(data, format);
let sharp = EncodeToolsNative.sharpNative()(EncodeTools.ensureBuffer(data));
return await sharp.toFormat(format.toString()).toBuffer();
}
/**
* Adjust brightness of image
* @param buffer - Image
* @param dims - Height/Width to resize to
* @param format - Format to save result as
*/
public async adjustImageBrightness(buffer: Buffer|ArrayBuffer, factor: number, format?: ImageFormat.png): Promise<Buffer>;
/**
* Adjust brightness of image
* @param buffer - Image
* @param dims - Height/Width to resize to
* @param format - Format to save result as
*/
public async adjustImageBrightness(buffer: Buffer|ArrayBuffer, factor: number, format?: ImageFormat.jpeg): Promise<Buffer>;
/**
* Adjust brightness of image
* @param buffer - Image
* @param dims - Height/Width to resize to
* @param format - Format to save result as
*/
public async adjustImageBrightness(buffer: Buffer|ArrayBuffer, factor: number, format?: ImageFormat.webp): Promise<Buffer>;
/**
* Adjust brightness of image
* @param buffer - Image
* @param dims - Height/Width to resize to
* @param format - Format to save result as
*/
public async adjustImageBrightness(buffer: Buffer|ArrayBuffer, factor: number, format?: ImageFormat.avif): Promise<Buffer>;
/**
* Adjust brightness of image
* @param buffer - Image
* @param dims - Height/Width to resize to
* @param format - Format to save result as
*/
public async adjustImageBrightness(buffer: Buffer|ArrayBuffer, factor: number, format?: ImageFormat.tiff): Promise<Buffer>;
// public async adjustImageBrightness(buffer: Buffer|ArrayBuffer|string, factor: number, format?: ImageFormat.svg): Promise<Buffer>;
/**
* Adjust brightness of image
* @param data - Image
* @param dims - Height/Width to resize to
* @param format - Format to save result as
*/
public async adjustImageBrightness(data: BinaryInputOutput, factor: number, format?: ImageFormat): Promise<Buffer>;
/**
* Adjust brightness of image
* @param data - Image
* @param dims - Height/Width to resize to
* @param format - Format to save result as
*/
public async adjustImageBrightness(data: BinaryInputOutput, factor: number, format: ImageFormat = this.options.imageFormat): Promise<Buffer> {
let sharp = EncodeToolsNative.sharpNative()(EncodeTools.ensureBuffer(data));
return await sharp.modulate({ brightness: 1+factor }).toFormat(format.toString()).toBuffer();
}
/**
* Gets metadata of the image provided as a buffer
* @param buffer - Image
*/
public static async getImageMetadata(buffer: Buffer|ArrayBuffer): Promise<ImageMetadata>;
/**
* Gets metadata of the image provided as a buffer
* @param buffer - Image
*/
public static async getImageMetadata(buffer: Buffer|ArrayBuffer): Promise<ImageMetadata>;
/**
* Gets metadata of the image provided as a buffer
* @param buffer - Image
*/
public static async getImageMetadata(buffer: string): Promise<ImageMetadata>;
/**
* Gets metadata of the image provided as a buffer
* @param data - Image
*/
public static async getImageMetadata(data: BinaryInputOutput): Promise<ImageMetadata>;
/**
* Gets metadata of the image provided as a buffer
* @param data - Image
*/
public static async getImageMetadata(data: BinaryInputOutput): Promise<ImageMetadata> {
let sharp = EncodeToolsNative.sharpNative()(EncodeTools.ensureBuffer(data));
let meta = await sharp.metadata();
return {
format: meta.format as ImageFormat,
height: meta.height,
width: meta.width
}
}
/**
* Hashes data using the provided algorithm, returning a node.js Buffer.
*
* @param buffer
* @param algorithm
*/
public async hashString(buffer: BinaryInputOutput, algorithm: HashAlgorithm = this.options.hashAlgorithm, ...args: any[]): Promise<string> {
let buf = (await this.hash(EncodeTools.ensureBuffer(buffer), algorithm, ...args));
return buf.toString('hex');
}
/**
* Hashes an object using the provided algorithm, returning a node.js Buffer.
*
* @param buffer
* @param algorithm
*/
public async hashObject(obj: any, algorithm: HashAlgorithm = this.options.hashAlgorithm, ...args: any[]): Promise<Buffer> {
// @ts-ignore
let sorter = ObjSorter();
let buffer = EncodeTools.ensureBuffer(
sorter(obj)
);
return (await this.hash(buffer, algorithm, ...args));
}
/**
* Hashes data using the provided algorithm, returning a node.js Buffer.
*
* @param buffer
* @param algorithm
*/
public async hash(buffer: BinaryInputOutput, algorithm: HashAlgorithm = this.options.hashAlgorithm, ...args: any[]): Promise<Buffer> {
if (algorithm === HashAlgorithm.xxhash3) return EncodeToolsNative.xxhash3(buffer, ...args);
else if (algorithm === HashAlgorithm.xxhash64) return EncodeToolsNative.xxhash64(buffer, ...args);
else if (algorithm === HashAlgorithm.xxhash32) return EncodeToolsNative.xxhash32(buffer, ...args);
else if (algorithm === HashAlgorithm.sha1) return EncodeToolsNative.sha1(buffer);
else if (algorithm === HashAlgorithm.sha2) return EncodeToolsNative.sha2(buffer);
else if (algorithm === HashAlgorithm.sha512) return EncodeToolsNative.sha512(buffer);
else if (algorithm === HashAlgorithm.md5) return EncodeToolsNative.md5(buffer);
return super.hash(buffer, algorithm);
}
}
export default EncodeToolsNative;