import * as stream from '@openpgp/web-stream-tools';import { getBigInteger } from './biginteger';
const debugMode = (() => { try { return process.env.NODE_ENV === 'development'; } catch (e) {} return false;})();
const util = { isString: function(data) { return typeof data === 'string' || String.prototype.isPrototypeOf(data); },
isArray: function(data) { return Array.prototype.isPrototypeOf(data); },
isUint8Array: stream.isUint8Array,
isStream: stream.isStream,
readNumber: function (bytes) { let n = 0; for (let i = 0; i < bytes.length; i++) { n += (256 ** i) * bytes[bytes.length - 1 - i]; } return n; },
writeNumber: function (n, bytes) { const b = new Uint8Array(bytes); for (let i = 0; i < bytes; i++) { b[i] = (n >> (8 * (bytes - i - 1))) & 0xFF; }
return b; },
readDate: function (bytes) { const n = util.readNumber(bytes); const d = new Date(n * 1000); return d; },
writeDate: function (time) { const numeric = Math.floor(time.getTime() / 1000);
return util.writeNumber(numeric, 4); },
normalizeDate: function (time = Date.now()) { return time === null || time === Infinity ? time : new Date(Math.floor(+time / 1000) * 1000); },
readMPI: function (bytes) { const bits = (bytes[0] << 8) | bytes[1]; const bytelen = (bits + 7) >>> 3; return bytes.subarray(2, 2 + bytelen); },
leftPad(bytes, length) { const padded = new Uint8Array(length); const offset = length - bytes.length; padded.set(bytes, offset); return padded; },
uint8ArrayToMPI: function (bin) { const bitSize = util.uint8ArrayBitLength(bin); if (bitSize === 0) { throw new Error('Zero MPI'); } const stripped = bin.subarray(bin.length - Math.ceil(bitSize / 8)); const prefix = new Uint8Array([(bitSize & 0xFF00) >> 8, bitSize & 0xFF]); return util.concatUint8Array([prefix, stripped]); },
uint8ArrayBitLength: function (bin) { let i; for (i = 0; i < bin.length; i++) if (bin[i] !== 0) break; if (i === bin.length) { return 0; } const stripped = bin.subarray(i); return (stripped.length - 1) * 8 + util.nbits(stripped[0]); },
hexToUint8Array: function (hex) { const result = new Uint8Array(hex.length >> 1); for (let k = 0; k < hex.length >> 1; k++) { result[k] = parseInt(hex.substr(k << 1, 2), 16); } return result; },
uint8ArrayToHex: function (bytes) { const r = []; const e = bytes.length; let c = 0; let h; while (c < e) { h = bytes[c++].toString(16); while (h.length < 2) { h = '0' + h; } r.push('' + h); } return r.join(''); },
stringToUint8Array: function (str) { return stream.transform(str, str => { if (!util.isString(str)) { throw new Error('stringToUint8Array: Data must be in the form of a string'); }
const result = new Uint8Array(str.length); for (let i = 0; i < str.length; i++) { result[i] = str.charCodeAt(i); } return result; }); },
uint8ArrayToString: function (bytes) { bytes = new Uint8Array(bytes); const result = []; const bs = 1 << 14; const j = bytes.length;
for (let i = 0; i < j; i += bs) { result.push(String.fromCharCode.apply(String, bytes.subarray(i, i + bs < j ? i + bs : j))); } return result.join(''); },
encodeUTF8: function (str) { const encoder = new TextEncoder('utf-8'); function process(value, lastChunk = false) { return encoder.encode(value, { stream: !lastChunk }); } return stream.transform(str, process, () => process('', true)); },
decodeUTF8: function (utf8) { const decoder = new TextDecoder('utf-8'); function process(value, lastChunk = false) { return decoder.decode(value, { stream: !lastChunk }); } return stream.transform(utf8, process, () => process(new Uint8Array(), true)); },
concat: stream.concat,
concatUint8Array: stream.concatUint8Array,
equalsUint8Array: function (array1, array2) { if (!util.isUint8Array(array1) || !util.isUint8Array(array2)) { throw new Error('Data must be in the form of a Uint8Array'); }
if (array1.length !== array2.length) { return false; }
for (let i = 0; i < array1.length; i++) { if (array1[i] !== array2[i]) { return false; } } return true; },
writeChecksum: function (text) { let s = 0; for (let i = 0; i < text.length; i++) { s = (s + text[i]) & 0xFFFF; } return util.writeNumber(s, 2); },
printDebug: function (str) { if (debugMode) { console.log(str); } },
printDebugError: function (error) { if (debugMode) { console.error(error); } },
nbits: function (x) { let r = 1; let t = x >>> 16; if (t !== 0) { x = t; r += 16; } t = x >> 8; if (t !== 0) { x = t; r += 8; } t = x >> 4; if (t !== 0) { x = t; r += 4; } t = x >> 2; if (t !== 0) { x = t; r += 2; } t = x >> 1; if (t !== 0) { x = t; r += 1; } return r; },
double: function(data) { const doubleVar = new Uint8Array(data.length); const last = data.length - 1; for (let i = 0; i < last; i++) { doubleVar[i] = (data[i] << 1) ^ (data[i + 1] >> 7); } doubleVar[last] = (data[last] << 1) ^ ((data[0] >> 7) * 0x87); return doubleVar; },
shiftRight: function (array, bits) { if (bits) { for (let i = array.length - 1; i >= 0; i--) { array[i] >>= bits; if (i > 0) { array[i] |= (array[i - 1] << (8 - bits)); } } } return array; },
getWebCrypto: function() { return typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle; },
detectNode: function() { return typeof globalThis.process === 'object' && typeof globalThis.process.versions === 'object'; },
detectBigInt: () => typeof BigInt !== 'undefined',
getBigInteger,
getNodeCrypto: function() { return require('crypto'); },
getNodeZlib: function() { return require('zlib'); },
getNodeBuffer: function() { return (require('buffer') || {}).Buffer; },
getHardwareConcurrency: function() { if (util.detectNode()) { const os = require('os'); return os.cpus().length; }
return (typeof navigator !== 'undefined' && navigator.hardwareConcurrency) || 1; },
isEmailAddress: function(data) { if (!util.isString(data)) { return false; } const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+([a-zA-Z]{2,}|xn--[a-zA-Z\-0-9]+)))$/; return re.test(data); },
canonicalizeEOL: function(data) { const CR = 13; const LF = 10; let carryOverCR = false;
return stream.transform(data, bytes => { if (carryOverCR) { bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]); }
if (bytes[bytes.length - 1] === CR) { carryOverCR = true; bytes = bytes.subarray(0, -1); } else { carryOverCR = false; }
let index; const indices = []; for (let i = 0; ; i = index) { index = bytes.indexOf(LF, i) + 1; if (index) { if (bytes[index - 2] !== CR) indices.push(index); } else { break; } } if (!indices.length) { return bytes; }
const normalized = new Uint8Array(bytes.length + indices.length); let j = 0; for (let i = 0; i < indices.length; i++) { const sub = bytes.subarray(indices[i - 1] || 0, indices[i]); normalized.set(sub, j); j += sub.length; normalized[j - 1] = CR; normalized[j] = LF; j++; } normalized.set(bytes.subarray(indices[indices.length - 1] || 0), j); return normalized; }, () => (carryOverCR ? new Uint8Array([CR]) : undefined)); },
nativeEOL: function(data) { const CR = 13; const LF = 10; let carryOverCR = false;
return stream.transform(data, bytes => { if (carryOverCR && bytes[0] !== LF) { bytes = util.concatUint8Array([new Uint8Array([CR]), bytes]); } else { bytes = new Uint8Array(bytes); }
if (bytes[bytes.length - 1] === CR) { carryOverCR = true; bytes = bytes.subarray(0, -1); } else { carryOverCR = false; }
let index; let j = 0; for (let i = 0; i !== bytes.length; i = index) { index = bytes.indexOf(CR, i) + 1; if (!index) index = bytes.length; const last = index - (bytes[index] === LF ? 1 : 0); if (i) bytes.copyWithin(j, i, last); j += last - i; } return bytes.subarray(0, j); }, () => (carryOverCR ? new Uint8Array([CR]) : undefined)); },
removeTrailingSpaces: function(text) { return text.split('\n').map(line => { let i = line.length - 1; for (; i >= 0 && (line[i] === ' ' || line[i] === '\t'); i--); return line.substr(0, i + 1); }).join('\n'); },
wrapError: function(message, error) { if (!error) { return new Error(message); }
try { error.message = message + ': ' + error.message; } catch (e) {}
return error; },
constructAllowedPackets: function(allowedClasses) { const map = {}; allowedClasses.forEach(PacketClass => { if (!PacketClass.tag) { throw new Error('Invalid input: expected a packet class'); } map[PacketClass.tag] = PacketClass; }); return map; },
anyPromise: function(promises) { return new Promise(async (resolve, reject) => { let exception; await Promise.all(promises.map(async promise => { try { resolve(await promise); } catch (e) { exception = e; } })); reject(exception); }); },
selectUint8Array: function(cond, a, b) { const length = Math.max(a.length, b.length); const result = new Uint8Array(length); let end = 0; for (let i = 0; i < result.length; i++) { result[i] = (a[i] & (256 - cond)) | (b[i] & (255 + cond)); end += (cond & i < a.length) | ((1 - cond) & i < b.length); } return result.subarray(0, end); }, selectUint8: function(cond, a, b) { return (a & (256 - cond)) | (b & (255 + cond)); }};
export default util;