react-native-quick-crypto 0.4.5 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -25,13 +25,13 @@ const end = performance.now()
25
25
  console.log(`Creating a Wallet took ${end - start} ms.`)
26
26
  ```
27
27
 
28
- **Without** react-native-crypto 🐢:
28
+ **Without** react-native-quick-crypto 🐢:
29
29
 
30
30
  ```
31
31
  Creating a Wallet took 16862 ms
32
32
  ```
33
33
 
34
- **With** react-native-crypto ⚡️:
34
+ **With** react-native-quick-crypto ⚡️:
35
35
 
36
36
  ```
37
37
  Creating a Wallet took 289 ms
@@ -451,9 +451,6 @@ void MGLCipherHostObject::installMethods() {
451
451
  "setAuthTag", JSIF([=]) {
452
452
  if (count != 1 || !arguments[0].isObject() ||
453
453
  !arguments[0].asObject(runtime).isArrayBuffer(runtime)) {
454
- jsi::detail::throwJSError(
455
- runtime,
456
- "cipher.setAuthTag requires an ArrayBuffer tag argument");
457
454
  throw jsi::JSError(
458
455
  runtime,
459
456
  "cipher.setAuthTag requires an ArrayBuffer tag argument");
@@ -467,9 +464,6 @@ void MGLCipherHostObject::installMethods() {
467
464
  auto authTagArrayBuffer =
468
465
  arguments[0].asObject(runtime).getArrayBuffer(runtime);
469
466
  if (!CheckSizeInt32(runtime, authTagArrayBuffer)) {
470
- jsi::detail::throwJSError(
471
- runtime,
472
- "cipher.setAuthTag requires an ArrayBuffer tag argument");
473
467
  throw jsi::JSError(
474
468
  runtime,
475
469
  "cipher.setAuthTag requires an ArrayBuffer tag argument");
@@ -502,8 +496,6 @@ void MGLCipherHostObject::installMethods() {
502
496
  }
503
497
 
504
498
  if (!is_valid) {
505
- jsi::detail::throwJSError(runtime,
506
- "Invalid authentication tag length");
507
499
  throw jsi::JSError(runtime, "Invalid authentication tag length");
508
500
  }
509
501
 
@@ -57,20 +57,17 @@ FieldDefinition getPublicCipherFieldDefinition(
57
57
  runtime, arguments, &offset);
58
58
 
59
59
  if (!pkey) {
60
- jsi::detail::throwJSError(runtime, "Could not generate key");
61
60
  throw new jsi::JSError(runtime, "Could not generate key");
62
61
  }
63
62
 
64
63
  auto buf = arguments[offset].asObject(runtime).getArrayBuffer(runtime);
65
64
  if (!CheckSizeInt32(runtime, buf)) {
66
- jsi::detail::throwJSError(runtime, "Data buffer is too long");
67
65
  throw new jsi::JSError(runtime, "Data buffer is too long");
68
66
  }
69
67
 
70
68
  uint32_t padding =
71
69
  static_cast<uint32_t>(arguments[offset + 1].getNumber());
72
70
  if (!padding) {
73
- jsi::detail::throwJSError(runtime, "Invalid padding");
74
71
  throw new jsi::JSError(runtime, "Invalid padding");
75
72
  }
76
73
 
@@ -81,7 +78,6 @@ FieldDefinition getPublicCipherFieldDefinition(
81
78
 
82
79
  digest = EVP_get_digestbyname(oaep_str.c_str());
83
80
  if (digest == nullptr) {
84
- jsi::detail::throwJSError(runtime, "Invalid digest (oaep_str)");
85
81
  throw new jsi::JSError(runtime, "Invalid digest (oaep_str)");
86
82
  }
87
83
  }
@@ -90,7 +86,6 @@ FieldDefinition getPublicCipherFieldDefinition(
90
86
  auto oaep_label_buffer =
91
87
  arguments[offset + 3].getObject(runtime).getArrayBuffer(runtime);
92
88
  if (!CheckSizeInt32(runtime, oaep_label_buffer)) {
93
- jsi::detail::throwJSError(runtime, "oaep_label buffer is too long");
94
89
  throw new jsi::JSError(runtime, "oaep_label buffer is too long");
95
90
  }
96
91
  }
@@ -101,7 +96,6 @@ FieldDefinition getPublicCipherFieldDefinition(
101
96
  runtime, pkey, padding, digest, arguments[offset + 3], buf);
102
97
 
103
98
  if (!out.has_value()) {
104
- jsi::detail::throwJSError(runtime, "Failed to decrypt");
105
99
  throw new jsi::JSError(runtime, "Failed to decrypt");
106
100
  }
107
101
 
@@ -108,7 +108,6 @@ RsaKeyPairGenConfig prepareRsaKeyGenConfig(jsi::Runtime& runtime,
108
108
  arguments[offset].asString(runtime).utf8(runtime).c_str());
109
109
 
110
110
  if (config.md == nullptr) {
111
- jsi::detail::throwJSError(runtime, "invalid digest");
112
111
  throw new jsi::JSError(runtime, "invalid digest");
113
112
  }
114
113
  }
@@ -119,7 +118,6 @@ RsaKeyPairGenConfig prepareRsaKeyGenConfig(jsi::Runtime& runtime,
119
118
  arguments[offset + 1].asString(runtime).utf8(runtime).c_str());
120
119
 
121
120
  if (config.mgf1_md == nullptr) {
122
- jsi::detail::throwJSError(runtime, "invalid digest");
123
121
  throw new jsi::JSError(runtime, "invalid digest");
124
122
  }
125
123
  }
@@ -129,7 +127,6 @@ RsaKeyPairGenConfig prepareRsaKeyGenConfig(jsi::Runtime& runtime,
129
127
  config.saltlen = static_cast<int>(arguments[offset + 2].asNumber());
130
128
 
131
129
  if (config.saltlen < 0) {
132
- jsi::detail::throwJSError(runtime, "salt length is out of range");
133
130
  throw new jsi::JSError(runtime, "salt length is out of range");
134
131
  }
135
132
  }
@@ -157,14 +154,12 @@ std::pair<StringOrBuffer, StringOrBuffer> generateRSAKeyPair(
157
154
  EVPKeyCtxPointer ctx = setup(config);
158
155
 
159
156
  if (!ctx) {
160
- jsi::detail::throwJSError(runtime, "Error on key generation job");
161
157
  throw new jsi::JSError(runtime, "Error on key generation job");
162
158
  }
163
159
 
164
160
  // Generate the key
165
161
  EVP_PKEY* pkey = nullptr;
166
162
  if (!EVP_PKEY_keygen(ctx.get(), &pkey)) {
167
- jsi::detail::throwJSError(runtime, "Error generating key");
168
163
  throw new jsi::JSError(runtime, "Error generating key");
169
164
  }
170
165
 
@@ -178,7 +173,7 @@ std::pair<StringOrBuffer, StringOrBuffer> generateRSAKeyPair(
178
173
  config->private_key_encoding);
179
174
 
180
175
  if (!publicBuffer.has_value() || !privateBuffer.has_value()) {
181
- jsi::detail::throwJSError(runtime,
176
+ throw jsi::JSError(runtime,
182
177
  "Failed to encode public and/or private key");
183
178
  }
184
179
 
package/cpp/MGLKeys.cpp CHANGED
@@ -348,8 +348,7 @@ std::optional<StringOrBuffer> WritePrivateKey(
348
348
  }
349
349
 
350
350
  if (err) {
351
- jsi::detail::throwJSError(runtime, "Failed to encode private key");
352
- return {};
351
+ throw jsi::JSError(runtime, "Failed to encode private key");
353
352
  }
354
353
 
355
354
  return BIOToStringOrBuffer(bio.get(), config.format_);
@@ -389,8 +388,7 @@ std::optional<StringOrBuffer> WritePublicKey(
389
388
  // CHECK(bio);
390
389
 
391
390
  if (!WritePublicKeyInner(pkey, bio, config)) {
392
- jsi::detail::throwJSError(runtime, "Failed to encode public key");
393
- return std::nullopt;
391
+ throw jsi::JSError(runtime, "Failed to encode public key");
394
392
  }
395
393
 
396
394
  return BIOToStringOrBuffer(bio.get(), config.format_);
@@ -648,8 +646,7 @@ ManagedEVPPKey::GetPrivateKeyEncodingFromJs(jsi::Runtime& runtime,
648
646
  auto cipher_name = arguments[*offset].getString(runtime).utf8(runtime);
649
647
  result.cipher_ = EVP_get_cipherbyname(cipher_name.c_str());
650
648
  if (result.cipher_ == nullptr) {
651
- jsi::detail::throwJSError(runtime, "Unknown cipher");
652
- return NonCopyableMaybe<PrivateKeyEncodingConfig>();
649
+ throw jsi::JSError(runtime, "Unknown cipher");
653
650
  }
654
651
  needs_passphrase = true;
655
652
  } else {
@@ -666,7 +663,7 @@ ManagedEVPPKey::GetPrivateKeyEncodingFromJs(jsi::Runtime& runtime,
666
663
  jsi::ArrayBuffer passphrase =
667
664
  arguments[*offset].asObject(runtime).getArrayBuffer(runtime);
668
665
  if (!CheckSizeInt32(runtime, passphrase)) {
669
- jsi::detail::throwJSError(runtime, "passphrase is too long");
666
+ throw jsi::JSError(runtime, "passphrase is too long");
670
667
  }
671
668
 
672
669
  result.passphrase_ = NonCopyableMaybe<ByteSource>(
@@ -674,7 +671,7 @@ ManagedEVPPKey::GetPrivateKeyEncodingFromJs(jsi::Runtime& runtime,
674
671
  } else {
675
672
  if (needs_passphrase &&
676
673
  (arguments[*offset].isNull() || arguments[*offset].isUndefined())) {
677
- jsi::detail::throwJSError(
674
+ throw jsi::JSError(
678
675
  runtime, "passphrase is null or unfedined but it is required");
679
676
  }
680
677
  }
@@ -728,7 +725,7 @@ ManagedEVPPKey ManagedEVPPKey::GetPublicOrPrivateKeyFromJs(
728
725
  args[(*offset)++].asObject(runtime).getArrayBuffer(runtime);
729
726
 
730
727
  if (!CheckSizeInt32(runtime, dataArrayBuffer)) {
731
- jsi::detail::throwJSError(runtime, "data is too big");
728
+ throw jsi::JSError(runtime, "data is too big");
732
729
  }
733
730
 
734
731
  NonCopyableMaybe<PrivateKeyEncodingConfig> config_ =
@@ -766,7 +763,6 @@ ManagedEVPPKey ManagedEVPPKey::GetPublicOrPrivateKeyFromJs(
766
763
  is_public = false;
767
764
  break;
768
765
  default:
769
- jsi::detail::throwJSError(runtime, "Invalid key encoding type");
770
766
  throw new jsi::JSError(runtime, "Invalid key encoding type");
771
767
  }
772
768
 
@@ -784,9 +780,6 @@ ManagedEVPPKey ManagedEVPPKey::GetPublicOrPrivateKeyFromJs(
784
780
  return ManagedEVPPKey::GetParsedKey(runtime, std::move(pkey), ret,
785
781
  "Failed to read asymmetric key");
786
782
  } else {
787
- jsi::detail::throwJSError(runtime,
788
- "publicEncrypt api only supports ArrayBuffer keys"
789
- "for now");
790
783
  throw new jsi::JSError(
791
784
  runtime, "public encrypt only supports ArrayBuffer at the moment");
792
785
  // CHECK(args[*offset]->IsObject());
@@ -808,11 +801,10 @@ ManagedEVPPKey ManagedEVPPKey::GetParsedKey(jsi::Runtime& runtime,
808
801
  // CHECK(pkey);
809
802
  break;
810
803
  case ParseKeyResult::kParseKeyNeedPassphrase:
811
- jsi::detail::throwJSError(runtime,
804
+ throw jsi::JSError(runtime,
812
805
  "Passphrase required for encrypted key");
813
806
  break;
814
807
  default:
815
- jsi::detail::throwJSError(runtime, default_msg);
816
808
  throw new jsi::JSError(runtime, default_msg);
817
809
  }
818
810
 
@@ -350,7 +350,7 @@ void SignBase::InstallMethods(mode mode) {
350
350
  this->fields.push_back(buildPair(
351
351
  "init", JSIF([=]) {
352
352
  if (count != 1 || !arguments[0].isString()) {
353
- jsi::detail::throwJSError(runtime, "init requires algorithm param");
353
+ throw jsi::JSError(runtime, "init requires algorithm param");
354
354
  return {};
355
355
  }
356
356
 
@@ -378,19 +378,19 @@ void SignBase::InstallMethods(mode mode) {
378
378
  this->fields.push_back(buildPair(
379
379
  "update", JSIF([=]) {
380
380
  if (count != 1) {
381
- jsi::detail::throwJSError(runtime, "update requires 2 arguments");
381
+ throw jsi::JSError(runtime, "update requires 2 arguments");
382
382
  }
383
383
 
384
384
  if (!arguments[0].isObject() ||
385
385
  !arguments[0].asObject(runtime).isArrayBuffer(runtime)) {
386
- jsi::detail::throwJSError(
386
+ throw jsi::JSError(
387
387
  runtime, "First argument (data) needs to be an array buffer");
388
388
  }
389
389
 
390
390
  auto data = arguments[0].asObject(runtime).getArrayBuffer(runtime);
391
391
 
392
392
  if (!CheckSizeInt32(runtime, data)) {
393
- jsi::detail::throwJSError(runtime, "data is too large");
393
+ throw jsi::JSError(runtime, "data is too large");
394
394
  }
395
395
 
396
396
  if (mdctx_ == nullptr) return (int)kSignNotInitialised;
@@ -433,7 +433,6 @@ void SignBase::InstallMethods(mode mode) {
433
433
  this->SignFinal(runtime, key, padding, salt_len, dsa_sig_enc);
434
434
 
435
435
  if (ret.error != kSignOk) {
436
- jsi::detail::throwJSError(runtime, "Error signing");
437
436
  throw new jsi::JSError(runtime, "Error signing");
438
437
  }
439
438
 
@@ -455,7 +454,6 @@ void SignBase::InstallMethods(mode mode) {
455
454
  jsi::ArrayBuffer hbuf =
456
455
  arguments[offset].asObject(runtime).getArrayBuffer(runtime);
457
456
  if (!CheckSizeInt32(runtime, hbuf)) {
458
- jsi::detail::throwJSError(runtime, "buffer is too big");
459
457
  throw jsi::JSError(runtime, "buffer is too big");
460
458
  }
461
459
 
@@ -482,7 +480,7 @@ void SignBase::InstallMethods(mode mode) {
482
480
  signature = ConvertSignatureToDER(
483
481
  pkey, ArrayBufferToByteSource(runtime, hbuf));
484
482
  if (signature.data() == nullptr) {
485
- jsi::detail::throwJSError(runtime, "kSignMalformedSignature");
483
+ throw jsi::JSError(runtime, "kSignMalformedSignature");
486
484
  }
487
485
  // return crypto::CheckThrow(env,
488
486
  // Error::kSignMalformedSignature);
@@ -492,7 +490,7 @@ void SignBase::InstallMethods(mode mode) {
492
490
  Error err = this->VerifyFinal(pkey, signature, padding, salt_len,
493
491
  &verify_result);
494
492
  if (err != kSignOk) {
495
- jsi::detail::throwJSError(runtime, "Error on verify");
493
+ throw jsi::JSError(runtime, "Error on verify");
496
494
  }
497
495
 
498
496
  return verify_result;
@@ -6,7 +6,6 @@ Object.defineProperty(exports, "__esModule", {
6
6
  exports.ab2str = ab2str;
7
7
  exports.binaryLikeToArrayBuffer = binaryLikeToArrayBuffer;
8
8
  exports.getDefaultEncoding = getDefaultEncoding;
9
- exports.isBuffer = isBuffer;
10
9
  exports.isStringOrBuffer = isStringOrBuffer;
11
10
  exports.kEmptyObject = void 0;
12
11
  exports.setDefaultEncoding = setDefaultEncoding;
@@ -102,12 +101,6 @@ const kEmptyObject = Object.freeze(Object.create(null)); // Should be used by Ci
102
101
 
103
102
  exports.kEmptyObject = kEmptyObject;
104
103
 
105
- function isBuffer(buf) {
106
- var _buf$constructor;
107
-
108
- return buf instanceof _reactNativeBuffer.Buffer || (buf === null || buf === void 0 ? void 0 : (_buf$constructor = buf.constructor) === null || _buf$constructor === void 0 ? void 0 : _buf$constructor.name) === 'Buffer';
109
- }
110
-
111
104
  function toArrayBuffer(buf) {
112
105
  var _buf$buffer;
113
106
 
@@ -134,7 +127,7 @@ function binaryLikeToArrayBuffer(input) {
134
127
  return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
135
128
  }
136
129
 
137
- if (isBuffer(input)) {
130
+ if (_reactNativeBuffer.Buffer.isBuffer(input)) {
138
131
  return toArrayBuffer(input);
139
132
  } // TODO add further binary types to BinaryLike, UInt8Array and so for have this array as property
140
133
 
@@ -1 +1 @@
1
- {"version":3,"sources":["Utils.ts"],"names":["defaultEncoding","setDefaultEncoding","encoding","getDefaultEncoding","kEmptyObject","Object","freeze","create","isBuffer","buf","Buffer","constructor","name","toArrayBuffer","buffer","slice","byteOffset","byteLength","ab","ArrayBuffer","length","view","Uint8Array","i","binaryLikeToArrayBuffer","input","from","ab2str","toString","validateString","str","isString","Error","validateFunction","f","isStringOrBuffer","val","isView","validateObject","value","options","useDefaultOptions","allowArray","allowFunction","nullable","Array","isArray","validateInt32","min","max","Number","isInteger","validateUint32","positive"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;;AAeA;AACA,IAAIA,eAA+B,GAAG,QAAtC;;AAEO,SAASC,kBAAT,CAA4BC,QAA5B,EAAsD;AAC3DF,EAAAA,eAAe,GAAGE,QAAlB;AACD;;AAEM,SAASC,kBAAT,GAA8C;AACnD,SAAOH,eAAP;AACD;;AAEM,MAAMI,YAAY,GAAGC,MAAM,CAACC,MAAP,CAAcD,MAAM,CAACE,MAAP,CAAc,IAAd,CAAd,CAArB,C,CAEP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AAEO,SAASC,QAAT,CAAkBC,GAAlB,EAA2C;AAAA;;AAChD,SAAOA,GAAG,YAAYC,yBAAf,IAAyB,CAAAD,GAAG,SAAH,IAAAA,GAAG,WAAH,gCAAAA,GAAG,CAAEE,WAAL,sEAAkBC,IAAlB,MAA2B,QAA3D;AACD;;AAEM,SAASC,aAAT,CAAuBJ,GAAvB,EAAiD;AAAA;;AACtD,MAAIA,GAAJ,aAA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MJ,GAAG,GAAG,UAAZ;;AACA,MAAIV,KAAK,GAAGS,GAAR,IAAeT,KAAK,GAAGU,GAA3B,EAAgC;AAC9B;AACA,UAAM,IAAIjB,KAAJ,CACH,sBAAqBpB,IAAK,oBAAmBoC,GAAI,UAASC,GAAI,KAAIV,KAAM,EADrE,CAAN;AAGD;AACF","sourcesContent":["import { Buffer } from '@craftzdog/react-native-buffer';\n\nexport type BinaryLike = string | ArrayBuffer | Buffer;\n\nexport type BinaryToTextEncoding = 'base64' | 'base64url' | 'hex' | 'binary';\nexport type CharacterEncoding = 'utf8' | 'utf-8' | 'utf16le' | 'latin1';\nexport type LegacyCharacterEncoding = 'ascii' | 'binary' | 'ucs2' | 'ucs-2';\nexport type Encoding =\n | BinaryToTextEncoding\n | CharacterEncoding\n | LegacyCharacterEncoding;\n\n// TODO(osp) should buffer be part of the Encoding type?\nexport type CipherEncoding = Encoding | 'buffer';\n\n// Mimics node behavior for default global encoding\nlet defaultEncoding: CipherEncoding = 'buffer';\n\nexport function setDefaultEncoding(encoding: CipherEncoding) {\n defaultEncoding = encoding;\n}\n\nexport function getDefaultEncoding(): CipherEncoding {\n return defaultEncoding;\n}\n\nexport const kEmptyObject = Object.freeze(Object.create(null));\n\n// Should be used by Cipher (or any other module that requires valid encodings)\n// function slowCases(enc: string) {\n// switch (enc.length) {\n// case 4:\n// if (enc === 'UTF8') return 'utf8';\n// if (enc === 'ucs2' || enc === 'UCS2') return 'utf16le';\n// enc = `${enc}`.toLowerCase();\n// if (enc === 'utf8') return 'utf8';\n// if (enc === 'ucs2') return 'utf16le';\n// break;\n// case 3:\n// if (enc === 'hex' || enc === 'HEX' || `${enc}`.toLowerCase() === 'hex')\n// return 'hex';\n// break;\n// case 5:\n// if (enc === 'ascii') return 'ascii';\n// if (enc === 'ucs-2') return 'utf16le';\n// if (enc === 'UTF-8') return 'utf8';\n// if (enc === 'ASCII') return 'ascii';\n// if (enc === 'UCS-2') return 'utf16le';\n// enc = `${enc}`.toLowerCase();\n// if (enc === 'utf-8') return 'utf8';\n// if (enc === 'ascii') return 'ascii';\n// if (enc === 'ucs-2') return 'utf16le';\n// break;\n// case 6:\n// if (enc === 'base64') return 'base64';\n// if (enc === 'latin1' || enc === 'binary') return 'latin1';\n// if (enc === 'BASE64') return 'base64';\n// if (enc === 'LATIN1' || enc === 'BINARY') return 'latin1';\n// enc = `${enc}`.toLowerCase();\n// if (enc === 'base64') return 'base64';\n// if (enc === 'latin1' || enc === 'binary') return 'latin1';\n// break;\n// case 7:\n// if (\n// enc === 'utf16le' ||\n// enc === 'UTF16LE' ||\n// `${enc}`.toLowerCase() === 'utf16le'\n// )\n// return 'utf16le';\n// break;\n// case 8:\n// if (\n// enc === 'utf-16le' ||\n// enc === 'UTF-16LE' ||\n// `${enc}`.toLowerCase() === 'utf-16le'\n// )\n// return 'utf16le';\n// break;\n// case 9:\n// if (\n// enc === 'base64url' ||\n// enc === 'BASE64URL' ||\n// `${enc}`.toLowerCase() === 'base64url'\n// )\n// return 'base64url';\n// break;\n// default:\n// if (enc === '') return 'utf8';\n// }\n// }\n\n// // Return undefined if there is no match.\n// // Move the \"slow cases\" to a separate function to make sure this function gets\n// // inlined properly. That prioritizes the common case.\n// export function normalizeEncoding(enc?: string) {\n// if (enc == null || enc === 'utf8' || enc === 'utf-8') return 'utf8';\n// return slowCases(enc);\n// }\n\nexport function isBuffer(buf: any): buf is Buffer {\n return buf instanceof Buffer || buf?.constructor?.name === 'Buffer';\n}\n\nexport function toArrayBuffer(buf: Buffer): ArrayBuffer {\n if (buf?.buffer?.slice) {\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);\n }\n const ab = new ArrayBuffer(buf.length);\n const view = new Uint8Array(ab);\n for (let i = 0; i < buf.length; ++i) {\n view[i] = buf[i];\n }\n return ab;\n}\n\nexport function binaryLikeToArrayBuffer(\n input: BinaryLike,\n encoding: string = 'utf-8'\n): ArrayBuffer {\n if (typeof input === 'string') {\n const buffer = Buffer.from(input, encoding);\n\n return buffer.buffer.slice(\n buffer.byteOffset,\n buffer.byteOffset + buffer.byteLength\n );\n }\n\n if (isBuffer(input)) {\n return toArrayBuffer(input);\n }\n\n // TODO add further binary types to BinaryLike, UInt8Array and so for have this array as property\n if ((input as any).buffer) {\n return (input as any).buffer;\n }\n\n if (!(input instanceof ArrayBuffer)) {\n try {\n const buffer = Buffer.from(input);\n return buffer.buffer.slice(\n buffer.byteOffset,\n buffer.byteOffset + buffer.byteLength\n );\n } catch {\n throw 'error';\n }\n }\n return input;\n}\n\nexport function ab2str(buf: ArrayBuffer, encoding: string = 'hex') {\n return Buffer.from(buf).toString(encoding);\n}\n\nexport function validateString(str: any, name?: string): str is string {\n const isString = typeof str === 'string';\n if (isString) {\n throw new Error(`${name} is not a string`);\n }\n return isString;\n}\n\nexport function validateFunction(f: any): f is Function {\n return f != null && typeof f === 'function';\n}\n\nexport function isStringOrBuffer(val: any): val is string | ArrayBuffer {\n return typeof val === 'string' || ArrayBuffer.isView(val);\n}\n\nexport function validateObject<T>(\n value: any,\n name: string,\n options?: {\n allowArray: boolean;\n allowFunction: boolean;\n nullable: boolean;\n } | null\n): value is T {\n const useDefaultOptions = options == null;\n const allowArray = useDefaultOptions ? false : options.allowArray;\n const allowFunction = useDefaultOptions ? false : options.allowFunction;\n const nullable = useDefaultOptions ? false : options.nullable;\n if (\n (!nullable && value === null) ||\n (!allowArray && Array.isArray(value)) ||\n (typeof value !== 'object' &&\n (!allowFunction || typeof value !== 'function'))\n ) {\n throw new Error(`${name} is not a valid object $${value}`);\n }\n return true;\n}\n\nexport function validateInt32(\n value: any,\n name: string,\n min = -2147483648,\n max = 2147483647\n) {\n // The defaults for min and max correspond to the limits of 32-bit integers.\n if (typeof value !== 'number') {\n throw new Error(`Invalid argument - ${name} is not a number: ${value}`);\n }\n if (!Number.isInteger(value)) {\n throw new Error(\n `Argument out of range - ${name} out of integer range: ${value}`\n );\n }\n if (value < min || value > max) {\n throw new Error(\n `Invalid argument - ${name} out of range >= ${min} && <= ${max}: ${value}`\n );\n }\n}\n\nexport function validateUint32(\n value: number,\n name: string,\n positive?: boolean\n) {\n if (typeof value !== 'number') {\n // throw new ERR_INVALID_ARG_TYPE(name, 'number', value);\n throw new Error(`Invalid argument - ${name} is not a number: ${value}`);\n }\n if (!Number.isInteger(value)) {\n // throw new ERR_OUT_OF_RANGE(name, 'an integer', value);\n throw new Error(\n `Argument out of range - ${name} out of integer range: ${value}`\n );\n }\n const min = positive ? 1 : 0;\n // 2 ** 32 === 4294967296\n const max = 4294967295;\n if (value < min || value > max) {\n // throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value);\n throw new Error(\n `Invalid argument - ${name} out of range >= ${min} && <= ${max}: ${value}`\n );\n }\n}\n"]}
1
+ {"version":3,"sources":["Utils.ts"],"names":["defaultEncoding","setDefaultEncoding","encoding","getDefaultEncoding","kEmptyObject","Object","freeze","create","toArrayBuffer","buf","buffer","slice","byteOffset","byteLength","ab","ArrayBuffer","length","view","Uint8Array","i","binaryLikeToArrayBuffer","input","Buffer","from","isBuffer","ab2str","toString","validateString","str","name","isString","Error","validateFunction","f","isStringOrBuffer","val","isView","validateObject","value","options","useDefaultOptions","allowArray","allowFunction","nullable","Array","isArray","validateInt32","min","max","Number","isInteger","validateUint32","positive"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;;AAeA;AACA,IAAIA,eAA+B,GAAG,QAAtC;;AAEO,SAASC,kBAAT,CAA4BC,QAA5B,EAAsD;AAC3DF,EAAAA,eAAe,GAAGE,QAAlB;AACD;;AAEM,SAASC,kBAAT,GAA8C;AACnD,SAAOH,eAAP;AACD;;AAEM,MAAMI,YAAY,GAAGC,MAAM,CAACC,MAAP,CAAcD,MAAM,CAACE,MAAP,CAAc,IAAd,CAAd,CAArB,C,CAEP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA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BS,KAAM,EAA/D,CAAN;AACD;;AACD,MAAI,CAACW,MAAM,CAACC,SAAP,CAAiBZ,KAAjB,CAAL,EAA8B;AAC5B;AACA,UAAM,IAAIP,KAAJ,CACH,2BAA0BF,IAAK,0BAAyBS,KAAM,EAD3D,CAAN;AAGD;;AACD,QAAMS,GAAG,GAAGK,QAAQ,GAAG,CAAH,GAAO,CAA3B,CAXA,CAYA;;AACA,QAAMJ,GAAG,GAAG,UAAZ;;AACA,MAAIV,KAAK,GAAGS,GAAR,IAAeT,KAAK,GAAGU,GAA3B,EAAgC;AAC9B;AACA,UAAM,IAAIjB,KAAJ,CACH,sBAAqBF,IAAK,oBAAmBkB,GAAI,UAASC,GAAI,KAAIV,KAAM,EADrE,CAAN;AAGD;AACF","sourcesContent":["import { Buffer } from '@craftzdog/react-native-buffer';\n\nexport type BinaryLike = string | ArrayBuffer | Buffer;\n\nexport type BinaryToTextEncoding = 'base64' | 'base64url' | 'hex' | 'binary';\nexport type CharacterEncoding = 'utf8' | 'utf-8' | 'utf16le' | 'latin1';\nexport type LegacyCharacterEncoding = 'ascii' | 'binary' | 'ucs2' | 'ucs-2';\nexport type Encoding =\n | BinaryToTextEncoding\n | CharacterEncoding\n | LegacyCharacterEncoding;\n\n// TODO(osp) should buffer be part of the Encoding type?\nexport type CipherEncoding = Encoding | 'buffer';\n\n// Mimics node behavior for default global encoding\nlet defaultEncoding: CipherEncoding = 'buffer';\n\nexport function setDefaultEncoding(encoding: CipherEncoding) {\n defaultEncoding = encoding;\n}\n\nexport function getDefaultEncoding(): CipherEncoding {\n return defaultEncoding;\n}\n\nexport const kEmptyObject = Object.freeze(Object.create(null));\n\n// Should be used by Cipher (or any other module that requires valid encodings)\n// function slowCases(enc: string) {\n// switch (enc.length) {\n// case 4:\n// if (enc === 'UTF8') return 'utf8';\n// if (enc === 'ucs2' || enc === 'UCS2') return 'utf16le';\n// enc = `${enc}`.toLowerCase();\n// if (enc === 'utf8') return 'utf8';\n// if (enc === 'ucs2') return 'utf16le';\n// break;\n// case 3:\n// if (enc === 'hex' || enc === 'HEX' || `${enc}`.toLowerCase() === 'hex')\n// return 'hex';\n// break;\n// case 5:\n// if (enc === 'ascii') return 'ascii';\n// if (enc === 'ucs-2') return 'utf16le';\n// if (enc === 'UTF-8') return 'utf8';\n// if (enc === 'ASCII') return 'ascii';\n// if (enc === 'UCS-2') return 'utf16le';\n// enc = `${enc}`.toLowerCase();\n// if (enc === 'utf-8') return 'utf8';\n// if (enc === 'ascii') return 'ascii';\n// if (enc === 'ucs-2') return 'utf16le';\n// break;\n// case 6:\n// if (enc === 'base64') return 'base64';\n// if (enc === 'latin1' || enc === 'binary') return 'latin1';\n// if (enc === 'BASE64') return 'base64';\n// if (enc === 'LATIN1' || enc === 'BINARY') return 'latin1';\n// enc = `${enc}`.toLowerCase();\n// if (enc === 'base64') return 'base64';\n// if (enc === 'latin1' || enc === 'binary') return 'latin1';\n// break;\n// case 7:\n// if (\n// enc === 'utf16le' ||\n// enc === 'UTF16LE' ||\n// `${enc}`.toLowerCase() === 'utf16le'\n// )\n// return 'utf16le';\n// break;\n// case 8:\n// if (\n// enc === 'utf-16le' ||\n// enc === 'UTF-16LE' ||\n// `${enc}`.toLowerCase() === 'utf-16le'\n// )\n// return 'utf16le';\n// break;\n// case 9:\n// if (\n// enc === 'base64url' ||\n// enc === 'BASE64URL' ||\n// `${enc}`.toLowerCase() === 'base64url'\n// )\n// return 'base64url';\n// break;\n// default:\n// if (enc === '') return 'utf8';\n// }\n// }\n\n// // Return undefined if there is no match.\n// // Move the \"slow cases\" to a separate function to make sure this function gets\n// // inlined properly. That prioritizes the common case.\n// export function normalizeEncoding(enc?: string) {\n// if (enc == null || enc === 'utf8' || enc === 'utf-8') return 'utf8';\n// return slowCases(enc);\n// }\n\nexport function toArrayBuffer(buf: Buffer): ArrayBuffer {\n if (buf?.buffer?.slice) {\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);\n }\n const ab = new ArrayBuffer(buf.length);\n const view = new Uint8Array(ab);\n for (let i = 0; i < buf.length; ++i) {\n view[i] = buf[i];\n }\n return ab;\n}\n\nexport function binaryLikeToArrayBuffer(\n input: BinaryLike,\n encoding: string = 'utf-8'\n): ArrayBuffer {\n if (typeof input === 'string') {\n const buffer = Buffer.from(input, encoding);\n\n return buffer.buffer.slice(\n buffer.byteOffset,\n buffer.byteOffset + buffer.byteLength\n );\n }\n\n if (Buffer.isBuffer(input)) {\n return toArrayBuffer(input);\n }\n\n // TODO add further binary types to BinaryLike, UInt8Array and so for have this array as property\n if ((input as any).buffer) {\n return (input as any).buffer;\n }\n\n if (!(input instanceof ArrayBuffer)) {\n try {\n const buffer = Buffer.from(input);\n return buffer.buffer.slice(\n buffer.byteOffset,\n buffer.byteOffset + buffer.byteLength\n );\n } catch {\n throw 'error';\n }\n }\n return input;\n}\n\nexport function ab2str(buf: ArrayBuffer, encoding: string = 'hex') {\n return Buffer.from(buf).toString(encoding);\n}\n\nexport function validateString(str: any, name?: string): str is string {\n const isString = typeof str === 'string';\n if (isString) {\n throw new Error(`${name} is not a string`);\n }\n return isString;\n}\n\nexport function validateFunction(f: any): f is Function {\n return f != null && typeof f === 'function';\n}\n\nexport function isStringOrBuffer(val: any): val is string | ArrayBuffer {\n return typeof val === 'string' || ArrayBuffer.isView(val);\n}\n\nexport function validateObject<T>(\n value: any,\n name: string,\n options?: {\n allowArray: boolean;\n allowFunction: boolean;\n nullable: boolean;\n } | null\n): value is T {\n const useDefaultOptions = options == null;\n const allowArray = useDefaultOptions ? false : options.allowArray;\n const allowFunction = useDefaultOptions ? false : options.allowFunction;\n const nullable = useDefaultOptions ? false : options.nullable;\n if (\n (!nullable && value === null) ||\n (!allowArray && Array.isArray(value)) ||\n (typeof value !== 'object' &&\n (!allowFunction || typeof value !== 'function'))\n ) {\n throw new Error(`${name} is not a valid object $${value}`);\n }\n return true;\n}\n\nexport function validateInt32(\n value: any,\n name: string,\n min = -2147483648,\n max = 2147483647\n) {\n // The defaults for min and max correspond to the limits of 32-bit integers.\n if (typeof value !== 'number') {\n throw new Error(`Invalid argument - ${name} is not a number: ${value}`);\n }\n if (!Number.isInteger(value)) {\n throw new Error(\n `Argument out of range - ${name} out of integer range: ${value}`\n );\n }\n if (value < min || value > max) {\n throw new Error(\n `Invalid argument - ${name} out of range >= ${min} && <= ${max}: ${value}`\n );\n }\n}\n\nexport function validateUint32(\n value: number,\n name: string,\n positive?: boolean\n) {\n if (typeof value !== 'number') {\n // throw new ERR_INVALID_ARG_TYPE(name, 'number', value);\n throw new Error(`Invalid argument - ${name} is not a number: ${value}`);\n }\n if (!Number.isInteger(value)) {\n // throw new ERR_OUT_OF_RANGE(name, 'an integer', value);\n throw new Error(\n `Argument out of range - ${name} out of integer range: ${value}`\n );\n }\n const min = positive ? 1 : 0;\n // 2 ** 32 === 4294967296\n const max = 4294967295;\n if (value < min || value > max) {\n // throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value);\n throw new Error(\n `Invalid argument - ${name} out of range >= ${min} && <= ${max}: ${value}`\n );\n }\n}\n"]}
@@ -9,14 +9,13 @@ exports.randomBytes = randomBytes;
9
9
  exports.randomFill = randomFill;
10
10
  exports.randomFillSync = randomFillSync;
11
11
  exports.randomInt = randomInt;
12
+ exports.randomUUID = randomUUID;
12
13
  exports.rng = void 0;
13
14
 
14
15
  var _NativeQuickCrypto = require("./NativeQuickCrypto/NativeQuickCrypto");
15
16
 
16
17
  var _reactNativeBuffer = require("@craftzdog/react-native-buffer");
17
18
 
18
- var _Utils = require("../src/Utils");
19
-
20
19
  const random = _NativeQuickCrypto.NativeQuickCrypto.random;
21
20
 
22
21
  function randomFill(buffer) {
@@ -39,7 +38,7 @@ function randomFill(buffer) {
39
38
  offset = arguments.length <= 1 ? undefined : arguments[1];
40
39
  }
41
40
 
42
- random.randomFill((0, _Utils.isBuffer)(buffer) ? buffer.buffer : buffer, offset, size).then(() => {
41
+ random.randomFill(_reactNativeBuffer.Buffer.isBuffer(buffer) ? buffer.buffer : buffer, offset, size).then(() => {
43
42
  callback(null, buffer);
44
43
  }, e => {
45
44
  callback(e);
@@ -210,4 +209,21 @@ function getRandomValues(data) {
210
209
  randomFillSync(data, 0);
211
210
  return data;
212
211
  }
212
+
213
+ const byteToHex = [];
214
+
215
+ for (let i = 0; i < 256; ++i) {
216
+ byteToHex.push((i + 0x100).toString(16).slice(1));
217
+ } // Based on https://github.com/uuidjs/uuid/blob/main/src/v4.js
218
+
219
+
220
+ function randomUUID() {
221
+ const size = 16;
222
+ const buffer = new _reactNativeBuffer.Buffer(size);
223
+ randomFillSync(buffer, 0, size); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
224
+
225
+ buffer[6] = buffer[6] & 0x0f | 0x40;
226
+ buffer[8] = buffer[8] & 0x3f | 0x80;
227
+ return (byteToHex[buffer[0]] + byteToHex[buffer[1]] + byteToHex[buffer[2]] + byteToHex[buffer[3]] + '-' + byteToHex[buffer[4]] + byteToHex[buffer[5]] + '-' + byteToHex[buffer[6]] + byteToHex[buffer[7]] + '-' + byteToHex[buffer[8]] + byteToHex[buffer[9]] + '-' + byteToHex[buffer[10]] + byteToHex[buffer[11]] + byteToHex[buffer[12]] + byteToHex[buffer[13]] + byteToHex[buffer[14]] + byteToHex[buffer[15]]).toLowerCase();
228
+ }
213
229
  //# sourceMappingURL=random.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["random.ts"],"names":["random","NativeQuickCrypto","randomFill","buffer","Error","callback","offset","size","byteLength","then","e","randomFillSync","randomBytes","buf","Buffer","undefined","error","rng","pseudoRandomBytes","prng","RAND_MAX","randomCache","randomCacheOffset","length","asyncCacheFillInProgress","asyncCachePendingTasks","randomInt","arg1","arg2","max","min","minNotSpecified","isSync","Number","isSafeInteger","range","randLimit","x","readUIntBE","n","process","nextTick","push","asyncRefillRandomIntCache","err","tasks","errorReceiver","shift","splice","forEach","task","getRandomValues","data"],"mappings":";;;;;;;;;;;;;AAAA;;AACA;;AACA;;AAEA,MAAMA,MA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B;AACAsC,IAAAA,yBAAyB;AAC1B;AACF;;AAED,SAASA,yBAAT,GAAqC;AACnC,MAAInB,wBAAJ,EAA8B;AAE9BA,EAAAA,wBAAwB,GAAG,IAA3B;AACAtB,EAAAA,UAAU,CAACmB,WAAD,EAAeuB,GAAD,IAAS;AAC/BpB,IAAAA,wBAAwB,GAAG,KAA3B;AAEA,UAAMqB,KAAK,GAAGpB,sBAAd;AACA,UAAMqB,aAAa,GAAGF,GAAG,IAAIC,KAAK,CAACE,KAAN,EAA7B;AACA,QAAI,CAACH,GAAL,EAAUtB,iBAAiB,GAAG,CAApB,CALqB,CAO/B;AACA;AACA;AACA;;AACAuB,IAAAA,KAAK,CAACG,MAAN,CAAa,CAAb,EAAgBC,OAAhB,CAAyBC,IAAD,IAAU;AAChCxB,MAAAA,SAAS,CAACwB,IAAI,CAACpB,GAAN,EAAWoB,IAAI,CAACrB,GAAhB,EAAqBqB,IAAI,CAAC7C,QAA1B,CAAT;AACD,KAFD,EAX+B,CAe/B;;AACA,QAAIyC,aAAJ,EAAmBA,aAAa,CAACzC,QAAd,CAAuBuC,GAAvB,EAA4B,CAA5B;AACpB,GAjBS,CAAV;AAkBD,C,CAED;AACA;AACA;AACA;AACA;;;AAQO,SAASO,eAAT,CAAyBC,IAAzB,EAAyC;AAC9C,MAAIA,IAAI,CAAC5C,UAAL,GAAkB,KAAtB,EAA6B;AAC3B,UAAM,IAAIJ,KAAJ,CAAU,2CAAV,CAAN;AACD;;AACDO,EAAAA,cAAc,CAACyC,IAAD,EAAO,CAAP,CAAd;AACA,SAAOA,IAAP;AACD","sourcesContent":["import { NativeQuickCrypto } from './NativeQuickCrypto/NativeQuickCrypto';\nimport { Buffer } from '@craftzdog/react-native-buffer';\nimport { isBuffer } from '../src/Utils';\n\nconst random = NativeQuickCrypto.random;\n\ntype TypedArray =\n | Uint8Array\n | Uint8ClampedArray\n | Uint16Array\n | Uint32Array\n | Int8Array\n | Int16Array\n | Int32Array\n | Float32Array\n | Float64Array;\ntype ArrayBufferView = TypedArray | DataView | ArrayBufferLike | Buffer;\n\nexport function randomFill<T extends ArrayBufferView>(\n buffer: T,\n callback: (err: Error | null, buf: T) => void\n): void;\n\nexport function randomFill<T extends ArrayBufferView>(\n buffer: T,\n offset: number,\n callback: (err: Error | null, buf: T) => void\n): void;\n\nexport function randomFill<T extends ArrayBufferView>(\n buffer: T,\n offset: number,\n size: number,\n callback: (err: Error | null, buf: T) => void\n): void;\n\nexport function randomFill(buffer: any, ...rest: any[]): void {\n if (typeof rest[rest.length - 1] !== 'function') {\n throw new Error('No callback provided to randomDill');\n }\n\n const callback = rest[rest.length - 1] as any as (\n err: Error | null,\n buf?: ArrayBuffer\n ) => void;\n\n let offset: number = 0;\n let size: number = buffer.byteLength;\n\n if (typeof rest[2] === 'function') {\n offset = rest[0];\n size = rest[1];\n }\n\n if (typeof rest[1] === 'function') {\n offset = rest[0];\n }\n\n random\n .randomFill(isBuffer(buffer) ? buffer.buffer : buffer, offset, size)\n .then(\n () => {\n callback(null, buffer);\n },\n (e: Error) => {\n callback(e);\n }\n );\n}\n\nexport function randomFillSync<T extends ArrayBufferView>(\n buffer: T,\n offset?: number,\n size?: number\n): T;\n\nexport function randomFillSync(buffer: any, offset: number = 0, size?: number) {\n random.randomFillSync(\n buffer.buffer ? buffer.buffer : buffer,\n offset,\n size ?? buffer.byteLength\n );\n return buffer;\n}\n\nexport function randomBytes(size: number): ArrayBuffer;\n\nexport function randomBytes(\n size: number,\n callback: (err: Error | null, buf?: ArrayBuffer) => void\n): void;\n\nexport function randomBytes(\n size: number,\n callback?: (err: Error | null, buf?: ArrayBuffer) => void\n): void | ArrayBuffer {\n const buf = new Buffer(size);\n\n if (callback === undefined) {\n randomFillSync(buf.buffer, 0, size);\n return buf;\n }\n\n randomFill(buf.buffer, 0, size, (error: Error | null) => {\n if (error) {\n callback(error);\n }\n callback(null, buf);\n });\n}\n\nexport const rng = randomBytes;\nexport const pseudoRandomBytes = randomBytes;\nexport const prng = randomBytes;\n\ntype RandomIntCallback = (err: Error | null, value: number) => void;\ntype Task = {\n min: number;\n max: number;\n callback: RandomIntCallback;\n};\n\n// The rest of the file is taken from https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js\n\n// Largest integer we can read from a buffer.\n// e.g.: Buffer.from(\"ff\".repeat(6), \"hex\").readUIntBE(0, 6);\nconst RAND_MAX = 0xffffffffffff;\n\n// Cache random data to use in randomInt. The cache size must be evenly\n// divisible by 6 because each attempt to obtain a random int uses 6 bytes.\nconst randomCache = new Buffer(6 * 1024);\nlet randomCacheOffset = randomCache.length;\nlet asyncCacheFillInProgress = false;\nconst asyncCachePendingTasks: Task[] = [];\n\n// Generates an integer in [min, max) range where min is inclusive and max is\n// exclusive.\n\nexport function randomInt(max: number, callback: RandomIntCallback): void;\nexport function randomInt(max: number): number;\nexport function randomInt(\n min: number,\n max: number,\n callback: RandomIntCallback\n): void;\nexport function randomInt(min: number, max: number): number;\nexport function randomInt(\n arg1: number,\n arg2?: number | RandomIntCallback,\n callback?: RandomIntCallback\n): void | number {\n // Detect optional min syntax\n // randomInt(max)\n // randomInt(max, callback)\n let max: number;\n let min: number;\n const minNotSpecified =\n typeof arg2 === 'undefined' || typeof arg2 === 'function';\n\n if (minNotSpecified) {\n callback = arg2 as any as undefined | RandomIntCallback;\n max = arg1;\n min = 0;\n } else {\n min = arg1;\n max = arg2 as any as number;\n }\n\n const isSync = typeof callback === 'undefined';\n if (!Number.isSafeInteger(min)) {\n // todo throw new ERR_INVALID_ARG_TYPE('min', 'a safe integer', min);\n throw 'ERR_INVALID_ARG_TYPE';\n }\n if (!Number.isSafeInteger(max)) {\n // todo throw new ERR_INVALID_ARG_TYPE('max', 'a safe integer', max);\n throw 'ERR_INVALID_ARG_TYPE';\n }\n if (max <= min) {\n /* todo throw new ERR_OUT_OF_RANGE(\n 'max',\n `greater than the value of \"min\" (${min})`,\n max\n );*/\n throw 'ERR_OUT_OF_RANGE';\n }\n\n // First we generate a random int between [0..range)\n const range = max - min;\n\n if (!(range <= RAND_MAX)) {\n /* todo throw new ERR_OUT_OF_RANGE(\n `max${minNotSpecified ? '' : ' - min'}`,\n `<= ${RAND_MAX}`,\n range\n );*/\n throw 'ERR_OUT_OF_RANGE';\n }\n\n // For (x % range) to produce an unbiased value greater than or equal to 0 and\n // less than range, x must be drawn randomly from the set of integers greater\n // than or equal to 0 and less than randLimit.\n const randLimit = RAND_MAX - (RAND_MAX % range);\n\n // If we don't have a callback, or if there is still data in the cache, we can\n // do this synchronously, which is super fast.\n while (isSync || randomCacheOffset < randomCache.length) {\n if (randomCacheOffset === randomCache.length) {\n // This might block the thread for a bit, but we are in sync mode.\n randomFillSync(randomCache);\n randomCacheOffset = 0;\n }\n\n const x = randomCache.readUIntBE(randomCacheOffset, 6);\n randomCacheOffset += 6;\n\n if (x < randLimit) {\n const n = (x % range) + min;\n if (isSync) return n;\n process.nextTick(callback as Function, undefined, n);\n return;\n }\n }\n\n // At this point, we are in async mode with no data in the cache. We cannot\n // simply refill the cache, because another async call to randomInt might\n // already be doing that. Instead, queue this call for when the cache has\n // been refilled.\n if (callback !== undefined) {\n // it is (typescript doesn't know it)\n asyncCachePendingTasks.push({ min, max, callback });\n asyncRefillRandomIntCache();\n }\n}\n\nfunction asyncRefillRandomIntCache() {\n if (asyncCacheFillInProgress) return;\n\n asyncCacheFillInProgress = true;\n randomFill(randomCache, (err) => {\n asyncCacheFillInProgress = false;\n\n const tasks = asyncCachePendingTasks;\n const errorReceiver = err && tasks.shift();\n if (!err) randomCacheOffset = 0;\n\n // Restart all pending tasks. If an error occurred, we only notify a single\n // callback (errorReceiver) about it. This way, every async call to\n // randomInt has a chance of being successful, and it avoids complex\n // exception handling here.\n tasks.splice(0).forEach((task) => {\n randomInt(task.min, task.max, task.callback);\n });\n\n // This is the only call that might throw, and is therefore done at the end.\n if (errorReceiver) errorReceiver.callback(err, 0);\n });\n}\n\n// Really just the Web Crypto API alternative\n// to require('crypto').randomFillSync() with an\n// additional limitation that the input buffer is\n// not allowed to exceed 65536 bytes, and can only\n// be an integer-type TypedArray.\ntype DataType =\n | Int8Array\n | Int16Array\n | Int32Array\n | Uint8Array\n | Uint16Array\n | Uint32Array;\nexport function getRandomValues(data: DataType) {\n if (data.byteLength > 65536) {\n throw new Error('The requested length exceeds 65,536 bytes');\n }\n randomFillSync(data, 0);\n return data;\n}\n"]}
1
+ {"version":3,"sources":["random.ts"],"names":["random","NativeQuickCrypto","randomFill","buffer","Error","callback","offset","size","byteLength","Buffer","isBuffer","then","e","randomFillSync","randomBytes","buf","undefined","error","rng","pseudoRandomBytes","prng","RAND_MAX","randomCache","randomCacheOffset","length","asyncCacheFillInProgress","asyncCachePendingTasks","randomInt","arg1","arg2","max","min","minNotSpecified","isSync","Number","isSafeInteger","range","randLimit","x","readUIntBE","n","process","nextTick","push","asyncRefillRandomIntCache","err","tasks","errorReceiver","shift","splice","forEach","task","getRandomValues","data","byteToHex","i","toString","slice","randomUUID","toLowerCase"],"mappings":";;;;;;;;;;;;;;AAAA;;AACA;;AAEA,MAAMA,MAAM,GAAGC,qCAAkBD,MAAjC;;AAgCO,SAASE,UAAT,CAAoBC,MAApB,EAAuD;AAAA;;AAC5D,MAAI,eAAY,qDAAc,CAA1B,8EAAiC,UAArC,EAAiD;AAC/C,UAAM,IAAIC,KAAJ,CAAU,oCAAV,CAAN;AACD;;AAED,QAAMC,QAAQ,YAAQ,qDAAc,CAAtB,4EAAd;AAKA,MAAIC,MAAc,GAAG,CAArB;AACA,MAAIC,IAAY,GAAGJ,MAAM,CAACK,UAA1B;;AAEA,MAAI,8DAAmB,UAAvB,EAAmC;AACjCF,IAAAA,MAAM,mDAAN;AACAC,IAAAA,IAAI,mDAAJ;AACD;;AAED,MAAI,8DAAmB,UAAvB,EAAmC;AACjCD,IAAAA,MAAM,mDAAN;AACD;;AAEDN,EAAAA,MAAM,CACHE,UADH,CACcO,0BAAOC,QAAP,CAAgBP,MAAhB,IAA0BA,MAAM,CAACA,MAAjC,GAA0CA,MADx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AAP,CAFT,GAGAmD,SAAS,CAACnD,MAAM,CAAC,CAAD,CAAP,CAHT,GAIA,GAJA,GAKAmD,SAAS,CAACnD,MAAM,CAAC,CAAD,CAAP,CALT,GAMAmD,SAAS,CAACnD,MAAM,CAAC,CAAD,CAAP,CANT,GAOA,GAPA,GAQAmD,SAAS,CAACnD,MAAM,CAAC,CAAD,CAAP,CART,GASAmD,SAAS,CAACnD,MAAM,CAAC,CAAD,CAAP,CATT,GAUA,GAVA,GAWAmD,SAAS,CAACnD,MAAM,CAAC,CAAD,CAAP,CAXT,GAYAmD,SAAS,CAACnD,MAAM,CAAC,CAAD,CAAP,CAZT,GAaA,GAbA,GAcAmD,SAAS,CAACnD,MAAM,CAAC,EAAD,CAAP,CAdT,GAeAmD,SAAS,CAACnD,MAAM,CAAC,EAAD,CAAP,CAfT,GAgBAmD,SAAS,CAACnD,MAAM,CAAC,EAAD,CAAP,CAhBT,GAiBAmD,SAAS,CAACnD,MAAM,CAAC,EAAD,CAAP,CAjBT,GAkBAmD,SAAS,CAACnD,MAAM,CAAC,EAAD,CAAP,CAlBT,GAmBAmD,SAAS,CAACnD,MAAM,CAAC,EAAD,CAAP,CApBJ,EAqBLwD,WArBK,EAAP;AAsBD","sourcesContent":["import { NativeQuickCrypto } from './NativeQuickCrypto/NativeQuickCrypto';\nimport { Buffer } from '@craftzdog/react-native-buffer';\n\nconst random = NativeQuickCrypto.random;\n\ntype TypedArray =\n | Uint8Array\n | Uint8ClampedArray\n | Uint16Array\n | Uint32Array\n | Int8Array\n | Int16Array\n | Int32Array\n | Float32Array\n | Float64Array;\ntype ArrayBufferView = TypedArray | DataView | ArrayBufferLike | Buffer;\n\nexport function randomFill<T extends ArrayBufferView>(\n buffer: T,\n callback: (err: Error | null, buf: T) => void\n): void;\n\nexport function randomFill<T extends ArrayBufferView>(\n buffer: T,\n offset: number,\n callback: (err: Error | null, buf: T) => void\n): void;\n\nexport function randomFill<T extends ArrayBufferView>(\n buffer: T,\n offset: number,\n size: number,\n callback: (err: Error | null, buf: T) => void\n): void;\n\nexport function randomFill(buffer: any, ...rest: any[]): void {\n if (typeof rest[rest.length - 1] !== 'function') {\n throw new Error('No callback provided to randomDill');\n }\n\n const callback = rest[rest.length - 1] as any as (\n err: Error | null,\n buf?: ArrayBuffer\n ) => void;\n\n let offset: number = 0;\n let size: number = buffer.byteLength;\n\n if (typeof rest[2] === 'function') {\n offset = rest[0];\n size = rest[1];\n }\n\n if (typeof rest[1] === 'function') {\n offset = rest[0];\n }\n\n random\n .randomFill(Buffer.isBuffer(buffer) ? buffer.buffer : buffer, offset, size)\n .then(\n () => {\n callback(null, buffer);\n },\n (e: Error) => {\n callback(e);\n }\n );\n}\n\nexport function randomFillSync<T extends ArrayBufferView>(\n buffer: T,\n offset?: number,\n size?: number\n): T;\n\nexport function randomFillSync(buffer: any, offset: number = 0, size?: number) {\n random.randomFillSync(\n buffer.buffer ? buffer.buffer : buffer,\n offset,\n size ?? buffer.byteLength\n );\n return buffer;\n}\n\nexport function randomBytes(size: number): ArrayBuffer;\n\nexport function randomBytes(\n size: number,\n callback: (err: Error | null, buf?: ArrayBuffer) => void\n): void;\n\nexport function randomBytes(\n size: number,\n callback?: (err: Error | null, buf?: ArrayBuffer) => void\n): void | ArrayBuffer {\n const buf = new Buffer(size);\n\n if (callback === undefined) {\n randomFillSync(buf.buffer, 0, size);\n return buf;\n }\n\n randomFill(buf.buffer, 0, size, (error: Error | null) => {\n if (error) {\n callback(error);\n }\n callback(null, buf);\n });\n}\n\nexport const rng = randomBytes;\nexport const pseudoRandomBytes = randomBytes;\nexport const prng = randomBytes;\n\ntype RandomIntCallback = (err: Error | null, value: number) => void;\ntype Task = {\n min: number;\n max: number;\n callback: RandomIntCallback;\n};\n\n// The rest of the file is taken from https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js\n\n// Largest integer we can read from a buffer.\n// e.g.: Buffer.from(\"ff\".repeat(6), \"hex\").readUIntBE(0, 6);\nconst RAND_MAX = 0xffffffffffff;\n\n// Cache random data to use in randomInt. The cache size must be evenly\n// divisible by 6 because each attempt to obtain a random int uses 6 bytes.\nconst randomCache = new Buffer(6 * 1024);\nlet randomCacheOffset = randomCache.length;\nlet asyncCacheFillInProgress = false;\nconst asyncCachePendingTasks: Task[] = [];\n\n// Generates an integer in [min, max) range where min is inclusive and max is\n// exclusive.\n\nexport function randomInt(max: number, callback: RandomIntCallback): void;\nexport function randomInt(max: number): number;\nexport function randomInt(\n min: number,\n max: number,\n callback: RandomIntCallback\n): void;\nexport function randomInt(min: number, max: number): number;\nexport function randomInt(\n arg1: number,\n arg2?: number | RandomIntCallback,\n callback?: RandomIntCallback\n): void | number {\n // Detect optional min syntax\n // randomInt(max)\n // randomInt(max, callback)\n let max: number;\n let min: number;\n const minNotSpecified =\n typeof arg2 === 'undefined' || typeof arg2 === 'function';\n\n if (minNotSpecified) {\n callback = arg2 as any as undefined | RandomIntCallback;\n max = arg1;\n min = 0;\n } else {\n min = arg1;\n max = arg2 as any as number;\n }\n\n const isSync = typeof callback === 'undefined';\n if (!Number.isSafeInteger(min)) {\n // todo throw new ERR_INVALID_ARG_TYPE('min', 'a safe integer', min);\n throw 'ERR_INVALID_ARG_TYPE';\n }\n if (!Number.isSafeInteger(max)) {\n // todo throw new ERR_INVALID_ARG_TYPE('max', 'a safe integer', max);\n throw 'ERR_INVALID_ARG_TYPE';\n }\n if (max <= min) {\n /* todo throw new ERR_OUT_OF_RANGE(\n 'max',\n `greater than the value of \"min\" (${min})`,\n max\n );*/\n throw 'ERR_OUT_OF_RANGE';\n }\n\n // First we generate a random int between [0..range)\n const range = max - min;\n\n if (!(range <= RAND_MAX)) {\n /* todo throw new ERR_OUT_OF_RANGE(\n `max${minNotSpecified ? '' : ' - min'}`,\n `<= ${RAND_MAX}`,\n range\n );*/\n throw 'ERR_OUT_OF_RANGE';\n }\n\n // For (x % range) to produce an unbiased value greater than or equal to 0 and\n // less than range, x must be drawn randomly from the set of integers greater\n // than or equal to 0 and less than randLimit.\n const randLimit = RAND_MAX - (RAND_MAX % range);\n\n // If we don't have a callback, or if there is still data in the cache, we can\n // do this synchronously, which is super fast.\n while (isSync || randomCacheOffset < randomCache.length) {\n if (randomCacheOffset === randomCache.length) {\n // This might block the thread for a bit, but we are in sync mode.\n randomFillSync(randomCache);\n randomCacheOffset = 0;\n }\n\n const x = randomCache.readUIntBE(randomCacheOffset, 6);\n randomCacheOffset += 6;\n\n if (x < randLimit) {\n const n = (x % range) + min;\n if (isSync) return n;\n process.nextTick(callback as Function, undefined, n);\n return;\n }\n }\n\n // At this point, we are in async mode with no data in the cache. We cannot\n // simply refill the cache, because another async call to randomInt might\n // already be doing that. Instead, queue this call for when the cache has\n // been refilled.\n if (callback !== undefined) {\n // it is (typescript doesn't know it)\n asyncCachePendingTasks.push({ min, max, callback });\n asyncRefillRandomIntCache();\n }\n}\n\nfunction asyncRefillRandomIntCache() {\n if (asyncCacheFillInProgress) return;\n\n asyncCacheFillInProgress = true;\n randomFill(randomCache, (err) => {\n asyncCacheFillInProgress = false;\n\n const tasks = asyncCachePendingTasks;\n const errorReceiver = err && tasks.shift();\n if (!err) randomCacheOffset = 0;\n\n // Restart all pending tasks. If an error occurred, we only notify a single\n // callback (errorReceiver) about it. This way, every async call to\n // randomInt has a chance of being successful, and it avoids complex\n // exception handling here.\n tasks.splice(0).forEach((task) => {\n randomInt(task.min, task.max, task.callback);\n });\n\n // This is the only call that might throw, and is therefore done at the end.\n if (errorReceiver) errorReceiver.callback(err, 0);\n });\n}\n\n// Really just the Web Crypto API alternative\n// to require('crypto').randomFillSync() with an\n// additional limitation that the input buffer is\n// not allowed to exceed 65536 bytes, and can only\n// be an integer-type TypedArray.\ntype DataType =\n | Int8Array\n | Int16Array\n | Int32Array\n | Uint8Array\n | Uint16Array\n | Uint32Array;\nexport function getRandomValues(data: DataType) {\n if (data.byteLength > 65536) {\n throw new Error('The requested length exceeds 65,536 bytes');\n }\n randomFillSync(data, 0);\n return data;\n}\n\nconst byteToHex: string[] = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\n\n// Based on https://github.com/uuidjs/uuid/blob/main/src/v4.js\nexport function randomUUID() {\n const size = 16;\n const buffer = new Buffer(size)\n randomFillSync(buffer, 0, size);\n\n // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n buffer[6] = (buffer[6] & 0x0f) | 0x40;\n buffer[8] = (buffer[8] & 0x3f) | 0x80;\n\n return (\n byteToHex[buffer[0]] +\n byteToHex[buffer[1]] +\n byteToHex[buffer[2]] +\n byteToHex[buffer[3]] +\n '-' +\n byteToHex[buffer[4]] +\n byteToHex[buffer[5]] +\n '-' +\n byteToHex[buffer[6]] +\n byteToHex[buffer[7]] +\n '-' +\n byteToHex[buffer[8]] +\n byteToHex[buffer[9]] +\n '-' +\n byteToHex[buffer[10]] +\n byteToHex[buffer[11]] +\n byteToHex[buffer[12]] +\n byteToHex[buffer[13]] +\n byteToHex[buffer[14]] +\n byteToHex[buffer[15]]\n ).toLowerCase();\n}\n\n"]}
@@ -77,11 +77,6 @@ export const kEmptyObject = Object.freeze(Object.create(null)); // Should be use
77
77
  // return slowCases(enc);
78
78
  // }
79
79
 
80
- export function isBuffer(buf) {
81
- var _buf$constructor;
82
-
83
- return buf instanceof Buffer || (buf === null || buf === void 0 ? void 0 : (_buf$constructor = buf.constructor) === null || _buf$constructor === void 0 ? void 0 : _buf$constructor.name) === 'Buffer';
84
- }
85
80
  export function toArrayBuffer(buf) {
86
81
  var _buf$buffer;
87
82
 
@@ -106,7 +101,7 @@ export function binaryLikeToArrayBuffer(input) {
106
101
  return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
107
102
  }
108
103
 
109
- if (isBuffer(input)) {
104
+ if (Buffer.isBuffer(input)) {
110
105
  return toArrayBuffer(input);
111
106
  } // TODO add further binary types to BinaryLike, UInt8Array and so for have this array as property
112
107
 
@@ -1 +1 @@
1
- {"version":3,"sources":["Utils.ts"],"names":["Buffer","defaultEncoding","setDefaultEncoding","encoding","getDefaultEncoding","kEmptyObject","Object","freeze","create","isBuffer","buf","constructor","name","toArrayBuffer","buffer","slice","byteOffset","byteLength","ab","ArrayBuffer","length","view","Uint8Array","i","binaryLikeToArrayBuffer","input","from","ab2str","toString","validateString","str","isString","Error","validateFunction","f","isStringOrBuffer","val","isView","validateObject","value","options","useDefaultOptions","allowArray","allowFunction","nullable","Array","isArray","validateInt32","min","max","Number","isInteger","validateUint32","positive"],"mappings":"AAAA,SAASA,MAAT,QAAuB,gCAAvB;AAeA;AACA,IAAIC,eAA+B,GAAG,QAAtC;AAEA,OAAO,SAASC,kBAAT,CAA4BC,QAA5B,EAAsD;AAC3DF,EAAAA,eAAe,GAAGE,QAAlB;AACD;AAED,OAAO,SAASC,kBAAT,GAA8C;AACnD,SAAOH,eAAP;AACD;AAED,OAAO,MAAMI,YAAY,GAAGC,MAAM,CAACC,MAAP,CAAcD,MAAM,CAACE,MAAP,CAAc,IAAd,CAAd,CAArB,C,CAEP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,OAAO,SAASC,QAAT,CAAkBC,GAAlB,EAA2C;AAAA;;AAChD,SAAOA,GAAG,YAAYV,MAAf,IAAyB,CAAAU,GAAG,SAAH,IAAAA,GAAG,WAAH,gCAAAA,GAAG,CAAEC,WAAL,sEAAkBC,IAAlB,MAA2B,QAA3D;AACD;AAED,OAAO,SAASC,aAAT,CAAuBH,GAAvB,EAAiD;AAAA;;AACtD,MAAIA,GAAJ,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CAAH,GAAO,CAA3B,CAXA,CAYA;;AACA,QAAMJ,GAAG,GAAG,UAAZ;;AACA,MAAIV,KAAK,GAAGS,GAAR,IAAeT,KAAK,GAAGU,GAA3B,EAAgC;AAC9B;AACA,UAAM,IAAIjB,KAAJ,CACH,sBAAqBpB,IAAK,oBAAmBoC,GAAI,UAASC,GAAI,KAAIV,KAAM,EADrE,CAAN;AAGD;AACF","sourcesContent":["import { Buffer } from '@craftzdog/react-native-buffer';\n\nexport type BinaryLike = string | ArrayBuffer | Buffer;\n\nexport type BinaryToTextEncoding = 'base64' | 'base64url' | 'hex' | 'binary';\nexport type CharacterEncoding = 'utf8' | 'utf-8' | 'utf16le' | 'latin1';\nexport type LegacyCharacterEncoding = 'ascii' | 'binary' | 'ucs2' | 'ucs-2';\nexport type Encoding =\n | BinaryToTextEncoding\n | CharacterEncoding\n | LegacyCharacterEncoding;\n\n// TODO(osp) should buffer be part of the Encoding type?\nexport type CipherEncoding = Encoding | 'buffer';\n\n// Mimics node behavior for default global encoding\nlet defaultEncoding: CipherEncoding = 'buffer';\n\nexport function setDefaultEncoding(encoding: CipherEncoding) {\n defaultEncoding = encoding;\n}\n\nexport function getDefaultEncoding(): CipherEncoding {\n return defaultEncoding;\n}\n\nexport const kEmptyObject = Object.freeze(Object.create(null));\n\n// Should be used by Cipher (or any other module that requires valid encodings)\n// function slowCases(enc: string) {\n// switch (enc.length) {\n// case 4:\n// if (enc === 'UTF8') return 'utf8';\n// if (enc === 'ucs2' || enc === 'UCS2') return 'utf16le';\n// enc = `${enc}`.toLowerCase();\n// if (enc === 'utf8') return 'utf8';\n// if (enc === 'ucs2') return 'utf16le';\n// break;\n// case 3:\n// if (enc === 'hex' || enc === 'HEX' || `${enc}`.toLowerCase() === 'hex')\n// return 'hex';\n// break;\n// case 5:\n// if (enc === 'ascii') return 'ascii';\n// if (enc === 'ucs-2') return 'utf16le';\n// if (enc === 'UTF-8') return 'utf8';\n// if (enc === 'ASCII') return 'ascii';\n// if (enc === 'UCS-2') return 'utf16le';\n// enc = `${enc}`.toLowerCase();\n// if (enc === 'utf-8') return 'utf8';\n// if (enc === 'ascii') return 'ascii';\n// if (enc === 'ucs-2') return 'utf16le';\n// break;\n// case 6:\n// if (enc === 'base64') return 'base64';\n// if (enc === 'latin1' || enc === 'binary') return 'latin1';\n// if (enc === 'BASE64') return 'base64';\n// if (enc === 'LATIN1' || enc === 'BINARY') return 'latin1';\n// enc = `${enc}`.toLowerCase();\n// if (enc === 'base64') return 'base64';\n// if (enc === 'latin1' || enc === 'binary') return 'latin1';\n// break;\n// case 7:\n// if (\n// enc === 'utf16le' ||\n// enc === 'UTF16LE' ||\n// `${enc}`.toLowerCase() === 'utf16le'\n// )\n// return 'utf16le';\n// break;\n// case 8:\n// if (\n// enc === 'utf-16le' ||\n// enc === 'UTF-16LE' ||\n// `${enc}`.toLowerCase() === 'utf-16le'\n// )\n// return 'utf16le';\n// break;\n// case 9:\n// if (\n// enc === 'base64url' ||\n// enc === 'BASE64URL' ||\n// `${enc}`.toLowerCase() === 'base64url'\n// )\n// return 'base64url';\n// break;\n// default:\n// if (enc === '') return 'utf8';\n// }\n// }\n\n// // Return undefined if there is no match.\n// // Move the \"slow cases\" to a separate function to make sure this function gets\n// // inlined properly. That prioritizes the common case.\n// export function normalizeEncoding(enc?: string) {\n// if (enc == null || enc === 'utf8' || enc === 'utf-8') return 'utf8';\n// return slowCases(enc);\n// }\n\nexport function isBuffer(buf: any): buf is Buffer {\n return buf instanceof Buffer || buf?.constructor?.name === 'Buffer';\n}\n\nexport function toArrayBuffer(buf: Buffer): ArrayBuffer {\n if (buf?.buffer?.slice) {\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);\n }\n const ab = new ArrayBuffer(buf.length);\n const view = new Uint8Array(ab);\n for (let i = 0; i < buf.length; ++i) {\n view[i] = buf[i];\n }\n return ab;\n}\n\nexport function binaryLikeToArrayBuffer(\n input: BinaryLike,\n encoding: string = 'utf-8'\n): ArrayBuffer {\n if (typeof input === 'string') {\n const buffer = Buffer.from(input, encoding);\n\n return buffer.buffer.slice(\n buffer.byteOffset,\n buffer.byteOffset + buffer.byteLength\n );\n }\n\n if (isBuffer(input)) {\n return toArrayBuffer(input);\n }\n\n // TODO add further binary types to BinaryLike, UInt8Array and so for have this array as property\n if ((input as any).buffer) {\n return (input as any).buffer;\n }\n\n if (!(input instanceof ArrayBuffer)) {\n try {\n const buffer = Buffer.from(input);\n return buffer.buffer.slice(\n buffer.byteOffset,\n buffer.byteOffset + buffer.byteLength\n );\n } catch {\n throw 'error';\n }\n }\n return input;\n}\n\nexport function ab2str(buf: ArrayBuffer, encoding: string = 'hex') {\n return Buffer.from(buf).toString(encoding);\n}\n\nexport function validateString(str: any, name?: string): str is string {\n const isString = typeof str === 'string';\n if (isString) {\n throw new Error(`${name} is not a string`);\n }\n return isString;\n}\n\nexport function validateFunction(f: any): f is Function {\n return f != null && typeof f === 'function';\n}\n\nexport function isStringOrBuffer(val: any): val is string | ArrayBuffer {\n return typeof val === 'string' || ArrayBuffer.isView(val);\n}\n\nexport function validateObject<T>(\n value: any,\n name: string,\n options?: {\n allowArray: boolean;\n allowFunction: boolean;\n nullable: boolean;\n } | null\n): value is T {\n const useDefaultOptions = options == null;\n const allowArray = useDefaultOptions ? false : options.allowArray;\n const allowFunction = useDefaultOptions ? false : options.allowFunction;\n const nullable = useDefaultOptions ? false : options.nullable;\n if (\n (!nullable && value === null) ||\n (!allowArray && Array.isArray(value)) ||\n (typeof value !== 'object' &&\n (!allowFunction || typeof value !== 'function'))\n ) {\n throw new Error(`${name} is not a valid object $${value}`);\n }\n return true;\n}\n\nexport function validateInt32(\n value: any,\n name: string,\n min = -2147483648,\n max = 2147483647\n) {\n // The defaults for min and max correspond to the limits of 32-bit integers.\n if (typeof value !== 'number') {\n throw new Error(`Invalid argument - ${name} is not a number: ${value}`);\n }\n if (!Number.isInteger(value)) {\n throw new Error(\n `Argument out of range - ${name} out of integer range: ${value}`\n );\n }\n if (value < min || value > max) {\n throw new Error(\n `Invalid argument - ${name} out of range >= ${min} && <= ${max}: ${value}`\n );\n }\n}\n\nexport function validateUint32(\n value: number,\n name: string,\n positive?: boolean\n) {\n if (typeof value !== 'number') {\n // throw new ERR_INVALID_ARG_TYPE(name, 'number', value);\n throw new Error(`Invalid argument - ${name} is not a number: ${value}`);\n }\n if (!Number.isInteger(value)) {\n // throw new ERR_OUT_OF_RANGE(name, 'an integer', value);\n throw new Error(\n `Argument out of range - ${name} out of integer range: ${value}`\n );\n }\n const min = positive ? 1 : 0;\n // 2 ** 32 === 4294967296\n const max = 4294967295;\n if (value < min || value > max) {\n // throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value);\n throw new Error(\n `Invalid argument - ${name} out of range >= ${min} && <= ${max}: ${value}`\n );\n }\n}\n"]}
1
+ {"version":3,"sources":["Utils.ts"],"names":["Buffer","defaultEncoding","setDefaultEncoding","encoding","getDefaultEncoding","kEmptyObject","Object","freeze","create","toArrayBuffer","buf","buffer","slice","byteOffset","byteLength","ab","ArrayBuffer","length","view","Uint8Array","i","binaryLikeToArrayBuffer","input","from","isBuffer","ab2str","toString","validateString","str","name","isString","Error","validateFunction","f","isStringOrBuffer","val","isView","validateObject","value","options","useDefaultOptions","allowArray","allowFunction","nullable","Array","isArray","validateInt32","min","max","Number","isInteger","validateUint32","positive"],"mappings":"AAAA,SAASA,MAAT,QAAuB,gCAAvB;AAeA;AACA,IAAIC,eAA+B,GAAG,QAAtC;AAEA,OAAO,SAASC,kBAAT,CAA4BC,QAA5B,EAAsD;AAC3DF,EAAAA,eAAe,GAAGE,QAAlB;AACD;AAED,OAAO,SAASC,kBAAT,GAA8C;AACnD,SAAOH,eAAP;AACD;AAED,OAAO,MAAMI,YAAY,GAAGC,MAAM,CAACC,MAAP,CAAcD,MAAM,CAACE,MAAP,CAAc,IAAd,CAAd,CAArB,C,CAEP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAC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AACA,MAAI,OAAOd,KAAP,KAAiB,QAArB,EAA+B;AAC7B;AACA,UAAM,IAAIP,KAAJ,CAAW,sBAAqBF,IAAK,qBAAoBS,KAAM,EAA/D,CAAN;AACD;;AACD,MAAI,CAACW,MAAM,CAACC,SAAP,CAAiBZ,KAAjB,CAAL,EAA8B;AAC5B;AACA,UAAM,IAAIP,KAAJ,CACH,2BAA0BF,IAAK,0BAAyBS,KAAM,EAD3D,CAAN;AAGD;;AACD,QAAMS,GAAG,GAAGK,QAAQ,GAAG,CAAH,GAAO,CAA3B,CAXA,CAYA;;AACA,QAAMJ,GAAG,GAAG,UAAZ;;AACA,MAAIV,KAAK,GAAGS,GAAR,IAAeT,KAAK,GAAGU,GAA3B,EAAgC;AAC9B;AACA,UAAM,IAAIjB,KAAJ,CACH,sBAAqBF,IAAK,oBAAmBkB,GAAI,UAASC,GAAI,KAAIV,KAAM,EADrE,CAAN;AAGD;AACF","sourcesContent":["import { Buffer } from '@craftzdog/react-native-buffer';\n\nexport type BinaryLike = string | ArrayBuffer | Buffer;\n\nexport type BinaryToTextEncoding = 'base64' | 'base64url' | 'hex' | 'binary';\nexport type CharacterEncoding = 'utf8' | 'utf-8' | 'utf16le' | 'latin1';\nexport type LegacyCharacterEncoding = 'ascii' | 'binary' | 'ucs2' | 'ucs-2';\nexport type Encoding =\n | BinaryToTextEncoding\n | CharacterEncoding\n | LegacyCharacterEncoding;\n\n// TODO(osp) should buffer be part of the Encoding type?\nexport type CipherEncoding = Encoding | 'buffer';\n\n// Mimics node behavior for default global encoding\nlet defaultEncoding: CipherEncoding = 'buffer';\n\nexport function setDefaultEncoding(encoding: CipherEncoding) {\n defaultEncoding = encoding;\n}\n\nexport function getDefaultEncoding(): CipherEncoding {\n return defaultEncoding;\n}\n\nexport const kEmptyObject = Object.freeze(Object.create(null));\n\n// Should be used by Cipher (or any other module that requires valid encodings)\n// function slowCases(enc: string) {\n// switch (enc.length) {\n// case 4:\n// if (enc === 'UTF8') return 'utf8';\n// if (enc === 'ucs2' || enc === 'UCS2') return 'utf16le';\n// enc = `${enc}`.toLowerCase();\n// if (enc === 'utf8') return 'utf8';\n// if (enc === 'ucs2') return 'utf16le';\n// break;\n// case 3:\n// if (enc === 'hex' || enc === 'HEX' || `${enc}`.toLowerCase() === 'hex')\n// return 'hex';\n// break;\n// case 5:\n// if (enc === 'ascii') return 'ascii';\n// if (enc === 'ucs-2') return 'utf16le';\n// if (enc === 'UTF-8') return 'utf8';\n// if (enc === 'ASCII') return 'ascii';\n// if (enc === 'UCS-2') return 'utf16le';\n// enc = `${enc}`.toLowerCase();\n// if (enc === 'utf-8') return 'utf8';\n// if (enc === 'ascii') return 'ascii';\n// if (enc === 'ucs-2') return 'utf16le';\n// break;\n// case 6:\n// if (enc === 'base64') return 'base64';\n// if (enc === 'latin1' || enc === 'binary') return 'latin1';\n// if (enc === 'BASE64') return 'base64';\n// if (enc === 'LATIN1' || enc === 'BINARY') return 'latin1';\n// enc = `${enc}`.toLowerCase();\n// if (enc === 'base64') return 'base64';\n// if (enc === 'latin1' || enc === 'binary') return 'latin1';\n// break;\n// case 7:\n// if (\n// enc === 'utf16le' ||\n// enc === 'UTF16LE' ||\n// `${enc}`.toLowerCase() === 'utf16le'\n// )\n// return 'utf16le';\n// break;\n// case 8:\n// if (\n// enc === 'utf-16le' ||\n// enc === 'UTF-16LE' ||\n// `${enc}`.toLowerCase() === 'utf-16le'\n// )\n// return 'utf16le';\n// break;\n// case 9:\n// if (\n// enc === 'base64url' ||\n// enc === 'BASE64URL' ||\n// `${enc}`.toLowerCase() === 'base64url'\n// )\n// return 'base64url';\n// break;\n// default:\n// if (enc === '') return 'utf8';\n// }\n// }\n\n// // Return undefined if there is no match.\n// // Move the \"slow cases\" to a separate function to make sure this function gets\n// // inlined properly. That prioritizes the common case.\n// export function normalizeEncoding(enc?: string) {\n// if (enc == null || enc === 'utf8' || enc === 'utf-8') return 'utf8';\n// return slowCases(enc);\n// }\n\nexport function toArrayBuffer(buf: Buffer): ArrayBuffer {\n if (buf?.buffer?.slice) {\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);\n }\n const ab = new ArrayBuffer(buf.length);\n const view = new Uint8Array(ab);\n for (let i = 0; i < buf.length; ++i) {\n view[i] = buf[i];\n }\n return ab;\n}\n\nexport function binaryLikeToArrayBuffer(\n input: BinaryLike,\n encoding: string = 'utf-8'\n): ArrayBuffer {\n if (typeof input === 'string') {\n const buffer = Buffer.from(input, encoding);\n\n return buffer.buffer.slice(\n buffer.byteOffset,\n buffer.byteOffset + buffer.byteLength\n );\n }\n\n if (Buffer.isBuffer(input)) {\n return toArrayBuffer(input);\n }\n\n // TODO add further binary types to BinaryLike, UInt8Array and so for have this array as property\n if ((input as any).buffer) {\n return (input as any).buffer;\n }\n\n if (!(input instanceof ArrayBuffer)) {\n try {\n const buffer = Buffer.from(input);\n return buffer.buffer.slice(\n buffer.byteOffset,\n buffer.byteOffset + buffer.byteLength\n );\n } catch {\n throw 'error';\n }\n }\n return input;\n}\n\nexport function ab2str(buf: ArrayBuffer, encoding: string = 'hex') {\n return Buffer.from(buf).toString(encoding);\n}\n\nexport function validateString(str: any, name?: string): str is string {\n const isString = typeof str === 'string';\n if (isString) {\n throw new Error(`${name} is not a string`);\n }\n return isString;\n}\n\nexport function validateFunction(f: any): f is Function {\n return f != null && typeof f === 'function';\n}\n\nexport function isStringOrBuffer(val: any): val is string | ArrayBuffer {\n return typeof val === 'string' || ArrayBuffer.isView(val);\n}\n\nexport function validateObject<T>(\n value: any,\n name: string,\n options?: {\n allowArray: boolean;\n allowFunction: boolean;\n nullable: boolean;\n } | null\n): value is T {\n const useDefaultOptions = options == null;\n const allowArray = useDefaultOptions ? false : options.allowArray;\n const allowFunction = useDefaultOptions ? false : options.allowFunction;\n const nullable = useDefaultOptions ? false : options.nullable;\n if (\n (!nullable && value === null) ||\n (!allowArray && Array.isArray(value)) ||\n (typeof value !== 'object' &&\n (!allowFunction || typeof value !== 'function'))\n ) {\n throw new Error(`${name} is not a valid object $${value}`);\n }\n return true;\n}\n\nexport function validateInt32(\n value: any,\n name: string,\n min = -2147483648,\n max = 2147483647\n) {\n // The defaults for min and max correspond to the limits of 32-bit integers.\n if (typeof value !== 'number') {\n throw new Error(`Invalid argument - ${name} is not a number: ${value}`);\n }\n if (!Number.isInteger(value)) {\n throw new Error(\n `Argument out of range - ${name} out of integer range: ${value}`\n );\n }\n if (value < min || value > max) {\n throw new Error(\n `Invalid argument - ${name} out of range >= ${min} && <= ${max}: ${value}`\n );\n }\n}\n\nexport function validateUint32(\n value: number,\n name: string,\n positive?: boolean\n) {\n if (typeof value !== 'number') {\n // throw new ERR_INVALID_ARG_TYPE(name, 'number', value);\n throw new Error(`Invalid argument - ${name} is not a number: ${value}`);\n }\n if (!Number.isInteger(value)) {\n // throw new ERR_OUT_OF_RANGE(name, 'an integer', value);\n throw new Error(\n `Argument out of range - ${name} out of integer range: ${value}`\n );\n }\n const min = positive ? 1 : 0;\n // 2 ** 32 === 4294967296\n const max = 4294967295;\n if (value < min || value > max) {\n // throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value);\n throw new Error(\n `Invalid argument - ${name} out of range >= ${min} && <= ${max}: ${value}`\n );\n }\n}\n"]}
@@ -1,6 +1,5 @@
1
1
  import { NativeQuickCrypto } from './NativeQuickCrypto/NativeQuickCrypto';
2
2
  import { Buffer } from '@craftzdog/react-native-buffer';
3
- import { isBuffer } from '../src/Utils';
4
3
  const random = NativeQuickCrypto.random;
5
4
  export function randomFill(buffer) {
6
5
  var _ref, _ref2;
@@ -22,7 +21,7 @@ export function randomFill(buffer) {
22
21
  offset = arguments.length <= 1 ? undefined : arguments[1];
23
22
  }
24
23
 
25
- random.randomFill(isBuffer(buffer) ? buffer.buffer : buffer, offset, size).then(() => {
24
+ random.randomFill(Buffer.isBuffer(buffer) ? buffer.buffer : buffer, offset, size).then(() => {
26
25
  callback(null, buffer);
27
26
  }, e => {
28
27
  callback(e);
@@ -187,4 +186,20 @@ export function getRandomValues(data) {
187
186
  randomFillSync(data, 0);
188
187
  return data;
189
188
  }
189
+ const byteToHex = [];
190
+
191
+ for (let i = 0; i < 256; ++i) {
192
+ byteToHex.push((i + 0x100).toString(16).slice(1));
193
+ } // Based on https://github.com/uuidjs/uuid/blob/main/src/v4.js
194
+
195
+
196
+ export function randomUUID() {
197
+ const size = 16;
198
+ const buffer = new Buffer(size);
199
+ randomFillSync(buffer, 0, size); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
200
+
201
+ buffer[6] = buffer[6] & 0x0f | 0x40;
202
+ buffer[8] = buffer[8] & 0x3f | 0x80;
203
+ return (byteToHex[buffer[0]] + byteToHex[buffer[1]] + byteToHex[buffer[2]] + byteToHex[buffer[3]] + '-' + byteToHex[buffer[4]] + byteToHex[buffer[5]] + '-' + byteToHex[buffer[6]] + byteToHex[buffer[7]] + '-' + byteToHex[buffer[8]] + byteToHex[buffer[9]] + '-' + byteToHex[buffer[10]] + byteToHex[buffer[11]] + byteToHex[buffer[12]] + byteToHex[buffer[13]] + byteToHex[buffer[14]] + byteToHex[buffer[15]]).toLowerCase();
204
+ }
190
205
  //# sourceMappingURL=random.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["random.ts"],"names":["NativeQuickCrypto","Buffer","isBuffer","random","randomFill","buffer","Error","callback","offset","size","byteLength","then","e","randomFillSync","randomBytes","buf","undefined","error","rng","pseudoRandomBytes","prng","RAND_MAX","randomCache","randomCacheOffset","length","asyncCacheFillInProgress","asyncCachePendingTasks","randomInt","arg1","arg2","max","min","minNotSpecified","isSync","Number","isSafeInteger","range","randLimit","x","readUIntBE","n","process","nextTick","push","asyncRefillRandomIntCache","err","tasks","errorReceiver","shift","splice","forEach","task","getRandomValues","data"],"mappings":"AAAA,SAASA,iBAAT,QAAkC,uCAAlC;AACA,SAASC,MAAT,QAAuB,gCAAvB;AACA,SAASC,QAAT,QAAyB,cAAzB;AAEA,MAAMC,MAAM,GAAGH,iBAAiB,CAACG,MAA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MAAAA;AAAZ,KAA5B;AACAqC,IAAAA,yBAAyB;AAC1B;AACF;;AAED,SAASA,yBAAT,GAAqC;AACnC,MAAInB,wBAAJ,EAA8B;AAE9BA,EAAAA,wBAAwB,GAAG,IAA3B;AACArB,EAAAA,UAAU,CAACkB,WAAD,EAAeuB,GAAD,IAAS;AAC/BpB,IAAAA,wBAAwB,GAAG,KAA3B;AAEA,UAAMqB,KAAK,GAAGpB,sBAAd;AACA,UAAMqB,aAAa,GAAGF,GAAG,IAAIC,KAAK,CAACE,KAAN,EAA7B;AACA,QAAI,CAACH,GAAL,EAAUtB,iBAAiB,GAAG,CAApB,CALqB,CAO/B;AACA;AACA;AACA;;AACAuB,IAAAA,KAAK,CAACG,MAAN,CAAa,CAAb,EAAgBC,OAAhB,CAAyBC,IAAD,IAAU;AAChCxB,MAAAA,SAAS,CAACwB,IAAI,CAACpB,GAAN,EAAWoB,IAAI,CAACrB,GAAhB,EAAqBqB,IAAI,CAAC5C,QAA1B,CAAT;AACD,KAFD,EAX+B,CAe/B;;AACA,QAAIwC,aAAJ,EAAmBA,aAAa,CAACxC,QAAd,CAAuBsC,GAAvB,EAA4B,CAA5B;AACpB,GAjBS,CAAV;AAkBD,C,CAED;AACA;AACA;AACA;AACA;;;AAQA,OAAO,SAASO,eAAT,CAAyBC,IAAzB,EAAyC;AAC9C,MAAIA,IAAI,CAAC3C,UAAL,GAAkB,KAAtB,EAA6B;AAC3B,UAAM,IAAIJ,KAAJ,CAAU,2CAAV,CAAN;AACD;;AACDO,EAAAA,cAAc,CAACwC,IAAD,EAAO,CAAP,CAAd;AACA,SAAOA,IAAP;AACD","sourcesContent":["import { NativeQuickCrypto } from './NativeQuickCrypto/NativeQuickCrypto';\nimport { Buffer } from '@craftzdog/react-native-buffer';\nimport { isBuffer } from '../src/Utils';\n\nconst random = NativeQuickCrypto.random;\n\ntype TypedArray =\n | Uint8Array\n | Uint8ClampedArray\n | Uint16Array\n | Uint32Array\n | Int8Array\n | Int16Array\n | Int32Array\n | Float32Array\n | Float64Array;\ntype ArrayBufferView = TypedArray | DataView | ArrayBufferLike | Buffer;\n\nexport function randomFill<T extends ArrayBufferView>(\n buffer: T,\n callback: (err: Error | null, buf: T) => void\n): void;\n\nexport function randomFill<T extends ArrayBufferView>(\n buffer: T,\n offset: number,\n callback: (err: Error | null, buf: T) => void\n): void;\n\nexport function randomFill<T extends ArrayBufferView>(\n buffer: T,\n offset: number,\n size: number,\n callback: (err: Error | null, buf: T) => void\n): void;\n\nexport function randomFill(buffer: any, ...rest: any[]): void {\n if (typeof rest[rest.length - 1] !== 'function') {\n throw new Error('No callback provided to randomDill');\n }\n\n const callback = rest[rest.length - 1] as any as (\n err: Error | null,\n buf?: ArrayBuffer\n ) => void;\n\n let offset: number = 0;\n let size: number = buffer.byteLength;\n\n if (typeof rest[2] === 'function') {\n offset = rest[0];\n size = rest[1];\n }\n\n if (typeof rest[1] === 'function') {\n offset = rest[0];\n }\n\n random\n .randomFill(isBuffer(buffer) ? buffer.buffer : buffer, offset, size)\n .then(\n () => {\n callback(null, buffer);\n },\n (e: Error) => {\n callback(e);\n }\n );\n}\n\nexport function randomFillSync<T extends ArrayBufferView>(\n buffer: T,\n offset?: number,\n size?: number\n): T;\n\nexport function randomFillSync(buffer: any, offset: number = 0, size?: number) {\n random.randomFillSync(\n buffer.buffer ? buffer.buffer : buffer,\n offset,\n size ?? buffer.byteLength\n );\n return buffer;\n}\n\nexport function randomBytes(size: number): ArrayBuffer;\n\nexport function randomBytes(\n size: number,\n callback: (err: Error | null, buf?: ArrayBuffer) => void\n): void;\n\nexport function randomBytes(\n size: number,\n callback?: (err: Error | null, buf?: ArrayBuffer) => void\n): void | ArrayBuffer {\n const buf = new Buffer(size);\n\n if (callback === undefined) {\n randomFillSync(buf.buffer, 0, size);\n return buf;\n }\n\n randomFill(buf.buffer, 0, size, (error: Error | null) => {\n if (error) {\n callback(error);\n }\n callback(null, buf);\n });\n}\n\nexport const rng = randomBytes;\nexport const pseudoRandomBytes = randomBytes;\nexport const prng = randomBytes;\n\ntype RandomIntCallback = (err: Error | null, value: number) => void;\ntype Task = {\n min: number;\n max: number;\n callback: RandomIntCallback;\n};\n\n// The rest of the file is taken from https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js\n\n// Largest integer we can read from a buffer.\n// e.g.: Buffer.from(\"ff\".repeat(6), \"hex\").readUIntBE(0, 6);\nconst RAND_MAX = 0xffffffffffff;\n\n// Cache random data to use in randomInt. The cache size must be evenly\n// divisible by 6 because each attempt to obtain a random int uses 6 bytes.\nconst randomCache = new Buffer(6 * 1024);\nlet randomCacheOffset = randomCache.length;\nlet asyncCacheFillInProgress = false;\nconst asyncCachePendingTasks: Task[] = [];\n\n// Generates an integer in [min, max) range where min is inclusive and max is\n// exclusive.\n\nexport function randomInt(max: number, callback: RandomIntCallback): void;\nexport function randomInt(max: number): number;\nexport function randomInt(\n min: number,\n max: number,\n callback: RandomIntCallback\n): void;\nexport function randomInt(min: number, max: number): number;\nexport function randomInt(\n arg1: number,\n arg2?: number | RandomIntCallback,\n callback?: RandomIntCallback\n): void | number {\n // Detect optional min syntax\n // randomInt(max)\n // randomInt(max, callback)\n let max: number;\n let min: number;\n const minNotSpecified =\n typeof arg2 === 'undefined' || typeof arg2 === 'function';\n\n if (minNotSpecified) {\n callback = arg2 as any as undefined | RandomIntCallback;\n max = arg1;\n min = 0;\n } else {\n min = arg1;\n max = arg2 as any as number;\n }\n\n const isSync = typeof callback === 'undefined';\n if (!Number.isSafeInteger(min)) {\n // todo throw new ERR_INVALID_ARG_TYPE('min', 'a safe integer', min);\n throw 'ERR_INVALID_ARG_TYPE';\n }\n if (!Number.isSafeInteger(max)) {\n // todo throw new ERR_INVALID_ARG_TYPE('max', 'a safe integer', max);\n throw 'ERR_INVALID_ARG_TYPE';\n }\n if (max <= min) {\n /* todo throw new ERR_OUT_OF_RANGE(\n 'max',\n `greater than the value of \"min\" (${min})`,\n max\n );*/\n throw 'ERR_OUT_OF_RANGE';\n }\n\n // First we generate a random int between [0..range)\n const range = max - min;\n\n if (!(range <= RAND_MAX)) {\n /* todo throw new ERR_OUT_OF_RANGE(\n `max${minNotSpecified ? '' : ' - min'}`,\n `<= ${RAND_MAX}`,\n range\n );*/\n throw 'ERR_OUT_OF_RANGE';\n }\n\n // For (x % range) to produce an unbiased value greater than or equal to 0 and\n // less than range, x must be drawn randomly from the set of integers greater\n // than or equal to 0 and less than randLimit.\n const randLimit = RAND_MAX - (RAND_MAX % range);\n\n // If we don't have a callback, or if there is still data in the cache, we can\n // do this synchronously, which is super fast.\n while (isSync || randomCacheOffset < randomCache.length) {\n if (randomCacheOffset === randomCache.length) {\n // This might block the thread for a bit, but we are in sync mode.\n randomFillSync(randomCache);\n randomCacheOffset = 0;\n }\n\n const x = randomCache.readUIntBE(randomCacheOffset, 6);\n randomCacheOffset += 6;\n\n if (x < randLimit) {\n const n = (x % range) + min;\n if (isSync) return n;\n process.nextTick(callback as Function, undefined, n);\n return;\n }\n }\n\n // At this point, we are in async mode with no data in the cache. We cannot\n // simply refill the cache, because another async call to randomInt might\n // already be doing that. Instead, queue this call for when the cache has\n // been refilled.\n if (callback !== undefined) {\n // it is (typescript doesn't know it)\n asyncCachePendingTasks.push({ min, max, callback });\n asyncRefillRandomIntCache();\n }\n}\n\nfunction asyncRefillRandomIntCache() {\n if (asyncCacheFillInProgress) return;\n\n asyncCacheFillInProgress = true;\n randomFill(randomCache, (err) => {\n asyncCacheFillInProgress = false;\n\n const tasks = asyncCachePendingTasks;\n const errorReceiver = err && tasks.shift();\n if (!err) randomCacheOffset = 0;\n\n // Restart all pending tasks. If an error occurred, we only notify a single\n // callback (errorReceiver) about it. This way, every async call to\n // randomInt has a chance of being successful, and it avoids complex\n // exception handling here.\n tasks.splice(0).forEach((task) => {\n randomInt(task.min, task.max, task.callback);\n });\n\n // This is the only call that might throw, and is therefore done at the end.\n if (errorReceiver) errorReceiver.callback(err, 0);\n });\n}\n\n// Really just the Web Crypto API alternative\n// to require('crypto').randomFillSync() with an\n// additional limitation that the input buffer is\n// not allowed to exceed 65536 bytes, and can only\n// be an integer-type TypedArray.\ntype DataType =\n | Int8Array\n | Int16Array\n | Int32Array\n | Uint8Array\n | Uint16Array\n | Uint32Array;\nexport function getRandomValues(data: DataType) {\n if (data.byteLength > 65536) {\n throw new Error('The requested length exceeds 65,536 bytes');\n }\n randomFillSync(data, 0);\n return data;\n}\n"]}
1
+ {"version":3,"sources":["random.ts"],"names":["NativeQuickCrypto","Buffer","random","randomFill","buffer","Error","callback","offset","size","byteLength","isBuffer","then","e","randomFillSync","randomBytes","buf","undefined","error","rng","pseudoRandomBytes","prng","RAND_MAX","randomCache","randomCacheOffset","length","asyncCacheFillInProgress","asyncCachePendingTasks","randomInt","arg1","arg2","max","min","minNotSpecified","isSync","Number","isSafeInteger","range","randLimit","x","readUIntBE","n","process","nextTick","push","asyncRefillRandomIntCache","err","tasks","errorReceiver","shift","splice","forEach","task","getRandomValues","data","byteToHex","i","toString","slice","randomUUID","toLowerCase"],"mappings":"AAAA,SAASA,iBAAT,QAAkC,uCAAlC;AACA,SAASC,MAAT,QAAuB,gCAAvB;AAEA,MAAMC,MAAM,GAAGF,iBAAiB,CAACE,MAAjC;AAgCA,OAAO,SAASC,UAAT,CAAoBC,MAApB,EAAuD;AAAA;;AAC5D,MAAI,eAAY,qDAAc,CAA1B,8EAAiC,UAArC,EAAiD;AAC/C,UAAM,IAAIC,KAAJ,CAAU,oCAAV,CAAN;AACD;;AAED,QAAMC,QAAQ,YAAQ,qDAAc,CAAtB,4EAAd;AAKA,MAAIC,MAAc,GAAG,CAArB;AACA,MAAIC,IAAY,GAAGJ,MAAM,CAACK,UAA1B;;AAEA,MAAI,8DAAmB,UAAvB,EAAmC;AACjCF,IAAAA,MAAM,mDAAN;AACAC,IAAAA,IAAI,mDAAJ;AACD;;AAED,MAAI,8DAAmB,UAAvB,EAAmC;AACjCD,IAAAA,MAAM,mDAAN;AACD;;AAEDL,EAAAA,MAAM,CACHC,UADH,CACc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CAAD,CAAP,CAAT,GACAkD,SAAS,CAAClD,MAAM,CAAC,CAAD,CAAP,CADT,GAEAkD,SAAS,CAAClD,MAAM,CAAC,CAAD,CAAP,CAFT,GAGAkD,SAAS,CAAClD,MAAM,CAAC,CAAD,CAAP,CAHT,GAIA,GAJA,GAKAkD,SAAS,CAAClD,MAAM,CAAC,CAAD,CAAP,CALT,GAMAkD,SAAS,CAAClD,MAAM,CAAC,CAAD,CAAP,CANT,GAOA,GAPA,GAQAkD,SAAS,CAAClD,MAAM,CAAC,CAAD,CAAP,CART,GASAkD,SAAS,CAAClD,MAAM,CAAC,CAAD,CAAP,CATT,GAUA,GAVA,GAWAkD,SAAS,CAAClD,MAAM,CAAC,CAAD,CAAP,CAXT,GAYAkD,SAAS,CAAClD,MAAM,CAAC,CAAD,CAAP,CAZT,GAaA,GAbA,GAcAkD,SAAS,CAAClD,MAAM,CAAC,EAAD,CAAP,CAdT,GAeAkD,SAAS,CAAClD,MAAM,CAAC,EAAD,CAAP,CAfT,GAgBAkD,SAAS,CAAClD,MAAM,CAAC,EAAD,CAAP,CAhBT,GAiBAkD,SAAS,CAAClD,MAAM,CAAC,EAAD,CAAP,CAjBT,GAkBAkD,SAAS,CAAClD,MAAM,CAAC,EAAD,CAAP,CAlBT,GAmBAkD,SAAS,CAAClD,MAAM,CAAC,EAAD,CAAP,CApBJ,EAqBLuD,WArBK,EAAP;AAsBD","sourcesContent":["import { NativeQuickCrypto } from './NativeQuickCrypto/NativeQuickCrypto';\nimport { Buffer } from '@craftzdog/react-native-buffer';\n\nconst random = NativeQuickCrypto.random;\n\ntype TypedArray =\n | Uint8Array\n | Uint8ClampedArray\n | Uint16Array\n | Uint32Array\n | Int8Array\n | Int16Array\n | Int32Array\n | Float32Array\n | Float64Array;\ntype ArrayBufferView = TypedArray | DataView | ArrayBufferLike | Buffer;\n\nexport function randomFill<T extends ArrayBufferView>(\n buffer: T,\n callback: (err: Error | null, buf: T) => void\n): void;\n\nexport function randomFill<T extends ArrayBufferView>(\n buffer: T,\n offset: number,\n callback: (err: Error | null, buf: T) => void\n): void;\n\nexport function randomFill<T extends ArrayBufferView>(\n buffer: T,\n offset: number,\n size: number,\n callback: (err: Error | null, buf: T) => void\n): void;\n\nexport function randomFill(buffer: any, ...rest: any[]): void {\n if (typeof rest[rest.length - 1] !== 'function') {\n throw new Error('No callback provided to randomDill');\n }\n\n const callback = rest[rest.length - 1] as any as (\n err: Error | null,\n buf?: ArrayBuffer\n ) => void;\n\n let offset: number = 0;\n let size: number = buffer.byteLength;\n\n if (typeof rest[2] === 'function') {\n offset = rest[0];\n size = rest[1];\n }\n\n if (typeof rest[1] === 'function') {\n offset = rest[0];\n }\n\n random\n .randomFill(Buffer.isBuffer(buffer) ? buffer.buffer : buffer, offset, size)\n .then(\n () => {\n callback(null, buffer);\n },\n (e: Error) => {\n callback(e);\n }\n );\n}\n\nexport function randomFillSync<T extends ArrayBufferView>(\n buffer: T,\n offset?: number,\n size?: number\n): T;\n\nexport function randomFillSync(buffer: any, offset: number = 0, size?: number) {\n random.randomFillSync(\n buffer.buffer ? buffer.buffer : buffer,\n offset,\n size ?? buffer.byteLength\n );\n return buffer;\n}\n\nexport function randomBytes(size: number): ArrayBuffer;\n\nexport function randomBytes(\n size: number,\n callback: (err: Error | null, buf?: ArrayBuffer) => void\n): void;\n\nexport function randomBytes(\n size: number,\n callback?: (err: Error | null, buf?: ArrayBuffer) => void\n): void | ArrayBuffer {\n const buf = new Buffer(size);\n\n if (callback === undefined) {\n randomFillSync(buf.buffer, 0, size);\n return buf;\n }\n\n randomFill(buf.buffer, 0, size, (error: Error | null) => {\n if (error) {\n callback(error);\n }\n callback(null, buf);\n });\n}\n\nexport const rng = randomBytes;\nexport const pseudoRandomBytes = randomBytes;\nexport const prng = randomBytes;\n\ntype RandomIntCallback = (err: Error | null, value: number) => void;\ntype Task = {\n min: number;\n max: number;\n callback: RandomIntCallback;\n};\n\n// The rest of the file is taken from https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js\n\n// Largest integer we can read from a buffer.\n// e.g.: Buffer.from(\"ff\".repeat(6), \"hex\").readUIntBE(0, 6);\nconst RAND_MAX = 0xffffffffffff;\n\n// Cache random data to use in randomInt. The cache size must be evenly\n// divisible by 6 because each attempt to obtain a random int uses 6 bytes.\nconst randomCache = new Buffer(6 * 1024);\nlet randomCacheOffset = randomCache.length;\nlet asyncCacheFillInProgress = false;\nconst asyncCachePendingTasks: Task[] = [];\n\n// Generates an integer in [min, max) range where min is inclusive and max is\n// exclusive.\n\nexport function randomInt(max: number, callback: RandomIntCallback): void;\nexport function randomInt(max: number): number;\nexport function randomInt(\n min: number,\n max: number,\n callback: RandomIntCallback\n): void;\nexport function randomInt(min: number, max: number): number;\nexport function randomInt(\n arg1: number,\n arg2?: number | RandomIntCallback,\n callback?: RandomIntCallback\n): void | number {\n // Detect optional min syntax\n // randomInt(max)\n // randomInt(max, callback)\n let max: number;\n let min: number;\n const minNotSpecified =\n typeof arg2 === 'undefined' || typeof arg2 === 'function';\n\n if (minNotSpecified) {\n callback = arg2 as any as undefined | RandomIntCallback;\n max = arg1;\n min = 0;\n } else {\n min = arg1;\n max = arg2 as any as number;\n }\n\n const isSync = typeof callback === 'undefined';\n if (!Number.isSafeInteger(min)) {\n // todo throw new ERR_INVALID_ARG_TYPE('min', 'a safe integer', min);\n throw 'ERR_INVALID_ARG_TYPE';\n }\n if (!Number.isSafeInteger(max)) {\n // todo throw new ERR_INVALID_ARG_TYPE('max', 'a safe integer', max);\n throw 'ERR_INVALID_ARG_TYPE';\n }\n if (max <= min) {\n /* todo throw new ERR_OUT_OF_RANGE(\n 'max',\n `greater than the value of \"min\" (${min})`,\n max\n );*/\n throw 'ERR_OUT_OF_RANGE';\n }\n\n // First we generate a random int between [0..range)\n const range = max - min;\n\n if (!(range <= RAND_MAX)) {\n /* todo throw new ERR_OUT_OF_RANGE(\n `max${minNotSpecified ? '' : ' - min'}`,\n `<= ${RAND_MAX}`,\n range\n );*/\n throw 'ERR_OUT_OF_RANGE';\n }\n\n // For (x % range) to produce an unbiased value greater than or equal to 0 and\n // less than range, x must be drawn randomly from the set of integers greater\n // than or equal to 0 and less than randLimit.\n const randLimit = RAND_MAX - (RAND_MAX % range);\n\n // If we don't have a callback, or if there is still data in the cache, we can\n // do this synchronously, which is super fast.\n while (isSync || randomCacheOffset < randomCache.length) {\n if (randomCacheOffset === randomCache.length) {\n // This might block the thread for a bit, but we are in sync mode.\n randomFillSync(randomCache);\n randomCacheOffset = 0;\n }\n\n const x = randomCache.readUIntBE(randomCacheOffset, 6);\n randomCacheOffset += 6;\n\n if (x < randLimit) {\n const n = (x % range) + min;\n if (isSync) return n;\n process.nextTick(callback as Function, undefined, n);\n return;\n }\n }\n\n // At this point, we are in async mode with no data in the cache. We cannot\n // simply refill the cache, because another async call to randomInt might\n // already be doing that. Instead, queue this call for when the cache has\n // been refilled.\n if (callback !== undefined) {\n // it is (typescript doesn't know it)\n asyncCachePendingTasks.push({ min, max, callback });\n asyncRefillRandomIntCache();\n }\n}\n\nfunction asyncRefillRandomIntCache() {\n if (asyncCacheFillInProgress) return;\n\n asyncCacheFillInProgress = true;\n randomFill(randomCache, (err) => {\n asyncCacheFillInProgress = false;\n\n const tasks = asyncCachePendingTasks;\n const errorReceiver = err && tasks.shift();\n if (!err) randomCacheOffset = 0;\n\n // Restart all pending tasks. If an error occurred, we only notify a single\n // callback (errorReceiver) about it. This way, every async call to\n // randomInt has a chance of being successful, and it avoids complex\n // exception handling here.\n tasks.splice(0).forEach((task) => {\n randomInt(task.min, task.max, task.callback);\n });\n\n // This is the only call that might throw, and is therefore done at the end.\n if (errorReceiver) errorReceiver.callback(err, 0);\n });\n}\n\n// Really just the Web Crypto API alternative\n// to require('crypto').randomFillSync() with an\n// additional limitation that the input buffer is\n// not allowed to exceed 65536 bytes, and can only\n// be an integer-type TypedArray.\ntype DataType =\n | Int8Array\n | Int16Array\n | Int32Array\n | Uint8Array\n | Uint16Array\n | Uint32Array;\nexport function getRandomValues(data: DataType) {\n if (data.byteLength > 65536) {\n throw new Error('The requested length exceeds 65,536 bytes');\n }\n randomFillSync(data, 0);\n return data;\n}\n\nconst byteToHex: string[] = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\n\n// Based on https://github.com/uuidjs/uuid/blob/main/src/v4.js\nexport function randomUUID() {\n const size = 16;\n const buffer = new Buffer(size)\n randomFillSync(buffer, 0, size);\n\n // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n buffer[6] = (buffer[6] & 0x0f) | 0x40;\n buffer[8] = (buffer[8] & 0x3f) | 0x80;\n\n return (\n byteToHex[buffer[0]] +\n byteToHex[buffer[1]] +\n byteToHex[buffer[2]] +\n byteToHex[buffer[3]] +\n '-' +\n byteToHex[buffer[4]] +\n byteToHex[buffer[5]] +\n '-' +\n byteToHex[buffer[6]] +\n byteToHex[buffer[7]] +\n '-' +\n byteToHex[buffer[8]] +\n byteToHex[buffer[9]] +\n '-' +\n byteToHex[buffer[10]] +\n byteToHex[buffer[11]] +\n byteToHex[buffer[12]] +\n byteToHex[buffer[13]] +\n byteToHex[buffer[14]] +\n byteToHex[buffer[15]]\n ).toLowerCase();\n}\n\n"]}
@@ -15,6 +15,7 @@ export declare const QuickCrypto: {
15
15
  randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void;
16
16
  randomInt(min: number, max: number): number;
17
17
  getRandomValues(data: Uint8Array | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array): Uint8Array | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array;
18
+ randomUUID(): string;
18
19
  rng: typeof random.randomBytes;
19
20
  pseudoRandomBytes: typeof random.randomBytes;
20
21
  prng: typeof random.randomBytes;
@@ -8,7 +8,6 @@ export declare type CipherEncoding = Encoding | 'buffer';
8
8
  export declare function setDefaultEncoding(encoding: CipherEncoding): void;
9
9
  export declare function getDefaultEncoding(): CipherEncoding;
10
10
  export declare const kEmptyObject: any;
11
- export declare function isBuffer(buf: any): buf is Buffer;
12
11
  export declare function toArrayBuffer(buf: Buffer): ArrayBuffer;
13
12
  export declare function binaryLikeToArrayBuffer(input: BinaryLike, encoding?: string): ArrayBuffer;
14
13
  export declare function ab2str(buf: ArrayBuffer, encoding?: string): string;
@@ -15,6 +15,7 @@ declare const crypto: {
15
15
  randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void;
16
16
  randomInt(min: number, max: number): number;
17
17
  getRandomValues(data: Uint8Array | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array): Uint8Array | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array;
18
+ randomUUID(): string;
18
19
  rng: typeof import("./random").randomBytes;
19
20
  pseudoRandomBytes: typeof import("./random").randomBytes;
20
21
  prng: typeof import("./random").randomBytes;
@@ -173,7 +174,6 @@ declare const crypto: {
173
174
  hkdf(digest: string, irm: FallbackCrypto.KeyObject | FallbackCrypto.BinaryLike, salt: FallbackCrypto.BinaryLike, info: FallbackCrypto.BinaryLike, keylen: number, callback: (err: Error | null, derivedKey: ArrayBuffer) => void): void;
174
175
  hkdfSync(digest: string, ikm: FallbackCrypto.KeyObject | FallbackCrypto.BinaryLike, salt: FallbackCrypto.BinaryLike, info: FallbackCrypto.BinaryLike, keylen: number): ArrayBuffer;
175
176
  secureHeapUsed(): FallbackCrypto.SecureHeapUsage;
176
- randomUUID(options?: FallbackCrypto.RandomUUIDOptions | undefined): string;
177
177
  generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void;
178
178
  generatePrime(size: number, options: FallbackCrypto.GeneratePrimeOptionsBigInt, callback: (err: Error | null, prime: bigint) => void): void;
179
179
  generatePrime(size: number, options: FallbackCrypto.GeneratePrimeOptionsArrayBuffer, callback: (err: Error | null, prime: ArrayBuffer) => void): void;
@@ -17,4 +17,5 @@ export declare function randomInt(min: number, max: number, callback: RandomIntC
17
17
  export declare function randomInt(min: number, max: number): number;
18
18
  declare type DataType = Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array;
19
19
  export declare function getRandomValues(data: DataType): DataType;
20
+ export declare function randomUUID(): string;
20
21
  export {};
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "react-native-quick-crypto",
3
- "version": "0.4.5",
3
+ "version": "0.5.0",
4
4
  "description": "A fast implementation of Node's `crypto` module written in C/C++ JSI",
5
5
  "main": "lib/commonjs/index",
6
6
  "module": "lib/module/index",
7
7
  "types": "lib/typescript/index.d.ts",
8
- "react-native": "src/index",
8
+ "react-native": "lib/module/index",
9
9
  "source": "src/index",
10
10
  "files": [
11
11
  "src",
package/src/Utils.ts CHANGED
@@ -97,10 +97,6 @@ export const kEmptyObject = Object.freeze(Object.create(null));
97
97
  // return slowCases(enc);
98
98
  // }
99
99
 
100
- export function isBuffer(buf: any): buf is Buffer {
101
- return buf instanceof Buffer || buf?.constructor?.name === 'Buffer';
102
- }
103
-
104
100
  export function toArrayBuffer(buf: Buffer): ArrayBuffer {
105
101
  if (buf?.buffer?.slice) {
106
102
  return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
@@ -126,7 +122,7 @@ export function binaryLikeToArrayBuffer(
126
122
  );
127
123
  }
128
124
 
129
- if (isBuffer(input)) {
125
+ if (Buffer.isBuffer(input)) {
130
126
  return toArrayBuffer(input);
131
127
  }
132
128
 
package/src/random.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { NativeQuickCrypto } from './NativeQuickCrypto/NativeQuickCrypto';
2
2
  import { Buffer } from '@craftzdog/react-native-buffer';
3
- import { isBuffer } from '../src/Utils';
4
3
 
5
4
  const random = NativeQuickCrypto.random;
6
5
 
@@ -57,7 +56,7 @@ export function randomFill(buffer: any, ...rest: any[]): void {
57
56
  }
58
57
 
59
58
  random
60
- .randomFill(isBuffer(buffer) ? buffer.buffer : buffer, offset, size)
59
+ .randomFill(Buffer.isBuffer(buffer) ? buffer.buffer : buffer, offset, size)
61
60
  .then(
62
61
  () => {
63
62
  callback(null, buffer);
@@ -275,3 +274,44 @@ export function getRandomValues(data: DataType) {
275
274
  randomFillSync(data, 0);
276
275
  return data;
277
276
  }
277
+
278
+ const byteToHex: string[] = [];
279
+
280
+ for (let i = 0; i < 256; ++i) {
281
+ byteToHex.push((i + 0x100).toString(16).slice(1));
282
+ }
283
+
284
+ // Based on https://github.com/uuidjs/uuid/blob/main/src/v4.js
285
+ export function randomUUID() {
286
+ const size = 16;
287
+ const buffer = new Buffer(size)
288
+ randomFillSync(buffer, 0, size);
289
+
290
+ // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
291
+ buffer[6] = (buffer[6] & 0x0f) | 0x40;
292
+ buffer[8] = (buffer[8] & 0x3f) | 0x80;
293
+
294
+ return (
295
+ byteToHex[buffer[0]] +
296
+ byteToHex[buffer[1]] +
297
+ byteToHex[buffer[2]] +
298
+ byteToHex[buffer[3]] +
299
+ '-' +
300
+ byteToHex[buffer[4]] +
301
+ byteToHex[buffer[5]] +
302
+ '-' +
303
+ byteToHex[buffer[6]] +
304
+ byteToHex[buffer[7]] +
305
+ '-' +
306
+ byteToHex[buffer[8]] +
307
+ byteToHex[buffer[9]] +
308
+ '-' +
309
+ byteToHex[buffer[10]] +
310
+ byteToHex[buffer[11]] +
311
+ byteToHex[buffer[12]] +
312
+ byteToHex[buffer[13]] +
313
+ byteToHex[buffer[14]] +
314
+ byteToHex[buffer[15]]
315
+ ).toLowerCase();
316
+ }
317
+
package/android/.DS_Store DELETED
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
package/cpp/.DS_Store DELETED
Binary file
package/ios/.DS_Store DELETED
Binary file
package/lib/.DS_Store DELETED
Binary file
package/src/.DS_Store DELETED
Binary file