@junobuild/core 0.0.59 → 0.0.60
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/dist/browser/canisterStatus-APCJZWVG.js +2 -0
- package/dist/browser/chunk-3YVZN56F.js +46 -0
- package/dist/browser/chunk-3YVZN56F.js.map +7 -0
- package/dist/browser/index.js +14 -14
- package/dist/browser/index.js.map +3 -3
- package/dist/node/index.mjs +34 -31
- package/dist/node/index.mjs.map +4 -4
- package/dist/workers/auth.worker.js +14 -14
- package/dist/workers/auth.worker.js.map +3 -3
- package/package.json +5 -5
- package/dist/browser/canisterStatus-7ZJKVFTO.js +0 -2
- package/dist/browser/chunk-FOA6PEDK.js +0 -43
- package/dist/browser/chunk-FOA6PEDK.js.map +0 -7
- /package/dist/browser/{canisterStatus-7ZJKVFTO.js.map → canisterStatus-APCJZWVG.js.map} +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../node_modules/base64-js/index.js", "../../../../node_modules/buffer/index.js", "../../../utils/src/utils/debounce.utils.ts", "../../../utils/src/utils/json.utils.ts", "../../../utils/src/utils/null.utils.ts", "../../../utils/src/utils/did.utils.ts", "../../../utils/src/utils/env.utils.ts", "../../src/stores/store.ts", "../../src/stores/auth.store.ts", "../../src/utils/events.utils.ts", "../../src/constants/auth.constants.ts", "../../src/constants/container.constants.ts", "../../src/stores/env.store.ts", "../../src/utils/window.utils.ts", "../../src/providers/auth.providers.ts", "../../../../node_modules/@dfinity/agent/src/actor.ts", "../../../../node_modules/@dfinity/agent/src/agent/api.ts", "../../../../node_modules/@dfinity/agent/src/auth.ts", "../../../../node_modules/@dfinity/agent/src/agent/http/transforms.ts", "../../../../node_modules/@dfinity/agent/src/utils/random.ts", "../../../../node_modules/@dfinity/agent/src/agent/http/types.ts", "../../../../node_modules/@dfinity/agent/src/agent/http/errors.ts", "../../../../node_modules/@noble/hashes/src/_u64.ts", "../../../../node_modules/@noble/hashes/src/sha512.ts", "../../../../node_modules/@noble/curves/src/abstract/edwards.ts", "../../../../node_modules/@noble/curves/src/ed25519.ts", "../../../../node_modules/@dfinity/agent/src/utils/expirableMap.ts", "../../../../node_modules/@dfinity/agent/src/der.ts", "../../../../node_modules/@dfinity/agent/src/public_key.ts", "../../../../node_modules/@dfinity/agent/src/observable.ts", "../../../../node_modules/@dfinity/agent/src/polling/backoff.ts", "../../../../node_modules/@dfinity/agent/src/agent/http/index.ts", "../../../../node_modules/@dfinity/agent/src/agent/proxy.ts", "../../../../node_modules/@dfinity/agent/src/agent/index.ts", "../../../../node_modules/@dfinity/agent/src/polling/strategy.ts", "../../../../node_modules/@dfinity/agent/src/polling/index.ts", "../../../../node_modules/@dfinity/agent/src/canisters/management_idl.ts", "../../../../node_modules/@dfinity/identity/src/identity/ed25519.ts", "../../../../node_modules/@dfinity/identity/src/identity/ecdsa.ts", "../../../../node_modules/@dfinity/identity/src/identity/delegation.ts", "../../../../node_modules/@dfinity/identity/src/identity/partial.ts", "../../../../node_modules/@dfinity/identity/src/identity/webauthn.ts", "../../../../node_modules/@dfinity/auth-client/src/idleManager.ts", "../../../../node_modules/idb/build/wrap-idb-value.js", "../../../../node_modules/idb/build/index.js", "../../../../node_modules/@dfinity/auth-client/src/db.ts", "../../../../node_modules/@dfinity/auth-client/src/storage.ts", "../../../../node_modules/@dfinity/auth-client/src/index.ts", "../../src/utils/auth.utils.ts", "../../src/utils/data.utils.ts", "../../src/utils/doc.utils.ts", "../../src/utils/list.utils.ts", "../../declarations/satellite/satellite.factory.did.js", "../../src/utils/actor.utils.ts", "../../src/utils/env.utils.ts", "../../src/api/actor.api.ts", "../../src/api/doc.api.ts", "../../src/services/identity.services.ts", "../../src/services/doc.services.ts", "../../src/services/user.services.ts", "../../src/services/auth.services.ts", "../../src/services/auth-timout.services.ts", "../../src/utils/window.env.utils.ts", "../../../utils/src/utils/debounce.utils.ts", "../../../utils/src/utils/json.utils.ts", "../../../utils/src/utils/null.utils.ts", "../../../utils/src/utils/did.utils.ts", "../../../utils/src/utils/env.utils.ts", "../../../storage/src/api/storage.api.ts", "../../src/api/storage.api.ts", "../../src/utils/crypto.utils.ts", "../../src/services/storage.services.ts", "../../src/index.ts"],
|
|
4
|
-
"sourcesContent": ["'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n", "/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh <https://feross.org>\n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nconst base64 = require('base64-js')\nconst ieee754 = require('ieee754')\nconst customInspectSymbol =\n (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation\n ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation\n : null\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nconst K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n const arr = new Uint8Array(1)\n const proto = { foo: function () { return 42 } }\n Object.setPrototypeOf(proto, Uint8Array.prototype)\n Object.setPrototypeOf(arr, proto)\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n const buf = new Uint8Array(length)\n Object.setPrototypeOf(buf, Buffer.prototype)\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayView(value)\n }\n\n if (value == null) {\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof SharedArrayBuffer !== 'undefined' &&\n (isInstance(value, SharedArrayBuffer) ||\n (value && isInstance(value.buffer, SharedArrayBuffer)))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n const valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n const b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length)\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nObject.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)\nObject.setPrototypeOf(Buffer, Uint8Array)\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpreted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n const length = byteLength(string, encoding) | 0\n let buf = createBuffer(length)\n\n const actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n const length = array.length < 0 ? 0 : checked(array.length) | 0\n const buf = createBuffer(length)\n for (let i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayView (arrayView) {\n if (isInstance(arrayView, Uint8Array)) {\n const copy = new Uint8Array(arrayView)\n return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)\n }\n return fromArrayLike(arrayView)\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n let buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(buf, Buffer.prototype)\n\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n const len = checked(obj.length) | 0\n const buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n let x = a.length\n let y = b.length\n\n for (let i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n let i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n const buffer = Buffer.allocUnsafe(length)\n let pos = 0\n for (i = 0; i < list.length; ++i) {\n let buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n if (pos + buf.length > buffer.length) {\n if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)\n buf.copy(buffer, pos)\n } else {\n Uint8Array.prototype.set.call(\n buffer,\n buf,\n pos\n )\n }\n } else if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n } else {\n buf.copy(buffer, pos)\n }\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n const len = string.length\n const mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n let loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coercion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n const i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n const len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (let i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n const len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (let i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n const len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (let i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n const length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n let str = ''\n const max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return '<Buffer ' + str + '>'\n}\nif (customInspectSymbol) {\n Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n let x = thisEnd - thisStart\n let y = end - start\n const len = Math.min(x, y)\n\n const thisCopy = this.slice(thisStart, thisEnd)\n const targetCopy = target.slice(start, end)\n\n for (let i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n let indexSize = 1\n let arrLength = arr.length\n let valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n let i\n if (dir) {\n let foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n let found = true\n for (let j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n const remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n const strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n let i\n for (i = 0; i < length; ++i) {\n const parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n const remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n case 'latin1':\n case 'binary':\n return asciiWrite(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n const res = []\n\n let i = start\n while (i < end) {\n const firstByte = buf[i]\n let codePoint = null\n let bytesPerSequence = (firstByte > 0xEF)\n ? 4\n : (firstByte > 0xDF)\n ? 3\n : (firstByte > 0xBF)\n ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n let secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nconst MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n const len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n let res = ''\n let i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n const len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n let out = ''\n for (let i = start; i < end; ++i) {\n out += hexSliceLookupTable[buf[i]]\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n const bytes = buf.slice(start, end)\n let res = ''\n // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)\n for (let i = 0; i < bytes.length - 1; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n const len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n const newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(newBuf, Buffer.prototype)\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUintLE =\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUintBE =\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n let val = this[offset + --byteLength]\n let mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUint8 =\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUint16LE =\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUint16BE =\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUint32LE =\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUint32BE =\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const lo = first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24\n\n const hi = this[++offset] +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n last * 2 ** 24\n\n return BigInt(lo) + (BigInt(hi) << BigInt(32))\n})\n\nBuffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const hi = first * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n const lo = this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last\n\n return (BigInt(hi) << BigInt(32)) + BigInt(lo)\n})\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let i = byteLength\n let mul = 1\n let val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = this[offset + 4] +\n this[offset + 5] * 2 ** 8 +\n this[offset + 6] * 2 ** 16 +\n (last << 24) // Overflow\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24)\n})\n\nBuffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = (first << 24) + // Overflow\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last)\n})\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUintLE =\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let mul = 1\n let i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUintBE =\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let i = byteLength - 1\n let mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUint8 =\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUint16LE =\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUint16BE =\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUint32LE =\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUint32BE =\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction wrtBigUInt64LE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n return offset\n}\n\nfunction wrtBigUInt64BE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset + 7] = lo\n lo = lo >> 8\n buf[offset + 6] = lo\n lo = lo >> 8\n buf[offset + 5] = lo\n lo = lo >> 8\n buf[offset + 4] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset + 3] = hi\n hi = hi >> 8\n buf[offset + 2] = hi\n hi = hi >> 8\n buf[offset + 1] = hi\n hi = hi >> 8\n buf[offset] = hi\n return offset + 8\n}\n\nBuffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = 0\n let mul = 1\n let sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = byteLength - 1\n let mul = 1\n let sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nBuffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n const len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n const code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n } else if (typeof val === 'boolean') {\n val = Number(val)\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n let i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n const bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n const len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// CUSTOM ERRORS\n// =============\n\n// Simplified versions from Node, changed for Buffer-only usage\nconst errors = {}\nfunction E (sym, getMessage, Base) {\n errors[sym] = class NodeError extends Base {\n constructor () {\n super()\n\n Object.defineProperty(this, 'message', {\n value: getMessage.apply(this, arguments),\n writable: true,\n configurable: true\n })\n\n // Add the error code to the name to include it in the stack trace.\n this.name = `${this.name} [${sym}]`\n // Access the stack to generate the error message including the error code\n // from the name.\n this.stack // eslint-disable-line no-unused-expressions\n // Reset the name to the actual name.\n delete this.name\n }\n\n get code () {\n return sym\n }\n\n set code (value) {\n Object.defineProperty(this, 'code', {\n configurable: true,\n enumerable: true,\n value,\n writable: true\n })\n }\n\n toString () {\n return `${this.name} [${sym}]: ${this.message}`\n }\n }\n}\n\nE('ERR_BUFFER_OUT_OF_BOUNDS',\n function (name) {\n if (name) {\n return `${name} is outside of buffer bounds`\n }\n\n return 'Attempt to access memory outside buffer bounds'\n }, RangeError)\nE('ERR_INVALID_ARG_TYPE',\n function (name, actual) {\n return `The \"${name}\" argument must be of type number. Received type ${typeof actual}`\n }, TypeError)\nE('ERR_OUT_OF_RANGE',\n function (str, range, input) {\n let msg = `The value of \"${str}\" is out of range.`\n let received = input\n if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {\n received = addNumericalSeparator(String(input))\n } else if (typeof input === 'bigint') {\n received = String(input)\n if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {\n received = addNumericalSeparator(received)\n }\n received += 'n'\n }\n msg += ` It must be ${range}. Received ${received}`\n return msg\n }, RangeError)\n\nfunction addNumericalSeparator (val) {\n let res = ''\n let i = val.length\n const start = val[0] === '-' ? 1 : 0\n for (; i >= start + 4; i -= 3) {\n res = `_${val.slice(i - 3, i)}${res}`\n }\n return `${val.slice(0, i)}${res}`\n}\n\n// CHECK FUNCTIONS\n// ===============\n\nfunction checkBounds (buf, offset, byteLength) {\n validateNumber(offset, 'offset')\n if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {\n boundsError(offset, buf.length - (byteLength + 1))\n }\n}\n\nfunction checkIntBI (value, min, max, buf, offset, byteLength) {\n if (value > max || value < min) {\n const n = typeof min === 'bigint' ? 'n' : ''\n let range\n if (byteLength > 3) {\n if (min === 0 || min === BigInt(0)) {\n range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`\n } else {\n range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` +\n `${(byteLength + 1) * 8 - 1}${n}`\n }\n } else {\n range = `>= ${min}${n} and <= ${max}${n}`\n }\n throw new errors.ERR_OUT_OF_RANGE('value', range, value)\n }\n checkBounds(buf, offset, byteLength)\n}\n\nfunction validateNumber (value, name) {\n if (typeof value !== 'number') {\n throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)\n }\n}\n\nfunction boundsError (value, length, type) {\n if (Math.floor(value) !== value) {\n validateNumber(value, type)\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value)\n }\n\n if (length < 0) {\n throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()\n }\n\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset',\n `>= ${type ? 1 : 0} and <= ${length}`,\n value)\n}\n\n// HELPER FUNCTIONS\n// ================\n\nconst INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n let codePoint\n const length = string.length\n let leadSurrogate = null\n const bytes = []\n\n for (let i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n let c, hi, lo\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n let i\n for (i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n\n// Create lookup table for `toString('hex')`\n// See: https://github.com/feross/buffer/issues/219\nconst hexSliceLookupTable = (function () {\n const alphabet = '0123456789abcdef'\n const table = new Array(256)\n for (let i = 0; i < 16; ++i) {\n const i16 = i * 16\n for (let j = 0; j < 16; ++j) {\n table[i16 + j] = alphabet[i] + alphabet[j]\n }\n }\n return table\n})()\n\n// Return not function with Error if BigInt not supported\nfunction defineBigIntMethod (fn) {\n return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn\n}\n\nfunction BufferBigIntNotDefined () {\n throw new Error('BigInt not supported')\n}\n", "/**\n * Creates a debounced function that delays invoking the provided function until after the specified timeout.\n * @param {Function} func - The function to debounce.\n * @param {number} [timeout=300] - The number of milliseconds to delay. Defaults to 300ms if not specified or invalid.\n * @returns {Function} A debounced function.\n */\n/* eslint-disable-next-line @typescript-eslint/ban-types */\nexport const debounce = (func: Function, timeout?: number): Function => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n return (...args: unknown[]) => {\n const next = () => func(...args);\n\n if (timer) {\n clearTimeout(timer);\n }\n\n timer = setTimeout(next, timeout !== undefined && timeout > 0 ? timeout : 300);\n };\n};\n", "import {Principal} from '@dfinity/principal';\nimport {nonNullish} from './null.utils';\n\nconst JSON_KEY_BIGINT = '__bigint__';\nconst JSON_KEY_PRINCIPAL = '__principal__';\nconst JSON_KEY_UINT8ARRAY = '__uint8array__';\n\n/**\n * A function that alters the behavior of the stringification process for BigInt, Principal, and Uint8Array.\n * @param {string} _key - The key of the value being stringified.\n * @param {unknown} value - The value being stringified.\n * @returns {unknown} The altered value for stringification.\n */\nexport const jsonReplacer = (_key: string, value: unknown): unknown => {\n if (typeof value === 'bigint') {\n return {[JSON_KEY_BIGINT]: `${value}`};\n }\n\n if (nonNullish(value) && value instanceof Principal) {\n return {[JSON_KEY_PRINCIPAL]: value.toText()};\n }\n\n if (nonNullish(value) && value instanceof Uint8Array) {\n return {[JSON_KEY_UINT8ARRAY]: Array.from(value)};\n }\n\n return value;\n};\n\n/**\n * A parser that interprets revived BigInt, Principal, and Uint8Array when constructing JavaScript values or objects.\n * @param {string} _key - The key of the value being parsed.\n * @param {unknown} value - The value being parsed.\n * @returns {unknown} The parsed value.\n */\nexport const jsonReviver = (_key: string, value: unknown): unknown => {\n const mapValue = <T>(key: string): T => (value as Record<string, T>)[key];\n\n if (nonNullish(value) && typeof value === 'object' && JSON_KEY_BIGINT in value) {\n return BigInt(mapValue(JSON_KEY_BIGINT));\n }\n\n if (nonNullish(value) && typeof value === 'object' && JSON_KEY_PRINCIPAL in value) {\n return Principal.fromText(mapValue(JSON_KEY_PRINCIPAL));\n }\n\n if (nonNullish(value) && typeof value === 'object' && JSON_KEY_UINT8ARRAY in value) {\n return Uint8Array.from(mapValue(JSON_KEY_UINT8ARRAY));\n }\n\n return value;\n};\n", "/**\n * Checks if the provided argument is null or undefined.\n * @template T\n * @param {T | undefined | null} argument - The argument to check.\n * @returns {boolean} True if the argument is null or undefined, false otherwise.\n */\nexport const isNullish = <T>(argument: T | undefined | null): argument is undefined | null =>\n argument === null || argument === undefined;\n\n/**\n * Checks if the provided argument is neither null nor undefined.\n * @template T\n * @param {T | undefined | null} argument - The argument to check.\n * @returns {boolean} True if the argument is neither null nor undefined, false otherwise.\n */\nexport const nonNullish = <T>(argument: T | undefined | null): argument is NonNullable<T> =>\n !isNullish(argument);\n\n/**\n * Represents an error thrown when a value is null or undefined.\n * @class\n * @extends {Error}\n */\nexport class NullishError extends Error {}\n\n/**\n * Asserts that a value is neither null nor undefined.\n * @template T\n * @param {T} value - The value to check.\n * @param {string} [message] - The optional error message to use if the assertion fails.\n * @throws {NullishError} If the value is null or undefined.\n * @returns {asserts value is NonNullable<T>} Asserts that the value is neither null nor undefined.\n */\nexport const assertNonNullish: <T>(\n value: T,\n message?: string\n) => asserts value is NonNullable<T> = <T>(value: T, message?: string): void => {\n if (isNullish(value)) {\n throw new NullishError(message);\n }\n};\n", "import {jsonReplacer, jsonReviver} from './json.utils';\nimport {nonNullish} from './null.utils';\n\n/**\n * Converts a value to a nullable array.\n * @template T\n * @param {T} [value] - The value to convert.\n * @returns {([] | [T])} A nullable array containing the value if non-nullish, or an empty array if nullish.\n */\nexport const toNullable = <T>(value?: T): [] | [T] => {\n return nonNullish(value) ? [value] : [];\n};\n\n/**\n * Extracts a value from a nullable array.\n * @template T\n * @param {([] | [T])} value - The nullable array.\n * @returns {(T | undefined)} The value if present, or undefined if the array is empty.\n */\nexport const fromNullable = <T>(value: [] | [T]): T | undefined => {\n return value?.[0];\n};\n\n/**\n * Converts data to a Uint8Array for transmission or storage.\n * @template T\n * @param {T} data - The data to convert.\n * @returns {Promise<Uint8Array>} A promise that resolves to a Uint8Array representation of the data.\n */\nexport const toArray = async <T>(data: T): Promise<Uint8Array> => {\n const blob: Blob = new Blob([JSON.stringify(data, jsonReplacer)], {\n type: 'application/json; charset=utf-8'\n });\n return new Uint8Array(await blob.arrayBuffer());\n};\n\n/**\n * Converts a Uint8Array or number array back to the original data type.\n * @template T\n * @param {(Uint8Array | number[])} data - The array to convert.\n * @returns {Promise<T>} A promise that resolves to the original data.\n */\nexport const fromArray = async <T>(data: Uint8Array | number[]): Promise<T> => {\n const blob: Blob = new Blob([data instanceof Uint8Array ? data : new Uint8Array(data)], {\n type: 'application/json; charset=utf-8'\n });\n return JSON.parse(await blob.text(), jsonReviver);\n};\n", "/**\n * Checks if the current environment is a browser.\n * @returns {boolean} True if the current environment is a browser, false otherwise.\n */\nexport const isBrowser = (): boolean => typeof window !== `undefined`;\n", "export abstract class Store<T> {\n private callbacks: {id: symbol; callback: (data: T | null) => void}[] = [];\n\n protected populate(data: T | null) {\n this.callbacks.forEach(({callback}: {id: symbol; callback: (data: T | null) => void}) =>\n callback(data)\n );\n }\n\n subscribe(callback: (data: T | null) => void): () => void {\n const callbackId = Symbol();\n this.callbacks.push({id: callbackId, callback});\n\n return () =>\n (this.callbacks = this.callbacks.filter(\n ({id}: {id: symbol; callback: (data: T | null) => void}) => id !== callbackId\n ));\n }\n}\n", "import type {User} from '../types/auth.types';\nimport type {Unsubscribe} from '../types/subscription.types';\nimport {Store} from './store';\n\nexport class AuthStore extends Store<User | null> {\n private static instance: AuthStore;\n\n private authUser: User | null = null;\n\n private constructor() {\n super();\n }\n\n static getInstance() {\n if (!AuthStore.instance) {\n AuthStore.instance = new AuthStore();\n }\n return AuthStore.instance;\n }\n\n set(authUser: User | null) {\n this.authUser = authUser;\n\n this.populate(authUser);\n }\n\n get(): User | null {\n return this.authUser;\n }\n\n override subscribe(callback: (data: User | null) => void): Unsubscribe {\n const unsubscribe: () => void = super.subscribe(callback);\n\n callback(this.authUser);\n\n return unsubscribe;\n }\n\n reset() {\n this.authUser = null;\n\n this.populate(this.authUser);\n }\n}\n", "export const emit = <T>({message, detail}: {message: string; detail?: T | undefined}) => {\n const $event: CustomEvent<T> = new CustomEvent<T>(message, {detail, bubbles: true});\n document.dispatchEvent($event);\n};\n", "// How long the delegation identity should remain valid?\n// e.g. BigInt(7 * 24 * 60 * 60 * 1000 * 1000 * 1000) = 7 days in nanoseconds\n// For Juno: 4 hours\nexport const DELEGATION_IDENTITY_EXPIRATION = BigInt(4 * 60 * 60 * 1000 * 1000 * 1000);\n\n// We consider PIN authentication as \"insecure\" because users can easily lose their PIN if they do not register a passphrase, especially since Safari clears the browser cache every two weeks in cases of inactivity.\n// That's why we disable it by default.\nexport const ALLOW_PIN_AUTHENTICATION = false;\n\nexport const II_POPUP: {width: number; height: number} = {width: 576, height: 576};\nexport const NFID_POPUP: {width: number; height: number} = {width: 505, height: 705};\n\nexport const INTERNET_COMPUTER_ORG = 'internetcomputer.org';\n\n// Worker\nexport const AUTH_TIMER_INTERVAL = 1000;\n", "export const DOCKER_CONTAINER_URL = 'http://127.0.0.1:5987';\nexport const DOCKER_INTERNET_IDENTITY_ID = 'rdmx6-jaaaa-aaaaa-aaadq-cai';\n", "import type {Environment} from '../types/env.types';\nimport {Store} from './store';\n\nexport class EnvStore extends Store<Environment | undefined> {\n private static instance: EnvStore;\n\n private env: Environment | undefined;\n\n private constructor() {\n super();\n }\n\n static getInstance() {\n if (!EnvStore.instance) {\n EnvStore.instance = new EnvStore();\n }\n return EnvStore.instance;\n }\n\n set(env: Environment | undefined) {\n this.env = env;\n\n this.populate(env);\n }\n\n get(): Environment | undefined {\n return this.env;\n }\n\n override subscribe(callback: (data: Environment | null | undefined) => void): () => void {\n const unsubscribe: () => void = super.subscribe(callback);\n\n callback(this.env);\n\n return unsubscribe;\n }\n}\n", "import {isBrowser, isNullish} from '@junobuild/utils';\n\nexport const popupCenter = ({\n width,\n height\n}: {\n width: number;\n height: number;\n}): string | undefined => {\n if (!isBrowser()) {\n return undefined;\n }\n\n if (isNullish(window) || isNullish(window.top)) {\n return undefined;\n }\n\n const {\n top: {innerWidth, innerHeight}\n } = window;\n\n const y = innerHeight / 2 + screenY - height / 2;\n const x = innerWidth / 2 + screenX - width / 2;\n\n return `toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width=${width}, height=${height}, top=${y}, left=${x}`;\n};\n", "import {isNullish, nonNullish} from '@junobuild/utils';\nimport {II_POPUP, INTERNET_COMPUTER_ORG, NFID_POPUP} from '../constants/auth.constants';\nimport {DOCKER_CONTAINER_URL, DOCKER_INTERNET_IDENTITY_ID} from '../constants/container.constants';\nimport {EnvStore} from '../stores/env.store';\nimport type {\n InternetIdentityConfig,\n InternetIdentityDomain,\n NFIDConfig,\n Provider,\n SignInOptions\n} from '../types/auth.types';\nimport {popupCenter} from '../utils/window.utils';\n\n/**\n * Options for signing in with an authentication provider.\n * @interface AuthProviderSignInOptions\n */\nexport interface AuthProviderSignInOptions {\n /**\n * The URL of the identity provider - commonly Internet Identity.\n */\n identityProvider: string;\n /**\n * Optional features for the window opener.\n */\n windowOpenerFeatures?: string;\n}\n\n/**\n * Common traits for all authentication providers\n * @interface AuthProvider\n */\nexport interface AuthProvider {\n /**\n * The unique identifier of the provider.\n */\n readonly id: Provider;\n /**\n * Method to get the sign-in options for the provider.\n * @param options - The sign-in options.\n * @returns The sign-in options for the provider that can be use to effectively perform a sign-in.\n */\n signInOptions: (options: Pick<SignInOptions, 'windowed'>) => AuthProviderSignInOptions;\n}\n\n/**\n * Internet Identity authentication provider.\n * @class InternetIdentityProvider\n * @implements {AuthProvider}\n */\nexport class InternetIdentityProvider implements AuthProvider {\n #domain?: InternetIdentityDomain;\n\n /**\n * Creates an instance of InternetIdentityProvider.\n * @param {InternetIdentityConfig} config - The configuration for Internet Identity.\n */\n constructor({domain}: InternetIdentityConfig) {\n this.#domain = domain;\n }\n\n /**\n * Gets the identifier of the provider.\n * @returns {Provider} The identifier of the provider - `internet_identity`.\n */\n get id(): Provider {\n return 'internet_identity';\n }\n\n /**\n * Gets the sign-in options for Internet Identity.\n * @param {Pick<SignInOptions, 'windowed'>} options - The sign-in options.\n * @returns {AuthProviderSignInOptions} The sign-in options for Internet Identity.\n */\n signInOptions({windowed}: Pick<SignInOptions, 'windowed'>): AuthProviderSignInOptions {\n const identityProviderUrl = (): string => {\n const container = EnvStore.getInstance().get()?.container;\n\n // Production\n if (isNullish(container) || container === false) {\n return `https://identity.${this.#domain ?? INTERNET_COMPUTER_ORG}`;\n }\n\n const env = EnvStore.getInstance().get();\n\n const internetIdentityId =\n nonNullish(env) && nonNullish(env?.internetIdentityId)\n ? env.internetIdentityId\n : DOCKER_INTERNET_IDENTITY_ID;\n\n const {host: containerHost, protocol} = new URL(\n container === true ? DOCKER_CONTAINER_URL : container\n );\n\n return /apple/i.test(navigator?.vendor)\n ? `${protocol}//${containerHost}?canisterId=${internetIdentityId}`\n : `${protocol}//${internetIdentityId}.${containerHost.replace('127.0.0.1', 'localhost')}`;\n };\n\n return {\n ...(windowed !== false && {\n windowOpenerFeatures: popupCenter(II_POPUP)\n }),\n identityProvider: identityProviderUrl()\n };\n }\n}\n\n/**\n * NFID authentication provider.\n * @class NFIDProvider\n * @implements {AuthProvider}\n */\nexport class NFIDProvider implements AuthProvider {\n #appName: string;\n #logoUrl: string;\n\n /**\n * Creates an instance of NFIDProvider.\n * @param {NFIDConfig} config - The configuration for NFID.\n */\n constructor({appName, logoUrl}: NFIDConfig) {\n this.#appName = appName;\n this.#logoUrl = logoUrl;\n }\n\n /**\n * Gets the identifier of the provider.\n * @returns {Provider} The identifier of the provider- nfid.\n */\n get id(): Provider {\n return 'nfid';\n }\n\n /**\n * Gets the sign-in options for NFID.\n * @param {Pick<SignInOptions, 'windowed'>} options - The sign-in options.\n * @returns {AuthProviderSignInOptions} The sign-in options to effectively sign-in with NFID.\n */\n signInOptions({windowed}: Pick<SignInOptions, 'windowed'>): AuthProviderSignInOptions {\n return {\n ...(windowed !== false && {\n windowOpenerFeatures: popupCenter(NFID_POPUP)\n }),\n identityProvider: `https://nfid.one/authenticate/?applicationName=${encodeURI(\n this.#appName\n )}&applicationLogo=${encodeURI(this.#logoUrl)}`\n };\n }\n}\n", "import { Buffer } from 'buffer/';\nimport {\n Agent,\n getDefaultAgent,\n HttpDetailsResponse,\n QueryResponseRejected,\n QueryResponseStatus,\n ReplicaRejectCode,\n SubmitResponse,\n} from './agent';\nimport { AgentError } from './errors';\nimport { IDL } from '@dfinity/candid';\nimport { pollForResponse, PollStrategyFactory, strategy } from './polling';\nimport { Principal } from '@dfinity/principal';\nimport { RequestId } from './request_id';\nimport { toHex } from './utils/buffer';\nimport { CreateCertificateOptions } from './certificate';\nimport managementCanisterIdl from './canisters/management_idl';\nimport _SERVICE, { canister_install_mode, canister_settings } from './canisters/management_service';\n\nexport class ActorCallError extends AgentError {\n constructor(\n public readonly canisterId: Principal,\n public readonly methodName: string,\n public readonly type: 'query' | 'update',\n public readonly props: Record<string, string>,\n ) {\n super(\n [\n `Call failed:`,\n ` Canister: ${canisterId.toText()}`,\n ` Method: ${methodName} (${type})`,\n ...Object.getOwnPropertyNames(props).map(n => ` \"${n}\": ${JSON.stringify(props[n])}`),\n ].join('\\n'),\n );\n }\n}\n\nexport class QueryCallRejectedError extends ActorCallError {\n constructor(\n canisterId: Principal,\n methodName: string,\n public readonly result: QueryResponseRejected,\n ) {\n super(canisterId, methodName, 'query', {\n Status: result.status,\n Code: ReplicaRejectCode[result.reject_code] ?? `Unknown Code \"${result.reject_code}\"`,\n Message: result.reject_message,\n });\n }\n}\n\nexport class UpdateCallRejectedError extends ActorCallError {\n constructor(\n canisterId: Principal,\n methodName: string,\n public readonly requestId: RequestId,\n public readonly response: SubmitResponse['response'],\n ) {\n super(canisterId, methodName, 'update', {\n 'Request ID': toHex(requestId),\n ...(response.body\n ? {\n ...(response.body.error_code\n ? {\n 'Error code': response.body.error_code,\n }\n : {}),\n 'Reject code': String(response.body.reject_code),\n 'Reject message': response.body.reject_message,\n }\n : {\n 'HTTP status code': response.status.toString(),\n 'HTTP status text': response.statusText,\n }),\n });\n }\n}\n\n/**\n * Configuration to make calls to the Replica.\n */\nexport interface CallConfig {\n /**\n * An agent to use in this call, otherwise the actor or call will try to discover the\n * agent to use.\n */\n agent?: Agent;\n\n /**\n * A polling strategy factory that dictates how much and often we should poll the\n * read_state endpoint to get the result of an update call.\n */\n pollingStrategyFactory?: PollStrategyFactory;\n\n /**\n * The canister ID of this Actor.\n */\n canisterId?: string | Principal;\n\n /**\n * The effective canister ID. This should almost always be ignored.\n */\n effectiveCanisterId?: Principal;\n}\n\n/**\n * Configuration that can be passed to customize the Actor behaviour.\n */\nexport interface ActorConfig extends CallConfig {\n /**\n * The Canister ID of this Actor. This is required for an Actor.\n */\n canisterId: string | Principal;\n\n /**\n * An override function for update calls' CallConfig. This will be called on every calls.\n */\n callTransform?(\n methodName: string,\n args: unknown[],\n callConfig: CallConfig,\n ): Partial<CallConfig> | void;\n\n /**\n * An override function for query calls' CallConfig. This will be called on every query.\n */\n queryTransform?(\n methodName: string,\n args: unknown[],\n callConfig: CallConfig,\n ): Partial<CallConfig> | void;\n\n /**\n * Polyfill for BLS Certificate verification in case wasm is not supported\n */\n blsVerify?: CreateCertificateOptions['blsVerify'];\n}\n\n// TODO: move this to proper typing when Candid support TypeScript.\n/**\n * A subclass of an actor. Actor class itself is meant to be a based class.\n */\nexport type ActorSubclass<T = Record<string, ActorMethod>> = Actor & T;\n\n/**\n * An actor method type, defined for each methods of the actor service.\n */\nexport interface ActorMethod<Args extends unknown[] = unknown[], Ret = unknown> {\n (...args: Args): Promise<Ret>;\n withOptions(options: CallConfig): (...args: Args) => Promise<Ret>;\n}\n\n/**\n * An actor method type, defined for each methods of the actor service.\n */\nexport interface ActorMethodWithHttpDetails<Args extends unknown[] = unknown[], Ret = unknown>\n extends ActorMethod {\n (...args: Args): Promise<{ httpDetails: HttpDetailsResponse; result: Ret }>;\n}\n\nexport type FunctionWithArgsAndReturn<Args extends unknown[] = unknown[], Ret = unknown> = (\n ...args: Args\n) => Ret;\n\n// Update all entries of T with the extra information from ActorMethodWithInfo\nexport type ActorMethodMappedWithHttpDetails<T> = {\n [K in keyof T]: T[K] extends FunctionWithArgsAndReturn<infer Args, infer Ret>\n ? ActorMethodWithHttpDetails<Args, Ret>\n : never;\n};\n\n/**\n * The mode used when installing a canister.\n */\nexport type CanisterInstallMode =\n | {\n reinstall: null;\n }\n | {\n upgrade:\n | []\n | [\n {\n skip_pre_upgrade: [] | [boolean];\n },\n ];\n }\n | {\n install: null;\n };\n\n/**\n * Internal metadata for actors. It's an enhanced version of ActorConfig with\n * some fields marked as required (as they are defaulted) and canisterId as\n * a Principal type.\n */\ninterface ActorMetadata {\n service: IDL.ServiceClass;\n agent?: Agent;\n config: ActorConfig;\n}\n\nconst metadataSymbol = Symbol.for('ic-agent-metadata');\n\nexport interface CreateActorClassOpts {\n httpDetails?: boolean;\n}\n\ninterface CreateCanisterSettings {\n freezing_threshold?: bigint;\n controllers?: Array<Principal>;\n memory_allocation?: bigint;\n compute_allocation?: bigint;\n}\n\n/**\n * An actor base class. An actor is an object containing only functions that will\n * return a promise. These functions are derived from the IDL definition.\n */\nexport class Actor {\n /**\n * Get the Agent class this Actor would call, or undefined if the Actor would use\n * the default agent (global.ic.agent).\n * @param actor The actor to get the agent of.\n */\n public static agentOf(actor: Actor): Agent | undefined {\n return actor[metadataSymbol].config.agent;\n }\n\n /**\n * Get the interface of an actor, in the form of an instance of a Service.\n * @param actor The actor to get the interface of.\n */\n public static interfaceOf(actor: Actor): IDL.ServiceClass {\n return actor[metadataSymbol].service;\n }\n\n public static canisterIdOf(actor: Actor): Principal {\n return Principal.from(actor[metadataSymbol].config.canisterId);\n }\n\n public static async install(\n fields: {\n module: ArrayBuffer;\n mode?: canister_install_mode;\n arg?: ArrayBuffer;\n },\n config: ActorConfig,\n ): Promise<void> {\n const mode = fields.mode === undefined ? { install: null } : fields.mode;\n // Need to transform the arg into a number array.\n const arg = fields.arg ? [...new Uint8Array(fields.arg)] : [];\n // Same for module.\n const wasmModule = [...new Uint8Array(fields.module)];\n const canisterId =\n typeof config.canisterId === 'string'\n ? Principal.fromText(config.canisterId)\n : config.canisterId;\n\n await getManagementCanister(config).install_code({\n mode,\n arg,\n wasm_module: wasmModule,\n canister_id: canisterId,\n sender_canister_version: [],\n });\n }\n\n public static async createCanister(\n config?: CallConfig,\n settings?: CreateCanisterSettings,\n ): Promise<Principal> {\n function settingsToCanisterSettings(settings: CreateCanisterSettings): [canister_settings] {\n return [\n {\n controllers: settings.controllers ? [settings.controllers] : [],\n compute_allocation: settings.compute_allocation ? [settings.compute_allocation] : [],\n freezing_threshold: settings.freezing_threshold ? [settings.freezing_threshold] : [],\n memory_allocation: settings.memory_allocation ? [settings.memory_allocation] : [],\n reserved_cycles_limit: [],\n log_visibility: [],\n wasm_memory_limit: [],\n },\n ];\n }\n\n const { canister_id: canisterId } = await getManagementCanister(\n config || {},\n ).provisional_create_canister_with_cycles({\n amount: [],\n settings: settingsToCanisterSettings(settings || {}),\n specified_id: [],\n sender_canister_version: [],\n });\n\n return canisterId;\n }\n\n public static async createAndInstallCanister(\n interfaceFactory: IDL.InterfaceFactory,\n fields: {\n module: ArrayBuffer;\n arg?: ArrayBuffer;\n },\n config?: CallConfig,\n ): Promise<ActorSubclass> {\n const canisterId = await this.createCanister(config);\n await this.install(\n {\n ...fields,\n },\n { ...config, canisterId },\n );\n\n return this.createActor(interfaceFactory, { ...config, canisterId });\n }\n\n public static createActorClass(\n interfaceFactory: IDL.InterfaceFactory,\n options?: CreateActorClassOpts,\n ): ActorConstructor {\n const service = interfaceFactory({ IDL });\n\n class CanisterActor extends Actor {\n [x: string]: ActorMethod;\n\n constructor(config: ActorConfig) {\n if (!config.canisterId)\n throw new AgentError(\n `Canister ID is required, but received ${typeof config.canisterId} instead. If you are using automatically generated declarations, this may be because your application is not setting the canister ID in process.env correctly.`,\n );\n const canisterId =\n typeof config.canisterId === 'string'\n ? Principal.fromText(config.canisterId)\n : config.canisterId;\n\n super({\n config: {\n ...DEFAULT_ACTOR_CONFIG,\n ...config,\n canisterId,\n },\n service,\n });\n\n for (const [methodName, func] of service._fields) {\n if (options?.httpDetails) {\n func.annotations.push(ACTOR_METHOD_WITH_HTTP_DETAILS);\n }\n\n this[methodName] = _createActorMethod(this, methodName, func, config.blsVerify);\n }\n }\n }\n\n return CanisterActor;\n }\n\n public static createActor<T = Record<string, ActorMethod>>(\n interfaceFactory: IDL.InterfaceFactory,\n configuration: ActorConfig,\n ): ActorSubclass<T> {\n if (!configuration.canisterId) {\n throw new AgentError(\n `Canister ID is required, but received ${typeof configuration.canisterId} instead. If you are using automatically generated declarations, this may be because your application is not setting the canister ID in process.env correctly.`,\n );\n }\n return new (this.createActorClass(interfaceFactory))(\n configuration,\n ) as unknown as ActorSubclass<T>;\n }\n\n public static createActorWithHttpDetails<T = Record<string, ActorMethod>>(\n interfaceFactory: IDL.InterfaceFactory,\n configuration: ActorConfig,\n ): ActorSubclass<ActorMethodMappedWithHttpDetails<T>> {\n return new (this.createActorClass(interfaceFactory, { httpDetails: true }))(\n configuration,\n ) as unknown as ActorSubclass<ActorMethodMappedWithHttpDetails<T>>;\n }\n\n private [metadataSymbol]: ActorMetadata;\n\n protected constructor(metadata: ActorMetadata) {\n this[metadataSymbol] = Object.freeze(metadata);\n }\n}\n\n// IDL functions can have multiple return values, so decoding always\n// produces an array. Ensure that functions with single or zero return\n// values behave as expected.\nfunction decodeReturnValue(types: IDL.Type[], msg: ArrayBuffer) {\n const returnValues = IDL.decode(types, Buffer.from(msg));\n switch (returnValues.length) {\n case 0:\n return undefined;\n case 1:\n return returnValues[0];\n default:\n return returnValues;\n }\n}\n\nconst DEFAULT_ACTOR_CONFIG = {\n pollingStrategyFactory: strategy.defaultStrategy,\n};\n\nexport type ActorConstructor = new (config: ActorConfig) => ActorSubclass;\n\nexport const ACTOR_METHOD_WITH_HTTP_DETAILS = 'http-details';\n\nfunction _createActorMethod(\n actor: Actor,\n methodName: string,\n func: IDL.FuncClass,\n blsVerify?: CreateCertificateOptions['blsVerify'],\n): ActorMethod {\n let caller: (options: CallConfig, ...args: unknown[]) => Promise<unknown>;\n if (func.annotations.includes('query') || func.annotations.includes('composite_query')) {\n caller = async (options, ...args) => {\n // First, if there's a config transformation, call it.\n options = {\n ...options,\n ...actor[metadataSymbol].config.queryTransform?.(methodName, args, {\n ...actor[metadataSymbol].config,\n ...options,\n }),\n };\n\n const agent = options.agent || actor[metadataSymbol].config.agent || getDefaultAgent();\n const cid = Principal.from(options.canisterId || actor[metadataSymbol].config.canisterId);\n const arg = IDL.encode(func.argTypes, args);\n\n const result = await agent.query(cid, {\n methodName,\n arg,\n effectiveCanisterId: options.effectiveCanisterId,\n });\n\n switch (result.status) {\n case QueryResponseStatus.Rejected:\n throw new QueryCallRejectedError(cid, methodName, result);\n\n case QueryResponseStatus.Replied:\n return func.annotations.includes(ACTOR_METHOD_WITH_HTTP_DETAILS)\n ? {\n httpDetails: result.httpDetails,\n result: decodeReturnValue(func.retTypes, result.reply.arg),\n }\n : decodeReturnValue(func.retTypes, result.reply.arg);\n }\n };\n } else {\n caller = async (options, ...args) => {\n // First, if there's a config transformation, call it.\n options = {\n ...options,\n ...actor[metadataSymbol].config.callTransform?.(methodName, args, {\n ...actor[metadataSymbol].config,\n ...options,\n }),\n };\n\n const agent = options.agent || actor[metadataSymbol].config.agent || getDefaultAgent();\n const { canisterId, effectiveCanisterId, pollingStrategyFactory } = {\n ...DEFAULT_ACTOR_CONFIG,\n ...actor[metadataSymbol].config,\n ...options,\n };\n const cid = Principal.from(canisterId);\n const ecid = effectiveCanisterId !== undefined ? Principal.from(effectiveCanisterId) : cid;\n const arg = IDL.encode(func.argTypes, args);\n const { requestId, response } = await agent.call(cid, {\n methodName,\n arg,\n effectiveCanisterId: ecid,\n });\n\n if (!response.ok || response.body /* IC-1462 */) {\n throw new UpdateCallRejectedError(cid, methodName, requestId, response);\n }\n\n const pollStrategy = pollingStrategyFactory();\n const responseBytes = await pollForResponse(agent, ecid, requestId, pollStrategy, blsVerify);\n const shouldIncludeHttpDetails = func.annotations.includes(ACTOR_METHOD_WITH_HTTP_DETAILS);\n\n if (responseBytes !== undefined) {\n return shouldIncludeHttpDetails\n ? {\n httpDetails: response,\n result: decodeReturnValue(func.retTypes, responseBytes),\n }\n : decodeReturnValue(func.retTypes, responseBytes);\n } else if (func.retTypes.length === 0) {\n return shouldIncludeHttpDetails\n ? {\n httpDetails: response,\n result: undefined,\n }\n : undefined;\n } else {\n throw new Error(`Call was returned undefined, but type [${func.retTypes.join(',')}].`);\n }\n };\n }\n\n const handler = (...args: unknown[]) => caller({}, ...args);\n handler.withOptions =\n (options: CallConfig) =>\n (...args: unknown[]) =>\n caller(options, ...args);\n return handler as ActorMethod;\n}\n\nexport type ManagementCanisterRecord = _SERVICE;\n\n/**\n * Create a management canister actor\n * @param config - a CallConfig\n */\nexport function getManagementCanister(config: CallConfig): ActorSubclass<ManagementCanisterRecord> {\n function transform(\n _methodName: string,\n args: Record<string, unknown> & { canister_id: string }[],\n ) {\n if (config.effectiveCanisterId) {\n return { effectiveCanisterId: Principal.from(config.effectiveCanisterId) };\n }\n const first = args[0];\n let effectiveCanisterId = Principal.fromHex('');\n if (first && typeof first === 'object' && first.canister_id) {\n effectiveCanisterId = Principal.from(first.canister_id as unknown);\n }\n return { effectiveCanisterId };\n }\n\n return Actor.createActor<ManagementCanisterRecord>(managementCanisterIdl, {\n ...config,\n canisterId: Principal.fromHex(''),\n ...{\n callTransform: transform,\n queryTransform: transform,\n },\n });\n}\n", "import { Principal } from '@dfinity/principal';\nimport { RequestId } from '../request_id';\nimport { JsonObject } from '@dfinity/candid';\nimport { Identity } from '../auth';\nimport { HttpHeaderField } from './http/types';\n\n/**\n * Codes used by the replica for rejecting a message.\n * See {@link https://sdk.dfinity.org/docs/interface-spec/#reject-codes | the interface spec}.\n */\nexport enum ReplicaRejectCode {\n SysFatal = 1,\n SysTransient = 2,\n DestinationInvalid = 3,\n CanisterReject = 4,\n CanisterError = 5,\n}\n\n/**\n * Options when doing a {@link Agent.readState} call.\n */\nexport interface ReadStateOptions {\n /**\n * A list of paths to read the state of.\n */\n paths: ArrayBuffer[][];\n}\n\n/**\n *\n */\nexport type QueryResponse = QueryResponseReplied | QueryResponseRejected;\n\nexport const enum QueryResponseStatus {\n Replied = 'replied',\n Rejected = 'rejected',\n}\n\nexport interface HttpDetailsResponse {\n ok: boolean;\n status: number;\n statusText: string;\n headers: HttpHeaderField[];\n}\n\nexport type ApiQueryResponse = QueryResponse & {\n httpDetails: HttpDetailsResponse;\n requestId: RequestId;\n};\n\nexport interface QueryResponseBase {\n status: QueryResponseStatus;\n}\n\nexport type NodeSignature = {\n // the batch time\n timestamp: bigint;\n // the signature\n signature: Uint8Array;\n // the ID of the node that created the signature\n identity: Uint8Array;\n};\n\nexport interface QueryResponseReplied extends QueryResponseBase {\n status: QueryResponseStatus.Replied;\n reply: { arg: ArrayBuffer };\n signatures?: NodeSignature[];\n}\n\nexport interface QueryResponseRejected extends QueryResponseBase {\n status: QueryResponseStatus.Rejected;\n reject_code: ReplicaRejectCode;\n reject_message: string;\n error_code: string;\n signatures?: NodeSignature[];\n}\n\n/**\n * Options when doing a {@link Agent.query} call.\n */\nexport interface QueryFields {\n /**\n * The method name to call.\n */\n methodName: string;\n\n /**\n * A binary encoded argument. This is already encoded and will be sent as is.\n */\n arg: ArrayBuffer;\n\n /**\n * Overrides canister id for path to fetch. This is used for management canister calls.\n */\n effectiveCanisterId?: Principal;\n}\n\n/**\n * Options when doing a {@link Agent.call} call.\n */\nexport interface CallOptions {\n /**\n * The method name to call.\n */\n methodName: string;\n\n /**\n * A binary encoded argument. This is already encoded and will be sent as is.\n */\n arg: ArrayBuffer;\n\n /**\n * An effective canister ID, used for routing. This should only be mentioned if\n * it's different from the canister ID.\n */\n effectiveCanisterId: Principal | string;\n}\n\nexport interface ReadStateResponse {\n certificate: ArrayBuffer;\n}\n\nexport interface SubmitResponse {\n requestId: RequestId;\n response: {\n ok: boolean;\n status: number;\n statusText: string;\n body: {\n error_code?: string;\n reject_code: number;\n reject_message: string;\n } | null;\n headers: HttpHeaderField[];\n };\n}\n\n/**\n * An Agent able to make calls and queries to a Replica.\n */\nexport interface Agent {\n readonly rootKey: ArrayBuffer | null;\n /**\n * Returns the principal ID associated with this agent (by default). It only shows\n * the principal of the default identity in the agent, which is the principal used\n * when calls don't specify it.\n */\n getPrincipal(): Promise<Principal>;\n\n /**\n * Create the request for the read state call.\n * `readState` uses this internally.\n * Useful to avoid signing the same request multiple times.\n */\n createReadStateRequest?(\n options: ReadStateOptions,\n identity?: Identity,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any>;\n\n /**\n * Send a read state query to the replica. This includes a list of paths to return,\n * and will return a Certificate. This will only reject on communication errors,\n * but the certificate might contain less information than requested.\n * @param effectiveCanisterId A Canister ID related to this call.\n * @param options The options for this call.\n * @param identity Identity for the call. If not specified, uses the instance identity.\n * @param request The request to send in case it has already been created.\n */\n readState(\n effectiveCanisterId: Principal | string,\n options: ReadStateOptions,\n identity?: Identity,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n request?: any,\n ): Promise<ReadStateResponse>;\n\n call(canisterId: Principal | string, fields: CallOptions): Promise<SubmitResponse>;\n\n /**\n * Query the status endpoint of the replica. This normally has a few fields that\n * corresponds to the version of the replica, its root public key, and any other\n * information made public.\n * @returns A JsonObject that is essentially a record of fields from the status\n * endpoint.\n */\n status(): Promise<JsonObject>;\n\n /**\n * Send a query call to a canister. See\n * {@link https://sdk.dfinity.org/docs/interface-spec/#http-query | the interface spec}.\n * @param canisterId The Principal of the Canister to send the query to. Sending a query to\n * the management canister is not supported (as it has no meaning from an agent).\n * @param options Options to use to create and send the query.\n * @param identity Sender principal to use when sending the query.\n * @returns The response from the replica. The Promise will only reject when the communication\n * failed. If the query itself failed but no protocol errors happened, the response will\n * be of type QueryResponseRejected.\n */\n query(\n canisterId: Principal | string,\n options: QueryFields,\n identity?: Identity | Promise<Identity>,\n ): Promise<ApiQueryResponse>;\n\n /**\n * By default, the agent is configured to talk to the main Internet Computer,\n * and verifies responses using a hard-coded public key.\n *\n * This function will instruct the agent to ask the endpoint for its public\n * key, and use that instead. This is required when talking to a local test\n * instance, for example.\n *\n * Only use this when you are _not_ talking to the main Internet Computer,\n * otherwise you are prone to man-in-the-middle attacks! Do not call this\n * function by default.\n */\n fetchRootKey(): Promise<ArrayBuffer>;\n /**\n * If an application needs to invalidate an identity under certain conditions, an `Agent` may expose an `invalidateIdentity` method.\n * Invoking this method will set the inner identity used by the `Agent` to `null`.\n *\n * A use case for this would be - after a certain period of inactivity, a secure application chooses to invalidate the identity of any `HttpAgent` instances. An invalid identity can be replaced by `Agent.replaceIdentity`\n */\n invalidateIdentity?(): void;\n /**\n * If an application needs to replace an identity under certain conditions, an `Agent` may expose a `replaceIdentity` method.\n * Invoking this method will set the inner identity used by the `Agent` to a newly provided identity.\n *\n * A use case for this would be - after authenticating using `@dfinity/auth-client`, you can replace the `AnonymousIdentity` of your `Actor` with a `DelegationIdentity`.\n *\n * ```Actor.agentOf(defaultActor).replaceIdentity(await authClient.getIdentity());```\n */\n replaceIdentity?(identity: Identity): void;\n}\n", "import { Principal } from '@dfinity/principal';\nimport { HttpAgentRequest } from './agent/http/types';\nimport { requestIdOf } from './request_id';\nimport { concat, toHex } from './utils/buffer';\n\nconst domainSeparator = new TextEncoder().encode('\\x0Aic-request');\n\n/**\n * A Key Pair, containing a secret and public key.\n */\nexport interface KeyPair {\n secretKey: ArrayBuffer;\n publicKey: PublicKey;\n}\n\n/**\n * A public key that is DER encoded. This is a branded ArrayBuffer.\n */\nexport type DerEncodedPublicKey = ArrayBuffer & { __derEncodedPublicKey__?: void };\n\n/**\n * A signature array buffer.\n */\nexport type Signature = ArrayBuffer & { __signature__: void };\n\n/**\n * A Public Key implementation.\n */\nexport interface PublicKey {\n toDer(): DerEncodedPublicKey;\n // rawKey, toRaw, and derKey are optional for backwards compatibility.\n toRaw?(): ArrayBuffer;\n rawKey?: ArrayBuffer;\n derKey?: DerEncodedPublicKey;\n}\n\n/**\n * A General Identity object. This does not have to be a private key (for example,\n * the Anonymous identity), but it must be able to transform request.\n */\nexport interface Identity {\n /**\n * Get the principal represented by this identity. Normally should be a\n * `Principal.selfAuthenticating()`.\n */\n getPrincipal(): Principal;\n\n /**\n * Transform a request into a signed version of the request. This is done last\n * after the transforms on the body of a request. The returned object can be\n * anything, but must be serializable to CBOR.\n */\n transformRequest(request: HttpAgentRequest): Promise<unknown>;\n}\n\n/**\n * An Identity that can sign blobs.\n */\nexport abstract class SignIdentity implements Identity {\n protected _principal: Principal | undefined;\n\n /**\n * Returns the public key that would match this identity's signature.\n */\n public abstract getPublicKey(): PublicKey;\n\n /**\n * Signs a blob of data, with this identity's private key.\n */\n public abstract sign(blob: ArrayBuffer): Promise<Signature>;\n\n /**\n * Get the principal represented by this identity. Normally should be a\n * `Principal.selfAuthenticating()`.\n */\n public getPrincipal(): Principal {\n if (!this._principal) {\n this._principal = Principal.selfAuthenticating(new Uint8Array(this.getPublicKey().toDer()));\n }\n return this._principal;\n }\n\n /**\n * Transform a request into a signed version of the request. This is done last\n * after the transforms on the body of a request. The returned object can be\n * anything, but must be serializable to CBOR.\n * @param request - internet computer request to transform\n */\n public async transformRequest(request: HttpAgentRequest): Promise<unknown> {\n const { body, ...fields } = request;\n const requestId = await requestIdOf(body);\n return {\n ...fields,\n body: {\n content: body,\n sender_pubkey: this.getPublicKey().toDer(),\n sender_sig: await this.sign(concat(domainSeparator, requestId)),\n },\n };\n }\n}\n\nexport class AnonymousIdentity implements Identity {\n public getPrincipal(): Principal {\n return Principal.anonymous();\n }\n\n public async transformRequest(request: HttpAgentRequest): Promise<unknown> {\n return {\n ...request,\n body: { content: request.body },\n };\n }\n}\n\n/*\n * We need to communicate with other agents on the page about identities,\n * but those messages may need to go across boundaries where it's not possible to\n * serialize/deserialize object prototypes easily.\n * So these are lightweight, serializable objects that contain enough information to recreate\n * SignIdentities, but don't commit to having all methods of SignIdentity.\n *\n * Use Case:\n * * DOM Events that let differently-versioned components communicate to one another about\n * Identities, even if they're using slightly different versions of agent packages to\n * create/interpret them.\n */\nexport interface AnonymousIdentityDescriptor {\n type: 'AnonymousIdentity';\n}\nexport interface PublicKeyIdentityDescriptor {\n type: 'PublicKeyIdentity';\n publicKey: string;\n}\nexport type IdentityDescriptor = AnonymousIdentityDescriptor | PublicKeyIdentityDescriptor;\n\n/**\n * Create an IdentityDescriptor from a @dfinity/identity Identity\n * @param identity - identity describe in returned descriptor\n */\nexport function createIdentityDescriptor(\n identity: SignIdentity | AnonymousIdentity,\n): IdentityDescriptor {\n const identityIndicator: IdentityDescriptor =\n 'getPublicKey' in identity\n ? { type: 'PublicKeyIdentity', publicKey: toHex(identity.getPublicKey().toDer()) }\n : { type: 'AnonymousIdentity' };\n return identityIndicator;\n}\n", "import { lebEncode } from '@dfinity/candid';\nimport * as cbor from 'simple-cbor';\nimport {\n Endpoint,\n HttpAgentRequest,\n HttpAgentRequestTransformFn,\n HttpHeaderField,\n makeNonce,\n Nonce,\n} from './types';\n\nconst NANOSECONDS_PER_MILLISECONDS = BigInt(1_000_000);\n\nconst REPLICA_PERMITTED_DRIFT_MILLISECONDS = 60 * 1000;\n\nexport class Expiry {\n private readonly _value: bigint;\n\n constructor(deltaInMSec: number) {\n // Use bigint because it can overflow the maximum number allowed in a double float.\n const raw_value =\n BigInt(Math.floor(Date.now() + deltaInMSec - REPLICA_PERMITTED_DRIFT_MILLISECONDS)) *\n NANOSECONDS_PER_MILLISECONDS;\n\n // round down to the nearest second\n const ingress_as_seconds = raw_value / BigInt(1_000_000_000);\n\n // round down to nearest minute\n const ingress_as_minutes = ingress_as_seconds / BigInt(60);\n\n const rounded_down_nanos = ingress_as_minutes * BigInt(60) * BigInt(1_000_000_000);\n\n this._value = rounded_down_nanos;\n }\n\n public toCBOR(): cbor.CborValue {\n // TODO: change this to take the minimum amount of space (it always takes 8 bytes now).\n return cbor.value.u64(this._value.toString(16), 16);\n }\n\n public toHash(): ArrayBuffer {\n return lebEncode(this._value);\n }\n}\n\n/**\n * Create a Nonce transform, which takes a function that returns a Buffer, and adds it\n * as the nonce to every call requests.\n * @param nonceFn A function that returns a buffer. By default uses a semi-random method.\n */\nexport function makeNonceTransform(nonceFn: () => Nonce = makeNonce): HttpAgentRequestTransformFn {\n return async (request: HttpAgentRequest) => {\n // Nonce needs to be inserted into the header for all requests, to enable logs to be correlated with requests.\n const headers = request.request.headers;\n // TODO: uncomment this when the http proxy supports it.\n // headers.set('X-IC-Request-ID', toHex(new Uint8Array(nonce)));\n request.request.headers = headers;\n\n // Nonce only needs to be inserted into the body for async calls, to prevent replay attacks.\n if (request.endpoint === Endpoint.Call) {\n request.body.nonce = nonceFn();\n }\n };\n}\n\n/**\n * Create a transform that adds a delay (by default 5 minutes) to the expiry.\n *\n * @param delayInMilliseconds The delay to add to the call time, in milliseconds.\n */\nexport function makeExpiryTransform(delayInMilliseconds: number): HttpAgentRequestTransformFn {\n return async (request: HttpAgentRequest) => {\n request.body.ingress_expiry = new Expiry(delayInMilliseconds);\n };\n}\n\n/**\n * Maps the default fetch headers field to the serializable HttpHeaderField.\n *\n * @param headers Fetch definition of the headers type\n * @returns array of header fields\n */\nexport function httpHeadersTransform(headers: Headers): HttpHeaderField[] {\n const headerFields: HttpHeaderField[] = [];\n headers.forEach((value, key) => {\n headerFields.push([key, value]);\n });\n return headerFields;\n}\n", "/**\n * Generates a random unsigned 32-bit integer between 0 and 0xffffffff\n * @returns {number} a random number\n */\nexport const randomNumber = (): number => {\n // determine whether browser crypto is available\n if (typeof window !== 'undefined' && !!window.crypto && !!window.crypto.getRandomValues) {\n const array = new Uint32Array(1);\n window.crypto.getRandomValues(array);\n return array[0];\n }\n // A second check for webcrypto, in case it is loaded under global instead of window\n if (typeof crypto !== 'undefined' && crypto.getRandomValues) {\n const array = new Uint32Array(1);\n crypto.getRandomValues(array);\n return array[0];\n }\n\n type nodeCrypto = {\n randomInt: (min: number, max: number) => number;\n };\n\n // determine whether node crypto is available\n if (typeof crypto !== 'undefined' && (crypto as unknown as nodeCrypto).randomInt) {\n return (crypto as unknown as nodeCrypto).randomInt(0, 0xffffffff);\n }\n\n // fall back to Math.random\n return Math.floor(Math.random() * 0xffffffff);\n};\n", "import type { Principal } from '@dfinity/principal';\nimport { Expiry } from './transforms';\nimport { randomNumber } from '../../utils/random';\n\n/**\n * @internal\n */\nexport const enum Endpoint {\n Query = 'read',\n ReadState = 'read_state',\n Call = 'call',\n}\n\n// An HttpAgent request, before it gets encoded and sent to the server.\n// We create an empty request that we will fill later.\nexport type HttpAgentRequest =\n | HttpAgentQueryRequest\n | HttpAgentSubmitRequest\n | HttpAgentReadStateRequest;\n\nexport interface HttpAgentBaseRequest {\n readonly endpoint: Endpoint;\n request: RequestInit;\n}\n\nexport type HttpHeaderField = [string, string];\n\nexport interface HttpAgentSubmitRequest extends HttpAgentBaseRequest {\n readonly endpoint: Endpoint.Call;\n body: CallRequest;\n}\n\nexport interface HttpAgentQueryRequest extends HttpAgentBaseRequest {\n readonly endpoint: Endpoint.Query;\n body: ReadRequest;\n}\n\nexport interface HttpAgentReadStateRequest extends HttpAgentBaseRequest {\n readonly endpoint: Endpoint.ReadState;\n body: ReadRequest;\n}\n\nexport interface Signed<T> {\n content: T;\n sender_pubkey: ArrayBuffer;\n sender_sig: ArrayBuffer;\n}\n\nexport interface UnSigned<T> {\n content: T;\n}\n\nexport type Envelope<T> = Signed<T> | UnSigned<T>;\n\nexport interface HttpAgentRequestTransformFn {\n (args: HttpAgentRequest): Promise<HttpAgentRequest | undefined | void>;\n priority?: number;\n}\n\n// The fields in a \"call\" submit request.\nexport interface CallRequest extends Record<string, any> {\n request_type: SubmitRequestType.Call;\n canister_id: Principal;\n method_name: string;\n arg: ArrayBuffer;\n sender: Uint8Array | Principal;\n ingress_expiry: Expiry;\n}\n\n// The types of values allowed in the `request_type` field for submit requests.\nexport enum SubmitRequestType {\n Call = 'call',\n}\n\n// The types of values allowed in the `request_type` field for read requests.\nexport const enum ReadRequestType {\n Query = 'query',\n ReadState = 'read_state',\n}\n\n// The fields in a \"query\" read request.\nexport interface QueryRequest extends Record<string, any> {\n request_type: ReadRequestType.Query;\n canister_id: Principal;\n method_name: string;\n arg: ArrayBuffer;\n sender: Uint8Array | Principal;\n ingress_expiry: Expiry;\n}\n\nexport interface ReadStateRequest extends Record<string, any> {\n request_type: ReadRequestType.ReadState;\n paths: ArrayBuffer[][];\n ingress_expiry: Expiry;\n sender: Uint8Array | Principal;\n}\n\nexport type ReadRequest = QueryRequest | ReadStateRequest;\n\n// A Nonce that can be used for calls.\nexport type Nonce = Uint8Array & { __nonce__: void };\n\n/**\n * Create a random Nonce, based on random values\n */\nexport function makeNonce(): Nonce {\n // Encode 128 bits.\n const buffer = new ArrayBuffer(16);\n const view = new DataView(buffer);\n const rand1 = randomNumber();\n const rand2 = randomNumber();\n const rand3 = randomNumber();\n const rand4 = randomNumber();\n\n view.setUint32(0, rand1);\n view.setUint32(4, rand2);\n view.setUint32(8, rand3);\n view.setUint32(12, rand4);\n\n return buffer as Nonce;\n}\n", "import { AgentError } from '../../errors';\nimport { HttpDetailsResponse } from '../api';\n\nexport class AgentHTTPResponseError extends AgentError {\n constructor(message: string, public readonly response: HttpDetailsResponse) {\n super(message);\n this.name = this.constructor.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n", "const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n: bigint, le = false) {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number) => h >>> s;\nconst shrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number) => l;\nconst rotr32L = (h: number, _l: number) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number) => (h << (s - 32)) | (l >>> (64 - s));\n\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah: number, Al: number, Bh: number, Bl: number) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number) =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number) =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number) =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number) =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n", "import { HashMD } from './_md.js';\nimport u64 from './_u64.js';\nimport { wrapConstructor } from './utils.js';\n\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD<SHA512> {\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0x6a09e667 | 0;\n Al = 0xf3bcc908 | 0;\n Bh = 0xbb67ae85 | 0;\n Bl = 0x84caa73b | 0;\n Ch = 0x3c6ef372 | 0;\n Cl = 0xfe94f82b | 0;\n Dh = 0xa54ff53a | 0;\n Dl = 0x5f1d36f1 | 0;\n Eh = 0x510e527f | 0;\n El = 0xade682d1 | 0;\n Fh = 0x9b05688c | 0;\n Fl = 0x2b3e6c1f | 0;\n Gh = 0x1f83d9ab | 0;\n Gl = 0xfb41bd6b | 0;\n Hh = 0x5be0cd19 | 0;\n Hl = 0x137e2179 | 0;\n\n constructor() {\n super(128, 64, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nclass SHA512_224 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0x8c3d37c8 | 0;\n Al = 0x19544da2 | 0;\n Bh = 0x73e19966 | 0;\n Bl = 0x89dcd4d6 | 0;\n Ch = 0x1dfab7ae | 0;\n Cl = 0x32ff9c82 | 0;\n Dh = 0x679dd514 | 0;\n Dl = 0x582f9fcf | 0;\n Eh = 0x0f6d2b69 | 0;\n El = 0x7bd44da8 | 0;\n Fh = 0x77e36f73 | 0;\n Fl = 0x04c48942 | 0;\n Gh = 0x3f9d85a8 | 0;\n Gl = 0x6a1d36c8 | 0;\n Hh = 0x1112e6ad | 0;\n Hl = 0x91d692a1 | 0;\n\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\nclass SHA512_256 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0x22312194 | 0;\n Al = 0xfc2bf72c | 0;\n Bh = 0x9f555fa3 | 0;\n Bl = 0xc84c64c2 | 0;\n Ch = 0x2393b86b | 0;\n Cl = 0x6f53b151 | 0;\n Dh = 0x96387719 | 0;\n Dl = 0x5940eabd | 0;\n Eh = 0x96283ee2 | 0;\n El = 0xa88effe3 | 0;\n Fh = 0xbe5e1e25 | 0;\n Fl = 0x53863992 | 0;\n Gh = 0x2b0199fc | 0;\n Gl = 0x2c85b8aa | 0;\n Hh = 0x0eb72ddc | 0;\n Hl = 0x81c52ca2 | 0;\n\n constructor() {\n super();\n this.outputLen = 32;\n }\n}\n\nclass SHA384 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0xcbbb9d5d | 0;\n Al = 0xc1059ed8 | 0;\n Bh = 0x629a292a | 0;\n Bl = 0x367cd507 | 0;\n Ch = 0x9159015a | 0;\n Cl = 0x3070dd17 | 0;\n Dh = 0x152fecd8 | 0;\n Dl = 0xf70e5939 | 0;\n Eh = 0x67332667 | 0;\n El = 0xffc00b31 | 0;\n Fh = 0x8eb44a87 | 0;\n Fl = 0x68581511 | 0;\n Gh = 0xdb0c2e0d | 0;\n Gl = 0x64f98fa7 | 0;\n Hh = 0x47b5481d | 0;\n Hl = 0xbefa4fa4 | 0;\n\n constructor() {\n super();\n this.outputLen = 48;\n }\n}\n\nexport const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());\nexport const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224());\nexport const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256());\nexport const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384());\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Twisted Edwards curve. The formula is: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2\nimport { AffinePoint, BasicCurve, Group, GroupConstructor, validateBasic, wNAF } from './curve.js';\nimport { mod } from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes, FHash, Hex } from './utils.js';\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n\n// Edwards curves must declare params a & d.\nexport type CurveType = BasicCurve<bigint> & {\n a: bigint; // curve param a\n d: bigint; // curve param d\n hash: FHash; // Hashing\n randomBytes: (bytesLength?: number) => Uint8Array; // CSPRNG\n adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; // clears bits to get valid field elemtn\n domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; // Used for hashing\n uvRatio?: (u: bigint, v: bigint) => { isValid: boolean; value: bigint }; // Ratio \u221A(u/v)\n prehash?: FHash; // RFC 8032 pre-hashing of messages to sign() / verify()\n mapToCurve?: (scalar: bigint[]) => AffinePoint<bigint>; // for hash-to-curve standard\n};\n\n// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\nconst VERIFY_DEFAULT = { zip215: true };\n\nfunction validateOpts(curve: CurveType) {\n const opts = validateBasic(curve);\n ut.validateObject(\n curve,\n {\n hash: 'function',\n a: 'bigint',\n d: 'bigint',\n randomBytes: 'function',\n },\n {\n adjustScalarBytes: 'function',\n domain: 'function',\n uvRatio: 'function',\n mapToCurve: 'function',\n }\n );\n // Set defaults\n return Object.freeze({ ...opts } as const);\n}\n\n// Instance of Extended Point with coordinates in X, Y, Z, T\nexport interface ExtPointType extends Group<ExtPointType> {\n readonly ex: bigint;\n readonly ey: bigint;\n readonly ez: bigint;\n readonly et: bigint;\n get x(): bigint;\n get y(): bigint;\n assertValidity(): void;\n multiply(scalar: bigint): ExtPointType;\n multiplyUnsafe(scalar: bigint): ExtPointType;\n isSmallOrder(): boolean;\n isTorsionFree(): boolean;\n clearCofactor(): ExtPointType;\n toAffine(iz?: bigint): AffinePoint<bigint>;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n}\n// Static methods of Extended Point with coordinates in X, Y, Z, T\nexport interface ExtPointConstructor extends GroupConstructor<ExtPointType> {\n new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType;\n fromAffine(p: AffinePoint<bigint>): ExtPointType;\n fromHex(hex: Hex): ExtPointType;\n fromPrivateKey(privateKey: Hex): ExtPointType;\n}\n\nexport type CurveFn = {\n CURVE: ReturnType<typeof validateOpts>;\n getPublicKey: (privateKey: Hex) => Uint8Array;\n sign: (message: Hex, privateKey: Hex, options?: { context?: Hex }) => Uint8Array;\n verify: (\n sig: Hex,\n message: Hex,\n publicKey: Hex,\n options?: { context?: Hex; zip215: boolean }\n ) => boolean;\n ExtendedPoint: ExtPointConstructor;\n utils: {\n randomPrivateKey: () => Uint8Array;\n getExtendedPublicKey: (key: Hex) => {\n head: Uint8Array;\n prefix: Uint8Array;\n scalar: bigint;\n point: ExtPointType;\n pointBytes: Uint8Array;\n };\n };\n};\n\n// It is not generic twisted curve for now, but ed25519/ed448 generic implementation\nexport function twistedEdwards(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType<typeof validateOpts>;\n const {\n Fp,\n n: CURVE_ORDER,\n prehash: prehash,\n hash: cHash,\n randomBytes,\n nByteLength,\n h: cofactor,\n } = CURVE;\n const MASK = _2n << (BigInt(nByteLength * 8) - _1n);\n const modP = Fp.create; // Function overrides\n\n // sqrt(u/v)\n const uvRatio =\n CURVE.uvRatio ||\n ((u: bigint, v: bigint) => {\n try {\n return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };\n } catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes); // NOOP\n const domain =\n CURVE.domain ||\n ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => {\n if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n const inBig = (n: bigint) => typeof n === 'bigint' && _0n < n; // n in [1..]\n const inRange = (n: bigint, max: bigint) => inBig(n) && inBig(max) && n < max; // n in [1..max-1]\n const in0MaskRange = (n: bigint) => n === _0n || inRange(n, MASK); // n in [0..MASK-1]\n function assertInRange(n: bigint, max: bigint) {\n // n in [1..max-1]\n if (inRange(n, max)) return n;\n throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`);\n }\n function assertGE0(n: bigint) {\n // n in [0..CURVE_ORDER-1]\n return n === _0n ? n : assertInRange(n, CURVE_ORDER); // GE = prime subgroup, not full group\n }\n const pointPrecomputes = new Map<Point, Point[]>();\n function isPoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ExtendedPoint expected');\n }\n // Extended Point works in extended coordinates: (x, y, z, t) \u220B (x=x/z, y=y/z, t=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point implements ExtPointType {\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n\n constructor(\n readonly ex: bigint,\n readonly ey: bigint,\n readonly ez: bigint,\n readonly et: bigint\n ) {\n if (!in0MaskRange(ex)) throw new Error('x required');\n if (!in0MaskRange(ey)) throw new Error('y required');\n if (!in0MaskRange(ez)) throw new Error('z required');\n if (!in0MaskRange(et)) throw new Error('t required');\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n static fromAffine(p: AffinePoint<bigint>): Point {\n if (p instanceof Point) throw new Error('extended point not allowed');\n const { x, y } = p || {};\n if (!in0MaskRange(x) || !in0MaskRange(y)) throw new Error('invalid affine point');\n return new Point(x, y, _1n, modP(x * y));\n }\n static normalizeZ(points: Point[]): Point[] {\n const toInv = Fp.invertBatch(points.map((p) => p.ez));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n _WINDOW_SIZE?: number;\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n this._WINDOW_SIZE = windowSize;\n pointPrecomputes.delete(this);\n }\n // Not required for fromHex(), which always creates valid points.\n // Could be useful for fromAffine().\n assertValidity(): void {\n const { a, d } = CURVE;\n if (this.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX\u00B2 + Y\u00B2)Z\u00B2 = Z\u2074 + dX\u00B2Y\u00B2\n const { ex: X, ey: Y, ez: Z, et: T } = this;\n const X2 = modP(X * X); // X\u00B2\n const Y2 = modP(Y * Y); // Y\u00B2\n const Z2 = modP(Z * Z); // Z\u00B2\n const Z4 = modP(Z2 * Z2); // Z\u2074\n const aX2 = modP(X2 * a); // aX\u00B2\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX\u00B2 + Y\u00B2)Z\u00B2\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z\u2074 + dX\u00B2Y\u00B2\n if (left !== right) throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT) throw new Error('bad point: equation left != right (2)');\n }\n\n // Compare one point to another.\n equals(other: Point): boolean {\n isPoint(other);\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n\n protected is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n negate(): Point {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));\n }\n\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double(): Point {\n const { a } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other: Point) {\n isPoint(other);\n const { a, d } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;\n // Faster algo for adding 2 Extended Points when curve's a=-1.\n // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4\n // Cost: 8M + 8add + 2*2.\n // Note: It does not check whether the `other` point is valid.\n if (a === BigInt(-1)) {\n const A = modP((Y1 - X1) * (Y2 + X2));\n const B = modP((Y1 + X1) * (Y2 - X2));\n const F = modP(B - A);\n if (F === _0n) return this.double(); // Same point. Tests say it doesn't affect timing\n const C = modP(Z1 * _2n * T2);\n const D = modP(T1 * _2n * Z2);\n const E = D + C;\n const G = B + A;\n const H = D - C;\n const X3 = modP(E * F);\n const Y3 = modP(G * H);\n const T3 = modP(E * H);\n const Z3 = modP(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n\n return new Point(X3, Y3, Z3, T3);\n }\n\n subtract(other: Point): Point {\n return this.add(other.negate());\n }\n\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, pointPrecomputes, n, Point.normalizeZ);\n }\n\n // Constant-time multiplication.\n multiply(scalar: bigint): Point {\n const { p, f } = this.wNAF(assertInRange(scalar, CURVE_ORDER));\n return Point.normalizeZ([p, f])[0];\n }\n\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n multiplyUnsafe(scalar: bigint): Point {\n let n = assertGE0(scalar); // 0 <= scalar < CURVE.n\n if (n === _0n) return I;\n if (this.equals(I) || n === _1n) return this;\n if (this.equals(G)) return this.wNAF(n).p;\n return wnaf.unsafeLadder(this, n);\n }\n\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder(): boolean {\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree(): boolean {\n return wnaf.unsafeLadder(this, CURVE_ORDER).is0();\n }\n\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(iz?: bigint): AffinePoint<bigint> {\n const { ex: x, ey: y, ez: z } = this;\n const is0 = this.is0();\n if (iz == null) iz = is0 ? _8n : (Fp.inv(z) as bigint); // 8 was chosen arbitrarily\n const ax = modP(x * iz);\n const ay = modP(y * iz);\n const zz = modP(z * iz);\n if (is0) return { x: _0n, y: _1n };\n if (zz !== _1n) throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n }\n\n clearCofactor(): Point {\n const { h: cofactor } = CURVE;\n if (cofactor === _1n) return this;\n return this.multiplyUnsafe(cofactor);\n }\n\n // Converts hash string or Uint8Array to Point.\n // Uses algo from RFC8032 5.1.3.\n static fromHex(hex: Hex, zip215 = false): Point {\n const { d, a } = CURVE;\n const len = Fp.BYTES;\n hex = ensureBytes('pointHex', hex, len); // copy hex to a new array\n const normed = hex.slice(); // copy again, we'll manipulate it\n const lastByte = hex[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = ut.bytesToNumberLE(normed);\n if (y === _0n) {\n // y=0 is allowed\n } else {\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n if (zip215)\n assertInRange(y, MASK); // zip215=true [1..P-1] (2^255-19-1 for ed25519)\n else assertInRange(y, Fp.ORDER); // zip215=false [1..MASK-1] (2^256-1 for ed25519)\n }\n\n // Ed25519: x\u00B2 = (y\u00B2-1)/(dy\u00B2+1) mod p. Ed448: x\u00B2 = (y\u00B2-1)/(dy\u00B2-1) mod p. Generic case:\n // ax\u00B2+y\u00B2=1+dx\u00B2y\u00B2 => y\u00B2-1=dx\u00B2y\u00B2-ax\u00B2 => y\u00B2-1=x\u00B2(dy\u00B2-a) => x\u00B2=(y\u00B2-1)/(dy\u00B2-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y\u00B2 - 1\n const v = modP(d * y2 - a); // v = d y\u00B2 + 1.\n let { isValid, value: x } = uvRatio(u, v); // \u221A(u/v)\n if (!isValid) throw new Error('Point.fromHex: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('Point.fromHex: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromPrivateKey(privKey: Hex) {\n return getExtendedPublicKey(privKey).point;\n }\n toRawBytes(): Uint8Array {\n const { x, y } = this.toAffine();\n const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y\n return bytes; // and use the last byte to encode sign of x\n }\n toHex(): string {\n return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.\n }\n }\n const { BASE: G, ZERO: I } = Point;\n const wnaf = wNAF(Point, nByteLength * 8);\n\n function modN(a: bigint) {\n return mod(a, CURVE_ORDER);\n }\n // Little-endian SHA512 with modulo n\n function modN_LE(hash: Uint8Array): bigint {\n return modN(ut.bytesToNumberLE(hash));\n }\n\n /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */\n function getExtendedPublicKey(key: Hex) {\n const len = nByteLength;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n const point = G.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toRawBytes(); // Uint8Array representation\n return { head, prefix, scalar, point, pointBytes };\n }\n\n // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared\n function getPublicKey(privKey: Hex): Uint8Array {\n return getExtendedPublicKey(privKey).pointBytes;\n }\n\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context: Hex = new Uint8Array(), ...msgs: Uint8Array[]) {\n const msg = ut.concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg: Hex, privKey: Hex, options: { context?: Hex } = {}): Uint8Array {\n msg = ensureBytes('message', msg);\n if (prehash) msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = G.multiply(r).toRawBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = modN(r + k * scalar); // S = (r + k * s) mod L\n assertGE0(s); // 0 <= s < l\n const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES));\n return ensureBytes('result', res, nByteLength * 2); // 64-byte signature\n }\n\n const verifyOpts: { context?: Hex; zip215?: boolean } = VERIFY_DEFAULT;\n function verify(sig: Hex, msg: Hex, publicKey: Hex, options = verifyOpts): boolean {\n const { context, zip215 } = options;\n const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.\n msg = ensureBytes('message', msg);\n if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n const s = ut.bytesToNumberLE(sig.slice(len, 2 * len));\n // zip215: true is good for consensus-critical apps and allows points < 2^256\n // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p\n let A, R, SB;\n try {\n A = Point.fromHex(publicKey, zip215);\n R = Point.fromHex(sig.slice(0, len), zip215);\n SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside\n } catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder()) return false;\n\n const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);\n }\n\n G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n\n const utils = {\n getExtendedPublicKey,\n // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.\n randomPrivateKey: (): Uint8Array => randomBytes(Fp.BYTES),\n\n /**\n * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT\n * values. This slows down first getPublicKey() by milliseconds (see Speed section),\n * but allows to speed-up subsequent getPublicKey() calls up to 20x.\n * @param windowSize 2, 4, 8, 16\n */\n precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3));\n return point;\n },\n };\n\n return {\n CURVE,\n getPublicKey,\n sign,\n verify,\n ExtendedPoint: Point,\n utils,\n };\n}\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha512';\nimport { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils';\nimport { AffinePoint, Group } from './abstract/curve.js';\nimport { ExtPointType, twistedEdwards } from './abstract/edwards.js';\nimport { createHasher, expand_message_xmd, htfBasicOpts } from './abstract/hash-to-curve.js';\nimport { Field, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.js';\nimport { montgomery } from './abstract/montgomery.js';\nimport {\n bytesToHex,\n bytesToNumberLE,\n ensureBytes,\n equalBytes,\n Hex,\n numberToBytesLE,\n} from './abstract/utils.js';\n\n/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n */\n\nconst ED25519_P = BigInt(\n '57896044618658097711785492504343953926634992332820282019728792003956564819949'\n);\n// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt(\n '19681161376707505956807079304988542015446066515923890162744021073123829784752'\n);\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _5n = BigInt(5), _8n = BigInt(8);\n\nfunction ed25519_pow_2_252_3(x: bigint) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ED25519_P;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\n\nfunction adjustScalarBytes(bytes: Uint8Array): Uint8Array {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n\n// sqrt(u/v)\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n const P = ED25519_P;\n const v3 = mod(v * v * v, P); // v\u00B3\n const v7 = mod(v3 * v3 * v, P); // v\u2077\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv\u00B3)(uv\u2077)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx\u00B2\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx\u00B2 = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx\u00B2 = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx\u00B2 = -u\u221A(-1)\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P)) x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n\n// Just in case\nexport const ED25519_TORSION_SUBGROUP = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n\nconst Fp = /* @__PURE__ */ (() => Field(ED25519_P, undefined, true))();\n\nconst ed25519Defaults = /* @__PURE__ */ (() =>\n ({\n // Param: a\n a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster\n // d is equal to -121665/121666 over finite field.\n // Negative number is P - number, and division is invert(number, P)\n d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),\n // Finite field \uD835\uDD3Dp over which we'll do calculations; 2n**255n - 19n\n Fp,\n // Subgroup order: how many points curve has\n // 2n**252n + 27742317777372353535851937790883648493n;\n n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),\n // Cofactor\n h: _8n,\n // Base point (x, y) aka generator point\n Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),\n Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),\n hash: sha512,\n randomBytes,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/\u221Av\n uvRatio,\n }) as const)();\n\nexport const ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();\n\nfunction ed25519_domain(data: Uint8Array, ctx: Uint8Array, phflag: boolean) {\n if (ctx.length > 255) throw new Error('Context is too big');\n return concatBytes(\n utf8ToBytes('SigEd25519 no Ed25519 collisions'),\n new Uint8Array([phflag ? 1 : 0, ctx.length]),\n ctx,\n data\n );\n}\n\nexport const ed25519ctx = /* @__PURE__ */ (() =>\n twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n }))();\nexport const ed25519ph = /* @__PURE__ */ (() =>\n twistedEdwards(\n Object.assign({}, ed25519Defaults, {\n domain: ed25519_domain,\n prehash: sha512,\n })\n ))();\n\nexport const x25519 = /* @__PURE__ */ (() =>\n montgomery({\n P: ED25519_P,\n a: BigInt(486662),\n montgomeryBits: 255, // n is 253 bits\n nByteLength: 32,\n Gu: BigInt(9),\n powPminus2: (x: bigint): bigint => {\n const P = ED25519_P;\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n },\n adjustScalarBytes,\n randomBytes,\n }))();\n\n/**\n * Converts ed25519 public key to x25519 public key. Uses formula:\n * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * @example\n * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());\n * const aPriv = x25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub))\n */\nexport function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array {\n const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub);\n const _1n = BigInt(1);\n return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y)));\n}\nexport const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated\n\n/**\n * Converts ed25519 secret key to x25519 secret key.\n * @example\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey());\n * const aPriv = ed25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub)\n */\nexport function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array {\n const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32));\n return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32);\n}\n\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\n\nconst ELL2_C1 = /* @__PURE__ */ (() => (Fp.ORDER + _3n) / _8n)(); // 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\n\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u: bigint) {\n const ELL2_C4 = (Fp.ORDER - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic\n const ELL2_J = BigInt(486662);\n\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J);// 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\n\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u: bigint) {\n const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n\n const inv = Fp.invertBatch([xd, yd]); // batch division\n return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd)\n}\n\nconst htf = /* @__PURE__ */ (() =>\n createHasher(\n ed25519.ExtendedPoint,\n (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]),\n {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n }\n ))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n\nfunction assertRstPoint(other: unknown) {\n if (!(other instanceof RistPoint)) throw new Error('RistrettoPoint expected');\n}\n\n// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// \u221A(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt(\n '25063068953384623474111414158702152701244531502492656460079210482610430750235'\n);\n// 1 / \u221A(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt(\n '54469307008909316920995813868745141605393597292927456921205312896311721017578'\n);\n// 1-d\u00B2\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt(\n '1159843021668779879193775521855586647937357759715417654439879720876111806838'\n);\n// (d-1)\u00B2\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt(\n '40440834346308536858101042469323190826248399146238708352240133220865137265952'\n);\n// Calculates 1/\u221A(number)\nconst invertSqrt = (number: bigint) => uvRatio(_1n, number);\n\nconst MAX_255B = /* @__PURE__ */ BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'\n);\nconst bytes255ToNumberLE = (bytes: Uint8Array) =>\n ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\ntype ExtendedPoint = ExtPointType;\n\n// Computes Elligator map for Ristretto\n// https://ristretto.group/formulas/elligator.html\nfunction calcElligatorRistrettoMap(r0: bigint): ExtendedPoint {\n const { d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P)) s_ = mod(-s_);\n if (!Ns_D_is_sq) s = s_; // 7\n if (!Ns_D_is_sq) c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\n/**\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448\n */\nclass RistPoint implements Group<RistPoint> {\n static BASE: RistPoint;\n static ZERO: RistPoint;\n // Private property to discourage combining ExtendedPoint + RistrettoPoint\n // Always use Ristretto encoding/decoding instead.\n constructor(private readonly ep: ExtendedPoint) {}\n\n static fromAffine(ap: AffinePoint<bigint>) {\n return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap));\n }\n\n /**\n * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`.\n * The hash-to-group operation applies Elligator twice and adds the results.\n * **Note:** this is one-way map, there is no conversion from point to hash.\n * https://ristretto.group/formulas/elligator.html\n * @param hex 64-byte output of a hash function\n */\n static hashToCurve(hex: Hex): RistPoint {\n hex = ensureBytes('ristrettoHash', hex, 64);\n const r1 = bytes255ToNumberLE(hex.slice(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(hex.slice(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new RistPoint(R1.add(R2));\n }\n\n /**\n * Converts ristretto-encoded string to ristretto point.\n * https://ristretto.group/formulas/decoding.html\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex: Hex): RistPoint {\n hex = ensureBytes('ristrettoHex', hex, 32);\n const { a, d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';\n const s = bytes255ToNumberLE(hex);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P)) throw new Error(emsg);\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P)) x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n) throw new Error(emsg);\n return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t));\n }\n\n /**\n * Encodes ristretto point to Uint8Array.\n * https://ristretto.group/formulas/encoding.html\n */\n toRawBytes(): Uint8Array {\n let { ex: x, ey: y, ez: z, et: t } = this.ep;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const u1 = mod(mod(z + y) * mod(z - y)); // 1\n const u2 = mod(x * y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * t); // 6\n let D: bigint; // 7\n if (isNegativeLE(t * zInv, P)) {\n let _x = mod(y * SQRT_M1);\n let _y = mod(x * SQRT_M1);\n x = _x;\n y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n } else {\n D = D2; // 8\n }\n if (isNegativeLE(x * zInv, P)) y = mod(-y); // 9\n let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P)) s = mod(-s);\n return numberToBytesLE(s, 32); // 11\n }\n\n toHex(): string {\n return bytesToHex(this.toRawBytes());\n }\n\n toString(): string {\n return this.toHex();\n }\n\n // Compare one point to another.\n equals(other: RistPoint): boolean {\n assertRstPoint(other);\n const { ex: X1, ey: Y1 } = this.ep;\n const { ex: X2, ey: Y2 } = other.ep;\n const mod = ed25519.CURVE.Fp.create;\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n\n add(other: RistPoint): RistPoint {\n assertRstPoint(other);\n return new RistPoint(this.ep.add(other.ep));\n }\n\n subtract(other: RistPoint): RistPoint {\n assertRstPoint(other);\n return new RistPoint(this.ep.subtract(other.ep));\n }\n\n multiply(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiply(scalar));\n }\n\n multiplyUnsafe(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiplyUnsafe(scalar));\n }\n\n double(): RistPoint {\n return new RistPoint(this.ep.double());\n }\n\n negate(): RistPoint {\n return new RistPoint(this.ep.negate());\n }\n}\nexport const RistrettoPoint = /* @__PURE__ */ (() => {\n if (!RistPoint.BASE) RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE);\n if (!RistPoint.ZERO) RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO);\n return RistPoint;\n})();\n\n// Hashing to ristretto255. https://www.rfc-editor.org/rfc/rfc9380#appendix-B\nexport const hashToRistretto255 = (msg: Uint8Array, options: htfBasicOpts) => {\n const d = options.DST;\n const DST = typeof d === 'string' ? utf8ToBytes(d) : d;\n const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512);\n const P = RistPoint.hashToCurve(uniform_bytes);\n return P;\n};\nexport const hash_to_ristretto255 = hashToRistretto255; // legacy\n", "export type ExpirableMapOptions<K, V> = {\n source?: Iterable<[K, V]>;\n expirationTime?: number;\n};\n\n/**\n * A map that expires entries after a given time.\n * Defaults to 10 minutes.\n */\nexport class ExpirableMap<K, V> implements Map<K, V> {\n // Internals\n #inner: Map<K, { value: V; timestamp: number }>;\n #expirationTime: number;\n\n [Symbol.iterator]: () => IterableIterator<[K, V]> = this.entries.bind(this);\n [Symbol.toStringTag] = 'ExpirableMap';\n\n /**\n * Create a new ExpirableMap.\n * @param {ExpirableMapOptions<any, any>} options - options for the map.\n * @param {Iterable<[any, any]>} options.source - an optional source of entries to initialize the map with.\n * @param {number} options.expirationTime - the time in milliseconds after which entries will expire.\n */\n constructor(options: ExpirableMapOptions<K, V> = {}) {\n const { source = [], expirationTime = 10 * 60 * 1000 } = options;\n const currentTime = Date.now();\n this.#inner = new Map(\n [...source].map(([key, value]) => [key, { value, timestamp: currentTime }]),\n );\n this.#expirationTime = expirationTime;\n }\n\n /**\n * Prune removes all expired entries.\n */\n prune() {\n const currentTime = Date.now();\n for (const [key, entry] of this.#inner.entries()) {\n if (currentTime - entry.timestamp > this.#expirationTime) {\n this.#inner.delete(key);\n }\n }\n return this;\n }\n\n // Implementing the Map interface\n\n /**\n * Set the value for the given key. Prunes expired entries.\n * @param key for the entry\n * @param value of the entry\n * @returns this\n */\n set(key: K, value: V) {\n this.prune();\n const entry = {\n value,\n timestamp: Date.now(),\n };\n this.#inner.set(key, entry);\n\n return this;\n }\n\n /**\n * Get the value associated with the key, if it exists and has not expired.\n * @param key K\n * @returns the value associated with the key, or undefined if the key is not present or has expired.\n */\n get(key: K) {\n const entry = this.#inner.get(key);\n if (entry === undefined) {\n return undefined;\n }\n if (Date.now() - entry.timestamp > this.#expirationTime) {\n this.#inner.delete(key);\n return undefined;\n }\n return entry.value;\n }\n\n /**\n * Clear all entries.\n */\n clear() {\n this.#inner.clear();\n }\n\n /**\n * Entries returns the entries of the map, without the expiration time.\n * @returns an iterator over the entries of the map.\n */\n entries(): IterableIterator<[K, V]> {\n const iterator = this.#inner.entries();\n const generator = function* () {\n for (const [key, value] of iterator) {\n yield [key, value.value] as [K, V];\n }\n };\n return generator();\n }\n\n /**\n * Values returns the values of the map, without the expiration time.\n * @returns an iterator over the values of the map.\n */\n values(): IterableIterator<V> {\n const iterator = this.#inner.values();\n const generator = function* () {\n for (const value of iterator) {\n yield value.value;\n }\n };\n return generator();\n }\n\n /**\n * Keys returns the keys of the map\n * @returns an iterator over the keys of the map.\n */\n keys(): IterableIterator<K> {\n return this.#inner.keys();\n }\n\n /**\n * forEach calls the callbackfn on each entry of the map.\n * @param callbackfn to call on each entry\n * @param thisArg to use as this when calling the callbackfn\n */\n forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: ExpirableMap<K, V>) {\n for (const [key, value] of this.#inner.entries()) {\n callbackfn.call(thisArg, value.value, key, this);\n }\n }\n\n /**\n * has returns true if the key exists and has not expired.\n * @param key K\n * @returns true if the key exists and has not expired.\n */\n has(key: K): boolean {\n return this.#inner.has(key);\n }\n\n /**\n * delete the entry for the given key.\n * @param key K\n * @returns true if the key existed and has been deleted.\n */\n delete(key: K) {\n return this.#inner.delete(key);\n }\n\n /**\n * get size of the map.\n * @returns the size of the map.\n */\n get size() {\n return this.#inner.size;\n }\n}\n", "import { bufEquals } from './utils/buffer';\n\nexport const encodeLenBytes = (len: number): number => {\n if (len <= 0x7f) {\n return 1;\n } else if (len <= 0xff) {\n return 2;\n } else if (len <= 0xffff) {\n return 3;\n } else if (len <= 0xffffff) {\n return 4;\n } else {\n throw new Error('Length too long (> 4 bytes)');\n }\n};\n\nexport const encodeLen = (buf: Uint8Array, offset: number, len: number): number => {\n if (len <= 0x7f) {\n buf[offset] = len;\n return 1;\n } else if (len <= 0xff) {\n buf[offset] = 0x81;\n buf[offset + 1] = len;\n return 2;\n } else if (len <= 0xffff) {\n buf[offset] = 0x82;\n buf[offset + 1] = len >> 8;\n buf[offset + 2] = len;\n return 3;\n } else if (len <= 0xffffff) {\n buf[offset] = 0x83;\n buf[offset + 1] = len >> 16;\n buf[offset + 2] = len >> 8;\n buf[offset + 3] = len;\n return 4;\n } else {\n throw new Error('Length too long (> 4 bytes)');\n }\n};\n\nexport const decodeLenBytes = (buf: Uint8Array, offset: number): number => {\n if (buf[offset] < 0x80) return 1;\n if (buf[offset] === 0x80) throw new Error('Invalid length 0');\n if (buf[offset] === 0x81) return 2;\n if (buf[offset] === 0x82) return 3;\n if (buf[offset] === 0x83) return 4;\n throw new Error('Length too long (> 4 bytes)');\n};\n\nexport const decodeLen = (buf: Uint8Array, offset: number): number => {\n const lenBytes = decodeLenBytes(buf, offset);\n if (lenBytes === 1) return buf[offset];\n else if (lenBytes === 2) return buf[offset + 1];\n else if (lenBytes === 3) return (buf[offset + 1] << 8) + buf[offset + 2];\n else if (lenBytes === 4)\n return (buf[offset + 1] << 16) + (buf[offset + 2] << 8) + buf[offset + 3];\n throw new Error('Length too long (> 4 bytes)');\n};\n\n/**\n * A DER encoded `SEQUENCE(OID)` for DER-encoded-COSE\n */\nexport const DER_COSE_OID = Uint8Array.from([\n ...[0x30, 0x0c], // SEQUENCE\n ...[0x06, 0x0a], // OID with 10 bytes\n ...[0x2b, 0x06, 0x01, 0x04, 0x01, 0x83, 0xb8, 0x43, 0x01, 0x01], // DER encoded COSE\n]);\n\n/**\n * A DER encoded `SEQUENCE(OID)` for the Ed25519 algorithm\n */\nexport const ED25519_OID = Uint8Array.from([\n ...[0x30, 0x05], // SEQUENCE\n ...[0x06, 0x03], // OID with 3 bytes\n ...[0x2b, 0x65, 0x70], // id-Ed25519 OID\n]);\n\n/**\n * A DER encoded `SEQUENCE(OID)` for secp256k1 with the ECDSA algorithm\n */\nexport const SECP256K1_OID = Uint8Array.from([\n ...[0x30, 0x10], // SEQUENCE\n ...[0x06, 0x07], // OID with 7 bytes\n ...[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01], // OID ECDSA\n ...[0x06, 0x05], // OID with 5 bytes\n ...[0x2b, 0x81, 0x04, 0x00, 0x0a], // OID secp256k1\n]);\n\n/**\n * Wraps the given `payload` in a DER encoding tagged with the given encoded `oid` like so:\n * `SEQUENCE(oid, BITSTRING(payload))`\n *\n * @param payload The payload to encode as the bit string\n * @param oid The DER encoded (and SEQUENCE wrapped!) OID to tag the payload with\n */\nexport function wrapDER(payload: ArrayBuffer, oid: Uint8Array): Uint8Array {\n // The Bit String header needs to include the unused bit count byte in its length\n const bitStringHeaderLength = 2 + encodeLenBytes(payload.byteLength + 1);\n const len = oid.byteLength + bitStringHeaderLength + payload.byteLength;\n let offset = 0;\n const buf = new Uint8Array(1 + encodeLenBytes(len) + len);\n // Sequence\n buf[offset++] = 0x30;\n // Sequence Length\n offset += encodeLen(buf, offset, len);\n\n // OID\n buf.set(oid, offset);\n offset += oid.byteLength;\n\n // Bit String Header\n buf[offset++] = 0x03;\n offset += encodeLen(buf, offset, payload.byteLength + 1);\n // 0 padding\n buf[offset++] = 0x00;\n buf.set(new Uint8Array(payload), offset);\n\n return buf;\n}\n\n/**\n * Extracts a payload from the given `derEncoded` data, and checks that it was tagged with the given `oid`.\n *\n * `derEncoded = SEQUENCE(oid, BITSTRING(payload))`\n *\n * @param derEncoded The DER encoded and tagged data\n * @param oid The DER encoded (and SEQUENCE wrapped!) expected OID\n * @returns The unwrapped payload\n */\nexport const unwrapDER = (derEncoded: ArrayBuffer, oid: Uint8Array): Uint8Array => {\n let offset = 0;\n const expect = (n: number, msg: string) => {\n if (buf[offset++] !== n) {\n throw new Error('Expected: ' + msg);\n }\n };\n\n const buf = new Uint8Array(derEncoded);\n expect(0x30, 'sequence');\n offset += decodeLenBytes(buf, offset);\n\n if (!bufEquals(buf.slice(offset, offset + oid.byteLength), oid)) {\n throw new Error('Not the expected OID.');\n }\n offset += oid.byteLength;\n\n expect(0x03, 'bit string');\n const payloadLen = decodeLen(buf, offset) - 1; // Subtracting 1 to account for the 0 padding\n offset += decodeLenBytes(buf, offset);\n expect(0x00, '0 padding');\n const result = buf.slice(offset);\n if (payloadLen !== result.length) {\n throw new Error(\n `DER payload mismatch: Expected length ${payloadLen} actual length ${result.length}`,\n );\n }\n return result;\n};\n", "import { DerEncodedPublicKey, PublicKey } from './auth';\nimport { ED25519_OID, unwrapDER, wrapDER } from './der';\n\nexport class Ed25519PublicKey implements PublicKey {\n public static from(key: PublicKey): Ed25519PublicKey {\n return this.fromDer(key.toDer());\n }\n\n public static fromRaw(rawKey: ArrayBuffer): Ed25519PublicKey {\n return new Ed25519PublicKey(rawKey);\n }\n\n public static fromDer(derKey: DerEncodedPublicKey): Ed25519PublicKey {\n return new Ed25519PublicKey(this.derDecode(derKey));\n }\n\n // The length of Ed25519 public keys is always 32 bytes.\n private static RAW_KEY_LENGTH = 32;\n\n private static derEncode(publicKey: ArrayBuffer): DerEncodedPublicKey {\n return wrapDER(publicKey, ED25519_OID).buffer as DerEncodedPublicKey;\n }\n\n private static derDecode(key: DerEncodedPublicKey): ArrayBuffer {\n const unwrapped = unwrapDER(key, ED25519_OID);\n if (unwrapped.length !== this.RAW_KEY_LENGTH) {\n throw new Error('An Ed25519 public key must be exactly 32bytes long');\n }\n return unwrapped;\n }\n\n #rawKey: ArrayBuffer;\n\n public get rawKey(): ArrayBuffer {\n return this.#rawKey;\n }\n\n #derKey: DerEncodedPublicKey;\n\n public get derKey(): DerEncodedPublicKey {\n return this.#derKey;\n }\n\n // `fromRaw` and `fromDer` should be used for instantiation, not this constructor.\n private constructor(key: ArrayBuffer) {\n if (key.byteLength !== Ed25519PublicKey.RAW_KEY_LENGTH) {\n throw new Error('An Ed25519 public key must be exactly 32bytes long');\n }\n this.#rawKey = key;\n this.#derKey = Ed25519PublicKey.derEncode(key);\n }\n\n public toDer(): DerEncodedPublicKey {\n return this.derKey;\n }\n\n public toRaw(): ArrayBuffer {\n return this.rawKey;\n }\n}\n", "import { AgentError } from './errors';\n\nexport type ObserveFunction<T> = (data: T, ...rest: unknown[]) => void;\n\nexport class Observable<T> {\n observers: ObserveFunction<T>[];\n\n constructor() {\n this.observers = [];\n }\n\n subscribe(func: ObserveFunction<T>) {\n this.observers.push(func);\n }\n\n unsubscribe(func: ObserveFunction<T>) {\n this.observers = this.observers.filter(observer => observer !== func);\n }\n\n notify(data: T, ...rest: unknown[]) {\n this.observers.forEach(observer => observer(data, ...rest));\n }\n}\n\nexport type AgentLog =\n | {\n message: string;\n level: 'warn' | 'info';\n }\n | {\n message: string;\n level: 'error';\n error: AgentError;\n };\n\nexport class ObservableLog extends Observable<AgentLog> {\n constructor() {\n super();\n }\n print(message: string, ...rest: unknown[]) {\n this.notify({ message, level: 'info' }, ...rest);\n }\n warn(message: string, ...rest: unknown[]) {\n this.notify({ message, level: 'warn' }, ...rest);\n }\n error(message: string, error: AgentError, ...rest: unknown[]) {\n this.notify({ message, level: 'error', error }, ...rest);\n }\n}\n", "const RANDOMIZATION_FACTOR = 0.5;\nconst MULTIPLIER = 1.5;\nconst INITIAL_INTERVAL_MSEC = 500;\nconst MAX_INTERVAL_MSEC = 60_000;\nconst MAX_ELAPSED_TIME_MSEC = 900_000;\nconst MAX_ITERATIONS = 10;\n\nexport type BackoffStrategy = {\n next: () => number | null;\n currentInterval?: number;\n count?: number;\n ellapsedTimeInMsec?: number;\n};\n\nexport type BackoffStrategyArgs = {\n maxIterations?: number;\n maxElapsedTime?: number;\n};\n\nexport type BackoffStrategyFactory = (args?: BackoffStrategyArgs) => BackoffStrategy;\n\n// export type BackoffStrategyGenerator = Generator<number, void, unknown>;\n\nexport type ExponentialBackoffOptions = {\n initialInterval?: number;\n randomizationFactor?: number;\n multiplier?: number;\n maxInterval?: number;\n maxElapsedTime?: number;\n maxIterations?: number;\n date?: DateConstructor;\n};\n\n/**\n * Exponential backoff strategy.\n */\nexport class ExponentialBackoff {\n #currentInterval: number;\n #randomizationFactor: number;\n #multiplier: number;\n #maxInterval: number;\n #startTime: number;\n #maxElapsedTime: number;\n #maxIterations: number;\n #date: DateConstructor;\n #count = 0;\n\n static default = {\n initialInterval: INITIAL_INTERVAL_MSEC,\n randomizationFactor: RANDOMIZATION_FACTOR,\n multiplier: MULTIPLIER,\n maxInterval: MAX_INTERVAL_MSEC,\n // 1 minute\n maxElapsedTime: MAX_ELAPSED_TIME_MSEC,\n maxIterations: MAX_ITERATIONS,\n date: Date,\n };\n\n constructor(options: ExponentialBackoffOptions = ExponentialBackoff.default) {\n const {\n initialInterval = INITIAL_INTERVAL_MSEC,\n randomizationFactor = RANDOMIZATION_FACTOR,\n multiplier = MULTIPLIER,\n maxInterval = MAX_INTERVAL_MSEC,\n maxElapsedTime = MAX_ELAPSED_TIME_MSEC,\n maxIterations = MAX_ITERATIONS,\n date = Date,\n } = options;\n this.#currentInterval = initialInterval;\n this.#randomizationFactor = randomizationFactor;\n this.#multiplier = multiplier;\n this.#maxInterval = maxInterval;\n this.#date = date;\n this.#startTime = date.now();\n this.#maxElapsedTime = maxElapsedTime;\n this.#maxIterations = maxIterations;\n }\n\n get ellapsedTimeInMsec() {\n return this.#date.now() - this.#startTime;\n }\n\n get currentInterval() {\n return this.#currentInterval;\n }\n\n get count() {\n return this.#count;\n }\n\n get randomValueFromInterval() {\n const delta = this.#randomizationFactor * this.#currentInterval;\n const min = this.#currentInterval - delta;\n const max = this.#currentInterval + delta;\n return Math.random() * (max - min) + min;\n }\n\n public incrementCurrentInterval() {\n this.#currentInterval = Math.min(this.#currentInterval * this.#multiplier, this.#maxInterval);\n this.#count++;\n\n return this.#currentInterval;\n }\n\n public next() {\n if (this.ellapsedTimeInMsec >= this.#maxElapsedTime || this.#count >= this.#maxIterations) {\n return null;\n } else {\n this.incrementCurrentInterval();\n return this.randomValueFromInterval;\n }\n }\n}\n/**\n * Utility function to create an exponential backoff iterator.\n * @param options - for the exponential backoff\n * @returns an iterator that yields the next delay in the exponential backoff\n * @yields the next delay in the exponential backoff\n */\nexport function* exponentialBackoff(\n options: ExponentialBackoffOptions = ExponentialBackoff.default,\n) {\n const backoff = new ExponentialBackoff(options);\n\n let next = backoff.next();\n while (next) {\n yield next;\n next = backoff.next();\n }\n}\n", "import { JsonObject } from '@dfinity/candid';\nimport { Principal } from '@dfinity/principal';\nimport { AgentError } from '../../errors';\nimport { AnonymousIdentity, Identity } from '../../auth';\nimport * as cbor from '../../cbor';\nimport { RequestId, hashOfMap, requestIdOf } from '../../request_id';\nimport { bufFromBufLike, concat, fromHex } from '../../utils/buffer';\nimport {\n Agent,\n ApiQueryResponse,\n QueryFields,\n QueryResponse,\n ReadStateOptions,\n ReadStateResponse,\n SubmitResponse,\n} from '../api';\nimport { Expiry, httpHeadersTransform, makeNonceTransform } from './transforms';\nimport {\n CallRequest,\n Endpoint,\n HttpAgentRequest,\n HttpAgentRequestTransformFn,\n HttpAgentSubmitRequest,\n makeNonce,\n Nonce,\n QueryRequest,\n ReadRequestType,\n SubmitRequestType,\n} from './types';\nimport { AgentHTTPResponseError } from './errors';\nimport { SubnetStatus, request } from '../../canisterStatus';\nimport {\n CertificateVerificationError,\n HashTree,\n LookupStatus,\n lookup_path,\n} from '../../certificate';\nimport { ed25519 } from '@noble/curves/ed25519';\nimport { ExpirableMap } from '../../utils/expirableMap';\nimport { Ed25519PublicKey } from '../../public_key';\nimport { decodeTime } from '../../utils/leb';\nimport { ObservableLog } from '../../observable';\nimport { BackoffStrategy, BackoffStrategyFactory, ExponentialBackoff } from '../../polling/backoff';\nexport * from './transforms';\nexport { Nonce, makeNonce } from './types';\n\nexport enum RequestStatusResponseStatus {\n Received = 'received',\n Processing = 'processing',\n Replied = 'replied',\n Rejected = 'rejected',\n Unknown = 'unknown',\n Done = 'done',\n}\n\n// Default delta for ingress expiry is 5 minutes.\nconst DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS = 5 * 60 * 1000;\n\n// Root public key for the IC, encoded as hex\nexport const IC_ROOT_KEY =\n '308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814' +\n 'c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d968' +\n '5f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484' +\n 'b01291091c5f87b98883463f98091a0baaae';\n\nexport const MANAGEMENT_CANISTER_ID = 'aaaaa-aa';\n\n// IC0 domain info\nconst IC0_DOMAIN = 'ic0.app';\nconst IC0_SUB_DOMAIN = '.ic0.app';\n\nconst ICP0_DOMAIN = 'icp0.io';\nconst ICP0_SUB_DOMAIN = '.icp0.io';\n\nconst ICP_API_DOMAIN = 'icp-api.io';\nconst ICP_API_SUB_DOMAIN = '.icp-api.io';\n\nclass HttpDefaultFetchError extends AgentError {\n constructor(public readonly message: string) {\n super(message);\n }\n}\nexport class IdentityInvalidError extends AgentError {\n constructor(public readonly message: string) {\n super(message);\n }\n}\n\n// HttpAgent options that can be used at construction.\nexport interface HttpAgentOptions {\n // Another HttpAgent to inherit configuration (pipeline and fetch) of. This\n // is only used at construction.\n source?: HttpAgent;\n\n // A surrogate to the global fetch function. Useful for testing.\n fetch?: typeof fetch;\n\n // Additional options to pass along to fetch. Will not override fields that\n // the agent already needs to set\n // Should follow the RequestInit interface, but we intentially support non-standard fields\n fetchOptions?: Record<string, unknown>;\n\n // Additional options to pass along to fetch for the call API.\n callOptions?: Record<string, unknown>;\n\n // The host to use for the client. By default, uses the same host as\n // the current page.\n host?: string;\n\n // The principal used to send messages. This cannot be empty at the request\n // time (will throw).\n identity?: Identity | Promise<Identity>;\n\n credentials?: {\n name: string;\n password?: string;\n };\n /**\n * Adds a unique {@link Nonce} with each query.\n * Enabling will prevent queries from being answered with a cached response.\n * @example\n * const agent = new HttpAgent({ useQueryNonces: true });\n * agent.addTransform(makeNonceTransform(makeNonce);\n * @default false\n */\n useQueryNonces?: boolean;\n /**\n * Number of times to retry requests before throwing an error\n * @default 3\n */\n retryTimes?: number;\n /**\n * The strategy to use for backoff when retrying requests\n */\n backoffStrategy?: BackoffStrategyFactory;\n /**\n * Whether the agent should verify signatures signed by node keys on query responses. Increases security, but adds overhead and must make a separate request to cache the node keys for the canister's subnet.\n * @default true\n */\n verifyQuerySignatures?: boolean;\n /**\n * Whether to log to the console. Defaults to false.\n */\n logToConsole?: boolean;\n}\n\nfunction getDefaultFetch(): typeof fetch {\n let defaultFetch;\n\n if (typeof window !== 'undefined') {\n // Browser context\n if (window.fetch) {\n defaultFetch = window.fetch.bind(window);\n } else {\n throw new HttpDefaultFetchError(\n 'Fetch implementation was not available. You appear to be in a browser context, but window.fetch was not present.',\n );\n }\n } else if (typeof global !== 'undefined') {\n // Node context\n if (global.fetch) {\n defaultFetch = global.fetch.bind(global);\n } else {\n throw new HttpDefaultFetchError(\n 'Fetch implementation was not available. You appear to be in a Node.js context, but global.fetch was not available.',\n );\n }\n } else if (typeof self !== 'undefined') {\n if (self.fetch) {\n defaultFetch = self.fetch.bind(self);\n }\n }\n\n if (defaultFetch) {\n return defaultFetch;\n }\n throw new HttpDefaultFetchError(\n 'Fetch implementation was not available. Please provide fetch to the HttpAgent constructor, or ensure it is available in the window or global context.',\n );\n}\n\n// A HTTP agent allows users to interact with a client of the internet computer\n// using the available methods. It exposes an API that closely follows the\n// public view of the internet computer, and is not intended to be exposed\n// directly to the majority of users due to its low-level interface.\n//\n// There is a pipeline to apply transformations to the request before sending\n// it to the client. This is to decouple signature, nonce generation and\n// other computations so that this class can stay as simple as possible while\n// allowing extensions.\nexport class HttpAgent implements Agent {\n public rootKey = fromHex(IC_ROOT_KEY);\n private _identity: Promise<Identity> | null;\n private readonly _fetch: typeof fetch;\n private readonly _fetchOptions?: Record<string, unknown>;\n private readonly _callOptions?: Record<string, unknown>;\n private _timeDiffMsecs = 0;\n private readonly _host: URL;\n private readonly _credentials: string | undefined;\n private _rootKeyFetched = false;\n #retryTimes; // Retry requests N times before erroring by default\n #backoffStrategy: BackoffStrategyFactory;\n public readonly _isAgent = true;\n\n // The UTC time in milliseconds when the latest request was made\n #waterMark = 0;\n\n get waterMark(): number {\n return this.#waterMark;\n }\n\n public log: ObservableLog = new ObservableLog();\n\n #queryPipeline: HttpAgentRequestTransformFn[] = [];\n #updatePipeline: HttpAgentRequestTransformFn[] = [];\n\n #subnetKeys: ExpirableMap<string, SubnetStatus> = new ExpirableMap({\n expirationTime: 5 * 60 * 1000, // 5 minutes\n });\n #verifyQuerySignatures = true;\n\n constructor(options: HttpAgentOptions = {}) {\n if (options.source) {\n if (!(options.source instanceof HttpAgent)) {\n throw new Error(\"An Agent's source can only be another HttpAgent\");\n }\n this._identity = options.source._identity;\n this._fetch = options.source._fetch;\n this._host = options.source._host;\n this._credentials = options.source._credentials;\n } else {\n this._fetch = options.fetch || getDefaultFetch() || fetch.bind(global);\n this._fetchOptions = options.fetchOptions;\n this._callOptions = options.callOptions;\n }\n if (options.host !== undefined) {\n if (!options.host.match(/^[a-z]+:/) && typeof window !== 'undefined') {\n this._host = new URL(window.location.protocol + '//' + options.host);\n } else {\n this._host = new URL(options.host);\n }\n } else if (options.source !== undefined) {\n // Safe to ignore here.\n this._host = options.source._host;\n } else {\n const location = typeof window !== 'undefined' ? window.location : undefined;\n if (!location) {\n this._host = new URL('https://icp-api.io');\n this.log.warn(\n 'Could not infer host from window.location, defaulting to mainnet gateway of https://icp-api.io. Please provide a host to the HttpAgent constructor to avoid this warning.',\n );\n }\n // Mainnet, local, and remote environments will have the api route available\n const knownHosts = ['ic0.app', 'icp0.io', '127.0.0.1', 'localhost'];\n const remoteHosts = ['.github.dev', '.gitpod.io'];\n const hostname = location?.hostname;\n let knownHost;\n if (hostname && typeof hostname === 'string') {\n if (remoteHosts.some(host => hostname.endsWith(host))) {\n knownHost = hostname;\n } else {\n knownHost = knownHosts.find(host => hostname.endsWith(host));\n }\n }\n\n if (location && knownHost) {\n // If the user is on a boundary-node provided host, we can use the same host for the agent\n this._host = new URL(\n `${location.protocol}//${knownHost}${location.port ? ':' + location.port : ''}`,\n );\n } else {\n this._host = new URL('https://icp-api.io');\n this.log.warn(\n 'Could not infer host from window.location, defaulting to mainnet gateway of https://icp-api.io. Please provide a host to the HttpAgent constructor to avoid this warning.',\n );\n }\n }\n if (options.verifyQuerySignatures !== undefined) {\n this.#verifyQuerySignatures = options.verifyQuerySignatures;\n }\n // Default is 3\n this.#retryTimes = options.retryTimes ?? 3;\n // Delay strategy for retries. Default is exponential backoff\n const defaultBackoffFactory = () =>\n new ExponentialBackoff({\n maxIterations: this.#retryTimes,\n });\n this.#backoffStrategy = options.backoffStrategy || defaultBackoffFactory;\n // Rewrite to avoid redirects\n if (this._host.hostname.endsWith(IC0_SUB_DOMAIN)) {\n this._host.hostname = IC0_DOMAIN;\n } else if (this._host.hostname.endsWith(ICP0_SUB_DOMAIN)) {\n this._host.hostname = ICP0_DOMAIN;\n } else if (this._host.hostname.endsWith(ICP_API_SUB_DOMAIN)) {\n this._host.hostname = ICP_API_DOMAIN;\n }\n\n if (options.credentials) {\n const { name, password } = options.credentials;\n this._credentials = `${name}${password ? ':' + password : ''}`;\n }\n this._identity = Promise.resolve(options.identity || new AnonymousIdentity());\n\n // Add a nonce transform to ensure calls are unique\n this.addTransform('update', makeNonceTransform(makeNonce));\n if (options.useQueryNonces) {\n this.addTransform('query', makeNonceTransform(makeNonce));\n }\n if (options.logToConsole) {\n this.log.subscribe(log => {\n if (log.level === 'error') {\n console.error(log.message);\n } else if (log.level === 'warn') {\n console.warn(log.message);\n } else {\n console.log(log.message);\n }\n });\n }\n }\n\n public isLocal(): boolean {\n const hostname = this._host.hostname;\n return hostname === '127.0.0.1' || hostname.endsWith('127.0.0.1');\n }\n\n public addTransform(\n type: 'update' | 'query',\n fn: HttpAgentRequestTransformFn,\n priority = fn.priority || 0,\n ): void {\n if (type === 'update') {\n // Keep the pipeline sorted at all time, by priority.\n const i = this.#updatePipeline.findIndex(x => (x.priority || 0) < priority);\n this.#updatePipeline.splice(\n i >= 0 ? i : this.#updatePipeline.length,\n 0,\n Object.assign(fn, { priority }),\n );\n } else if (type === 'query') {\n // Keep the pipeline sorted at all time, by priority.\n const i = this.#queryPipeline.findIndex(x => (x.priority || 0) < priority);\n this.#queryPipeline.splice(\n i >= 0 ? i : this.#queryPipeline.length,\n 0,\n Object.assign(fn, { priority }),\n );\n }\n }\n\n public async getPrincipal(): Promise<Principal> {\n if (!this._identity) {\n throw new IdentityInvalidError(\n \"This identity has expired due this application's security policy. Please refresh your authentication.\",\n );\n }\n return (await this._identity).getPrincipal();\n }\n\n public async call(\n canisterId: Principal | string,\n options: {\n methodName: string;\n arg: ArrayBuffer;\n effectiveCanisterId?: Principal | string;\n },\n identity?: Identity | Promise<Identity>,\n ): Promise<SubmitResponse> {\n const id = await (identity !== undefined ? await identity : await this._identity);\n if (!id) {\n throw new IdentityInvalidError(\n \"This identity has expired due this application's security policy. Please refresh your authentication.\",\n );\n }\n const canister = Principal.from(canisterId);\n const ecid = options.effectiveCanisterId\n ? Principal.from(options.effectiveCanisterId)\n : canister;\n\n const sender: Principal = id.getPrincipal() || Principal.anonymous();\n\n let ingress_expiry = new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS);\n\n // If the value is off by more than 30 seconds, reconcile system time with the network\n if (Math.abs(this._timeDiffMsecs) > 1_000 * 30) {\n ingress_expiry = new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS + this._timeDiffMsecs);\n }\n\n const submit: CallRequest = {\n request_type: SubmitRequestType.Call,\n canister_id: canister,\n method_name: options.methodName,\n arg: options.arg,\n sender,\n ingress_expiry,\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let transformedRequest: any = (await this._transform({\n request: {\n body: null,\n method: 'POST',\n headers: {\n 'Content-Type': 'application/cbor',\n ...(this._credentials ? { Authorization: 'Basic ' + btoa(this._credentials) } : {}),\n },\n },\n endpoint: Endpoint.Call,\n body: submit,\n })) as HttpAgentSubmitRequest;\n\n // Apply transform for identity.\n transformedRequest = await id.transformRequest(transformedRequest);\n\n const body = cbor.encode(transformedRequest.body);\n\n this.log.print(\n `fetching \"/api/v2/canister/${ecid.toText()}/call\" with request:`,\n transformedRequest,\n );\n\n // Run both in parallel. The fetch is quite expensive, so we have plenty of time to\n // calculate the requestId locally.\n const backoff = this.#backoffStrategy();\n const request = this.#requestAndRetry({\n request: () =>\n this._fetch('' + new URL(`/api/v2/canister/${ecid.toText()}/call`, this._host), {\n ...this._callOptions,\n ...transformedRequest.request,\n body,\n }),\n backoff,\n tries: 0,\n });\n\n const [response, requestId] = await Promise.all([request, requestIdOf(submit)]);\n\n const responseBuffer = await response.arrayBuffer();\n const responseBody = (\n response.status === 200 && responseBuffer.byteLength > 0 ? cbor.decode(responseBuffer) : null\n ) as SubmitResponse['response']['body'];\n\n return {\n requestId,\n response: {\n ok: response.ok,\n status: response.status,\n statusText: response.statusText,\n body: responseBody,\n headers: httpHeadersTransform(response.headers),\n },\n };\n }\n\n async #requestAndRetryQuery(args: {\n ecid: Principal;\n transformedRequest: HttpAgentRequest;\n body: ArrayBuffer;\n requestId: RequestId;\n backoff: BackoffStrategy;\n tries: number;\n }): Promise<ApiQueryResponse> {\n const { ecid, transformedRequest, body, requestId, backoff, tries } = args;\n\n const delay = tries === 0 ? 0 : backoff.next();\n this.log.print(`fetching \"/api/v2/canister/${ecid.toString()}/query\" with tries:`, {\n tries,\n backoff,\n delay,\n });\n\n // If delay is null, the backoff strategy is exhausted due to a maximum number of retries, duration, or other reason\n if (delay === null) {\n throw new AgentError(\n `Timestamp failed to pass the watermark after retrying the configured ${\n this.#retryTimes\n } times. We cannot guarantee the integrity of the response since it could be a replay attack.`,\n );\n }\n\n if (delay > 0) {\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n let response: ApiQueryResponse;\n // Make the request and retry if it throws an error\n try {\n this.log.print(\n `fetching \"/api/v2/canister/${ecid.toString()}/query\" with request:`,\n transformedRequest,\n );\n const fetchResponse = await this._fetch(\n '' + new URL(`/api/v2/canister/${ecid.toString()}/query`, this._host),\n {\n ...this._fetchOptions,\n ...transformedRequest.request,\n body,\n },\n );\n if (fetchResponse.status === 200) {\n const queryResponse: QueryResponse = cbor.decode(await fetchResponse.arrayBuffer());\n response = {\n ...queryResponse,\n httpDetails: {\n ok: fetchResponse.ok,\n status: fetchResponse.status,\n statusText: fetchResponse.statusText,\n headers: httpHeadersTransform(fetchResponse.headers),\n },\n requestId,\n };\n } else {\n throw new AgentHTTPResponseError(\n `Gateway returned an error:\\n` +\n ` Code: ${fetchResponse.status} (${fetchResponse.statusText})\\n` +\n ` Body: ${await fetchResponse.text()}\\n`,\n {\n ok: fetchResponse.ok,\n status: fetchResponse.status,\n statusText: fetchResponse.statusText,\n headers: httpHeadersTransform(fetchResponse.headers),\n },\n );\n }\n } catch (error) {\n if (tries < this.#retryTimes) {\n this.log.warn(\n `Caught exception while attempting to make query:\\n` +\n ` ${error}\\n` +\n ` Retrying query.`,\n );\n return await this.#requestAndRetryQuery({ ...args, tries: tries + 1 });\n }\n throw error;\n }\n\n const timestamp = response.signatures?.[0]?.timestamp;\n\n // Skip watermark verification if the user has set verifyQuerySignatures to false\n if (!this.#verifyQuerySignatures) {\n return response;\n }\n\n if (!timestamp) {\n throw new Error(\n 'Timestamp not found in query response. This suggests a malformed or malicious response.',\n );\n }\n\n // Convert the timestamp to milliseconds\n const timeStampInMs = Number(BigInt(timestamp) / BigInt(1_000_000));\n\n this.log.print('watermark and timestamp', {\n waterMark: this.waterMark,\n timestamp: timeStampInMs,\n });\n\n // If the timestamp is less than the watermark, retry the request up to the retry limit\n if (Number(this.waterMark) > timeStampInMs) {\n const error = new AgentError('Timestamp is below the watermark. Retrying query.');\n this.log.error('Timestamp is below', error, {\n timestamp,\n waterMark: this.waterMark,\n });\n if (tries < this.#retryTimes) {\n return await this.#requestAndRetryQuery({ ...args, tries: tries + 1 });\n }\n {\n throw new AgentError(\n `Timestamp failed to pass the watermark after retrying the configured ${\n this.#retryTimes\n } times. We cannot guarantee the integrity of the response since it could be a replay attack.`,\n );\n }\n }\n\n return response;\n }\n\n async #requestAndRetry(args: {\n request: () => Promise<Response>;\n backoff: BackoffStrategy;\n tries: number;\n }): Promise<Response> {\n const { request, backoff, tries } = args;\n const delay = tries === 0 ? 0 : backoff.next();\n\n // If delay is null, the backoff strategy is exhausted due to a maximum number of retries, duration, or other reason\n if (delay === null) {\n throw new AgentError(\n `Timestamp failed to pass the watermark after retrying the configured ${\n this.#retryTimes\n } times. We cannot guarantee the integrity of the response since it could be a replay attack.`,\n );\n }\n\n if (delay > 0) {\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n\n let response: Response;\n try {\n response = await request();\n } catch (error) {\n if (this.#retryTimes > tries) {\n this.log.warn(\n `Caught exception while attempting to make request:\\n` +\n ` ${error}\\n` +\n ` Retrying request.`,\n );\n // Delay the request by the configured backoff strategy\n return await this.#requestAndRetry({ request, backoff, tries: tries + 1 });\n }\n throw error;\n }\n if (response.ok) {\n return response;\n }\n\n const responseText = await response.clone().text();\n const errorMessage =\n `Server returned an error:\\n` +\n ` Code: ${response.status} (${response.statusText})\\n` +\n ` Body: ${responseText}\\n`;\n\n if (tries < this.#retryTimes) {\n return await this.#requestAndRetry({ request, backoff, tries: tries + 1 });\n }\n throw new AgentHTTPResponseError(errorMessage, {\n ok: response.ok,\n status: response.status,\n statusText: response.statusText,\n headers: httpHeadersTransform(response.headers),\n });\n }\n\n public async query(\n canisterId: Principal | string,\n fields: QueryFields,\n identity?: Identity | Promise<Identity>,\n ): Promise<ApiQueryResponse> {\n const backoff = this.#backoffStrategy();\n const ecid = fields.effectiveCanisterId\n ? Principal.from(fields.effectiveCanisterId)\n : Principal.from(canisterId);\n\n this.log.print(`ecid ${ecid.toString()}`);\n this.log.print(`canisterId ${canisterId.toString()}`);\n const makeQuery = async () => {\n const id = await (identity !== undefined ? await identity : await this._identity);\n if (!id) {\n throw new IdentityInvalidError(\n \"This identity has expired due this application's security policy. Please refresh your authentication.\",\n );\n }\n\n const canister = Principal.from(canisterId);\n const sender = id?.getPrincipal() || Principal.anonymous();\n\n const request: QueryRequest = {\n request_type: ReadRequestType.Query,\n canister_id: canister,\n method_name: fields.methodName,\n arg: fields.arg,\n sender,\n ingress_expiry: new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS),\n };\n\n const requestId = await requestIdOf(request);\n\n // TODO: remove this any. This can be a Signed or UnSigned request.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let transformedRequest: HttpAgentRequest = await this._transform({\n request: {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/cbor',\n ...(this._credentials ? { Authorization: 'Basic ' + btoa(this._credentials) } : {}),\n },\n },\n endpoint: Endpoint.Query,\n body: request,\n });\n\n // Apply transform for identity.\n transformedRequest = (await id?.transformRequest(transformedRequest)) as HttpAgentRequest;\n\n const body = cbor.encode(transformedRequest.body);\n\n const args = {\n canister: canister.toText(),\n ecid,\n transformedRequest,\n body,\n requestId,\n backoff,\n tries: 0,\n };\n\n return await this.#requestAndRetryQuery(args);\n };\n\n const getSubnetStatus = async (): Promise<SubnetStatus | void> => {\n if (!this.#verifyQuerySignatures) {\n return undefined;\n }\n const subnetStatus = this.#subnetKeys.get(ecid.toString());\n if (subnetStatus) {\n return subnetStatus;\n }\n await this.fetchSubnetKeys(ecid.toString());\n return this.#subnetKeys.get(ecid.toString());\n };\n // Attempt to make the query i=retryTimes times\n // Make query and fetch subnet keys in parallel\n const [query, subnetStatus] = await Promise.all([makeQuery(), getSubnetStatus()]);\n\n this.log.print('Query response:', query);\n // Skip verification if the user has disabled it\n if (!this.#verifyQuerySignatures) {\n return query;\n }\n\n try {\n return this.#verifyQueryResponse(query, subnetStatus);\n } catch (_) {\n // In case the node signatures have changed, refresh the subnet keys and try again\n this.log.warn('Query response verification failed. Retrying with fresh subnet keys.');\n this.#subnetKeys.delete(canisterId.toString());\n await this.fetchSubnetKeys(ecid.toString());\n\n const updatedSubnetStatus = this.#subnetKeys.get(canisterId.toString());\n if (!updatedSubnetStatus) {\n throw new CertificateVerificationError(\n 'Invalid signature from replica signed query: no matching node key found.',\n );\n }\n return this.#verifyQueryResponse(query, updatedSubnetStatus);\n }\n }\n\n /**\n * See https://internetcomputer.org/docs/current/references/ic-interface-spec/#http-query for details on validation\n * @param queryResponse - The response from the query\n * @param subnetStatus - The subnet status, including all node keys\n * @returns ApiQueryResponse\n */\n #verifyQueryResponse = (\n queryResponse: ApiQueryResponse,\n subnetStatus: SubnetStatus | void,\n ): ApiQueryResponse => {\n if (this.#verifyQuerySignatures === false) {\n // This should not be called if the user has disabled verification\n return queryResponse;\n }\n if (!subnetStatus) {\n throw new CertificateVerificationError(\n 'Invalid signature from replica signed query: no matching node key found.',\n );\n }\n const { status, signatures = [], requestId } = queryResponse;\n\n const domainSeparator = new TextEncoder().encode('\\x0Bic-response');\n for (const sig of signatures) {\n const { timestamp, identity } = sig;\n const nodeId = Principal.fromUint8Array(identity).toText();\n let hash: ArrayBuffer;\n\n // Hash is constructed differently depending on the status\n if (status === 'replied') {\n const { reply } = queryResponse;\n hash = hashOfMap({\n status: status,\n reply: reply,\n timestamp: BigInt(timestamp),\n request_id: requestId,\n });\n } else if (status === 'rejected') {\n const { reject_code, reject_message, error_code } = queryResponse;\n hash = hashOfMap({\n status: status,\n reject_code: reject_code,\n reject_message: reject_message,\n error_code: error_code,\n timestamp: BigInt(timestamp),\n request_id: requestId,\n });\n } else {\n throw new Error(`Unknown status: ${status}`);\n }\n\n const separatorWithHash = concat(domainSeparator, new Uint8Array(hash));\n\n // FIX: check for match without verifying N times\n const pubKey = subnetStatus?.nodeKeys.get(nodeId);\n if (!pubKey) {\n throw new CertificateVerificationError(\n 'Invalid signature from replica signed query: no matching node key found.',\n );\n }\n const rawKey = Ed25519PublicKey.fromDer(pubKey).rawKey;\n const valid = ed25519.verify(\n sig.signature,\n new Uint8Array(separatorWithHash),\n new Uint8Array(rawKey),\n );\n if (valid) return queryResponse;\n\n throw new CertificateVerificationError(\n `Invalid signature from replica ${nodeId} signed query.`,\n );\n }\n return queryResponse;\n };\n\n public async createReadStateRequest(\n fields: ReadStateOptions,\n identity?: Identity | Promise<Identity>,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any> {\n const id = await (identity !== undefined ? await identity : await this._identity);\n if (!id) {\n throw new IdentityInvalidError(\n \"This identity has expired due this application's security policy. Please refresh your authentication.\",\n );\n }\n const sender = id?.getPrincipal() || Principal.anonymous();\n\n // TODO: remove this any. This can be a Signed or UnSigned request.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const transformedRequest: any = await this._transform({\n request: {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/cbor',\n ...(this._credentials ? { Authorization: 'Basic ' + btoa(this._credentials) } : {}),\n },\n },\n endpoint: Endpoint.ReadState,\n body: {\n request_type: ReadRequestType.ReadState,\n paths: fields.paths,\n sender,\n ingress_expiry: new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS),\n },\n });\n\n // Apply transform for identity.\n return id?.transformRequest(transformedRequest);\n }\n\n public async readState(\n canisterId: Principal | string,\n fields: ReadStateOptions,\n identity?: Identity | Promise<Identity>,\n // eslint-disable-next-line\n request?: any,\n ): Promise<ReadStateResponse> {\n const canister = typeof canisterId === 'string' ? Principal.fromText(canisterId) : canisterId;\n\n const transformedRequest = request ?? (await this.createReadStateRequest(fields, identity));\n const body = cbor.encode(transformedRequest.body);\n\n this.log.print(\n `fetching \"/api/v2/canister/${canister}/read_state\" with request:`,\n transformedRequest,\n );\n // TODO - https://dfinity.atlassian.net/browse/SDK-1092\n const backoff = this.#backoffStrategy();\n\n const response = await this.#requestAndRetry({\n request: () =>\n this._fetch(\n '' + new URL(`/api/v2/canister/${canister.toString()}/read_state`, this._host),\n {\n ...this._fetchOptions,\n ...transformedRequest.request,\n body,\n },\n ),\n backoff,\n tries: 0,\n });\n\n if (!response.ok) {\n throw new Error(\n `Server returned an error:\\n` +\n ` Code: ${response.status} (${response.statusText})\\n` +\n ` Body: ${await response.text()}\\n`,\n );\n }\n const decodedResponse: ReadStateResponse = cbor.decode(await response.arrayBuffer());\n\n this.log.print('Read state response:', decodedResponse);\n const parsedTime = await this.parseTimeFromResponse(decodedResponse);\n if (parsedTime > 0) {\n this.log.print('Read state response time:', parsedTime);\n this.#waterMark = parsedTime;\n }\n\n return decodedResponse;\n }\n\n public async parseTimeFromResponse(response: ReadStateResponse): Promise<number> {\n let tree: HashTree;\n if (response.certificate) {\n const decoded: { tree: HashTree } | undefined = cbor.decode(response.certificate);\n if (decoded && 'tree' in decoded) {\n tree = decoded.tree;\n } else {\n throw new Error('Could not decode time from response');\n }\n const timeLookup = lookup_path(['time'], tree);\n if (timeLookup.status !== LookupStatus.Found) {\n throw new Error('Time was not found in the response or was not in its expected format.');\n }\n\n if (!(timeLookup.value instanceof ArrayBuffer) && !ArrayBuffer.isView(timeLookup)) {\n throw new Error('Time was not found in the response or was not in its expected format.');\n }\n const date = decodeTime(bufFromBufLike(timeLookup.value as ArrayBuffer));\n this.log.print('Time from response:', date);\n this.log.print('Time from response in milliseconds:', Number(date));\n return Number(date);\n } else {\n this.log.warn('No certificate found in response');\n }\n return 0;\n }\n\n /**\n * Allows agent to sync its time with the network. Can be called during intialization or mid-lifecycle if the device's clock has drifted away from the network time. This is necessary to set the Expiry for a request\n * @param {Principal} canisterId - Pass a canister ID if you need to sync the time with a particular replica. Uses the management canister by default\n */\n public async syncTime(canisterId?: Principal): Promise<void> {\n const CanisterStatus = await import('../../canisterStatus');\n const callTime = Date.now();\n try {\n if (!canisterId) {\n this.log.print(\n 'Syncing time with the IC. No canisterId provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai',\n );\n }\n const status = await CanisterStatus.request({\n // Fall back with canisterId of the ICP Ledger\n canisterId: canisterId ?? Principal.from('ryjl3-tyaaa-aaaaa-aaaba-cai'),\n agent: this,\n paths: ['time'],\n });\n\n const replicaTime = status.get('time');\n if (replicaTime) {\n this._timeDiffMsecs = Number(replicaTime as bigint) - Number(callTime);\n }\n } catch (error) {\n this.log.error('Caught exception while attempting to sync time', error as AgentError);\n }\n }\n\n public async status(): Promise<JsonObject> {\n const headers: Record<string, string> = this._credentials\n ? {\n Authorization: 'Basic ' + btoa(this._credentials),\n }\n : {};\n\n this.log.print(`fetching \"/api/v2/status\"`);\n const backoff = this.#backoffStrategy();\n const response = await this.#requestAndRetry({\n backoff,\n request: () =>\n this._fetch('' + new URL(`/api/v2/status`, this._host), { headers, ...this._fetchOptions }),\n tries: 0,\n });\n return cbor.decode(await response.arrayBuffer());\n }\n\n public async fetchRootKey(): Promise<ArrayBuffer> {\n if (!this._rootKeyFetched) {\n // Hex-encoded version of the replica root key\n this.rootKey = ((await this.status()) as JsonObject & { root_key: ArrayBuffer }).root_key;\n this._rootKeyFetched = true;\n }\n return this.rootKey;\n }\n\n public invalidateIdentity(): void {\n this._identity = null;\n }\n\n public replaceIdentity(identity: Identity): void {\n this._identity = Promise.resolve(identity);\n }\n\n public async fetchSubnetKeys(canisterId: Principal | string) {\n const effectiveCanisterId: Principal = Principal.from(canisterId);\n const response = await request({\n canisterId: effectiveCanisterId,\n paths: ['subnet'],\n agent: this,\n });\n\n const subnetResponse = response.get('subnet');\n if (subnetResponse && typeof subnetResponse === 'object' && 'nodeKeys' in subnetResponse) {\n this.#subnetKeys.set(effectiveCanisterId.toText(), subnetResponse as SubnetStatus);\n return subnetResponse as SubnetStatus;\n }\n // If the subnet status is not returned, return undefined\n return undefined;\n }\n\n protected _transform(request: HttpAgentRequest): Promise<HttpAgentRequest> {\n let p = Promise.resolve(request);\n if (request.endpoint === Endpoint.Call) {\n for (const fn of this.#updatePipeline) {\n p = p.then(r => fn(r).then(r2 => r2 || r));\n }\n } else {\n for (const fn of this.#queryPipeline) {\n p = p.then(r => fn(r).then(r2 => r2 || r));\n }\n }\n\n return p;\n }\n}\n", "import { JsonObject } from '@dfinity/candid';\nimport {\n Agent,\n ApiQueryResponse,\n CallOptions,\n QueryFields,\n QueryResponse,\n ReadStateOptions,\n ReadStateResponse,\n SubmitResponse,\n} from './api';\nimport { Principal } from '@dfinity/principal';\n\nexport enum ProxyMessageKind {\n Error = 'err',\n GetPrincipal = 'gp',\n GetPrincipalResponse = 'gpr',\n Query = 'q',\n QueryResponse = 'qr',\n Call = 'c',\n CallResponse = 'cr',\n ReadState = 'rs',\n ReadStateResponse = 'rsr',\n Status = 's',\n StatusResponse = 'sr',\n}\n\nexport interface ProxyMessageBase {\n id: number;\n type: ProxyMessageKind;\n}\n\nexport interface ProxyMessageError extends ProxyMessageBase {\n type: ProxyMessageKind.Error;\n error: any;\n}\n\nexport interface ProxyMessageGetPrincipal extends ProxyMessageBase {\n type: ProxyMessageKind.GetPrincipal;\n}\n\nexport interface ProxyMessageGetPrincipalResponse extends ProxyMessageBase {\n type: ProxyMessageKind.GetPrincipalResponse;\n response: string;\n}\n\nexport interface ProxyMessageQuery extends ProxyMessageBase {\n type: ProxyMessageKind.Query;\n args: [string, QueryFields];\n}\n\nexport interface ProxyMessageQueryResponse extends ProxyMessageBase {\n type: ProxyMessageKind.QueryResponse;\n response: QueryResponse;\n}\n\nexport interface ProxyMessageCall extends ProxyMessageBase {\n type: ProxyMessageKind.Call;\n args: [string, CallOptions];\n}\n\nexport interface ProxyMessageCallResponse extends ProxyMessageBase {\n type: ProxyMessageKind.CallResponse;\n response: SubmitResponse;\n}\n\nexport interface ProxyMessageReadState extends ProxyMessageBase {\n type: ProxyMessageKind.ReadState;\n args: [string, ReadStateOptions];\n}\n\nexport interface ProxyMessageReadStateResponse extends ProxyMessageBase {\n type: ProxyMessageKind.ReadStateResponse;\n response: ReadStateResponse;\n}\n\nexport interface ProxyMessageStatus extends ProxyMessageBase {\n type: ProxyMessageKind.Status;\n}\n\nexport interface ProxyMessageStatusResponse extends ProxyMessageBase {\n type: ProxyMessageKind.StatusResponse;\n response: JsonObject;\n}\n\nexport type ProxyMessage =\n | ProxyMessageError\n | ProxyMessageGetPrincipal\n | ProxyMessageGetPrincipalResponse\n | ProxyMessageQuery\n | ProxyMessageQueryResponse\n | ProxyMessageCall\n | ProxyMessageReadState\n | ProxyMessageReadStateResponse\n | ProxyMessageCallResponse\n | ProxyMessageStatus\n | ProxyMessageStatusResponse;\n\n// A Stub Agent that forwards calls to another Agent implementation.\nexport class ProxyStubAgent {\n constructor(private _frontend: (msg: ProxyMessage) => void, private _agent: Agent) {}\n\n public onmessage(msg: ProxyMessage): void {\n switch (msg.type) {\n case ProxyMessageKind.GetPrincipal:\n this._agent.getPrincipal().then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.GetPrincipalResponse,\n response: response.toText(),\n });\n });\n break;\n case ProxyMessageKind.Query:\n this._agent.query(...msg.args).then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.QueryResponse,\n response,\n });\n });\n break;\n case ProxyMessageKind.Call:\n this._agent.call(...msg.args).then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.CallResponse,\n response,\n });\n });\n break;\n case ProxyMessageKind.ReadState:\n this._agent.readState(...msg.args).then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.ReadStateResponse,\n response,\n });\n });\n break;\n case ProxyMessageKind.Status:\n this._agent.status().then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.StatusResponse,\n response,\n });\n });\n break;\n\n default:\n throw new Error(`Invalid message received: ${JSON.stringify(msg)}`);\n }\n }\n}\n\n// An Agent that forwards calls to a backend. The calls are serialized\nexport class ProxyAgent implements Agent {\n private _nextId = 0;\n private _pendingCalls = new Map<number, [(resolve: any) => void, (reject: any) => void]>();\n public rootKey = null;\n\n constructor(private _backend: (msg: ProxyMessage) => void) {}\n\n public onmessage(msg: ProxyMessage): void {\n const id = msg.id;\n\n const maybePromise = this._pendingCalls.get(id);\n if (!maybePromise) {\n throw new Error('A proxy get the same message twice...');\n }\n\n this._pendingCalls.delete(id);\n const [resolve, reject] = maybePromise;\n\n switch (msg.type) {\n case ProxyMessageKind.Error:\n return reject(msg.error);\n case ProxyMessageKind.GetPrincipalResponse:\n case ProxyMessageKind.CallResponse:\n case ProxyMessageKind.QueryResponse:\n case ProxyMessageKind.ReadStateResponse:\n case ProxyMessageKind.StatusResponse:\n return resolve(msg.response);\n default:\n throw new Error(`Invalid message being sent to ProxyAgent: ${JSON.stringify(msg)}`);\n }\n }\n\n public async getPrincipal(): Promise<Principal> {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.GetPrincipal,\n }).then(principal => {\n if (typeof principal !== 'string') {\n throw new Error('Invalid principal received.');\n }\n return Principal.fromText(principal);\n });\n }\n\n public readState(\n canisterId: Principal | string,\n fields: ReadStateOptions,\n ): Promise<ReadStateResponse> {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.ReadState,\n args: [canisterId.toString(), fields],\n }) as Promise<ReadStateResponse>;\n }\n\n public call(canisterId: Principal | string, fields: CallOptions): Promise<SubmitResponse> {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.Call,\n args: [canisterId.toString(), fields],\n }) as Promise<SubmitResponse>;\n }\n\n public status(): Promise<JsonObject> {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.Status,\n }) as Promise<JsonObject>;\n }\n\n public query(canisterId: Principal | string, fields: QueryFields): Promise<ApiQueryResponse> {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.Query,\n args: [canisterId.toString(), fields],\n }) as Promise<ApiQueryResponse>;\n }\n\n private async _sendAndWait(msg: ProxyMessage): Promise<unknown> {\n return new Promise((resolve, reject) => {\n this._pendingCalls.set(msg.id, [resolve, reject]);\n\n this._backend(msg);\n });\n }\n\n public async fetchRootKey(): Promise<ArrayBuffer> {\n // Hex-encoded version of the replica root key\n const rootKey = ((await this.status()) as any).root_key;\n this.rootKey = rootKey;\n return rootKey;\n }\n}\n", "import { GlobalInternetComputer } from '../index';\nimport { Agent } from './api';\n\nexport * from './api';\nexport * from './http';\nexport * from './http/errors';\nexport * from './proxy';\n\ndeclare const window: GlobalInternetComputer;\ndeclare const global: GlobalInternetComputer;\ndeclare const self: GlobalInternetComputer;\n\nexport function getDefaultAgent(): Agent {\n const agent =\n typeof window === 'undefined'\n ? typeof global === 'undefined'\n ? typeof self === 'undefined'\n ? undefined\n : self.ic.agent\n : global.ic.agent\n : window.ic.agent;\n\n if (!agent) {\n throw new Error('No Agent could be found.');\n }\n\n return agent;\n}\n", "import { Principal } from '@dfinity/principal';\nimport { RequestStatusResponseStatus } from '../agent';\nimport { toHex } from '../utils/buffer';\nimport { PollStrategy } from './index';\nimport { RequestId } from '../request_id';\n\nexport type Predicate<T> = (\n canisterId: Principal,\n requestId: RequestId,\n status: RequestStatusResponseStatus,\n) => Promise<T>;\n\nconst FIVE_MINUTES_IN_MSEC = 5 * 60 * 1000;\n\n/**\n * A best practices polling strategy: wait 2 seconds before the first poll, then 1 second\n * with an exponential backoff factor of 1.2. Timeout after 5 minutes.\n */\nexport function defaultStrategy(): PollStrategy {\n return chain(conditionalDelay(once(), 1000), backoff(1000, 1.2), timeout(FIVE_MINUTES_IN_MSEC));\n}\n\n/**\n * Predicate that returns true once.\n */\nexport function once(): Predicate<boolean> {\n let first = true;\n return async () => {\n if (first) {\n first = false;\n return true;\n }\n return false;\n };\n}\n\n/**\n * Delay the polling once.\n * @param condition A predicate that indicates when to delay.\n * @param timeInMsec The amount of time to delay.\n */\nexport function conditionalDelay(condition: Predicate<boolean>, timeInMsec: number): PollStrategy {\n return async (\n canisterId: Principal,\n requestId: RequestId,\n status: RequestStatusResponseStatus,\n ) => {\n if (await condition(canisterId, requestId, status)) {\n return new Promise(resolve => setTimeout(resolve, timeInMsec));\n }\n };\n}\n\n/**\n * Error out after a maximum number of polling has been done.\n * @param count The maximum attempts to poll.\n */\nexport function maxAttempts(count: number): PollStrategy {\n let attempts = count;\n return async (\n canisterId: Principal,\n requestId: RequestId,\n status: RequestStatusResponseStatus,\n ) => {\n if (--attempts <= 0) {\n throw new Error(\n `Failed to retrieve a reply for request after ${count} attempts:\\n` +\n ` Request ID: ${toHex(requestId)}\\n` +\n ` Request status: ${status}\\n`,\n );\n }\n };\n}\n\n/**\n * Throttle polling.\n * @param throttleInMsec Amount in millisecond to wait between each polling.\n */\nexport function throttle(throttleInMsec: number): PollStrategy {\n return () => new Promise(resolve => setTimeout(resolve, throttleInMsec));\n}\n\n/**\n * Reject a call after a certain amount of time.\n * @param timeInMsec Time in milliseconds before the polling should be rejected.\n */\nexport function timeout(timeInMsec: number): PollStrategy {\n const end = Date.now() + timeInMsec;\n return async (\n canisterId: Principal,\n requestId: RequestId,\n status: RequestStatusResponseStatus,\n ) => {\n if (Date.now() > end) {\n throw new Error(\n `Request timed out after ${timeInMsec} msec:\\n` +\n ` Request ID: ${toHex(requestId)}\\n` +\n ` Request status: ${status}\\n`,\n );\n }\n };\n}\n\n/**\n * A strategy that throttle, but using an exponential backoff strategy.\n * @param startingThrottleInMsec The throttle in milliseconds to start with.\n * @param backoffFactor The factor to multiple the throttle time between every poll. For\n * example if using 2, the throttle will double between every run.\n */\nexport function backoff(startingThrottleInMsec: number, backoffFactor: number): PollStrategy {\n let currentThrottling = startingThrottleInMsec;\n\n return () =>\n new Promise(resolve =>\n setTimeout(() => {\n currentThrottling *= backoffFactor;\n resolve();\n }, currentThrottling),\n );\n}\n\n/**\n * Chain multiple polling strategy. This _chains_ the strategies, so if you pass in,\n * say, two throttling strategy of 1 second, it will result in a throttle of 2 seconds.\n * @param strategies A strategy list to chain.\n */\nexport function chain(...strategies: PollStrategy[]): PollStrategy {\n return async (\n canisterId: Principal,\n requestId: RequestId,\n status: RequestStatusResponseStatus,\n ) => {\n for (const a of strategies) {\n await a(canisterId, requestId, status);\n }\n };\n}\n", "import { Principal } from '@dfinity/principal';\nimport { Agent, RequestStatusResponseStatus } from '../agent';\nimport { Certificate, CreateCertificateOptions, lookupResultToBuffer } from '../certificate';\nimport { RequestId } from '../request_id';\nimport { toHex } from '../utils/buffer';\n\nexport * as strategy from './strategy';\nexport { defaultStrategy } from './strategy';\nexport type PollStrategy = (\n canisterId: Principal,\n requestId: RequestId,\n status: RequestStatusResponseStatus,\n) => Promise<void>;\nexport type PollStrategyFactory = () => PollStrategy;\n\n/**\n * Polls the IC to check the status of the given request then\n * returns the response bytes once the request has been processed.\n * @param agent The agent to use to poll read_state.\n * @param canisterId The effective canister ID.\n * @param requestId The Request ID to poll status for.\n * @param strategy A polling strategy.\n * @param request Request for the readState call.\n * @param blsVerify - optional replacement function that verifies the BLS signature of a certificate.\n */\nexport async function pollForResponse(\n agent: Agent,\n canisterId: Principal,\n requestId: RequestId,\n strategy: PollStrategy,\n // eslint-disable-next-line\n request?: any,\n blsVerify?: CreateCertificateOptions['blsVerify'],\n): Promise<ArrayBuffer> {\n const path = [new TextEncoder().encode('request_status'), requestId];\n const currentRequest = request ?? (await agent.createReadStateRequest?.({ paths: [path] }));\n const state = await agent.readState(canisterId, { paths: [path] }, undefined, currentRequest);\n if (agent.rootKey == null) throw new Error('Agent root key not initialized before polling');\n const cert = await Certificate.create({\n certificate: state.certificate,\n rootKey: agent.rootKey,\n canisterId: canisterId,\n blsVerify,\n });\n const maybeBuf = lookupResultToBuffer(cert.lookup([...path, new TextEncoder().encode('status')]));\n let status;\n if (typeof maybeBuf === 'undefined') {\n // Missing requestId means we need to wait\n status = RequestStatusResponseStatus.Unknown;\n } else {\n status = new TextDecoder().decode(maybeBuf);\n }\n\n switch (status) {\n case RequestStatusResponseStatus.Replied: {\n return lookupResultToBuffer(cert.lookup([...path, 'reply']))!;\n }\n\n case RequestStatusResponseStatus.Received:\n case RequestStatusResponseStatus.Unknown:\n case RequestStatusResponseStatus.Processing:\n // Execute the polling strategy, then retry.\n await strategy(canisterId, requestId, status);\n return pollForResponse(agent, canisterId, requestId, strategy, currentRequest);\n\n case RequestStatusResponseStatus.Rejected: {\n const rejectCode = new Uint8Array(\n lookupResultToBuffer(cert.lookup([...path, 'reject_code']))!,\n )[0];\n const rejectMessage = new TextDecoder().decode(\n lookupResultToBuffer(cert.lookup([...path, 'reject_message']))!,\n );\n throw new Error(\n `Call was rejected:\\n` +\n ` Request ID: ${toHex(requestId)}\\n` +\n ` Reject code: ${rejectCode}\\n` +\n ` Reject text: ${rejectMessage}\\n`,\n );\n }\n\n case RequestStatusResponseStatus.Done:\n // This is _technically_ not an error, but we still didn't see the `Replied` status so\n // we don't know the result and cannot decode it.\n throw new Error(\n `Call was marked as done but we never saw the reply:\\n` +\n ` Request ID: ${toHex(requestId)}\\n`,\n );\n }\n throw new Error('unreachable');\n}\n", "/*\n * This file is generated from the candid for asset management.\n * didc version: 0.4.0\n */\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\n\nexport default ({ IDL }) => {\n const bitcoin_network = IDL.Variant({\n mainnet: IDL.Null,\n testnet: IDL.Null,\n });\n const bitcoin_address = IDL.Text;\n const bitcoin_get_balance_args = IDL.Record({\n network: bitcoin_network,\n address: bitcoin_address,\n min_confirmations: IDL.Opt(IDL.Nat32),\n });\n const satoshi = IDL.Nat64;\n const bitcoin_get_balance_result = satoshi;\n const bitcoin_get_current_fee_percentiles_args = IDL.Record({\n network: bitcoin_network,\n });\n const millisatoshi_per_byte = IDL.Nat64;\n const bitcoin_get_current_fee_percentiles_result = IDL.Vec(millisatoshi_per_byte);\n const bitcoin_get_utxos_args = IDL.Record({\n network: bitcoin_network,\n filter: IDL.Opt(\n IDL.Variant({\n page: IDL.Vec(IDL.Nat8),\n min_confirmations: IDL.Nat32,\n }),\n ),\n address: bitcoin_address,\n });\n const block_hash = IDL.Vec(IDL.Nat8);\n const outpoint = IDL.Record({\n txid: IDL.Vec(IDL.Nat8),\n vout: IDL.Nat32,\n });\n const utxo = IDL.Record({\n height: IDL.Nat32,\n value: satoshi,\n outpoint: outpoint,\n });\n const bitcoin_get_utxos_result = IDL.Record({\n next_page: IDL.Opt(IDL.Vec(IDL.Nat8)),\n tip_height: IDL.Nat32,\n tip_block_hash: block_hash,\n utxos: IDL.Vec(utxo),\n });\n const bitcoin_send_transaction_args = IDL.Record({\n transaction: IDL.Vec(IDL.Nat8),\n network: bitcoin_network,\n });\n const canister_id = IDL.Principal;\n const canister_info_args = IDL.Record({\n canister_id: canister_id,\n num_requested_changes: IDL.Opt(IDL.Nat64),\n });\n const change_origin = IDL.Variant({\n from_user: IDL.Record({ user_id: IDL.Principal }),\n from_canister: IDL.Record({\n canister_version: IDL.Opt(IDL.Nat64),\n canister_id: IDL.Principal,\n }),\n });\n const change_details = IDL.Variant({\n creation: IDL.Record({ controllers: IDL.Vec(IDL.Principal) }),\n code_deployment: IDL.Record({\n mode: IDL.Variant({\n reinstall: IDL.Null,\n upgrade: IDL.Null,\n install: IDL.Null,\n }),\n module_hash: IDL.Vec(IDL.Nat8),\n }),\n controllers_change: IDL.Record({\n controllers: IDL.Vec(IDL.Principal),\n }),\n code_uninstall: IDL.Null,\n });\n const change = IDL.Record({\n timestamp_nanos: IDL.Nat64,\n canister_version: IDL.Nat64,\n origin: change_origin,\n details: change_details,\n });\n const canister_info_result = IDL.Record({\n controllers: IDL.Vec(IDL.Principal),\n module_hash: IDL.Opt(IDL.Vec(IDL.Nat8)),\n recent_changes: IDL.Vec(change),\n total_num_changes: IDL.Nat64,\n });\n const canister_status_args = IDL.Record({ canister_id: canister_id });\n const log_visibility = IDL.Variant({\n controllers: IDL.Null,\n public: IDL.Null,\n });\n const definite_canister_settings = IDL.Record({\n freezing_threshold: IDL.Nat,\n controllers: IDL.Vec(IDL.Principal),\n reserved_cycles_limit: IDL.Nat,\n log_visibility: log_visibility,\n wasm_memory_limit: IDL.Nat,\n memory_allocation: IDL.Nat,\n compute_allocation: IDL.Nat,\n });\n const canister_status_result = IDL.Record({\n status: IDL.Variant({\n stopped: IDL.Null,\n stopping: IDL.Null,\n running: IDL.Null,\n }),\n memory_size: IDL.Nat,\n cycles: IDL.Nat,\n settings: definite_canister_settings,\n query_stats: IDL.Record({\n response_payload_bytes_total: IDL.Nat,\n num_instructions_total: IDL.Nat,\n num_calls_total: IDL.Nat,\n request_payload_bytes_total: IDL.Nat,\n }),\n idle_cycles_burned_per_day: IDL.Nat,\n module_hash: IDL.Opt(IDL.Vec(IDL.Nat8)),\n reserved_cycles: IDL.Nat,\n });\n const clear_chunk_store_args = IDL.Record({ canister_id: canister_id });\n const canister_settings = IDL.Record({\n freezing_threshold: IDL.Opt(IDL.Nat),\n controllers: IDL.Opt(IDL.Vec(IDL.Principal)),\n reserved_cycles_limit: IDL.Opt(IDL.Nat),\n log_visibility: IDL.Opt(log_visibility),\n wasm_memory_limit: IDL.Opt(IDL.Nat),\n memory_allocation: IDL.Opt(IDL.Nat),\n compute_allocation: IDL.Opt(IDL.Nat),\n });\n const create_canister_args = IDL.Record({\n settings: IDL.Opt(canister_settings),\n sender_canister_version: IDL.Opt(IDL.Nat64),\n });\n const create_canister_result = IDL.Record({ canister_id: canister_id });\n const delete_canister_args = IDL.Record({ canister_id: canister_id });\n const deposit_cycles_args = IDL.Record({ canister_id: canister_id });\n const ecdsa_curve = IDL.Variant({ secp256k1: IDL.Null });\n const ecdsa_public_key_args = IDL.Record({\n key_id: IDL.Record({ name: IDL.Text, curve: ecdsa_curve }),\n canister_id: IDL.Opt(canister_id),\n derivation_path: IDL.Vec(IDL.Vec(IDL.Nat8)),\n });\n const ecdsa_public_key_result = IDL.Record({\n public_key: IDL.Vec(IDL.Nat8),\n chain_code: IDL.Vec(IDL.Nat8),\n });\n const fetch_canister_logs_args = IDL.Record({ canister_id: canister_id });\n const canister_log_record = IDL.Record({\n idx: IDL.Nat64,\n timestamp_nanos: IDL.Nat64,\n content: IDL.Vec(IDL.Nat8),\n });\n const fetch_canister_logs_result = IDL.Record({\n canister_log_records: IDL.Vec(canister_log_record),\n });\n const http_header = IDL.Record({ value: IDL.Text, name: IDL.Text });\n const http_request_result = IDL.Record({\n status: IDL.Nat,\n body: IDL.Vec(IDL.Nat8),\n headers: IDL.Vec(http_header),\n });\n const http_request_args = IDL.Record({\n url: IDL.Text,\n method: IDL.Variant({\n get: IDL.Null,\n head: IDL.Null,\n post: IDL.Null,\n }),\n max_response_bytes: IDL.Opt(IDL.Nat64),\n body: IDL.Opt(IDL.Vec(IDL.Nat8)),\n transform: IDL.Opt(\n IDL.Record({\n function: IDL.Func(\n [\n IDL.Record({\n context: IDL.Vec(IDL.Nat8),\n response: http_request_result,\n }),\n ],\n [http_request_result],\n ['query'],\n ),\n context: IDL.Vec(IDL.Nat8),\n }),\n ),\n headers: IDL.Vec(http_header),\n });\n const canister_install_mode = IDL.Variant({\n reinstall: IDL.Null,\n upgrade: IDL.Opt(\n IDL.Record({\n wasm_memory_persistence: IDL.Opt(IDL.Variant({ keep: IDL.Null, replace: IDL.Null })),\n skip_pre_upgrade: IDL.Opt(IDL.Bool),\n }),\n ),\n install: IDL.Null,\n });\n const chunk_hash = IDL.Record({ hash: IDL.Vec(IDL.Nat8) });\n const install_chunked_code_args = IDL.Record({\n arg: IDL.Vec(IDL.Nat8),\n wasm_module_hash: IDL.Vec(IDL.Nat8),\n mode: canister_install_mode,\n chunk_hashes_list: IDL.Vec(chunk_hash),\n target_canister: canister_id,\n store_canister: IDL.Opt(canister_id),\n sender_canister_version: IDL.Opt(IDL.Nat64),\n });\n const wasm_module = IDL.Vec(IDL.Nat8);\n const install_code_args = IDL.Record({\n arg: IDL.Vec(IDL.Nat8),\n wasm_module: wasm_module,\n mode: canister_install_mode,\n canister_id: canister_id,\n sender_canister_version: IDL.Opt(IDL.Nat64),\n });\n const node_metrics_history_args = IDL.Record({\n start_at_timestamp_nanos: IDL.Nat64,\n subnet_id: IDL.Principal,\n });\n const node_metrics = IDL.Record({\n num_block_failures_total: IDL.Nat64,\n node_id: IDL.Principal,\n num_blocks_proposed_total: IDL.Nat64,\n });\n const node_metrics_history_result = IDL.Vec(\n IDL.Record({\n timestamp_nanos: IDL.Nat64,\n node_metrics: IDL.Vec(node_metrics),\n }),\n );\n const provisional_create_canister_with_cycles_args = IDL.Record({\n settings: IDL.Opt(canister_settings),\n specified_id: IDL.Opt(canister_id),\n amount: IDL.Opt(IDL.Nat),\n sender_canister_version: IDL.Opt(IDL.Nat64),\n });\n const provisional_create_canister_with_cycles_result = IDL.Record({\n canister_id: canister_id,\n });\n const provisional_top_up_canister_args = IDL.Record({\n canister_id: canister_id,\n amount: IDL.Nat,\n });\n const raw_rand_result = IDL.Vec(IDL.Nat8);\n const sign_with_ecdsa_args = IDL.Record({\n key_id: IDL.Record({ name: IDL.Text, curve: ecdsa_curve }),\n derivation_path: IDL.Vec(IDL.Vec(IDL.Nat8)),\n message_hash: IDL.Vec(IDL.Nat8),\n });\n const sign_with_ecdsa_result = IDL.Record({\n signature: IDL.Vec(IDL.Nat8),\n });\n const start_canister_args = IDL.Record({ canister_id: canister_id });\n const stop_canister_args = IDL.Record({ canister_id: canister_id });\n const stored_chunks_args = IDL.Record({ canister_id: canister_id });\n const stored_chunks_result = IDL.Vec(chunk_hash);\n const uninstall_code_args = IDL.Record({\n canister_id: canister_id,\n sender_canister_version: IDL.Opt(IDL.Nat64),\n });\n const update_settings_args = IDL.Record({\n canister_id: IDL.Principal,\n settings: canister_settings,\n sender_canister_version: IDL.Opt(IDL.Nat64),\n });\n const upload_chunk_args = IDL.Record({\n chunk: IDL.Vec(IDL.Nat8),\n canister_id: IDL.Principal,\n });\n const upload_chunk_result = chunk_hash;\n return IDL.Service({\n bitcoin_get_balance: IDL.Func([bitcoin_get_balance_args], [bitcoin_get_balance_result], []),\n bitcoin_get_current_fee_percentiles: IDL.Func(\n [bitcoin_get_current_fee_percentiles_args],\n [bitcoin_get_current_fee_percentiles_result],\n [],\n ),\n bitcoin_get_utxos: IDL.Func([bitcoin_get_utxos_args], [bitcoin_get_utxos_result], []),\n bitcoin_send_transaction: IDL.Func([bitcoin_send_transaction_args], [], []),\n canister_info: IDL.Func([canister_info_args], [canister_info_result], []),\n canister_status: IDL.Func([canister_status_args], [canister_status_result], []),\n clear_chunk_store: IDL.Func([clear_chunk_store_args], [], []),\n create_canister: IDL.Func([create_canister_args], [create_canister_result], []),\n delete_canister: IDL.Func([delete_canister_args], [], []),\n deposit_cycles: IDL.Func([deposit_cycles_args], [], []),\n ecdsa_public_key: IDL.Func([ecdsa_public_key_args], [ecdsa_public_key_result], []),\n fetch_canister_logs: IDL.Func(\n [fetch_canister_logs_args],\n [fetch_canister_logs_result],\n ['query'],\n ),\n http_request: IDL.Func([http_request_args], [http_request_result], []),\n install_chunked_code: IDL.Func([install_chunked_code_args], [], []),\n install_code: IDL.Func([install_code_args], [], []),\n node_metrics_history: IDL.Func([node_metrics_history_args], [node_metrics_history_result], []),\n provisional_create_canister_with_cycles: IDL.Func(\n [provisional_create_canister_with_cycles_args],\n [provisional_create_canister_with_cycles_result],\n [],\n ),\n provisional_top_up_canister: IDL.Func([provisional_top_up_canister_args], [], []),\n raw_rand: IDL.Func([], [raw_rand_result], []),\n sign_with_ecdsa: IDL.Func([sign_with_ecdsa_args], [sign_with_ecdsa_result], []),\n start_canister: IDL.Func([start_canister_args], [], []),\n stop_canister: IDL.Func([stop_canister_args], [], []),\n stored_chunks: IDL.Func([stored_chunks_args], [stored_chunks_result], []),\n uninstall_code: IDL.Func([uninstall_code_args], [], []),\n update_settings: IDL.Func([update_settings_args], [], []),\n upload_chunk: IDL.Func([upload_chunk_args], [upload_chunk_result], []),\n });\n};\n", "import { bufEquals } from '@dfinity/agent';\nimport {\n DerEncodedPublicKey,\n KeyPair,\n PublicKey,\n Signature,\n SignIdentity,\n uint8ToBuf,\n ED25519_OID,\n unwrapDER,\n wrapDER,\n fromHex,\n toHex,\n bufFromBufLike,\n} from '@dfinity/agent';\nimport { ed25519 } from '@noble/curves/ed25519';\n\ndeclare type KeyLike = PublicKey | DerEncodedPublicKey | ArrayBuffer | ArrayBufferView;\n\nfunction isObject(value: unknown) {\n return value !== null && typeof value === 'object';\n}\n\nexport class Ed25519PublicKey implements PublicKey {\n /**\n * Construct Ed25519PublicKey from an existing PublicKey\n * @param {unknown} maybeKey - existing PublicKey, ArrayBuffer, DerEncodedPublicKey, or hex string\n * @returns {Ed25519PublicKey} Instance of Ed25519PublicKey\n */\n public static from(maybeKey: unknown): Ed25519PublicKey {\n if (typeof maybeKey === 'string') {\n const key = fromHex(maybeKey);\n return this.fromRaw(key);\n } else if (isObject(maybeKey)) {\n const key = maybeKey as KeyLike;\n if (isObject(key) && Object.hasOwnProperty.call(key, '__derEncodedPublicKey__')) {\n return this.fromDer(key as DerEncodedPublicKey);\n } else if (ArrayBuffer.isView(key)) {\n const view = key as ArrayBufferView;\n return this.fromRaw(bufFromBufLike(view.buffer));\n } else if (key instanceof ArrayBuffer) {\n return this.fromRaw(key);\n } else if ('rawKey' in key) {\n return this.fromRaw(key.rawKey as ArrayBuffer);\n } else if ('derKey' in key) {\n return this.fromDer(key.derKey as DerEncodedPublicKey);\n } else if ('toDer' in key) {\n return this.fromDer(key.toDer() as ArrayBuffer);\n }\n }\n throw new Error('Cannot construct Ed25519PublicKey from the provided key.');\n }\n\n public static fromRaw(rawKey: ArrayBuffer): Ed25519PublicKey {\n return new Ed25519PublicKey(rawKey);\n }\n\n public static fromDer(derKey: DerEncodedPublicKey): Ed25519PublicKey {\n return new Ed25519PublicKey(this.derDecode(derKey));\n }\n\n // The length of Ed25519 public keys is always 32 bytes.\n private static RAW_KEY_LENGTH = 32;\n\n private static derEncode(publicKey: ArrayBuffer): DerEncodedPublicKey {\n const key = wrapDER(publicKey, ED25519_OID).buffer as DerEncodedPublicKey;\n key.__derEncodedPublicKey__ = undefined;\n return key;\n }\n\n private static derDecode(key: DerEncodedPublicKey): ArrayBuffer {\n const unwrapped = unwrapDER(key, ED25519_OID);\n if (unwrapped.length !== this.RAW_KEY_LENGTH) {\n throw new Error('An Ed25519 public key must be exactly 32bytes long');\n }\n return unwrapped;\n }\n\n #rawKey: ArrayBuffer;\n\n public get rawKey(): ArrayBuffer {\n return this.#rawKey;\n }\n\n #derKey: DerEncodedPublicKey;\n\n public get derKey(): DerEncodedPublicKey {\n return this.#derKey;\n }\n\n // `fromRaw` and `fromDer` should be used for instantiation, not this constructor.\n private constructor(key: ArrayBuffer) {\n if (key.byteLength !== Ed25519PublicKey.RAW_KEY_LENGTH) {\n throw new Error('An Ed25519 public key must be exactly 32bytes long');\n }\n this.#rawKey = key;\n this.#derKey = Ed25519PublicKey.derEncode(key);\n }\n\n public toDer(): DerEncodedPublicKey {\n return this.derKey;\n }\n\n public toRaw(): ArrayBuffer {\n return this.rawKey;\n }\n}\n\n/**\n * Ed25519KeyIdentity is an implementation of SignIdentity that uses Ed25519 keys. This class is used to sign and verify messages for an agent.\n */\nexport class Ed25519KeyIdentity extends SignIdentity {\n /**\n * Generate a new Ed25519KeyIdentity.\n * @param seed a 32-byte seed for the private key. If not provided, a random seed will be generated.\n * @returns Ed25519KeyIdentity\n */\n public static generate(seed?: Uint8Array): Ed25519KeyIdentity {\n\n if (seed && seed.length !== 32) {\n throw new Error('Ed25519 Seed needs to be 32 bytes long.');\n }\n if (!seed) seed = ed25519.utils.randomPrivateKey();\n // Check if the seed is all zeros\n if(bufEquals(seed, new Uint8Array(new Array(32).fill(0)))) {\n console.warn('Seed is all zeros. This is not a secure seed. Please provide a seed with sufficient entropy if this is a production environment.');\n }\n const sk = new Uint8Array(32);\n for (let i = 0; i < 32; i++) sk[i] = new Uint8Array(seed)[i];\n\n const pk = ed25519.getPublicKey(sk);\n return Ed25519KeyIdentity.fromKeyPair(pk, sk);\n }\n\n public static fromParsedJson(obj: JsonnableEd25519KeyIdentity): Ed25519KeyIdentity {\n const [publicKeyDer, privateKeyRaw] = obj;\n return new Ed25519KeyIdentity(\n Ed25519PublicKey.fromDer(fromHex(publicKeyDer) as DerEncodedPublicKey),\n fromHex(privateKeyRaw),\n );\n }\n\n public static fromJSON(json: string): Ed25519KeyIdentity {\n const parsed = JSON.parse(json);\n if (Array.isArray(parsed)) {\n if (typeof parsed[0] === 'string' && typeof parsed[1] === 'string') {\n return this.fromParsedJson([parsed[0], parsed[1]]);\n } else {\n throw new Error('Deserialization error: JSON must have at least 2 items.');\n }\n }\n throw new Error(`Deserialization error: Invalid JSON type for string: ${JSON.stringify(json)}`);\n }\n\n public static fromKeyPair(publicKey: ArrayBuffer, privateKey: ArrayBuffer): Ed25519KeyIdentity {\n return new Ed25519KeyIdentity(Ed25519PublicKey.fromRaw(publicKey), privateKey);\n }\n\n public static fromSecretKey(secretKey: ArrayBuffer): Ed25519KeyIdentity {\n const publicKey = ed25519.getPublicKey(new Uint8Array(secretKey));\n return Ed25519KeyIdentity.fromKeyPair(publicKey, secretKey);\n }\n\n #publicKey: Ed25519PublicKey;\n #privateKey: Uint8Array;\n\n // `fromRaw` and `fromDer` should be used for instantiation, not this constructor.\n protected constructor(publicKey: PublicKey, privateKey: ArrayBuffer) {\n super();\n this.#publicKey = Ed25519PublicKey.from(publicKey);\n this.#privateKey = new Uint8Array(privateKey);\n }\n\n /**\n * Serialize this key to JSON.\n */\n public toJSON(): JsonnableEd25519KeyIdentity {\n return [toHex(this.#publicKey.toDer()), toHex(this.#privateKey)];\n }\n\n /**\n * Return a copy of the key pair.\n */\n public getKeyPair(): KeyPair {\n return {\n secretKey: this.#privateKey,\n publicKey: this.#publicKey,\n };\n }\n\n /**\n * Return the public key.\n */\n public getPublicKey(): Required<PublicKey> {\n return this.#publicKey;\n }\n\n /**\n * Signs a blob of data, with this identity's private key.\n * @param challenge - challenge to sign with this identity's secretKey, producing a signature\n */\n public async sign(challenge: ArrayBuffer): Promise<Signature> {\n const blob = new Uint8Array(challenge);\n // Some implementations of Ed25519 private keys append a public key to the end of the private key. We only want the private key.\n const signature = uint8ToBuf(ed25519.sign(blob, this.#privateKey.slice(0, 32)));\n // add { __signature__: void; } to the signature to make it compatible with the agent\n\n Object.defineProperty(signature, '__signature__', {\n enumerable: false,\n value: undefined,\n });\n\n return signature as Signature;\n }\n\n /**\n * Verify\n * @param sig - signature to verify\n * @param msg - message to verify\n * @param pk - public key\n * @returns - true if the signature is valid, false otherwise\n */\n public static verify(\n sig: ArrayBuffer | Uint8Array | string,\n msg: ArrayBuffer | Uint8Array | string,\n pk: ArrayBuffer | Uint8Array | string,\n ) {\n const [signature, message, publicKey] = [sig, msg, pk].map(x => {\n if (typeof x === 'string') {\n x = fromHex(x);\n }\n if (x instanceof Uint8Array) {\n x = x.buffer;\n }\n return new Uint8Array(x);\n });\n return ed25519.verify(message, signature, publicKey);\n }\n}\n\ntype PublicKeyHex = string;\ntype SecretKeyHex = string;\nexport type JsonnableEd25519KeyIdentity = [PublicKeyHex, SecretKeyHex];\n", "import { DerEncodedPublicKey, PublicKey, Signature, SignIdentity } from '@dfinity/agent';\n\n/**\n * Options used in a {@link ECDSAKeyIdentity}\n */\nexport type CryptoKeyOptions = {\n extractable?: boolean;\n keyUsages?: KeyUsage[];\n subtleCrypto?: SubtleCrypto;\n};\n\nexport class CryptoError extends Error {\n constructor(public readonly message: string) {\n super(message);\n Object.setPrototypeOf(this, CryptoError.prototype);\n }\n}\n\nexport interface DerCryptoKey extends CryptoKey {\n toDer: () => DerEncodedPublicKey;\n}\n\n/**\n * Utility method to ensure that a subtleCrypto implementation is provided or is available in the global context\n * @param subtleCrypto SubtleCrypto implementation\n * @returns subleCrypto\n */\nfunction _getEffectiveCrypto(subtleCrypto: CryptoKeyOptions['subtleCrypto']): SubtleCrypto {\n if (typeof global !== 'undefined' && global['crypto'] && global['crypto']['subtle']) {\n return global['crypto']['subtle'];\n }\n if (subtleCrypto) {\n return subtleCrypto;\n } else if (typeof crypto !== 'undefined' && crypto['subtle']) {\n return crypto.subtle;\n } else {\n throw new CryptoError(\n 'Global crypto was not available and none was provided. Please inlcude a SubtleCrypto implementation. See https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto',\n );\n }\n}\n\n/**\n * An identity interface that wraps an ECDSA keypair using the P-256 named curve. Supports DER-encoding and decoding for agent calls\n */\nexport class ECDSAKeyIdentity extends SignIdentity {\n /**\n * Generates a randomly generated identity for use in calls to the Internet Computer.\n * @param {CryptoKeyOptions} options optional settings\n * @param {CryptoKeyOptions['extractable']} options.extractable - whether the key should allow itself to be used. Set to false for maximum security.\n * @param {CryptoKeyOptions['keyUsages']} options.keyUsages - a list of key usages that the key can be used for\n * @param {CryptoKeyOptions['subtleCrypto']} options.subtleCrypto interface\n * @constructs ECDSAKeyIdentity\n * @returns a {@link ECDSAKeyIdentity}\n */\n public static async generate(options?: CryptoKeyOptions): Promise<ECDSAKeyIdentity> {\n const { extractable = false, keyUsages = ['sign', 'verify'], subtleCrypto } = options ?? {};\n const effectiveCrypto = _getEffectiveCrypto(subtleCrypto);\n const keyPair = await effectiveCrypto.generateKey(\n {\n name: 'ECDSA',\n namedCurve: 'P-256',\n },\n extractable,\n keyUsages,\n );\n const derKey = (await effectiveCrypto.exportKey(\n 'spki',\n keyPair.publicKey,\n )) as DerEncodedPublicKey;\n\n return new this(keyPair, derKey, effectiveCrypto);\n }\n\n /**\n * generates an identity from a public and private key. Please ensure that you are generating these keys securely and protect the user's private key\n * @param keyPair a CryptoKeyPair\n * @param subtleCrypto - a SubtleCrypto interface in case one is not available globally\n * @returns an {@link ECDSAKeyIdentity}\n */\n public static async fromKeyPair(\n keyPair: CryptoKeyPair | { privateKey: CryptoKey; publicKey: CryptoKey },\n subtleCrypto?: SubtleCrypto,\n ): Promise<ECDSAKeyIdentity> {\n const effectiveCrypto = _getEffectiveCrypto(subtleCrypto);\n const derKey = (await effectiveCrypto.exportKey(\n 'spki',\n keyPair.publicKey,\n )) as DerEncodedPublicKey;\n return new ECDSAKeyIdentity(keyPair, derKey, effectiveCrypto);\n }\n\n protected _derKey: DerEncodedPublicKey;\n protected _keyPair: CryptoKeyPair;\n protected _subtleCrypto: SubtleCrypto;\n\n // `fromKeyPair` and `generate` should be used for instantiation, not this constructor.\n protected constructor(\n keyPair: CryptoKeyPair,\n derKey: DerEncodedPublicKey,\n subtleCrypto: SubtleCrypto,\n ) {\n super();\n this._keyPair = keyPair;\n this._derKey = derKey;\n this._subtleCrypto = subtleCrypto;\n }\n\n /**\n * Return the internally-used key pair.\n * @returns a CryptoKeyPair\n */\n public getKeyPair(): CryptoKeyPair {\n return this._keyPair;\n }\n\n /**\n * Return the public key.\n * @returns an {@link PublicKey & DerCryptoKey}\n */\n public getPublicKey(): PublicKey & DerCryptoKey {\n const derKey = this._derKey;\n const key: DerCryptoKey = Object.create(this._keyPair.publicKey);\n key.toDer = function () {\n return derKey;\n };\n\n return key;\n }\n\n /**\n * Signs a blob of data, with this identity's private key.\n * @param {ArrayBuffer} challenge - challenge to sign with this identity's secretKey, producing a signature\n * @returns {Promise<Signature>} signature\n */\n public async sign(challenge: ArrayBuffer): Promise<Signature> {\n const params: EcdsaParams = {\n name: 'ECDSA',\n hash: { name: 'SHA-256' },\n };\n this._keyPair.privateKey;\n const signature = await this._subtleCrypto.sign(params, this._keyPair.privateKey, challenge);\n\n return signature as Signature;\n }\n}\n\nexport default ECDSAKeyIdentity;\n", "import {\n DerEncodedPublicKey,\n fromHex,\n HttpAgentRequest,\n PublicKey,\n requestIdOf,\n Signature,\n SignIdentity,\n toHex,\n} from '@dfinity/agent';\nimport { Principal } from '@dfinity/principal';\nimport * as cbor from 'simple-cbor';\nimport { PartialIdentity } from './partial';\n\nconst domainSeparator = new TextEncoder().encode('\\x1Aic-request-auth-delegation');\nconst requestDomainSeparator = new TextEncoder().encode('\\x0Aic-request');\n\nfunction _parseBlob(value: unknown): ArrayBuffer {\n if (typeof value !== 'string' || value.length < 64) {\n throw new Error('Invalid public key.');\n }\n\n return fromHex(value);\n}\n\n/**\n * A single delegation object that is signed by a private key. This is constructed by\n * `DelegationChain.create()`.\n *\n * {@see DelegationChain}\n */\nexport class Delegation {\n constructor(\n public readonly pubkey: ArrayBuffer,\n public readonly expiration: bigint,\n public readonly targets?: Principal[],\n ) {}\n\n public toCBOR(): cbor.CborValue {\n // Expiration field needs to be encoded as a u64 specifically.\n return cbor.value.map({\n pubkey: cbor.value.bytes(this.pubkey),\n expiration: cbor.value.u64(this.expiration.toString(16), 16),\n ...(this.targets && {\n targets: cbor.value.array(this.targets.map(t => cbor.value.bytes(t.toUint8Array()))),\n }),\n });\n }\n\n public toJSON(): JsonnableDelegation {\n // every string should be hex and once-de-hexed,\n // discoverable what it is (e.g. de-hex to get JSON with a 'type' property, or de-hex to DER\n // with an OID). After de-hex, if it's not obvious what it is, it's an ArrayBuffer.\n return {\n expiration: this.expiration.toString(16),\n pubkey: toHex(this.pubkey),\n ...(this.targets && { targets: this.targets.map(p => p.toHex()) }),\n };\n }\n}\n\n/**\n * Type of ReturnType<Delegation.toJSON>.\n * The goal here is to stringify all non-JSON-compatible types to some bytes representation we can\n * stringify as hex.\n * (Hex shouldn't be ambiguous ever, because you can encode as DER with semantic OIDs).\n */\ninterface JsonnableDelegation {\n // A BigInt of Nanoseconds since epoch as hex\n expiration: string;\n // Hexadecimal representation of the DER public key.\n pubkey: string;\n // Array of strings, where each string is hex of principal blob (*NOT* textual representation).\n targets?: string[];\n}\n\n/**\n * A signed delegation, which lends its identity to the public key in the delegation\n * object. This is constructed by `DelegationChain.create()`.\n *\n * {@see DelegationChain}\n */\nexport interface SignedDelegation {\n delegation: Delegation;\n signature: Signature;\n}\n\n/**\n * Sign a single delegation object for a period of time.\n * @param from The identity that lends its delegation.\n * @param to The identity that receives the delegation.\n * @param expiration An expiration date for this delegation.\n * @param targets Limit this delegation to the target principals.\n */\nasync function _createSingleDelegation(\n from: SignIdentity,\n to: PublicKey,\n expiration: Date,\n targets?: Principal[],\n): Promise<SignedDelegation> {\n const delegation: Delegation = new Delegation(\n to.toDer(),\n BigInt(+expiration) * BigInt(1000000), // In nanoseconds.\n targets,\n );\n // The signature is calculated by signing the concatenation of the domain separator\n // and the message.\n // Note: To ensure Safari treats this as a user gesture, ensure to not use async methods\n // besides the actualy webauthn functionality (such as `sign`). Safari will de-register\n // a user gesture if you await an async call thats not fetch, xhr, or setTimeout.\n const challenge = new Uint8Array([\n ...domainSeparator,\n ...new Uint8Array(requestIdOf(delegation)),\n ]);\n const signature = await from.sign(challenge);\n\n return {\n delegation,\n signature,\n };\n}\n\nexport interface JsonnableDelegationChain {\n publicKey: string;\n delegations: Array<{\n signature: string;\n delegation: {\n pubkey: string;\n expiration: string;\n targets?: string[];\n };\n }>;\n}\n\n/**\n * A chain of delegations. This is JSON Serializable.\n * This is the object to serialize and pass to a DelegationIdentity. It does not keep any\n * private keys.\n */\nexport class DelegationChain {\n /**\n * Create a delegation chain between two (or more) keys. By default, the expiration time\n * will be very short (15 minutes).\n *\n * To build a chain of more than 2 identities, this function needs to be called multiple times,\n * passing the previous delegation chain into the options argument. For example:\n * @example\n * const rootKey = createKey();\n * const middleKey = createKey();\n * const bottomeKey = createKey();\n *\n * const rootToMiddle = await DelegationChain.create(\n * root, middle.getPublicKey(), Date.parse('2100-01-01'),\n * );\n * const middleToBottom = await DelegationChain.create(\n * middle, bottom.getPublicKey(), Date.parse('2100-01-01'), { previous: rootToMiddle },\n * );\n *\n * // We can now use a delegation identity that uses the delegation above:\n * const identity = DelegationIdentity.fromDelegation(bottomKey, middleToBottom);\n * @param from The identity that will delegate.\n * @param to The identity that gets delegated. It can now sign messages as if it was the\n * identity above.\n * @param expiration The length the delegation is valid. By default, 15 minutes from calling\n * this function.\n * @param options A set of options for this delegation. expiration and previous\n * @param options.previous - Another DelegationChain that this chain should start with.\n * @param options.targets - targets that scope the delegation (e.g. Canister Principals)\n */\n public static async create(\n from: SignIdentity,\n to: PublicKey,\n expiration: Date = new Date(Date.now() + 15 * 60 * 1000),\n options: {\n previous?: DelegationChain;\n targets?: Principal[];\n } = {},\n ): Promise<DelegationChain> {\n const delegation = await _createSingleDelegation(from, to, expiration, options.targets);\n return new DelegationChain(\n [...(options.previous?.delegations || []), delegation],\n options.previous?.publicKey || from.getPublicKey().toDer(),\n );\n }\n\n /**\n * Creates a DelegationChain object from a JSON string.\n * @param json The JSON string to parse.\n */\n public static fromJSON(json: string | JsonnableDelegationChain): DelegationChain {\n const { publicKey, delegations } = typeof json === 'string' ? JSON.parse(json) : json;\n if (!Array.isArray(delegations)) {\n throw new Error('Invalid delegations.');\n }\n\n const parsedDelegations: SignedDelegation[] = delegations.map(signedDelegation => {\n const { delegation, signature } = signedDelegation;\n const { pubkey, expiration, targets } = delegation;\n if (targets !== undefined && !Array.isArray(targets)) {\n throw new Error('Invalid targets.');\n }\n\n return {\n delegation: new Delegation(\n _parseBlob(pubkey),\n BigInt('0x' + expiration), // expiration in JSON is an hexa string (See toJSON() below).\n targets &&\n targets.map((t: unknown) => {\n if (typeof t !== 'string') {\n throw new Error('Invalid target.');\n }\n return Principal.fromHex(t);\n }),\n ),\n signature: _parseBlob(signature) as Signature,\n };\n });\n\n return new this(parsedDelegations, _parseBlob(publicKey) as DerEncodedPublicKey);\n }\n\n /**\n * Creates a DelegationChain object from a list of delegations and a DER-encoded public key.\n * @param delegations The list of delegations.\n * @param publicKey The DER-encoded public key of the key-pair signing the first delegation.\n */\n public static fromDelegations(\n delegations: SignedDelegation[],\n publicKey: DerEncodedPublicKey,\n ): DelegationChain {\n return new this(delegations, publicKey);\n }\n\n protected constructor(\n public readonly delegations: SignedDelegation[],\n public readonly publicKey: DerEncodedPublicKey,\n ) {}\n\n public toJSON(): JsonnableDelegationChain {\n return {\n delegations: this.delegations.map(signedDelegation => {\n const { delegation, signature } = signedDelegation;\n const { targets } = delegation;\n return {\n delegation: {\n expiration: delegation.expiration.toString(16),\n pubkey: toHex(delegation.pubkey),\n ...(targets && {\n targets: targets.map(t => t.toHex()),\n }),\n },\n signature: toHex(signature),\n };\n }),\n publicKey: toHex(this.publicKey),\n };\n }\n}\n\n/**\n * An Identity that adds delegation to a request. Everywhere in this class, the name\n * innerKey refers to the SignIdentity that is being used to sign the requests, while\n * originalKey is the identity that is being borrowed. More identities can be used\n * in the middle to delegate.\n */\nexport class DelegationIdentity extends SignIdentity {\n /**\n * Create a delegation without having access to delegateKey.\n * @param key The key used to sign the reqyests.\n * @param delegation A delegation object created using `createDelegation`.\n */\n public static fromDelegation(\n key: Pick<SignIdentity, 'sign'>,\n delegation: DelegationChain,\n ): DelegationIdentity {\n return new this(key, delegation);\n }\n\n protected constructor(\n private _inner: Pick<SignIdentity, 'sign'>,\n private _delegation: DelegationChain,\n ) {\n super();\n }\n\n public getDelegation(): DelegationChain {\n return this._delegation;\n }\n\n public getPublicKey(): PublicKey {\n return {\n derKey: this._delegation.publicKey,\n toDer: () => this._delegation.publicKey,\n };\n }\n public sign(blob: ArrayBuffer): Promise<Signature> {\n return this._inner.sign(blob);\n }\n\n public async transformRequest(request: HttpAgentRequest): Promise<unknown> {\n const { body, ...fields } = request;\n const requestId = await requestIdOf(body);\n return {\n ...fields,\n body: {\n content: body,\n sender_sig: await this.sign(\n new Uint8Array([...requestDomainSeparator, ...new Uint8Array(requestId)]),\n ),\n sender_delegation: this._delegation.delegations,\n sender_pubkey: this._delegation.publicKey,\n },\n };\n }\n}\n\n/**\n * A partial delegated identity, representing a delegation chain and the public key that it targets\n */\nexport class PartialDelegationIdentity extends PartialIdentity {\n #delegation: DelegationChain;\n\n /**\n * The Delegation Chain of this identity.\n */\n get delegation(): DelegationChain {\n return this.#delegation;\n }\n\n private constructor(inner: PublicKey, delegation: DelegationChain) {\n super(inner);\n this.#delegation = delegation;\n }\n\n /**\n * Create a {@link PartialDelegationIdentity} from a {@link PublicKey} and a {@link DelegationChain}.\n * @param key The {@link PublicKey} to delegate to.\n * @param delegation a {@link DelegationChain} targeting the inner key.\n * @constructs PartialDelegationIdentity\n */\n public static fromDelegation(key: PublicKey, delegation: DelegationChain) {\n return new PartialDelegationIdentity(key, delegation);\n }\n}\n\n/**\n * List of things to check for a delegation chain validity.\n */\nexport interface DelegationValidChecks {\n /**\n * Check that the scope is amongst the scopes that this delegation has access to.\n */\n scope?: Principal | string | Array<Principal | string>;\n}\n\n/**\n * Analyze a DelegationChain and validate that it's valid, ie. not expired and apply to the\n * scope.\n * @param chain The chain to validate.\n * @param checks Various checks to validate on the chain.\n */\nexport function isDelegationValid(chain: DelegationChain, checks?: DelegationValidChecks): boolean {\n // Verify that the no delegation is expired. If any are in the chain, returns false.\n for (const { delegation } of chain.delegations) {\n // prettier-ignore\n if (+new Date(Number(delegation.expiration / BigInt(1000000))) <= +Date.now()) {\n return false;\n }\n }\n\n // Check the scopes.\n const scopes: Principal[] = [];\n const maybeScope = checks?.scope;\n if (maybeScope) {\n if (Array.isArray(maybeScope)) {\n scopes.push(...maybeScope.map(s => (typeof s === 'string' ? Principal.fromText(s) : s)));\n } else {\n scopes.push(typeof maybeScope === 'string' ? Principal.fromText(maybeScope) : maybeScope);\n }\n }\n\n for (const s of scopes) {\n const scope = s.toText();\n for (const { delegation } of chain.delegations) {\n if (delegation.targets === undefined) {\n continue;\n }\n\n let none = true;\n for (const target of delegation.targets) {\n if (target.toText() === scope) {\n none = false;\n break;\n }\n }\n if (none) {\n return false;\n }\n }\n }\n\n return true;\n}\n", "import { Identity, PublicKey } from '@dfinity/agent';\nimport { Principal } from '@dfinity/principal';\n\n/**\n * A partial delegated identity, representing a delegation chain and the public key that it targets\n */\nexport class PartialIdentity implements Identity {\n #inner: PublicKey;\n\n /**\n * The raw public key of this identity.\n */\n get rawKey(): ArrayBuffer | undefined {\n return this.#inner.rawKey;\n }\n\n /**\n * The DER-encoded public key of this identity.\n */\n get derKey(): ArrayBuffer | undefined {\n return this.#inner.derKey;\n }\n\n /**\n * The DER-encoded public key of this identity.\n */\n public toDer(): ArrayBuffer {\n return this.#inner.toDer();\n }\n\n /**\n * The inner {@link PublicKey} used by this identity.\n */\n public getPublicKey(): PublicKey {\n return this.#inner;\n }\n\n /**\n * The {@link Principal} of this identity.\n */\n public getPrincipal(): Principal {\n return Principal.from(this.#inner.rawKey);\n }\n\n /**\n * Required for the Identity interface, but cannot implemented for just a public key.\n */\n public transformRequest(): Promise<never> {\n return Promise.reject(\n 'Not implemented. You are attempting to use a partial identity to sign calls, but this identity only has access to the public key.To sign calls, use a DelegationIdentity instead.',\n );\n }\n\n constructor(inner: PublicKey) {\n this.#inner = inner;\n }\n}\n", "import {\n DerEncodedPublicKey,\n PublicKey,\n Signature,\n SignIdentity,\n wrapDER,\n DER_COSE_OID,\n fromHex,\n toHex,\n} from '@dfinity/agent';\nimport borc from 'borc';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { bufFromBufLike } from '@dfinity/candid';\n\nfunction _coseToDerEncodedBlob(cose: ArrayBuffer): DerEncodedPublicKey {\n return wrapDER(cose, DER_COSE_OID).buffer as DerEncodedPublicKey;\n}\n\ntype PublicKeyCredentialWithAttachment = PublicKeyCredential & {\n // Extends `PublicKeyCredential` with an optional field introduced in the WebAuthn level 3 spec:\n // https://w3c.github.io/webauthn/#dom-publickeycredential-authenticatorattachment\n // Already supported by Chrome, Safari and Edge\n // Note: `null` is included here as a possible value because Edge set this value to null in the\n // past.\n authenticatorAttachment: AuthenticatorAttachment | undefined | null;\n};\n\n/**\n * From the documentation;\n * The authData is a byte array described in the spec. Parsing it will involve slicing bytes from\n * the array and converting them into usable objects.\n *\n * See https://webauthn.guide/#registration (subsection \"Example: Parsing the authenticator data\").\n * @param authData The authData field of the attestation response.\n * @returns The COSE key of the authData.\n */\nfunction _authDataToCose(authData: ArrayBuffer): ArrayBuffer {\n const dataView = new DataView(new ArrayBuffer(2));\n const idLenBytes = authData.slice(53, 55);\n [...new Uint8Array(idLenBytes)].forEach((v, i) => dataView.setUint8(i, v));\n const credentialIdLength = dataView.getUint16(0);\n\n // Get the public key object.\n return authData.slice(55 + credentialIdLength);\n}\n\nexport class CosePublicKey implements PublicKey {\n protected _encodedKey: DerEncodedPublicKey;\n\n public constructor(protected _cose: ArrayBuffer) {\n this._encodedKey = _coseToDerEncodedBlob(_cose);\n }\n\n public toDer(): DerEncodedPublicKey {\n return this._encodedKey;\n }\n\n public getCose(): ArrayBuffer {\n return this._cose;\n }\n}\n\n/**\n * Create a challenge from a string or array. The default challenge is always the same\n * because we don't need to verify the authenticity of the key on the server (we don't\n * register our keys with the IC). Any challenge would do, even one per key, randomly\n * generated.\n * @param challenge The challenge to transform into a byte array. By default a hard\n * coded string.\n */\nfunction _createChallengeBuffer(challenge: string | Uint8Array = '<ic0.app>'): Uint8Array {\n if (typeof challenge === 'string') {\n return Uint8Array.from(challenge, c => c.charCodeAt(0));\n } else {\n return challenge;\n }\n}\n\n/**\n * Create a credentials to authenticate with a server. This is necessary in order in\n * WebAuthn to get credentials IDs (which give us the public key and allow us to\n * sign), but in the case of the Internet Computer, we don't actually need to register\n * it, so we don't.\n * @param credentialCreationOptions an optional CredentialCreationOptions object\n */\nasync function _createCredential(\n credentialCreationOptions?: CredentialCreationOptions,\n): Promise<PublicKeyCredentialWithAttachment | null> {\n const creds = (await navigator.credentials.create(\n credentialCreationOptions ?? {\n publicKey: {\n authenticatorSelection: {\n userVerification: 'preferred',\n },\n attestation: 'direct',\n challenge: _createChallengeBuffer(),\n pubKeyCredParams: [{ type: 'public-key', alg: PubKeyCoseAlgo.ECDSA_WITH_SHA256 }],\n rp: {\n name: 'Internet Identity Service',\n },\n user: {\n id: randomBytes(16),\n name: 'Internet Identity',\n displayName: 'Internet Identity',\n },\n },\n },\n )) as PublicKeyCredentialWithAttachment | null;\n\n if (creds === null) {\n return null;\n }\n\n return {\n // do _not_ use ...creds here, as creds is not enumerable in all cases\n id: creds.id,\n response: creds.response,\n type: creds.type,\n authenticatorAttachment: creds.authenticatorAttachment,\n getClientExtensionResults: creds.getClientExtensionResults,\n // Some password managers will return a Uint8Array, so we ensure we return an ArrayBuffer.\n rawId: bufFromBufLike(creds.rawId),\n };\n}\n\n// See https://www.iana.org/assignments/cose/cose.xhtml#algorithms for a complete\n// list of these algorithms. We only list the ones we support here.\nenum PubKeyCoseAlgo {\n ECDSA_WITH_SHA256 = -7,\n}\n\n/**\n * A SignIdentity that uses `navigator.credentials`. See https://webauthn.guide/ for\n * more information about WebAuthentication.\n */\nexport class WebAuthnIdentity extends SignIdentity {\n /**\n * Create an identity from a JSON serialization.\n * @param json - json to parse\n */\n public static fromJSON(json: string): WebAuthnIdentity {\n const { publicKey, rawId } = JSON.parse(json);\n\n if (typeof publicKey !== 'string' || typeof rawId !== 'string') {\n throw new Error('Invalid JSON string.');\n }\n\n return new this(fromHex(rawId), fromHex(publicKey), undefined);\n }\n\n /**\n * Create an identity.\n * @param credentialCreationOptions an optional CredentialCreationOptions Challenge\n */\n public static async create(\n credentialCreationOptions?: CredentialCreationOptions,\n ): Promise<WebAuthnIdentity> {\n const creds = await _createCredential(credentialCreationOptions);\n\n if (!creds || creds.type !== 'public-key') {\n throw new Error('Could not create credentials.');\n }\n\n const response = creds.response as AuthenticatorAttestationResponse;\n if (response.attestationObject === undefined) {\n throw new Error('Was expecting an attestation response.');\n }\n\n // Parse the attestationObject as CBOR.\n const attObject = borc.decodeFirst(new Uint8Array(response.attestationObject));\n\n return new this(\n creds.rawId,\n _authDataToCose(attObject.authData),\n creds.authenticatorAttachment ?? undefined,\n );\n }\n\n protected _publicKey: CosePublicKey;\n\n public constructor(\n public readonly rawId: ArrayBuffer,\n cose: ArrayBuffer,\n protected authenticatorAttachment: AuthenticatorAttachment | undefined,\n ) {\n super();\n this._publicKey = new CosePublicKey(cose);\n }\n\n public getPublicKey(): PublicKey {\n return this._publicKey;\n }\n\n /**\n * WebAuthn level 3 spec introduces a new attribute on successful WebAuthn interactions,\n * see https://w3c.github.io/webauthn/#dom-publickeycredential-authenticatorattachment.\n * This attribute is already implemented for Chrome, Safari and Edge.\n *\n * Given the attribute is only available after a successful interaction, the information is\n * provided opportunistically and might also be `undefined`.\n */\n public getAuthenticatorAttachment(): AuthenticatorAttachment | undefined {\n return this.authenticatorAttachment;\n }\n\n public async sign(blob: ArrayBuffer): Promise<Signature> {\n const result = (await navigator.credentials.get({\n publicKey: {\n allowCredentials: [\n {\n type: 'public-key',\n id: this.rawId,\n },\n ],\n challenge: blob,\n userVerification: 'preferred',\n },\n })) as PublicKeyCredentialWithAttachment;\n\n if (result.authenticatorAttachment !== null) {\n this.authenticatorAttachment = result.authenticatorAttachment;\n }\n\n const response = result.response as AuthenticatorAssertionResponse;\n\n const cbor = borc.encode(\n new borc.Tagged(55799, {\n authenticator_data: new Uint8Array(response.authenticatorData),\n client_data_json: new TextDecoder().decode(response.clientDataJSON),\n signature: new Uint8Array(response.signature),\n }),\n );\n if (!cbor) {\n throw new Error('failed to encode cbor');\n }\n return cbor.buffer as Signature;\n }\n\n /**\n * Allow for JSON serialization of all information needed to reuse this identity.\n */\n public toJSON(): JsonnableWebAuthnIdentity {\n return {\n publicKey: toHex(this._publicKey.getCose()),\n rawId: toHex(this.rawId),\n };\n }\n}\n\n/**\n * ReturnType<WebAuthnIdentity.toJSON>\n */\nexport interface JsonnableWebAuthnIdentity {\n // The hexadecimal representation of the DER encoded public key.\n publicKey: string;\n // The string representation of the local WebAuthn Credential.id (base64url encoded).\n rawId: string;\n}\n", "/** @module IdleManager */\ntype IdleCB = () => unknown;\nexport type IdleManagerOptions = {\n /**\n * Callback after the user has gone idle\n */\n onIdle?: IdleCB;\n /**\n * timeout in ms\n * @default 30 minutes [600_000]\n */\n idleTimeout?: number;\n /**\n * capture scroll events\n * @default false\n */\n captureScroll?: boolean;\n /**\n * scroll debounce time in ms\n * @default 100\n */\n scrollDebounce?: number;\n};\n\nconst events = ['mousedown', 'mousemove', 'keydown', 'touchstart', 'wheel'];\n\n/**\n * Detects if the user has been idle for a duration of `idleTimeout` ms, and calls `onIdle` and registered callbacks.\n * By default, the IdleManager will log a user out after 10 minutes of inactivity.\n * To override these defaults, you can pass an `onIdle` callback, or configure a custom `idleTimeout` in milliseconds\n */\nexport class IdleManager {\n callbacks: IdleCB[] = [];\n idleTimeout: IdleManagerOptions['idleTimeout'] = 10 * 60 * 1000;\n timeoutID?: number = undefined;\n\n /**\n * Creates an {@link IdleManager}\n * @param {IdleManagerOptions} options Optional configuration\n * @see {@link IdleManagerOptions}\n * @param options.onIdle Callback once user has been idle. Use to prompt for fresh login, and use `Actor.agentOf(your_actor).invalidateIdentity()` to protect the user\n * @param options.idleTimeout timeout in ms\n * @param options.captureScroll capture scroll events\n * @param options.scrollDebounce scroll debounce time in ms\n */\n public static create(\n options: {\n /**\n * Callback after the user has gone idle\n * @see {@link IdleCB}\n */\n onIdle?: () => unknown;\n /**\n * timeout in ms\n * @default 10 minutes [600_000]\n */\n idleTimeout?: number;\n /**\n * capture scroll events\n * @default false\n */\n captureScroll?: boolean;\n /**\n * scroll debounce time in ms\n * @default 100\n */\n scrollDebounce?: number;\n } = {},\n ): IdleManager {\n return new this(options);\n }\n\n /**\n * @protected\n * @param options {@link IdleManagerOptions}\n */\n protected constructor(options: IdleManagerOptions = {}) {\n const { onIdle, idleTimeout = 10 * 60 * 1000 } = options || {};\n\n this.callbacks = onIdle ? [onIdle] : [];\n this.idleTimeout = idleTimeout;\n\n const _resetTimer = this._resetTimer.bind(this);\n\n window.addEventListener('load', _resetTimer, true);\n\n events.forEach(function (name) {\n document.addEventListener(name, _resetTimer, true);\n });\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n const debounce = (func: Function, wait: number) => {\n let timeout: number | undefined;\n return (...args: unknown[]) => {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const context = this;\n const later = function () {\n timeout = undefined;\n func.apply(context, args);\n };\n clearTimeout(timeout);\n timeout = window.setTimeout(later, wait);\n };\n };\n\n if (options?.captureScroll) {\n // debounce scroll events\n const scroll = debounce(_resetTimer, options?.scrollDebounce ?? 100);\n window.addEventListener('scroll', scroll, true);\n }\n\n _resetTimer();\n }\n\n /**\n * @param {IdleCB} callback function to be called when user goes idle\n */\n public registerCallback(callback: IdleCB): void {\n this.callbacks.push(callback);\n }\n\n /**\n * Cleans up the idle manager and its listeners\n */\n public exit(): void {\n clearTimeout(this.timeoutID);\n window.removeEventListener('load', this._resetTimer, true);\n\n const _resetTimer = this._resetTimer.bind(this);\n events.forEach(function (name) {\n document.removeEventListener(name, _resetTimer, true);\n });\n this.callbacks.forEach(cb => cb());\n }\n\n /**\n * Resets the timeouts during cleanup\n */\n _resetTimer(): void {\n const exit = this.exit.bind(this);\n window.clearTimeout(this.timeoutID);\n this.timeoutID = window.setTimeout(exit, this.idleTimeout);\n }\n}\n", "const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n", "import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);\n });\n }\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event.newVersion, event));\n }\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking) {\n db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));\n }\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event));\n }\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n", "import { openDB, IDBPDatabase } from 'idb';\nimport { DB_VERSION, isBrowser, KEY_STORAGE_DELEGATION, KEY_STORAGE_KEY } from './storage';\n\ntype Database = IDBPDatabase<unknown>;\ntype IDBValidKey = string | number | Date | BufferSource | IDBValidKey[];\nconst AUTH_DB_NAME = 'auth-client-db';\nconst OBJECT_STORE_NAME = 'ic-keyval';\n\nconst _openDbStore = async (\n dbName = AUTH_DB_NAME,\n storeName = OBJECT_STORE_NAME,\n version: number,\n) => {\n // Clear legacy stored delegations\n if (isBrowser && localStorage?.getItem(KEY_STORAGE_DELEGATION)) {\n localStorage.removeItem(KEY_STORAGE_DELEGATION);\n localStorage.removeItem(KEY_STORAGE_KEY);\n }\n return await openDB(dbName, version, {\n upgrade: database => {\n database.objectStoreNames;\n if (database.objectStoreNames.contains(storeName)) {\n database.clear(storeName);\n }\n database.createObjectStore(storeName);\n },\n });\n};\n\nasync function _getValue<T>(\n db: Database,\n storeName: string,\n key: IDBValidKey,\n): Promise<T | undefined> {\n return await db.get(storeName, key);\n}\n\nasync function _setValue<T>(\n db: Database,\n storeName: string,\n key: IDBValidKey,\n value: T,\n): Promise<IDBValidKey> {\n return await db.put(storeName, value, key);\n}\n\nasync function _removeValue(db: Database, storeName: string, key: IDBValidKey): Promise<void> {\n return await db.delete(storeName, key);\n}\n\nexport type DBCreateOptions = {\n dbName?: string;\n storeName?: string;\n version?: number;\n};\n\n/**\n * Simple Key Value store\n * Defaults to `'auth-client-db'` with an object store of `'ic-keyval'`\n */\nexport class IdbKeyVal {\n /**\n * @param {DBCreateOptions} options - DBCreateOptions\n * @param {DBCreateOptions['dbName']} options.dbName name for the indexeddb database\n * @default\n * @param {DBCreateOptions['storeName']} options.storeName name for the indexeddb Data Store\n * @default\n * @param {DBCreateOptions['version']} options.version version of the database. Increment to safely upgrade\n * @constructs an {@link IdbKeyVal}\n */\n public static async create(options?: DBCreateOptions): Promise<IdbKeyVal> {\n const { dbName = AUTH_DB_NAME, storeName = OBJECT_STORE_NAME, version = DB_VERSION } = options ?? {};\n const db = await _openDbStore(dbName, storeName, version);\n return new IdbKeyVal(db, storeName);\n }\n\n // Do not use - instead prefer create\n private constructor(private _db: Database, private _storeName: string) {}\n\n /**\n * Basic setter\n * @param {IDBValidKey} key string | number | Date | BufferSource | IDBValidKey[]\n * @param value value to set\n * @returns void\n */\n public async set<T>(key: IDBValidKey, value: T) {\n return await _setValue<T>(this._db, this._storeName, key, value);\n }\n /**\n * Basic getter\n * Pass in a type T for type safety if you know the type the value will have if it is found\n * @param {IDBValidKey} key string | number | Date | BufferSource | IDBValidKey[]\n * @returns `Promise<T | null>`\n * @example\n * await get<string>('exampleKey') -> 'exampleValue'\n */\n public async get<T>(key: IDBValidKey): Promise<T | null> {\n return (await _getValue<T>(this._db, this._storeName, key)) ?? null;\n }\n\n /**\n * Remove a key\n * @param key {@link IDBValidKey}\n * @returns void\n */\n public async remove(key: IDBValidKey) {\n return await _removeValue(this._db, this._storeName, key);\n }\n}\n", "import { DBCreateOptions, IdbKeyVal } from './db';\n\nexport const KEY_STORAGE_KEY = 'identity';\nexport const KEY_STORAGE_DELEGATION = 'delegation';\nexport const KEY_VECTOR = 'iv';\n// Increment if any fields are modified\nexport const DB_VERSION = 1;\n\nexport const isBrowser = typeof window !== 'undefined';\n\nexport type StoredKey = string | CryptoKeyPair;\n\n/**\n * Interface for persisting user authentication data\n */\nexport interface AuthClientStorage {\n get(key: string): Promise<StoredKey | null>;\n\n set(key: string, value: StoredKey): Promise<void>;\n\n remove(key: string): Promise<void>;\n}\n\n/**\n * Legacy implementation of AuthClientStorage, for use where IndexedDb is not available\n */\nexport class LocalStorage implements AuthClientStorage {\n constructor(public readonly prefix = 'ic-', private readonly _localStorage?: Storage) {}\n\n public get(key: string): Promise<string | null> {\n return Promise.resolve(this._getLocalStorage().getItem(this.prefix + key));\n }\n\n public set(key: string, value: string): Promise<void> {\n this._getLocalStorage().setItem(this.prefix + key, value);\n return Promise.resolve();\n }\n\n public remove(key: string): Promise<void> {\n this._getLocalStorage().removeItem(this.prefix + key);\n return Promise.resolve();\n }\n\n private _getLocalStorage() {\n if (this._localStorage) {\n return this._localStorage;\n }\n\n const ls =\n typeof window === 'undefined'\n ? typeof global === 'undefined'\n ? typeof self === 'undefined'\n ? undefined\n : self.localStorage\n : global.localStorage\n : window.localStorage;\n\n if (!ls) {\n throw new Error('Could not find local storage.');\n }\n\n return ls;\n }\n}\n\n/**\n * IdbStorage is an interface for simple storage of string key-value pairs built on {@link IdbKeyVal}\n *\n * It replaces {@link LocalStorage}\n * @see implements {@link AuthClientStorage}\n */\nexport class IdbStorage implements AuthClientStorage {\n #options: DBCreateOptions;\n\n /**\n * @param options - DBCreateOptions\n * @param options.dbName - name for the indexeddb database\n * @param options.storeName - name for the indexeddb Data Store\n * @param options.version - version of the database. Increment to safely upgrade\n * @constructs an {@link IdbStorage}\n * @example\n * ```typescript\n * const storage = new IdbStorage({ dbName: 'my-db', storeName: 'my-store', version: 2 });\n * ```\n */\n constructor(options?: DBCreateOptions) {\n this.#options = options ?? {};\n }\n\n // Initializes a KeyVal on first request\n private initializedDb: IdbKeyVal | undefined;\n get _db(): Promise<IdbKeyVal> {\n return new Promise(resolve => {\n if (this.initializedDb) {\n resolve(this.initializedDb);\n return;\n }\n IdbKeyVal.create(this.#options).then(db => {\n this.initializedDb = db;\n resolve(db);\n });\n });\n }\n\n public async get<T = string>(key: string): Promise<T | null> {\n const db = await this._db;\n return await db.get<T>(key);\n // return (await db.get<string>(key)) ?? null;\n }\n\n public async set<T = string>(key: string, value: T): Promise<void> {\n const db = await this._db;\n await db.set(key, value);\n }\n\n public async remove(key: string): Promise<void> {\n const db = await this._db;\n await db.remove(key);\n }\n}\n", "/** @module AuthClient */\nimport {\n AnonymousIdentity,\n DerEncodedPublicKey,\n Identity,\n Signature,\n SignIdentity,\n} from '@dfinity/agent';\nimport {\n Delegation,\n DelegationChain,\n isDelegationValid,\n DelegationIdentity,\n Ed25519KeyIdentity,\n ECDSAKeyIdentity,\n PartialDelegationIdentity,\n} from '@dfinity/identity';\nimport { Principal } from '@dfinity/principal';\nimport { IdleManager, IdleManagerOptions } from './idleManager';\nimport {\n AuthClientStorage,\n IdbStorage,\n isBrowser,\n KEY_STORAGE_DELEGATION,\n KEY_STORAGE_KEY,\n KEY_VECTOR,\n LocalStorage,\n} from './storage';\nimport { PartialIdentity } from '@dfinity/identity/lib/cjs/identity/partial';\n\nexport { AuthClientStorage, IdbStorage, LocalStorage, KEY_STORAGE_DELEGATION, KEY_STORAGE_KEY } from './storage';\nexport { IdbKeyVal, DBCreateOptions } from './db';\n\nconst IDENTITY_PROVIDER_DEFAULT = 'https://identity.ic0.app';\nconst IDENTITY_PROVIDER_ENDPOINT = '#authorize';\n\nconst ECDSA_KEY_LABEL = 'ECDSA';\nconst ED25519_KEY_LABEL = 'Ed25519';\ntype BaseKeyType = typeof ECDSA_KEY_LABEL | typeof ED25519_KEY_LABEL;\n\nconst INTERRUPT_CHECK_INTERVAL = 500;\n\nexport const ERROR_USER_INTERRUPT = 'UserInterrupt';\n\n/**\n * List of options for creating an {@link AuthClient}.\n */\nexport interface AuthClientCreateOptions {\n /**\n * An identity to use as the base\n */\n identity?: SignIdentity | PartialIdentity;\n /**\n * Optional storage with get, set, and remove. Uses {@link IdbStorage} by default\n */\n storage?: AuthClientStorage;\n /**\n * type to use for the base key\n * @default 'ECDSA'\n * If you are using a custom storage provider that does not support CryptoKey storage,\n * you should use 'Ed25519' as the key type, as it can serialize to a string\n */\n keyType?: BaseKeyType;\n\n /**\n * Options to handle idle timeouts\n * @default after 30 minutes, invalidates the identity\n */\n idleOptions?: IdleOptions;\n}\n\nexport interface IdleOptions extends IdleManagerOptions {\n /**\n * Disables idle functionality for {@link IdleManager}\n * @default false\n */\n disableIdle?: boolean;\n\n /**\n * Disables default idle behavior - call logout & reload window\n * @default false\n */\n disableDefaultIdleCallback?: boolean;\n}\n\nexport * from './idleManager';\n\nexport type OnSuccessFunc =\n | (() => void | Promise<void>)\n | ((message: InternetIdentityAuthResponseSuccess) => void | Promise<void>);\n\nexport type OnErrorFunc = (error?: string) => void | Promise<void>;\n\nexport interface AuthClientLoginOptions {\n /**\n * Identity provider\n * @default \"https://identity.ic0.app\"\n */\n identityProvider?: string | URL;\n /**\n * Expiration of the authentication in nanoseconds\n * @default BigInt(8) hours * BigInt(3_600_000_000_000) nanoseconds\n */\n maxTimeToLive?: bigint;\n /**\n * If present, indicates whether or not the Identity Provider should allow the user to authenticate and/or register using a temporary key/PIN identity. Authenticating dapps may want to prevent users from using Temporary keys/PIN identities because Temporary keys/PIN identities are less secure than Passkeys (webauthn credentials) and because Temporary keys/PIN identities generally only live in a browser database (which may get cleared by the browser/OS).\n */\n allowPinAuthentication?: boolean;\n /**\n * Origin for Identity Provider to use while generating the delegated identity. For II, the derivation origin must authorize this origin by setting a record at `<derivation-origin>/.well-known/ii-alternative-origins`.\n * @see https://github.com/dfinity/internet-identity/blob/main/docs/internet-identity-spec.adoc\n */\n derivationOrigin?: string | URL;\n /**\n * Auth Window feature config string\n * @example \"toolbar=0,location=0,menubar=0,width=500,height=500,left=100,top=100\"\n */\n windowOpenerFeatures?: string;\n /**\n * Callback once login has completed\n */\n onSuccess?: OnSuccessFunc;\n /**\n * Callback in case authentication fails\n */\n onError?: OnErrorFunc;\n /**\n * Extra values to be passed in the login request during the authorize-ready phase\n */\n customValues?: Record<string, unknown>;\n}\n\ninterface InternetIdentityAuthRequest {\n kind: 'authorize-client';\n sessionPublicKey: Uint8Array;\n maxTimeToLive?: bigint;\n allowPinAuthentication?: boolean;\n derivationOrigin?: string;\n}\n\nexport interface InternetIdentityAuthResponseSuccess {\n kind: 'authorize-client-success';\n delegations: {\n delegation: {\n pubkey: Uint8Array;\n expiration: bigint;\n targets?: Principal[];\n };\n signature: Uint8Array;\n }[];\n userPublicKey: Uint8Array;\n authnMethod: 'passkey' | 'pin' | 'recovery';\n}\n\ninterface AuthReadyMessage {\n kind: 'authorize-ready';\n}\n\ninterface AuthResponseSuccess {\n kind: 'authorize-client-success';\n delegations: {\n delegation: {\n pubkey: Uint8Array;\n expiration: bigint;\n targets?: Principal[];\n };\n signature: Uint8Array;\n }[];\n userPublicKey: Uint8Array;\n authnMethod: 'passkey' | 'pin' | 'recovery';\n}\n\ninterface AuthResponseFailure {\n kind: 'authorize-client-failure';\n text: string;\n}\n\ntype IdentityServiceResponseMessage = AuthReadyMessage | AuthResponse;\ntype AuthResponse = AuthResponseSuccess | AuthResponseFailure;\n\n/**\n * Tool to manage authentication and identity\n * @see {@link AuthClient}\n */\nexport class AuthClient {\n /**\n * Create an AuthClient to manage authentication and identity\n * @constructs\n * @param {AuthClientCreateOptions} options - Options for creating an {@link AuthClient}\n * @see {@link AuthClientCreateOptions}\n * @param options.identity Optional Identity to use as the base\n * @see {@link SignIdentity}\n * @param options.storage Storage mechanism for delegration credentials\n * @see {@link AuthClientStorage}\n * @param options.keyType Type of key to use for the base key\n * @param {IdleOptions} options.idleOptions Configures an {@link IdleManager}\n * @see {@link IdleOptions}\n * Default behavior is to clear stored identity and reload the page when a user goes idle, unless you set the disableDefaultIdleCallback flag or pass in a custom idle callback.\n * @example\n * const authClient = await AuthClient.create({\n * idleOptions: {\n * disableIdle: true\n * }\n * })\n */\n public static async create(\n options: {\n /**\n * An {@link SignIdentity} or {@link PartialIdentity} to authenticate via delegation.\n */\n identity?: SignIdentity | PartialIdentity;\n /**\n * {@link AuthClientStorage}\n * @description Optional storage with get, set, and remove. Uses {@link IdbStorage} by default\n */\n storage?: AuthClientStorage;\n /**\n * type to use for the base key\n * @default 'ECDSA'\n * If you are using a custom storage provider that does not support CryptoKey storage,\n * you should use 'Ed25519' as the key type, as it can serialize to a string\n */\n keyType?: BaseKeyType;\n /**\n * Options to handle idle timeouts\n * @default after 10 minutes, invalidates the identity\n */\n idleOptions?: IdleOptions;\n } = {},\n ): Promise<AuthClient> {\n const storage = options.storage ?? new IdbStorage();\n const keyType = options.keyType ?? ECDSA_KEY_LABEL;\n\n let key: null | SignIdentity | PartialIdentity = null;\n if (options.identity) {\n key = options.identity;\n } else {\n let maybeIdentityStorage = await storage.get(KEY_STORAGE_KEY);\n if (!maybeIdentityStorage && isBrowser) {\n // Attempt to migrate from localstorage\n try {\n const fallbackLocalStorage = new LocalStorage();\n const localChain = await fallbackLocalStorage.get(KEY_STORAGE_DELEGATION);\n const localKey = await fallbackLocalStorage.get(KEY_STORAGE_KEY);\n // not relevant for Ed25519\n if (localChain && localKey && keyType === ECDSA_KEY_LABEL) {\n console.log('Discovered an identity stored in localstorage. Migrating to IndexedDB');\n await storage.set(KEY_STORAGE_DELEGATION, localChain);\n await storage.set(KEY_STORAGE_KEY, localKey);\n\n maybeIdentityStorage = localChain;\n // clean up\n await fallbackLocalStorage.remove(KEY_STORAGE_DELEGATION);\n await fallbackLocalStorage.remove(KEY_STORAGE_KEY);\n }\n } catch (error) {\n console.error('error while attempting to recover localstorage: ' + error);\n }\n }\n if (maybeIdentityStorage) {\n try {\n if (typeof maybeIdentityStorage === 'object') {\n if (keyType === ED25519_KEY_LABEL && typeof maybeIdentityStorage === 'string') {\n key = await Ed25519KeyIdentity.fromJSON(maybeIdentityStorage);\n } else {\n key = await ECDSAKeyIdentity.fromKeyPair(maybeIdentityStorage);\n }\n } else if (typeof maybeIdentityStorage === 'string') {\n // This is a legacy identity, which is a serialized Ed25519KeyIdentity.\n key = Ed25519KeyIdentity.fromJSON(maybeIdentityStorage);\n }\n } catch (e) {\n // Ignore this, this means that the localStorage value isn't a valid Ed25519KeyIdentity or ECDSAKeyIdentity\n // serialization.\n }\n }\n }\n\n let identity: SignIdentity | PartialIdentity = new AnonymousIdentity() as PartialIdentity;\n let chain: null | DelegationChain = null;\n if (key) {\n try {\n const chainStorage = await storage.get(KEY_STORAGE_DELEGATION);\n if (typeof chainStorage === 'object' && chainStorage !== null) {\n throw new Error(\n 'Delegation chain is incorrectly stored. A delegation chain should be stored as a string.',\n );\n }\n\n if (options.identity) {\n identity = options.identity;\n } else if (chainStorage) {\n chain = DelegationChain.fromJSON(chainStorage);\n\n // Verify that the delegation isn't expired.\n if (!isDelegationValid(chain)) {\n await _deleteStorage(storage);\n key = null;\n } else {\n // If the key is a public key, then we create a PartialDelegationIdentity.\n if ('toDer' in key) {\n identity = PartialDelegationIdentity.fromDelegation(key, chain);\n // otherwise, we create a DelegationIdentity.\n } else {\n identity = DelegationIdentity.fromDelegation(key, chain);\n }\n }\n }\n } catch (e) {\n console.error(e);\n // If there was a problem loading the chain, delete the key.\n await _deleteStorage(storage);\n key = null;\n }\n }\n let idleManager: IdleManager | undefined = undefined;\n if (options.idleOptions?.disableIdle) {\n idleManager = undefined;\n }\n // if there is a delegation chain or provided identity, setup idleManager\n else if (chain || options.identity) {\n idleManager = IdleManager.create(options.idleOptions);\n }\n\n if (!key) {\n // Create a new key (whether or not one was in storage).\n if (keyType === ED25519_KEY_LABEL) {\n key = await Ed25519KeyIdentity.generate();\n await storage.set(KEY_STORAGE_KEY, JSON.stringify((key as Ed25519KeyIdentity).toJSON()));\n } else {\n if (options.storage && keyType === ECDSA_KEY_LABEL) {\n console.warn(\n `You are using a custom storage provider that may not support CryptoKey storage. If you are using a custom storage provider that does not support CryptoKey storage, you should use '${ED25519_KEY_LABEL}' as the key type, as it can serialize to a string`,\n );\n }\n key = await ECDSAKeyIdentity.generate();\n await storage.set(KEY_STORAGE_KEY, (key as ECDSAKeyIdentity).getKeyPair());\n }\n }\n\n return new this(identity, key, chain, storage, idleManager, options);\n }\n\n protected constructor(\n private _identity: Identity | PartialIdentity,\n private _key: SignIdentity | PartialIdentity,\n private _chain: DelegationChain | null,\n private _storage: AuthClientStorage,\n public idleManager: IdleManager | undefined,\n private _createOptions: AuthClientCreateOptions | undefined,\n // A handle on the IdP window.\n private _idpWindow?: Window,\n // The event handler for processing events from the IdP.\n private _eventHandler?: (event: MessageEvent) => void,\n ) {\n this._registerDefaultIdleCallback();\n }\n\n private _registerDefaultIdleCallback() {\n const idleOptions = this._createOptions?.idleOptions;\n /**\n * Default behavior is to clear stored identity and reload the page.\n * By either setting the disableDefaultIdleCallback flag or passing in a custom idle callback, we will ignore this config\n */\n if (!idleOptions?.onIdle && !idleOptions?.disableDefaultIdleCallback) {\n this.idleManager?.registerCallback(() => {\n this.logout();\n location.reload();\n });\n }\n }\n\n private async _handleSuccess(\n message: InternetIdentityAuthResponseSuccess,\n onSuccess?: OnSuccessFunc,\n ) {\n const delegations = message.delegations.map(signedDelegation => {\n return {\n delegation: new Delegation(\n signedDelegation.delegation.pubkey,\n signedDelegation.delegation.expiration,\n signedDelegation.delegation.targets,\n ),\n signature: signedDelegation.signature.buffer as Signature,\n };\n });\n\n const delegationChain = DelegationChain.fromDelegations(\n delegations,\n message.userPublicKey.buffer as DerEncodedPublicKey,\n );\n\n const key = this._key;\n if (!key) {\n return;\n }\n\n this._chain = delegationChain;\n\n if ('toDer' in key) {\n this._identity = PartialDelegationIdentity.fromDelegation(key, this._chain);\n } else {\n this._identity = DelegationIdentity.fromDelegation(key, this._chain);\n }\n\n this._idpWindow?.close();\n const idleOptions = this._createOptions?.idleOptions;\n // create the idle manager on a successful login if we haven't disabled it\n // and it doesn't already exist.\n if (!this.idleManager && !idleOptions?.disableIdle) {\n this.idleManager = IdleManager.create(idleOptions);\n this._registerDefaultIdleCallback();\n }\n\n this._removeEventListener();\n delete this._idpWindow;\n\n if (this._chain) {\n await this._storage.set(KEY_STORAGE_DELEGATION, JSON.stringify(this._chain.toJSON()));\n }\n\n // onSuccess should be the last thing to do to avoid consumers\n // interfering by navigating or refreshing the page\n onSuccess?.(message);\n }\n\n public getIdentity(): Identity {\n return this._identity;\n }\n\n public async isAuthenticated(): Promise<boolean> {\n return !this.getIdentity().getPrincipal().isAnonymous() && this._chain !== null;\n }\n\n /**\n * AuthClient Login -\n * Opens up a new window to authenticate with Internet Identity\n * @param {AuthClientLoginOptions} options - Options for logging in\n * @param options.identityProvider Identity provider\n * @param options.maxTimeToLive Expiration of the authentication in nanoseconds\n * @param options.allowPinAuthentication If present, indicates whether or not the Identity Provider should allow the user to authenticate and/or register using a temporary key/PIN identity. Authenticating dapps may want to prevent users from using Temporary keys/PIN identities because Temporary keys/PIN identities are less secure than Passkeys (webauthn credentials) and because Temporary keys/PIN identities generally only live in a browser database (which may get cleared by the browser/OS).\n * @param options.derivationOrigin Origin for Identity Provider to use while generating the delegated identity\n * @param options.windowOpenerFeatures Configures the opened authentication window\n * @param options.onSuccess Callback once login has completed\n * @param options.onError Callback in case authentication fails\n * @example\n * const authClient = await AuthClient.create();\n * authClient.login({\n * identityProvider: 'http://<canisterID>.127.0.0.1:8000',\n * maxTimeToLive: BigInt (7) * BigInt(24) * BigInt(3_600_000_000_000), // 1 week\n * windowOpenerFeatures: \"toolbar=0,location=0,menubar=0,width=500,height=500,left=100,top=100\",\n * onSuccess: () => {\n * console.log('Login Successful!');\n * },\n * onError: (error) => {\n * console.error('Login Failed: ', error);\n * }\n * });\n */\n public async login(options?: AuthClientLoginOptions): Promise<void> {\n // Set default maxTimeToLive to 8 hours\n const defaultTimeToLive = /* hours */ BigInt(8) * /* nanoseconds */ BigInt(3_600_000_000_000);\n\n // Create the URL of the IDP. (e.g. https://XXXX/#authorize)\n const identityProviderUrl = new URL(\n options?.identityProvider?.toString() || IDENTITY_PROVIDER_DEFAULT,\n );\n // Set the correct hash if it isn't already set.\n identityProviderUrl.hash = IDENTITY_PROVIDER_ENDPOINT;\n\n // If `login` has been called previously, then close/remove any previous windows\n // and event listeners.\n this._idpWindow?.close();\n this._removeEventListener();\n\n // Add an event listener to handle responses.\n this._eventHandler = this._getEventHandler(identityProviderUrl, {\n maxTimeToLive: options?.maxTimeToLive ?? defaultTimeToLive,\n ...options,\n });\n window.addEventListener('message', this._eventHandler);\n\n // Open a new window with the IDP provider.\n this._idpWindow =\n window.open(identityProviderUrl.toString(), 'idpWindow', options?.windowOpenerFeatures) ??\n undefined;\n\n // Check if the _idpWindow is closed by user.\n const checkInterruption = (): void => {\n // The _idpWindow is opened and not yet closed by the client\n if (this._idpWindow) {\n if (this._idpWindow.closed) {\n this._handleFailure(ERROR_USER_INTERRUPT, options?.onError);\n } else {\n setTimeout(checkInterruption, INTERRUPT_CHECK_INTERVAL);\n }\n }\n };\n checkInterruption();\n }\n\n private _getEventHandler(identityProviderUrl: URL, options?: AuthClientLoginOptions) {\n return async (event: MessageEvent) => {\n if (event.origin !== identityProviderUrl.origin) {\n console.warn(\n `WARNING: expected origin '${identityProviderUrl.origin}', got '${event.origin}' (ignoring)`,\n );\n return;\n }\n\n const message = event.data as IdentityServiceResponseMessage;\n\n switch (message.kind) {\n case 'authorize-ready': {\n // IDP is ready. Send a message to request authorization.\n const request: InternetIdentityAuthRequest = {\n kind: 'authorize-client',\n sessionPublicKey: new Uint8Array(this._key?.getPublicKey().toDer() as ArrayBuffer),\n maxTimeToLive: options?.maxTimeToLive,\n allowPinAuthentication: options?.allowPinAuthentication,\n derivationOrigin: options?.derivationOrigin?.toString(),\n // Pass any custom values to the IDP.\n ...options?.customValues,\n };\n this._idpWindow?.postMessage(request, identityProviderUrl.origin);\n break;\n }\n case 'authorize-client-success':\n // Create the delegation chain and store it.\n try {\n await this._handleSuccess(message, options?.onSuccess);\n } catch (err) {\n this._handleFailure((err as Error).message, options?.onError);\n }\n break;\n case 'authorize-client-failure':\n this._handleFailure(message.text, options?.onError);\n break;\n default:\n break;\n }\n };\n }\n\n private _handleFailure(errorMessage?: string, onError?: (error?: string) => void): void {\n this._idpWindow?.close();\n onError?.(errorMessage);\n this._removeEventListener();\n delete this._idpWindow;\n }\n\n private _removeEventListener() {\n if (this._eventHandler) {\n window.removeEventListener('message', this._eventHandler);\n }\n this._eventHandler = undefined;\n }\n\n public async logout(options: { returnTo?: string } = {}): Promise<void> {\n await _deleteStorage(this._storage);\n\n // Reset this auth client to a non-authenticated state.\n this._identity = new AnonymousIdentity();\n this._chain = null;\n\n if (options.returnTo) {\n try {\n window.history.pushState({}, '', options.returnTo);\n } catch (e) {\n window.location.href = options.returnTo;\n }\n }\n }\n}\n\nasync function _deleteStorage(storage: AuthClientStorage) {\n await storage.remove(KEY_STORAGE_KEY);\n await storage.remove(KEY_STORAGE_DELEGATION);\n await storage.remove(KEY_VECTOR);\n}\n", "import {AuthClient} from '@dfinity/auth-client';\n\nexport const createAuthClient = (): Promise<AuthClient> =>\n AuthClient.create({\n idleOptions: {\n disableIdle: true,\n disableDefaultIdleCallback: true\n }\n });\n", "import {fromArray} from '@junobuild/utils';\nimport type {Doc} from '../../declarations/satellite/satellite.did';\n\nexport const mapData = async <D>({data}: Pick<Doc, 'data'>): Promise<D> => {\n try {\n return await fromArray<D>(data);\n } catch (err: unknown) {\n console.error('The data parsing has failed, mapping to undefined as a fallback.', err);\n return undefined as D;\n }\n};\n", "import {fromArray, fromNullable, toArray, toNullable} from '@junobuild/utils';\nimport type {DelDoc, Doc as DocApi, SetDoc} from '../../declarations/satellite/satellite.did';\nimport type {Doc} from '../types/doc.types';\n\nexport const toSetDoc = async <D>(doc: Doc<D>): Promise<SetDoc> => {\n const {data, version, description} = doc;\n\n return {\n description: toNullable(description),\n data: await toArray<D>(data),\n version: toNullable(version)\n };\n};\n\nexport const toDelDoc = <D>(doc: Doc<D>): DelDoc => {\n const {version} = doc;\n\n return {\n version: toNullable(version)\n };\n};\n\nexport const fromDoc = async <D>({doc, key}: {doc: DocApi; key: string}): Promise<Doc<D>> => {\n const {owner, version, description: docDescription, data, ...rest} = doc;\n\n return {\n key,\n description: fromNullable(docDescription),\n owner: owner.toText(),\n data: await fromArray<D>(data),\n version: fromNullable(version),\n ...rest\n };\n};\n", "import {Principal} from '@dfinity/principal';\nimport {isNullish, toNullable} from '@junobuild/utils';\nimport type {\n ListParams as ListParamsApi,\n TimestampMatcher\n} from '../../declarations/satellite/satellite.did';\nimport type {ListParams, ListTimestampMatcher} from '../types/list.types';\n\nconst toListMatcherTimestamp = (matcher?: ListTimestampMatcher): [] | [TimestampMatcher] => {\n if (isNullish(matcher)) {\n return toNullable();\n }\n\n switch (matcher.matcher) {\n case 'equal':\n return toNullable({Equal: matcher.timestamp});\n case 'greaterThan':\n return toNullable({GreaterThan: matcher.timestamp});\n case 'lessThan':\n return toNullable({LessThan: matcher.timestamp});\n case 'between':\n return toNullable({Between: [matcher.timestamps.start, matcher.timestamps.end]});\n default:\n throw new Error('Invalid list matcher for timestamp', matcher);\n }\n};\n\nexport const toListParams = ({matcher, paginate, order, owner}: ListParams): ListParamsApi => ({\n matcher: isNullish(matcher)\n ? []\n : [\n {\n key: toNullable(matcher.key),\n description: toNullable(matcher.description),\n created_at: toListMatcherTimestamp(matcher.createdAt),\n updated_at: toListMatcherTimestamp(matcher.updatedAt)\n }\n ],\n paginate: toNullable(\n isNullish(paginate)\n ? undefined\n : {\n start_after: toNullable(paginate.startAfter),\n limit: toNullable(isNullish(paginate.limit) ? undefined : BigInt(paginate.limit))\n }\n ),\n order: toNullable(\n isNullish(order)\n ? undefined\n : {\n desc: order.desc,\n field:\n order.field === 'created_at'\n ? {CreatedAt: null}\n : order.field === 'updated_at'\n ? {UpdatedAt: null}\n : {Keys: null}\n }\n ),\n owner: toNullable(\n isNullish(owner) ? undefined : typeof owner === 'string' ? Principal.fromText(owner) : owner\n )\n});\n", "// @ts-ignore\nexport const idlFactory = ({IDL}) => {\n const CommitBatch = IDL.Record({\n batch_id: IDL.Nat,\n headers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n chunk_ids: IDL.Vec(IDL.Nat)\n });\n const ListOrderField = IDL.Variant({\n UpdatedAt: IDL.Null,\n Keys: IDL.Null,\n CreatedAt: IDL.Null\n });\n const ListOrder = IDL.Record({field: ListOrderField, desc: IDL.Bool});\n const TimestampMatcher = IDL.Variant({\n Equal: IDL.Nat64,\n Between: IDL.Tuple(IDL.Nat64, IDL.Nat64),\n GreaterThan: IDL.Nat64,\n LessThan: IDL.Nat64\n });\n const ListMatcher = IDL.Record({\n key: IDL.Opt(IDL.Text),\n updated_at: IDL.Opt(TimestampMatcher),\n description: IDL.Opt(IDL.Text),\n created_at: IDL.Opt(TimestampMatcher)\n });\n const ListPaginate = IDL.Record({\n start_after: IDL.Opt(IDL.Text),\n limit: IDL.Opt(IDL.Nat64)\n });\n const ListParams = IDL.Record({\n order: IDL.Opt(ListOrder),\n owner: IDL.Opt(IDL.Principal),\n matcher: IDL.Opt(ListMatcher),\n paginate: IDL.Opt(ListPaginate)\n });\n const DeleteControllersArgs = IDL.Record({\n controllers: IDL.Vec(IDL.Principal)\n });\n const ControllerScope = IDL.Variant({\n Write: IDL.Null,\n Admin: IDL.Null\n });\n const Controller = IDL.Record({\n updated_at: IDL.Nat64,\n metadata: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n created_at: IDL.Nat64,\n scope: ControllerScope,\n expires_at: IDL.Opt(IDL.Nat64)\n });\n const DelDoc = IDL.Record({version: IDL.Opt(IDL.Nat64)});\n const RulesType = IDL.Variant({Db: IDL.Null, Storage: IDL.Null});\n const DelRule = IDL.Record({version: IDL.Opt(IDL.Nat64)});\n const DepositCyclesArgs = IDL.Record({\n cycles: IDL.Nat,\n destination_id: IDL.Principal\n });\n const AssetKey = IDL.Record({\n token: IDL.Opt(IDL.Text),\n collection: IDL.Text,\n owner: IDL.Principal,\n name: IDL.Text,\n description: IDL.Opt(IDL.Text),\n full_path: IDL.Text\n });\n const AssetEncodingNoContent = IDL.Record({\n modified: IDL.Nat64,\n sha256: IDL.Vec(IDL.Nat8),\n total_length: IDL.Nat\n });\n const AssetNoContent = IDL.Record({\n key: AssetKey,\n updated_at: IDL.Nat64,\n encodings: IDL.Vec(IDL.Tuple(IDL.Text, AssetEncodingNoContent)),\n headers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n created_at: IDL.Nat64,\n version: IDL.Opt(IDL.Nat64)\n });\n const AuthenticationConfigInternetIdentity = IDL.Record({\n derivation_origin: IDL.Opt(IDL.Text)\n });\n const AuthenticationConfig = IDL.Record({\n internet_identity: IDL.Opt(AuthenticationConfigInternetIdentity)\n });\n const ConfigMaxMemorySize = IDL.Record({\n stable: IDL.Opt(IDL.Nat64),\n heap: IDL.Opt(IDL.Nat64)\n });\n const DbConfig = IDL.Record({\n max_memory_size: IDL.Opt(ConfigMaxMemorySize)\n });\n const StorageConfigIFrame = IDL.Variant({\n Deny: IDL.Null,\n AllowAny: IDL.Null,\n SameOrigin: IDL.Null\n });\n const StorageConfigRawAccess = IDL.Variant({\n Deny: IDL.Null,\n Allow: IDL.Null\n });\n const StorageConfigRedirect = IDL.Record({\n status_code: IDL.Nat16,\n location: IDL.Text\n });\n const StorageConfig = IDL.Record({\n iframe: IDL.Opt(StorageConfigIFrame),\n rewrites: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n headers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)))),\n max_memory_size: IDL.Opt(ConfigMaxMemorySize),\n raw_access: IDL.Opt(StorageConfigRawAccess),\n redirects: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, StorageConfigRedirect)))\n });\n const Config = IDL.Record({\n db: IDL.Opt(DbConfig),\n authentication: IDL.Opt(AuthenticationConfig),\n storage: StorageConfig\n });\n const Doc = IDL.Record({\n updated_at: IDL.Nat64,\n owner: IDL.Principal,\n data: IDL.Vec(IDL.Nat8),\n description: IDL.Opt(IDL.Text),\n created_at: IDL.Nat64,\n version: IDL.Opt(IDL.Nat64)\n });\n const HttpRequest = IDL.Record({\n url: IDL.Text,\n method: IDL.Text,\n body: IDL.Vec(IDL.Nat8),\n headers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n certificate_version: IDL.Opt(IDL.Nat16)\n });\n const Memory = IDL.Variant({Heap: IDL.Null, Stable: IDL.Null});\n const StreamingCallbackToken = IDL.Record({\n memory: Memory,\n token: IDL.Opt(IDL.Text),\n sha256: IDL.Opt(IDL.Vec(IDL.Nat8)),\n headers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n index: IDL.Nat64,\n encoding_type: IDL.Text,\n full_path: IDL.Text\n });\n const StreamingStrategy = IDL.Variant({\n Callback: IDL.Record({\n token: StreamingCallbackToken,\n callback: IDL.Func([], [], ['query'])\n })\n });\n const HttpResponse = IDL.Record({\n body: IDL.Vec(IDL.Nat8),\n headers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n streaming_strategy: IDL.Opt(StreamingStrategy),\n status_code: IDL.Nat16\n });\n const StreamingCallbackHttpResponse = IDL.Record({\n token: IDL.Opt(StreamingCallbackToken),\n body: IDL.Vec(IDL.Nat8)\n });\n const InitAssetKey = IDL.Record({\n token: IDL.Opt(IDL.Text),\n collection: IDL.Text,\n name: IDL.Text,\n description: IDL.Opt(IDL.Text),\n encoding_type: IDL.Opt(IDL.Text),\n full_path: IDL.Text\n });\n const InitUploadResult = IDL.Record({batch_id: IDL.Nat});\n const ListResults = IDL.Record({\n matches_pages: IDL.Opt(IDL.Nat64),\n matches_length: IDL.Nat64,\n items_page: IDL.Opt(IDL.Nat64),\n items: IDL.Vec(IDL.Tuple(IDL.Text, AssetNoContent)),\n items_length: IDL.Nat64\n });\n const CustomDomain = IDL.Record({\n updated_at: IDL.Nat64,\n created_at: IDL.Nat64,\n version: IDL.Opt(IDL.Nat64),\n bn_id: IDL.Opt(IDL.Text)\n });\n const ListResults_1 = IDL.Record({\n matches_pages: IDL.Opt(IDL.Nat64),\n matches_length: IDL.Nat64,\n items_page: IDL.Opt(IDL.Nat64),\n items: IDL.Vec(IDL.Tuple(IDL.Text, Doc)),\n items_length: IDL.Nat64\n });\n const Permission = IDL.Variant({\n Controllers: IDL.Null,\n Private: IDL.Null,\n Public: IDL.Null,\n Managed: IDL.Null\n });\n const Rule = IDL.Record({\n max_capacity: IDL.Opt(IDL.Nat32),\n memory: IDL.Opt(Memory),\n updated_at: IDL.Nat64,\n max_size: IDL.Opt(IDL.Nat),\n read: Permission,\n created_at: IDL.Nat64,\n version: IDL.Opt(IDL.Nat64),\n mutable_permissions: IDL.Opt(IDL.Bool),\n write: Permission\n });\n const MemorySize = IDL.Record({stable: IDL.Nat64, heap: IDL.Nat64});\n const SetController = IDL.Record({\n metadata: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n scope: ControllerScope,\n expires_at: IDL.Opt(IDL.Nat64)\n });\n const SetControllersArgs = IDL.Record({\n controller: SetController,\n controllers: IDL.Vec(IDL.Principal)\n });\n const SetDoc = IDL.Record({\n data: IDL.Vec(IDL.Nat8),\n description: IDL.Opt(IDL.Text),\n version: IDL.Opt(IDL.Nat64)\n });\n const SetRule = IDL.Record({\n max_capacity: IDL.Opt(IDL.Nat32),\n memory: IDL.Opt(Memory),\n max_size: IDL.Opt(IDL.Nat),\n read: Permission,\n version: IDL.Opt(IDL.Nat64),\n mutable_permissions: IDL.Opt(IDL.Bool),\n write: Permission\n });\n const UploadChunk = IDL.Record({\n content: IDL.Vec(IDL.Nat8),\n batch_id: IDL.Nat,\n order_id: IDL.Opt(IDL.Nat)\n });\n const UploadChunkResult = IDL.Record({chunk_id: IDL.Nat});\n return IDL.Service({\n build_version: IDL.Func([], [IDL.Text], ['query']),\n commit_asset_upload: IDL.Func([CommitBatch], [], []),\n count_assets: IDL.Func([IDL.Text, ListParams], [IDL.Nat64], ['query']),\n count_collection_assets: IDL.Func([IDL.Text], [IDL.Nat64], ['query']),\n count_collection_docs: IDL.Func([IDL.Text], [IDL.Nat64], ['query']),\n count_docs: IDL.Func([IDL.Text, ListParams], [IDL.Nat64], ['query']),\n del_asset: IDL.Func([IDL.Text, IDL.Text], [], []),\n del_assets: IDL.Func([IDL.Text], [], []),\n del_controllers: IDL.Func(\n [DeleteControllersArgs],\n [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))],\n []\n ),\n del_custom_domain: IDL.Func([IDL.Text], [], []),\n del_doc: IDL.Func([IDL.Text, IDL.Text, DelDoc], [], []),\n del_docs: IDL.Func([IDL.Text], [], []),\n del_many_assets: IDL.Func([IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))], [], []),\n del_many_docs: IDL.Func([IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text, DelDoc))], [], []),\n del_rule: IDL.Func([RulesType, IDL.Text, DelRule], [], []),\n deposit_cycles: IDL.Func([DepositCyclesArgs], [], []),\n get_asset: IDL.Func([IDL.Text, IDL.Text], [IDL.Opt(AssetNoContent)], ['query']),\n get_auth_config: IDL.Func([], [IDL.Opt(AuthenticationConfig)], ['query']),\n get_config: IDL.Func([], [Config], []),\n get_db_config: IDL.Func([], [IDL.Opt(DbConfig)], ['query']),\n get_doc: IDL.Func([IDL.Text, IDL.Text], [IDL.Opt(Doc)], ['query']),\n get_many_assets: IDL.Func(\n [IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))],\n [IDL.Vec(IDL.Tuple(IDL.Text, IDL.Opt(AssetNoContent)))],\n ['query']\n ),\n get_many_docs: IDL.Func(\n [IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))],\n [IDL.Vec(IDL.Tuple(IDL.Text, IDL.Opt(Doc)))],\n ['query']\n ),\n get_storage_config: IDL.Func([], [StorageConfig], ['query']),\n http_request: IDL.Func([HttpRequest], [HttpResponse], ['query']),\n http_request_streaming_callback: IDL.Func(\n [StreamingCallbackToken],\n [StreamingCallbackHttpResponse],\n ['query']\n ),\n init_asset_upload: IDL.Func([InitAssetKey], [InitUploadResult], []),\n list_assets: IDL.Func([IDL.Text, ListParams], [ListResults], ['query']),\n list_controllers: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))], ['query']),\n list_custom_domains: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Text, CustomDomain))], ['query']),\n list_docs: IDL.Func([IDL.Text, ListParams], [ListResults_1], ['query']),\n list_rules: IDL.Func([RulesType], [IDL.Vec(IDL.Tuple(IDL.Text, Rule))], ['query']),\n memory_size: IDL.Func([], [MemorySize], ['query']),\n set_auth_config: IDL.Func([AuthenticationConfig], [], []),\n set_controllers: IDL.Func(\n [SetControllersArgs],\n [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))],\n []\n ),\n set_custom_domain: IDL.Func([IDL.Text, IDL.Opt(IDL.Text)], [], []),\n set_db_config: IDL.Func([DbConfig], [], []),\n set_doc: IDL.Func([IDL.Text, IDL.Text, SetDoc], [Doc], []),\n set_many_docs: IDL.Func(\n [IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text, SetDoc))],\n [IDL.Vec(IDL.Tuple(IDL.Text, Doc))],\n []\n ),\n set_rule: IDL.Func([RulesType, IDL.Text, SetRule], [], []),\n set_storage_config: IDL.Func([StorageConfig], [], []),\n upload_asset_chunk: IDL.Func([UploadChunk], [UploadChunkResult], []),\n version: IDL.Func([], [IDL.Text], ['query'])\n });\n};\n// @ts-ignore\nexport const init = ({IDL}) => {\n return [];\n};\n", "import type {ActorMethod, ActorSubclass} from '@dfinity/agent';\nimport {Actor, HttpAgent} from '@dfinity/agent';\nimport type {IDL} from '@dfinity/candid';\nimport {nonNullish} from '@junobuild/utils';\nimport {DOCKER_CONTAINER_URL} from '../constants/container.constants';\nimport type {Satellite} from '../types/satellite.types';\n\nexport const createActor = async <T = Record<string, ActorMethod>>({\n satelliteId: canisterId,\n idlFactory,\n identity,\n fetch,\n container\n}: {\n idlFactory: IDL.InterfaceFactory;\n} & Required<Pick<Satellite, 'satelliteId' | 'identity'>> &\n Pick<Satellite, 'fetch' | 'container'>): Promise<ActorSubclass<T>> => {\n const localActor = nonNullish(container) && container !== false;\n\n const host = localActor\n ? container === true\n ? DOCKER_CONTAINER_URL\n : container\n : 'https://icp-api.io';\n\n const agent: HttpAgent = new HttpAgent({identity, host, ...(fetch && {fetch})});\n\n if (nonNullish(container)) {\n // Fetch root key for certificate validation during development\n await agent.fetchRootKey();\n }\n\n // Creates an actor with using the candid interface and the HttpAgent\n return Actor.createActor(idlFactory, {\n agent,\n canisterId\n });\n};\n", "import {nonNullish} from '@junobuild/utils';\nimport {DOCKER_CONTAINER_URL} from '../constants/container.constants';\nimport {EnvStore} from '../stores/env.store';\nimport type {Satellite} from '../types/satellite.types';\n\nexport const satelliteUrl = ({\n satelliteId: customSatelliteId,\n container: customContainer\n}: Satellite): string => {\n const {satelliteId} = customOrEnvSatelliteId({satelliteId: customSatelliteId});\n const {container} = customOrEnvContainer({container: customContainer});\n\n if (nonNullish(container) && container !== false) {\n const {host: containerHost, protocol} = new URL(\n container === true ? DOCKER_CONTAINER_URL : container\n );\n return `${protocol}//${satelliteId ?? 'unknown'}.${containerHost.replace('127.0.0.1', 'localhost')}`;\n }\n\n return `https://${satelliteId ?? 'unknown'}.icp0.io`;\n};\n\nexport const customOrEnvSatelliteId = ({\n satelliteId\n}: Pick<Satellite, 'satelliteId'>): Pick<Satellite, 'satelliteId'> =>\n nonNullish(satelliteId)\n ? {satelliteId}\n : (EnvStore.getInstance().get() ?? {satelliteId: undefined});\n\nexport const customOrEnvContainer = ({\n container: customContainer\n}: Pick<Satellite, 'container'>): Pick<Satellite, 'container'> =>\n nonNullish(customContainer)\n ? {container: customContainer}\n : (EnvStore.getInstance().get() ?? {container: undefined});\n", "import {assertNonNullish} from '@junobuild/utils';\nimport type {_SERVICE as SatelliteActor} from '../../declarations/satellite/satellite.did';\nimport {idlFactory} from '../../declarations/satellite/satellite.factory.did.js';\nimport type {Satellite} from '../types/satellite.types';\nimport {createActor} from '../utils/actor.utils';\nimport {customOrEnvContainer, customOrEnvSatelliteId} from '../utils/env.utils';\n\nexport const getSatelliteActor = async ({\n satelliteId: customSatelliteId,\n container: customContainer,\n ...rest\n}: Satellite): Promise<SatelliteActor> => {\n const {satelliteId} = customOrEnvSatelliteId({satelliteId: customSatelliteId});\n\n assertNonNullish(satelliteId, 'No satellite ID defined. Did you initialize Juno?');\n\n const {container} = customOrEnvContainer({container: customContainer});\n\n return createActor({\n satelliteId,\n container,\n idlFactory,\n ...rest\n });\n};\n", "import {fromNullable, isNullish, nonNullish} from '@junobuild/utils';\nimport type {DelDoc, SetDoc} from '../../declarations/satellite/satellite.did';\nimport type {Doc} from '../types/doc.types';\nimport type {ListParams, ListResults} from '../types/list.types';\nimport type {Satellite} from '../types/satellite.types';\nimport {mapData} from '../utils/data.utils';\nimport {fromDoc, toDelDoc, toSetDoc} from '../utils/doc.utils';\nimport {toListParams} from '../utils/list.utils';\nimport {getSatelliteActor} from './actor.api';\n\nexport const getDoc = async <D>({\n collection,\n key,\n satellite\n}: {\n collection: string;\n satellite: Satellite;\n} & Pick<Doc<D>, 'key'>): Promise<Doc<D> | undefined> => {\n const {get_doc} = await getSatelliteActor(satellite);\n\n const doc = fromNullable(await get_doc(collection, key));\n\n if (isNullish(doc)) {\n return undefined;\n }\n\n return fromDoc({doc, key});\n};\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport const getManyDocs = async ({\n docs,\n satellite\n}: {\n docs: ({collection: string} & Pick<Doc<any>, 'key'>)[];\n satellite: Satellite;\n}): Promise<(Doc<any> | undefined)[]> => {\n const {get_many_docs} = await getSatelliteActor(satellite);\n\n const payload: [string, string][] = docs.map(({collection, key}) => [collection, key]);\n\n const resultsDocs = await get_many_docs(payload);\n\n const results: (Doc<any> | undefined)[] = [];\n for (const [key, resultDoc] of resultsDocs) {\n const doc = fromNullable(resultDoc);\n results.push(nonNullish(doc) ? await fromDoc({key, doc}) : undefined);\n }\n\n return results;\n};\n/* eslint-enable */\n\nexport const setDoc = async <D>({\n collection,\n doc,\n satellite\n}: {\n collection: string;\n doc: Doc<D>;\n satellite: Satellite;\n}): Promise<Doc<D>> => {\n const {set_doc} = await getSatelliteActor(satellite);\n\n const {key} = doc;\n\n const setDoc = await toSetDoc(doc);\n\n const updatedDoc = await set_doc(collection, key, setDoc);\n\n return await fromDoc({key, doc: updatedDoc});\n};\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport const setManyDocs = async ({\n docs,\n satellite\n}: {\n docs: {collection: string; doc: Doc<any>}[];\n satellite: Satellite;\n}): Promise<Doc<any>[]> => {\n const {set_many_docs} = await getSatelliteActor(satellite);\n\n const payload: [string, string, SetDoc][] = [];\n for (const {collection, doc} of docs) {\n const {key} = doc;\n payload.push([collection, key, await toSetDoc(doc)]);\n }\n\n const updatedDocs = await set_many_docs(payload);\n\n const results: Doc<any>[] = [];\n for (const [key, updatedDoc] of updatedDocs) {\n results.push(await fromDoc({key, doc: updatedDoc}));\n }\n\n return results;\n};\n/* eslint-enable */\n\nexport const deleteDoc = async <D>({\n collection,\n doc,\n satellite\n}: {\n collection: string;\n doc: Doc<D>;\n satellite: Satellite;\n}): Promise<void> => {\n const {del_doc} = await getSatelliteActor(satellite);\n\n const {key} = doc;\n\n return del_doc(collection, key, toDelDoc(doc));\n};\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport const deleteManyDocs = async ({\n docs,\n satellite\n}: {\n docs: {collection: string; doc: Doc<any>}[];\n satellite: Satellite;\n}): Promise<void> => {\n const {del_many_docs} = await getSatelliteActor(satellite);\n\n const payload: [string, string, DelDoc][] = docs.map(({collection, doc}) => [\n collection,\n doc.key,\n toDelDoc(doc)\n ]);\n\n await del_many_docs(payload);\n};\n/* eslint-enable */\n\nexport const listDocs = async <D>({\n collection,\n filter,\n satellite\n}: {\n collection: string;\n filter: ListParams;\n satellite: Satellite;\n}): Promise<ListResults<Doc<D>>> => {\n const {list_docs} = await getSatelliteActor(satellite);\n\n const {items, items_page, items_length, matches_length, matches_pages} = await list_docs(\n collection,\n toListParams(filter)\n );\n\n const docs: Doc<D>[] = [];\n\n for (const [key, item] of items) {\n const {data: dataArray, owner, description, version, ...rest} = item;\n\n docs.push({\n key,\n description: fromNullable(description),\n owner: owner.toText(),\n data: await mapData<D>({data: dataArray}),\n version: fromNullable(version),\n ...rest\n });\n }\n\n return {\n items: docs,\n items_length,\n items_page: fromNullable(items_page),\n matches_length,\n matches_pages: fromNullable(matches_pages)\n };\n};\n\nexport const countDocs = async ({\n collection,\n filter,\n satellite\n}: {\n collection: string;\n filter: ListParams;\n satellite: Satellite;\n}): Promise<bigint> => {\n const {count_docs} = await getSatelliteActor(satellite);\n\n return count_docs(collection, toListParams(filter));\n};\n", "import type {Identity} from '@dfinity/agent';\nimport {AnonymousIdentity} from '@dfinity/agent';\nimport {getIdentity as getAuthIdentity} from './auth.services';\n\nexport const getIdentity = (identity?: Identity): Identity => {\n if (identity !== undefined) {\n return identity;\n }\n\n const authIdentity: Identity | undefined = getAuthIdentity();\n\n return authIdentity ?? new AnonymousIdentity();\n};\n", "import {\n countDocs as countDocsApi,\n deleteDoc as deleteDocApi,\n deleteManyDocs as deleteManyDocsApi,\n getDoc as getDocApi,\n getManyDocs as getManyDocsApi,\n listDocs as listDocsApi,\n setDoc as setDocApi,\n setManyDocs as setManyDocsApi\n} from '../api/doc.api';\nimport type {Doc} from '../types/doc.types';\nimport type {ListParams, ListResults} from '../types/list.types';\nimport type {SatelliteOptions} from '../types/satellite.types';\nimport {getIdentity} from './identity.services';\n\n/**\n * Retrieves a single document from a collection.\n * @template D\n * @param {Object} params - The parameters for retrieving the document.\n * @param {string} params.collection - The name of the collection.\n * @param {SatelliteOptions} [params.satellite] - Options for the satellite (useful for NodeJS usage only).\n * @param {string} params.key - The key of the document to retrieve.\n * @returns {Promise<Doc<D> | undefined>} A promise that resolves to the document or undefined if not found.\n */\nexport const getDoc = async <D>({\n satellite,\n ...rest\n}: {\n collection: string;\n satellite?: SatelliteOptions;\n} & Pick<Doc<D>, 'key'>): Promise<Doc<D> | undefined> => {\n const identity = getIdentity(satellite?.identity);\n\n return getDocApi({...rest, satellite: {...satellite, identity}});\n};\n\n/**\n * Retrieves multiple documents from a single or different collections in a single call.\n * @param {Object} params - The parameters for retrieving the documents.\n * @param {Array} params.docs - The list of documents with their collections and keys.\n * @param {SatelliteOptions} [params.satellite] - Options for the satellite (useful for NodeJS usage only).\n * @returns {Promise<Array<Doc<any> | undefined>>} A promise that resolves to an array of documents or undefined if not found.\n */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport const getManyDocs = async ({\n satellite,\n ...rest\n}: {\n docs: ({collection: string} & Pick<Doc<any>, 'key'>)[];\n satellite?: SatelliteOptions;\n}): Promise<(Doc<any> | undefined)[]> => {\n const identity = getIdentity(satellite?.identity);\n\n return getManyDocsApi({...rest, satellite: {...satellite, identity}});\n};\n/* eslint-enable */\n\n/**\n * Adds or updates a single document in a collection.\n * @template D\n * @param {Object} params - The parameters for adding or updating the document.\n * @param {string} params.collection - The name of the collection.\n * @param {Doc<D>} params.doc - The document to add or update.\n * @param {SatelliteOptions} [params.satellite] - Options for the satellite (useful for NodeJS usage only).\n * @returns {Promise<Doc<D>>} A promise that resolves to the added or updated document.\n */\nexport const setDoc = async <D>({\n satellite,\n ...rest\n}: {\n collection: string;\n doc: Doc<D>;\n satellite?: SatelliteOptions;\n}): Promise<Doc<D>> => {\n const identity = getIdentity(satellite?.identity);\n\n return setDocApi({...rest, satellite: {...satellite, identity}});\n};\n\n/**\n * Adds or updates multiple documents in a or different collections.\n * @param {Object} params - The parameters for adding or updating the documents.\n * @param {Array} params.docs - The list of documents with their collections and data.\n * @param {SatelliteOptions} [params.satellite] - Options for the satellite (useful for NodeJS usage only).\n * @returns {Promise<Array<Doc<any>>>} A promise that resolves to an array of added or updated documents.\n */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport const setManyDocs = async ({\n satellite,\n ...rest\n}: {\n docs: {collection: string; doc: Doc<any>}[];\n satellite?: SatelliteOptions;\n}): Promise<Doc<any>[]> => {\n const identity = getIdentity(satellite?.identity);\n\n return setManyDocsApi({...rest, satellite: {...satellite, identity}});\n};\n/* eslint-enable */\n\n/**\n * Deletes a single document from a collection.\n * @template D\n * @param {Object} params - The parameters for deleting the document.\n * @param {string} params.collection - The name of the collection.\n * @param {Doc<D>} params.doc - The document to delete.\n * @param {SatelliteOptions} [params.satellite] - Options for the satellite (useful for NodeJS usage only).\n * @returns {Promise<void>} A promise that resolves when the document is deleted.\n */\nexport const deleteDoc = async <D>({\n satellite,\n ...rest\n}: {\n collection: string;\n doc: Doc<D>;\n satellite?: SatelliteOptions;\n}): Promise<void> => {\n const identity = getIdentity(satellite?.identity);\n\n return deleteDocApi({...rest, satellite: {...satellite, identity}});\n};\n\n/**\n * Deletes multiple documents from a or different collections.\n * @param {Object} params - The parameters for deleting the documents.\n * @param {Array} params.docs - The list of documents with their collections and data.\n * @param {SatelliteOptions} [params.satellite] - Options for the satellite (useful for NodeJS usage only).\n * @returns {Promise<void>} A promise that resolves when the documents are deleted.\n */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport const deleteManyDocs = async ({\n satellite,\n ...rest\n}: {\n docs: {collection: string; doc: Doc<any>}[];\n satellite?: SatelliteOptions;\n}): Promise<void> => {\n const identity = getIdentity(satellite?.identity);\n\n return deleteManyDocsApi({...rest, satellite: {...satellite, identity}});\n};\n/* eslint-enable */\n\n/**\n * Lists documents in a collection with optional filtering.\n * @template D\n * @param {Object} params - The parameters for listing the documents.\n * @param {string} params.collection - The name of the collection.\n * @param {ListParams} [params.filter] - Optional filter parameters.\n * @param {SatelliteOptions} [params.satellite] - Options for the satellite (useful for NodeJS usage only).\n * @returns {Promise<ListResults<Doc<D>>>} A promise that resolves to the list of documents.\n */\nexport const listDocs = async <D>({\n satellite,\n filter,\n ...rest\n}: {\n collection: string;\n filter?: ListParams;\n satellite?: SatelliteOptions;\n}): Promise<ListResults<Doc<D>>> => {\n const identity = getIdentity(satellite?.identity);\n\n return listDocsApi<D>({...rest, filter: filter ?? {}, satellite: {...satellite, identity}});\n};\n\n/**\n * Counts documents in a collection with optional filtering.\n * @param {Object} params - The parameters for counting the documents.\n * @param {string} params.collection - The name of the collection.\n * @param {ListParams} [params.filter] - Optional filter parameters.\n * @param {SatelliteOptions} [params.satellite] - Options for the satellite (useful for NodeJS usage only).\n * @returns {Promise<bigint>} A promise that resolves to the count of documents as a bigint.\n */\nexport const countDocs = async ({\n satellite,\n filter,\n ...rest\n}: {\n collection: string;\n filter?: ListParams;\n satellite?: SatelliteOptions;\n}): Promise<bigint> => {\n const identity = getIdentity(satellite?.identity);\n\n return countDocsApi({...rest, filter: filter ?? {}, satellite: {...satellite, identity}});\n};\n", "import type {Identity} from '@dfinity/agent';\nimport {isNullish} from '@junobuild/utils';\nimport type {Provider, User, UserData} from '../types/auth.types';\nimport {getIdentity} from './auth.services';\nimport {getDoc, setDoc} from './doc.services';\n\nexport const initUser = async (provider?: Provider): Promise<User> => {\n const identity: Identity | undefined = getIdentity();\n\n if (isNullish(identity)) {\n throw new Error('No identity to initialize the user. Have you initialized Juno?');\n }\n\n const userId = identity.getPrincipal().toText();\n\n const user: User | undefined = await getDoc<UserData>({\n collection: `#user`,\n key: userId\n });\n\n if (isNullish(user)) {\n const newUser: User = await createUser({userId, provider});\n return newUser;\n }\n\n return user;\n};\n\nconst createUser = async ({\n userId,\n ...rest\n}: {\n userId: string;\n} & UserData): Promise<User> =>\n setDoc<UserData>({\n collection: `#user`,\n doc: {\n key: userId,\n data: rest\n }\n });\n", "import type {Identity} from '@dfinity/agent';\nimport type {AuthClient} from '@dfinity/auth-client';\nimport {\n ALLOW_PIN_AUTHENTICATION,\n DELEGATION_IDENTITY_EXPIRATION\n} from '../constants/auth.constants';\nimport {InternetIdentityProvider} from '../providers/auth.providers';\nimport {AuthStore} from '../stores/auth.store';\nimport type {Provider, SignInOptions} from '../types/auth.types';\nimport {createAuthClient} from '../utils/auth.utils';\nimport {initUser} from './user.services';\n\nlet authClient: AuthClient | undefined;\n\nexport const initAuth = async (provider?: Provider) => {\n authClient = authClient ?? (await createAuthClient());\n\n const isAuthenticated: boolean = (await authClient?.isAuthenticated()) ?? false;\n\n if (!isAuthenticated) {\n return;\n }\n\n const user = await initUser(provider);\n AuthStore.getInstance().set(user);\n};\n\n/**\n * Signs in a user with the specified options.\n * @param {SignInOptions} [options] - The options for signing in.\n * @returns {Promise<void>} A promise that resolves when the sign-in process is complete and the authenticated user is initialized.\n * @throws Will throw an error if the sign-in process fails.\n */\nexport const signIn = async (options?: SignInOptions): Promise<void> =>\n /* eslint-disable no-async-promise-executor */\n new Promise<void>(async (resolve, reject) => {\n authClient = authClient ?? (await createAuthClient());\n\n const provider = options?.provider ?? new InternetIdentityProvider({});\n\n await authClient.login({\n onSuccess: async () => {\n await initAuth(provider.id);\n resolve();\n },\n onError: (error?: string) => reject(error),\n maxTimeToLive: options?.maxTimeToLive ?? DELEGATION_IDENTITY_EXPIRATION,\n allowPinAuthentication: options?.allowPin ?? ALLOW_PIN_AUTHENTICATION,\n ...(options?.derivationOrigin !== undefined && {derivationOrigin: options.derivationOrigin}),\n ...provider.signInOptions({\n windowed: options?.windowed\n })\n });\n });\n\n/**\n * Signs out the current user.\n * @returns {Promise<void>} A promise that resolves when the sign-out process is complete.\n */\nexport const signOut = async (): Promise<void> => {\n await authClient?.logout();\n\n // Reset local object otherwise next sign in (sign in - sign out - sign in) might not work out - i.e. agent-js might not recreate the delegation or identity if not resetted\n authClient = undefined;\n\n AuthStore.getInstance().reset();\n};\n\nexport const getIdentity = (): Identity | undefined => {\n return authClient?.getIdentity();\n};\n\n/**\n * Returns the identity of a signed-in user or an anonymous identity.\n * This function is useful for loading an identity in web workers.\n * Used to imperatively get the identity. Please be certain before using it.\n * @returns {Promise<Identity>} A promise that resolves to the identity of the user or an anonymous identity.\n */\nexport const unsafeIdentity = async (): Promise<Identity> =>\n (authClient ?? (await createAuthClient())).getIdentity();\n", "import {isNullish} from '@junobuild/utils';\nimport {AuthStore} from '../stores/auth.store';\nimport type {User} from '../types/auth.types';\nimport type {EnvironmentWorker} from '../types/env.types';\nimport type {PostMessage, PostMessageDataResponseAuth} from '../types/post-message';\nimport type {Unsubscribe} from '../types/subscription.types';\nimport {emit} from '../utils/events.utils';\nimport {signOut} from './auth.services';\n\nexport const initAuthTimeoutWorker = (auth: EnvironmentWorker): Unsubscribe => {\n const workerUrl = auth === true ? './workers/auth.worker.js' : auth;\n const worker = new Worker(workerUrl);\n\n const timeoutSignOut = async () => {\n emit({message: 'junoSignOutAuthTimer'});\n await signOut();\n };\n\n worker.onmessage = async ({data}: MessageEvent<PostMessage<PostMessageDataResponseAuth>>) => {\n const {msg, data: value} = data;\n\n switch (msg) {\n case 'junoSignOutAuthTimer':\n await timeoutSignOut();\n return;\n case 'junoDelegationRemainingTime':\n emit({message: 'junoDelegationRemainingTime', detail: value?.authRemainingTime});\n return;\n }\n };\n\n return AuthStore.getInstance().subscribe((user: User | null) => {\n if (isNullish(user)) {\n worker.postMessage({msg: 'junoStopAuthTimer'});\n return;\n }\n\n worker.postMessage({msg: 'junoStartAuthTimer'});\n });\n};\n", "// TODO: duplicated because those should not be bundled in web worker. We can avoid this by transforming utils into a library of modules.\ntype ImportMeta = {env: Record<string, string> | undefined};\n\nexport const envSatelliteId = (): string | undefined => {\n const viteEnvSatelliteId = (): string | undefined =>\n typeof import.meta !== 'undefined' &&\n typeof (import.meta as unknown as ImportMeta).env !== 'undefined'\n ? ((import.meta as unknown as ImportMeta).env?.VITE_SATELLITE_ID ??\n (import.meta as unknown as ImportMeta).env?.PUBLIC_SATELLITE_ID)\n : undefined;\n\n return typeof process !== 'undefined'\n ? (process.env?.NEXT_PUBLIC_SATELLITE_ID ?? viteEnvSatelliteId())\n : viteEnvSatelliteId();\n};\n\nexport const envContainer = (): string | undefined => {\n const viteEnvContainer = (): string | undefined =>\n typeof import.meta !== 'undefined' &&\n typeof (import.meta as unknown as ImportMeta).env !== 'undefined'\n ? ((import.meta as unknown as ImportMeta).env?.VITE_CONTAINER ??\n (import.meta as unknown as ImportMeta).env?.PUBLIC_CONTAINER)\n : undefined;\n\n return typeof process !== 'undefined'\n ? (process.env?.NEXT_PUBLIC_CONTAINER ?? viteEnvContainer())\n : viteEnvContainer();\n};\n", "/**\n * Creates a debounced function that delays invoking the provided function until after the specified timeout.\n * @param {Function} func - The function to debounce.\n * @param {number} [timeout=300] - The number of milliseconds to delay. Defaults to 300ms if not specified or invalid.\n * @returns {Function} A debounced function.\n */\n/* eslint-disable-next-line @typescript-eslint/ban-types */\nexport const debounce = (func: Function, timeout?: number): Function => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n return (...args: unknown[]) => {\n const next = () => func(...args);\n\n if (timer) {\n clearTimeout(timer);\n }\n\n timer = setTimeout(next, timeout !== undefined && timeout > 0 ? timeout : 300);\n };\n};\n", "import {Principal} from '@dfinity/principal';\nimport {nonNullish} from './null.utils';\n\nconst JSON_KEY_BIGINT = '__bigint__';\nconst JSON_KEY_PRINCIPAL = '__principal__';\nconst JSON_KEY_UINT8ARRAY = '__uint8array__';\n\n/**\n * A function that alters the behavior of the stringification process for BigInt, Principal, and Uint8Array.\n * @param {string} _key - The key of the value being stringified.\n * @param {unknown} value - The value being stringified.\n * @returns {unknown} The altered value for stringification.\n */\nexport const jsonReplacer = (_key: string, value: unknown): unknown => {\n if (typeof value === 'bigint') {\n return {[JSON_KEY_BIGINT]: `${value}`};\n }\n\n if (nonNullish(value) && value instanceof Principal) {\n return {[JSON_KEY_PRINCIPAL]: value.toText()};\n }\n\n if (nonNullish(value) && value instanceof Uint8Array) {\n return {[JSON_KEY_UINT8ARRAY]: Array.from(value)};\n }\n\n return value;\n};\n\n/**\n * A parser that interprets revived BigInt, Principal, and Uint8Array when constructing JavaScript values or objects.\n * @param {string} _key - The key of the value being parsed.\n * @param {unknown} value - The value being parsed.\n * @returns {unknown} The parsed value.\n */\nexport const jsonReviver = (_key: string, value: unknown): unknown => {\n const mapValue = <T>(key: string): T => (value as Record<string, T>)[key];\n\n if (nonNullish(value) && typeof value === 'object' && JSON_KEY_BIGINT in value) {\n return BigInt(mapValue(JSON_KEY_BIGINT));\n }\n\n if (nonNullish(value) && typeof value === 'object' && JSON_KEY_PRINCIPAL in value) {\n return Principal.fromText(mapValue(JSON_KEY_PRINCIPAL));\n }\n\n if (nonNullish(value) && typeof value === 'object' && JSON_KEY_UINT8ARRAY in value) {\n return Uint8Array.from(mapValue(JSON_KEY_UINT8ARRAY));\n }\n\n return value;\n};\n", "/**\n * Checks if the provided argument is null or undefined.\n * @template T\n * @param {T | undefined | null} argument - The argument to check.\n * @returns {boolean} True if the argument is null or undefined, false otherwise.\n */\nexport const isNullish = <T>(argument: T | undefined | null): argument is undefined | null =>\n argument === null || argument === undefined;\n\n/**\n * Checks if the provided argument is neither null nor undefined.\n * @template T\n * @param {T | undefined | null} argument - The argument to check.\n * @returns {boolean} True if the argument is neither null nor undefined, false otherwise.\n */\nexport const nonNullish = <T>(argument: T | undefined | null): argument is NonNullable<T> =>\n !isNullish(argument);\n\n/**\n * Represents an error thrown when a value is null or undefined.\n * @class\n * @extends {Error}\n */\nexport class NullishError extends Error {}\n\n/**\n * Asserts that a value is neither null nor undefined.\n * @template T\n * @param {T} value - The value to check.\n * @param {string} [message] - The optional error message to use if the assertion fails.\n * @throws {NullishError} If the value is null or undefined.\n * @returns {asserts value is NonNullable<T>} Asserts that the value is neither null nor undefined.\n */\nexport const assertNonNullish: <T>(\n value: T,\n message?: string\n) => asserts value is NonNullable<T> = <T>(value: T, message?: string): void => {\n if (isNullish(value)) {\n throw new NullishError(message);\n }\n};\n", "import {jsonReplacer, jsonReviver} from './json.utils';\nimport {nonNullish} from './null.utils';\n\n/**\n * Converts a value to a nullable array.\n * @template T\n * @param {T} [value] - The value to convert.\n * @returns {([] | [T])} A nullable array containing the value if non-nullish, or an empty array if nullish.\n */\nexport const toNullable = <T>(value?: T): [] | [T] => {\n return nonNullish(value) ? [value] : [];\n};\n\n/**\n * Extracts a value from a nullable array.\n * @template T\n * @param {([] | [T])} value - The nullable array.\n * @returns {(T | undefined)} The value if present, or undefined if the array is empty.\n */\nexport const fromNullable = <T>(value: [] | [T]): T | undefined => {\n return value?.[0];\n};\n\n/**\n * Converts data to a Uint8Array for transmission or storage.\n * @template T\n * @param {T} data - The data to convert.\n * @returns {Promise<Uint8Array>} A promise that resolves to a Uint8Array representation of the data.\n */\nexport const toArray = async <T>(data: T): Promise<Uint8Array> => {\n const blob: Blob = new Blob([JSON.stringify(data, jsonReplacer)], {\n type: 'application/json; charset=utf-8'\n });\n return new Uint8Array(await blob.arrayBuffer());\n};\n\n/**\n * Converts a Uint8Array or number array back to the original data type.\n * @template T\n * @param {(Uint8Array | number[])} data - The array to convert.\n * @returns {Promise<T>} A promise that resolves to the original data.\n */\nexport const fromArray = async <T>(data: Uint8Array | number[]): Promise<T> => {\n const blob: Blob = new Blob([data instanceof Uint8Array ? data : new Uint8Array(data)], {\n type: 'application/json; charset=utf-8'\n });\n return JSON.parse(await blob.text(), jsonReviver);\n};\n", "/**\n * Checks if the current environment is a browser.\n * @returns {boolean} True if the current environment is a browser, false otherwise.\n */\nexport const isBrowser = (): boolean => typeof window !== `undefined`;\n", "import {isBrowser, toNullable} from '@junobuild/utils';\nimport type {\n _SERVICE as ConsoleActor,\n InitAssetKey as ConsoleInitAssetKey,\n InitUploadResult as ConsoleInitUploadResult\n} from '../../declarations/console/console.did';\nimport type {\n _SERVICE as SatelliteActor,\n InitAssetKey as SatelliteInitAssetKey,\n InitUploadResult as SatelliteInitUploadResult\n} from '../../declarations/satellite/satellite.did';\nimport type {ENCODING_TYPE, Storage} from '../types/storage.types';\n\nexport type UploadAsset = Required<Omit<Storage, 'token' | 'encoding' | 'description'>> &\n Pick<Storage, 'token' | 'encoding' | 'description'>;\n\nexport const uploadAsset = async ({\n asset: {data, filename, collection, headers, token, fullPath, encoding, description},\n actor,\n init_asset_upload\n}: {\n asset: UploadAsset;\n actor: SatelliteActor | ConsoleActor;\n init_asset_upload: (\n initAssetKey: SatelliteInitAssetKey | ConsoleInitAssetKey\n ) => Promise<SatelliteInitUploadResult | ConsoleInitUploadResult>;\n}): Promise<void> => {\n const {batch_id: batchId} = await init_asset_upload({\n collection,\n full_path: fullPath,\n name: filename,\n token: toNullable<string>(token),\n encoding_type: toNullable<ENCODING_TYPE>(encoding),\n description: toNullable(description)\n });\n\n // https://forum.dfinity.org/t/optimal-upload-chunk-size/20444/23?u=peterparker\n const chunkSize = 1900000;\n\n const uploadChunks: UploadChunkParams[] = [];\n\n // Prevent transforming chunk to arrayBuffer error: The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.\n const clone: Blob = isBrowser() ? new Blob([await data.arrayBuffer()]) : data;\n\n // Split data into chunks\n let orderId = 0n;\n for (let start = 0; start < clone.size; start += chunkSize) {\n const chunk: Blob = clone.slice(start, start + chunkSize);\n\n uploadChunks.push({\n batchId,\n chunk,\n actor,\n orderId\n });\n\n orderId++;\n }\n\n // Upload chunks to the IC in batch - i.e. 12 chunks uploaded at a time.\n let chunkIds: UploadChunkResult[] = [];\n for await (const results of batchUploadChunks({uploadChunks})) {\n chunkIds = [...chunkIds, ...results];\n }\n\n const contentType: [[string, string]] | undefined =\n headers.find(([type, _]) => type.toLowerCase() === 'content-type') === undefined &&\n data.type !== undefined &&\n data.type !== ''\n ? [['Content-Type', data.type]]\n : undefined;\n\n await actor.commit_asset_upload({\n batch_id: batchId,\n chunk_ids: chunkIds.map(({chunk_id}: UploadChunkResult) => chunk_id),\n headers: [...headers, ...(contentType ? contentType : [])]\n });\n};\n\nasync function* batchUploadChunks({\n uploadChunks,\n limit = 12\n}: {\n uploadChunks: UploadChunkParams[];\n limit?: number;\n}): AsyncGenerator<UploadChunkResult[], void> {\n for (let i = 0; i < uploadChunks.length; i = i + limit) {\n const batch = uploadChunks.slice(i, i + limit);\n const result = await Promise.all(batch.map((params) => uploadChunk(params)));\n yield result;\n }\n}\n\ntype UploadChunkResult = {chunk_id: bigint};\n\ntype UploadChunkParams = {\n batchId: bigint;\n chunk: Blob;\n actor: SatelliteActor | ConsoleActor;\n orderId: bigint;\n};\n\nconst uploadChunk = async ({\n batchId,\n chunk,\n actor,\n orderId\n}: UploadChunkParams): Promise<UploadChunkResult> =>\n actor.upload_asset_chunk({\n batch_id: batchId,\n content: new Uint8Array(await chunk.arrayBuffer()),\n order_id: toNullable(orderId)\n });\n", "import type {UploadAsset} from '@junobuild/storage';\nimport {uploadAsset as uploadAssetStorage, type AssetKey} from '@junobuild/storage';\nimport {fromNullable} from '@junobuild/utils';\nimport type {\n AssetNoContent,\n InitAssetKey,\n InitUploadResult,\n _SERVICE as SatelliteActor\n} from '../../declarations/satellite/satellite.did';\nimport type {ListParams, ListResults} from '../types/list.types';\nimport type {Satellite} from '../types/satellite.types';\nimport {toListParams} from '../utils/list.utils';\nimport {getSatelliteActor} from './actor.api';\n\nexport const uploadAsset = async ({\n satellite,\n ...asset\n}: UploadAsset & {satellite: Satellite}): Promise<void> => {\n const actor = await getSatelliteActor(satellite);\n\n const init_asset_upload = async (initAssetKey: InitAssetKey): Promise<InitUploadResult> => {\n return await actor.init_asset_upload(initAssetKey);\n };\n\n await uploadAssetStorage({\n actor,\n asset,\n init_asset_upload\n });\n};\n\nexport const listAssets = async ({\n collection,\n satellite,\n filter\n}: {\n collection: string;\n satellite: Satellite;\n filter: ListParams;\n}): Promise<ListResults<AssetNoContent>> => {\n const {list_assets} = await getSatelliteActor(satellite);\n\n const {\n items: assets,\n items_length,\n items_page,\n matches_length,\n matches_pages\n } = await list_assets(collection, toListParams(filter));\n\n return {\n items: assets.map(([_, asset]) => asset),\n items_length,\n items_page: fromNullable(items_page),\n matches_length,\n matches_pages: fromNullable(matches_pages)\n };\n};\n\nexport const countAssets = async ({\n collection,\n satellite,\n filter\n}: {\n collection: string;\n satellite: Satellite;\n filter: ListParams;\n}): Promise<bigint> => {\n const {count_assets} = await getSatelliteActor(satellite);\n\n return count_assets(collection, toListParams(filter));\n};\n\nexport const deleteAsset = async ({\n collection,\n fullPath,\n satellite\n}: {\n collection: string;\n satellite: Satellite;\n} & Pick<AssetKey, 'fullPath'>): Promise<void> => {\n const actor: SatelliteActor = await getSatelliteActor(satellite);\n\n return actor.del_asset(collection, fullPath);\n};\n\nexport const deleteManyAssets = async ({\n assets,\n satellite\n}: {\n assets: ({collection: string} & Pick<AssetKey, 'fullPath'>)[];\n satellite: Satellite;\n}): Promise<void> => {\n const {del_many_assets} = await getSatelliteActor(satellite);\n\n const payload: [string, string][] = assets.map(({collection, fullPath}) => [\n collection,\n fullPath\n ]);\n\n await del_many_assets(payload);\n};\n\nexport const getAsset = async ({\n collection,\n fullPath,\n satellite\n}: {\n collection: string;\n satellite: Satellite;\n} & Pick<AssetKey, 'fullPath'>): Promise<AssetNoContent | undefined> => {\n const {get_asset} = await getSatelliteActor(satellite);\n return fromNullable(await get_asset(collection, fullPath));\n};\n\nexport const getManyAssets = async ({\n assets,\n satellite\n}: {\n assets: ({collection: string} & Pick<AssetKey, 'fullPath'>)[];\n satellite: Satellite;\n}): Promise<(AssetNoContent | undefined)[]> => {\n const {get_many_assets} = await getSatelliteActor(satellite);\n\n const payload: [string, string][] = assets.map(({collection, fullPath}) => [\n collection,\n fullPath\n ]);\n\n const resultsAssets = await get_many_assets(payload);\n\n return resultsAssets.map(([_, resultAsset]) => fromNullable(resultAsset));\n};\n", "export const sha256ToBase64String = (sha256: Iterable<number>): string =>\n btoa([...sha256].map((c) => String.fromCharCode(c)).join(''));\n", "import type {Asset, AssetEncoding, AssetKey, Storage} from '@junobuild/storage';\nimport {fromNullable, nonNullish} from '@junobuild/utils';\nimport type {AssetNoContent} from '../../declarations/satellite/satellite.did';\nimport {\n countAssets as countAssetsApi,\n deleteAsset as deleteAssetApi,\n deleteManyAssets as deleteManyAssetsApi,\n getAsset as getAssetApi,\n getManyAssets as getManyAssetsApi,\n listAssets as listAssetsApi,\n uploadAsset as uploadAssetApi\n} from '../api/storage.api';\nimport type {ListParams} from '../types/list.types';\nimport type {SatelliteOptions} from '../types/satellite.types';\nimport type {Assets} from '../types/storage.types';\nimport {sha256ToBase64String} from '../utils/crypto.utils';\nimport {satelliteUrl} from '../utils/env.utils';\nimport {getIdentity} from './identity.services';\n\n/**\n * Uploads a blob to the storage.\n * @param {Storage & {satellite?: SatelliteOptions}} params - The storage parameters. Satellite options are required only in NodeJS environment.\n * @returns {Promise<AssetKey>} A promise that resolves to the asset key.\n */\nexport const uploadBlob = async (\n params: Storage & {satellite?: SatelliteOptions}\n): Promise<AssetKey> => uploadAssetIC(params);\n\n/**\n * Uploads a file to the storage.\n * @param {Partial<Pick<Storage, 'filename'>> & Omit<Storage, 'filename' | 'data'> & {data: File} & {satellite?: SatelliteOptions}} params - The storage parameters. Satellite options are required only in NodeJS environment.\n * @returns {Promise<AssetKey>} A promise that resolves to the asset key.\n */\nexport const uploadFile = async (\n params: Partial<Pick<Storage, 'filename'>> &\n Omit<Storage, 'filename' | 'data'> & {data: File} & {satellite?: SatelliteOptions}\n): Promise<AssetKey> =>\n uploadAssetIC({\n filename: params.data.name,\n ...params\n });\n\nconst uploadAssetIC = async ({\n filename: storageFilename,\n data,\n collection,\n headers = [],\n fullPath: storagePath,\n token,\n satellite: satelliteOptions,\n encoding,\n description\n}: Storage & {satellite?: SatelliteOptions}): Promise<AssetKey> => {\n const identity = getIdentity(satelliteOptions?.identity);\n\n // The IC certification does not currently support encoding\n const filename: string = decodeURI(storageFilename);\n const fullPath: string = storagePath ?? `/${collection}/${filename}`;\n\n const satellite = {...satelliteOptions, identity};\n\n await uploadAssetApi({\n data,\n filename,\n collection,\n token,\n headers,\n fullPath,\n encoding,\n satellite,\n description\n });\n\n return {\n downloadUrl: downloadUrl({\n satellite,\n assetKey: {\n fullPath,\n token\n }\n }),\n fullPath,\n name: filename\n };\n};\n\n/**\n * Lists assets in a collection with optional filtering.\n * @param {Object} params - The parameters for listing the assets.\n * @param {string} params.collection - The name of the collection.\n * @param {SatelliteOptions} [params.satellite] - The satellite options (required only in NodeJS environment).\n * @param {ListParams} [params.filter] - The filter parameters.\n * @returns {Promise<Assets>} A promise that resolves to the list of assets.\n */\nexport const listAssets = async ({\n collection,\n satellite: satelliteOptions,\n filter\n}: {\n collection: string;\n satellite?: SatelliteOptions;\n filter?: ListParams;\n}): Promise<Assets> => {\n const satellite = {...satelliteOptions, identity: getIdentity(satelliteOptions?.identity)};\n\n const {items, ...rest} = await listAssetsApi({\n collection,\n satellite,\n filter: filter ?? {}\n });\n\n const assets = items.map(\n ({\n key: {full_path: fullPath, token: t, name, owner, description},\n headers,\n encodings,\n created_at,\n updated_at\n }: AssetNoContent) => {\n const token = fromNullable(t);\n\n return {\n fullPath,\n description: fromNullable(description),\n name,\n downloadUrl: downloadUrl({\n satellite,\n assetKey: {fullPath, token}\n }),\n token,\n headers,\n encodings: encodings.reduce(\n (acc, [type, {modified, sha256, total_length}]) => ({\n ...acc,\n [type]: {\n modified,\n sha256: sha256ToBase64String(sha256),\n total_length\n }\n }),\n {} as Record<string, AssetEncoding>\n ),\n owner: owner.toText(),\n created_at,\n updated_at\n } as Asset;\n }\n );\n\n return {\n items: assets,\n assets,\n ...rest\n };\n};\n\n/**\n * Counts assets in a collection with optional filtering.\n * @param {Object} params - The parameters for counting the assets.\n * @param {string} params.collection - The name of the collection.\n * @param {SatelliteOptions} [params.satellite] - The satellite options (required only in NodeJS environment).\n * @param {ListParams} [params.filter] - The filter parameters for narrowing down the count.\n * @returns {Promise<bigint>} A promise that resolves to the count of assets as a bigint.\n */\nexport const countAssets = async ({\n collection,\n satellite: satelliteOptions,\n filter\n}: {\n collection: string;\n satellite?: SatelliteOptions;\n filter?: ListParams;\n}): Promise<bigint> => {\n const satellite = {...satelliteOptions, identity: getIdentity(satelliteOptions?.identity)};\n\n return countAssetsApi({\n collection,\n satellite,\n filter: filter ?? {}\n });\n};\n\n/**\n * Deletes an asset from the storage.\n * @param {Object} params - The parameters for deleting the asset.\n * @param {string} params.collection - The name of the collection.\n * @param {SatelliteOptions} [params.satellite] - The satellite options (required only in NodeJS environment).\n * @param {string} params.fullPath - The full path of the asset.\n * @returns {Promise<void>} A promise that resolves when the asset is deleted.\n */\nexport const deleteAsset = async ({\n collection,\n fullPath,\n satellite\n}: {\n collection: string;\n satellite?: SatelliteOptions;\n} & Pick<AssetKey, 'fullPath'>): Promise<void> =>\n deleteAssetApi({\n collection,\n fullPath,\n satellite: {...satellite, identity: getIdentity(satellite?.identity)}\n });\n\n/**\n * Deletes multiple assets from the storage.\n * @param {Object} params - The parameters for deleting the assets.\n * @param {Array} params.assets - The list of assets with their collections and full paths.\n * @param {SatelliteOptions} [params.satellite] - The satellite options (required only in NodeJS environment).\n * @returns {Promise<void>} A promise that resolves when the assets are deleted.\n */\nexport const deleteManyAssets = async ({\n assets,\n satellite\n}: {\n assets: ({collection: string} & Pick<AssetKey, 'fullPath'>)[];\n satellite?: SatelliteOptions;\n} & Pick<AssetKey, 'fullPath'>): Promise<void> =>\n deleteManyAssetsApi({\n assets,\n satellite: {...satellite, identity: getIdentity(satellite?.identity)}\n });\n\n/**\n * Retrieves an asset from the storage.\n * @param {Object} params - The parameters for retrieving the asset.\n * @param {string} params.collection - The name of the collection.\n * @param {SatelliteOptions} [params.satellite] - The satellite options (required only in NodeJS environment).\n * @param {string} params.fullPath - The full path of the asset.\n * @returns {Promise<AssetNoContent | undefined>} A promise that resolves to the asset or undefined if not found.\n */\nexport const getAsset = async ({\n satellite,\n ...rest\n}: {\n collection: string;\n satellite?: SatelliteOptions;\n} & Pick<AssetKey, 'fullPath'>): Promise<AssetNoContent | undefined> => {\n const identity = getIdentity(satellite?.identity);\n\n return getAssetApi({...rest, satellite: {...satellite, identity}});\n};\n\n/**\n * Retrieves multiple assets from the storage.\n * @param {Object} params - The parameters for retrieving the assets.\n * @param {Array} params.assets - The list of assets with their collections and full paths.\n * @param {SatelliteOptions} [params.satellite] - The satellite options (required only in NodeJS environment).\n * @returns {Promise<Array<AssetNoContent | undefined>>} A promise that resolves to an array of assets or undefined if not found.\n */\nexport const getManyAssets = async ({\n satellite,\n ...rest\n}: {\n assets: ({collection: string} & Pick<AssetKey, 'fullPath'>)[];\n satellite?: SatelliteOptions;\n}): Promise<(AssetNoContent | undefined)[]> => {\n const identity = getIdentity(satellite?.identity);\n\n return getManyAssetsApi({...rest, satellite: {...satellite, identity}});\n};\n\n/**\n * Generates a download URL for a given asset.\n *\n * @param {Object} params - The parameters for generating the download URL.\n * @param {Object} params.assetKey - The key details of the asset.\n * @param {string} params.assetKey.fullPath - The full path of the asset.\n * @param {string} params.assetKey.token - The access token for the asset.\n * @param {SatelliteOptions} [params.satellite] - The satellite options (required only in NodeJS environment).\n *\n * @returns {string} The generated download URL.\n */\nexport const downloadUrl = ({\n assetKey: {fullPath, token},\n satellite: satelliteOptions\n}: {\n assetKey: Pick<Asset, 'fullPath' | 'token'>;\n} & {satellite?: SatelliteOptions}): string => {\n const satellite = {...satelliteOptions, identity: getIdentity(satelliteOptions?.identity)};\n\n return `${satelliteUrl(satellite)}${fullPath}${nonNullish(token) ? `?token=${token}` : ''}`;\n};\n", "import type {Asset, AssetEncoding, AssetKey, ENCODING_TYPE, Storage} from '@junobuild/storage';\nimport {assertNonNullish} from '@junobuild/utils';\nimport {initAuthTimeoutWorker} from './services/auth-timout.services';\nimport {initAuth} from './services/auth.services';\nimport {AuthStore} from './stores/auth.store';\nimport {EnvStore} from './stores/env.store';\nimport type {User} from './types/auth.types';\nimport type {Environment, UserEnvironment} from './types/env.types';\nimport type {Unsubscribe} from './types/subscription.types';\nimport {envContainer, envSatelliteId} from './utils/window.env.utils';\n\nexport * from './providers/auth.providers';\nexport {signIn, signOut, unsafeIdentity} from './services/auth.services';\nexport * from './services/doc.services';\nexport * from './services/storage.services';\nexport * from './types/auth.types';\nexport * from './types/doc.types';\nexport * from './types/env.types';\nexport {ListOrder, ListPaginate, ListParams, ListResults} from './types/list.types';\nexport * from './types/satellite.types';\nexport * from './types/storage.types';\nexport * from './types/subscription.types';\nexport type {Asset, AssetEncoding, AssetKey, ENCODING_TYPE, Storage};\n\nconst parseEnv = (userEnv?: UserEnvironment): Environment => {\n const satelliteId = userEnv?.satelliteId ?? envSatelliteId();\n\n assertNonNullish(satelliteId, 'Satellite ID is not configured. Juno cannot be initialized.');\n\n const container = userEnv?.container ?? envContainer();\n\n return {\n satelliteId,\n internetIdentityId: userEnv?.internetIdentityId,\n workers: userEnv?.workers,\n container\n };\n};\n\n/**\n * Initializes Juno with the provided optional environment parameters.\n * If no environment is provided, the variables injected by the Vite or NextJS plugins will be used.\n * @deprecated Use {@link initSatellite} instead.\n * @param {UserEnvironment} [userEnv] - The optional user environment configuration.\n * @returns {Promise<Unsubscribe[]>} A promise that resolves to an array of unsubscribe functions.\n */\nexport const initJuno = async (userEnv?: UserEnvironment): Promise<Unsubscribe[]> =>\n initSatellite(userEnv);\n\n/**\n * Initializes a Juno satellite with the provided optional environment parameters.\n * If no environment is provided, the variables injected by the Vite or NextJS plugins will be used.\n * @param {UserEnvironment} [userEnv] - The optional user environment configuration.\n * @returns {Promise<Unsubscribe[]>} A promise that resolves to an array of unsubscribe functions.\n */\nexport const initSatellite = async (userEnv?: UserEnvironment): Promise<Unsubscribe[]> => {\n const env = parseEnv(userEnv);\n\n EnvStore.getInstance().set(env);\n\n await initAuth();\n\n const authSubscribe =\n env.workers?.auth !== undefined ? initAuthTimeoutWorker(env.workers.auth) : undefined;\n\n return [...(authSubscribe ? [authSubscribe] : [])];\n};\n\n/**\n * Subscribes to authentication state changes. i.e. each time a user signs in or signs out, the callback will be triggered.\n * @param {function(User | null): void} callback - The callback function to execute when the authentication state changes.\n * @returns {Unsubscribe} A function to unsubscribe from the authentication state changes.\n */\nexport const authSubscribe = (callback: (authUser: User | null) => void): Unsubscribe =>\n AuthStore.getInstance().subscribe(callback);\n"],
|
|
5
|
-
"mappings": "+WAAA,IAAAA,GAAAC,GAAAC,IAAA,cAEAA,GAAQ,WAAaC,GACrBD,GAAQ,YAAcE,GACtBF,GAAQ,cAAgBG,GAExB,IAAIC,GAAS,CAAC,EACVC,GAAY,CAAC,EACbC,GAAM,OAAO,WAAe,IAAc,WAAa,MAEvDC,GAAO,mEACX,IAASC,GAAI,EAAGC,GAAMF,GAAK,OAAQC,GAAIC,GAAK,EAAED,GAC5CJ,GAAOI,EAAC,EAAID,GAAKC,EAAC,EAClBH,GAAUE,GAAK,WAAWC,EAAC,CAAC,EAAIA,GAFzB,IAAAA,GAAOC,GAOhBJ,GAAU,EAAiB,EAAI,GAC/BA,GAAU,EAAiB,EAAI,GAE/B,SAASK,GAASC,EAAK,CACrB,IAAIF,EAAME,EAAI,OAEd,GAAIF,EAAM,EAAI,EACZ,MAAM,IAAI,MAAM,gDAAgD,EAKlE,IAAIG,EAAWD,EAAI,QAAQ,GAAG,EAC1BC,IAAa,KAAIA,EAAWH,GAEhC,IAAII,EAAkBD,IAAaH,EAC/B,EACA,EAAKG,EAAW,EAEpB,MAAO,CAACA,EAAUC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EAAI,QAAQ,IAAI,EAAI,OAE9E,MAAO,CAAC,GAAIG,EAAgB,CAACA,CAAa,EAAI,CAAC,CAAE,CACnD,EAOaA,GAAiBE,GAC5BC,GAAU,YAAY,EAAE,UAAUD,CAAQ",
|
|
6
|
-
"names": ["require_base64_js", "__commonJSMin", "exports", "byteLength", "toByteArray", "fromByteArray", "lookup", "revLookup", "Arr", "code", "i", "len", "getLens", "b64", "validLen", "placeHoldersLen", "lens", "_byteLength", "tmp", "arr", "curByte", "tripletToBase64", "num", "encodeChunk", "uint8", "start", "end", "output", "extraBytes", "parts", "maxChunkLength", "len2", "require_buffer", "__commonJSMin", "exports", "base64", "ieee754", "customInspectSymbol", "Buffer", "SlowBuffer", "K_MAX_LENGTH", "typedArraySupport", "arr", "proto", "createBuffer", "length", "buf", "arg", "encodingOrOffset", "allocUnsafe", "from", "value", "fromString", "fromArrayView", "isInstance", "fromArrayBuffer", "valueOf", "b", "fromObject", "assertSize", "size", "alloc", "fill", "encoding", "checked", "string", "byteLength", "actual", "fromArrayLike", "array", "i", "arrayView", "copy", "byteOffset", "obj", "len", "numberIsNaN", "a", "x", "y", "list", "buffer", "pos", "mustMatch", "loweredCase", "utf8ToBytes", "base64ToBytes", "slowToString", "start", "end", "hexSlice", "utf8Slice", "asciiSlice", "latin1Slice", "base64Slice", "utf16leSlice", "swap", "n", "m", "str", "max", "target", "thisStart", "thisEnd", "thisCopy", "targetCopy", "bidirectionalIndexOf", "val", "dir", "arrayIndexOf", "indexSize", "arrLength", "valLength", "read", "foundIndex", "found", "j", "hexWrite", "offset", "remaining", "strLen", "parsed", "utf8Write", "blitBuffer", "asciiWrite", "asciiToBytes", "base64Write", "ucs2Write", "utf16leToBytes", "res", "firstByte", "codePoint", "bytesPerSequence", "secondByte", "thirdByte", "fourthByte", "tempCodePoint", "decodeCodePointsArray", "MAX_ARGUMENTS_LENGTH", "codePoints", "ret", "out", "hexSliceLookupTable", "bytes", "newBuf", "checkOffset", "ext", "noAssert", "mul", "defineBigIntMethod", "validateNumber", "first", "last", "boundsError", "lo", "hi", "checkInt", "min", "maxBytes", "wrtBigUInt64LE", "checkIntBI", "wrtBigUInt64BE", "limit", "sub", "checkIEEE754", "writeFloat", "littleEndian", "writeDouble", "targetStart", "code", "errors", "E", "sym", "getMessage", "Base", "name", "range", "input", "msg", "received", "addNumericalSeparator", "checkBounds", "type", "INVALID_BASE64_RE", "base64clean", "units", "leadSurrogate", "byteArray", "c", "src", "dst", "alphabet", "table", "i16", "fn", "BufferBigIntNotDefined", "isNullish", "argument", "nonNullish", "NullishError", "assertNonNullish", "value", "message", "JSON_KEY_BIGINT", "JSON_KEY_PRINCIPAL", "JSON_KEY_UINT8ARRAY", "jsonReplacer", "_key", "Principal", "jsonReviver", "mapValue", "key", "toNullable", "fromNullable", "toArray", "data", "blob", "fromArray", "isBrowser", "Store", "data", "callback", "callbackId", "id", "AuthStore", "_AuthStore", "Store", "authUser", "callback", "unsubscribe", "emit", "message", "detail", "$event", "DELEGATION_IDENTITY_EXPIRATION", "ALLOW_PIN_AUTHENTICATION", "II_POPUP", "NFID_POPUP", "INTERNET_COMPUTER_ORG", "DOCKER_CONTAINER_URL", "DOCKER_INTERNET_IDENTITY_ID", "EnvStore", "_EnvStore", "Store", "env", "callback", "unsubscribe", "popupCenter", "width", "height", "h", "c", "innerWidth", "innerHeight", "y", "x", "InternetIdentityProvider", "#domain", "domain", "windowed", "identityProviderUrl", "container", "EnvStore", "c", "INTERNET_COMPUTER_ORG", "env", "internetIdentityId", "t", "DOCKER_INTERNET_IDENTITY_ID", "containerHost", "protocol", "DOCKER_CONTAINER_URL", "popupCenter", "II_POPUP", "NFIDProvider", "#appName", "#logoUrl", "appName", "logoUrl", "NFID_POPUP", "import_buffer", "ReplicaRejectCode", "domainSeparator", "SignIdentity", "Principal", "request", "body", "fields", "__rest", "requestId", "requestIdOf", "concat", "AnonymousIdentity", "cbor", "randomNumber", "array", "SubmitRequestType", "makeNonce", "buffer", "view", "rand1", "randomNumber", "rand2", "rand3", "rand4", "NANOSECONDS_PER_MILLISECONDS", "REPLICA_PERMITTED_DRIFT_MILLISECONDS", "Expiry", "deltaInMSec", "rounded_down_nanos", "lebEncode", "makeNonceTransform", "nonceFn", "makeNonce", "request", "headers", "httpHeadersTransform", "headers", "headerFields", "value", "key", "AgentHTTPResponseError", "AgentError", "message", "response", "U32_MASK64", "_32n", "fromBig", "n", "le", "split", "lst", "Ah", "Al", "h", "l", "toBig", "shrSH", "_l", "s", "shrSL", "rotrSH", "rotrSL", "rotrBH", "rotrBL", "rotr32H", "_h", "rotr32L", "rotlSH", "rotlSL", "rotlBH", "rotlBL", "add", "Bh", "Bl", "add3L", "Cl", "add3H", "low", "Ch", "add4L", "Dl", "add4H", "Dh", "add5L", "El", "add5H", "Eh", "u64", "fromBig", "split", "toBig", "shrSH", "shrSL", "rotrSH", "rotrSL", "rotrBH", "rotrBL", "rotr32H", "rotr32L", "rotlSH", "rotlSL", "rotlBH", "rotlBL", "add", "add3L", "add3H", "add4L", "add4H", "add5H", "add5L", "u64_default", "SHA512_Kh", "SHA512_Kl", "u64_default", "n", "SHA512_W_H", "SHA512_W_L", "SHA512", "HashMD", "Ah", "Al", "Bh", "Bl", "Ch", "Cl", "Dh", "Dl", "Eh", "El", "Fh", "Fl", "Gh", "Gl", "Hh", "Hl", "view", "offset", "i", "W15h", "W15l", "s0h", "s0l", "W2h", "W2l", "s1h", "s1l", "SUMl", "SUMh", "sigma1h", "sigma1l", "CHIh", "CHIl", "T1ll", "T1h", "T1l", "sigma0h", "sigma0l", "MAJh", "MAJl", "All", "sha512", "wrapConstructor", "SHA512", "_0n", "_1n", "_2n", "_8n", "VERIFY_DEFAULT", "validateOpts", "curve", "opts", "validateBasic", "validateObject", "twistedEdwards", "curveDef", "CURVE", "Fp", "CURVE_ORDER", "prehash", "cHash", "randomBytes", "nByteLength", "cofactor", "MASK", "modP", "uvRatio", "u", "v", "adjustScalarBytes", "bytes", "domain", "data", "ctx", "phflag", "inBig", "n", "inRange", "max", "in0MaskRange", "assertInRange", "assertGE0", "pointPrecomputes", "isPoint", "other", "Point", "ex", "ey", "ez", "et", "x", "y", "points", "toInv", "p", "i", "windowSize", "a", "d", "X", "Y", "Z", "T", "X2", "Y2", "Z2", "Z4", "aX2", "left", "right", "XY", "ZT", "X1", "Y1", "Z1", "X1Z2", "X2Z1", "Y1Z2", "Y2Z1", "A", "B", "D", "x1y1", "E", "G", "F", "X3", "Y3", "T3", "Z3", "T1", "T2", "C", "H", "wnaf", "scalar", "f", "I", "iz", "z", "is0", "ax", "ay", "zz", "hex", "zip215", "len", "ensureBytes", "normed", "lastByte", "bytesToNumberLE", "y2", "isValid", "isXOdd", "isLastByteOdd", "privKey", "getExtendedPublicKey", "numberToBytesLE", "bytesToHex", "wNAF", "modN", "mod", "modN_LE", "hash", "key", "hashed", "head", "prefix", "point", "pointBytes", "getPublicKey", "hashDomainToScalar", "context", "msgs", "msg", "concatBytes", "sign", "options", "r", "R", "k", "s", "res", "verifyOpts", "verify", "sig", "publicKey", "SB", "ED25519_P", "ED25519_SQRT_M1", "_0n", "_1n", "_2n", "_3n", "_5n", "_8n", "ed25519_pow_2_252_3", "x", "_10n", "_20n", "_40n", "_80n", "P", "b2", "b4", "pow2", "b5", "b10", "b20", "b40", "b80", "b160", "b240", "b250", "adjustScalarBytes", "bytes", "uvRatio", "u", "v", "v3", "mod", "v7", "pow", "vx2", "root1", "root2", "useRoot1", "useRoot2", "noRoot", "isNegativeLE", "Fp", "Field", "ED25519_P", "ed25519Defaults", "_8n", "sha512", "randomBytes", "adjustScalarBytes", "uvRatio", "ed25519", "twistedEdwards", "ExpirableMap", "options", "_ExpirableMap_inner", "_ExpirableMap_expirationTime", "_a", "_b", "source", "expirationTime", "currentTime", "__classPrivateFieldSet", "key", "value", "entry", "__classPrivateFieldGet", "iterator", "callbackfn", "thisArg", "encodeLenBytes", "len", "encodeLen", "buf", "offset", "decodeLenBytes", "decodeLen", "lenBytes", "DER_COSE_OID", "ED25519_OID", "SECP256K1_OID", "wrapDER", "payload", "oid", "bitStringHeaderLength", "unwrapDER", "derEncoded", "expect", "n", "msg", "bufEquals", "payloadLen", "result", "Ed25519PublicKey", "_Ed25519PublicKey", "key", "_Ed25519PublicKey_rawKey", "_Ed25519PublicKey_derKey", "__classPrivateFieldSet", "rawKey", "derKey", "publicKey", "wrapDER", "ED25519_OID", "unwrapped", "unwrapDER", "__classPrivateFieldGet", "Observable", "func", "observer", "data", "rest", "ObservableLog", "message", "error", "ExponentialBackoff", "_ExponentialBackoff", "options", "_ExponentialBackoff_currentInterval", "_ExponentialBackoff_randomizationFactor", "_ExponentialBackoff_multiplier", "_ExponentialBackoff_maxInterval", "_ExponentialBackoff_startTime", "_ExponentialBackoff_maxElapsedTime", "_ExponentialBackoff_maxIterations", "_ExponentialBackoff_date", "_ExponentialBackoff_count", "initialInterval", "randomizationFactor", "multiplier", "maxInterval", "maxElapsedTime", "maxIterations", "date", "__classPrivateFieldSet", "__classPrivateFieldGet", "delta", "min", "max", "_a", "RequestStatusResponseStatus", "DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS", "IC_ROOT_KEY", "IC0_DOMAIN", "IC0_SUB_DOMAIN", "ICP0_DOMAIN", "ICP0_SUB_DOMAIN", "ICP_API_DOMAIN", "ICP_API_SUB_DOMAIN", "HttpDefaultFetchError", "AgentError", "message", "IdentityInvalidError", "getDefaultFetch", "defaultFetch", "HttpAgent", "_HttpAgent", "options", "fromHex", "IC_ROOT_KEY", "_HttpAgent_retryTimes", "_HttpAgent_backoffStrategy", "_HttpAgent_waterMark", "ObservableLog", "_HttpAgent_queryPipeline", "_HttpAgent_updatePipeline", "_HttpAgent_subnetKeys", "ExpirableMap", "_HttpAgent_verifyQuerySignatures", "_HttpAgent_verifyQueryResponse", "queryResponse", "subnetStatus", "__classPrivateFieldGet", "CertificateVerificationError", "status", "signatures", "requestId", "domainSeparator", "sig", "timestamp", "identity", "nodeId", "Principal", "hash", "reply", "hashOfMap", "reject_code", "reject_message", "error_code", "separatorWithHash", "concat", "pubKey", "rawKey", "Ed25519PublicKey", "ed25519", "location", "knownHosts", "remoteHosts", "hostname", "knownHost", "host", "__classPrivateFieldSet", "_a", "defaultBackoffFactory", "ExponentialBackoff", "name", "password", "AnonymousIdentity", "makeNonceTransform", "makeNonce", "log", "type", "fn", "priority", "x", "canisterId", "id", "canister", "ecid", "sender", "ingress_expiry", "Expiry", "DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS", "submit", "SubmitRequestType", "transformedRequest", "body", "encode", "backoff", "request", "_HttpAgent_instances", "_HttpAgent_requestAndRetry", "response", "requestIdOf", "responseBuffer", "responseBody", "decode", "httpHeadersTransform", "fields", "makeQuery", "args", "_HttpAgent_requestAndRetryQuery", "getSubnetStatus", "query", "updatedSubnetStatus", "decodedResponse", "parsedTime", "tree", "decoded", "timeLookup", "lookup_path", "LookupStatus", "date", "decodeTime", "bufFromBufLike", "CanisterStatus", "callTime", "replicaTime", "error", "headers", "effectiveCanisterId", "subnetResponse", "p", "r", "r2", "tries", "delay", "resolve", "fetchResponse", "AgentHTTPResponseError", "_b", "timeStampInMs", "responseText", "errorMessage", "ProxyMessageKind", "getDefaultAgent", "agent", "strategy_exports", "__export", "backoff", "chain", "conditionalDelay", "defaultStrategy", "maxAttempts", "once", "throttle", "timeout", "FIVE_MINUTES_IN_MSEC", "defaultStrategy", "chain", "conditionalDelay", "once", "backoff", "timeout", "first", "condition", "timeInMsec", "canisterId", "requestId", "status", "resolve", "maxAttempts", "count", "attempts", "toHex", "throttle", "throttleInMsec", "end", "startingThrottleInMsec", "backoffFactor", "currentThrottling", "strategies", "a", "pollForResponse", "agent", "canisterId", "requestId", "strategy", "request", "blsVerify", "path", "currentRequest", "_a", "state", "cert", "Certificate", "maybeBuf", "lookupResultToBuffer", "status", "RequestStatusResponseStatus", "rejectCode", "rejectMessage", "toHex", "management_idl_default", "IDL", "bitcoin_network", "bitcoin_address", "bitcoin_get_balance_args", "satoshi", "bitcoin_get_balance_result", "bitcoin_get_current_fee_percentiles_args", "millisatoshi_per_byte", "bitcoin_get_current_fee_percentiles_result", "bitcoin_get_utxos_args", "block_hash", "outpoint", "utxo", "bitcoin_get_utxos_result", "bitcoin_send_transaction_args", "canister_id", "canister_info_args", "change_origin", "change_details", "change", "canister_info_result", "canister_status_args", "log_visibility", "definite_canister_settings", "canister_status_result", "clear_chunk_store_args", "canister_settings", "create_canister_args", "create_canister_result", "delete_canister_args", "deposit_cycles_args", "ecdsa_curve", "ecdsa_public_key_args", "ecdsa_public_key_result", "fetch_canister_logs_args", "canister_log_record", "fetch_canister_logs_result", "http_header", "http_request_result", "http_request_args", "canister_install_mode", "chunk_hash", "install_chunked_code_args", "wasm_module", "install_code_args", "node_metrics_history_args", "node_metrics", "node_metrics_history_result", "provisional_create_canister_with_cycles_args", "provisional_create_canister_with_cycles_result", "provisional_top_up_canister_args", "raw_rand_result", "sign_with_ecdsa_args", "sign_with_ecdsa_result", "start_canister_args", "stop_canister_args", "stored_chunks_args", "stored_chunks_result", "uninstall_code_args", "update_settings_args", "upload_chunk_args", "upload_chunk_result", "ActorCallError", "AgentError", "canisterId", "methodName", "type", "props", "n", "QueryCallRejectedError", "result", "_a", "ReplicaRejectCode", "UpdateCallRejectedError", "requestId", "response", "toHex", "metadataSymbol", "Actor", "_Actor", "metadata", "actor", "Principal", "fields", "config", "mode", "arg", "wasmModule", "getManagementCanister", "settings", "settingsToCanisterSettings", "interfaceFactory", "options", "service", "idl_exports", "CanisterActor", "DEFAULT_ACTOR_CONFIG", "func", "ACTOR_METHOD_WITH_HTTP_DETAILS", "_createActorMethod", "configuration", "decodeReturnValue", "types", "msg", "returnValues", "strategy_exports", "blsVerify", "caller", "args", "_b", "agent", "getDefaultAgent", "cid", "effectiveCanisterId", "pollingStrategyFactory", "ecid", "pollStrategy", "responseBytes", "pollForResponse", "shouldIncludeHttpDetails", "handler", "transform", "_methodName", "first", "management_idl_default", "isObject", "value", "Ed25519PublicKey", "_Ed25519PublicKey", "key", "_Ed25519PublicKey_rawKey", "_Ed25519PublicKey_derKey", "__classPrivateFieldSet", "maybeKey", "fromHex", "view", "bufFromBufLike", "rawKey", "derKey", "publicKey", "wrapDER", "ED25519_OID", "unwrapped", "unwrapDER", "__classPrivateFieldGet", "Ed25519KeyIdentity", "_Ed25519KeyIdentity", "SignIdentity", "privateKey", "_Ed25519KeyIdentity_publicKey", "_Ed25519KeyIdentity_privateKey", "seed", "ed25519", "bufEquals", "sk", "pk", "obj", "publicKeyDer", "privateKeyRaw", "json", "parsed", "secretKey", "toHex", "challenge", "blob", "signature", "uint8ToBuf", "sig", "msg", "message", "x", "CryptoError", "_CryptoError", "message", "_getEffectiveCrypto", "subtleCrypto", "ECDSAKeyIdentity", "_ECDSAKeyIdentity", "SignIdentity", "keyPair", "derKey", "options", "extractable", "keyUsages", "effectiveCrypto", "key", "challenge", "params", "cbor", "PartialIdentity", "inner", "_PartialIdentity_inner", "__classPrivateFieldSet", "__classPrivateFieldGet", "Principal", "domainSeparator", "requestDomainSeparator", "_parseBlob", "value", "fromHex", "Delegation", "pubkey", "expiration", "targets", "t", "toHex", "p", "_createSingleDelegation", "from", "to", "delegation", "challenge", "requestIdOf", "signature", "DelegationChain", "_DelegationChain", "delegations", "publicKey", "options", "_a", "_b", "json", "parsedDelegations", "signedDelegation", "Principal", "DelegationIdentity", "SignIdentity", "_inner", "_delegation", "key", "blob", "request", "body", "fields", "__rest", "requestId", "PartialDelegationIdentity", "_PartialDelegationIdentity", "PartialIdentity", "inner", "_PartialDelegationIdentity_delegation", "__classPrivateFieldSet", "__classPrivateFieldGet", "isDelegationValid", "chain", "checks", "scopes", "maybeScope", "s", "scope", "none", "target", "import_borc", "PubKeyCoseAlgo", "events", "IdleManager", "options", "onIdle", "idleTimeout", "_resetTimer", "name", "debounce", "func", "wait", "timeout", "args", "context", "later", "scroll", "_a", "callback", "cb", "exit", "instanceOfAny", "object", "constructors", "c", "idbProxyableTypes", "cursorAdvanceMethods", "getIdbProxyableTypes", "getCursorAdvanceMethods", "cursorRequestMap", "transactionDoneMap", "transactionStoreNamesMap", "transformCache", "reverseTransformCache", "promisifyRequest", "request", "promise", "resolve", "reject", "unlisten", "success", "error", "wrap", "value", "cacheDonePromiseForTransaction", "tx", "done", "complete", "idbProxyTraps", "target", "prop", "receiver", "replaceTraps", "callback", "wrapFunction", "func", "storeNames", "args", "unwrap", "transformCachableValue", "newValue", "openDB", "name", "version", "blocked", "upgrade", "blocking", "terminated", "request", "openPromise", "wrap", "event", "db", "readMethods", "writeMethods", "cachedMethods", "getMethod", "target", "prop", "targetFuncName", "useIndex", "isWrite", "method", "storeName", "args", "tx", "replaceTraps", "oldTraps", "receiver", "AUTH_DB_NAME", "OBJECT_STORE_NAME", "_openDbStore", "dbName", "storeName", "version", "isBrowser", "KEY_STORAGE_DELEGATION", "KEY_STORAGE_KEY", "openDB", "database", "_getValue", "db", "key", "_setValue", "value", "_removeValue", "IdbKeyVal", "_IdbKeyVal", "_db", "_storeName", "options", "DB_VERSION", "_a", "KEY_STORAGE_KEY", "KEY_STORAGE_DELEGATION", "KEY_VECTOR", "DB_VERSION", "isBrowser", "LocalStorage", "prefix", "_localStorage", "key", "value", "ls", "IdbStorage", "options", "_IdbStorage_options", "__classPrivateFieldSet", "resolve", "IdbKeyVal", "__classPrivateFieldGet", "db", "IDENTITY_PROVIDER_DEFAULT", "IDENTITY_PROVIDER_ENDPOINT", "ECDSA_KEY_LABEL", "ED25519_KEY_LABEL", "INTERRUPT_CHECK_INTERVAL", "ERROR_USER_INTERRUPT", "AuthClient", "_identity", "_key", "_chain", "_storage", "idleManager", "_createOptions", "_idpWindow", "_eventHandler", "options", "storage", "_a", "IdbStorage", "keyType", "_b", "key", "maybeIdentityStorage", "KEY_STORAGE_KEY", "isBrowser", "fallbackLocalStorage", "LocalStorage", "localChain", "KEY_STORAGE_DELEGATION", "localKey", "error", "Ed25519KeyIdentity", "ECDSAKeyIdentity", "identity", "AnonymousIdentity", "chain", "chainStorage", "DelegationChain", "isDelegationValid", "PartialDelegationIdentity", "DelegationIdentity", "_deleteStorage", "e", "_c", "IdleManager", "idleOptions", "message", "onSuccess", "delegations", "signedDelegation", "Delegation", "delegationChain", "defaultTimeToLive", "identityProviderUrl", "_d", "checkInterruption", "event", "request", "err", "errorMessage", "onError", "KEY_VECTOR", "createAuthClient", "AuthClient", "mapData", "data", "B", "err", "toSetDoc", "doc", "data", "version", "description", "g", "R", "toDelDoc", "fromDoc", "key", "owner", "docDescription", "rest", "j", "B", "toListMatcherTimestamp", "matcher", "c", "g", "toListParams", "paginate", "order", "owner", "Principal", "idlFactory", "IDL", "CommitBatch", "ListOrderField", "ListOrder", "TimestampMatcher", "ListMatcher", "ListPaginate", "ListParams", "DeleteControllersArgs", "ControllerScope", "Controller", "DelDoc", "RulesType", "DelRule", "DepositCyclesArgs", "AssetKey", "AssetEncodingNoContent", "AssetNoContent", "AuthenticationConfigInternetIdentity", "AuthenticationConfig", "ConfigMaxMemorySize", "DbConfig", "StorageConfigIFrame", "StorageConfigRawAccess", "StorageConfigRedirect", "StorageConfig", "Config", "Doc", "HttpRequest", "Memory", "StreamingCallbackToken", "StreamingStrategy", "HttpResponse", "StreamingCallbackHttpResponse", "InitAssetKey", "InitUploadResult", "ListResults", "CustomDomain", "ListResults_1", "Permission", "Rule", "MemorySize", "SetController", "SetControllersArgs", "SetDoc", "SetRule", "UploadChunk", "UploadChunkResult", "createActor", "canisterId", "idlFactory", "identity", "fetch", "container", "host", "t", "DOCKER_CONTAINER_URL", "agent", "HttpAgent", "Actor", "satelliteUrl", "customSatelliteId", "customContainer", "satelliteId", "customOrEnvSatelliteId", "container", "customOrEnvContainer", "t", "containerHost", "protocol", "DOCKER_CONTAINER_URL", "EnvStore", "getSatelliteActor", "customSatelliteId", "customContainer", "rest", "satelliteId", "customOrEnvSatelliteId", "x", "container", "customOrEnvContainer", "createActor", "idlFactory", "getDoc", "collection", "key", "satellite", "get_doc", "getSatelliteActor", "doc", "j", "c", "fromDoc", "getManyDocs", "docs", "get_many_docs", "payload", "resultsDocs", "results", "resultDoc", "t", "setDoc", "set_doc", "toSetDoc", "updatedDoc", "setManyDocs", "set_many_docs", "updatedDocs", "deleteDoc", "del_doc", "toDelDoc", "deleteManyDocs", "del_many_docs", "listDocs", "filter", "list_docs", "items", "items_page", "items_length", "matches_length", "matches_pages", "toListParams", "item", "dataArray", "owner", "description", "version", "rest", "mapData", "countDocs", "count_docs", "getIdentity", "identity", "AnonymousIdentity", "getDoc", "satellite", "rest", "identity", "getIdentity", "getManyDocs", "setDoc", "setManyDocs", "deleteDoc", "deleteManyDocs", "listDocs", "filter", "countDocs", "initUser", "provider", "identity", "getIdentity", "c", "userId", "user", "getDoc", "createUser", "rest", "setDoc", "authClient", "initAuth", "provider", "createAuthClient", "user", "initUser", "AuthStore", "signIn", "options", "resolve", "reject", "InternetIdentityProvider", "error", "DELEGATION_IDENTITY_EXPIRATION", "ALLOW_PIN_AUTHENTICATION", "signOut", "getIdentity", "unsafeIdentity", "initAuthTimeoutWorker", "auth", "workerUrl", "worker", "timeoutSignOut", "emit", "signOut", "data", "msg", "value", "AuthStore", "user", "c", "envSatelliteId", "viteEnvSatelliteId", "envContainer", "viteEnvContainer", "isNullish", "argument", "nonNullish", "toNullable", "value", "isBrowser", "uploadAsset", "data", "filename", "collection", "headers", "token", "fullPath", "encoding", "description", "actor", "init_asset_upload", "batchId", "g", "chunkSize", "uploadChunks", "clone", "h", "orderId", "start", "chunk", "chunkIds", "results", "batchUploadChunks", "contentType", "type", "_", "chunk_id", "limit", "i", "batch", "params", "uploadChunk", "uploadAsset", "satellite", "asset", "actor", "getSatelliteActor", "B", "initAssetKey", "listAssets", "collection", "filter", "list_assets", "assets", "items_length", "items_page", "matches_length", "matches_pages", "toListParams", "_", "j", "countAssets", "count_assets", "deleteAsset", "fullPath", "deleteManyAssets", "del_many_assets", "payload", "getAsset", "get_asset", "getManyAssets", "get_many_assets", "resultAsset", "sha256ToBase64String", "sha256", "c", "uploadBlob", "params", "uploadAssetIC", "uploadFile", "storageFilename", "data", "collection", "headers", "storagePath", "token", "satelliteOptions", "encoding", "description", "identity", "getIdentity", "filename", "fullPath", "satellite", "uploadAsset", "downloadUrl", "listAssets", "filter", "items", "rest", "assets", "t", "name", "owner", "encodings", "created_at", "updated_at", "j", "acc", "type", "modified", "sha256", "total_length", "sha256ToBase64String", "countAssets", "deleteAsset", "deleteManyAssets", "getAsset", "getManyAssets", "satelliteUrl", "parseEnv", "userEnv", "satelliteId", "envSatelliteId", "x", "container", "envContainer", "initJuno", "initSatellite", "env", "EnvStore", "initAuth", "authSubscribe", "initAuthTimeoutWorker", "callback", "AuthStore"]
|
|
4
|
+
"sourcesContent": ["'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n", "/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh <https://feross.org>\n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nconst base64 = require('base64-js')\nconst ieee754 = require('ieee754')\nconst customInspectSymbol =\n (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation\n ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation\n : null\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nconst K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n const arr = new Uint8Array(1)\n const proto = { foo: function () { return 42 } }\n Object.setPrototypeOf(proto, Uint8Array.prototype)\n Object.setPrototypeOf(arr, proto)\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n const buf = new Uint8Array(length)\n Object.setPrototypeOf(buf, Buffer.prototype)\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayView(value)\n }\n\n if (value == null) {\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof SharedArrayBuffer !== 'undefined' &&\n (isInstance(value, SharedArrayBuffer) ||\n (value && isInstance(value.buffer, SharedArrayBuffer)))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n const valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n const b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length)\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nObject.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)\nObject.setPrototypeOf(Buffer, Uint8Array)\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpreted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n const length = byteLength(string, encoding) | 0\n let buf = createBuffer(length)\n\n const actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n const length = array.length < 0 ? 0 : checked(array.length) | 0\n const buf = createBuffer(length)\n for (let i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayView (arrayView) {\n if (isInstance(arrayView, Uint8Array)) {\n const copy = new Uint8Array(arrayView)\n return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)\n }\n return fromArrayLike(arrayView)\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n let buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(buf, Buffer.prototype)\n\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n const len = checked(obj.length) | 0\n const buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n let x = a.length\n let y = b.length\n\n for (let i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n let i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n const buffer = Buffer.allocUnsafe(length)\n let pos = 0\n for (i = 0; i < list.length; ++i) {\n let buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n if (pos + buf.length > buffer.length) {\n if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)\n buf.copy(buffer, pos)\n } else {\n Uint8Array.prototype.set.call(\n buffer,\n buf,\n pos\n )\n }\n } else if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n } else {\n buf.copy(buffer, pos)\n }\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n const len = string.length\n const mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n let loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coercion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n const i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n const len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (let i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n const len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (let i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n const len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (let i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n const length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n let str = ''\n const max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return '<Buffer ' + str + '>'\n}\nif (customInspectSymbol) {\n Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n let x = thisEnd - thisStart\n let y = end - start\n const len = Math.min(x, y)\n\n const thisCopy = this.slice(thisStart, thisEnd)\n const targetCopy = target.slice(start, end)\n\n for (let i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n let indexSize = 1\n let arrLength = arr.length\n let valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n let i\n if (dir) {\n let foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n let found = true\n for (let j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n const remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n const strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n let i\n for (i = 0; i < length; ++i) {\n const parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n const remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n case 'latin1':\n case 'binary':\n return asciiWrite(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n const res = []\n\n let i = start\n while (i < end) {\n const firstByte = buf[i]\n let codePoint = null\n let bytesPerSequence = (firstByte > 0xEF)\n ? 4\n : (firstByte > 0xDF)\n ? 3\n : (firstByte > 0xBF)\n ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n let secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nconst MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n const len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n let res = ''\n let i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n const len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n let out = ''\n for (let i = start; i < end; ++i) {\n out += hexSliceLookupTable[buf[i]]\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n const bytes = buf.slice(start, end)\n let res = ''\n // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)\n for (let i = 0; i < bytes.length - 1; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n const len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n const newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(newBuf, Buffer.prototype)\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUintLE =\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUintBE =\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n let val = this[offset + --byteLength]\n let mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUint8 =\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUint16LE =\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUint16BE =\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUint32LE =\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUint32BE =\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const lo = first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24\n\n const hi = this[++offset] +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n last * 2 ** 24\n\n return BigInt(lo) + (BigInt(hi) << BigInt(32))\n})\n\nBuffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const hi = first * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n const lo = this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last\n\n return (BigInt(hi) << BigInt(32)) + BigInt(lo)\n})\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let i = byteLength\n let mul = 1\n let val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = this[offset + 4] +\n this[offset + 5] * 2 ** 8 +\n this[offset + 6] * 2 ** 16 +\n (last << 24) // Overflow\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24)\n})\n\nBuffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = (first << 24) + // Overflow\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last)\n})\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUintLE =\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let mul = 1\n let i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUintBE =\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let i = byteLength - 1\n let mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUint8 =\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUint16LE =\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUint16BE =\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUint32LE =\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUint32BE =\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction wrtBigUInt64LE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n return offset\n}\n\nfunction wrtBigUInt64BE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset + 7] = lo\n lo = lo >> 8\n buf[offset + 6] = lo\n lo = lo >> 8\n buf[offset + 5] = lo\n lo = lo >> 8\n buf[offset + 4] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset + 3] = hi\n hi = hi >> 8\n buf[offset + 2] = hi\n hi = hi >> 8\n buf[offset + 1] = hi\n hi = hi >> 8\n buf[offset] = hi\n return offset + 8\n}\n\nBuffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = 0\n let mul = 1\n let sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = byteLength - 1\n let mul = 1\n let sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nBuffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n const len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n const code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n } else if (typeof val === 'boolean') {\n val = Number(val)\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n let i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n const bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n const len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// CUSTOM ERRORS\n// =============\n\n// Simplified versions from Node, changed for Buffer-only usage\nconst errors = {}\nfunction E (sym, getMessage, Base) {\n errors[sym] = class NodeError extends Base {\n constructor () {\n super()\n\n Object.defineProperty(this, 'message', {\n value: getMessage.apply(this, arguments),\n writable: true,\n configurable: true\n })\n\n // Add the error code to the name to include it in the stack trace.\n this.name = `${this.name} [${sym}]`\n // Access the stack to generate the error message including the error code\n // from the name.\n this.stack // eslint-disable-line no-unused-expressions\n // Reset the name to the actual name.\n delete this.name\n }\n\n get code () {\n return sym\n }\n\n set code (value) {\n Object.defineProperty(this, 'code', {\n configurable: true,\n enumerable: true,\n value,\n writable: true\n })\n }\n\n toString () {\n return `${this.name} [${sym}]: ${this.message}`\n }\n }\n}\n\nE('ERR_BUFFER_OUT_OF_BOUNDS',\n function (name) {\n if (name) {\n return `${name} is outside of buffer bounds`\n }\n\n return 'Attempt to access memory outside buffer bounds'\n }, RangeError)\nE('ERR_INVALID_ARG_TYPE',\n function (name, actual) {\n return `The \"${name}\" argument must be of type number. Received type ${typeof actual}`\n }, TypeError)\nE('ERR_OUT_OF_RANGE',\n function (str, range, input) {\n let msg = `The value of \"${str}\" is out of range.`\n let received = input\n if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {\n received = addNumericalSeparator(String(input))\n } else if (typeof input === 'bigint') {\n received = String(input)\n if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {\n received = addNumericalSeparator(received)\n }\n received += 'n'\n }\n msg += ` It must be ${range}. Received ${received}`\n return msg\n }, RangeError)\n\nfunction addNumericalSeparator (val) {\n let res = ''\n let i = val.length\n const start = val[0] === '-' ? 1 : 0\n for (; i >= start + 4; i -= 3) {\n res = `_${val.slice(i - 3, i)}${res}`\n }\n return `${val.slice(0, i)}${res}`\n}\n\n// CHECK FUNCTIONS\n// ===============\n\nfunction checkBounds (buf, offset, byteLength) {\n validateNumber(offset, 'offset')\n if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {\n boundsError(offset, buf.length - (byteLength + 1))\n }\n}\n\nfunction checkIntBI (value, min, max, buf, offset, byteLength) {\n if (value > max || value < min) {\n const n = typeof min === 'bigint' ? 'n' : ''\n let range\n if (byteLength > 3) {\n if (min === 0 || min === BigInt(0)) {\n range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`\n } else {\n range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` +\n `${(byteLength + 1) * 8 - 1}${n}`\n }\n } else {\n range = `>= ${min}${n} and <= ${max}${n}`\n }\n throw new errors.ERR_OUT_OF_RANGE('value', range, value)\n }\n checkBounds(buf, offset, byteLength)\n}\n\nfunction validateNumber (value, name) {\n if (typeof value !== 'number') {\n throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)\n }\n}\n\nfunction boundsError (value, length, type) {\n if (Math.floor(value) !== value) {\n validateNumber(value, type)\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value)\n }\n\n if (length < 0) {\n throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()\n }\n\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset',\n `>= ${type ? 1 : 0} and <= ${length}`,\n value)\n}\n\n// HELPER FUNCTIONS\n// ================\n\nconst INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n let codePoint\n const length = string.length\n let leadSurrogate = null\n const bytes = []\n\n for (let i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n let c, hi, lo\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n let i\n for (i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n\n// Create lookup table for `toString('hex')`\n// See: https://github.com/feross/buffer/issues/219\nconst hexSliceLookupTable = (function () {\n const alphabet = '0123456789abcdef'\n const table = new Array(256)\n for (let i = 0; i < 16; ++i) {\n const i16 = i * 16\n for (let j = 0; j < 16; ++j) {\n table[i16 + j] = alphabet[i] + alphabet[j]\n }\n }\n return table\n})()\n\n// Return not function with Error if BigInt not supported\nfunction defineBigIntMethod (fn) {\n return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn\n}\n\nfunction BufferBigIntNotDefined () {\n throw new Error('BigInt not supported')\n}\n", "/**\n * Creates a debounced function that delays invoking the provided function until after the specified timeout.\n * @param {Function} func - The function to debounce.\n * @param {number} [timeout=300] - The number of milliseconds to delay. Defaults to 300ms if not specified or invalid.\n * @returns {Function} A debounced function.\n */\n/* eslint-disable-next-line @typescript-eslint/ban-types */\nexport const debounce = (func: Function, timeout?: number): Function => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n return (...args: unknown[]) => {\n const next = () => func(...args);\n\n if (timer) {\n clearTimeout(timer);\n }\n\n timer = setTimeout(next, timeout !== undefined && timeout > 0 ? timeout : 300);\n };\n};\n", "import {Principal} from '@dfinity/principal';\nimport {nonNullish} from './null.utils';\n\nconst JSON_KEY_BIGINT = '__bigint__';\nconst JSON_KEY_PRINCIPAL = '__principal__';\nconst JSON_KEY_UINT8ARRAY = '__uint8array__';\n\n/**\n * A function that alters the behavior of the stringification process for BigInt, Principal, and Uint8Array.\n * @param {string} _key - The key of the value being stringified.\n * @param {unknown} value - The value being stringified.\n * @returns {unknown} The altered value for stringification.\n */\nexport const jsonReplacer = (_key: string, value: unknown): unknown => {\n if (typeof value === 'bigint') {\n return {[JSON_KEY_BIGINT]: `${value}`};\n }\n\n if (nonNullish(value) && value instanceof Principal) {\n return {[JSON_KEY_PRINCIPAL]: value.toText()};\n }\n\n if (nonNullish(value) && value instanceof Uint8Array) {\n return {[JSON_KEY_UINT8ARRAY]: Array.from(value)};\n }\n\n return value;\n};\n\n/**\n * A parser that interprets revived BigInt, Principal, and Uint8Array when constructing JavaScript values or objects.\n * @param {string} _key - The key of the value being parsed.\n * @param {unknown} value - The value being parsed.\n * @returns {unknown} The parsed value.\n */\nexport const jsonReviver = (_key: string, value: unknown): unknown => {\n const mapValue = <T>(key: string): T => (value as Record<string, T>)[key];\n\n if (nonNullish(value) && typeof value === 'object' && JSON_KEY_BIGINT in value) {\n return BigInt(mapValue(JSON_KEY_BIGINT));\n }\n\n if (nonNullish(value) && typeof value === 'object' && JSON_KEY_PRINCIPAL in value) {\n return Principal.fromText(mapValue(JSON_KEY_PRINCIPAL));\n }\n\n if (nonNullish(value) && typeof value === 'object' && JSON_KEY_UINT8ARRAY in value) {\n return Uint8Array.from(mapValue(JSON_KEY_UINT8ARRAY));\n }\n\n return value;\n};\n", "/**\n * Checks if the provided argument is null or undefined.\n * @template T\n * @param {T | undefined | null} argument - The argument to check.\n * @returns {boolean} True if the argument is null or undefined, false otherwise.\n */\nexport const isNullish = <T>(argument: T | undefined | null): argument is undefined | null =>\n argument === null || argument === undefined;\n\n/**\n * Checks if the provided argument is neither null nor undefined.\n * @template T\n * @param {T | undefined | null} argument - The argument to check.\n * @returns {boolean} True if the argument is neither null nor undefined, false otherwise.\n */\nexport const nonNullish = <T>(argument: T | undefined | null): argument is NonNullable<T> =>\n !isNullish(argument);\n\n/**\n * Represents an error thrown when a value is null or undefined.\n * @class\n * @extends {Error}\n */\nexport class NullishError extends Error {}\n\n/**\n * Asserts that a value is neither null nor undefined.\n * @template T\n * @param {T} value - The value to check.\n * @param {string} [message] - The optional error message to use if the assertion fails.\n * @throws {NullishError} If the value is null or undefined.\n * @returns {asserts value is NonNullable<T>} Asserts that the value is neither null nor undefined.\n */\nexport const assertNonNullish: <T>(\n value: T,\n message?: string\n) => asserts value is NonNullable<T> = <T>(value: T, message?: string): void => {\n if (isNullish(value)) {\n throw new NullishError(message);\n }\n};\n", "import {jsonReplacer, jsonReviver} from './json.utils';\nimport {nonNullish} from './null.utils';\n\n/**\n * Converts a value to a nullable array.\n * @template T\n * @param {T} [value] - The value to convert.\n * @returns {([] | [T])} A nullable array containing the value if non-nullish, or an empty array if nullish.\n */\nexport const toNullable = <T>(value?: T): [] | [T] => {\n return nonNullish(value) ? [value] : [];\n};\n\n/**\n * Extracts a value from a nullable array.\n * @template T\n * @param {([] | [T])} value - The nullable array.\n * @returns {(T | undefined)} The value if present, or undefined if the array is empty.\n */\nexport const fromNullable = <T>(value: [] | [T]): T | undefined => {\n return value?.[0];\n};\n\n/**\n * Converts data to a Uint8Array for transmission or storage.\n * @template T\n * @param {T} data - The data to convert.\n * @returns {Promise<Uint8Array>} A promise that resolves to a Uint8Array representation of the data.\n */\nexport const toArray = async <T>(data: T): Promise<Uint8Array> => {\n const blob: Blob = new Blob([JSON.stringify(data, jsonReplacer)], {\n type: 'application/json; charset=utf-8'\n });\n return new Uint8Array(await blob.arrayBuffer());\n};\n\n/**\n * Converts a Uint8Array or number array back to the original data type.\n * @template T\n * @param {(Uint8Array | number[])} data - The array to convert.\n * @returns {Promise<T>} A promise that resolves to the original data.\n */\nexport const fromArray = async <T>(data: Uint8Array | number[]): Promise<T> => {\n const blob: Blob = new Blob([data instanceof Uint8Array ? data : new Uint8Array(data)], {\n type: 'application/json; charset=utf-8'\n });\n return JSON.parse(await blob.text(), jsonReviver);\n};\n", "/**\n * Checks if the current environment is a browser.\n * @returns {boolean} True if the current environment is a browser, false otherwise.\n */\nexport const isBrowser = (): boolean => typeof window !== `undefined`;\n", "export abstract class Store<T> {\n private callbacks: {id: symbol; callback: (data: T | null) => void}[] = [];\n\n protected populate(data: T | null) {\n this.callbacks.forEach(({callback}: {id: symbol; callback: (data: T | null) => void}) =>\n callback(data)\n );\n }\n\n subscribe(callback: (data: T | null) => void): () => void {\n const callbackId = Symbol();\n this.callbacks.push({id: callbackId, callback});\n\n return () =>\n (this.callbacks = this.callbacks.filter(\n ({id}: {id: symbol; callback: (data: T | null) => void}) => id !== callbackId\n ));\n }\n}\n", "import type {User} from '../types/auth.types';\nimport type {Unsubscribe} from '../types/subscription.types';\nimport {Store} from './store';\n\nexport class AuthStore extends Store<User | null> {\n private static instance: AuthStore;\n\n private authUser: User | null = null;\n\n private constructor() {\n super();\n }\n\n static getInstance() {\n if (!AuthStore.instance) {\n AuthStore.instance = new AuthStore();\n }\n return AuthStore.instance;\n }\n\n set(authUser: User | null) {\n this.authUser = authUser;\n\n this.populate(authUser);\n }\n\n get(): User | null {\n return this.authUser;\n }\n\n override subscribe(callback: (data: User | null) => void): Unsubscribe {\n const unsubscribe: () => void = super.subscribe(callback);\n\n callback(this.authUser);\n\n return unsubscribe;\n }\n\n reset() {\n this.authUser = null;\n\n this.populate(this.authUser);\n }\n}\n", "export const emit = <T>({message, detail}: {message: string; detail?: T | undefined}) => {\n const $event: CustomEvent<T> = new CustomEvent<T>(message, {detail, bubbles: true});\n document.dispatchEvent($event);\n};\n", "// How long the delegation identity should remain valid?\n// e.g. BigInt(7 * 24 * 60 * 60 * 1000 * 1000 * 1000) = 7 days in nanoseconds\n// For Juno: 4 hours\nexport const DELEGATION_IDENTITY_EXPIRATION = BigInt(4 * 60 * 60 * 1000 * 1000 * 1000);\n\n// We consider PIN authentication as \"insecure\" because users can easily lose their PIN if they do not register a passphrase, especially since Safari clears the browser cache every two weeks in cases of inactivity.\n// That's why we disable it by default.\nexport const ALLOW_PIN_AUTHENTICATION = false;\n\nexport const II_POPUP: {width: number; height: number} = {width: 576, height: 576};\nexport const NFID_POPUP: {width: number; height: number} = {width: 505, height: 705};\n\nexport const INTERNET_COMPUTER_ORG = 'internetcomputer.org';\n\n// Worker\nexport const AUTH_TIMER_INTERVAL = 1000;\n", "export const DOCKER_CONTAINER_URL = 'http://127.0.0.1:5987';\nexport const DOCKER_INTERNET_IDENTITY_ID = 'rdmx6-jaaaa-aaaaa-aaadq-cai';\n", "import type {Environment} from '../types/env.types';\nimport {Store} from './store';\n\nexport class EnvStore extends Store<Environment | undefined> {\n private static instance: EnvStore;\n\n private env: Environment | undefined;\n\n private constructor() {\n super();\n }\n\n static getInstance() {\n if (!EnvStore.instance) {\n EnvStore.instance = new EnvStore();\n }\n return EnvStore.instance;\n }\n\n set(env: Environment | undefined) {\n this.env = env;\n\n this.populate(env);\n }\n\n get(): Environment | undefined {\n return this.env;\n }\n\n override subscribe(callback: (data: Environment | null | undefined) => void): () => void {\n const unsubscribe: () => void = super.subscribe(callback);\n\n callback(this.env);\n\n return unsubscribe;\n }\n}\n", "import {isBrowser, isNullish} from '@junobuild/utils';\n\nexport const popupCenter = ({\n width,\n height\n}: {\n width: number;\n height: number;\n}): string | undefined => {\n if (!isBrowser()) {\n return undefined;\n }\n\n if (isNullish(window) || isNullish(window.top)) {\n return undefined;\n }\n\n const {\n top: {innerWidth, innerHeight}\n } = window;\n\n const y = innerHeight / 2 + screenY - height / 2;\n const x = innerWidth / 2 + screenX - width / 2;\n\n return `toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width=${width}, height=${height}, top=${y}, left=${x}`;\n};\n", "import {isNullish, nonNullish} from '@junobuild/utils';\nimport {II_POPUP, INTERNET_COMPUTER_ORG, NFID_POPUP} from '../constants/auth.constants';\nimport {DOCKER_CONTAINER_URL, DOCKER_INTERNET_IDENTITY_ID} from '../constants/container.constants';\nimport {EnvStore} from '../stores/env.store';\nimport type {\n InternetIdentityConfig,\n InternetIdentityDomain,\n NFIDConfig,\n Provider,\n SignInOptions\n} from '../types/auth.types';\nimport {popupCenter} from '../utils/window.utils';\n\n/**\n * Options for signing in with an authentication provider.\n * @interface AuthProviderSignInOptions\n */\nexport interface AuthProviderSignInOptions {\n /**\n * The URL of the identity provider - commonly Internet Identity.\n */\n identityProvider: string;\n /**\n * Optional features for the window opener.\n */\n windowOpenerFeatures?: string;\n}\n\n/**\n * Common traits for all authentication providers\n * @interface AuthProvider\n */\nexport interface AuthProvider {\n /**\n * The unique identifier of the provider.\n */\n readonly id: Provider;\n /**\n * Method to get the sign-in options for the provider.\n * @param options - The sign-in options.\n * @returns The sign-in options for the provider that can be use to effectively perform a sign-in.\n */\n signInOptions: (options: Pick<SignInOptions, 'windowed'>) => AuthProviderSignInOptions;\n}\n\n/**\n * Internet Identity authentication provider.\n * @class InternetIdentityProvider\n * @implements {AuthProvider}\n */\nexport class InternetIdentityProvider implements AuthProvider {\n #domain?: InternetIdentityDomain;\n\n /**\n * Creates an instance of InternetIdentityProvider.\n * @param {InternetIdentityConfig} config - The configuration for Internet Identity.\n */\n constructor({domain}: InternetIdentityConfig) {\n this.#domain = domain;\n }\n\n /**\n * Gets the identifier of the provider.\n * @returns {Provider} The identifier of the provider - `internet_identity`.\n */\n get id(): Provider {\n return 'internet_identity';\n }\n\n /**\n * Gets the sign-in options for Internet Identity.\n * @param {Pick<SignInOptions, 'windowed'>} options - The sign-in options.\n * @returns {AuthProviderSignInOptions} The sign-in options for Internet Identity.\n */\n signInOptions({windowed}: Pick<SignInOptions, 'windowed'>): AuthProviderSignInOptions {\n const identityProviderUrl = (): string => {\n const container = EnvStore.getInstance().get()?.container;\n\n // Production\n if (isNullish(container) || container === false) {\n return `https://identity.${this.#domain ?? INTERNET_COMPUTER_ORG}`;\n }\n\n const env = EnvStore.getInstance().get();\n\n const internetIdentityId =\n nonNullish(env) && nonNullish(env?.internetIdentityId)\n ? env.internetIdentityId\n : DOCKER_INTERNET_IDENTITY_ID;\n\n const {host: containerHost, protocol} = new URL(\n container === true ? DOCKER_CONTAINER_URL : container\n );\n\n return /apple/i.test(navigator?.vendor)\n ? `${protocol}//${containerHost}?canisterId=${internetIdentityId}`\n : `${protocol}//${internetIdentityId}.${containerHost.replace('127.0.0.1', 'localhost')}`;\n };\n\n return {\n ...(windowed !== false && {\n windowOpenerFeatures: popupCenter(II_POPUP)\n }),\n identityProvider: identityProviderUrl()\n };\n }\n}\n\n/**\n * NFID authentication provider.\n * @class NFIDProvider\n * @implements {AuthProvider}\n */\nexport class NFIDProvider implements AuthProvider {\n #appName: string;\n #logoUrl: string;\n\n /**\n * Creates an instance of NFIDProvider.\n * @param {NFIDConfig} config - The configuration for NFID.\n */\n constructor({appName, logoUrl}: NFIDConfig) {\n this.#appName = appName;\n this.#logoUrl = logoUrl;\n }\n\n /**\n * Gets the identifier of the provider.\n * @returns {Provider} The identifier of the provider- nfid.\n */\n get id(): Provider {\n return 'nfid';\n }\n\n /**\n * Gets the sign-in options for NFID.\n * @param {Pick<SignInOptions, 'windowed'>} options - The sign-in options.\n * @returns {AuthProviderSignInOptions} The sign-in options to effectively sign-in with NFID.\n */\n signInOptions({windowed}: Pick<SignInOptions, 'windowed'>): AuthProviderSignInOptions {\n return {\n ...(windowed !== false && {\n windowOpenerFeatures: popupCenter(NFID_POPUP)\n }),\n identityProvider: `https://nfid.one/authenticate/?applicationName=${encodeURI(\n this.#appName\n )}&applicationLogo=${encodeURI(this.#logoUrl)}`\n };\n }\n}\n", "import { Buffer } from 'buffer/';\nimport {\n Agent,\n getDefaultAgent,\n HttpDetailsResponse,\n QueryResponseRejected,\n QueryResponseStatus,\n ReplicaRejectCode,\n SubmitResponse,\n} from './agent';\nimport { AgentError } from './errors';\nimport { IDL } from '@dfinity/candid';\nimport { pollForResponse, PollStrategyFactory, strategy } from './polling';\nimport { Principal } from '@dfinity/principal';\nimport { RequestId } from './request_id';\nimport { toHex } from './utils/buffer';\nimport { Certificate, CreateCertificateOptions } from './certificate';\nimport managementCanisterIdl from './canisters/management_idl';\nimport _SERVICE, { canister_install_mode, canister_settings } from './canisters/management_service';\n\nexport class ActorCallError extends AgentError {\n constructor(\n public readonly canisterId: Principal,\n public readonly methodName: string,\n public readonly type: 'query' | 'update',\n public readonly props: Record<string, string>,\n ) {\n super(\n [\n `Call failed:`,\n ` Canister: ${canisterId.toText()}`,\n ` Method: ${methodName} (${type})`,\n ...Object.getOwnPropertyNames(props).map(n => ` \"${n}\": ${JSON.stringify(props[n])}`),\n ].join('\\n'),\n );\n }\n}\n\nexport class QueryCallRejectedError extends ActorCallError {\n constructor(\n canisterId: Principal,\n methodName: string,\n public readonly result: QueryResponseRejected,\n ) {\n super(canisterId, methodName, 'query', {\n Status: result.status,\n Code: ReplicaRejectCode[result.reject_code] ?? `Unknown Code \"${result.reject_code}\"`,\n Message: result.reject_message,\n });\n }\n}\n\nexport class UpdateCallRejectedError extends ActorCallError {\n constructor(\n canisterId: Principal,\n methodName: string,\n public readonly requestId: RequestId,\n public readonly response: SubmitResponse['response'],\n ) {\n super(canisterId, methodName, 'update', {\n 'Request ID': toHex(requestId),\n ...(response.body\n ? {\n ...(response.body.error_code\n ? {\n 'Error code': response.body.error_code,\n }\n : {}),\n 'Reject code': String(response.body.reject_code),\n 'Reject message': response.body.reject_message,\n }\n : {\n 'HTTP status code': response.status.toString(),\n 'HTTP status text': response.statusText,\n }),\n });\n }\n}\n\n/**\n * Configuration to make calls to the Replica.\n */\nexport interface CallConfig {\n /**\n * An agent to use in this call, otherwise the actor or call will try to discover the\n * agent to use.\n */\n agent?: Agent;\n\n /**\n * A polling strategy factory that dictates how much and often we should poll the\n * read_state endpoint to get the result of an update call.\n */\n pollingStrategyFactory?: PollStrategyFactory;\n\n /**\n * The canister ID of this Actor.\n */\n canisterId?: string | Principal;\n\n /**\n * The effective canister ID. This should almost always be ignored.\n */\n effectiveCanisterId?: Principal;\n}\n\n/**\n * Configuration that can be passed to customize the Actor behaviour.\n */\nexport interface ActorConfig extends CallConfig {\n /**\n * The Canister ID of this Actor. This is required for an Actor.\n */\n canisterId: string | Principal;\n\n /**\n * An override function for update calls' CallConfig. This will be called on every calls.\n */\n callTransform?(\n methodName: string,\n args: unknown[],\n callConfig: CallConfig,\n ): Partial<CallConfig> | void;\n\n /**\n * An override function for query calls' CallConfig. This will be called on every query.\n */\n queryTransform?(\n methodName: string,\n args: unknown[],\n callConfig: CallConfig,\n ): Partial<CallConfig> | void;\n\n /**\n * Polyfill for BLS Certificate verification in case wasm is not supported\n */\n blsVerify?: CreateCertificateOptions['blsVerify'];\n}\n\n// TODO: move this to proper typing when Candid support TypeScript.\n/**\n * A subclass of an actor. Actor class itself is meant to be a based class.\n */\nexport type ActorSubclass<T = Record<string, ActorMethod>> = Actor & T;\n\n/**\n * An actor method type, defined for each methods of the actor service.\n */\nexport interface ActorMethod<Args extends unknown[] = unknown[], Ret = unknown> {\n (...args: Args): Promise<Ret>;\n withOptions(options: CallConfig): (...args: Args) => Promise<Ret>;\n}\n\n/**\n * An actor method type, defined for each methods of the actor service.\n */\nexport interface ActorMethodWithHttpDetails<Args extends unknown[] = unknown[], Ret = unknown>\n extends ActorMethod {\n (...args: Args): Promise<{ httpDetails: HttpDetailsResponse; result: Ret }>;\n}\n\n/**\n * An actor method type, defined for each methods of the actor service.\n */\nexport interface ActorMethodExtended<Args extends unknown[] = unknown[], Ret = unknown>\n extends ActorMethod {\n (...args: Args): Promise<{\n certificate?: Certificate;\n httpDetails?: HttpDetailsResponse;\n result: Ret;\n }>;\n}\n\nexport type FunctionWithArgsAndReturn<Args extends unknown[] = unknown[], Ret = unknown> = (\n ...args: Args\n) => Ret;\n\n// Update all entries of T with the extra information from ActorMethodWithInfo\nexport type ActorMethodMappedWithHttpDetails<T> = {\n [K in keyof T]: T[K] extends FunctionWithArgsAndReturn<infer Args, infer Ret>\n ? ActorMethodWithHttpDetails<Args, Ret>\n : never;\n};\n\n// Update all entries of T with the extra information from ActorMethodWithInfo\nexport type ActorMethodMappedExtended<T> = {\n [K in keyof T]: T[K] extends FunctionWithArgsAndReturn<infer Args, infer Ret>\n ? ActorMethodExtended<Args, Ret>\n : never;\n};\n\n/**\n * The mode used when installing a canister.\n */\nexport type CanisterInstallMode =\n | {\n reinstall: null;\n }\n | {\n upgrade:\n | []\n | [\n {\n skip_pre_upgrade: [] | [boolean];\n },\n ];\n }\n | {\n install: null;\n };\n\n/**\n * Internal metadata for actors. It's an enhanced version of ActorConfig with\n * some fields marked as required (as they are defaulted) and canisterId as\n * a Principal type.\n */\ninterface ActorMetadata {\n service: IDL.ServiceClass;\n agent?: Agent;\n config: ActorConfig;\n}\n\nconst metadataSymbol = Symbol.for('ic-agent-metadata');\n\nexport interface CreateActorClassOpts {\n httpDetails?: boolean;\n certificate?: boolean;\n}\n\ninterface CreateCanisterSettings {\n freezing_threshold?: bigint;\n controllers?: Array<Principal>;\n memory_allocation?: bigint;\n compute_allocation?: bigint;\n}\n\n/**\n * An actor base class. An actor is an object containing only functions that will\n * return a promise. These functions are derived from the IDL definition.\n */\nexport class Actor {\n /**\n * Get the Agent class this Actor would call, or undefined if the Actor would use\n * the default agent (global.ic.agent).\n * @param actor The actor to get the agent of.\n */\n public static agentOf(actor: Actor): Agent | undefined {\n return actor[metadataSymbol].config.agent;\n }\n\n /**\n * Get the interface of an actor, in the form of an instance of a Service.\n * @param actor The actor to get the interface of.\n */\n public static interfaceOf(actor: Actor): IDL.ServiceClass {\n return actor[metadataSymbol].service;\n }\n\n public static canisterIdOf(actor: Actor): Principal {\n return Principal.from(actor[metadataSymbol].config.canisterId);\n }\n\n public static async install(\n fields: {\n module: ArrayBuffer;\n mode?: canister_install_mode;\n arg?: ArrayBuffer;\n },\n config: ActorConfig,\n ): Promise<void> {\n const mode = fields.mode === undefined ? { install: null } : fields.mode;\n // Need to transform the arg into a number array.\n const arg = fields.arg ? [...new Uint8Array(fields.arg)] : [];\n // Same for module.\n const wasmModule = [...new Uint8Array(fields.module)];\n const canisterId =\n typeof config.canisterId === 'string'\n ? Principal.fromText(config.canisterId)\n : config.canisterId;\n\n await getManagementCanister(config).install_code({\n mode,\n arg,\n wasm_module: wasmModule,\n canister_id: canisterId,\n sender_canister_version: [],\n });\n }\n\n public static async createCanister(\n config?: CallConfig,\n settings?: CreateCanisterSettings,\n ): Promise<Principal> {\n function settingsToCanisterSettings(settings: CreateCanisterSettings): [canister_settings] {\n return [\n {\n controllers: settings.controllers ? [settings.controllers] : [],\n compute_allocation: settings.compute_allocation ? [settings.compute_allocation] : [],\n freezing_threshold: settings.freezing_threshold ? [settings.freezing_threshold] : [],\n memory_allocation: settings.memory_allocation ? [settings.memory_allocation] : [],\n reserved_cycles_limit: [],\n log_visibility: [],\n wasm_memory_limit: [],\n },\n ];\n }\n\n const { canister_id: canisterId } = await getManagementCanister(\n config || {},\n ).provisional_create_canister_with_cycles({\n amount: [],\n settings: settingsToCanisterSettings(settings || {}),\n specified_id: [],\n sender_canister_version: [],\n });\n\n return canisterId;\n }\n\n public static async createAndInstallCanister(\n interfaceFactory: IDL.InterfaceFactory,\n fields: {\n module: ArrayBuffer;\n arg?: ArrayBuffer;\n },\n config?: CallConfig,\n ): Promise<ActorSubclass> {\n const canisterId = await this.createCanister(config);\n await this.install(\n {\n ...fields,\n },\n { ...config, canisterId },\n );\n\n return this.createActor(interfaceFactory, { ...config, canisterId });\n }\n\n public static createActorClass(\n interfaceFactory: IDL.InterfaceFactory,\n options?: CreateActorClassOpts,\n ): ActorConstructor {\n const service = interfaceFactory({ IDL });\n\n class CanisterActor extends Actor {\n [x: string]: ActorMethod;\n\n constructor(config: ActorConfig) {\n if (!config.canisterId)\n throw new AgentError(\n `Canister ID is required, but received ${typeof config.canisterId} instead. If you are using automatically generated declarations, this may be because your application is not setting the canister ID in process.env correctly.`,\n );\n const canisterId =\n typeof config.canisterId === 'string'\n ? Principal.fromText(config.canisterId)\n : config.canisterId;\n\n super({\n config: {\n ...DEFAULT_ACTOR_CONFIG,\n ...config,\n canisterId,\n },\n service,\n });\n\n for (const [methodName, func] of service._fields) {\n if (options?.httpDetails) {\n func.annotations.push(ACTOR_METHOD_WITH_HTTP_DETAILS);\n }\n if (options?.certificate) {\n func.annotations.push(ACTOR_METHOD_WITH_CERTIFICATE);\n }\n\n this[methodName] = _createActorMethod(this, methodName, func, config.blsVerify);\n }\n }\n }\n\n return CanisterActor;\n }\n\n public static createActor<T = Record<string, ActorMethod>>(\n interfaceFactory: IDL.InterfaceFactory,\n configuration: ActorConfig,\n ): ActorSubclass<T> {\n if (!configuration.canisterId) {\n throw new AgentError(\n `Canister ID is required, but received ${typeof configuration.canisterId} instead. If you are using automatically generated declarations, this may be because your application is not setting the canister ID in process.env correctly.`,\n );\n }\n return new (this.createActorClass(interfaceFactory))(\n configuration,\n ) as unknown as ActorSubclass<T>;\n }\n\n /**\n * Returns an actor with methods that return the http response details along with the result\n * @param interfaceFactory - the interface factory for the actor\n * @param configuration - the configuration for the actor\n * @deprecated - use createActor with actorClassOptions instead\n */\n public static createActorWithHttpDetails<T = Record<string, ActorMethod>>(\n interfaceFactory: IDL.InterfaceFactory,\n configuration: ActorConfig,\n ): ActorSubclass<ActorMethodMappedWithHttpDetails<T>> {\n return new (this.createActorClass(interfaceFactory, { httpDetails: true }))(\n configuration,\n ) as unknown as ActorSubclass<ActorMethodMappedWithHttpDetails<T>>;\n }\n\n /**\n * Returns an actor with methods that return the http response details along with the result\n * @param interfaceFactory - the interface factory for the actor\n * @param configuration - the configuration for the actor\n * @param actorClassOptions - options for the actor class extended details to return with the result\n */\n public static createActorWithExtendedDetails<T = Record<string, ActorMethod>>(\n interfaceFactory: IDL.InterfaceFactory,\n configuration: ActorConfig,\n actorClassOptions: CreateActorClassOpts = {\n httpDetails: true,\n certificate: true,\n },\n ): ActorSubclass<ActorMethodMappedExtended<T>> {\n return new (this.createActorClass(interfaceFactory, actorClassOptions))(\n configuration,\n ) as unknown as ActorSubclass<ActorMethodMappedExtended<T>>;\n }\n\n private [metadataSymbol]: ActorMetadata;\n\n protected constructor(metadata: ActorMetadata) {\n this[metadataSymbol] = Object.freeze(metadata);\n }\n}\n\n// IDL functions can have multiple return values, so decoding always\n// produces an array. Ensure that functions with single or zero return\n// values behave as expected.\nfunction decodeReturnValue(types: IDL.Type[], msg: ArrayBuffer) {\n const returnValues = IDL.decode(types, Buffer.from(msg));\n switch (returnValues.length) {\n case 0:\n return undefined;\n case 1:\n return returnValues[0];\n default:\n return returnValues;\n }\n}\n\nconst DEFAULT_ACTOR_CONFIG = {\n pollingStrategyFactory: strategy.defaultStrategy,\n};\n\nexport type ActorConstructor = new (config: ActorConfig) => ActorSubclass;\n\nexport const ACTOR_METHOD_WITH_HTTP_DETAILS = 'http-details';\nexport const ACTOR_METHOD_WITH_CERTIFICATE = 'certificate';\n\nfunction _createActorMethod(\n actor: Actor,\n methodName: string,\n func: IDL.FuncClass,\n blsVerify?: CreateCertificateOptions['blsVerify'],\n): ActorMethod {\n let caller: (options: CallConfig, ...args: unknown[]) => Promise<unknown>;\n if (func.annotations.includes('query') || func.annotations.includes('composite_query')) {\n caller = async (options, ...args) => {\n // First, if there's a config transformation, call it.\n options = {\n ...options,\n ...actor[metadataSymbol].config.queryTransform?.(methodName, args, {\n ...actor[metadataSymbol].config,\n ...options,\n }),\n };\n\n const agent = options.agent || actor[metadataSymbol].config.agent || getDefaultAgent();\n const cid = Principal.from(options.canisterId || actor[metadataSymbol].config.canisterId);\n const arg = IDL.encode(func.argTypes, args);\n\n const result = await agent.query(cid, {\n methodName,\n arg,\n effectiveCanisterId: options.effectiveCanisterId,\n });\n const httpDetails = {\n ...result.httpDetails,\n requestDetails: result.requestDetails,\n } as HttpDetailsResponse;\n\n switch (result.status) {\n case QueryResponseStatus.Rejected:\n throw new QueryCallRejectedError(cid, methodName, result);\n\n case QueryResponseStatus.Replied:\n return func.annotations.includes(ACTOR_METHOD_WITH_HTTP_DETAILS)\n ? {\n httpDetails,\n result: decodeReturnValue(func.retTypes, result.reply.arg),\n }\n : decodeReturnValue(func.retTypes, result.reply.arg);\n }\n };\n } else {\n caller = async (options, ...args) => {\n // First, if there's a config transformation, call it.\n options = {\n ...options,\n ...actor[metadataSymbol].config.callTransform?.(methodName, args, {\n ...actor[metadataSymbol].config,\n ...options,\n }),\n };\n\n const agent = options.agent || actor[metadataSymbol].config.agent || getDefaultAgent();\n const { canisterId, effectiveCanisterId, pollingStrategyFactory } = {\n ...DEFAULT_ACTOR_CONFIG,\n ...actor[metadataSymbol].config,\n ...options,\n };\n const cid = Principal.from(canisterId);\n const ecid = effectiveCanisterId !== undefined ? Principal.from(effectiveCanisterId) : cid;\n const arg = IDL.encode(func.argTypes, args);\n\n const { requestId, response, requestDetails } = await agent.call(cid, {\n methodName,\n arg,\n effectiveCanisterId: ecid,\n });\n\n requestId;\n response;\n requestDetails;\n\n if (!response.ok || response.body /* IC-1462 */) {\n throw new UpdateCallRejectedError(cid, methodName, requestId, response);\n }\n\n const pollStrategy = pollingStrategyFactory();\n // Contains the certificate and the reply from the boundary node\n const { certificate, reply } = await pollForResponse(\n agent,\n ecid,\n requestId,\n pollStrategy,\n blsVerify,\n );\n reply;\n const shouldIncludeHttpDetails = func.annotations.includes(ACTOR_METHOD_WITH_HTTP_DETAILS);\n const shouldIncludeCertificate = func.annotations.includes(ACTOR_METHOD_WITH_CERTIFICATE);\n\n const httpDetails = { ...response, requestDetails } as HttpDetailsResponse;\n\n if (reply !== undefined) {\n if (shouldIncludeHttpDetails && shouldIncludeCertificate) {\n return {\n httpDetails,\n certificate,\n result: decodeReturnValue(func.retTypes, reply),\n };\n } else if (shouldIncludeCertificate) {\n return {\n certificate,\n result: decodeReturnValue(func.retTypes, reply),\n };\n } else if (shouldIncludeHttpDetails) {\n return {\n httpDetails,\n result: decodeReturnValue(func.retTypes, reply),\n };\n }\n return decodeReturnValue(func.retTypes, reply);\n } else if (func.retTypes.length === 0) {\n return shouldIncludeHttpDetails\n ? {\n httpDetails: response,\n result: undefined,\n }\n : undefined;\n } else {\n throw new Error(`Call was returned undefined, but type [${func.retTypes.join(',')}].`);\n }\n };\n }\n\n const handler = (...args: unknown[]) => caller({}, ...args);\n handler.withOptions =\n (options: CallConfig) =>\n (...args: unknown[]) =>\n caller(options, ...args);\n return handler as ActorMethod;\n}\n\nexport type ManagementCanisterRecord = _SERVICE;\n\n/**\n * Create a management canister actor\n * @param config - a CallConfig\n */\nexport function getManagementCanister(config: CallConfig): ActorSubclass<ManagementCanisterRecord> {\n function transform(\n _methodName: string,\n args: Record<string, unknown> & { canister_id: string }[],\n ) {\n if (config.effectiveCanisterId) {\n return { effectiveCanisterId: Principal.from(config.effectiveCanisterId) };\n }\n const first = args[0];\n let effectiveCanisterId = Principal.fromHex('');\n if (first && typeof first === 'object' && first.canister_id) {\n effectiveCanisterId = Principal.from(first.canister_id as unknown);\n }\n return { effectiveCanisterId };\n }\n\n return Actor.createActor<ManagementCanisterRecord>(managementCanisterIdl, {\n ...config,\n canisterId: Principal.fromHex(''),\n ...{\n callTransform: transform,\n queryTransform: transform,\n },\n });\n}\n\nexport class AdvancedActor extends Actor {\n constructor(metadata: ActorMetadata) {\n super(metadata);\n }\n}\n", "import { Principal } from '@dfinity/principal';\nimport { RequestId } from '../request_id';\nimport { JsonObject } from '@dfinity/candid';\nimport { Identity } from '../auth';\nimport { CallRequest, HttpHeaderField, QueryRequest } from './http/types';\n\n/**\n * Codes used by the replica for rejecting a message.\n * See {@link https://sdk.dfinity.org/docs/interface-spec/#reject-codes | the interface spec}.\n */\nexport enum ReplicaRejectCode {\n SysFatal = 1,\n SysTransient = 2,\n DestinationInvalid = 3,\n CanisterReject = 4,\n CanisterError = 5,\n}\n\n/**\n * Options when doing a {@link Agent.readState} call.\n */\nexport interface ReadStateOptions {\n /**\n * A list of paths to read the state of.\n */\n paths: ArrayBuffer[][];\n}\n\n/**\n *\n */\nexport type QueryResponse = QueryResponseReplied | QueryResponseRejected;\n\nexport const enum QueryResponseStatus {\n Replied = 'replied',\n Rejected = 'rejected',\n}\n\nexport interface HttpDetailsResponse {\n ok: boolean;\n status: number;\n statusText: string;\n headers: HttpHeaderField[];\n}\n\nexport type ApiQueryResponse = QueryResponse & {\n httpDetails: HttpDetailsResponse;\n requestId: RequestId;\n};\n\nexport interface QueryResponseBase {\n status: QueryResponseStatus;\n requestDetails?: QueryRequest;\n}\n\nexport type NodeSignature = {\n // the batch time\n timestamp: bigint;\n // the signature\n signature: Uint8Array;\n // the ID of the node that created the signature\n identity: Uint8Array;\n};\n\nexport interface QueryResponseReplied extends QueryResponseBase {\n status: QueryResponseStatus.Replied;\n reply: { arg: ArrayBuffer };\n signatures?: NodeSignature[];\n}\n\nexport interface QueryResponseRejected extends QueryResponseBase {\n status: QueryResponseStatus.Rejected;\n reject_code: ReplicaRejectCode;\n reject_message: string;\n error_code: string;\n signatures?: NodeSignature[];\n}\n\n/**\n * Options when doing a {@link Agent.query} call.\n */\nexport interface QueryFields {\n /**\n * The method name to call.\n */\n methodName: string;\n\n /**\n * A binary encoded argument. This is already encoded and will be sent as is.\n */\n arg: ArrayBuffer;\n\n /**\n * Overrides canister id for path to fetch. This is used for management canister calls.\n */\n effectiveCanisterId?: Principal;\n}\n\n/**\n * Options when doing a {@link Agent.call} call.\n */\nexport interface CallOptions {\n /**\n * The method name to call.\n */\n methodName: string;\n\n /**\n * A binary encoded argument. This is already encoded and will be sent as is.\n */\n arg: ArrayBuffer;\n\n /**\n * An effective canister ID, used for routing. This should only be mentioned if\n * it's different from the canister ID.\n */\n effectiveCanisterId: Principal | string;\n}\n\nexport interface ReadStateResponse {\n certificate: ArrayBuffer;\n}\n\nexport interface SubmitResponse {\n requestId: RequestId;\n response: {\n ok: boolean;\n status: number;\n statusText: string;\n body: {\n error_code?: string;\n reject_code: number;\n reject_message: string;\n } | null;\n headers: HttpHeaderField[];\n };\n requestDetails?: CallRequest;\n}\n\n/**\n * An Agent able to make calls and queries to a Replica.\n */\nexport interface Agent {\n readonly rootKey: ArrayBuffer | null;\n /**\n * Returns the principal ID associated with this agent (by default). It only shows\n * the principal of the default identity in the agent, which is the principal used\n * when calls don't specify it.\n */\n getPrincipal(): Promise<Principal>;\n\n /**\n * Create the request for the read state call.\n * `readState` uses this internally.\n * Useful to avoid signing the same request multiple times.\n */\n createReadStateRequest?(\n options: ReadStateOptions,\n identity?: Identity,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any>;\n\n /**\n * Send a read state query to the replica. This includes a list of paths to return,\n * and will return a Certificate. This will only reject on communication errors,\n * but the certificate might contain less information than requested.\n * @param effectiveCanisterId A Canister ID related to this call.\n * @param options The options for this call.\n * @param identity Identity for the call. If not specified, uses the instance identity.\n * @param request The request to send in case it has already been created.\n */\n readState(\n effectiveCanisterId: Principal | string,\n options: ReadStateOptions,\n identity?: Identity,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n request?: any,\n ): Promise<ReadStateResponse>;\n\n call(canisterId: Principal | string, fields: CallOptions): Promise<SubmitResponse>;\n\n /**\n * Query the status endpoint of the replica. This normally has a few fields that\n * corresponds to the version of the replica, its root public key, and any other\n * information made public.\n * @returns A JsonObject that is essentially a record of fields from the status\n * endpoint.\n */\n status(): Promise<JsonObject>;\n\n /**\n * Send a query call to a canister. See\n * {@link https://sdk.dfinity.org/docs/interface-spec/#http-query | the interface spec}.\n * @param canisterId The Principal of the Canister to send the query to. Sending a query to\n * the management canister is not supported (as it has no meaning from an agent).\n * @param options Options to use to create and send the query.\n * @param identity Sender principal to use when sending the query.\n * @returns The response from the replica. The Promise will only reject when the communication\n * failed. If the query itself failed but no protocol errors happened, the response will\n * be of type QueryResponseRejected.\n */\n query(\n canisterId: Principal | string,\n options: QueryFields,\n identity?: Identity | Promise<Identity>,\n ): Promise<ApiQueryResponse>;\n\n /**\n * By default, the agent is configured to talk to the main Internet Computer,\n * and verifies responses using a hard-coded public key.\n *\n * This function will instruct the agent to ask the endpoint for its public\n * key, and use that instead. This is required when talking to a local test\n * instance, for example.\n *\n * Only use this when you are _not_ talking to the main Internet Computer,\n * otherwise you are prone to man-in-the-middle attacks! Do not call this\n * function by default.\n */\n fetchRootKey(): Promise<ArrayBuffer>;\n /**\n * If an application needs to invalidate an identity under certain conditions, an `Agent` may expose an `invalidateIdentity` method.\n * Invoking this method will set the inner identity used by the `Agent` to `null`.\n *\n * A use case for this would be - after a certain period of inactivity, a secure application chooses to invalidate the identity of any `HttpAgent` instances. An invalid identity can be replaced by `Agent.replaceIdentity`\n */\n invalidateIdentity?(): void;\n /**\n * If an application needs to replace an identity under certain conditions, an `Agent` may expose a `replaceIdentity` method.\n * Invoking this method will set the inner identity used by the `Agent` to a newly provided identity.\n *\n * A use case for this would be - after authenticating using `@dfinity/auth-client`, you can replace the `AnonymousIdentity` of your `Actor` with a `DelegationIdentity`.\n *\n * ```Actor.agentOf(defaultActor).replaceIdentity(await authClient.getIdentity());```\n */\n replaceIdentity?(identity: Identity): void;\n}\n", "import { Principal } from '@dfinity/principal';\nimport { HttpAgentRequest } from './agent/http/types';\nimport { requestIdOf } from './request_id';\nimport { concat, toHex } from './utils/buffer';\n\nconst domainSeparator = new TextEncoder().encode('\\x0Aic-request');\n\n/**\n * A Key Pair, containing a secret and public key.\n */\nexport interface KeyPair {\n secretKey: ArrayBuffer;\n publicKey: PublicKey;\n}\n\n/**\n * A public key that is DER encoded. This is a branded ArrayBuffer.\n */\nexport type DerEncodedPublicKey = ArrayBuffer & { __derEncodedPublicKey__?: void };\n\n/**\n * A signature array buffer.\n */\nexport type Signature = ArrayBuffer & { __signature__: void };\n\n/**\n * A Public Key implementation.\n */\nexport interface PublicKey {\n toDer(): DerEncodedPublicKey;\n // rawKey, toRaw, and derKey are optional for backwards compatibility.\n toRaw?(): ArrayBuffer;\n rawKey?: ArrayBuffer;\n derKey?: DerEncodedPublicKey;\n}\n\n/**\n * A General Identity object. This does not have to be a private key (for example,\n * the Anonymous identity), but it must be able to transform request.\n */\nexport interface Identity {\n /**\n * Get the principal represented by this identity. Normally should be a\n * `Principal.selfAuthenticating()`.\n */\n getPrincipal(): Principal;\n\n /**\n * Transform a request into a signed version of the request. This is done last\n * after the transforms on the body of a request. The returned object can be\n * anything, but must be serializable to CBOR.\n */\n transformRequest(request: HttpAgentRequest): Promise<unknown>;\n}\n\n/**\n * An Identity that can sign blobs.\n */\nexport abstract class SignIdentity implements Identity {\n protected _principal: Principal | undefined;\n\n /**\n * Returns the public key that would match this identity's signature.\n */\n public abstract getPublicKey(): PublicKey;\n\n /**\n * Signs a blob of data, with this identity's private key.\n */\n public abstract sign(blob: ArrayBuffer): Promise<Signature>;\n\n /**\n * Get the principal represented by this identity. Normally should be a\n * `Principal.selfAuthenticating()`.\n */\n public getPrincipal(): Principal {\n if (!this._principal) {\n this._principal = Principal.selfAuthenticating(new Uint8Array(this.getPublicKey().toDer()));\n }\n return this._principal;\n }\n\n /**\n * Transform a request into a signed version of the request. This is done last\n * after the transforms on the body of a request. The returned object can be\n * anything, but must be serializable to CBOR.\n * @param request - internet computer request to transform\n */\n public async transformRequest(request: HttpAgentRequest): Promise<unknown> {\n const { body, ...fields } = request;\n const requestId = await requestIdOf(body);\n return {\n ...fields,\n body: {\n content: body,\n sender_pubkey: this.getPublicKey().toDer(),\n sender_sig: await this.sign(concat(domainSeparator, requestId)),\n },\n };\n }\n}\n\nexport class AnonymousIdentity implements Identity {\n public getPrincipal(): Principal {\n return Principal.anonymous();\n }\n\n public async transformRequest(request: HttpAgentRequest): Promise<unknown> {\n return {\n ...request,\n body: { content: request.body },\n };\n }\n}\n\n/*\n * We need to communicate with other agents on the page about identities,\n * but those messages may need to go across boundaries where it's not possible to\n * serialize/deserialize object prototypes easily.\n * So these are lightweight, serializable objects that contain enough information to recreate\n * SignIdentities, but don't commit to having all methods of SignIdentity.\n *\n * Use Case:\n * * DOM Events that let differently-versioned components communicate to one another about\n * Identities, even if they're using slightly different versions of agent packages to\n * create/interpret them.\n */\nexport interface AnonymousIdentityDescriptor {\n type: 'AnonymousIdentity';\n}\nexport interface PublicKeyIdentityDescriptor {\n type: 'PublicKeyIdentity';\n publicKey: string;\n}\nexport type IdentityDescriptor = AnonymousIdentityDescriptor | PublicKeyIdentityDescriptor;\n\n/**\n * Create an IdentityDescriptor from a @dfinity/identity Identity\n * @param identity - identity describe in returned descriptor\n */\nexport function createIdentityDescriptor(\n identity: SignIdentity | AnonymousIdentity,\n): IdentityDescriptor {\n const identityIndicator: IdentityDescriptor =\n 'getPublicKey' in identity\n ? { type: 'PublicKeyIdentity', publicKey: toHex(identity.getPublicKey().toDer()) }\n : { type: 'AnonymousIdentity' };\n return identityIndicator;\n}\n", "import { lebEncode } from '@dfinity/candid';\nimport * as cbor from 'simple-cbor';\nimport {\n Endpoint,\n HttpAgentRequest,\n HttpAgentRequestTransformFn,\n HttpHeaderField,\n makeNonce,\n Nonce,\n} from './types';\n\nconst NANOSECONDS_PER_MILLISECONDS = BigInt(1_000_000);\n\nconst REPLICA_PERMITTED_DRIFT_MILLISECONDS = 60 * 1000;\n\nexport class Expiry {\n private readonly _value: bigint;\n\n constructor(deltaInMSec: number) {\n // Use bigint because it can overflow the maximum number allowed in a double float.\n const raw_value =\n BigInt(Math.floor(Date.now() + deltaInMSec - REPLICA_PERMITTED_DRIFT_MILLISECONDS)) *\n NANOSECONDS_PER_MILLISECONDS;\n\n // round down to the nearest second\n const ingress_as_seconds = raw_value / BigInt(1_000_000_000);\n\n // round down to nearest minute\n const ingress_as_minutes = ingress_as_seconds / BigInt(60);\n\n const rounded_down_nanos = ingress_as_minutes * BigInt(60) * BigInt(1_000_000_000);\n\n this._value = rounded_down_nanos;\n }\n\n public toCBOR(): cbor.CborValue {\n // TODO: change this to take the minimum amount of space (it always takes 8 bytes now).\n return cbor.value.u64(this._value.toString(16), 16);\n }\n\n public toHash(): ArrayBuffer {\n return lebEncode(this._value);\n }\n}\n\n/**\n * Create a Nonce transform, which takes a function that returns a Buffer, and adds it\n * as the nonce to every call requests.\n * @param nonceFn A function that returns a buffer. By default uses a semi-random method.\n */\nexport function makeNonceTransform(nonceFn: () => Nonce = makeNonce): HttpAgentRequestTransformFn {\n return async (request: HttpAgentRequest) => {\n // Nonce needs to be inserted into the header for all requests, to enable logs to be correlated with requests.\n const headers = request.request.headers;\n // TODO: uncomment this when the http proxy supports it.\n // headers.set('X-IC-Request-ID', toHex(new Uint8Array(nonce)));\n request.request.headers = headers;\n\n // Nonce only needs to be inserted into the body for async calls, to prevent replay attacks.\n if (request.endpoint === Endpoint.Call) {\n request.body.nonce = nonceFn();\n }\n };\n}\n\n/**\n * Create a transform that adds a delay (by default 5 minutes) to the expiry.\n *\n * @param delayInMilliseconds The delay to add to the call time, in milliseconds.\n */\nexport function makeExpiryTransform(delayInMilliseconds: number): HttpAgentRequestTransformFn {\n return async (request: HttpAgentRequest) => {\n request.body.ingress_expiry = new Expiry(delayInMilliseconds);\n };\n}\n\n/**\n * Maps the default fetch headers field to the serializable HttpHeaderField.\n *\n * @param headers Fetch definition of the headers type\n * @returns array of header fields\n */\nexport function httpHeadersTransform(headers: Headers): HttpHeaderField[] {\n const headerFields: HttpHeaderField[] = [];\n headers.forEach((value, key) => {\n headerFields.push([key, value]);\n });\n return headerFields;\n}\n", "/**\n * Generates a random unsigned 32-bit integer between 0 and 0xffffffff\n * @returns {number} a random number\n */\nexport const randomNumber = (): number => {\n // determine whether browser crypto is available\n if (typeof window !== 'undefined' && !!window.crypto && !!window.crypto.getRandomValues) {\n const array = new Uint32Array(1);\n window.crypto.getRandomValues(array);\n return array[0];\n }\n // A second check for webcrypto, in case it is loaded under global instead of window\n if (typeof crypto !== 'undefined' && crypto.getRandomValues) {\n const array = new Uint32Array(1);\n crypto.getRandomValues(array);\n return array[0];\n }\n\n type nodeCrypto = {\n randomInt: (min: number, max: number) => number;\n };\n\n // determine whether node crypto is available\n if (typeof crypto !== 'undefined' && (crypto as unknown as nodeCrypto).randomInt) {\n return (crypto as unknown as nodeCrypto).randomInt(0, 0xffffffff);\n }\n\n // fall back to Math.random\n return Math.floor(Math.random() * 0xffffffff);\n};\n", "import type { Principal } from '@dfinity/principal';\nimport { Expiry } from './transforms';\nimport { randomNumber } from '../../utils/random';\n\n/**\n * @internal\n */\nexport const enum Endpoint {\n Query = 'read',\n ReadState = 'read_state',\n Call = 'call',\n}\n\n// An HttpAgent request, before it gets encoded and sent to the server.\n// We create an empty request that we will fill later.\nexport type HttpAgentRequest =\n | HttpAgentQueryRequest\n | HttpAgentSubmitRequest\n | HttpAgentReadStateRequest;\n\nexport interface HttpAgentBaseRequest {\n readonly endpoint: Endpoint;\n request: RequestInit;\n}\n\nexport type HttpHeaderField = [string, string];\n\nexport interface HttpAgentSubmitRequest extends HttpAgentBaseRequest {\n readonly endpoint: Endpoint.Call;\n body: CallRequest;\n}\n\nexport interface HttpAgentQueryRequest extends HttpAgentBaseRequest {\n readonly endpoint: Endpoint.Query;\n body: ReadRequest;\n}\n\nexport interface HttpAgentReadStateRequest extends HttpAgentBaseRequest {\n readonly endpoint: Endpoint.ReadState;\n body: ReadRequest;\n}\n\nexport interface Signed<T> {\n content: T;\n sender_pubkey: ArrayBuffer;\n sender_sig: ArrayBuffer;\n}\n\nexport interface UnSigned<T> {\n content: T;\n}\n\nexport type Envelope<T> = Signed<T> | UnSigned<T>;\n\nexport interface HttpAgentRequestTransformFn {\n (args: HttpAgentRequest): Promise<HttpAgentRequest | undefined | void>;\n priority?: number;\n}\n\n// The fields in a \"call\" submit request.\nexport interface CallRequest extends Record<string, any> {\n request_type: SubmitRequestType.Call;\n canister_id: Principal;\n method_name: string;\n arg: ArrayBuffer;\n sender: Uint8Array | Principal;\n ingress_expiry: Expiry;\n nonce?: Nonce;\n}\n\n// The types of values allowed in the `request_type` field for submit requests.\nexport enum SubmitRequestType {\n Call = 'call',\n}\n\n// The types of values allowed in the `request_type` field for read requests.\nexport const enum ReadRequestType {\n Query = 'query',\n ReadState = 'read_state',\n}\n\n// The fields in a \"query\" read request.\nexport interface QueryRequest extends Record<string, any> {\n request_type: ReadRequestType.Query;\n canister_id: Principal;\n method_name: string;\n arg: ArrayBuffer;\n sender: Uint8Array | Principal;\n ingress_expiry: Expiry;\n nonce?: Nonce;\n}\n\nexport interface ReadStateRequest extends Record<string, any> {\n request_type: ReadRequestType.ReadState;\n paths: ArrayBuffer[][];\n ingress_expiry: Expiry;\n sender: Uint8Array | Principal;\n}\n\nexport type ReadRequest = QueryRequest | ReadStateRequest;\n\n// A Nonce that can be used for calls.\nexport type Nonce = Uint8Array & { __nonce__: void };\n\n/**\n * Create a random Nonce, based on random values\n */\nexport function makeNonce(): Nonce {\n // Encode 128 bits.\n const buffer = new ArrayBuffer(16);\n const view = new DataView(buffer);\n const rand1 = randomNumber();\n const rand2 = randomNumber();\n const rand3 = randomNumber();\n const rand4 = randomNumber();\n\n view.setUint32(0, rand1);\n view.setUint32(4, rand2);\n view.setUint32(8, rand3);\n view.setUint32(12, rand4);\n\n return buffer as Nonce;\n}\n", "import { AgentError } from '../../errors';\nimport { HttpDetailsResponse } from '../api';\n\nexport class AgentHTTPResponseError extends AgentError {\n constructor(message: string, public readonly response: HttpDetailsResponse) {\n super(message);\n this.name = this.constructor.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n", "const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n: bigint, le = false) {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number) => h >>> s;\nconst shrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number) => l;\nconst rotr32L = (h: number, _l: number) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number) => (h << (s - 32)) | (l >>> (64 - s));\n\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah: number, Al: number, Bh: number, Bl: number) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number) =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number) =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number) =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number) =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n", "import { HashMD } from './_md.js';\nimport u64 from './_u64.js';\nimport { wrapConstructor } from './utils.js';\n\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD<SHA512> {\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0x6a09e667 | 0;\n Al = 0xf3bcc908 | 0;\n Bh = 0xbb67ae85 | 0;\n Bl = 0x84caa73b | 0;\n Ch = 0x3c6ef372 | 0;\n Cl = 0xfe94f82b | 0;\n Dh = 0xa54ff53a | 0;\n Dl = 0x5f1d36f1 | 0;\n Eh = 0x510e527f | 0;\n El = 0xade682d1 | 0;\n Fh = 0x9b05688c | 0;\n Fl = 0x2b3e6c1f | 0;\n Gh = 0x1f83d9ab | 0;\n Gl = 0xfb41bd6b | 0;\n Hh = 0x5be0cd19 | 0;\n Hl = 0x137e2179 | 0;\n\n constructor() {\n super(128, 64, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nclass SHA512_224 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0x8c3d37c8 | 0;\n Al = 0x19544da2 | 0;\n Bh = 0x73e19966 | 0;\n Bl = 0x89dcd4d6 | 0;\n Ch = 0x1dfab7ae | 0;\n Cl = 0x32ff9c82 | 0;\n Dh = 0x679dd514 | 0;\n Dl = 0x582f9fcf | 0;\n Eh = 0x0f6d2b69 | 0;\n El = 0x7bd44da8 | 0;\n Fh = 0x77e36f73 | 0;\n Fl = 0x04c48942 | 0;\n Gh = 0x3f9d85a8 | 0;\n Gl = 0x6a1d36c8 | 0;\n Hh = 0x1112e6ad | 0;\n Hl = 0x91d692a1 | 0;\n\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\nclass SHA512_256 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0x22312194 | 0;\n Al = 0xfc2bf72c | 0;\n Bh = 0x9f555fa3 | 0;\n Bl = 0xc84c64c2 | 0;\n Ch = 0x2393b86b | 0;\n Cl = 0x6f53b151 | 0;\n Dh = 0x96387719 | 0;\n Dl = 0x5940eabd | 0;\n Eh = 0x96283ee2 | 0;\n El = 0xa88effe3 | 0;\n Fh = 0xbe5e1e25 | 0;\n Fl = 0x53863992 | 0;\n Gh = 0x2b0199fc | 0;\n Gl = 0x2c85b8aa | 0;\n Hh = 0x0eb72ddc | 0;\n Hl = 0x81c52ca2 | 0;\n\n constructor() {\n super();\n this.outputLen = 32;\n }\n}\n\nclass SHA384 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0xcbbb9d5d | 0;\n Al = 0xc1059ed8 | 0;\n Bh = 0x629a292a | 0;\n Bl = 0x367cd507 | 0;\n Ch = 0x9159015a | 0;\n Cl = 0x3070dd17 | 0;\n Dh = 0x152fecd8 | 0;\n Dl = 0xf70e5939 | 0;\n Eh = 0x67332667 | 0;\n El = 0xffc00b31 | 0;\n Fh = 0x8eb44a87 | 0;\n Fl = 0x68581511 | 0;\n Gh = 0xdb0c2e0d | 0;\n Gl = 0x64f98fa7 | 0;\n Hh = 0x47b5481d | 0;\n Hl = 0xbefa4fa4 | 0;\n\n constructor() {\n super();\n this.outputLen = 48;\n }\n}\n\nexport const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());\nexport const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224());\nexport const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256());\nexport const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384());\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Twisted Edwards curve. The formula is: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2\nimport { AffinePoint, BasicCurve, Group, GroupConstructor, validateBasic, wNAF } from './curve.js';\nimport { mod } from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes, FHash, Hex, memoized, abool } from './utils.js';\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n\n// Edwards curves must declare params a & d.\nexport type CurveType = BasicCurve<bigint> & {\n a: bigint; // curve param a\n d: bigint; // curve param d\n hash: FHash; // Hashing\n randomBytes: (bytesLength?: number) => Uint8Array; // CSPRNG\n adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; // clears bits to get valid field elemtn\n domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; // Used for hashing\n uvRatio?: (u: bigint, v: bigint) => { isValid: boolean; value: bigint }; // Ratio \u221A(u/v)\n prehash?: FHash; // RFC 8032 pre-hashing of messages to sign() / verify()\n mapToCurve?: (scalar: bigint[]) => AffinePoint<bigint>; // for hash-to-curve standard\n};\n\n// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\nconst VERIFY_DEFAULT = { zip215: true };\n\nfunction validateOpts(curve: CurveType) {\n const opts = validateBasic(curve);\n ut.validateObject(\n curve,\n {\n hash: 'function',\n a: 'bigint',\n d: 'bigint',\n randomBytes: 'function',\n },\n {\n adjustScalarBytes: 'function',\n domain: 'function',\n uvRatio: 'function',\n mapToCurve: 'function',\n }\n );\n // Set defaults\n return Object.freeze({ ...opts } as const);\n}\n\n// Instance of Extended Point with coordinates in X, Y, Z, T\nexport interface ExtPointType extends Group<ExtPointType> {\n readonly ex: bigint;\n readonly ey: bigint;\n readonly ez: bigint;\n readonly et: bigint;\n get x(): bigint;\n get y(): bigint;\n assertValidity(): void;\n multiply(scalar: bigint): ExtPointType;\n multiplyUnsafe(scalar: bigint): ExtPointType;\n isSmallOrder(): boolean;\n isTorsionFree(): boolean;\n clearCofactor(): ExtPointType;\n toAffine(iz?: bigint): AffinePoint<bigint>;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n}\n// Static methods of Extended Point with coordinates in X, Y, Z, T\nexport interface ExtPointConstructor extends GroupConstructor<ExtPointType> {\n new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType;\n fromAffine(p: AffinePoint<bigint>): ExtPointType;\n fromHex(hex: Hex): ExtPointType;\n fromPrivateKey(privateKey: Hex): ExtPointType;\n}\n\n/**\n * Edwards Curve interface.\n * Main methods: `getPublicKey(priv)`, `sign(msg, priv)`, `verify(sig, msg, pub)`.\n */\nexport type CurveFn = {\n CURVE: ReturnType<typeof validateOpts>;\n getPublicKey: (privateKey: Hex) => Uint8Array;\n sign: (message: Hex, privateKey: Hex, options?: { context?: Hex }) => Uint8Array;\n verify: (\n sig: Hex,\n message: Hex,\n publicKey: Hex,\n options?: { context?: Hex; zip215: boolean }\n ) => boolean;\n ExtendedPoint: ExtPointConstructor;\n utils: {\n randomPrivateKey: () => Uint8Array;\n getExtendedPublicKey: (key: Hex) => {\n head: Uint8Array;\n prefix: Uint8Array;\n scalar: bigint;\n point: ExtPointType;\n pointBytes: Uint8Array;\n };\n };\n};\n\n/**\n * Creates Twisted Edwards curve with EdDSA signatures.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h\n * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h })\n */\nexport function twistedEdwards(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType<typeof validateOpts>;\n const {\n Fp,\n n: CURVE_ORDER,\n prehash: prehash,\n hash: cHash,\n randomBytes,\n nByteLength,\n h: cofactor,\n } = CURVE;\n const MASK = _2n << (BigInt(nByteLength * 8) - _1n);\n const modP = Fp.create; // Function overrides\n\n // sqrt(u/v)\n const uvRatio =\n CURVE.uvRatio ||\n ((u: bigint, v: bigint) => {\n try {\n return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };\n } catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes); // NOOP\n const domain =\n CURVE.domain ||\n ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => {\n abool('phflag', phflag);\n if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n // 0 <= n < MASK\n // Coordinates larger than Fp.ORDER are allowed for zip215\n function aCoordinate(title: string, n: bigint) {\n ut.aInRange('coordinate ' + title, n, _0n, MASK);\n }\n\n function assertPoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ExtendedPoint expected');\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n const toAffineMemo = memoized((p: Point, iz?: bigint): AffinePoint<bigint> => {\n const { ex: x, ey: y, ez: z } = p;\n const is0 = p.is0();\n if (iz == null) iz = is0 ? _8n : (Fp.inv(z) as bigint); // 8 was chosen arbitrarily\n const ax = modP(x * iz);\n const ay = modP(y * iz);\n const zz = modP(z * iz);\n if (is0) return { x: _0n, y: _1n };\n if (zz !== _1n) throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n const assertValidMemo = memoized((p: Point) => {\n const { a, d } = CURVE;\n if (p.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX\u00B2 + Y\u00B2)Z\u00B2 = Z\u2074 + dX\u00B2Y\u00B2\n const { ex: X, ey: Y, ez: Z, et: T } = p;\n const X2 = modP(X * X); // X\u00B2\n const Y2 = modP(Y * Y); // Y\u00B2\n const Z2 = modP(Z * Z); // Z\u00B2\n const Z4 = modP(Z2 * Z2); // Z\u2074\n const aX2 = modP(X2 * a); // aX\u00B2\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX\u00B2 + Y\u00B2)Z\u00B2\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z\u2074 + dX\u00B2Y\u00B2\n if (left !== right) throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT) throw new Error('bad point: equation left != right (2)');\n return true;\n });\n\n // Extended Point works in extended coordinates: (x, y, z, t) \u220B (x=x/z, y=y/z, t=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point implements ExtPointType {\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n\n constructor(\n readonly ex: bigint,\n readonly ey: bigint,\n readonly ez: bigint,\n readonly et: bigint\n ) {\n aCoordinate('x', ex);\n aCoordinate('y', ey);\n aCoordinate('z', ez);\n aCoordinate('t', et);\n Object.freeze(this);\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n static fromAffine(p: AffinePoint<bigint>): Point {\n if (p instanceof Point) throw new Error('extended point not allowed');\n const { x, y } = p || {};\n aCoordinate('x', x);\n aCoordinate('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n static normalizeZ(points: Point[]): Point[] {\n const toInv = Fp.invertBatch(points.map((p) => p.ez));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n wnaf.setWindowSize(this, windowSize);\n }\n // Not required for fromHex(), which always creates valid points.\n // Could be useful for fromAffine().\n assertValidity(): void {\n assertValidMemo(this);\n }\n\n // Compare one point to another.\n equals(other: Point): boolean {\n assertPoint(other);\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n\n is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n negate(): Point {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));\n }\n\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double(): Point {\n const { a } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other: Point) {\n assertPoint(other);\n const { a, d } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;\n // Faster algo for adding 2 Extended Points when curve's a=-1.\n // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4\n // Cost: 8M + 8add + 2*2.\n // Note: It does not check whether the `other` point is valid.\n if (a === BigInt(-1)) {\n const A = modP((Y1 - X1) * (Y2 + X2));\n const B = modP((Y1 + X1) * (Y2 - X2));\n const F = modP(B - A);\n if (F === _0n) return this.double(); // Same point. Tests say it doesn't affect timing\n const C = modP(Z1 * _2n * T2);\n const D = modP(T1 * _2n * Z2);\n const E = D + C;\n const G = B + A;\n const H = D - C;\n const X3 = modP(E * F);\n const Y3 = modP(G * H);\n const T3 = modP(E * H);\n const Z3 = modP(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n\n return new Point(X3, Y3, Z3, T3);\n }\n\n subtract(other: Point): Point {\n return this.add(other.negate());\n }\n\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n\n // Constant-time multiplication.\n multiply(scalar: bigint): Point {\n const n = scalar;\n ut.aInRange('scalar', n, _1n, CURVE_ORDER); // 1 <= scalar < L\n const { p, f } = this.wNAF(n);\n return Point.normalizeZ([p, f])[0];\n }\n\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n multiplyUnsafe(scalar: bigint): Point {\n const n = scalar;\n ut.aInRange('scalar', n, _0n, CURVE_ORDER); // 0 <= scalar < L\n if (n === _0n) return I;\n if (this.equals(I) || n === _1n) return this;\n if (this.equals(G)) return this.wNAF(n).p;\n return wnaf.unsafeLadder(this, n);\n }\n\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder(): boolean {\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree(): boolean {\n return wnaf.unsafeLadder(this, CURVE_ORDER).is0();\n }\n\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(iz?: bigint): AffinePoint<bigint> {\n return toAffineMemo(this, iz);\n }\n\n clearCofactor(): Point {\n const { h: cofactor } = CURVE;\n if (cofactor === _1n) return this;\n return this.multiplyUnsafe(cofactor);\n }\n\n // Converts hash string or Uint8Array to Point.\n // Uses algo from RFC8032 5.1.3.\n static fromHex(hex: Hex, zip215 = false): Point {\n const { d, a } = CURVE;\n const len = Fp.BYTES;\n hex = ensureBytes('pointHex', hex, len); // copy hex to a new array\n abool('zip215', zip215);\n const normed = hex.slice(); // copy again, we'll manipulate it\n const lastByte = hex[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = ut.bytesToNumberLE(normed);\n\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n ut.aInRange('pointHex.y', y, _0n, max);\n\n // Ed25519: x\u00B2 = (y\u00B2-1)/(dy\u00B2+1) mod p. Ed448: x\u00B2 = (y\u00B2-1)/(dy\u00B2-1) mod p. Generic case:\n // ax\u00B2+y\u00B2=1+dx\u00B2y\u00B2 => y\u00B2-1=dx\u00B2y\u00B2-ax\u00B2 => y\u00B2-1=x\u00B2(dy\u00B2-a) => x\u00B2=(y\u00B2-1)/(dy\u00B2-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y\u00B2 - 1\n const v = modP(d * y2 - a); // v = d y\u00B2 + 1.\n let { isValid, value: x } = uvRatio(u, v); // \u221A(u/v)\n if (!isValid) throw new Error('Point.fromHex: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('Point.fromHex: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromPrivateKey(privKey: Hex) {\n return getExtendedPublicKey(privKey).point;\n }\n toRawBytes(): Uint8Array {\n const { x, y } = this.toAffine();\n const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y\n return bytes; // and use the last byte to encode sign of x\n }\n toHex(): string {\n return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.\n }\n }\n const { BASE: G, ZERO: I } = Point;\n const wnaf = wNAF(Point, nByteLength * 8);\n\n function modN(a: bigint) {\n return mod(a, CURVE_ORDER);\n }\n // Little-endian SHA512 with modulo n\n function modN_LE(hash: Uint8Array): bigint {\n return modN(ut.bytesToNumberLE(hash));\n }\n\n /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */\n function getExtendedPublicKey(key: Hex) {\n const len = nByteLength;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n const point = G.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toRawBytes(); // Uint8Array representation\n return { head, prefix, scalar, point, pointBytes };\n }\n\n // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared\n function getPublicKey(privKey: Hex): Uint8Array {\n return getExtendedPublicKey(privKey).pointBytes;\n }\n\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context: Hex = new Uint8Array(), ...msgs: Uint8Array[]) {\n const msg = ut.concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg: Hex, privKey: Hex, options: { context?: Hex } = {}): Uint8Array {\n msg = ensureBytes('message', msg);\n if (prehash) msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = G.multiply(r).toRawBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = modN(r + k * scalar); // S = (r + k * s) mod L\n ut.aInRange('signature.s', s, _0n, CURVE_ORDER); // 0 <= s < l\n const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES));\n return ensureBytes('result', res, nByteLength * 2); // 64-byte signature\n }\n\n const verifyOpts: { context?: Hex; zip215?: boolean } = VERIFY_DEFAULT;\n function verify(sig: Hex, msg: Hex, publicKey: Hex, options = verifyOpts): boolean {\n const { context, zip215 } = options;\n const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.\n msg = ensureBytes('message', msg);\n if (zip215 !== undefined) abool('zip215', zip215);\n if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n const s = ut.bytesToNumberLE(sig.slice(len, 2 * len));\n // zip215: true is good for consensus-critical apps and allows points < 2^256\n // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p\n let A, R, SB;\n try {\n A = Point.fromHex(publicKey, zip215);\n R = Point.fromHex(sig.slice(0, len), zip215);\n SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside\n } catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder()) return false;\n\n const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);\n }\n\n G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n\n const utils = {\n getExtendedPublicKey,\n // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.\n randomPrivateKey: (): Uint8Array => randomBytes(Fp.BYTES),\n\n /**\n * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT\n * values. This slows down first getPublicKey() by milliseconds (see Speed section),\n * but allows to speed-up subsequent getPublicKey() calls up to 20x.\n * @param windowSize 2, 4, 8, 16\n */\n precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3));\n return point;\n },\n };\n\n return {\n CURVE,\n getPublicKey,\n sign,\n verify,\n ExtendedPoint: Point,\n utils,\n };\n}\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha512';\nimport { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils';\nimport { AffinePoint, Group } from './abstract/curve.js';\nimport { CurveFn, ExtPointType, twistedEdwards } from './abstract/edwards.js';\nimport { createHasher, expand_message_xmd, htfBasicOpts } from './abstract/hash-to-curve.js';\nimport { Field, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.js';\nimport { montgomery } from './abstract/montgomery.js';\nimport {\n bytesToHex,\n bytesToNumberLE,\n ensureBytes,\n equalBytes,\n Hex,\n numberToBytesLE,\n} from './abstract/utils.js';\n\n/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n */\n\nconst ED25519_P = BigInt(\n '57896044618658097711785492504343953926634992332820282019728792003956564819949'\n);\n// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt(\n '19681161376707505956807079304988542015446066515923890162744021073123829784752'\n);\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _5n = BigInt(5), _8n = BigInt(8);\n\nfunction ed25519_pow_2_252_3(x: bigint) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ED25519_P;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\n\nfunction adjustScalarBytes(bytes: Uint8Array): Uint8Array {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n\n// sqrt(u/v)\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n const P = ED25519_P;\n const v3 = mod(v * v * v, P); // v\u00B3\n const v7 = mod(v3 * v3 * v, P); // v\u2077\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv\u00B3)(uv\u2077)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx\u00B2\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx\u00B2 = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx\u00B2 = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx\u00B2 = -u\u221A(-1)\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P)) x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n\n// Just in case\nexport const ED25519_TORSION_SUBGROUP = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n\nconst Fp = /* @__PURE__ */ (() => Field(ED25519_P, undefined, true))();\n\nconst ed25519Defaults = /* @__PURE__ */ (() =>\n ({\n // Param: a\n a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster\n // d is equal to -121665/121666 over finite field.\n // Negative number is P - number, and division is invert(number, P)\n d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),\n // Finite field \uD835\uDD3Dp over which we'll do calculations; 2n**255n - 19n\n Fp,\n // Subgroup order: how many points curve has\n // 2n**252n + 27742317777372353535851937790883648493n;\n n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),\n // Cofactor\n h: _8n,\n // Base point (x, y) aka generator point\n Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),\n Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),\n hash: sha512,\n randomBytes,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/\u221Av\n uvRatio,\n }) as const)();\n\n/**\n * ed25519 curve with EdDSA signatures.\n */\nexport const ed25519: CurveFn = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();\n\nfunction ed25519_domain(data: Uint8Array, ctx: Uint8Array, phflag: boolean) {\n if (ctx.length > 255) throw new Error('Context is too big');\n return concatBytes(\n utf8ToBytes('SigEd25519 no Ed25519 collisions'),\n new Uint8Array([phflag ? 1 : 0, ctx.length]),\n ctx,\n data\n );\n}\n\nexport const ed25519ctx = /* @__PURE__ */ (() =>\n twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n }))();\nexport const ed25519ph = /* @__PURE__ */ (() =>\n twistedEdwards(\n Object.assign({}, ed25519Defaults, {\n domain: ed25519_domain,\n prehash: sha512,\n })\n ))();\n\nexport const x25519 = /* @__PURE__ */ (() =>\n montgomery({\n P: ED25519_P,\n a: BigInt(486662),\n montgomeryBits: 255, // n is 253 bits\n nByteLength: 32,\n Gu: BigInt(9),\n powPminus2: (x: bigint): bigint => {\n const P = ED25519_P;\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n },\n adjustScalarBytes,\n randomBytes,\n }))();\n\n/**\n * Converts ed25519 public key to x25519 public key. Uses formula:\n * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * @example\n * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());\n * const aPriv = x25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub))\n */\nexport function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array {\n const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub);\n const _1n = BigInt(1);\n return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y)));\n}\nexport const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated\n\n/**\n * Converts ed25519 secret key to x25519 secret key.\n * @example\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey());\n * const aPriv = ed25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub)\n */\nexport function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array {\n const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32));\n return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32);\n}\n\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\n\nconst ELL2_C1 = /* @__PURE__ */ (() => (Fp.ORDER + _3n) / _8n)(); // 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\n\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u: bigint) {\n const ELL2_C4 = (Fp.ORDER - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic\n const ELL2_J = BigInt(486662);\n\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J);// 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\n\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u: bigint) {\n const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n\n const inv = Fp.invertBatch([xd, yd]); // batch division\n return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd)\n}\n\nconst htf = /* @__PURE__ */ (() =>\n createHasher(\n ed25519.ExtendedPoint,\n (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]),\n {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n }\n ))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n\nfunction assertRstPoint(other: unknown) {\n if (!(other instanceof RistPoint)) throw new Error('RistrettoPoint expected');\n}\n\n// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// \u221A(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt(\n '25063068953384623474111414158702152701244531502492656460079210482610430750235'\n);\n// 1 / \u221A(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt(\n '54469307008909316920995813868745141605393597292927456921205312896311721017578'\n);\n// 1-d\u00B2\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt(\n '1159843021668779879193775521855586647937357759715417654439879720876111806838'\n);\n// (d-1)\u00B2\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt(\n '40440834346308536858101042469323190826248399146238708352240133220865137265952'\n);\n// Calculates 1/\u221A(number)\nconst invertSqrt = (number: bigint) => uvRatio(_1n, number);\n\nconst MAX_255B = /* @__PURE__ */ BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'\n);\nconst bytes255ToNumberLE = (bytes: Uint8Array) =>\n ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\ntype ExtendedPoint = ExtPointType;\n\n// Computes Elligator map for Ristretto\n// https://ristretto.group/formulas/elligator.html\nfunction calcElligatorRistrettoMap(r0: bigint): ExtendedPoint {\n const { d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P)) s_ = mod(-s_);\n if (!Ns_D_is_sq) s = s_; // 7\n if (!Ns_D_is_sq) c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\n/**\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448\n */\nclass RistPoint implements Group<RistPoint> {\n static BASE: RistPoint;\n static ZERO: RistPoint;\n // Private property to discourage combining ExtendedPoint + RistrettoPoint\n // Always use Ristretto encoding/decoding instead.\n constructor(private readonly ep: ExtendedPoint) {}\n\n static fromAffine(ap: AffinePoint<bigint>) {\n return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap));\n }\n\n /**\n * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`.\n * The hash-to-group operation applies Elligator twice and adds the results.\n * **Note:** this is one-way map, there is no conversion from point to hash.\n * https://ristretto.group/formulas/elligator.html\n * @param hex 64-byte output of a hash function\n */\n static hashToCurve(hex: Hex): RistPoint {\n hex = ensureBytes('ristrettoHash', hex, 64);\n const r1 = bytes255ToNumberLE(hex.slice(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(hex.slice(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new RistPoint(R1.add(R2));\n }\n\n /**\n * Converts ristretto-encoded string to ristretto point.\n * https://ristretto.group/formulas/decoding.html\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex: Hex): RistPoint {\n hex = ensureBytes('ristrettoHex', hex, 32);\n const { a, d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';\n const s = bytes255ToNumberLE(hex);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P)) throw new Error(emsg);\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P)) x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n) throw new Error(emsg);\n return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t));\n }\n\n /**\n * Encodes ristretto point to Uint8Array.\n * https://ristretto.group/formulas/encoding.html\n */\n toRawBytes(): Uint8Array {\n let { ex: x, ey: y, ez: z, et: t } = this.ep;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const u1 = mod(mod(z + y) * mod(z - y)); // 1\n const u2 = mod(x * y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * t); // 6\n let D: bigint; // 7\n if (isNegativeLE(t * zInv, P)) {\n let _x = mod(y * SQRT_M1);\n let _y = mod(x * SQRT_M1);\n x = _x;\n y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n } else {\n D = D2; // 8\n }\n if (isNegativeLE(x * zInv, P)) y = mod(-y); // 9\n let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P)) s = mod(-s);\n return numberToBytesLE(s, 32); // 11\n }\n\n toHex(): string {\n return bytesToHex(this.toRawBytes());\n }\n\n toString(): string {\n return this.toHex();\n }\n\n // Compare one point to another.\n equals(other: RistPoint): boolean {\n assertRstPoint(other);\n const { ex: X1, ey: Y1 } = this.ep;\n const { ex: X2, ey: Y2 } = other.ep;\n const mod = ed25519.CURVE.Fp.create;\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n\n add(other: RistPoint): RistPoint {\n assertRstPoint(other);\n return new RistPoint(this.ep.add(other.ep));\n }\n\n subtract(other: RistPoint): RistPoint {\n assertRstPoint(other);\n return new RistPoint(this.ep.subtract(other.ep));\n }\n\n multiply(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiply(scalar));\n }\n\n multiplyUnsafe(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiplyUnsafe(scalar));\n }\n\n double(): RistPoint {\n return new RistPoint(this.ep.double());\n }\n\n negate(): RistPoint {\n return new RistPoint(this.ep.negate());\n }\n}\nexport const RistrettoPoint = /* @__PURE__ */ (() => {\n if (!RistPoint.BASE) RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE);\n if (!RistPoint.ZERO) RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO);\n return RistPoint;\n})();\n\n// Hashing to ristretto255. https://www.rfc-editor.org/rfc/rfc9380#appendix-B\nexport const hashToRistretto255 = (msg: Uint8Array, options: htfBasicOpts) => {\n const d = options.DST;\n const DST = typeof d === 'string' ? utf8ToBytes(d) : d;\n const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512);\n const P = RistPoint.hashToCurve(uniform_bytes);\n return P;\n};\nexport const hash_to_ristretto255 = hashToRistretto255; // legacy\n", "export type ExpirableMapOptions<K, V> = {\n source?: Iterable<[K, V]>;\n expirationTime?: number;\n};\n\n/**\n * A map that expires entries after a given time.\n * Defaults to 10 minutes.\n */\nexport class ExpirableMap<K, V> implements Map<K, V> {\n // Internals\n #inner: Map<K, { value: V; timestamp: number }>;\n #expirationTime: number;\n\n [Symbol.iterator]: () => IterableIterator<[K, V]> = this.entries.bind(this);\n [Symbol.toStringTag] = 'ExpirableMap';\n\n /**\n * Create a new ExpirableMap.\n * @param {ExpirableMapOptions<any, any>} options - options for the map.\n * @param {Iterable<[any, any]>} options.source - an optional source of entries to initialize the map with.\n * @param {number} options.expirationTime - the time in milliseconds after which entries will expire.\n */\n constructor(options: ExpirableMapOptions<K, V> = {}) {\n const { source = [], expirationTime = 10 * 60 * 1000 } = options;\n const currentTime = Date.now();\n this.#inner = new Map(\n [...source].map(([key, value]) => [key, { value, timestamp: currentTime }]),\n );\n this.#expirationTime = expirationTime;\n }\n\n /**\n * Prune removes all expired entries.\n */\n prune() {\n const currentTime = Date.now();\n for (const [key, entry] of this.#inner.entries()) {\n if (currentTime - entry.timestamp > this.#expirationTime) {\n this.#inner.delete(key);\n }\n }\n return this;\n }\n\n // Implementing the Map interface\n\n /**\n * Set the value for the given key. Prunes expired entries.\n * @param key for the entry\n * @param value of the entry\n * @returns this\n */\n set(key: K, value: V) {\n this.prune();\n const entry = {\n value,\n timestamp: Date.now(),\n };\n this.#inner.set(key, entry);\n\n return this;\n }\n\n /**\n * Get the value associated with the key, if it exists and has not expired.\n * @param key K\n * @returns the value associated with the key, or undefined if the key is not present or has expired.\n */\n get(key: K) {\n const entry = this.#inner.get(key);\n if (entry === undefined) {\n return undefined;\n }\n if (Date.now() - entry.timestamp > this.#expirationTime) {\n this.#inner.delete(key);\n return undefined;\n }\n return entry.value;\n }\n\n /**\n * Clear all entries.\n */\n clear() {\n this.#inner.clear();\n }\n\n /**\n * Entries returns the entries of the map, without the expiration time.\n * @returns an iterator over the entries of the map.\n */\n entries(): IterableIterator<[K, V]> {\n const iterator = this.#inner.entries();\n const generator = function* () {\n for (const [key, value] of iterator) {\n yield [key, value.value] as [K, V];\n }\n };\n return generator();\n }\n\n /**\n * Values returns the values of the map, without the expiration time.\n * @returns an iterator over the values of the map.\n */\n values(): IterableIterator<V> {\n const iterator = this.#inner.values();\n const generator = function* () {\n for (const value of iterator) {\n yield value.value;\n }\n };\n return generator();\n }\n\n /**\n * Keys returns the keys of the map\n * @returns an iterator over the keys of the map.\n */\n keys(): IterableIterator<K> {\n return this.#inner.keys();\n }\n\n /**\n * forEach calls the callbackfn on each entry of the map.\n * @param callbackfn to call on each entry\n * @param thisArg to use as this when calling the callbackfn\n */\n forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: ExpirableMap<K, V>) {\n for (const [key, value] of this.#inner.entries()) {\n callbackfn.call(thisArg, value.value, key, this);\n }\n }\n\n /**\n * has returns true if the key exists and has not expired.\n * @param key K\n * @returns true if the key exists and has not expired.\n */\n has(key: K): boolean {\n return this.#inner.has(key);\n }\n\n /**\n * delete the entry for the given key.\n * @param key K\n * @returns true if the key existed and has been deleted.\n */\n delete(key: K) {\n return this.#inner.delete(key);\n }\n\n /**\n * get size of the map.\n * @returns the size of the map.\n */\n get size() {\n return this.#inner.size;\n }\n}\n", "import { bufEquals } from './utils/buffer';\n\nexport const encodeLenBytes = (len: number): number => {\n if (len <= 0x7f) {\n return 1;\n } else if (len <= 0xff) {\n return 2;\n } else if (len <= 0xffff) {\n return 3;\n } else if (len <= 0xffffff) {\n return 4;\n } else {\n throw new Error('Length too long (> 4 bytes)');\n }\n};\n\nexport const encodeLen = (buf: Uint8Array, offset: number, len: number): number => {\n if (len <= 0x7f) {\n buf[offset] = len;\n return 1;\n } else if (len <= 0xff) {\n buf[offset] = 0x81;\n buf[offset + 1] = len;\n return 2;\n } else if (len <= 0xffff) {\n buf[offset] = 0x82;\n buf[offset + 1] = len >> 8;\n buf[offset + 2] = len;\n return 3;\n } else if (len <= 0xffffff) {\n buf[offset] = 0x83;\n buf[offset + 1] = len >> 16;\n buf[offset + 2] = len >> 8;\n buf[offset + 3] = len;\n return 4;\n } else {\n throw new Error('Length too long (> 4 bytes)');\n }\n};\n\nexport const decodeLenBytes = (buf: Uint8Array, offset: number): number => {\n if (buf[offset] < 0x80) return 1;\n if (buf[offset] === 0x80) throw new Error('Invalid length 0');\n if (buf[offset] === 0x81) return 2;\n if (buf[offset] === 0x82) return 3;\n if (buf[offset] === 0x83) return 4;\n throw new Error('Length too long (> 4 bytes)');\n};\n\nexport const decodeLen = (buf: Uint8Array, offset: number): number => {\n const lenBytes = decodeLenBytes(buf, offset);\n if (lenBytes === 1) return buf[offset];\n else if (lenBytes === 2) return buf[offset + 1];\n else if (lenBytes === 3) return (buf[offset + 1] << 8) + buf[offset + 2];\n else if (lenBytes === 4)\n return (buf[offset + 1] << 16) + (buf[offset + 2] << 8) + buf[offset + 3];\n throw new Error('Length too long (> 4 bytes)');\n};\n\n/**\n * A DER encoded `SEQUENCE(OID)` for DER-encoded-COSE\n */\nexport const DER_COSE_OID = Uint8Array.from([\n ...[0x30, 0x0c], // SEQUENCE\n ...[0x06, 0x0a], // OID with 10 bytes\n ...[0x2b, 0x06, 0x01, 0x04, 0x01, 0x83, 0xb8, 0x43, 0x01, 0x01], // DER encoded COSE\n]);\n\n/**\n * A DER encoded `SEQUENCE(OID)` for the Ed25519 algorithm\n */\nexport const ED25519_OID = Uint8Array.from([\n ...[0x30, 0x05], // SEQUENCE\n ...[0x06, 0x03], // OID with 3 bytes\n ...[0x2b, 0x65, 0x70], // id-Ed25519 OID\n]);\n\n/**\n * A DER encoded `SEQUENCE(OID)` for secp256k1 with the ECDSA algorithm\n */\nexport const SECP256K1_OID = Uint8Array.from([\n ...[0x30, 0x10], // SEQUENCE\n ...[0x06, 0x07], // OID with 7 bytes\n ...[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01], // OID ECDSA\n ...[0x06, 0x05], // OID with 5 bytes\n ...[0x2b, 0x81, 0x04, 0x00, 0x0a], // OID secp256k1\n]);\n\n/**\n * Wraps the given `payload` in a DER encoding tagged with the given encoded `oid` like so:\n * `SEQUENCE(oid, BITSTRING(payload))`\n *\n * @param payload The payload to encode as the bit string\n * @param oid The DER encoded (and SEQUENCE wrapped!) OID to tag the payload with\n */\nexport function wrapDER(payload: ArrayBuffer, oid: Uint8Array): Uint8Array {\n // The Bit String header needs to include the unused bit count byte in its length\n const bitStringHeaderLength = 2 + encodeLenBytes(payload.byteLength + 1);\n const len = oid.byteLength + bitStringHeaderLength + payload.byteLength;\n let offset = 0;\n const buf = new Uint8Array(1 + encodeLenBytes(len) + len);\n // Sequence\n buf[offset++] = 0x30;\n // Sequence Length\n offset += encodeLen(buf, offset, len);\n\n // OID\n buf.set(oid, offset);\n offset += oid.byteLength;\n\n // Bit String Header\n buf[offset++] = 0x03;\n offset += encodeLen(buf, offset, payload.byteLength + 1);\n // 0 padding\n buf[offset++] = 0x00;\n buf.set(new Uint8Array(payload), offset);\n\n return buf;\n}\n\n/**\n * Extracts a payload from the given `derEncoded` data, and checks that it was tagged with the given `oid`.\n *\n * `derEncoded = SEQUENCE(oid, BITSTRING(payload))`\n *\n * @param derEncoded The DER encoded and tagged data\n * @param oid The DER encoded (and SEQUENCE wrapped!) expected OID\n * @returns The unwrapped payload\n */\nexport const unwrapDER = (derEncoded: ArrayBuffer, oid: Uint8Array): Uint8Array => {\n let offset = 0;\n const expect = (n: number, msg: string) => {\n if (buf[offset++] !== n) {\n throw new Error('Expected: ' + msg);\n }\n };\n\n const buf = new Uint8Array(derEncoded);\n expect(0x30, 'sequence');\n offset += decodeLenBytes(buf, offset);\n\n if (!bufEquals(buf.slice(offset, offset + oid.byteLength), oid)) {\n throw new Error('Not the expected OID.');\n }\n offset += oid.byteLength;\n\n expect(0x03, 'bit string');\n const payloadLen = decodeLen(buf, offset) - 1; // Subtracting 1 to account for the 0 padding\n offset += decodeLenBytes(buf, offset);\n expect(0x00, '0 padding');\n const result = buf.slice(offset);\n if (payloadLen !== result.length) {\n throw new Error(\n `DER payload mismatch: Expected length ${payloadLen} actual length ${result.length}`,\n );\n }\n return result;\n};\n", "import { DerEncodedPublicKey, PublicKey } from './auth';\nimport { ED25519_OID, unwrapDER, wrapDER } from './der';\n\nexport class Ed25519PublicKey implements PublicKey {\n public static from(key: PublicKey): Ed25519PublicKey {\n return this.fromDer(key.toDer());\n }\n\n public static fromRaw(rawKey: ArrayBuffer): Ed25519PublicKey {\n return new Ed25519PublicKey(rawKey);\n }\n\n public static fromDer(derKey: DerEncodedPublicKey): Ed25519PublicKey {\n return new Ed25519PublicKey(this.derDecode(derKey));\n }\n\n // The length of Ed25519 public keys is always 32 bytes.\n private static RAW_KEY_LENGTH = 32;\n\n private static derEncode(publicKey: ArrayBuffer): DerEncodedPublicKey {\n return wrapDER(publicKey, ED25519_OID).buffer as DerEncodedPublicKey;\n }\n\n private static derDecode(key: DerEncodedPublicKey): ArrayBuffer {\n const unwrapped = unwrapDER(key, ED25519_OID);\n if (unwrapped.length !== this.RAW_KEY_LENGTH) {\n throw new Error('An Ed25519 public key must be exactly 32bytes long');\n }\n return unwrapped;\n }\n\n #rawKey: ArrayBuffer;\n\n public get rawKey(): ArrayBuffer {\n return this.#rawKey;\n }\n\n #derKey: DerEncodedPublicKey;\n\n public get derKey(): DerEncodedPublicKey {\n return this.#derKey;\n }\n\n // `fromRaw` and `fromDer` should be used for instantiation, not this constructor.\n private constructor(key: ArrayBuffer) {\n if (key.byteLength !== Ed25519PublicKey.RAW_KEY_LENGTH) {\n throw new Error('An Ed25519 public key must be exactly 32bytes long');\n }\n this.#rawKey = key;\n this.#derKey = Ed25519PublicKey.derEncode(key);\n }\n\n public toDer(): DerEncodedPublicKey {\n return this.derKey;\n }\n\n public toRaw(): ArrayBuffer {\n return this.rawKey;\n }\n}\n", "import { AgentError } from './errors';\n\nexport type ObserveFunction<T> = (data: T, ...rest: unknown[]) => void;\n\nexport class Observable<T> {\n observers: ObserveFunction<T>[];\n\n constructor() {\n this.observers = [];\n }\n\n subscribe(func: ObserveFunction<T>) {\n this.observers.push(func);\n }\n\n unsubscribe(func: ObserveFunction<T>) {\n this.observers = this.observers.filter(observer => observer !== func);\n }\n\n notify(data: T, ...rest: unknown[]) {\n this.observers.forEach(observer => observer(data, ...rest));\n }\n}\n\nexport type AgentLog =\n | {\n message: string;\n level: 'warn' | 'info';\n }\n | {\n message: string;\n level: 'error';\n error: AgentError;\n };\n\nexport class ObservableLog extends Observable<AgentLog> {\n constructor() {\n super();\n }\n print(message: string, ...rest: unknown[]) {\n this.notify({ message, level: 'info' }, ...rest);\n }\n warn(message: string, ...rest: unknown[]) {\n this.notify({ message, level: 'warn' }, ...rest);\n }\n error(message: string, error: AgentError, ...rest: unknown[]) {\n this.notify({ message, level: 'error', error }, ...rest);\n }\n}\n", "const RANDOMIZATION_FACTOR = 0.5;\nconst MULTIPLIER = 1.5;\nconst INITIAL_INTERVAL_MSEC = 500;\nconst MAX_INTERVAL_MSEC = 60_000;\nconst MAX_ELAPSED_TIME_MSEC = 900_000;\nconst MAX_ITERATIONS = 10;\n\nexport type BackoffStrategy = {\n next: () => number | null;\n currentInterval?: number;\n count?: number;\n ellapsedTimeInMsec?: number;\n};\n\nexport type BackoffStrategyArgs = {\n maxIterations?: number;\n maxElapsedTime?: number;\n};\n\nexport type BackoffStrategyFactory = (args?: BackoffStrategyArgs) => BackoffStrategy;\n\n// export type BackoffStrategyGenerator = Generator<number, void, unknown>;\n\nexport type ExponentialBackoffOptions = {\n initialInterval?: number;\n randomizationFactor?: number;\n multiplier?: number;\n maxInterval?: number;\n maxElapsedTime?: number;\n maxIterations?: number;\n date?: DateConstructor;\n};\n\n/**\n * Exponential backoff strategy.\n */\nexport class ExponentialBackoff {\n #currentInterval: number;\n #randomizationFactor: number;\n #multiplier: number;\n #maxInterval: number;\n #startTime: number;\n #maxElapsedTime: number;\n #maxIterations: number;\n #date: DateConstructor;\n #count = 0;\n\n static default = {\n initialInterval: INITIAL_INTERVAL_MSEC,\n randomizationFactor: RANDOMIZATION_FACTOR,\n multiplier: MULTIPLIER,\n maxInterval: MAX_INTERVAL_MSEC,\n // 1 minute\n maxElapsedTime: MAX_ELAPSED_TIME_MSEC,\n maxIterations: MAX_ITERATIONS,\n date: Date,\n };\n\n constructor(options: ExponentialBackoffOptions = ExponentialBackoff.default) {\n const {\n initialInterval = INITIAL_INTERVAL_MSEC,\n randomizationFactor = RANDOMIZATION_FACTOR,\n multiplier = MULTIPLIER,\n maxInterval = MAX_INTERVAL_MSEC,\n maxElapsedTime = MAX_ELAPSED_TIME_MSEC,\n maxIterations = MAX_ITERATIONS,\n date = Date,\n } = options;\n this.#currentInterval = initialInterval;\n this.#randomizationFactor = randomizationFactor;\n this.#multiplier = multiplier;\n this.#maxInterval = maxInterval;\n this.#date = date;\n this.#startTime = date.now();\n this.#maxElapsedTime = maxElapsedTime;\n this.#maxIterations = maxIterations;\n }\n\n get ellapsedTimeInMsec() {\n return this.#date.now() - this.#startTime;\n }\n\n get currentInterval() {\n return this.#currentInterval;\n }\n\n get count() {\n return this.#count;\n }\n\n get randomValueFromInterval() {\n const delta = this.#randomizationFactor * this.#currentInterval;\n const min = this.#currentInterval - delta;\n const max = this.#currentInterval + delta;\n return Math.random() * (max - min) + min;\n }\n\n public incrementCurrentInterval() {\n this.#currentInterval = Math.min(this.#currentInterval * this.#multiplier, this.#maxInterval);\n this.#count++;\n\n return this.#currentInterval;\n }\n\n public next() {\n if (this.ellapsedTimeInMsec >= this.#maxElapsedTime || this.#count >= this.#maxIterations) {\n return null;\n } else {\n this.incrementCurrentInterval();\n return this.randomValueFromInterval;\n }\n }\n}\n/**\n * Utility function to create an exponential backoff iterator.\n * @param options - for the exponential backoff\n * @returns an iterator that yields the next delay in the exponential backoff\n * @yields the next delay in the exponential backoff\n */\nexport function* exponentialBackoff(\n options: ExponentialBackoffOptions = ExponentialBackoff.default,\n) {\n const backoff = new ExponentialBackoff(options);\n\n let next = backoff.next();\n while (next) {\n yield next;\n next = backoff.next();\n }\n}\n", "import { JsonObject } from '@dfinity/candid';\nimport { Principal } from '@dfinity/principal';\nimport { AgentError } from '../../errors';\nimport { AnonymousIdentity, Identity } from '../../auth';\nimport * as cbor from '../../cbor';\nimport { RequestId, hashOfMap, requestIdOf } from '../../request_id';\nimport { bufFromBufLike, concat, fromHex } from '../../utils/buffer';\nimport {\n Agent,\n ApiQueryResponse,\n QueryFields,\n QueryResponse,\n ReadStateOptions,\n ReadStateResponse,\n SubmitResponse,\n} from '../api';\nimport { Expiry, httpHeadersTransform, makeNonceTransform } from './transforms';\nimport {\n CallRequest,\n Endpoint,\n HttpAgentRequest,\n HttpAgentRequestTransformFn,\n HttpAgentSubmitRequest,\n makeNonce,\n Nonce,\n QueryRequest,\n ReadRequestType,\n SubmitRequestType,\n} from './types';\nimport { AgentHTTPResponseError } from './errors';\nimport { SubnetStatus, request } from '../../canisterStatus';\nimport {\n CertificateVerificationError,\n HashTree,\n LookupStatus,\n lookup_path,\n} from '../../certificate';\nimport { ed25519 } from '@noble/curves/ed25519';\nimport { ExpirableMap } from '../../utils/expirableMap';\nimport { Ed25519PublicKey } from '../../public_key';\nimport { decodeTime } from '../../utils/leb';\nimport { ObservableLog } from '../../observable';\nimport { BackoffStrategy, BackoffStrategyFactory, ExponentialBackoff } from '../../polling/backoff';\nexport * from './transforms';\nexport { Nonce, makeNonce } from './types';\n\nexport enum RequestStatusResponseStatus {\n Received = 'received',\n Processing = 'processing',\n Replied = 'replied',\n Rejected = 'rejected',\n Unknown = 'unknown',\n Done = 'done',\n}\n\n// Default delta for ingress expiry is 5 minutes.\nconst DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS = 5 * 60 * 1000;\n\n// Root public key for the IC, encoded as hex\nexport const IC_ROOT_KEY =\n '308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814' +\n 'c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d968' +\n '5f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484' +\n 'b01291091c5f87b98883463f98091a0baaae';\n\nexport const MANAGEMENT_CANISTER_ID = 'aaaaa-aa';\n\n// IC0 domain info\nconst IC0_DOMAIN = 'ic0.app';\nconst IC0_SUB_DOMAIN = '.ic0.app';\n\nconst ICP0_DOMAIN = 'icp0.io';\nconst ICP0_SUB_DOMAIN = '.icp0.io';\n\nconst ICP_API_DOMAIN = 'icp-api.io';\nconst ICP_API_SUB_DOMAIN = '.icp-api.io';\n\nclass HttpDefaultFetchError extends AgentError {\n constructor(public readonly message: string) {\n super(message);\n }\n}\nexport class IdentityInvalidError extends AgentError {\n constructor(public readonly message: string) {\n super(message);\n }\n}\n\n// HttpAgent options that can be used at construction.\nexport interface HttpAgentOptions {\n // A surrogate to the global fetch function. Useful for testing.\n fetch?: typeof fetch;\n\n // Additional options to pass along to fetch. Will not override fields that\n // the agent already needs to set\n // Should follow the RequestInit interface, but we intentially support non-standard fields\n fetchOptions?: Record<string, unknown>;\n\n // Additional options to pass along to fetch for the call API.\n callOptions?: Record<string, unknown>;\n\n // The host to use for the client. By default, uses the same host as\n // the current page.\n host?: string;\n\n // The principal used to send messages. This cannot be empty at the request\n // time (will throw).\n identity?: Identity | Promise<Identity>;\n\n credentials?: {\n name: string;\n password?: string;\n };\n /**\n * Adds a unique {@link Nonce} with each query.\n * Enabling will prevent queries from being answered with a cached response.\n * @example\n * const agent = new HttpAgent({ useQueryNonces: true });\n * agent.addTransform(makeNonceTransform(makeNonce);\n * @default false\n */\n useQueryNonces?: boolean;\n /**\n * Number of times to retry requests before throwing an error\n * @default 3\n */\n retryTimes?: number;\n /**\n * The strategy to use for backoff when retrying requests\n */\n backoffStrategy?: BackoffStrategyFactory;\n /**\n * Whether the agent should verify signatures signed by node keys on query responses. Increases security, but adds overhead and must make a separate request to cache the node keys for the canister's subnet.\n * @default true\n */\n verifyQuerySignatures?: boolean;\n /**\n * Whether to log to the console. Defaults to false.\n */\n logToConsole?: boolean;\n}\n\nfunction getDefaultFetch(): typeof fetch {\n let defaultFetch;\n\n if (typeof window !== 'undefined') {\n // Browser context\n if (window.fetch) {\n defaultFetch = window.fetch.bind(window);\n } else {\n throw new HttpDefaultFetchError(\n 'Fetch implementation was not available. You appear to be in a browser context, but window.fetch was not present.',\n );\n }\n } else if (typeof global !== 'undefined') {\n // Node context\n if (global.fetch) {\n defaultFetch = global.fetch.bind(global);\n } else {\n throw new HttpDefaultFetchError(\n 'Fetch implementation was not available. You appear to be in a Node.js context, but global.fetch was not available.',\n );\n }\n } else if (typeof self !== 'undefined') {\n if (self.fetch) {\n defaultFetch = self.fetch.bind(self);\n }\n }\n\n if (defaultFetch) {\n return defaultFetch;\n }\n throw new HttpDefaultFetchError(\n 'Fetch implementation was not available. Please provide fetch to the HttpAgent constructor, or ensure it is available in the window or global context.',\n );\n}\n\nfunction determineHost(configuredHost: string | undefined): string {\n let host: URL;\n if (configuredHost !== undefined) {\n if (!configuredHost.match(/^[a-z]+:/) && typeof window !== 'undefined') {\n host = new URL(window.location.protocol + '//' + configuredHost);\n } else {\n host = new URL(configuredHost);\n }\n } else {\n // Mainnet, local, and remote environments will have the api route available\n const knownHosts = ['ic0.app', 'icp0.io', '127.0.0.1', 'localhost'];\n const remoteHosts = ['.github.dev', '.gitpod.io'];\n const location = typeof window !== 'undefined' ? window.location : undefined;\n const hostname = location?.hostname;\n let knownHost;\n if (hostname && typeof hostname === 'string') {\n if (remoteHosts.some(host => hostname.endsWith(host))) {\n knownHost = hostname;\n } else {\n knownHost = knownHosts.find(host => hostname.endsWith(host));\n }\n }\n\n if (location && knownHost) {\n // If the user is on a boundary-node provided host, we can use the same host for the agent\n host = new URL(\n `${location.protocol}//${knownHost}${location.port ? ':' + location.port : ''}`,\n );\n } else {\n host = new URL('https://icp-api.io');\n }\n }\n return host.toString();\n}\n\ninterface V1HttpAgentInterface {\n _identity: Promise<Identity> | null;\n readonly _fetch: typeof fetch;\n readonly _fetchOptions?: Record<string, unknown>;\n readonly _callOptions?: Record<string, unknown>;\n\n readonly _host: URL;\n readonly _credentials: string | undefined;\n readonly _retryTimes: number; // Retry requests N times before erroring by default\n _isAgent: true;\n}\n\n// A HTTP agent allows users to interact with a client of the internet computer\n// using the available methods. It exposes an API that closely follows the\n// public view of the internet computer, and is not intended to be exposed\n// directly to the majority of users due to its low-level interface.\n//\n// There is a pipeline to apply transformations to the request before sending\n// it to the client. This is to decouple signature, nonce generation and\n// other computations so that this class can stay as simple as possible while\n// allowing extensions.\nexport class HttpAgent implements Agent {\n public rootKey = fromHex(IC_ROOT_KEY);\n #identity: Promise<Identity> | null;\n readonly #fetch: typeof fetch;\n readonly #fetchOptions?: Record<string, unknown>;\n readonly #callOptions?: Record<string, unknown>;\n #timeDiffMsecs = 0;\n readonly host: URL;\n readonly #credentials: string | undefined;\n #rootKeyFetched = false;\n readonly #retryTimes; // Retry requests N times before erroring by default\n #backoffStrategy: BackoffStrategyFactory;\n\n // Public signature to help with type checking.\n public readonly _isAgent = true;\n public config: HttpAgentOptions = {};\n\n // The UTC time in milliseconds when the latest request was made\n #waterMark = 0;\n\n get waterMark(): number {\n return this.#waterMark;\n }\n\n public log: ObservableLog = new ObservableLog();\n\n #queryPipeline: HttpAgentRequestTransformFn[] = [];\n #updatePipeline: HttpAgentRequestTransformFn[] = [];\n\n #subnetKeys: ExpirableMap<string, SubnetStatus> = new ExpirableMap({\n expirationTime: 5 * 60 * 1000, // 5 minutes\n });\n #verifyQuerySignatures = true;\n\n /**\n * @param options - Options for the HttpAgent\n * @deprecated Use `HttpAgent.create` or `HttpAgent.createSync` instead\n */\n constructor(options: HttpAgentOptions = {}) {\n this.config = options;\n this.#fetch = options.fetch || getDefaultFetch() || fetch.bind(global);\n this.#fetchOptions = options.fetchOptions;\n this.#callOptions = options.callOptions;\n\n const host = determineHost(options.host);\n this.host = new URL(host);\n\n if (options.verifyQuerySignatures !== undefined) {\n this.#verifyQuerySignatures = options.verifyQuerySignatures;\n }\n // Default is 3\n this.#retryTimes = options.retryTimes ?? 3;\n // Delay strategy for retries. Default is exponential backoff\n const defaultBackoffFactory = () =>\n new ExponentialBackoff({\n maxIterations: this.#retryTimes,\n });\n this.#backoffStrategy = options.backoffStrategy || defaultBackoffFactory;\n // Rewrite to avoid redirects\n if (this.host.hostname.endsWith(IC0_SUB_DOMAIN)) {\n this.host.hostname = IC0_DOMAIN;\n } else if (this.host.hostname.endsWith(ICP0_SUB_DOMAIN)) {\n this.host.hostname = ICP0_DOMAIN;\n } else if (this.host.hostname.endsWith(ICP_API_SUB_DOMAIN)) {\n this.host.hostname = ICP_API_DOMAIN;\n }\n\n if (options.credentials) {\n const { name, password } = options.credentials;\n this.#credentials = `${name}${password ? ':' + password : ''}`;\n }\n this.#identity = Promise.resolve(options.identity || new AnonymousIdentity());\n\n // Add a nonce transform to ensure calls are unique\n this.addTransform('update', makeNonceTransform(makeNonce));\n if (options.useQueryNonces) {\n this.addTransform('query', makeNonceTransform(makeNonce));\n }\n if (options.logToConsole) {\n this.log.subscribe(log => {\n if (log.level === 'error') {\n console.error(log.message);\n } else if (log.level === 'warn') {\n console.warn(log.message);\n } else {\n console.log(log.message);\n }\n });\n }\n }\n\n public static createSync(options: HttpAgentOptions = {}): HttpAgent {\n return new this({ ...options });\n }\n\n public static async create(\n options: HttpAgentOptions & { shouldFetchRootKey?: boolean } = {\n shouldFetchRootKey: false,\n },\n ): Promise<HttpAgent> {\n const agent = HttpAgent.createSync(options);\n const initPromises: Promise<ArrayBuffer | void>[] = [agent.syncTime()];\n if (agent.host.toString() !== 'https://icp-api.io' && options.shouldFetchRootKey) {\n initPromises.push(agent.fetchRootKey());\n }\n await Promise.all(initPromises);\n return agent;\n }\n\n public static async from(\n agent: Pick<HttpAgent, 'config'> | V1HttpAgentInterface,\n ): Promise<HttpAgent> {\n try {\n if ('config' in agent) {\n return await HttpAgent.create(agent.config);\n }\n return await HttpAgent.create({\n fetch: agent._fetch,\n fetchOptions: agent._fetchOptions,\n callOptions: agent._callOptions,\n host: agent._host.toString(),\n identity: agent._identity ?? undefined,\n });\n } catch (error) {\n throw new AgentError('Failed to create agent from provided agent');\n }\n }\n\n public isLocal(): boolean {\n const hostname = this.host.hostname;\n return hostname === '127.0.0.1' || hostname.endsWith('127.0.0.1');\n }\n\n public addTransform(\n type: 'update' | 'query',\n fn: HttpAgentRequestTransformFn,\n priority = fn.priority || 0,\n ): void {\n if (type === 'update') {\n // Keep the pipeline sorted at all time, by priority.\n const i = this.#updatePipeline.findIndex(x => (x.priority || 0) < priority);\n this.#updatePipeline.splice(\n i >= 0 ? i : this.#updatePipeline.length,\n 0,\n Object.assign(fn, { priority }),\n );\n } else if (type === 'query') {\n // Keep the pipeline sorted at all time, by priority.\n const i = this.#queryPipeline.findIndex(x => (x.priority || 0) < priority);\n this.#queryPipeline.splice(\n i >= 0 ? i : this.#queryPipeline.length,\n 0,\n Object.assign(fn, { priority }),\n );\n }\n }\n\n public async getPrincipal(): Promise<Principal> {\n if (!this.#identity) {\n throw new IdentityInvalidError(\n \"This identity has expired due this application's security policy. Please refresh your authentication.\",\n );\n }\n return (await this.#identity).getPrincipal();\n }\n\n public async call(\n canisterId: Principal | string,\n options: {\n methodName: string;\n arg: ArrayBuffer;\n effectiveCanisterId?: Principal | string;\n },\n identity?: Identity | Promise<Identity>,\n ): Promise<SubmitResponse> {\n const id = await (identity !== undefined ? await identity : await this.#identity);\n if (!id) {\n throw new IdentityInvalidError(\n \"This identity has expired due this application's security policy. Please refresh your authentication.\",\n );\n }\n const canister = Principal.from(canisterId);\n const ecid = options.effectiveCanisterId\n ? Principal.from(options.effectiveCanisterId)\n : canister;\n\n const sender: Principal = id.getPrincipal() || Principal.anonymous();\n\n let ingress_expiry = new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS);\n\n // If the value is off by more than 30 seconds, reconcile system time with the network\n if (Math.abs(this.#timeDiffMsecs) > 1_000 * 30) {\n ingress_expiry = new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS + this.#timeDiffMsecs);\n }\n\n const submit: CallRequest = {\n request_type: SubmitRequestType.Call,\n canister_id: canister,\n method_name: options.methodName,\n arg: options.arg,\n sender,\n ingress_expiry,\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let transformedRequest: any = (await this._transform({\n request: {\n body: null,\n method: 'POST',\n headers: {\n 'Content-Type': 'application/cbor',\n ...(this.#credentials ? { Authorization: 'Basic ' + btoa(this.#credentials) } : {}),\n },\n },\n endpoint: Endpoint.Call,\n body: submit,\n })) as HttpAgentSubmitRequest;\n\n const nonce: Nonce | undefined = transformedRequest.body.nonce\n ? toNonce(transformedRequest.body.nonce)\n : undefined;\n\n submit.nonce = nonce;\n\n function toNonce(buf: ArrayBuffer): Nonce {\n return new Uint8Array(buf) as Nonce;\n }\n\n // Apply transform for identity.\n transformedRequest = await id.transformRequest(transformedRequest);\n\n const body = cbor.encode(transformedRequest.body);\n\n this.log.print(\n `fetching \"/api/v2/canister/${ecid.toText()}/call\" with request:`,\n transformedRequest,\n );\n\n // Run both in parallel. The fetch is quite expensive, so we have plenty of time to\n // calculate the requestId locally.\n const backoff = this.#backoffStrategy();\n const request = this.#requestAndRetry({\n request: () =>\n this.#fetch('' + new URL(`/api/v2/canister/${ecid.toText()}/call`, this.host), {\n ...this.#callOptions,\n ...transformedRequest.request,\n body,\n }),\n backoff,\n tries: 0,\n });\n\n const [response, requestId] = await Promise.all([request, requestIdOf(submit)]);\n\n const responseBuffer = await response.arrayBuffer();\n const responseBody = (\n response.status === 200 && responseBuffer.byteLength > 0 ? cbor.decode(responseBuffer) : null\n ) as SubmitResponse['response']['body'];\n\n return {\n requestId,\n response: {\n ok: response.ok,\n status: response.status,\n statusText: response.statusText,\n body: responseBody,\n headers: httpHeadersTransform(response.headers),\n },\n requestDetails: submit,\n };\n }\n\n async #requestAndRetryQuery(args: {\n ecid: Principal;\n transformedRequest: HttpAgentRequest;\n body: ArrayBuffer;\n requestId: RequestId;\n backoff: BackoffStrategy;\n tries: number;\n }): Promise<ApiQueryResponse> {\n const { ecid, transformedRequest, body, requestId, backoff, tries } = args;\n\n const delay = tries === 0 ? 0 : backoff.next();\n this.log.print(`fetching \"/api/v2/canister/${ecid.toString()}/query\" with tries:`, {\n tries,\n backoff,\n delay,\n });\n\n // If delay is null, the backoff strategy is exhausted due to a maximum number of retries, duration, or other reason\n if (delay === null) {\n throw new AgentError(\n `Timestamp failed to pass the watermark after retrying the configured ${\n this.#retryTimes\n } times. We cannot guarantee the integrity of the response since it could be a replay attack.`,\n );\n }\n\n if (delay > 0) {\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n let response: ApiQueryResponse;\n // Make the request and retry if it throws an error\n try {\n this.log.print(\n `fetching \"/api/v2/canister/${ecid.toString()}/query\" with request:`,\n transformedRequest,\n );\n const fetchResponse = await this.#fetch(\n '' + new URL(`/api/v2/canister/${ecid.toString()}/query`, this.host),\n {\n ...this.#fetchOptions,\n ...transformedRequest.request,\n body,\n },\n );\n if (fetchResponse.status === 200) {\n const queryResponse: QueryResponse = cbor.decode(await fetchResponse.arrayBuffer());\n response = {\n ...queryResponse,\n httpDetails: {\n ok: fetchResponse.ok,\n status: fetchResponse.status,\n statusText: fetchResponse.statusText,\n headers: httpHeadersTransform(fetchResponse.headers),\n },\n requestId,\n };\n } else {\n throw new AgentHTTPResponseError(\n `Gateway returned an error:\\n` +\n ` Code: ${fetchResponse.status} (${fetchResponse.statusText})\\n` +\n ` Body: ${await fetchResponse.text()}\\n`,\n {\n ok: fetchResponse.ok,\n status: fetchResponse.status,\n statusText: fetchResponse.statusText,\n headers: httpHeadersTransform(fetchResponse.headers),\n },\n );\n }\n } catch (error) {\n if (tries < this.#retryTimes) {\n this.log.warn(\n `Caught exception while attempting to make query:\\n` +\n ` ${error}\\n` +\n ` Retrying query.`,\n );\n return await this.#requestAndRetryQuery({ ...args, tries: tries + 1 });\n }\n throw error;\n }\n\n const timestamp = response.signatures?.[0]?.timestamp;\n\n // Skip watermark verification if the user has set verifyQuerySignatures to false\n if (!this.#verifyQuerySignatures) {\n return response;\n }\n\n if (!timestamp) {\n throw new Error(\n 'Timestamp not found in query response. This suggests a malformed or malicious response.',\n );\n }\n\n // Convert the timestamp to milliseconds\n const timeStampInMs = Number(BigInt(timestamp) / BigInt(1_000_000));\n\n this.log.print('watermark and timestamp', {\n waterMark: this.waterMark,\n timestamp: timeStampInMs,\n });\n\n // If the timestamp is less than the watermark, retry the request up to the retry limit\n if (Number(this.waterMark) > timeStampInMs) {\n const error = new AgentError('Timestamp is below the watermark. Retrying query.');\n this.log.error('Timestamp is below', error, {\n timestamp,\n waterMark: this.waterMark,\n });\n if (tries < this.#retryTimes) {\n return await this.#requestAndRetryQuery({ ...args, tries: tries + 1 });\n }\n {\n throw new AgentError(\n `Timestamp failed to pass the watermark after retrying the configured ${\n this.#retryTimes\n } times. We cannot guarantee the integrity of the response since it could be a replay attack.`,\n );\n }\n }\n\n return response;\n }\n\n async #requestAndRetry(args: {\n request: () => Promise<Response>;\n backoff: BackoffStrategy;\n tries: number;\n }): Promise<Response> {\n const { request, backoff, tries } = args;\n const delay = tries === 0 ? 0 : backoff.next();\n\n // If delay is null, the backoff strategy is exhausted due to a maximum number of retries, duration, or other reason\n if (delay === null) {\n throw new AgentError(\n `Timestamp failed to pass the watermark after retrying the configured ${\n this.#retryTimes\n } times. We cannot guarantee the integrity of the response since it could be a replay attack.`,\n );\n }\n\n if (delay > 0) {\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n\n let response: Response;\n try {\n response = await request();\n } catch (error) {\n if (this.#retryTimes > tries) {\n this.log.warn(\n `Caught exception while attempting to make request:\\n` +\n ` ${error}\\n` +\n ` Retrying request.`,\n );\n // Delay the request by the configured backoff strategy\n return await this.#requestAndRetry({ request, backoff, tries: tries + 1 });\n }\n throw error;\n }\n if (response.ok) {\n return response;\n }\n\n const responseText = await response.clone().text();\n const errorMessage =\n `Server returned an error:\\n` +\n ` Code: ${response.status} (${response.statusText})\\n` +\n ` Body: ${responseText}\\n`;\n\n if (tries < this.#retryTimes) {\n return await this.#requestAndRetry({ request, backoff, tries: tries + 1 });\n }\n throw new AgentHTTPResponseError(errorMessage, {\n ok: response.ok,\n status: response.status,\n statusText: response.statusText,\n headers: httpHeadersTransform(response.headers),\n });\n }\n\n public async query(\n canisterId: Principal | string,\n fields: QueryFields,\n identity?: Identity | Promise<Identity>,\n ): Promise<ApiQueryResponse> {\n const backoff = this.#backoffStrategy();\n const ecid = fields.effectiveCanisterId\n ? Principal.from(fields.effectiveCanisterId)\n : Principal.from(canisterId);\n\n this.log.print(`ecid ${ecid.toString()}`);\n this.log.print(`canisterId ${canisterId.toString()}`);\n const makeQuery = async () => {\n const id = await (identity !== undefined ? await identity : await this.#identity);\n if (!id) {\n throw new IdentityInvalidError(\n \"This identity has expired due this application's security policy. Please refresh your authentication.\",\n );\n }\n\n const canister = Principal.from(canisterId);\n const sender = id?.getPrincipal() || Principal.anonymous();\n\n const request: QueryRequest = {\n request_type: ReadRequestType.Query,\n canister_id: canister,\n method_name: fields.methodName,\n arg: fields.arg,\n sender,\n ingress_expiry: new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS),\n };\n\n const requestId = await requestIdOf(request);\n\n // TODO: remove this any. This can be a Signed or UnSigned request.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let transformedRequest: HttpAgentRequest = await this._transform({\n request: {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/cbor',\n ...(this.#credentials ? { Authorization: 'Basic ' + btoa(this.#credentials) } : {}),\n },\n },\n endpoint: Endpoint.Query,\n body: request,\n });\n\n // Apply transform for identity.\n transformedRequest = (await id?.transformRequest(transformedRequest)) as HttpAgentRequest;\n\n const body = cbor.encode(transformedRequest.body);\n\n const args = {\n canister: canister.toText(),\n ecid,\n transformedRequest,\n body,\n requestId,\n backoff,\n tries: 0,\n };\n\n return {\n requestDetails: request,\n query: await this.#requestAndRetryQuery(args),\n };\n };\n\n const getSubnetStatus = async (): Promise<SubnetStatus | void> => {\n if (!this.#verifyQuerySignatures) {\n return undefined;\n }\n const subnetStatus = this.#subnetKeys.get(ecid.toString());\n if (subnetStatus) {\n return subnetStatus;\n }\n await this.fetchSubnetKeys(ecid.toString());\n return this.#subnetKeys.get(ecid.toString());\n };\n // Attempt to make the query i=retryTimes times\n // Make query and fetch subnet keys in parallel\n const [queryResult, subnetStatus] = await Promise.all([makeQuery(), getSubnetStatus()]);\n const { requestDetails, query } = queryResult;\n\n const queryWithDetails = {\n ...query,\n requestDetails,\n };\n\n this.log.print('Query response:', queryWithDetails);\n // Skip verification if the user has disabled it\n if (!this.#verifyQuerySignatures) {\n return queryWithDetails;\n }\n\n try {\n return this.#verifyQueryResponse(queryWithDetails, subnetStatus);\n } catch (_) {\n // In case the node signatures have changed, refresh the subnet keys and try again\n this.log.warn('Query response verification failed. Retrying with fresh subnet keys.');\n this.#subnetKeys.delete(canisterId.toString());\n await this.fetchSubnetKeys(ecid.toString());\n\n const updatedSubnetStatus = this.#subnetKeys.get(canisterId.toString());\n if (!updatedSubnetStatus) {\n throw new CertificateVerificationError(\n 'Invalid signature from replica signed query: no matching node key found.',\n );\n }\n return this.#verifyQueryResponse(queryWithDetails, updatedSubnetStatus);\n }\n }\n\n /**\n * See https://internetcomputer.org/docs/current/references/ic-interface-spec/#http-query for details on validation\n * @param queryResponse - The response from the query\n * @param subnetStatus - The subnet status, including all node keys\n * @returns ApiQueryResponse\n */\n #verifyQueryResponse = (\n queryResponse: ApiQueryResponse,\n subnetStatus: SubnetStatus | void,\n ): ApiQueryResponse => {\n if (this.#verifyQuerySignatures === false) {\n // This should not be called if the user has disabled verification\n return queryResponse;\n }\n if (!subnetStatus) {\n throw new CertificateVerificationError(\n 'Invalid signature from replica signed query: no matching node key found.',\n );\n }\n const { status, signatures = [], requestId } = queryResponse;\n\n const domainSeparator = new TextEncoder().encode('\\x0Bic-response');\n for (const sig of signatures) {\n const { timestamp, identity } = sig;\n const nodeId = Principal.fromUint8Array(identity).toText();\n let hash: ArrayBuffer;\n\n // Hash is constructed differently depending on the status\n if (status === 'replied') {\n const { reply } = queryResponse;\n hash = hashOfMap({\n status: status,\n reply: reply,\n timestamp: BigInt(timestamp),\n request_id: requestId,\n });\n } else if (status === 'rejected') {\n const { reject_code, reject_message, error_code } = queryResponse;\n hash = hashOfMap({\n status: status,\n reject_code: reject_code,\n reject_message: reject_message,\n error_code: error_code,\n timestamp: BigInt(timestamp),\n request_id: requestId,\n });\n } else {\n throw new Error(`Unknown status: ${status}`);\n }\n\n const separatorWithHash = concat(domainSeparator, new Uint8Array(hash));\n\n // FIX: check for match without verifying N times\n const pubKey = subnetStatus?.nodeKeys.get(nodeId);\n if (!pubKey) {\n throw new CertificateVerificationError(\n 'Invalid signature from replica signed query: no matching node key found.',\n );\n }\n const rawKey = Ed25519PublicKey.fromDer(pubKey).rawKey;\n const valid = ed25519.verify(\n sig.signature,\n new Uint8Array(separatorWithHash),\n new Uint8Array(rawKey),\n );\n if (valid) return queryResponse;\n\n throw new CertificateVerificationError(\n `Invalid signature from replica ${nodeId} signed query.`,\n );\n }\n return queryResponse;\n };\n\n public async createReadStateRequest(\n fields: ReadStateOptions,\n identity?: Identity | Promise<Identity>,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any> {\n const id = await (identity !== undefined ? await identity : await this.#identity);\n if (!id) {\n throw new IdentityInvalidError(\n \"This identity has expired due this application's security policy. Please refresh your authentication.\",\n );\n }\n const sender = id?.getPrincipal() || Principal.anonymous();\n\n // TODO: remove this any. This can be a Signed or UnSigned request.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const transformedRequest: any = await this._transform({\n request: {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/cbor',\n ...(this.#credentials ? { Authorization: 'Basic ' + btoa(this.#credentials) } : {}),\n },\n },\n endpoint: Endpoint.ReadState,\n body: {\n request_type: ReadRequestType.ReadState,\n paths: fields.paths,\n sender,\n ingress_expiry: new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS),\n },\n });\n\n // Apply transform for identity.\n return id?.transformRequest(transformedRequest);\n }\n\n public async readState(\n canisterId: Principal | string,\n fields: ReadStateOptions,\n identity?: Identity | Promise<Identity>,\n // eslint-disable-next-line\n request?: any,\n ): Promise<ReadStateResponse> {\n const canister = typeof canisterId === 'string' ? Principal.fromText(canisterId) : canisterId;\n\n const transformedRequest = request ?? (await this.createReadStateRequest(fields, identity));\n const body = cbor.encode(transformedRequest.body);\n\n this.log.print(\n `fetching \"/api/v2/canister/${canister}/read_state\" with request:`,\n transformedRequest,\n );\n // TODO - https://dfinity.atlassian.net/browse/SDK-1092\n const backoff = this.#backoffStrategy();\n\n const response = await this.#requestAndRetry({\n request: () =>\n this.#fetch('' + new URL(`/api/v2/canister/${canister.toString()}/read_state`, this.host), {\n ...this.#fetchOptions,\n ...transformedRequest.request,\n body,\n }),\n backoff,\n tries: 0,\n });\n\n if (!response.ok) {\n throw new Error(\n `Server returned an error:\\n` +\n ` Code: ${response.status} (${response.statusText})\\n` +\n ` Body: ${await response.text()}\\n`,\n );\n }\n const decodedResponse: ReadStateResponse = cbor.decode(await response.arrayBuffer());\n\n this.log.print('Read state response:', decodedResponse);\n const parsedTime = await this.parseTimeFromResponse(decodedResponse);\n if (parsedTime > 0) {\n this.log.print('Read state response time:', parsedTime);\n this.#waterMark = parsedTime;\n }\n\n return decodedResponse;\n }\n\n public async parseTimeFromResponse(response: ReadStateResponse): Promise<number> {\n let tree: HashTree;\n if (response.certificate) {\n const decoded: { tree: HashTree } | undefined = cbor.decode(response.certificate);\n if (decoded && 'tree' in decoded) {\n tree = decoded.tree;\n } else {\n throw new Error('Could not decode time from response');\n }\n const timeLookup = lookup_path(['time'], tree);\n if (timeLookup.status !== LookupStatus.Found) {\n throw new Error('Time was not found in the response or was not in its expected format.');\n }\n\n if (!(timeLookup.value instanceof ArrayBuffer) && !ArrayBuffer.isView(timeLookup)) {\n throw new Error('Time was not found in the response or was not in its expected format.');\n }\n const date = decodeTime(bufFromBufLike(timeLookup.value as ArrayBuffer));\n this.log.print('Time from response:', date);\n this.log.print('Time from response in milliseconds:', Number(date));\n return Number(date);\n } else {\n this.log.warn('No certificate found in response');\n }\n return 0;\n }\n\n /**\n * Allows agent to sync its time with the network. Can be called during intialization or mid-lifecycle if the device's clock has drifted away from the network time. This is necessary to set the Expiry for a request\n * @param {Principal} canisterId - Pass a canister ID if you need to sync the time with a particular replica. Uses the management canister by default\n */\n public async syncTime(canisterId?: Principal): Promise<void> {\n const CanisterStatus = await import('../../canisterStatus');\n const callTime = Date.now();\n try {\n if (!canisterId) {\n this.log.print(\n 'Syncing time with the IC. No canisterId provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai',\n );\n }\n const status = await CanisterStatus.request({\n // Fall back with canisterId of the ICP Ledger\n canisterId: canisterId ?? Principal.from('ryjl3-tyaaa-aaaaa-aaaba-cai'),\n agent: this,\n paths: ['time'],\n });\n\n const replicaTime = status.get('time');\n if (replicaTime) {\n this.#timeDiffMsecs = Number(replicaTime as bigint) - Number(callTime);\n }\n } catch (error) {\n this.log.error('Caught exception while attempting to sync time', error as AgentError);\n }\n }\n\n public async status(): Promise<JsonObject> {\n const headers: Record<string, string> = this.#credentials\n ? {\n Authorization: 'Basic ' + btoa(this.#credentials),\n }\n : {};\n\n this.log.print(`fetching \"/api/v2/status\"`);\n const backoff = this.#backoffStrategy();\n const response = await this.#requestAndRetry({\n backoff,\n request: () =>\n this.#fetch('' + new URL(`/api/v2/status`, this.host), { headers, ...this.#fetchOptions }),\n tries: 0,\n });\n return cbor.decode(await response.arrayBuffer());\n }\n\n public async fetchRootKey(): Promise<ArrayBuffer> {\n if (!this.#rootKeyFetched) {\n // Hex-encoded version of the replica root key\n this.rootKey = ((await this.status()) as JsonObject & { root_key: ArrayBuffer }).root_key;\n this.#rootKeyFetched = true;\n }\n return this.rootKey;\n }\n\n public invalidateIdentity(): void {\n this.#identity = null;\n }\n\n public replaceIdentity(identity: Identity): void {\n this.#identity = Promise.resolve(identity);\n }\n\n public async fetchSubnetKeys(canisterId: Principal | string) {\n const effectiveCanisterId: Principal = Principal.from(canisterId);\n const response = await request({\n canisterId: effectiveCanisterId,\n paths: ['subnet'],\n agent: this,\n });\n\n const subnetResponse = response.get('subnet');\n if (subnetResponse && typeof subnetResponse === 'object' && 'nodeKeys' in subnetResponse) {\n this.#subnetKeys.set(effectiveCanisterId.toText(), subnetResponse as SubnetStatus);\n return subnetResponse as SubnetStatus;\n }\n // If the subnet status is not returned, return undefined\n return undefined;\n }\n\n protected _transform(request: HttpAgentRequest): Promise<HttpAgentRequest> {\n let p = Promise.resolve(request);\n if (request.endpoint === Endpoint.Call) {\n for (const fn of this.#updatePipeline) {\n p = p.then(r => fn(r).then(r2 => r2 || r));\n }\n } else {\n for (const fn of this.#queryPipeline) {\n p = p.then(r => fn(r).then(r2 => r2 || r));\n }\n }\n\n return p;\n }\n}\n\n", "import { JsonObject } from '@dfinity/candid';\nimport {\n Agent,\n ApiQueryResponse,\n CallOptions,\n QueryFields,\n QueryResponse,\n ReadStateOptions,\n ReadStateResponse,\n SubmitResponse,\n} from './api';\nimport { Principal } from '@dfinity/principal';\n\nexport enum ProxyMessageKind {\n Error = 'err',\n GetPrincipal = 'gp',\n GetPrincipalResponse = 'gpr',\n Query = 'q',\n QueryResponse = 'qr',\n Call = 'c',\n CallResponse = 'cr',\n ReadState = 'rs',\n ReadStateResponse = 'rsr',\n Status = 's',\n StatusResponse = 'sr',\n}\n\nexport interface ProxyMessageBase {\n id: number;\n type: ProxyMessageKind;\n}\n\nexport interface ProxyMessageError extends ProxyMessageBase {\n type: ProxyMessageKind.Error;\n error: any;\n}\n\nexport interface ProxyMessageGetPrincipal extends ProxyMessageBase {\n type: ProxyMessageKind.GetPrincipal;\n}\n\nexport interface ProxyMessageGetPrincipalResponse extends ProxyMessageBase {\n type: ProxyMessageKind.GetPrincipalResponse;\n response: string;\n}\n\nexport interface ProxyMessageQuery extends ProxyMessageBase {\n type: ProxyMessageKind.Query;\n args: [string, QueryFields];\n}\n\nexport interface ProxyMessageQueryResponse extends ProxyMessageBase {\n type: ProxyMessageKind.QueryResponse;\n response: QueryResponse;\n}\n\nexport interface ProxyMessageCall extends ProxyMessageBase {\n type: ProxyMessageKind.Call;\n args: [string, CallOptions];\n}\n\nexport interface ProxyMessageCallResponse extends ProxyMessageBase {\n type: ProxyMessageKind.CallResponse;\n response: SubmitResponse;\n}\n\nexport interface ProxyMessageReadState extends ProxyMessageBase {\n type: ProxyMessageKind.ReadState;\n args: [string, ReadStateOptions];\n}\n\nexport interface ProxyMessageReadStateResponse extends ProxyMessageBase {\n type: ProxyMessageKind.ReadStateResponse;\n response: ReadStateResponse;\n}\n\nexport interface ProxyMessageStatus extends ProxyMessageBase {\n type: ProxyMessageKind.Status;\n}\n\nexport interface ProxyMessageStatusResponse extends ProxyMessageBase {\n type: ProxyMessageKind.StatusResponse;\n response: JsonObject;\n}\n\nexport type ProxyMessage =\n | ProxyMessageError\n | ProxyMessageGetPrincipal\n | ProxyMessageGetPrincipalResponse\n | ProxyMessageQuery\n | ProxyMessageQueryResponse\n | ProxyMessageCall\n | ProxyMessageReadState\n | ProxyMessageReadStateResponse\n | ProxyMessageCallResponse\n | ProxyMessageStatus\n | ProxyMessageStatusResponse;\n\n// A Stub Agent that forwards calls to another Agent implementation.\nexport class ProxyStubAgent {\n constructor(private _frontend: (msg: ProxyMessage) => void, private _agent: Agent) {}\n\n public onmessage(msg: ProxyMessage): void {\n switch (msg.type) {\n case ProxyMessageKind.GetPrincipal:\n this._agent.getPrincipal().then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.GetPrincipalResponse,\n response: response.toText(),\n });\n });\n break;\n case ProxyMessageKind.Query:\n this._agent.query(...msg.args).then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.QueryResponse,\n response,\n });\n });\n break;\n case ProxyMessageKind.Call:\n this._agent.call(...msg.args).then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.CallResponse,\n response,\n });\n });\n break;\n case ProxyMessageKind.ReadState:\n this._agent.readState(...msg.args).then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.ReadStateResponse,\n response,\n });\n });\n break;\n case ProxyMessageKind.Status:\n this._agent.status().then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.StatusResponse,\n response,\n });\n });\n break;\n\n default:\n throw new Error(`Invalid message received: ${JSON.stringify(msg)}`);\n }\n }\n}\n\n// An Agent that forwards calls to a backend. The calls are serialized\nexport class ProxyAgent implements Agent {\n private _nextId = 0;\n private _pendingCalls = new Map<number, [(resolve: any) => void, (reject: any) => void]>();\n public rootKey = null;\n\n constructor(private _backend: (msg: ProxyMessage) => void) {}\n\n public onmessage(msg: ProxyMessage): void {\n const id = msg.id;\n\n const maybePromise = this._pendingCalls.get(id);\n if (!maybePromise) {\n throw new Error('A proxy get the same message twice...');\n }\n\n this._pendingCalls.delete(id);\n const [resolve, reject] = maybePromise;\n\n switch (msg.type) {\n case ProxyMessageKind.Error:\n return reject(msg.error);\n case ProxyMessageKind.GetPrincipalResponse:\n case ProxyMessageKind.CallResponse:\n case ProxyMessageKind.QueryResponse:\n case ProxyMessageKind.ReadStateResponse:\n case ProxyMessageKind.StatusResponse:\n return resolve(msg.response);\n default:\n throw new Error(`Invalid message being sent to ProxyAgent: ${JSON.stringify(msg)}`);\n }\n }\n\n public async getPrincipal(): Promise<Principal> {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.GetPrincipal,\n }).then(principal => {\n if (typeof principal !== 'string') {\n throw new Error('Invalid principal received.');\n }\n return Principal.fromText(principal);\n });\n }\n\n public readState(\n canisterId: Principal | string,\n fields: ReadStateOptions,\n ): Promise<ReadStateResponse> {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.ReadState,\n args: [canisterId.toString(), fields],\n }) as Promise<ReadStateResponse>;\n }\n\n public call(canisterId: Principal | string, fields: CallOptions): Promise<SubmitResponse> {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.Call,\n args: [canisterId.toString(), fields],\n }) as Promise<SubmitResponse>;\n }\n\n public status(): Promise<JsonObject> {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.Status,\n }) as Promise<JsonObject>;\n }\n\n public query(canisterId: Principal | string, fields: QueryFields): Promise<ApiQueryResponse> {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.Query,\n args: [canisterId.toString(), fields],\n }) as Promise<ApiQueryResponse>;\n }\n\n private async _sendAndWait(msg: ProxyMessage): Promise<unknown> {\n return new Promise((resolve, reject) => {\n this._pendingCalls.set(msg.id, [resolve, reject]);\n\n this._backend(msg);\n });\n }\n\n public async fetchRootKey(): Promise<ArrayBuffer> {\n // Hex-encoded version of the replica root key\n const rootKey = ((await this.status()) as any).root_key;\n this.rootKey = rootKey;\n return rootKey;\n }\n}\n", "import { GlobalInternetComputer } from '../index';\nimport { Agent } from './api';\n\nexport * from './api';\nexport * from './http';\nexport * from './http/errors';\nexport * from './proxy';\n\ndeclare const window: GlobalInternetComputer;\ndeclare const global: GlobalInternetComputer;\ndeclare const self: GlobalInternetComputer;\n\nexport function getDefaultAgent(): Agent {\n const agent =\n typeof window === 'undefined'\n ? typeof global === 'undefined'\n ? typeof self === 'undefined'\n ? undefined\n : self.ic.agent\n : global.ic.agent\n : window.ic.agent;\n\n if (!agent) {\n throw new Error('No Agent could be found.');\n }\n\n return agent;\n}\n", "import { Principal } from '@dfinity/principal';\nimport { RequestStatusResponseStatus } from '../agent';\nimport { toHex } from '../utils/buffer';\nimport { PollStrategy } from './index';\nimport { RequestId } from '../request_id';\n\nexport type Predicate<T> = (\n canisterId: Principal,\n requestId: RequestId,\n status: RequestStatusResponseStatus,\n) => Promise<T>;\n\nconst FIVE_MINUTES_IN_MSEC = 5 * 60 * 1000;\n\n/**\n * A best practices polling strategy: wait 2 seconds before the first poll, then 1 second\n * with an exponential backoff factor of 1.2. Timeout after 5 minutes.\n */\nexport function defaultStrategy(): PollStrategy {\n return chain(conditionalDelay(once(), 1000), backoff(1000, 1.2), timeout(FIVE_MINUTES_IN_MSEC));\n}\n\n/**\n * Predicate that returns true once.\n */\nexport function once(): Predicate<boolean> {\n let first = true;\n return async () => {\n if (first) {\n first = false;\n return true;\n }\n return false;\n };\n}\n\n/**\n * Delay the polling once.\n * @param condition A predicate that indicates when to delay.\n * @param timeInMsec The amount of time to delay.\n */\nexport function conditionalDelay(condition: Predicate<boolean>, timeInMsec: number): PollStrategy {\n return async (\n canisterId: Principal,\n requestId: RequestId,\n status: RequestStatusResponseStatus,\n ) => {\n if (await condition(canisterId, requestId, status)) {\n return new Promise(resolve => setTimeout(resolve, timeInMsec));\n }\n };\n}\n\n/**\n * Error out after a maximum number of polling has been done.\n * @param count The maximum attempts to poll.\n */\nexport function maxAttempts(count: number): PollStrategy {\n let attempts = count;\n return async (\n canisterId: Principal,\n requestId: RequestId,\n status: RequestStatusResponseStatus,\n ) => {\n if (--attempts <= 0) {\n throw new Error(\n `Failed to retrieve a reply for request after ${count} attempts:\\n` +\n ` Request ID: ${toHex(requestId)}\\n` +\n ` Request status: ${status}\\n`,\n );\n }\n };\n}\n\n/**\n * Throttle polling.\n * @param throttleInMsec Amount in millisecond to wait between each polling.\n */\nexport function throttle(throttleInMsec: number): PollStrategy {\n return () => new Promise(resolve => setTimeout(resolve, throttleInMsec));\n}\n\n/**\n * Reject a call after a certain amount of time.\n * @param timeInMsec Time in milliseconds before the polling should be rejected.\n */\nexport function timeout(timeInMsec: number): PollStrategy {\n const end = Date.now() + timeInMsec;\n return async (\n canisterId: Principal,\n requestId: RequestId,\n status: RequestStatusResponseStatus,\n ) => {\n if (Date.now() > end) {\n throw new Error(\n `Request timed out after ${timeInMsec} msec:\\n` +\n ` Request ID: ${toHex(requestId)}\\n` +\n ` Request status: ${status}\\n`,\n );\n }\n };\n}\n\n/**\n * A strategy that throttle, but using an exponential backoff strategy.\n * @param startingThrottleInMsec The throttle in milliseconds to start with.\n * @param backoffFactor The factor to multiple the throttle time between every poll. For\n * example if using 2, the throttle will double between every run.\n */\nexport function backoff(startingThrottleInMsec: number, backoffFactor: number): PollStrategy {\n let currentThrottling = startingThrottleInMsec;\n\n return () =>\n new Promise(resolve =>\n setTimeout(() => {\n currentThrottling *= backoffFactor;\n resolve();\n }, currentThrottling),\n );\n}\n\n/**\n * Chain multiple polling strategy. This _chains_ the strategies, so if you pass in,\n * say, two throttling strategy of 1 second, it will result in a throttle of 2 seconds.\n * @param strategies A strategy list to chain.\n */\nexport function chain(...strategies: PollStrategy[]): PollStrategy {\n return async (\n canisterId: Principal,\n requestId: RequestId,\n status: RequestStatusResponseStatus,\n ) => {\n for (const a of strategies) {\n await a(canisterId, requestId, status);\n }\n };\n}\n", "import { Principal } from '@dfinity/principal';\nimport { Agent, RequestStatusResponseStatus } from '../agent';\nimport { Certificate, CreateCertificateOptions, lookupResultToBuffer } from '../certificate';\nimport { RequestId } from '../request_id';\nimport { toHex } from '../utils/buffer';\n\nexport * as strategy from './strategy';\nexport { defaultStrategy } from './strategy';\nexport type PollStrategy = (\n canisterId: Principal,\n requestId: RequestId,\n status: RequestStatusResponseStatus,\n) => Promise<void>;\nexport type PollStrategyFactory = () => PollStrategy;\n\n/**\n * Polls the IC to check the status of the given request then\n * returns the response bytes once the request has been processed.\n * @param agent The agent to use to poll read_state.\n * @param canisterId The effective canister ID.\n * @param requestId The Request ID to poll status for.\n * @param strategy A polling strategy.\n * @param request Request for the readState call.\n * @param blsVerify - optional replacement function that verifies the BLS signature of a certificate.\n */\nexport async function pollForResponse(\n agent: Agent,\n canisterId: Principal,\n requestId: RequestId,\n strategy: PollStrategy,\n // eslint-disable-next-line\n request?: any,\n blsVerify?: CreateCertificateOptions['blsVerify'],\n): Promise<{\n certificate: Certificate;\n reply: ArrayBuffer;\n}> {\n const path = [new TextEncoder().encode('request_status'), requestId];\n const currentRequest = request ?? (await agent.createReadStateRequest?.({ paths: [path] }));\n const state = await agent.readState(canisterId, { paths: [path] }, undefined, currentRequest);\n if (agent.rootKey == null) throw new Error('Agent root key not initialized before polling');\n const cert = await Certificate.create({\n certificate: state.certificate,\n rootKey: agent.rootKey,\n canisterId: canisterId,\n blsVerify,\n });\n\n const maybeBuf = lookupResultToBuffer(cert.lookup([...path, new TextEncoder().encode('status')]));\n let status;\n if (typeof maybeBuf === 'undefined') {\n // Missing requestId means we need to wait\n status = RequestStatusResponseStatus.Unknown;\n } else {\n status = new TextDecoder().decode(maybeBuf);\n }\n\n switch (status) {\n case RequestStatusResponseStatus.Replied: {\n return {\n reply: lookupResultToBuffer(cert.lookup([...path, 'reply']))!,\n certificate: cert,\n };\n }\n\n case RequestStatusResponseStatus.Received:\n case RequestStatusResponseStatus.Unknown:\n case RequestStatusResponseStatus.Processing:\n // Execute the polling strategy, then retry.\n await strategy(canisterId, requestId, status);\n return pollForResponse(agent, canisterId, requestId, strategy, currentRequest);\n\n case RequestStatusResponseStatus.Rejected: {\n const rejectCode = new Uint8Array(\n lookupResultToBuffer(cert.lookup([...path, 'reject_code']))!,\n )[0];\n const rejectMessage = new TextDecoder().decode(\n lookupResultToBuffer(cert.lookup([...path, 'reject_message']))!,\n );\n throw new Error(\n `Call was rejected:\\n` +\n ` Request ID: ${toHex(requestId)}\\n` +\n ` Reject code: ${rejectCode}\\n` +\n ` Reject text: ${rejectMessage}\\n`,\n );\n }\n\n case RequestStatusResponseStatus.Done:\n // This is _technically_ not an error, but we still didn't see the `Replied` status so\n // we don't know the result and cannot decode it.\n throw new Error(\n `Call was marked as done but we never saw the reply:\\n` +\n ` Request ID: ${toHex(requestId)}\\n`,\n );\n }\n throw new Error('unreachable');\n}\n", "/*\n * This file is generated from the candid for asset management.\n * didc version: 0.4.0\n */\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\n\nexport default ({ IDL }) => {\n const bitcoin_network = IDL.Variant({\n mainnet: IDL.Null,\n testnet: IDL.Null,\n });\n const bitcoin_address = IDL.Text;\n const bitcoin_get_balance_args = IDL.Record({\n network: bitcoin_network,\n address: bitcoin_address,\n min_confirmations: IDL.Opt(IDL.Nat32),\n });\n const satoshi = IDL.Nat64;\n const bitcoin_get_balance_result = satoshi;\n const bitcoin_get_current_fee_percentiles_args = IDL.Record({\n network: bitcoin_network,\n });\n const millisatoshi_per_byte = IDL.Nat64;\n const bitcoin_get_current_fee_percentiles_result = IDL.Vec(millisatoshi_per_byte);\n const bitcoin_get_utxos_args = IDL.Record({\n network: bitcoin_network,\n filter: IDL.Opt(\n IDL.Variant({\n page: IDL.Vec(IDL.Nat8),\n min_confirmations: IDL.Nat32,\n }),\n ),\n address: bitcoin_address,\n });\n const block_hash = IDL.Vec(IDL.Nat8);\n const outpoint = IDL.Record({\n txid: IDL.Vec(IDL.Nat8),\n vout: IDL.Nat32,\n });\n const utxo = IDL.Record({\n height: IDL.Nat32,\n value: satoshi,\n outpoint: outpoint,\n });\n const bitcoin_get_utxos_result = IDL.Record({\n next_page: IDL.Opt(IDL.Vec(IDL.Nat8)),\n tip_height: IDL.Nat32,\n tip_block_hash: block_hash,\n utxos: IDL.Vec(utxo),\n });\n const bitcoin_send_transaction_args = IDL.Record({\n transaction: IDL.Vec(IDL.Nat8),\n network: bitcoin_network,\n });\n const canister_id = IDL.Principal;\n const canister_info_args = IDL.Record({\n canister_id: canister_id,\n num_requested_changes: IDL.Opt(IDL.Nat64),\n });\n const change_origin = IDL.Variant({\n from_user: IDL.Record({ user_id: IDL.Principal }),\n from_canister: IDL.Record({\n canister_version: IDL.Opt(IDL.Nat64),\n canister_id: IDL.Principal,\n }),\n });\n const change_details = IDL.Variant({\n creation: IDL.Record({ controllers: IDL.Vec(IDL.Principal) }),\n code_deployment: IDL.Record({\n mode: IDL.Variant({\n reinstall: IDL.Null,\n upgrade: IDL.Null,\n install: IDL.Null,\n }),\n module_hash: IDL.Vec(IDL.Nat8),\n }),\n controllers_change: IDL.Record({\n controllers: IDL.Vec(IDL.Principal),\n }),\n code_uninstall: IDL.Null,\n });\n const change = IDL.Record({\n timestamp_nanos: IDL.Nat64,\n canister_version: IDL.Nat64,\n origin: change_origin,\n details: change_details,\n });\n const canister_info_result = IDL.Record({\n controllers: IDL.Vec(IDL.Principal),\n module_hash: IDL.Opt(IDL.Vec(IDL.Nat8)),\n recent_changes: IDL.Vec(change),\n total_num_changes: IDL.Nat64,\n });\n const canister_status_args = IDL.Record({ canister_id: canister_id });\n const log_visibility = IDL.Variant({\n controllers: IDL.Null,\n public: IDL.Null,\n });\n const definite_canister_settings = IDL.Record({\n freezing_threshold: IDL.Nat,\n controllers: IDL.Vec(IDL.Principal),\n reserved_cycles_limit: IDL.Nat,\n log_visibility: log_visibility,\n wasm_memory_limit: IDL.Nat,\n memory_allocation: IDL.Nat,\n compute_allocation: IDL.Nat,\n });\n const canister_status_result = IDL.Record({\n status: IDL.Variant({\n stopped: IDL.Null,\n stopping: IDL.Null,\n running: IDL.Null,\n }),\n memory_size: IDL.Nat,\n cycles: IDL.Nat,\n settings: definite_canister_settings,\n query_stats: IDL.Record({\n response_payload_bytes_total: IDL.Nat,\n num_instructions_total: IDL.Nat,\n num_calls_total: IDL.Nat,\n request_payload_bytes_total: IDL.Nat,\n }),\n idle_cycles_burned_per_day: IDL.Nat,\n module_hash: IDL.Opt(IDL.Vec(IDL.Nat8)),\n reserved_cycles: IDL.Nat,\n });\n const clear_chunk_store_args = IDL.Record({ canister_id: canister_id });\n const canister_settings = IDL.Record({\n freezing_threshold: IDL.Opt(IDL.Nat),\n controllers: IDL.Opt(IDL.Vec(IDL.Principal)),\n reserved_cycles_limit: IDL.Opt(IDL.Nat),\n log_visibility: IDL.Opt(log_visibility),\n wasm_memory_limit: IDL.Opt(IDL.Nat),\n memory_allocation: IDL.Opt(IDL.Nat),\n compute_allocation: IDL.Opt(IDL.Nat),\n });\n const create_canister_args = IDL.Record({\n settings: IDL.Opt(canister_settings),\n sender_canister_version: IDL.Opt(IDL.Nat64),\n });\n const create_canister_result = IDL.Record({ canister_id: canister_id });\n const delete_canister_args = IDL.Record({ canister_id: canister_id });\n const deposit_cycles_args = IDL.Record({ canister_id: canister_id });\n const ecdsa_curve = IDL.Variant({ secp256k1: IDL.Null });\n const ecdsa_public_key_args = IDL.Record({\n key_id: IDL.Record({ name: IDL.Text, curve: ecdsa_curve }),\n canister_id: IDL.Opt(canister_id),\n derivation_path: IDL.Vec(IDL.Vec(IDL.Nat8)),\n });\n const ecdsa_public_key_result = IDL.Record({\n public_key: IDL.Vec(IDL.Nat8),\n chain_code: IDL.Vec(IDL.Nat8),\n });\n const fetch_canister_logs_args = IDL.Record({ canister_id: canister_id });\n const canister_log_record = IDL.Record({\n idx: IDL.Nat64,\n timestamp_nanos: IDL.Nat64,\n content: IDL.Vec(IDL.Nat8),\n });\n const fetch_canister_logs_result = IDL.Record({\n canister_log_records: IDL.Vec(canister_log_record),\n });\n const http_header = IDL.Record({ value: IDL.Text, name: IDL.Text });\n const http_request_result = IDL.Record({\n status: IDL.Nat,\n body: IDL.Vec(IDL.Nat8),\n headers: IDL.Vec(http_header),\n });\n const http_request_args = IDL.Record({\n url: IDL.Text,\n method: IDL.Variant({\n get: IDL.Null,\n head: IDL.Null,\n post: IDL.Null,\n }),\n max_response_bytes: IDL.Opt(IDL.Nat64),\n body: IDL.Opt(IDL.Vec(IDL.Nat8)),\n transform: IDL.Opt(\n IDL.Record({\n function: IDL.Func(\n [\n IDL.Record({\n context: IDL.Vec(IDL.Nat8),\n response: http_request_result,\n }),\n ],\n [http_request_result],\n ['query'],\n ),\n context: IDL.Vec(IDL.Nat8),\n }),\n ),\n headers: IDL.Vec(http_header),\n });\n const canister_install_mode = IDL.Variant({\n reinstall: IDL.Null,\n upgrade: IDL.Opt(\n IDL.Record({\n wasm_memory_persistence: IDL.Opt(IDL.Variant({ keep: IDL.Null, replace: IDL.Null })),\n skip_pre_upgrade: IDL.Opt(IDL.Bool),\n }),\n ),\n install: IDL.Null,\n });\n const chunk_hash = IDL.Record({ hash: IDL.Vec(IDL.Nat8) });\n const install_chunked_code_args = IDL.Record({\n arg: IDL.Vec(IDL.Nat8),\n wasm_module_hash: IDL.Vec(IDL.Nat8),\n mode: canister_install_mode,\n chunk_hashes_list: IDL.Vec(chunk_hash),\n target_canister: canister_id,\n store_canister: IDL.Opt(canister_id),\n sender_canister_version: IDL.Opt(IDL.Nat64),\n });\n const wasm_module = IDL.Vec(IDL.Nat8);\n const install_code_args = IDL.Record({\n arg: IDL.Vec(IDL.Nat8),\n wasm_module: wasm_module,\n mode: canister_install_mode,\n canister_id: canister_id,\n sender_canister_version: IDL.Opt(IDL.Nat64),\n });\n const node_metrics_history_args = IDL.Record({\n start_at_timestamp_nanos: IDL.Nat64,\n subnet_id: IDL.Principal,\n });\n const node_metrics = IDL.Record({\n num_block_failures_total: IDL.Nat64,\n node_id: IDL.Principal,\n num_blocks_proposed_total: IDL.Nat64,\n });\n const node_metrics_history_result = IDL.Vec(\n IDL.Record({\n timestamp_nanos: IDL.Nat64,\n node_metrics: IDL.Vec(node_metrics),\n }),\n );\n const provisional_create_canister_with_cycles_args = IDL.Record({\n settings: IDL.Opt(canister_settings),\n specified_id: IDL.Opt(canister_id),\n amount: IDL.Opt(IDL.Nat),\n sender_canister_version: IDL.Opt(IDL.Nat64),\n });\n const provisional_create_canister_with_cycles_result = IDL.Record({\n canister_id: canister_id,\n });\n const provisional_top_up_canister_args = IDL.Record({\n canister_id: canister_id,\n amount: IDL.Nat,\n });\n const raw_rand_result = IDL.Vec(IDL.Nat8);\n const sign_with_ecdsa_args = IDL.Record({\n key_id: IDL.Record({ name: IDL.Text, curve: ecdsa_curve }),\n derivation_path: IDL.Vec(IDL.Vec(IDL.Nat8)),\n message_hash: IDL.Vec(IDL.Nat8),\n });\n const sign_with_ecdsa_result = IDL.Record({\n signature: IDL.Vec(IDL.Nat8),\n });\n const start_canister_args = IDL.Record({ canister_id: canister_id });\n const stop_canister_args = IDL.Record({ canister_id: canister_id });\n const stored_chunks_args = IDL.Record({ canister_id: canister_id });\n const stored_chunks_result = IDL.Vec(chunk_hash);\n const uninstall_code_args = IDL.Record({\n canister_id: canister_id,\n sender_canister_version: IDL.Opt(IDL.Nat64),\n });\n const update_settings_args = IDL.Record({\n canister_id: IDL.Principal,\n settings: canister_settings,\n sender_canister_version: IDL.Opt(IDL.Nat64),\n });\n const upload_chunk_args = IDL.Record({\n chunk: IDL.Vec(IDL.Nat8),\n canister_id: IDL.Principal,\n });\n const upload_chunk_result = chunk_hash;\n return IDL.Service({\n bitcoin_get_balance: IDL.Func([bitcoin_get_balance_args], [bitcoin_get_balance_result], []),\n bitcoin_get_current_fee_percentiles: IDL.Func(\n [bitcoin_get_current_fee_percentiles_args],\n [bitcoin_get_current_fee_percentiles_result],\n [],\n ),\n bitcoin_get_utxos: IDL.Func([bitcoin_get_utxos_args], [bitcoin_get_utxos_result], []),\n bitcoin_send_transaction: IDL.Func([bitcoin_send_transaction_args], [], []),\n canister_info: IDL.Func([canister_info_args], [canister_info_result], []),\n canister_status: IDL.Func([canister_status_args], [canister_status_result], []),\n clear_chunk_store: IDL.Func([clear_chunk_store_args], [], []),\n create_canister: IDL.Func([create_canister_args], [create_canister_result], []),\n delete_canister: IDL.Func([delete_canister_args], [], []),\n deposit_cycles: IDL.Func([deposit_cycles_args], [], []),\n ecdsa_public_key: IDL.Func([ecdsa_public_key_args], [ecdsa_public_key_result], []),\n fetch_canister_logs: IDL.Func(\n [fetch_canister_logs_args],\n [fetch_canister_logs_result],\n ['query'],\n ),\n http_request: IDL.Func([http_request_args], [http_request_result], []),\n install_chunked_code: IDL.Func([install_chunked_code_args], [], []),\n install_code: IDL.Func([install_code_args], [], []),\n node_metrics_history: IDL.Func([node_metrics_history_args], [node_metrics_history_result], []),\n provisional_create_canister_with_cycles: IDL.Func(\n [provisional_create_canister_with_cycles_args],\n [provisional_create_canister_with_cycles_result],\n [],\n ),\n provisional_top_up_canister: IDL.Func([provisional_top_up_canister_args], [], []),\n raw_rand: IDL.Func([], [raw_rand_result], []),\n sign_with_ecdsa: IDL.Func([sign_with_ecdsa_args], [sign_with_ecdsa_result], []),\n start_canister: IDL.Func([start_canister_args], [], []),\n stop_canister: IDL.Func([stop_canister_args], [], []),\n stored_chunks: IDL.Func([stored_chunks_args], [stored_chunks_result], []),\n uninstall_code: IDL.Func([uninstall_code_args], [], []),\n update_settings: IDL.Func([update_settings_args], [], []),\n upload_chunk: IDL.Func([upload_chunk_args], [upload_chunk_result], []),\n });\n};\n", "import { bufEquals } from '@dfinity/agent';\nimport {\n DerEncodedPublicKey,\n KeyPair,\n PublicKey,\n Signature,\n SignIdentity,\n uint8ToBuf,\n ED25519_OID,\n unwrapDER,\n wrapDER,\n fromHex,\n toHex,\n bufFromBufLike,\n} from '@dfinity/agent';\nimport { ed25519 } from '@noble/curves/ed25519';\n\ndeclare type KeyLike = PublicKey | DerEncodedPublicKey | ArrayBuffer | ArrayBufferView;\n\nfunction isObject(value: unknown) {\n return value !== null && typeof value === 'object';\n}\n\nexport class Ed25519PublicKey implements PublicKey {\n /**\n * Construct Ed25519PublicKey from an existing PublicKey\n * @param {unknown} maybeKey - existing PublicKey, ArrayBuffer, DerEncodedPublicKey, or hex string\n * @returns {Ed25519PublicKey} Instance of Ed25519PublicKey\n */\n public static from(maybeKey: unknown): Ed25519PublicKey {\n if (typeof maybeKey === 'string') {\n const key = fromHex(maybeKey);\n return this.fromRaw(key);\n } else if (isObject(maybeKey)) {\n const key = maybeKey as KeyLike;\n if (isObject(key) && Object.hasOwnProperty.call(key, '__derEncodedPublicKey__')) {\n return this.fromDer(key as DerEncodedPublicKey);\n } else if (ArrayBuffer.isView(key)) {\n const view = key as ArrayBufferView;\n return this.fromRaw(bufFromBufLike(view.buffer));\n } else if (key instanceof ArrayBuffer) {\n return this.fromRaw(key);\n } else if ('rawKey' in key) {\n return this.fromRaw(key.rawKey as ArrayBuffer);\n } else if ('derKey' in key) {\n return this.fromDer(key.derKey as DerEncodedPublicKey);\n } else if ('toDer' in key) {\n return this.fromDer(key.toDer() as ArrayBuffer);\n }\n }\n throw new Error('Cannot construct Ed25519PublicKey from the provided key.');\n }\n\n public static fromRaw(rawKey: ArrayBuffer): Ed25519PublicKey {\n return new Ed25519PublicKey(rawKey);\n }\n\n public static fromDer(derKey: DerEncodedPublicKey): Ed25519PublicKey {\n return new Ed25519PublicKey(this.derDecode(derKey));\n }\n\n // The length of Ed25519 public keys is always 32 bytes.\n private static RAW_KEY_LENGTH = 32;\n\n private static derEncode(publicKey: ArrayBuffer): DerEncodedPublicKey {\n const key = wrapDER(publicKey, ED25519_OID).buffer as DerEncodedPublicKey;\n key.__derEncodedPublicKey__ = undefined;\n return key;\n }\n\n private static derDecode(key: DerEncodedPublicKey): ArrayBuffer {\n const unwrapped = unwrapDER(key, ED25519_OID);\n if (unwrapped.length !== this.RAW_KEY_LENGTH) {\n throw new Error('An Ed25519 public key must be exactly 32bytes long');\n }\n return unwrapped;\n }\n\n #rawKey: ArrayBuffer;\n\n public get rawKey(): ArrayBuffer {\n return this.#rawKey;\n }\n\n #derKey: DerEncodedPublicKey;\n\n public get derKey(): DerEncodedPublicKey {\n return this.#derKey;\n }\n\n // `fromRaw` and `fromDer` should be used for instantiation, not this constructor.\n private constructor(key: ArrayBuffer) {\n if (key.byteLength !== Ed25519PublicKey.RAW_KEY_LENGTH) {\n throw new Error('An Ed25519 public key must be exactly 32bytes long');\n }\n this.#rawKey = key;\n this.#derKey = Ed25519PublicKey.derEncode(key);\n }\n\n public toDer(): DerEncodedPublicKey {\n return this.derKey;\n }\n\n public toRaw(): ArrayBuffer {\n return this.rawKey;\n }\n}\n\n/**\n * Ed25519KeyIdentity is an implementation of SignIdentity that uses Ed25519 keys. This class is used to sign and verify messages for an agent.\n */\nexport class Ed25519KeyIdentity extends SignIdentity {\n /**\n * Generate a new Ed25519KeyIdentity.\n * @param seed a 32-byte seed for the private key. If not provided, a random seed will be generated.\n * @returns Ed25519KeyIdentity\n */\n public static generate(seed?: Uint8Array): Ed25519KeyIdentity {\n\n if (seed && seed.length !== 32) {\n throw new Error('Ed25519 Seed needs to be 32 bytes long.');\n }\n if (!seed) seed = ed25519.utils.randomPrivateKey();\n // Check if the seed is all zeros\n if(bufEquals(seed, new Uint8Array(new Array(32).fill(0)))) {\n console.warn('Seed is all zeros. This is not a secure seed. Please provide a seed with sufficient entropy if this is a production environment.');\n }\n const sk = new Uint8Array(32);\n for (let i = 0; i < 32; i++) sk[i] = new Uint8Array(seed)[i];\n\n const pk = ed25519.getPublicKey(sk);\n return Ed25519KeyIdentity.fromKeyPair(pk, sk);\n }\n\n public static fromParsedJson(obj: JsonnableEd25519KeyIdentity): Ed25519KeyIdentity {\n const [publicKeyDer, privateKeyRaw] = obj;\n return new Ed25519KeyIdentity(\n Ed25519PublicKey.fromDer(fromHex(publicKeyDer) as DerEncodedPublicKey),\n fromHex(privateKeyRaw),\n );\n }\n\n public static fromJSON(json: string): Ed25519KeyIdentity {\n const parsed = JSON.parse(json);\n if (Array.isArray(parsed)) {\n if (typeof parsed[0] === 'string' && typeof parsed[1] === 'string') {\n return this.fromParsedJson([parsed[0], parsed[1]]);\n } else {\n throw new Error('Deserialization error: JSON must have at least 2 items.');\n }\n }\n throw new Error(`Deserialization error: Invalid JSON type for string: ${JSON.stringify(json)}`);\n }\n\n public static fromKeyPair(publicKey: ArrayBuffer, privateKey: ArrayBuffer): Ed25519KeyIdentity {\n return new Ed25519KeyIdentity(Ed25519PublicKey.fromRaw(publicKey), privateKey);\n }\n\n public static fromSecretKey(secretKey: ArrayBuffer): Ed25519KeyIdentity {\n const publicKey = ed25519.getPublicKey(new Uint8Array(secretKey));\n return Ed25519KeyIdentity.fromKeyPair(publicKey, secretKey);\n }\n\n #publicKey: Ed25519PublicKey;\n #privateKey: Uint8Array;\n\n // `fromRaw` and `fromDer` should be used for instantiation, not this constructor.\n protected constructor(publicKey: PublicKey, privateKey: ArrayBuffer) {\n super();\n this.#publicKey = Ed25519PublicKey.from(publicKey);\n this.#privateKey = new Uint8Array(privateKey);\n }\n\n /**\n * Serialize this key to JSON.\n */\n public toJSON(): JsonnableEd25519KeyIdentity {\n return [toHex(this.#publicKey.toDer()), toHex(this.#privateKey)];\n }\n\n /**\n * Return a copy of the key pair.\n */\n public getKeyPair(): KeyPair {\n return {\n secretKey: this.#privateKey,\n publicKey: this.#publicKey,\n };\n }\n\n /**\n * Return the public key.\n */\n public getPublicKey(): Required<PublicKey> {\n return this.#publicKey;\n }\n\n /**\n * Signs a blob of data, with this identity's private key.\n * @param challenge - challenge to sign with this identity's secretKey, producing a signature\n */\n public async sign(challenge: ArrayBuffer): Promise<Signature> {\n const blob = new Uint8Array(challenge);\n // Some implementations of Ed25519 private keys append a public key to the end of the private key. We only want the private key.\n const signature = uint8ToBuf(ed25519.sign(blob, this.#privateKey.slice(0, 32)));\n // add { __signature__: void; } to the signature to make it compatible with the agent\n\n Object.defineProperty(signature, '__signature__', {\n enumerable: false,\n value: undefined,\n });\n\n return signature as Signature;\n }\n\n /**\n * Verify\n * @param sig - signature to verify\n * @param msg - message to verify\n * @param pk - public key\n * @returns - true if the signature is valid, false otherwise\n */\n public static verify(\n sig: ArrayBuffer | Uint8Array | string,\n msg: ArrayBuffer | Uint8Array | string,\n pk: ArrayBuffer | Uint8Array | string,\n ) {\n const [signature, message, publicKey] = [sig, msg, pk].map(x => {\n if (typeof x === 'string') {\n x = fromHex(x);\n }\n if (x instanceof Uint8Array) {\n x = x.buffer;\n }\n return new Uint8Array(x);\n });\n return ed25519.verify(message, signature, publicKey);\n }\n}\n\ntype PublicKeyHex = string;\ntype SecretKeyHex = string;\nexport type JsonnableEd25519KeyIdentity = [PublicKeyHex, SecretKeyHex];\n", "import { DerEncodedPublicKey, PublicKey, Signature, SignIdentity } from '@dfinity/agent';\n\n/**\n * Options used in a {@link ECDSAKeyIdentity}\n */\nexport type CryptoKeyOptions = {\n extractable?: boolean;\n keyUsages?: KeyUsage[];\n subtleCrypto?: SubtleCrypto;\n};\n\nexport class CryptoError extends Error {\n constructor(public readonly message: string) {\n super(message);\n Object.setPrototypeOf(this, CryptoError.prototype);\n }\n}\n\nexport interface DerCryptoKey extends CryptoKey {\n toDer: () => DerEncodedPublicKey;\n}\n\n/**\n * Utility method to ensure that a subtleCrypto implementation is provided or is available in the global context\n * @param subtleCrypto SubtleCrypto implementation\n * @returns subleCrypto\n */\nfunction _getEffectiveCrypto(subtleCrypto: CryptoKeyOptions['subtleCrypto']): SubtleCrypto {\n if (typeof global !== 'undefined' && global['crypto'] && global['crypto']['subtle']) {\n return global['crypto']['subtle'];\n }\n if (subtleCrypto) {\n return subtleCrypto;\n } else if (typeof crypto !== 'undefined' && crypto['subtle']) {\n return crypto.subtle;\n } else {\n throw new CryptoError(\n 'Global crypto was not available and none was provided. Please inlcude a SubtleCrypto implementation. See https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto',\n );\n }\n}\n\n/**\n * An identity interface that wraps an ECDSA keypair using the P-256 named curve. Supports DER-encoding and decoding for agent calls\n */\nexport class ECDSAKeyIdentity extends SignIdentity {\n /**\n * Generates a randomly generated identity for use in calls to the Internet Computer.\n * @param {CryptoKeyOptions} options optional settings\n * @param {CryptoKeyOptions['extractable']} options.extractable - whether the key should allow itself to be used. Set to false for maximum security.\n * @param {CryptoKeyOptions['keyUsages']} options.keyUsages - a list of key usages that the key can be used for\n * @param {CryptoKeyOptions['subtleCrypto']} options.subtleCrypto interface\n * @constructs ECDSAKeyIdentity\n * @returns a {@link ECDSAKeyIdentity}\n */\n public static async generate(options?: CryptoKeyOptions): Promise<ECDSAKeyIdentity> {\n const { extractable = false, keyUsages = ['sign', 'verify'], subtleCrypto } = options ?? {};\n const effectiveCrypto = _getEffectiveCrypto(subtleCrypto);\n const keyPair = await effectiveCrypto.generateKey(\n {\n name: 'ECDSA',\n namedCurve: 'P-256',\n },\n extractable,\n keyUsages,\n );\n const derKey = (await effectiveCrypto.exportKey(\n 'spki',\n keyPair.publicKey,\n )) as DerEncodedPublicKey;\n\n return new this(keyPair, derKey, effectiveCrypto);\n }\n\n /**\n * generates an identity from a public and private key. Please ensure that you are generating these keys securely and protect the user's private key\n * @param keyPair a CryptoKeyPair\n * @param subtleCrypto - a SubtleCrypto interface in case one is not available globally\n * @returns an {@link ECDSAKeyIdentity}\n */\n public static async fromKeyPair(\n keyPair: CryptoKeyPair | { privateKey: CryptoKey; publicKey: CryptoKey },\n subtleCrypto?: SubtleCrypto,\n ): Promise<ECDSAKeyIdentity> {\n const effectiveCrypto = _getEffectiveCrypto(subtleCrypto);\n const derKey = (await effectiveCrypto.exportKey(\n 'spki',\n keyPair.publicKey,\n )) as DerEncodedPublicKey;\n return new ECDSAKeyIdentity(keyPair, derKey, effectiveCrypto);\n }\n\n protected _derKey: DerEncodedPublicKey;\n protected _keyPair: CryptoKeyPair;\n protected _subtleCrypto: SubtleCrypto;\n\n // `fromKeyPair` and `generate` should be used for instantiation, not this constructor.\n protected constructor(\n keyPair: CryptoKeyPair,\n derKey: DerEncodedPublicKey,\n subtleCrypto: SubtleCrypto,\n ) {\n super();\n this._keyPair = keyPair;\n this._derKey = derKey;\n this._subtleCrypto = subtleCrypto;\n }\n\n /**\n * Return the internally-used key pair.\n * @returns a CryptoKeyPair\n */\n public getKeyPair(): CryptoKeyPair {\n return this._keyPair;\n }\n\n /**\n * Return the public key.\n * @returns an {@link PublicKey & DerCryptoKey}\n */\n public getPublicKey(): PublicKey & DerCryptoKey {\n const derKey = this._derKey;\n const key: DerCryptoKey = Object.create(this._keyPair.publicKey);\n key.toDer = function () {\n return derKey;\n };\n\n return key;\n }\n\n /**\n * Signs a blob of data, with this identity's private key.\n * @param {ArrayBuffer} challenge - challenge to sign with this identity's secretKey, producing a signature\n * @returns {Promise<Signature>} signature\n */\n public async sign(challenge: ArrayBuffer): Promise<Signature> {\n const params: EcdsaParams = {\n name: 'ECDSA',\n hash: { name: 'SHA-256' },\n };\n this._keyPair.privateKey;\n const signature = await this._subtleCrypto.sign(params, this._keyPair.privateKey, challenge);\n\n return signature as Signature;\n }\n}\n\nexport default ECDSAKeyIdentity;\n", "import {\n DerEncodedPublicKey,\n fromHex,\n HttpAgentRequest,\n PublicKey,\n requestIdOf,\n Signature,\n SignIdentity,\n toHex,\n} from '@dfinity/agent';\nimport { Principal } from '@dfinity/principal';\nimport * as cbor from 'simple-cbor';\nimport { PartialIdentity } from './partial';\n\nconst domainSeparator = new TextEncoder().encode('\\x1Aic-request-auth-delegation');\nconst requestDomainSeparator = new TextEncoder().encode('\\x0Aic-request');\n\nfunction _parseBlob(value: unknown): ArrayBuffer {\n if (typeof value !== 'string' || value.length < 64) {\n throw new Error('Invalid public key.');\n }\n\n return fromHex(value);\n}\n\n/**\n * A single delegation object that is signed by a private key. This is constructed by\n * `DelegationChain.create()`.\n *\n * {@see DelegationChain}\n */\nexport class Delegation {\n constructor(\n public readonly pubkey: ArrayBuffer,\n public readonly expiration: bigint,\n public readonly targets?: Principal[],\n ) {}\n\n public toCBOR(): cbor.CborValue {\n // Expiration field needs to be encoded as a u64 specifically.\n return cbor.value.map({\n pubkey: cbor.value.bytes(this.pubkey),\n expiration: cbor.value.u64(this.expiration.toString(16), 16),\n ...(this.targets && {\n targets: cbor.value.array(this.targets.map(t => cbor.value.bytes(t.toUint8Array()))),\n }),\n });\n }\n\n public toJSON(): JsonnableDelegation {\n // every string should be hex and once-de-hexed,\n // discoverable what it is (e.g. de-hex to get JSON with a 'type' property, or de-hex to DER\n // with an OID). After de-hex, if it's not obvious what it is, it's an ArrayBuffer.\n return {\n expiration: this.expiration.toString(16),\n pubkey: toHex(this.pubkey),\n ...(this.targets && { targets: this.targets.map(p => p.toHex()) }),\n };\n }\n}\n\n/**\n * Type of ReturnType<Delegation.toJSON>.\n * The goal here is to stringify all non-JSON-compatible types to some bytes representation we can\n * stringify as hex.\n * (Hex shouldn't be ambiguous ever, because you can encode as DER with semantic OIDs).\n */\ninterface JsonnableDelegation {\n // A BigInt of Nanoseconds since epoch as hex\n expiration: string;\n // Hexadecimal representation of the DER public key.\n pubkey: string;\n // Array of strings, where each string is hex of principal blob (*NOT* textual representation).\n targets?: string[];\n}\n\n/**\n * A signed delegation, which lends its identity to the public key in the delegation\n * object. This is constructed by `DelegationChain.create()`.\n *\n * {@see DelegationChain}\n */\nexport interface SignedDelegation {\n delegation: Delegation;\n signature: Signature;\n}\n\n/**\n * Sign a single delegation object for a period of time.\n * @param from The identity that lends its delegation.\n * @param to The identity that receives the delegation.\n * @param expiration An expiration date for this delegation.\n * @param targets Limit this delegation to the target principals.\n */\nasync function _createSingleDelegation(\n from: SignIdentity,\n to: PublicKey,\n expiration: Date,\n targets?: Principal[],\n): Promise<SignedDelegation> {\n const delegation: Delegation = new Delegation(\n to.toDer(),\n BigInt(+expiration) * BigInt(1000000), // In nanoseconds.\n targets,\n );\n // The signature is calculated by signing the concatenation of the domain separator\n // and the message.\n // Note: To ensure Safari treats this as a user gesture, ensure to not use async methods\n // besides the actualy webauthn functionality (such as `sign`). Safari will de-register\n // a user gesture if you await an async call thats not fetch, xhr, or setTimeout.\n const challenge = new Uint8Array([\n ...domainSeparator,\n ...new Uint8Array(requestIdOf(delegation)),\n ]);\n const signature = await from.sign(challenge);\n\n return {\n delegation,\n signature,\n };\n}\n\nexport interface JsonnableDelegationChain {\n publicKey: string;\n delegations: Array<{\n signature: string;\n delegation: {\n pubkey: string;\n expiration: string;\n targets?: string[];\n };\n }>;\n}\n\n/**\n * A chain of delegations. This is JSON Serializable.\n * This is the object to serialize and pass to a DelegationIdentity. It does not keep any\n * private keys.\n */\nexport class DelegationChain {\n /**\n * Create a delegation chain between two (or more) keys. By default, the expiration time\n * will be very short (15 minutes).\n *\n * To build a chain of more than 2 identities, this function needs to be called multiple times,\n * passing the previous delegation chain into the options argument. For example:\n * @example\n * const rootKey = createKey();\n * const middleKey = createKey();\n * const bottomeKey = createKey();\n *\n * const rootToMiddle = await DelegationChain.create(\n * root, middle.getPublicKey(), Date.parse('2100-01-01'),\n * );\n * const middleToBottom = await DelegationChain.create(\n * middle, bottom.getPublicKey(), Date.parse('2100-01-01'), { previous: rootToMiddle },\n * );\n *\n * // We can now use a delegation identity that uses the delegation above:\n * const identity = DelegationIdentity.fromDelegation(bottomKey, middleToBottom);\n * @param from The identity that will delegate.\n * @param to The identity that gets delegated. It can now sign messages as if it was the\n * identity above.\n * @param expiration The length the delegation is valid. By default, 15 minutes from calling\n * this function.\n * @param options A set of options for this delegation. expiration and previous\n * @param options.previous - Another DelegationChain that this chain should start with.\n * @param options.targets - targets that scope the delegation (e.g. Canister Principals)\n */\n public static async create(\n from: SignIdentity,\n to: PublicKey,\n expiration: Date = new Date(Date.now() + 15 * 60 * 1000),\n options: {\n previous?: DelegationChain;\n targets?: Principal[];\n } = {},\n ): Promise<DelegationChain> {\n const delegation = await _createSingleDelegation(from, to, expiration, options.targets);\n return new DelegationChain(\n [...(options.previous?.delegations || []), delegation],\n options.previous?.publicKey || from.getPublicKey().toDer(),\n );\n }\n\n /**\n * Creates a DelegationChain object from a JSON string.\n * @param json The JSON string to parse.\n */\n public static fromJSON(json: string | JsonnableDelegationChain): DelegationChain {\n const { publicKey, delegations } = typeof json === 'string' ? JSON.parse(json) : json;\n if (!Array.isArray(delegations)) {\n throw new Error('Invalid delegations.');\n }\n\n const parsedDelegations: SignedDelegation[] = delegations.map(signedDelegation => {\n const { delegation, signature } = signedDelegation;\n const { pubkey, expiration, targets } = delegation;\n if (targets !== undefined && !Array.isArray(targets)) {\n throw new Error('Invalid targets.');\n }\n\n return {\n delegation: new Delegation(\n _parseBlob(pubkey),\n BigInt('0x' + expiration), // expiration in JSON is an hexa string (See toJSON() below).\n targets &&\n targets.map((t: unknown) => {\n if (typeof t !== 'string') {\n throw new Error('Invalid target.');\n }\n return Principal.fromHex(t);\n }),\n ),\n signature: _parseBlob(signature) as Signature,\n };\n });\n\n return new this(parsedDelegations, _parseBlob(publicKey) as DerEncodedPublicKey);\n }\n\n /**\n * Creates a DelegationChain object from a list of delegations and a DER-encoded public key.\n * @param delegations The list of delegations.\n * @param publicKey The DER-encoded public key of the key-pair signing the first delegation.\n */\n public static fromDelegations(\n delegations: SignedDelegation[],\n publicKey: DerEncodedPublicKey,\n ): DelegationChain {\n return new this(delegations, publicKey);\n }\n\n protected constructor(\n public readonly delegations: SignedDelegation[],\n public readonly publicKey: DerEncodedPublicKey,\n ) {}\n\n public toJSON(): JsonnableDelegationChain {\n return {\n delegations: this.delegations.map(signedDelegation => {\n const { delegation, signature } = signedDelegation;\n const { targets } = delegation;\n return {\n delegation: {\n expiration: delegation.expiration.toString(16),\n pubkey: toHex(delegation.pubkey),\n ...(targets && {\n targets: targets.map(t => t.toHex()),\n }),\n },\n signature: toHex(signature),\n };\n }),\n publicKey: toHex(this.publicKey),\n };\n }\n}\n\n/**\n * An Identity that adds delegation to a request. Everywhere in this class, the name\n * innerKey refers to the SignIdentity that is being used to sign the requests, while\n * originalKey is the identity that is being borrowed. More identities can be used\n * in the middle to delegate.\n */\nexport class DelegationIdentity extends SignIdentity {\n /**\n * Create a delegation without having access to delegateKey.\n * @param key The key used to sign the reqyests.\n * @param delegation A delegation object created using `createDelegation`.\n */\n public static fromDelegation(\n key: Pick<SignIdentity, 'sign'>,\n delegation: DelegationChain,\n ): DelegationIdentity {\n return new this(key, delegation);\n }\n\n protected constructor(\n private _inner: Pick<SignIdentity, 'sign'>,\n private _delegation: DelegationChain,\n ) {\n super();\n }\n\n public getDelegation(): DelegationChain {\n return this._delegation;\n }\n\n public getPublicKey(): PublicKey {\n return {\n derKey: this._delegation.publicKey,\n toDer: () => this._delegation.publicKey,\n };\n }\n public sign(blob: ArrayBuffer): Promise<Signature> {\n return this._inner.sign(blob);\n }\n\n public async transformRequest(request: HttpAgentRequest): Promise<unknown> {\n const { body, ...fields } = request;\n const requestId = await requestIdOf(body);\n return {\n ...fields,\n body: {\n content: body,\n sender_sig: await this.sign(\n new Uint8Array([...requestDomainSeparator, ...new Uint8Array(requestId)]),\n ),\n sender_delegation: this._delegation.delegations,\n sender_pubkey: this._delegation.publicKey,\n },\n };\n }\n}\n\n/**\n * A partial delegated identity, representing a delegation chain and the public key that it targets\n */\nexport class PartialDelegationIdentity extends PartialIdentity {\n #delegation: DelegationChain;\n\n /**\n * The Delegation Chain of this identity.\n */\n get delegation(): DelegationChain {\n return this.#delegation;\n }\n\n private constructor(inner: PublicKey, delegation: DelegationChain) {\n super(inner);\n this.#delegation = delegation;\n }\n\n /**\n * Create a {@link PartialDelegationIdentity} from a {@link PublicKey} and a {@link DelegationChain}.\n * @param key The {@link PublicKey} to delegate to.\n * @param delegation a {@link DelegationChain} targeting the inner key.\n * @constructs PartialDelegationIdentity\n */\n public static fromDelegation(key: PublicKey, delegation: DelegationChain) {\n return new PartialDelegationIdentity(key, delegation);\n }\n}\n\n/**\n * List of things to check for a delegation chain validity.\n */\nexport interface DelegationValidChecks {\n /**\n * Check that the scope is amongst the scopes that this delegation has access to.\n */\n scope?: Principal | string | Array<Principal | string>;\n}\n\n/**\n * Analyze a DelegationChain and validate that it's valid, ie. not expired and apply to the\n * scope.\n * @param chain The chain to validate.\n * @param checks Various checks to validate on the chain.\n */\nexport function isDelegationValid(chain: DelegationChain, checks?: DelegationValidChecks): boolean {\n // Verify that the no delegation is expired. If any are in the chain, returns false.\n for (const { delegation } of chain.delegations) {\n // prettier-ignore\n if (+new Date(Number(delegation.expiration / BigInt(1000000))) <= +Date.now()) {\n return false;\n }\n }\n\n // Check the scopes.\n const scopes: Principal[] = [];\n const maybeScope = checks?.scope;\n if (maybeScope) {\n if (Array.isArray(maybeScope)) {\n scopes.push(...maybeScope.map(s => (typeof s === 'string' ? Principal.fromText(s) : s)));\n } else {\n scopes.push(typeof maybeScope === 'string' ? Principal.fromText(maybeScope) : maybeScope);\n }\n }\n\n for (const s of scopes) {\n const scope = s.toText();\n for (const { delegation } of chain.delegations) {\n if (delegation.targets === undefined) {\n continue;\n }\n\n let none = true;\n for (const target of delegation.targets) {\n if (target.toText() === scope) {\n none = false;\n break;\n }\n }\n if (none) {\n return false;\n }\n }\n }\n\n return true;\n}\n", "import { Identity, PublicKey } from '@dfinity/agent';\nimport { Principal } from '@dfinity/principal';\n\n/**\n * A partial delegated identity, representing a delegation chain and the public key that it targets\n */\nexport class PartialIdentity implements Identity {\n #inner: PublicKey;\n\n /**\n * The raw public key of this identity.\n */\n get rawKey(): ArrayBuffer | undefined {\n return this.#inner.rawKey;\n }\n\n /**\n * The DER-encoded public key of this identity.\n */\n get derKey(): ArrayBuffer | undefined {\n return this.#inner.derKey;\n }\n\n /**\n * The DER-encoded public key of this identity.\n */\n public toDer(): ArrayBuffer {\n return this.#inner.toDer();\n }\n\n /**\n * The inner {@link PublicKey} used by this identity.\n */\n public getPublicKey(): PublicKey {\n return this.#inner;\n }\n\n /**\n * The {@link Principal} of this identity.\n */\n public getPrincipal(): Principal {\n return Principal.from(this.#inner.rawKey);\n }\n\n /**\n * Required for the Identity interface, but cannot implemented for just a public key.\n */\n public transformRequest(): Promise<never> {\n return Promise.reject(\n 'Not implemented. You are attempting to use a partial identity to sign calls, but this identity only has access to the public key.To sign calls, use a DelegationIdentity instead.',\n );\n }\n\n constructor(inner: PublicKey) {\n this.#inner = inner;\n }\n}\n", "import {\n DerEncodedPublicKey,\n PublicKey,\n Signature,\n SignIdentity,\n wrapDER,\n DER_COSE_OID,\n fromHex,\n toHex,\n} from '@dfinity/agent';\nimport borc from 'borc';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { bufFromBufLike } from '@dfinity/candid';\n\nfunction _coseToDerEncodedBlob(cose: ArrayBuffer): DerEncodedPublicKey {\n return wrapDER(cose, DER_COSE_OID).buffer as DerEncodedPublicKey;\n}\n\ntype PublicKeyCredentialWithAttachment = PublicKeyCredential & {\n // Extends `PublicKeyCredential` with an optional field introduced in the WebAuthn level 3 spec:\n // https://w3c.github.io/webauthn/#dom-publickeycredential-authenticatorattachment\n // Already supported by Chrome, Safari and Edge\n // Note: `null` is included here as a possible value because Edge set this value to null in the\n // past.\n authenticatorAttachment: AuthenticatorAttachment | undefined | null;\n};\n\n/**\n * From the documentation;\n * The authData is a byte array described in the spec. Parsing it will involve slicing bytes from\n * the array and converting them into usable objects.\n *\n * See https://webauthn.guide/#registration (subsection \"Example: Parsing the authenticator data\").\n * @param authData The authData field of the attestation response.\n * @returns The COSE key of the authData.\n */\nfunction _authDataToCose(authData: ArrayBuffer): ArrayBuffer {\n const dataView = new DataView(new ArrayBuffer(2));\n const idLenBytes = authData.slice(53, 55);\n [...new Uint8Array(idLenBytes)].forEach((v, i) => dataView.setUint8(i, v));\n const credentialIdLength = dataView.getUint16(0);\n\n // Get the public key object.\n return authData.slice(55 + credentialIdLength);\n}\n\nexport class CosePublicKey implements PublicKey {\n protected _encodedKey: DerEncodedPublicKey;\n\n public constructor(protected _cose: ArrayBuffer) {\n this._encodedKey = _coseToDerEncodedBlob(_cose);\n }\n\n public toDer(): DerEncodedPublicKey {\n return this._encodedKey;\n }\n\n public getCose(): ArrayBuffer {\n return this._cose;\n }\n}\n\n/**\n * Create a challenge from a string or array. The default challenge is always the same\n * because we don't need to verify the authenticity of the key on the server (we don't\n * register our keys with the IC). Any challenge would do, even one per key, randomly\n * generated.\n * @param challenge The challenge to transform into a byte array. By default a hard\n * coded string.\n */\nfunction _createChallengeBuffer(challenge: string | Uint8Array = '<ic0.app>'): Uint8Array {\n if (typeof challenge === 'string') {\n return Uint8Array.from(challenge, c => c.charCodeAt(0));\n } else {\n return challenge;\n }\n}\n\n/**\n * Create a credentials to authenticate with a server. This is necessary in order in\n * WebAuthn to get credentials IDs (which give us the public key and allow us to\n * sign), but in the case of the Internet Computer, we don't actually need to register\n * it, so we don't.\n * @param credentialCreationOptions an optional CredentialCreationOptions object\n */\nasync function _createCredential(\n credentialCreationOptions?: CredentialCreationOptions,\n): Promise<PublicKeyCredentialWithAttachment | null> {\n const creds = (await navigator.credentials.create(\n credentialCreationOptions ?? {\n publicKey: {\n authenticatorSelection: {\n userVerification: 'preferred',\n },\n attestation: 'direct',\n challenge: _createChallengeBuffer(),\n pubKeyCredParams: [{ type: 'public-key', alg: PubKeyCoseAlgo.ECDSA_WITH_SHA256 }],\n rp: {\n name: 'Internet Identity Service',\n },\n user: {\n id: randomBytes(16),\n name: 'Internet Identity',\n displayName: 'Internet Identity',\n },\n },\n },\n )) as PublicKeyCredentialWithAttachment | null;\n\n if (creds === null) {\n return null;\n }\n\n return {\n // do _not_ use ...creds here, as creds is not enumerable in all cases\n id: creds.id,\n response: creds.response,\n type: creds.type,\n authenticatorAttachment: creds.authenticatorAttachment,\n getClientExtensionResults: creds.getClientExtensionResults,\n // Some password managers will return a Uint8Array, so we ensure we return an ArrayBuffer.\n rawId: bufFromBufLike(creds.rawId),\n };\n}\n\n// See https://www.iana.org/assignments/cose/cose.xhtml#algorithms for a complete\n// list of these algorithms. We only list the ones we support here.\nenum PubKeyCoseAlgo {\n ECDSA_WITH_SHA256 = -7,\n}\n\n/**\n * A SignIdentity that uses `navigator.credentials`. See https://webauthn.guide/ for\n * more information about WebAuthentication.\n */\nexport class WebAuthnIdentity extends SignIdentity {\n /**\n * Create an identity from a JSON serialization.\n * @param json - json to parse\n */\n public static fromJSON(json: string): WebAuthnIdentity {\n const { publicKey, rawId } = JSON.parse(json);\n\n if (typeof publicKey !== 'string' || typeof rawId !== 'string') {\n throw new Error('Invalid JSON string.');\n }\n\n return new this(fromHex(rawId), fromHex(publicKey), undefined);\n }\n\n /**\n * Create an identity.\n * @param credentialCreationOptions an optional CredentialCreationOptions Challenge\n */\n public static async create(\n credentialCreationOptions?: CredentialCreationOptions,\n ): Promise<WebAuthnIdentity> {\n const creds = await _createCredential(credentialCreationOptions);\n\n if (!creds || creds.type !== 'public-key') {\n throw new Error('Could not create credentials.');\n }\n\n const response = creds.response as AuthenticatorAttestationResponse;\n if (response.attestationObject === undefined) {\n throw new Error('Was expecting an attestation response.');\n }\n\n // Parse the attestationObject as CBOR.\n const attObject = borc.decodeFirst(new Uint8Array(response.attestationObject));\n\n return new this(\n creds.rawId,\n _authDataToCose(attObject.authData),\n creds.authenticatorAttachment ?? undefined,\n );\n }\n\n protected _publicKey: CosePublicKey;\n\n public constructor(\n public readonly rawId: ArrayBuffer,\n cose: ArrayBuffer,\n protected authenticatorAttachment: AuthenticatorAttachment | undefined,\n ) {\n super();\n this._publicKey = new CosePublicKey(cose);\n }\n\n public getPublicKey(): PublicKey {\n return this._publicKey;\n }\n\n /**\n * WebAuthn level 3 spec introduces a new attribute on successful WebAuthn interactions,\n * see https://w3c.github.io/webauthn/#dom-publickeycredential-authenticatorattachment.\n * This attribute is already implemented for Chrome, Safari and Edge.\n *\n * Given the attribute is only available after a successful interaction, the information is\n * provided opportunistically and might also be `undefined`.\n */\n public getAuthenticatorAttachment(): AuthenticatorAttachment | undefined {\n return this.authenticatorAttachment;\n }\n\n public async sign(blob: ArrayBuffer): Promise<Signature> {\n const result = (await navigator.credentials.get({\n publicKey: {\n allowCredentials: [\n {\n type: 'public-key',\n id: this.rawId,\n },\n ],\n challenge: blob,\n userVerification: 'preferred',\n },\n })) as PublicKeyCredentialWithAttachment;\n\n if (result.authenticatorAttachment !== null) {\n this.authenticatorAttachment = result.authenticatorAttachment;\n }\n\n const response = result.response as AuthenticatorAssertionResponse;\n\n const cbor = borc.encode(\n new borc.Tagged(55799, {\n authenticator_data: new Uint8Array(response.authenticatorData),\n client_data_json: new TextDecoder().decode(response.clientDataJSON),\n signature: new Uint8Array(response.signature),\n }),\n );\n if (!cbor) {\n throw new Error('failed to encode cbor');\n }\n return cbor.buffer as Signature;\n }\n\n /**\n * Allow for JSON serialization of all information needed to reuse this identity.\n */\n public toJSON(): JsonnableWebAuthnIdentity {\n return {\n publicKey: toHex(this._publicKey.getCose()),\n rawId: toHex(this.rawId),\n };\n }\n}\n\n/**\n * ReturnType<WebAuthnIdentity.toJSON>\n */\nexport interface JsonnableWebAuthnIdentity {\n // The hexadecimal representation of the DER encoded public key.\n publicKey: string;\n // The string representation of the local WebAuthn Credential.id (base64url encoded).\n rawId: string;\n}\n", "/** @module IdleManager */\ntype IdleCB = () => unknown;\nexport type IdleManagerOptions = {\n /**\n * Callback after the user has gone idle\n */\n onIdle?: IdleCB;\n /**\n * timeout in ms\n * @default 30 minutes [600_000]\n */\n idleTimeout?: number;\n /**\n * capture scroll events\n * @default false\n */\n captureScroll?: boolean;\n /**\n * scroll debounce time in ms\n * @default 100\n */\n scrollDebounce?: number;\n};\n\nconst events = ['mousedown', 'mousemove', 'keydown', 'touchstart', 'wheel'];\n\n/**\n * Detects if the user has been idle for a duration of `idleTimeout` ms, and calls `onIdle` and registered callbacks.\n * By default, the IdleManager will log a user out after 10 minutes of inactivity.\n * To override these defaults, you can pass an `onIdle` callback, or configure a custom `idleTimeout` in milliseconds\n */\nexport class IdleManager {\n callbacks: IdleCB[] = [];\n idleTimeout: IdleManagerOptions['idleTimeout'] = 10 * 60 * 1000;\n timeoutID?: number = undefined;\n\n /**\n * Creates an {@link IdleManager}\n * @param {IdleManagerOptions} options Optional configuration\n * @see {@link IdleManagerOptions}\n * @param options.onIdle Callback once user has been idle. Use to prompt for fresh login, and use `Actor.agentOf(your_actor).invalidateIdentity()` to protect the user\n * @param options.idleTimeout timeout in ms\n * @param options.captureScroll capture scroll events\n * @param options.scrollDebounce scroll debounce time in ms\n */\n public static create(\n options: {\n /**\n * Callback after the user has gone idle\n * @see {@link IdleCB}\n */\n onIdle?: () => unknown;\n /**\n * timeout in ms\n * @default 10 minutes [600_000]\n */\n idleTimeout?: number;\n /**\n * capture scroll events\n * @default false\n */\n captureScroll?: boolean;\n /**\n * scroll debounce time in ms\n * @default 100\n */\n scrollDebounce?: number;\n } = {},\n ): IdleManager {\n return new this(options);\n }\n\n /**\n * @protected\n * @param options {@link IdleManagerOptions}\n */\n protected constructor(options: IdleManagerOptions = {}) {\n const { onIdle, idleTimeout = 10 * 60 * 1000 } = options || {};\n\n this.callbacks = onIdle ? [onIdle] : [];\n this.idleTimeout = idleTimeout;\n\n const _resetTimer = this._resetTimer.bind(this);\n\n window.addEventListener('load', _resetTimer, true);\n\n events.forEach(function (name) {\n document.addEventListener(name, _resetTimer, true);\n });\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n const debounce = (func: Function, wait: number) => {\n let timeout: number | undefined;\n return (...args: unknown[]) => {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const context = this;\n const later = function () {\n timeout = undefined;\n func.apply(context, args);\n };\n clearTimeout(timeout);\n timeout = window.setTimeout(later, wait);\n };\n };\n\n if (options?.captureScroll) {\n // debounce scroll events\n const scroll = debounce(_resetTimer, options?.scrollDebounce ?? 100);\n window.addEventListener('scroll', scroll, true);\n }\n\n _resetTimer();\n }\n\n /**\n * @param {IdleCB} callback function to be called when user goes idle\n */\n public registerCallback(callback: IdleCB): void {\n this.callbacks.push(callback);\n }\n\n /**\n * Cleans up the idle manager and its listeners\n */\n public exit(): void {\n clearTimeout(this.timeoutID);\n window.removeEventListener('load', this._resetTimer, true);\n\n const _resetTimer = this._resetTimer.bind(this);\n events.forEach(function (name) {\n document.removeEventListener(name, _resetTimer, true);\n });\n this.callbacks.forEach(cb => cb());\n }\n\n /**\n * Resets the timeouts during cleanup\n */\n _resetTimer(): void {\n const exit = this.exit.bind(this);\n window.clearTimeout(this.timeoutID);\n this.timeoutID = window.setTimeout(exit, this.idleTimeout);\n }\n}\n", "const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n", "import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);\n });\n }\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event.newVersion, event));\n }\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking) {\n db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));\n }\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event));\n }\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n", "import { openDB, IDBPDatabase } from 'idb';\nimport { DB_VERSION, isBrowser, KEY_STORAGE_DELEGATION, KEY_STORAGE_KEY } from './storage';\n\ntype Database = IDBPDatabase<unknown>;\ntype IDBValidKey = string | number | Date | BufferSource | IDBValidKey[];\nconst AUTH_DB_NAME = 'auth-client-db';\nconst OBJECT_STORE_NAME = 'ic-keyval';\n\nconst _openDbStore = async (\n dbName = AUTH_DB_NAME,\n storeName = OBJECT_STORE_NAME,\n version: number,\n) => {\n // Clear legacy stored delegations\n if (isBrowser && localStorage?.getItem(KEY_STORAGE_DELEGATION)) {\n localStorage.removeItem(KEY_STORAGE_DELEGATION);\n localStorage.removeItem(KEY_STORAGE_KEY);\n }\n return await openDB(dbName, version, {\n upgrade: database => {\n database.objectStoreNames;\n if (database.objectStoreNames.contains(storeName)) {\n database.clear(storeName);\n }\n database.createObjectStore(storeName);\n },\n });\n};\n\nasync function _getValue<T>(\n db: Database,\n storeName: string,\n key: IDBValidKey,\n): Promise<T | undefined> {\n return await db.get(storeName, key);\n}\n\nasync function _setValue<T>(\n db: Database,\n storeName: string,\n key: IDBValidKey,\n value: T,\n): Promise<IDBValidKey> {\n return await db.put(storeName, value, key);\n}\n\nasync function _removeValue(db: Database, storeName: string, key: IDBValidKey): Promise<void> {\n return await db.delete(storeName, key);\n}\n\nexport type DBCreateOptions = {\n dbName?: string;\n storeName?: string;\n version?: number;\n};\n\n/**\n * Simple Key Value store\n * Defaults to `'auth-client-db'` with an object store of `'ic-keyval'`\n */\nexport class IdbKeyVal {\n /**\n * @param {DBCreateOptions} options - DBCreateOptions\n * @param {DBCreateOptions['dbName']} options.dbName name for the indexeddb database\n * @default\n * @param {DBCreateOptions['storeName']} options.storeName name for the indexeddb Data Store\n * @default\n * @param {DBCreateOptions['version']} options.version version of the database. Increment to safely upgrade\n * @constructs an {@link IdbKeyVal}\n */\n public static async create(options?: DBCreateOptions): Promise<IdbKeyVal> {\n const { dbName = AUTH_DB_NAME, storeName = OBJECT_STORE_NAME, version = DB_VERSION } = options ?? {};\n const db = await _openDbStore(dbName, storeName, version);\n return new IdbKeyVal(db, storeName);\n }\n\n // Do not use - instead prefer create\n private constructor(private _db: Database, private _storeName: string) {}\n\n /**\n * Basic setter\n * @param {IDBValidKey} key string | number | Date | BufferSource | IDBValidKey[]\n * @param value value to set\n * @returns void\n */\n public async set<T>(key: IDBValidKey, value: T) {\n return await _setValue<T>(this._db, this._storeName, key, value);\n }\n /**\n * Basic getter\n * Pass in a type T for type safety if you know the type the value will have if it is found\n * @param {IDBValidKey} key string | number | Date | BufferSource | IDBValidKey[]\n * @returns `Promise<T | null>`\n * @example\n * await get<string>('exampleKey') -> 'exampleValue'\n */\n public async get<T>(key: IDBValidKey): Promise<T | null> {\n return (await _getValue<T>(this._db, this._storeName, key)) ?? null;\n }\n\n /**\n * Remove a key\n * @param key {@link IDBValidKey}\n * @returns void\n */\n public async remove(key: IDBValidKey) {\n return await _removeValue(this._db, this._storeName, key);\n }\n}\n", "import { DBCreateOptions, IdbKeyVal } from './db';\n\nexport const KEY_STORAGE_KEY = 'identity';\nexport const KEY_STORAGE_DELEGATION = 'delegation';\nexport const KEY_VECTOR = 'iv';\n// Increment if any fields are modified\nexport const DB_VERSION = 1;\n\nexport const isBrowser = typeof window !== 'undefined';\n\nexport type StoredKey = string | CryptoKeyPair;\n\n/**\n * Interface for persisting user authentication data\n */\nexport interface AuthClientStorage {\n get(key: string): Promise<StoredKey | null>;\n\n set(key: string, value: StoredKey): Promise<void>;\n\n remove(key: string): Promise<void>;\n}\n\n/**\n * Legacy implementation of AuthClientStorage, for use where IndexedDb is not available\n */\nexport class LocalStorage implements AuthClientStorage {\n constructor(public readonly prefix = 'ic-', private readonly _localStorage?: Storage) {}\n\n public get(key: string): Promise<string | null> {\n return Promise.resolve(this._getLocalStorage().getItem(this.prefix + key));\n }\n\n public set(key: string, value: string): Promise<void> {\n this._getLocalStorage().setItem(this.prefix + key, value);\n return Promise.resolve();\n }\n\n public remove(key: string): Promise<void> {\n this._getLocalStorage().removeItem(this.prefix + key);\n return Promise.resolve();\n }\n\n private _getLocalStorage() {\n if (this._localStorage) {\n return this._localStorage;\n }\n\n const ls =\n typeof window === 'undefined'\n ? typeof global === 'undefined'\n ? typeof self === 'undefined'\n ? undefined\n : self.localStorage\n : global.localStorage\n : window.localStorage;\n\n if (!ls) {\n throw new Error('Could not find local storage.');\n }\n\n return ls;\n }\n}\n\n/**\n * IdbStorage is an interface for simple storage of string key-value pairs built on {@link IdbKeyVal}\n *\n * It replaces {@link LocalStorage}\n * @see implements {@link AuthClientStorage}\n */\nexport class IdbStorage implements AuthClientStorage {\n #options: DBCreateOptions;\n\n /**\n * @param options - DBCreateOptions\n * @param options.dbName - name for the indexeddb database\n * @param options.storeName - name for the indexeddb Data Store\n * @param options.version - version of the database. Increment to safely upgrade\n * @constructs an {@link IdbStorage}\n * @example\n * ```typescript\n * const storage = new IdbStorage({ dbName: 'my-db', storeName: 'my-store', version: 2 });\n * ```\n */\n constructor(options?: DBCreateOptions) {\n this.#options = options ?? {};\n }\n\n // Initializes a KeyVal on first request\n private initializedDb: IdbKeyVal | undefined;\n get _db(): Promise<IdbKeyVal> {\n return new Promise(resolve => {\n if (this.initializedDb) {\n resolve(this.initializedDb);\n return;\n }\n IdbKeyVal.create(this.#options).then(db => {\n this.initializedDb = db;\n resolve(db);\n });\n });\n }\n\n public async get<T = string>(key: string): Promise<T | null> {\n const db = await this._db;\n return await db.get<T>(key);\n // return (await db.get<string>(key)) ?? null;\n }\n\n public async set<T = string>(key: string, value: T): Promise<void> {\n const db = await this._db;\n await db.set(key, value);\n }\n\n public async remove(key: string): Promise<void> {\n const db = await this._db;\n await db.remove(key);\n }\n}\n", "/** @module AuthClient */\nimport {\n AnonymousIdentity,\n DerEncodedPublicKey,\n Identity,\n Signature,\n SignIdentity,\n} from '@dfinity/agent';\nimport {\n Delegation,\n DelegationChain,\n isDelegationValid,\n DelegationIdentity,\n Ed25519KeyIdentity,\n ECDSAKeyIdentity,\n PartialDelegationIdentity,\n} from '@dfinity/identity';\nimport { Principal } from '@dfinity/principal';\nimport { IdleManager, IdleManagerOptions } from './idleManager';\nimport {\n AuthClientStorage,\n IdbStorage,\n isBrowser,\n KEY_STORAGE_DELEGATION,\n KEY_STORAGE_KEY,\n KEY_VECTOR,\n LocalStorage,\n} from './storage';\nimport { PartialIdentity } from '@dfinity/identity/lib/cjs/identity/partial';\n\nexport { AuthClientStorage, IdbStorage, LocalStorage, KEY_STORAGE_DELEGATION, KEY_STORAGE_KEY } from './storage';\nexport { IdbKeyVal, DBCreateOptions } from './db';\n\nconst IDENTITY_PROVIDER_DEFAULT = 'https://identity.ic0.app';\nconst IDENTITY_PROVIDER_ENDPOINT = '#authorize';\n\nconst ECDSA_KEY_LABEL = 'ECDSA';\nconst ED25519_KEY_LABEL = 'Ed25519';\ntype BaseKeyType = typeof ECDSA_KEY_LABEL | typeof ED25519_KEY_LABEL;\n\nconst INTERRUPT_CHECK_INTERVAL = 500;\n\nexport const ERROR_USER_INTERRUPT = 'UserInterrupt';\n\n/**\n * List of options for creating an {@link AuthClient}.\n */\nexport interface AuthClientCreateOptions {\n /**\n * An identity to use as the base\n */\n identity?: SignIdentity | PartialIdentity;\n /**\n * Optional storage with get, set, and remove. Uses {@link IdbStorage} by default\n */\n storage?: AuthClientStorage;\n /**\n * type to use for the base key\n * @default 'ECDSA'\n * If you are using a custom storage provider that does not support CryptoKey storage,\n * you should use 'Ed25519' as the key type, as it can serialize to a string\n */\n keyType?: BaseKeyType;\n\n /**\n * Options to handle idle timeouts\n * @default after 30 minutes, invalidates the identity\n */\n idleOptions?: IdleOptions;\n}\n\nexport interface IdleOptions extends IdleManagerOptions {\n /**\n * Disables idle functionality for {@link IdleManager}\n * @default false\n */\n disableIdle?: boolean;\n\n /**\n * Disables default idle behavior - call logout & reload window\n * @default false\n */\n disableDefaultIdleCallback?: boolean;\n}\n\nexport * from './idleManager';\n\nexport type OnSuccessFunc =\n | (() => void | Promise<void>)\n | ((message: InternetIdentityAuthResponseSuccess) => void | Promise<void>);\n\nexport type OnErrorFunc = (error?: string) => void | Promise<void>;\n\nexport interface AuthClientLoginOptions {\n /**\n * Identity provider\n * @default \"https://identity.ic0.app\"\n */\n identityProvider?: string | URL;\n /**\n * Expiration of the authentication in nanoseconds\n * @default BigInt(8) hours * BigInt(3_600_000_000_000) nanoseconds\n */\n maxTimeToLive?: bigint;\n /**\n * If present, indicates whether or not the Identity Provider should allow the user to authenticate and/or register using a temporary key/PIN identity. Authenticating dapps may want to prevent users from using Temporary keys/PIN identities because Temporary keys/PIN identities are less secure than Passkeys (webauthn credentials) and because Temporary keys/PIN identities generally only live in a browser database (which may get cleared by the browser/OS).\n */\n allowPinAuthentication?: boolean;\n /**\n * Origin for Identity Provider to use while generating the delegated identity. For II, the derivation origin must authorize this origin by setting a record at `<derivation-origin>/.well-known/ii-alternative-origins`.\n * @see https://github.com/dfinity/internet-identity/blob/main/docs/internet-identity-spec.adoc\n */\n derivationOrigin?: string | URL;\n /**\n * Auth Window feature config string\n * @example \"toolbar=0,location=0,menubar=0,width=500,height=500,left=100,top=100\"\n */\n windowOpenerFeatures?: string;\n /**\n * Callback once login has completed\n */\n onSuccess?: OnSuccessFunc;\n /**\n * Callback in case authentication fails\n */\n onError?: OnErrorFunc;\n /**\n * Extra values to be passed in the login request during the authorize-ready phase\n */\n customValues?: Record<string, unknown>;\n}\n\ninterface InternetIdentityAuthRequest {\n kind: 'authorize-client';\n sessionPublicKey: Uint8Array;\n maxTimeToLive?: bigint;\n allowPinAuthentication?: boolean;\n derivationOrigin?: string;\n}\n\nexport interface InternetIdentityAuthResponseSuccess {\n kind: 'authorize-client-success';\n delegations: {\n delegation: {\n pubkey: Uint8Array;\n expiration: bigint;\n targets?: Principal[];\n };\n signature: Uint8Array;\n }[];\n userPublicKey: Uint8Array;\n authnMethod: 'passkey' | 'pin' | 'recovery';\n}\n\ninterface AuthReadyMessage {\n kind: 'authorize-ready';\n}\n\ninterface AuthResponseSuccess {\n kind: 'authorize-client-success';\n delegations: {\n delegation: {\n pubkey: Uint8Array;\n expiration: bigint;\n targets?: Principal[];\n };\n signature: Uint8Array;\n }[];\n userPublicKey: Uint8Array;\n authnMethod: 'passkey' | 'pin' | 'recovery';\n}\n\ninterface AuthResponseFailure {\n kind: 'authorize-client-failure';\n text: string;\n}\n\ntype IdentityServiceResponseMessage = AuthReadyMessage | AuthResponse;\ntype AuthResponse = AuthResponseSuccess | AuthResponseFailure;\n\n/**\n * Tool to manage authentication and identity\n * @see {@link AuthClient}\n */\nexport class AuthClient {\n /**\n * Create an AuthClient to manage authentication and identity\n * @constructs\n * @param {AuthClientCreateOptions} options - Options for creating an {@link AuthClient}\n * @see {@link AuthClientCreateOptions}\n * @param options.identity Optional Identity to use as the base\n * @see {@link SignIdentity}\n * @param options.storage Storage mechanism for delegration credentials\n * @see {@link AuthClientStorage}\n * @param options.keyType Type of key to use for the base key\n * @param {IdleOptions} options.idleOptions Configures an {@link IdleManager}\n * @see {@link IdleOptions}\n * Default behavior is to clear stored identity and reload the page when a user goes idle, unless you set the disableDefaultIdleCallback flag or pass in a custom idle callback.\n * @example\n * const authClient = await AuthClient.create({\n * idleOptions: {\n * disableIdle: true\n * }\n * })\n */\n public static async create(\n options: {\n /**\n * An {@link SignIdentity} or {@link PartialIdentity} to authenticate via delegation.\n */\n identity?: SignIdentity | PartialIdentity;\n /**\n * {@link AuthClientStorage}\n * @description Optional storage with get, set, and remove. Uses {@link IdbStorage} by default\n */\n storage?: AuthClientStorage;\n /**\n * type to use for the base key\n * @default 'ECDSA'\n * If you are using a custom storage provider that does not support CryptoKey storage,\n * you should use 'Ed25519' as the key type, as it can serialize to a string\n */\n keyType?: BaseKeyType;\n /**\n * Options to handle idle timeouts\n * @default after 10 minutes, invalidates the identity\n */\n idleOptions?: IdleOptions;\n } = {},\n ): Promise<AuthClient> {\n const storage = options.storage ?? new IdbStorage();\n const keyType = options.keyType ?? ECDSA_KEY_LABEL;\n\n let key: null | SignIdentity | PartialIdentity = null;\n if (options.identity) {\n key = options.identity;\n } else {\n let maybeIdentityStorage = await storage.get(KEY_STORAGE_KEY);\n if (!maybeIdentityStorage && isBrowser) {\n // Attempt to migrate from localstorage\n try {\n const fallbackLocalStorage = new LocalStorage();\n const localChain = await fallbackLocalStorage.get(KEY_STORAGE_DELEGATION);\n const localKey = await fallbackLocalStorage.get(KEY_STORAGE_KEY);\n // not relevant for Ed25519\n if (localChain && localKey && keyType === ECDSA_KEY_LABEL) {\n console.log('Discovered an identity stored in localstorage. Migrating to IndexedDB');\n await storage.set(KEY_STORAGE_DELEGATION, localChain);\n await storage.set(KEY_STORAGE_KEY, localKey);\n\n maybeIdentityStorage = localChain;\n // clean up\n await fallbackLocalStorage.remove(KEY_STORAGE_DELEGATION);\n await fallbackLocalStorage.remove(KEY_STORAGE_KEY);\n }\n } catch (error) {\n console.error('error while attempting to recover localstorage: ' + error);\n }\n }\n if (maybeIdentityStorage) {\n try {\n if (typeof maybeIdentityStorage === 'object') {\n if (keyType === ED25519_KEY_LABEL && typeof maybeIdentityStorage === 'string') {\n key = await Ed25519KeyIdentity.fromJSON(maybeIdentityStorage);\n } else {\n key = await ECDSAKeyIdentity.fromKeyPair(maybeIdentityStorage);\n }\n } else if (typeof maybeIdentityStorage === 'string') {\n // This is a legacy identity, which is a serialized Ed25519KeyIdentity.\n key = Ed25519KeyIdentity.fromJSON(maybeIdentityStorage);\n }\n } catch (e) {\n // Ignore this, this means that the localStorage value isn't a valid Ed25519KeyIdentity or ECDSAKeyIdentity\n // serialization.\n }\n }\n }\n\n let identity: SignIdentity | PartialIdentity = new AnonymousIdentity() as PartialIdentity;\n let chain: null | DelegationChain = null;\n if (key) {\n try {\n const chainStorage = await storage.get(KEY_STORAGE_DELEGATION);\n if (typeof chainStorage === 'object' && chainStorage !== null) {\n throw new Error(\n 'Delegation chain is incorrectly stored. A delegation chain should be stored as a string.',\n );\n }\n\n if (options.identity) {\n identity = options.identity;\n } else if (chainStorage) {\n chain = DelegationChain.fromJSON(chainStorage);\n\n // Verify that the delegation isn't expired.\n if (!isDelegationValid(chain)) {\n await _deleteStorage(storage);\n key = null;\n } else {\n // If the key is a public key, then we create a PartialDelegationIdentity.\n if ('toDer' in key) {\n identity = PartialDelegationIdentity.fromDelegation(key, chain);\n // otherwise, we create a DelegationIdentity.\n } else {\n identity = DelegationIdentity.fromDelegation(key, chain);\n }\n }\n }\n } catch (e) {\n console.error(e);\n // If there was a problem loading the chain, delete the key.\n await _deleteStorage(storage);\n key = null;\n }\n }\n let idleManager: IdleManager | undefined = undefined;\n if (options.idleOptions?.disableIdle) {\n idleManager = undefined;\n }\n // if there is a delegation chain or provided identity, setup idleManager\n else if (chain || options.identity) {\n idleManager = IdleManager.create(options.idleOptions);\n }\n\n if (!key) {\n // Create a new key (whether or not one was in storage).\n if (keyType === ED25519_KEY_LABEL) {\n key = await Ed25519KeyIdentity.generate();\n await storage.set(KEY_STORAGE_KEY, JSON.stringify((key as Ed25519KeyIdentity).toJSON()));\n } else {\n if (options.storage && keyType === ECDSA_KEY_LABEL) {\n console.warn(\n `You are using a custom storage provider that may not support CryptoKey storage. If you are using a custom storage provider that does not support CryptoKey storage, you should use '${ED25519_KEY_LABEL}' as the key type, as it can serialize to a string`,\n );\n }\n key = await ECDSAKeyIdentity.generate();\n await storage.set(KEY_STORAGE_KEY, (key as ECDSAKeyIdentity).getKeyPair());\n }\n }\n\n return new this(identity, key, chain, storage, idleManager, options);\n }\n\n protected constructor(\n private _identity: Identity | PartialIdentity,\n private _key: SignIdentity | PartialIdentity,\n private _chain: DelegationChain | null,\n private _storage: AuthClientStorage,\n public idleManager: IdleManager | undefined,\n private _createOptions: AuthClientCreateOptions | undefined,\n // A handle on the IdP window.\n private _idpWindow?: Window,\n // The event handler for processing events from the IdP.\n private _eventHandler?: (event: MessageEvent) => void,\n ) {\n this._registerDefaultIdleCallback();\n }\n\n private _registerDefaultIdleCallback() {\n const idleOptions = this._createOptions?.idleOptions;\n /**\n * Default behavior is to clear stored identity and reload the page.\n * By either setting the disableDefaultIdleCallback flag or passing in a custom idle callback, we will ignore this config\n */\n if (!idleOptions?.onIdle && !idleOptions?.disableDefaultIdleCallback) {\n this.idleManager?.registerCallback(() => {\n this.logout();\n location.reload();\n });\n }\n }\n\n private async _handleSuccess(\n message: InternetIdentityAuthResponseSuccess,\n onSuccess?: OnSuccessFunc,\n ) {\n const delegations = message.delegations.map(signedDelegation => {\n return {\n delegation: new Delegation(\n signedDelegation.delegation.pubkey,\n signedDelegation.delegation.expiration,\n signedDelegation.delegation.targets,\n ),\n signature: signedDelegation.signature.buffer as Signature,\n };\n });\n\n const delegationChain = DelegationChain.fromDelegations(\n delegations,\n message.userPublicKey.buffer as DerEncodedPublicKey,\n );\n\n const key = this._key;\n if (!key) {\n return;\n }\n\n this._chain = delegationChain;\n\n if ('toDer' in key) {\n this._identity = PartialDelegationIdentity.fromDelegation(key, this._chain);\n } else {\n this._identity = DelegationIdentity.fromDelegation(key, this._chain);\n }\n\n this._idpWindow?.close();\n const idleOptions = this._createOptions?.idleOptions;\n // create the idle manager on a successful login if we haven't disabled it\n // and it doesn't already exist.\n if (!this.idleManager && !idleOptions?.disableIdle) {\n this.idleManager = IdleManager.create(idleOptions);\n this._registerDefaultIdleCallback();\n }\n\n this._removeEventListener();\n delete this._idpWindow;\n\n if (this._chain) {\n await this._storage.set(KEY_STORAGE_DELEGATION, JSON.stringify(this._chain.toJSON()));\n }\n\n // onSuccess should be the last thing to do to avoid consumers\n // interfering by navigating or refreshing the page\n onSuccess?.(message);\n }\n\n public getIdentity(): Identity {\n return this._identity;\n }\n\n public async isAuthenticated(): Promise<boolean> {\n return !this.getIdentity().getPrincipal().isAnonymous() && this._chain !== null;\n }\n\n /**\n * AuthClient Login -\n * Opens up a new window to authenticate with Internet Identity\n * @param {AuthClientLoginOptions} options - Options for logging in\n * @param options.identityProvider Identity provider\n * @param options.maxTimeToLive Expiration of the authentication in nanoseconds\n * @param options.allowPinAuthentication If present, indicates whether or not the Identity Provider should allow the user to authenticate and/or register using a temporary key/PIN identity. Authenticating dapps may want to prevent users from using Temporary keys/PIN identities because Temporary keys/PIN identities are less secure than Passkeys (webauthn credentials) and because Temporary keys/PIN identities generally only live in a browser database (which may get cleared by the browser/OS).\n * @param options.derivationOrigin Origin for Identity Provider to use while generating the delegated identity\n * @param options.windowOpenerFeatures Configures the opened authentication window\n * @param options.onSuccess Callback once login has completed\n * @param options.onError Callback in case authentication fails\n * @example\n * const authClient = await AuthClient.create();\n * authClient.login({\n * identityProvider: 'http://<canisterID>.127.0.0.1:8000',\n * maxTimeToLive: BigInt (7) * BigInt(24) * BigInt(3_600_000_000_000), // 1 week\n * windowOpenerFeatures: \"toolbar=0,location=0,menubar=0,width=500,height=500,left=100,top=100\",\n * onSuccess: () => {\n * console.log('Login Successful!');\n * },\n * onError: (error) => {\n * console.error('Login Failed: ', error);\n * }\n * });\n */\n public async login(options?: AuthClientLoginOptions): Promise<void> {\n // Set default maxTimeToLive to 8 hours\n const defaultTimeToLive = /* hours */ BigInt(8) * /* nanoseconds */ BigInt(3_600_000_000_000);\n\n // Create the URL of the IDP. (e.g. https://XXXX/#authorize)\n const identityProviderUrl = new URL(\n options?.identityProvider?.toString() || IDENTITY_PROVIDER_DEFAULT,\n );\n // Set the correct hash if it isn't already set.\n identityProviderUrl.hash = IDENTITY_PROVIDER_ENDPOINT;\n\n // If `login` has been called previously, then close/remove any previous windows\n // and event listeners.\n this._idpWindow?.close();\n this._removeEventListener();\n\n // Add an event listener to handle responses.\n this._eventHandler = this._getEventHandler(identityProviderUrl, {\n maxTimeToLive: options?.maxTimeToLive ?? defaultTimeToLive,\n ...options,\n });\n window.addEventListener('message', this._eventHandler);\n\n // Open a new window with the IDP provider.\n this._idpWindow =\n window.open(identityProviderUrl.toString(), 'idpWindow', options?.windowOpenerFeatures) ??\n undefined;\n\n // Check if the _idpWindow is closed by user.\n const checkInterruption = (): void => {\n // The _idpWindow is opened and not yet closed by the client\n if (this._idpWindow) {\n if (this._idpWindow.closed) {\n this._handleFailure(ERROR_USER_INTERRUPT, options?.onError);\n } else {\n setTimeout(checkInterruption, INTERRUPT_CHECK_INTERVAL);\n }\n }\n };\n checkInterruption();\n }\n\n private _getEventHandler(identityProviderUrl: URL, options?: AuthClientLoginOptions) {\n return async (event: MessageEvent) => {\n if (event.origin !== identityProviderUrl.origin) {\n console.warn(\n `WARNING: expected origin '${identityProviderUrl.origin}', got '${event.origin}' (ignoring)`,\n );\n return;\n }\n\n const message = event.data as IdentityServiceResponseMessage;\n\n switch (message.kind) {\n case 'authorize-ready': {\n // IDP is ready. Send a message to request authorization.\n const request: InternetIdentityAuthRequest = {\n kind: 'authorize-client',\n sessionPublicKey: new Uint8Array(this._key?.getPublicKey().toDer() as ArrayBuffer),\n maxTimeToLive: options?.maxTimeToLive,\n allowPinAuthentication: options?.allowPinAuthentication,\n derivationOrigin: options?.derivationOrigin?.toString(),\n // Pass any custom values to the IDP.\n ...options?.customValues,\n };\n this._idpWindow?.postMessage(request, identityProviderUrl.origin);\n break;\n }\n case 'authorize-client-success':\n // Create the delegation chain and store it.\n try {\n await this._handleSuccess(message, options?.onSuccess);\n } catch (err) {\n this._handleFailure((err as Error).message, options?.onError);\n }\n break;\n case 'authorize-client-failure':\n this._handleFailure(message.text, options?.onError);\n break;\n default:\n break;\n }\n };\n }\n\n private _handleFailure(errorMessage?: string, onError?: (error?: string) => void): void {\n this._idpWindow?.close();\n onError?.(errorMessage);\n this._removeEventListener();\n delete this._idpWindow;\n }\n\n private _removeEventListener() {\n if (this._eventHandler) {\n window.removeEventListener('message', this._eventHandler);\n }\n this._eventHandler = undefined;\n }\n\n public async logout(options: { returnTo?: string } = {}): Promise<void> {\n await _deleteStorage(this._storage);\n\n // Reset this auth client to a non-authenticated state.\n this._identity = new AnonymousIdentity();\n this._chain = null;\n\n if (options.returnTo) {\n try {\n window.history.pushState({}, '', options.returnTo);\n } catch (e) {\n window.location.href = options.returnTo;\n }\n }\n }\n}\n\nasync function _deleteStorage(storage: AuthClientStorage) {\n await storage.remove(KEY_STORAGE_KEY);\n await storage.remove(KEY_STORAGE_DELEGATION);\n await storage.remove(KEY_VECTOR);\n}\n", "import {AuthClient} from '@dfinity/auth-client';\n\nexport const createAuthClient = (): Promise<AuthClient> =>\n AuthClient.create({\n idleOptions: {\n disableIdle: true,\n disableDefaultIdleCallback: true\n }\n });\n", "import {fromArray} from '@junobuild/utils';\nimport type {Doc} from '../../declarations/satellite/satellite.did';\n\nexport const mapData = async <D>({data}: Pick<Doc, 'data'>): Promise<D> => {\n try {\n return await fromArray<D>(data);\n } catch (err: unknown) {\n console.error('The data parsing has failed, mapping to undefined as a fallback.', err);\n return undefined as D;\n }\n};\n", "import {fromArray, fromNullable, toArray, toNullable} from '@junobuild/utils';\nimport type {DelDoc, Doc as DocApi, SetDoc} from '../../declarations/satellite/satellite.did';\nimport type {Doc} from '../types/doc.types';\n\nexport const toSetDoc = async <D>(doc: Doc<D>): Promise<SetDoc> => {\n const {data, version, description} = doc;\n\n return {\n description: toNullable(description),\n data: await toArray<D>(data),\n version: toNullable(version)\n };\n};\n\nexport const toDelDoc = <D>(doc: Doc<D>): DelDoc => {\n const {version} = doc;\n\n return {\n version: toNullable(version)\n };\n};\n\nexport const fromDoc = async <D>({doc, key}: {doc: DocApi; key: string}): Promise<Doc<D>> => {\n const {owner, version, description: docDescription, data, ...rest} = doc;\n\n return {\n key,\n description: fromNullable(docDescription),\n owner: owner.toText(),\n data: await fromArray<D>(data),\n version: fromNullable(version),\n ...rest\n };\n};\n", "import {Principal} from '@dfinity/principal';\nimport {isNullish, toNullable} from '@junobuild/utils';\nimport type {\n ListParams as ListParamsApi,\n TimestampMatcher\n} from '../../declarations/satellite/satellite.did';\nimport type {ListParams, ListTimestampMatcher} from '../types/list.types';\n\nconst toListMatcherTimestamp = (matcher?: ListTimestampMatcher): [] | [TimestampMatcher] => {\n if (isNullish(matcher)) {\n return toNullable();\n }\n\n switch (matcher.matcher) {\n case 'equal':\n return toNullable({Equal: matcher.timestamp});\n case 'greaterThan':\n return toNullable({GreaterThan: matcher.timestamp});\n case 'lessThan':\n return toNullable({LessThan: matcher.timestamp});\n case 'between':\n return toNullable({Between: [matcher.timestamps.start, matcher.timestamps.end]});\n default:\n throw new Error('Invalid list matcher for timestamp', matcher);\n }\n};\n\nexport const toListParams = ({matcher, paginate, order, owner}: ListParams): ListParamsApi => ({\n matcher: isNullish(matcher)\n ? []\n : [\n {\n key: toNullable(matcher.key),\n description: toNullable(matcher.description),\n created_at: toListMatcherTimestamp(matcher.createdAt),\n updated_at: toListMatcherTimestamp(matcher.updatedAt)\n }\n ],\n paginate: toNullable(\n isNullish(paginate)\n ? undefined\n : {\n start_after: toNullable(paginate.startAfter),\n limit: toNullable(isNullish(paginate.limit) ? undefined : BigInt(paginate.limit))\n }\n ),\n order: toNullable(\n isNullish(order)\n ? undefined\n : {\n desc: order.desc,\n field:\n order.field === 'created_at'\n ? {CreatedAt: null}\n : order.field === 'updated_at'\n ? {UpdatedAt: null}\n : {Keys: null}\n }\n ),\n owner: toNullable(\n isNullish(owner) ? undefined : typeof owner === 'string' ? Principal.fromText(owner) : owner\n )\n});\n", "// @ts-ignore\nexport const idlFactory = ({IDL}) => {\n const CommitBatch = IDL.Record({\n batch_id: IDL.Nat,\n headers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n chunk_ids: IDL.Vec(IDL.Nat)\n });\n const ListOrderField = IDL.Variant({\n UpdatedAt: IDL.Null,\n Keys: IDL.Null,\n CreatedAt: IDL.Null\n });\n const ListOrder = IDL.Record({field: ListOrderField, desc: IDL.Bool});\n const TimestampMatcher = IDL.Variant({\n Equal: IDL.Nat64,\n Between: IDL.Tuple(IDL.Nat64, IDL.Nat64),\n GreaterThan: IDL.Nat64,\n LessThan: IDL.Nat64\n });\n const ListMatcher = IDL.Record({\n key: IDL.Opt(IDL.Text),\n updated_at: IDL.Opt(TimestampMatcher),\n description: IDL.Opt(IDL.Text),\n created_at: IDL.Opt(TimestampMatcher)\n });\n const ListPaginate = IDL.Record({\n start_after: IDL.Opt(IDL.Text),\n limit: IDL.Opt(IDL.Nat64)\n });\n const ListParams = IDL.Record({\n order: IDL.Opt(ListOrder),\n owner: IDL.Opt(IDL.Principal),\n matcher: IDL.Opt(ListMatcher),\n paginate: IDL.Opt(ListPaginate)\n });\n const DeleteControllersArgs = IDL.Record({\n controllers: IDL.Vec(IDL.Principal)\n });\n const ControllerScope = IDL.Variant({\n Write: IDL.Null,\n Admin: IDL.Null\n });\n const Controller = IDL.Record({\n updated_at: IDL.Nat64,\n metadata: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n created_at: IDL.Nat64,\n scope: ControllerScope,\n expires_at: IDL.Opt(IDL.Nat64)\n });\n const DelDoc = IDL.Record({version: IDL.Opt(IDL.Nat64)});\n const RulesType = IDL.Variant({Db: IDL.Null, Storage: IDL.Null});\n const DelRule = IDL.Record({version: IDL.Opt(IDL.Nat64)});\n const DepositCyclesArgs = IDL.Record({\n cycles: IDL.Nat,\n destination_id: IDL.Principal\n });\n const AssetKey = IDL.Record({\n token: IDL.Opt(IDL.Text),\n collection: IDL.Text,\n owner: IDL.Principal,\n name: IDL.Text,\n description: IDL.Opt(IDL.Text),\n full_path: IDL.Text\n });\n const AssetEncodingNoContent = IDL.Record({\n modified: IDL.Nat64,\n sha256: IDL.Vec(IDL.Nat8),\n total_length: IDL.Nat\n });\n const AssetNoContent = IDL.Record({\n key: AssetKey,\n updated_at: IDL.Nat64,\n encodings: IDL.Vec(IDL.Tuple(IDL.Text, AssetEncodingNoContent)),\n headers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n created_at: IDL.Nat64,\n version: IDL.Opt(IDL.Nat64)\n });\n const AuthenticationConfigInternetIdentity = IDL.Record({\n derivation_origin: IDL.Opt(IDL.Text)\n });\n const AuthenticationConfig = IDL.Record({\n internet_identity: IDL.Opt(AuthenticationConfigInternetIdentity)\n });\n const ConfigMaxMemorySize = IDL.Record({\n stable: IDL.Opt(IDL.Nat64),\n heap: IDL.Opt(IDL.Nat64)\n });\n const DbConfig = IDL.Record({\n max_memory_size: IDL.Opt(ConfigMaxMemorySize)\n });\n const StorageConfigIFrame = IDL.Variant({\n Deny: IDL.Null,\n AllowAny: IDL.Null,\n SameOrigin: IDL.Null\n });\n const StorageConfigRawAccess = IDL.Variant({\n Deny: IDL.Null,\n Allow: IDL.Null\n });\n const StorageConfigRedirect = IDL.Record({\n status_code: IDL.Nat16,\n location: IDL.Text\n });\n const StorageConfig = IDL.Record({\n iframe: IDL.Opt(StorageConfigIFrame),\n rewrites: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n headers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)))),\n max_memory_size: IDL.Opt(ConfigMaxMemorySize),\n raw_access: IDL.Opt(StorageConfigRawAccess),\n redirects: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, StorageConfigRedirect)))\n });\n const Config = IDL.Record({\n db: IDL.Opt(DbConfig),\n authentication: IDL.Opt(AuthenticationConfig),\n storage: StorageConfig\n });\n const Doc = IDL.Record({\n updated_at: IDL.Nat64,\n owner: IDL.Principal,\n data: IDL.Vec(IDL.Nat8),\n description: IDL.Opt(IDL.Text),\n created_at: IDL.Nat64,\n version: IDL.Opt(IDL.Nat64)\n });\n const HttpRequest = IDL.Record({\n url: IDL.Text,\n method: IDL.Text,\n body: IDL.Vec(IDL.Nat8),\n headers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n certificate_version: IDL.Opt(IDL.Nat16)\n });\n const Memory = IDL.Variant({Heap: IDL.Null, Stable: IDL.Null});\n const StreamingCallbackToken = IDL.Record({\n memory: Memory,\n token: IDL.Opt(IDL.Text),\n sha256: IDL.Opt(IDL.Vec(IDL.Nat8)),\n headers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n index: IDL.Nat64,\n encoding_type: IDL.Text,\n full_path: IDL.Text\n });\n const StreamingStrategy = IDL.Variant({\n Callback: IDL.Record({\n token: StreamingCallbackToken,\n callback: IDL.Func([], [], ['query'])\n })\n });\n const HttpResponse = IDL.Record({\n body: IDL.Vec(IDL.Nat8),\n headers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n streaming_strategy: IDL.Opt(StreamingStrategy),\n status_code: IDL.Nat16\n });\n const StreamingCallbackHttpResponse = IDL.Record({\n token: IDL.Opt(StreamingCallbackToken),\n body: IDL.Vec(IDL.Nat8)\n });\n const InitAssetKey = IDL.Record({\n token: IDL.Opt(IDL.Text),\n collection: IDL.Text,\n name: IDL.Text,\n description: IDL.Opt(IDL.Text),\n encoding_type: IDL.Opt(IDL.Text),\n full_path: IDL.Text\n });\n const InitUploadResult = IDL.Record({batch_id: IDL.Nat});\n const ListResults = IDL.Record({\n matches_pages: IDL.Opt(IDL.Nat64),\n matches_length: IDL.Nat64,\n items_page: IDL.Opt(IDL.Nat64),\n items: IDL.Vec(IDL.Tuple(IDL.Text, AssetNoContent)),\n items_length: IDL.Nat64\n });\n const CustomDomain = IDL.Record({\n updated_at: IDL.Nat64,\n created_at: IDL.Nat64,\n version: IDL.Opt(IDL.Nat64),\n bn_id: IDL.Opt(IDL.Text)\n });\n const ListResults_1 = IDL.Record({\n matches_pages: IDL.Opt(IDL.Nat64),\n matches_length: IDL.Nat64,\n items_page: IDL.Opt(IDL.Nat64),\n items: IDL.Vec(IDL.Tuple(IDL.Text, Doc)),\n items_length: IDL.Nat64\n });\n const Permission = IDL.Variant({\n Controllers: IDL.Null,\n Private: IDL.Null,\n Public: IDL.Null,\n Managed: IDL.Null\n });\n const Rule = IDL.Record({\n max_capacity: IDL.Opt(IDL.Nat32),\n memory: IDL.Opt(Memory),\n updated_at: IDL.Nat64,\n max_size: IDL.Opt(IDL.Nat),\n read: Permission,\n created_at: IDL.Nat64,\n version: IDL.Opt(IDL.Nat64),\n mutable_permissions: IDL.Opt(IDL.Bool),\n write: Permission\n });\n const MemorySize = IDL.Record({stable: IDL.Nat64, heap: IDL.Nat64});\n const SetController = IDL.Record({\n metadata: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n scope: ControllerScope,\n expires_at: IDL.Opt(IDL.Nat64)\n });\n const SetControllersArgs = IDL.Record({\n controller: SetController,\n controllers: IDL.Vec(IDL.Principal)\n });\n const SetDoc = IDL.Record({\n data: IDL.Vec(IDL.Nat8),\n description: IDL.Opt(IDL.Text),\n version: IDL.Opt(IDL.Nat64)\n });\n const SetRule = IDL.Record({\n max_capacity: IDL.Opt(IDL.Nat32),\n memory: IDL.Opt(Memory),\n max_size: IDL.Opt(IDL.Nat),\n read: Permission,\n version: IDL.Opt(IDL.Nat64),\n mutable_permissions: IDL.Opt(IDL.Bool),\n write: Permission\n });\n const UploadChunk = IDL.Record({\n content: IDL.Vec(IDL.Nat8),\n batch_id: IDL.Nat,\n order_id: IDL.Opt(IDL.Nat)\n });\n const UploadChunkResult = IDL.Record({chunk_id: IDL.Nat});\n return IDL.Service({\n build_version: IDL.Func([], [IDL.Text], ['query']),\n commit_asset_upload: IDL.Func([CommitBatch], [], []),\n count_assets: IDL.Func([IDL.Text, ListParams], [IDL.Nat64], ['query']),\n count_collection_assets: IDL.Func([IDL.Text], [IDL.Nat64], ['query']),\n count_collection_docs: IDL.Func([IDL.Text], [IDL.Nat64], ['query']),\n count_docs: IDL.Func([IDL.Text, ListParams], [IDL.Nat64], ['query']),\n del_asset: IDL.Func([IDL.Text, IDL.Text], [], []),\n del_assets: IDL.Func([IDL.Text], [], []),\n del_controllers: IDL.Func(\n [DeleteControllersArgs],\n [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))],\n []\n ),\n del_custom_domain: IDL.Func([IDL.Text], [], []),\n del_doc: IDL.Func([IDL.Text, IDL.Text, DelDoc], [], []),\n del_docs: IDL.Func([IDL.Text], [], []),\n del_many_assets: IDL.Func([IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))], [], []),\n del_many_docs: IDL.Func([IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text, DelDoc))], [], []),\n del_rule: IDL.Func([RulesType, IDL.Text, DelRule], [], []),\n deposit_cycles: IDL.Func([DepositCyclesArgs], [], []),\n get_asset: IDL.Func([IDL.Text, IDL.Text], [IDL.Opt(AssetNoContent)], ['query']),\n get_auth_config: IDL.Func([], [IDL.Opt(AuthenticationConfig)], ['query']),\n get_config: IDL.Func([], [Config], []),\n get_db_config: IDL.Func([], [IDL.Opt(DbConfig)], ['query']),\n get_doc: IDL.Func([IDL.Text, IDL.Text], [IDL.Opt(Doc)], ['query']),\n get_many_assets: IDL.Func(\n [IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))],\n [IDL.Vec(IDL.Tuple(IDL.Text, IDL.Opt(AssetNoContent)))],\n ['query']\n ),\n get_many_docs: IDL.Func(\n [IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))],\n [IDL.Vec(IDL.Tuple(IDL.Text, IDL.Opt(Doc)))],\n ['query']\n ),\n get_storage_config: IDL.Func([], [StorageConfig], ['query']),\n http_request: IDL.Func([HttpRequest], [HttpResponse], ['query']),\n http_request_streaming_callback: IDL.Func(\n [StreamingCallbackToken],\n [StreamingCallbackHttpResponse],\n ['query']\n ),\n init_asset_upload: IDL.Func([InitAssetKey], [InitUploadResult], []),\n list_assets: IDL.Func([IDL.Text, ListParams], [ListResults], ['query']),\n list_controllers: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))], ['query']),\n list_custom_domains: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Text, CustomDomain))], ['query']),\n list_docs: IDL.Func([IDL.Text, ListParams], [ListResults_1], ['query']),\n list_rules: IDL.Func([RulesType], [IDL.Vec(IDL.Tuple(IDL.Text, Rule))], ['query']),\n memory_size: IDL.Func([], [MemorySize], ['query']),\n set_auth_config: IDL.Func([AuthenticationConfig], [], []),\n set_controllers: IDL.Func(\n [SetControllersArgs],\n [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))],\n []\n ),\n set_custom_domain: IDL.Func([IDL.Text, IDL.Opt(IDL.Text)], [], []),\n set_db_config: IDL.Func([DbConfig], [], []),\n set_doc: IDL.Func([IDL.Text, IDL.Text, SetDoc], [Doc], []),\n set_many_docs: IDL.Func(\n [IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text, SetDoc))],\n [IDL.Vec(IDL.Tuple(IDL.Text, Doc))],\n []\n ),\n set_rule: IDL.Func([RulesType, IDL.Text, SetRule], [], []),\n set_storage_config: IDL.Func([StorageConfig], [], []),\n upload_asset_chunk: IDL.Func([UploadChunk], [UploadChunkResult], []),\n version: IDL.Func([], [IDL.Text], ['query'])\n });\n};\n// @ts-ignore\nexport const init = ({IDL}) => {\n return [];\n};\n", "import type {ActorMethod, ActorSubclass} from '@dfinity/agent';\nimport {Actor, HttpAgent} from '@dfinity/agent';\nimport type {IDL} from '@dfinity/candid';\nimport {nonNullish} from '@junobuild/utils';\nimport {DOCKER_CONTAINER_URL} from '../constants/container.constants';\nimport type {Satellite} from '../types/satellite.types';\n\nexport const createActor = async <T = Record<string, ActorMethod>>({\n satelliteId: canisterId,\n idlFactory,\n identity,\n fetch,\n container\n}: {\n idlFactory: IDL.InterfaceFactory;\n} & Required<Pick<Satellite, 'satelliteId' | 'identity'>> &\n Pick<Satellite, 'fetch' | 'container'>): Promise<ActorSubclass<T>> => {\n const localActor = nonNullish(container) && container !== false;\n\n const host = localActor\n ? container === true\n ? DOCKER_CONTAINER_URL\n : container\n : 'https://icp-api.io';\n\n const shouldFetchRootKey = nonNullish(container);\n\n const agent: HttpAgent = await HttpAgent.create({\n identity,\n shouldFetchRootKey,\n host,\n ...(fetch && {fetch})\n });\n\n // Creates an actor with using the candid interface and the HttpAgent\n return Actor.createActor(idlFactory, {\n agent,\n canisterId\n });\n};\n", "import {nonNullish} from '@junobuild/utils';\nimport {DOCKER_CONTAINER_URL} from '../constants/container.constants';\nimport {EnvStore} from '../stores/env.store';\nimport type {Satellite} from '../types/satellite.types';\n\nexport const satelliteUrl = ({\n satelliteId: customSatelliteId,\n container: customContainer\n}: Satellite): string => {\n const {satelliteId} = customOrEnvSatelliteId({satelliteId: customSatelliteId});\n const {container} = customOrEnvContainer({container: customContainer});\n\n if (nonNullish(container) && container !== false) {\n const {host: containerHost, protocol} = new URL(\n container === true ? DOCKER_CONTAINER_URL : container\n );\n return `${protocol}//${satelliteId ?? 'unknown'}.${containerHost.replace('127.0.0.1', 'localhost')}`;\n }\n\n return `https://${satelliteId ?? 'unknown'}.icp0.io`;\n};\n\nexport const customOrEnvSatelliteId = ({\n satelliteId\n}: Pick<Satellite, 'satelliteId'>): Pick<Satellite, 'satelliteId'> =>\n nonNullish(satelliteId)\n ? {satelliteId}\n : (EnvStore.getInstance().get() ?? {satelliteId: undefined});\n\nexport const customOrEnvContainer = ({\n container: customContainer\n}: Pick<Satellite, 'container'>): Pick<Satellite, 'container'> =>\n nonNullish(customContainer)\n ? {container: customContainer}\n : (EnvStore.getInstance().get() ?? {container: undefined});\n", "import {assertNonNullish} from '@junobuild/utils';\nimport type {_SERVICE as SatelliteActor} from '../../declarations/satellite/satellite.did';\nimport {idlFactory} from '../../declarations/satellite/satellite.factory.did.js';\nimport type {Satellite} from '../types/satellite.types';\nimport {createActor} from '../utils/actor.utils';\nimport {customOrEnvContainer, customOrEnvSatelliteId} from '../utils/env.utils';\n\nexport const getSatelliteActor = async ({\n satelliteId: customSatelliteId,\n container: customContainer,\n ...rest\n}: Satellite): Promise<SatelliteActor> => {\n const {satelliteId} = customOrEnvSatelliteId({satelliteId: customSatelliteId});\n\n assertNonNullish(satelliteId, 'No satellite ID defined. Did you initialize Juno?');\n\n const {container} = customOrEnvContainer({container: customContainer});\n\n return createActor({\n satelliteId,\n container,\n idlFactory,\n ...rest\n });\n};\n", "import {fromNullable, isNullish, nonNullish} from '@junobuild/utils';\nimport type {DelDoc, SetDoc} from '../../declarations/satellite/satellite.did';\nimport type {Doc} from '../types/doc.types';\nimport type {ListParams, ListResults} from '../types/list.types';\nimport type {Satellite} from '../types/satellite.types';\nimport {mapData} from '../utils/data.utils';\nimport {fromDoc, toDelDoc, toSetDoc} from '../utils/doc.utils';\nimport {toListParams} from '../utils/list.utils';\nimport {getSatelliteActor} from './actor.api';\n\nexport const getDoc = async <D>({\n collection,\n key,\n satellite\n}: {\n collection: string;\n satellite: Satellite;\n} & Pick<Doc<D>, 'key'>): Promise<Doc<D> | undefined> => {\n const {get_doc} = await getSatelliteActor(satellite);\n\n const doc = fromNullable(await get_doc(collection, key));\n\n if (isNullish(doc)) {\n return undefined;\n }\n\n return fromDoc({doc, key});\n};\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport const getManyDocs = async ({\n docs,\n satellite\n}: {\n docs: ({collection: string} & Pick<Doc<any>, 'key'>)[];\n satellite: Satellite;\n}): Promise<(Doc<any> | undefined)[]> => {\n const {get_many_docs} = await getSatelliteActor(satellite);\n\n const payload: [string, string][] = docs.map(({collection, key}) => [collection, key]);\n\n const resultsDocs = await get_many_docs(payload);\n\n const results: (Doc<any> | undefined)[] = [];\n for (const [key, resultDoc] of resultsDocs) {\n const doc = fromNullable(resultDoc);\n results.push(nonNullish(doc) ? await fromDoc({key, doc}) : undefined);\n }\n\n return results;\n};\n/* eslint-enable */\n\nexport const setDoc = async <D>({\n collection,\n doc,\n satellite\n}: {\n collection: string;\n doc: Doc<D>;\n satellite: Satellite;\n}): Promise<Doc<D>> => {\n const {set_doc} = await getSatelliteActor(satellite);\n\n const {key} = doc;\n\n const setDoc = await toSetDoc(doc);\n\n const updatedDoc = await set_doc(collection, key, setDoc);\n\n return await fromDoc({key, doc: updatedDoc});\n};\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport const setManyDocs = async ({\n docs,\n satellite\n}: {\n docs: {collection: string; doc: Doc<any>}[];\n satellite: Satellite;\n}): Promise<Doc<any>[]> => {\n const {set_many_docs} = await getSatelliteActor(satellite);\n\n const payload: [string, string, SetDoc][] = [];\n for (const {collection, doc} of docs) {\n const {key} = doc;\n payload.push([collection, key, await toSetDoc(doc)]);\n }\n\n const updatedDocs = await set_many_docs(payload);\n\n const results: Doc<any>[] = [];\n for (const [key, updatedDoc] of updatedDocs) {\n results.push(await fromDoc({key, doc: updatedDoc}));\n }\n\n return results;\n};\n/* eslint-enable */\n\nexport const deleteDoc = async <D>({\n collection,\n doc,\n satellite\n}: {\n collection: string;\n doc: Doc<D>;\n satellite: Satellite;\n}): Promise<void> => {\n const {del_doc} = await getSatelliteActor(satellite);\n\n const {key} = doc;\n\n return del_doc(collection, key, toDelDoc(doc));\n};\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport const deleteManyDocs = async ({\n docs,\n satellite\n}: {\n docs: {collection: string; doc: Doc<any>}[];\n satellite: Satellite;\n}): Promise<void> => {\n const {del_many_docs} = await getSatelliteActor(satellite);\n\n const payload: [string, string, DelDoc][] = docs.map(({collection, doc}) => [\n collection,\n doc.key,\n toDelDoc(doc)\n ]);\n\n await del_many_docs(payload);\n};\n/* eslint-enable */\n\nexport const listDocs = async <D>({\n collection,\n filter,\n satellite\n}: {\n collection: string;\n filter: ListParams;\n satellite: Satellite;\n}): Promise<ListResults<Doc<D>>> => {\n const {list_docs} = await getSatelliteActor(satellite);\n\n const {items, items_page, items_length, matches_length, matches_pages} = await list_docs(\n collection,\n toListParams(filter)\n );\n\n const docs: Doc<D>[] = [];\n\n for (const [key, item] of items) {\n const {data: dataArray, owner, description, version, ...rest} = item;\n\n docs.push({\n key,\n description: fromNullable(description),\n owner: owner.toText(),\n data: await mapData<D>({data: dataArray}),\n version: fromNullable(version),\n ...rest\n });\n }\n\n return {\n items: docs,\n items_length,\n items_page: fromNullable(items_page),\n matches_length,\n matches_pages: fromNullable(matches_pages)\n };\n};\n\nexport const countDocs = async ({\n collection,\n filter,\n satellite\n}: {\n collection: string;\n filter: ListParams;\n satellite: Satellite;\n}): Promise<bigint> => {\n const {count_docs} = await getSatelliteActor(satellite);\n\n return count_docs(collection, toListParams(filter));\n};\n", "import type {Identity} from '@dfinity/agent';\nimport {AnonymousIdentity} from '@dfinity/agent';\nimport {getIdentity as getAuthIdentity} from './auth.services';\n\nexport const getIdentity = (identity?: Identity): Identity => {\n if (identity !== undefined) {\n return identity;\n }\n\n const authIdentity: Identity | undefined = getAuthIdentity();\n\n return authIdentity ?? new AnonymousIdentity();\n};\n", "import {\n countDocs as countDocsApi,\n deleteDoc as deleteDocApi,\n deleteManyDocs as deleteManyDocsApi,\n getDoc as getDocApi,\n getManyDocs as getManyDocsApi,\n listDocs as listDocsApi,\n setDoc as setDocApi,\n setManyDocs as setManyDocsApi\n} from '../api/doc.api';\nimport type {Doc} from '../types/doc.types';\nimport type {ListParams, ListResults} from '../types/list.types';\nimport type {SatelliteOptions} from '../types/satellite.types';\nimport {getIdentity} from './identity.services';\n\n/**\n * Retrieves a single document from a collection.\n * @template D\n * @param {Object} params - The parameters for retrieving the document.\n * @param {string} params.collection - The name of the collection.\n * @param {SatelliteOptions} [params.satellite] - Options for the satellite (useful for NodeJS usage only).\n * @param {string} params.key - The key of the document to retrieve.\n * @returns {Promise<Doc<D> | undefined>} A promise that resolves to the document or undefined if not found.\n */\nexport const getDoc = async <D>({\n satellite,\n ...rest\n}: {\n collection: string;\n satellite?: SatelliteOptions;\n} & Pick<Doc<D>, 'key'>): Promise<Doc<D> | undefined> => {\n const identity = getIdentity(satellite?.identity);\n\n return getDocApi({...rest, satellite: {...satellite, identity}});\n};\n\n/**\n * Retrieves multiple documents from a single or different collections in a single call.\n * @param {Object} params - The parameters for retrieving the documents.\n * @param {Array} params.docs - The list of documents with their collections and keys.\n * @param {SatelliteOptions} [params.satellite] - Options for the satellite (useful for NodeJS usage only).\n * @returns {Promise<Array<Doc<any> | undefined>>} A promise that resolves to an array of documents or undefined if not found.\n */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport const getManyDocs = async ({\n satellite,\n ...rest\n}: {\n docs: ({collection: string} & Pick<Doc<any>, 'key'>)[];\n satellite?: SatelliteOptions;\n}): Promise<(Doc<any> | undefined)[]> => {\n const identity = getIdentity(satellite?.identity);\n\n return getManyDocsApi({...rest, satellite: {...satellite, identity}});\n};\n/* eslint-enable */\n\n/**\n * Adds or updates a single document in a collection.\n * @template D\n * @param {Object} params - The parameters for adding or updating the document.\n * @param {string} params.collection - The name of the collection.\n * @param {Doc<D>} params.doc - The document to add or update.\n * @param {SatelliteOptions} [params.satellite] - Options for the satellite (useful for NodeJS usage only).\n * @returns {Promise<Doc<D>>} A promise that resolves to the added or updated document.\n */\nexport const setDoc = async <D>({\n satellite,\n ...rest\n}: {\n collection: string;\n doc: Doc<D>;\n satellite?: SatelliteOptions;\n}): Promise<Doc<D>> => {\n const identity = getIdentity(satellite?.identity);\n\n return setDocApi({...rest, satellite: {...satellite, identity}});\n};\n\n/**\n * Adds or updates multiple documents in a or different collections.\n * @param {Object} params - The parameters for adding or updating the documents.\n * @param {Array} params.docs - The list of documents with their collections and data.\n * @param {SatelliteOptions} [params.satellite] - Options for the satellite (useful for NodeJS usage only).\n * @returns {Promise<Array<Doc<any>>>} A promise that resolves to an array of added or updated documents.\n */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport const setManyDocs = async ({\n satellite,\n ...rest\n}: {\n docs: {collection: string; doc: Doc<any>}[];\n satellite?: SatelliteOptions;\n}): Promise<Doc<any>[]> => {\n const identity = getIdentity(satellite?.identity);\n\n return setManyDocsApi({...rest, satellite: {...satellite, identity}});\n};\n/* eslint-enable */\n\n/**\n * Deletes a single document from a collection.\n * @template D\n * @param {Object} params - The parameters for deleting the document.\n * @param {string} params.collection - The name of the collection.\n * @param {Doc<D>} params.doc - The document to delete.\n * @param {SatelliteOptions} [params.satellite] - Options for the satellite (useful for NodeJS usage only).\n * @returns {Promise<void>} A promise that resolves when the document is deleted.\n */\nexport const deleteDoc = async <D>({\n satellite,\n ...rest\n}: {\n collection: string;\n doc: Doc<D>;\n satellite?: SatelliteOptions;\n}): Promise<void> => {\n const identity = getIdentity(satellite?.identity);\n\n return deleteDocApi({...rest, satellite: {...satellite, identity}});\n};\n\n/**\n * Deletes multiple documents from a or different collections.\n * @param {Object} params - The parameters for deleting the documents.\n * @param {Array} params.docs - The list of documents with their collections and data.\n * @param {SatelliteOptions} [params.satellite] - Options for the satellite (useful for NodeJS usage only).\n * @returns {Promise<void>} A promise that resolves when the documents are deleted.\n */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport const deleteManyDocs = async ({\n satellite,\n ...rest\n}: {\n docs: {collection: string; doc: Doc<any>}[];\n satellite?: SatelliteOptions;\n}): Promise<void> => {\n const identity = getIdentity(satellite?.identity);\n\n return deleteManyDocsApi({...rest, satellite: {...satellite, identity}});\n};\n/* eslint-enable */\n\n/**\n * Lists documents in a collection with optional filtering.\n * @template D\n * @param {Object} params - The parameters for listing the documents.\n * @param {string} params.collection - The name of the collection.\n * @param {ListParams} [params.filter] - Optional filter parameters.\n * @param {SatelliteOptions} [params.satellite] - Options for the satellite (useful for NodeJS usage only).\n * @returns {Promise<ListResults<Doc<D>>>} A promise that resolves to the list of documents.\n */\nexport const listDocs = async <D>({\n satellite,\n filter,\n ...rest\n}: {\n collection: string;\n filter?: ListParams;\n satellite?: SatelliteOptions;\n}): Promise<ListResults<Doc<D>>> => {\n const identity = getIdentity(satellite?.identity);\n\n return listDocsApi<D>({...rest, filter: filter ?? {}, satellite: {...satellite, identity}});\n};\n\n/**\n * Counts documents in a collection with optional filtering.\n * @param {Object} params - The parameters for counting the documents.\n * @param {string} params.collection - The name of the collection.\n * @param {ListParams} [params.filter] - Optional filter parameters.\n * @param {SatelliteOptions} [params.satellite] - Options for the satellite (useful for NodeJS usage only).\n * @returns {Promise<bigint>} A promise that resolves to the count of documents as a bigint.\n */\nexport const countDocs = async ({\n satellite,\n filter,\n ...rest\n}: {\n collection: string;\n filter?: ListParams;\n satellite?: SatelliteOptions;\n}): Promise<bigint> => {\n const identity = getIdentity(satellite?.identity);\n\n return countDocsApi({...rest, filter: filter ?? {}, satellite: {...satellite, identity}});\n};\n", "import type {Identity} from '@dfinity/agent';\nimport {isNullish} from '@junobuild/utils';\nimport type {Provider, User, UserData} from '../types/auth.types';\nimport {getIdentity} from './auth.services';\nimport {getDoc, setDoc} from './doc.services';\n\nexport const initUser = async (provider?: Provider): Promise<User> => {\n const identity: Identity | undefined = getIdentity();\n\n if (isNullish(identity)) {\n throw new Error('No identity to initialize the user. Have you initialized Juno?');\n }\n\n const userId = identity.getPrincipal().toText();\n\n const user: User | undefined = await getDoc<UserData>({\n collection: `#user`,\n key: userId\n });\n\n if (isNullish(user)) {\n const newUser: User = await createUser({userId, provider});\n return newUser;\n }\n\n return user;\n};\n\nconst createUser = async ({\n userId,\n ...rest\n}: {\n userId: string;\n} & UserData): Promise<User> =>\n setDoc<UserData>({\n collection: `#user`,\n doc: {\n key: userId,\n data: rest\n }\n });\n", "import type {Identity} from '@dfinity/agent';\nimport type {AuthClient} from '@dfinity/auth-client';\nimport {\n ALLOW_PIN_AUTHENTICATION,\n DELEGATION_IDENTITY_EXPIRATION\n} from '../constants/auth.constants';\nimport {InternetIdentityProvider} from '../providers/auth.providers';\nimport {AuthStore} from '../stores/auth.store';\nimport type {Provider, SignInOptions} from '../types/auth.types';\nimport {createAuthClient} from '../utils/auth.utils';\nimport {initUser} from './user.services';\n\nlet authClient: AuthClient | undefined;\n\nexport const initAuth = async (provider?: Provider) => {\n authClient = authClient ?? (await createAuthClient());\n\n const isAuthenticated: boolean = (await authClient?.isAuthenticated()) ?? false;\n\n if (!isAuthenticated) {\n return;\n }\n\n const user = await initUser(provider);\n AuthStore.getInstance().set(user);\n};\n\n/**\n * Signs in a user with the specified options.\n * @param {SignInOptions} [options] - The options for signing in.\n * @returns {Promise<void>} A promise that resolves when the sign-in process is complete and the authenticated user is initialized.\n * @throws Will throw an error if the sign-in process fails.\n */\nexport const signIn = async (options?: SignInOptions): Promise<void> =>\n /* eslint-disable no-async-promise-executor */\n new Promise<void>(async (resolve, reject) => {\n authClient = authClient ?? (await createAuthClient());\n\n const provider = options?.provider ?? new InternetIdentityProvider({});\n\n await authClient.login({\n onSuccess: async () => {\n await initAuth(provider.id);\n resolve();\n },\n onError: (error?: string) => reject(error),\n maxTimeToLive: options?.maxTimeToLive ?? DELEGATION_IDENTITY_EXPIRATION,\n allowPinAuthentication: options?.allowPin ?? ALLOW_PIN_AUTHENTICATION,\n ...(options?.derivationOrigin !== undefined && {derivationOrigin: options.derivationOrigin}),\n ...provider.signInOptions({\n windowed: options?.windowed\n })\n });\n });\n\n/**\n * Signs out the current user.\n * @returns {Promise<void>} A promise that resolves when the sign-out process is complete.\n */\nexport const signOut = async (): Promise<void> => {\n await authClient?.logout();\n\n // Reset local object otherwise next sign in (sign in - sign out - sign in) might not work out - i.e. agent-js might not recreate the delegation or identity if not resetted\n authClient = undefined;\n\n AuthStore.getInstance().reset();\n};\n\nexport const getIdentity = (): Identity | undefined => {\n return authClient?.getIdentity();\n};\n\n/**\n * Returns the identity of a signed-in user or an anonymous identity.\n * This function is useful for loading an identity in web workers.\n * Used to imperatively get the identity. Please be certain before using it.\n * @returns {Promise<Identity>} A promise that resolves to the identity of the user or an anonymous identity.\n */\nexport const unsafeIdentity = async (): Promise<Identity> =>\n (authClient ?? (await createAuthClient())).getIdentity();\n", "import {isNullish} from '@junobuild/utils';\nimport {AuthStore} from '../stores/auth.store';\nimport type {User} from '../types/auth.types';\nimport type {EnvironmentWorker} from '../types/env.types';\nimport type {PostMessage, PostMessageDataResponseAuth} from '../types/post-message';\nimport type {Unsubscribe} from '../types/subscription.types';\nimport {emit} from '../utils/events.utils';\nimport {signOut} from './auth.services';\n\nexport const initAuthTimeoutWorker = (auth: EnvironmentWorker): Unsubscribe => {\n const workerUrl = auth === true ? './workers/auth.worker.js' : auth;\n const worker = new Worker(workerUrl);\n\n const timeoutSignOut = async () => {\n emit({message: 'junoSignOutAuthTimer'});\n await signOut();\n };\n\n worker.onmessage = async ({data}: MessageEvent<PostMessage<PostMessageDataResponseAuth>>) => {\n const {msg, data: value} = data;\n\n switch (msg) {\n case 'junoSignOutAuthTimer':\n await timeoutSignOut();\n return;\n case 'junoDelegationRemainingTime':\n emit({message: 'junoDelegationRemainingTime', detail: value?.authRemainingTime});\n return;\n }\n };\n\n return AuthStore.getInstance().subscribe((user: User | null) => {\n if (isNullish(user)) {\n worker.postMessage({msg: 'junoStopAuthTimer'});\n return;\n }\n\n worker.postMessage({msg: 'junoStartAuthTimer'});\n });\n};\n", "// TODO: duplicated because those should not be bundled in web worker. We can avoid this by transforming utils into a library of modules.\ntype ImportMeta = {env: Record<string, string> | undefined};\n\nexport const envSatelliteId = (): string | undefined => {\n const viteEnvSatelliteId = (): string | undefined =>\n typeof import.meta !== 'undefined' &&\n typeof (import.meta as unknown as ImportMeta).env !== 'undefined'\n ? ((import.meta as unknown as ImportMeta).env?.VITE_SATELLITE_ID ??\n (import.meta as unknown as ImportMeta).env?.PUBLIC_SATELLITE_ID)\n : undefined;\n\n return typeof process !== 'undefined'\n ? (process.env?.NEXT_PUBLIC_SATELLITE_ID ?? viteEnvSatelliteId())\n : viteEnvSatelliteId();\n};\n\nexport const envContainer = (): string | undefined => {\n const viteEnvContainer = (): string | undefined =>\n typeof import.meta !== 'undefined' &&\n typeof (import.meta as unknown as ImportMeta).env !== 'undefined'\n ? ((import.meta as unknown as ImportMeta).env?.VITE_CONTAINER ??\n (import.meta as unknown as ImportMeta).env?.PUBLIC_CONTAINER)\n : undefined;\n\n return typeof process !== 'undefined'\n ? (process.env?.NEXT_PUBLIC_CONTAINER ?? viteEnvContainer())\n : viteEnvContainer();\n};\n", "/**\n * Creates a debounced function that delays invoking the provided function until after the specified timeout.\n * @param {Function} func - The function to debounce.\n * @param {number} [timeout=300] - The number of milliseconds to delay. Defaults to 300ms if not specified or invalid.\n * @returns {Function} A debounced function.\n */\n/* eslint-disable-next-line @typescript-eslint/ban-types */\nexport const debounce = (func: Function, timeout?: number): Function => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n return (...args: unknown[]) => {\n const next = () => func(...args);\n\n if (timer) {\n clearTimeout(timer);\n }\n\n timer = setTimeout(next, timeout !== undefined && timeout > 0 ? timeout : 300);\n };\n};\n", "import {Principal} from '@dfinity/principal';\nimport {nonNullish} from './null.utils';\n\nconst JSON_KEY_BIGINT = '__bigint__';\nconst JSON_KEY_PRINCIPAL = '__principal__';\nconst JSON_KEY_UINT8ARRAY = '__uint8array__';\n\n/**\n * A function that alters the behavior of the stringification process for BigInt, Principal, and Uint8Array.\n * @param {string} _key - The key of the value being stringified.\n * @param {unknown} value - The value being stringified.\n * @returns {unknown} The altered value for stringification.\n */\nexport const jsonReplacer = (_key: string, value: unknown): unknown => {\n if (typeof value === 'bigint') {\n return {[JSON_KEY_BIGINT]: `${value}`};\n }\n\n if (nonNullish(value) && value instanceof Principal) {\n return {[JSON_KEY_PRINCIPAL]: value.toText()};\n }\n\n if (nonNullish(value) && value instanceof Uint8Array) {\n return {[JSON_KEY_UINT8ARRAY]: Array.from(value)};\n }\n\n return value;\n};\n\n/**\n * A parser that interprets revived BigInt, Principal, and Uint8Array when constructing JavaScript values or objects.\n * @param {string} _key - The key of the value being parsed.\n * @param {unknown} value - The value being parsed.\n * @returns {unknown} The parsed value.\n */\nexport const jsonReviver = (_key: string, value: unknown): unknown => {\n const mapValue = <T>(key: string): T => (value as Record<string, T>)[key];\n\n if (nonNullish(value) && typeof value === 'object' && JSON_KEY_BIGINT in value) {\n return BigInt(mapValue(JSON_KEY_BIGINT));\n }\n\n if (nonNullish(value) && typeof value === 'object' && JSON_KEY_PRINCIPAL in value) {\n return Principal.fromText(mapValue(JSON_KEY_PRINCIPAL));\n }\n\n if (nonNullish(value) && typeof value === 'object' && JSON_KEY_UINT8ARRAY in value) {\n return Uint8Array.from(mapValue(JSON_KEY_UINT8ARRAY));\n }\n\n return value;\n};\n", "/**\n * Checks if the provided argument is null or undefined.\n * @template T\n * @param {T | undefined | null} argument - The argument to check.\n * @returns {boolean} True if the argument is null or undefined, false otherwise.\n */\nexport const isNullish = <T>(argument: T | undefined | null): argument is undefined | null =>\n argument === null || argument === undefined;\n\n/**\n * Checks if the provided argument is neither null nor undefined.\n * @template T\n * @param {T | undefined | null} argument - The argument to check.\n * @returns {boolean} True if the argument is neither null nor undefined, false otherwise.\n */\nexport const nonNullish = <T>(argument: T | undefined | null): argument is NonNullable<T> =>\n !isNullish(argument);\n\n/**\n * Represents an error thrown when a value is null or undefined.\n * @class\n * @extends {Error}\n */\nexport class NullishError extends Error {}\n\n/**\n * Asserts that a value is neither null nor undefined.\n * @template T\n * @param {T} value - The value to check.\n * @param {string} [message] - The optional error message to use if the assertion fails.\n * @throws {NullishError} If the value is null or undefined.\n * @returns {asserts value is NonNullable<T>} Asserts that the value is neither null nor undefined.\n */\nexport const assertNonNullish: <T>(\n value: T,\n message?: string\n) => asserts value is NonNullable<T> = <T>(value: T, message?: string): void => {\n if (isNullish(value)) {\n throw new NullishError(message);\n }\n};\n", "import {jsonReplacer, jsonReviver} from './json.utils';\nimport {nonNullish} from './null.utils';\n\n/**\n * Converts a value to a nullable array.\n * @template T\n * @param {T} [value] - The value to convert.\n * @returns {([] | [T])} A nullable array containing the value if non-nullish, or an empty array if nullish.\n */\nexport const toNullable = <T>(value?: T): [] | [T] => {\n return nonNullish(value) ? [value] : [];\n};\n\n/**\n * Extracts a value from a nullable array.\n * @template T\n * @param {([] | [T])} value - The nullable array.\n * @returns {(T | undefined)} The value if present, or undefined if the array is empty.\n */\nexport const fromNullable = <T>(value: [] | [T]): T | undefined => {\n return value?.[0];\n};\n\n/**\n * Converts data to a Uint8Array for transmission or storage.\n * @template T\n * @param {T} data - The data to convert.\n * @returns {Promise<Uint8Array>} A promise that resolves to a Uint8Array representation of the data.\n */\nexport const toArray = async <T>(data: T): Promise<Uint8Array> => {\n const blob: Blob = new Blob([JSON.stringify(data, jsonReplacer)], {\n type: 'application/json; charset=utf-8'\n });\n return new Uint8Array(await blob.arrayBuffer());\n};\n\n/**\n * Converts a Uint8Array or number array back to the original data type.\n * @template T\n * @param {(Uint8Array | number[])} data - The array to convert.\n * @returns {Promise<T>} A promise that resolves to the original data.\n */\nexport const fromArray = async <T>(data: Uint8Array | number[]): Promise<T> => {\n const blob: Blob = new Blob([data instanceof Uint8Array ? data : new Uint8Array(data)], {\n type: 'application/json; charset=utf-8'\n });\n return JSON.parse(await blob.text(), jsonReviver);\n};\n", "/**\n * Checks if the current environment is a browser.\n * @returns {boolean} True if the current environment is a browser, false otherwise.\n */\nexport const isBrowser = (): boolean => typeof window !== `undefined`;\n", "import {isBrowser, toNullable} from '@junobuild/utils';\nimport type {\n _SERVICE as ConsoleActor,\n InitAssetKey as ConsoleInitAssetKey,\n InitUploadResult as ConsoleInitUploadResult\n} from '../../declarations/console/console.did';\nimport type {\n _SERVICE as SatelliteActor,\n InitAssetKey as SatelliteInitAssetKey,\n InitUploadResult as SatelliteInitUploadResult\n} from '../../declarations/satellite/satellite.did';\nimport type {ENCODING_TYPE, Storage} from '../types/storage.types';\n\nexport type UploadAsset = Required<Omit<Storage, 'token' | 'encoding' | 'description'>> &\n Pick<Storage, 'token' | 'encoding' | 'description'>;\n\nexport const uploadAsset = async ({\n asset: {data, filename, collection, headers, token, fullPath, encoding, description},\n actor,\n init_asset_upload\n}: {\n asset: UploadAsset;\n actor: SatelliteActor | ConsoleActor;\n init_asset_upload: (\n initAssetKey: SatelliteInitAssetKey | ConsoleInitAssetKey\n ) => Promise<SatelliteInitUploadResult | ConsoleInitUploadResult>;\n}): Promise<void> => {\n const {batch_id: batchId} = await init_asset_upload({\n collection,\n full_path: fullPath,\n name: filename,\n token: toNullable<string>(token),\n encoding_type: toNullable<ENCODING_TYPE>(encoding),\n description: toNullable(description)\n });\n\n // https://forum.dfinity.org/t/optimal-upload-chunk-size/20444/23?u=peterparker\n const chunkSize = 1900000;\n\n const uploadChunks: UploadChunkParams[] = [];\n\n // Prevent transforming chunk to arrayBuffer error: The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.\n const clone: Blob = isBrowser() ? new Blob([await data.arrayBuffer()]) : data;\n\n // Split data into chunks\n let orderId = 0n;\n for (let start = 0; start < clone.size; start += chunkSize) {\n const chunk: Blob = clone.slice(start, start + chunkSize);\n\n uploadChunks.push({\n batchId,\n chunk,\n actor,\n orderId\n });\n\n orderId++;\n }\n\n // Upload chunks to the IC in batch - i.e. 12 chunks uploaded at a time.\n let chunkIds: UploadChunkResult[] = [];\n for await (const results of batchUploadChunks({uploadChunks})) {\n chunkIds = [...chunkIds, ...results];\n }\n\n const contentType: [[string, string]] | undefined =\n headers.find(([type, _]) => type.toLowerCase() === 'content-type') === undefined &&\n data.type !== undefined &&\n data.type !== ''\n ? [['Content-Type', data.type]]\n : undefined;\n\n await actor.commit_asset_upload({\n batch_id: batchId,\n chunk_ids: chunkIds.map(({chunk_id}: UploadChunkResult) => chunk_id),\n headers: [...headers, ...(contentType ? contentType : [])]\n });\n};\n\nasync function* batchUploadChunks({\n uploadChunks,\n limit = 12\n}: {\n uploadChunks: UploadChunkParams[];\n limit?: number;\n}): AsyncGenerator<UploadChunkResult[], void> {\n for (let i = 0; i < uploadChunks.length; i = i + limit) {\n const batch = uploadChunks.slice(i, i + limit);\n const result = await Promise.all(batch.map((params) => uploadChunk(params)));\n yield result;\n }\n}\n\ntype UploadChunkResult = {chunk_id: bigint};\n\ntype UploadChunkParams = {\n batchId: bigint;\n chunk: Blob;\n actor: SatelliteActor | ConsoleActor;\n orderId: bigint;\n};\n\nconst uploadChunk = async ({\n batchId,\n chunk,\n actor,\n orderId\n}: UploadChunkParams): Promise<UploadChunkResult> =>\n actor.upload_asset_chunk({\n batch_id: batchId,\n content: new Uint8Array(await chunk.arrayBuffer()),\n order_id: toNullable(orderId)\n });\n", "import type {UploadAsset} from '@junobuild/storage';\nimport {uploadAsset as uploadAssetStorage, type AssetKey} from '@junobuild/storage';\nimport {fromNullable} from '@junobuild/utils';\nimport type {\n AssetNoContent,\n InitAssetKey,\n InitUploadResult,\n _SERVICE as SatelliteActor\n} from '../../declarations/satellite/satellite.did';\nimport type {ListParams, ListResults} from '../types/list.types';\nimport type {Satellite} from '../types/satellite.types';\nimport {toListParams} from '../utils/list.utils';\nimport {getSatelliteActor} from './actor.api';\n\nexport const uploadAsset = async ({\n satellite,\n ...asset\n}: UploadAsset & {satellite: Satellite}): Promise<void> => {\n const actor = await getSatelliteActor(satellite);\n\n const init_asset_upload = async (initAssetKey: InitAssetKey): Promise<InitUploadResult> => {\n return await actor.init_asset_upload(initAssetKey);\n };\n\n await uploadAssetStorage({\n actor,\n asset,\n init_asset_upload\n });\n};\n\nexport const listAssets = async ({\n collection,\n satellite,\n filter\n}: {\n collection: string;\n satellite: Satellite;\n filter: ListParams;\n}): Promise<ListResults<AssetNoContent>> => {\n const {list_assets} = await getSatelliteActor(satellite);\n\n const {\n items: assets,\n items_length,\n items_page,\n matches_length,\n matches_pages\n } = await list_assets(collection, toListParams(filter));\n\n return {\n items: assets.map(([_, asset]) => asset),\n items_length,\n items_page: fromNullable(items_page),\n matches_length,\n matches_pages: fromNullable(matches_pages)\n };\n};\n\nexport const countAssets = async ({\n collection,\n satellite,\n filter\n}: {\n collection: string;\n satellite: Satellite;\n filter: ListParams;\n}): Promise<bigint> => {\n const {count_assets} = await getSatelliteActor(satellite);\n\n return count_assets(collection, toListParams(filter));\n};\n\nexport const deleteAsset = async ({\n collection,\n fullPath,\n satellite\n}: {\n collection: string;\n satellite: Satellite;\n} & Pick<AssetKey, 'fullPath'>): Promise<void> => {\n const actor: SatelliteActor = await getSatelliteActor(satellite);\n\n return actor.del_asset(collection, fullPath);\n};\n\nexport const deleteManyAssets = async ({\n assets,\n satellite\n}: {\n assets: ({collection: string} & Pick<AssetKey, 'fullPath'>)[];\n satellite: Satellite;\n}): Promise<void> => {\n const {del_many_assets} = await getSatelliteActor(satellite);\n\n const payload: [string, string][] = assets.map(({collection, fullPath}) => [\n collection,\n fullPath\n ]);\n\n await del_many_assets(payload);\n};\n\nexport const getAsset = async ({\n collection,\n fullPath,\n satellite\n}: {\n collection: string;\n satellite: Satellite;\n} & Pick<AssetKey, 'fullPath'>): Promise<AssetNoContent | undefined> => {\n const {get_asset} = await getSatelliteActor(satellite);\n return fromNullable(await get_asset(collection, fullPath));\n};\n\nexport const getManyAssets = async ({\n assets,\n satellite\n}: {\n assets: ({collection: string} & Pick<AssetKey, 'fullPath'>)[];\n satellite: Satellite;\n}): Promise<(AssetNoContent | undefined)[]> => {\n const {get_many_assets} = await getSatelliteActor(satellite);\n\n const payload: [string, string][] = assets.map(({collection, fullPath}) => [\n collection,\n fullPath\n ]);\n\n const resultsAssets = await get_many_assets(payload);\n\n return resultsAssets.map(([_, resultAsset]) => fromNullable(resultAsset));\n};\n", "export const sha256ToBase64String = (sha256: Iterable<number>): string =>\n btoa([...sha256].map((c) => String.fromCharCode(c)).join(''));\n", "import type {Asset, AssetEncoding, AssetKey, Storage} from '@junobuild/storage';\nimport {fromNullable, nonNullish} from '@junobuild/utils';\nimport type {AssetNoContent} from '../../declarations/satellite/satellite.did';\nimport {\n countAssets as countAssetsApi,\n deleteAsset as deleteAssetApi,\n deleteManyAssets as deleteManyAssetsApi,\n getAsset as getAssetApi,\n getManyAssets as getManyAssetsApi,\n listAssets as listAssetsApi,\n uploadAsset as uploadAssetApi\n} from '../api/storage.api';\nimport type {ListParams} from '../types/list.types';\nimport type {SatelliteOptions} from '../types/satellite.types';\nimport type {Assets} from '../types/storage.types';\nimport {sha256ToBase64String} from '../utils/crypto.utils';\nimport {satelliteUrl} from '../utils/env.utils';\nimport {getIdentity} from './identity.services';\n\n/**\n * Uploads a blob to the storage.\n * @param {Storage & {satellite?: SatelliteOptions}} params - The storage parameters. Satellite options are required only in NodeJS environment.\n * @returns {Promise<AssetKey>} A promise that resolves to the asset key.\n */\nexport const uploadBlob = async (\n params: Storage & {satellite?: SatelliteOptions}\n): Promise<AssetKey> => uploadAssetIC(params);\n\n/**\n * Uploads a file to the storage.\n * @param {Partial<Pick<Storage, 'filename'>> & Omit<Storage, 'filename' | 'data'> & {data: File} & {satellite?: SatelliteOptions}} params - The storage parameters. Satellite options are required only in NodeJS environment.\n * @returns {Promise<AssetKey>} A promise that resolves to the asset key.\n */\nexport const uploadFile = async (\n params: Partial<Pick<Storage, 'filename'>> &\n Omit<Storage, 'filename' | 'data'> & {data: File} & {satellite?: SatelliteOptions}\n): Promise<AssetKey> =>\n uploadAssetIC({\n filename: params.data.name,\n ...params\n });\n\nconst uploadAssetIC = async ({\n filename: storageFilename,\n data,\n collection,\n headers = [],\n fullPath: storagePath,\n token,\n satellite: satelliteOptions,\n encoding,\n description\n}: Storage & {satellite?: SatelliteOptions}): Promise<AssetKey> => {\n const identity = getIdentity(satelliteOptions?.identity);\n\n // The IC certification does not currently support encoding\n const filename: string = decodeURI(storageFilename);\n const fullPath: string = storagePath ?? `/${collection}/${filename}`;\n\n const satellite = {...satelliteOptions, identity};\n\n await uploadAssetApi({\n data,\n filename,\n collection,\n token,\n headers,\n fullPath,\n encoding,\n satellite,\n description\n });\n\n return {\n downloadUrl: downloadUrl({\n satellite,\n assetKey: {\n fullPath,\n token\n }\n }),\n fullPath,\n name: filename\n };\n};\n\n/**\n * Lists assets in a collection with optional filtering.\n * @param {Object} params - The parameters for listing the assets.\n * @param {string} params.collection - The name of the collection.\n * @param {SatelliteOptions} [params.satellite] - The satellite options (required only in NodeJS environment).\n * @param {ListParams} [params.filter] - The filter parameters.\n * @returns {Promise<Assets>} A promise that resolves to the list of assets.\n */\nexport const listAssets = async ({\n collection,\n satellite: satelliteOptions,\n filter\n}: {\n collection: string;\n satellite?: SatelliteOptions;\n filter?: ListParams;\n}): Promise<Assets> => {\n const satellite = {...satelliteOptions, identity: getIdentity(satelliteOptions?.identity)};\n\n const {items, ...rest} = await listAssetsApi({\n collection,\n satellite,\n filter: filter ?? {}\n });\n\n const assets = items.map(\n ({\n key: {full_path: fullPath, token: t, name, owner, description},\n headers,\n encodings,\n created_at,\n updated_at\n }: AssetNoContent) => {\n const token = fromNullable(t);\n\n return {\n fullPath,\n description: fromNullable(description),\n name,\n downloadUrl: downloadUrl({\n satellite,\n assetKey: {fullPath, token}\n }),\n token,\n headers,\n encodings: encodings.reduce(\n (acc, [type, {modified, sha256, total_length}]) => ({\n ...acc,\n [type]: {\n modified,\n sha256: sha256ToBase64String(sha256),\n total_length\n }\n }),\n {} as Record<string, AssetEncoding>\n ),\n owner: owner.toText(),\n created_at,\n updated_at\n } as Asset;\n }\n );\n\n return {\n items: assets,\n assets,\n ...rest\n };\n};\n\n/**\n * Counts assets in a collection with optional filtering.\n * @param {Object} params - The parameters for counting the assets.\n * @param {string} params.collection - The name of the collection.\n * @param {SatelliteOptions} [params.satellite] - The satellite options (required only in NodeJS environment).\n * @param {ListParams} [params.filter] - The filter parameters for narrowing down the count.\n * @returns {Promise<bigint>} A promise that resolves to the count of assets as a bigint.\n */\nexport const countAssets = async ({\n collection,\n satellite: satelliteOptions,\n filter\n}: {\n collection: string;\n satellite?: SatelliteOptions;\n filter?: ListParams;\n}): Promise<bigint> => {\n const satellite = {...satelliteOptions, identity: getIdentity(satelliteOptions?.identity)};\n\n return countAssetsApi({\n collection,\n satellite,\n filter: filter ?? {}\n });\n};\n\n/**\n * Deletes an asset from the storage.\n * @param {Object} params - The parameters for deleting the asset.\n * @param {string} params.collection - The name of the collection.\n * @param {SatelliteOptions} [params.satellite] - The satellite options (required only in NodeJS environment).\n * @param {string} params.fullPath - The full path of the asset.\n * @returns {Promise<void>} A promise that resolves when the asset is deleted.\n */\nexport const deleteAsset = async ({\n collection,\n fullPath,\n satellite\n}: {\n collection: string;\n satellite?: SatelliteOptions;\n} & Pick<AssetKey, 'fullPath'>): Promise<void> =>\n deleteAssetApi({\n collection,\n fullPath,\n satellite: {...satellite, identity: getIdentity(satellite?.identity)}\n });\n\n/**\n * Deletes multiple assets from the storage.\n * @param {Object} params - The parameters for deleting the assets.\n * @param {Array} params.assets - The list of assets with their collections and full paths.\n * @param {SatelliteOptions} [params.satellite] - The satellite options (required only in NodeJS environment).\n * @returns {Promise<void>} A promise that resolves when the assets are deleted.\n */\nexport const deleteManyAssets = async ({\n assets,\n satellite\n}: {\n assets: ({collection: string} & Pick<AssetKey, 'fullPath'>)[];\n satellite?: SatelliteOptions;\n} & Pick<AssetKey, 'fullPath'>): Promise<void> =>\n deleteManyAssetsApi({\n assets,\n satellite: {...satellite, identity: getIdentity(satellite?.identity)}\n });\n\n/**\n * Retrieves an asset from the storage.\n * @param {Object} params - The parameters for retrieving the asset.\n * @param {string} params.collection - The name of the collection.\n * @param {SatelliteOptions} [params.satellite] - The satellite options (required only in NodeJS environment).\n * @param {string} params.fullPath - The full path of the asset.\n * @returns {Promise<AssetNoContent | undefined>} A promise that resolves to the asset or undefined if not found.\n */\nexport const getAsset = async ({\n satellite,\n ...rest\n}: {\n collection: string;\n satellite?: SatelliteOptions;\n} & Pick<AssetKey, 'fullPath'>): Promise<AssetNoContent | undefined> => {\n const identity = getIdentity(satellite?.identity);\n\n return getAssetApi({...rest, satellite: {...satellite, identity}});\n};\n\n/**\n * Retrieves multiple assets from the storage.\n * @param {Object} params - The parameters for retrieving the assets.\n * @param {Array} params.assets - The list of assets with their collections and full paths.\n * @param {SatelliteOptions} [params.satellite] - The satellite options (required only in NodeJS environment).\n * @returns {Promise<Array<AssetNoContent | undefined>>} A promise that resolves to an array of assets or undefined if not found.\n */\nexport const getManyAssets = async ({\n satellite,\n ...rest\n}: {\n assets: ({collection: string} & Pick<AssetKey, 'fullPath'>)[];\n satellite?: SatelliteOptions;\n}): Promise<(AssetNoContent | undefined)[]> => {\n const identity = getIdentity(satellite?.identity);\n\n return getManyAssetsApi({...rest, satellite: {...satellite, identity}});\n};\n\n/**\n * Generates a download URL for a given asset.\n *\n * @param {Object} params - The parameters for generating the download URL.\n * @param {Object} params.assetKey - The key details of the asset.\n * @param {string} params.assetKey.fullPath - The full path of the asset.\n * @param {string} params.assetKey.token - The access token for the asset.\n * @param {SatelliteOptions} [params.satellite] - The satellite options (required only in NodeJS environment).\n *\n * @returns {string} The generated download URL.\n */\nexport const downloadUrl = ({\n assetKey: {fullPath, token},\n satellite: satelliteOptions\n}: {\n assetKey: Pick<Asset, 'fullPath' | 'token'>;\n} & {satellite?: SatelliteOptions}): string => {\n const satellite = {...satelliteOptions, identity: getIdentity(satelliteOptions?.identity)};\n\n return `${satelliteUrl(satellite)}${fullPath}${nonNullish(token) ? `?token=${token}` : ''}`;\n};\n", "import type {Asset, AssetEncoding, AssetKey, ENCODING_TYPE, Storage} from '@junobuild/storage';\nimport {assertNonNullish} from '@junobuild/utils';\nimport {initAuthTimeoutWorker} from './services/auth-timout.services';\nimport {initAuth} from './services/auth.services';\nimport {AuthStore} from './stores/auth.store';\nimport {EnvStore} from './stores/env.store';\nimport type {User} from './types/auth.types';\nimport type {Environment, UserEnvironment} from './types/env.types';\nimport type {Unsubscribe} from './types/subscription.types';\nimport {envContainer, envSatelliteId} from './utils/window.env.utils';\n\nexport * from './providers/auth.providers';\nexport {signIn, signOut, unsafeIdentity} from './services/auth.services';\nexport * from './services/doc.services';\nexport * from './services/storage.services';\nexport * from './types/auth.types';\nexport * from './types/doc.types';\nexport * from './types/env.types';\nexport {ListOrder, ListPaginate, ListParams, ListResults} from './types/list.types';\nexport * from './types/satellite.types';\nexport * from './types/storage.types';\nexport * from './types/subscription.types';\nexport type {Asset, AssetEncoding, AssetKey, ENCODING_TYPE, Storage};\n\nconst parseEnv = (userEnv?: UserEnvironment): Environment => {\n const satelliteId = userEnv?.satelliteId ?? envSatelliteId();\n\n assertNonNullish(satelliteId, 'Satellite ID is not configured. Juno cannot be initialized.');\n\n const container = userEnv?.container ?? envContainer();\n\n return {\n satelliteId,\n internetIdentityId: userEnv?.internetIdentityId,\n workers: userEnv?.workers,\n container\n };\n};\n\n/**\n * Initializes Juno with the provided optional environment parameters.\n * If no environment is provided, the variables injected by the Vite or NextJS plugins will be used.\n * @deprecated Use {@link initSatellite} instead.\n * @param {UserEnvironment} [userEnv] - The optional user environment configuration.\n * @returns {Promise<Unsubscribe[]>} A promise that resolves to an array of unsubscribe functions.\n */\nexport const initJuno = async (userEnv?: UserEnvironment): Promise<Unsubscribe[]> =>\n initSatellite(userEnv);\n\n/**\n * Initializes a Juno satellite with the provided optional environment parameters.\n * If no environment is provided, the variables injected by the Vite or NextJS plugins will be used.\n * @param {UserEnvironment} [userEnv] - The optional user environment configuration.\n * @returns {Promise<Unsubscribe[]>} A promise that resolves to an array of unsubscribe functions.\n */\nexport const initSatellite = async (userEnv?: UserEnvironment): Promise<Unsubscribe[]> => {\n const env = parseEnv(userEnv);\n\n EnvStore.getInstance().set(env);\n\n await initAuth();\n\n const authSubscribe =\n env.workers?.auth !== undefined ? initAuthTimeoutWorker(env.workers.auth) : undefined;\n\n return [...(authSubscribe ? [authSubscribe] : [])];\n};\n\n/**\n * Subscribes to authentication state changes. i.e. each time a user signs in or signs out, the callback will be triggered.\n * @param {function(User | null): void} callback - The callback function to execute when the authentication state changes.\n * @returns {Unsubscribe} A function to unsubscribe from the authentication state changes.\n */\nexport const authSubscribe = (callback: (authUser: User | null) => void): Unsubscribe =>\n AuthStore.getInstance().subscribe(callback);\n"],
|
|
5
|
+
"mappings": "uYAAA,IAAAA,GAAAC,GAAAC,IAAA,cAEAA,GAAQ,WAAaC,GACrBD,GAAQ,YAAcE,GACtBF,GAAQ,cAAgBG,GAExB,IAAIC,GAAS,CAAC,EACVC,GAAY,CAAC,EACbC,GAAM,OAAO,WAAe,IAAc,WAAa,MAEvDC,GAAO,mEACX,IAASC,GAAI,EAAGC,GAAMF,GAAK,OAAQC,GAAIC,GAAK,EAAED,GAC5CJ,GAAOI,EAAC,EAAID,GAAKC,EAAC,EAClBH,GAAUE,GAAK,WAAWC,EAAC,CAAC,EAAIA,GAFzB,IAAAA,GAAOC,GAOhBJ,GAAU,EAAiB,EAAI,GAC/BA,GAAU,EAAiB,EAAI,GAE/B,SAASK,GAASC,EAAK,CACrB,IAAIF,EAAME,EAAI,OAEd,GAAIF,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,CAACA,CAAa,EAAI,CAAC,CAAE,CACnD,EAOaA,GAAiBE,GAC5BC,GAAU,YAAY,EAAE,UAAUD,CAAQ",
|
|
6
|
+
"names": ["require_base64_js", "__commonJSMin", "exports", "byteLength", "toByteArray", "fromByteArray", "lookup", "revLookup", "Arr", "code", "i", "len", "getLens", "b64", "validLen", "placeHoldersLen", "lens", "_byteLength", "tmp", "arr", "curByte", "tripletToBase64", "num", "encodeChunk", "uint8", "start", "end", "output", "extraBytes", "parts", "maxChunkLength", "len2", "require_buffer", "__commonJSMin", "exports", "base64", "ieee754", "customInspectSymbol", "Buffer", "SlowBuffer", "K_MAX_LENGTH", "typedArraySupport", "arr", "proto", "createBuffer", "length", "buf", "arg", "encodingOrOffset", "allocUnsafe", "from", "value", "fromString", "fromArrayView", "isInstance", "fromArrayBuffer", "valueOf", "b", "fromObject", "assertSize", "size", "alloc", "fill", "encoding", "checked", "string", "byteLength", "actual", "fromArrayLike", "array", "i", "arrayView", "copy", "byteOffset", "obj", "len", "numberIsNaN", "a", "x", "y", "list", "buffer", "pos", "mustMatch", "loweredCase", "utf8ToBytes", "base64ToBytes", "slowToString", "start", "end", "hexSlice", "utf8Slice", "asciiSlice", "latin1Slice", "base64Slice", "utf16leSlice", "swap", "n", "m", "str", "max", "target", "thisStart", "thisEnd", "thisCopy", "targetCopy", "bidirectionalIndexOf", "val", "dir", "arrayIndexOf", "indexSize", "arrLength", "valLength", "read", "foundIndex", "found", "j", "hexWrite", "offset", "remaining", "strLen", "parsed", "utf8Write", "blitBuffer", "asciiWrite", "asciiToBytes", "base64Write", "ucs2Write", "utf16leToBytes", "res", "firstByte", "codePoint", "bytesPerSequence", "secondByte", "thirdByte", "fourthByte", "tempCodePoint", "decodeCodePointsArray", "MAX_ARGUMENTS_LENGTH", "codePoints", "ret", "out", "hexSliceLookupTable", "bytes", "newBuf", "checkOffset", "ext", "noAssert", "mul", "defineBigIntMethod", "validateNumber", "first", "last", "boundsError", "lo", "hi", "checkInt", "min", "maxBytes", "wrtBigUInt64LE", "checkIntBI", "wrtBigUInt64BE", "limit", "sub", "checkIEEE754", "writeFloat", "littleEndian", "writeDouble", "targetStart", "code", "errors", "E", "sym", "getMessage", "Base", "name", "range", "input", "msg", "received", "addNumericalSeparator", "checkBounds", "type", "INVALID_BASE64_RE", "base64clean", "units", "leadSurrogate", "byteArray", "c", "src", "dst", "alphabet", "table", "i16", "fn", "BufferBigIntNotDefined", "isNullish", "argument", "nonNullish", "NullishError", "assertNonNullish", "value", "message", "JSON_KEY_BIGINT", "JSON_KEY_PRINCIPAL", "JSON_KEY_UINT8ARRAY", "jsonReplacer", "_key", "Principal", "jsonReviver", "mapValue", "key", "toNullable", "fromNullable", "toArray", "data", "blob", "fromArray", "isBrowser", "Store", "data", "callback", "callbackId", "id", "AuthStore", "_AuthStore", "Store", "authUser", "callback", "unsubscribe", "emit", "message", "detail", "$event", "DELEGATION_IDENTITY_EXPIRATION", "ALLOW_PIN_AUTHENTICATION", "II_POPUP", "NFID_POPUP", "INTERNET_COMPUTER_ORG", "DOCKER_CONTAINER_URL", "DOCKER_INTERNET_IDENTITY_ID", "EnvStore", "_EnvStore", "Store", "env", "callback", "unsubscribe", "popupCenter", "width", "height", "h", "c", "innerWidth", "innerHeight", "y", "x", "InternetIdentityProvider", "#domain", "domain", "windowed", "identityProviderUrl", "container", "EnvStore", "c", "INTERNET_COMPUTER_ORG", "env", "internetIdentityId", "t", "DOCKER_INTERNET_IDENTITY_ID", "containerHost", "protocol", "DOCKER_CONTAINER_URL", "popupCenter", "II_POPUP", "NFIDProvider", "#appName", "#logoUrl", "appName", "logoUrl", "NFID_POPUP", "import_buffer", "ReplicaRejectCode", "domainSeparator", "SignIdentity", "Principal", "request", "body", "fields", "__rest", "requestId", "requestIdOf", "concat", "AnonymousIdentity", "cbor", "randomNumber", "array", "SubmitRequestType", "makeNonce", "buffer", "view", "rand1", "randomNumber", "rand2", "rand3", "rand4", "NANOSECONDS_PER_MILLISECONDS", "REPLICA_PERMITTED_DRIFT_MILLISECONDS", "Expiry", "deltaInMSec", "rounded_down_nanos", "lebEncode", "makeNonceTransform", "nonceFn", "makeNonce", "request", "headers", "httpHeadersTransform", "headers", "headerFields", "value", "key", "AgentHTTPResponseError", "AgentError", "message", "response", "U32_MASK64", "_32n", "fromBig", "n", "le", "split", "lst", "Ah", "Al", "h", "l", "toBig", "shrSH", "_l", "s", "shrSL", "rotrSH", "rotrSL", "rotrBH", "rotrBL", "rotr32H", "_h", "rotr32L", "rotlSH", "rotlSL", "rotlBH", "rotlBL", "add", "Bh", "Bl", "add3L", "Cl", "add3H", "low", "Ch", "add4L", "Dl", "add4H", "Dh", "add5L", "El", "add5H", "Eh", "u64", "fromBig", "split", "toBig", "shrSH", "shrSL", "rotrSH", "rotrSL", "rotrBH", "rotrBL", "rotr32H", "rotr32L", "rotlSH", "rotlSL", "rotlBH", "rotlBL", "add", "add3L", "add3H", "add4L", "add4H", "add5H", "add5L", "u64_default", "SHA512_Kh", "SHA512_Kl", "u64_default", "n", "SHA512_W_H", "SHA512_W_L", "SHA512", "HashMD", "Ah", "Al", "Bh", "Bl", "Ch", "Cl", "Dh", "Dl", "Eh", "El", "Fh", "Fl", "Gh", "Gl", "Hh", "Hl", "view", "offset", "i", "W15h", "W15l", "s0h", "s0l", "W2h", "W2l", "s1h", "s1l", "SUMl", "SUMh", "sigma1h", "sigma1l", "CHIh", "CHIl", "T1ll", "T1h", "T1l", "sigma0h", "sigma0l", "MAJh", "MAJl", "All", "sha512", "wrapConstructor", "SHA512", "_0n", "_1n", "_2n", "_8n", "VERIFY_DEFAULT", "validateOpts", "curve", "opts", "validateBasic", "validateObject", "twistedEdwards", "curveDef", "CURVE", "Fp", "CURVE_ORDER", "prehash", "cHash", "randomBytes", "nByteLength", "cofactor", "MASK", "modP", "uvRatio", "u", "v", "adjustScalarBytes", "bytes", "domain", "data", "ctx", "phflag", "abool", "aCoordinate", "title", "n", "aInRange", "assertPoint", "other", "Point", "toAffineMemo", "memoized", "p", "iz", "y", "z", "is0", "ax", "ay", "zz", "assertValidMemo", "a", "d", "X", "Y", "Z", "T", "X2", "Y2", "Z2", "Z4", "aX2", "left", "right", "XY", "ZT", "ex", "ey", "ez", "et", "points", "toInv", "i", "windowSize", "wnaf", "X1", "Y1", "Z1", "X1Z2", "X2Z1", "Y1Z2", "Y2Z1", "A", "B", "C", "D", "x1y1", "E", "G", "F", "H", "X3", "Y3", "T3", "Z3", "T1", "T2", "scalar", "f", "I", "hex", "zip215", "len", "ensureBytes", "normed", "lastByte", "bytesToNumberLE", "max", "y2", "isValid", "x", "isXOdd", "isLastByteOdd", "privKey", "getExtendedPublicKey", "numberToBytesLE", "bytesToHex", "wNAF", "modN", "mod", "modN_LE", "hash", "key", "hashed", "head", "prefix", "point", "pointBytes", "getPublicKey", "hashDomainToScalar", "context", "msgs", "msg", "concatBytes", "sign", "options", "r", "R", "k", "s", "res", "verifyOpts", "verify", "sig", "publicKey", "SB", "ED25519_P", "ED25519_SQRT_M1", "_0n", "_1n", "_2n", "_3n", "_5n", "_8n", "ed25519_pow_2_252_3", "x", "_10n", "_20n", "_40n", "_80n", "P", "b2", "b4", "pow2", "b5", "b10", "b20", "b40", "b80", "b160", "b240", "b250", "adjustScalarBytes", "bytes", "uvRatio", "u", "v", "v3", "mod", "v7", "pow", "vx2", "root1", "root2", "useRoot1", "useRoot2", "noRoot", "isNegativeLE", "Fp", "Field", "ED25519_P", "ed25519Defaults", "_8n", "sha512", "randomBytes", "adjustScalarBytes", "uvRatio", "ed25519", "twistedEdwards", "ExpirableMap", "options", "_ExpirableMap_inner", "_ExpirableMap_expirationTime", "_a", "_b", "source", "expirationTime", "currentTime", "__classPrivateFieldSet", "key", "value", "entry", "__classPrivateFieldGet", "iterator", "callbackfn", "thisArg", "encodeLenBytes", "len", "encodeLen", "buf", "offset", "decodeLenBytes", "decodeLen", "lenBytes", "DER_COSE_OID", "ED25519_OID", "SECP256K1_OID", "wrapDER", "payload", "oid", "bitStringHeaderLength", "unwrapDER", "derEncoded", "expect", "n", "msg", "bufEquals", "payloadLen", "result", "Ed25519PublicKey", "_Ed25519PublicKey", "key", "_Ed25519PublicKey_rawKey", "_Ed25519PublicKey_derKey", "__classPrivateFieldSet", "rawKey", "derKey", "publicKey", "wrapDER", "ED25519_OID", "unwrapped", "unwrapDER", "__classPrivateFieldGet", "Observable", "func", "observer", "data", "rest", "ObservableLog", "message", "error", "ExponentialBackoff", "_ExponentialBackoff", "options", "_ExponentialBackoff_currentInterval", "_ExponentialBackoff_randomizationFactor", "_ExponentialBackoff_multiplier", "_ExponentialBackoff_maxInterval", "_ExponentialBackoff_startTime", "_ExponentialBackoff_maxElapsedTime", "_ExponentialBackoff_maxIterations", "_ExponentialBackoff_date", "_ExponentialBackoff_count", "initialInterval", "randomizationFactor", "multiplier", "maxInterval", "maxElapsedTime", "maxIterations", "date", "__classPrivateFieldSet", "__classPrivateFieldGet", "delta", "min", "max", "_a", "RequestStatusResponseStatus", "DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS", "IC_ROOT_KEY", "IC0_DOMAIN", "IC0_SUB_DOMAIN", "ICP0_DOMAIN", "ICP0_SUB_DOMAIN", "ICP_API_DOMAIN", "ICP_API_SUB_DOMAIN", "HttpDefaultFetchError", "AgentError", "message", "IdentityInvalidError", "getDefaultFetch", "defaultFetch", "determineHost", "configuredHost", "host", "knownHosts", "remoteHosts", "location", "hostname", "knownHost", "HttpAgent", "_HttpAgent", "options", "fromHex", "IC_ROOT_KEY", "_HttpAgent_identity", "_HttpAgent_fetch", "_HttpAgent_fetchOptions", "_HttpAgent_callOptions", "_HttpAgent_timeDiffMsecs", "_HttpAgent_credentials", "_HttpAgent_rootKeyFetched", "_HttpAgent_retryTimes", "_HttpAgent_backoffStrategy", "_HttpAgent_waterMark", "ObservableLog", "_HttpAgent_queryPipeline", "_HttpAgent_updatePipeline", "_HttpAgent_subnetKeys", "ExpirableMap", "_HttpAgent_verifyQuerySignatures", "_HttpAgent_verifyQueryResponse", "queryResponse", "subnetStatus", "__classPrivateFieldGet", "CertificateVerificationError", "status", "signatures", "requestId", "domainSeparator", "sig", "timestamp", "identity", "nodeId", "Principal", "hash", "reply", "hashOfMap", "reject_code", "reject_message", "error_code", "separatorWithHash", "concat", "pubKey", "rawKey", "Ed25519PublicKey", "ed25519", "__classPrivateFieldSet", "_a", "defaultBackoffFactory", "ExponentialBackoff", "name", "password", "AnonymousIdentity", "makeNonceTransform", "makeNonce", "log", "agent", "initPromises", "type", "fn", "priority", "x", "canisterId", "id", "canister", "ecid", "sender", "ingress_expiry", "Expiry", "DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS", "submit", "SubmitRequestType", "transformedRequest", "nonce", "toNonce", "buf", "body", "encode", "backoff", "request", "_HttpAgent_instances", "_HttpAgent_requestAndRetry", "response", "requestIdOf", "responseBuffer", "responseBody", "decode", "httpHeadersTransform", "fields", "makeQuery", "args", "_HttpAgent_requestAndRetryQuery", "getSubnetStatus", "queryResult", "requestDetails", "query", "queryWithDetails", "updatedSubnetStatus", "decodedResponse", "parsedTime", "tree", "decoded", "timeLookup", "lookup_path", "LookupStatus", "date", "decodeTime", "bufFromBufLike", "CanisterStatus", "callTime", "replicaTime", "error", "headers", "effectiveCanisterId", "subnetResponse", "p", "r", "r2", "tries", "delay", "resolve", "fetchResponse", "AgentHTTPResponseError", "_b", "timeStampInMs", "responseText", "errorMessage", "ProxyMessageKind", "getDefaultAgent", "agent", "strategy_exports", "__export", "backoff", "chain", "conditionalDelay", "defaultStrategy", "maxAttempts", "once", "throttle", "timeout", "FIVE_MINUTES_IN_MSEC", "defaultStrategy", "chain", "conditionalDelay", "once", "backoff", "timeout", "first", "condition", "timeInMsec", "canisterId", "requestId", "status", "resolve", "maxAttempts", "count", "attempts", "toHex", "throttle", "throttleInMsec", "end", "startingThrottleInMsec", "backoffFactor", "currentThrottling", "strategies", "a", "pollForResponse", "agent", "canisterId", "requestId", "strategy", "request", "blsVerify", "path", "currentRequest", "_a", "state", "cert", "Certificate", "maybeBuf", "lookupResultToBuffer", "status", "RequestStatusResponseStatus", "rejectCode", "rejectMessage", "toHex", "management_idl_default", "IDL", "bitcoin_network", "bitcoin_address", "bitcoin_get_balance_args", "satoshi", "bitcoin_get_balance_result", "bitcoin_get_current_fee_percentiles_args", "millisatoshi_per_byte", "bitcoin_get_current_fee_percentiles_result", "bitcoin_get_utxos_args", "block_hash", "outpoint", "utxo", "bitcoin_get_utxos_result", "bitcoin_send_transaction_args", "canister_id", "canister_info_args", "change_origin", "change_details", "change", "canister_info_result", "canister_status_args", "log_visibility", "definite_canister_settings", "canister_status_result", "clear_chunk_store_args", "canister_settings", "create_canister_args", "create_canister_result", "delete_canister_args", "deposit_cycles_args", "ecdsa_curve", "ecdsa_public_key_args", "ecdsa_public_key_result", "fetch_canister_logs_args", "canister_log_record", "fetch_canister_logs_result", "http_header", "http_request_result", "http_request_args", "canister_install_mode", "chunk_hash", "install_chunked_code_args", "wasm_module", "install_code_args", "node_metrics_history_args", "node_metrics", "node_metrics_history_result", "provisional_create_canister_with_cycles_args", "provisional_create_canister_with_cycles_result", "provisional_top_up_canister_args", "raw_rand_result", "sign_with_ecdsa_args", "sign_with_ecdsa_result", "start_canister_args", "stop_canister_args", "stored_chunks_args", "stored_chunks_result", "uninstall_code_args", "update_settings_args", "upload_chunk_args", "upload_chunk_result", "ActorCallError", "AgentError", "canisterId", "methodName", "type", "props", "n", "QueryCallRejectedError", "result", "_a", "ReplicaRejectCode", "UpdateCallRejectedError", "requestId", "response", "toHex", "metadataSymbol", "Actor", "_Actor", "metadata", "actor", "Principal", "fields", "config", "mode", "arg", "wasmModule", "getManagementCanister", "settings", "settingsToCanisterSettings", "interfaceFactory", "options", "service", "idl_exports", "CanisterActor", "DEFAULT_ACTOR_CONFIG", "func", "ACTOR_METHOD_WITH_HTTP_DETAILS", "ACTOR_METHOD_WITH_CERTIFICATE", "_createActorMethod", "configuration", "actorClassOptions", "decodeReturnValue", "types", "msg", "returnValues", "strategy_exports", "blsVerify", "caller", "args", "_b", "agent", "getDefaultAgent", "cid", "httpDetails", "effectiveCanisterId", "pollingStrategyFactory", "ecid", "requestDetails", "pollStrategy", "certificate", "reply", "pollForResponse", "shouldIncludeHttpDetails", "shouldIncludeCertificate", "handler", "transform", "_methodName", "first", "management_idl_default", "isObject", "value", "Ed25519PublicKey", "_Ed25519PublicKey", "key", "_Ed25519PublicKey_rawKey", "_Ed25519PublicKey_derKey", "__classPrivateFieldSet", "maybeKey", "fromHex", "view", "bufFromBufLike", "rawKey", "derKey", "publicKey", "wrapDER", "ED25519_OID", "unwrapped", "unwrapDER", "__classPrivateFieldGet", "Ed25519KeyIdentity", "_Ed25519KeyIdentity", "SignIdentity", "privateKey", "_Ed25519KeyIdentity_publicKey", "_Ed25519KeyIdentity_privateKey", "seed", "ed25519", "bufEquals", "sk", "pk", "obj", "publicKeyDer", "privateKeyRaw", "json", "parsed", "secretKey", "toHex", "challenge", "blob", "signature", "uint8ToBuf", "sig", "msg", "message", "x", "CryptoError", "_CryptoError", "message", "_getEffectiveCrypto", "subtleCrypto", "ECDSAKeyIdentity", "_ECDSAKeyIdentity", "SignIdentity", "keyPair", "derKey", "options", "extractable", "keyUsages", "effectiveCrypto", "key", "challenge", "params", "cbor", "PartialIdentity", "inner", "_PartialIdentity_inner", "__classPrivateFieldSet", "__classPrivateFieldGet", "Principal", "domainSeparator", "requestDomainSeparator", "_parseBlob", "value", "fromHex", "Delegation", "pubkey", "expiration", "targets", "t", "toHex", "p", "_createSingleDelegation", "from", "to", "delegation", "challenge", "requestIdOf", "signature", "DelegationChain", "_DelegationChain", "delegations", "publicKey", "options", "_a", "_b", "json", "parsedDelegations", "signedDelegation", "Principal", "DelegationIdentity", "SignIdentity", "_inner", "_delegation", "key", "blob", "request", "body", "fields", "__rest", "requestId", "PartialDelegationIdentity", "_PartialDelegationIdentity", "PartialIdentity", "inner", "_PartialDelegationIdentity_delegation", "__classPrivateFieldSet", "__classPrivateFieldGet", "isDelegationValid", "chain", "checks", "scopes", "maybeScope", "s", "scope", "none", "target", "import_borc", "PubKeyCoseAlgo", "events", "IdleManager", "options", "onIdle", "idleTimeout", "_resetTimer", "name", "debounce", "func", "wait", "timeout", "args", "context", "later", "scroll", "_a", "callback", "cb", "exit", "instanceOfAny", "object", "constructors", "c", "idbProxyableTypes", "cursorAdvanceMethods", "getIdbProxyableTypes", "getCursorAdvanceMethods", "cursorRequestMap", "transactionDoneMap", "transactionStoreNamesMap", "transformCache", "reverseTransformCache", "promisifyRequest", "request", "promise", "resolve", "reject", "unlisten", "success", "error", "wrap", "value", "cacheDonePromiseForTransaction", "tx", "done", "complete", "idbProxyTraps", "target", "prop", "receiver", "replaceTraps", "callback", "wrapFunction", "func", "storeNames", "args", "unwrap", "transformCachableValue", "newValue", "openDB", "name", "version", "blocked", "upgrade", "blocking", "terminated", "request", "openPromise", "wrap", "event", "db", "readMethods", "writeMethods", "cachedMethods", "getMethod", "target", "prop", "targetFuncName", "useIndex", "isWrite", "method", "storeName", "args", "tx", "replaceTraps", "oldTraps", "receiver", "AUTH_DB_NAME", "OBJECT_STORE_NAME", "_openDbStore", "dbName", "storeName", "version", "isBrowser", "KEY_STORAGE_DELEGATION", "KEY_STORAGE_KEY", "openDB", "database", "_getValue", "db", "key", "_setValue", "value", "_removeValue", "IdbKeyVal", "_IdbKeyVal", "_db", "_storeName", "options", "DB_VERSION", "_a", "KEY_STORAGE_KEY", "KEY_STORAGE_DELEGATION", "KEY_VECTOR", "DB_VERSION", "isBrowser", "LocalStorage", "prefix", "_localStorage", "key", "value", "ls", "IdbStorage", "options", "_IdbStorage_options", "__classPrivateFieldSet", "resolve", "IdbKeyVal", "__classPrivateFieldGet", "db", "IDENTITY_PROVIDER_DEFAULT", "IDENTITY_PROVIDER_ENDPOINT", "ECDSA_KEY_LABEL", "ED25519_KEY_LABEL", "INTERRUPT_CHECK_INTERVAL", "ERROR_USER_INTERRUPT", "AuthClient", "_identity", "_key", "_chain", "_storage", "idleManager", "_createOptions", "_idpWindow", "_eventHandler", "options", "storage", "_a", "IdbStorage", "keyType", "_b", "key", "maybeIdentityStorage", "KEY_STORAGE_KEY", "isBrowser", "fallbackLocalStorage", "LocalStorage", "localChain", "KEY_STORAGE_DELEGATION", "localKey", "error", "Ed25519KeyIdentity", "ECDSAKeyIdentity", "identity", "AnonymousIdentity", "chain", "chainStorage", "DelegationChain", "isDelegationValid", "PartialDelegationIdentity", "DelegationIdentity", "_deleteStorage", "e", "_c", "IdleManager", "idleOptions", "message", "onSuccess", "delegations", "signedDelegation", "Delegation", "delegationChain", "defaultTimeToLive", "identityProviderUrl", "_d", "checkInterruption", "event", "request", "err", "errorMessage", "onError", "KEY_VECTOR", "createAuthClient", "AuthClient", "mapData", "data", "B", "err", "toSetDoc", "doc", "data", "version", "description", "g", "R", "toDelDoc", "fromDoc", "key", "owner", "docDescription", "rest", "j", "B", "toListMatcherTimestamp", "matcher", "c", "g", "toListParams", "paginate", "order", "owner", "Principal", "idlFactory", "IDL", "CommitBatch", "ListOrderField", "ListOrder", "TimestampMatcher", "ListMatcher", "ListPaginate", "ListParams", "DeleteControllersArgs", "ControllerScope", "Controller", "DelDoc", "RulesType", "DelRule", "DepositCyclesArgs", "AssetKey", "AssetEncodingNoContent", "AssetNoContent", "AuthenticationConfigInternetIdentity", "AuthenticationConfig", "ConfigMaxMemorySize", "DbConfig", "StorageConfigIFrame", "StorageConfigRawAccess", "StorageConfigRedirect", "StorageConfig", "Config", "Doc", "HttpRequest", "Memory", "StreamingCallbackToken", "StreamingStrategy", "HttpResponse", "StreamingCallbackHttpResponse", "InitAssetKey", "InitUploadResult", "ListResults", "CustomDomain", "ListResults_1", "Permission", "Rule", "MemorySize", "SetController", "SetControllersArgs", "SetDoc", "SetRule", "UploadChunk", "UploadChunkResult", "createActor", "canisterId", "idlFactory", "identity", "fetch", "container", "host", "t", "DOCKER_CONTAINER_URL", "shouldFetchRootKey", "agent", "HttpAgent", "Actor", "satelliteUrl", "customSatelliteId", "customContainer", "satelliteId", "customOrEnvSatelliteId", "container", "customOrEnvContainer", "t", "containerHost", "protocol", "DOCKER_CONTAINER_URL", "EnvStore", "getSatelliteActor", "customSatelliteId", "customContainer", "rest", "satelliteId", "customOrEnvSatelliteId", "x", "container", "customOrEnvContainer", "createActor", "idlFactory", "getDoc", "collection", "key", "satellite", "get_doc", "getSatelliteActor", "doc", "j", "c", "fromDoc", "getManyDocs", "docs", "get_many_docs", "payload", "resultsDocs", "results", "resultDoc", "t", "setDoc", "set_doc", "toSetDoc", "updatedDoc", "setManyDocs", "set_many_docs", "updatedDocs", "deleteDoc", "del_doc", "toDelDoc", "deleteManyDocs", "del_many_docs", "listDocs", "filter", "list_docs", "items", "items_page", "items_length", "matches_length", "matches_pages", "toListParams", "item", "dataArray", "owner", "description", "version", "rest", "mapData", "countDocs", "count_docs", "getIdentity", "identity", "AnonymousIdentity", "getDoc", "satellite", "rest", "identity", "getIdentity", "getManyDocs", "setDoc", "setManyDocs", "deleteDoc", "deleteManyDocs", "listDocs", "filter", "countDocs", "initUser", "provider", "identity", "getIdentity", "c", "userId", "user", "getDoc", "createUser", "rest", "setDoc", "authClient", "initAuth", "provider", "createAuthClient", "user", "initUser", "AuthStore", "signIn", "options", "resolve", "reject", "InternetIdentityProvider", "error", "DELEGATION_IDENTITY_EXPIRATION", "ALLOW_PIN_AUTHENTICATION", "signOut", "getIdentity", "unsafeIdentity", "initAuthTimeoutWorker", "auth", "workerUrl", "worker", "timeoutSignOut", "emit", "signOut", "data", "msg", "value", "AuthStore", "user", "c", "envSatelliteId", "viteEnvSatelliteId", "envContainer", "viteEnvContainer", "isNullish", "argument", "nonNullish", "toNullable", "value", "isBrowser", "uploadAsset", "data", "filename", "collection", "headers", "token", "fullPath", "encoding", "description", "actor", "init_asset_upload", "batchId", "g", "chunkSize", "uploadChunks", "clone", "h", "orderId", "start", "chunk", "chunkIds", "results", "batchUploadChunks", "contentType", "type", "_", "chunk_id", "limit", "i", "batch", "params", "uploadChunk", "uploadAsset", "satellite", "asset", "actor", "getSatelliteActor", "B", "initAssetKey", "listAssets", "collection", "filter", "list_assets", "assets", "items_length", "items_page", "matches_length", "matches_pages", "toListParams", "_", "j", "countAssets", "count_assets", "deleteAsset", "fullPath", "deleteManyAssets", "del_many_assets", "payload", "getAsset", "get_asset", "getManyAssets", "get_many_assets", "resultAsset", "sha256ToBase64String", "sha256", "c", "uploadBlob", "params", "uploadAssetIC", "uploadFile", "storageFilename", "data", "collection", "headers", "storagePath", "token", "satelliteOptions", "encoding", "description", "identity", "getIdentity", "filename", "fullPath", "satellite", "uploadAsset", "downloadUrl", "listAssets", "filter", "items", "rest", "assets", "t", "name", "owner", "encodings", "created_at", "updated_at", "j", "acc", "type", "modified", "sha256", "total_length", "sha256ToBase64String", "countAssets", "deleteAsset", "deleteManyAssets", "getAsset", "getManyAssets", "satelliteUrl", "parseEnv", "userEnv", "satelliteId", "envSatelliteId", "x", "container", "envContainer", "initJuno", "initSatellite", "env", "EnvStore", "initAuth", "authSubscribe", "initAuthTimeoutWorker", "callback", "AuthStore"]
|
|
7
7
|
}
|