1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | exports.isInstance = exports.concatArray = exports.concatBytes = exports.toBytes = exports.octetsToBytes = exports.bytesToAscii = exports.asciiToBytes = exports.bytesToUtf8 = exports.utf8ToBytes = exports.hexToBytes = exports.bytesToHex = exports.fromTwos = exports.toTwos = exports.bigIntToBytes = exports.hexToInt = exports.intToHex = exports.hexToBigInt = exports.with0x = exports.intToBigInt = exports.intToBytes = exports.getGlobalObjects = exports.getGlobalObject = exports.getGlobalScope = exports.isSameOriginAbsoluteUrl = exports.makeUUID4 = exports.isLaterVersion = exports.updateQueryStringParameter = exports.getBase64OutputLength = exports.getAesCbcOutputLength = exports.megabytesToBytes = exports.nextHour = exports.nextMonth = exports.nextYear = exports.BLOCKSTACK_HANDLER = void 0;
|
4 | const logger_1 = require("./logger");
|
5 | exports.BLOCKSTACK_HANDLER = 'blockstack';
|
6 | function nextYear() {
|
7 | return new Date(new Date().setFullYear(new Date().getFullYear() + 1));
|
8 | }
|
9 | exports.nextYear = nextYear;
|
10 | function nextMonth() {
|
11 | return new Date(new Date().setMonth(new Date().getMonth() + 1));
|
12 | }
|
13 | exports.nextMonth = nextMonth;
|
14 | function nextHour() {
|
15 | return new Date(new Date().setHours(new Date().getHours() + 1));
|
16 | }
|
17 | exports.nextHour = nextHour;
|
18 | function megabytesToBytes(megabytes) {
|
19 | if (!Number.isFinite(megabytes)) {
|
20 | return 0;
|
21 | }
|
22 | return Math.floor(megabytes * 1024 * 1024);
|
23 | }
|
24 | exports.megabytesToBytes = megabytesToBytes;
|
25 | function getAesCbcOutputLength(inputByteLength) {
|
26 | const cipherTextLength = (Math.floor(inputByteLength / 16) + 1) * 16;
|
27 | return cipherTextLength;
|
28 | }
|
29 | exports.getAesCbcOutputLength = getAesCbcOutputLength;
|
30 | function getBase64OutputLength(inputByteLength) {
|
31 | const encodedLength = Math.ceil(inputByteLength / 3) * 4;
|
32 | return encodedLength;
|
33 | }
|
34 | exports.getBase64OutputLength = getBase64OutputLength;
|
35 | function updateQueryStringParameter(uri, key, value) {
|
36 | const re = new RegExp(`([?&])${key}=.*?(&|$)`, 'i');
|
37 | const separator = uri.indexOf('?') !== -1 ? '&' : '?';
|
38 | if (uri.match(re)) {
|
39 | return uri.replace(re, `$1${key}=${value}$2`);
|
40 | }
|
41 | else {
|
42 | return `${uri}${separator}${key}=${value}`;
|
43 | }
|
44 | }
|
45 | exports.updateQueryStringParameter = updateQueryStringParameter;
|
46 | function isLaterVersion(v1, v2) {
|
47 | if (v1 === undefined || v1 === '') {
|
48 | v1 = '0.0.0';
|
49 | }
|
50 | if (v2 === undefined || v1 === '') {
|
51 | v2 = '0.0.0';
|
52 | }
|
53 | const v1tuple = v1.split('.').map(x => parseInt(x, 10));
|
54 | const v2tuple = v2.split('.').map(x => parseInt(x, 10));
|
55 | for (let index = 0; index < v2.length; index++) {
|
56 | if (index >= v1.length) {
|
57 | v2tuple.push(0);
|
58 | }
|
59 | if (v1tuple[index] < v2tuple[index]) {
|
60 | return false;
|
61 | }
|
62 | }
|
63 | return true;
|
64 | }
|
65 | exports.isLaterVersion = isLaterVersion;
|
66 | function makeUUID4() {
|
67 | let d = new Date().getTime();
|
68 | if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
|
69 | d += performance.now();
|
70 | }
|
71 | return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
|
72 | const r = (d + Math.random() * 16) % 16 | 0;
|
73 | d = Math.floor(d / 16);
|
74 | return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
|
75 | });
|
76 | }
|
77 | exports.makeUUID4 = makeUUID4;
|
78 | function isSameOriginAbsoluteUrl(uri1, uri2) {
|
79 | try {
|
80 | const parsedUri1 = new URL(uri1);
|
81 | const parsedUri2 = new URL(uri2);
|
82 | const port1 = parseInt(parsedUri1.port || '0', 10) | 0 || (parsedUri1.protocol === 'https:' ? 443 : 80);
|
83 | const port2 = parseInt(parsedUri2.port || '0', 10) | 0 || (parsedUri2.protocol === 'https:' ? 443 : 80);
|
84 | const match = {
|
85 | scheme: parsedUri1.protocol === parsedUri2.protocol,
|
86 | hostname: parsedUri1.hostname === parsedUri2.hostname,
|
87 | port: port1 === port2,
|
88 | absolute: (uri1.includes('http://') || uri1.includes('https://')) &&
|
89 | (uri2.includes('http://') || uri2.includes('https://')),
|
90 | };
|
91 | return match.scheme && match.hostname && match.port && match.absolute;
|
92 | }
|
93 | catch (error) {
|
94 | console.log(error);
|
95 | console.log('Parsing error in same URL origin check');
|
96 | return false;
|
97 | }
|
98 | }
|
99 | exports.isSameOriginAbsoluteUrl = isSameOriginAbsoluteUrl;
|
100 | function getGlobalScope() {
|
101 | if (typeof self !== 'undefined') {
|
102 | return self;
|
103 | }
|
104 | if (typeof window !== 'undefined') {
|
105 | return window;
|
106 | }
|
107 | if (typeof global !== 'undefined') {
|
108 | return global;
|
109 | }
|
110 | throw new Error('Unexpected runtime environment - no supported global scope (`window`, `self`, `global`) available');
|
111 | }
|
112 | exports.getGlobalScope = getGlobalScope;
|
113 | function getAPIUsageErrorMessage(scopeObject, apiName, usageDesc) {
|
114 | if (usageDesc) {
|
115 | return `Use of '${usageDesc}' requires \`${apiName}\` which is unavailable on the '${scopeObject}' object within the currently executing environment.`;
|
116 | }
|
117 | else {
|
118 | return `\`${apiName}\` is unavailable on the '${scopeObject}' object within the currently executing environment.`;
|
119 | }
|
120 | }
|
121 | function getGlobalObject(name, { throwIfUnavailable, usageDesc, returnEmptyObject } = {}) {
|
122 | let globalScope = undefined;
|
123 | try {
|
124 | globalScope = getGlobalScope();
|
125 | if (globalScope) {
|
126 | const obj = globalScope[name];
|
127 | if (obj) {
|
128 | return obj;
|
129 | }
|
130 | }
|
131 | }
|
132 | catch (error) {
|
133 | logger_1.Logger.error(`Error getting object '${name}' from global scope '${globalScope}': ${error}`);
|
134 | }
|
135 | if (throwIfUnavailable) {
|
136 | const errMsg = getAPIUsageErrorMessage(globalScope, name.toString(), usageDesc);
|
137 | logger_1.Logger.error(errMsg);
|
138 | throw new Error(errMsg);
|
139 | }
|
140 | if (returnEmptyObject) {
|
141 | return {};
|
142 | }
|
143 | return undefined;
|
144 | }
|
145 | exports.getGlobalObject = getGlobalObject;
|
146 | function getGlobalObjects(names, { throwIfUnavailable, usageDesc, returnEmptyObject } = {}) {
|
147 | let globalScope;
|
148 | try {
|
149 | globalScope = getGlobalScope();
|
150 | }
|
151 | catch (error) {
|
152 | logger_1.Logger.error(`Error getting global scope: ${error}`);
|
153 | if (throwIfUnavailable) {
|
154 | const errMsg = getAPIUsageErrorMessage(globalScope, names[0].toString(), usageDesc);
|
155 | logger_1.Logger.error(errMsg);
|
156 | throw errMsg;
|
157 | }
|
158 | else if (returnEmptyObject) {
|
159 | globalScope = {};
|
160 | }
|
161 | }
|
162 | const result = {};
|
163 | for (let i = 0; i < names.length; i++) {
|
164 | const name = names[i];
|
165 | try {
|
166 | if (globalScope) {
|
167 | const obj = globalScope[name];
|
168 | if (obj) {
|
169 | result[name] = obj;
|
170 | }
|
171 | else if (throwIfUnavailable) {
|
172 | const errMsg = getAPIUsageErrorMessage(globalScope, name.toString(), usageDesc);
|
173 | logger_1.Logger.error(errMsg);
|
174 | throw new Error(errMsg);
|
175 | }
|
176 | else if (returnEmptyObject) {
|
177 | result[name] = {};
|
178 | }
|
179 | }
|
180 | }
|
181 | catch (error) {
|
182 | if (throwIfUnavailable) {
|
183 | const errMsg = getAPIUsageErrorMessage(globalScope, name.toString(), usageDesc);
|
184 | logger_1.Logger.error(errMsg);
|
185 | throw new Error(errMsg);
|
186 | }
|
187 | }
|
188 | }
|
189 | return result;
|
190 | }
|
191 | exports.getGlobalObjects = getGlobalObjects;
|
192 | function intToBytes(value, signed, byteLength) {
|
193 | return bigIntToBytes(intToBigInt(value, signed), byteLength);
|
194 | }
|
195 | exports.intToBytes = intToBytes;
|
196 | function intToBigInt(value, signed) {
|
197 | let parsedValue = value;
|
198 | if (typeof parsedValue === 'number') {
|
199 | if (!Number.isInteger(parsedValue)) {
|
200 | throw new RangeError(`Invalid value. Values of type 'number' must be an integer.`);
|
201 | }
|
202 | return BigInt(parsedValue);
|
203 | }
|
204 | if (typeof parsedValue === 'string') {
|
205 | if (parsedValue.toLowerCase().startsWith('0x')) {
|
206 | let hex = parsedValue.slice(2);
|
207 | hex = hex.padStart(hex.length + (hex.length % 2), '0');
|
208 | parsedValue = hexToBytes(hex);
|
209 | }
|
210 | else {
|
211 | try {
|
212 | return BigInt(parsedValue);
|
213 | }
|
214 | catch (error) {
|
215 | if (error instanceof SyntaxError) {
|
216 | throw new RangeError(`Invalid value. String integer '${parsedValue}' is not finite.`);
|
217 | }
|
218 | }
|
219 | }
|
220 | }
|
221 | if (typeof parsedValue === 'bigint') {
|
222 | return parsedValue;
|
223 | }
|
224 | if (parsedValue instanceof Uint8Array) {
|
225 | if (signed) {
|
226 | const bn = fromTwos(BigInt(`0x${bytesToHex(parsedValue)}`), BigInt(parsedValue.byteLength * 8));
|
227 | return BigInt(bn.toString());
|
228 | }
|
229 | else {
|
230 | return BigInt(`0x${bytesToHex(parsedValue)}`);
|
231 | }
|
232 | }
|
233 | if (parsedValue != null &&
|
234 | typeof parsedValue === 'object' &&
|
235 | parsedValue.constructor.name === 'BN') {
|
236 | return BigInt(parsedValue.toString());
|
237 | }
|
238 | throw new TypeError(`Invalid value type. Must be a number, bigint, integer-string, hex-string, or Uint8Array.`);
|
239 | }
|
240 | exports.intToBigInt = intToBigInt;
|
241 | function with0x(value) {
|
242 | return !value.startsWith('0x') ? `0x${value}` : value;
|
243 | }
|
244 | exports.with0x = with0x;
|
245 | function hexToBigInt(hex) {
|
246 | if (typeof hex !== 'string')
|
247 | throw new TypeError(`hexToBigInt: expected string, got ${typeof hex}`);
|
248 | return BigInt(`0x${hex}`);
|
249 | }
|
250 | exports.hexToBigInt = hexToBigInt;
|
251 | function intToHex(integer, lengthBytes = 8) {
|
252 | const value = typeof integer === 'bigint' ? integer : intToBigInt(integer, false);
|
253 | return value.toString(16).padStart(lengthBytes * 2, '0');
|
254 | }
|
255 | exports.intToHex = intToHex;
|
256 | function hexToInt(hex) {
|
257 | return parseInt(hex, 16);
|
258 | }
|
259 | exports.hexToInt = hexToInt;
|
260 | function bigIntToBytes(value, length = 16) {
|
261 | const hex = intToHex(value, length);
|
262 | return hexToBytes(hex);
|
263 | }
|
264 | exports.bigIntToBytes = bigIntToBytes;
|
265 | function toTwos(value, width) {
|
266 | if (value < -(BigInt(1) << (width - BigInt(1))) ||
|
267 | (BigInt(1) << (width - BigInt(1))) - BigInt(1) < value) {
|
268 | throw `Unable to represent integer in width: ${width}`;
|
269 | }
|
270 | if (value >= BigInt(0)) {
|
271 | return BigInt(value);
|
272 | }
|
273 | return value + (BigInt(1) << width);
|
274 | }
|
275 | exports.toTwos = toTwos;
|
276 | function nthBit(value, n) {
|
277 | return value & (BigInt(1) << n);
|
278 | }
|
279 | function fromTwos(value, width) {
|
280 | if (nthBit(value, width - BigInt(1))) {
|
281 | return value - (BigInt(1) << width);
|
282 | }
|
283 | return value;
|
284 | }
|
285 | exports.fromTwos = fromTwos;
|
286 | const hexes = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
|
287 | function bytesToHex(uint8a) {
|
288 | if (!(uint8a instanceof Uint8Array))
|
289 | throw new Error('Uint8Array expected');
|
290 | let hex = '';
|
291 | for (const u of uint8a) {
|
292 | hex += hexes[u];
|
293 | }
|
294 | return hex;
|
295 | }
|
296 | exports.bytesToHex = bytesToHex;
|
297 | function hexToBytes(hex) {
|
298 | if (typeof hex !== 'string') {
|
299 | throw new TypeError(`hexToBytes: expected string, got ${typeof hex}`);
|
300 | }
|
301 | const paddedHex = hex.length % 2 ? `0${hex}` : hex;
|
302 | const array = new Uint8Array(paddedHex.length / 2);
|
303 | for (let i = 0; i < array.length; i++) {
|
304 | const j = i * 2;
|
305 | const hexByte = paddedHex.slice(j, j + 2);
|
306 | const byte = Number.parseInt(hexByte, 16);
|
307 | if (Number.isNaN(byte) || byte < 0)
|
308 | throw new Error('Invalid byte sequence');
|
309 | array[i] = byte;
|
310 | }
|
311 | return array;
|
312 | }
|
313 | exports.hexToBytes = hexToBytes;
|
314 | function utf8ToBytes(str) {
|
315 | return new TextEncoder().encode(str);
|
316 | }
|
317 | exports.utf8ToBytes = utf8ToBytes;
|
318 | function bytesToUtf8(arr) {
|
319 | return new TextDecoder().decode(arr);
|
320 | }
|
321 | exports.bytesToUtf8 = bytesToUtf8;
|
322 | function asciiToBytes(str) {
|
323 | const byteArray = [];
|
324 | for (let i = 0; i < str.length; i++) {
|
325 | byteArray.push(str.charCodeAt(i) & 0xff);
|
326 | }
|
327 | return new Uint8Array(byteArray);
|
328 | }
|
329 | exports.asciiToBytes = asciiToBytes;
|
330 | function bytesToAscii(arr) {
|
331 | return String.fromCharCode.apply(null, arr);
|
332 | }
|
333 | exports.bytesToAscii = bytesToAscii;
|
334 | function isNotOctet(octet) {
|
335 | return !Number.isInteger(octet) || octet < 0 || octet > 255;
|
336 | }
|
337 | function octetsToBytes(numbers) {
|
338 | if (numbers.some(isNotOctet))
|
339 | throw new Error('Some values are invalid bytes.');
|
340 | return new Uint8Array(numbers);
|
341 | }
|
342 | exports.octetsToBytes = octetsToBytes;
|
343 | function toBytes(data) {
|
344 | if (typeof data === 'string')
|
345 | return utf8ToBytes(data);
|
346 | if (data instanceof Uint8Array)
|
347 | return data;
|
348 | throw new TypeError(`Expected input type is (Uint8Array | string) but got (${typeof data})`);
|
349 | }
|
350 | exports.toBytes = toBytes;
|
351 | function concatBytes(...arrays) {
|
352 | if (!arrays.every(a => a instanceof Uint8Array))
|
353 | throw new Error('Uint8Array list expected');
|
354 | if (arrays.length === 1)
|
355 | return arrays[0];
|
356 | const length = arrays.reduce((a, arr) => a + arr.length, 0);
|
357 | const result = new Uint8Array(length);
|
358 | for (let i = 0, pad = 0; i < arrays.length; i++) {
|
359 | const arr = arrays[i];
|
360 | result.set(arr, pad);
|
361 | pad += arr.length;
|
362 | }
|
363 | return result;
|
364 | }
|
365 | exports.concatBytes = concatBytes;
|
366 | function concatArray(elements) {
|
367 | return concatBytes(...elements.map(e => {
|
368 | if (typeof e === 'number')
|
369 | return octetsToBytes([e]);
|
370 | if (e instanceof Array)
|
371 | return octetsToBytes(e);
|
372 | return e;
|
373 | }));
|
374 | }
|
375 | exports.concatArray = concatArray;
|
376 | function isInstance(object, type) {
|
377 | var _a;
|
378 | return (object instanceof type ||
|
379 | (((_a = object === null || object === void 0 ? void 0 : object.constructor) === null || _a === void 0 ? void 0 : _a.name) != null && object.constructor.name === type.name));
|
380 | }
|
381 | exports.isInstance = isInstance;
|
382 |
|
\ | No newline at end of file |