@junobuild/core-standalone 2.0.0 → 2.0.1

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../node_modules/base64-js/index.js", "../../../../node_modules/buffer/index.js", "../../../../node_modules/@dfinity/agent/src/actor.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/utils/src/enums/token.enums.ts", "../../../../node_modules/@dfinity/utils/src/constants/constants.ts", "../../../../node_modules/@dfinity/utils/src/parser/token.ts", "../../../../node_modules/@dfinity/utils/src/services/canister.ts", "../../../../node_modules/@dfinity/utils/src/utils/nullish.utils.ts", "../../../../node_modules/@dfinity/utils/src/services/query.ts", "../../../../node_modules/@dfinity/utils/src/utils/actor.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/agent.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/asserts.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/arrays.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/base32.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/base64.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/crc.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/json.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/crypto.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/date.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/debounce.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/did.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/principal.utils.ts", "../../../../node_modules/@dfinity/utils/src/utils/version.utils.ts", "../../../ic-client/src/webauthn/aaguid.ts", "../../../ic-client/src/webauthn/agent-js/cose-utils.ts", "../../../ic-client/src/webauthn/agent-js/cose-key.ts", "../../../ic-client/src/webauthn/credential.ts", "../../../ic-client/src/webauthn/errors.ts", "../../../ic-client/src/webauthn/identity.ts", "../../../ic-client/src/webauthn/_constants.ts", "../../../ic-client/src/webauthn/_options.ts", "../../../ic-client/src/webauthn/_progress.ts", "../../../ic-client/src/webauthn/types/progress.ts", "../../../ic-client/src/webauthn/utils.ts", "../../src/core/stores/_store.ts", "../../src/auth/stores/auth.store.ts", "../../src/auth/utils/events.utils.ts", "../../src/core/constants/container.constants.ts", "../../src/core/stores/_agent.factory.ts", "../../src/core/stores/agent.store.ts", "../../src/core/stores/actor.store.ts", "../../src/auth/helpers/window.helpers.ts", "../../src/core/stores/env.store.ts", "../../src/auth/constants/auth.constants.ts", "../../../utils/src/utils/did.utils.ts", "../../../utils/src/utils/env.utils.ts", "../../src/auth/utils/window.utils.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/auth/helpers/progress.helpers.ts", "../../src/auth/types/auth-client.ts", "../../src/auth/types/errors.ts", "../../src/auth/providers/_auth-client.providers.ts", "../../src/auth/providers/internet-identity.providers.ts", "../../src/auth/providers/nfid.providers.ts", "../../src/core/constants/call-options.constants.ts", "../../src/core/services/identity.services.ts", "../../../ic-client/src/actor/api/actor.api.ts", "../../../ic-client/src/declarations/mission_control/mission_control.factory.did.js", "../../../ic-client/src/declarations/orbiter/orbiter.factory.did.js", "../../../ic-client/src/declarations/orbiter/orbiter.factory.certified.did.js", "../../../ic-client/src/declarations/deprecated/satellite-deprecated-no-scope.factory.did.js", "../../../ic-client/src/declarations/deprecated/satellite-deprecated-version.factory.did.js", "../../../ic-client/src/declarations/deprecated/orbiter-deprecated-version.factory.did.js", "../../../ic-client/src/declarations/deprecated/mission_control-deprecated-version.factory.did.js", "../../../ic-client/src/declarations/deprecated/satellite-deprecated.factory.did.js", "../../../ic-client/src/declarations/satellite/satellite.factory.did.js", "../../../ic-client/src/declarations/satellite/satellite.factory.certified.did.js", "../../../ic-client/src/declarations/console/console.factory.did.js", "../../../ic-client/src/declarations/console/console.factory.certified.did.js", "../../../ic-client/src/declarations/sputnik/sputnik.factory.did.js", "../../../ic-client/src/actor/api/agent.api.ts", "../../../ic-client/src/actor/utils/agent.utils.ts", "../../src/core/utils/env.utils.ts", "../../src/core/api/actor.api.ts", "../../src/core/utils/list.utils.ts", "../../src/datastore/utils/data.utils.ts", "../../src/datastore/utils/doc.utils.ts", "../../src/datastore/api/doc.api.ts", "../../src/datastore/services/doc.services.ts", "../../src/auth/services/user-webauthn.services.ts", "../../src/auth/types/webauthn.ts", "../../src/auth/providers/webauthn.providers.ts", "../../src/auth/utils/auth.utils.ts", "../../../errors/src/utils.ts", "../../../errors/src/constants/cdn.constants.ts", "../../../errors/src/constants/collections.constants.ts", "../../../errors/src/constants/satellite.constants.ts", "../../../errors/src/constants/shared.constants.ts", "../../src/auth/services/_user.services.ts", "../../src/auth/services/auth.services.ts", "../../src/auth/services/auth-timout.services.ts", "../../src/core/utils/window.env.utils.ts", "../../src/functions/services/functions.services.ts", "../../../storage/src/services/upload.services.ts", "../../src/storage/api/storage.api.ts", "../../src/storage/utils/crypto.utils.ts", "../../src/storage/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", "import { Buffer } from 'buffer/';\nimport {\n Agent,\n getDefaultAgent,\n HttpDetailsResponse,\n QueryResponseRejected,\n QueryResponseStatus,\n ReplicaRejectCode,\n SubmitResponse,\n v2ResponseBody,\n v3ResponseBody,\n} from './agent';\nimport { AgentError } from './errors';\nimport { bufFromBufLike, 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, lookupResultToBuffer } 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 public readonly reject_code: ReplicaRejectCode,\n public readonly reject_message: string,\n public readonly error_code?: string,\n ) {\n super(canisterId, methodName, 'update', {\n 'Request ID': toHex(requestId),\n ...(response.body\n ? {\n ...(error_code\n ? {\n 'Error code': error_code,\n }\n : {}),\n 'Reject code': String(reject_code),\n 'Reject message': 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\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 let reply: ArrayBuffer | undefined;\n let certificate: Certificate | undefined;\n if (response.body && (response.body as v3ResponseBody).certificate) {\n if (agent.rootKey == null) {\n throw new Error('Agent is missing root key');\n }\n const cert = (response.body as v3ResponseBody).certificate;\n certificate = await Certificate.create({\n certificate: bufFromBufLike(cert),\n rootKey: agent.rootKey,\n canisterId: Principal.from(canisterId),\n blsVerify,\n });\n const path = [new TextEncoder().encode('request_status'), requestId];\n const status = new TextDecoder().decode(\n lookupResultToBuffer(certificate.lookup([...path, 'status'])),\n );\n\n switch (status) {\n case 'replied':\n reply = lookupResultToBuffer(certificate.lookup([...path, 'reply']));\n break;\n case 'rejected': {\n // Find rejection details in the certificate\n const rejectCode = new Uint8Array(\n lookupResultToBuffer(certificate.lookup([...path, 'reject_code']))!,\n )[0];\n const rejectMessage = new TextDecoder().decode(\n lookupResultToBuffer(certificate.lookup([...path, 'reject_message']))!,\n );\n const error_code_buf = lookupResultToBuffer(\n certificate.lookup([...path, 'error_code']),\n );\n const error_code = error_code_buf\n ? new TextDecoder().decode(error_code_buf)\n : undefined;\n throw new UpdateCallRejectedError(\n cid,\n methodName,\n requestId,\n response,\n rejectCode,\n rejectMessage,\n error_code,\n );\n }\n }\n } else if (response.body && 'reject_message' in response.body) {\n // handle v2 response errors by throwing an UpdateCallRejectedError object\n const { reject_code, reject_message, error_code } = response.body as v2ResponseBody;\n throw new UpdateCallRejectedError(\n cid,\n methodName,\n requestId,\n response,\n reject_code,\n reject_message,\n error_code,\n );\n }\n\n // Fall back to polling if we receive an Accepted response code\n if (response.status === 202) {\n const pollStrategy = pollingStrategyFactory();\n // Contains the certificate and the reply from the boundary node\n const response = await pollForResponse(agent, ecid, requestId, pollStrategy, blsVerify);\n certificate = response.certificate;\n reply = response.reply;\n }\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 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; target_canister?: unknown }[],\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.target_canister && methodName === \"install_chunked_code\") {\n effectiveCanisterId = Principal.from(first.target_canister);\n }\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 { 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, Expiry, 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';\nimport { defaultStrategy } from './strategy';\nimport { DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS } from '../constants';\nimport { ReadRequestType, ReadStateRequest } from '../agent/http/types';\nexport { defaultStrategy } from './strategy';\nexport type PollStrategy = (\n canisterId: Principal,\n requestId: RequestId,\n status: RequestStatusResponseStatus,\n) => Promise<void>;\nexport type PollStrategyFactory = () => PollStrategy;\n\ninterface SignedReadStateRequestWithExpiry {\n body: {\n content: Pick<ReadStateRequest, 'request_type' | 'ingress_expiry'>;\n };\n}\n\n/**\n * Check if an object has a property\n * @param value the object that might have the property\n * @param property the key of property we're looking for\n */\nfunction hasProperty<O extends object, P extends string>(\n value: O,\n property: P,\n): value is O & Record<P, unknown> {\n return Object.prototype.hasOwnProperty.call(value, property);\n}\n\n/**\n * Check if value is a signed read state request with expiry\n * @param value to check\n */\nfunction isSignedReadStateRequestWithExpiry(\n value: unknown,\n): value is SignedReadStateRequestWithExpiry {\n return (\n value !== null &&\n typeof value === 'object' &&\n hasProperty(value, 'body') &&\n value.body !== null &&\n typeof value.body === 'object' &&\n hasProperty(value.body, 'content') &&\n value.body.content !== null &&\n typeof value.body.content === 'object' &&\n hasProperty(value.body.content, 'request_type') &&\n value.body.content.request_type === ReadRequestType.ReadState &&\n hasProperty(value.body.content, 'ingress_expiry') &&\n typeof value.body.content.ingress_expiry === 'object' &&\n value.body.content.ingress_expiry !== null &&\n hasProperty(value.body.content.ingress_expiry, 'toCBOR') &&\n typeof value.body.content.ingress_expiry.toCBOR === 'function' &&\n hasProperty(value.body.content.ingress_expiry, 'toHash') &&\n typeof value.body.content.ingress_expiry.toHash === 'function'\n );\n}\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 repeated 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 = defaultStrategy(),\n request?: unknown,\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\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, blsVerify);\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_block_height = IDL.Nat32;\n const bitcoin_get_block_headers_args = IDL.Record({\n start_height: bitcoin_block_height,\n end_height: IDL.Opt(bitcoin_block_height),\n network: bitcoin_network,\n });\n const bitcoin_block_header = IDL.Vec(IDL.Nat8);\n const bitcoin_get_block_headers_result = IDL.Record({\n tip_height: bitcoin_block_height,\n block_headers: IDL.Vec(bitcoin_block_header),\n });\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 bitcoin_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: bitcoin_block_height,\n tip_block_hash: bitcoin_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 snapshot_id = IDL.Vec(IDL.Nat8);\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 load_snapshot: IDL.Record({\n canister_version: IDL.Nat64,\n taken_at_timestamp: IDL.Nat64,\n snapshot_id: snapshot_id,\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 allowed_viewers: IDL.Vec(IDL.Principal),\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 delete_canister_snapshot_args = IDL.Record({\n canister_id: canister_id,\n snapshot_id: snapshot_id,\n });\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 list_canister_snapshots_args = IDL.Record({\n canister_id: canister_id,\n });\n const snapshot = IDL.Record({\n id: snapshot_id,\n total_size: IDL.Nat64,\n taken_at_timestamp: IDL.Nat64,\n });\n const list_canister_snapshots_result = IDL.Vec(snapshot);\n const load_canister_snapshot_args = IDL.Record({\n canister_id: canister_id,\n sender_canister_version: IDL.Opt(IDL.Nat64),\n snapshot_id: snapshot_id,\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 schnorr_algorithm = IDL.Variant({\n ed25519: IDL.Null,\n bip340secp256k1: IDL.Null,\n });\n const schnorr_public_key_args = IDL.Record({\n key_id: IDL.Record({\n algorithm: schnorr_algorithm,\n name: IDL.Text,\n }),\n canister_id: IDL.Opt(canister_id),\n derivation_path: IDL.Vec(IDL.Vec(IDL.Nat8)),\n });\n const schnorr_public_key_result = IDL.Record({\n public_key: IDL.Vec(IDL.Nat8),\n chain_code: IDL.Vec(IDL.Nat8),\n });\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 schnorr_aux = IDL.Variant({\n bip341: IDL.Record({ merkle_root_hash: IDL.Vec(IDL.Nat8) }),\n });\n const sign_with_schnorr_args = IDL.Record({\n aux: IDL.Opt(schnorr_aux),\n key_id: IDL.Record({\n algorithm: schnorr_algorithm,\n name: IDL.Text,\n }),\n derivation_path: IDL.Vec(IDL.Vec(IDL.Nat8)),\n message: IDL.Vec(IDL.Nat8),\n });\n const sign_with_schnorr_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 subnet_info_args = IDL.Record({ subnet_id: IDL.Principal });\n const subnet_info_result = IDL.Record({ replica_version: IDL.Text });\n const take_canister_snapshot_args = IDL.Record({\n replace_snapshot: IDL.Opt(snapshot_id),\n canister_id: canister_id,\n });\n const take_canister_snapshot_result = snapshot;\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_block_headers: IDL.Func(\n [bitcoin_get_block_headers_args],\n [bitcoin_get_block_headers_result],\n [],\n ),\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 delete_canister_snapshot: IDL.Func([delete_canister_snapshot_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 list_canister_snapshots: IDL.Func(\n [list_canister_snapshots_args],\n [list_canister_snapshots_result],\n [],\n ),\n load_canister_snapshot: IDL.Func([load_canister_snapshot_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 schnorr_public_key: IDL.Func([schnorr_public_key_args], [schnorr_public_key_result], []),\n sign_with_ecdsa: IDL.Func([sign_with_ecdsa_args], [sign_with_ecdsa_result], []),\n sign_with_schnorr: IDL.Func([sign_with_schnorr_args], [sign_with_schnorr_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 subnet_info: IDL.Func([subnet_info_args], [subnet_info_result], []),\n take_canister_snapshot: IDL.Func(\n [take_canister_snapshot_args],\n [take_canister_snapshot_result],\n [],\n ),\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", "export enum FromStringToTokenError {\n FractionalMoreThan8Decimals,\n InvalidFormat,\n FractionalTooManyDecimals,\n}\n", "export const E8S_PER_TOKEN = BigInt(100000000);\n", "import { E8S_PER_TOKEN } from \"../constants/constants\";\nimport { FromStringToTokenError } from \"../enums/token.enums\";\n\nconst DECIMALS_CONVERSION_SUPPORTED = 8;\n\n/**\n * Receives a string representing a number and returns the big int or error.\n *\n * @param amount - in string format\n * @returns bigint | FromStringToTokenError\n */\nexport const convertStringToE8s = (\n value: string,\n): bigint | FromStringToTokenError => {\n // replace exponential format (1e-4) with plain (0.0001)\n // doesn't support decimals for values >= ~1e16\n let amount = value.includes(\"e\")\n ? Number(value).toLocaleString(\"en\", {\n useGrouping: false,\n maximumFractionDigits: 20,\n })\n : value;\n\n // Remove all instances of \",\" and \"'\".\n amount = amount.trim().replace(/[,']/g, \"\");\n\n // Verify that the string is of the format 1234.5678\n const regexMatch = amount.match(/\\d*(\\.\\d*)?/);\n if (!regexMatch || regexMatch[0] !== amount) {\n return FromStringToTokenError.InvalidFormat;\n }\n\n const [integral, fractional] = amount.split(\".\");\n\n let e8s = BigInt(0);\n\n if (integral) {\n try {\n e8s += BigInt(integral) * E8S_PER_TOKEN;\n } catch {\n return FromStringToTokenError.InvalidFormat;\n }\n }\n\n if (fractional) {\n if (fractional.length > 8) {\n return FromStringToTokenError.FractionalMoreThan8Decimals;\n }\n try {\n e8s += BigInt(fractional.padEnd(8, \"0\"));\n } catch {\n return FromStringToTokenError.InvalidFormat;\n }\n }\n\n return e8s;\n};\n\n/**\n * Receives a string representing a number and returns the big int or error.\n *\n * @param amount - in string format\n * @returns bigint | FromStringToTokenError\n */\nconst convertStringToUlps = ({\n amount,\n decimals,\n}: {\n amount: string;\n decimals: number;\n}): bigint | FromStringToTokenError => {\n // Remove all instances of \",\" and \"'\".\n amount = amount.trim().replace(/[,']/g, \"\");\n\n // Verify that the string is of the format 1234.5678\n const regexMatch = amount.match(/\\d*(\\.\\d*)?/);\n if (!regexMatch || regexMatch[0] !== amount) {\n return FromStringToTokenError.InvalidFormat;\n }\n\n const [integral, fractional] = amount.split(\".\");\n\n let ulps = 0n;\n const ulpsPerToken = 10n ** BigInt(decimals);\n\n if (integral) {\n try {\n ulps += BigInt(integral) * ulpsPerToken;\n } catch {\n return FromStringToTokenError.InvalidFormat;\n }\n }\n\n if (fractional) {\n if (fractional.length > decimals) {\n return FromStringToTokenError.FractionalTooManyDecimals;\n }\n try {\n ulps += BigInt(fractional.padEnd(decimals, \"0\"));\n } catch {\n return FromStringToTokenError.InvalidFormat;\n }\n }\n\n return ulps;\n};\n\nexport interface Token {\n symbol: string;\n name: string;\n decimals: number;\n logo?: string;\n}\n\n// TODO: Remove this token and use the value from ICP ledger\nexport const ICPToken: Token = {\n symbol: \"ICP\",\n name: \"Internet Computer\",\n decimals: 8,\n};\n\n/**\n * Deprecated. Use TokenAmountV2 instead which supports decimals !== 8.\n *\n * Represents an amount of tokens.\n *\n * @param e8s - The amount of tokens in bigint.\n * @param token - The token type.\n */\nexport class TokenAmount {\n private constructor(\n protected e8s: bigint,\n public token: Token,\n ) {\n if (token.decimals !== 8) {\n throw new Error(\"Use TokenAmountV2 for number of decimals other than 8\");\n }\n }\n\n /**\n * Initialize from a bigint. Bigint are considered e8s.\n *\n * @param {amount: bigint; token?: Token;} params\n * @param {bigint} params.amount The amount in bigint format.\n * @param {Token} params.token The token type.\n */\n public static fromE8s({\n amount,\n token,\n }: {\n amount: bigint;\n token: Token;\n }): TokenAmount {\n return new TokenAmount(amount, token);\n }\n\n /**\n * Initialize from a string. Accepted formats:\n *\n * 1234567.8901\n * 1'234'567.8901\n * 1,234,567.8901\n *\n * @param {amount: string; token?: Token;} params\n * @param {string} params.amount The amount in string format.\n * @param {Token} params.token The token type.\n */\n public static fromString({\n amount,\n token,\n }: {\n amount: string;\n token: Token;\n }): TokenAmount | FromStringToTokenError {\n // If parsing the number fails because of the number of decimals, we still\n // want the error to be about the number of decimals and not about the\n // parsing.\n if (token.decimals !== 8) {\n throw new Error(\"Use TokenAmountV2 for number of decimals other than 8\");\n }\n const e8s = convertStringToE8s(amount);\n\n if (typeof e8s === \"bigint\") {\n return new TokenAmount(e8s, token);\n }\n return e8s;\n }\n\n /**\n * Initialize from a number.\n *\n * 1 integer is considered E8S_PER_TOKEN\n *\n * @param {amount: number; token?: Token;} params\n * @param {string} params.amount The amount in number format.\n * @param {Token} params.token The token type.\n */\n public static fromNumber({\n amount,\n token,\n }: {\n amount: number;\n token: Token;\n }): TokenAmount {\n const tokenAmount = TokenAmount.fromString({\n amount: amount.toString(),\n token,\n });\n if (tokenAmount instanceof TokenAmount) {\n return tokenAmount;\n }\n if (tokenAmount === FromStringToTokenError.FractionalMoreThan8Decimals) {\n throw new Error(`Number ${amount} has more than 8 decimals`);\n }\n\n // This should never happen\n throw new Error(`Invalid number ${amount}`);\n }\n\n /**\n *\n * @returns The amount of e8s.\n */\n public toE8s(): bigint {\n return this.e8s;\n }\n}\n\n/**\n * Represents an amount of tokens.\n *\n * @param upls - The amount of tokens in units in the last place. If the token\n * supports N decimals, 10^N ulp = 1 token.\n * @param token - The token type.\n */\nexport class TokenAmountV2 {\n private constructor(\n protected ulps: bigint,\n public token: Token,\n ) {}\n\n /**\n * Initialize from a bigint. Bigint are considered ulps.\n *\n * @param {amount: bigint; token?: Token;} params\n * @param {bigint} params.amount The amount in bigint format.\n * @param {Token} params.token The token type.\n */\n public static fromUlps({\n amount,\n token,\n }: {\n amount: bigint;\n token: Token;\n }): TokenAmountV2 {\n return new TokenAmountV2(amount, token);\n }\n\n /**\n * Initialize from a string. Accepted formats:\n *\n * 1234567.8901\n * 1'234'567.8901\n * 1,234,567.8901\n *\n * @param {amount: string; token?: Token;} params\n * @param {string} params.amount The amount in string format.\n * @param {Token} params.token The token type.\n */\n public static fromString({\n amount,\n token,\n }: {\n amount: string;\n token: Token;\n }): TokenAmountV2 | FromStringToTokenError {\n const ulps = convertStringToUlps({ amount, decimals: token.decimals });\n\n if (typeof ulps === \"bigint\") {\n return new TokenAmountV2(ulps, token);\n }\n return ulps;\n }\n\n /**\n * Initialize from a number.\n *\n * 1 integer is considered 10^{token.decimals} ulps\n *\n * @param {amount: number; token?: Token;} params\n * @param {string} params.amount The amount in number format.\n * @param {Token} params.token The token type.\n */\n public static fromNumber({\n amount,\n token,\n }: {\n amount: number;\n token: Token;\n }): TokenAmountV2 {\n const tokenAmount = TokenAmountV2.fromString({\n amount: amount.toFixed(\n Math.min(DECIMALS_CONVERSION_SUPPORTED, token.decimals),\n ),\n token,\n });\n if (tokenAmount instanceof TokenAmountV2) {\n return tokenAmount;\n }\n if (tokenAmount === FromStringToTokenError.FractionalTooManyDecimals) {\n throw new Error(\n `Number ${amount} has more than ${token.decimals} decimals`,\n );\n }\n\n // This should never happen\n throw new Error(`Invalid number ${amount}`);\n }\n\n /**\n *\n * @returns The amount of ulps.\n */\n public toUlps(): bigint {\n return this.ulps;\n }\n\n /**\n *\n * @returns The amount of ulps in e8s precision\n */\n public toE8s(): bigint {\n if (this.token.decimals < 8) {\n return this.ulps * 10n ** BigInt(8 - this.token.decimals);\n }\n if (this.token.decimals === 8) {\n return this.ulps;\n }\n return this.ulps / 10n ** BigInt(this.token.decimals - 8);\n }\n}\n", "import type { Principal } from \"@dfinity/principal\";\nimport type { QueryParams } from \"../types/query.params\";\n\nexport abstract class Canister<T> {\n protected constructor(\n private readonly id: Principal,\n protected readonly service: T,\n protected readonly certifiedService: T,\n ) {}\n\n get canisterId(): Principal {\n return this.id;\n }\n\n protected caller = ({ certified = true }: QueryParams): T =>\n certified ? this.certifiedService : this.service;\n}\n", "/**\n * Checks if a given argument is null or undefined.\n *\n * @template T - The type of the argument.\n * @param {T | undefined | null} argument - The argument to check.\n * @returns {argument is undefined | null} `true` if the argument is null or undefined; otherwise, `false`.\n */\nexport const isNullish = <T>(\n argument: T | undefined | null,\n): argument is undefined | null => argument === null || argument === undefined;\n\n/**\n * Checks if a given argument is neither null nor undefined.\n *\n * @template T - The type of the argument.\n * @param {T | undefined | null} argument - The argument to check.\n * @returns {argument is NonNullable<T>} `true` if the argument is not null or undefined; otherwise, `false`.\n */\nexport const nonNullish = <T>(\n argument: T | undefined | null,\n): argument is NonNullable<T> => !isNullish(argument);\n\n/**\n * Checks if a given value is not null, not undefined, and not an empty string.\n *\n * @param {string | undefined | null} value - The value to check.\n * @returns {boolean} `true` if the value is not null, not undefined, and not an empty string; otherwise, `false`.\n */\nexport const notEmptyString = (\n value: string | undefined | null,\n): value is string => nonNullish(value) && value !== \"\";\n\n/**\n * Checks if a given value is null, undefined, or an empty string.\n *\n * @param {string | undefined | null} value - The value to check.\n * @returns {value is undefined | null | \"\"} Type predicate indicating if the value is null, undefined, or an empty string.\n */\nexport const isEmptyString = (\n value: string | undefined | null,\n): value is undefined | null | \"\" => !notEmptyString(value);\n", "import type { QueryAndUpdateParams } from \"../types/query-and-update.params\";\nimport { isNullish } from \"../utils/nullish.utils\";\n\n/**\n * This service performs a query (not-certified) call and/or an update (certified) call, and handles the results.\n *\n * It is useful because it can do both type of calls for security reasons.\n * For example, malicious nodes can forge transactions and balance when calling an Index canister, if no update is performed to certify the results.\n *\n * Furthermore, it can handle the results of the calls in different ways:\n * - `query` only performs a query call.\n * - `update` only performs an update call.\n * - `query_and_update` performs both calls.\n *\n * The resolution can be:\n * - `all_settled` waits for all calls to settle.\n * - `race` waits for the first call to settle (typically, `query` is the fastest one).\n *\n * Once the call(s) are done, the response is handled by the `onLoad` callback.\n * However, if an error occurs, it is handled by the error callbacks, if provided: one for the query call and one for the update call.\n *\n * @param {QueryAndUpdateParams<R, E>} params The parameters to perform the request.\n * @param {QueryAndUpdateRequest<R>} params.request The request to perform.\n * @param {QueryAndUpdateOnResponse<R>} params.onLoad The callback to handle the response of the request.\n * @param {QueryAndUpdateOnQueryError<E>} [params.onQueryError] The callback to handle the error of the `query` request.\n * @param {QueryAndUpdateOnUpdateError<E>} [params.onUpdateError] The callback to handle the error of the `update` request.\n * @param {QueryAndUpdateStrategy} [params.strategy=\"query_and_update\"] The strategy to use. Default is `query_and_update`.\n * @param {QueryAndUpdateIdentity} params.identity The identity to use for the request.\n * @param {QueryAndUpdatePromiseResolution} [params.resolution=\"race\"] The resolution to use. Default is `race`.\n *\n * @template R The type of the response.\n * @template E The type of the error.\n *\n * @returns A promise that resolves when the request is done.\n */\nexport const queryAndUpdate = async <R, E = unknown>({\n request,\n onLoad,\n onQueryError,\n onUpdateError,\n strategy = \"query_and_update\",\n identity,\n resolution = \"race\",\n}: QueryAndUpdateParams<R, E>): Promise<void> => {\n let certifiedDone = false;\n\n const queryOrUpdate = (certified: boolean) =>\n request({ certified, identity })\n .then((response) => {\n if (certifiedDone) {\n return;\n }\n\n onLoad({ certified, response });\n })\n .catch((error: E) => {\n if (!certified) {\n onQueryError?.({ error, identity });\n }\n\n if (certifiedDone) {\n return;\n }\n\n if (isNullish(onUpdateError)) {\n return;\n }\n\n console.error(error);\n\n if (!certified) {\n return;\n }\n\n onUpdateError({ error, identity });\n })\n .finally(() => (certifiedDone = certifiedDone || certified));\n\n const requests: Array<Promise<void>> =\n strategy === \"query\"\n ? [queryOrUpdate(false)]\n : strategy === \"update\"\n ? [queryOrUpdate(true)]\n : [queryOrUpdate(false), queryOrUpdate(true)];\n\n await (resolution === \"all_settled\"\n ? Promise.allSettled(requests)\n : Promise.race(requests));\n};\n", "import {\n Actor,\n type ActorConfig,\n type ActorSubclass,\n type Agent,\n} from \"@dfinity/agent\";\nimport type { IDL } from \"@dfinity/candid\";\nimport type { Principal } from \"@dfinity/principal\";\nimport type { CanisterOptions } from \"../types/canister.options\";\nimport { defaultAgent } from \"./agent.utils\";\n\ntype RequiredCanisterOptions<T> = Required<\n Pick<CanisterOptions<T>, \"canisterId\">\n> &\n Omit<CanisterOptions<T>, \"canisterId\">;\n\nexport const createServices = <T>({\n options: {\n canisterId,\n serviceOverride,\n certifiedServiceOverride,\n agent: agentOption,\n callTransform,\n queryTransform,\n },\n idlFactory,\n certifiedIdlFactory,\n}: {\n options: RequiredCanisterOptions<T> &\n Pick<ActorConfig, \"queryTransform\" | \"callTransform\">;\n idlFactory: IDL.InterfaceFactory;\n certifiedIdlFactory: IDL.InterfaceFactory;\n}): {\n service: ActorSubclass<T>;\n certifiedService: ActorSubclass<T>;\n agent: Agent;\n canisterId: Principal;\n} => {\n const agent: Agent = agentOption ?? defaultAgent();\n\n const service: ActorSubclass<T> =\n serviceOverride ??\n Actor.createActor<T>(idlFactory, {\n agent,\n canisterId,\n callTransform,\n queryTransform,\n });\n\n const certifiedService: ActorSubclass<T> =\n certifiedServiceOverride ??\n Actor.createActor<T>(certifiedIdlFactory, {\n agent,\n canisterId,\n callTransform,\n queryTransform,\n });\n\n return { service, certifiedService, agent, canisterId };\n};\n", "import {\n AnonymousIdentity,\n HttpAgent,\n type Agent,\n type Identity,\n} from \"@dfinity/agent\";\nimport type { CreateAgentParams } from \"../types/agent.utils\";\nimport { isNullish, nonNullish } from \"./nullish.utils\";\n\n/**\n * Get a default agent that connects to mainnet with the anonymous identity.\n * @returns The default agent to use\n */\nexport const defaultAgent = (): Agent =>\n HttpAgent.createSync({\n host: \"https://icp-api.io\",\n identity: new AnonymousIdentity(),\n });\n\n/**\n * Create an agent for a given identity\n *\n * @param {CreateAgentParams} params The parameters to create a new HTTP agent\n * @param {Identity} params.identity A mandatory identity to use for the agent\n * @param {string} params.host An optional host to connect to, particularly useful for local development\n * @param {boolean} params.fetchRootKey Fetch root key for certificate validation during local development or on testnet\n * @param {boolean} params.verifyQuerySignatures Check for signatures in the state tree signed by the node that replies to queries - i.e. certify responses.\n * @param {number} params.retryTimes Set the number of retries the agent should perform before error.\n */\nexport const createAgent = async ({\n identity,\n host,\n fetchRootKey = false,\n verifyQuerySignatures = false,\n retryTimes,\n}: CreateAgentParams): Promise<HttpAgent> =>\n await HttpAgent.create({\n identity,\n ...(nonNullish(host) && { host }),\n verifyQuerySignatures,\n ...(nonNullish(retryTimes) && { retryTimes }),\n shouldFetchRootKey: fetchRootKey,\n });\n\nexport type AgentManagerConfig = Pick<\n CreateAgentParams,\n \"fetchRootKey\" | \"host\"\n>;\n\n/**\n * AgentManager class manages HttpAgent instances for different identities.\n *\n * It caches agents by identity to optimise resource usage and avoid unnecessary agent creation.\n * Provides functionality to create new agents, retrieve cached agents, and clear the cache when needed.\n */\nexport class AgentManager {\n private agents: Record<string, HttpAgent> | undefined | null = undefined;\n\n private constructor(private readonly config: AgentManagerConfig) {}\n\n /**\n * Static factory method to create a new AgentManager instance.\n *\n * This method serves as an alternative to directly using the private constructor,\n * making it more convenient to create instances of `AgentManager` using a simple and clear method.\n *\n * @param {AgentManagerConfig} config - Configuration options for the AgentManager instance.\n * @param {boolean} config.fetchRootKey - Whether to fetch the root key for certificate validation.\n * @param {string} config.host - The host to connect to.\n * @returns {AgentManager} A new instance of `AgentManager`.\n */\n public static create(config: AgentManagerConfig): AgentManager {\n return new AgentManager(config);\n }\n\n /**\n * Get or create an HTTP agent for a given identity.\n *\n * If the agent for the specified identity has been created and cached, it is retrieved from the cache.\n * If no agent exists for the identity, a new one is created, cached, and then returned.\n *\n * @param {Identity} identity - The identity to be used to create the agent.\n * @returns {Promise<HttpAgent>} The HttpAgent associated with the given identity.\n */\n public getAgent = async ({\n identity,\n }: {\n identity: Identity;\n }): Promise<HttpAgent> => {\n const key = identity.getPrincipal().toText();\n\n if (isNullish(this.agents) || isNullish(this.agents[key])) {\n const agent = await createAgent({\n identity,\n fetchRootKey: this.config.fetchRootKey,\n host: this.config.host,\n verifyQuerySignatures: true,\n });\n\n this.agents = {\n ...(this.agents ?? {}),\n [key]: agent,\n };\n\n return agent;\n }\n\n return this.agents[key];\n };\n\n /**\n * Clear the cache of HTTP agents.\n *\n * This method removes all cached agents, forcing new agent creation on the next request for any identity.\n * Useful when identities have changed or if you want to reset all active connections.\n */\n public clearAgents = (): void => {\n this.agents = null;\n };\n}\n", "export class InvalidPercentageError extends Error {}\nexport class NullishError extends Error {}\n\nexport const assertNonNullish: <T>(\n value: T,\n message?: string,\n // eslint-disable-next-line local-rules/prefer-object-params\n) => asserts value is NonNullable<T> = <T>(\n value: T,\n message?: string,\n): void => {\n if (value === null || value === undefined) {\n throw new NullishError(message);\n }\n};\n\n// eslint-disable-next-line local-rules/prefer-object-params\nexport const asNonNullish = <T>(value: T, message?: string): NonNullable<T> => {\n assertNonNullish(value, message);\n return value;\n};\n\nexport const assertPercentageNumber = (percentage: number) => {\n if (percentage < 0 || percentage > 100) {\n throw new InvalidPercentageError(\n `${percentage} is not a valid percentage number.`,\n );\n }\n};\n", "import { assertNonNullish } from \"./asserts.utils\";\n\nexport const uint8ArrayToBigInt = (array: Uint8Array): bigint => {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n if (typeof view.getBigUint64 === \"function\") {\n return view.getBigUint64(0);\n }\n const high = BigInt(view.getUint32(0));\n const low = BigInt(view.getUint32(4));\n\n return (high << BigInt(32)) + low;\n};\n\nexport const bigIntToUint8Array = (value: bigint): Uint8Array => {\n const buffer = new ArrayBuffer(8);\n const view = new DataView(buffer);\n if (typeof view.setBigUint64 === \"function\") {\n view.setBigUint64(0, value);\n } else {\n const high = Number(value >> BigInt(32));\n const low = Number(value & BigInt(0xffffffff));\n\n view.setUint32(0, high);\n view.setUint32(4, low);\n }\n\n return new Uint8Array(buffer);\n};\n\nexport const numberToUint8Array = (value: number): Uint8Array => {\n const view = new DataView(new ArrayBuffer(8));\n for (let index = 7; index >= 0; --index) {\n view.setUint8(index, value % 256);\n value = value >> 8;\n }\n return new Uint8Array(view.buffer);\n};\n\nexport const arrayBufferToUint8Array = (buffer: ArrayBuffer): Uint8Array =>\n new Uint8Array(buffer);\n\nexport const uint8ArrayToArrayOfNumber = (array: Uint8Array): Array<number> =>\n Array.from(array);\n\nexport const arrayOfNumberToUint8Array = (numbers: Array<number>): Uint8Array =>\n new Uint8Array(numbers);\n\nexport const asciiStringToByteArray = (text: string): Array<number> =>\n Array.from(text).map((c) => c.charCodeAt(0));\n\nexport const hexStringToUint8Array = (hexString: string): Uint8Array => {\n const matches = hexString.match(/.{1,2}/g);\n\n assertNonNullish(matches, \"Invalid hex string.\");\n\n return Uint8Array.from(matches.map((byte) => parseInt(byte, 16)));\n};\n\n/**\n * Compare two Uint8Arrays for byte-level equality.\n *\n * @param {Object} params\n * @param {Uint8Array} params.a - First Uint8Array to compare.\n * @param {Uint8Array} params.b - Second Uint8Array to compare.\n * @returns {boolean} True if both arrays have the same length and identical contents.\n */\nexport const uint8ArraysEqual = ({ a, b }: { a: Uint8Array; b: Uint8Array }) =>\n a.length === b.length && a.every((byte, i) => byte === b[i]);\n\nexport const uint8ArrayToHexString = (bytes: Uint8Array | number[]) => {\n if (!(bytes instanceof Uint8Array)) {\n bytes = Uint8Array.from(bytes);\n }\n return bytes.reduce(\n (str, byte) => str + byte.toString(16).padStart(2, \"0\"),\n \"\",\n );\n};\n\nexport const candidNumberArrayToBigInt = (array: number[]): bigint => {\n let result = 0n;\n for (let i = array.length - 1; i >= 0; i--) {\n result = (result << 32n) + BigInt(array[i]);\n }\n return result;\n};\n", "import { assertNonNullish } from \"./asserts.utils\";\n\nconst ALPHABET = \"abcdefghijklmnopqrstuvwxyz234567\";\n\n// Build a lookup table for decoding.\nconst LOOKUP_TABLE: Record<string, number> = Object.create(null);\nfor (let i = 0; i < ALPHABET.length; i++) {\n LOOKUP_TABLE[ALPHABET[i]] = i;\n}\n\n// Add aliases for rfc4648.\nLOOKUP_TABLE[\"0\"] = LOOKUP_TABLE.o;\nLOOKUP_TABLE[\"1\"] = LOOKUP_TABLE.i;\n\n/**\n * Encode an Uint8Array to a base32 string.\n *\n * @param input The input array to encode.\n * @returns A Base32 string encoding the input.\n */\nexport const encodeBase32 = (input: Uint8Array): string => {\n // How many bits will we skip from the first byte.\n let skip = 0;\n // 5 high bits, carry from one byte to the next.\n let bits = 0;\n\n // The output string in base32.\n let output = \"\";\n\n const encodeByte = (byte: number): number => {\n if (skip < 0) {\n // we have a carry from the previous byte\n bits |= byte >> -skip;\n } else {\n // no carry\n bits = (byte << skip) & 248;\n }\n\n if (skip > 3) {\n // Not enough data to produce a character, get us another one\n skip -= 8;\n return 1;\n }\n\n if (skip < 4) {\n // produce a character\n output += ALPHABET[bits >> 3];\n skip += 5;\n }\n\n return 0;\n };\n\n for (let i = 0; i < input.length; ) {\n i += encodeByte(input[i]);\n }\n\n return output + (skip < 0 ? ALPHABET[bits >> 3] : \"\");\n};\n\n/**\n * Decode a base32 string to Uint8Array.\n *\n * @param input The input string to decode.\n * @param input The base32 encoded string to decode.\n */\nexport const decodeBase32 = (input: string): Uint8Array => {\n // how many bits we have from the previous character.\n let skip = 0;\n // current byte we're producing.\n let byte = 0;\n\n const output = new Uint8Array(((input.length * 4) / 3) | 0);\n let o = 0;\n\n const decodeChar = (char: string) => {\n // Consume a character from the stream, store\n // the output in this.output. As before, better\n // to use update().\n let val = LOOKUP_TABLE[char.toLowerCase()];\n assertNonNullish(val, `Invalid character: ${JSON.stringify(char)}`);\n\n // move to the high bits\n val <<= 3;\n byte |= val >>> skip;\n skip += 5;\n\n if (skip >= 8) {\n // We have enough bytes to produce an output\n output[o++] = byte;\n skip -= 8;\n\n if (skip > 0) {\n byte = (val << (5 - skip)) & 255;\n } else {\n byte = 0;\n }\n }\n };\n\n for (const c of input) {\n decodeChar(c);\n }\n\n return output.slice(0, o);\n};\n", "/**\n * Converts a Uint8Array (binary data) to a base64 encoded string.\n *\n * @param {Uint8Array} uint8Array - The Uint8Array containing binary data to be encoded.\n * @returns {string} - The base64 encoded string representation of the binary data.\n */\nexport const uint8ArrayToBase64 = (uint8Array: Uint8Array): string =>\n btoa(String.fromCharCode(...new Uint8Array(uint8Array)));\n\n/**\n * Converts a base64 encoded string to a Uint8Array (binary data).\n *\n * @param {string} base64String - The base64 encoded string to be decoded.\n * @returns {Uint8Array} - The Uint8Array representation of the decoded binary data.\n */\nexport const base64ToUint8Array = (base64String: string): Uint8Array =>\n Uint8Array.from(atob(base64String), (c) => c.charCodeAt(0));\n", "// This file is translated to JavaScript from\n// https://lxp32.github.io/docs/a-simple-example-crc32-calculation/\nconst lookUpTable: Uint32Array = new Uint32Array([\n 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,\n 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,\n 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,\n 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,\n 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,\n 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,\n 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,\n 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,\n 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,\n 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,\n 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,\n 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,\n 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,\n 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,\n 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,\n 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,\n 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,\n 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,\n 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,\n 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,\n 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,\n 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,\n 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,\n 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,\n 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,\n 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,\n 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,\n 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,\n 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,\n 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,\n 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,\n 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,\n 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,\n 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,\n 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,\n 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,\n 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,\n 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,\n 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,\n 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,\n 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,\n 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,\n 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,\n]);\n\nconst crc32 = (bytes: Uint8Array): number => {\n let crc = -1;\n\n for (let i = 0; i < bytes.length; i++) {\n const byte = bytes[i];\n const t = (byte ^ crc) & 0xff;\n crc = lookUpTable[t] ^ (crc >>> 8);\n }\n\n return (crc ^ -1) >>> 0;\n};\n\nexport const bigEndianCrc32 = (bytes: Uint8Array): Uint8Array => {\n const checksumArrayBuf = new ArrayBuffer(4);\n const view = new DataView(checksumArrayBuf);\n view.setUint32(0, crc32(bytes), false);\n return new Uint8Array(checksumArrayBuf);\n};\n", "import { Principal } from \"@dfinity/principal\";\nimport { nonNullish } from \"./nullish.utils\";\n\nconst JSON_KEY_BIGINT = \"__bigint__\";\nconst JSON_KEY_PRINCIPAL = \"__principal__\";\nconst JSON_KEY_UINT8ARRAY = \"__uint8array__\";\n\n/**\n * A custom replacer for `JSON.stringify` that converts specific types not natively supported\n * by the API into JSON-compatible formats.\n *\n * Supported conversions:\n * - `BigInt` \u2192 `{ \"__bigint__\": string }`\n * - `Principal` \u2192 `{ \"__principal__\": string }`\n * - `Uint8Array` \u2192 `{ \"__uint8array__\": number[] }`\n *\n * @param {string} _key - Ignored. Only provided for API compatibility.\n * @param {unknown} value - The value to transform before stringification.\n * @returns {unknown} The transformed value if it matches a known type, otherwise the original value.\n */\n// eslint-disable-next-line local-rules/prefer-object-params\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 custom reviver for `JSON.parse` that reconstructs specific types from their JSON-encoded representations.\n *\n * This reverses the transformations applied by `jsonReplacer`, restoring the original types.\n *\n * Supported conversions:\n * - `{ \"__bigint__\": string }` \u2192 `BigInt`\n * - `{ \"__principal__\": string }` \u2192 `Principal`\n * - `{ \"__uint8array__\": number[] }` \u2192 `Uint8Array`\n *\n * @param {string} _key - Ignored but provided for API compatibility.\n * @param {unknown} value - The parsed value to transform.\n * @returns {unknown} The reconstructed value if it matches a known type, otherwise the original value.\n */\n// eslint-disable-next-line local-rules/prefer-object-params\nexport const jsonReviver = (_key: string, value: unknown): unknown => {\n const mapValue = <T>(key: string): T => (value as Record<string, T>)[key];\n\n if (\n nonNullish(value) &&\n typeof value === \"object\" &&\n JSON_KEY_BIGINT in value\n ) {\n return BigInt(mapValue(JSON_KEY_BIGINT));\n }\n\n if (\n nonNullish(value) &&\n typeof value === \"object\" &&\n JSON_KEY_PRINCIPAL in value\n ) {\n return Principal.fromText(mapValue(JSON_KEY_PRINCIPAL));\n }\n\n if (\n nonNullish(value) &&\n typeof value === \"object\" &&\n JSON_KEY_UINT8ARRAY in value\n ) {\n return Uint8Array.from(mapValue(JSON_KEY_UINT8ARRAY));\n }\n\n return value;\n};\n", "import { uint8ArrayToHexString } from \"./arrays.utils\";\nimport { jsonReplacer } from \"./json.utils\";\n\n/**\n * Generates a SHA-256 hash from the given object.\n *\n * The object is first stringified using a custom `jsonReplacer`, then\n * hashed using the SubtleCrypto API. The resulting hash is returned as a hex string.\n *\n * @template T - The type of the input object.\n * @param {T} params - The object to hash.\n * @returns {Promise<string>} A promise that resolves to the hex string of the SHA-256 hash.\n */\nexport const hashObject = async <T extends object>(\n params: T,\n): Promise<string> => {\n const jsonString = JSON.stringify(params, jsonReplacer);\n\n return await hashText(jsonString);\n};\n\n/**\n * Generates a SHA-256 hash from a plain text string.\n *\n * The string is UTF-8 encoded and hashed using the SubtleCrypto API.\n * The resulting hash is returned as a hexadecimal string.\n *\n * @param {string} text - The text to hash.\n * @returns {Promise<string>} A promise that resolves to the hex string of the SHA-256 hash.\n */\nexport const hashText = async (text: string): Promise<string> => {\n const dataBuffer = new TextEncoder().encode(text);\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", dataBuffer);\n\n return uint8ArrayToHexString(new Uint8Array(hashBuffer));\n};\n", "const SECONDS_IN_MINUTE = 60;\nconst MINUTES_IN_HOUR = 60;\nconst HOURS_IN_DAY = 24;\nconst DAYS_IN_NON_LEAP_YEAR = 365;\n\nexport interface I18nSecondsToDuration {\n year: string;\n year_plural: string;\n month: string;\n month_plural: string;\n day: string;\n day_plural: string;\n hour: string;\n hour_plural: string;\n minute: string;\n minute_plural: string;\n second: string;\n second_plural: string;\n}\n\nconst EN_TIME: I18nSecondsToDuration = {\n year: \"year\",\n year_plural: \"years\",\n month: \"month\",\n month_plural: \"months\",\n day: \"day\",\n day_plural: \"days\",\n hour: \"hour\",\n hour_plural: \"hours\",\n minute: \"minute\",\n minute_plural: \"minutes\",\n second: \"second\",\n second_plural: \"seconds\",\n};\n\n/**\n * Convert seconds to a human-readable duration, such as \"6 days, 10 hours.\"\n * @param {Object} options - The options object.\n * @param {bigint} options.seconds - The number of seconds to convert.\n * @param {I18nSecondsToDuration} [options.i18n] - The i18n object for customizing language and units. Defaults to English.\n * @returns {string} The human-readable duration string.\n */\nexport const secondsToDuration = ({\n seconds,\n i18n = EN_TIME,\n}: {\n seconds: bigint;\n i18n?: I18nSecondsToDuration;\n}): string => {\n let minutes = seconds / BigInt(SECONDS_IN_MINUTE);\n\n let hours = minutes / BigInt(MINUTES_IN_HOUR);\n minutes -= hours * BigInt(MINUTES_IN_HOUR);\n\n let days = hours / BigInt(HOURS_IN_DAY);\n hours -= days * BigInt(HOURS_IN_DAY);\n\n const years = fullYearsInDays(days);\n days -= daysInYears(years);\n\n const periods = [\n createLabel({ labelKey: \"year\", amount: years }),\n createLabel({ labelKey: \"day\", amount: days }),\n createLabel({ labelKey: \"hour\", amount: hours }),\n createLabel({ labelKey: \"minute\", amount: minutes }),\n ...(seconds > BigInt(0) && seconds < BigInt(60)\n ? [createLabel({ labelKey: \"second\", amount: seconds })]\n : []),\n ];\n\n return periods\n .filter(({ amount }) => amount > 0)\n .slice(0, 2)\n .map(\n (labelInfo) =>\n `${labelInfo.amount} ${\n labelInfo.amount === 1\n ? i18n[labelInfo.labelKey]\n : i18n[`${labelInfo.labelKey}_plural`]\n }`,\n )\n .join(\", \");\n};\n\nconst fullYearsInDays = (days: bigint): bigint => {\n // Use integer division.\n let years = days / BigInt(DAYS_IN_NON_LEAP_YEAR);\n while (daysInYears(years) > days) {\n years--;\n }\n return years;\n};\n\nconst daysInYears = (years: bigint): bigint => {\n // Use integer division.\n const leapDays = years / BigInt(4);\n return years * BigInt(DAYS_IN_NON_LEAP_YEAR) + leapDays;\n};\n\ntype LabelKey = \"year\" | \"month\" | \"day\" | \"hour\" | \"minute\" | \"second\";\ninterface LabelInfo {\n labelKey: LabelKey;\n amount: number;\n}\nconst createLabel = ({\n labelKey,\n amount,\n}: {\n labelKey: LabelKey;\n amount: bigint;\n}): LabelInfo => ({\n labelKey,\n amount: Number(amount),\n});\n\nconst NANOSECONDS_PER_MILLISECOND = 1_000_000n;\n\n/**\n * Returns the current timestamp in nanoseconds as a `bigint`.\n *\n * @returns {bigint} The current timestamp in nanoseconds.\n */\nexport const nowInBigIntNanoSeconds = (): bigint =>\n BigInt(Date.now()) * NANOSECONDS_PER_MILLISECOND;\n\n/**\n * Converts a given `Date` object to a timestamp in nanoseconds as a `bigint`.\n *\n * @param {Date} date - The `Date` object to convert.\n * @returns {bigint} The timestamp in nanoseconds.\n */\nexport const toBigIntNanoSeconds = (date: Date): bigint =>\n BigInt(date.getTime()) * NANOSECONDS_PER_MILLISECOND;\n", "/**\n * Creates a debounced version of the provided function.\n *\n * The debounced function postpones its execution until after a certain amount of time\n * has elapsed since the last time it was invoked. This is useful for limiting the rate\n * at which a function is called (e.g. in response to user input or events).\n *\n * @param {Function} func - The function to debounce. It will only be called after no new calls happen within the specified timeout.\n * @param {number} [timeout=300] - The debounce delay in milliseconds. Defaults to 300ms if not provided or invalid.\n * @returns {(args: unknown[]) => void} A debounced version of the original function.\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type, local-rules/prefer-object-params\nexport const debounce = (func: Function, timeout?: number) => {\n let timer: NodeJS.Timer | undefined;\n\n return (...args: unknown[]) => {\n const next = () => func(...args);\n\n if (timer) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore TypeScript global and window confusion even if we are using @types/node\n clearTimeout(timer);\n }\n\n timer = setTimeout(\n next,\n timeout !== undefined && timeout > 0 ? timeout : 300,\n );\n };\n};\n", "import type { Nullable, NullishNullable } from \"../types/did.utils\";\nimport { assertNonNullish } from \"./asserts.utils\";\nimport { nonNullish } from \"./nullish.utils\";\n\n/**\n * Converts a value into a Candid-style variant representation of an optional value.\n *\n * @template T The type of the value.\n * @param {T | null | undefined} value - The value to convert into a Candid-style variant.\n * @returns {Nullable<T>} A Candid-style variant representation: an empty array for `null` and `undefined` or an array with the value.\n */\nexport const toNullable = <T>(value?: T | null): Nullable<T> =>\n nonNullish(value) ? [value] : [];\n\n/**\n * Extracts the value from a Candid-style variant representation of an optional value.\n *\n * @template T The type of the value.\n * @param {Nullable<T>} value - A Candid-style variant representing an optional value.\n * @returns {T | undefined} The extracted value, or `undefined` if the array is empty.\n */\nexport const fromNullable = <T>(value: Nullable<T>): T | undefined =>\n value?.[0];\n\n/**\n * Extracts the value from a Candid-style variant representation of an optional value,\n * ensuring the value is defined. Throws an error if the array is empty or the value is nullish.\n *\n * @template T The type of the value.\n * @param {Nullable<T>} value - A Candid-style variant representing an optional value.\n * @returns {T} The extracted value.\n * @throws {Error} If the array is empty or the value is nullish.\n */\nexport const fromDefinedNullable = <T>(value: Nullable<T>): T => {\n const result = fromNullable(value);\n\n assertNonNullish(result);\n\n return result;\n};\n\n/**\n * Extracts the value from a nullish Candid-style variant representation.\n *\n * @template T The type of the value.\n * @param {NullishNullable<T>} value - A Candid-style variant or `undefined`.\n * @returns {T | undefined} The extracted value, or `undefined` if the input is nullish or the array is empty.\n */\nexport const fromNullishNullable = <T>(\n value: NullishNullable<T>,\n): T | undefined => fromNullable(value ?? []);\n", "import type { Principal } from \"@dfinity/principal\";\n\n/**\n * Convert a principal to a Uint8Array 32 length.\n * e.g. Useful to convert a canister ID when topping up cycles with the Cmc canister\n * @param principal The principal that needs to be converted to Subaccount\n */\nexport const principalToSubAccount = (principal: Principal): Uint8Array => {\n const bytes: Uint8Array = principal.toUint8Array();\n const subAccount: Uint8Array = new Uint8Array(32);\n subAccount[0] = bytes.length;\n subAccount.set(bytes, 1);\n return subAccount;\n};\n", "const AMOUNT_VERSION_PARTS = 3;\nconst addZeros = ({\n nums,\n amountZeros,\n}: {\n nums: number[];\n amountZeros: number;\n}): number[] =>\n amountZeros > nums.length\n ? [...nums, ...[...Array(amountZeros - nums.length).keys()].map(() => 0)]\n : nums;\n\nconst convertToNumber = (versionStringPart: string): number => {\n if (!Number.isNaN(Number(versionStringPart))) {\n return Number(versionStringPart);\n }\n const strippedVersion = versionStringPart.split(\"\").reduce((acc, char) => {\n if (Number.isNaN(Number(char))) {\n return acc;\n }\n return acc + char;\n }, \"\");\n return Number(strippedVersion);\n};\n/**\n * Returns true if the current version is smaller than the minVersion, false if equal or bigger.\n * Tags after patch version are ignored, e.g. 1.0.0-beta.1 is considered equal to 1.0.0.\n *\n * @param {Object} params\n * @param {string} params.minVersion Ex: \"1.0.0\"\n * @param {string} params.currentVersion Ex: \"2.0.0\"\n * @returns boolean\n */\nexport const smallerVersion = ({\n minVersion,\n currentVersion,\n}: {\n minVersion: string;\n currentVersion: string;\n}): boolean => {\n const minVersionStandarized = addZeros({\n nums: minVersion.split(\".\").map(convertToNumber),\n amountZeros: AMOUNT_VERSION_PARTS,\n }).join(\".\");\n const currentVersionStandarized = addZeros({\n nums: currentVersion.split(\".\").map(convertToNumber),\n amountZeros: AMOUNT_VERSION_PARTS,\n }).join(\".\");\n // Versions need to have the same number of parts to be comparable\n // Source: https://stackoverflow.com/a/65687141\n return (\n currentVersionStandarized.localeCompare(minVersionStandarized, undefined, {\n numeric: true,\n sensitivity: \"base\",\n }) < 0\n );\n};\n", "import {uint8ArrayToArrayOfNumber} from '@dfinity/utils';\n\n/**\n * Extracts the AAGUID (Authenticator Attestation GUID) from a WebAuthn data buffer.\n *\n * The AAGUID is a 16-byte value located at offsets 37..53 within `authenticatorData`\n * when **attested credential data** is present (i.e., during registration/attestation).\n *\n * For assertion (sign-in) responses, `authenticatorData` is typically 37 bytes and\n * does not include an AAGUID.\n *\n * If the extracted value is all zeros (`00000000-0000-0000-0000-000000000000`),\n * this function returns `{ unknownProvider: null }` since some passkey providers\n * intentionally use a zero AAGUID.\n *\n * @param {Object} params\n * @param {Uint8Array} params.authData - The WebAuthn `authenticatorData` bytes.\n * @returns {{aaguid: string; bytes: Uint8Array} | {invalidAuthData: null} | {unknownProvider: null}}\n * - { aaguidText, aaguidBytes } for valid AAGUID\n * - { unknownProvider: null } for all-zero AAGUID\n * - { invalidAuthData: null } if `authData` is invalid (too short, too long, etc.)\n *\n * @see https://web.dev/articles/webauthn-aaguid\n */\nexport const extractAAGUID = ({\n authData\n}: {\n authData: Uint8Array;\n}):\n | {aaguidText: string; aaguidBytes: Uint8Array}\n | {invalidAuthData: null}\n | {unknownProvider: null} => {\n if (authData.byteLength < 37) {\n return {invalidAuthData: null};\n }\n\n if (authData.byteLength < 53) {\n return {invalidAuthData: null};\n }\n\n const bytes = authData.slice(37, 53);\n\n const result = bytesToAAGUID({bytes});\n\n if ('aaguid' in result) {\n return {aaguidBytes: bytes, aaguidText: result.aaguid};\n }\n\n return {unknownProvider: null};\n};\n\n/**\n * Convert 16 AAGUID bytes to canonical UUID string (lowercase, hyphenated).\n *\n * Returns:\n * - { aaguid } for non-zero AAGUIDs\n * - { unknownProvider: null } for all-zero AAGUID\n * - { invalidBytes: null } if length \u2260 16\n *\n * @param {{bytes: Uint8Array | number[]}} params\n * @returns {{aaguid: string} | {invalidBytes: null} | {unknownProvider: null}}\n */\nexport const bytesToAAGUID = ({\n bytes\n}: {\n bytes: Uint8Array | number[];\n}): {aaguid: string} | {invalidBytes: null} | {unknownProvider: null} => {\n if (bytes.length !== 16) {\n return {invalidBytes: null};\n }\n\n const hex = (bytes instanceof Uint8Array ? uint8ArrayToArrayOfNumber(bytes) : bytes)\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join('');\n\n const aaguid = hex.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, '$1-$2-$3-$4-$5');\n\n // \"00000000-0000-0000-0000-0000000000000\" represents an unknown passkey provider. Some passkey providers use this AAGUID intentionally.\n // Source: https://web.dev/articles/webauthn-aaguid\n if (aaguid === '00000000-0000-0000-0000-000000000000') {\n return {unknownProvider: null};\n }\n\n return {aaguid};\n};\n", "import {DER_COSE_OID, wrapDER, type DerEncodedPublicKey} from '@dfinity/agent';\n\n/**\n * \u26A0\uFE0F !!!WARNING!!! \u26A0\uFE0F\n * This module is a copy/paste of the webauthn functions not exposed by Agent-js.\n * It is therefore not covered by any tests (\u203C\uFE0F) in this library.\n *\n * @see https://github.com/dfinity/agent-js/blob/main/packages/identity/src/identity/webauthn.ts\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 */\nexport function _authDataToCose(authData: Uint8Array): Uint8Array {\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 function _coseToDerEncodedBlob(cose: Uint8Array): DerEncodedPublicKey {\n return wrapDER(cose.buffer as ArrayBuffer, DER_COSE_OID).buffer as DerEncodedPublicKey;\n}\n", "import type {DerEncodedPublicKey, PublicKey} from '@dfinity/agent';\nimport {_coseToDerEncodedBlob} from './cose-utils';\n\n/**\n * \u26A0\uFE0F !!!WARNING!!! \u26A0\uFE0F\n * This module is a copy/paste of the webauthn classes not exposed by Agent-js.\n * It is therefore not covered by any tests (\u203C\uFE0F) in this library.\n *\n * @see https://github.com/dfinity/agent-js/blob/main/packages/identity/src/identity/webauthn.ts\n */\n\n/**\n * COSE-encoded key (CBOR Object Signing and Encryption).\n * serialized as a Uint8Array.\n */\nexport type CoseEncodedKey = Uint8Array;\n\nexport class CosePublicKey implements PublicKey {\n protected _encodedKey: DerEncodedPublicKey;\n\n public constructor(protected _cose: CoseEncodedKey) {\n this._encodedKey = _coseToDerEncodedBlob(_cose);\n }\n\n public toDer(): DerEncodedPublicKey {\n return this._encodedKey;\n }\n}\n", "import type {PublicKey} from '@dfinity/agent';\nimport {uint8ArrayToBase64} from '@dfinity/utils';\nimport {extractAAGUID} from './aaguid';\nimport {type CoseEncodedKey, CosePublicKey} from './agent-js/cose-key';\n\n/**\n * Arguments to initialize a WebAuthn object.\n */\nexport interface InitWebAuthnCredentialArgs {\n /**\n * The credential ID (authenticator\u2019s `rawId`) as bytes.\n */\n rawId: Uint8Array;\n\n /**\n * COSE-encoded public key extracted from attestation/authData.\n */\n cose: CoseEncodedKey;\n}\n\nexport interface InitWebAuthnNewCredentialArgs extends InitWebAuthnCredentialArgs {\n /**\n * The authenticator data from the attestation.\n */\n authData: Uint8Array;\n}\n\n/**\n * A wrapper around a WebAuthn credential that provides various base information such as its ID or public key.\n */\nexport abstract class WebAuthnCredential {\n readonly #credentialId: Uint8Array;\n readonly #publicKey: CosePublicKey;\n\n /**\n * @param args - {@link InitWebAuthnCredentialArgs} used to initialize the credential.\n * @param args.rawId - Credential ID (`rawId`) as bytes.\n * @param args.cose - COSE-encoded public key.\n */\n constructor({rawId: credentialId, cose}: InitWebAuthnCredentialArgs) {\n this.#credentialId = credentialId;\n this.#publicKey = new CosePublicKey(cose);\n }\n\n /**\n * Returns the public key for this credential.\n */\n getPublicKey(): PublicKey {\n return this.#publicKey;\n }\n\n /**\n * Returns the credential ID as bytes.\n */\n getCredentialId(): Uint8Array {\n return this.#credentialId;\n }\n\n /**\n * Returns the credential ID as textual representation (a base64 string).\n */\n getCredentialIdText(): string {\n return uint8ArrayToBase64(this.#credentialId);\n }\n}\n\n/**\n * A wrapper around a newly created WebAuthn credential.\n * It is created using `navigator.credentials.create` which provides an attestation.\n */\nexport class WebAuthnNewCredential extends WebAuthnCredential {\n readonly #aaguidText: string | undefined;\n readonly #aaguidBytes: Uint8Array | undefined;\n\n /**\n * @param args - {@link InitWebAuthnNewCredentialArgs} used to initialize the credential.\n * @param args.rawId - Credential ID (`rawId`) as bytes.\n * @param args.cose - COSE-encoded public key.\n * @params args.authData - Authenticator data from the attestation.\n */\n constructor({authData, ...rest}: InitWebAuthnNewCredentialArgs) {\n super(rest);\n\n const optionAaguid = extractAAGUID({authData});\n this.#aaguidText = 'aaguidText' in optionAaguid ? optionAaguid.aaguidText : undefined;\n this.#aaguidBytes = 'aaguidBytes' in optionAaguid ? optionAaguid.aaguidBytes : undefined;\n }\n\n /**\n * Returns AAGUID (Authenticator Attestation GUID).\n */\n getAAGUID(): Uint8Array | undefined {\n return this.#aaguidBytes;\n }\n\n /**\n * Returns the textual representation of the AAGUID (Authenticator Attestation GUID).\n */\n getAAGUIDText(): string | undefined {\n return this.#aaguidText;\n }\n}\n\n/**\n * A wrapper around a retrieval of existing WebAuthn credential.\n * It is created using `navigator.credentials.get` which provides an assertion.\n */\nexport class WebAuthnExistingCredential extends WebAuthnCredential {}\n", "export class WebAuthnIdentityHostnameError extends Error {}\nexport class WebAuthnIdentityCredentialNotInitializedError extends Error {}\nexport class WebAuthnIdentityCreateCredentialOnTheDeviceError extends Error {}\nexport class WebAuthnIdentityCredentialNotPublicKeyError extends Error {}\nexport class WebAuthnIdentityNoAttestationError extends Error {}\nexport class WebAuthnIdentityInvalidCredentialIdError extends Error {}\nexport class WebAuthnIdentityEncodeCborSignatureError extends Error {}\n// https://developer.mozilla.org/en-US/docs/Web/API/AuthenticatorAssertionResponse/authenticatorData\nexport class WebAuthnIdentityNoAuthenticatorDataError extends Error {}\n// https://developer.mozilla.org/en-US/docs/Web/API/AuthenticatorAssertionResponse/signature\nexport class WebAuthnIdentityNoSignatureError extends Error {}\n", "import {Cbor, type PublicKey, type Signature, SignIdentity} from '@dfinity/agent';\nimport {arrayBufferToUint8Array, isNullish, uint8ArraysEqual} from '@dfinity/utils';\nimport {AUTHENTICATOR_ABORT_TIMEOUT} from './_constants';\nimport {createPasskeyOptions, retrievePasskeyOptions} from './_options';\nimport {execute} from './_progress';\nimport {_authDataToCose} from './agent-js/cose-utils';\nimport {\n type InitWebAuthnNewCredentialArgs,\n type WebAuthnCredential,\n WebAuthnExistingCredential,\n WebAuthnNewCredential\n} from './credential';\nimport {\n WebAuthnIdentityCreateCredentialOnTheDeviceError,\n WebAuthnIdentityCredentialNotInitializedError,\n WebAuthnIdentityCredentialNotPublicKeyError,\n WebAuthnIdentityEncodeCborSignatureError,\n WebAuthnIdentityInvalidCredentialIdError,\n WebAuthnIdentityNoAttestationError,\n WebAuthnIdentityNoAuthenticatorDataError\n} from './errors';\nimport type {\n AuthenticatorOptions,\n CreateWebAuthnIdentityWithExistingCredentialArgs,\n CreateWebAuthnIdentityWithNewCredentialArgs,\n RetrievePublicKeyFn\n} from './types/identity';\nimport type {PasskeyOptions} from './types/passkey';\nimport {\n type WebAuthnSignProgressArgs,\n type WebAuthnSignProgressFn,\n WebAuthnSignProgressStep\n} from './types/progress';\n\ntype PublicKeyCredentialWithAttachment = Omit<PublicKeyCredential, 'response'> & {\n response: AuthenticatorAssertionResponse & {\n attestationObject?: ArrayBuffer;\n };\n};\n\nconst createAbortSignal = ({\n timeout\n}: Pick<AuthenticatorOptions<PasskeyOptions>, 'timeout'>): AbortSignal =>\n AbortSignal.timeout(timeout ?? AUTHENTICATOR_ABORT_TIMEOUT);\n\nconst retrieveCredentials = async ({\n challenge,\n credentialIds,\n passkeyOptions,\n timeout\n}: {\n challenge: Uint8Array;\n credentialIds?: Uint8Array[];\n} & AuthenticatorOptions<PasskeyOptions>): Promise<Credential | null> =>\n await navigator.credentials.get({\n publicKey: {\n ...retrievePasskeyOptions(passkeyOptions),\n challenge: challenge.buffer as BufferSource,\n allowCredentials: (credentialIds ?? []).map((id) => ({\n id: id.buffer as BufferSource,\n type: 'public-key'\n }))\n },\n signal: createAbortSignal({timeout})\n });\n\ntype WebAuthnState<T extends WebAuthnCredential> =\n | {status: 'pending'; retrievePublicKey: RetrievePublicKeyFn}\n | {status: 'initialized'; credential: T};\n\nconst assertWebAuthnStateInitialized: <T extends WebAuthnCredential>(\n state: WebAuthnState<T>\n) => asserts state is {\n status: 'initialized';\n credential: T;\n} = <T extends WebAuthnCredential>(state: WebAuthnState<T>): void => {\n if (state.status !== 'initialized') {\n throw new WebAuthnIdentityCredentialNotInitializedError();\n }\n};\n\nconst assertNonNullishCredential: (\n credential: Credential | null\n) => asserts credential is Credential = (credential: Credential | null): void => {\n if (isNullish(credential)) {\n throw new WebAuthnIdentityCreateCredentialOnTheDeviceError();\n }\n};\n\nconst assertCredentialPublicKey: (\n credential: Credential\n) => asserts credential is PublicKeyCredentialWithAttachment = ({type}: Credential): void => {\n if (type !== 'public-key') {\n throw new WebAuthnIdentityCredentialNotPublicKeyError();\n }\n};\n\n/**\n * A signing identity for the Internet Computer, backed by a WebAuthn credential.\n *\n * Use one of the factory methods to construct an instance:\n * - {@link WebAuthnIdentity.createWithNewCredential} to create a new passkey on the device.\n * - {@link WebAuthnIdentity.createWithExistingCredential} to use an existing passkey.\n *\n * @template T Concrete credential type for this identity\n * ({@link WebAuthnNewCredential} or {@link WebAuthnExistingCredential}).\n */\nexport class WebAuthnIdentity<T extends WebAuthnCredential> extends SignIdentity {\n readonly #onSignProgress: WebAuthnSignProgressFn | undefined;\n #state: WebAuthnState<T>;\n\n /**\n * @hidden Use the factory methods instead.\n *\n * Initializes the identity in either:\n * - **pending** state (existing-credential path; public key not yet known), or\n * - **initialized** state (new-credential path; public key known immediately).\n *\n * @private\n */\n private constructor({\n onProgress,\n ...args\n }: WebAuthnSignProgressArgs &\n (\n | InitWebAuthnNewCredentialArgs\n | Pick<CreateWebAuthnIdentityWithExistingCredentialArgs, 'retrievePublicKey'>\n )) {\n super();\n\n this.#onSignProgress = onProgress;\n\n if ('retrievePublicKey' in args) {\n const {retrievePublicKey} = args;\n\n this.#state = {\n status: 'pending',\n retrievePublicKey\n };\n\n return;\n }\n\n this.#state = WebAuthnIdentity.#createInitializedState({\n credential: new WebAuthnNewCredential(args)\n });\n }\n\n static #createInitializedState<T extends WebAuthnCredential>({\n credential\n }: {\n credential: WebAuthnNewCredential | WebAuthnExistingCredential;\n }): WebAuthnState<T> {\n return {\n status: 'initialized',\n credential: credential as T\n };\n }\n\n /**\n * Creates a new passkey on the device and returns an initialized identity.\n *\n * If you chain `create` and `sign`, the user will be prompted twice to authenticate\n * with their authenticator. You can track progress via the `onProgress` callback.\n *\n * @param args {@link CreateWebAuthnIdentityWithNewCredentialArgs} Options to create the passkey.\n * @returns A {@link WebAuthnIdentity} parameterized with {@link WebAuthnNewCredential}.\n */\n static async createWithNewCredential({\n passkeyOptions,\n timeout,\n ...restArgs\n }: CreateWebAuthnIdentityWithNewCredentialArgs = {}): Promise<\n WebAuthnIdentity<WebAuthnNewCredential>\n > {\n const credential = await navigator.credentials.create({\n publicKey: createPasskeyOptions(passkeyOptions),\n signal: createAbortSignal({timeout})\n });\n\n assertNonNullishCredential(credential);\n assertCredentialPublicKey(credential);\n\n const {\n response: {attestationObject},\n rawId\n } = credential;\n\n if (isNullish(attestationObject)) {\n throw new WebAuthnIdentityNoAttestationError();\n }\n\n // We have to parse the attestationObject as CBOR to ultimately retrieve the public key.\n // Similar as what's implemented in AgentJS.\n const {authData} = Cbor.decode<{authData: Uint8Array}>(attestationObject);\n\n const cose = _authDataToCose(authData);\n\n return new WebAuthnIdentity<WebAuthnNewCredential>({\n ...restArgs,\n rawId: arrayBufferToUint8Array(rawId),\n cose,\n authData\n });\n }\n\n /**\n * Creates an identity for an existing passkey.\n *\n * @param args {@link CreateWebAuthnIdentityWithExistingCredentialArgs} Options to retrieve the passkey.\n * @returns A {@link WebAuthnIdentity} parameterized with {@link WebAuthnExistingCredential}.\n */\n // We use async for consistency reason and because it might be future prone.\n // eslint-disable-next-line require-await\n static async createWithExistingCredential(\n args: CreateWebAuthnIdentityWithExistingCredentialArgs\n ): Promise<WebAuthnIdentity<WebAuthnExistingCredential>> {\n return new WebAuthnIdentity<WebAuthnExistingCredential>(args);\n }\n\n /**\n * Returns the credential\u2019s public key.\n *\n * @returns {PublicKey}\n * @throws WebAuthnIdentityCredentialNotInitializedError if the identity has not signed\n * any request yet.\n */\n override getPublicKey(): PublicKey {\n assertWebAuthnStateInitialized(this.#state);\n\n const {credential} = this.#state;\n\n return credential.getPublicKey();\n }\n\n /**\n * Returns the concrete credential wrapper for this identity.\n *\n * For identities created with:\n * - `createWithNewCredential` \u2192 {@link WebAuthnNewCredential}\n * - `createWithExistingCredential` \u2192 {@link WebAuthnExistingCredential}\n *\n * @throws WebAuthnIdentityCredentialNotInitializedError if the identity has not signed\n * any request yet.\n */\n getCredential(): T {\n assertWebAuthnStateInitialized(this.#state);\n\n const {credential} = this.#state;\n\n return credential;\n }\n\n /**\n * Signs an arbitrary blob using the platform authenticator.\n *\n * @param blob Bytes to sign (used as the WebAuthn challenge).\n * @returns {Promise<Signature>} CBOR-encoded signature payload.\n */\n override async sign(blob: ArrayBuffer): Promise<Signature> {\n // 1. Request user credential (navigator.credentials.get)\n const requestCredential = async (): Promise<PublicKeyCredential> => {\n const credential = await retrieveCredentials({\n challenge: arrayBufferToUint8Array(blob),\n ...(this.#state.status === 'initialized' && {\n credentialIds: [this.#state.credential.getCredentialId()]\n })\n });\n\n assertNonNullishCredential(credential);\n assertCredentialPublicKey(credential);\n\n return credential;\n };\n\n const credential = await execute({\n fn: requestCredential,\n step: WebAuthnSignProgressStep.RequestingUserCredential,\n onProgress: this.#onSignProgress\n });\n\n // 2. Assert credential ID if already initialized or load public key from backend and init state\n const finalizingCredential = async () => {\n const {rawId} = credential;\n\n // If the state was already initialized - credentials.create - then we \"only\"\n // assert that the rawId retrieved by credentials.get is equals to the one already known.\n if (this.#state.status === 'initialized') {\n if (\n !uint8ArraysEqual({\n a: this.#state.credential.getCredentialId(),\n b: arrayBufferToUint8Array(rawId)\n })\n ) {\n throw new WebAuthnIdentityInvalidCredentialIdError();\n }\n\n return;\n }\n\n // If the state was pending, we need to retrieve the public key for the credential\n // that was saved during a previous sign-up\n // because credentials.get does not provide an attestation.\n const {retrievePublicKey} = this.#state;\n\n const cose = await retrievePublicKey({\n credentialId: arrayBufferToUint8Array(rawId)\n });\n\n this.#state = WebAuthnIdentity.#createInitializedState({\n credential: new WebAuthnExistingCredential({\n rawId: arrayBufferToUint8Array(rawId),\n cose\n })\n });\n };\n\n await execute({\n fn: finalizingCredential,\n step: WebAuthnSignProgressStep.FinalizingCredential,\n onProgress: this.#onSignProgress\n });\n\n // 3. Sign the request\n // eslint-disable-next-line require-await\n const encodeSignature = async (): Promise<Signature> => {\n const {response} = credential;\n\n const {clientDataJSON} = response;\n\n // Only the response of type AuthenticatorAssertionResponse provides authenticatorData and signature\n // which is the type of response we are expecting.\n const {authenticatorData, signature} =\n 'authenticatorData' in response && 'signature' in response\n ? (response as AuthenticatorAssertionResponse)\n : {};\n\n if (isNullish(authenticatorData)) {\n throw new WebAuthnIdentityNoAuthenticatorDataError();\n }\n\n if (isNullish(signature)) {\n throw new WebAuthnIdentityNoAuthenticatorDataError();\n }\n\n const encoded = Cbor.encode({\n authenticator_data: authenticatorData,\n client_data_json: new TextDecoder().decode(clientDataJSON),\n signature: arrayBufferToUint8Array(signature)\n });\n\n if (isNullish(encoded)) {\n throw new WebAuthnIdentityEncodeCborSignatureError();\n }\n\n // Similar as AgentJS code.\n Object.assign(encoded, {\n __signature__: undefined\n });\n\n return encoded as Signature;\n };\n\n return await execute({\n fn: encodeSignature,\n step: WebAuthnSignProgressStep.Signing,\n onProgress: this.#onSignProgress\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.\n//\n// According Google tutorial, https://web.dev/articles/passkey-registration, specifying\n// support for ECDSA with P-256 (-7) and RSA PKCS#1 (-257) gives complete coverage.\nexport const PUBLIC_KEY_COSE_ALGORITHMS = {\n ECDSA_WITH_SHA256: -7,\n RSA_WITH_SHA256: -257\n};\n\nexport const AUTHENTICATOR_ABORT_TIMEOUT = 60000;\n", "import {isNullish} from '@dfinity/utils';\nimport {PUBLIC_KEY_COSE_ALGORITHMS} from './_constants';\nimport {WebAuthnIdentityHostnameError} from './errors';\nimport type {CreatePasskeyOptions, PasskeyOptions} from './types/passkey';\n\nconst randomValue = (): BufferSource => window.crypto.getRandomValues(new Uint8Array(16));\n\n/**\n * When creating a passkey, the challenge can simply be a random value.\n * Since the server doesn\u2019t need to verify the authenticity of the key,\n * it doesn\u2019t have to generate the challenge itself.\n *\n * In contrast, when signing a request with our credentials,\n * the request itself becomes the data (blob), the challenge, that must be signed.\n */\nconst createChallenge = (): BufferSource => randomValue();\n\n/**\n * The user ID is set to a random value, which holds little relevance\n * for the end user beyond being unique.\n *\n * Ultimately, once signed in, the user's actual identifier will be\n * the public key (principal) of the identity used to interact with the IC.\n */\nconst createUserId = (): BufferSource => randomValue();\n\nconst hostname = (): string => {\n const {\n location: {href}\n } = window;\n\n const url = URL.parse(href);\n\n if (isNullish(url)) {\n throw new WebAuthnIdentityHostnameError();\n }\n\n const {hostname} = url;\n\n return hostname;\n};\n\nconst relyingPartyId = ({appId}: Pick<PasskeyOptions, 'appId'>): string => appId?.id ?? hostname();\n\nexport const createPasskeyOptions = ({\n appId,\n user: userOptions\n}: CreatePasskeyOptions = {}): PublicKeyCredentialCreationOptions => {\n const {\n document: {title: name}\n } = window;\n\n const relyingParty = (): Pick<PublicKeyCredentialCreationOptions, 'rp'> => ({\n rp: {\n // Note: deprecated in WebAuthn L3\n name: appId?.name ?? name,\n id: relyingPartyId({appId})\n }\n });\n\n const user = (): Pick<PublicKeyCredentialCreationOptions, 'user'> => ({\n user: {\n id: createUserId(),\n name: userOptions?.name ?? userOptions?.displayName ?? name,\n displayName: userOptions?.displayName ?? name\n }\n });\n\n return {\n // We want to receive the attestation statement as generated by the authenticator\n attestation: 'direct',\n challenge: createChallenge(),\n ...relyingParty(),\n ...user(),\n pubKeyCredParams: Object.values(PUBLIC_KEY_COSE_ALGORITHMS).map((algorithm) => ({\n type: 'public-key',\n alg: algorithm\n })),\n excludeCredentials: [],\n authenticatorSelection: {\n // At least for now, we want a simplified flow and therefore indicates that we want a\n // platform authenticator ((an authenticator embedded to the platform device).\n authenticatorAttachment: 'platform',\n userVerification: 'preferred',\n // Along with requireResidentKey, make passkey discoverable,\n residentKey: 'required',\n requireResidentKey: true\n }\n };\n};\n\nexport const retrievePasskeyOptions = (\n options: PasskeyOptions = {}\n): Omit<PublicKeyCredentialRequestOptions, 'challenge'> => ({\n rpId: relyingPartyId(options),\n allowCredentials: [],\n userVerification: 'required'\n});\n", "import type {WebAuthnSignProgress, WebAuthnSignProgressArgs} from './types/progress';\n\nexport const execute = async <T>({\n fn,\n step,\n onProgress\n}: {\n fn: () => Promise<T>;\n} & Pick<WebAuthnSignProgress, 'step'> &\n WebAuthnSignProgressArgs): Promise<T> => {\n onProgress?.({\n step,\n state: 'in_progress'\n });\n\n try {\n const result = await fn();\n\n onProgress?.({\n step,\n state: 'success'\n });\n\n return result;\n } catch (err: unknown) {\n onProgress?.({\n step,\n state: 'error'\n });\n\n throw err;\n }\n};\n", "/**\n * Progress steps in the WebAuthn signing flow.\n */\nexport enum WebAuthnSignProgressStep {\n /** Calling `navigator.credentials.get` to obtain an assertion. */\n RequestingUserCredential,\n /** Verifying/initializing the credential (e.g., ID match, loading public key). */\n FinalizingCredential,\n /** Producing the signature and encoding the result. */\n Signing\n}\n\n/**\n * Status of the current step.\n */\nexport type WebAuthnSignProgressState = 'in_progress' | 'success' | 'error';\n\n/**\n * Payload emitted on progress updates.\n */\nexport interface WebAuthnSignProgress {\n /** The step being executed. */\n step: WebAuthnSignProgressStep;\n /** State of that step. */\n state: WebAuthnSignProgressState;\n}\n\n/**\n * Callback invoked on each progress update.\n */\nexport type WebAuthnSignProgressFn = (progress: WebAuthnSignProgress) => void;\n\n/**\n * Optional handler for progress updates.\n */\nexport interface WebAuthnSignProgressArgs {\n onProgress?: WebAuthnSignProgressFn;\n}\n", "import {nonNullish} from '@dfinity/utils';\n\n/**\n * Checks if a user-verifying platform authenticator (passkeys) is available on this device / browser.\n *\n * Returns `true` when:\n * 1) `window.PublicKeyCredential` exists, and\n * 2) the browser reports a user-verifying **platform** authenticator is available\n * (e.g., Touch ID, Windows Hello, Android biometrics/PIN).\n *\n * @returns {Promise<boolean>} `true` if an authenticator is available, otherwise `false`.\n */\nexport const isWebAuthnAvailable = async (): Promise<boolean> => {\n if (\n nonNullish(window.PublicKeyCredential) &&\n 'isUserVerifyingPlatformAuthenticatorAvailable' in PublicKeyCredential\n ) {\n return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();\n }\n\n return false;\n};\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 {Store} from '../../core/stores/_store';\nimport type {Unsubscribe} from '../../core/types/subscription';\n\nimport type {User} from '../types/user';\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", "export const DOCKER_CONTAINER_URL = 'http://127.0.0.1:5987';\nexport const DOCKER_INTERNET_IDENTITY_ID = 'rdmx6-jaaaa-aaaaa-aaadq-cai';\n", "import {HttpAgent} from '@dfinity/agent';\nimport {nonNullish} from '@dfinity/utils';\nimport {DOCKER_CONTAINER_URL} from '../constants/container.constants';\nimport type {SatelliteContext} from '../types/satellite';\n\nexport type CreateAgentParams = Required<Pick<SatelliteContext, 'identity'>> &\n Pick<SatelliteContext, 'container'>;\n\nexport const createAgent = async ({identity, container}: CreateAgentParams): Promise<HttpAgent> => {\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 return await HttpAgent.create({\n identity,\n shouldFetchRootKey,\n host\n });\n};\n", "import type {Agent, HttpAgent} from '@dfinity/agent';\nimport {isNullish} from '@dfinity/utils';\nimport {type CreateAgentParams, createAgent} from './_agent.factory';\n\nexport class AgentStore {\n private static instance: AgentStore;\n\n #agents: Record<string, HttpAgent> | undefined | null = undefined;\n\n private constructor() {}\n\n static getInstance() {\n if (isNullish(AgentStore.instance)) {\n AgentStore.instance = new AgentStore();\n }\n return AgentStore.instance;\n }\n\n async getAgent({identity, ...rest}: CreateAgentParams): Promise<Agent> {\n const key = identity.getPrincipal().toText();\n\n if (isNullish(this.#agents) || isNullish(this.#agents[key])) {\n const agent = await createAgent({identity, ...rest});\n\n this.#agents = {\n ...(this.#agents ?? {}),\n [key]: agent\n };\n\n return agent;\n }\n\n return this.#agents[key];\n }\n\n reset() {\n this.#agents = null;\n }\n}\n", "import {Actor, type ActorMethod, type ActorSubclass} from '@dfinity/agent';\nimport type {IDL} from '@dfinity/candid';\nimport {isNullish} from '@dfinity/utils';\nimport type {ActorKey} from '../types/actor';\nimport type {SatelliteContext} from '../types/satellite';\nimport {AgentStore} from './agent.store';\n\ntype ActorParams = {\n idlFactory: IDL.InterfaceFactory;\n} & Required<Pick<SatelliteContext, 'satelliteId' | 'identity'>> &\n Pick<SatelliteContext, 'container'>;\n\ntype ActorRecord = Record<string, ActorMethod>;\n\nexport class ActorStore {\n private static instance: ActorStore;\n\n #actors: Record<string, ActorSubclass<ActorRecord>> | undefined | null = undefined;\n\n private constructor() {}\n\n static getInstance() {\n if (isNullish(ActorStore.instance)) {\n ActorStore.instance = new ActorStore();\n }\n return ActorStore.instance;\n }\n\n async getActor<T = ActorRecord>({\n satelliteId,\n identity,\n actorKey,\n ...rest\n }: ActorParams & {actorKey: ActorKey}): Promise<ActorSubclass<T>> {\n const key = `${actorKey}#${identity.getPrincipal().toText()}#${satelliteId};`;\n\n if (isNullish(this.#actors) || isNullish(this.#actors[key])) {\n const actor = await this.createActor({satelliteId, identity, ...rest});\n\n this.#actors = {\n ...(this.#actors ?? {}),\n [key]: actor\n };\n\n return actor as ActorSubclass<T>;\n }\n\n return this.#actors[key] as ActorSubclass<T>;\n }\n\n reset() {\n this.#actors = null;\n }\n\n private async createActor<T = ActorRecord>({\n idlFactory,\n satelliteId: canisterId,\n ...rest\n }: ActorParams): Promise<ActorSubclass<T>> {\n const agent = await AgentStore.getInstance().getAgent(rest);\n\n return Actor.createActor(idlFactory, {\n agent,\n canisterId\n });\n }\n}\n", "const onBeforeUnload = ($event: BeforeUnloadEvent) => {\n $event.preventDefault();\n return ($event.returnValue = 'Are you sure you want to exit?');\n};\n\nconst addBeforeUnload = () => {\n window.addEventListener('beforeunload', onBeforeUnload, {capture: true});\n};\n\nconst removeBeforeUnload = () => {\n window.removeEventListener('beforeunload', onBeforeUnload, {capture: true});\n};\n\nexport const executeWithWindowGuard = async <T>({fn}: {fn: () => Promise<T>}): Promise<T> => {\n try {\n addBeforeUnload();\n\n return await fn();\n } finally {\n removeBeforeUnload();\n }\n};\n", "import type {Environment} from '../types/env';\nimport {Store} from './_store';\n\nexport class EnvStore extends Store<Environment | undefined> {\n private static instance: EnvStore;\n\n private env: Environment | undefined | null;\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 | null {\n return this.env;\n }\n\n reset() {\n this.env = null;\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", "// 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_IN_MILLISECONDS = 4 * 60 * 60 * 1000;\nexport const DELEGATION_IDENTITY_EXPIRATION = BigInt(\n DELEGATION_IDENTITY_EXPIRATION_IN_MILLISECONDS * 1000 * 1000\n);\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", "import {jsonReplacer, jsonReviver} from '@dfinity/utils';\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 {isNullish} from '@dfinity/utils';\nimport {isBrowser} 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 { 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 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 requests.\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/no-unsafe-function-type\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 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 {\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 // Ignore any event that is not from the identity provider\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 {\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 type {SignProgressFn} from '../types/progress';\n\nexport const execute = async <T, Step>({\n fn,\n step,\n onProgress\n}: {\n fn: () => Promise<T>;\n step: Step;\n onProgress?: SignProgressFn<Step>;\n}): Promise<T> => {\n onProgress?.({\n step,\n state: 'in_progress'\n });\n\n try {\n const result = await fn();\n\n onProgress?.({\n step,\n state: 'success'\n });\n\n return result;\n } catch (err: unknown) {\n onProgress?.({\n step,\n state: 'error'\n });\n\n throw err;\n }\n};\n", "import type {SignProgressFn} from './progress';\n\n/**\n * Enum representing the different steps of the sign-in flow with Internet Identity or NFID.\n */\nexport enum AuthClientSignInProgressStep {\n /** User is authenticating with the identity provider (II / NFID). */\n AuthorizingWithProvider,\n /** App is creating a new user or retrieving an existing one after authorization. */\n CreatingOrRetrievingUser\n}\n\n/**\n * Interface representing sign-in options when using an AuthClient based provider.\n * @interface AuthClientSignInOptions\n */\nexport interface AuthClientSignInOptions {\n /**\n * Maximum time to live for the session in nanoseconds. Cannot be extended.\n * @type {bigint}\n */\n maxTimeToLiveInNanoseconds?: bigint;\n\n /**\n * Origin for derivation. Useful when sign-in using the same domain - e.g. sign-in on www.hello.com for hello.com.\n * @type {(string | URL)}\n */\n derivationOrigin?: string | URL;\n\n /**\n * Whether to open the sign-in window.\n * @default true\n * @type {boolean}\n */\n windowed?: boolean;\n\n /**\n * Whether to allow the infamous PIN authentication.\n * @default false\n * @type {boolean}\n */\n allowPin?: boolean;\n\n /**\n * Optional callback to receive progress updates about the sign-in flow.\n * Useful for showing UI feedback such as loading indicators or status messages.\n */\n onProgress?: SignProgressFn<AuthClientSignInProgressStep>;\n}\n", "export class SignInError extends Error {}\nexport class SignInInitError extends Error {}\nexport class SignInUserInterruptError extends Error {}\nexport class SignInProviderNotSupportedError extends Error {}\n\nexport class WebAuthnSignInRetrievePublicKeyError extends Error {}\n\nexport class SignUpProviderNotSupportedError extends Error {}\n\nexport class InitError extends Error {}\n\nexport class ListError extends Error {}\n", "import {type AuthClient, ERROR_USER_INTERRUPT} from '@dfinity/auth-client';\nimport {isNullish} from '@dfinity/utils';\nimport {\n ALLOW_PIN_AUTHENTICATION,\n DELEGATION_IDENTITY_EXPIRATION\n} from '../constants/auth.constants';\nimport {execute} from '../helpers/progress.helpers';\nimport {type AuthClientSignInOptions, AuthClientSignInProgressStep} from '../types/auth-client';\nimport {SignInError, SignInInitError, SignInUserInterruptError} from '../types/errors';\nimport type {Provider} from '../types/provider';\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\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 * Abstract base class for all authentication providers that integrate with the `@dfinity/auth-client`.\n *\n * @abstract\n * @class AuthClientProvider\n * @implements {AuthProvider}\n */\nexport abstract class AuthClientProvider implements AuthProvider {\n /**\n * The unique identifier of the provider.\n *\n * @abstract\n * @type {Provider}\n */\n abstract get id(): Provider;\n\n /**\n * Returns the sign-in options for the provider.\n *\n * Note: set as public instead of protected for testing purposes.\n *\n * @abstract\n * @param {Pick<SignInOptions, 'windowed'>} options - Options controlling window behavior.\n * @returns {AuthProviderSignInOptions} Provider-specific sign-in options.\n */\n abstract signInOptions(\n options: Pick<AuthClientSignInOptions, 'windowed'>\n ): AuthProviderSignInOptions;\n\n /**\n * Signs in a user with the given authentication provider.\n *\n * @param {Object} params - The sign-in parameters.\n * @param {AuthClientSignInOptions} [params.options] - Optional configuration for the login request.\n * @param {AuthClient | undefined | null} params.authClient - The AuthClient instance in its current state.\n * @param {initAuth} params.initAuth - The function to load or initialize the user. Provided as a callback to avoid recursive import.\n *\n * @returns {Promise<void>} Resolves if the sign-in is successful. Rejects with:\n * - {@link SignInInitError} if no AuthClient is available.\n * - {@link SignInUserInterruptError} if the user cancels the login.\n * - {@link SignInError} for other errors during sign-in.\n */\n async signIn({\n options,\n authClient,\n initAuth\n }: {\n options?: AuthClientSignInOptions;\n authClient: AuthClient | undefined | null;\n initAuth: (params: {provider: Provider}) => Promise<void>;\n }): Promise<void> {\n // 1. Sign-in or sign-up with third party provider\n const login = async () => await this.#loginWithAuthClient({options, authClient});\n\n await execute({\n fn: login,\n step: AuthClientSignInProgressStep.AuthorizingWithProvider,\n onProgress: options?.onProgress\n });\n\n // 2. Create or load the user for the authentication\n const runAuth = async () => await initAuth({provider: this.id});\n\n await execute({\n fn: runAuth,\n step: AuthClientSignInProgressStep.CreatingOrRetrievingUser,\n onProgress: options?.onProgress\n });\n }\n\n #loginWithAuthClient({\n options,\n authClient\n }: {\n options?: Omit<AuthClientSignInOptions, 'onProgress'>;\n authClient: AuthClient | undefined | null;\n }): Promise<void> {\n /* eslint-disable no-async-promise-executor */\n return new Promise<void>(async (resolve, reject) => {\n if (isNullish(authClient)) {\n reject(\n new SignInInitError(\n 'No client is ready to perform a sign-in. Have you initialized the Satellite?'\n )\n );\n return;\n }\n\n await authClient.login({\n onSuccess: resolve,\n onError: (error?: string) => {\n if (error === ERROR_USER_INTERRUPT) {\n reject(new SignInUserInterruptError(error));\n return;\n }\n\n reject(new SignInError(error));\n },\n maxTimeToLive: options?.maxTimeToLiveInNanoseconds ?? DELEGATION_IDENTITY_EXPIRATION,\n allowPinAuthentication: options?.allowPin ?? ALLOW_PIN_AUTHENTICATION,\n ...(options?.derivationOrigin !== undefined && {\n derivationOrigin: options.derivationOrigin\n }),\n ...this.signInOptions({\n windowed: options?.windowed\n })\n });\n });\n }\n}\n", "import {isNullish, nonNullish} from '@dfinity/utils';\nimport {\n DOCKER_CONTAINER_URL,\n DOCKER_INTERNET_IDENTITY_ID\n} from '../../core/constants/container.constants';\nimport {EnvStore} from '../../core/stores/env.store';\nimport {II_POPUP, INTERNET_COMPUTER_ORG} from '../constants/auth.constants';\nimport type {AuthClientSignInOptions} from '../types/auth-client';\nimport type {InternetIdentityConfig, InternetIdentityDomain} from '../types/internet-identity';\nimport type {Provider} from '../types/provider';\nimport {popupCenter} from '../utils/window.utils';\nimport {AuthClientProvider, type AuthProviderSignInOptions} from './_auth-client.providers';\n\n/**\n * Internet Identity authentication provider.\n * @class InternetIdentityProvider\n * @implements {AuthProvider}\n */\nexport class InternetIdentityProvider extends AuthClientProvider {\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 super();\n\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 override 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 override signInOptions({\n windowed\n }: Pick<AuthClientSignInOptions, '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", "import {NFID_POPUP} from '../constants/auth.constants';\nimport type {AuthClientSignInOptions} from '../types/auth-client';\nimport type {NFIDConfig} from '../types/nfid';\nimport type {Provider} from '../types/provider';\nimport {popupCenter} from '../utils/window.utils';\nimport {AuthClientProvider, type AuthProviderSignInOptions} from './_auth-client.providers';\n\n/**\n * NFID authentication provider.\n * @class NFIDProvider\n * @implements {AuthProvider}\n */\nexport class NFIDProvider extends AuthClientProvider {\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 super();\n\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 override 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 override signInOptions({\n windowed\n }: Pick<AuthClientSignInOptions, '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 type {ReadOptions} from '../types/call-options';\n\n/**\n * Default options for read operations.\n *\n * For backwards compatibility and because most developers probably prioritize speed over\n * additional security when fetching read-only data from the Internet Computer,\n * read operations are performed in an uncertified way by default.\n */\nexport const DEFAULT_READ_OPTIONS: ReadOptions = {certified: false};\n", "import {AnonymousIdentity, type Identity} from '@dfinity/agent';\nimport {nonNullish} from '@dfinity/utils';\nimport {getIdentity as getAuthIdentity} from '../../auth/services/auth.services';\n\nexport const getAnyIdentity = (identity?: Identity): Identity => {\n if (nonNullish(identity)) {\n return identity;\n }\n\n return getAuthIdentity() ?? new AnonymousIdentity();\n};\n", "import {Actor, type ActorConfig, type ActorMethod, type ActorSubclass} from '@dfinity/agent';\nimport type {IDL} from '@dfinity/candid';\nimport type {Principal} from '@dfinity/principal';\nimport {isNullish} from '@dfinity/utils';\nimport type {\n ActorParameters,\n ConsoleParameters,\n MissionControlParameters,\n OrbiterParameters,\n SatelliteParameters\n} from '../types/actor';\nimport {\n idlCertifiedFactoryConsole,\n idlCertifiedFactoryOrbiter,\n idlCertifiedFactorySatellite,\n idlDeprecatedFactoryMissionControlVersion,\n idlDeprecatedFactoryOrbiterVersion,\n idlDeprecatedFactorySatellite,\n idlDeprecatedFactorySatelliteNoScope,\n idlDeprecatedFactorySatelliteVersion,\n idlFactoryConsole,\n idlFactoryMissionControl,\n idlFactoryOrbiter,\n idlFactorySatellite,\n type ConsoleActor,\n type DeprecatedMissionControlVersionActor,\n type DeprecatedOrbiterVersionActor,\n type DeprecatedSatelliteActor,\n type DeprecatedSatelliteNoScopeActor,\n type DeprecatedSatelliteVersionActor,\n type MissionControlActor,\n type OrbiterActor,\n type SatelliteActor\n} from './actor.factory';\nimport {useOrInitAgent} from './agent.api';\n\n/**\n * @deprecated TODO: for backwards compatibility - to be removed\n */\nexport const getDeprecatedSatelliteActor = ({\n satelliteId,\n ...rest\n}: SatelliteParameters): Promise<DeprecatedSatelliteActor> =>\n getActor({\n canisterId: satelliteId,\n ...rest,\n idlFactory: idlDeprecatedFactorySatellite\n });\n\nexport const getSatelliteActor = ({\n satelliteId,\n certified = false,\n ...rest\n}: SatelliteParameters & {certified?: boolean}): Promise<SatelliteActor> =>\n getActor({\n canisterId: satelliteId,\n ...rest,\n idlFactory: certified ? idlCertifiedFactorySatellite : idlFactorySatellite\n });\n\n/**\n * @deprecated TODO: for backwards compatibility - to be removed\n */\nexport const getDeprecatedSatelliteNoScopeActor = ({\n satelliteId,\n ...rest\n}: SatelliteParameters): Promise<DeprecatedSatelliteNoScopeActor> =>\n getActor({\n canisterId: satelliteId,\n ...rest,\n idlFactory: idlDeprecatedFactorySatelliteNoScope\n });\n\n/**\n * @deprecated TODO: for backwards compatibility - to be removed\n */\nexport const getDeprecatedSatelliteVersionActor = ({\n satelliteId,\n ...rest\n}: SatelliteParameters): Promise<DeprecatedSatelliteVersionActor> =>\n getActor({\n canisterId: satelliteId,\n ...rest,\n idlFactory: idlDeprecatedFactorySatelliteVersion\n });\n\nexport const getMissionControlActor = ({\n missionControlId,\n ...rest\n}: MissionControlParameters): Promise<MissionControlActor> =>\n getActor({\n canisterId: missionControlId,\n ...rest,\n idlFactory: idlFactoryMissionControl\n });\n\n/**\n * @deprecated TODO: for backwards compatibility - to be removed\n */\nexport const getDeprecatedMissionControlVersionActor = ({\n missionControlId,\n ...rest\n}: MissionControlParameters): Promise<DeprecatedMissionControlVersionActor> =>\n getActor({\n canisterId: missionControlId,\n ...rest,\n idlFactory: idlDeprecatedFactoryMissionControlVersion\n });\n\nexport const getOrbiterActor = ({\n orbiterId,\n certified = false,\n ...rest\n}: OrbiterParameters & {certified?: boolean}): Promise<OrbiterActor> =>\n getActor({\n canisterId: orbiterId,\n ...rest,\n idlFactory: certified ? idlCertifiedFactoryOrbiter : idlFactoryOrbiter\n });\n\n/**\n * @deprecated TODO: for backwards compatibility - to be removed\n */\nexport const getDeprecatedOrbiterVersionActor = ({\n orbiterId,\n ...rest\n}: OrbiterParameters): Promise<DeprecatedOrbiterVersionActor> =>\n getActor({\n canisterId: orbiterId,\n ...rest,\n idlFactory: idlDeprecatedFactoryOrbiterVersion\n });\n\nexport const getConsoleActor = ({\n consoleId,\n certified = false,\n ...rest\n}: ConsoleParameters & {certified?: boolean}): Promise<ConsoleActor> =>\n getActor({\n canisterId: consoleId,\n ...rest,\n idlFactory: certified ? idlCertifiedFactoryConsole : idlFactoryConsole\n });\n\nexport const getActor = <T>({\n canisterId,\n idlFactory,\n ...rest\n}: ActorParameters & {\n canisterId: Principal | string | undefined;\n idlFactory: IDL.InterfaceFactory;\n}): Promise<T> => {\n if (isNullish(canisterId)) {\n throw new Error('No canister ID provided.');\n }\n\n return createActor({\n canisterId,\n idlFactory,\n ...rest\n });\n};\n\nconst createActor = async <T = Record<string, ActorMethod>>({\n canisterId,\n idlFactory,\n config,\n ...rest\n}: {\n idlFactory: IDL.InterfaceFactory;\n canisterId: Principal | string;\n config?: Pick<ActorConfig, 'callTransform' | 'queryTransform'>;\n} & ActorParameters): Promise<ActorSubclass<T>> => {\n const agent = await useOrInitAgent(rest);\n\n // Creates an actor with using the candid interface and the HttpAgent\n return Actor.createActor(idlFactory, {\n agent,\n canisterId,\n ...(config ?? {})\n });\n};\n", "// @ts-ignore\nexport const idlFactory = ({IDL}) => {\n const MissionControlArgs = IDL.Record({user: IDL.Principal});\n const CyclesThreshold = IDL.Record({\n fund_cycles: IDL.Nat,\n min_cycles: IDL.Nat\n });\n const CyclesMonitoringStrategy = IDL.Variant({\n BelowThreshold: CyclesThreshold\n });\n const CyclesMonitoring = IDL.Record({\n strategy: IDL.Opt(CyclesMonitoringStrategy),\n enabled: IDL.Bool\n });\n const Monitoring = IDL.Record({cycles: IDL.Opt(CyclesMonitoring)});\n const Settings = IDL.Record({monitoring: IDL.Opt(Monitoring)});\n const Orbiter = IDL.Record({\n updated_at: IDL.Nat64,\n orbiter_id: IDL.Principal,\n metadata: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n created_at: IDL.Nat64,\n settings: IDL.Opt(Settings)\n });\n const CreateCanisterConfig = IDL.Record({\n subnet_id: IDL.Opt(IDL.Principal),\n name: IDL.Opt(IDL.Text)\n });\n const Satellite = IDL.Record({\n updated_at: IDL.Nat64,\n metadata: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n created_at: IDL.Nat64,\n satellite_id: IDL.Principal,\n settings: IDL.Opt(Settings)\n });\n const DepositCyclesArgs = IDL.Record({\n cycles: IDL.Nat,\n destination_id: IDL.Principal\n });\n const DepositedCyclesEmailNotification = IDL.Record({\n to: IDL.Opt(IDL.Text),\n enabled: IDL.Bool\n });\n const CyclesMonitoringConfig = IDL.Record({\n notification: IDL.Opt(DepositedCyclesEmailNotification),\n default_strategy: IDL.Opt(CyclesMonitoringStrategy)\n });\n const MonitoringConfig = IDL.Record({\n cycles: IDL.Opt(CyclesMonitoringConfig)\n });\n const Config = IDL.Record({monitoring: IDL.Opt(MonitoringConfig)});\n const GetMonitoringHistory = IDL.Record({\n to: IDL.Opt(IDL.Nat64),\n from: IDL.Opt(IDL.Nat64),\n segment_id: IDL.Principal\n });\n const MonitoringHistoryKey = IDL.Record({\n segment_id: IDL.Principal,\n created_at: IDL.Nat64,\n nonce: IDL.Int32\n });\n const CyclesBalance = IDL.Record({\n timestamp: IDL.Nat64,\n amount: IDL.Nat\n });\n const FundingErrorCode = IDL.Variant({\n BalanceCheckFailed: IDL.Null,\n ObtainCyclesFailed: IDL.Null,\n DepositFailed: IDL.Null,\n InsufficientCycles: IDL.Null,\n Other: IDL.Text\n });\n const FundingFailure = IDL.Record({\n timestamp: IDL.Nat64,\n error_code: FundingErrorCode\n });\n const MonitoringHistoryCycles = IDL.Record({\n deposited_cycles: IDL.Opt(CyclesBalance),\n cycles: CyclesBalance,\n funding_failure: IDL.Opt(FundingFailure)\n });\n const MonitoringHistory = IDL.Record({\n cycles: IDL.Opt(MonitoringHistoryCycles)\n });\n const CyclesMonitoringStatus = IDL.Record({\n monitored_ids: IDL.Vec(IDL.Principal),\n running: IDL.Bool\n });\n const MonitoringStatus = IDL.Record({\n cycles: IDL.Opt(CyclesMonitoringStatus)\n });\n const MissionControlSettings = IDL.Record({\n updated_at: IDL.Nat64,\n created_at: IDL.Nat64,\n monitoring: IDL.Opt(Monitoring)\n });\n const User = IDL.Record({\n updated_at: IDL.Nat64,\n metadata: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n user: IDL.Opt(IDL.Principal),\n created_at: IDL.Nat64,\n config: IDL.Opt(Config)\n });\n const Tokens = IDL.Record({e8s: IDL.Nat64});\n const Timestamp = IDL.Record({timestamp_nanos: IDL.Nat64});\n const TransferArgs = IDL.Record({\n to: IDL.Vec(IDL.Nat8),\n fee: Tokens,\n memo: IDL.Nat64,\n from_subaccount: IDL.Opt(IDL.Vec(IDL.Nat8)),\n created_at_time: IDL.Opt(Timestamp),\n amount: Tokens\n });\n const TransferError = IDL.Variant({\n TxTooOld: IDL.Record({allowed_window_nanos: IDL.Nat64}),\n BadFee: IDL.Record({expected_fee: Tokens}),\n TxDuplicate: IDL.Record({duplicate_of: IDL.Nat64}),\n TxCreatedInFuture: IDL.Null,\n InsufficientFunds: IDL.Record({balance: Tokens})\n });\n const Result = IDL.Variant({Ok: IDL.Nat64, Err: TransferError});\n const Account = IDL.Record({\n owner: IDL.Principal,\n subaccount: IDL.Opt(IDL.Vec(IDL.Nat8))\n });\n const TransferArg = IDL.Record({\n to: Account,\n fee: IDL.Opt(IDL.Nat),\n memo: IDL.Opt(IDL.Vec(IDL.Nat8)),\n from_subaccount: IDL.Opt(IDL.Vec(IDL.Nat8)),\n created_at_time: IDL.Opt(IDL.Nat64),\n amount: IDL.Nat\n });\n const TransferError_1 = IDL.Variant({\n GenericError: IDL.Record({\n message: IDL.Text,\n error_code: IDL.Nat\n }),\n TemporarilyUnavailable: IDL.Null,\n BadBurn: IDL.Record({min_burn_amount: IDL.Nat}),\n Duplicate: IDL.Record({duplicate_of: IDL.Nat}),\n BadFee: IDL.Record({expected_fee: IDL.Nat}),\n CreatedInFuture: IDL.Record({ledger_time: IDL.Nat64}),\n TooOld: IDL.Null,\n InsufficientFunds: IDL.Record({balance: IDL.Nat})\n });\n const Result_1 = IDL.Variant({Ok: IDL.Nat, Err: TransferError_1});\n const ControllerScope = IDL.Variant({\n Write: IDL.Null,\n Admin: IDL.Null,\n Submit: 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 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 SegmentsMonitoringStrategy = IDL.Record({\n ids: IDL.Vec(IDL.Principal),\n strategy: CyclesMonitoringStrategy\n });\n const CyclesMonitoringStartConfig = IDL.Record({\n orbiters_strategy: IDL.Opt(SegmentsMonitoringStrategy),\n mission_control_strategy: IDL.Opt(CyclesMonitoringStrategy),\n satellites_strategy: IDL.Opt(SegmentsMonitoringStrategy)\n });\n const MonitoringStartConfig = IDL.Record({\n cycles_config: IDL.Opt(CyclesMonitoringStartConfig)\n });\n const CyclesMonitoringStopConfig = IDL.Record({\n satellite_ids: IDL.Opt(IDL.Vec(IDL.Principal)),\n try_mission_control: IDL.Opt(IDL.Bool),\n orbiter_ids: IDL.Opt(IDL.Vec(IDL.Principal))\n });\n const MonitoringStopConfig = IDL.Record({\n cycles_config: IDL.Opt(CyclesMonitoringStopConfig)\n });\n return IDL.Service({\n add_mission_control_controllers: IDL.Func([IDL.Vec(IDL.Principal)], [], []),\n add_satellites_controllers: IDL.Func([IDL.Vec(IDL.Principal), IDL.Vec(IDL.Principal)], [], []),\n create_orbiter: IDL.Func([IDL.Opt(IDL.Text)], [Orbiter], []),\n create_orbiter_with_config: IDL.Func([CreateCanisterConfig], [Orbiter], []),\n create_satellite: IDL.Func([IDL.Text], [Satellite], []),\n create_satellite_with_config: IDL.Func([CreateCanisterConfig], [Satellite], []),\n del_mission_control_controllers: IDL.Func([IDL.Vec(IDL.Principal)], [], []),\n del_orbiter: IDL.Func([IDL.Principal, IDL.Nat], [], []),\n del_orbiters_controllers: IDL.Func([IDL.Vec(IDL.Principal), IDL.Vec(IDL.Principal)], [], []),\n del_satellite: IDL.Func([IDL.Principal, IDL.Nat], [], []),\n del_satellites_controllers: IDL.Func([IDL.Vec(IDL.Principal), IDL.Vec(IDL.Principal)], [], []),\n deposit_cycles: IDL.Func([DepositCyclesArgs], [], []),\n get_config: IDL.Func([], [IDL.Opt(Config)], ['query']),\n get_metadata: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))], ['query']),\n get_monitoring_history: IDL.Func(\n [GetMonitoringHistory],\n [IDL.Vec(IDL.Tuple(MonitoringHistoryKey, MonitoringHistory))],\n ['query']\n ),\n get_monitoring_status: IDL.Func([], [MonitoringStatus], ['query']),\n get_settings: IDL.Func([], [IDL.Opt(MissionControlSettings)], ['query']),\n get_user: IDL.Func([], [IDL.Principal], ['query']),\n get_user_data: IDL.Func([], [User], ['query']),\n icp_transfer: IDL.Func([TransferArgs], [Result], []),\n icrc_transfer: IDL.Func([IDL.Principal, TransferArg], [Result_1], []),\n list_mission_control_controllers: IDL.Func(\n [],\n [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))],\n ['query']\n ),\n list_orbiters: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Principal, Orbiter))], ['query']),\n list_satellites: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Principal, Satellite))], ['query']),\n remove_mission_control_controllers: IDL.Func([IDL.Vec(IDL.Principal)], [], []),\n remove_satellites_controllers: IDL.Func(\n [IDL.Vec(IDL.Principal), IDL.Vec(IDL.Principal)],\n [],\n []\n ),\n set_config: IDL.Func([IDL.Opt(Config)], [], []),\n set_metadata: IDL.Func([IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))], [], []),\n set_mission_control_controllers: IDL.Func([IDL.Vec(IDL.Principal), SetController], [], []),\n set_orbiter: IDL.Func([IDL.Principal, IDL.Opt(IDL.Text)], [Orbiter], []),\n set_orbiter_metadata: IDL.Func(\n [IDL.Principal, IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))],\n [Orbiter],\n []\n ),\n set_orbiters_controllers: IDL.Func(\n [IDL.Vec(IDL.Principal), IDL.Vec(IDL.Principal), SetController],\n [],\n []\n ),\n set_satellite: IDL.Func([IDL.Principal, IDL.Opt(IDL.Text)], [Satellite], []),\n set_satellite_metadata: IDL.Func(\n [IDL.Principal, IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))],\n [Satellite],\n []\n ),\n set_satellites_controllers: IDL.Func(\n [IDL.Vec(IDL.Principal), IDL.Vec(IDL.Principal), SetController],\n [],\n []\n ),\n start_monitoring: IDL.Func([], [], []),\n stop_monitoring: IDL.Func([], [], []),\n top_up: IDL.Func([IDL.Principal, Tokens], [], []),\n unset_orbiter: IDL.Func([IDL.Principal], [], []),\n unset_satellite: IDL.Func([IDL.Principal], [], []),\n update_and_start_monitoring: IDL.Func([MonitoringStartConfig], [], []),\n update_and_stop_monitoring: IDL.Func([MonitoringStopConfig], [], [])\n });\n};\n// @ts-ignore\nexport const init = ({IDL}) => {\n const MissionControlArgs = IDL.Record({user: IDL.Principal});\n return [MissionControlArgs];\n};\n", "// @ts-ignore\nexport const idlFactory = ({IDL}) => {\n const SegmentArgs = IDL.Record({controllers: IDL.Vec(IDL.Principal)});\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 Submit: 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 DelSatelliteConfig = IDL.Record({version: IDL.Opt(IDL.Nat64)});\n const DepositCyclesArgs = IDL.Record({\n cycles: IDL.Nat,\n destination_id: IDL.Principal\n });\n const GetAnalytics = IDL.Record({\n to: IDL.Opt(IDL.Nat64),\n from: IDL.Opt(IDL.Nat64),\n satellite_id: IDL.Opt(IDL.Principal)\n });\n const AnalyticKey = IDL.Record({\n key: IDL.Text,\n collected_at: IDL.Nat64\n });\n const PageViewClient = IDL.Record({\n os: IDL.Text,\n device: IDL.Opt(IDL.Text),\n browser: IDL.Text\n });\n const PageViewCampaign = IDL.Record({\n utm_content: IDL.Opt(IDL.Text),\n utm_medium: IDL.Opt(IDL.Text),\n utm_source: IDL.Text,\n utm_term: IDL.Opt(IDL.Text),\n utm_campaign: IDL.Opt(IDL.Text)\n });\n const PageViewDevice = IDL.Record({\n inner_height: IDL.Nat16,\n screen_height: IDL.Opt(IDL.Nat16),\n screen_width: IDL.Opt(IDL.Nat16),\n inner_width: IDL.Nat16\n });\n const PageView = IDL.Record({\n client: IDL.Opt(PageViewClient),\n title: IDL.Text,\n updated_at: IDL.Nat64,\n referrer: IDL.Opt(IDL.Text),\n time_zone: IDL.Text,\n session_id: IDL.Text,\n campaign: IDL.Opt(PageViewCampaign),\n href: IDL.Text,\n created_at: IDL.Nat64,\n satellite_id: IDL.Principal,\n device: PageViewDevice,\n version: IDL.Opt(IDL.Nat64),\n user_agent: IDL.Opt(IDL.Text)\n });\n const AnalyticsBrowsersPageViews = IDL.Record({\n safari: IDL.Float64,\n opera: IDL.Float64,\n others: IDL.Float64,\n firefox: IDL.Float64,\n chrome: IDL.Float64\n });\n const AnalyticsOperatingSystemsPageViews = IDL.Record({\n ios: IDL.Float64,\n macos: IDL.Float64,\n others: IDL.Float64,\n linux: IDL.Float64,\n android: IDL.Float64,\n windows: IDL.Float64\n });\n const AnalyticsDevicesPageViews = IDL.Record({\n desktop: IDL.Float64,\n laptop: IDL.Opt(IDL.Float64),\n others: IDL.Float64,\n tablet: IDL.Opt(IDL.Float64),\n mobile: IDL.Float64\n });\n const AnalyticsClientsPageViews = IDL.Record({\n browsers: AnalyticsBrowsersPageViews,\n operating_systems: IDL.Opt(AnalyticsOperatingSystemsPageViews),\n devices: AnalyticsDevicesPageViews\n });\n const CalendarDate = IDL.Record({\n day: IDL.Nat8,\n month: IDL.Nat8,\n year: IDL.Int32\n });\n const AnalyticsMetricsPageViews = IDL.Record({\n bounce_rate: IDL.Float64,\n average_page_views_per_session: IDL.Float64,\n daily_total_page_views: IDL.Vec(IDL.Tuple(CalendarDate, IDL.Nat32)),\n total_page_views: IDL.Nat32,\n unique_page_views: IDL.Nat64,\n unique_sessions: IDL.Nat64\n });\n const AnalyticsTop10PageViews = IDL.Record({\n referrers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32)),\n pages: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32)),\n utm_campaigns: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32))),\n utm_sources: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32))),\n time_zones: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32)))\n });\n const NavigationType = IDL.Variant({\n Navigate: IDL.Null,\n Restore: IDL.Null,\n Reload: IDL.Null,\n BackForward: IDL.Null,\n BackForwardCache: IDL.Null,\n Prerender: IDL.Null\n });\n const WebVitalsMetric = IDL.Record({\n id: IDL.Text,\n value: IDL.Float64,\n navigation_type: IDL.Opt(NavigationType),\n delta: IDL.Float64\n });\n const PerformanceData = IDL.Variant({WebVitalsMetric: WebVitalsMetric});\n const PerformanceMetricName = IDL.Variant({\n CLS: IDL.Null,\n FCP: IDL.Null,\n INP: IDL.Null,\n LCP: IDL.Null,\n TTFB: IDL.Null\n });\n const PerformanceMetric = IDL.Record({\n updated_at: IDL.Nat64,\n session_id: IDL.Text,\n data: PerformanceData,\n href: IDL.Text,\n metric_name: PerformanceMetricName,\n created_at: IDL.Nat64,\n satellite_id: IDL.Principal,\n version: IDL.Opt(IDL.Nat64)\n });\n const AnalyticsWebVitalsPageMetrics = IDL.Record({\n cls: IDL.Opt(IDL.Float64),\n fcp: IDL.Opt(IDL.Float64),\n inp: IDL.Opt(IDL.Float64),\n lcp: IDL.Opt(IDL.Float64),\n ttfb: IDL.Opt(IDL.Float64)\n });\n const AnalyticsWebVitalsPerformanceMetrics = IDL.Record({\n overall: AnalyticsWebVitalsPageMetrics,\n pages: IDL.Vec(IDL.Tuple(IDL.Text, AnalyticsWebVitalsPageMetrics))\n });\n const TrackEvent = IDL.Record({\n updated_at: IDL.Nat64,\n session_id: IDL.Text,\n metadata: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))),\n name: IDL.Text,\n created_at: IDL.Nat64,\n satellite_id: IDL.Principal,\n version: IDL.Opt(IDL.Nat64)\n });\n const AnalyticsTrackEvents = IDL.Record({\n total: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32))\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 HttpResponse = IDL.Record({\n body: IDL.Vec(IDL.Nat8),\n headers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n upgrade: IDL.Opt(IDL.Bool),\n status_code: IDL.Nat16\n });\n const OrbiterSatelliteFeatures = IDL.Record({\n performance_metrics: IDL.Bool,\n track_events: IDL.Bool,\n page_views: IDL.Bool\n });\n const OrbiterSatelliteConfig = IDL.Record({\n updated_at: IDL.Nat64,\n features: IDL.Opt(OrbiterSatelliteFeatures),\n restricted_origin: IDL.Opt(IDL.Text),\n created_at: IDL.Nat64,\n version: IDL.Opt(IDL.Nat64)\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 SetPageView = IDL.Record({\n client: IDL.Opt(PageViewClient),\n title: IDL.Text,\n updated_at: IDL.Opt(IDL.Nat64),\n referrer: IDL.Opt(IDL.Text),\n time_zone: IDL.Text,\n session_id: IDL.Text,\n campaign: IDL.Opt(PageViewCampaign),\n href: IDL.Text,\n satellite_id: IDL.Principal,\n device: PageViewDevice,\n version: IDL.Opt(IDL.Nat64),\n user_agent: IDL.Opt(IDL.Text)\n });\n const Result = IDL.Variant({Ok: PageView, Err: IDL.Text});\n const Result_1 = IDL.Variant({\n Ok: IDL.Null,\n Err: IDL.Vec(IDL.Tuple(AnalyticKey, IDL.Text))\n });\n const SetPerformanceMetric = IDL.Record({\n session_id: IDL.Text,\n data: PerformanceData,\n href: IDL.Text,\n metric_name: PerformanceMetricName,\n satellite_id: IDL.Principal,\n version: IDL.Opt(IDL.Nat64),\n user_agent: IDL.Opt(IDL.Text)\n });\n const Result_2 = IDL.Variant({Ok: PerformanceMetric, Err: IDL.Text});\n const SetSatelliteConfig = IDL.Record({\n features: IDL.Opt(OrbiterSatelliteFeatures),\n restricted_origin: IDL.Opt(IDL.Text),\n version: IDL.Opt(IDL.Nat64)\n });\n const SetTrackEvent = IDL.Record({\n updated_at: IDL.Opt(IDL.Nat64),\n session_id: IDL.Text,\n metadata: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))),\n name: IDL.Text,\n satellite_id: IDL.Principal,\n version: IDL.Opt(IDL.Nat64),\n user_agent: IDL.Opt(IDL.Text)\n });\n const Result_3 = IDL.Variant({Ok: TrackEvent, Err: IDL.Text});\n return IDL.Service({\n del_controllers: IDL.Func(\n [DeleteControllersArgs],\n [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))],\n []\n ),\n del_satellite_config: IDL.Func([IDL.Principal, DelSatelliteConfig], [], []),\n deposit_cycles: IDL.Func([DepositCyclesArgs], [], []),\n get_page_views: IDL.Func(\n [GetAnalytics],\n [IDL.Vec(IDL.Tuple(AnalyticKey, PageView))],\n ['query']\n ),\n get_page_views_analytics_clients: IDL.Func(\n [GetAnalytics],\n [AnalyticsClientsPageViews],\n ['query']\n ),\n get_page_views_analytics_metrics: IDL.Func(\n [GetAnalytics],\n [AnalyticsMetricsPageViews],\n ['query']\n ),\n get_page_views_analytics_top_10: IDL.Func([GetAnalytics], [AnalyticsTop10PageViews], ['query']),\n get_performance_metrics: IDL.Func(\n [GetAnalytics],\n [IDL.Vec(IDL.Tuple(AnalyticKey, PerformanceMetric))],\n ['query']\n ),\n get_performance_metrics_analytics_web_vitals: IDL.Func(\n [GetAnalytics],\n [AnalyticsWebVitalsPerformanceMetrics],\n ['query']\n ),\n get_track_events: IDL.Func(\n [GetAnalytics],\n [IDL.Vec(IDL.Tuple(AnalyticKey, TrackEvent))],\n ['query']\n ),\n get_track_events_analytics: IDL.Func([GetAnalytics], [AnalyticsTrackEvents], ['query']),\n http_request: IDL.Func([HttpRequest], [HttpResponse], ['query']),\n http_request_update: IDL.Func([HttpRequest], [HttpResponse], []),\n list_controllers: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))], ['query']),\n list_satellite_configs: IDL.Func(\n [],\n [IDL.Vec(IDL.Tuple(IDL.Principal, OrbiterSatelliteConfig))],\n ['query']\n ),\n memory_size: IDL.Func([], [MemorySize], ['query']),\n set_controllers: IDL.Func(\n [SetControllersArgs],\n [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))],\n []\n ),\n set_page_view: IDL.Func([AnalyticKey, SetPageView], [Result], []),\n set_page_views: IDL.Func([IDL.Vec(IDL.Tuple(AnalyticKey, SetPageView))], [Result_1], []),\n set_performance_metric: IDL.Func([AnalyticKey, SetPerformanceMetric], [Result_2], []),\n set_performance_metrics: IDL.Func(\n [IDL.Vec(IDL.Tuple(AnalyticKey, SetPerformanceMetric))],\n [Result_1],\n []\n ),\n set_satellite_configs: IDL.Func(\n [IDL.Vec(IDL.Tuple(IDL.Principal, SetSatelliteConfig))],\n [IDL.Vec(IDL.Tuple(IDL.Principal, OrbiterSatelliteConfig))],\n []\n ),\n set_track_event: IDL.Func([AnalyticKey, SetTrackEvent], [Result_3], []),\n set_track_events: IDL.Func([IDL.Vec(IDL.Tuple(AnalyticKey, SetTrackEvent))], [Result_1], [])\n });\n};\n// @ts-ignore\nexport const init = ({IDL}) => {\n const SegmentArgs = IDL.Record({controllers: IDL.Vec(IDL.Principal)});\n return [SegmentArgs];\n};\n", "// @ts-ignore\nexport const idlFactory = ({IDL}) => {\n const SegmentArgs = IDL.Record({controllers: IDL.Vec(IDL.Principal)});\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 Submit: 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 DelSatelliteConfig = IDL.Record({version: IDL.Opt(IDL.Nat64)});\n const DepositCyclesArgs = IDL.Record({\n cycles: IDL.Nat,\n destination_id: IDL.Principal\n });\n const GetAnalytics = IDL.Record({\n to: IDL.Opt(IDL.Nat64),\n from: IDL.Opt(IDL.Nat64),\n satellite_id: IDL.Opt(IDL.Principal)\n });\n const AnalyticKey = IDL.Record({\n key: IDL.Text,\n collected_at: IDL.Nat64\n });\n const PageViewClient = IDL.Record({\n os: IDL.Text,\n device: IDL.Opt(IDL.Text),\n browser: IDL.Text\n });\n const PageViewCampaign = IDL.Record({\n utm_content: IDL.Opt(IDL.Text),\n utm_medium: IDL.Opt(IDL.Text),\n utm_source: IDL.Text,\n utm_term: IDL.Opt(IDL.Text),\n utm_campaign: IDL.Opt(IDL.Text)\n });\n const PageViewDevice = IDL.Record({\n inner_height: IDL.Nat16,\n screen_height: IDL.Opt(IDL.Nat16),\n screen_width: IDL.Opt(IDL.Nat16),\n inner_width: IDL.Nat16\n });\n const PageView = IDL.Record({\n client: IDL.Opt(PageViewClient),\n title: IDL.Text,\n updated_at: IDL.Nat64,\n referrer: IDL.Opt(IDL.Text),\n time_zone: IDL.Text,\n session_id: IDL.Text,\n campaign: IDL.Opt(PageViewCampaign),\n href: IDL.Text,\n created_at: IDL.Nat64,\n satellite_id: IDL.Principal,\n device: PageViewDevice,\n version: IDL.Opt(IDL.Nat64),\n user_agent: IDL.Opt(IDL.Text)\n });\n const AnalyticsBrowsersPageViews = IDL.Record({\n safari: IDL.Float64,\n opera: IDL.Float64,\n others: IDL.Float64,\n firefox: IDL.Float64,\n chrome: IDL.Float64\n });\n const AnalyticsOperatingSystemsPageViews = IDL.Record({\n ios: IDL.Float64,\n macos: IDL.Float64,\n others: IDL.Float64,\n linux: IDL.Float64,\n android: IDL.Float64,\n windows: IDL.Float64\n });\n const AnalyticsDevicesPageViews = IDL.Record({\n desktop: IDL.Float64,\n laptop: IDL.Opt(IDL.Float64),\n others: IDL.Float64,\n tablet: IDL.Opt(IDL.Float64),\n mobile: IDL.Float64\n });\n const AnalyticsClientsPageViews = IDL.Record({\n browsers: AnalyticsBrowsersPageViews,\n operating_systems: IDL.Opt(AnalyticsOperatingSystemsPageViews),\n devices: AnalyticsDevicesPageViews\n });\n const CalendarDate = IDL.Record({\n day: IDL.Nat8,\n month: IDL.Nat8,\n year: IDL.Int32\n });\n const AnalyticsMetricsPageViews = IDL.Record({\n bounce_rate: IDL.Float64,\n average_page_views_per_session: IDL.Float64,\n daily_total_page_views: IDL.Vec(IDL.Tuple(CalendarDate, IDL.Nat32)),\n total_page_views: IDL.Nat32,\n unique_page_views: IDL.Nat64,\n unique_sessions: IDL.Nat64\n });\n const AnalyticsTop10PageViews = IDL.Record({\n referrers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32)),\n pages: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32)),\n utm_campaigns: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32))),\n utm_sources: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32))),\n time_zones: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32)))\n });\n const NavigationType = IDL.Variant({\n Navigate: IDL.Null,\n Restore: IDL.Null,\n Reload: IDL.Null,\n BackForward: IDL.Null,\n BackForwardCache: IDL.Null,\n Prerender: IDL.Null\n });\n const WebVitalsMetric = IDL.Record({\n id: IDL.Text,\n value: IDL.Float64,\n navigation_type: IDL.Opt(NavigationType),\n delta: IDL.Float64\n });\n const PerformanceData = IDL.Variant({WebVitalsMetric: WebVitalsMetric});\n const PerformanceMetricName = IDL.Variant({\n CLS: IDL.Null,\n FCP: IDL.Null,\n INP: IDL.Null,\n LCP: IDL.Null,\n TTFB: IDL.Null\n });\n const PerformanceMetric = IDL.Record({\n updated_at: IDL.Nat64,\n session_id: IDL.Text,\n data: PerformanceData,\n href: IDL.Text,\n metric_name: PerformanceMetricName,\n created_at: IDL.Nat64,\n satellite_id: IDL.Principal,\n version: IDL.Opt(IDL.Nat64)\n });\n const AnalyticsWebVitalsPageMetrics = IDL.Record({\n cls: IDL.Opt(IDL.Float64),\n fcp: IDL.Opt(IDL.Float64),\n inp: IDL.Opt(IDL.Float64),\n lcp: IDL.Opt(IDL.Float64),\n ttfb: IDL.Opt(IDL.Float64)\n });\n const AnalyticsWebVitalsPerformanceMetrics = IDL.Record({\n overall: AnalyticsWebVitalsPageMetrics,\n pages: IDL.Vec(IDL.Tuple(IDL.Text, AnalyticsWebVitalsPageMetrics))\n });\n const TrackEvent = IDL.Record({\n updated_at: IDL.Nat64,\n session_id: IDL.Text,\n metadata: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))),\n name: IDL.Text,\n created_at: IDL.Nat64,\n satellite_id: IDL.Principal,\n version: IDL.Opt(IDL.Nat64)\n });\n const AnalyticsTrackEvents = IDL.Record({\n total: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32))\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 HttpResponse = IDL.Record({\n body: IDL.Vec(IDL.Nat8),\n headers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n upgrade: IDL.Opt(IDL.Bool),\n status_code: IDL.Nat16\n });\n const OrbiterSatelliteFeatures = IDL.Record({\n performance_metrics: IDL.Bool,\n track_events: IDL.Bool,\n page_views: IDL.Bool\n });\n const OrbiterSatelliteConfig = IDL.Record({\n updated_at: IDL.Nat64,\n features: IDL.Opt(OrbiterSatelliteFeatures),\n restricted_origin: IDL.Opt(IDL.Text),\n created_at: IDL.Nat64,\n version: IDL.Opt(IDL.Nat64)\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 SetPageView = IDL.Record({\n client: IDL.Opt(PageViewClient),\n title: IDL.Text,\n updated_at: IDL.Opt(IDL.Nat64),\n referrer: IDL.Opt(IDL.Text),\n time_zone: IDL.Text,\n session_id: IDL.Text,\n campaign: IDL.Opt(PageViewCampaign),\n href: IDL.Text,\n satellite_id: IDL.Principal,\n device: PageViewDevice,\n version: IDL.Opt(IDL.Nat64),\n user_agent: IDL.Opt(IDL.Text)\n });\n const Result = IDL.Variant({Ok: PageView, Err: IDL.Text});\n const Result_1 = IDL.Variant({\n Ok: IDL.Null,\n Err: IDL.Vec(IDL.Tuple(AnalyticKey, IDL.Text))\n });\n const SetPerformanceMetric = IDL.Record({\n session_id: IDL.Text,\n data: PerformanceData,\n href: IDL.Text,\n metric_name: PerformanceMetricName,\n satellite_id: IDL.Principal,\n version: IDL.Opt(IDL.Nat64),\n user_agent: IDL.Opt(IDL.Text)\n });\n const Result_2 = IDL.Variant({Ok: PerformanceMetric, Err: IDL.Text});\n const SetSatelliteConfig = IDL.Record({\n features: IDL.Opt(OrbiterSatelliteFeatures),\n restricted_origin: IDL.Opt(IDL.Text),\n version: IDL.Opt(IDL.Nat64)\n });\n const SetTrackEvent = IDL.Record({\n updated_at: IDL.Opt(IDL.Nat64),\n session_id: IDL.Text,\n metadata: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))),\n name: IDL.Text,\n satellite_id: IDL.Principal,\n version: IDL.Opt(IDL.Nat64),\n user_agent: IDL.Opt(IDL.Text)\n });\n const Result_3 = IDL.Variant({Ok: TrackEvent, Err: IDL.Text});\n return IDL.Service({\n del_controllers: IDL.Func(\n [DeleteControllersArgs],\n [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))],\n []\n ),\n del_satellite_config: IDL.Func([IDL.Principal, DelSatelliteConfig], [], []),\n deposit_cycles: IDL.Func([DepositCyclesArgs], [], []),\n get_page_views: IDL.Func([GetAnalytics], [IDL.Vec(IDL.Tuple(AnalyticKey, PageView))], []),\n get_page_views_analytics_clients: IDL.Func([GetAnalytics], [AnalyticsClientsPageViews], []),\n get_page_views_analytics_metrics: IDL.Func([GetAnalytics], [AnalyticsMetricsPageViews], []),\n get_page_views_analytics_top_10: IDL.Func([GetAnalytics], [AnalyticsTop10PageViews], []),\n get_performance_metrics: IDL.Func(\n [GetAnalytics],\n [IDL.Vec(IDL.Tuple(AnalyticKey, PerformanceMetric))],\n []\n ),\n get_performance_metrics_analytics_web_vitals: IDL.Func(\n [GetAnalytics],\n [AnalyticsWebVitalsPerformanceMetrics],\n []\n ),\n get_track_events: IDL.Func([GetAnalytics], [IDL.Vec(IDL.Tuple(AnalyticKey, TrackEvent))], []),\n get_track_events_analytics: IDL.Func([GetAnalytics], [AnalyticsTrackEvents], []),\n http_request: IDL.Func([HttpRequest], [HttpResponse], []),\n http_request_update: IDL.Func([HttpRequest], [HttpResponse], []),\n list_controllers: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))], []),\n list_satellite_configs: IDL.Func(\n [],\n [IDL.Vec(IDL.Tuple(IDL.Principal, OrbiterSatelliteConfig))],\n []\n ),\n memory_size: IDL.Func([], [MemorySize], []),\n set_controllers: IDL.Func(\n [SetControllersArgs],\n [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))],\n []\n ),\n set_page_view: IDL.Func([AnalyticKey, SetPageView], [Result], []),\n set_page_views: IDL.Func([IDL.Vec(IDL.Tuple(AnalyticKey, SetPageView))], [Result_1], []),\n set_performance_metric: IDL.Func([AnalyticKey, SetPerformanceMetric], [Result_2], []),\n set_performance_metrics: IDL.Func(\n [IDL.Vec(IDL.Tuple(AnalyticKey, SetPerformanceMetric))],\n [Result_1],\n []\n ),\n set_satellite_configs: IDL.Func(\n [IDL.Vec(IDL.Tuple(IDL.Principal, SetSatelliteConfig))],\n [IDL.Vec(IDL.Tuple(IDL.Principal, OrbiterSatelliteConfig))],\n []\n ),\n set_track_event: IDL.Func([AnalyticKey, SetTrackEvent], [Result_3], []),\n set_track_events: IDL.Func([IDL.Vec(IDL.Tuple(AnalyticKey, SetTrackEvent))], [Result_1], [])\n });\n};\n// @ts-ignore\nexport const init = ({IDL}) => {\n const SegmentArgs = IDL.Record({controllers: IDL.Vec(IDL.Principal)});\n return [SegmentArgs];\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 DeleteControllersArgs = IDL.Record({\n controllers: IDL.Vec(IDL.Principal)\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 expires_at: IDL.Opt(IDL.Nat64)\n });\n const DelDoc = IDL.Record({updated_at: IDL.Opt(IDL.Nat64)});\n const StorageConfig = IDL.Record({\n headers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))))\n });\n const Config = IDL.Record({storage: StorageConfig});\n const Doc = IDL.Record({\n updated_at: IDL.Nat64,\n owner: IDL.Principal,\n data: IDL.Vec(IDL.Nat8),\n created_at: 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 });\n const StreamingCallbackToken = IDL.Record({\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([], [], [])\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 encoding_type: IDL.Opt(IDL.Text),\n full_path: IDL.Text\n });\n const InitUploadResult = IDL.Record({batch_id: IDL.Nat});\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 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(IDL.Text),\n paginate: IDL.Opt(ListPaginate)\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 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 });\n const ListResults = IDL.Record({\n matches_length: IDL.Nat64,\n length: IDL.Nat64,\n items: IDL.Vec(IDL.Tuple(IDL.Text, AssetNoContent))\n });\n const CustomDomain = IDL.Record({\n updated_at: IDL.Nat64,\n created_at: IDL.Nat64,\n bn_id: IDL.Opt(IDL.Text)\n });\n const ListResults_1 = IDL.Record({\n matches_length: IDL.Nat64,\n length: IDL.Nat64,\n items: IDL.Vec(IDL.Tuple(IDL.Text, Doc))\n });\n const RulesType = IDL.Variant({Db: IDL.Null, Storage: IDL.Null});\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 updated_at: IDL.Nat64,\n max_size: IDL.Opt(IDL.Nat),\n read: Permission,\n created_at: IDL.Nat64,\n write: Permission\n });\n const SetController = IDL.Record({\n metadata: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\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 updated_at: IDL.Opt(IDL.Nat64),\n data: IDL.Vec(IDL.Nat8)\n });\n const SetRule = IDL.Record({\n updated_at: IDL.Opt(IDL.Nat64),\n max_size: IDL.Opt(IDL.Nat),\n read: Permission,\n write: Permission\n });\n const Chunk = IDL.Record({\n content: IDL.Vec(IDL.Nat8),\n batch_id: IDL.Nat\n });\n const UploadChunk = IDL.Record({chunk_id: IDL.Nat});\n return IDL.Service({\n commit_asset_upload: IDL.Func([CommitBatch], [], []),\n del_asset: IDL.Func([IDL.Text, IDL.Text], [], []),\n del_assets: IDL.Func([IDL.Opt(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 get_config: IDL.Func([], [Config], []),\n get_doc: IDL.Func([IDL.Text, IDL.Text], [IDL.Opt(Doc)], ['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.Opt(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 set_config: IDL.Func([Config], [], []),\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_doc: IDL.Func([IDL.Text, IDL.Text, SetDoc], [Doc], []),\n set_rule: IDL.Func([RulesType, IDL.Text, SetRule], [], []),\n upload_asset_chunk: IDL.Func([Chunk], [UploadChunk], []),\n version: IDL.Func([], [IDL.Text], ['query'])\n });\n};\n// @ts-ignore\nexport const init = ({IDL}) => {\n return [];\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 CollectionType = 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 external_alternative_origins: IDL.Opt(IDL.Vec(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 Memory = IDL.Variant({Heap: IDL.Null, Stable: IDL.Null});\n const Permission = IDL.Variant({\n Controllers: IDL.Null,\n Private: IDL.Null,\n Public: IDL.Null,\n Managed: IDL.Null\n });\n const RateConfig = IDL.Record({\n max_tokens: IDL.Nat64,\n time_per_token_ns: IDL.Nat64\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 rate_config: IDL.Opt(RateConfig),\n write: Permission,\n max_changes_per_user: IDL.Opt(IDL.Nat32)\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 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 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 rate_config: IDL.Opt(RateConfig),\n write: Permission,\n max_changes_per_user: IDL.Opt(IDL.Nat32)\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_filtered_assets: IDL.Func([IDL.Text, ListParams], [], []),\n del_filtered_docs: IDL.Func([IDL.Text, ListParams], [], []),\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([CollectionType, 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_rule: IDL.Func([CollectionType, IDL.Text], [IDL.Opt(Rule)], ['query']),\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([CollectionType], [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([CollectionType, IDL.Text, SetRule], [Rule], []),\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", "// @ts-ignore\nexport const idlFactory = ({IDL}) => {\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 DelSatelliteConfig = IDL.Record({version: IDL.Opt(IDL.Nat64)});\n const DepositCyclesArgs = IDL.Record({\n cycles: IDL.Nat,\n destination_id: IDL.Principal\n });\n const GetAnalytics = IDL.Record({\n to: IDL.Opt(IDL.Nat64),\n from: IDL.Opt(IDL.Nat64),\n satellite_id: IDL.Opt(IDL.Principal)\n });\n const AnalyticKey = IDL.Record({\n key: IDL.Text,\n collected_at: IDL.Nat64\n });\n const PageViewDevice = IDL.Record({\n inner_height: IDL.Nat16,\n inner_width: IDL.Nat16\n });\n const PageView = IDL.Record({\n title: IDL.Text,\n updated_at: IDL.Nat64,\n referrer: IDL.Opt(IDL.Text),\n time_zone: IDL.Text,\n session_id: IDL.Text,\n href: IDL.Text,\n created_at: IDL.Nat64,\n satellite_id: IDL.Principal,\n device: PageViewDevice,\n version: IDL.Opt(IDL.Nat64),\n user_agent: IDL.Opt(IDL.Text)\n });\n const AnalyticsBrowsersPageViews = IDL.Record({\n safari: IDL.Float64,\n opera: IDL.Float64,\n others: IDL.Float64,\n firefox: IDL.Float64,\n chrome: IDL.Float64\n });\n const AnalyticsDevicesPageViews = IDL.Record({\n desktop: IDL.Float64,\n others: IDL.Float64,\n mobile: IDL.Float64\n });\n const AnalyticsClientsPageViews = IDL.Record({\n browsers: AnalyticsBrowsersPageViews,\n devices: AnalyticsDevicesPageViews\n });\n const CalendarDate = IDL.Record({\n day: IDL.Nat8,\n month: IDL.Nat8,\n year: IDL.Int32\n });\n const AnalyticsMetricsPageViews = IDL.Record({\n bounce_rate: IDL.Float64,\n average_page_views_per_session: IDL.Float64,\n daily_total_page_views: IDL.Vec(IDL.Tuple(CalendarDate, IDL.Nat32)),\n total_page_views: IDL.Nat32,\n unique_page_views: IDL.Nat64,\n unique_sessions: IDL.Nat64\n });\n const AnalyticsTop10PageViews = IDL.Record({\n referrers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32)),\n pages: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32))\n });\n const NavigationType = IDL.Variant({\n Navigate: IDL.Null,\n Restore: IDL.Null,\n Reload: IDL.Null,\n BackForward: IDL.Null,\n BackForwardCache: IDL.Null,\n Prerender: IDL.Null\n });\n const WebVitalsMetric = IDL.Record({\n id: IDL.Text,\n value: IDL.Float64,\n navigation_type: IDL.Opt(NavigationType),\n delta: IDL.Float64\n });\n const PerformanceData = IDL.Variant({WebVitalsMetric: WebVitalsMetric});\n const PerformanceMetricName = IDL.Variant({\n CLS: IDL.Null,\n FCP: IDL.Null,\n INP: IDL.Null,\n LCP: IDL.Null,\n TTFB: IDL.Null\n });\n const PerformanceMetric = IDL.Record({\n updated_at: IDL.Nat64,\n session_id: IDL.Text,\n data: PerformanceData,\n href: IDL.Text,\n metric_name: PerformanceMetricName,\n created_at: IDL.Nat64,\n satellite_id: IDL.Principal,\n version: IDL.Opt(IDL.Nat64)\n });\n const AnalyticsWebVitalsPageMetrics = IDL.Record({\n cls: IDL.Opt(IDL.Float64),\n fcp: IDL.Opt(IDL.Float64),\n inp: IDL.Opt(IDL.Float64),\n lcp: IDL.Opt(IDL.Float64),\n ttfb: IDL.Opt(IDL.Float64)\n });\n const AnalyticsWebVitalsPerformanceMetrics = IDL.Record({\n overall: AnalyticsWebVitalsPageMetrics,\n pages: IDL.Vec(IDL.Tuple(IDL.Text, AnalyticsWebVitalsPageMetrics))\n });\n const TrackEvent = IDL.Record({\n updated_at: IDL.Nat64,\n session_id: IDL.Text,\n metadata: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))),\n name: IDL.Text,\n created_at: IDL.Nat64,\n satellite_id: IDL.Principal,\n version: IDL.Opt(IDL.Nat64)\n });\n const AnalyticsTrackEvents = IDL.Record({\n total: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32))\n });\n const OrbiterSatelliteFeatures = IDL.Record({\n performance_metrics: IDL.Bool,\n track_events: IDL.Bool,\n page_views: IDL.Bool\n });\n const OrbiterSatelliteConfig = IDL.Record({\n updated_at: IDL.Nat64,\n features: IDL.Opt(OrbiterSatelliteFeatures),\n created_at: IDL.Nat64,\n version: IDL.Opt(IDL.Nat64)\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 SetPageView = IDL.Record({\n title: IDL.Text,\n updated_at: IDL.Opt(IDL.Nat64),\n referrer: IDL.Opt(IDL.Text),\n time_zone: IDL.Text,\n session_id: IDL.Text,\n href: IDL.Text,\n satellite_id: IDL.Principal,\n device: PageViewDevice,\n version: IDL.Opt(IDL.Nat64),\n user_agent: IDL.Opt(IDL.Text)\n });\n const Result = IDL.Variant({Ok: PageView, Err: IDL.Text});\n const Result_1 = IDL.Variant({\n Ok: IDL.Null,\n Err: IDL.Vec(IDL.Tuple(AnalyticKey, IDL.Text))\n });\n const SetPerformanceMetric = IDL.Record({\n session_id: IDL.Text,\n data: PerformanceData,\n href: IDL.Text,\n metric_name: PerformanceMetricName,\n satellite_id: IDL.Principal,\n version: IDL.Opt(IDL.Nat64),\n user_agent: IDL.Opt(IDL.Text)\n });\n const Result_2 = IDL.Variant({Ok: PerformanceMetric, Err: IDL.Text});\n const SetSatelliteConfig = IDL.Record({\n features: IDL.Opt(OrbiterSatelliteFeatures),\n version: IDL.Opt(IDL.Nat64)\n });\n const SetTrackEvent = IDL.Record({\n updated_at: IDL.Opt(IDL.Nat64),\n session_id: IDL.Text,\n metadata: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))),\n name: IDL.Text,\n satellite_id: IDL.Principal,\n version: IDL.Opt(IDL.Nat64),\n user_agent: IDL.Opt(IDL.Text)\n });\n const Result_3 = IDL.Variant({Ok: TrackEvent, Err: IDL.Text});\n return IDL.Service({\n del_controllers: IDL.Func(\n [DeleteControllersArgs],\n [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))],\n []\n ),\n del_satellite_config: IDL.Func([IDL.Principal, DelSatelliteConfig], [], []),\n deposit_cycles: IDL.Func([DepositCyclesArgs], [], []),\n get_page_views: IDL.Func(\n [GetAnalytics],\n [IDL.Vec(IDL.Tuple(AnalyticKey, PageView))],\n ['query']\n ),\n get_page_views_analytics_clients: IDL.Func(\n [GetAnalytics],\n [AnalyticsClientsPageViews],\n ['query']\n ),\n get_page_views_analytics_metrics: IDL.Func(\n [GetAnalytics],\n [AnalyticsMetricsPageViews],\n ['query']\n ),\n get_page_views_analytics_top_10: IDL.Func([GetAnalytics], [AnalyticsTop10PageViews], ['query']),\n get_performance_metrics: IDL.Func(\n [GetAnalytics],\n [IDL.Vec(IDL.Tuple(AnalyticKey, PerformanceMetric))],\n ['query']\n ),\n get_performance_metrics_analytics_web_vitals: IDL.Func(\n [GetAnalytics],\n [AnalyticsWebVitalsPerformanceMetrics],\n ['query']\n ),\n get_track_events: IDL.Func(\n [GetAnalytics],\n [IDL.Vec(IDL.Tuple(AnalyticKey, TrackEvent))],\n ['query']\n ),\n get_track_events_analytics: IDL.Func([GetAnalytics], [AnalyticsTrackEvents], ['query']),\n list_controllers: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))], ['query']),\n list_satellite_configs: IDL.Func(\n [],\n [IDL.Vec(IDL.Tuple(IDL.Principal, OrbiterSatelliteConfig))],\n ['query']\n ),\n memory_size: IDL.Func([], [MemorySize], ['query']),\n set_controllers: IDL.Func(\n [SetControllersArgs],\n [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))],\n []\n ),\n set_page_view: IDL.Func([AnalyticKey, SetPageView], [Result], []),\n set_page_views: IDL.Func([IDL.Vec(IDL.Tuple(AnalyticKey, SetPageView))], [Result_1], []),\n set_performance_metric: IDL.Func([AnalyticKey, SetPerformanceMetric], [Result_2], []),\n set_performance_metrics: IDL.Func(\n [IDL.Vec(IDL.Tuple(AnalyticKey, SetPerformanceMetric))],\n [Result_1],\n []\n ),\n set_satellite_configs: IDL.Func(\n [IDL.Vec(IDL.Tuple(IDL.Principal, SetSatelliteConfig))],\n [IDL.Vec(IDL.Tuple(IDL.Principal, OrbiterSatelliteConfig))],\n []\n ),\n set_track_event: IDL.Func([AnalyticKey, SetTrackEvent], [Result_3], []),\n set_track_events: IDL.Func([IDL.Vec(IDL.Tuple(AnalyticKey, SetTrackEvent))], [Result_1], []),\n version: IDL.Func([], [IDL.Text], ['query'])\n });\n};\n// @ts-ignore\nexport const init = ({IDL}) => {\n return [];\n};\n", "// @ts-ignore\nexport const idlFactory = ({IDL}) => {\n const CyclesThreshold = IDL.Record({\n fund_cycles: IDL.Nat,\n min_cycles: IDL.Nat\n });\n const CyclesMonitoringStrategy = IDL.Variant({\n BelowThreshold: CyclesThreshold\n });\n const CyclesMonitoring = IDL.Record({\n strategy: IDL.Opt(CyclesMonitoringStrategy),\n enabled: IDL.Bool\n });\n const Monitoring = IDL.Record({cycles: IDL.Opt(CyclesMonitoring)});\n const Settings = IDL.Record({monitoring: IDL.Opt(Monitoring)});\n const Orbiter = IDL.Record({\n updated_at: IDL.Nat64,\n orbiter_id: IDL.Principal,\n metadata: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n created_at: IDL.Nat64,\n settings: IDL.Opt(Settings)\n });\n const CreateCanisterConfig = IDL.Record({\n subnet_id: IDL.Opt(IDL.Principal),\n name: IDL.Opt(IDL.Text)\n });\n const Satellite = IDL.Record({\n updated_at: IDL.Nat64,\n metadata: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n created_at: IDL.Nat64,\n satellite_id: IDL.Principal,\n settings: IDL.Opt(Settings)\n });\n const DepositCyclesArgs = IDL.Record({\n cycles: IDL.Nat,\n destination_id: IDL.Principal\n });\n const DepositedCyclesEmailNotification = IDL.Record({\n to: IDL.Opt(IDL.Text),\n enabled: IDL.Bool\n });\n const CyclesMonitoringConfig = IDL.Record({\n notification: IDL.Opt(DepositedCyclesEmailNotification),\n default_strategy: IDL.Opt(CyclesMonitoringStrategy)\n });\n const MonitoringConfig = IDL.Record({\n cycles: IDL.Opt(CyclesMonitoringConfig)\n });\n const Config = IDL.Record({monitoring: IDL.Opt(MonitoringConfig)});\n const GetMonitoringHistory = IDL.Record({\n to: IDL.Opt(IDL.Nat64),\n from: IDL.Opt(IDL.Nat64),\n segment_id: IDL.Principal\n });\n const MonitoringHistoryKey = IDL.Record({\n segment_id: IDL.Principal,\n created_at: IDL.Nat64,\n nonce: IDL.Int32\n });\n const CyclesBalance = IDL.Record({\n timestamp: IDL.Nat64,\n amount: IDL.Nat\n });\n const MonitoringHistoryCycles = IDL.Record({\n deposited_cycles: IDL.Opt(CyclesBalance),\n cycles: CyclesBalance\n });\n const MonitoringHistory = IDL.Record({\n cycles: IDL.Opt(MonitoringHistoryCycles)\n });\n const CyclesMonitoringStatus = IDL.Record({\n monitored_ids: IDL.Vec(IDL.Principal),\n running: IDL.Bool\n });\n const MonitoringStatus = IDL.Record({\n cycles: IDL.Opt(CyclesMonitoringStatus)\n });\n const MissionControlSettings = IDL.Record({\n updated_at: IDL.Nat64,\n created_at: IDL.Nat64,\n monitoring: IDL.Opt(Monitoring)\n });\n const User = IDL.Record({\n updated_at: IDL.Nat64,\n metadata: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n user: IDL.Opt(IDL.Principal),\n created_at: IDL.Nat64,\n config: IDL.Opt(Config)\n });\n const Tokens = IDL.Record({e8s: IDL.Nat64});\n const Timestamp = IDL.Record({timestamp_nanos: IDL.Nat64});\n const TransferArgs = IDL.Record({\n to: IDL.Vec(IDL.Nat8),\n fee: Tokens,\n memo: IDL.Nat64,\n from_subaccount: IDL.Opt(IDL.Vec(IDL.Nat8)),\n created_at_time: IDL.Opt(Timestamp),\n amount: Tokens\n });\n const TransferError = IDL.Variant({\n TxTooOld: IDL.Record({allowed_window_nanos: IDL.Nat64}),\n BadFee: IDL.Record({expected_fee: Tokens}),\n TxDuplicate: IDL.Record({duplicate_of: IDL.Nat64}),\n TxCreatedInFuture: IDL.Null,\n InsufficientFunds: IDL.Record({balance: Tokens})\n });\n const Result = IDL.Variant({Ok: IDL.Nat64, Err: TransferError});\n const Account = IDL.Record({\n owner: IDL.Principal,\n subaccount: IDL.Opt(IDL.Vec(IDL.Nat8))\n });\n const TransferArg = IDL.Record({\n to: Account,\n fee: IDL.Opt(IDL.Nat),\n memo: IDL.Opt(IDL.Vec(IDL.Nat8)),\n from_subaccount: IDL.Opt(IDL.Vec(IDL.Nat8)),\n created_at_time: IDL.Opt(IDL.Nat64),\n amount: IDL.Nat\n });\n const TransferError_1 = IDL.Variant({\n GenericError: IDL.Record({\n message: IDL.Text,\n error_code: IDL.Nat\n }),\n TemporarilyUnavailable: IDL.Null,\n BadBurn: IDL.Record({min_burn_amount: IDL.Nat}),\n Duplicate: IDL.Record({duplicate_of: IDL.Nat}),\n BadFee: IDL.Record({expected_fee: IDL.Nat}),\n CreatedInFuture: IDL.Record({ledger_time: IDL.Nat64}),\n TooOld: IDL.Null,\n InsufficientFunds: IDL.Record({balance: IDL.Nat})\n });\n const Result_1 = IDL.Variant({Ok: IDL.Nat, Err: TransferError_1});\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 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 SegmentsMonitoringStrategy = IDL.Record({\n ids: IDL.Vec(IDL.Principal),\n strategy: CyclesMonitoringStrategy\n });\n const CyclesMonitoringStartConfig = IDL.Record({\n orbiters_strategy: IDL.Opt(SegmentsMonitoringStrategy),\n mission_control_strategy: IDL.Opt(CyclesMonitoringStrategy),\n satellites_strategy: IDL.Opt(SegmentsMonitoringStrategy)\n });\n const MonitoringStartConfig = IDL.Record({\n cycles_config: IDL.Opt(CyclesMonitoringStartConfig)\n });\n const CyclesMonitoringStopConfig = IDL.Record({\n satellite_ids: IDL.Opt(IDL.Vec(IDL.Principal)),\n try_mission_control: IDL.Opt(IDL.Bool),\n orbiter_ids: IDL.Opt(IDL.Vec(IDL.Principal))\n });\n const MonitoringStopConfig = IDL.Record({\n cycles_config: IDL.Opt(CyclesMonitoringStopConfig)\n });\n return IDL.Service({\n add_mission_control_controllers: IDL.Func([IDL.Vec(IDL.Principal)], [], []),\n add_satellites_controllers: IDL.Func([IDL.Vec(IDL.Principal), IDL.Vec(IDL.Principal)], [], []),\n create_orbiter: IDL.Func([IDL.Opt(IDL.Text)], [Orbiter], []),\n create_orbiter_with_config: IDL.Func([CreateCanisterConfig], [Orbiter], []),\n create_satellite: IDL.Func([IDL.Text], [Satellite], []),\n create_satellite_with_config: IDL.Func([CreateCanisterConfig], [Satellite], []),\n del_mission_control_controllers: IDL.Func([IDL.Vec(IDL.Principal)], [], []),\n del_orbiter: IDL.Func([IDL.Principal, IDL.Nat], [], []),\n del_orbiters_controllers: IDL.Func([IDL.Vec(IDL.Principal), IDL.Vec(IDL.Principal)], [], []),\n del_satellite: IDL.Func([IDL.Principal, IDL.Nat], [], []),\n del_satellites_controllers: IDL.Func([IDL.Vec(IDL.Principal), IDL.Vec(IDL.Principal)], [], []),\n deposit_cycles: IDL.Func([DepositCyclesArgs], [], []),\n get_config: IDL.Func([], [IDL.Opt(Config)], ['query']),\n get_metadata: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))], ['query']),\n get_monitoring_history: IDL.Func(\n [GetMonitoringHistory],\n [IDL.Vec(IDL.Tuple(MonitoringHistoryKey, MonitoringHistory))],\n ['query']\n ),\n get_monitoring_status: IDL.Func([], [MonitoringStatus], ['query']),\n get_settings: IDL.Func([], [IDL.Opt(MissionControlSettings)], ['query']),\n get_user: IDL.Func([], [IDL.Principal], ['query']),\n get_user_data: IDL.Func([], [User], ['query']),\n icp_transfer: IDL.Func([TransferArgs], [Result], []),\n icrc_transfer: IDL.Func([IDL.Principal, TransferArg], [Result_1], []),\n list_mission_control_controllers: IDL.Func(\n [],\n [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))],\n ['query']\n ),\n list_orbiters: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Principal, Orbiter))], ['query']),\n list_satellites: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Principal, Satellite))], ['query']),\n remove_mission_control_controllers: IDL.Func([IDL.Vec(IDL.Principal)], [], []),\n remove_satellites_controllers: IDL.Func(\n [IDL.Vec(IDL.Principal), IDL.Vec(IDL.Principal)],\n [],\n []\n ),\n set_config: IDL.Func([IDL.Opt(Config)], [], []),\n set_metadata: IDL.Func([IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))], [], []),\n set_mission_control_controllers: IDL.Func([IDL.Vec(IDL.Principal), SetController], [], []),\n set_orbiter: IDL.Func([IDL.Principal, IDL.Opt(IDL.Text)], [Orbiter], []),\n set_orbiter_metadata: IDL.Func(\n [IDL.Principal, IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))],\n [Orbiter],\n []\n ),\n set_orbiters_controllers: IDL.Func(\n [IDL.Vec(IDL.Principal), IDL.Vec(IDL.Principal), SetController],\n [],\n []\n ),\n set_satellite: IDL.Func([IDL.Principal, IDL.Opt(IDL.Text)], [Satellite], []),\n set_satellite_metadata: IDL.Func(\n [IDL.Principal, IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))],\n [Satellite],\n []\n ),\n set_satellites_controllers: IDL.Func(\n [IDL.Vec(IDL.Principal), IDL.Vec(IDL.Principal), SetController],\n [],\n []\n ),\n start_monitoring: IDL.Func([], [], []),\n stop_monitoring: IDL.Func([], [], []),\n top_up: IDL.Func([IDL.Principal, Tokens], [], []),\n unset_orbiter: IDL.Func([IDL.Principal], [], []),\n unset_satellite: IDL.Func([IDL.Principal], [], []),\n update_and_start_monitoring: IDL.Func([MonitoringStartConfig], [], []),\n update_and_stop_monitoring: IDL.Func([MonitoringStopConfig], [], []),\n version: IDL.Func([], [IDL.Text], ['query'])\n });\n};\n// @ts-ignore\nexport const init = ({IDL}) => {\n return [];\n};\n", "export 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 DeleteControllersArgs = IDL.Record({\n controllers: IDL.Vec(IDL.Principal)\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 expires_at: IDL.Opt(IDL.Nat64)\n });\n const DelDoc = IDL.Record({updated_at: IDL.Opt(IDL.Nat64)});\n const StorageConfig = IDL.Record({\n headers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))))\n });\n const Config = IDL.Record({storage: StorageConfig});\n const Doc = IDL.Record({\n updated_at: IDL.Nat64,\n owner: IDL.Principal,\n data: IDL.Vec(IDL.Nat8),\n created_at: 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 });\n const StreamingCallbackToken = IDL.Record({\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([], [], [])\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 encoding_type: IDL.Opt(IDL.Text),\n full_path: IDL.Text\n });\n const InitUploadResult = IDL.Record({batch_id: IDL.Nat});\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 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 matcher: IDL.Opt(IDL.Text),\n paginate: IDL.Opt(ListPaginate)\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 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 });\n const ListResults = IDL.Record({\n matches_length: IDL.Nat64,\n length: IDL.Nat64,\n items: IDL.Vec(IDL.Tuple(IDL.Text, AssetNoContent))\n });\n const CustomDomain = IDL.Record({\n updated_at: IDL.Nat64,\n created_at: IDL.Nat64,\n bn_id: IDL.Opt(IDL.Text)\n });\n const ListResults_1 = IDL.Record({\n matches_length: IDL.Nat64,\n length: IDL.Nat64,\n items: IDL.Vec(IDL.Tuple(IDL.Text, Doc))\n });\n const RulesType = IDL.Variant({Db: IDL.Null, Storage: IDL.Null});\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 updated_at: IDL.Nat64,\n max_size: IDL.Opt(IDL.Nat),\n read: Permission,\n created_at: IDL.Nat64,\n write: Permission\n });\n const SetController = IDL.Record({\n metadata: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\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 updated_at: IDL.Opt(IDL.Nat64),\n data: IDL.Vec(IDL.Nat8)\n });\n const SetRule = IDL.Record({\n updated_at: IDL.Opt(IDL.Nat64),\n max_size: IDL.Opt(IDL.Nat),\n read: Permission,\n write: Permission\n });\n const Chunk = IDL.Record({\n content: IDL.Vec(IDL.Nat8),\n batch_id: IDL.Nat\n });\n const UploadChunk = IDL.Record({chunk_id: IDL.Nat});\n return IDL.Service({\n commit_asset_upload: IDL.Func([CommitBatch], [], []),\n del_asset: IDL.Func([IDL.Text, IDL.Text], [], []),\n del_assets: IDL.Func([IDL.Opt(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 get_config: IDL.Func([], [Config], []),\n get_doc: IDL.Func([IDL.Text, IDL.Text], [IDL.Opt(Doc)], ['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.Opt(IDL.Text), ListParams], [ListResults], ['query']),\n list_controllers: IDL.Func([], [IDL.Vec(IDL.Principal)], ['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 set_config: IDL.Func([Config], [], []),\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_doc: IDL.Func([IDL.Text, IDL.Text, SetDoc], [Doc], []),\n set_rule: IDL.Func([RulesType, IDL.Text, SetRule], [], []),\n upload_asset_chunk: IDL.Func([Chunk], [UploadChunk], []),\n version: IDL.Func([], [IDL.Text], ['query'])\n });\n};\nexport const init = ({IDL}) => {\n return [];\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 CommitProposal = IDL.Record({\n sha256: IDL.Vec(IDL.Nat8),\n proposal_id: 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 Submit: 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 CollectionType = IDL.Variant({Db: IDL.Null, Storage: IDL.Null});\n const DelRule = IDL.Record({version: IDL.Opt(IDL.Nat64)});\n const DeleteProposalAssets = IDL.Record({\n proposal_ids: IDL.Vec(IDL.Nat)\n });\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 external_alternative_origins: IDL.Opt(IDL.Vec(IDL.Text))\n });\n const AuthenticationRules = IDL.Record({\n allowed_callers: IDL.Vec(IDL.Principal)\n });\n const AuthenticationConfig = IDL.Record({\n updated_at: IDL.Opt(IDL.Nat64),\n created_at: IDL.Opt(IDL.Nat64),\n version: IDL.Opt(IDL.Nat64),\n internet_identity: IDL.Opt(AuthenticationConfigInternetIdentity),\n rules: IDL.Opt(AuthenticationRules)\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 updated_at: IDL.Opt(IDL.Nat64),\n created_at: IDL.Opt(IDL.Nat64),\n version: IDL.Opt(IDL.Nat64),\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 updated_at: IDL.Opt(IDL.Nat64),\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 created_at: IDL.Opt(IDL.Nat64),\n version: IDL.Opt(IDL.Nat64),\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 ProposalStatus = IDL.Variant({\n Initialized: IDL.Null,\n Failed: IDL.Null,\n Open: IDL.Null,\n Rejected: IDL.Null,\n Executed: IDL.Null,\n Accepted: IDL.Null\n });\n const AssetsUpgradeOptions = IDL.Record({\n clear_existing_assets: IDL.Opt(IDL.Bool)\n });\n const SegmentsDeploymentOptions = IDL.Record({\n orbiter: IDL.Opt(IDL.Text),\n mission_control_version: IDL.Opt(IDL.Text),\n satellite_version: IDL.Opt(IDL.Text)\n });\n const ProposalType = IDL.Variant({\n AssetsUpgrade: AssetsUpgradeOptions,\n SegmentsDeployment: SegmentsDeploymentOptions\n });\n const Proposal = IDL.Record({\n status: ProposalStatus,\n updated_at: IDL.Nat64,\n sha256: IDL.Opt(IDL.Vec(IDL.Nat8)),\n executed_at: IDL.Opt(IDL.Nat64),\n owner: IDL.Principal,\n created_at: IDL.Nat64,\n version: IDL.Opt(IDL.Nat64),\n proposal_type: ProposalType\n });\n const Memory = IDL.Variant({Heap: IDL.Null, Stable: IDL.Null});\n const Permission = IDL.Variant({\n Controllers: IDL.Null,\n Private: IDL.Null,\n Public: IDL.Null,\n Managed: IDL.Null\n });\n const RateConfig = IDL.Record({\n max_tokens: IDL.Nat64,\n time_per_token_ns: IDL.Nat64\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 rate_config: IDL.Opt(RateConfig),\n write: Permission,\n max_changes_per_user: IDL.Opt(IDL.Nat32)\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 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 ListProposalsOrder = IDL.Record({desc: IDL.Bool});\n const ListProposalsPaginate = IDL.Record({\n start_after: IDL.Opt(IDL.Nat),\n limit: IDL.Opt(IDL.Nat)\n });\n const ListProposalsParams = IDL.Record({\n order: IDL.Opt(ListProposalsOrder),\n paginate: IDL.Opt(ListProposalsPaginate)\n });\n const ProposalKey = IDL.Record({proposal_id: IDL.Nat});\n const ListProposalResults = IDL.Record({\n matches_length: IDL.Nat64,\n items: IDL.Vec(IDL.Tuple(ProposalKey, Proposal)),\n items_length: IDL.Nat64\n });\n const ListRulesMatcher = IDL.Record({include_system: IDL.Bool});\n const ListRulesParams = IDL.Record({matcher: IDL.Opt(ListRulesMatcher)});\n const ListRulesResults = IDL.Record({\n matches_length: IDL.Nat64,\n items: IDL.Vec(IDL.Tuple(IDL.Text, Rule)),\n items_length: IDL.Nat64\n });\n const MemorySize = IDL.Record({stable: IDL.Nat64, heap: IDL.Nat64});\n const SetAuthenticationConfig = IDL.Record({\n version: IDL.Opt(IDL.Nat64),\n internet_identity: IDL.Opt(AuthenticationConfigInternetIdentity),\n rules: IDL.Opt(AuthenticationRules)\n });\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 SetDbConfig = IDL.Record({\n version: IDL.Opt(IDL.Nat64),\n max_memory_size: IDL.Opt(ConfigMaxMemorySize)\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 rate_config: IDL.Opt(RateConfig),\n write: Permission,\n max_changes_per_user: IDL.Opt(IDL.Nat32)\n });\n const SetStorageConfig = 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 version: IDL.Opt(IDL.Nat64),\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 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 commit_asset_upload: IDL.Func([CommitBatch], [], []),\n commit_proposal: IDL.Func([CommitProposal], [IDL.Null], []),\n commit_proposal_asset_upload: IDL.Func([CommitBatch], [], []),\n commit_proposal_many_assets_upload: IDL.Func([IDL.Vec(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 count_proposals: IDL.Func([], [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_filtered_assets: IDL.Func([IDL.Text, ListParams], [], []),\n del_filtered_docs: IDL.Func([IDL.Text, ListParams], [], []),\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([CollectionType, IDL.Text, DelRule], [], []),\n delete_proposal_assets: IDL.Func([DeleteProposalAssets], [], []),\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_proposal: IDL.Func([IDL.Nat], [IDL.Opt(Proposal)], ['query']),\n get_rule: IDL.Func([CollectionType, IDL.Text], [IDL.Opt(Rule)], ['query']),\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 init_proposal: IDL.Func([ProposalType], [IDL.Nat, Proposal], []),\n init_proposal_asset_upload: IDL.Func([InitAssetKey, IDL.Nat], [InitUploadResult], []),\n init_proposal_many_assets_upload: IDL.Func(\n [IDL.Vec(InitAssetKey), IDL.Nat],\n [IDL.Vec(IDL.Tuple(IDL.Text, InitUploadResult))],\n []\n ),\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_proposals: IDL.Func([ListProposalsParams], [ListProposalResults], ['query']),\n list_rules: IDL.Func([CollectionType, ListRulesParams], [ListRulesResults], ['query']),\n memory_size: IDL.Func([], [MemorySize], ['query']),\n reject_proposal: IDL.Func([CommitProposal], [IDL.Null], []),\n set_auth_config: IDL.Func([SetAuthenticationConfig], [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([SetDbConfig], [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([CollectionType, IDL.Text, SetRule], [Rule], []),\n set_storage_config: IDL.Func([SetStorageConfig], [StorageConfig], []),\n submit_proposal: IDL.Func([IDL.Nat], [IDL.Nat, Proposal], []),\n upload_asset_chunk: IDL.Func([UploadChunk], [UploadChunkResult], []),\n upload_proposal_asset_chunk: IDL.Func([UploadChunk], [UploadChunkResult], [])\n });\n};\n// @ts-ignore\nexport const init = ({IDL}) => {\n return [];\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 CommitProposal = IDL.Record({\n sha256: IDL.Vec(IDL.Nat8),\n proposal_id: 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 Submit: 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 CollectionType = IDL.Variant({Db: IDL.Null, Storage: IDL.Null});\n const DelRule = IDL.Record({version: IDL.Opt(IDL.Nat64)});\n const DeleteProposalAssets = IDL.Record({\n proposal_ids: IDL.Vec(IDL.Nat)\n });\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 external_alternative_origins: IDL.Opt(IDL.Vec(IDL.Text))\n });\n const AuthenticationRules = IDL.Record({\n allowed_callers: IDL.Vec(IDL.Principal)\n });\n const AuthenticationConfig = IDL.Record({\n updated_at: IDL.Opt(IDL.Nat64),\n created_at: IDL.Opt(IDL.Nat64),\n version: IDL.Opt(IDL.Nat64),\n internet_identity: IDL.Opt(AuthenticationConfigInternetIdentity),\n rules: IDL.Opt(AuthenticationRules)\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 updated_at: IDL.Opt(IDL.Nat64),\n created_at: IDL.Opt(IDL.Nat64),\n version: IDL.Opt(IDL.Nat64),\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 updated_at: IDL.Opt(IDL.Nat64),\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 created_at: IDL.Opt(IDL.Nat64),\n version: IDL.Opt(IDL.Nat64),\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 ProposalStatus = IDL.Variant({\n Initialized: IDL.Null,\n Failed: IDL.Null,\n Open: IDL.Null,\n Rejected: IDL.Null,\n Executed: IDL.Null,\n Accepted: IDL.Null\n });\n const AssetsUpgradeOptions = IDL.Record({\n clear_existing_assets: IDL.Opt(IDL.Bool)\n });\n const SegmentsDeploymentOptions = IDL.Record({\n orbiter: IDL.Opt(IDL.Text),\n mission_control_version: IDL.Opt(IDL.Text),\n satellite_version: IDL.Opt(IDL.Text)\n });\n const ProposalType = IDL.Variant({\n AssetsUpgrade: AssetsUpgradeOptions,\n SegmentsDeployment: SegmentsDeploymentOptions\n });\n const Proposal = IDL.Record({\n status: ProposalStatus,\n updated_at: IDL.Nat64,\n sha256: IDL.Opt(IDL.Vec(IDL.Nat8)),\n executed_at: IDL.Opt(IDL.Nat64),\n owner: IDL.Principal,\n created_at: IDL.Nat64,\n version: IDL.Opt(IDL.Nat64),\n proposal_type: ProposalType\n });\n const Memory = IDL.Variant({Heap: IDL.Null, Stable: IDL.Null});\n const Permission = IDL.Variant({\n Controllers: IDL.Null,\n Private: IDL.Null,\n Public: IDL.Null,\n Managed: IDL.Null\n });\n const RateConfig = IDL.Record({\n max_tokens: IDL.Nat64,\n time_per_token_ns: IDL.Nat64\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 rate_config: IDL.Opt(RateConfig),\n write: Permission,\n max_changes_per_user: IDL.Opt(IDL.Nat32)\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 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([], [], [])\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 ListProposalsOrder = IDL.Record({desc: IDL.Bool});\n const ListProposalsPaginate = IDL.Record({\n start_after: IDL.Opt(IDL.Nat),\n limit: IDL.Opt(IDL.Nat)\n });\n const ListProposalsParams = IDL.Record({\n order: IDL.Opt(ListProposalsOrder),\n paginate: IDL.Opt(ListProposalsPaginate)\n });\n const ProposalKey = IDL.Record({proposal_id: IDL.Nat});\n const ListProposalResults = IDL.Record({\n matches_length: IDL.Nat64,\n items: IDL.Vec(IDL.Tuple(ProposalKey, Proposal)),\n items_length: IDL.Nat64\n });\n const ListRulesMatcher = IDL.Record({include_system: IDL.Bool});\n const ListRulesParams = IDL.Record({matcher: IDL.Opt(ListRulesMatcher)});\n const ListRulesResults = IDL.Record({\n matches_length: IDL.Nat64,\n items: IDL.Vec(IDL.Tuple(IDL.Text, Rule)),\n items_length: IDL.Nat64\n });\n const MemorySize = IDL.Record({stable: IDL.Nat64, heap: IDL.Nat64});\n const SetAuthenticationConfig = IDL.Record({\n version: IDL.Opt(IDL.Nat64),\n internet_identity: IDL.Opt(AuthenticationConfigInternetIdentity),\n rules: IDL.Opt(AuthenticationRules)\n });\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 SetDbConfig = IDL.Record({\n version: IDL.Opt(IDL.Nat64),\n max_memory_size: IDL.Opt(ConfigMaxMemorySize)\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 rate_config: IDL.Opt(RateConfig),\n write: Permission,\n max_changes_per_user: IDL.Opt(IDL.Nat32)\n });\n const SetStorageConfig = 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 version: IDL.Opt(IDL.Nat64),\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 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 commit_asset_upload: IDL.Func([CommitBatch], [], []),\n commit_proposal: IDL.Func([CommitProposal], [IDL.Null], []),\n commit_proposal_asset_upload: IDL.Func([CommitBatch], [], []),\n commit_proposal_many_assets_upload: IDL.Func([IDL.Vec(CommitBatch)], [], []),\n count_assets: IDL.Func([IDL.Text, ListParams], [IDL.Nat64], []),\n count_collection_assets: IDL.Func([IDL.Text], [IDL.Nat64], []),\n count_collection_docs: IDL.Func([IDL.Text], [IDL.Nat64], []),\n count_docs: IDL.Func([IDL.Text, ListParams], [IDL.Nat64], []),\n count_proposals: IDL.Func([], [IDL.Nat64], []),\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_filtered_assets: IDL.Func([IDL.Text, ListParams], [], []),\n del_filtered_docs: IDL.Func([IDL.Text, ListParams], [], []),\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([CollectionType, IDL.Text, DelRule], [], []),\n delete_proposal_assets: IDL.Func([DeleteProposalAssets], [], []),\n deposit_cycles: IDL.Func([DepositCyclesArgs], [], []),\n get_asset: IDL.Func([IDL.Text, IDL.Text], [IDL.Opt(AssetNoContent)], []),\n get_auth_config: IDL.Func([], [IDL.Opt(AuthenticationConfig)], []),\n get_config: IDL.Func([], [Config], []),\n get_db_config: IDL.Func([], [IDL.Opt(DbConfig)], []),\n get_doc: IDL.Func([IDL.Text, IDL.Text], [IDL.Opt(Doc)], []),\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 []\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 []\n ),\n get_proposal: IDL.Func([IDL.Nat], [IDL.Opt(Proposal)], []),\n get_rule: IDL.Func([CollectionType, IDL.Text], [IDL.Opt(Rule)], []),\n get_storage_config: IDL.Func([], [StorageConfig], []),\n http_request: IDL.Func([HttpRequest], [HttpResponse], []),\n http_request_streaming_callback: IDL.Func(\n [StreamingCallbackToken],\n [StreamingCallbackHttpResponse],\n []\n ),\n init_asset_upload: IDL.Func([InitAssetKey], [InitUploadResult], []),\n init_proposal: IDL.Func([ProposalType], [IDL.Nat, Proposal], []),\n init_proposal_asset_upload: IDL.Func([InitAssetKey, IDL.Nat], [InitUploadResult], []),\n init_proposal_many_assets_upload: IDL.Func(\n [IDL.Vec(InitAssetKey), IDL.Nat],\n [IDL.Vec(IDL.Tuple(IDL.Text, InitUploadResult))],\n []\n ),\n list_assets: IDL.Func([IDL.Text, ListParams], [ListResults], []),\n list_controllers: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))], []),\n list_custom_domains: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Text, CustomDomain))], []),\n list_docs: IDL.Func([IDL.Text, ListParams], [ListResults_1], []),\n list_proposals: IDL.Func([ListProposalsParams], [ListProposalResults], []),\n list_rules: IDL.Func([CollectionType, ListRulesParams], [ListRulesResults], []),\n memory_size: IDL.Func([], [MemorySize], []),\n reject_proposal: IDL.Func([CommitProposal], [IDL.Null], []),\n set_auth_config: IDL.Func([SetAuthenticationConfig], [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([SetDbConfig], [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([CollectionType, IDL.Text, SetRule], [Rule], []),\n set_storage_config: IDL.Func([SetStorageConfig], [StorageConfig], []),\n submit_proposal: IDL.Func([IDL.Nat], [IDL.Nat, Proposal], []),\n upload_asset_chunk: IDL.Func([UploadChunk], [UploadChunkResult], []),\n upload_proposal_asset_chunk: IDL.Func([UploadChunk], [UploadChunkResult], [])\n });\n};\n// @ts-ignore\nexport const init = ({IDL}) => {\n return [];\n};\n", "// @ts-ignore\nexport const idlFactory = ({IDL}) => {\n const Tokens = IDL.Record({e8s: IDL.Nat64});\n const AssertMissionControlCenterArgs = IDL.Record({\n mission_control_id: IDL.Principal,\n user: IDL.Principal\n });\n const CommitProposal = IDL.Record({\n sha256: IDL.Vec(IDL.Nat8),\n proposal_id: IDL.Nat\n });\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 CreateCanisterArgs = IDL.Record({\n block_index: IDL.Opt(IDL.Nat64),\n subnet_id: IDL.Opt(IDL.Principal),\n user: IDL.Principal\n });\n const DeleteControllersArgs = IDL.Record({\n controllers: IDL.Vec(IDL.Principal)\n });\n const DeleteProposalAssets = IDL.Record({\n proposal_ids: IDL.Vec(IDL.Nat)\n });\n const StorageConfigIFrame = IDL.Variant({\n Deny: IDL.Null,\n AllowAny: IDL.Null,\n SameOrigin: IDL.Null\n });\n const ConfigMaxMemorySize = IDL.Record({\n stable: IDL.Opt(IDL.Nat64),\n heap: IDL.Opt(IDL.Nat64)\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 updated_at: IDL.Opt(IDL.Nat64),\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 created_at: IDL.Opt(IDL.Nat64),\n version: IDL.Opt(IDL.Nat64),\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({storage: StorageConfig});\n const GetCreateCanisterFeeArgs = IDL.Record({user: IDL.Principal});\n const ProposalStatus = IDL.Variant({\n Initialized: IDL.Null,\n Failed: IDL.Null,\n Open: IDL.Null,\n Rejected: IDL.Null,\n Executed: IDL.Null,\n Accepted: IDL.Null\n });\n const AssetsUpgradeOptions = IDL.Record({\n clear_existing_assets: IDL.Opt(IDL.Bool)\n });\n const SegmentsDeploymentOptions = IDL.Record({\n orbiter: IDL.Opt(IDL.Text),\n mission_control_version: IDL.Opt(IDL.Text),\n satellite_version: IDL.Opt(IDL.Text)\n });\n const ProposalType = IDL.Variant({\n AssetsUpgrade: AssetsUpgradeOptions,\n SegmentsDeployment: SegmentsDeploymentOptions\n });\n const Proposal = IDL.Record({\n status: ProposalStatus,\n updated_at: IDL.Nat64,\n sha256: IDL.Opt(IDL.Vec(IDL.Nat8)),\n executed_at: IDL.Opt(IDL.Nat64),\n owner: IDL.Principal,\n created_at: IDL.Nat64,\n version: IDL.Opt(IDL.Nat64),\n proposal_type: ProposalType\n });\n const MissionControl = IDL.Record({\n updated_at: IDL.Nat64,\n credits: Tokens,\n mission_control_id: IDL.Opt(IDL.Principal),\n owner: IDL.Principal,\n created_at: 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 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 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 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 ControllerScope = IDL.Variant({\n Write: IDL.Null,\n Admin: IDL.Null,\n Submit: 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 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 PaymentStatus = IDL.Variant({\n Refunded: IDL.Null,\n Acknowledged: IDL.Null,\n Completed: IDL.Null\n });\n const Payment = IDL.Record({\n status: PaymentStatus,\n updated_at: IDL.Nat64,\n block_index_payment: IDL.Nat64,\n mission_control_id: IDL.Opt(IDL.Principal),\n created_at: IDL.Nat64,\n block_index_refunded: IDL.Opt(IDL.Nat64)\n });\n const ListProposalsOrder = IDL.Record({desc: IDL.Bool});\n const ListProposalsPaginate = IDL.Record({\n start_after: IDL.Opt(IDL.Nat),\n limit: IDL.Opt(IDL.Nat)\n });\n const ListProposalsParams = IDL.Record({\n order: IDL.Opt(ListProposalsOrder),\n paginate: IDL.Opt(ListProposalsPaginate)\n });\n const ProposalKey = IDL.Record({proposal_id: IDL.Nat});\n const ListProposalResults = IDL.Record({\n matches_length: IDL.Nat64,\n items: IDL.Vec(IDL.Tuple(ProposalKey, Proposal)),\n items_length: IDL.Nat64\n });\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 SegmentKind = IDL.Variant({\n Orbiter: IDL.Null,\n MissionControl: IDL.Null,\n Satellite: IDL.Null\n });\n const SetStorageConfig = 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 version: IDL.Opt(IDL.Nat64),\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 RateConfig = IDL.Record({\n max_tokens: IDL.Nat64,\n time_per_token_ns: IDL.Nat64\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 add_credits: IDL.Func([IDL.Principal, Tokens], [], []),\n add_invitation_code: IDL.Func([IDL.Text], [], []),\n assert_mission_control_center: IDL.Func([AssertMissionControlCenterArgs], [], ['query']),\n commit_proposal: IDL.Func([CommitProposal], [IDL.Null], []),\n commit_proposal_asset_upload: IDL.Func([CommitBatch], [], []),\n commit_proposal_many_assets_upload: IDL.Func([IDL.Vec(CommitBatch)], [], []),\n count_proposals: IDL.Func([], [IDL.Nat64], ['query']),\n create_orbiter: IDL.Func([CreateCanisterArgs], [IDL.Principal], []),\n create_satellite: IDL.Func([CreateCanisterArgs], [IDL.Principal], []),\n del_controllers: IDL.Func([DeleteControllersArgs], [], []),\n del_custom_domain: IDL.Func([IDL.Text], [], []),\n delete_proposal_assets: IDL.Func([DeleteProposalAssets], [], []),\n get_config: IDL.Func([], [Config], ['query']),\n get_create_orbiter_fee: IDL.Func([GetCreateCanisterFeeArgs], [IDL.Opt(Tokens)], ['query']),\n get_create_satellite_fee: IDL.Func([GetCreateCanisterFeeArgs], [IDL.Opt(Tokens)], ['query']),\n get_credits: IDL.Func([], [Tokens], ['query']),\n get_proposal: IDL.Func([IDL.Nat], [IDL.Opt(Proposal)], ['query']),\n get_storage_config: IDL.Func([], [StorageConfig], ['query']),\n get_user_mission_control_center: IDL.Func([], [IDL.Opt(MissionControl)], ['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_proposal: IDL.Func([ProposalType], [IDL.Nat, Proposal], []),\n init_proposal_asset_upload: IDL.Func([InitAssetKey, IDL.Nat], [InitUploadResult], []),\n init_proposal_many_assets_upload: IDL.Func(\n [IDL.Vec(InitAssetKey), IDL.Nat],\n [IDL.Vec(IDL.Tuple(IDL.Text, InitUploadResult))],\n []\n ),\n init_user_mission_control_center: IDL.Func([], [MissionControl], []),\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_payments: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Nat64, Payment))], ['query']),\n list_proposals: IDL.Func([ListProposalsParams], [ListProposalResults], ['query']),\n list_user_mission_control_centers: IDL.Func(\n [],\n [IDL.Vec(IDL.Tuple(IDL.Principal, MissionControl))],\n ['query']\n ),\n reject_proposal: IDL.Func([CommitProposal], [IDL.Null], []),\n set_controllers: IDL.Func([SetControllersArgs], [], []),\n set_custom_domain: IDL.Func([IDL.Text, IDL.Opt(IDL.Text)], [], []),\n set_fee: IDL.Func([SegmentKind, Tokens], [], []),\n set_storage_config: IDL.Func([SetStorageConfig], [StorageConfig], []),\n submit_proposal: IDL.Func([IDL.Nat], [IDL.Nat, Proposal], []),\n update_rate_config: IDL.Func([SegmentKind, RateConfig], [], []),\n upload_proposal_asset_chunk: IDL.Func([UploadChunk], [UploadChunkResult], [])\n });\n};\n// @ts-ignore\nexport const init = ({IDL}) => {\n return [];\n};\n", "// @ts-ignore\nexport const idlFactory = ({IDL}) => {\n const Tokens = IDL.Record({e8s: IDL.Nat64});\n const AssertMissionControlCenterArgs = IDL.Record({\n mission_control_id: IDL.Principal,\n user: IDL.Principal\n });\n const CommitProposal = IDL.Record({\n sha256: IDL.Vec(IDL.Nat8),\n proposal_id: IDL.Nat\n });\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 CreateCanisterArgs = IDL.Record({\n block_index: IDL.Opt(IDL.Nat64),\n subnet_id: IDL.Opt(IDL.Principal),\n user: IDL.Principal\n });\n const DeleteControllersArgs = IDL.Record({\n controllers: IDL.Vec(IDL.Principal)\n });\n const DeleteProposalAssets = IDL.Record({\n proposal_ids: IDL.Vec(IDL.Nat)\n });\n const StorageConfigIFrame = IDL.Variant({\n Deny: IDL.Null,\n AllowAny: IDL.Null,\n SameOrigin: IDL.Null\n });\n const ConfigMaxMemorySize = IDL.Record({\n stable: IDL.Opt(IDL.Nat64),\n heap: IDL.Opt(IDL.Nat64)\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 updated_at: IDL.Opt(IDL.Nat64),\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 created_at: IDL.Opt(IDL.Nat64),\n version: IDL.Opt(IDL.Nat64),\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({storage: StorageConfig});\n const GetCreateCanisterFeeArgs = IDL.Record({user: IDL.Principal});\n const ProposalStatus = IDL.Variant({\n Initialized: IDL.Null,\n Failed: IDL.Null,\n Open: IDL.Null,\n Rejected: IDL.Null,\n Executed: IDL.Null,\n Accepted: IDL.Null\n });\n const AssetsUpgradeOptions = IDL.Record({\n clear_existing_assets: IDL.Opt(IDL.Bool)\n });\n const SegmentsDeploymentOptions = IDL.Record({\n orbiter: IDL.Opt(IDL.Text),\n mission_control_version: IDL.Opt(IDL.Text),\n satellite_version: IDL.Opt(IDL.Text)\n });\n const ProposalType = IDL.Variant({\n AssetsUpgrade: AssetsUpgradeOptions,\n SegmentsDeployment: SegmentsDeploymentOptions\n });\n const Proposal = IDL.Record({\n status: ProposalStatus,\n updated_at: IDL.Nat64,\n sha256: IDL.Opt(IDL.Vec(IDL.Nat8)),\n executed_at: IDL.Opt(IDL.Nat64),\n owner: IDL.Principal,\n created_at: IDL.Nat64,\n version: IDL.Opt(IDL.Nat64),\n proposal_type: ProposalType\n });\n const MissionControl = IDL.Record({\n updated_at: IDL.Nat64,\n credits: Tokens,\n mission_control_id: IDL.Opt(IDL.Principal),\n owner: IDL.Principal,\n created_at: 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([], [], [])\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 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 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 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 ControllerScope = IDL.Variant({\n Write: IDL.Null,\n Admin: IDL.Null,\n Submit: 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 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 PaymentStatus = IDL.Variant({\n Refunded: IDL.Null,\n Acknowledged: IDL.Null,\n Completed: IDL.Null\n });\n const Payment = IDL.Record({\n status: PaymentStatus,\n updated_at: IDL.Nat64,\n block_index_payment: IDL.Nat64,\n mission_control_id: IDL.Opt(IDL.Principal),\n created_at: IDL.Nat64,\n block_index_refunded: IDL.Opt(IDL.Nat64)\n });\n const ListProposalsOrder = IDL.Record({desc: IDL.Bool});\n const ListProposalsPaginate = IDL.Record({\n start_after: IDL.Opt(IDL.Nat),\n limit: IDL.Opt(IDL.Nat)\n });\n const ListProposalsParams = IDL.Record({\n order: IDL.Opt(ListProposalsOrder),\n paginate: IDL.Opt(ListProposalsPaginate)\n });\n const ProposalKey = IDL.Record({proposal_id: IDL.Nat});\n const ListProposalResults = IDL.Record({\n matches_length: IDL.Nat64,\n items: IDL.Vec(IDL.Tuple(ProposalKey, Proposal)),\n items_length: IDL.Nat64\n });\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 SegmentKind = IDL.Variant({\n Orbiter: IDL.Null,\n MissionControl: IDL.Null,\n Satellite: IDL.Null\n });\n const SetStorageConfig = 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 version: IDL.Opt(IDL.Nat64),\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 RateConfig = IDL.Record({\n max_tokens: IDL.Nat64,\n time_per_token_ns: IDL.Nat64\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 add_credits: IDL.Func([IDL.Principal, Tokens], [], []),\n add_invitation_code: IDL.Func([IDL.Text], [], []),\n assert_mission_control_center: IDL.Func([AssertMissionControlCenterArgs], [], []),\n commit_proposal: IDL.Func([CommitProposal], [IDL.Null], []),\n commit_proposal_asset_upload: IDL.Func([CommitBatch], [], []),\n commit_proposal_many_assets_upload: IDL.Func([IDL.Vec(CommitBatch)], [], []),\n count_proposals: IDL.Func([], [IDL.Nat64], []),\n create_orbiter: IDL.Func([CreateCanisterArgs], [IDL.Principal], []),\n create_satellite: IDL.Func([CreateCanisterArgs], [IDL.Principal], []),\n del_controllers: IDL.Func([DeleteControllersArgs], [], []),\n del_custom_domain: IDL.Func([IDL.Text], [], []),\n delete_proposal_assets: IDL.Func([DeleteProposalAssets], [], []),\n get_config: IDL.Func([], [Config], []),\n get_create_orbiter_fee: IDL.Func([GetCreateCanisterFeeArgs], [IDL.Opt(Tokens)], []),\n get_create_satellite_fee: IDL.Func([GetCreateCanisterFeeArgs], [IDL.Opt(Tokens)], []),\n get_credits: IDL.Func([], [Tokens], []),\n get_proposal: IDL.Func([IDL.Nat], [IDL.Opt(Proposal)], []),\n get_storage_config: IDL.Func([], [StorageConfig], []),\n get_user_mission_control_center: IDL.Func([], [IDL.Opt(MissionControl)], []),\n http_request: IDL.Func([HttpRequest], [HttpResponse], []),\n http_request_streaming_callback: IDL.Func(\n [StreamingCallbackToken],\n [StreamingCallbackHttpResponse],\n []\n ),\n init_proposal: IDL.Func([ProposalType], [IDL.Nat, Proposal], []),\n init_proposal_asset_upload: IDL.Func([InitAssetKey, IDL.Nat], [InitUploadResult], []),\n init_proposal_many_assets_upload: IDL.Func(\n [IDL.Vec(InitAssetKey), IDL.Nat],\n [IDL.Vec(IDL.Tuple(IDL.Text, InitUploadResult))],\n []\n ),\n init_user_mission_control_center: IDL.Func([], [MissionControl], []),\n list_assets: IDL.Func([IDL.Text, ListParams], [ListResults], []),\n list_controllers: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))], []),\n list_custom_domains: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Text, CustomDomain))], []),\n list_payments: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Nat64, Payment))], []),\n list_proposals: IDL.Func([ListProposalsParams], [ListProposalResults], []),\n list_user_mission_control_centers: IDL.Func(\n [],\n [IDL.Vec(IDL.Tuple(IDL.Principal, MissionControl))],\n []\n ),\n reject_proposal: IDL.Func([CommitProposal], [IDL.Null], []),\n set_controllers: IDL.Func([SetControllersArgs], [], []),\n set_custom_domain: IDL.Func([IDL.Text, IDL.Opt(IDL.Text)], [], []),\n set_fee: IDL.Func([SegmentKind, Tokens], [], []),\n set_storage_config: IDL.Func([SetStorageConfig], [StorageConfig], []),\n submit_proposal: IDL.Func([IDL.Nat], [IDL.Nat, Proposal], []),\n update_rate_config: IDL.Func([SegmentKind, RateConfig], [], []),\n upload_proposal_asset_chunk: IDL.Func([UploadChunk], [UploadChunkResult], [])\n });\n};\n// @ts-ignore\nexport const init = ({IDL}) => {\n return [];\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 CommitProposal = IDL.Record({\n sha256: IDL.Vec(IDL.Nat8),\n proposal_id: 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 Submit: 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 CollectionType = IDL.Variant({Db: IDL.Null, Storage: IDL.Null});\n const DelRule = IDL.Record({version: IDL.Opt(IDL.Nat64)});\n const DeleteProposalAssets = IDL.Record({\n proposal_ids: IDL.Vec(IDL.Nat)\n });\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 external_alternative_origins: IDL.Opt(IDL.Vec(IDL.Text))\n });\n const AuthenticationRules = IDL.Record({\n allowed_callers: IDL.Vec(IDL.Principal)\n });\n const AuthenticationConfig = IDL.Record({\n updated_at: IDL.Opt(IDL.Nat64),\n created_at: IDL.Opt(IDL.Nat64),\n version: IDL.Opt(IDL.Nat64),\n internet_identity: IDL.Opt(AuthenticationConfigInternetIdentity),\n rules: IDL.Opt(AuthenticationRules)\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 updated_at: IDL.Opt(IDL.Nat64),\n created_at: IDL.Opt(IDL.Nat64),\n version: IDL.Opt(IDL.Nat64),\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 updated_at: IDL.Opt(IDL.Nat64),\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 created_at: IDL.Opt(IDL.Nat64),\n version: IDL.Opt(IDL.Nat64),\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 ProposalStatus = IDL.Variant({\n Initialized: IDL.Null,\n Failed: IDL.Null,\n Open: IDL.Null,\n Rejected: IDL.Null,\n Executed: IDL.Null,\n Accepted: IDL.Null\n });\n const AssetsUpgradeOptions = IDL.Record({\n clear_existing_assets: IDL.Opt(IDL.Bool)\n });\n const SegmentsDeploymentOptions = IDL.Record({\n orbiter: IDL.Opt(IDL.Text),\n mission_control_version: IDL.Opt(IDL.Text),\n satellite_version: IDL.Opt(IDL.Text)\n });\n const ProposalType = IDL.Variant({\n AssetsUpgrade: AssetsUpgradeOptions,\n SegmentsDeployment: SegmentsDeploymentOptions\n });\n const Proposal = IDL.Record({\n status: ProposalStatus,\n updated_at: IDL.Nat64,\n sha256: IDL.Opt(IDL.Vec(IDL.Nat8)),\n executed_at: IDL.Opt(IDL.Nat64),\n owner: IDL.Principal,\n created_at: IDL.Nat64,\n version: IDL.Opt(IDL.Nat64),\n proposal_type: ProposalType\n });\n const Memory = IDL.Variant({Heap: IDL.Null, Stable: IDL.Null});\n const Permission = IDL.Variant({\n Controllers: IDL.Null,\n Private: IDL.Null,\n Public: IDL.Null,\n Managed: IDL.Null\n });\n const RateConfig = IDL.Record({\n max_tokens: IDL.Nat64,\n time_per_token_ns: IDL.Nat64\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 rate_config: IDL.Opt(RateConfig),\n write: Permission,\n max_changes_per_user: IDL.Opt(IDL.Nat32)\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 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 ListProposalsOrder = IDL.Record({desc: IDL.Bool});\n const ListProposalsPaginate = IDL.Record({\n start_after: IDL.Opt(IDL.Nat),\n limit: IDL.Opt(IDL.Nat)\n });\n const ListProposalsParams = IDL.Record({\n order: IDL.Opt(ListProposalsOrder),\n paginate: IDL.Opt(ListProposalsPaginate)\n });\n const ProposalKey = IDL.Record({proposal_id: IDL.Nat});\n const ListProposalResults = IDL.Record({\n matches_length: IDL.Nat64,\n items: IDL.Vec(IDL.Tuple(ProposalKey, Proposal)),\n items_length: IDL.Nat64\n });\n const ListRulesMatcher = IDL.Record({include_system: IDL.Bool});\n const ListRulesParams = IDL.Record({matcher: IDL.Opt(ListRulesMatcher)});\n const ListRulesResults = IDL.Record({\n matches_length: IDL.Nat64,\n items: IDL.Vec(IDL.Tuple(IDL.Text, Rule)),\n items_length: IDL.Nat64\n });\n const MemorySize = IDL.Record({stable: IDL.Nat64, heap: IDL.Nat64});\n const SetAuthenticationConfig = IDL.Record({\n version: IDL.Opt(IDL.Nat64),\n internet_identity: IDL.Opt(AuthenticationConfigInternetIdentity),\n rules: IDL.Opt(AuthenticationRules)\n });\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 SetDbConfig = IDL.Record({\n version: IDL.Opt(IDL.Nat64),\n max_memory_size: IDL.Opt(ConfigMaxMemorySize)\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 rate_config: IDL.Opt(RateConfig),\n write: Permission,\n max_changes_per_user: IDL.Opt(IDL.Nat32)\n });\n const SetStorageConfig = 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 version: IDL.Opt(IDL.Nat64),\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 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 commit_asset_upload: IDL.Func([CommitBatch], [], []),\n commit_proposal: IDL.Func([CommitProposal], [IDL.Null], []),\n commit_proposal_asset_upload: IDL.Func([CommitBatch], [], []),\n commit_proposal_many_assets_upload: IDL.Func([IDL.Vec(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 count_proposals: IDL.Func([], [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_filtered_assets: IDL.Func([IDL.Text, ListParams], [], []),\n del_filtered_docs: IDL.Func([IDL.Text, ListParams], [], []),\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([CollectionType, IDL.Text, DelRule], [], []),\n delete_proposal_assets: IDL.Func([DeleteProposalAssets], [], []),\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_proposal: IDL.Func([IDL.Nat], [IDL.Opt(Proposal)], ['query']),\n get_rule: IDL.Func([CollectionType, IDL.Text], [IDL.Opt(Rule)], ['query']),\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 init_proposal: IDL.Func([ProposalType], [IDL.Nat, Proposal], []),\n init_proposal_asset_upload: IDL.Func([InitAssetKey, IDL.Nat], [InitUploadResult], []),\n init_proposal_many_assets_upload: IDL.Func(\n [IDL.Vec(InitAssetKey), IDL.Nat],\n [IDL.Vec(IDL.Tuple(IDL.Text, InitUploadResult))],\n []\n ),\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_proposals: IDL.Func([ListProposalsParams], [ListProposalResults], ['query']),\n list_rules: IDL.Func([CollectionType, ListRulesParams], [ListRulesResults], ['query']),\n memory_size: IDL.Func([], [MemorySize], ['query']),\n reject_proposal: IDL.Func([CommitProposal], [IDL.Null], []),\n set_auth_config: IDL.Func([SetAuthenticationConfig], [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([SetDbConfig], [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([CollectionType, IDL.Text, SetRule], [Rule], []),\n set_storage_config: IDL.Func([SetStorageConfig], [StorageConfig], []),\n submit_proposal: IDL.Func([IDL.Nat], [IDL.Nat, Proposal], []),\n upload_asset_chunk: IDL.Func([UploadChunk], [UploadChunkResult], []),\n upload_proposal_asset_chunk: IDL.Func([UploadChunk], [UploadChunkResult], [])\n });\n};\n// @ts-ignore\nexport const init = ({IDL}) => {\n return [];\n};\n", "import type {HttpAgent} from '@dfinity/agent';\nimport {nonNullish} from '@dfinity/utils';\nimport type {ActorParameters} from '../types/actor';\nimport {createAgent} from '../utils/agent.utils';\n\nexport const useOrInitAgent = async ({agent, ...rest}: ActorParameters): Promise<HttpAgent> =>\n agent ?? (await initAgent(rest));\n\nconst initAgent = async ({\n identity,\n container\n}: Omit<ActorParameters, 'agent'>): Promise<HttpAgent> => {\n const localActor = nonNullish(container) && container !== false;\n\n const host = localActor\n ? container === true\n ? 'http://127.0.0.1:5987'\n : container\n : 'https://icp-api.io';\n\n return await createAgent({\n identity,\n host,\n localActor\n });\n};\n", "import {HttpAgent} from '@dfinity/agent';\nimport type {ActorParameters} from '../types/actor';\n\n// We have this in a utils because we want to mock it for test purposes.\n// Not really happy with that, I welcome better ideas!\nexport const createAgent = async ({\n identity,\n host,\n localActor\n}: Pick<ActorParameters, 'identity'> & {host: string; localActor: boolean}) =>\n await HttpAgent.create({\n identity,\n host,\n retryTimes: 10,\n shouldFetchRootKey: localActor\n });\n", "import {nonNullish} from '@dfinity/utils';\nimport {DOCKER_CONTAINER_URL} from '../constants/container.constants';\nimport {EnvStore} from '../stores/env.store';\nimport type {SatelliteContext} from '../types/satellite';\n\nexport const satelliteUrl = ({\n satelliteId: customSatelliteId,\n container: customContainer\n}: SatelliteContext): 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<SatelliteContext, 'satelliteId'>): Pick<SatelliteContext, 'satelliteId'> =>\n nonNullish(satelliteId)\n ? {satelliteId}\n : (EnvStore.getInstance().get() ?? {satelliteId: undefined});\n\nexport const customOrEnvContainer = ({\n container: customContainer\n}: Pick<SatelliteContext, 'container'>): Pick<SatelliteContext, 'container'> =>\n nonNullish(customContainer)\n ? {container: customContainer}\n : (EnvStore.getInstance().get() ?? {container: undefined});\n", "import type {ActorMethod, ActorSubclass} from '@dfinity/agent';\nimport type {IDL} from '@dfinity/candid';\nimport {assertNonNullish} from '@dfinity/utils';\nimport {\n idlCertifiedFactorySatellite,\n idlFactorySatellite,\n type SatelliteActor\n} from '@junobuild/ic-client/actor';\nimport {ActorStore} from '../stores/actor.store';\nimport type {ActorKey} from '../types/actor';\nimport type {CallOptions} from '../types/call-options';\nimport type {SatelliteContext} from '../types/satellite';\nimport {customOrEnvContainer, customOrEnvSatelliteId} from '../utils/env.utils';\n\nexport const getSatelliteActor = ({\n satellite,\n options: {certified}\n}: {\n satellite: SatelliteContext;\n options: CallOptions;\n}): Promise<SatelliteActor> =>\n getActor({\n idlFactory: certified ? idlCertifiedFactorySatellite : idlFactorySatellite,\n actorKey: `stock#${certified ? 'update' : 'query'}`,\n ...satellite\n });\n\nexport const getSatelliteExtendedActor = <T = Record<string, ActorMethod>>({\n idlFactory,\n ...rest\n}: SatelliteContext & {idlFactory: IDL.InterfaceFactory}): Promise<ActorSubclass<T>> =>\n getActor({\n idlFactory,\n actorKey: 'extended#query',\n ...rest\n });\n\nconst getActor = async <T = Record<string, ActorMethod>>({\n satelliteId: customSatelliteId,\n container: customContainer,\n ...rest\n}: SatelliteContext & {idlFactory: IDL.InterfaceFactory; actorKey: ActorKey}): Promise<\n ActorSubclass<T>\n> => {\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 await ActorStore.getInstance().getActor({\n satelliteId,\n container,\n ...rest\n });\n};\n", "import {Principal} from '@dfinity/principal';\nimport {isNullish, toNullable} from '@dfinity/utils';\nimport type {SatelliteDid} from '@junobuild/ic-client/actor';\nimport {ListError} from '../../auth/types/errors';\nimport type {ListParams, ListTimestampMatcher} from '../types/list';\n\nconst toListMatcherTimestamp = (\n matcher?: ListTimestampMatcher\n): [] | [SatelliteDid.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 ListError('Invalid list matcher for timestamp', matcher);\n }\n};\n\nexport const toListParams = ({\n matcher,\n paginate,\n order,\n owner\n}: ListParams): SatelliteDid.ListParams => ({\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", "import type {SatelliteDid} from '@junobuild/ic-client/actor';\nimport {fromArray} from '@junobuild/utils';\n\nexport const mapData = async <D>({data}: Pick<SatelliteDid.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 {fromNullable, toNullable} from '@dfinity/utils';\nimport type {SatelliteDid} from '@junobuild/ic-client/actor';\nimport {fromArray, toArray} from '@junobuild/utils';\nimport type {ExcludeDate} from '../../core/types/utility';\nimport type {Doc} from '../types/doc';\n\nexport const toSetDoc = async <D>(doc: Doc<D>): Promise<SatelliteDid.SetDoc> => {\n const {data, version, description} = doc;\n\n return {\n description: toNullable(description),\n data: await toArray<ExcludeDate<D>>(data),\n version: toNullable(version)\n };\n};\n\nexport const toDelDoc = <D>(doc: Doc<D>): SatelliteDid.DelDoc => {\n const {version} = doc;\n\n return {\n version: toNullable(version)\n };\n};\n\nexport const fromDoc = async <D>({\n doc,\n key\n}: {\n doc: SatelliteDid.Doc;\n key: string;\n}): 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<ExcludeDate<D>>(data),\n version: fromNullable(version),\n ...rest\n };\n};\n", "import {fromNullable, isNullish, nonNullish} from '@dfinity/utils';\nimport type {SatelliteDid} from '@junobuild/ic-client/actor';\nimport {getSatelliteActor} from '../../core/api/actor.api';\nimport type {ActorReadParams, ActorUpdateParams} from '../../core/types/actor';\nimport type {ListParams, ListResults} from '../../core/types/list';\nimport type {ExcludeDate} from '../../core/types/utility';\nimport {toListParams} from '../../core/utils/list.utils';\nimport type {Doc} from '../types/doc';\nimport {mapData} from '../utils/data.utils';\nimport {fromDoc, toDelDoc, toSetDoc} from '../utils/doc.utils';\n\nexport const getDoc = async <D>({\n collection,\n key,\n ...rest\n}: {\n collection: string;\n} & ActorReadParams &\n Pick<Doc<D>, 'key'>): Promise<Doc<D> | undefined> => {\n const {get_doc} = await getSatelliteActor(rest);\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 ...rest\n}: {\n docs: ({collection: string} & Pick<Doc<any>, 'key'>)[];\n} & ActorReadParams): Promise<(Doc<any> | undefined)[]> => {\n const {get_many_docs} = await getSatelliteActor(rest);\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 ...rest\n}: {\n collection: string;\n doc: Doc<D>;\n} & ActorUpdateParams): Promise<Doc<D>> => {\n const {set_doc} = await getSatelliteActor(rest);\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 ...rest\n}: {\n docs: {collection: string; doc: Doc<any>}[];\n} & ActorUpdateParams): Promise<Doc<any>[]> => {\n const {set_many_docs} = await getSatelliteActor(rest);\n\n const payload: [string, string, SatelliteDid.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 ...rest\n}: {\n collection: string;\n doc: Doc<D>;\n} & ActorUpdateParams): Promise<void> => {\n const {del_doc} = await getSatelliteActor(rest);\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 ...rest\n}: {\n docs: {collection: string; doc: Doc<any>}[];\n} & ActorUpdateParams): Promise<void> => {\n const {del_many_docs} = await getSatelliteActor(rest);\n\n const payload: [string, string, SatelliteDid.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 deleteFilteredDocs = async ({\n collection,\n filter,\n ...rest\n}: {\n collection: string;\n filter: ListParams;\n} & ActorUpdateParams): Promise<void> => {\n const {del_filtered_docs} = await getSatelliteActor(rest);\n\n return del_filtered_docs(collection, toListParams(filter));\n};\n\nexport const listDocs = async <D>({\n collection,\n filter,\n ...rest\n}: {\n collection: string;\n filter: ListParams;\n} & ActorReadParams): Promise<ListResults<Doc<D>>> => {\n const {list_docs} = await getSatelliteActor(rest);\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<ExcludeDate<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 ...rest\n}: {\n collection: string;\n filter: ListParams;\n} & ActorReadParams): Promise<bigint> => {\n const {count_docs} = await getSatelliteActor(rest);\n\n return count_docs(collection, toListParams(filter));\n};\n", "import {DEFAULT_READ_OPTIONS} from '../../core/constants/call-options.constants';\nimport {getAnyIdentity} from '../../core/services/identity.services';\nimport type {ReadOptions} from '../../core/types/call-options';\nimport type {ListParams, ListResults} from '../../core/types/list';\nimport type {SatelliteOptions} from '../../core/types/satellite';\nimport {\n countDocs as countDocsApi,\n deleteDoc as deleteDocApi,\n deleteFilteredDocs as deleteFilteredDocsApi,\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';\n\n/**\n * Retrieves a single document from a collection.\n *\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 {string} params.key - The key of the document to retrieve.\n * @param {ReadOptions} [params.options] - Call options controlling certification. Defaults to uncertified reads for performance unless specified.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\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 options,\n ...rest\n}: {\n collection: string;\n satellite?: SatelliteOptions;\n options?: ReadOptions;\n} & Pick<Doc<D>, 'key'>): Promise<Doc<D> | undefined> => {\n const identity = getAnyIdentity(satellite?.identity);\n\n return await getDocApi({\n ...rest,\n satellite: {...satellite, identity},\n options: options ?? DEFAULT_READ_OPTIONS\n });\n};\n\n/**\n * Retrieves multiple documents from a single or different collections in a single call.\n *\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 {ReadOptions} [params.options] - Call options controlling certification. Defaults to uncertified reads for performance unless specified.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\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 options,\n ...rest\n}: {\n docs: ({collection: string} & Pick<Doc<any>, 'key'>)[];\n satellite?: SatelliteOptions;\n options?: ReadOptions;\n}): Promise<(Doc<any> | undefined)[]> => {\n const identity = getAnyIdentity(satellite?.identity);\n\n return await getManyDocsApi({\n ...rest,\n satellite: {...satellite, identity},\n options: options ?? DEFAULT_READ_OPTIONS\n });\n};\n/* eslint-enable */\n\n/**\n * Adds or updates a single document in a collection.\n *\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 to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\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 = getAnyIdentity(satellite?.identity);\n\n return await setDocApi({\n ...rest,\n satellite: {...satellite, identity},\n options: {certified: true}\n });\n};\n\n/**\n * Adds or updates multiple documents in a or different collections.\n *\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 to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\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 = getAnyIdentity(satellite?.identity);\n\n return await setManyDocsApi({\n ...rest,\n satellite: {...satellite, identity},\n options: {certified: true}\n });\n};\n/* eslint-enable */\n\n/**\n * Deletes a single document from a collection.\n *\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 to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\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 = getAnyIdentity(satellite?.identity);\n\n return await deleteDocApi({\n ...rest,\n satellite: {...satellite, identity},\n options: {certified: true}\n });\n};\n\n/**\n * Deletes multiple documents from a or different collections.\n *\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 to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\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 = getAnyIdentity(satellite?.identity);\n\n return await deleteManyDocsApi({\n ...rest,\n satellite: {...satellite, identity},\n options: {certified: true}\n });\n};\n/* eslint-enable */\n\n/**\n * Deletes documents from a collection with optional filtering.\n *\n * @param {Object} params - The parameters for deleting documents.\n * @param {string} params.collection - The name of the collection.\n * @param {ListParams} [params.filter] - The filter criteria to match documents for deletion.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\n * @returns {Promise<void>} A promise that resolves when the documents are deleted.\n */\nexport const deleteFilteredDocs = async ({\n satellite,\n filter,\n ...rest\n}: {\n collection: string;\n filter?: ListParams;\n satellite?: SatelliteOptions;\n}): Promise<void> => {\n const identity = getAnyIdentity(satellite?.identity);\n\n return await deleteFilteredDocsApi({\n ...rest,\n filter: filter ?? {},\n satellite: {...satellite, identity},\n options: {certified: true}\n });\n};\n\n/**\n * Lists documents in a collection with optional filtering.\n *\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 {ReadOptions} [params.options] - Call options controlling certification. Defaults to uncertified reads for performance unless specified.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\n * @returns {Promise<ListResults<Doc<D>>>} A promise that resolves to the list of documents.\n */\nexport const listDocs = async <D>({\n satellite,\n options,\n filter,\n ...rest\n}: {\n collection: string;\n filter?: ListParams;\n satellite?: SatelliteOptions;\n options?: ReadOptions;\n}): Promise<ListResults<Doc<D>>> => {\n const identity = getAnyIdentity(satellite?.identity);\n\n return await listDocsApi<D>({\n ...rest,\n filter: filter ?? {},\n satellite: {...satellite, identity},\n options: options ?? DEFAULT_READ_OPTIONS\n });\n};\n\n/**\n * Counts documents in a collection with optional filtering.\n *\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 {ReadOptions} [params.options] - Call options controlling certification. Defaults to uncertified reads for performance unless specified.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\n * @returns {Promise<bigint>} A promise that resolves to the count of documents as a bigint.\n */\nexport const countDocs = async ({\n satellite,\n options,\n filter,\n ...rest\n}: {\n collection: string;\n filter?: ListParams;\n satellite?: SatelliteOptions;\n options?: ReadOptions;\n}): Promise<bigint> => {\n const identity = getAnyIdentity(satellite?.identity);\n\n return await countDocsApi({\n ...rest,\n filter: filter ?? {},\n satellite: {...satellite, identity},\n options: options ?? DEFAULT_READ_OPTIONS\n });\n};\n", "import type {Identity} from '@dfinity/agent';\nimport {arrayBufferToUint8Array, nonNullish, uint8ArrayToArrayOfNumber} from '@dfinity/utils';\nimport type {WebAuthnIdentity, WebAuthnNewCredential} from '@junobuild/ic-client/webauthn';\nimport type {Environment} from '../../core/types/env';\nimport {setManyDocs} from '../../datastore/services/doc.services';\nimport type {User} from '../types/user';\n\nexport const createWebAuthnUser = async ({\n delegationIdentity,\n passkeyIdentity,\n satelliteId\n}: {\n delegationIdentity: Identity;\n passkeyIdentity: WebAuthnIdentity<WebAuthnNewCredential>;\n} & Pick<Environment, 'satelliteId'>): Promise<User> => {\n // We serialize the AAGUID as number[] instead of Uint8Array because\n // it results in slightly smaller JSON output with the stringifier.\n // When reading the data, we support both formats.\n const aaguid = passkeyIdentity.getCredential().getAAGUID();\n\n const [user, _] = await setManyDocs({\n docs: [\n {\n collection: '#user',\n doc: {\n key: delegationIdentity.getPrincipal().toText(),\n data: {\n provider: 'webauthn',\n providerData: {\n webauthn: {\n ...(nonNullish(aaguid) && {aaguid: uint8ArrayToArrayOfNumber(aaguid)})\n }\n }\n }\n }\n },\n {\n collection: '#user-webauthn',\n doc: {\n key: passkeyIdentity.getCredential().getCredentialIdText(),\n data: {\n publicKey: arrayBufferToUint8Array(passkeyIdentity.getPublicKey().toDer())\n }\n }\n }\n ],\n satellite: {\n identity: delegationIdentity,\n satelliteId\n }\n });\n\n return user;\n};\n", "import type {CreatePasskeyOptions} from '@junobuild/ic-client/webauthn';\nimport type {SignProgressFn} from './progress';\n\n/**\n * Enum representing the different steps of the WebAuthn sign-in flow.\n */\nexport enum WebAuthnSignInProgressStep {\n /** Requesting a passkey (credential) from the user */\n RequestingUserCredential,\n /** Validating and finalizing the credential provided by the user */\n FinalizingCredential,\n /** Signing the authentication challenge with the user's credential */\n Signing,\n /** Completing the session setup after signing */\n FinalizingSession,\n /** Retrieving the authenticated user information */\n RetrievingUser\n}\n\n/**\n * Enum representing the different steps of the WebAuthn sign-up (registration) flow.\n */\nexport enum WebAuthnSignUpProgressStep {\n /** Creating a new passkey (credential) for the user */\n CreatingUserCredential,\n /** Validating the created credential */\n ValidatingUserCredential,\n /** Finalizing the credential for use */\n FinalizingCredential,\n /** Signing the registration challenge. Requires the user to interact again with the authenticator for confirmation. */\n Signing,\n /** Completing the session setup after signing */\n FinalizingSession,\n /** Registering the new user in the system */\n RegisteringUser\n}\n\n/**\n * Interface representing common sign-in and sing-up options when using a WebAuthn (passkey) based provider.\n * @interface WebAuthnSignOptions\n */\nexport interface WebAuthnSignOptions {\n /**\n * Maximum time to live for the session in milliseconds. Cannot be extended.\n * @type {number}\n */\n maxTimeToLiveInMilliseconds?: number;\n}\n\n/**\n * Interface representing sign-in options when using a WebAuthn (passkey) based provider.\n * @interface WebAuthnSignInOptions\n */\nexport interface WebAuthnSignInOptions extends WebAuthnSignOptions {\n /**\n * Optional callback to receive progress updates about the sign-in flow.\n * Useful for showing UI feedback such as loading indicators or status messages.\n */\n onProgress?: SignProgressFn<WebAuthnSignInProgressStep>;\n}\n\n/**\n * Interface representing sign-up options when using a WebAuthn (passkey) based provider.\n * @interface WebAuthnSignUpSessionOptions\n */\nexport interface WebAuthnSignUpOptions extends WebAuthnSignOptions {\n /**\n * Optional callback to receive progress updates about the sign-up flow.\n * Useful for showing UI feedback such as loading indicators or status messages.\n */\n onProgress?: SignProgressFn<WebAuthnSignUpProgressStep>;\n\n /**\n * Options for creating the passkey credential.\n *\n * For example, you can provide a user-friendly display name so the passkey\n * is easier to recognize later.\n */\n passkey?: CreatePasskeyOptions;\n}\n", "import {type SignIdentity, AnonymousIdentity} from '@dfinity/agent';\nimport {IdbStorage, KEY_STORAGE_DELEGATION, KEY_STORAGE_KEY} from '@dfinity/auth-client';\nimport {\n DelegationChain,\n DelegationIdentity,\n DER_COSE_OID,\n ECDSAKeyIdentity,\n unwrapDER\n} from '@dfinity/identity';\nimport {isNullish, uint8ArrayToBase64} from '@dfinity/utils';\nimport {\n type RetrievePublicKeyFn,\n type WebAuthnNewCredential,\n type WebAuthnSignProgressFn,\n WebAuthnIdentity,\n WebAuthnSignProgressStep\n} from '@junobuild/ic-client/webauthn';\nimport {EnvStore} from '../../core/stores/env.store';\nimport {getDoc} from '../../datastore/services/doc.services';\nimport {DELEGATION_IDENTITY_EXPIRATION_IN_MILLISECONDS} from '../constants/auth.constants';\nimport {execute} from '../helpers/progress.helpers';\nimport {createWebAuthnUser} from '../services/user-webauthn.services';\nimport {SignInInitError, WebAuthnSignInRetrievePublicKeyError} from '../types/errors';\nimport type {Provider} from '../types/provider';\nimport type {User} from '../types/user';\nimport {\n type WebAuthnSignInOptions,\n type WebAuthnSignUpOptions,\n WebAuthnSignInProgressStep,\n WebAuthnSignUpProgressStep\n} from '../types/webauthn';\nimport type {AuthProvider} from './_auth-client.providers';\n\ninterface SessionDelegationIdentity {\n delegationIdentity: DelegationIdentity;\n sessionKey: ECDSAKeyIdentity;\n}\n\nexport class WebAuthnProvider implements AuthProvider {\n /**\n * Gets the identifier of the provider.\n * @returns {Provider} The identifier of the provider is webauthn.\n */\n get id(): Provider {\n return 'webauthn';\n }\n\n /**\n * Signs up a user by creating a new passkey.\n *\n * @param {Object} params - The sign-up parameters.\n * @param {WebAuthnSignUpOptions} [params.options] - Optional configuration for the login request.\n * @param {loadAuth} params.loadAuthWithUser - The function to load the authentication with the user. Provided as a callback to avoid recursive import.\n *\n * @returns {Promise<void>} Resolves if the sign-up is successful.\n */\n async signUp({\n options: {onProgress, maxTimeToLiveInMilliseconds, passkey: passkeyOptions} = {},\n loadAuthWithUser\n }: {\n options?: WebAuthnSignUpOptions;\n loadAuthWithUser: (params: {user: User}) => Promise<void>;\n }) {\n const {satelliteId} = EnvStore.getInstance().get() ?? {satelliteId: undefined};\n\n if (isNullish(satelliteId)) {\n throw new SignInInitError('Satellite ID not set. Have you initialized the Satellite?');\n }\n\n const onSignProgress: WebAuthnSignProgressFn = ({step, state}) => {\n switch (step) {\n case WebAuthnSignProgressStep.RequestingUserCredential:\n onProgress?.({\n step: WebAuthnSignUpProgressStep.ValidatingUserCredential,\n state\n });\n break;\n case WebAuthnSignProgressStep.FinalizingCredential:\n onProgress?.({\n step: WebAuthnSignUpProgressStep.FinalizingCredential,\n state\n });\n break;\n case WebAuthnSignProgressStep.Signing:\n onProgress?.({\n step: WebAuthnSignUpProgressStep.Signing,\n state\n });\n break;\n }\n };\n\n // 1. Create passkey\n const createPasskey = async (): Promise<WebAuthnIdentity<WebAuthnNewCredential>> =>\n await WebAuthnIdentity.createWithNewCredential({\n onProgress: onSignProgress,\n passkeyOptions\n });\n\n const passkeyIdentity = await execute({\n fn: createPasskey,\n step: WebAuthnSignUpProgressStep.CreatingUserCredential,\n onProgress\n });\n\n // 2. Create session delegation. This will require the user the sign the session using their authenticator.\n // i.e. they will have to use their authenticator a second time after create.\n const {delegationIdentity, sessionKey} = await this.#createSessionDelegation({\n identity: passkeyIdentity,\n maxTimeToLiveInMilliseconds\n });\n\n // 3. Make update calls to create user and save public key.\n // Note: We create the user before saving the session identity to avoid\n // a race condition where the user would reload the window and the lib\n // would try to retrieve and undefined user for the delegation saved in indexeddb.\n const register = async () =>\n await createWebAuthnUser({\n delegationIdentity,\n passkeyIdentity,\n satelliteId\n });\n\n const user = await execute({\n fn: register,\n step: WebAuthnSignUpProgressStep.RegisteringUser,\n onProgress\n });\n\n // 4. Save session identity for loading it with auth client\n const saveSession = async () =>\n await this.#saveSessionIdentityForAuthClient({delegationIdentity, sessionKey});\n\n await execute({\n fn: saveSession,\n step: WebAuthnSignUpProgressStep.FinalizingSession,\n onProgress\n });\n\n // 5. Load the user for the authentication\n const loadAuth = async () => await loadAuthWithUser({user});\n\n await execute({\n fn: loadAuth,\n step: WebAuthnSignUpProgressStep.RegisteringUser,\n onProgress\n });\n }\n\n /**\n * Signs in a user with an existing passkey.\n *\n * @param {Object} params - The sign-in parameters.\n * @param {WebAuthnSignInOptions} [params.options] - Optional configuration for the login request.\n * @param {loadAuth} params.loadAuth - The function to load the user. Provided as a callback to avoid recursive import.\n *\n * @returns {Promise<void>} Resolves if the sign-in is successful.\n */\n async signIn({\n options: {onProgress, maxTimeToLiveInMilliseconds} = {},\n loadAuth\n }: {\n options?: WebAuthnSignInOptions;\n loadAuth: () => Promise<void>;\n }) {\n const {satelliteId} = EnvStore.getInstance().get() ?? {satelliteId: undefined};\n\n if (isNullish(satelliteId)) {\n throw new SignInInitError('Satellite ID not set. Have you initialized the Satellite?');\n }\n\n const retrievePublicKey: RetrievePublicKeyFn = async ({credentialId}) => {\n const doc = await getDoc({\n collection: '#user-webauthn',\n key: uint8ArrayToBase64(credentialId),\n options: {\n certified: true\n },\n satellite: {\n identity: new AnonymousIdentity(),\n satelliteId\n }\n });\n\n if (isNullish(doc)) {\n throw new WebAuthnSignInRetrievePublicKeyError(\n 'No public key found for the selected passkey.'\n );\n }\n\n const {data} = doc;\n\n const {publicKey} = data as {publicKey: Uint8Array};\n\n return unwrapDER(publicKey.buffer as ArrayBuffer, DER_COSE_OID);\n };\n\n const onSignProgress: WebAuthnSignProgressFn = ({step, state}) => {\n switch (step) {\n case WebAuthnSignProgressStep.RequestingUserCredential:\n onProgress?.({\n step: WebAuthnSignInProgressStep.RequestingUserCredential,\n state\n });\n break;\n case WebAuthnSignProgressStep.FinalizingCredential:\n onProgress?.({\n step: WebAuthnSignInProgressStep.FinalizingCredential,\n state\n });\n break;\n case WebAuthnSignProgressStep.Signing:\n onProgress?.({\n step: WebAuthnSignInProgressStep.Signing,\n state\n });\n break;\n }\n };\n\n const passkeyIdentity = await WebAuthnIdentity.createWithExistingCredential({\n retrievePublicKey,\n onProgress: onSignProgress\n });\n\n // When the signing of the session occurs, the Identity.sign is triggered\n // which in turns lead to:\n // 1. Get passkey (navigator.credentials.get)\n // 2. Retrieve the public key from the backend\n // 3. Create signature\n const {delegationIdentity, sessionKey} = await this.#createSessionDelegation({\n identity: passkeyIdentity,\n maxTimeToLiveInMilliseconds\n });\n\n // 4. Save session identity for loading it with auth client\n const saveSession = async () =>\n await this.#saveSessionIdentityForAuthClient({delegationIdentity, sessionKey});\n\n await execute({\n fn: saveSession,\n step: WebAuthnSignInProgressStep.FinalizingSession,\n onProgress\n });\n\n // 5. Load the user\n await execute({\n fn: loadAuth,\n step: WebAuthnSignInProgressStep.RetrievingUser,\n onProgress\n });\n }\n\n async #createSessionDelegation({\n identity,\n maxTimeToLiveInMilliseconds\n }: {identity: SignIdentity} & Pick<\n WebAuthnSignInOptions,\n 'maxTimeToLiveInMilliseconds'\n >): Promise<SessionDelegationIdentity> {\n const sessionKey = await ECDSAKeyIdentity.generate({extractable: false});\n\n const sessionLengthInMilliseconds =\n maxTimeToLiveInMilliseconds ?? DELEGATION_IDENTITY_EXPIRATION_IN_MILLISECONDS;\n\n // We do not provide any particular targets. This delegation is meant to work\n // on the Internet Computer with any canister.\n const chain = await DelegationChain.create(\n identity,\n sessionKey.getPublicKey(),\n new Date(Date.now() + sessionLengthInMilliseconds)\n );\n\n const delegationIdentity = DelegationIdentity.fromDelegation(sessionKey, chain);\n\n return {delegationIdentity, sessionKey};\n }\n\n async #saveSessionIdentityForAuthClient({\n sessionKey,\n delegationIdentity\n }: SessionDelegationIdentity) {\n const storage = new IdbStorage();\n\n await Promise.all([\n storage.set(KEY_STORAGE_KEY, sessionKey.getKeyPair()),\n storage.set(\n KEY_STORAGE_DELEGATION,\n JSON.stringify(delegationIdentity.getDelegation().toJSON())\n )\n ]);\n }\n}\n", "import {AuthClient, IdbStorage, KEY_STORAGE_KEY} from '@dfinity/auth-client';\n\nexport const createAuthClient = (): Promise<AuthClient> =>\n AuthClient.create({\n idleOptions: {\n disableIdle: true,\n disableDefaultIdleCallback: true\n }\n });\n\nexport const resetAuthClient = async (): Promise<AuthClient> => {\n // Since AgentJS persists the identity key in IndexedDB by default,\n // it can be tampered with and affect the next login with Internet Identity or NFID.\n // To ensure each session starts clean and safe, we clear the stored keys before creating a new AuthClient\n // in case the user is not authenticated.\n const storage = new IdbStorage();\n await storage.remove(KEY_STORAGE_KEY);\n\n return await createAuthClient();\n};\n", "export const isSatelliteError = ({error, type}: {error: unknown; type: string}): boolean => {\n if (typeof error === 'string') {\n return error.includes(type);\n }\n\n if (error instanceof Error) {\n return error.message.includes(type);\n }\n\n return false;\n};\n", "export const JUNO_CDN_PROPOSALS_ERROR_CANNOT_SUBMIT = 'juno.cdn.proposals.error.cannot_submit';\nexport const JUNO_CDN_PROPOSALS_ERROR_CANNOT_SUBMIT_INVALID_STATUS =\n 'juno.cdn.proposals.error.cannot_submit_invalid_status';\n\nexport const JUNO_CDN_PROPOSALS_ERROR_CANNOT_REJECT = 'juno.cdn.proposals.error.cannot_reject';\nexport const JUNO_CDN_PROPOSALS_ERROR_CANNOT_REJECT_INVALID_STATUS =\n 'juno.cdn.proposals.error.cannot_reject_invalid_status';\n\nexport const JUNO_CDN_PROPOSALS_ERROR_CANNOT_COMMIT = 'juno.cdn.proposals.error.cannot_commit';\nexport const JUNO_CDN_PROPOSALS_ERROR_CANNOT_COMMIT_INVALID_STATUS =\n 'juno.cdn.proposals.error.cannot_commit_invalid_status';\n\nexport const JUNO_CDN_PROPOSALS_ERROR_INVALID_HASH = 'juno.cdn.proposals.error.invalid_hash';\n\nexport const JUNO_CDN_PROPOSALS_ERROR_UNKNOWN_TYPE = 'juno.cdn.proposals.error.unknown_type';\n\nexport const JUNO_CDN_PROPOSALS_ERROR_EMPTY_CONTENT_CHUNKS =\n 'juno.cdn.proposals.error.empty_content_chunks';\nexport const JUNO_CDN_PROPOSALS_ERROR_NOT_CONTENT_CHUNKS_AT_INDEX =\n 'juno.cdn.proposals.error.no_content_chunks_at_index';\n\nexport const JUNO_CDN_PROPOSALS_ERROR_EMPTY_ASSETS = 'juno.cdn.proposals.error.empty_assets';\nexport const JUNO_CDN_PROPOSALS_ERROR_CANNOT_DELETE_ASSETS =\n 'juno.cdn.proposals.error.cannot_delete_assets';\nexport const JUNO_CDN_PROPOSALS_ERROR_CANNOT_DELETE_ASSETS_INVALID_STATUS =\n 'juno.cdn.proposals.error.cannot_delete_assets_invalid_status';\n\nexport const JUNO_CDN_PROPOSALS_ERROR_NEXT_ID_CONVERT = 'juno.cdn.proposals.error.next_id_convert';\nexport const JUNO_CDN_PROPOSALS_ERROR_NEXT_ID_OVERFLOW =\n 'juno.cdn.proposals.error.next_id_overflow';\n\nexport const JUNO_CDN_STORAGE_ERROR_CANNOT_INSERT_ASSET_UNKNOWN_REFERENCE_ID =\n 'juno.cdn.storage.error.cannot_insert_asset_unknown_reference_id';\nexport const JUNO_CDN_STORAGE_ERROR_CANNOT_GET_ASSET_UNKNOWN_REFERENCE_ID =\n 'juno.cdn.storage.error.cannot_get_asset_unknown_reference_id';\nexport const JUNO_CDN_STORAGE_ERROR_CANNOT_INSERT_ASSET_ENCODING_UNKNOWN_REFERENCE_ID =\n 'juno.cdn.storage.error.cannot_insert_asset_encoding_unknown_reference_id';\n\nexport const JUNO_CDN_STORAGE_ERROR_NO_PROPOSAL_FOUND = 'juno.cdn.storage.error.no_proposal_found';\n\nexport const JUNO_CDN_STORAGE_ERROR_INVALID_RELEASES_PATH =\n 'juno.cdn.storage.error.invalid_releases_path';\n\nexport const JUNO_CDN_STORAGE_ERROR_MISSING_RELEASES_DESCRIPTION =\n 'juno.cdn.storage.error.missing_releases_description';\n\nexport const JUNO_CDN_STORAGE_ERROR_INVALID_RELEASES_DESCRIPTION =\n 'juno.cdn.storage.error.invalid_releases_description';\n\nexport const JUNO_CDN_STORAGE_ERROR_INVALID_COLLECTION =\n 'juno.cdn.storage.error.invalid_collection';\n", "export const JUNO_COLLECTIONS_ERROR_MODIFY_RESERVED_COLLECTION =\n 'juno.collections.error.modify_reserved_collection';\nexport const JUNO_COLLECTIONS_ERROR_RESERVED_NAME = 'juno.collections.error.reserved_name';\nexport const JUNO_COLLECTIONS_ERROR_RESERVED_COLLECTION =\n 'juno.collections.error.reserved_collection';\nexport const JUNO_COLLECTIONS_ERROR_RATE_CONFIG_ENABLED =\n 'juno.collections.error.rate_config_enabled';\nexport const JUNO_COLLECTIONS_ERROR_DELETE_PREFIX_RESERVED =\n 'juno.collections.error.prefix_deletion';\nexport const JUNO_COLLECTIONS_ERROR_COLLECTION_NOT_EMPTY = 'juno.collections.error.not_empty';\nexport const JUNO_COLLECTIONS_ERROR_COLLECTION_NOT_FOUND = 'juno.collections.error.not_found';\nexport const JUNO_COLLECTIONS_ERROR_PREFIX_RESERVED = 'juno.collections.error.prefix_reserved';\n", "export const JUNO_ERROR_NO_TIMESTAMP_PROVIDED = 'juno.error.no_timestamp_provided';\nexport const JUNO_ERROR_TIMESTAMP_OUTDATED_OR_FUTURE = 'juno.error.timestamp_outdated_or_future';\nexport const JUNO_ERROR_NO_VERSION_PROVIDED = 'juno.error.no_version_provided';\nexport const JUNO_ERROR_VERSION_OUTDATED_OR_FUTURE = 'juno.error.version_outdated_or_future';\n\nexport const JUNO_DATASTORE_ERROR_CANNOT_WRITE = 'juno.datastore.error.cannot_write';\nexport const JUNO_DATASTORE_ERROR_CANNOT_READ = 'juno.datastore.error.cannot_read';\n\nexport const JUNO_STORAGE_ERROR_UPLOAD_NOT_ALLOWED = 'juno.storage.error.upload_not_allowed';\nexport const JUNO_STORAGE_ERROR_SET_NOT_ALLOWED = 'juno.storage.error.set_not_allowed';\nexport const JUNO_STORAGE_ERROR_CANNOT_COMMIT_INVALID_COLLECTION =\n 'juno.storage.error.cannot_commit_invalid_collection';\nexport const JUNO_STORAGE_ERROR_CANNOT_COMMIT_BATCH = 'juno.storage.error.cannot_commit_batch';\nexport const JUNO_STORAGE_ERROR_ASSET_NOT_FOUND = 'juno.storage.error.asset_not_found';\nexport const JUNO_STORAGE_ERROR_CANNOT_READ_ASSET = 'juno.storage.error.cannot_read_asset';\nexport const JUNO_STORAGE_ERROR_UPLOAD_PATH_COLLECTION_PREFIX =\n 'juno.storage.error.upload_path_collection_prefix';\nexport const JUNO_STORAGE_ERROR_RESERVED_ASSET = 'juno.storage.error.reserved_asset';\nexport const JUNO_STORAGE_ERROR_BATCH_NOT_FOUND = 'juno.storage.error.batch_not_found';\nexport const JUNO_STORAGE_ERROR_CHUNK_NOT_FOUND = 'juno.storage.error.chunk_not_found';\nexport const JUNO_STORAGE_ERROR_CHUNK_NOT_INCLUDED_IN_BATCH =\n 'juno.storage.error.chunk_not_included_in_batch';\nexport const JUNO_STORAGE_ERROR_CHUNK_TO_COMMIT_NOT_FOUND =\n 'juno.storage.error.chunk_to_commit_not_found';\nexport const JUNO_STORAGE_ERROR_ASSET_MAX_ALLOWED_SIZE =\n 'juno.storage.error.asset_max_allowed_size';\n\nexport const JUNO_AUTH_ERROR_NOT_ADMIN_CONTROLLER = 'juno.auth.error.not_admin_controller';\nexport const JUNO_AUTH_ERROR_INVALID_ORIGIN = 'juno.auth.error.invalid_origin';\nexport const JUNO_AUTH_ERROR_NOT_WRITE_CONTROLLER = 'juno.auth.error.not_write_controller';\nexport const JUNO_AUTH_ERROR_NOT_CONTROLLER = 'juno.auth.error.not_controller';\nexport const JUNO_AUTH_ERROR_CALLER_NOT_ALLOWED = 'juno.auth.error.caller.not_allowed';\n\nexport const JUNO_DATASTORE_ERROR_USER_CANNOT_UPDATE = 'juno.datastore.error.user.cannot_update';\nexport const JUNO_DATASTORE_ERROR_USER_INVALID_DATA = 'juno.datastore.error.user.invalid_data';\nexport const JUNO_DATASTORE_ERROR_USER_CALLER_KEY = 'juno.datastore.error.user.caller_key';\nexport const JUNO_DATASTORE_ERROR_USER_KEY_NO_PRINCIPAL =\n 'juno.datastore.error.user.key_no_principal';\nexport const JUNO_DATASTORE_ERROR_USER_NOT_ALLOWED = 'juno.datastore.error.user.not_allowed';\nexport const JUNO_DATASTORE_ERROR_USER_AAGUID_INVALID_LENGTH =\n 'juno.datastore.error.user.webauthn.aaguid_invalid_length';\nexport const JUNO_DATASTORE_ERROR_USER_PROVIDER_INVALID_DATA =\n 'juno.datastore.error.user.webauthn.provider_invalid_data';\nexport const JUNO_DATASTORE_ERROR_USER_PROVIDER_WEBAUTHN_INVALID_DATA =\n 'juno.datastore.error.user.webauthn.provider_webauthn_invalid_data';\n\nexport const JUNO_DATASTORE_ERROR_USER_USAGE_CHANGE_LIMIT_REACHED =\n 'juno.datastore.error.user.usage.change_limit_reached';\nexport const JUNO_DATASTORE_ERROR_USER_USAGE_INVALID_DATA =\n 'juno.datastore.error.user.usage.invalid_data';\n\nexport const JUNO_DATASTORE_ERROR_USER_WEBAUTHN_CANNOT_UPDATE =\n 'juno.datastore.error.user.webauthn.cannot_update';\nexport const JUNO_DATASTORE_ERROR_USER_WEBAUTHN_INVALID_DATA =\n 'juno.datastore.error.user.webauthn.invalid_data';\nexport const JUNO_DATASTORE_ERROR_USER_WEBAUTHN_CALLER_KEY =\n 'juno.datastore.error.user.webauthn.caller_key';\n", "export const JUNO_ERROR_CONTROLLERS_MAX_NUMBER = 'juno.error.controllers.max_number';\nexport const JUNO_ERROR_CONTROLLERS_ANONYMOUS_NOT_ALLOWED =\n 'juno.error.controllers.anonymous_not_allowed';\nexport const JUNO_ERROR_CONTROLLERS_REVOKED_NOT_ALLOWED =\n 'juno.error.controllers.revoked_not_allowed';\n\nexport const JUNO_ERROR_MEMORY_STABLE_EXCEEDED = 'juno.error.memory.stable_exceeded';\nexport const JUNO_ERROR_MEMORY_HEAP_EXCEEDED = 'juno.error.memory.heap_exceeded';\n\nexport const JUNO_ERROR_CYCLES_DEPOSIT_BALANCE_LOW = 'juno.error.cycles.deposit_balance_low';\nexport const JUNO_ERROR_CYCLES_DEPOSIT_FAILED = 'juno.error.cycles.deposit_failed';\n\nexport const JUNO_ERROR_CANISTER_CREATE_FAILED = 'juno.error.canister.create_failed';\nexport const JUNO_ERROR_CANISTER_INSTALL_CODE_FAILED = 'juno.error.canister.install_code_failed';\n\nexport const JUNO_ERROR_SEGMENT_STOP_FAILED = 'juno.error.segment.stop_failed';\nexport const JUNO_ERROR_SEGMENT_DELETE_FAILED = 'juno.error.segment.delete_failed';\n\nexport const JUNO_ERROR_CMC_CALL_LEDGER_FAILED = 'juno.error.cmc.call_ledger_failed';\nexport const JUNO_ERROR_CMC_LEDGER_TRANSFER_FAILED = 'juno.error.cmc.ledger_transfer_failed';\nexport const JUNO_ERROR_CMC_TOP_UP_FAILED = 'juno.error.cmc.top_up_failed';\nexport const JUNO_ERROR_CMC_CALL_CREATE_CANISTER_FAILED =\n 'juno.error.cmc.call_create_canister_failed';\nexport const JUNO_ERROR_CMC_CREATE_CANISTER_FAILED = 'juno.error.cmc.create_canister_failed';\nexport const JUNO_ERROR_CMC_INSTALL_CODE_FAILED = 'juno.error.cmc.install_code_failed';\n\nexport const JUNO_ERROR_INVALID_REGEX = 'juno.error.invalid_regex';\n", "import {isNullish, nonNullish} from '@dfinity/utils';\nimport {isSatelliteError, JUNO_DATASTORE_ERROR_USER_CANNOT_UPDATE} from '@junobuild/errors';\nimport {getDoc, setDoc} from '../../datastore/services/doc.services';\nimport {InitError} from '../types/errors';\nimport type {Provider} from '../types/provider';\nimport type {User, UserData} from '../types/user';\nimport {getIdentity} from './auth.services';\n\ntype UserId = string;\n\nexport const initUser = async ({provider}: {provider: Provider}): Promise<User> => {\n const {user, userId} = await loadUser();\n\n // For returning users we do not need to create a user entry.\n // Sign-in, sign-out, and sign-in again.\n if (nonNullish(user)) {\n return user;\n }\n\n try {\n return await createUser({userId, provider});\n } catch (error: unknown) {\n // It's unlikely, but since updating a user is restricted to the controller,\n // we want to guard against a rare race condition where a user attempts\n // to create a user entry that already exists. In such a case, instead of\n // throwing, we retry loading the user data. If that succeeds, it provides\n // a more graceful UX.\n //\n // With the new flow introduced in core library v2, this scenario should\n // never occur, but the handling remains given it was already implemented\n // with the earlier flow where user creation could happen during init.\n if (isSatelliteError({error, type: JUNO_DATASTORE_ERROR_USER_CANNOT_UPDATE})) {\n const userOnCreateError = await getUser({userId});\n\n if (nonNullish(userOnCreateError)) {\n return userOnCreateError;\n }\n }\n\n throw error;\n }\n};\n\nexport const loadUser = async (): Promise<{userId: UserId; user: User | undefined}> => {\n const identity = getIdentity();\n\n if (isNullish(identity)) {\n throw new InitError('No identity to initialize the user. Have you initialized Juno?');\n }\n\n const userId = identity.getPrincipal().toText();\n\n const user = await getUser({userId});\n\n return {\n userId,\n user\n };\n};\n\nconst getUser = ({userId}: {userId: UserId}): Promise<User | undefined> =>\n getDoc<UserData>({\n collection: `#user`,\n key: userId\n });\n\nconst createUser = ({\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 {isNullish} from '@dfinity/utils';\nimport {ActorStore} from '../../core/stores/actor.store';\nimport {AgentStore} from '../../core/stores/agent.store';\nimport {executeWithWindowGuard} from '../helpers/window.helpers';\nimport {InternetIdentityProvider} from '../providers/internet-identity.providers';\nimport {NFIDProvider} from '../providers/nfid.providers';\nimport {WebAuthnProvider} from '../providers/webauthn.providers';\nimport {AuthStore} from '../stores/auth.store';\nimport type {SignInOptions, SignOutOptions, SignUpOptions} from '../types/auth';\nimport {SignInProviderNotSupportedError, SignUpProviderNotSupportedError} from '../types/errors';\nimport type {Provider} from '../types/provider';\nimport type {User} from '../types/user';\nimport {createAuthClient, resetAuthClient} from '../utils/auth.utils';\nimport {initUser, loadUser} from './_user.services';\n\nlet authClient: AuthClient | undefined | null;\n\n/**\n * Initialize the authClient and load the existing user.\n * Executed when the library is initialized through initSatellite.\n */\nexport const loadAuth = async () => {\n const init = async () => {\n const {user} = await loadUser();\n AuthStore.getInstance().set(user ?? null);\n };\n\n await authenticate({fn: init});\n};\n\n/**\n * Initialize the authClient, load the user passed as parameter.\n * Executed on sign-up.\n */\nconst loadAuthWithUser = async ({user}: {user: User}) => {\n // eslint-disable-next-line require-await\n const init = async () => {\n AuthStore.getInstance().set(user);\n };\n\n await authenticate({fn: init});\n};\n\n/**\n * Initialize the authClient, load or create a new user.\n * Executed on sign-in.\n */\nexport const createAuth = async ({provider}: {provider: Provider}) => {\n const init = async () => {\n const user = await initUser({provider});\n AuthStore.getInstance().set(user);\n };\n\n await authenticate({fn: init});\n};\n\n/**\n * Initializes a new `AuthClient`, checks authentication state,\n * and executes the provided function if already authenticated.\n *\n * - Always creates a fresh `AuthClient` using {@link createAuthClient}.\n * - If the client is **not authenticated**, it resets the client via {@link resetAuthClient}\n * to ensure a clean session.\n * - If authenticated, it runs the given async function `fn`.\n *\n * @param {Object} params\n * @param {() => Promise<void>} params.fn - The asynchronous function to execute when authenticated.\n *\n * @returns {Promise<void>} Resolves when authentication is handled and the provided function is executed (if applicable).\n */\nconst authenticate = async ({fn}: {fn: () => Promise<void>}) => {\n authClient = await createAuthClient();\n\n const isAuthenticated = await authClient.isAuthenticated();\n\n if (!isAuthenticated) {\n authClient = await resetAuthClient();\n return;\n }\n\n await fn();\n};\n\n/**\n * Signs in a user with the specified options.\n *\n * @default Signs in by default with Internet Identity\n * @param {SignInOptions} [options] - The options for signing in including the provider to use for the process.\n * @returns {Promise<void>} A promise that resolves when the sign-in process is complete and the authenticated user is initialized.\n */\nexport const signIn = async (options: SignInOptions): Promise<void> => {\n const fn = async () => await signInWithProvider(options);\n\n const disableWindowGuard = Object.values(options)[0].context?.windowGuard === false;\n\n if (disableWindowGuard) {\n await fn();\n return;\n }\n\n await executeWithWindowGuard({fn});\n};\n\n/**\n * Signs up to create a new user with the specified options.\n *\n * @param {SignUpOptions} [options] - The options for signing up including the provider to use for the process.\n * @returns {Promise<void>} A promise that resolves when the sign-up process is complete and the user is authenticated.\n */\nexport const signUp = async (options: SignUpOptions): Promise<void> => {\n const fn = async () => await signUpWithProvider(options);\n\n const disableWindowGuard = Object.values(options)?.[0].context?.windowGuard === false;\n\n if (disableWindowGuard) {\n await fn();\n return;\n }\n\n await executeWithWindowGuard({fn});\n};\n\nconst signInWithProvider = async (options: SignInOptions): Promise<void> => {\n if ('webauthn' in options) {\n const {\n webauthn: {options: signInOptions}\n } = options;\n\n await new WebAuthnProvider().signIn({\n options: signInOptions,\n loadAuth\n });\n return;\n }\n\n if ('nfid' in options) {\n const {\n nfid: {options: nfidOptions}\n } = options;\n\n const {appName, logoUrl, ...signInOptions} = nfidOptions ?? {};\n\n await new NFIDProvider({appName, logoUrl}).signIn({\n options: signInOptions,\n authClient,\n initAuth: createAuth\n });\n return;\n }\n\n if ('internet_identity' in options) {\n const {\n internet_identity: {options: iiOptions}\n } = options;\n\n const {domain, ...signInOptions} = iiOptions ?? {};\n\n await new InternetIdentityProvider({domain}).signIn({\n options: signInOptions,\n authClient,\n initAuth: createAuth\n });\n return;\n }\n\n throw new SignInProviderNotSupportedError(\n 'An unknown or unsupported provider was provided for sign-in.'\n );\n};\n\nconst signUpWithProvider = async (options: SignUpOptions): Promise<void> => {\n if ('webauthn' in options) {\n const {\n webauthn: {options: signUpOptions}\n } = options;\n\n await new WebAuthnProvider().signUp({\n options: signUpOptions,\n loadAuthWithUser\n });\n return;\n }\n\n throw new SignUpProviderNotSupportedError(\n 'An unknown or unsupported provider was provided for sign-up.'\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 (options?: SignOutOptions): Promise<void> => {\n await resetAuth();\n\n // Recreate an HttpClient immediately because next sign-in, if window is not reloaded, would fail if the agent is created within the process.\n // For example, Safari blocks the Internet Identity (II) window if the agent is created during the interaction.\n // Agent-js must be created either globally or at least before performing a sign-in.\n // We proceed with this reset regardless of the window reloading. This way we ensure it is reset not matter what.\n authClient = await createAuthClient();\n\n if (options?.windowReload === false) {\n return;\n }\n\n window.location.reload();\n};\n\n/**\n * \u2139\uFE0F Exposed for testing purpose only. Should not be leaked to consumer or used by the library.\n */\nexport const resetAuth = async () => {\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 // Technically we do not need this since we recreate the agent below. We just keep it to make the reset explicit.\n authClient = null;\n\n AuthStore.getInstance().reset();\n\n ActorStore.getInstance().reset();\n AgentStore.getInstance().reset();\n};\n\nexport const getIdentity = (): Identity | undefined => authClient?.getIdentity();\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\n/**\n * Returns the current identity if the user is authenticated.\n *\n * \u26A0\uFE0F Use this function imperatively only. Do **not** persist the identity in global state.\n * It is intended for short-lived or one-time operations.\n *\n * Typical use case is to enable developers to implement custom features for the Internet Computer:\n * - Passing the identity to temporarily create an actor or agent to call a canister\n * - Signing a message or making a one-time authenticated call\n *\n * @returns The authenticated identity, or null if unavailable.\n */\nexport const getIdentityOnce = async (): Promise<Identity | null> => {\n const user = AuthStore.getInstance().get();\n\n if (isNullish(user)) {\n return null;\n }\n\n const authenticated = (await authClient?.isAuthenticated()) ?? false;\n\n if (!authenticated) {\n return null;\n }\n\n return authClient?.getIdentity() ?? null;\n};\n", "import {isNullish} from '@dfinity/utils';\nimport type {EnvironmentWorker} from '../../core/types/env';\nimport type {Unsubscribe} from '../../core/types/subscription';\nimport {AuthStore} from '../stores/auth.store';\nimport type {PostMessage, PostMessageDataResponseAuth} from '../types/post-message';\nimport type {User} from '../types/user';\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.\ninterface ImportMeta {\n env: Record<string, string> | undefined;\n}\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", "import type {ActorSubclass} from '@dfinity/agent';\nimport type {ActorMethod} from '@dfinity/agent/lib/esm/actor';\nimport type {IDL} from '@dfinity/candid';\nimport {getSatelliteExtendedActor as getSatelliteExtendedActorApi} from '../../core/api/actor.api';\nimport {getAnyIdentity} from '../../core/services/identity.services';\nimport type {SatelliteOptions} from '../../core/types/satellite';\n\n/**\n * Returns an extended satellite actor instance using the provided IDL factory and satellite options.\n *\n * This function is intended for advanced use cases where developers have implemented\n * custom endpoints in their serverless functions using the extended build type.\n *\n * In most cases, developers should not need to call this directly.\n * Extended actors are typically mapped and handled automatically.\n *\n * @template T - The actor interface type.\n *\n * @param {Object} params - The parameters for creating the actor.\n * @param {IDL.InterfaceFactory} params.idlFactory - The IDL factory defining the custom actor interface.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only.\n * In browser environments, configuration is automatically inherited from `initSatellite()`.\n *\n * @returns {Promise<ActorSubclass<T>>} A promise that resolves to the extended actor instance.\n */\nexport const getSatelliteExtendedActor = async <T = Record<string, ActorMethod>>({\n idlFactory,\n satellite\n}: {\n idlFactory: IDL.InterfaceFactory;\n satellite?: SatelliteOptions;\n}): Promise<ActorSubclass<T>> => {\n const identity = getAnyIdentity(satellite?.identity);\n\n return await getSatelliteExtendedActorApi({\n idlFactory,\n ...satellite,\n identity\n });\n};\n", "import {assertNonNullish, toNullable} from '@dfinity/utils';\nimport type {ConsoleDid, SatelliteDid} from '@junobuild/ic-client/actor';\nimport {isBrowser} from '@junobuild/utils';\nimport {UPLOAD_CHUNK_SIZE} from '../constants/upload.constants';\nimport type {EncodingType} from '../types/storage';\nimport type {UploadAsset, UploadParams, UploadWithProposalParams} from '../types/upload';\n\ntype InitAssetKey = SatelliteDid.InitAssetKey | ConsoleDid.InitAssetKey;\ntype UploadChunk = SatelliteDid.UploadChunk | ConsoleDid.UploadChunk;\ntype CommitBatch = SatelliteDid.CommitBatch | ConsoleDid.CommitBatch;\n\nexport const uploadAsset = async ({\n asset: {data, headers, ...restAsset},\n actor,\n progress\n}: {\n asset: UploadAsset;\n} & UploadParams): Promise<void> => {\n const {init_asset_upload, upload_asset_chunk, commit_asset_upload} = actor;\n\n const {batch_id: batchId} = await init_asset_upload(mapInitAssetUploadParams(restAsset));\n\n progress?.onInitiatedBatch();\n\n const {chunkIds} = await uploadChunks({data, uploadFn: upload_asset_chunk, batchId});\n\n progress?.onUploadedFileChunks(restAsset.fullPath);\n\n await commitAsset({\n commitFn: commit_asset_upload,\n batchId,\n data,\n headers,\n chunkIds\n });\n\n progress?.onCommittedBatch();\n};\n\nexport const uploadAssetWithProposal = async ({\n asset: {data, headers, ...restAsset},\n proposalId,\n actor,\n progress\n}: {\n asset: UploadAsset;\n} & UploadWithProposalParams): Promise<void> => {\n const {init_proposal_asset_upload, upload_proposal_asset_chunk, commit_proposal_asset_upload} =\n actor;\n\n progress?.onInitiatedBatch();\n\n const {batch_id: batchId} = await init_proposal_asset_upload(\n mapInitAssetUploadParams(restAsset),\n proposalId\n );\n\n const {chunkIds} = await uploadChunks({data, uploadFn: upload_proposal_asset_chunk, batchId});\n\n progress?.onUploadedFileChunks(restAsset.fullPath);\n\n await commitAsset({\n commitFn: commit_proposal_asset_upload,\n batchId,\n data,\n headers,\n chunkIds\n });\n\n progress?.onCommittedBatch();\n};\n\nexport const uploadAssetsWithProposal = async ({\n assets,\n proposalId,\n actor,\n progress\n}: {\n assets: UploadAsset[];\n} & UploadWithProposalParams): Promise<void> => {\n const {\n init_proposal_many_assets_upload,\n upload_proposal_asset_chunk,\n commit_proposal_many_assets_upload\n } = actor;\n\n const batchIds = await init_proposal_many_assets_upload(\n assets.map(mapInitAssetUploadParams),\n proposalId\n );\n\n progress?.onInitiatedBatch();\n\n const uploadAssetChunk = async ({\n fullPath,\n data,\n headers\n }: UploadAsset): Promise<BatchToCommit> => {\n const initializedBatch = batchIds.find(([batchIdFullPath]) => batchIdFullPath === fullPath);\n\n assertNonNullish(initializedBatch);\n\n const [_, initUpload] = initializedBatch;\n const {batch_id: batchId} = initUpload;\n\n const {chunkIds} = await uploadChunks({data, uploadFn: upload_proposal_asset_chunk, batchId});\n\n progress?.onUploadedFileChunks(fullPath);\n\n return {\n batchId,\n headers,\n chunkIds,\n data\n };\n };\n\n const batchAndChunkIdsToCommit = await Promise.all(assets.map(uploadAssetChunk));\n\n await commit_proposal_many_assets_upload(batchAndChunkIdsToCommit.map(mapCommitBatch));\n\n progress?.onCommittedBatch();\n};\n\nconst mapInitAssetUploadParams = ({\n filename,\n collection,\n token,\n fullPath,\n encoding,\n description\n}: Omit<UploadAsset, 'headers' | 'data'>): InitAssetKey => ({\n collection,\n full_path: fullPath,\n name: filename,\n token: toNullable<string>(token),\n encoding_type: toNullable<EncodingType>(encoding),\n description: toNullable(description)\n});\n\ntype BatchToCommit = {\n batchId: bigint;\n chunkIds: UploadChunkResult[];\n} & Pick<UploadAsset, 'headers' | 'data'>;\n\nconst mapCommitBatch = ({batchId, chunkIds, headers, data}: BatchToCommit): CommitBatch => {\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 return {\n batch_id: batchId,\n chunk_ids: chunkIds.map(({chunk_id}: UploadChunkResult) => chunk_id),\n headers: [...headers, ...(contentType ?? [])]\n };\n};\n\nconst commitAsset = async ({\n commitFn,\n ...rest\n}: {\n commitFn: (commitBatch: CommitBatch) => Promise<void>;\n batchId: bigint;\n chunkIds: UploadChunkResult[];\n} & Pick<UploadAsset, 'headers' | 'data'>) => {\n const commitBatch = mapCommitBatch(rest);\n await commitFn(commitBatch);\n};\n\nconst uploadChunks = async ({\n data,\n uploadFn,\n batchId\n}: {\n batchId: bigint;\n} & Pick<UploadAsset, 'data'> &\n Pick<UploadChunkParams, 'uploadFn'>): Promise<{chunkIds: UploadChunkResult[]}> => {\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 += UPLOAD_CHUNK_SIZE) {\n const chunk: Blob = clone.slice(start, start + UPLOAD_CHUNK_SIZE);\n\n uploadChunks.push({\n batchId,\n chunk,\n uploadFn,\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 return {chunkIds};\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\ninterface UploadChunkResult {\n chunk_id: bigint;\n}\n\ninterface UploadChunkParams {\n batchId: bigint;\n chunk: Blob;\n uploadFn: (uploadChunk: UploadChunk) => Promise<UploadChunkResult>;\n orderId: bigint;\n}\n\nconst uploadChunk = async ({\n batchId,\n chunk,\n uploadFn,\n orderId\n}: UploadChunkParams): Promise<UploadChunkResult> =>\n uploadFn({\n batch_id: batchId,\n content: new Uint8Array(await chunk.arrayBuffer()),\n order_id: toNullable(orderId)\n });\n", "import {fromNullable} from '@dfinity/utils';\nimport type {SatelliteDid} from '@junobuild/ic-client/actor';\nimport {\n uploadAsset as uploadAssetStorage,\n type AssetKey,\n type UploadAsset\n} from '@junobuild/storage';\nimport {getSatelliteActor} from '../../core/api/actor.api';\nimport type {ActorReadParams, ActorUpdateParams} from '../../core/types/actor';\nimport type {ListParams, ListResults} from '../../core/types/list';\nimport {toListParams} from '../../core/utils/list.utils';\n\nexport const uploadAsset = async ({\n asset,\n ...rest\n}: {asset: UploadAsset} & ActorUpdateParams): Promise<void> => {\n const actor = await getSatelliteActor(rest);\n\n await uploadAssetStorage({\n actor,\n asset\n });\n};\n\nexport const listAssets = async ({\n collection,\n filter,\n ...rest\n}: {\n collection: string;\n filter: ListParams;\n} & ActorReadParams): Promise<ListResults<SatelliteDid.AssetNoContent>> => {\n const {list_assets} = await getSatelliteActor(rest);\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 filter,\n ...rest\n}: {\n collection: string;\n filter: ListParams;\n} & ActorReadParams): Promise<bigint> => {\n const {count_assets} = await getSatelliteActor(rest);\n\n return count_assets(collection, toListParams(filter));\n};\n\nexport const deleteAsset = async ({\n collection,\n fullPath,\n ...rest\n}: {\n collection: string;\n} & ActorUpdateParams &\n Pick<AssetKey, 'fullPath'>): Promise<void> => {\n const actor = await getSatelliteActor(rest);\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} & ActorUpdateParams): Promise<void> => {\n const {del_many_assets} = await getSatelliteActor({satellite, options: {certified: true}});\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 deleteFilteredAssets = async ({\n collection,\n filter,\n ...rest\n}: {\n collection: string;\n filter: ListParams;\n} & ActorUpdateParams): Promise<void> => {\n const {del_filtered_assets} = await getSatelliteActor(rest);\n\n return del_filtered_assets(collection, toListParams(filter));\n};\n\nexport const getAsset = async ({\n collection,\n fullPath,\n ...rest\n}: {\n collection: string;\n} & ActorReadParams &\n Pick<AssetKey, 'fullPath'>): Promise<SatelliteDid.AssetNoContent | undefined> => {\n const {get_asset} = await getSatelliteActor(rest);\n return fromNullable(await get_asset(collection, fullPath));\n};\n\nexport const getManyAssets = async ({\n assets,\n ...rest\n}: {\n assets: ({collection: string} & Pick<AssetKey, 'fullPath'>)[];\n} & ActorReadParams): Promise<(SatelliteDid.AssetNoContent | undefined)[]> => {\n const {get_many_assets} = await getSatelliteActor(rest);\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 {fromNullable, nonNullish} from '@dfinity/utils';\nimport type {SatelliteDid} from '@junobuild/ic-client/actor';\nimport type {Asset, AssetEncoding, AssetKey, Storage} from '@junobuild/storage';\nimport {DEFAULT_READ_OPTIONS} from '../../core/constants/call-options.constants';\nimport {getAnyIdentity} from '../../core/services/identity.services';\nimport type {ReadOptions} from '../../core/types/call-options';\nimport type {ListParams} from '../../core/types/list';\nimport type {SatelliteOptions} from '../../core/types/satellite';\nimport {satelliteUrl} from '../../core/utils/env.utils';\nimport {\n countAssets as countAssetsApi,\n deleteAsset as deleteAssetApi,\n deleteFilteredAssets as deleteFilteredAssetsApi,\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 {Assets} from '../types/storage';\nimport {sha256ToBase64String} from '../utils/crypto.utils';\n\n/**\n * Uploads a blob to the storage.\n *\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\n * @returns {Promise<AssetKey>} A promise that resolves to the asset key.\n */\nexport const uploadBlob = (params: Storage & {satellite?: SatelliteOptions}): Promise<AssetKey> =>\n uploadAssetIC(params);\n\n/**\n * Uploads a file to the storage.\n *\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\n * @returns {Promise<AssetKey>} A promise that resolves to the asset key.\n */\nexport const uploadFile = (\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 = getAnyIdentity(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 asset: {\n data,\n filename,\n collection,\n token,\n headers,\n fullPath,\n encoding,\n description\n },\n satellite,\n options: {certified: true}\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 *\n * @param {Object} params - The parameters for listing the assets.\n * @param {string} params.collection - The name of the collection.\n * @param {ListParams} [params.filter] - The filter parameters.\n * @param {ReadOptions} [params.options] - Call options controlling certification. Defaults to uncertified reads for performance unless specified.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\n * @returns {Promise<Assets>} A promise that resolves to the list of assets.\n */\nexport const listAssets = async ({\n collection,\n filter,\n satellite: satelliteOptions,\n options\n}: {\n collection: string;\n filter?: ListParams;\n satellite?: SatelliteOptions;\n options?: ReadOptions;\n}): Promise<Assets> => {\n const satellite = {...satelliteOptions, identity: getAnyIdentity(satelliteOptions?.identity)};\n\n const {items, ...rest} = await listAssetsApi({\n collection,\n filter: filter ?? {},\n satellite,\n options: options ?? DEFAULT_READ_OPTIONS\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 }: SatelliteDid.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<Record<string, AssetEncoding>>(\n (acc, [type, {modified, sha256, total_length}]) => ({\n ...acc,\n [type]: {\n modified,\n sha256: sha256ToBase64String(sha256),\n total_length\n }\n }),\n {}\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 *\n * @param {Object} params - The parameters for counting the assets.\n * @param {string} params.collection - The name of the collection.\n * @param {ListParams} [params.filter] - The filter parameters for narrowing down the count.\n * @param {ReadOptions} [params.options] - Call options controlling certification. Defaults to uncertified reads for performance unless specified.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\n * @returns {Promise<bigint>} A promise that resolves to the count of assets as a bigint.\n */\nexport const countAssets = async ({\n collection,\n filter,\n satellite: satelliteOptions,\n options\n}: {\n collection: string;\n filter?: ListParams;\n satellite?: SatelliteOptions;\n options?: ReadOptions;\n}): Promise<bigint> => {\n const satellite = {...satelliteOptions, identity: getAnyIdentity(satelliteOptions?.identity)};\n\n return await countAssetsApi({\n collection,\n satellite,\n filter: filter ?? {},\n options: options ?? DEFAULT_READ_OPTIONS\n });\n};\n\n/**\n * Deletes an asset from the storage.\n *\n * @param {Object} params - The parameters for deleting the asset.\n * @param {string} params.collection - The name of the collection.\n * @param {string} params.fullPath - The full path of the asset.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\n * @returns {Promise<void>} A promise that resolves when the asset is deleted.\n */\nexport const deleteAsset = ({\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: getAnyIdentity(satellite?.identity)},\n options: {certified: true}\n });\n\n/**\n * Deletes multiple assets from the storage.\n *\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] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\n * @returns {Promise<void>} A promise that resolves when the assets are deleted.\n */\nexport const deleteManyAssets = ({\n assets,\n satellite\n}: {\n assets: ({collection: string} & Pick<AssetKey, 'fullPath'>)[];\n satellite?: SatelliteOptions;\n}): Promise<void> =>\n deleteManyAssetsApi({\n assets,\n satellite: {...satellite, identity: getAnyIdentity(satellite?.identity)},\n options: {certified: true}\n });\n\n/**\n * Deletes multiple assets from a collection based on filtering criteria.\n *\n * @param {Object} params - The parameters for deleting the assets.\n * @param {string} params.collection - The name of the collection from which to delete assets.\n * @param {ListParams} [params.filter] - The filter criteria to match assets for deletion.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\n * @returns {Promise<void>} A promise that resolves when the assets matching the filter criteria are deleted.\n */\nexport const deleteFilteredAssets = async ({\n collection,\n satellite: satelliteOptions,\n filter\n}: {\n collection: string;\n satellite?: SatelliteOptions;\n filter?: ListParams;\n}): Promise<void> => {\n const satellite = {...satelliteOptions, identity: getAnyIdentity(satelliteOptions?.identity)};\n\n return await deleteFilteredAssetsApi({\n collection,\n satellite,\n filter: filter ?? {},\n options: {certified: true}\n });\n};\n\n/**\n * Retrieves an asset from the storage.\n *\n * @param {Object} params - The parameters for retrieving the asset.\n * @param {string} params.collection - The name of the collection.\n * @param {string} params.fullPath - The full path of the asset.\n * @param {ReadOptions} [params.options] - Call options controlling certification. Defaults to uncertified reads for performance unless specified.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\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 options,\n ...rest\n}: {\n collection: string;\n satellite?: SatelliteOptions;\n options?: ReadOptions;\n} & Pick<AssetKey, 'fullPath'>): Promise<SatelliteDid.AssetNoContent | undefined> => {\n const identity = getAnyIdentity(satellite?.identity);\n\n return await getAssetApi({\n ...rest,\n satellite: {...satellite, identity},\n options: options ?? DEFAULT_READ_OPTIONS\n });\n};\n\n/**\n * Retrieves multiple assets from the storage.\n *\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 {ReadOptions} [params.options] - Call options controlling certification. Defaults to uncertified reads for performance unless specified.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\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 options,\n ...rest\n}: {\n assets: ({collection: string} & Pick<AssetKey, 'fullPath'>)[];\n satellite?: SatelliteOptions;\n options?: ReadOptions;\n}): Promise<(SatelliteDid.AssetNoContent | undefined)[]> => {\n const identity = getAnyIdentity(satellite?.identity);\n\n return await getManyAssetsApi({\n ...rest,\n satellite: {...satellite, identity},\n options: options ?? DEFAULT_READ_OPTIONS\n });\n};\n\n/**\n * Returns a public URL for accessing a specific asset stored on a Satellite.\n *\n * This URL can be used to:\n * - Open the file directly in a browser\n * - Embed the asset in HTML elements like `<img src=\"...\">`, `<video src=\"...\">`, or `<a href=\"...\">`\n * - Programmatically download or display the asset in your application\n *\n * ### Example\n * ```ts\n * const url = downloadUrl({\n * assetKey: {\n * fullPath: '/images/logo.png',\n * }\n * });\n *\n * // Usage in an <img> tag\n * <img src={url} alt=\"Logo\" />\n * ```\n *\n * @param {Object} params - Parameters for generating the URL.\n * @param {Object} params.assetKey - Identifies the asset to generate the URL for.\n * @param {string} params.assetKey.fullPath - The full path of the asset (e.g., `/folder/file.jpg`).\n * @param {string} [params.assetKey.token] - Optional access token for accessing protected assets.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\n * @returns {string} A full URL pointing to the asset.\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: getAnyIdentity(satelliteOptions?.identity)};\n\n return `${satelliteUrl(satellite)}${fullPath}${nonNullish(token) ? `?token=${token}` : ''}`;\n};\n", "import {assertNonNullish} from '@dfinity/utils';\nimport {isWebAuthnAvailable} from '@junobuild/ic-client/webauthn';\nimport type {Asset, AssetEncoding, AssetKey, EncodingType, Storage} from '@junobuild/storage';\nimport {initAuthTimeoutWorker} from './auth/services/auth-timout.services';\nimport {loadAuth} from './auth/services/auth.services';\nimport {AuthStore} from './auth/stores/auth.store';\nimport type {User} from './auth/types/user';\nimport {EnvStore} from './core/stores/env.store';\nimport type {Environment, UserEnvironment} from './core/types/env';\nimport type {Unsubscribe} from './core/types/subscription';\nimport {envContainer, envSatelliteId} from './core/utils/window.env.utils';\nexport * from './auth/providers/internet-identity.providers';\nexport * from './auth/providers/nfid.providers';\nexport {\n getIdentityOnce,\n signIn,\n signOut,\n signUp,\n unsafeIdentity\n} from './auth/services/auth.services';\nexport type * from './auth/types/auth';\nexport * from './auth/types/auth-client';\nexport * from './auth/types/errors';\nexport type * from './auth/types/progress';\nexport type * from './auth/types/provider';\nexport type * from './auth/types/user';\nexport * from './auth/types/webauthn';\nexport type * from './core/types/env';\nexport {ListOrder, ListPaginate, ListParams, ListResults} from './core/types/list';\nexport type * from './core/types/satellite';\nexport type * from './core/types/subscription';\nexport type * from './core/types/utility';\nexport * from './datastore/services/doc.services';\nexport type * from './datastore/types/doc';\nexport * from './functions/services/functions.services';\nexport * from './storage/services/storage.services';\nexport type * from './storage/types/storage';\nexport {isWebAuthnAvailable};\nexport type {Asset, AssetEncoding, AssetKey, EncodingType, 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 * @deprecated Use {@link initSatellite} instead.\n */\nexport const initJuno = (userEnv?: UserEnvironment): Promise<Unsubscribe[]> =>\n initSatellite(userEnv);\n\n/**\n * Initializes a 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 loadAuth();\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 onAuthStateChange = (callback: (authUser: User | null) => void): Unsubscribe =>\n AuthStore.getInstance().subscribe(callback);\n\n/**\n * @deprecated Use {@link onAuthStateChange} instead.\n */\nexport const authSubscribe = onAuthStateChange;\nexport {InternetIdentityConfig, InternetIdentityDomain} from './auth/types/internet-identity';\nexport {NFIDConfig} from './auth/types/nfid';\n"],
5
- "mappings": "8QAAA,IAAAA,GAAAC,GAAAC,IAAA,cAEAA,GAAQ,WAAaC,GACrBD,GAAQ,YAAcE,GACtBF,GAAQ,cAAgBG,GAExB,IAAIC,EAAS,CAAC,EACVC,EAAY,CAAC,EACbC,GAAM,OAAO,WAAe,IAAc,WAAa,MAEvDC,GAAO,mEACX,IAASC,GAAI,EAAGC,GAAMF,GAAK,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C1B,SAAU,CAAC,SAAAH,EAAU,MAAAP,CAAK,EAC1B,UAAWC,CACb,IAE+C,CAC7C,IAAMO,EAAY,CAAC,GAAGP,EAAkB,SAAUI,EAAeJ,GAAkB,QAAQ,CAAC,EAE5F,MAAO,GAAGoC,GAAa7B,CAAS,CAAC,GAAGD,CAAQ,GAAG+B,EAAWtC,CAAK,EAAI,UAAUA,CAAK,GAAK,EAAE,EAC3F,ECnUA,IAAMuC,GAAYC,GAA2C,CAC3D,IAAMC,EAAcD,GAAS,aAAeE,GAAe,EAE3DC,GAAiBF,EAAa,6DAA6D,EAE3F,IAAMG,EAAYJ,GAAS,WAAaK,GAAa,EAErD,MAAO,CACL,YAAAJ,EACA,mBAAoBD,GAAS,mBAC7B,QAASA,GAAS,QAClB,UAAAI,CACF,CACF,EAKaE,GAAYN,GACvBO,GAAcP,CAAO,EAQVO,GAAgB,MAAOP,GAAsD,CACxF,IAAMQ,EAAMT,GAASC,CAAO,EAE5BS,EAAS,YAAY,EAAE,IAAID,CAAG,EAE9B,MAAME,GAAS,EAEf,IAAMC,EACJH,EAAI,SAAS,OAAS,OAAYI,GAAsBJ,EAAI,QAAQ,IAAI,EAAI,OAE9E,MAAO,CAAC,GAAIG,EAAgB,CAACA,CAAa,EAAI,CAAC,CAAE,CACnD,EAOaE,GAAqBC,GAChCC,EAAU,YAAY,EAAE,UAAUD,CAAQ,EAK/BH,GAAgBE",
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", "import { Buffer } from 'buffer/';\nimport {\n Agent,\n getDefaultAgent,\n HttpDetailsResponse,\n QueryResponseRejected,\n QueryResponseStatus,\n ReplicaRejectCode,\n SubmitResponse,\n v2ResponseBody,\n v3ResponseBody,\n} from './agent';\nimport { AgentError } from './errors';\nimport { bufFromBufLike, 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, lookupResultToBuffer } 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 public readonly reject_code: ReplicaRejectCode,\n public readonly reject_message: string,\n public readonly error_code?: string,\n ) {\n super(canisterId, methodName, 'update', {\n 'Request ID': toHex(requestId),\n ...(response.body\n ? {\n ...(error_code\n ? {\n 'Error code': error_code,\n }\n : {}),\n 'Reject code': String(reject_code),\n 'Reject message': 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\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 let reply: ArrayBuffer | undefined;\n let certificate: Certificate | undefined;\n if (response.body && (response.body as v3ResponseBody).certificate) {\n if (agent.rootKey == null) {\n throw new Error('Agent is missing root key');\n }\n const cert = (response.body as v3ResponseBody).certificate;\n certificate = await Certificate.create({\n certificate: bufFromBufLike(cert),\n rootKey: agent.rootKey,\n canisterId: Principal.from(canisterId),\n blsVerify,\n });\n const path = [new TextEncoder().encode('request_status'), requestId];\n const status = new TextDecoder().decode(\n lookupResultToBuffer(certificate.lookup([...path, 'status'])),\n );\n\n switch (status) {\n case 'replied':\n reply = lookupResultToBuffer(certificate.lookup([...path, 'reply']));\n break;\n case 'rejected': {\n // Find rejection details in the certificate\n const rejectCode = new Uint8Array(\n lookupResultToBuffer(certificate.lookup([...path, 'reject_code']))!,\n )[0];\n const rejectMessage = new TextDecoder().decode(\n lookupResultToBuffer(certificate.lookup([...path, 'reject_message']))!,\n );\n const error_code_buf = lookupResultToBuffer(\n certificate.lookup([...path, 'error_code']),\n );\n const error_code = error_code_buf\n ? new TextDecoder().decode(error_code_buf)\n : undefined;\n throw new UpdateCallRejectedError(\n cid,\n methodName,\n requestId,\n response,\n rejectCode,\n rejectMessage,\n error_code,\n );\n }\n }\n } else if (response.body && 'reject_message' in response.body) {\n // handle v2 response errors by throwing an UpdateCallRejectedError object\n const { reject_code, reject_message, error_code } = response.body as v2ResponseBody;\n throw new UpdateCallRejectedError(\n cid,\n methodName,\n requestId,\n response,\n reject_code,\n reject_message,\n error_code,\n );\n }\n\n // Fall back to polling if we receive an Accepted response code\n if (response.status === 202) {\n const pollStrategy = pollingStrategyFactory();\n // Contains the certificate and the reply from the boundary node\n const response = await pollForResponse(agent, ecid, requestId, pollStrategy, blsVerify);\n certificate = response.certificate;\n reply = response.reply;\n }\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 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; target_canister?: unknown }[],\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.target_canister && methodName === \"install_chunked_code\") {\n effectiveCanisterId = Principal.from(first.target_canister);\n }\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 { 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, Expiry, 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';\nimport { defaultStrategy } from './strategy';\nimport { DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS } from '../constants';\nimport { ReadRequestType, ReadStateRequest } from '../agent/http/types';\nexport { defaultStrategy } from './strategy';\nexport type PollStrategy = (\n canisterId: Principal,\n requestId: RequestId,\n status: RequestStatusResponseStatus,\n) => Promise<void>;\nexport type PollStrategyFactory = () => PollStrategy;\n\ninterface SignedReadStateRequestWithExpiry {\n body: {\n content: Pick<ReadStateRequest, 'request_type' | 'ingress_expiry'>;\n };\n}\n\n/**\n * Check if an object has a property\n * @param value the object that might have the property\n * @param property the key of property we're looking for\n */\nfunction hasProperty<O extends object, P extends string>(\n value: O,\n property: P,\n): value is O & Record<P, unknown> {\n return Object.prototype.hasOwnProperty.call(value, property);\n}\n\n/**\n * Check if value is a signed read state request with expiry\n * @param value to check\n */\nfunction isSignedReadStateRequestWithExpiry(\n value: unknown,\n): value is SignedReadStateRequestWithExpiry {\n return (\n value !== null &&\n typeof value === 'object' &&\n hasProperty(value, 'body') &&\n value.body !== null &&\n typeof value.body === 'object' &&\n hasProperty(value.body, 'content') &&\n value.body.content !== null &&\n typeof value.body.content === 'object' &&\n hasProperty(value.body.content, 'request_type') &&\n value.body.content.request_type === ReadRequestType.ReadState &&\n hasProperty(value.body.content, 'ingress_expiry') &&\n typeof value.body.content.ingress_expiry === 'object' &&\n value.body.content.ingress_expiry !== null &&\n hasProperty(value.body.content.ingress_expiry, 'toCBOR') &&\n typeof value.body.content.ingress_expiry.toCBOR === 'function' &&\n hasProperty(value.body.content.ingress_expiry, 'toHash') &&\n typeof value.body.content.ingress_expiry.toHash === 'function'\n );\n}\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 repeated 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 = defaultStrategy(),\n request?: unknown,\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\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, blsVerify);\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_block_height = IDL.Nat32;\n const bitcoin_get_block_headers_args = IDL.Record({\n start_height: bitcoin_block_height,\n end_height: IDL.Opt(bitcoin_block_height),\n network: bitcoin_network,\n });\n const bitcoin_block_header = IDL.Vec(IDL.Nat8);\n const bitcoin_get_block_headers_result = IDL.Record({\n tip_height: bitcoin_block_height,\n block_headers: IDL.Vec(bitcoin_block_header),\n });\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 bitcoin_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: bitcoin_block_height,\n tip_block_hash: bitcoin_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 snapshot_id = IDL.Vec(IDL.Nat8);\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 load_snapshot: IDL.Record({\n canister_version: IDL.Nat64,\n taken_at_timestamp: IDL.Nat64,\n snapshot_id: snapshot_id,\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 allowed_viewers: IDL.Vec(IDL.Principal),\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 delete_canister_snapshot_args = IDL.Record({\n canister_id: canister_id,\n snapshot_id: snapshot_id,\n });\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 list_canister_snapshots_args = IDL.Record({\n canister_id: canister_id,\n });\n const snapshot = IDL.Record({\n id: snapshot_id,\n total_size: IDL.Nat64,\n taken_at_timestamp: IDL.Nat64,\n });\n const list_canister_snapshots_result = IDL.Vec(snapshot);\n const load_canister_snapshot_args = IDL.Record({\n canister_id: canister_id,\n sender_canister_version: IDL.Opt(IDL.Nat64),\n snapshot_id: snapshot_id,\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 schnorr_algorithm = IDL.Variant({\n ed25519: IDL.Null,\n bip340secp256k1: IDL.Null,\n });\n const schnorr_public_key_args = IDL.Record({\n key_id: IDL.Record({\n algorithm: schnorr_algorithm,\n name: IDL.Text,\n }),\n canister_id: IDL.Opt(canister_id),\n derivation_path: IDL.Vec(IDL.Vec(IDL.Nat8)),\n });\n const schnorr_public_key_result = IDL.Record({\n public_key: IDL.Vec(IDL.Nat8),\n chain_code: IDL.Vec(IDL.Nat8),\n });\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 schnorr_aux = IDL.Variant({\n bip341: IDL.Record({ merkle_root_hash: IDL.Vec(IDL.Nat8) }),\n });\n const sign_with_schnorr_args = IDL.Record({\n aux: IDL.Opt(schnorr_aux),\n key_id: IDL.Record({\n algorithm: schnorr_algorithm,\n name: IDL.Text,\n }),\n derivation_path: IDL.Vec(IDL.Vec(IDL.Nat8)),\n message: IDL.Vec(IDL.Nat8),\n });\n const sign_with_schnorr_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 subnet_info_args = IDL.Record({ subnet_id: IDL.Principal });\n const subnet_info_result = IDL.Record({ replica_version: IDL.Text });\n const take_canister_snapshot_args = IDL.Record({\n replace_snapshot: IDL.Opt(snapshot_id),\n canister_id: canister_id,\n });\n const take_canister_snapshot_result = snapshot;\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_block_headers: IDL.Func(\n [bitcoin_get_block_headers_args],\n [bitcoin_get_block_headers_result],\n [],\n ),\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 delete_canister_snapshot: IDL.Func([delete_canister_snapshot_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 list_canister_snapshots: IDL.Func(\n [list_canister_snapshots_args],\n [list_canister_snapshots_result],\n [],\n ),\n load_canister_snapshot: IDL.Func([load_canister_snapshot_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 schnorr_public_key: IDL.Func([schnorr_public_key_args], [schnorr_public_key_result], []),\n sign_with_ecdsa: IDL.Func([sign_with_ecdsa_args], [sign_with_ecdsa_result], []),\n sign_with_schnorr: IDL.Func([sign_with_schnorr_args], [sign_with_schnorr_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 subnet_info: IDL.Func([subnet_info_args], [subnet_info_result], []),\n take_canister_snapshot: IDL.Func(\n [take_canister_snapshot_args],\n [take_canister_snapshot_result],\n [],\n ),\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", "export enum FromStringToTokenError {\n FractionalMoreThan8Decimals,\n InvalidFormat,\n FractionalTooManyDecimals,\n}\n", "export const E8S_PER_TOKEN = BigInt(100000000);\n", "import { E8S_PER_TOKEN } from \"../constants/constants\";\nimport { FromStringToTokenError } from \"../enums/token.enums\";\n\nconst DECIMALS_CONVERSION_SUPPORTED = 8;\n\n/**\n * Receives a string representing a number and returns the big int or error.\n *\n * @param amount - in string format\n * @returns bigint | FromStringToTokenError\n */\nexport const convertStringToE8s = (\n value: string,\n): bigint | FromStringToTokenError => {\n // replace exponential format (1e-4) with plain (0.0001)\n // doesn't support decimals for values >= ~1e16\n let amount = value.includes(\"e\")\n ? Number(value).toLocaleString(\"en\", {\n useGrouping: false,\n maximumFractionDigits: 20,\n })\n : value;\n\n // Remove all instances of \",\" and \"'\".\n amount = amount.trim().replace(/[,']/g, \"\");\n\n // Verify that the string is of the format 1234.5678\n const regexMatch = amount.match(/\\d*(\\.\\d*)?/);\n if (!regexMatch || regexMatch[0] !== amount) {\n return FromStringToTokenError.InvalidFormat;\n }\n\n const [integral, fractional] = amount.split(\".\");\n\n let e8s = BigInt(0);\n\n if (integral) {\n try {\n e8s += BigInt(integral) * E8S_PER_TOKEN;\n } catch {\n return FromStringToTokenError.InvalidFormat;\n }\n }\n\n if (fractional) {\n if (fractional.length > 8) {\n return FromStringToTokenError.FractionalMoreThan8Decimals;\n }\n try {\n e8s += BigInt(fractional.padEnd(8, \"0\"));\n } catch {\n return FromStringToTokenError.InvalidFormat;\n }\n }\n\n return e8s;\n};\n\n/**\n * Receives a string representing a number and returns the big int or error.\n *\n * @param amount - in string format\n * @returns bigint | FromStringToTokenError\n */\nconst convertStringToUlps = ({\n amount,\n decimals,\n}: {\n amount: string;\n decimals: number;\n}): bigint | FromStringToTokenError => {\n // Remove all instances of \",\" and \"'\".\n amount = amount.trim().replace(/[,']/g, \"\");\n\n // Verify that the string is of the format 1234.5678\n const regexMatch = amount.match(/\\d*(\\.\\d*)?/);\n if (!regexMatch || regexMatch[0] !== amount) {\n return FromStringToTokenError.InvalidFormat;\n }\n\n const [integral, fractional] = amount.split(\".\");\n\n let ulps = 0n;\n const ulpsPerToken = 10n ** BigInt(decimals);\n\n if (integral) {\n try {\n ulps += BigInt(integral) * ulpsPerToken;\n } catch {\n return FromStringToTokenError.InvalidFormat;\n }\n }\n\n if (fractional) {\n if (fractional.length > decimals) {\n return FromStringToTokenError.FractionalTooManyDecimals;\n }\n try {\n ulps += BigInt(fractional.padEnd(decimals, \"0\"));\n } catch {\n return FromStringToTokenError.InvalidFormat;\n }\n }\n\n return ulps;\n};\n\nexport interface Token {\n symbol: string;\n name: string;\n decimals: number;\n logo?: string;\n}\n\n// TODO: Remove this token and use the value from ICP ledger\nexport const ICPToken: Token = {\n symbol: \"ICP\",\n name: \"Internet Computer\",\n decimals: 8,\n};\n\n/**\n * Deprecated. Use TokenAmountV2 instead which supports decimals !== 8.\n *\n * Represents an amount of tokens.\n *\n * @param e8s - The amount of tokens in bigint.\n * @param token - The token type.\n */\nexport class TokenAmount {\n private constructor(\n protected e8s: bigint,\n public token: Token,\n ) {\n if (token.decimals !== 8) {\n throw new Error(\"Use TokenAmountV2 for number of decimals other than 8\");\n }\n }\n\n /**\n * Initialize from a bigint. Bigint are considered e8s.\n *\n * @param {amount: bigint; token?: Token;} params\n * @param {bigint} params.amount The amount in bigint format.\n * @param {Token} params.token The token type.\n */\n public static fromE8s({\n amount,\n token,\n }: {\n amount: bigint;\n token: Token;\n }): TokenAmount {\n return new TokenAmount(amount, token);\n }\n\n /**\n * Initialize from a string. Accepted formats:\n *\n * 1234567.8901\n * 1'234'567.8901\n * 1,234,567.8901\n *\n * @param {amount: string; token?: Token;} params\n * @param {string} params.amount The amount in string format.\n * @param {Token} params.token The token type.\n */\n public static fromString({\n amount,\n token,\n }: {\n amount: string;\n token: Token;\n }): TokenAmount | FromStringToTokenError {\n // If parsing the number fails because of the number of decimals, we still\n // want the error to be about the number of decimals and not about the\n // parsing.\n if (token.decimals !== 8) {\n throw new Error(\"Use TokenAmountV2 for number of decimals other than 8\");\n }\n const e8s = convertStringToE8s(amount);\n\n if (typeof e8s === \"bigint\") {\n return new TokenAmount(e8s, token);\n }\n return e8s;\n }\n\n /**\n * Initialize from a number.\n *\n * 1 integer is considered E8S_PER_TOKEN\n *\n * @param {amount: number; token?: Token;} params\n * @param {string} params.amount The amount in number format.\n * @param {Token} params.token The token type.\n */\n public static fromNumber({\n amount,\n token,\n }: {\n amount: number;\n token: Token;\n }): TokenAmount {\n const tokenAmount = TokenAmount.fromString({\n amount: amount.toString(),\n token,\n });\n if (tokenAmount instanceof TokenAmount) {\n return tokenAmount;\n }\n if (tokenAmount === FromStringToTokenError.FractionalMoreThan8Decimals) {\n throw new Error(`Number ${amount} has more than 8 decimals`);\n }\n\n // This should never happen\n throw new Error(`Invalid number ${amount}`);\n }\n\n /**\n *\n * @returns The amount of e8s.\n */\n public toE8s(): bigint {\n return this.e8s;\n }\n}\n\n/**\n * Represents an amount of tokens.\n *\n * @param upls - The amount of tokens in units in the last place. If the token\n * supports N decimals, 10^N ulp = 1 token.\n * @param token - The token type.\n */\nexport class TokenAmountV2 {\n private constructor(\n protected ulps: bigint,\n public token: Token,\n ) {}\n\n /**\n * Initialize from a bigint. Bigint are considered ulps.\n *\n * @param {amount: bigint; token?: Token;} params\n * @param {bigint} params.amount The amount in bigint format.\n * @param {Token} params.token The token type.\n */\n public static fromUlps({\n amount,\n token,\n }: {\n amount: bigint;\n token: Token;\n }): TokenAmountV2 {\n return new TokenAmountV2(amount, token);\n }\n\n /**\n * Initialize from a string. Accepted formats:\n *\n * 1234567.8901\n * 1'234'567.8901\n * 1,234,567.8901\n *\n * @param {amount: string; token?: Token;} params\n * @param {string} params.amount The amount in string format.\n * @param {Token} params.token The token type.\n */\n public static fromString({\n amount,\n token,\n }: {\n amount: string;\n token: Token;\n }): TokenAmountV2 | FromStringToTokenError {\n const ulps = convertStringToUlps({ amount, decimals: token.decimals });\n\n if (typeof ulps === \"bigint\") {\n return new TokenAmountV2(ulps, token);\n }\n return ulps;\n }\n\n /**\n * Initialize from a number.\n *\n * 1 integer is considered 10^{token.decimals} ulps\n *\n * @param {amount: number; token?: Token;} params\n * @param {string} params.amount The amount in number format.\n * @param {Token} params.token The token type.\n */\n public static fromNumber({\n amount,\n token,\n }: {\n amount: number;\n token: Token;\n }): TokenAmountV2 {\n const tokenAmount = TokenAmountV2.fromString({\n amount: amount.toFixed(\n Math.min(DECIMALS_CONVERSION_SUPPORTED, token.decimals),\n ),\n token,\n });\n if (tokenAmount instanceof TokenAmountV2) {\n return tokenAmount;\n }\n if (tokenAmount === FromStringToTokenError.FractionalTooManyDecimals) {\n throw new Error(\n `Number ${amount} has more than ${token.decimals} decimals`,\n );\n }\n\n // This should never happen\n throw new Error(`Invalid number ${amount}`);\n }\n\n /**\n *\n * @returns The amount of ulps.\n */\n public toUlps(): bigint {\n return this.ulps;\n }\n\n /**\n *\n * @returns The amount of ulps in e8s precision\n */\n public toE8s(): bigint {\n if (this.token.decimals < 8) {\n return this.ulps * 10n ** BigInt(8 - this.token.decimals);\n }\n if (this.token.decimals === 8) {\n return this.ulps;\n }\n return this.ulps / 10n ** BigInt(this.token.decimals - 8);\n }\n}\n", "import type { Principal } from \"@dfinity/principal\";\nimport type { QueryParams } from \"../types/query.params\";\n\nexport abstract class Canister<T> {\n protected constructor(\n private readonly id: Principal,\n protected readonly service: T,\n protected readonly certifiedService: T,\n ) {}\n\n get canisterId(): Principal {\n return this.id;\n }\n\n protected caller = ({ certified = true }: QueryParams): T =>\n certified ? this.certifiedService : this.service;\n}\n", "/**\n * Checks if a given argument is null or undefined.\n *\n * @template T - The type of the argument.\n * @param {T | undefined | null} argument - The argument to check.\n * @returns {argument is undefined | null} `true` if the argument is null or undefined; otherwise, `false`.\n */\nexport const isNullish = <T>(\n argument: T | undefined | null,\n): argument is undefined | null => argument === null || argument === undefined;\n\n/**\n * Checks if a given argument is neither null nor undefined.\n *\n * @template T - The type of the argument.\n * @param {T | undefined | null} argument - The argument to check.\n * @returns {argument is NonNullable<T>} `true` if the argument is not null or undefined; otherwise, `false`.\n */\nexport const nonNullish = <T>(\n argument: T | undefined | null,\n): argument is NonNullable<T> => !isNullish(argument);\n\n/**\n * Checks if a given value is not null, not undefined, and not an empty string.\n *\n * @param {string | undefined | null} value - The value to check.\n * @returns {boolean} `true` if the value is not null, not undefined, and not an empty string; otherwise, `false`.\n */\nexport const notEmptyString = (\n value: string | undefined | null,\n): value is string => nonNullish(value) && value !== \"\";\n\n/**\n * Checks if a given value is null, undefined, or an empty string.\n *\n * @param {string | undefined | null} value - The value to check.\n * @returns {value is undefined | null | \"\"} Type predicate indicating if the value is null, undefined, or an empty string.\n */\nexport const isEmptyString = (\n value: string | undefined | null,\n): value is undefined | null | \"\" => !notEmptyString(value);\n", "import type { QueryAndUpdateParams } from \"../types/query-and-update.params\";\nimport { isNullish } from \"../utils/nullish.utils\";\n\n/**\n * This service performs a query (not-certified) call and/or an update (certified) call, and handles the results.\n *\n * It is useful because it can do both type of calls for security reasons.\n * For example, malicious nodes can forge transactions and balance when calling an Index canister, if no update is performed to certify the results.\n *\n * Furthermore, it can handle the results of the calls in different ways:\n * - `query` only performs a query call.\n * - `update` only performs an update call.\n * - `query_and_update` performs both calls.\n *\n * The resolution can be:\n * - `all_settled` waits for all calls to settle.\n * - `race` waits for the first call to settle (typically, `query` is the fastest one).\n *\n * Once the call(s) are done, the response is handled by the `onLoad` callback.\n * However, if an error occurs, it is handled by the error callbacks, if provided: one for the query call and one for the update call.\n *\n * @param {QueryAndUpdateParams<R, E>} params The parameters to perform the request.\n * @param {QueryAndUpdateRequest<R>} params.request The request to perform.\n * @param {QueryAndUpdateOnResponse<R>} params.onLoad The callback to handle the response of the request.\n * @param {QueryAndUpdateOnQueryError<E>} [params.onQueryError] The callback to handle the error of the `query` request.\n * @param {QueryAndUpdateOnUpdateError<E>} [params.onUpdateError] The callback to handle the error of the `update` request.\n * @param {QueryAndUpdateStrategy} [params.strategy=\"query_and_update\"] The strategy to use. Default is `query_and_update`.\n * @param {QueryAndUpdateIdentity} params.identity The identity to use for the request.\n * @param {QueryAndUpdatePromiseResolution} [params.resolution=\"race\"] The resolution to use. Default is `race`.\n *\n * @template R The type of the response.\n * @template E The type of the error.\n *\n * @returns A promise that resolves when the request is done.\n */\nexport const queryAndUpdate = async <R, E = unknown>({\n request,\n onLoad,\n onQueryError,\n onUpdateError,\n strategy = \"query_and_update\",\n identity,\n resolution = \"race\",\n}: QueryAndUpdateParams<R, E>): Promise<void> => {\n let certifiedDone = false;\n\n const queryOrUpdate = (certified: boolean) =>\n request({ certified, identity })\n .then((response) => {\n if (certifiedDone) {\n return;\n }\n\n onLoad({ certified, response });\n })\n .catch((error: E) => {\n if (!certified) {\n onQueryError?.({ error, identity });\n }\n\n if (certifiedDone) {\n return;\n }\n\n if (isNullish(onUpdateError)) {\n return;\n }\n\n console.error(error);\n\n if (!certified) {\n return;\n }\n\n onUpdateError({ error, identity });\n })\n .finally(() => (certifiedDone = certifiedDone || certified));\n\n const requests: Array<Promise<void>> =\n strategy === \"query\"\n ? [queryOrUpdate(false)]\n : strategy === \"update\"\n ? [queryOrUpdate(true)]\n : [queryOrUpdate(false), queryOrUpdate(true)];\n\n await (resolution === \"all_settled\"\n ? Promise.allSettled(requests)\n : Promise.race(requests));\n};\n", "import {\n Actor,\n type ActorConfig,\n type ActorSubclass,\n type Agent,\n} from \"@dfinity/agent\";\nimport type { IDL } from \"@dfinity/candid\";\nimport type { Principal } from \"@dfinity/principal\";\nimport type { CanisterOptions } from \"../types/canister.options\";\nimport { defaultAgent } from \"./agent.utils\";\n\ntype RequiredCanisterOptions<T> = Required<\n Pick<CanisterOptions<T>, \"canisterId\">\n> &\n Omit<CanisterOptions<T>, \"canisterId\">;\n\nexport const createServices = <T>({\n options: {\n canisterId,\n serviceOverride,\n certifiedServiceOverride,\n agent: agentOption,\n callTransform,\n queryTransform,\n },\n idlFactory,\n certifiedIdlFactory,\n}: {\n options: RequiredCanisterOptions<T> &\n Pick<ActorConfig, \"queryTransform\" | \"callTransform\">;\n idlFactory: IDL.InterfaceFactory;\n certifiedIdlFactory: IDL.InterfaceFactory;\n}): {\n service: ActorSubclass<T>;\n certifiedService: ActorSubclass<T>;\n agent: Agent;\n canisterId: Principal;\n} => {\n const agent: Agent = agentOption ?? defaultAgent();\n\n const service: ActorSubclass<T> =\n serviceOverride ??\n Actor.createActor<T>(idlFactory, {\n agent,\n canisterId,\n callTransform,\n queryTransform,\n });\n\n const certifiedService: ActorSubclass<T> =\n certifiedServiceOverride ??\n Actor.createActor<T>(certifiedIdlFactory, {\n agent,\n canisterId,\n callTransform,\n queryTransform,\n });\n\n return { service, certifiedService, agent, canisterId };\n};\n", "import {\n AnonymousIdentity,\n HttpAgent,\n type Agent,\n type Identity,\n} from \"@dfinity/agent\";\nimport type { CreateAgentParams } from \"../types/agent.utils\";\nimport { isNullish, nonNullish } from \"./nullish.utils\";\n\n/**\n * Get a default agent that connects to mainnet with the anonymous identity.\n * @returns The default agent to use\n */\nexport const defaultAgent = (): Agent =>\n HttpAgent.createSync({\n host: \"https://icp-api.io\",\n identity: new AnonymousIdentity(),\n });\n\n/**\n * Create an agent for a given identity\n *\n * @param {CreateAgentParams} params The parameters to create a new HTTP agent\n * @param {Identity} params.identity A mandatory identity to use for the agent\n * @param {string} params.host An optional host to connect to, particularly useful for local development\n * @param {boolean} params.fetchRootKey Fetch root key for certificate validation during local development or on testnet\n * @param {boolean} params.verifyQuerySignatures Check for signatures in the state tree signed by the node that replies to queries - i.e. certify responses.\n * @param {number} params.retryTimes Set the number of retries the agent should perform before error.\n */\nexport const createAgent = async ({\n identity,\n host,\n fetchRootKey = false,\n verifyQuerySignatures = false,\n retryTimes,\n}: CreateAgentParams): Promise<HttpAgent> =>\n await HttpAgent.create({\n identity,\n ...(nonNullish(host) && { host }),\n verifyQuerySignatures,\n ...(nonNullish(retryTimes) && { retryTimes }),\n shouldFetchRootKey: fetchRootKey,\n });\n\nexport type AgentManagerConfig = Pick<\n CreateAgentParams,\n \"fetchRootKey\" | \"host\"\n>;\n\n/**\n * AgentManager class manages HttpAgent instances for different identities.\n *\n * It caches agents by identity to optimise resource usage and avoid unnecessary agent creation.\n * Provides functionality to create new agents, retrieve cached agents, and clear the cache when needed.\n */\nexport class AgentManager {\n private agents: Record<string, HttpAgent> | undefined | null = undefined;\n\n private constructor(private readonly config: AgentManagerConfig) {}\n\n /**\n * Static factory method to create a new AgentManager instance.\n *\n * This method serves as an alternative to directly using the private constructor,\n * making it more convenient to create instances of `AgentManager` using a simple and clear method.\n *\n * @param {AgentManagerConfig} config - Configuration options for the AgentManager instance.\n * @param {boolean} config.fetchRootKey - Whether to fetch the root key for certificate validation.\n * @param {string} config.host - The host to connect to.\n * @returns {AgentManager} A new instance of `AgentManager`.\n */\n public static create(config: AgentManagerConfig): AgentManager {\n return new AgentManager(config);\n }\n\n /**\n * Get or create an HTTP agent for a given identity.\n *\n * If the agent for the specified identity has been created and cached, it is retrieved from the cache.\n * If no agent exists for the identity, a new one is created, cached, and then returned.\n *\n * @param {Identity} identity - The identity to be used to create the agent.\n * @returns {Promise<HttpAgent>} The HttpAgent associated with the given identity.\n */\n public getAgent = async ({\n identity,\n }: {\n identity: Identity;\n }): Promise<HttpAgent> => {\n const key = identity.getPrincipal().toText();\n\n if (isNullish(this.agents) || isNullish(this.agents[key])) {\n const agent = await createAgent({\n identity,\n fetchRootKey: this.config.fetchRootKey,\n host: this.config.host,\n verifyQuerySignatures: true,\n });\n\n this.agents = {\n ...(this.agents ?? {}),\n [key]: agent,\n };\n\n return agent;\n }\n\n return this.agents[key];\n };\n\n /**\n * Clear the cache of HTTP agents.\n *\n * This method removes all cached agents, forcing new agent creation on the next request for any identity.\n * Useful when identities have changed or if you want to reset all active connections.\n */\n public clearAgents = (): void => {\n this.agents = null;\n };\n}\n", "export class InvalidPercentageError extends Error {}\nexport class NullishError extends Error {}\n\nexport const assertNonNullish: <T>(\n value: T,\n message?: string,\n // eslint-disable-next-line local-rules/prefer-object-params\n) => asserts value is NonNullable<T> = <T>(\n value: T,\n message?: string,\n): void => {\n if (value === null || value === undefined) {\n throw new NullishError(message);\n }\n};\n\n// eslint-disable-next-line local-rules/prefer-object-params\nexport const asNonNullish = <T>(value: T, message?: string): NonNullable<T> => {\n assertNonNullish(value, message);\n return value;\n};\n\nexport const assertPercentageNumber = (percentage: number) => {\n if (percentage < 0 || percentage > 100) {\n throw new InvalidPercentageError(\n `${percentage} is not a valid percentage number.`,\n );\n }\n};\n", "import { assertNonNullish } from \"./asserts.utils\";\n\nexport const uint8ArrayToBigInt = (array: Uint8Array): bigint => {\n const view = new DataView(array.buffer, array.byteOffset, array.byteLength);\n if (typeof view.getBigUint64 === \"function\") {\n return view.getBigUint64(0);\n }\n const high = BigInt(view.getUint32(0));\n const low = BigInt(view.getUint32(4));\n\n return (high << BigInt(32)) + low;\n};\n\nexport const bigIntToUint8Array = (value: bigint): Uint8Array => {\n const buffer = new ArrayBuffer(8);\n const view = new DataView(buffer);\n if (typeof view.setBigUint64 === \"function\") {\n view.setBigUint64(0, value);\n } else {\n const high = Number(value >> BigInt(32));\n const low = Number(value & BigInt(0xffffffff));\n\n view.setUint32(0, high);\n view.setUint32(4, low);\n }\n\n return new Uint8Array(buffer);\n};\n\nexport const numberToUint8Array = (value: number): Uint8Array => {\n const view = new DataView(new ArrayBuffer(8));\n for (let index = 7; index >= 0; --index) {\n view.setUint8(index, value % 256);\n value = value >> 8;\n }\n return new Uint8Array(view.buffer);\n};\n\nexport const arrayBufferToUint8Array = (buffer: ArrayBuffer): Uint8Array =>\n new Uint8Array(buffer);\n\nexport const uint8ArrayToArrayOfNumber = (array: Uint8Array): Array<number> =>\n Array.from(array);\n\nexport const arrayOfNumberToUint8Array = (numbers: Array<number>): Uint8Array =>\n new Uint8Array(numbers);\n\nexport const asciiStringToByteArray = (text: string): Array<number> =>\n Array.from(text).map((c) => c.charCodeAt(0));\n\nexport const hexStringToUint8Array = (hexString: string): Uint8Array => {\n const matches = hexString.match(/.{1,2}/g);\n\n assertNonNullish(matches, \"Invalid hex string.\");\n\n return Uint8Array.from(matches.map((byte) => parseInt(byte, 16)));\n};\n\n/**\n * Compare two Uint8Arrays for byte-level equality.\n *\n * @param {Object} params\n * @param {Uint8Array} params.a - First Uint8Array to compare.\n * @param {Uint8Array} params.b - Second Uint8Array to compare.\n * @returns {boolean} True if both arrays have the same length and identical contents.\n */\nexport const uint8ArraysEqual = ({ a, b }: { a: Uint8Array; b: Uint8Array }) =>\n a.length === b.length && a.every((byte, i) => byte === b[i]);\n\nexport const uint8ArrayToHexString = (bytes: Uint8Array | number[]) => {\n if (!(bytes instanceof Uint8Array)) {\n bytes = Uint8Array.from(bytes);\n }\n return bytes.reduce(\n (str, byte) => str + byte.toString(16).padStart(2, \"0\"),\n \"\",\n );\n};\n\nexport const candidNumberArrayToBigInt = (array: number[]): bigint => {\n let result = 0n;\n for (let i = array.length - 1; i >= 0; i--) {\n result = (result << 32n) + BigInt(array[i]);\n }\n return result;\n};\n", "import { assertNonNullish } from \"./asserts.utils\";\n\nconst ALPHABET = \"abcdefghijklmnopqrstuvwxyz234567\";\n\n// Build a lookup table for decoding.\nconst LOOKUP_TABLE: Record<string, number> = Object.create(null);\nfor (let i = 0; i < ALPHABET.length; i++) {\n LOOKUP_TABLE[ALPHABET[i]] = i;\n}\n\n// Add aliases for rfc4648.\nLOOKUP_TABLE[\"0\"] = LOOKUP_TABLE.o;\nLOOKUP_TABLE[\"1\"] = LOOKUP_TABLE.i;\n\n/**\n * Encode an Uint8Array to a base32 string.\n *\n * @param input The input array to encode.\n * @returns A Base32 string encoding the input.\n */\nexport const encodeBase32 = (input: Uint8Array): string => {\n // How many bits will we skip from the first byte.\n let skip = 0;\n // 5 high bits, carry from one byte to the next.\n let bits = 0;\n\n // The output string in base32.\n let output = \"\";\n\n const encodeByte = (byte: number): number => {\n if (skip < 0) {\n // we have a carry from the previous byte\n bits |= byte >> -skip;\n } else {\n // no carry\n bits = (byte << skip) & 248;\n }\n\n if (skip > 3) {\n // Not enough data to produce a character, get us another one\n skip -= 8;\n return 1;\n }\n\n if (skip < 4) {\n // produce a character\n output += ALPHABET[bits >> 3];\n skip += 5;\n }\n\n return 0;\n };\n\n for (let i = 0; i < input.length; ) {\n i += encodeByte(input[i]);\n }\n\n return output + (skip < 0 ? ALPHABET[bits >> 3] : \"\");\n};\n\n/**\n * Decode a base32 string to Uint8Array.\n *\n * @param input The input string to decode.\n * @param input The base32 encoded string to decode.\n */\nexport const decodeBase32 = (input: string): Uint8Array => {\n // how many bits we have from the previous character.\n let skip = 0;\n // current byte we're producing.\n let byte = 0;\n\n const output = new Uint8Array(((input.length * 4) / 3) | 0);\n let o = 0;\n\n const decodeChar = (char: string) => {\n // Consume a character from the stream, store\n // the output in this.output. As before, better\n // to use update().\n let val = LOOKUP_TABLE[char.toLowerCase()];\n assertNonNullish(val, `Invalid character: ${JSON.stringify(char)}`);\n\n // move to the high bits\n val <<= 3;\n byte |= val >>> skip;\n skip += 5;\n\n if (skip >= 8) {\n // We have enough bytes to produce an output\n output[o++] = byte;\n skip -= 8;\n\n if (skip > 0) {\n byte = (val << (5 - skip)) & 255;\n } else {\n byte = 0;\n }\n }\n };\n\n for (const c of input) {\n decodeChar(c);\n }\n\n return output.slice(0, o);\n};\n", "/**\n * Converts a Uint8Array (binary data) to a base64 encoded string.\n *\n * @param {Uint8Array} uint8Array - The Uint8Array containing binary data to be encoded.\n * @returns {string} - The base64 encoded string representation of the binary data.\n */\nexport const uint8ArrayToBase64 = (uint8Array: Uint8Array): string =>\n btoa(String.fromCharCode(...new Uint8Array(uint8Array)));\n\n/**\n * Converts a base64 encoded string to a Uint8Array (binary data).\n *\n * @param {string} base64String - The base64 encoded string to be decoded.\n * @returns {Uint8Array} - The Uint8Array representation of the decoded binary data.\n */\nexport const base64ToUint8Array = (base64String: string): Uint8Array =>\n Uint8Array.from(atob(base64String), (c) => c.charCodeAt(0));\n", "// This file is translated to JavaScript from\n// https://lxp32.github.io/docs/a-simple-example-crc32-calculation/\nconst lookUpTable: Uint32Array = new Uint32Array([\n 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,\n 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,\n 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,\n 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,\n 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,\n 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,\n 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,\n 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,\n 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,\n 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,\n 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,\n 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,\n 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,\n 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,\n 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,\n 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,\n 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,\n 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,\n 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,\n 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,\n 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,\n 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,\n 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,\n 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,\n 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,\n 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,\n 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,\n 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,\n 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,\n 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,\n 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,\n 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,\n 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,\n 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,\n 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,\n 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,\n 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,\n 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,\n 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,\n 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,\n 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,\n 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,\n 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,\n]);\n\nconst crc32 = (bytes: Uint8Array): number => {\n let crc = -1;\n\n for (let i = 0; i < bytes.length; i++) {\n const byte = bytes[i];\n const t = (byte ^ crc) & 0xff;\n crc = lookUpTable[t] ^ (crc >>> 8);\n }\n\n return (crc ^ -1) >>> 0;\n};\n\nexport const bigEndianCrc32 = (bytes: Uint8Array): Uint8Array => {\n const checksumArrayBuf = new ArrayBuffer(4);\n const view = new DataView(checksumArrayBuf);\n view.setUint32(0, crc32(bytes), false);\n return new Uint8Array(checksumArrayBuf);\n};\n", "import { Principal } from \"@dfinity/principal\";\nimport { nonNullish } from \"./nullish.utils\";\n\nconst JSON_KEY_BIGINT = \"__bigint__\";\nconst JSON_KEY_PRINCIPAL = \"__principal__\";\nconst JSON_KEY_UINT8ARRAY = \"__uint8array__\";\n\n/**\n * A custom replacer for `JSON.stringify` that converts specific types not natively supported\n * by the API into JSON-compatible formats.\n *\n * Supported conversions:\n * - `BigInt` \u2192 `{ \"__bigint__\": string }`\n * - `Principal` \u2192 `{ \"__principal__\": string }`\n * - `Uint8Array` \u2192 `{ \"__uint8array__\": number[] }`\n *\n * @param {string} _key - Ignored. Only provided for API compatibility.\n * @param {unknown} value - The value to transform before stringification.\n * @returns {unknown} The transformed value if it matches a known type, otherwise the original value.\n */\n// eslint-disable-next-line local-rules/prefer-object-params\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 custom reviver for `JSON.parse` that reconstructs specific types from their JSON-encoded representations.\n *\n * This reverses the transformations applied by `jsonReplacer`, restoring the original types.\n *\n * Supported conversions:\n * - `{ \"__bigint__\": string }` \u2192 `BigInt`\n * - `{ \"__principal__\": string }` \u2192 `Principal`\n * - `{ \"__uint8array__\": number[] }` \u2192 `Uint8Array`\n *\n * @param {string} _key - Ignored but provided for API compatibility.\n * @param {unknown} value - The parsed value to transform.\n * @returns {unknown} The reconstructed value if it matches a known type, otherwise the original value.\n */\n// eslint-disable-next-line local-rules/prefer-object-params\nexport const jsonReviver = (_key: string, value: unknown): unknown => {\n const mapValue = <T>(key: string): T => (value as Record<string, T>)[key];\n\n if (\n nonNullish(value) &&\n typeof value === \"object\" &&\n JSON_KEY_BIGINT in value\n ) {\n return BigInt(mapValue(JSON_KEY_BIGINT));\n }\n\n if (\n nonNullish(value) &&\n typeof value === \"object\" &&\n JSON_KEY_PRINCIPAL in value\n ) {\n return Principal.fromText(mapValue(JSON_KEY_PRINCIPAL));\n }\n\n if (\n nonNullish(value) &&\n typeof value === \"object\" &&\n JSON_KEY_UINT8ARRAY in value\n ) {\n return Uint8Array.from(mapValue(JSON_KEY_UINT8ARRAY));\n }\n\n return value;\n};\n", "import { uint8ArrayToHexString } from \"./arrays.utils\";\nimport { jsonReplacer } from \"./json.utils\";\n\n/**\n * Generates a SHA-256 hash from the given object.\n *\n * The object is first stringified using a custom `jsonReplacer`, then\n * hashed using the SubtleCrypto API. The resulting hash is returned as a hex string.\n *\n * @template T - The type of the input object.\n * @param {T} params - The object to hash.\n * @returns {Promise<string>} A promise that resolves to the hex string of the SHA-256 hash.\n */\nexport const hashObject = async <T extends object>(\n params: T,\n): Promise<string> => {\n const jsonString = JSON.stringify(params, jsonReplacer);\n\n return await hashText(jsonString);\n};\n\n/**\n * Generates a SHA-256 hash from a plain text string.\n *\n * The string is UTF-8 encoded and hashed using the SubtleCrypto API.\n * The resulting hash is returned as a hexadecimal string.\n *\n * @param {string} text - The text to hash.\n * @returns {Promise<string>} A promise that resolves to the hex string of the SHA-256 hash.\n */\nexport const hashText = async (text: string): Promise<string> => {\n const dataBuffer = new TextEncoder().encode(text);\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", dataBuffer);\n\n return uint8ArrayToHexString(new Uint8Array(hashBuffer));\n};\n", "const SECONDS_IN_MINUTE = 60;\nconst MINUTES_IN_HOUR = 60;\nconst HOURS_IN_DAY = 24;\nconst DAYS_IN_NON_LEAP_YEAR = 365;\n\nexport interface I18nSecondsToDuration {\n year: string;\n year_plural: string;\n month: string;\n month_plural: string;\n day: string;\n day_plural: string;\n hour: string;\n hour_plural: string;\n minute: string;\n minute_plural: string;\n second: string;\n second_plural: string;\n}\n\nconst EN_TIME: I18nSecondsToDuration = {\n year: \"year\",\n year_plural: \"years\",\n month: \"month\",\n month_plural: \"months\",\n day: \"day\",\n day_plural: \"days\",\n hour: \"hour\",\n hour_plural: \"hours\",\n minute: \"minute\",\n minute_plural: \"minutes\",\n second: \"second\",\n second_plural: \"seconds\",\n};\n\n/**\n * Convert seconds to a human-readable duration, such as \"6 days, 10 hours.\"\n * @param {Object} options - The options object.\n * @param {bigint} options.seconds - The number of seconds to convert.\n * @param {I18nSecondsToDuration} [options.i18n] - The i18n object for customizing language and units. Defaults to English.\n * @returns {string} The human-readable duration string.\n */\nexport const secondsToDuration = ({\n seconds,\n i18n = EN_TIME,\n}: {\n seconds: bigint;\n i18n?: I18nSecondsToDuration;\n}): string => {\n let minutes = seconds / BigInt(SECONDS_IN_MINUTE);\n\n let hours = minutes / BigInt(MINUTES_IN_HOUR);\n minutes -= hours * BigInt(MINUTES_IN_HOUR);\n\n let days = hours / BigInt(HOURS_IN_DAY);\n hours -= days * BigInt(HOURS_IN_DAY);\n\n const years = fullYearsInDays(days);\n days -= daysInYears(years);\n\n const periods = [\n createLabel({ labelKey: \"year\", amount: years }),\n createLabel({ labelKey: \"day\", amount: days }),\n createLabel({ labelKey: \"hour\", amount: hours }),\n createLabel({ labelKey: \"minute\", amount: minutes }),\n ...(seconds > BigInt(0) && seconds < BigInt(60)\n ? [createLabel({ labelKey: \"second\", amount: seconds })]\n : []),\n ];\n\n return periods\n .filter(({ amount }) => amount > 0)\n .slice(0, 2)\n .map(\n (labelInfo) =>\n `${labelInfo.amount} ${\n labelInfo.amount === 1\n ? i18n[labelInfo.labelKey]\n : i18n[`${labelInfo.labelKey}_plural`]\n }`,\n )\n .join(\", \");\n};\n\nconst fullYearsInDays = (days: bigint): bigint => {\n // Use integer division.\n let years = days / BigInt(DAYS_IN_NON_LEAP_YEAR);\n while (daysInYears(years) > days) {\n years--;\n }\n return years;\n};\n\nconst daysInYears = (years: bigint): bigint => {\n // Use integer division.\n const leapDays = years / BigInt(4);\n return years * BigInt(DAYS_IN_NON_LEAP_YEAR) + leapDays;\n};\n\ntype LabelKey = \"year\" | \"month\" | \"day\" | \"hour\" | \"minute\" | \"second\";\ninterface LabelInfo {\n labelKey: LabelKey;\n amount: number;\n}\nconst createLabel = ({\n labelKey,\n amount,\n}: {\n labelKey: LabelKey;\n amount: bigint;\n}): LabelInfo => ({\n labelKey,\n amount: Number(amount),\n});\n\nconst NANOSECONDS_PER_MILLISECOND = 1_000_000n;\n\n/**\n * Returns the current timestamp in nanoseconds as a `bigint`.\n *\n * @returns {bigint} The current timestamp in nanoseconds.\n */\nexport const nowInBigIntNanoSeconds = (): bigint =>\n BigInt(Date.now()) * NANOSECONDS_PER_MILLISECOND;\n\n/**\n * Converts a given `Date` object to a timestamp in nanoseconds as a `bigint`.\n *\n * @param {Date} date - The `Date` object to convert.\n * @returns {bigint} The timestamp in nanoseconds.\n */\nexport const toBigIntNanoSeconds = (date: Date): bigint =>\n BigInt(date.getTime()) * NANOSECONDS_PER_MILLISECOND;\n", "/**\n * Creates a debounced version of the provided function.\n *\n * The debounced function postpones its execution until after a certain amount of time\n * has elapsed since the last time it was invoked. This is useful for limiting the rate\n * at which a function is called (e.g. in response to user input or events).\n *\n * @param {Function} func - The function to debounce. It will only be called after no new calls happen within the specified timeout.\n * @param {number} [timeout=300] - The debounce delay in milliseconds. Defaults to 300ms if not provided or invalid.\n * @returns {(args: unknown[]) => void} A debounced version of the original function.\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type, local-rules/prefer-object-params\nexport const debounce = (func: Function, timeout?: number) => {\n let timer: NodeJS.Timer | undefined;\n\n return (...args: unknown[]) => {\n const next = () => func(...args);\n\n if (timer) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore TypeScript global and window confusion even if we are using @types/node\n clearTimeout(timer);\n }\n\n timer = setTimeout(\n next,\n timeout !== undefined && timeout > 0 ? timeout : 300,\n );\n };\n};\n", "import type { Nullable, NullishNullable } from \"../types/did.utils\";\nimport { assertNonNullish } from \"./asserts.utils\";\nimport { nonNullish } from \"./nullish.utils\";\n\n/**\n * Converts a value into a Candid-style variant representation of an optional value.\n *\n * @template T The type of the value.\n * @param {T | null | undefined} value - The value to convert into a Candid-style variant.\n * @returns {Nullable<T>} A Candid-style variant representation: an empty array for `null` and `undefined` or an array with the value.\n */\nexport const toNullable = <T>(value?: T | null): Nullable<T> =>\n nonNullish(value) ? [value] : [];\n\n/**\n * Extracts the value from a Candid-style variant representation of an optional value.\n *\n * @template T The type of the value.\n * @param {Nullable<T>} value - A Candid-style variant representing an optional value.\n * @returns {T | undefined} The extracted value, or `undefined` if the array is empty.\n */\nexport const fromNullable = <T>(value: Nullable<T>): T | undefined =>\n value?.[0];\n\n/**\n * Extracts the value from a Candid-style variant representation of an optional value,\n * ensuring the value is defined. Throws an error if the array is empty or the value is nullish.\n *\n * @template T The type of the value.\n * @param {Nullable<T>} value - A Candid-style variant representing an optional value.\n * @returns {T} The extracted value.\n * @throws {Error} If the array is empty or the value is nullish.\n */\nexport const fromDefinedNullable = <T>(value: Nullable<T>): T => {\n const result = fromNullable(value);\n\n assertNonNullish(result);\n\n return result;\n};\n\n/**\n * Extracts the value from a nullish Candid-style variant representation.\n *\n * @template T The type of the value.\n * @param {NullishNullable<T>} value - A Candid-style variant or `undefined`.\n * @returns {T | undefined} The extracted value, or `undefined` if the input is nullish or the array is empty.\n */\nexport const fromNullishNullable = <T>(\n value: NullishNullable<T>,\n): T | undefined => fromNullable(value ?? []);\n", "import type { Principal } from \"@dfinity/principal\";\n\n/**\n * Convert a principal to a Uint8Array 32 length.\n * e.g. Useful to convert a canister ID when topping up cycles with the Cmc canister\n * @param principal The principal that needs to be converted to Subaccount\n */\nexport const principalToSubAccount = (principal: Principal): Uint8Array => {\n const bytes: Uint8Array = principal.toUint8Array();\n const subAccount: Uint8Array = new Uint8Array(32);\n subAccount[0] = bytes.length;\n subAccount.set(bytes, 1);\n return subAccount;\n};\n", "const AMOUNT_VERSION_PARTS = 3;\nconst addZeros = ({\n nums,\n amountZeros,\n}: {\n nums: number[];\n amountZeros: number;\n}): number[] =>\n amountZeros > nums.length\n ? [...nums, ...[...Array(amountZeros - nums.length).keys()].map(() => 0)]\n : nums;\n\nconst convertToNumber = (versionStringPart: string): number => {\n if (!Number.isNaN(Number(versionStringPart))) {\n return Number(versionStringPart);\n }\n const strippedVersion = versionStringPart.split(\"\").reduce((acc, char) => {\n if (Number.isNaN(Number(char))) {\n return acc;\n }\n return acc + char;\n }, \"\");\n return Number(strippedVersion);\n};\n/**\n * Returns true if the current version is smaller than the minVersion, false if equal or bigger.\n * Tags after patch version are ignored, e.g. 1.0.0-beta.1 is considered equal to 1.0.0.\n *\n * @param {Object} params\n * @param {string} params.minVersion Ex: \"1.0.0\"\n * @param {string} params.currentVersion Ex: \"2.0.0\"\n * @returns boolean\n */\nexport const smallerVersion = ({\n minVersion,\n currentVersion,\n}: {\n minVersion: string;\n currentVersion: string;\n}): boolean => {\n const minVersionStandarized = addZeros({\n nums: minVersion.split(\".\").map(convertToNumber),\n amountZeros: AMOUNT_VERSION_PARTS,\n }).join(\".\");\n const currentVersionStandarized = addZeros({\n nums: currentVersion.split(\".\").map(convertToNumber),\n amountZeros: AMOUNT_VERSION_PARTS,\n }).join(\".\");\n // Versions need to have the same number of parts to be comparable\n // Source: https://stackoverflow.com/a/65687141\n return (\n currentVersionStandarized.localeCompare(minVersionStandarized, undefined, {\n numeric: true,\n sensitivity: \"base\",\n }) < 0\n );\n};\n", "import {uint8ArrayToArrayOfNumber} from '@dfinity/utils';\n\n/**\n * Extracts the AAGUID (Authenticator Attestation GUID) from a WebAuthn data buffer.\n *\n * The AAGUID is a 16-byte value located at offsets 37..53 within `authenticatorData`\n * when **attested credential data** is present (i.e., during registration/attestation).\n *\n * For assertion (sign-in) responses, `authenticatorData` is typically 37 bytes and\n * does not include an AAGUID.\n *\n * If the extracted value is all zeros (`00000000-0000-0000-0000-000000000000`),\n * this function returns `{ unknownProvider: null }` since some passkey providers\n * intentionally use a zero AAGUID.\n *\n * @param {Object} params\n * @param {Uint8Array} params.authData - The WebAuthn `authenticatorData` bytes.\n * @returns {{aaguid: string; bytes: Uint8Array} | {invalidAuthData: null} | {unknownProvider: null}}\n * - { aaguidText, aaguidBytes } for valid AAGUID\n * - { unknownProvider: null } for all-zero AAGUID\n * - { invalidAuthData: null } if `authData` is invalid (too short, too long, etc.)\n *\n * @see https://web.dev/articles/webauthn-aaguid\n */\nexport const extractAAGUID = ({\n authData\n}: {\n authData: Uint8Array;\n}):\n | {aaguidText: string; aaguidBytes: Uint8Array}\n | {invalidAuthData: null}\n | {unknownProvider: null} => {\n if (authData.byteLength < 37) {\n return {invalidAuthData: null};\n }\n\n if (authData.byteLength < 53) {\n return {invalidAuthData: null};\n }\n\n const bytes = authData.slice(37, 53);\n\n const result = bytesToAAGUID({bytes});\n\n if ('aaguid' in result) {\n return {aaguidBytes: bytes, aaguidText: result.aaguid};\n }\n\n return {unknownProvider: null};\n};\n\n/**\n * Convert 16 AAGUID bytes to canonical UUID string (lowercase, hyphenated).\n *\n * Returns:\n * - { aaguid } for non-zero AAGUIDs\n * - { unknownProvider: null } for all-zero AAGUID\n * - { invalidBytes: null } if length \u2260 16\n *\n * @param {{bytes: Uint8Array | number[]}} params\n * @returns {{aaguid: string} | {invalidBytes: null} | {unknownProvider: null}}\n */\nexport const bytesToAAGUID = ({\n bytes\n}: {\n bytes: Uint8Array | number[];\n}): {aaguid: string} | {invalidBytes: null} | {unknownProvider: null} => {\n if (bytes.length !== 16) {\n return {invalidBytes: null};\n }\n\n const hex = (bytes instanceof Uint8Array ? uint8ArrayToArrayOfNumber(bytes) : bytes)\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join('');\n\n const aaguid = hex.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, '$1-$2-$3-$4-$5');\n\n // \"00000000-0000-0000-0000-0000000000000\" represents an unknown passkey provider. Some passkey providers use this AAGUID intentionally.\n // Source: https://web.dev/articles/webauthn-aaguid\n if (aaguid === '00000000-0000-0000-0000-000000000000') {\n return {unknownProvider: null};\n }\n\n return {aaguid};\n};\n", "import {DER_COSE_OID, wrapDER, type DerEncodedPublicKey} from '@dfinity/agent';\n\n/**\n * \u26A0\uFE0F !!!WARNING!!! \u26A0\uFE0F\n * This module is a copy/paste of the webauthn functions not exposed by Agent-js.\n * It is therefore not covered by any tests (\u203C\uFE0F) in this library.\n *\n * @see https://github.com/dfinity/agent-js/blob/main/packages/identity/src/identity/webauthn.ts\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 */\nexport function _authDataToCose(authData: Uint8Array): Uint8Array {\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 function _coseToDerEncodedBlob(cose: Uint8Array): DerEncodedPublicKey {\n return wrapDER(cose.buffer as ArrayBuffer, DER_COSE_OID).buffer as DerEncodedPublicKey;\n}\n", "import type {DerEncodedPublicKey, PublicKey} from '@dfinity/agent';\nimport {_coseToDerEncodedBlob} from './cose-utils';\n\n/**\n * \u26A0\uFE0F !!!WARNING!!! \u26A0\uFE0F\n * This module is a copy/paste of the webauthn classes not exposed by Agent-js.\n * It is therefore not covered by any tests (\u203C\uFE0F) in this library.\n *\n * @see https://github.com/dfinity/agent-js/blob/main/packages/identity/src/identity/webauthn.ts\n */\n\n/**\n * COSE-encoded key (CBOR Object Signing and Encryption).\n * serialized as a Uint8Array.\n */\nexport type CoseEncodedKey = Uint8Array;\n\nexport class CosePublicKey implements PublicKey {\n protected _encodedKey: DerEncodedPublicKey;\n\n public constructor(protected _cose: CoseEncodedKey) {\n this._encodedKey = _coseToDerEncodedBlob(_cose);\n }\n\n public toDer(): DerEncodedPublicKey {\n return this._encodedKey;\n }\n}\n", "import type {PublicKey} from '@dfinity/agent';\nimport {uint8ArrayToBase64} from '@dfinity/utils';\nimport {extractAAGUID} from './aaguid';\nimport {type CoseEncodedKey, CosePublicKey} from './agent-js/cose-key';\n\n/**\n * Arguments to initialize a WebAuthn object.\n */\nexport interface InitWebAuthnCredentialArgs {\n /**\n * The credential ID (authenticator\u2019s `rawId`) as bytes.\n */\n rawId: Uint8Array;\n\n /**\n * COSE-encoded public key extracted from attestation/authData.\n */\n cose: CoseEncodedKey;\n}\n\nexport interface InitWebAuthnNewCredentialArgs extends InitWebAuthnCredentialArgs {\n /**\n * The authenticator data from the attestation.\n */\n authData: Uint8Array;\n}\n\n/**\n * A wrapper around a WebAuthn credential that provides various base information such as its ID or public key.\n */\nexport abstract class WebAuthnCredential {\n readonly #credentialId: Uint8Array;\n readonly #publicKey: CosePublicKey;\n\n /**\n * @param args - {@link InitWebAuthnCredentialArgs} used to initialize the credential.\n * @param args.rawId - Credential ID (`rawId`) as bytes.\n * @param args.cose - COSE-encoded public key.\n */\n constructor({rawId: credentialId, cose}: InitWebAuthnCredentialArgs) {\n this.#credentialId = credentialId;\n this.#publicKey = new CosePublicKey(cose);\n }\n\n /**\n * Returns the public key for this credential.\n */\n getPublicKey(): PublicKey {\n return this.#publicKey;\n }\n\n /**\n * Returns the credential ID as bytes.\n */\n getCredentialId(): Uint8Array {\n return this.#credentialId;\n }\n\n /**\n * Returns the credential ID as textual representation (a base64 string).\n */\n getCredentialIdText(): string {\n return uint8ArrayToBase64(this.#credentialId);\n }\n}\n\n/**\n * A wrapper around a newly created WebAuthn credential.\n * It is created using `navigator.credentials.create` which provides an attestation.\n */\nexport class WebAuthnNewCredential extends WebAuthnCredential {\n readonly #aaguidText: string | undefined;\n readonly #aaguidBytes: Uint8Array | undefined;\n\n /**\n * @param args - {@link InitWebAuthnNewCredentialArgs} used to initialize the credential.\n * @param args.rawId - Credential ID (`rawId`) as bytes.\n * @param args.cose - COSE-encoded public key.\n * @params args.authData - Authenticator data from the attestation.\n */\n constructor({authData, ...rest}: InitWebAuthnNewCredentialArgs) {\n super(rest);\n\n const optionAaguid = extractAAGUID({authData});\n this.#aaguidText = 'aaguidText' in optionAaguid ? optionAaguid.aaguidText : undefined;\n this.#aaguidBytes = 'aaguidBytes' in optionAaguid ? optionAaguid.aaguidBytes : undefined;\n }\n\n /**\n * Returns AAGUID (Authenticator Attestation GUID).\n */\n getAAGUID(): Uint8Array | undefined {\n return this.#aaguidBytes;\n }\n\n /**\n * Returns the textual representation of the AAGUID (Authenticator Attestation GUID).\n */\n getAAGUIDText(): string | undefined {\n return this.#aaguidText;\n }\n}\n\n/**\n * A wrapper around a retrieval of existing WebAuthn credential.\n * It is created using `navigator.credentials.get` which provides an assertion.\n */\nexport class WebAuthnExistingCredential extends WebAuthnCredential {}\n", "export class WebAuthnIdentityHostnameError extends Error {}\nexport class WebAuthnIdentityCredentialNotInitializedError extends Error {}\nexport class WebAuthnIdentityCreateCredentialOnTheDeviceError extends Error {}\nexport class WebAuthnIdentityCredentialNotPublicKeyError extends Error {}\nexport class WebAuthnIdentityNoAttestationError extends Error {}\nexport class WebAuthnIdentityInvalidCredentialIdError extends Error {}\nexport class WebAuthnIdentityEncodeCborSignatureError extends Error {}\n// https://developer.mozilla.org/en-US/docs/Web/API/AuthenticatorAssertionResponse/authenticatorData\nexport class WebAuthnIdentityNoAuthenticatorDataError extends Error {}\n// https://developer.mozilla.org/en-US/docs/Web/API/AuthenticatorAssertionResponse/signature\nexport class WebAuthnIdentityNoSignatureError extends Error {}\n", "import {Cbor, type PublicKey, type Signature, SignIdentity} from '@dfinity/agent';\nimport {arrayBufferToUint8Array, isNullish, uint8ArraysEqual} from '@dfinity/utils';\nimport {AUTHENTICATOR_ABORT_TIMEOUT} from './_constants';\nimport {createPasskeyOptions, retrievePasskeyOptions} from './_options';\nimport {execute} from './_progress';\nimport {_authDataToCose} from './agent-js/cose-utils';\nimport {\n type InitWebAuthnNewCredentialArgs,\n type WebAuthnCredential,\n WebAuthnExistingCredential,\n WebAuthnNewCredential\n} from './credential';\nimport {\n WebAuthnIdentityCreateCredentialOnTheDeviceError,\n WebAuthnIdentityCredentialNotInitializedError,\n WebAuthnIdentityCredentialNotPublicKeyError,\n WebAuthnIdentityEncodeCborSignatureError,\n WebAuthnIdentityInvalidCredentialIdError,\n WebAuthnIdentityNoAttestationError,\n WebAuthnIdentityNoAuthenticatorDataError\n} from './errors';\nimport type {\n AuthenticatorOptions,\n CreateWebAuthnIdentityWithExistingCredentialArgs,\n CreateWebAuthnIdentityWithNewCredentialArgs,\n RetrievePublicKeyFn\n} from './types/identity';\nimport type {PasskeyOptions} from './types/passkey';\nimport {\n type WebAuthnSignProgressArgs,\n type WebAuthnSignProgressFn,\n WebAuthnSignProgressStep\n} from './types/progress';\n\ntype PublicKeyCredentialWithAttachment = Omit<PublicKeyCredential, 'response'> & {\n response: AuthenticatorAssertionResponse & {\n attestationObject?: ArrayBuffer;\n };\n};\n\nconst createAbortSignal = ({\n timeout\n}: Pick<AuthenticatorOptions<PasskeyOptions>, 'timeout'>): AbortSignal =>\n AbortSignal.timeout(timeout ?? AUTHENTICATOR_ABORT_TIMEOUT);\n\nconst retrieveCredentials = async ({\n challenge,\n credentialIds,\n passkeyOptions,\n timeout\n}: {\n challenge: Uint8Array;\n credentialIds?: Uint8Array[];\n} & AuthenticatorOptions<PasskeyOptions>): Promise<Credential | null> =>\n await navigator.credentials.get({\n publicKey: {\n ...retrievePasskeyOptions(passkeyOptions),\n challenge: challenge.buffer as BufferSource,\n allowCredentials: (credentialIds ?? []).map((id) => ({\n id: id.buffer as BufferSource,\n type: 'public-key'\n }))\n },\n signal: createAbortSignal({timeout})\n });\n\ntype WebAuthnState<T extends WebAuthnCredential> =\n | {status: 'pending'; retrievePublicKey: RetrievePublicKeyFn}\n | {status: 'initialized'; credential: T};\n\nconst assertWebAuthnStateInitialized: <T extends WebAuthnCredential>(\n state: WebAuthnState<T>\n) => asserts state is {\n status: 'initialized';\n credential: T;\n} = <T extends WebAuthnCredential>(state: WebAuthnState<T>): void => {\n if (state.status !== 'initialized') {\n throw new WebAuthnIdentityCredentialNotInitializedError();\n }\n};\n\nconst assertNonNullishCredential: (\n credential: Credential | null\n) => asserts credential is Credential = (credential: Credential | null): void => {\n if (isNullish(credential)) {\n throw new WebAuthnIdentityCreateCredentialOnTheDeviceError();\n }\n};\n\nconst assertCredentialPublicKey: (\n credential: Credential\n) => asserts credential is PublicKeyCredentialWithAttachment = ({type}: Credential): void => {\n if (type !== 'public-key') {\n throw new WebAuthnIdentityCredentialNotPublicKeyError();\n }\n};\n\n/**\n * A signing identity for the Internet Computer, backed by a WebAuthn credential.\n *\n * Use one of the factory methods to construct an instance:\n * - {@link WebAuthnIdentity.createWithNewCredential} to create a new passkey on the device.\n * - {@link WebAuthnIdentity.createWithExistingCredential} to use an existing passkey.\n *\n * @template T Concrete credential type for this identity\n * ({@link WebAuthnNewCredential} or {@link WebAuthnExistingCredential}).\n */\nexport class WebAuthnIdentity<T extends WebAuthnCredential> extends SignIdentity {\n readonly #onSignProgress: WebAuthnSignProgressFn | undefined;\n #state: WebAuthnState<T>;\n\n /**\n * @hidden Use the factory methods instead.\n *\n * Initializes the identity in either:\n * - **pending** state (existing-credential path; public key not yet known), or\n * - **initialized** state (new-credential path; public key known immediately).\n *\n * @private\n */\n private constructor({\n onProgress,\n ...args\n }: WebAuthnSignProgressArgs &\n (\n | InitWebAuthnNewCredentialArgs\n | Pick<CreateWebAuthnIdentityWithExistingCredentialArgs, 'retrievePublicKey'>\n )) {\n super();\n\n this.#onSignProgress = onProgress;\n\n if ('retrievePublicKey' in args) {\n const {retrievePublicKey} = args;\n\n this.#state = {\n status: 'pending',\n retrievePublicKey\n };\n\n return;\n }\n\n this.#state = WebAuthnIdentity.#createInitializedState({\n credential: new WebAuthnNewCredential(args)\n });\n }\n\n static #createInitializedState<T extends WebAuthnCredential>({\n credential\n }: {\n credential: WebAuthnNewCredential | WebAuthnExistingCredential;\n }): WebAuthnState<T> {\n return {\n status: 'initialized',\n credential: credential as T\n };\n }\n\n /**\n * Creates a new passkey on the device and returns an initialized identity.\n *\n * If you chain `create` and `sign`, the user will be prompted twice to authenticate\n * with their authenticator. You can track progress via the `onProgress` callback.\n *\n * @param args {@link CreateWebAuthnIdentityWithNewCredentialArgs} Options to create the passkey.\n * @returns A {@link WebAuthnIdentity} parameterized with {@link WebAuthnNewCredential}.\n */\n static async createWithNewCredential({\n passkeyOptions,\n timeout,\n ...restArgs\n }: CreateWebAuthnIdentityWithNewCredentialArgs = {}): Promise<\n WebAuthnIdentity<WebAuthnNewCredential>\n > {\n const credential = await navigator.credentials.create({\n publicKey: createPasskeyOptions(passkeyOptions),\n signal: createAbortSignal({timeout})\n });\n\n assertNonNullishCredential(credential);\n assertCredentialPublicKey(credential);\n\n const {\n response: {attestationObject},\n rawId\n } = credential;\n\n if (isNullish(attestationObject)) {\n throw new WebAuthnIdentityNoAttestationError();\n }\n\n // We have to parse the attestationObject as CBOR to ultimately retrieve the public key.\n // Similar as what's implemented in AgentJS.\n const {authData} = Cbor.decode<{authData: Uint8Array}>(attestationObject);\n\n const cose = _authDataToCose(authData);\n\n return new WebAuthnIdentity<WebAuthnNewCredential>({\n ...restArgs,\n rawId: arrayBufferToUint8Array(rawId),\n cose,\n authData\n });\n }\n\n /**\n * Creates an identity for an existing passkey.\n *\n * @param args {@link CreateWebAuthnIdentityWithExistingCredentialArgs} Options to retrieve the passkey.\n * @returns A {@link WebAuthnIdentity} parameterized with {@link WebAuthnExistingCredential}.\n */\n // We use async for consistency reason and because it might be future prone.\n // eslint-disable-next-line require-await\n static async createWithExistingCredential(\n args: CreateWebAuthnIdentityWithExistingCredentialArgs\n ): Promise<WebAuthnIdentity<WebAuthnExistingCredential>> {\n return new WebAuthnIdentity<WebAuthnExistingCredential>(args);\n }\n\n /**\n * Returns the credential\u2019s public key.\n *\n * @returns {PublicKey}\n * @throws WebAuthnIdentityCredentialNotInitializedError if the identity has not signed\n * any request yet.\n */\n override getPublicKey(): PublicKey {\n assertWebAuthnStateInitialized(this.#state);\n\n const {credential} = this.#state;\n\n return credential.getPublicKey();\n }\n\n /**\n * Returns the concrete credential wrapper for this identity.\n *\n * For identities created with:\n * - `createWithNewCredential` \u2192 {@link WebAuthnNewCredential}\n * - `createWithExistingCredential` \u2192 {@link WebAuthnExistingCredential}\n *\n * @throws WebAuthnIdentityCredentialNotInitializedError if the identity has not signed\n * any request yet.\n */\n getCredential(): T {\n assertWebAuthnStateInitialized(this.#state);\n\n const {credential} = this.#state;\n\n return credential;\n }\n\n /**\n * Signs an arbitrary blob using the platform authenticator.\n *\n * @param blob Bytes to sign (used as the WebAuthn challenge).\n * @returns {Promise<Signature>} CBOR-encoded signature payload.\n */\n override async sign(blob: ArrayBuffer): Promise<Signature> {\n // 1. Request user credential (navigator.credentials.get)\n const requestCredential = async (): Promise<PublicKeyCredential> => {\n const credential = await retrieveCredentials({\n challenge: arrayBufferToUint8Array(blob),\n ...(this.#state.status === 'initialized' && {\n credentialIds: [this.#state.credential.getCredentialId()]\n })\n });\n\n assertNonNullishCredential(credential);\n assertCredentialPublicKey(credential);\n\n return credential;\n };\n\n const credential = await execute({\n fn: requestCredential,\n step: WebAuthnSignProgressStep.RequestingUserCredential,\n onProgress: this.#onSignProgress\n });\n\n // 2. Assert credential ID if already initialized or load public key from backend and init state\n const finalizingCredential = async () => {\n const {rawId} = credential;\n\n // If the state was already initialized - credentials.create - then we \"only\"\n // assert that the rawId retrieved by credentials.get is equals to the one already known.\n if (this.#state.status === 'initialized') {\n if (\n !uint8ArraysEqual({\n a: this.#state.credential.getCredentialId(),\n b: arrayBufferToUint8Array(rawId)\n })\n ) {\n throw new WebAuthnIdentityInvalidCredentialIdError();\n }\n\n return;\n }\n\n // If the state was pending, we need to retrieve the public key for the credential\n // that was saved during a previous sign-up\n // because credentials.get does not provide an attestation.\n const {retrievePublicKey} = this.#state;\n\n const cose = await retrievePublicKey({\n credentialId: arrayBufferToUint8Array(rawId)\n });\n\n this.#state = WebAuthnIdentity.#createInitializedState({\n credential: new WebAuthnExistingCredential({\n rawId: arrayBufferToUint8Array(rawId),\n cose\n })\n });\n };\n\n await execute({\n fn: finalizingCredential,\n step: WebAuthnSignProgressStep.FinalizingCredential,\n onProgress: this.#onSignProgress\n });\n\n // 3. Sign the request\n // eslint-disable-next-line require-await\n const encodeSignature = async (): Promise<Signature> => {\n const {response} = credential;\n\n const {clientDataJSON} = response;\n\n // Only the response of type AuthenticatorAssertionResponse provides authenticatorData and signature\n // which is the type of response we are expecting.\n const {authenticatorData, signature} =\n 'authenticatorData' in response && 'signature' in response\n ? (response as AuthenticatorAssertionResponse)\n : {};\n\n if (isNullish(authenticatorData)) {\n throw new WebAuthnIdentityNoAuthenticatorDataError();\n }\n\n if (isNullish(signature)) {\n throw new WebAuthnIdentityNoAuthenticatorDataError();\n }\n\n const encoded = Cbor.encode({\n authenticator_data: authenticatorData,\n client_data_json: new TextDecoder().decode(clientDataJSON),\n signature: arrayBufferToUint8Array(signature)\n });\n\n if (isNullish(encoded)) {\n throw new WebAuthnIdentityEncodeCborSignatureError();\n }\n\n // Similar as AgentJS code.\n Object.assign(encoded, {\n __signature__: undefined\n });\n\n return encoded as Signature;\n };\n\n return await execute({\n fn: encodeSignature,\n step: WebAuthnSignProgressStep.Signing,\n onProgress: this.#onSignProgress\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.\n//\n// According Google tutorial, https://web.dev/articles/passkey-registration, specifying\n// support for ECDSA with P-256 (-7) and RSA PKCS#1 (-257) gives complete coverage.\nexport const PUBLIC_KEY_COSE_ALGORITHMS = {\n ECDSA_WITH_SHA256: -7,\n RSA_WITH_SHA256: -257\n};\n\nexport const AUTHENTICATOR_ABORT_TIMEOUT = 60000;\n", "import {isNullish} from '@dfinity/utils';\nimport {PUBLIC_KEY_COSE_ALGORITHMS} from './_constants';\nimport {WebAuthnIdentityHostnameError} from './errors';\nimport type {CreatePasskeyOptions, PasskeyOptions} from './types/passkey';\n\nconst randomValue = (): BufferSource => window.crypto.getRandomValues(new Uint8Array(16));\n\n/**\n * When creating a passkey, the challenge can simply be a random value.\n * Since the server doesn\u2019t need to verify the authenticity of the key,\n * it doesn\u2019t have to generate the challenge itself.\n *\n * In contrast, when signing a request with our credentials,\n * the request itself becomes the data (blob), the challenge, that must be signed.\n */\nconst createChallenge = (): BufferSource => randomValue();\n\n/**\n * The user ID is set to a random value, which holds little relevance\n * for the end user beyond being unique.\n *\n * Ultimately, once signed in, the user's actual identifier will be\n * the public key (principal) of the identity used to interact with the IC.\n */\nconst createUserId = (): BufferSource => randomValue();\n\nconst hostname = (): string => {\n const {\n location: {href}\n } = window;\n\n const url = URL.parse(href);\n\n if (isNullish(url)) {\n throw new WebAuthnIdentityHostnameError();\n }\n\n const {hostname} = url;\n\n return hostname;\n};\n\nconst relyingPartyId = ({appId}: Pick<PasskeyOptions, 'appId'>): string => appId?.id ?? hostname();\n\nexport const createPasskeyOptions = ({\n appId,\n user: userOptions\n}: CreatePasskeyOptions = {}): PublicKeyCredentialCreationOptions => {\n const {\n document: {title: name}\n } = window;\n\n const relyingParty = (): Pick<PublicKeyCredentialCreationOptions, 'rp'> => ({\n rp: {\n // Note: deprecated in WebAuthn L3\n name: appId?.name ?? name,\n id: relyingPartyId({appId})\n }\n });\n\n const user = (): Pick<PublicKeyCredentialCreationOptions, 'user'> => ({\n user: {\n id: createUserId(),\n name: userOptions?.name ?? userOptions?.displayName ?? name,\n displayName: userOptions?.displayName ?? name\n }\n });\n\n return {\n // We want to receive the attestation statement as generated by the authenticator\n attestation: 'direct',\n challenge: createChallenge(),\n ...relyingParty(),\n ...user(),\n pubKeyCredParams: Object.values(PUBLIC_KEY_COSE_ALGORITHMS).map((algorithm) => ({\n type: 'public-key',\n alg: algorithm\n })),\n excludeCredentials: [],\n authenticatorSelection: {\n // At least for now, we want a simplified flow and therefore indicates that we want a\n // platform authenticator ((an authenticator embedded to the platform device).\n authenticatorAttachment: 'platform',\n userVerification: 'preferred',\n // Along with requireResidentKey, make passkey discoverable,\n residentKey: 'required',\n requireResidentKey: true\n }\n };\n};\n\nexport const retrievePasskeyOptions = (\n options: PasskeyOptions = {}\n): Omit<PublicKeyCredentialRequestOptions, 'challenge'> => ({\n rpId: relyingPartyId(options),\n allowCredentials: [],\n userVerification: 'required'\n});\n", "import type {WebAuthnSignProgress, WebAuthnSignProgressArgs} from './types/progress';\n\nexport const execute = async <T>({\n fn,\n step,\n onProgress\n}: {\n fn: () => Promise<T>;\n} & Pick<WebAuthnSignProgress, 'step'> &\n WebAuthnSignProgressArgs): Promise<T> => {\n onProgress?.({\n step,\n state: 'in_progress'\n });\n\n try {\n const result = await fn();\n\n onProgress?.({\n step,\n state: 'success'\n });\n\n return result;\n } catch (err: unknown) {\n onProgress?.({\n step,\n state: 'error'\n });\n\n throw err;\n }\n};\n", "/**\n * Progress steps in the WebAuthn signing flow.\n */\nexport enum WebAuthnSignProgressStep {\n /** Calling `navigator.credentials.get` to obtain an assertion. */\n RequestingUserCredential,\n /** Verifying/initializing the credential (e.g., ID match, loading public key). */\n FinalizingCredential,\n /** Producing the signature and encoding the result. */\n Signing\n}\n\n/**\n * Status of the current step.\n */\nexport type WebAuthnSignProgressState = 'in_progress' | 'success' | 'error';\n\n/**\n * Payload emitted on progress updates.\n */\nexport interface WebAuthnSignProgress {\n /** The step being executed. */\n step: WebAuthnSignProgressStep;\n /** State of that step. */\n state: WebAuthnSignProgressState;\n}\n\n/**\n * Callback invoked on each progress update.\n */\nexport type WebAuthnSignProgressFn = (progress: WebAuthnSignProgress) => void;\n\n/**\n * Optional handler for progress updates.\n */\nexport interface WebAuthnSignProgressArgs {\n onProgress?: WebAuthnSignProgressFn;\n}\n", "import {nonNullish} from '@dfinity/utils';\n\n/**\n * Checks if a user-verifying platform authenticator (passkeys) is available on this device / browser.\n *\n * Returns `true` when:\n * 1) `window.PublicKeyCredential` exists, and\n * 2) the browser reports a user-verifying **platform** authenticator is available\n * (e.g., Touch ID, Windows Hello, Android biometrics/PIN).\n *\n * @returns {Promise<boolean>} `true` if an authenticator is available, otherwise `false`.\n */\nexport const isWebAuthnAvailable = async (): Promise<boolean> => {\n if (\n nonNullish(window.PublicKeyCredential) &&\n 'isUserVerifyingPlatformAuthenticatorAvailable' in PublicKeyCredential\n ) {\n return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();\n }\n\n return false;\n};\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 {Store} from '../../core/stores/_store';\nimport type {Unsubscribe} from '../../core/types/subscription';\n\nimport type {User} from '../types/user';\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", "export const DOCKER_CONTAINER_URL = 'http://127.0.0.1:5987';\nexport const DOCKER_INTERNET_IDENTITY_ID = 'rdmx6-jaaaa-aaaaa-aaadq-cai';\n", "import {HttpAgent} from '@dfinity/agent';\nimport {nonNullish} from '@dfinity/utils';\nimport {DOCKER_CONTAINER_URL} from '../constants/container.constants';\nimport type {SatelliteContext} from '../types/satellite';\n\nexport type CreateAgentParams = Required<Pick<SatelliteContext, 'identity'>> &\n Pick<SatelliteContext, 'container'>;\n\nexport const createAgent = async ({identity, container}: CreateAgentParams): Promise<HttpAgent> => {\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 return await HttpAgent.create({\n identity,\n shouldFetchRootKey,\n host\n });\n};\n", "import type {Agent, HttpAgent} from '@dfinity/agent';\nimport {isNullish} from '@dfinity/utils';\nimport {type CreateAgentParams, createAgent} from './_agent.factory';\n\nexport class AgentStore {\n private static instance: AgentStore;\n\n #agents: Record<string, HttpAgent> | undefined | null = undefined;\n\n private constructor() {}\n\n static getInstance() {\n if (isNullish(AgentStore.instance)) {\n AgentStore.instance = new AgentStore();\n }\n return AgentStore.instance;\n }\n\n async getAgent({identity, ...rest}: CreateAgentParams): Promise<Agent> {\n const key = identity.getPrincipal().toText();\n\n if (isNullish(this.#agents) || isNullish(this.#agents[key])) {\n const agent = await createAgent({identity, ...rest});\n\n this.#agents = {\n ...(this.#agents ?? {}),\n [key]: agent\n };\n\n return agent;\n }\n\n return this.#agents[key];\n }\n\n reset() {\n this.#agents = null;\n }\n}\n", "import {Actor, type ActorMethod, type ActorSubclass} from '@dfinity/agent';\nimport type {IDL} from '@dfinity/candid';\nimport {isNullish} from '@dfinity/utils';\nimport type {ActorKey} from '../types/actor';\nimport type {SatelliteContext} from '../types/satellite';\nimport {AgentStore} from './agent.store';\n\ntype ActorParams = {\n idlFactory: IDL.InterfaceFactory;\n} & Required<Pick<SatelliteContext, 'satelliteId' | 'identity'>> &\n Pick<SatelliteContext, 'container'>;\n\ntype ActorRecord = Record<string, ActorMethod>;\n\nexport class ActorStore {\n private static instance: ActorStore;\n\n #actors: Record<string, ActorSubclass<ActorRecord>> | undefined | null = undefined;\n\n private constructor() {}\n\n static getInstance() {\n if (isNullish(ActorStore.instance)) {\n ActorStore.instance = new ActorStore();\n }\n return ActorStore.instance;\n }\n\n async getActor<T = ActorRecord>({\n satelliteId,\n identity,\n actorKey,\n ...rest\n }: ActorParams & {actorKey: ActorKey}): Promise<ActorSubclass<T>> {\n const key = `${actorKey}#${identity.getPrincipal().toText()}#${satelliteId};`;\n\n if (isNullish(this.#actors) || isNullish(this.#actors[key])) {\n const actor = await this.createActor({satelliteId, identity, ...rest});\n\n this.#actors = {\n ...(this.#actors ?? {}),\n [key]: actor\n };\n\n return actor as ActorSubclass<T>;\n }\n\n return this.#actors[key] as ActorSubclass<T>;\n }\n\n reset() {\n this.#actors = null;\n }\n\n private async createActor<T = ActorRecord>({\n idlFactory,\n satelliteId: canisterId,\n ...rest\n }: ActorParams): Promise<ActorSubclass<T>> {\n const agent = await AgentStore.getInstance().getAgent(rest);\n\n return Actor.createActor(idlFactory, {\n agent,\n canisterId\n });\n }\n}\n", "const onBeforeUnload = ($event: BeforeUnloadEvent) => {\n $event.preventDefault();\n return ($event.returnValue = 'Are you sure you want to exit?');\n};\n\nconst addBeforeUnload = () => {\n window.addEventListener('beforeunload', onBeforeUnload, {capture: true});\n};\n\nconst removeBeforeUnload = () => {\n window.removeEventListener('beforeunload', onBeforeUnload, {capture: true});\n};\n\nexport const executeWithWindowGuard = async <T>({fn}: {fn: () => Promise<T>}): Promise<T> => {\n try {\n addBeforeUnload();\n\n return await fn();\n } finally {\n removeBeforeUnload();\n }\n};\n", "import type {Environment} from '../types/env';\nimport {Store} from './_store';\n\nexport class EnvStore extends Store<Environment | undefined> {\n private static instance: EnvStore;\n\n private env: Environment | undefined | null;\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 | null {\n return this.env;\n }\n\n reset() {\n this.env = null;\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", "// 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_IN_MILLISECONDS = 4 * 60 * 60 * 1000;\nexport const DELEGATION_IDENTITY_EXPIRATION = BigInt(\n DELEGATION_IDENTITY_EXPIRATION_IN_MILLISECONDS * 1000 * 1000\n);\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", "import {jsonReplacer, jsonReviver} from '@dfinity/utils';\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 {isNullish} from '@dfinity/utils';\nimport {isBrowser} 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 { 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 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 requests.\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/no-unsafe-function-type\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 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 {\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 // Ignore any event that is not from the identity provider\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 {\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 type {SignProgressFn} from '../types/progress';\n\nexport const execute = async <T, Step>({\n fn,\n step,\n onProgress\n}: {\n fn: () => Promise<T>;\n step: Step;\n onProgress?: SignProgressFn<Step>;\n}): Promise<T> => {\n onProgress?.({\n step,\n state: 'in_progress'\n });\n\n try {\n const result = await fn();\n\n onProgress?.({\n step,\n state: 'success'\n });\n\n return result;\n } catch (err: unknown) {\n onProgress?.({\n step,\n state: 'error'\n });\n\n throw err;\n }\n};\n", "import type {SignProgressFn} from './progress';\n\n/**\n * Enum representing the different steps of the sign-in flow with Internet Identity or NFID.\n */\nexport enum AuthClientSignInProgressStep {\n /** User is authenticating with the identity provider (II / NFID). */\n AuthorizingWithProvider,\n /** App is creating a new user or retrieving an existing one after authorization. */\n CreatingOrRetrievingUser\n}\n\n/**\n * Interface representing sign-in options when using an AuthClient based provider.\n * @interface AuthClientSignInOptions\n */\nexport interface AuthClientSignInOptions {\n /**\n * Maximum time to live for the session in nanoseconds. Cannot be extended.\n * @type {bigint}\n */\n maxTimeToLiveInNanoseconds?: bigint;\n\n /**\n * Origin for derivation. Useful when sign-in using the same domain - e.g. sign-in on www.hello.com for hello.com.\n * @type {(string | URL)}\n */\n derivationOrigin?: string | URL;\n\n /**\n * Whether to open the sign-in window.\n * @default true\n * @type {boolean}\n */\n windowed?: boolean;\n\n /**\n * Whether to allow the infamous PIN authentication.\n * @default false\n * @type {boolean}\n */\n allowPin?: boolean;\n\n /**\n * Optional callback to receive progress updates about the sign-in flow.\n * Useful for showing UI feedback such as loading indicators or status messages.\n */\n onProgress?: SignProgressFn<AuthClientSignInProgressStep>;\n}\n", "export class SignInError extends Error {}\nexport class SignInInitError extends Error {}\nexport class SignInUserInterruptError extends Error {}\nexport class SignInProviderNotSupportedError extends Error {}\n\nexport class WebAuthnSignInRetrievePublicKeyError extends Error {}\n\nexport class SignUpProviderNotSupportedError extends Error {}\n\nexport class InitError extends Error {}\n\nexport class ListError extends Error {}\n", "import {type AuthClient, ERROR_USER_INTERRUPT} from '@dfinity/auth-client';\nimport {isNullish} from '@dfinity/utils';\nimport {\n ALLOW_PIN_AUTHENTICATION,\n DELEGATION_IDENTITY_EXPIRATION\n} from '../constants/auth.constants';\nimport {execute} from '../helpers/progress.helpers';\nimport {type AuthClientSignInOptions, AuthClientSignInProgressStep} from '../types/auth-client';\nimport {SignInError, SignInInitError, SignInUserInterruptError} from '../types/errors';\nimport type {Provider} from '../types/provider';\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\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 * Abstract base class for all authentication providers that integrate with the `@dfinity/auth-client`.\n *\n * @abstract\n * @class AuthClientProvider\n * @implements {AuthProvider}\n */\nexport abstract class AuthClientProvider implements AuthProvider {\n /**\n * The unique identifier of the provider.\n *\n * @abstract\n * @type {Provider}\n */\n abstract get id(): Provider;\n\n /**\n * Returns the sign-in options for the provider.\n *\n * Note: set as public instead of protected for testing purposes.\n *\n * @abstract\n * @param {Pick<SignInOptions, 'windowed'>} options - Options controlling window behavior.\n * @returns {AuthProviderSignInOptions} Provider-specific sign-in options.\n */\n abstract signInOptions(\n options: Pick<AuthClientSignInOptions, 'windowed'>\n ): AuthProviderSignInOptions;\n\n /**\n * Signs in a user with the given authentication provider.\n *\n * @param {Object} params - The sign-in parameters.\n * @param {AuthClientSignInOptions} [params.options] - Optional configuration for the login request.\n * @param {AuthClient | undefined | null} params.authClient - The AuthClient instance in its current state.\n * @param {initAuth} params.initAuth - The function to load or initialize the user. Provided as a callback to avoid recursive import.\n *\n * @returns {Promise<void>} Resolves if the sign-in is successful. Rejects with:\n * - {@link SignInInitError} if no AuthClient is available.\n * - {@link SignInUserInterruptError} if the user cancels the login.\n * - {@link SignInError} for other errors during sign-in.\n */\n async signIn({\n options,\n authClient,\n initAuth\n }: {\n options?: AuthClientSignInOptions;\n authClient: AuthClient | undefined | null;\n initAuth: (params: {provider: Provider}) => Promise<void>;\n }): Promise<void> {\n // 1. Sign-in or sign-up with third party provider\n const login = async () => await this.#loginWithAuthClient({options, authClient});\n\n await execute({\n fn: login,\n step: AuthClientSignInProgressStep.AuthorizingWithProvider,\n onProgress: options?.onProgress\n });\n\n // 2. Create or load the user for the authentication\n const runAuth = async () => await initAuth({provider: this.id});\n\n await execute({\n fn: runAuth,\n step: AuthClientSignInProgressStep.CreatingOrRetrievingUser,\n onProgress: options?.onProgress\n });\n }\n\n #loginWithAuthClient({\n options,\n authClient\n }: {\n options?: Omit<AuthClientSignInOptions, 'onProgress'>;\n authClient: AuthClient | undefined | null;\n }): Promise<void> {\n /* eslint-disable no-async-promise-executor */\n return new Promise<void>(async (resolve, reject) => {\n if (isNullish(authClient)) {\n reject(\n new SignInInitError(\n 'No client is ready to perform a sign-in. Have you initialized the Satellite?'\n )\n );\n return;\n }\n\n await authClient.login({\n onSuccess: resolve,\n onError: (error?: string) => {\n if (error === ERROR_USER_INTERRUPT) {\n reject(new SignInUserInterruptError(error));\n return;\n }\n\n reject(new SignInError(error));\n },\n maxTimeToLive: options?.maxTimeToLiveInNanoseconds ?? DELEGATION_IDENTITY_EXPIRATION,\n allowPinAuthentication: options?.allowPin ?? ALLOW_PIN_AUTHENTICATION,\n ...(options?.derivationOrigin !== undefined && {\n derivationOrigin: options.derivationOrigin\n }),\n ...this.signInOptions({\n windowed: options?.windowed\n })\n });\n });\n }\n}\n", "import {isNullish, nonNullish} from '@dfinity/utils';\nimport {\n DOCKER_CONTAINER_URL,\n DOCKER_INTERNET_IDENTITY_ID\n} from '../../core/constants/container.constants';\nimport {EnvStore} from '../../core/stores/env.store';\nimport {II_POPUP, INTERNET_COMPUTER_ORG} from '../constants/auth.constants';\nimport type {AuthClientSignInOptions} from '../types/auth-client';\nimport type {InternetIdentityConfig, InternetIdentityDomain} from '../types/internet-identity';\nimport type {Provider} from '../types/provider';\nimport {popupCenter} from '../utils/window.utils';\nimport {AuthClientProvider, type AuthProviderSignInOptions} from './_auth-client.providers';\n\n/**\n * Internet Identity authentication provider.\n * @class InternetIdentityProvider\n * @implements {AuthProvider}\n */\nexport class InternetIdentityProvider extends AuthClientProvider {\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 super();\n\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 override 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 override signInOptions({\n windowed\n }: Pick<AuthClientSignInOptions, '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", "import {NFID_POPUP} from '../constants/auth.constants';\nimport type {AuthClientSignInOptions} from '../types/auth-client';\nimport type {NFIDConfig} from '../types/nfid';\nimport type {Provider} from '../types/provider';\nimport {popupCenter} from '../utils/window.utils';\nimport {AuthClientProvider, type AuthProviderSignInOptions} from './_auth-client.providers';\n\n/**\n * NFID authentication provider.\n * @class NFIDProvider\n * @implements {AuthProvider}\n */\nexport class NFIDProvider extends AuthClientProvider {\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 super();\n\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 override 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 override signInOptions({\n windowed\n }: Pick<AuthClientSignInOptions, '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 type {ReadOptions} from '../types/call-options';\n\n/**\n * Default options for read operations.\n *\n * For backwards compatibility and because most developers probably prioritize speed over\n * additional security when fetching read-only data from the Internet Computer,\n * read operations are performed in an uncertified way by default.\n */\nexport const DEFAULT_READ_OPTIONS: ReadOptions = {certified: false};\n", "import {AnonymousIdentity, type Identity} from '@dfinity/agent';\nimport {nonNullish} from '@dfinity/utils';\nimport {getIdentity as getAuthIdentity} from '../../auth/services/auth.services';\n\nexport const getAnyIdentity = (identity?: Identity): Identity => {\n if (nonNullish(identity)) {\n return identity;\n }\n\n return getAuthIdentity() ?? new AnonymousIdentity();\n};\n", "import {Actor, type ActorConfig, type ActorMethod, type ActorSubclass} from '@dfinity/agent';\nimport type {IDL} from '@dfinity/candid';\nimport type {Principal} from '@dfinity/principal';\nimport {isNullish} from '@dfinity/utils';\nimport type {\n ActorParameters,\n ConsoleParameters,\n MissionControlParameters,\n OrbiterParameters,\n SatelliteParameters\n} from '../types/actor';\nimport {\n idlCertifiedFactoryConsole,\n idlCertifiedFactoryOrbiter,\n idlCertifiedFactorySatellite,\n idlDeprecatedFactoryMissionControlVersion,\n idlDeprecatedFactoryOrbiterVersion,\n idlDeprecatedFactorySatellite,\n idlDeprecatedFactorySatelliteNoScope,\n idlDeprecatedFactorySatelliteVersion,\n idlFactoryConsole,\n idlFactoryMissionControl,\n idlFactoryOrbiter,\n idlFactorySatellite,\n type ConsoleActor,\n type DeprecatedMissionControlVersionActor,\n type DeprecatedOrbiterVersionActor,\n type DeprecatedSatelliteActor,\n type DeprecatedSatelliteNoScopeActor,\n type DeprecatedSatelliteVersionActor,\n type MissionControlActor,\n type OrbiterActor,\n type SatelliteActor\n} from './actor.factory';\nimport {useOrInitAgent} from './agent.api';\n\n/**\n * @deprecated TODO: for backwards compatibility - to be removed\n */\nexport const getDeprecatedSatelliteActor = ({\n satelliteId,\n ...rest\n}: SatelliteParameters): Promise<DeprecatedSatelliteActor> =>\n getActor({\n canisterId: satelliteId,\n ...rest,\n idlFactory: idlDeprecatedFactorySatellite\n });\n\nexport const getSatelliteActor = ({\n satelliteId,\n certified = false,\n ...rest\n}: SatelliteParameters & {certified?: boolean}): Promise<SatelliteActor> =>\n getActor({\n canisterId: satelliteId,\n ...rest,\n idlFactory: certified ? idlCertifiedFactorySatellite : idlFactorySatellite\n });\n\n/**\n * @deprecated TODO: for backwards compatibility - to be removed\n */\nexport const getDeprecatedSatelliteNoScopeActor = ({\n satelliteId,\n ...rest\n}: SatelliteParameters): Promise<DeprecatedSatelliteNoScopeActor> =>\n getActor({\n canisterId: satelliteId,\n ...rest,\n idlFactory: idlDeprecatedFactorySatelliteNoScope\n });\n\n/**\n * @deprecated TODO: for backwards compatibility - to be removed\n */\nexport const getDeprecatedSatelliteVersionActor = ({\n satelliteId,\n ...rest\n}: SatelliteParameters): Promise<DeprecatedSatelliteVersionActor> =>\n getActor({\n canisterId: satelliteId,\n ...rest,\n idlFactory: idlDeprecatedFactorySatelliteVersion\n });\n\nexport const getMissionControlActor = ({\n missionControlId,\n ...rest\n}: MissionControlParameters): Promise<MissionControlActor> =>\n getActor({\n canisterId: missionControlId,\n ...rest,\n idlFactory: idlFactoryMissionControl\n });\n\n/**\n * @deprecated TODO: for backwards compatibility - to be removed\n */\nexport const getDeprecatedMissionControlVersionActor = ({\n missionControlId,\n ...rest\n}: MissionControlParameters): Promise<DeprecatedMissionControlVersionActor> =>\n getActor({\n canisterId: missionControlId,\n ...rest,\n idlFactory: idlDeprecatedFactoryMissionControlVersion\n });\n\nexport const getOrbiterActor = ({\n orbiterId,\n certified = false,\n ...rest\n}: OrbiterParameters & {certified?: boolean}): Promise<OrbiterActor> =>\n getActor({\n canisterId: orbiterId,\n ...rest,\n idlFactory: certified ? idlCertifiedFactoryOrbiter : idlFactoryOrbiter\n });\n\n/**\n * @deprecated TODO: for backwards compatibility - to be removed\n */\nexport const getDeprecatedOrbiterVersionActor = ({\n orbiterId,\n ...rest\n}: OrbiterParameters): Promise<DeprecatedOrbiterVersionActor> =>\n getActor({\n canisterId: orbiterId,\n ...rest,\n idlFactory: idlDeprecatedFactoryOrbiterVersion\n });\n\nexport const getConsoleActor = ({\n consoleId,\n certified = false,\n ...rest\n}: ConsoleParameters & {certified?: boolean}): Promise<ConsoleActor> =>\n getActor({\n canisterId: consoleId,\n ...rest,\n idlFactory: certified ? idlCertifiedFactoryConsole : idlFactoryConsole\n });\n\nexport const getActor = <T>({\n canisterId,\n idlFactory,\n ...rest\n}: ActorParameters & {\n canisterId: Principal | string | undefined;\n idlFactory: IDL.InterfaceFactory;\n}): Promise<T> => {\n if (isNullish(canisterId)) {\n throw new Error('No canister ID provided.');\n }\n\n return createActor({\n canisterId,\n idlFactory,\n ...rest\n });\n};\n\nconst createActor = async <T = Record<string, ActorMethod>>({\n canisterId,\n idlFactory,\n config,\n ...rest\n}: {\n idlFactory: IDL.InterfaceFactory;\n canisterId: Principal | string;\n config?: Pick<ActorConfig, 'callTransform' | 'queryTransform'>;\n} & ActorParameters): Promise<ActorSubclass<T>> => {\n const agent = await useOrInitAgent(rest);\n\n // Creates an actor with using the candid interface and the HttpAgent\n return Actor.createActor(idlFactory, {\n agent,\n canisterId,\n ...(config ?? {})\n });\n};\n", "// @ts-ignore\nexport const idlFactory = ({IDL}) => {\n const MissionControlArgs = IDL.Record({user: IDL.Principal});\n const CyclesThreshold = IDL.Record({\n fund_cycles: IDL.Nat,\n min_cycles: IDL.Nat\n });\n const CyclesMonitoringStrategy = IDL.Variant({\n BelowThreshold: CyclesThreshold\n });\n const CyclesMonitoring = IDL.Record({\n strategy: IDL.Opt(CyclesMonitoringStrategy),\n enabled: IDL.Bool\n });\n const Monitoring = IDL.Record({cycles: IDL.Opt(CyclesMonitoring)});\n const Settings = IDL.Record({monitoring: IDL.Opt(Monitoring)});\n const Orbiter = IDL.Record({\n updated_at: IDL.Nat64,\n orbiter_id: IDL.Principal,\n metadata: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n created_at: IDL.Nat64,\n settings: IDL.Opt(Settings)\n });\n const CreateCanisterConfig = IDL.Record({\n subnet_id: IDL.Opt(IDL.Principal),\n name: IDL.Opt(IDL.Text)\n });\n const Satellite = IDL.Record({\n updated_at: IDL.Nat64,\n metadata: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n created_at: IDL.Nat64,\n satellite_id: IDL.Principal,\n settings: IDL.Opt(Settings)\n });\n const DepositCyclesArgs = IDL.Record({\n cycles: IDL.Nat,\n destination_id: IDL.Principal\n });\n const DepositedCyclesEmailNotification = IDL.Record({\n to: IDL.Opt(IDL.Text),\n enabled: IDL.Bool\n });\n const CyclesMonitoringConfig = IDL.Record({\n notification: IDL.Opt(DepositedCyclesEmailNotification),\n default_strategy: IDL.Opt(CyclesMonitoringStrategy)\n });\n const MonitoringConfig = IDL.Record({\n cycles: IDL.Opt(CyclesMonitoringConfig)\n });\n const Config = IDL.Record({monitoring: IDL.Opt(MonitoringConfig)});\n const GetMonitoringHistory = IDL.Record({\n to: IDL.Opt(IDL.Nat64),\n from: IDL.Opt(IDL.Nat64),\n segment_id: IDL.Principal\n });\n const MonitoringHistoryKey = IDL.Record({\n segment_id: IDL.Principal,\n created_at: IDL.Nat64,\n nonce: IDL.Int32\n });\n const CyclesBalance = IDL.Record({\n timestamp: IDL.Nat64,\n amount: IDL.Nat\n });\n const FundingErrorCode = IDL.Variant({\n BalanceCheckFailed: IDL.Null,\n ObtainCyclesFailed: IDL.Null,\n DepositFailed: IDL.Null,\n InsufficientCycles: IDL.Null,\n Other: IDL.Text\n });\n const FundingFailure = IDL.Record({\n timestamp: IDL.Nat64,\n error_code: FundingErrorCode\n });\n const MonitoringHistoryCycles = IDL.Record({\n deposited_cycles: IDL.Opt(CyclesBalance),\n cycles: CyclesBalance,\n funding_failure: IDL.Opt(FundingFailure)\n });\n const MonitoringHistory = IDL.Record({\n cycles: IDL.Opt(MonitoringHistoryCycles)\n });\n const CyclesMonitoringStatus = IDL.Record({\n monitored_ids: IDL.Vec(IDL.Principal),\n running: IDL.Bool\n });\n const MonitoringStatus = IDL.Record({\n cycles: IDL.Opt(CyclesMonitoringStatus)\n });\n const MissionControlSettings = IDL.Record({\n updated_at: IDL.Nat64,\n created_at: IDL.Nat64,\n monitoring: IDL.Opt(Monitoring)\n });\n const User = IDL.Record({\n updated_at: IDL.Nat64,\n metadata: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n user: IDL.Opt(IDL.Principal),\n created_at: IDL.Nat64,\n config: IDL.Opt(Config)\n });\n const Tokens = IDL.Record({e8s: IDL.Nat64});\n const Timestamp = IDL.Record({timestamp_nanos: IDL.Nat64});\n const TransferArgs = IDL.Record({\n to: IDL.Vec(IDL.Nat8),\n fee: Tokens,\n memo: IDL.Nat64,\n from_subaccount: IDL.Opt(IDL.Vec(IDL.Nat8)),\n created_at_time: IDL.Opt(Timestamp),\n amount: Tokens\n });\n const TransferError = IDL.Variant({\n TxTooOld: IDL.Record({allowed_window_nanos: IDL.Nat64}),\n BadFee: IDL.Record({expected_fee: Tokens}),\n TxDuplicate: IDL.Record({duplicate_of: IDL.Nat64}),\n TxCreatedInFuture: IDL.Null,\n InsufficientFunds: IDL.Record({balance: Tokens})\n });\n const Result = IDL.Variant({Ok: IDL.Nat64, Err: TransferError});\n const Account = IDL.Record({\n owner: IDL.Principal,\n subaccount: IDL.Opt(IDL.Vec(IDL.Nat8))\n });\n const TransferArg = IDL.Record({\n to: Account,\n fee: IDL.Opt(IDL.Nat),\n memo: IDL.Opt(IDL.Vec(IDL.Nat8)),\n from_subaccount: IDL.Opt(IDL.Vec(IDL.Nat8)),\n created_at_time: IDL.Opt(IDL.Nat64),\n amount: IDL.Nat\n });\n const TransferError_1 = IDL.Variant({\n GenericError: IDL.Record({\n message: IDL.Text,\n error_code: IDL.Nat\n }),\n TemporarilyUnavailable: IDL.Null,\n BadBurn: IDL.Record({min_burn_amount: IDL.Nat}),\n Duplicate: IDL.Record({duplicate_of: IDL.Nat}),\n BadFee: IDL.Record({expected_fee: IDL.Nat}),\n CreatedInFuture: IDL.Record({ledger_time: IDL.Nat64}),\n TooOld: IDL.Null,\n InsufficientFunds: IDL.Record({balance: IDL.Nat})\n });\n const Result_1 = IDL.Variant({Ok: IDL.Nat, Err: TransferError_1});\n const ControllerScope = IDL.Variant({\n Write: IDL.Null,\n Admin: IDL.Null,\n Submit: 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 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 SegmentsMonitoringStrategy = IDL.Record({\n ids: IDL.Vec(IDL.Principal),\n strategy: CyclesMonitoringStrategy\n });\n const CyclesMonitoringStartConfig = IDL.Record({\n orbiters_strategy: IDL.Opt(SegmentsMonitoringStrategy),\n mission_control_strategy: IDL.Opt(CyclesMonitoringStrategy),\n satellites_strategy: IDL.Opt(SegmentsMonitoringStrategy)\n });\n const MonitoringStartConfig = IDL.Record({\n cycles_config: IDL.Opt(CyclesMonitoringStartConfig)\n });\n const CyclesMonitoringStopConfig = IDL.Record({\n satellite_ids: IDL.Opt(IDL.Vec(IDL.Principal)),\n try_mission_control: IDL.Opt(IDL.Bool),\n orbiter_ids: IDL.Opt(IDL.Vec(IDL.Principal))\n });\n const MonitoringStopConfig = IDL.Record({\n cycles_config: IDL.Opt(CyclesMonitoringStopConfig)\n });\n return IDL.Service({\n add_mission_control_controllers: IDL.Func([IDL.Vec(IDL.Principal)], [], []),\n add_satellites_controllers: IDL.Func([IDL.Vec(IDL.Principal), IDL.Vec(IDL.Principal)], [], []),\n create_orbiter: IDL.Func([IDL.Opt(IDL.Text)], [Orbiter], []),\n create_orbiter_with_config: IDL.Func([CreateCanisterConfig], [Orbiter], []),\n create_satellite: IDL.Func([IDL.Text], [Satellite], []),\n create_satellite_with_config: IDL.Func([CreateCanisterConfig], [Satellite], []),\n del_mission_control_controllers: IDL.Func([IDL.Vec(IDL.Principal)], [], []),\n del_orbiter: IDL.Func([IDL.Principal, IDL.Nat], [], []),\n del_orbiters_controllers: IDL.Func([IDL.Vec(IDL.Principal), IDL.Vec(IDL.Principal)], [], []),\n del_satellite: IDL.Func([IDL.Principal, IDL.Nat], [], []),\n del_satellites_controllers: IDL.Func([IDL.Vec(IDL.Principal), IDL.Vec(IDL.Principal)], [], []),\n deposit_cycles: IDL.Func([DepositCyclesArgs], [], []),\n get_config: IDL.Func([], [IDL.Opt(Config)], ['query']),\n get_metadata: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))], ['query']),\n get_monitoring_history: IDL.Func(\n [GetMonitoringHistory],\n [IDL.Vec(IDL.Tuple(MonitoringHistoryKey, MonitoringHistory))],\n ['query']\n ),\n get_monitoring_status: IDL.Func([], [MonitoringStatus], ['query']),\n get_settings: IDL.Func([], [IDL.Opt(MissionControlSettings)], ['query']),\n get_user: IDL.Func([], [IDL.Principal], ['query']),\n get_user_data: IDL.Func([], [User], ['query']),\n icp_transfer: IDL.Func([TransferArgs], [Result], []),\n icrc_transfer: IDL.Func([IDL.Principal, TransferArg], [Result_1], []),\n list_mission_control_controllers: IDL.Func(\n [],\n [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))],\n ['query']\n ),\n list_orbiters: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Principal, Orbiter))], ['query']),\n list_satellites: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Principal, Satellite))], ['query']),\n remove_mission_control_controllers: IDL.Func([IDL.Vec(IDL.Principal)], [], []),\n remove_satellites_controllers: IDL.Func(\n [IDL.Vec(IDL.Principal), IDL.Vec(IDL.Principal)],\n [],\n []\n ),\n set_config: IDL.Func([IDL.Opt(Config)], [], []),\n set_metadata: IDL.Func([IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))], [], []),\n set_mission_control_controllers: IDL.Func([IDL.Vec(IDL.Principal), SetController], [], []),\n set_orbiter: IDL.Func([IDL.Principal, IDL.Opt(IDL.Text)], [Orbiter], []),\n set_orbiter_metadata: IDL.Func(\n [IDL.Principal, IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))],\n [Orbiter],\n []\n ),\n set_orbiters_controllers: IDL.Func(\n [IDL.Vec(IDL.Principal), IDL.Vec(IDL.Principal), SetController],\n [],\n []\n ),\n set_satellite: IDL.Func([IDL.Principal, IDL.Opt(IDL.Text)], [Satellite], []),\n set_satellite_metadata: IDL.Func(\n [IDL.Principal, IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))],\n [Satellite],\n []\n ),\n set_satellites_controllers: IDL.Func(\n [IDL.Vec(IDL.Principal), IDL.Vec(IDL.Principal), SetController],\n [],\n []\n ),\n start_monitoring: IDL.Func([], [], []),\n stop_monitoring: IDL.Func([], [], []),\n top_up: IDL.Func([IDL.Principal, Tokens], [], []),\n unset_orbiter: IDL.Func([IDL.Principal], [], []),\n unset_satellite: IDL.Func([IDL.Principal], [], []),\n update_and_start_monitoring: IDL.Func([MonitoringStartConfig], [], []),\n update_and_stop_monitoring: IDL.Func([MonitoringStopConfig], [], [])\n });\n};\n// @ts-ignore\nexport const init = ({IDL}) => {\n const MissionControlArgs = IDL.Record({user: IDL.Principal});\n return [MissionControlArgs];\n};\n", "// @ts-ignore\nexport const idlFactory = ({IDL}) => {\n const SegmentArgs = IDL.Record({controllers: IDL.Vec(IDL.Principal)});\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 Submit: 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 DelSatelliteConfig = IDL.Record({version: IDL.Opt(IDL.Nat64)});\n const DepositCyclesArgs = IDL.Record({\n cycles: IDL.Nat,\n destination_id: IDL.Principal\n });\n const GetAnalytics = IDL.Record({\n to: IDL.Opt(IDL.Nat64),\n from: IDL.Opt(IDL.Nat64),\n satellite_id: IDL.Opt(IDL.Principal)\n });\n const AnalyticKey = IDL.Record({\n key: IDL.Text,\n collected_at: IDL.Nat64\n });\n const PageViewClient = IDL.Record({\n os: IDL.Text,\n device: IDL.Opt(IDL.Text),\n browser: IDL.Text\n });\n const PageViewCampaign = IDL.Record({\n utm_content: IDL.Opt(IDL.Text),\n utm_medium: IDL.Opt(IDL.Text),\n utm_source: IDL.Text,\n utm_term: IDL.Opt(IDL.Text),\n utm_campaign: IDL.Opt(IDL.Text)\n });\n const PageViewDevice = IDL.Record({\n inner_height: IDL.Nat16,\n screen_height: IDL.Opt(IDL.Nat16),\n screen_width: IDL.Opt(IDL.Nat16),\n inner_width: IDL.Nat16\n });\n const PageView = IDL.Record({\n client: IDL.Opt(PageViewClient),\n title: IDL.Text,\n updated_at: IDL.Nat64,\n referrer: IDL.Opt(IDL.Text),\n time_zone: IDL.Text,\n session_id: IDL.Text,\n campaign: IDL.Opt(PageViewCampaign),\n href: IDL.Text,\n created_at: IDL.Nat64,\n satellite_id: IDL.Principal,\n device: PageViewDevice,\n version: IDL.Opt(IDL.Nat64),\n user_agent: IDL.Opt(IDL.Text)\n });\n const AnalyticsBrowsersPageViews = IDL.Record({\n safari: IDL.Float64,\n opera: IDL.Float64,\n others: IDL.Float64,\n firefox: IDL.Float64,\n chrome: IDL.Float64\n });\n const AnalyticsOperatingSystemsPageViews = IDL.Record({\n ios: IDL.Float64,\n macos: IDL.Float64,\n others: IDL.Float64,\n linux: IDL.Float64,\n android: IDL.Float64,\n windows: IDL.Float64\n });\n const AnalyticsDevicesPageViews = IDL.Record({\n desktop: IDL.Float64,\n laptop: IDL.Opt(IDL.Float64),\n others: IDL.Float64,\n tablet: IDL.Opt(IDL.Float64),\n mobile: IDL.Float64\n });\n const AnalyticsClientsPageViews = IDL.Record({\n browsers: AnalyticsBrowsersPageViews,\n operating_systems: IDL.Opt(AnalyticsOperatingSystemsPageViews),\n devices: AnalyticsDevicesPageViews\n });\n const CalendarDate = IDL.Record({\n day: IDL.Nat8,\n month: IDL.Nat8,\n year: IDL.Int32\n });\n const AnalyticsMetricsPageViews = IDL.Record({\n bounce_rate: IDL.Float64,\n average_page_views_per_session: IDL.Float64,\n daily_total_page_views: IDL.Vec(IDL.Tuple(CalendarDate, IDL.Nat32)),\n total_page_views: IDL.Nat32,\n unique_page_views: IDL.Nat64,\n unique_sessions: IDL.Nat64\n });\n const AnalyticsTop10PageViews = IDL.Record({\n referrers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32)),\n pages: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32)),\n utm_campaigns: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32))),\n utm_sources: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32))),\n time_zones: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32)))\n });\n const NavigationType = IDL.Variant({\n Navigate: IDL.Null,\n Restore: IDL.Null,\n Reload: IDL.Null,\n BackForward: IDL.Null,\n BackForwardCache: IDL.Null,\n Prerender: IDL.Null\n });\n const WebVitalsMetric = IDL.Record({\n id: IDL.Text,\n value: IDL.Float64,\n navigation_type: IDL.Opt(NavigationType),\n delta: IDL.Float64\n });\n const PerformanceData = IDL.Variant({WebVitalsMetric: WebVitalsMetric});\n const PerformanceMetricName = IDL.Variant({\n CLS: IDL.Null,\n FCP: IDL.Null,\n INP: IDL.Null,\n LCP: IDL.Null,\n TTFB: IDL.Null\n });\n const PerformanceMetric = IDL.Record({\n updated_at: IDL.Nat64,\n session_id: IDL.Text,\n data: PerformanceData,\n href: IDL.Text,\n metric_name: PerformanceMetricName,\n created_at: IDL.Nat64,\n satellite_id: IDL.Principal,\n version: IDL.Opt(IDL.Nat64)\n });\n const AnalyticsWebVitalsPageMetrics = IDL.Record({\n cls: IDL.Opt(IDL.Float64),\n fcp: IDL.Opt(IDL.Float64),\n inp: IDL.Opt(IDL.Float64),\n lcp: IDL.Opt(IDL.Float64),\n ttfb: IDL.Opt(IDL.Float64)\n });\n const AnalyticsWebVitalsPerformanceMetrics = IDL.Record({\n overall: AnalyticsWebVitalsPageMetrics,\n pages: IDL.Vec(IDL.Tuple(IDL.Text, AnalyticsWebVitalsPageMetrics))\n });\n const TrackEvent = IDL.Record({\n updated_at: IDL.Nat64,\n session_id: IDL.Text,\n metadata: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))),\n name: IDL.Text,\n created_at: IDL.Nat64,\n satellite_id: IDL.Principal,\n version: IDL.Opt(IDL.Nat64)\n });\n const AnalyticsTrackEvents = IDL.Record({\n total: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32))\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 HttpResponse = IDL.Record({\n body: IDL.Vec(IDL.Nat8),\n headers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n upgrade: IDL.Opt(IDL.Bool),\n status_code: IDL.Nat16\n });\n const OrbiterSatelliteFeatures = IDL.Record({\n performance_metrics: IDL.Bool,\n track_events: IDL.Bool,\n page_views: IDL.Bool\n });\n const OrbiterSatelliteConfig = IDL.Record({\n updated_at: IDL.Nat64,\n features: IDL.Opt(OrbiterSatelliteFeatures),\n restricted_origin: IDL.Opt(IDL.Text),\n created_at: IDL.Nat64,\n version: IDL.Opt(IDL.Nat64)\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 SetPageView = IDL.Record({\n client: IDL.Opt(PageViewClient),\n title: IDL.Text,\n updated_at: IDL.Opt(IDL.Nat64),\n referrer: IDL.Opt(IDL.Text),\n time_zone: IDL.Text,\n session_id: IDL.Text,\n campaign: IDL.Opt(PageViewCampaign),\n href: IDL.Text,\n satellite_id: IDL.Principal,\n device: PageViewDevice,\n version: IDL.Opt(IDL.Nat64),\n user_agent: IDL.Opt(IDL.Text)\n });\n const Result = IDL.Variant({Ok: PageView, Err: IDL.Text});\n const Result_1 = IDL.Variant({\n Ok: IDL.Null,\n Err: IDL.Vec(IDL.Tuple(AnalyticKey, IDL.Text))\n });\n const SetPerformanceMetric = IDL.Record({\n session_id: IDL.Text,\n data: PerformanceData,\n href: IDL.Text,\n metric_name: PerformanceMetricName,\n satellite_id: IDL.Principal,\n version: IDL.Opt(IDL.Nat64),\n user_agent: IDL.Opt(IDL.Text)\n });\n const Result_2 = IDL.Variant({Ok: PerformanceMetric, Err: IDL.Text});\n const SetSatelliteConfig = IDL.Record({\n features: IDL.Opt(OrbiterSatelliteFeatures),\n restricted_origin: IDL.Opt(IDL.Text),\n version: IDL.Opt(IDL.Nat64)\n });\n const SetTrackEvent = IDL.Record({\n updated_at: IDL.Opt(IDL.Nat64),\n session_id: IDL.Text,\n metadata: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))),\n name: IDL.Text,\n satellite_id: IDL.Principal,\n version: IDL.Opt(IDL.Nat64),\n user_agent: IDL.Opt(IDL.Text)\n });\n const Result_3 = IDL.Variant({Ok: TrackEvent, Err: IDL.Text});\n return IDL.Service({\n del_controllers: IDL.Func(\n [DeleteControllersArgs],\n [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))],\n []\n ),\n del_satellite_config: IDL.Func([IDL.Principal, DelSatelliteConfig], [], []),\n deposit_cycles: IDL.Func([DepositCyclesArgs], [], []),\n get_page_views: IDL.Func(\n [GetAnalytics],\n [IDL.Vec(IDL.Tuple(AnalyticKey, PageView))],\n ['query']\n ),\n get_page_views_analytics_clients: IDL.Func(\n [GetAnalytics],\n [AnalyticsClientsPageViews],\n ['query']\n ),\n get_page_views_analytics_metrics: IDL.Func(\n [GetAnalytics],\n [AnalyticsMetricsPageViews],\n ['query']\n ),\n get_page_views_analytics_top_10: IDL.Func([GetAnalytics], [AnalyticsTop10PageViews], ['query']),\n get_performance_metrics: IDL.Func(\n [GetAnalytics],\n [IDL.Vec(IDL.Tuple(AnalyticKey, PerformanceMetric))],\n ['query']\n ),\n get_performance_metrics_analytics_web_vitals: IDL.Func(\n [GetAnalytics],\n [AnalyticsWebVitalsPerformanceMetrics],\n ['query']\n ),\n get_track_events: IDL.Func(\n [GetAnalytics],\n [IDL.Vec(IDL.Tuple(AnalyticKey, TrackEvent))],\n ['query']\n ),\n get_track_events_analytics: IDL.Func([GetAnalytics], [AnalyticsTrackEvents], ['query']),\n http_request: IDL.Func([HttpRequest], [HttpResponse], ['query']),\n http_request_update: IDL.Func([HttpRequest], [HttpResponse], []),\n list_controllers: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))], ['query']),\n list_satellite_configs: IDL.Func(\n [],\n [IDL.Vec(IDL.Tuple(IDL.Principal, OrbiterSatelliteConfig))],\n ['query']\n ),\n memory_size: IDL.Func([], [MemorySize], ['query']),\n set_controllers: IDL.Func(\n [SetControllersArgs],\n [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))],\n []\n ),\n set_page_view: IDL.Func([AnalyticKey, SetPageView], [Result], []),\n set_page_views: IDL.Func([IDL.Vec(IDL.Tuple(AnalyticKey, SetPageView))], [Result_1], []),\n set_performance_metric: IDL.Func([AnalyticKey, SetPerformanceMetric], [Result_2], []),\n set_performance_metrics: IDL.Func(\n [IDL.Vec(IDL.Tuple(AnalyticKey, SetPerformanceMetric))],\n [Result_1],\n []\n ),\n set_satellite_configs: IDL.Func(\n [IDL.Vec(IDL.Tuple(IDL.Principal, SetSatelliteConfig))],\n [IDL.Vec(IDL.Tuple(IDL.Principal, OrbiterSatelliteConfig))],\n []\n ),\n set_track_event: IDL.Func([AnalyticKey, SetTrackEvent], [Result_3], []),\n set_track_events: IDL.Func([IDL.Vec(IDL.Tuple(AnalyticKey, SetTrackEvent))], [Result_1], [])\n });\n};\n// @ts-ignore\nexport const init = ({IDL}) => {\n const SegmentArgs = IDL.Record({controllers: IDL.Vec(IDL.Principal)});\n return [SegmentArgs];\n};\n", "// @ts-ignore\nexport const idlFactory = ({IDL}) => {\n const SegmentArgs = IDL.Record({controllers: IDL.Vec(IDL.Principal)});\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 Submit: 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 DelSatelliteConfig = IDL.Record({version: IDL.Opt(IDL.Nat64)});\n const DepositCyclesArgs = IDL.Record({\n cycles: IDL.Nat,\n destination_id: IDL.Principal\n });\n const GetAnalytics = IDL.Record({\n to: IDL.Opt(IDL.Nat64),\n from: IDL.Opt(IDL.Nat64),\n satellite_id: IDL.Opt(IDL.Principal)\n });\n const AnalyticKey = IDL.Record({\n key: IDL.Text,\n collected_at: IDL.Nat64\n });\n const PageViewClient = IDL.Record({\n os: IDL.Text,\n device: IDL.Opt(IDL.Text),\n browser: IDL.Text\n });\n const PageViewCampaign = IDL.Record({\n utm_content: IDL.Opt(IDL.Text),\n utm_medium: IDL.Opt(IDL.Text),\n utm_source: IDL.Text,\n utm_term: IDL.Opt(IDL.Text),\n utm_campaign: IDL.Opt(IDL.Text)\n });\n const PageViewDevice = IDL.Record({\n inner_height: IDL.Nat16,\n screen_height: IDL.Opt(IDL.Nat16),\n screen_width: IDL.Opt(IDL.Nat16),\n inner_width: IDL.Nat16\n });\n const PageView = IDL.Record({\n client: IDL.Opt(PageViewClient),\n title: IDL.Text,\n updated_at: IDL.Nat64,\n referrer: IDL.Opt(IDL.Text),\n time_zone: IDL.Text,\n session_id: IDL.Text,\n campaign: IDL.Opt(PageViewCampaign),\n href: IDL.Text,\n created_at: IDL.Nat64,\n satellite_id: IDL.Principal,\n device: PageViewDevice,\n version: IDL.Opt(IDL.Nat64),\n user_agent: IDL.Opt(IDL.Text)\n });\n const AnalyticsBrowsersPageViews = IDL.Record({\n safari: IDL.Float64,\n opera: IDL.Float64,\n others: IDL.Float64,\n firefox: IDL.Float64,\n chrome: IDL.Float64\n });\n const AnalyticsOperatingSystemsPageViews = IDL.Record({\n ios: IDL.Float64,\n macos: IDL.Float64,\n others: IDL.Float64,\n linux: IDL.Float64,\n android: IDL.Float64,\n windows: IDL.Float64\n });\n const AnalyticsDevicesPageViews = IDL.Record({\n desktop: IDL.Float64,\n laptop: IDL.Opt(IDL.Float64),\n others: IDL.Float64,\n tablet: IDL.Opt(IDL.Float64),\n mobile: IDL.Float64\n });\n const AnalyticsClientsPageViews = IDL.Record({\n browsers: AnalyticsBrowsersPageViews,\n operating_systems: IDL.Opt(AnalyticsOperatingSystemsPageViews),\n devices: AnalyticsDevicesPageViews\n });\n const CalendarDate = IDL.Record({\n day: IDL.Nat8,\n month: IDL.Nat8,\n year: IDL.Int32\n });\n const AnalyticsMetricsPageViews = IDL.Record({\n bounce_rate: IDL.Float64,\n average_page_views_per_session: IDL.Float64,\n daily_total_page_views: IDL.Vec(IDL.Tuple(CalendarDate, IDL.Nat32)),\n total_page_views: IDL.Nat32,\n unique_page_views: IDL.Nat64,\n unique_sessions: IDL.Nat64\n });\n const AnalyticsTop10PageViews = IDL.Record({\n referrers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32)),\n pages: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32)),\n utm_campaigns: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32))),\n utm_sources: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32))),\n time_zones: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32)))\n });\n const NavigationType = IDL.Variant({\n Navigate: IDL.Null,\n Restore: IDL.Null,\n Reload: IDL.Null,\n BackForward: IDL.Null,\n BackForwardCache: IDL.Null,\n Prerender: IDL.Null\n });\n const WebVitalsMetric = IDL.Record({\n id: IDL.Text,\n value: IDL.Float64,\n navigation_type: IDL.Opt(NavigationType),\n delta: IDL.Float64\n });\n const PerformanceData = IDL.Variant({WebVitalsMetric: WebVitalsMetric});\n const PerformanceMetricName = IDL.Variant({\n CLS: IDL.Null,\n FCP: IDL.Null,\n INP: IDL.Null,\n LCP: IDL.Null,\n TTFB: IDL.Null\n });\n const PerformanceMetric = IDL.Record({\n updated_at: IDL.Nat64,\n session_id: IDL.Text,\n data: PerformanceData,\n href: IDL.Text,\n metric_name: PerformanceMetricName,\n created_at: IDL.Nat64,\n satellite_id: IDL.Principal,\n version: IDL.Opt(IDL.Nat64)\n });\n const AnalyticsWebVitalsPageMetrics = IDL.Record({\n cls: IDL.Opt(IDL.Float64),\n fcp: IDL.Opt(IDL.Float64),\n inp: IDL.Opt(IDL.Float64),\n lcp: IDL.Opt(IDL.Float64),\n ttfb: IDL.Opt(IDL.Float64)\n });\n const AnalyticsWebVitalsPerformanceMetrics = IDL.Record({\n overall: AnalyticsWebVitalsPageMetrics,\n pages: IDL.Vec(IDL.Tuple(IDL.Text, AnalyticsWebVitalsPageMetrics))\n });\n const TrackEvent = IDL.Record({\n updated_at: IDL.Nat64,\n session_id: IDL.Text,\n metadata: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))),\n name: IDL.Text,\n created_at: IDL.Nat64,\n satellite_id: IDL.Principal,\n version: IDL.Opt(IDL.Nat64)\n });\n const AnalyticsTrackEvents = IDL.Record({\n total: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32))\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 HttpResponse = IDL.Record({\n body: IDL.Vec(IDL.Nat8),\n headers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n upgrade: IDL.Opt(IDL.Bool),\n status_code: IDL.Nat16\n });\n const OrbiterSatelliteFeatures = IDL.Record({\n performance_metrics: IDL.Bool,\n track_events: IDL.Bool,\n page_views: IDL.Bool\n });\n const OrbiterSatelliteConfig = IDL.Record({\n updated_at: IDL.Nat64,\n features: IDL.Opt(OrbiterSatelliteFeatures),\n restricted_origin: IDL.Opt(IDL.Text),\n created_at: IDL.Nat64,\n version: IDL.Opt(IDL.Nat64)\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 SetPageView = IDL.Record({\n client: IDL.Opt(PageViewClient),\n title: IDL.Text,\n updated_at: IDL.Opt(IDL.Nat64),\n referrer: IDL.Opt(IDL.Text),\n time_zone: IDL.Text,\n session_id: IDL.Text,\n campaign: IDL.Opt(PageViewCampaign),\n href: IDL.Text,\n satellite_id: IDL.Principal,\n device: PageViewDevice,\n version: IDL.Opt(IDL.Nat64),\n user_agent: IDL.Opt(IDL.Text)\n });\n const Result = IDL.Variant({Ok: PageView, Err: IDL.Text});\n const Result_1 = IDL.Variant({\n Ok: IDL.Null,\n Err: IDL.Vec(IDL.Tuple(AnalyticKey, IDL.Text))\n });\n const SetPerformanceMetric = IDL.Record({\n session_id: IDL.Text,\n data: PerformanceData,\n href: IDL.Text,\n metric_name: PerformanceMetricName,\n satellite_id: IDL.Principal,\n version: IDL.Opt(IDL.Nat64),\n user_agent: IDL.Opt(IDL.Text)\n });\n const Result_2 = IDL.Variant({Ok: PerformanceMetric, Err: IDL.Text});\n const SetSatelliteConfig = IDL.Record({\n features: IDL.Opt(OrbiterSatelliteFeatures),\n restricted_origin: IDL.Opt(IDL.Text),\n version: IDL.Opt(IDL.Nat64)\n });\n const SetTrackEvent = IDL.Record({\n updated_at: IDL.Opt(IDL.Nat64),\n session_id: IDL.Text,\n metadata: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))),\n name: IDL.Text,\n satellite_id: IDL.Principal,\n version: IDL.Opt(IDL.Nat64),\n user_agent: IDL.Opt(IDL.Text)\n });\n const Result_3 = IDL.Variant({Ok: TrackEvent, Err: IDL.Text});\n return IDL.Service({\n del_controllers: IDL.Func(\n [DeleteControllersArgs],\n [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))],\n []\n ),\n del_satellite_config: IDL.Func([IDL.Principal, DelSatelliteConfig], [], []),\n deposit_cycles: IDL.Func([DepositCyclesArgs], [], []),\n get_page_views: IDL.Func([GetAnalytics], [IDL.Vec(IDL.Tuple(AnalyticKey, PageView))], []),\n get_page_views_analytics_clients: IDL.Func([GetAnalytics], [AnalyticsClientsPageViews], []),\n get_page_views_analytics_metrics: IDL.Func([GetAnalytics], [AnalyticsMetricsPageViews], []),\n get_page_views_analytics_top_10: IDL.Func([GetAnalytics], [AnalyticsTop10PageViews], []),\n get_performance_metrics: IDL.Func(\n [GetAnalytics],\n [IDL.Vec(IDL.Tuple(AnalyticKey, PerformanceMetric))],\n []\n ),\n get_performance_metrics_analytics_web_vitals: IDL.Func(\n [GetAnalytics],\n [AnalyticsWebVitalsPerformanceMetrics],\n []\n ),\n get_track_events: IDL.Func([GetAnalytics], [IDL.Vec(IDL.Tuple(AnalyticKey, TrackEvent))], []),\n get_track_events_analytics: IDL.Func([GetAnalytics], [AnalyticsTrackEvents], []),\n http_request: IDL.Func([HttpRequest], [HttpResponse], []),\n http_request_update: IDL.Func([HttpRequest], [HttpResponse], []),\n list_controllers: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))], []),\n list_satellite_configs: IDL.Func(\n [],\n [IDL.Vec(IDL.Tuple(IDL.Principal, OrbiterSatelliteConfig))],\n []\n ),\n memory_size: IDL.Func([], [MemorySize], []),\n set_controllers: IDL.Func(\n [SetControllersArgs],\n [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))],\n []\n ),\n set_page_view: IDL.Func([AnalyticKey, SetPageView], [Result], []),\n set_page_views: IDL.Func([IDL.Vec(IDL.Tuple(AnalyticKey, SetPageView))], [Result_1], []),\n set_performance_metric: IDL.Func([AnalyticKey, SetPerformanceMetric], [Result_2], []),\n set_performance_metrics: IDL.Func(\n [IDL.Vec(IDL.Tuple(AnalyticKey, SetPerformanceMetric))],\n [Result_1],\n []\n ),\n set_satellite_configs: IDL.Func(\n [IDL.Vec(IDL.Tuple(IDL.Principal, SetSatelliteConfig))],\n [IDL.Vec(IDL.Tuple(IDL.Principal, OrbiterSatelliteConfig))],\n []\n ),\n set_track_event: IDL.Func([AnalyticKey, SetTrackEvent], [Result_3], []),\n set_track_events: IDL.Func([IDL.Vec(IDL.Tuple(AnalyticKey, SetTrackEvent))], [Result_1], [])\n });\n};\n// @ts-ignore\nexport const init = ({IDL}) => {\n const SegmentArgs = IDL.Record({controllers: IDL.Vec(IDL.Principal)});\n return [SegmentArgs];\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 DeleteControllersArgs = IDL.Record({\n controllers: IDL.Vec(IDL.Principal)\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 expires_at: IDL.Opt(IDL.Nat64)\n });\n const DelDoc = IDL.Record({updated_at: IDL.Opt(IDL.Nat64)});\n const StorageConfig = IDL.Record({\n headers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))))\n });\n const Config = IDL.Record({storage: StorageConfig});\n const Doc = IDL.Record({\n updated_at: IDL.Nat64,\n owner: IDL.Principal,\n data: IDL.Vec(IDL.Nat8),\n created_at: 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 });\n const StreamingCallbackToken = IDL.Record({\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([], [], [])\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 encoding_type: IDL.Opt(IDL.Text),\n full_path: IDL.Text\n });\n const InitUploadResult = IDL.Record({batch_id: IDL.Nat});\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 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(IDL.Text),\n paginate: IDL.Opt(ListPaginate)\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 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 });\n const ListResults = IDL.Record({\n matches_length: IDL.Nat64,\n length: IDL.Nat64,\n items: IDL.Vec(IDL.Tuple(IDL.Text, AssetNoContent))\n });\n const CustomDomain = IDL.Record({\n updated_at: IDL.Nat64,\n created_at: IDL.Nat64,\n bn_id: IDL.Opt(IDL.Text)\n });\n const ListResults_1 = IDL.Record({\n matches_length: IDL.Nat64,\n length: IDL.Nat64,\n items: IDL.Vec(IDL.Tuple(IDL.Text, Doc))\n });\n const RulesType = IDL.Variant({Db: IDL.Null, Storage: IDL.Null});\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 updated_at: IDL.Nat64,\n max_size: IDL.Opt(IDL.Nat),\n read: Permission,\n created_at: IDL.Nat64,\n write: Permission\n });\n const SetController = IDL.Record({\n metadata: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\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 updated_at: IDL.Opt(IDL.Nat64),\n data: IDL.Vec(IDL.Nat8)\n });\n const SetRule = IDL.Record({\n updated_at: IDL.Opt(IDL.Nat64),\n max_size: IDL.Opt(IDL.Nat),\n read: Permission,\n write: Permission\n });\n const Chunk = IDL.Record({\n content: IDL.Vec(IDL.Nat8),\n batch_id: IDL.Nat\n });\n const UploadChunk = IDL.Record({chunk_id: IDL.Nat});\n return IDL.Service({\n commit_asset_upload: IDL.Func([CommitBatch], [], []),\n del_asset: IDL.Func([IDL.Text, IDL.Text], [], []),\n del_assets: IDL.Func([IDL.Opt(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 get_config: IDL.Func([], [Config], []),\n get_doc: IDL.Func([IDL.Text, IDL.Text], [IDL.Opt(Doc)], ['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.Opt(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 set_config: IDL.Func([Config], [], []),\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_doc: IDL.Func([IDL.Text, IDL.Text, SetDoc], [Doc], []),\n set_rule: IDL.Func([RulesType, IDL.Text, SetRule], [], []),\n upload_asset_chunk: IDL.Func([Chunk], [UploadChunk], []),\n version: IDL.Func([], [IDL.Text], ['query'])\n });\n};\n// @ts-ignore\nexport const init = ({IDL}) => {\n return [];\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 CollectionType = 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 external_alternative_origins: IDL.Opt(IDL.Vec(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 Memory = IDL.Variant({Heap: IDL.Null, Stable: IDL.Null});\n const Permission = IDL.Variant({\n Controllers: IDL.Null,\n Private: IDL.Null,\n Public: IDL.Null,\n Managed: IDL.Null\n });\n const RateConfig = IDL.Record({\n max_tokens: IDL.Nat64,\n time_per_token_ns: IDL.Nat64\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 rate_config: IDL.Opt(RateConfig),\n write: Permission,\n max_changes_per_user: IDL.Opt(IDL.Nat32)\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 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 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 rate_config: IDL.Opt(RateConfig),\n write: Permission,\n max_changes_per_user: IDL.Opt(IDL.Nat32)\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_filtered_assets: IDL.Func([IDL.Text, ListParams], [], []),\n del_filtered_docs: IDL.Func([IDL.Text, ListParams], [], []),\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([CollectionType, 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_rule: IDL.Func([CollectionType, IDL.Text], [IDL.Opt(Rule)], ['query']),\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([CollectionType], [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([CollectionType, IDL.Text, SetRule], [Rule], []),\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", "// @ts-ignore\nexport const idlFactory = ({IDL}) => {\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 DelSatelliteConfig = IDL.Record({version: IDL.Opt(IDL.Nat64)});\n const DepositCyclesArgs = IDL.Record({\n cycles: IDL.Nat,\n destination_id: IDL.Principal\n });\n const GetAnalytics = IDL.Record({\n to: IDL.Opt(IDL.Nat64),\n from: IDL.Opt(IDL.Nat64),\n satellite_id: IDL.Opt(IDL.Principal)\n });\n const AnalyticKey = IDL.Record({\n key: IDL.Text,\n collected_at: IDL.Nat64\n });\n const PageViewDevice = IDL.Record({\n inner_height: IDL.Nat16,\n inner_width: IDL.Nat16\n });\n const PageView = IDL.Record({\n title: IDL.Text,\n updated_at: IDL.Nat64,\n referrer: IDL.Opt(IDL.Text),\n time_zone: IDL.Text,\n session_id: IDL.Text,\n href: IDL.Text,\n created_at: IDL.Nat64,\n satellite_id: IDL.Principal,\n device: PageViewDevice,\n version: IDL.Opt(IDL.Nat64),\n user_agent: IDL.Opt(IDL.Text)\n });\n const AnalyticsBrowsersPageViews = IDL.Record({\n safari: IDL.Float64,\n opera: IDL.Float64,\n others: IDL.Float64,\n firefox: IDL.Float64,\n chrome: IDL.Float64\n });\n const AnalyticsDevicesPageViews = IDL.Record({\n desktop: IDL.Float64,\n others: IDL.Float64,\n mobile: IDL.Float64\n });\n const AnalyticsClientsPageViews = IDL.Record({\n browsers: AnalyticsBrowsersPageViews,\n devices: AnalyticsDevicesPageViews\n });\n const CalendarDate = IDL.Record({\n day: IDL.Nat8,\n month: IDL.Nat8,\n year: IDL.Int32\n });\n const AnalyticsMetricsPageViews = IDL.Record({\n bounce_rate: IDL.Float64,\n average_page_views_per_session: IDL.Float64,\n daily_total_page_views: IDL.Vec(IDL.Tuple(CalendarDate, IDL.Nat32)),\n total_page_views: IDL.Nat32,\n unique_page_views: IDL.Nat64,\n unique_sessions: IDL.Nat64\n });\n const AnalyticsTop10PageViews = IDL.Record({\n referrers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32)),\n pages: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32))\n });\n const NavigationType = IDL.Variant({\n Navigate: IDL.Null,\n Restore: IDL.Null,\n Reload: IDL.Null,\n BackForward: IDL.Null,\n BackForwardCache: IDL.Null,\n Prerender: IDL.Null\n });\n const WebVitalsMetric = IDL.Record({\n id: IDL.Text,\n value: IDL.Float64,\n navigation_type: IDL.Opt(NavigationType),\n delta: IDL.Float64\n });\n const PerformanceData = IDL.Variant({WebVitalsMetric: WebVitalsMetric});\n const PerformanceMetricName = IDL.Variant({\n CLS: IDL.Null,\n FCP: IDL.Null,\n INP: IDL.Null,\n LCP: IDL.Null,\n TTFB: IDL.Null\n });\n const PerformanceMetric = IDL.Record({\n updated_at: IDL.Nat64,\n session_id: IDL.Text,\n data: PerformanceData,\n href: IDL.Text,\n metric_name: PerformanceMetricName,\n created_at: IDL.Nat64,\n satellite_id: IDL.Principal,\n version: IDL.Opt(IDL.Nat64)\n });\n const AnalyticsWebVitalsPageMetrics = IDL.Record({\n cls: IDL.Opt(IDL.Float64),\n fcp: IDL.Opt(IDL.Float64),\n inp: IDL.Opt(IDL.Float64),\n lcp: IDL.Opt(IDL.Float64),\n ttfb: IDL.Opt(IDL.Float64)\n });\n const AnalyticsWebVitalsPerformanceMetrics = IDL.Record({\n overall: AnalyticsWebVitalsPageMetrics,\n pages: IDL.Vec(IDL.Tuple(IDL.Text, AnalyticsWebVitalsPageMetrics))\n });\n const TrackEvent = IDL.Record({\n updated_at: IDL.Nat64,\n session_id: IDL.Text,\n metadata: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))),\n name: IDL.Text,\n created_at: IDL.Nat64,\n satellite_id: IDL.Principal,\n version: IDL.Opt(IDL.Nat64)\n });\n const AnalyticsTrackEvents = IDL.Record({\n total: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat32))\n });\n const OrbiterSatelliteFeatures = IDL.Record({\n performance_metrics: IDL.Bool,\n track_events: IDL.Bool,\n page_views: IDL.Bool\n });\n const OrbiterSatelliteConfig = IDL.Record({\n updated_at: IDL.Nat64,\n features: IDL.Opt(OrbiterSatelliteFeatures),\n created_at: IDL.Nat64,\n version: IDL.Opt(IDL.Nat64)\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 SetPageView = IDL.Record({\n title: IDL.Text,\n updated_at: IDL.Opt(IDL.Nat64),\n referrer: IDL.Opt(IDL.Text),\n time_zone: IDL.Text,\n session_id: IDL.Text,\n href: IDL.Text,\n satellite_id: IDL.Principal,\n device: PageViewDevice,\n version: IDL.Opt(IDL.Nat64),\n user_agent: IDL.Opt(IDL.Text)\n });\n const Result = IDL.Variant({Ok: PageView, Err: IDL.Text});\n const Result_1 = IDL.Variant({\n Ok: IDL.Null,\n Err: IDL.Vec(IDL.Tuple(AnalyticKey, IDL.Text))\n });\n const SetPerformanceMetric = IDL.Record({\n session_id: IDL.Text,\n data: PerformanceData,\n href: IDL.Text,\n metric_name: PerformanceMetricName,\n satellite_id: IDL.Principal,\n version: IDL.Opt(IDL.Nat64),\n user_agent: IDL.Opt(IDL.Text)\n });\n const Result_2 = IDL.Variant({Ok: PerformanceMetric, Err: IDL.Text});\n const SetSatelliteConfig = IDL.Record({\n features: IDL.Opt(OrbiterSatelliteFeatures),\n version: IDL.Opt(IDL.Nat64)\n });\n const SetTrackEvent = IDL.Record({\n updated_at: IDL.Opt(IDL.Nat64),\n session_id: IDL.Text,\n metadata: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))),\n name: IDL.Text,\n satellite_id: IDL.Principal,\n version: IDL.Opt(IDL.Nat64),\n user_agent: IDL.Opt(IDL.Text)\n });\n const Result_3 = IDL.Variant({Ok: TrackEvent, Err: IDL.Text});\n return IDL.Service({\n del_controllers: IDL.Func(\n [DeleteControllersArgs],\n [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))],\n []\n ),\n del_satellite_config: IDL.Func([IDL.Principal, DelSatelliteConfig], [], []),\n deposit_cycles: IDL.Func([DepositCyclesArgs], [], []),\n get_page_views: IDL.Func(\n [GetAnalytics],\n [IDL.Vec(IDL.Tuple(AnalyticKey, PageView))],\n ['query']\n ),\n get_page_views_analytics_clients: IDL.Func(\n [GetAnalytics],\n [AnalyticsClientsPageViews],\n ['query']\n ),\n get_page_views_analytics_metrics: IDL.Func(\n [GetAnalytics],\n [AnalyticsMetricsPageViews],\n ['query']\n ),\n get_page_views_analytics_top_10: IDL.Func([GetAnalytics], [AnalyticsTop10PageViews], ['query']),\n get_performance_metrics: IDL.Func(\n [GetAnalytics],\n [IDL.Vec(IDL.Tuple(AnalyticKey, PerformanceMetric))],\n ['query']\n ),\n get_performance_metrics_analytics_web_vitals: IDL.Func(\n [GetAnalytics],\n [AnalyticsWebVitalsPerformanceMetrics],\n ['query']\n ),\n get_track_events: IDL.Func(\n [GetAnalytics],\n [IDL.Vec(IDL.Tuple(AnalyticKey, TrackEvent))],\n ['query']\n ),\n get_track_events_analytics: IDL.Func([GetAnalytics], [AnalyticsTrackEvents], ['query']),\n list_controllers: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))], ['query']),\n list_satellite_configs: IDL.Func(\n [],\n [IDL.Vec(IDL.Tuple(IDL.Principal, OrbiterSatelliteConfig))],\n ['query']\n ),\n memory_size: IDL.Func([], [MemorySize], ['query']),\n set_controllers: IDL.Func(\n [SetControllersArgs],\n [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))],\n []\n ),\n set_page_view: IDL.Func([AnalyticKey, SetPageView], [Result], []),\n set_page_views: IDL.Func([IDL.Vec(IDL.Tuple(AnalyticKey, SetPageView))], [Result_1], []),\n set_performance_metric: IDL.Func([AnalyticKey, SetPerformanceMetric], [Result_2], []),\n set_performance_metrics: IDL.Func(\n [IDL.Vec(IDL.Tuple(AnalyticKey, SetPerformanceMetric))],\n [Result_1],\n []\n ),\n set_satellite_configs: IDL.Func(\n [IDL.Vec(IDL.Tuple(IDL.Principal, SetSatelliteConfig))],\n [IDL.Vec(IDL.Tuple(IDL.Principal, OrbiterSatelliteConfig))],\n []\n ),\n set_track_event: IDL.Func([AnalyticKey, SetTrackEvent], [Result_3], []),\n set_track_events: IDL.Func([IDL.Vec(IDL.Tuple(AnalyticKey, SetTrackEvent))], [Result_1], []),\n version: IDL.Func([], [IDL.Text], ['query'])\n });\n};\n// @ts-ignore\nexport const init = ({IDL}) => {\n return [];\n};\n", "// @ts-ignore\nexport const idlFactory = ({IDL}) => {\n const CyclesThreshold = IDL.Record({\n fund_cycles: IDL.Nat,\n min_cycles: IDL.Nat\n });\n const CyclesMonitoringStrategy = IDL.Variant({\n BelowThreshold: CyclesThreshold\n });\n const CyclesMonitoring = IDL.Record({\n strategy: IDL.Opt(CyclesMonitoringStrategy),\n enabled: IDL.Bool\n });\n const Monitoring = IDL.Record({cycles: IDL.Opt(CyclesMonitoring)});\n const Settings = IDL.Record({monitoring: IDL.Opt(Monitoring)});\n const Orbiter = IDL.Record({\n updated_at: IDL.Nat64,\n orbiter_id: IDL.Principal,\n metadata: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n created_at: IDL.Nat64,\n settings: IDL.Opt(Settings)\n });\n const CreateCanisterConfig = IDL.Record({\n subnet_id: IDL.Opt(IDL.Principal),\n name: IDL.Opt(IDL.Text)\n });\n const Satellite = IDL.Record({\n updated_at: IDL.Nat64,\n metadata: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n created_at: IDL.Nat64,\n satellite_id: IDL.Principal,\n settings: IDL.Opt(Settings)\n });\n const DepositCyclesArgs = IDL.Record({\n cycles: IDL.Nat,\n destination_id: IDL.Principal\n });\n const DepositedCyclesEmailNotification = IDL.Record({\n to: IDL.Opt(IDL.Text),\n enabled: IDL.Bool\n });\n const CyclesMonitoringConfig = IDL.Record({\n notification: IDL.Opt(DepositedCyclesEmailNotification),\n default_strategy: IDL.Opt(CyclesMonitoringStrategy)\n });\n const MonitoringConfig = IDL.Record({\n cycles: IDL.Opt(CyclesMonitoringConfig)\n });\n const Config = IDL.Record({monitoring: IDL.Opt(MonitoringConfig)});\n const GetMonitoringHistory = IDL.Record({\n to: IDL.Opt(IDL.Nat64),\n from: IDL.Opt(IDL.Nat64),\n segment_id: IDL.Principal\n });\n const MonitoringHistoryKey = IDL.Record({\n segment_id: IDL.Principal,\n created_at: IDL.Nat64,\n nonce: IDL.Int32\n });\n const CyclesBalance = IDL.Record({\n timestamp: IDL.Nat64,\n amount: IDL.Nat\n });\n const MonitoringHistoryCycles = IDL.Record({\n deposited_cycles: IDL.Opt(CyclesBalance),\n cycles: CyclesBalance\n });\n const MonitoringHistory = IDL.Record({\n cycles: IDL.Opt(MonitoringHistoryCycles)\n });\n const CyclesMonitoringStatus = IDL.Record({\n monitored_ids: IDL.Vec(IDL.Principal),\n running: IDL.Bool\n });\n const MonitoringStatus = IDL.Record({\n cycles: IDL.Opt(CyclesMonitoringStatus)\n });\n const MissionControlSettings = IDL.Record({\n updated_at: IDL.Nat64,\n created_at: IDL.Nat64,\n monitoring: IDL.Opt(Monitoring)\n });\n const User = IDL.Record({\n updated_at: IDL.Nat64,\n metadata: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\n user: IDL.Opt(IDL.Principal),\n created_at: IDL.Nat64,\n config: IDL.Opt(Config)\n });\n const Tokens = IDL.Record({e8s: IDL.Nat64});\n const Timestamp = IDL.Record({timestamp_nanos: IDL.Nat64});\n const TransferArgs = IDL.Record({\n to: IDL.Vec(IDL.Nat8),\n fee: Tokens,\n memo: IDL.Nat64,\n from_subaccount: IDL.Opt(IDL.Vec(IDL.Nat8)),\n created_at_time: IDL.Opt(Timestamp),\n amount: Tokens\n });\n const TransferError = IDL.Variant({\n TxTooOld: IDL.Record({allowed_window_nanos: IDL.Nat64}),\n BadFee: IDL.Record({expected_fee: Tokens}),\n TxDuplicate: IDL.Record({duplicate_of: IDL.Nat64}),\n TxCreatedInFuture: IDL.Null,\n InsufficientFunds: IDL.Record({balance: Tokens})\n });\n const Result = IDL.Variant({Ok: IDL.Nat64, Err: TransferError});\n const Account = IDL.Record({\n owner: IDL.Principal,\n subaccount: IDL.Opt(IDL.Vec(IDL.Nat8))\n });\n const TransferArg = IDL.Record({\n to: Account,\n fee: IDL.Opt(IDL.Nat),\n memo: IDL.Opt(IDL.Vec(IDL.Nat8)),\n from_subaccount: IDL.Opt(IDL.Vec(IDL.Nat8)),\n created_at_time: IDL.Opt(IDL.Nat64),\n amount: IDL.Nat\n });\n const TransferError_1 = IDL.Variant({\n GenericError: IDL.Record({\n message: IDL.Text,\n error_code: IDL.Nat\n }),\n TemporarilyUnavailable: IDL.Null,\n BadBurn: IDL.Record({min_burn_amount: IDL.Nat}),\n Duplicate: IDL.Record({duplicate_of: IDL.Nat}),\n BadFee: IDL.Record({expected_fee: IDL.Nat}),\n CreatedInFuture: IDL.Record({ledger_time: IDL.Nat64}),\n TooOld: IDL.Null,\n InsufficientFunds: IDL.Record({balance: IDL.Nat})\n });\n const Result_1 = IDL.Variant({Ok: IDL.Nat, Err: TransferError_1});\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 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 SegmentsMonitoringStrategy = IDL.Record({\n ids: IDL.Vec(IDL.Principal),\n strategy: CyclesMonitoringStrategy\n });\n const CyclesMonitoringStartConfig = IDL.Record({\n orbiters_strategy: IDL.Opt(SegmentsMonitoringStrategy),\n mission_control_strategy: IDL.Opt(CyclesMonitoringStrategy),\n satellites_strategy: IDL.Opt(SegmentsMonitoringStrategy)\n });\n const MonitoringStartConfig = IDL.Record({\n cycles_config: IDL.Opt(CyclesMonitoringStartConfig)\n });\n const CyclesMonitoringStopConfig = IDL.Record({\n satellite_ids: IDL.Opt(IDL.Vec(IDL.Principal)),\n try_mission_control: IDL.Opt(IDL.Bool),\n orbiter_ids: IDL.Opt(IDL.Vec(IDL.Principal))\n });\n const MonitoringStopConfig = IDL.Record({\n cycles_config: IDL.Opt(CyclesMonitoringStopConfig)\n });\n return IDL.Service({\n add_mission_control_controllers: IDL.Func([IDL.Vec(IDL.Principal)], [], []),\n add_satellites_controllers: IDL.Func([IDL.Vec(IDL.Principal), IDL.Vec(IDL.Principal)], [], []),\n create_orbiter: IDL.Func([IDL.Opt(IDL.Text)], [Orbiter], []),\n create_orbiter_with_config: IDL.Func([CreateCanisterConfig], [Orbiter], []),\n create_satellite: IDL.Func([IDL.Text], [Satellite], []),\n create_satellite_with_config: IDL.Func([CreateCanisterConfig], [Satellite], []),\n del_mission_control_controllers: IDL.Func([IDL.Vec(IDL.Principal)], [], []),\n del_orbiter: IDL.Func([IDL.Principal, IDL.Nat], [], []),\n del_orbiters_controllers: IDL.Func([IDL.Vec(IDL.Principal), IDL.Vec(IDL.Principal)], [], []),\n del_satellite: IDL.Func([IDL.Principal, IDL.Nat], [], []),\n del_satellites_controllers: IDL.Func([IDL.Vec(IDL.Principal), IDL.Vec(IDL.Principal)], [], []),\n deposit_cycles: IDL.Func([DepositCyclesArgs], [], []),\n get_config: IDL.Func([], [IDL.Opt(Config)], ['query']),\n get_metadata: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))], ['query']),\n get_monitoring_history: IDL.Func(\n [GetMonitoringHistory],\n [IDL.Vec(IDL.Tuple(MonitoringHistoryKey, MonitoringHistory))],\n ['query']\n ),\n get_monitoring_status: IDL.Func([], [MonitoringStatus], ['query']),\n get_settings: IDL.Func([], [IDL.Opt(MissionControlSettings)], ['query']),\n get_user: IDL.Func([], [IDL.Principal], ['query']),\n get_user_data: IDL.Func([], [User], ['query']),\n icp_transfer: IDL.Func([TransferArgs], [Result], []),\n icrc_transfer: IDL.Func([IDL.Principal, TransferArg], [Result_1], []),\n list_mission_control_controllers: IDL.Func(\n [],\n [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))],\n ['query']\n ),\n list_orbiters: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Principal, Orbiter))], ['query']),\n list_satellites: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Principal, Satellite))], ['query']),\n remove_mission_control_controllers: IDL.Func([IDL.Vec(IDL.Principal)], [], []),\n remove_satellites_controllers: IDL.Func(\n [IDL.Vec(IDL.Principal), IDL.Vec(IDL.Principal)],\n [],\n []\n ),\n set_config: IDL.Func([IDL.Opt(Config)], [], []),\n set_metadata: IDL.Func([IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))], [], []),\n set_mission_control_controllers: IDL.Func([IDL.Vec(IDL.Principal), SetController], [], []),\n set_orbiter: IDL.Func([IDL.Principal, IDL.Opt(IDL.Text)], [Orbiter], []),\n set_orbiter_metadata: IDL.Func(\n [IDL.Principal, IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))],\n [Orbiter],\n []\n ),\n set_orbiters_controllers: IDL.Func(\n [IDL.Vec(IDL.Principal), IDL.Vec(IDL.Principal), SetController],\n [],\n []\n ),\n set_satellite: IDL.Func([IDL.Principal, IDL.Opt(IDL.Text)], [Satellite], []),\n set_satellite_metadata: IDL.Func(\n [IDL.Principal, IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))],\n [Satellite],\n []\n ),\n set_satellites_controllers: IDL.Func(\n [IDL.Vec(IDL.Principal), IDL.Vec(IDL.Principal), SetController],\n [],\n []\n ),\n start_monitoring: IDL.Func([], [], []),\n stop_monitoring: IDL.Func([], [], []),\n top_up: IDL.Func([IDL.Principal, Tokens], [], []),\n unset_orbiter: IDL.Func([IDL.Principal], [], []),\n unset_satellite: IDL.Func([IDL.Principal], [], []),\n update_and_start_monitoring: IDL.Func([MonitoringStartConfig], [], []),\n update_and_stop_monitoring: IDL.Func([MonitoringStopConfig], [], []),\n version: IDL.Func([], [IDL.Text], ['query'])\n });\n};\n// @ts-ignore\nexport const init = ({IDL}) => {\n return [];\n};\n", "export 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 DeleteControllersArgs = IDL.Record({\n controllers: IDL.Vec(IDL.Principal)\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 expires_at: IDL.Opt(IDL.Nat64)\n });\n const DelDoc = IDL.Record({updated_at: IDL.Opt(IDL.Nat64)});\n const StorageConfig = IDL.Record({\n headers: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))))\n });\n const Config = IDL.Record({storage: StorageConfig});\n const Doc = IDL.Record({\n updated_at: IDL.Nat64,\n owner: IDL.Principal,\n data: IDL.Vec(IDL.Nat8),\n created_at: 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 });\n const StreamingCallbackToken = IDL.Record({\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([], [], [])\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 encoding_type: IDL.Opt(IDL.Text),\n full_path: IDL.Text\n });\n const InitUploadResult = IDL.Record({batch_id: IDL.Nat});\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 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 matcher: IDL.Opt(IDL.Text),\n paginate: IDL.Opt(ListPaginate)\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 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 });\n const ListResults = IDL.Record({\n matches_length: IDL.Nat64,\n length: IDL.Nat64,\n items: IDL.Vec(IDL.Tuple(IDL.Text, AssetNoContent))\n });\n const CustomDomain = IDL.Record({\n updated_at: IDL.Nat64,\n created_at: IDL.Nat64,\n bn_id: IDL.Opt(IDL.Text)\n });\n const ListResults_1 = IDL.Record({\n matches_length: IDL.Nat64,\n length: IDL.Nat64,\n items: IDL.Vec(IDL.Tuple(IDL.Text, Doc))\n });\n const RulesType = IDL.Variant({Db: IDL.Null, Storage: IDL.Null});\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 updated_at: IDL.Nat64,\n max_size: IDL.Opt(IDL.Nat),\n read: Permission,\n created_at: IDL.Nat64,\n write: Permission\n });\n const SetController = IDL.Record({\n metadata: IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text)),\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 updated_at: IDL.Opt(IDL.Nat64),\n data: IDL.Vec(IDL.Nat8)\n });\n const SetRule = IDL.Record({\n updated_at: IDL.Opt(IDL.Nat64),\n max_size: IDL.Opt(IDL.Nat),\n read: Permission,\n write: Permission\n });\n const Chunk = IDL.Record({\n content: IDL.Vec(IDL.Nat8),\n batch_id: IDL.Nat\n });\n const UploadChunk = IDL.Record({chunk_id: IDL.Nat});\n return IDL.Service({\n commit_asset_upload: IDL.Func([CommitBatch], [], []),\n del_asset: IDL.Func([IDL.Text, IDL.Text], [], []),\n del_assets: IDL.Func([IDL.Opt(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 get_config: IDL.Func([], [Config], []),\n get_doc: IDL.Func([IDL.Text, IDL.Text], [IDL.Opt(Doc)], ['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.Opt(IDL.Text), ListParams], [ListResults], ['query']),\n list_controllers: IDL.Func([], [IDL.Vec(IDL.Principal)], ['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 set_config: IDL.Func([Config], [], []),\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_doc: IDL.Func([IDL.Text, IDL.Text, SetDoc], [Doc], []),\n set_rule: IDL.Func([RulesType, IDL.Text, SetRule], [], []),\n upload_asset_chunk: IDL.Func([Chunk], [UploadChunk], []),\n version: IDL.Func([], [IDL.Text], ['query'])\n });\n};\nexport const init = ({IDL}) => {\n return [];\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 CommitProposal = IDL.Record({\n sha256: IDL.Vec(IDL.Nat8),\n proposal_id: 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 Submit: 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 CollectionType = IDL.Variant({Db: IDL.Null, Storage: IDL.Null});\n const DelRule = IDL.Record({version: IDL.Opt(IDL.Nat64)});\n const DeleteProposalAssets = IDL.Record({\n proposal_ids: IDL.Vec(IDL.Nat)\n });\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 external_alternative_origins: IDL.Opt(IDL.Vec(IDL.Text))\n });\n const AuthenticationRules = IDL.Record({\n allowed_callers: IDL.Vec(IDL.Principal)\n });\n const AuthenticationConfig = IDL.Record({\n updated_at: IDL.Opt(IDL.Nat64),\n created_at: IDL.Opt(IDL.Nat64),\n version: IDL.Opt(IDL.Nat64),\n internet_identity: IDL.Opt(AuthenticationConfigInternetIdentity),\n rules: IDL.Opt(AuthenticationRules)\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 updated_at: IDL.Opt(IDL.Nat64),\n created_at: IDL.Opt(IDL.Nat64),\n version: IDL.Opt(IDL.Nat64),\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 updated_at: IDL.Opt(IDL.Nat64),\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 created_at: IDL.Opt(IDL.Nat64),\n version: IDL.Opt(IDL.Nat64),\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 ProposalStatus = IDL.Variant({\n Initialized: IDL.Null,\n Failed: IDL.Null,\n Open: IDL.Null,\n Rejected: IDL.Null,\n Executed: IDL.Null,\n Accepted: IDL.Null\n });\n const AssetsUpgradeOptions = IDL.Record({\n clear_existing_assets: IDL.Opt(IDL.Bool)\n });\n const SegmentsDeploymentOptions = IDL.Record({\n orbiter: IDL.Opt(IDL.Text),\n mission_control_version: IDL.Opt(IDL.Text),\n satellite_version: IDL.Opt(IDL.Text)\n });\n const ProposalType = IDL.Variant({\n AssetsUpgrade: AssetsUpgradeOptions,\n SegmentsDeployment: SegmentsDeploymentOptions\n });\n const Proposal = IDL.Record({\n status: ProposalStatus,\n updated_at: IDL.Nat64,\n sha256: IDL.Opt(IDL.Vec(IDL.Nat8)),\n executed_at: IDL.Opt(IDL.Nat64),\n owner: IDL.Principal,\n created_at: IDL.Nat64,\n version: IDL.Opt(IDL.Nat64),\n proposal_type: ProposalType\n });\n const Memory = IDL.Variant({Heap: IDL.Null, Stable: IDL.Null});\n const Permission = IDL.Variant({\n Controllers: IDL.Null,\n Private: IDL.Null,\n Public: IDL.Null,\n Managed: IDL.Null\n });\n const RateConfig = IDL.Record({\n max_tokens: IDL.Nat64,\n time_per_token_ns: IDL.Nat64\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 rate_config: IDL.Opt(RateConfig),\n write: Permission,\n max_changes_per_user: IDL.Opt(IDL.Nat32)\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 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 ListProposalsOrder = IDL.Record({desc: IDL.Bool});\n const ListProposalsPaginate = IDL.Record({\n start_after: IDL.Opt(IDL.Nat),\n limit: IDL.Opt(IDL.Nat)\n });\n const ListProposalsParams = IDL.Record({\n order: IDL.Opt(ListProposalsOrder),\n paginate: IDL.Opt(ListProposalsPaginate)\n });\n const ProposalKey = IDL.Record({proposal_id: IDL.Nat});\n const ListProposalResults = IDL.Record({\n matches_length: IDL.Nat64,\n items: IDL.Vec(IDL.Tuple(ProposalKey, Proposal)),\n items_length: IDL.Nat64\n });\n const ListRulesMatcher = IDL.Record({include_system: IDL.Bool});\n const ListRulesParams = IDL.Record({matcher: IDL.Opt(ListRulesMatcher)});\n const ListRulesResults = IDL.Record({\n matches_length: IDL.Nat64,\n items: IDL.Vec(IDL.Tuple(IDL.Text, Rule)),\n items_length: IDL.Nat64\n });\n const MemorySize = IDL.Record({stable: IDL.Nat64, heap: IDL.Nat64});\n const SetAuthenticationConfig = IDL.Record({\n version: IDL.Opt(IDL.Nat64),\n internet_identity: IDL.Opt(AuthenticationConfigInternetIdentity),\n rules: IDL.Opt(AuthenticationRules)\n });\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 SetDbConfig = IDL.Record({\n version: IDL.Opt(IDL.Nat64),\n max_memory_size: IDL.Opt(ConfigMaxMemorySize)\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 rate_config: IDL.Opt(RateConfig),\n write: Permission,\n max_changes_per_user: IDL.Opt(IDL.Nat32)\n });\n const SetStorageConfig = 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 version: IDL.Opt(IDL.Nat64),\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 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 commit_asset_upload: IDL.Func([CommitBatch], [], []),\n commit_proposal: IDL.Func([CommitProposal], [IDL.Null], []),\n commit_proposal_asset_upload: IDL.Func([CommitBatch], [], []),\n commit_proposal_many_assets_upload: IDL.Func([IDL.Vec(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 count_proposals: IDL.Func([], [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_filtered_assets: IDL.Func([IDL.Text, ListParams], [], []),\n del_filtered_docs: IDL.Func([IDL.Text, ListParams], [], []),\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([CollectionType, IDL.Text, DelRule], [], []),\n delete_proposal_assets: IDL.Func([DeleteProposalAssets], [], []),\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_proposal: IDL.Func([IDL.Nat], [IDL.Opt(Proposal)], ['query']),\n get_rule: IDL.Func([CollectionType, IDL.Text], [IDL.Opt(Rule)], ['query']),\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 init_proposal: IDL.Func([ProposalType], [IDL.Nat, Proposal], []),\n init_proposal_asset_upload: IDL.Func([InitAssetKey, IDL.Nat], [InitUploadResult], []),\n init_proposal_many_assets_upload: IDL.Func(\n [IDL.Vec(InitAssetKey), IDL.Nat],\n [IDL.Vec(IDL.Tuple(IDL.Text, InitUploadResult))],\n []\n ),\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_proposals: IDL.Func([ListProposalsParams], [ListProposalResults], ['query']),\n list_rules: IDL.Func([CollectionType, ListRulesParams], [ListRulesResults], ['query']),\n memory_size: IDL.Func([], [MemorySize], ['query']),\n reject_proposal: IDL.Func([CommitProposal], [IDL.Null], []),\n set_auth_config: IDL.Func([SetAuthenticationConfig], [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([SetDbConfig], [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([CollectionType, IDL.Text, SetRule], [Rule], []),\n set_storage_config: IDL.Func([SetStorageConfig], [StorageConfig], []),\n submit_proposal: IDL.Func([IDL.Nat], [IDL.Nat, Proposal], []),\n upload_asset_chunk: IDL.Func([UploadChunk], [UploadChunkResult], []),\n upload_proposal_asset_chunk: IDL.Func([UploadChunk], [UploadChunkResult], [])\n });\n};\n// @ts-ignore\nexport const init = ({IDL}) => {\n return [];\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 CommitProposal = IDL.Record({\n sha256: IDL.Vec(IDL.Nat8),\n proposal_id: 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 Submit: 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 CollectionType = IDL.Variant({Db: IDL.Null, Storage: IDL.Null});\n const DelRule = IDL.Record({version: IDL.Opt(IDL.Nat64)});\n const DeleteProposalAssets = IDL.Record({\n proposal_ids: IDL.Vec(IDL.Nat)\n });\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 external_alternative_origins: IDL.Opt(IDL.Vec(IDL.Text))\n });\n const AuthenticationRules = IDL.Record({\n allowed_callers: IDL.Vec(IDL.Principal)\n });\n const AuthenticationConfig = IDL.Record({\n updated_at: IDL.Opt(IDL.Nat64),\n created_at: IDL.Opt(IDL.Nat64),\n version: IDL.Opt(IDL.Nat64),\n internet_identity: IDL.Opt(AuthenticationConfigInternetIdentity),\n rules: IDL.Opt(AuthenticationRules)\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 updated_at: IDL.Opt(IDL.Nat64),\n created_at: IDL.Opt(IDL.Nat64),\n version: IDL.Opt(IDL.Nat64),\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 updated_at: IDL.Opt(IDL.Nat64),\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 created_at: IDL.Opt(IDL.Nat64),\n version: IDL.Opt(IDL.Nat64),\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 ProposalStatus = IDL.Variant({\n Initialized: IDL.Null,\n Failed: IDL.Null,\n Open: IDL.Null,\n Rejected: IDL.Null,\n Executed: IDL.Null,\n Accepted: IDL.Null\n });\n const AssetsUpgradeOptions = IDL.Record({\n clear_existing_assets: IDL.Opt(IDL.Bool)\n });\n const SegmentsDeploymentOptions = IDL.Record({\n orbiter: IDL.Opt(IDL.Text),\n mission_control_version: IDL.Opt(IDL.Text),\n satellite_version: IDL.Opt(IDL.Text)\n });\n const ProposalType = IDL.Variant({\n AssetsUpgrade: AssetsUpgradeOptions,\n SegmentsDeployment: SegmentsDeploymentOptions\n });\n const Proposal = IDL.Record({\n status: ProposalStatus,\n updated_at: IDL.Nat64,\n sha256: IDL.Opt(IDL.Vec(IDL.Nat8)),\n executed_at: IDL.Opt(IDL.Nat64),\n owner: IDL.Principal,\n created_at: IDL.Nat64,\n version: IDL.Opt(IDL.Nat64),\n proposal_type: ProposalType\n });\n const Memory = IDL.Variant({Heap: IDL.Null, Stable: IDL.Null});\n const Permission = IDL.Variant({\n Controllers: IDL.Null,\n Private: IDL.Null,\n Public: IDL.Null,\n Managed: IDL.Null\n });\n const RateConfig = IDL.Record({\n max_tokens: IDL.Nat64,\n time_per_token_ns: IDL.Nat64\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 rate_config: IDL.Opt(RateConfig),\n write: Permission,\n max_changes_per_user: IDL.Opt(IDL.Nat32)\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 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([], [], [])\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 ListProposalsOrder = IDL.Record({desc: IDL.Bool});\n const ListProposalsPaginate = IDL.Record({\n start_after: IDL.Opt(IDL.Nat),\n limit: IDL.Opt(IDL.Nat)\n });\n const ListProposalsParams = IDL.Record({\n order: IDL.Opt(ListProposalsOrder),\n paginate: IDL.Opt(ListProposalsPaginate)\n });\n const ProposalKey = IDL.Record({proposal_id: IDL.Nat});\n const ListProposalResults = IDL.Record({\n matches_length: IDL.Nat64,\n items: IDL.Vec(IDL.Tuple(ProposalKey, Proposal)),\n items_length: IDL.Nat64\n });\n const ListRulesMatcher = IDL.Record({include_system: IDL.Bool});\n const ListRulesParams = IDL.Record({matcher: IDL.Opt(ListRulesMatcher)});\n const ListRulesResults = IDL.Record({\n matches_length: IDL.Nat64,\n items: IDL.Vec(IDL.Tuple(IDL.Text, Rule)),\n items_length: IDL.Nat64\n });\n const MemorySize = IDL.Record({stable: IDL.Nat64, heap: IDL.Nat64});\n const SetAuthenticationConfig = IDL.Record({\n version: IDL.Opt(IDL.Nat64),\n internet_identity: IDL.Opt(AuthenticationConfigInternetIdentity),\n rules: IDL.Opt(AuthenticationRules)\n });\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 SetDbConfig = IDL.Record({\n version: IDL.Opt(IDL.Nat64),\n max_memory_size: IDL.Opt(ConfigMaxMemorySize)\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 rate_config: IDL.Opt(RateConfig),\n write: Permission,\n max_changes_per_user: IDL.Opt(IDL.Nat32)\n });\n const SetStorageConfig = 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 version: IDL.Opt(IDL.Nat64),\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 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 commit_asset_upload: IDL.Func([CommitBatch], [], []),\n commit_proposal: IDL.Func([CommitProposal], [IDL.Null], []),\n commit_proposal_asset_upload: IDL.Func([CommitBatch], [], []),\n commit_proposal_many_assets_upload: IDL.Func([IDL.Vec(CommitBatch)], [], []),\n count_assets: IDL.Func([IDL.Text, ListParams], [IDL.Nat64], []),\n count_collection_assets: IDL.Func([IDL.Text], [IDL.Nat64], []),\n count_collection_docs: IDL.Func([IDL.Text], [IDL.Nat64], []),\n count_docs: IDL.Func([IDL.Text, ListParams], [IDL.Nat64], []),\n count_proposals: IDL.Func([], [IDL.Nat64], []),\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_filtered_assets: IDL.Func([IDL.Text, ListParams], [], []),\n del_filtered_docs: IDL.Func([IDL.Text, ListParams], [], []),\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([CollectionType, IDL.Text, DelRule], [], []),\n delete_proposal_assets: IDL.Func([DeleteProposalAssets], [], []),\n deposit_cycles: IDL.Func([DepositCyclesArgs], [], []),\n get_asset: IDL.Func([IDL.Text, IDL.Text], [IDL.Opt(AssetNoContent)], []),\n get_auth_config: IDL.Func([], [IDL.Opt(AuthenticationConfig)], []),\n get_config: IDL.Func([], [Config], []),\n get_db_config: IDL.Func([], [IDL.Opt(DbConfig)], []),\n get_doc: IDL.Func([IDL.Text, IDL.Text], [IDL.Opt(Doc)], []),\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 []\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 []\n ),\n get_proposal: IDL.Func([IDL.Nat], [IDL.Opt(Proposal)], []),\n get_rule: IDL.Func([CollectionType, IDL.Text], [IDL.Opt(Rule)], []),\n get_storage_config: IDL.Func([], [StorageConfig], []),\n http_request: IDL.Func([HttpRequest], [HttpResponse], []),\n http_request_streaming_callback: IDL.Func(\n [StreamingCallbackToken],\n [StreamingCallbackHttpResponse],\n []\n ),\n init_asset_upload: IDL.Func([InitAssetKey], [InitUploadResult], []),\n init_proposal: IDL.Func([ProposalType], [IDL.Nat, Proposal], []),\n init_proposal_asset_upload: IDL.Func([InitAssetKey, IDL.Nat], [InitUploadResult], []),\n init_proposal_many_assets_upload: IDL.Func(\n [IDL.Vec(InitAssetKey), IDL.Nat],\n [IDL.Vec(IDL.Tuple(IDL.Text, InitUploadResult))],\n []\n ),\n list_assets: IDL.Func([IDL.Text, ListParams], [ListResults], []),\n list_controllers: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))], []),\n list_custom_domains: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Text, CustomDomain))], []),\n list_docs: IDL.Func([IDL.Text, ListParams], [ListResults_1], []),\n list_proposals: IDL.Func([ListProposalsParams], [ListProposalResults], []),\n list_rules: IDL.Func([CollectionType, ListRulesParams], [ListRulesResults], []),\n memory_size: IDL.Func([], [MemorySize], []),\n reject_proposal: IDL.Func([CommitProposal], [IDL.Null], []),\n set_auth_config: IDL.Func([SetAuthenticationConfig], [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([SetDbConfig], [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([CollectionType, IDL.Text, SetRule], [Rule], []),\n set_storage_config: IDL.Func([SetStorageConfig], [StorageConfig], []),\n submit_proposal: IDL.Func([IDL.Nat], [IDL.Nat, Proposal], []),\n upload_asset_chunk: IDL.Func([UploadChunk], [UploadChunkResult], []),\n upload_proposal_asset_chunk: IDL.Func([UploadChunk], [UploadChunkResult], [])\n });\n};\n// @ts-ignore\nexport const init = ({IDL}) => {\n return [];\n};\n", "// @ts-ignore\nexport const idlFactory = ({IDL}) => {\n const Tokens = IDL.Record({e8s: IDL.Nat64});\n const AssertMissionControlCenterArgs = IDL.Record({\n mission_control_id: IDL.Principal,\n user: IDL.Principal\n });\n const CommitProposal = IDL.Record({\n sha256: IDL.Vec(IDL.Nat8),\n proposal_id: IDL.Nat\n });\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 CreateCanisterArgs = IDL.Record({\n block_index: IDL.Opt(IDL.Nat64),\n subnet_id: IDL.Opt(IDL.Principal),\n user: IDL.Principal\n });\n const DeleteControllersArgs = IDL.Record({\n controllers: IDL.Vec(IDL.Principal)\n });\n const DeleteProposalAssets = IDL.Record({\n proposal_ids: IDL.Vec(IDL.Nat)\n });\n const StorageConfigIFrame = IDL.Variant({\n Deny: IDL.Null,\n AllowAny: IDL.Null,\n SameOrigin: IDL.Null\n });\n const ConfigMaxMemorySize = IDL.Record({\n stable: IDL.Opt(IDL.Nat64),\n heap: IDL.Opt(IDL.Nat64)\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 updated_at: IDL.Opt(IDL.Nat64),\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 created_at: IDL.Opt(IDL.Nat64),\n version: IDL.Opt(IDL.Nat64),\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({storage: StorageConfig});\n const GetCreateCanisterFeeArgs = IDL.Record({user: IDL.Principal});\n const ProposalStatus = IDL.Variant({\n Initialized: IDL.Null,\n Failed: IDL.Null,\n Open: IDL.Null,\n Rejected: IDL.Null,\n Executed: IDL.Null,\n Accepted: IDL.Null\n });\n const AssetsUpgradeOptions = IDL.Record({\n clear_existing_assets: IDL.Opt(IDL.Bool)\n });\n const SegmentsDeploymentOptions = IDL.Record({\n orbiter: IDL.Opt(IDL.Text),\n mission_control_version: IDL.Opt(IDL.Text),\n satellite_version: IDL.Opt(IDL.Text)\n });\n const ProposalType = IDL.Variant({\n AssetsUpgrade: AssetsUpgradeOptions,\n SegmentsDeployment: SegmentsDeploymentOptions\n });\n const Proposal = IDL.Record({\n status: ProposalStatus,\n updated_at: IDL.Nat64,\n sha256: IDL.Opt(IDL.Vec(IDL.Nat8)),\n executed_at: IDL.Opt(IDL.Nat64),\n owner: IDL.Principal,\n created_at: IDL.Nat64,\n version: IDL.Opt(IDL.Nat64),\n proposal_type: ProposalType\n });\n const MissionControl = IDL.Record({\n updated_at: IDL.Nat64,\n credits: Tokens,\n mission_control_id: IDL.Opt(IDL.Principal),\n owner: IDL.Principal,\n created_at: 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 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 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 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 ControllerScope = IDL.Variant({\n Write: IDL.Null,\n Admin: IDL.Null,\n Submit: 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 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 PaymentStatus = IDL.Variant({\n Refunded: IDL.Null,\n Acknowledged: IDL.Null,\n Completed: IDL.Null\n });\n const Payment = IDL.Record({\n status: PaymentStatus,\n updated_at: IDL.Nat64,\n block_index_payment: IDL.Nat64,\n mission_control_id: IDL.Opt(IDL.Principal),\n created_at: IDL.Nat64,\n block_index_refunded: IDL.Opt(IDL.Nat64)\n });\n const ListProposalsOrder = IDL.Record({desc: IDL.Bool});\n const ListProposalsPaginate = IDL.Record({\n start_after: IDL.Opt(IDL.Nat),\n limit: IDL.Opt(IDL.Nat)\n });\n const ListProposalsParams = IDL.Record({\n order: IDL.Opt(ListProposalsOrder),\n paginate: IDL.Opt(ListProposalsPaginate)\n });\n const ProposalKey = IDL.Record({proposal_id: IDL.Nat});\n const ListProposalResults = IDL.Record({\n matches_length: IDL.Nat64,\n items: IDL.Vec(IDL.Tuple(ProposalKey, Proposal)),\n items_length: IDL.Nat64\n });\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 SegmentKind = IDL.Variant({\n Orbiter: IDL.Null,\n MissionControl: IDL.Null,\n Satellite: IDL.Null\n });\n const SetStorageConfig = 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 version: IDL.Opt(IDL.Nat64),\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 RateConfig = IDL.Record({\n max_tokens: IDL.Nat64,\n time_per_token_ns: IDL.Nat64\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 add_credits: IDL.Func([IDL.Principal, Tokens], [], []),\n add_invitation_code: IDL.Func([IDL.Text], [], []),\n assert_mission_control_center: IDL.Func([AssertMissionControlCenterArgs], [], ['query']),\n commit_proposal: IDL.Func([CommitProposal], [IDL.Null], []),\n commit_proposal_asset_upload: IDL.Func([CommitBatch], [], []),\n commit_proposal_many_assets_upload: IDL.Func([IDL.Vec(CommitBatch)], [], []),\n count_proposals: IDL.Func([], [IDL.Nat64], ['query']),\n create_orbiter: IDL.Func([CreateCanisterArgs], [IDL.Principal], []),\n create_satellite: IDL.Func([CreateCanisterArgs], [IDL.Principal], []),\n del_controllers: IDL.Func([DeleteControllersArgs], [], []),\n del_custom_domain: IDL.Func([IDL.Text], [], []),\n delete_proposal_assets: IDL.Func([DeleteProposalAssets], [], []),\n get_config: IDL.Func([], [Config], ['query']),\n get_create_orbiter_fee: IDL.Func([GetCreateCanisterFeeArgs], [IDL.Opt(Tokens)], ['query']),\n get_create_satellite_fee: IDL.Func([GetCreateCanisterFeeArgs], [IDL.Opt(Tokens)], ['query']),\n get_credits: IDL.Func([], [Tokens], ['query']),\n get_proposal: IDL.Func([IDL.Nat], [IDL.Opt(Proposal)], ['query']),\n get_storage_config: IDL.Func([], [StorageConfig], ['query']),\n get_user_mission_control_center: IDL.Func([], [IDL.Opt(MissionControl)], ['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_proposal: IDL.Func([ProposalType], [IDL.Nat, Proposal], []),\n init_proposal_asset_upload: IDL.Func([InitAssetKey, IDL.Nat], [InitUploadResult], []),\n init_proposal_many_assets_upload: IDL.Func(\n [IDL.Vec(InitAssetKey), IDL.Nat],\n [IDL.Vec(IDL.Tuple(IDL.Text, InitUploadResult))],\n []\n ),\n init_user_mission_control_center: IDL.Func([], [MissionControl], []),\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_payments: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Nat64, Payment))], ['query']),\n list_proposals: IDL.Func([ListProposalsParams], [ListProposalResults], ['query']),\n list_user_mission_control_centers: IDL.Func(\n [],\n [IDL.Vec(IDL.Tuple(IDL.Principal, MissionControl))],\n ['query']\n ),\n reject_proposal: IDL.Func([CommitProposal], [IDL.Null], []),\n set_controllers: IDL.Func([SetControllersArgs], [], []),\n set_custom_domain: IDL.Func([IDL.Text, IDL.Opt(IDL.Text)], [], []),\n set_fee: IDL.Func([SegmentKind, Tokens], [], []),\n set_storage_config: IDL.Func([SetStorageConfig], [StorageConfig], []),\n submit_proposal: IDL.Func([IDL.Nat], [IDL.Nat, Proposal], []),\n update_rate_config: IDL.Func([SegmentKind, RateConfig], [], []),\n upload_proposal_asset_chunk: IDL.Func([UploadChunk], [UploadChunkResult], [])\n });\n};\n// @ts-ignore\nexport const init = ({IDL}) => {\n return [];\n};\n", "// @ts-ignore\nexport const idlFactory = ({IDL}) => {\n const Tokens = IDL.Record({e8s: IDL.Nat64});\n const AssertMissionControlCenterArgs = IDL.Record({\n mission_control_id: IDL.Principal,\n user: IDL.Principal\n });\n const CommitProposal = IDL.Record({\n sha256: IDL.Vec(IDL.Nat8),\n proposal_id: IDL.Nat\n });\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 CreateCanisterArgs = IDL.Record({\n block_index: IDL.Opt(IDL.Nat64),\n subnet_id: IDL.Opt(IDL.Principal),\n user: IDL.Principal\n });\n const DeleteControllersArgs = IDL.Record({\n controllers: IDL.Vec(IDL.Principal)\n });\n const DeleteProposalAssets = IDL.Record({\n proposal_ids: IDL.Vec(IDL.Nat)\n });\n const StorageConfigIFrame = IDL.Variant({\n Deny: IDL.Null,\n AllowAny: IDL.Null,\n SameOrigin: IDL.Null\n });\n const ConfigMaxMemorySize = IDL.Record({\n stable: IDL.Opt(IDL.Nat64),\n heap: IDL.Opt(IDL.Nat64)\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 updated_at: IDL.Opt(IDL.Nat64),\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 created_at: IDL.Opt(IDL.Nat64),\n version: IDL.Opt(IDL.Nat64),\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({storage: StorageConfig});\n const GetCreateCanisterFeeArgs = IDL.Record({user: IDL.Principal});\n const ProposalStatus = IDL.Variant({\n Initialized: IDL.Null,\n Failed: IDL.Null,\n Open: IDL.Null,\n Rejected: IDL.Null,\n Executed: IDL.Null,\n Accepted: IDL.Null\n });\n const AssetsUpgradeOptions = IDL.Record({\n clear_existing_assets: IDL.Opt(IDL.Bool)\n });\n const SegmentsDeploymentOptions = IDL.Record({\n orbiter: IDL.Opt(IDL.Text),\n mission_control_version: IDL.Opt(IDL.Text),\n satellite_version: IDL.Opt(IDL.Text)\n });\n const ProposalType = IDL.Variant({\n AssetsUpgrade: AssetsUpgradeOptions,\n SegmentsDeployment: SegmentsDeploymentOptions\n });\n const Proposal = IDL.Record({\n status: ProposalStatus,\n updated_at: IDL.Nat64,\n sha256: IDL.Opt(IDL.Vec(IDL.Nat8)),\n executed_at: IDL.Opt(IDL.Nat64),\n owner: IDL.Principal,\n created_at: IDL.Nat64,\n version: IDL.Opt(IDL.Nat64),\n proposal_type: ProposalType\n });\n const MissionControl = IDL.Record({\n updated_at: IDL.Nat64,\n credits: Tokens,\n mission_control_id: IDL.Opt(IDL.Principal),\n owner: IDL.Principal,\n created_at: 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([], [], [])\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 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 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 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 ControllerScope = IDL.Variant({\n Write: IDL.Null,\n Admin: IDL.Null,\n Submit: 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 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 PaymentStatus = IDL.Variant({\n Refunded: IDL.Null,\n Acknowledged: IDL.Null,\n Completed: IDL.Null\n });\n const Payment = IDL.Record({\n status: PaymentStatus,\n updated_at: IDL.Nat64,\n block_index_payment: IDL.Nat64,\n mission_control_id: IDL.Opt(IDL.Principal),\n created_at: IDL.Nat64,\n block_index_refunded: IDL.Opt(IDL.Nat64)\n });\n const ListProposalsOrder = IDL.Record({desc: IDL.Bool});\n const ListProposalsPaginate = IDL.Record({\n start_after: IDL.Opt(IDL.Nat),\n limit: IDL.Opt(IDL.Nat)\n });\n const ListProposalsParams = IDL.Record({\n order: IDL.Opt(ListProposalsOrder),\n paginate: IDL.Opt(ListProposalsPaginate)\n });\n const ProposalKey = IDL.Record({proposal_id: IDL.Nat});\n const ListProposalResults = IDL.Record({\n matches_length: IDL.Nat64,\n items: IDL.Vec(IDL.Tuple(ProposalKey, Proposal)),\n items_length: IDL.Nat64\n });\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 SegmentKind = IDL.Variant({\n Orbiter: IDL.Null,\n MissionControl: IDL.Null,\n Satellite: IDL.Null\n });\n const SetStorageConfig = 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 version: IDL.Opt(IDL.Nat64),\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 RateConfig = IDL.Record({\n max_tokens: IDL.Nat64,\n time_per_token_ns: IDL.Nat64\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 add_credits: IDL.Func([IDL.Principal, Tokens], [], []),\n add_invitation_code: IDL.Func([IDL.Text], [], []),\n assert_mission_control_center: IDL.Func([AssertMissionControlCenterArgs], [], []),\n commit_proposal: IDL.Func([CommitProposal], [IDL.Null], []),\n commit_proposal_asset_upload: IDL.Func([CommitBatch], [], []),\n commit_proposal_many_assets_upload: IDL.Func([IDL.Vec(CommitBatch)], [], []),\n count_proposals: IDL.Func([], [IDL.Nat64], []),\n create_orbiter: IDL.Func([CreateCanisterArgs], [IDL.Principal], []),\n create_satellite: IDL.Func([CreateCanisterArgs], [IDL.Principal], []),\n del_controllers: IDL.Func([DeleteControllersArgs], [], []),\n del_custom_domain: IDL.Func([IDL.Text], [], []),\n delete_proposal_assets: IDL.Func([DeleteProposalAssets], [], []),\n get_config: IDL.Func([], [Config], []),\n get_create_orbiter_fee: IDL.Func([GetCreateCanisterFeeArgs], [IDL.Opt(Tokens)], []),\n get_create_satellite_fee: IDL.Func([GetCreateCanisterFeeArgs], [IDL.Opt(Tokens)], []),\n get_credits: IDL.Func([], [Tokens], []),\n get_proposal: IDL.Func([IDL.Nat], [IDL.Opt(Proposal)], []),\n get_storage_config: IDL.Func([], [StorageConfig], []),\n get_user_mission_control_center: IDL.Func([], [IDL.Opt(MissionControl)], []),\n http_request: IDL.Func([HttpRequest], [HttpResponse], []),\n http_request_streaming_callback: IDL.Func(\n [StreamingCallbackToken],\n [StreamingCallbackHttpResponse],\n []\n ),\n init_proposal: IDL.Func([ProposalType], [IDL.Nat, Proposal], []),\n init_proposal_asset_upload: IDL.Func([InitAssetKey, IDL.Nat], [InitUploadResult], []),\n init_proposal_many_assets_upload: IDL.Func(\n [IDL.Vec(InitAssetKey), IDL.Nat],\n [IDL.Vec(IDL.Tuple(IDL.Text, InitUploadResult))],\n []\n ),\n init_user_mission_control_center: IDL.Func([], [MissionControl], []),\n list_assets: IDL.Func([IDL.Text, ListParams], [ListResults], []),\n list_controllers: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Principal, Controller))], []),\n list_custom_domains: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Text, CustomDomain))], []),\n list_payments: IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Nat64, Payment))], []),\n list_proposals: IDL.Func([ListProposalsParams], [ListProposalResults], []),\n list_user_mission_control_centers: IDL.Func(\n [],\n [IDL.Vec(IDL.Tuple(IDL.Principal, MissionControl))],\n []\n ),\n reject_proposal: IDL.Func([CommitProposal], [IDL.Null], []),\n set_controllers: IDL.Func([SetControllersArgs], [], []),\n set_custom_domain: IDL.Func([IDL.Text, IDL.Opt(IDL.Text)], [], []),\n set_fee: IDL.Func([SegmentKind, Tokens], [], []),\n set_storage_config: IDL.Func([SetStorageConfig], [StorageConfig], []),\n submit_proposal: IDL.Func([IDL.Nat], [IDL.Nat, Proposal], []),\n update_rate_config: IDL.Func([SegmentKind, RateConfig], [], []),\n upload_proposal_asset_chunk: IDL.Func([UploadChunk], [UploadChunkResult], [])\n });\n};\n// @ts-ignore\nexport const init = ({IDL}) => {\n return [];\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 CommitProposal = IDL.Record({\n sha256: IDL.Vec(IDL.Nat8),\n proposal_id: 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 Submit: 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 CollectionType = IDL.Variant({Db: IDL.Null, Storage: IDL.Null});\n const DelRule = IDL.Record({version: IDL.Opt(IDL.Nat64)});\n const DeleteProposalAssets = IDL.Record({\n proposal_ids: IDL.Vec(IDL.Nat)\n });\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 external_alternative_origins: IDL.Opt(IDL.Vec(IDL.Text))\n });\n const AuthenticationRules = IDL.Record({\n allowed_callers: IDL.Vec(IDL.Principal)\n });\n const AuthenticationConfig = IDL.Record({\n updated_at: IDL.Opt(IDL.Nat64),\n created_at: IDL.Opt(IDL.Nat64),\n version: IDL.Opt(IDL.Nat64),\n internet_identity: IDL.Opt(AuthenticationConfigInternetIdentity),\n rules: IDL.Opt(AuthenticationRules)\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 updated_at: IDL.Opt(IDL.Nat64),\n created_at: IDL.Opt(IDL.Nat64),\n version: IDL.Opt(IDL.Nat64),\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 updated_at: IDL.Opt(IDL.Nat64),\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 created_at: IDL.Opt(IDL.Nat64),\n version: IDL.Opt(IDL.Nat64),\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 ProposalStatus = IDL.Variant({\n Initialized: IDL.Null,\n Failed: IDL.Null,\n Open: IDL.Null,\n Rejected: IDL.Null,\n Executed: IDL.Null,\n Accepted: IDL.Null\n });\n const AssetsUpgradeOptions = IDL.Record({\n clear_existing_assets: IDL.Opt(IDL.Bool)\n });\n const SegmentsDeploymentOptions = IDL.Record({\n orbiter: IDL.Opt(IDL.Text),\n mission_control_version: IDL.Opt(IDL.Text),\n satellite_version: IDL.Opt(IDL.Text)\n });\n const ProposalType = IDL.Variant({\n AssetsUpgrade: AssetsUpgradeOptions,\n SegmentsDeployment: SegmentsDeploymentOptions\n });\n const Proposal = IDL.Record({\n status: ProposalStatus,\n updated_at: IDL.Nat64,\n sha256: IDL.Opt(IDL.Vec(IDL.Nat8)),\n executed_at: IDL.Opt(IDL.Nat64),\n owner: IDL.Principal,\n created_at: IDL.Nat64,\n version: IDL.Opt(IDL.Nat64),\n proposal_type: ProposalType\n });\n const Memory = IDL.Variant({Heap: IDL.Null, Stable: IDL.Null});\n const Permission = IDL.Variant({\n Controllers: IDL.Null,\n Private: IDL.Null,\n Public: IDL.Null,\n Managed: IDL.Null\n });\n const RateConfig = IDL.Record({\n max_tokens: IDL.Nat64,\n time_per_token_ns: IDL.Nat64\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 rate_config: IDL.Opt(RateConfig),\n write: Permission,\n max_changes_per_user: IDL.Opt(IDL.Nat32)\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 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 ListProposalsOrder = IDL.Record({desc: IDL.Bool});\n const ListProposalsPaginate = IDL.Record({\n start_after: IDL.Opt(IDL.Nat),\n limit: IDL.Opt(IDL.Nat)\n });\n const ListProposalsParams = IDL.Record({\n order: IDL.Opt(ListProposalsOrder),\n paginate: IDL.Opt(ListProposalsPaginate)\n });\n const ProposalKey = IDL.Record({proposal_id: IDL.Nat});\n const ListProposalResults = IDL.Record({\n matches_length: IDL.Nat64,\n items: IDL.Vec(IDL.Tuple(ProposalKey, Proposal)),\n items_length: IDL.Nat64\n });\n const ListRulesMatcher = IDL.Record({include_system: IDL.Bool});\n const ListRulesParams = IDL.Record({matcher: IDL.Opt(ListRulesMatcher)});\n const ListRulesResults = IDL.Record({\n matches_length: IDL.Nat64,\n items: IDL.Vec(IDL.Tuple(IDL.Text, Rule)),\n items_length: IDL.Nat64\n });\n const MemorySize = IDL.Record({stable: IDL.Nat64, heap: IDL.Nat64});\n const SetAuthenticationConfig = IDL.Record({\n version: IDL.Opt(IDL.Nat64),\n internet_identity: IDL.Opt(AuthenticationConfigInternetIdentity),\n rules: IDL.Opt(AuthenticationRules)\n });\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 SetDbConfig = IDL.Record({\n version: IDL.Opt(IDL.Nat64),\n max_memory_size: IDL.Opt(ConfigMaxMemorySize)\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 rate_config: IDL.Opt(RateConfig),\n write: Permission,\n max_changes_per_user: IDL.Opt(IDL.Nat32)\n });\n const SetStorageConfig = 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 version: IDL.Opt(IDL.Nat64),\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 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 commit_asset_upload: IDL.Func([CommitBatch], [], []),\n commit_proposal: IDL.Func([CommitProposal], [IDL.Null], []),\n commit_proposal_asset_upload: IDL.Func([CommitBatch], [], []),\n commit_proposal_many_assets_upload: IDL.Func([IDL.Vec(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 count_proposals: IDL.Func([], [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_filtered_assets: IDL.Func([IDL.Text, ListParams], [], []),\n del_filtered_docs: IDL.Func([IDL.Text, ListParams], [], []),\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([CollectionType, IDL.Text, DelRule], [], []),\n delete_proposal_assets: IDL.Func([DeleteProposalAssets], [], []),\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_proposal: IDL.Func([IDL.Nat], [IDL.Opt(Proposal)], ['query']),\n get_rule: IDL.Func([CollectionType, IDL.Text], [IDL.Opt(Rule)], ['query']),\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 init_proposal: IDL.Func([ProposalType], [IDL.Nat, Proposal], []),\n init_proposal_asset_upload: IDL.Func([InitAssetKey, IDL.Nat], [InitUploadResult], []),\n init_proposal_many_assets_upload: IDL.Func(\n [IDL.Vec(InitAssetKey), IDL.Nat],\n [IDL.Vec(IDL.Tuple(IDL.Text, InitUploadResult))],\n []\n ),\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_proposals: IDL.Func([ListProposalsParams], [ListProposalResults], ['query']),\n list_rules: IDL.Func([CollectionType, ListRulesParams], [ListRulesResults], ['query']),\n memory_size: IDL.Func([], [MemorySize], ['query']),\n reject_proposal: IDL.Func([CommitProposal], [IDL.Null], []),\n set_auth_config: IDL.Func([SetAuthenticationConfig], [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([SetDbConfig], [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([CollectionType, IDL.Text, SetRule], [Rule], []),\n set_storage_config: IDL.Func([SetStorageConfig], [StorageConfig], []),\n submit_proposal: IDL.Func([IDL.Nat], [IDL.Nat, Proposal], []),\n upload_asset_chunk: IDL.Func([UploadChunk], [UploadChunkResult], []),\n upload_proposal_asset_chunk: IDL.Func([UploadChunk], [UploadChunkResult], [])\n });\n};\n// @ts-ignore\nexport const init = ({IDL}) => {\n return [];\n};\n", "import type {HttpAgent} from '@dfinity/agent';\nimport {nonNullish} from '@dfinity/utils';\nimport type {ActorParameters} from '../types/actor';\nimport {createAgent} from '../utils/agent.utils';\n\nexport const useOrInitAgent = async ({agent, ...rest}: ActorParameters): Promise<HttpAgent> =>\n agent ?? (await initAgent(rest));\n\nconst initAgent = async ({\n identity,\n container\n}: Omit<ActorParameters, 'agent'>): Promise<HttpAgent> => {\n const localActor = nonNullish(container) && container !== false;\n\n const host = localActor\n ? container === true\n ? 'http://127.0.0.1:5987'\n : container\n : 'https://icp-api.io';\n\n return await createAgent({\n identity,\n host,\n localActor\n });\n};\n", "import {HttpAgent} from '@dfinity/agent';\nimport type {ActorParameters} from '../types/actor';\n\n// We have this in a utils because we want to mock it for test purposes.\n// Not really happy with that, I welcome better ideas!\nexport const createAgent = async ({\n identity,\n host,\n localActor\n}: Pick<ActorParameters, 'identity'> & {host: string; localActor: boolean}) =>\n await HttpAgent.create({\n identity,\n host,\n retryTimes: 10,\n shouldFetchRootKey: localActor\n });\n", "import {nonNullish} from '@dfinity/utils';\nimport {DOCKER_CONTAINER_URL} from '../constants/container.constants';\nimport {EnvStore} from '../stores/env.store';\nimport type {SatelliteContext} from '../types/satellite';\n\nexport const satelliteUrl = ({\n satelliteId: customSatelliteId,\n container: customContainer\n}: SatelliteContext): 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<SatelliteContext, 'satelliteId'>): Pick<SatelliteContext, 'satelliteId'> =>\n nonNullish(satelliteId)\n ? {satelliteId}\n : (EnvStore.getInstance().get() ?? {satelliteId: undefined});\n\nexport const customOrEnvContainer = ({\n container: customContainer\n}: Pick<SatelliteContext, 'container'>): Pick<SatelliteContext, 'container'> =>\n nonNullish(customContainer)\n ? {container: customContainer}\n : (EnvStore.getInstance().get() ?? {container: undefined});\n", "import type {ActorMethod, ActorSubclass} from '@dfinity/agent';\nimport type {IDL} from '@dfinity/candid';\nimport {assertNonNullish} from '@dfinity/utils';\nimport {\n idlCertifiedFactorySatellite,\n idlFactorySatellite,\n type SatelliteActor\n} from '@junobuild/ic-client/actor';\nimport {ActorStore} from '../stores/actor.store';\nimport type {ActorKey} from '../types/actor';\nimport type {CallOptions} from '../types/call-options';\nimport type {SatelliteContext} from '../types/satellite';\nimport {customOrEnvContainer, customOrEnvSatelliteId} from '../utils/env.utils';\n\nexport const getSatelliteActor = ({\n satellite,\n options: {certified}\n}: {\n satellite: SatelliteContext;\n options: CallOptions;\n}): Promise<SatelliteActor> =>\n getActor({\n idlFactory: certified ? idlCertifiedFactorySatellite : idlFactorySatellite,\n actorKey: `stock#${certified ? 'update' : 'query'}`,\n ...satellite\n });\n\nexport const getSatelliteExtendedActor = <T = Record<string, ActorMethod>>({\n idlFactory,\n ...rest\n}: SatelliteContext & {idlFactory: IDL.InterfaceFactory}): Promise<ActorSubclass<T>> =>\n getActor({\n idlFactory,\n actorKey: 'extended#query',\n ...rest\n });\n\nconst getActor = async <T = Record<string, ActorMethod>>({\n satelliteId: customSatelliteId,\n container: customContainer,\n ...rest\n}: SatelliteContext & {idlFactory: IDL.InterfaceFactory; actorKey: ActorKey}): Promise<\n ActorSubclass<T>\n> => {\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 await ActorStore.getInstance().getActor({\n satelliteId,\n container,\n ...rest\n });\n};\n", "import {Principal} from '@dfinity/principal';\nimport {isNullish, toNullable} from '@dfinity/utils';\nimport type {SatelliteDid} from '@junobuild/ic-client/actor';\nimport {ListError} from '../../auth/types/errors';\nimport type {ListParams, ListTimestampMatcher} from '../types/list';\n\nconst toListMatcherTimestamp = (\n matcher?: ListTimestampMatcher\n): [] | [SatelliteDid.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 ListError('Invalid list matcher for timestamp', matcher);\n }\n};\n\nexport const toListParams = ({\n matcher,\n paginate,\n order,\n owner\n}: ListParams): SatelliteDid.ListParams => ({\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", "import type {SatelliteDid} from '@junobuild/ic-client/actor';\nimport {fromArray} from '@junobuild/utils';\n\nexport const mapData = async <D>({data}: Pick<SatelliteDid.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 {fromNullable, toNullable} from '@dfinity/utils';\nimport type {SatelliteDid} from '@junobuild/ic-client/actor';\nimport {fromArray, toArray} from '@junobuild/utils';\nimport type {ExcludeDate} from '../../core/types/utility';\nimport type {Doc} from '../types/doc';\n\nexport const toSetDoc = async <D>(doc: Doc<D>): Promise<SatelliteDid.SetDoc> => {\n const {data, version, description} = doc;\n\n return {\n description: toNullable(description),\n data: await toArray<ExcludeDate<D>>(data),\n version: toNullable(version)\n };\n};\n\nexport const toDelDoc = <D>(doc: Doc<D>): SatelliteDid.DelDoc => {\n const {version} = doc;\n\n return {\n version: toNullable(version)\n };\n};\n\nexport const fromDoc = async <D>({\n doc,\n key\n}: {\n doc: SatelliteDid.Doc;\n key: string;\n}): 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<ExcludeDate<D>>(data),\n version: fromNullable(version),\n ...rest\n };\n};\n", "import {fromNullable, isNullish, nonNullish} from '@dfinity/utils';\nimport type {SatelliteDid} from '@junobuild/ic-client/actor';\nimport {getSatelliteActor} from '../../core/api/actor.api';\nimport type {ActorReadParams, ActorUpdateParams} from '../../core/types/actor';\nimport type {ListParams, ListResults} from '../../core/types/list';\nimport type {ExcludeDate} from '../../core/types/utility';\nimport {toListParams} from '../../core/utils/list.utils';\nimport type {Doc} from '../types/doc';\nimport {mapData} from '../utils/data.utils';\nimport {fromDoc, toDelDoc, toSetDoc} from '../utils/doc.utils';\n\nexport const getDoc = async <D>({\n collection,\n key,\n ...rest\n}: {\n collection: string;\n} & ActorReadParams &\n Pick<Doc<D>, 'key'>): Promise<Doc<D> | undefined> => {\n const {get_doc} = await getSatelliteActor(rest);\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 ...rest\n}: {\n docs: ({collection: string} & Pick<Doc<any>, 'key'>)[];\n} & ActorReadParams): Promise<(Doc<any> | undefined)[]> => {\n const {get_many_docs} = await getSatelliteActor(rest);\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 ...rest\n}: {\n collection: string;\n doc: Doc<D>;\n} & ActorUpdateParams): Promise<Doc<D>> => {\n const {set_doc} = await getSatelliteActor(rest);\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 ...rest\n}: {\n docs: {collection: string; doc: Doc<any>}[];\n} & ActorUpdateParams): Promise<Doc<any>[]> => {\n const {set_many_docs} = await getSatelliteActor(rest);\n\n const payload: [string, string, SatelliteDid.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 ...rest\n}: {\n collection: string;\n doc: Doc<D>;\n} & ActorUpdateParams): Promise<void> => {\n const {del_doc} = await getSatelliteActor(rest);\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 ...rest\n}: {\n docs: {collection: string; doc: Doc<any>}[];\n} & ActorUpdateParams): Promise<void> => {\n const {del_many_docs} = await getSatelliteActor(rest);\n\n const payload: [string, string, SatelliteDid.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 deleteFilteredDocs = async ({\n collection,\n filter,\n ...rest\n}: {\n collection: string;\n filter: ListParams;\n} & ActorUpdateParams): Promise<void> => {\n const {del_filtered_docs} = await getSatelliteActor(rest);\n\n return del_filtered_docs(collection, toListParams(filter));\n};\n\nexport const listDocs = async <D>({\n collection,\n filter,\n ...rest\n}: {\n collection: string;\n filter: ListParams;\n} & ActorReadParams): Promise<ListResults<Doc<D>>> => {\n const {list_docs} = await getSatelliteActor(rest);\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<ExcludeDate<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 ...rest\n}: {\n collection: string;\n filter: ListParams;\n} & ActorReadParams): Promise<bigint> => {\n const {count_docs} = await getSatelliteActor(rest);\n\n return count_docs(collection, toListParams(filter));\n};\n", "import {DEFAULT_READ_OPTIONS} from '../../core/constants/call-options.constants';\nimport {getAnyIdentity} from '../../core/services/identity.services';\nimport type {ReadOptions} from '../../core/types/call-options';\nimport type {ListParams, ListResults} from '../../core/types/list';\nimport type {SatelliteOptions} from '../../core/types/satellite';\nimport {\n countDocs as countDocsApi,\n deleteDoc as deleteDocApi,\n deleteFilteredDocs as deleteFilteredDocsApi,\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';\n\n/**\n * Retrieves a single document from a collection.\n *\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 {string} params.key - The key of the document to retrieve.\n * @param {ReadOptions} [params.options] - Call options controlling certification. Defaults to uncertified reads for performance unless specified.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\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 options,\n ...rest\n}: {\n collection: string;\n satellite?: SatelliteOptions;\n options?: ReadOptions;\n} & Pick<Doc<D>, 'key'>): Promise<Doc<D> | undefined> => {\n const identity = getAnyIdentity(satellite?.identity);\n\n return await getDocApi({\n ...rest,\n satellite: {...satellite, identity},\n options: options ?? DEFAULT_READ_OPTIONS\n });\n};\n\n/**\n * Retrieves multiple documents from a single or different collections in a single call.\n *\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 {ReadOptions} [params.options] - Call options controlling certification. Defaults to uncertified reads for performance unless specified.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\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 options,\n ...rest\n}: {\n docs: ({collection: string} & Pick<Doc<any>, 'key'>)[];\n satellite?: SatelliteOptions;\n options?: ReadOptions;\n}): Promise<(Doc<any> | undefined)[]> => {\n const identity = getAnyIdentity(satellite?.identity);\n\n return await getManyDocsApi({\n ...rest,\n satellite: {...satellite, identity},\n options: options ?? DEFAULT_READ_OPTIONS\n });\n};\n/* eslint-enable */\n\n/**\n * Adds or updates a single document in a collection.\n *\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 to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\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 = getAnyIdentity(satellite?.identity);\n\n return await setDocApi({\n ...rest,\n satellite: {...satellite, identity},\n options: {certified: true}\n });\n};\n\n/**\n * Adds or updates multiple documents in a or different collections.\n *\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 to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\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 = getAnyIdentity(satellite?.identity);\n\n return await setManyDocsApi({\n ...rest,\n satellite: {...satellite, identity},\n options: {certified: true}\n });\n};\n/* eslint-enable */\n\n/**\n * Deletes a single document from a collection.\n *\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 to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\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 = getAnyIdentity(satellite?.identity);\n\n return await deleteDocApi({\n ...rest,\n satellite: {...satellite, identity},\n options: {certified: true}\n });\n};\n\n/**\n * Deletes multiple documents from a or different collections.\n *\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 to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\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 = getAnyIdentity(satellite?.identity);\n\n return await deleteManyDocsApi({\n ...rest,\n satellite: {...satellite, identity},\n options: {certified: true}\n });\n};\n/* eslint-enable */\n\n/**\n * Deletes documents from a collection with optional filtering.\n *\n * @param {Object} params - The parameters for deleting documents.\n * @param {string} params.collection - The name of the collection.\n * @param {ListParams} [params.filter] - The filter criteria to match documents for deletion.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\n * @returns {Promise<void>} A promise that resolves when the documents are deleted.\n */\nexport const deleteFilteredDocs = async ({\n satellite,\n filter,\n ...rest\n}: {\n collection: string;\n filter?: ListParams;\n satellite?: SatelliteOptions;\n}): Promise<void> => {\n const identity = getAnyIdentity(satellite?.identity);\n\n return await deleteFilteredDocsApi({\n ...rest,\n filter: filter ?? {},\n satellite: {...satellite, identity},\n options: {certified: true}\n });\n};\n\n/**\n * Lists documents in a collection with optional filtering.\n *\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 {ReadOptions} [params.options] - Call options controlling certification. Defaults to uncertified reads for performance unless specified.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\n * @returns {Promise<ListResults<Doc<D>>>} A promise that resolves to the list of documents.\n */\nexport const listDocs = async <D>({\n satellite,\n options,\n filter,\n ...rest\n}: {\n collection: string;\n filter?: ListParams;\n satellite?: SatelliteOptions;\n options?: ReadOptions;\n}): Promise<ListResults<Doc<D>>> => {\n const identity = getAnyIdentity(satellite?.identity);\n\n return await listDocsApi<D>({\n ...rest,\n filter: filter ?? {},\n satellite: {...satellite, identity},\n options: options ?? DEFAULT_READ_OPTIONS\n });\n};\n\n/**\n * Counts documents in a collection with optional filtering.\n *\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 {ReadOptions} [params.options] - Call options controlling certification. Defaults to uncertified reads for performance unless specified.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\n * @returns {Promise<bigint>} A promise that resolves to the count of documents as a bigint.\n */\nexport const countDocs = async ({\n satellite,\n options,\n filter,\n ...rest\n}: {\n collection: string;\n filter?: ListParams;\n satellite?: SatelliteOptions;\n options?: ReadOptions;\n}): Promise<bigint> => {\n const identity = getAnyIdentity(satellite?.identity);\n\n return await countDocsApi({\n ...rest,\n filter: filter ?? {},\n satellite: {...satellite, identity},\n options: options ?? DEFAULT_READ_OPTIONS\n });\n};\n", "import type {Identity} from '@dfinity/agent';\nimport {arrayBufferToUint8Array, nonNullish, uint8ArrayToArrayOfNumber} from '@dfinity/utils';\nimport type {WebAuthnIdentity, WebAuthnNewCredential} from '@junobuild/ic-client/webauthn';\nimport type {Environment} from '../../core/types/env';\nimport {setManyDocs} from '../../datastore/services/doc.services';\nimport type {User} from '../types/user';\n\nexport const createWebAuthnUser = async ({\n delegationIdentity,\n passkeyIdentity,\n satelliteId\n}: {\n delegationIdentity: Identity;\n passkeyIdentity: WebAuthnIdentity<WebAuthnNewCredential>;\n} & Pick<Environment, 'satelliteId'>): Promise<User> => {\n // We serialize the AAGUID as number[] instead of Uint8Array because\n // it results in slightly smaller JSON output with the stringifier.\n // When reading the data, we support both formats.\n const aaguid = passkeyIdentity.getCredential().getAAGUID();\n\n const [user, _] = await setManyDocs({\n docs: [\n {\n collection: '#user',\n doc: {\n key: delegationIdentity.getPrincipal().toText(),\n data: {\n provider: 'webauthn',\n providerData: {\n webauthn: {\n ...(nonNullish(aaguid) && {aaguid: uint8ArrayToArrayOfNumber(aaguid)})\n }\n }\n }\n }\n },\n {\n collection: '#user-webauthn',\n doc: {\n key: passkeyIdentity.getCredential().getCredentialIdText(),\n data: {\n publicKey: arrayBufferToUint8Array(passkeyIdentity.getPublicKey().toDer())\n }\n }\n }\n ],\n satellite: {\n identity: delegationIdentity,\n satelliteId\n }\n });\n\n return user;\n};\n", "import type {CreatePasskeyOptions} from '@junobuild/ic-client/webauthn';\nimport type {SignProgressFn} from './progress';\n\n/**\n * Enum representing the different steps of the WebAuthn sign-in flow.\n */\nexport enum WebAuthnSignInProgressStep {\n /** Requesting a passkey (credential) from the user */\n RequestingUserCredential,\n /** Validating and finalizing the credential provided by the user */\n FinalizingCredential,\n /** Signing the authentication challenge with the user's credential */\n Signing,\n /** Completing the session setup after signing */\n FinalizingSession,\n /** Retrieving the authenticated user information */\n RetrievingUser\n}\n\n/**\n * Enum representing the different steps of the WebAuthn sign-up (registration) flow.\n */\nexport enum WebAuthnSignUpProgressStep {\n /** Creating a new passkey (credential) for the user */\n CreatingUserCredential,\n /** Validating the created credential */\n ValidatingUserCredential,\n /** Finalizing the credential for use */\n FinalizingCredential,\n /** Signing the registration challenge. Requires the user to interact again with the authenticator for confirmation. */\n Signing,\n /** Completing the session setup after signing */\n FinalizingSession,\n /** Registering the new user in the system */\n RegisteringUser\n}\n\n/**\n * Interface representing common sign-in and sing-up options when using a WebAuthn (passkey) based provider.\n * @interface WebAuthnSignOptions\n */\nexport interface WebAuthnSignOptions {\n /**\n * Maximum time to live for the session in milliseconds. Cannot be extended.\n * @type {number}\n */\n maxTimeToLiveInMilliseconds?: number;\n}\n\n/**\n * Interface representing sign-in options when using a WebAuthn (passkey) based provider.\n * @interface WebAuthnSignInOptions\n */\nexport interface WebAuthnSignInOptions extends WebAuthnSignOptions {\n /**\n * Optional callback to receive progress updates about the sign-in flow.\n * Useful for showing UI feedback such as loading indicators or status messages.\n */\n onProgress?: SignProgressFn<WebAuthnSignInProgressStep>;\n}\n\n/**\n * Interface representing sign-up options when using a WebAuthn (passkey) based provider.\n * @interface WebAuthnSignUpSessionOptions\n */\nexport interface WebAuthnSignUpOptions extends WebAuthnSignOptions {\n /**\n * Optional callback to receive progress updates about the sign-up flow.\n * Useful for showing UI feedback such as loading indicators or status messages.\n */\n onProgress?: SignProgressFn<WebAuthnSignUpProgressStep>;\n\n /**\n * Options for creating the passkey credential.\n *\n * For example, you can provide a user-friendly display name so the passkey\n * is easier to recognize later.\n */\n passkey?: CreatePasskeyOptions;\n}\n", "import {type SignIdentity, AnonymousIdentity} from '@dfinity/agent';\nimport {IdbStorage, KEY_STORAGE_DELEGATION, KEY_STORAGE_KEY} from '@dfinity/auth-client';\nimport {\n DelegationChain,\n DelegationIdentity,\n DER_COSE_OID,\n ECDSAKeyIdentity,\n unwrapDER\n} from '@dfinity/identity';\nimport {isNullish, uint8ArrayToBase64} from '@dfinity/utils';\nimport {\n type RetrievePublicKeyFn,\n type WebAuthnNewCredential,\n type WebAuthnSignProgressFn,\n WebAuthnIdentity,\n WebAuthnSignProgressStep\n} from '@junobuild/ic-client/webauthn';\nimport {EnvStore} from '../../core/stores/env.store';\nimport {getDoc} from '../../datastore/services/doc.services';\nimport {DELEGATION_IDENTITY_EXPIRATION_IN_MILLISECONDS} from '../constants/auth.constants';\nimport {execute} from '../helpers/progress.helpers';\nimport {createWebAuthnUser} from '../services/user-webauthn.services';\nimport {SignInInitError, WebAuthnSignInRetrievePublicKeyError} from '../types/errors';\nimport type {Provider} from '../types/provider';\nimport type {User} from '../types/user';\nimport {\n type WebAuthnSignInOptions,\n type WebAuthnSignUpOptions,\n WebAuthnSignInProgressStep,\n WebAuthnSignUpProgressStep\n} from '../types/webauthn';\nimport type {AuthProvider} from './_auth-client.providers';\n\ninterface SessionDelegationIdentity {\n delegationIdentity: DelegationIdentity;\n sessionKey: ECDSAKeyIdentity;\n}\n\nexport class WebAuthnProvider implements AuthProvider {\n /**\n * Gets the identifier of the provider.\n * @returns {Provider} The identifier of the provider is webauthn.\n */\n get id(): Provider {\n return 'webauthn';\n }\n\n /**\n * Signs up a user by creating a new passkey.\n *\n * @param {Object} params - The sign-up parameters.\n * @param {WebAuthnSignUpOptions} [params.options] - Optional configuration for the login request.\n * @param {loadAuth} params.loadAuthWithUser - The function to load the authentication with the user. Provided as a callback to avoid recursive import.\n *\n * @returns {Promise<void>} Resolves if the sign-up is successful.\n */\n async signUp({\n options: {onProgress, maxTimeToLiveInMilliseconds, passkey: passkeyOptions} = {},\n loadAuthWithUser\n }: {\n options?: WebAuthnSignUpOptions;\n loadAuthWithUser: (params: {user: User}) => Promise<void>;\n }) {\n const {satelliteId} = EnvStore.getInstance().get() ?? {satelliteId: undefined};\n\n if (isNullish(satelliteId)) {\n throw new SignInInitError('Satellite ID not set. Have you initialized the Satellite?');\n }\n\n const onSignProgress: WebAuthnSignProgressFn = ({step, state}) => {\n switch (step) {\n case WebAuthnSignProgressStep.RequestingUserCredential:\n onProgress?.({\n step: WebAuthnSignUpProgressStep.ValidatingUserCredential,\n state\n });\n break;\n case WebAuthnSignProgressStep.FinalizingCredential:\n onProgress?.({\n step: WebAuthnSignUpProgressStep.FinalizingCredential,\n state\n });\n break;\n case WebAuthnSignProgressStep.Signing:\n onProgress?.({\n step: WebAuthnSignUpProgressStep.Signing,\n state\n });\n break;\n }\n };\n\n // 1. Create passkey\n const createPasskey = async (): Promise<WebAuthnIdentity<WebAuthnNewCredential>> =>\n await WebAuthnIdentity.createWithNewCredential({\n onProgress: onSignProgress,\n passkeyOptions\n });\n\n const passkeyIdentity = await execute({\n fn: createPasskey,\n step: WebAuthnSignUpProgressStep.CreatingUserCredential,\n onProgress\n });\n\n // 2. Create session delegation. This will require the user the sign the session using their authenticator.\n // i.e. they will have to use their authenticator a second time after create.\n const {delegationIdentity, sessionKey} = await this.#createSessionDelegation({\n identity: passkeyIdentity,\n maxTimeToLiveInMilliseconds\n });\n\n // 3. Make update calls to create user and save public key.\n // Note: We create the user before saving the session identity to avoid\n // a race condition where the user would reload the window and the lib\n // would try to retrieve and undefined user for the delegation saved in indexeddb.\n const register = async () =>\n await createWebAuthnUser({\n delegationIdentity,\n passkeyIdentity,\n satelliteId\n });\n\n const user = await execute({\n fn: register,\n step: WebAuthnSignUpProgressStep.RegisteringUser,\n onProgress\n });\n\n // 4. Save session identity for loading it with auth client\n const saveSession = async () =>\n await this.#saveSessionIdentityForAuthClient({delegationIdentity, sessionKey});\n\n await execute({\n fn: saveSession,\n step: WebAuthnSignUpProgressStep.FinalizingSession,\n onProgress\n });\n\n // 5. Load the user for the authentication\n const loadAuth = async () => await loadAuthWithUser({user});\n\n await execute({\n fn: loadAuth,\n step: WebAuthnSignUpProgressStep.RegisteringUser,\n onProgress\n });\n }\n\n /**\n * Signs in a user with an existing passkey.\n *\n * @param {Object} params - The sign-in parameters.\n * @param {WebAuthnSignInOptions} [params.options] - Optional configuration for the login request.\n * @param {loadAuth} params.loadAuth - The function to load the user. Provided as a callback to avoid recursive import.\n *\n * @returns {Promise<void>} Resolves if the sign-in is successful.\n */\n async signIn({\n options: {onProgress, maxTimeToLiveInMilliseconds} = {},\n loadAuth\n }: {\n options?: WebAuthnSignInOptions;\n loadAuth: () => Promise<void>;\n }) {\n const {satelliteId} = EnvStore.getInstance().get() ?? {satelliteId: undefined};\n\n if (isNullish(satelliteId)) {\n throw new SignInInitError('Satellite ID not set. Have you initialized the Satellite?');\n }\n\n const retrievePublicKey: RetrievePublicKeyFn = async ({credentialId}) => {\n const doc = await getDoc({\n collection: '#user-webauthn',\n key: uint8ArrayToBase64(credentialId),\n options: {\n certified: true\n },\n satellite: {\n identity: new AnonymousIdentity(),\n satelliteId\n }\n });\n\n if (isNullish(doc)) {\n throw new WebAuthnSignInRetrievePublicKeyError(\n 'No public key found for the selected passkey.'\n );\n }\n\n const {data} = doc;\n\n const {publicKey} = data as {publicKey: Uint8Array};\n\n return unwrapDER(publicKey.buffer as ArrayBuffer, DER_COSE_OID);\n };\n\n const onSignProgress: WebAuthnSignProgressFn = ({step, state}) => {\n switch (step) {\n case WebAuthnSignProgressStep.RequestingUserCredential:\n onProgress?.({\n step: WebAuthnSignInProgressStep.RequestingUserCredential,\n state\n });\n break;\n case WebAuthnSignProgressStep.FinalizingCredential:\n onProgress?.({\n step: WebAuthnSignInProgressStep.FinalizingCredential,\n state\n });\n break;\n case WebAuthnSignProgressStep.Signing:\n onProgress?.({\n step: WebAuthnSignInProgressStep.Signing,\n state\n });\n break;\n }\n };\n\n const passkeyIdentity = await WebAuthnIdentity.createWithExistingCredential({\n retrievePublicKey,\n onProgress: onSignProgress\n });\n\n // When the signing of the session occurs, the Identity.sign is triggered\n // which in turns lead to:\n // 1. Get passkey (navigator.credentials.get)\n // 2. Retrieve the public key from the backend\n // 3. Create signature\n const {delegationIdentity, sessionKey} = await this.#createSessionDelegation({\n identity: passkeyIdentity,\n maxTimeToLiveInMilliseconds\n });\n\n // 4. Save session identity for loading it with auth client\n const saveSession = async () =>\n await this.#saveSessionIdentityForAuthClient({delegationIdentity, sessionKey});\n\n await execute({\n fn: saveSession,\n step: WebAuthnSignInProgressStep.FinalizingSession,\n onProgress\n });\n\n // 5. Load the user\n await execute({\n fn: loadAuth,\n step: WebAuthnSignInProgressStep.RetrievingUser,\n onProgress\n });\n }\n\n async #createSessionDelegation({\n identity,\n maxTimeToLiveInMilliseconds\n }: {identity: SignIdentity} & Pick<\n WebAuthnSignInOptions,\n 'maxTimeToLiveInMilliseconds'\n >): Promise<SessionDelegationIdentity> {\n const sessionKey = await ECDSAKeyIdentity.generate({extractable: false});\n\n const sessionLengthInMilliseconds =\n maxTimeToLiveInMilliseconds ?? DELEGATION_IDENTITY_EXPIRATION_IN_MILLISECONDS;\n\n // We do not provide any particular targets. This delegation is meant to work\n // on the Internet Computer with any canister.\n const chain = await DelegationChain.create(\n identity,\n sessionKey.getPublicKey(),\n new Date(Date.now() + sessionLengthInMilliseconds)\n );\n\n const delegationIdentity = DelegationIdentity.fromDelegation(sessionKey, chain);\n\n return {delegationIdentity, sessionKey};\n }\n\n async #saveSessionIdentityForAuthClient({\n sessionKey,\n delegationIdentity\n }: SessionDelegationIdentity) {\n const storage = new IdbStorage();\n\n await Promise.all([\n storage.set(KEY_STORAGE_KEY, sessionKey.getKeyPair()),\n storage.set(\n KEY_STORAGE_DELEGATION,\n JSON.stringify(delegationIdentity.getDelegation().toJSON())\n )\n ]);\n }\n}\n", "import {AuthClient, IdbStorage, KEY_STORAGE_KEY} from '@dfinity/auth-client';\n\nexport const createAuthClient = (): Promise<AuthClient> =>\n AuthClient.create({\n idleOptions: {\n disableIdle: true,\n disableDefaultIdleCallback: true\n }\n });\n\nexport const resetAuthClient = async (): Promise<AuthClient> => {\n // Since AgentJS persists the identity key in IndexedDB by default,\n // it can be tampered with and affect the next login with Internet Identity or NFID.\n // To ensure each session starts clean and safe, we clear the stored keys before creating a new AuthClient\n // in case the user is not authenticated.\n const storage = new IdbStorage();\n await storage.remove(KEY_STORAGE_KEY);\n\n return await createAuthClient();\n};\n", "export const isSatelliteError = ({error, type}: {error: unknown; type: string}): boolean => {\n if (typeof error === 'string') {\n return error.includes(type);\n }\n\n if (error instanceof Error) {\n return error.message.includes(type);\n }\n\n return false;\n};\n", "export const JUNO_CDN_PROPOSALS_ERROR_CANNOT_SUBMIT = 'juno.cdn.proposals.error.cannot_submit';\nexport const JUNO_CDN_PROPOSALS_ERROR_CANNOT_SUBMIT_INVALID_STATUS =\n 'juno.cdn.proposals.error.cannot_submit_invalid_status';\n\nexport const JUNO_CDN_PROPOSALS_ERROR_CANNOT_REJECT = 'juno.cdn.proposals.error.cannot_reject';\nexport const JUNO_CDN_PROPOSALS_ERROR_CANNOT_REJECT_INVALID_STATUS =\n 'juno.cdn.proposals.error.cannot_reject_invalid_status';\n\nexport const JUNO_CDN_PROPOSALS_ERROR_CANNOT_COMMIT = 'juno.cdn.proposals.error.cannot_commit';\nexport const JUNO_CDN_PROPOSALS_ERROR_CANNOT_COMMIT_INVALID_STATUS =\n 'juno.cdn.proposals.error.cannot_commit_invalid_status';\n\nexport const JUNO_CDN_PROPOSALS_ERROR_INVALID_HASH = 'juno.cdn.proposals.error.invalid_hash';\n\nexport const JUNO_CDN_PROPOSALS_ERROR_UNKNOWN_TYPE = 'juno.cdn.proposals.error.unknown_type';\n\nexport const JUNO_CDN_PROPOSALS_ERROR_EMPTY_CONTENT_CHUNKS =\n 'juno.cdn.proposals.error.empty_content_chunks';\nexport const JUNO_CDN_PROPOSALS_ERROR_NOT_CONTENT_CHUNKS_AT_INDEX =\n 'juno.cdn.proposals.error.no_content_chunks_at_index';\n\nexport const JUNO_CDN_PROPOSALS_ERROR_EMPTY_ASSETS = 'juno.cdn.proposals.error.empty_assets';\nexport const JUNO_CDN_PROPOSALS_ERROR_CANNOT_DELETE_ASSETS =\n 'juno.cdn.proposals.error.cannot_delete_assets';\nexport const JUNO_CDN_PROPOSALS_ERROR_CANNOT_DELETE_ASSETS_INVALID_STATUS =\n 'juno.cdn.proposals.error.cannot_delete_assets_invalid_status';\n\nexport const JUNO_CDN_PROPOSALS_ERROR_NEXT_ID_CONVERT = 'juno.cdn.proposals.error.next_id_convert';\nexport const JUNO_CDN_PROPOSALS_ERROR_NEXT_ID_OVERFLOW =\n 'juno.cdn.proposals.error.next_id_overflow';\n\nexport const JUNO_CDN_STORAGE_ERROR_CANNOT_INSERT_ASSET_UNKNOWN_REFERENCE_ID =\n 'juno.cdn.storage.error.cannot_insert_asset_unknown_reference_id';\nexport const JUNO_CDN_STORAGE_ERROR_CANNOT_GET_ASSET_UNKNOWN_REFERENCE_ID =\n 'juno.cdn.storage.error.cannot_get_asset_unknown_reference_id';\nexport const JUNO_CDN_STORAGE_ERROR_CANNOT_INSERT_ASSET_ENCODING_UNKNOWN_REFERENCE_ID =\n 'juno.cdn.storage.error.cannot_insert_asset_encoding_unknown_reference_id';\n\nexport const JUNO_CDN_STORAGE_ERROR_NO_PROPOSAL_FOUND = 'juno.cdn.storage.error.no_proposal_found';\n\nexport const JUNO_CDN_STORAGE_ERROR_INVALID_RELEASES_PATH =\n 'juno.cdn.storage.error.invalid_releases_path';\n\nexport const JUNO_CDN_STORAGE_ERROR_MISSING_RELEASES_DESCRIPTION =\n 'juno.cdn.storage.error.missing_releases_description';\n\nexport const JUNO_CDN_STORAGE_ERROR_INVALID_RELEASES_DESCRIPTION =\n 'juno.cdn.storage.error.invalid_releases_description';\n\nexport const JUNO_CDN_STORAGE_ERROR_INVALID_COLLECTION =\n 'juno.cdn.storage.error.invalid_collection';\n", "export const JUNO_COLLECTIONS_ERROR_MODIFY_RESERVED_COLLECTION =\n 'juno.collections.error.modify_reserved_collection';\nexport const JUNO_COLLECTIONS_ERROR_RESERVED_NAME = 'juno.collections.error.reserved_name';\nexport const JUNO_COLLECTIONS_ERROR_RESERVED_COLLECTION =\n 'juno.collections.error.reserved_collection';\nexport const JUNO_COLLECTIONS_ERROR_RATE_CONFIG_ENABLED =\n 'juno.collections.error.rate_config_enabled';\nexport const JUNO_COLLECTIONS_ERROR_DELETE_PREFIX_RESERVED =\n 'juno.collections.error.prefix_deletion';\nexport const JUNO_COLLECTIONS_ERROR_COLLECTION_NOT_EMPTY = 'juno.collections.error.not_empty';\nexport const JUNO_COLLECTIONS_ERROR_COLLECTION_NOT_FOUND = 'juno.collections.error.not_found';\nexport const JUNO_COLLECTIONS_ERROR_PREFIX_RESERVED = 'juno.collections.error.prefix_reserved';\n", "export const JUNO_ERROR_NO_TIMESTAMP_PROVIDED = 'juno.error.no_timestamp_provided';\nexport const JUNO_ERROR_TIMESTAMP_OUTDATED_OR_FUTURE = 'juno.error.timestamp_outdated_or_future';\nexport const JUNO_ERROR_NO_VERSION_PROVIDED = 'juno.error.no_version_provided';\nexport const JUNO_ERROR_VERSION_OUTDATED_OR_FUTURE = 'juno.error.version_outdated_or_future';\n\nexport const JUNO_DATASTORE_ERROR_CANNOT_WRITE = 'juno.datastore.error.cannot_write';\nexport const JUNO_DATASTORE_ERROR_CANNOT_READ = 'juno.datastore.error.cannot_read';\n\nexport const JUNO_STORAGE_ERROR_UPLOAD_NOT_ALLOWED = 'juno.storage.error.upload_not_allowed';\nexport const JUNO_STORAGE_ERROR_SET_NOT_ALLOWED = 'juno.storage.error.set_not_allowed';\nexport const JUNO_STORAGE_ERROR_CANNOT_COMMIT_INVALID_COLLECTION =\n 'juno.storage.error.cannot_commit_invalid_collection';\nexport const JUNO_STORAGE_ERROR_CANNOT_COMMIT_BATCH = 'juno.storage.error.cannot_commit_batch';\nexport const JUNO_STORAGE_ERROR_ASSET_NOT_FOUND = 'juno.storage.error.asset_not_found';\nexport const JUNO_STORAGE_ERROR_CANNOT_READ_ASSET = 'juno.storage.error.cannot_read_asset';\nexport const JUNO_STORAGE_ERROR_UPLOAD_PATH_COLLECTION_PREFIX =\n 'juno.storage.error.upload_path_collection_prefix';\nexport const JUNO_STORAGE_ERROR_RESERVED_ASSET = 'juno.storage.error.reserved_asset';\nexport const JUNO_STORAGE_ERROR_BATCH_NOT_FOUND = 'juno.storage.error.batch_not_found';\nexport const JUNO_STORAGE_ERROR_CHUNK_NOT_FOUND = 'juno.storage.error.chunk_not_found';\nexport const JUNO_STORAGE_ERROR_CHUNK_NOT_INCLUDED_IN_BATCH =\n 'juno.storage.error.chunk_not_included_in_batch';\nexport const JUNO_STORAGE_ERROR_CHUNK_TO_COMMIT_NOT_FOUND =\n 'juno.storage.error.chunk_to_commit_not_found';\nexport const JUNO_STORAGE_ERROR_ASSET_MAX_ALLOWED_SIZE =\n 'juno.storage.error.asset_max_allowed_size';\n\nexport const JUNO_AUTH_ERROR_NOT_ADMIN_CONTROLLER = 'juno.auth.error.not_admin_controller';\nexport const JUNO_AUTH_ERROR_INVALID_ORIGIN = 'juno.auth.error.invalid_origin';\nexport const JUNO_AUTH_ERROR_NOT_WRITE_CONTROLLER = 'juno.auth.error.not_write_controller';\nexport const JUNO_AUTH_ERROR_NOT_CONTROLLER = 'juno.auth.error.not_controller';\nexport const JUNO_AUTH_ERROR_CALLER_NOT_ALLOWED = 'juno.auth.error.caller.not_allowed';\n\nexport const JUNO_DATASTORE_ERROR_USER_CANNOT_UPDATE = 'juno.datastore.error.user.cannot_update';\nexport const JUNO_DATASTORE_ERROR_USER_INVALID_DATA = 'juno.datastore.error.user.invalid_data';\nexport const JUNO_DATASTORE_ERROR_USER_CALLER_KEY = 'juno.datastore.error.user.caller_key';\nexport const JUNO_DATASTORE_ERROR_USER_KEY_NO_PRINCIPAL =\n 'juno.datastore.error.user.key_no_principal';\nexport const JUNO_DATASTORE_ERROR_USER_NOT_ALLOWED = 'juno.datastore.error.user.not_allowed';\nexport const JUNO_DATASTORE_ERROR_USER_AAGUID_INVALID_LENGTH =\n 'juno.datastore.error.user.webauthn.aaguid_invalid_length';\nexport const JUNO_DATASTORE_ERROR_USER_PROVIDER_INVALID_DATA =\n 'juno.datastore.error.user.webauthn.provider_invalid_data';\nexport const JUNO_DATASTORE_ERROR_USER_PROVIDER_WEBAUTHN_INVALID_DATA =\n 'juno.datastore.error.user.webauthn.provider_webauthn_invalid_data';\n\nexport const JUNO_DATASTORE_ERROR_USER_USAGE_CHANGE_LIMIT_REACHED =\n 'juno.datastore.error.user.usage.change_limit_reached';\nexport const JUNO_DATASTORE_ERROR_USER_USAGE_INVALID_DATA =\n 'juno.datastore.error.user.usage.invalid_data';\n\nexport const JUNO_DATASTORE_ERROR_USER_WEBAUTHN_CANNOT_UPDATE =\n 'juno.datastore.error.user.webauthn.cannot_update';\nexport const JUNO_DATASTORE_ERROR_USER_WEBAUTHN_INVALID_DATA =\n 'juno.datastore.error.user.webauthn.invalid_data';\nexport const JUNO_DATASTORE_ERROR_USER_WEBAUTHN_CALLER_KEY =\n 'juno.datastore.error.user.webauthn.caller_key';\n", "export const JUNO_ERROR_CONTROLLERS_MAX_NUMBER = 'juno.error.controllers.max_number';\nexport const JUNO_ERROR_CONTROLLERS_ANONYMOUS_NOT_ALLOWED =\n 'juno.error.controllers.anonymous_not_allowed';\nexport const JUNO_ERROR_CONTROLLERS_REVOKED_NOT_ALLOWED =\n 'juno.error.controllers.revoked_not_allowed';\n\nexport const JUNO_ERROR_MEMORY_STABLE_EXCEEDED = 'juno.error.memory.stable_exceeded';\nexport const JUNO_ERROR_MEMORY_HEAP_EXCEEDED = 'juno.error.memory.heap_exceeded';\n\nexport const JUNO_ERROR_CYCLES_DEPOSIT_BALANCE_LOW = 'juno.error.cycles.deposit_balance_low';\nexport const JUNO_ERROR_CYCLES_DEPOSIT_FAILED = 'juno.error.cycles.deposit_failed';\n\nexport const JUNO_ERROR_CANISTER_CREATE_FAILED = 'juno.error.canister.create_failed';\nexport const JUNO_ERROR_CANISTER_INSTALL_CODE_FAILED = 'juno.error.canister.install_code_failed';\n\nexport const JUNO_ERROR_SEGMENT_STOP_FAILED = 'juno.error.segment.stop_failed';\nexport const JUNO_ERROR_SEGMENT_DELETE_FAILED = 'juno.error.segment.delete_failed';\n\nexport const JUNO_ERROR_CMC_CALL_LEDGER_FAILED = 'juno.error.cmc.call_ledger_failed';\nexport const JUNO_ERROR_CMC_LEDGER_TRANSFER_FAILED = 'juno.error.cmc.ledger_transfer_failed';\nexport const JUNO_ERROR_CMC_TOP_UP_FAILED = 'juno.error.cmc.top_up_failed';\nexport const JUNO_ERROR_CMC_CALL_CREATE_CANISTER_FAILED =\n 'juno.error.cmc.call_create_canister_failed';\nexport const JUNO_ERROR_CMC_CREATE_CANISTER_FAILED = 'juno.error.cmc.create_canister_failed';\nexport const JUNO_ERROR_CMC_INSTALL_CODE_FAILED = 'juno.error.cmc.install_code_failed';\n\nexport const JUNO_ERROR_INVALID_REGEX = 'juno.error.invalid_regex';\n", "import {isNullish, nonNullish} from '@dfinity/utils';\nimport {isSatelliteError, JUNO_DATASTORE_ERROR_USER_CANNOT_UPDATE} from '@junobuild/errors';\nimport {getDoc, setDoc} from '../../datastore/services/doc.services';\nimport {InitError} from '../types/errors';\nimport type {Provider} from '../types/provider';\nimport type {User, UserData} from '../types/user';\nimport {getIdentity} from './auth.services';\n\ntype UserId = string;\n\nexport const initUser = async ({provider}: {provider: Provider}): Promise<User> => {\n const {user, userId} = await loadUser();\n\n // For returning users we do not need to create a user entry.\n // Sign-in, sign-out, and sign-in again.\n if (nonNullish(user)) {\n return user;\n }\n\n try {\n return await createUser({userId, provider});\n } catch (error: unknown) {\n // It's unlikely, but since updating a user is restricted to the controller,\n // we want to guard against a rare race condition where a user attempts\n // to create a user entry that already exists. In such a case, instead of\n // throwing, we retry loading the user data. If that succeeds, it provides\n // a more graceful UX.\n //\n // With the new flow introduced in core library v2, this scenario should\n // never occur, but the handling remains given it was already implemented\n // with the earlier flow where user creation could happen during init.\n if (isSatelliteError({error, type: JUNO_DATASTORE_ERROR_USER_CANNOT_UPDATE})) {\n const userOnCreateError = await getUser({userId});\n\n if (nonNullish(userOnCreateError)) {\n return userOnCreateError;\n }\n }\n\n throw error;\n }\n};\n\nexport const loadUser = async (): Promise<{userId: UserId; user: User | undefined}> => {\n const identity = getIdentity();\n\n if (isNullish(identity)) {\n throw new InitError('No identity to initialize the user. Have you initialized Juno?');\n }\n\n const userId = identity.getPrincipal().toText();\n\n const user = await getUser({userId});\n\n return {\n userId,\n user\n };\n};\n\nconst getUser = ({userId}: {userId: UserId}): Promise<User | undefined> =>\n getDoc<UserData>({\n collection: `#user`,\n key: userId\n });\n\nconst createUser = ({\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 {isNullish} from '@dfinity/utils';\nimport {ActorStore} from '../../core/stores/actor.store';\nimport {AgentStore} from '../../core/stores/agent.store';\nimport {executeWithWindowGuard} from '../helpers/window.helpers';\nimport {InternetIdentityProvider} from '../providers/internet-identity.providers';\nimport {NFIDProvider} from '../providers/nfid.providers';\nimport {WebAuthnProvider} from '../providers/webauthn.providers';\nimport {AuthStore} from '../stores/auth.store';\nimport type {SignInOptions, SignOutOptions, SignUpOptions} from '../types/auth';\nimport {SignInProviderNotSupportedError, SignUpProviderNotSupportedError} from '../types/errors';\nimport type {Provider} from '../types/provider';\nimport type {User} from '../types/user';\nimport {createAuthClient, resetAuthClient} from '../utils/auth.utils';\nimport {initUser, loadUser} from './_user.services';\n\nlet authClient: AuthClient | undefined | null;\n\n/**\n * Initialize the authClient and load the existing user.\n * Executed when the library is initialized through initSatellite.\n */\nexport const loadAuth = async () => {\n const init = async () => {\n const {user} = await loadUser();\n AuthStore.getInstance().set(user ?? null);\n };\n\n await authenticate({fn: init});\n};\n\n/**\n * Initialize the authClient, load the user passed as parameter.\n * Executed on sign-up.\n */\nconst loadAuthWithUser = async ({user}: {user: User}) => {\n // eslint-disable-next-line require-await\n const init = async () => {\n AuthStore.getInstance().set(user);\n };\n\n await authenticate({fn: init});\n};\n\n/**\n * Initialize the authClient, load or create a new user.\n * Executed on sign-in.\n */\nexport const createAuth = async ({provider}: {provider: Provider}) => {\n const init = async () => {\n const user = await initUser({provider});\n AuthStore.getInstance().set(user);\n };\n\n await authenticate({fn: init});\n};\n\n/**\n * Initializes a new `AuthClient`, checks authentication state,\n * and executes the provided function if already authenticated.\n *\n * - Always creates a fresh `AuthClient` using {@link createAuthClient}.\n * - If the client is **not authenticated**, it resets the client via {@link resetAuthClient}\n * to ensure a clean session.\n * - If authenticated, it runs the given async function `fn`.\n *\n * @param {Object} params\n * @param {() => Promise<void>} params.fn - The asynchronous function to execute when authenticated.\n *\n * @returns {Promise<void>} Resolves when authentication is handled and the provided function is executed (if applicable).\n */\nconst authenticate = async ({fn}: {fn: () => Promise<void>}) => {\n authClient = await createAuthClient();\n\n const isAuthenticated = await authClient.isAuthenticated();\n\n if (!isAuthenticated) {\n authClient = await resetAuthClient();\n return;\n }\n\n await fn();\n};\n\n/**\n * Signs in a user with the specified options.\n *\n * @default Signs in by default with Internet Identity\n * @param {SignInOptions} [options] - The options for signing in including the provider to use for the process.\n * @returns {Promise<void>} A promise that resolves when the sign-in process is complete and the authenticated user is initialized.\n */\nexport const signIn = async (options: SignInOptions): Promise<void> => {\n const fn = async () => await signInWithProvider(options);\n\n const disableWindowGuard = Object.values(options)[0].context?.windowGuard === false;\n\n if (disableWindowGuard) {\n await fn();\n return;\n }\n\n await executeWithWindowGuard({fn});\n};\n\n/**\n * Signs up to create a new user with the specified options.\n *\n * @param {SignUpOptions} [options] - The options for signing up including the provider to use for the process.\n * @returns {Promise<void>} A promise that resolves when the sign-up process is complete and the user is authenticated.\n */\nexport const signUp = async (options: SignUpOptions): Promise<void> => {\n const fn = async () => await signUpWithProvider(options);\n\n const disableWindowGuard = Object.values(options)?.[0].context?.windowGuard === false;\n\n if (disableWindowGuard) {\n await fn();\n return;\n }\n\n await executeWithWindowGuard({fn});\n};\n\nconst signInWithProvider = async (options: SignInOptions): Promise<void> => {\n if ('webauthn' in options) {\n const {\n webauthn: {options: signInOptions}\n } = options;\n\n await new WebAuthnProvider().signIn({\n options: signInOptions,\n loadAuth\n });\n return;\n }\n\n if ('nfid' in options) {\n const {\n nfid: {options: nfidOptions}\n } = options;\n\n const {appName, logoUrl, ...signInOptions} = nfidOptions ?? {};\n\n await new NFIDProvider({appName, logoUrl}).signIn({\n options: signInOptions,\n authClient,\n initAuth: createAuth\n });\n return;\n }\n\n if ('internet_identity' in options) {\n const {\n internet_identity: {options: iiOptions}\n } = options;\n\n const {domain, ...signInOptions} = iiOptions ?? {};\n\n await new InternetIdentityProvider({domain}).signIn({\n options: signInOptions,\n authClient,\n initAuth: createAuth\n });\n return;\n }\n\n throw new SignInProviderNotSupportedError(\n 'An unknown or unsupported provider was provided for sign-in.'\n );\n};\n\nconst signUpWithProvider = async (options: SignUpOptions): Promise<void> => {\n if ('webauthn' in options) {\n const {\n webauthn: {options: signUpOptions}\n } = options;\n\n await new WebAuthnProvider().signUp({\n options: signUpOptions,\n loadAuthWithUser\n });\n return;\n }\n\n throw new SignUpProviderNotSupportedError(\n 'An unknown or unsupported provider was provided for sign-up.'\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 (options?: SignOutOptions): Promise<void> => {\n await resetAuth();\n\n // Recreate an HttpClient immediately because next sign-in, if window is not reloaded, would fail if the agent is created within the process.\n // For example, Safari blocks the Internet Identity (II) window if the agent is created during the interaction.\n // Agent-js must be created either globally or at least before performing a sign-in.\n // We proceed with this reset regardless of the window reloading. This way we ensure it is reset not matter what.\n authClient = await createAuthClient();\n\n if (options?.windowReload === false) {\n return;\n }\n\n window.location.reload();\n};\n\n/**\n * \u2139\uFE0F Exposed for testing purpose only. Should not be leaked to consumer or used by the library.\n */\nexport const resetAuth = async () => {\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 // Technically we do not need this since we recreate the agent below. We just keep it to make the reset explicit.\n authClient = null;\n\n AuthStore.getInstance().reset();\n\n ActorStore.getInstance().reset();\n AgentStore.getInstance().reset();\n};\n\nexport const getIdentity = (): Identity | undefined => authClient?.getIdentity();\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\n/**\n * Returns the current identity if the user is authenticated.\n *\n * \u26A0\uFE0F Use this function imperatively only. Do **not** persist the identity in global state.\n * It is intended for short-lived or one-time operations.\n *\n * Typical use case is to enable developers to implement custom features for the Internet Computer:\n * - Passing the identity to temporarily create an actor or agent to call a canister\n * - Signing a message or making a one-time authenticated call\n *\n * @returns The authenticated identity, or null if unavailable.\n */\nexport const getIdentityOnce = async (): Promise<Identity | null> => {\n const user = AuthStore.getInstance().get();\n\n if (isNullish(user)) {\n return null;\n }\n\n const authenticated = (await authClient?.isAuthenticated()) ?? false;\n\n if (!authenticated) {\n return null;\n }\n\n return authClient?.getIdentity() ?? null;\n};\n", "import {isNullish} from '@dfinity/utils';\nimport type {EnvironmentWorker} from '../../core/types/env';\nimport type {Unsubscribe} from '../../core/types/subscription';\nimport {AuthStore} from '../stores/auth.store';\nimport type {PostMessage, PostMessageDataResponseAuth} from '../types/post-message';\nimport type {User} from '../types/user';\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.\ninterface ImportMeta {\n env: Record<string, string> | undefined;\n}\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' && typeof process.env !== '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' && typeof process.env !== 'undefined'\n ? (process.env.NEXT_PUBLIC_CONTAINER ?? viteEnvContainer())\n : viteEnvContainer();\n};\n", "import type {ActorSubclass} from '@dfinity/agent';\nimport type {ActorMethod} from '@dfinity/agent/lib/esm/actor';\nimport type {IDL} from '@dfinity/candid';\nimport {getSatelliteExtendedActor as getSatelliteExtendedActorApi} from '../../core/api/actor.api';\nimport {getAnyIdentity} from '../../core/services/identity.services';\nimport type {SatelliteOptions} from '../../core/types/satellite';\n\n/**\n * Returns an extended satellite actor instance using the provided IDL factory and satellite options.\n *\n * This function is intended for advanced use cases where developers have implemented\n * custom endpoints in their serverless functions using the extended build type.\n *\n * In most cases, developers should not need to call this directly.\n * Extended actors are typically mapped and handled automatically.\n *\n * @template T - The actor interface type.\n *\n * @param {Object} params - The parameters for creating the actor.\n * @param {IDL.InterfaceFactory} params.idlFactory - The IDL factory defining the custom actor interface.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only.\n * In browser environments, configuration is automatically inherited from `initSatellite()`.\n *\n * @returns {Promise<ActorSubclass<T>>} A promise that resolves to the extended actor instance.\n */\nexport const getSatelliteExtendedActor = async <T = Record<string, ActorMethod>>({\n idlFactory,\n satellite\n}: {\n idlFactory: IDL.InterfaceFactory;\n satellite?: SatelliteOptions;\n}): Promise<ActorSubclass<T>> => {\n const identity = getAnyIdentity(satellite?.identity);\n\n return await getSatelliteExtendedActorApi({\n idlFactory,\n ...satellite,\n identity\n });\n};\n", "import {assertNonNullish, toNullable} from '@dfinity/utils';\nimport type {ConsoleDid, SatelliteDid} from '@junobuild/ic-client/actor';\nimport {isBrowser} from '@junobuild/utils';\nimport {UPLOAD_CHUNK_SIZE} from '../constants/upload.constants';\nimport type {EncodingType} from '../types/storage';\nimport type {UploadAsset, UploadParams, UploadWithProposalParams} from '../types/upload';\n\ntype InitAssetKey = SatelliteDid.InitAssetKey | ConsoleDid.InitAssetKey;\ntype UploadChunk = SatelliteDid.UploadChunk | ConsoleDid.UploadChunk;\ntype CommitBatch = SatelliteDid.CommitBatch | ConsoleDid.CommitBatch;\n\nexport const uploadAsset = async ({\n asset: {data, headers, ...restAsset},\n actor,\n progress\n}: {\n asset: UploadAsset;\n} & UploadParams): Promise<void> => {\n const {init_asset_upload, upload_asset_chunk, commit_asset_upload} = actor;\n\n const {batch_id: batchId} = await init_asset_upload(mapInitAssetUploadParams(restAsset));\n\n progress?.onInitiatedBatch();\n\n const {chunkIds} = await uploadChunks({data, uploadFn: upload_asset_chunk, batchId});\n\n progress?.onUploadedFileChunks(restAsset.fullPath);\n\n await commitAsset({\n commitFn: commit_asset_upload,\n batchId,\n data,\n headers,\n chunkIds\n });\n\n progress?.onCommittedBatch();\n};\n\nexport const uploadAssetWithProposal = async ({\n asset: {data, headers, ...restAsset},\n proposalId,\n actor,\n progress\n}: {\n asset: UploadAsset;\n} & UploadWithProposalParams): Promise<void> => {\n const {init_proposal_asset_upload, upload_proposal_asset_chunk, commit_proposal_asset_upload} =\n actor;\n\n progress?.onInitiatedBatch();\n\n const {batch_id: batchId} = await init_proposal_asset_upload(\n mapInitAssetUploadParams(restAsset),\n proposalId\n );\n\n const {chunkIds} = await uploadChunks({data, uploadFn: upload_proposal_asset_chunk, batchId});\n\n progress?.onUploadedFileChunks(restAsset.fullPath);\n\n await commitAsset({\n commitFn: commit_proposal_asset_upload,\n batchId,\n data,\n headers,\n chunkIds\n });\n\n progress?.onCommittedBatch();\n};\n\nexport const uploadAssetsWithProposal = async ({\n assets,\n proposalId,\n actor,\n progress\n}: {\n assets: UploadAsset[];\n} & UploadWithProposalParams): Promise<void> => {\n const {\n init_proposal_many_assets_upload,\n upload_proposal_asset_chunk,\n commit_proposal_many_assets_upload\n } = actor;\n\n const batchIds = await init_proposal_many_assets_upload(\n assets.map(mapInitAssetUploadParams),\n proposalId\n );\n\n progress?.onInitiatedBatch();\n\n const uploadAssetChunk = async ({\n fullPath,\n data,\n headers\n }: UploadAsset): Promise<BatchToCommit> => {\n const initializedBatch = batchIds.find(([batchIdFullPath]) => batchIdFullPath === fullPath);\n\n assertNonNullish(initializedBatch);\n\n const [_, initUpload] = initializedBatch;\n const {batch_id: batchId} = initUpload;\n\n const {chunkIds} = await uploadChunks({data, uploadFn: upload_proposal_asset_chunk, batchId});\n\n progress?.onUploadedFileChunks(fullPath);\n\n return {\n batchId,\n headers,\n chunkIds,\n data\n };\n };\n\n const batchAndChunkIdsToCommit = await Promise.all(assets.map(uploadAssetChunk));\n\n await commit_proposal_many_assets_upload(batchAndChunkIdsToCommit.map(mapCommitBatch));\n\n progress?.onCommittedBatch();\n};\n\nconst mapInitAssetUploadParams = ({\n filename,\n collection,\n token,\n fullPath,\n encoding,\n description\n}: Omit<UploadAsset, 'headers' | 'data'>): InitAssetKey => ({\n collection,\n full_path: fullPath,\n name: filename,\n token: toNullable<string>(token),\n encoding_type: toNullable<EncodingType>(encoding),\n description: toNullable(description)\n});\n\ntype BatchToCommit = {\n batchId: bigint;\n chunkIds: UploadChunkResult[];\n} & Pick<UploadAsset, 'headers' | 'data'>;\n\nconst mapCommitBatch = ({batchId, chunkIds, headers, data}: BatchToCommit): CommitBatch => {\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 return {\n batch_id: batchId,\n chunk_ids: chunkIds.map(({chunk_id}: UploadChunkResult) => chunk_id),\n headers: [...headers, ...(contentType ?? [])]\n };\n};\n\nconst commitAsset = async ({\n commitFn,\n ...rest\n}: {\n commitFn: (commitBatch: CommitBatch) => Promise<void>;\n batchId: bigint;\n chunkIds: UploadChunkResult[];\n} & Pick<UploadAsset, 'headers' | 'data'>) => {\n const commitBatch = mapCommitBatch(rest);\n await commitFn(commitBatch);\n};\n\nconst uploadChunks = async ({\n data,\n uploadFn,\n batchId\n}: {\n batchId: bigint;\n} & Pick<UploadAsset, 'data'> &\n Pick<UploadChunkParams, 'uploadFn'>): Promise<{chunkIds: UploadChunkResult[]}> => {\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 += UPLOAD_CHUNK_SIZE) {\n const chunk: Blob = clone.slice(start, start + UPLOAD_CHUNK_SIZE);\n\n uploadChunks.push({\n batchId,\n chunk,\n uploadFn,\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 return {chunkIds};\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\ninterface UploadChunkResult {\n chunk_id: bigint;\n}\n\ninterface UploadChunkParams {\n batchId: bigint;\n chunk: Blob;\n uploadFn: (uploadChunk: UploadChunk) => Promise<UploadChunkResult>;\n orderId: bigint;\n}\n\nconst uploadChunk = async ({\n batchId,\n chunk,\n uploadFn,\n orderId\n}: UploadChunkParams): Promise<UploadChunkResult> =>\n uploadFn({\n batch_id: batchId,\n content: new Uint8Array(await chunk.arrayBuffer()),\n order_id: toNullable(orderId)\n });\n", "import {fromNullable} from '@dfinity/utils';\nimport type {SatelliteDid} from '@junobuild/ic-client/actor';\nimport {\n uploadAsset as uploadAssetStorage,\n type AssetKey,\n type UploadAsset\n} from '@junobuild/storage';\nimport {getSatelliteActor} from '../../core/api/actor.api';\nimport type {ActorReadParams, ActorUpdateParams} from '../../core/types/actor';\nimport type {ListParams, ListResults} from '../../core/types/list';\nimport {toListParams} from '../../core/utils/list.utils';\n\nexport const uploadAsset = async ({\n asset,\n ...rest\n}: {asset: UploadAsset} & ActorUpdateParams): Promise<void> => {\n const actor = await getSatelliteActor(rest);\n\n await uploadAssetStorage({\n actor,\n asset\n });\n};\n\nexport const listAssets = async ({\n collection,\n filter,\n ...rest\n}: {\n collection: string;\n filter: ListParams;\n} & ActorReadParams): Promise<ListResults<SatelliteDid.AssetNoContent>> => {\n const {list_assets} = await getSatelliteActor(rest);\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 filter,\n ...rest\n}: {\n collection: string;\n filter: ListParams;\n} & ActorReadParams): Promise<bigint> => {\n const {count_assets} = await getSatelliteActor(rest);\n\n return count_assets(collection, toListParams(filter));\n};\n\nexport const deleteAsset = async ({\n collection,\n fullPath,\n ...rest\n}: {\n collection: string;\n} & ActorUpdateParams &\n Pick<AssetKey, 'fullPath'>): Promise<void> => {\n const actor = await getSatelliteActor(rest);\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} & ActorUpdateParams): Promise<void> => {\n const {del_many_assets} = await getSatelliteActor({satellite, options: {certified: true}});\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 deleteFilteredAssets = async ({\n collection,\n filter,\n ...rest\n}: {\n collection: string;\n filter: ListParams;\n} & ActorUpdateParams): Promise<void> => {\n const {del_filtered_assets} = await getSatelliteActor(rest);\n\n return del_filtered_assets(collection, toListParams(filter));\n};\n\nexport const getAsset = async ({\n collection,\n fullPath,\n ...rest\n}: {\n collection: string;\n} & ActorReadParams &\n Pick<AssetKey, 'fullPath'>): Promise<SatelliteDid.AssetNoContent | undefined> => {\n const {get_asset} = await getSatelliteActor(rest);\n return fromNullable(await get_asset(collection, fullPath));\n};\n\nexport const getManyAssets = async ({\n assets,\n ...rest\n}: {\n assets: ({collection: string} & Pick<AssetKey, 'fullPath'>)[];\n} & ActorReadParams): Promise<(SatelliteDid.AssetNoContent | undefined)[]> => {\n const {get_many_assets} = await getSatelliteActor(rest);\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 {fromNullable, nonNullish} from '@dfinity/utils';\nimport type {SatelliteDid} from '@junobuild/ic-client/actor';\nimport type {Asset, AssetEncoding, AssetKey, Storage} from '@junobuild/storage';\nimport {DEFAULT_READ_OPTIONS} from '../../core/constants/call-options.constants';\nimport {getAnyIdentity} from '../../core/services/identity.services';\nimport type {ReadOptions} from '../../core/types/call-options';\nimport type {ListParams} from '../../core/types/list';\nimport type {SatelliteOptions} from '../../core/types/satellite';\nimport {satelliteUrl} from '../../core/utils/env.utils';\nimport {\n countAssets as countAssetsApi,\n deleteAsset as deleteAssetApi,\n deleteFilteredAssets as deleteFilteredAssetsApi,\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 {Assets} from '../types/storage';\nimport {sha256ToBase64String} from '../utils/crypto.utils';\n\n/**\n * Uploads a blob to the storage.\n *\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\n * @returns {Promise<AssetKey>} A promise that resolves to the asset key.\n */\nexport const uploadBlob = (params: Storage & {satellite?: SatelliteOptions}): Promise<AssetKey> =>\n uploadAssetIC(params);\n\n/**\n * Uploads a file to the storage.\n *\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\n * @returns {Promise<AssetKey>} A promise that resolves to the asset key.\n */\nexport const uploadFile = (\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 = getAnyIdentity(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 asset: {\n data,\n filename,\n collection,\n token,\n headers,\n fullPath,\n encoding,\n description\n },\n satellite,\n options: {certified: true}\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 *\n * @param {Object} params - The parameters for listing the assets.\n * @param {string} params.collection - The name of the collection.\n * @param {ListParams} [params.filter] - The filter parameters.\n * @param {ReadOptions} [params.options] - Call options controlling certification. Defaults to uncertified reads for performance unless specified.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\n * @returns {Promise<Assets>} A promise that resolves to the list of assets.\n */\nexport const listAssets = async ({\n collection,\n filter,\n satellite: satelliteOptions,\n options\n}: {\n collection: string;\n filter?: ListParams;\n satellite?: SatelliteOptions;\n options?: ReadOptions;\n}): Promise<Assets> => {\n const satellite = {...satelliteOptions, identity: getAnyIdentity(satelliteOptions?.identity)};\n\n const {items, ...rest} = await listAssetsApi({\n collection,\n filter: filter ?? {},\n satellite,\n options: options ?? DEFAULT_READ_OPTIONS\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 }: SatelliteDid.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<Record<string, AssetEncoding>>(\n (acc, [type, {modified, sha256, total_length}]) => ({\n ...acc,\n [type]: {\n modified,\n sha256: sha256ToBase64String(sha256),\n total_length\n }\n }),\n {}\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 *\n * @param {Object} params - The parameters for counting the assets.\n * @param {string} params.collection - The name of the collection.\n * @param {ListParams} [params.filter] - The filter parameters for narrowing down the count.\n * @param {ReadOptions} [params.options] - Call options controlling certification. Defaults to uncertified reads for performance unless specified.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\n * @returns {Promise<bigint>} A promise that resolves to the count of assets as a bigint.\n */\nexport const countAssets = async ({\n collection,\n filter,\n satellite: satelliteOptions,\n options\n}: {\n collection: string;\n filter?: ListParams;\n satellite?: SatelliteOptions;\n options?: ReadOptions;\n}): Promise<bigint> => {\n const satellite = {...satelliteOptions, identity: getAnyIdentity(satelliteOptions?.identity)};\n\n return await countAssetsApi({\n collection,\n satellite,\n filter: filter ?? {},\n options: options ?? DEFAULT_READ_OPTIONS\n });\n};\n\n/**\n * Deletes an asset from the storage.\n *\n * @param {Object} params - The parameters for deleting the asset.\n * @param {string} params.collection - The name of the collection.\n * @param {string} params.fullPath - The full path of the asset.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\n * @returns {Promise<void>} A promise that resolves when the asset is deleted.\n */\nexport const deleteAsset = ({\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: getAnyIdentity(satellite?.identity)},\n options: {certified: true}\n });\n\n/**\n * Deletes multiple assets from the storage.\n *\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] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\n * @returns {Promise<void>} A promise that resolves when the assets are deleted.\n */\nexport const deleteManyAssets = ({\n assets,\n satellite\n}: {\n assets: ({collection: string} & Pick<AssetKey, 'fullPath'>)[];\n satellite?: SatelliteOptions;\n}): Promise<void> =>\n deleteManyAssetsApi({\n assets,\n satellite: {...satellite, identity: getAnyIdentity(satellite?.identity)},\n options: {certified: true}\n });\n\n/**\n * Deletes multiple assets from a collection based on filtering criteria.\n *\n * @param {Object} params - The parameters for deleting the assets.\n * @param {string} params.collection - The name of the collection from which to delete assets.\n * @param {ListParams} [params.filter] - The filter criteria to match assets for deletion.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\n * @returns {Promise<void>} A promise that resolves when the assets matching the filter criteria are deleted.\n */\nexport const deleteFilteredAssets = async ({\n collection,\n satellite: satelliteOptions,\n filter\n}: {\n collection: string;\n satellite?: SatelliteOptions;\n filter?: ListParams;\n}): Promise<void> => {\n const satellite = {...satelliteOptions, identity: getAnyIdentity(satelliteOptions?.identity)};\n\n return await deleteFilteredAssetsApi({\n collection,\n satellite,\n filter: filter ?? {},\n options: {certified: true}\n });\n};\n\n/**\n * Retrieves an asset from the storage.\n *\n * @param {Object} params - The parameters for retrieving the asset.\n * @param {string} params.collection - The name of the collection.\n * @param {string} params.fullPath - The full path of the asset.\n * @param {ReadOptions} [params.options] - Call options controlling certification. Defaults to uncertified reads for performance unless specified.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\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 options,\n ...rest\n}: {\n collection: string;\n satellite?: SatelliteOptions;\n options?: ReadOptions;\n} & Pick<AssetKey, 'fullPath'>): Promise<SatelliteDid.AssetNoContent | undefined> => {\n const identity = getAnyIdentity(satellite?.identity);\n\n return await getAssetApi({\n ...rest,\n satellite: {...satellite, identity},\n options: options ?? DEFAULT_READ_OPTIONS\n });\n};\n\n/**\n * Retrieves multiple assets from the storage.\n *\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 {ReadOptions} [params.options] - Call options controlling certification. Defaults to uncertified reads for performance unless specified.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\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 options,\n ...rest\n}: {\n assets: ({collection: string} & Pick<AssetKey, 'fullPath'>)[];\n satellite?: SatelliteOptions;\n options?: ReadOptions;\n}): Promise<(SatelliteDid.AssetNoContent | undefined)[]> => {\n const identity = getAnyIdentity(satellite?.identity);\n\n return await getManyAssetsApi({\n ...rest,\n satellite: {...satellite, identity},\n options: options ?? DEFAULT_READ_OPTIONS\n });\n};\n\n/**\n * Returns a public URL for accessing a specific asset stored on a Satellite.\n *\n * This URL can be used to:\n * - Open the file directly in a browser\n * - Embed the asset in HTML elements like `<img src=\"...\">`, `<video src=\"...\">`, or `<a href=\"...\">`\n * - Programmatically download or display the asset in your application\n *\n * ### Example\n * ```ts\n * const url = downloadUrl({\n * assetKey: {\n * fullPath: '/images/logo.png',\n * }\n * });\n *\n * // Usage in an <img> tag\n * <img src={url} alt=\"Logo\" />\n * ```\n *\n * @param {Object} params - Parameters for generating the URL.\n * @param {Object} params.assetKey - Identifies the asset to generate the URL for.\n * @param {string} params.assetKey.fullPath - The full path of the asset (e.g., `/folder/file.jpg`).\n * @param {string} [params.assetKey.token] - Optional access token for accessing protected assets.\n * @param {SatelliteOptions} [params.satellite] - Options to specify a satellite in a NodeJS environment only. In browser environments, the satellite configuration is inherited from the initialization through `initSatellite()`.\n * @returns {string} A full URL pointing to the asset.\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: getAnyIdentity(satelliteOptions?.identity)};\n\n return `${satelliteUrl(satellite)}${fullPath}${nonNullish(token) ? `?token=${token}` : ''}`;\n};\n", "import {assertNonNullish} from '@dfinity/utils';\nimport {isWebAuthnAvailable} from '@junobuild/ic-client/webauthn';\nimport type {Asset, AssetEncoding, AssetKey, EncodingType, Storage} from '@junobuild/storage';\nimport {initAuthTimeoutWorker} from './auth/services/auth-timout.services';\nimport {loadAuth} from './auth/services/auth.services';\nimport {AuthStore} from './auth/stores/auth.store';\nimport type {User} from './auth/types/user';\nimport {EnvStore} from './core/stores/env.store';\nimport type {Environment, UserEnvironment} from './core/types/env';\nimport type {Unsubscribe} from './core/types/subscription';\nimport {envContainer, envSatelliteId} from './core/utils/window.env.utils';\nexport * from './auth/providers/internet-identity.providers';\nexport * from './auth/providers/nfid.providers';\nexport {\n getIdentityOnce,\n signIn,\n signOut,\n signUp,\n unsafeIdentity\n} from './auth/services/auth.services';\nexport type * from './auth/types/auth';\nexport * from './auth/types/auth-client';\nexport * from './auth/types/errors';\nexport type * from './auth/types/progress';\nexport type * from './auth/types/provider';\nexport type * from './auth/types/user';\nexport * from './auth/types/webauthn';\nexport type * from './core/types/env';\nexport {ListOrder, ListPaginate, ListParams, ListResults} from './core/types/list';\nexport type * from './core/types/satellite';\nexport type * from './core/types/subscription';\nexport type * from './core/types/utility';\nexport * from './datastore/services/doc.services';\nexport type * from './datastore/types/doc';\nexport * from './functions/services/functions.services';\nexport * from './storage/services/storage.services';\nexport type * from './storage/types/storage';\nexport {isWebAuthnAvailable};\nexport type {Asset, AssetEncoding, AssetKey, EncodingType, 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 * @deprecated Use {@link initSatellite} instead.\n */\nexport const initJuno = (userEnv?: UserEnvironment): Promise<Unsubscribe[]> =>\n initSatellite(userEnv);\n\n/**\n * Initializes a 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 loadAuth();\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 onAuthStateChange = (callback: (authUser: User | null) => void): Unsubscribe =>\n AuthStore.getInstance().subscribe(callback);\n\n/**\n * @deprecated Use {@link onAuthStateChange} instead.\n */\nexport const authSubscribe = onAuthStateChange;\nexport {InternetIdentityConfig, InternetIdentityDomain} from './auth/types/internet-identity';\nexport {NFIDConfig} from './auth/types/nfid';\n"],
5
+ "mappings": "8QAAA,IAAAA,GAAAC,GAAAC,IAAA,cAEAA,GAAQ,WAAaC,GACrBD,GAAQ,YAAcE,GACtBF,GAAQ,cAAgBG,GAExB,IAAIC,EAAS,CAAC,EACVC,EAAY,CAAC,EACbC,GAAM,OAAO,WAAe,IAAc,WAAa,MAEvDC,GAAO,mEACX,IAASC,GAAI,EAAGC,GAAMF,GAAK,OAAQC,GAAIC,GAAK,EAAED,GAC5CJ,EAAOI,EAAC,EAAID,GAAKC,EAAC,EAClBH,EAAUE,GAAK,WAAWC,EAAC,CAAC,EAAIA,GAFzB,IAAAA,GAAOC,GAOhBJ,EAAU,EAAiB,EAA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B,SAAUI,EAAeJ,GAAkB,QAAQ,CAAC,EAE5F,MAAO,GAAGoC,GAAa7B,CAAS,CAAC,GAAGD,CAAQ,GAAG+B,EAAWtC,CAAK,EAAI,UAAUA,CAAK,GAAK,EAAE,EAC3F,ECnUA,IAAMuC,GAAYC,GAA2C,CAC3D,IAAMC,EAAcD,GAAS,aAAeE,GAAe,EAE3DC,GAAiBF,EAAa,6DAA6D,EAE3F,IAAMG,EAAYJ,GAAS,WAAaK,GAAa,EAErD,MAAO,CACL,YAAAJ,EACA,mBAAoBD,GAAS,mBAC7B,QAASA,GAAS,QAClB,UAAAI,CACF,CACF,EAKaE,GAAYN,GACvBO,GAAcP,CAAO,EAQVO,GAAgB,MAAOP,GAAsD,CACxF,IAAMQ,EAAMT,GAASC,CAAO,EAE5BS,EAAS,YAAY,EAAE,IAAID,CAAG,EAE9B,MAAME,GAAS,EAEf,IAAMC,EACJH,EAAI,SAAS,OAAS,OAAYI,GAAsBJ,EAAI,QAAQ,IAAI,EAAI,OAE9E,MAAO,CAAC,GAAIG,EAAgB,CAACA,CAAa,EAAI,CAAC,CAAE,CACnD,EAOaE,GAAqBC,GAChCC,EAAU,YAAY,EAAE,UAAUD,CAAQ,EAK/BH,GAAgBE",
6
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", "import_buffer", "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", "defaultStrategy", "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_block_height", "bitcoin_get_block_headers_args", "bitcoin_block_header", "bitcoin_get_block_headers_result", "bitcoin_get_current_fee_percentiles_args", "millisatoshi_per_byte", "bitcoin_get_current_fee_percentiles_result", "bitcoin_get_utxos_args", "bitcoin_block_hash", "outpoint", "utxo", "bitcoin_get_utxos_result", "bitcoin_send_transaction_args", "canister_id", "canister_info_args", "change_origin", "snapshot_id", "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", "delete_canister_snapshot_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", "list_canister_snapshots_args", "snapshot", "list_canister_snapshots_result", "load_canister_snapshot_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", "schnorr_algorithm", "schnorr_public_key_args", "schnorr_public_key_result", "sign_with_ecdsa_args", "sign_with_ecdsa_result", "schnorr_aux", "sign_with_schnorr_args", "sign_with_schnorr_result", "start_canister_args", "stop_canister_args", "stored_chunks_args", "stored_chunks_result", "subnet_info_args", "subnet_info_result", "take_canister_snapshot_args", "take_canister_snapshot_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", "reject_code", "reject_message", "error_code", "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", "reply", "certificate", "cert", "Certificate", "bufFromBufLike", "path", "lookupResultToBuffer", "rejectCode", "rejectMessage", "error_code_buf", "pollStrategy", "pollForResponse", "shouldIncludeHttpDetails", "shouldIncludeCertificate", "handler", "transform", "first", "management_idl_default", "FromStringToTokenError", "E8S_PER_TOKEN", "isNullish", "argument", "nonNullish", "NullishError", "assertNonNullish", "value", "message", "arrayBufferToUint8Array", "buffer", "uint8ArrayToArrayOfNumber", "array", "uint8ArraysEqual", "a", "b", "byte", "i", "ALPHABET", "LOOKUP_TABLE", "i", "uint8ArrayToBase64", "uint8Array", "lookUpTable", "JSON_KEY_BIGINT", "JSON_KEY_PRINCIPAL", "JSON_KEY_UINT8ARRAY", "jsonReplacer", "_key", "value", "nonNullish", "Principal", "jsonReviver", "mapValue", "key", "toNullable", "value", "nonNullish", "fromNullable", "extractAAGUID", "authData", "bytes", "result", "bytesToAAGUID", "aaguid", "uint8ArrayToArrayOfNumber", "byte", "_authDataToCose", "dataView", "idLenBytes", "v", "i", "credentialIdLength", "_coseToDerEncodedBlob", "cose", "wrapDER", "DER_COSE_OID", "CosePublicKey", "_cose", "WebAuthnCredential", "#credentialId", "#publicKey", "credentialId", "uint8ArrayToBase64", "WebAuthnNewCredential", "#aaguidText", "#aaguidBytes", "rest", "optionAaguid", "WebAuthnExistingCredential", "WebAuthnIdentityHostnameError", "WebAuthnIdentityCredentialNotInitializedError", "WebAuthnIdentityCreateCredentialOnTheDeviceError", "WebAuthnIdentityCredentialNotPublicKeyError", "WebAuthnIdentityNoAttestationError", "WebAuthnIdentityInvalidCredentialIdError", "WebAuthnIdentityEncodeCborSignatureError", "WebAuthnIdentityNoAuthenticatorDataError", "PUBLIC_KEY_COSE_ALGORITHMS", "AUTHENTICATOR_ABORT_TIMEOUT", "randomValue", "createChallenge", "createUserId", "hostname", "href", "url", "isNullish", "WebAuthnIdentityHostnameError", "relyingPartyId", "appId", "createPasskeyOptions", "userOptions", "name", "relyingParty", "user", "algorithm", "retrievePasskeyOptions", "options", "execute", "fn", "step", "onProgress", "result", "err", "WebAuthnSignProgressStep", "createAbortSignal", "timeout", "retrieveCredentials", "challenge", "credentialIds", "passkeyOptions", "id", "assertWebAuthnStateInitialized", "state", "WebAuthnIdentityCredentialNotInitializedError", "assertNonNullishCredential", "credential", "WebAuthnIdentityCreateCredentialOnTheDeviceError", "assertCredentialPublicKey", "type", "WebAuthnIdentityCredentialNotPublicKeyError", "WebAuthnIdentity", "_WebAuthnIdentity", "SignIdentity", "#onSignProgress", "#state", "args", "retrievePublicKey", "#createInitializedState", "WebAuthnNewCredential", "restArgs", "attestationObject", "rawId", "WebAuthnIdentityNoAttestationError", "authData", "Cbor", "cose", "_authDataToCose", "arrayBufferToUint8Array", "blob", "uint8ArraysEqual", "WebAuthnIdentityInvalidCredentialIdError", "WebAuthnExistingCredential", "response", "clientDataJSON", "authenticatorData", "signature", "WebAuthnIdentityNoAuthenticatorDataError", "encoded", "WebAuthnIdentityEncodeCborSignatureError", "isWebAuthnAvailable", "nonNullish", "Store", "data", "callback", "callbackId", "id", "AuthStore", "_AuthStore", "Store", "authUser", "callback", "unsubscribe", "emit", "message", "detail", "$event", "DOCKER_CONTAINER_URL", "DOCKER_INTERNET_IDENTITY_ID", "createAgent", "identity", "container", "host", "s", "DOCKER_CONTAINER_URL", "shouldFetchRootKey", "HttpAgent", "AgentStore", "_AgentStore", "#agents", "u", "identity", "rest", "key", "agent", "createAgent", "ActorStore", "_ActorStore", "#actors", "u", "satelliteId", "identity", "actorKey", "rest", "key", "actor", "idlFactory", "canisterId", "agent", "AgentStore", "Actor", "onBeforeUnload", "$event", "addBeforeUnload", "removeBeforeUnload", "executeWithWindowGuard", "fn", "EnvStore", "_EnvStore", "Store", "env", "callback", "unsubscribe", "DELEGATION_IDENTITY_EXPIRATION", "ALLOW_PIN_AUTHENTICATION", "II_POPUP", "NFID_POPUP", "INTERNET_COMPUTER_ORG", "toArray", "data", "blob", "jsonReplacer", "fromArray", "jsonReviver", "isBrowser", "popupCenter", "width", "height", "p", "u", "innerWidth", "innerHeight", "y", "x", "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", "execute", "fn", "step", "onProgress", "result", "err", "AuthClientSignInProgressStep", "SignInError", "SignInInitError", "SignInUserInterruptError", "SignInProviderNotSupportedError", "WebAuthnSignInRetrievePublicKeyError", "SignUpProviderNotSupportedError", "InitError", "ListError", "AuthClientProvider", "options", "authClient", "initAuth", "execute", "#loginWithAuthClient", "resolve", "reject", "u", "SignInInitError", "error", "ERROR_USER_INTERRUPT", "SignInUserInterruptError", "SignInError", "DELEGATION_IDENTITY_EXPIRATION", "ALLOW_PIN_AUTHENTICATION", "InternetIdentityProvider", "AuthClientProvider", "#domain", "domain", "windowed", "identityProviderUrl", "container", "EnvStore", "u", "INTERNET_COMPUTER_ORG", "env", "internetIdentityId", "s", "DOCKER_INTERNET_IDENTITY_ID", "containerHost", "protocol", "DOCKER_CONTAINER_URL", "popupCenter", "II_POPUP", "NFIDProvider", "AuthClientProvider", "#appName", "#logoUrl", "appName", "logoUrl", "windowed", "popupCenter", "NFID_POPUP", "DEFAULT_READ_OPTIONS", "getAnyIdentity", "identity", "s", "getIdentity", "AnonymousIdentity", "idlFactory", "IDL", "CommitBatch", "CommitProposal", "ListOrderField", "ListOrder", "TimestampMatcher", "ListMatcher", "ListPaginate", "ListParams", "DeleteControllersArgs", "ControllerScope", "Controller", "DelDoc", "CollectionType", "DelRule", "DeleteProposalAssets", "DepositCyclesArgs", "AssetKey", "AssetEncodingNoContent", "AssetNoContent", "AuthenticationConfigInternetIdentity", "AuthenticationRules", "AuthenticationConfig", "ConfigMaxMemorySize", "DbConfig", "StorageConfigIFrame", "StorageConfigRawAccess", "StorageConfigRedirect", "StorageConfig", "Config", "Doc", "ProposalStatus", "AssetsUpgradeOptions", "SegmentsDeploymentOptions", "ProposalType", "Proposal", "Memory", "Permission", "RateConfig", "Rule", "HttpRequest", "StreamingCallbackToken", "StreamingStrategy", "HttpResponse", "StreamingCallbackHttpResponse", "InitAssetKey", "InitUploadResult", "ListResults", "CustomDomain", "ListResults_1", "ListProposalsOrder", "ListProposalsPaginate", "ListProposalsParams", "ProposalKey", "ListProposalResults", "ListRulesMatcher", "ListRulesParams", "ListRulesResults", "MemorySize", "SetAuthenticationConfig", "SetController", "SetControllersArgs", "SetDbConfig", "SetDoc", "SetRule", "SetStorageConfig", "UploadChunk", "UploadChunkResult", "satelliteUrl", "customSatelliteId", "customContainer", "satelliteId", "customOrEnvSatelliteId", "container", "customOrEnvContainer", "s", "containerHost", "protocol", "DOCKER_CONTAINER_URL", "EnvStore", "getSatelliteActor", "satellite", "certified", "getActor", "ft", "Vt", "getSatelliteExtendedActor", "idlFactory", "rest", "customSatelliteId", "customContainer", "satelliteId", "customOrEnvSatelliteId", "f", "container", "customOrEnvContainer", "ActorStore", "toListMatcherTimestamp", "matcher", "u", "re", "ListError", "toListParams", "paginate", "order", "owner", "Principal", "mapData", "data", "i", "err", "toSetDoc", "doc", "data", "version", "description", "re", "a", "toDelDoc", "fromDoc", "key", "owner", "docDescription", "rest", "K", "i", "getDoc", "collection", "key", "rest", "get_doc", "getSatelliteActor", "doc", "K", "u", "fromDoc", "getManyDocs", "docs", "get_many_docs", "payload", "resultsDocs", "results", "resultDoc", "s", "setDoc", "set_doc", "toSetDoc", "updatedDoc", "setManyDocs", "set_many_docs", "updatedDocs", "deleteDoc", "del_doc", "toDelDoc", "deleteManyDocs", "del_many_docs", "deleteFilteredDocs", "filter", "del_filtered_docs", "toListParams", "listDocs", "list_docs", "items", "items_page", "items_length", "matches_length", "matches_pages", "item", "dataArray", "owner", "description", "version", "mapData", "countDocs", "count_docs", "getDoc", "satellite", "options", "rest", "identity", "getAnyIdentity", "DEFAULT_READ_OPTIONS", "getManyDocs", "setDoc", "setManyDocs", "deleteDoc", "deleteManyDocs", "deleteFilteredDocs", "filter", "listDocs", "countDocs", "createWebAuthnUser", "delegationIdentity", "passkeyIdentity", "satelliteId", "aaguid", "user", "_", "setManyDocs", "s", "Ut", "It", "WebAuthnSignInProgressStep", "WebAuthnSignUpProgressStep", "WebAuthnProvider", "onProgress", "maxTimeToLiveInMilliseconds", "passkeyOptions", "loadAuthWithUser", "satelliteId", "EnvStore", "u", "SignInInitError", "onSignProgress", "step", "state", "N", "passkeyIdentity", "execute", "F", "delegationIdentity", "sessionKey", "#createSessionDelegation", "user", "createWebAuthnUser", "#saveSessionIdentityForAuthClient", "loadAuth", "retrievePublicKey", "credentialId", "doc", "getDoc", "Ct", "AnonymousIdentity", "WebAuthnSignInRetrievePublicKeyError", "data", "publicKey", "unwrapDER", "DER_COSE_OID", "identity", "ECDSAKeyIdentity", "sessionLengthInMilliseconds", "chain", "DelegationChain", "DelegationIdentity", "storage", "IdbStorage", "KEY_STORAGE_KEY", "KEY_STORAGE_DELEGATION", "createAuthClient", "AuthClient", "resetAuthClient", "IdbStorage", "KEY_STORAGE_KEY", "isSatelliteError", "error", "type", "JUNO_DATASTORE_ERROR_USER_CANNOT_UPDATE", "initUser", "provider", "user", "userId", "loadUser", "s", "createUser", "error", "t", "R_", "userOnCreateError", "getUser", "identity", "getIdentity", "u", "InitError", "getDoc", "rest", "setDoc", "authClient", "loadAuth", "authenticate", "user", "loadUser", "AuthStore", "loadAuthWithUser", "createAuth", "provider", "initUser", "fn", "createAuthClient", "resetAuthClient", "signIn", "options", "signInWithProvider", "executeWithWindowGuard", "signUp", "signUpWithProvider", "signInOptions", "WebAuthnProvider", "nfidOptions", "appName", "logoUrl", "NFIDProvider", "iiOptions", "domain", "InternetIdentityProvider", "SignInProviderNotSupportedError", "signUpOptions", "SignUpProviderNotSupportedError", "signOut", "resetAuth", "ActorStore", "AgentStore", "getIdentity", "unsafeIdentity", "getIdentityOnce", "u", "initAuthTimeoutWorker", "auth", "workerUrl", "worker", "timeoutSignOut", "emit", "signOut", "data", "msg", "value", "AuthStore", "user", "u", "envSatelliteId", "viteEnvSatelliteId", "envContainer", "viteEnvContainer", "getSatelliteExtendedActor", "idlFactory", "satellite", "identity", "getAnyIdentity", "uploadAsset", "data", "headers", "restAsset", "actor", "progress", "init_asset_upload", "upload_asset_chunk", "commit_asset_upload", "batchId", "mapInitAssetUploadParams", "chunkIds", "uploadChunks", "commitAsset", "mapInitAssetUploadParams", "filename", "collection", "token", "fullPath", "encoding", "description", "toNullable", "mapCommitBatch", "batchId", "chunkIds", "headers", "data", "contentType", "type", "_", "chunk_id", "commitAsset", "commitFn", "rest", "commitBatch", "uploadChunks", "uploadFn", "clone", "isBrowser", "orderId", "start", "chunk", "results", "batchUploadChunks", "limit", "i", "batch", "params", "uploadChunk", "uploadAsset", "asset", "rest", "actor", "getSatelliteActor", "K", "listAssets", "collection", "filter", "list_assets", "assets", "items_length", "items_page", "matches_length", "matches_pages", "toListParams", "_", "countAssets", "count_assets", "deleteAsset", "fullPath", "deleteManyAssets", "satellite", "del_many_assets", "payload", "deleteFilteredAssets", "del_filtered_assets", "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", "getAnyIdentity", "filename", "fullPath", "satellite", "uploadAsset", "downloadUrl", "listAssets", "filter", "options", "items", "rest", "DEFAULT_READ_OPTIONS", "assets", "t", "name", "owner", "encodings", "created_at", "updated_at", "K", "acc", "type", "modified", "sha256", "total_length", "sha256ToBase64String", "countAssets", "deleteAsset", "deleteManyAssets", "deleteFilteredAssets", "getAsset", "getManyAssets", "satelliteUrl", "s", "parseEnv", "userEnv", "satelliteId", "envSatelliteId", "f", "container", "envContainer", "initJuno", "initSatellite", "env", "EnvStore", "loadAuth", "authSubscribe", "initAuthTimeoutWorker", "onAuthStateChange", "callback", "AuthStore"]
7
7
  }