{"version":3,"file":"worker.js","sources":["../../node_modules/base64-js/index.js","../node_modules/@dfinity/agent/lib/esm/agent/api.js","../../node_modules/ieee754/index.js","../../node_modules/buffer/index.js","../node_modules/@dfinity/principal/lib/esm/utils/base32.js","../node_modules/@dfinity/principal/lib/esm/utils/getCrc.js","../../node_modules/@noble/hashes/esm/_assert.js","../../node_modules/@noble/hashes/esm/crypto.js","../../node_modules/@noble/hashes/esm/utils.js","../../node_modules/@noble/hashes/esm/_md.js","../../node_modules/@noble/hashes/esm/sha256.js","../node_modules/@dfinity/principal/lib/esm/index.js","../node_modules/@dfinity/principal/lib/esm/utils/sha224.js","../node_modules/@dfinity/agent/lib/esm/utils/buffer.js","../node_modules/@dfinity/candid/lib/esm/utils/buffer.js","../node_modules/@dfinity/candid/lib/esm/utils/leb128.js","../node_modules/@dfinity/candid/lib/esm/utils/bigint-math.js","../node_modules/@dfinity/candid/lib/esm/idl.js","../../node_modules/borc/node_modules/buffer/index.js","../../node_modules/bignumber.js/bignumber.js","../../node_modules/borc/src/decoder.asm.js","../../node_modules/borc/src/constants.js","../../node_modules/borc/src/utils.js","../../node_modules/borc/src/simple.js","../../node_modules/borc/src/tagged.js","../../node_modules/iso-url/src/url-browser.js","../../node_modules/iso-url/src/relative.js","../../node_modules/iso-url/index.js","../../node_modules/borc/src/decoder.js","../../node_modules/borc/src/diagnose.js","../../node_modules/borc/src/encoder.js","../../node_modules/borc/src/index.js","../node_modules/@dfinity/agent/lib/esm/request_id.js","../node_modules/@dfinity/agent/lib/esm/auth.js","../../node_modules/simple-cbor/src/value.js","../../node_modules/simple-cbor/src/serializer.js","../../node_modules/simple-cbor/src/index.js","../node_modules/@dfinity/agent/lib/esm/cbor.js","../node_modules/@dfinity/agent/lib/esm/agent/http/types.js","../node_modules/@dfinity/agent/lib/esm/agent/http/transforms.js","../../node_modules/@noble/curves/esm/abstract/utils.js","../../node_modules/@noble/curves/esm/abstract/modular.js","../../node_modules/@noble/curves/esm/abstract/hash-to-curve.js","../../node_modules/@noble/curves/esm/abstract/curve.js","../../node_modules/@noble/curves/esm/abstract/weierstrass.js","../../node_modules/@noble/curves/esm/abstract/bls.js","../../node_modules/@noble/curves/esm/bls12-381.js","../node_modules/@dfinity/agent/lib/esm/certificate.js","../../node_modules/@noble/hashes/esm/_u64.js","../../node_modules/@noble/hashes/esm/sha512.js","../../node_modules/@noble/curves/esm/abstract/edwards.js","../../node_modules/@noble/curves/esm/ed25519.js","../node_modules/@dfinity/agent/lib/esm/agent/http/index.js","../node_modules/@dfinity/agent/lib/esm/agent/proxy.js","../node_modules/@dfinity/agent/lib/esm/der.js","../node_modules/@dfinity/identity/lib/esm/identity/ed25519.js","../node_modules/@dfinity/identity/lib/esm/identity/ecdsa.js","../node_modules/@dfinity/identity/lib/esm/identity/delegation.js","../node_modules/@dfinity/identity/lib/esm/identity/webauthn.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/agent/api.js","../../openchat-agent/node_modules/@dfinity/principal/lib/esm/utils/base32.js","../../openchat-agent/node_modules/@dfinity/principal/lib/esm/utils/getCrc.js","../../openchat-agent/node_modules/@dfinity/principal/lib/esm/index.js","../../openchat-agent/node_modules/@dfinity/principal/lib/esm/utils/sha224.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/utils/buffer.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/errors.js","../../openchat-agent/node_modules/@dfinity/candid/lib/esm/utils/buffer.js","../../openchat-agent/node_modules/@dfinity/candid/lib/esm/utils/hash.js","../../openchat-agent/node_modules/@dfinity/candid/lib/esm/utils/leb128.js","../../openchat-agent/node_modules/@dfinity/candid/lib/esm/utils/bigint-math.js","../../openchat-agent/node_modules/@dfinity/candid/lib/esm/idl.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/request_id.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/auth.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/cbor.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/utils/random.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/agent/http/types.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/agent/http/transforms.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/agent/http/errors.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/utils/bls.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/utils/leb.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/certificate.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/canisterStatus/index.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/utils/expirableMap.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/der.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/public_key.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/observable.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/polling/backoff.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/constants.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/agent/http/index.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/agent/proxy.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/agent/index.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/polling/strategy.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/polling/index.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/canisters/management_idl.js","../../openchat-agent/node_modules/@dfinity/agent/lib/esm/actor.js","../../node_modules/idb/build/wrap-idb-value.js","../../node_modules/idb/build/index.js","../../openchat-shared/lib/domain/auth.js","../../openchat-shared/node_modules/@dfinity/agent/lib/esm/agent/api.js","../../openchat-shared/lib/utils/bigint.js","../../openchat-shared/lib/utils/chat.js","../../openchat-shared/node_modules/@dfinity/principal/lib/esm/utils/base32.js","../../openchat-shared/node_modules/@dfinity/principal/lib/esm/utils/getCrc.js","../../openchat-shared/node_modules/@dfinity/principal/lib/esm/index.js","../../openchat-shared/node_modules/@dfinity/principal/lib/esm/utils/sha224.js","../../openchat-shared/node_modules/@dfinity/agent/lib/esm/utils/buffer.js","../../openchat-shared/node_modules/@dfinity/candid/lib/esm/utils/buffer.js","../../openchat-shared/node_modules/@dfinity/candid/lib/esm/utils/leb128.js","../../openchat-shared/node_modules/@dfinity/candid/lib/esm/utils/bigint-math.js","../../openchat-shared/node_modules/@dfinity/candid/lib/esm/idl.js","../../openchat-shared/node_modules/@dfinity/agent/lib/esm/request_id.js","../../openchat-shared/node_modules/@dfinity/agent/lib/esm/auth.js","../../openchat-shared/node_modules/@dfinity/agent/lib/esm/cbor.js","../../openchat-shared/node_modules/@dfinity/agent/lib/esm/agent/http/types.js","../../openchat-shared/node_modules/@dfinity/agent/lib/esm/certificate.js","../../openchat-shared/node_modules/@dfinity/agent/lib/esm/agent/http/index.js","../../openchat-shared/node_modules/@dfinity/agent/lib/esm/agent/proxy.js","../../openchat-shared/node_modules/@dfinity/agent/lib/esm/agent/http/transforms.js","../../openchat-shared/node_modules/@dfinity/agent/lib/esm/der.js","../../openchat-shared/node_modules/@dfinity/identity/lib/esm/identity/ecdsa.js","../../openchat-shared/node_modules/@dfinity/identity/lib/esm/identity/delegation.js","../../openchat-shared/node_modules/@dfinity/identity/lib/esm/identity/webauthn.js","../../openchat-shared/lib/utils/identity.js","../../openchat-shared/node_modules/@dfinity/auth-client/lib/esm/db.js","../../openchat-shared/node_modules/@dfinity/auth-client/lib/esm/storage.js","../../openchat-shared/lib/utils/identityStorage.js","../../openchat-shared/lib/utils/lazy.js","../../node_modules/rollbar/dist/rollbar.umd.min.js","../../openchat-shared/lib/constants.js","../../openchat-shared/lib/utils/network.js","../../openchat-shared/lib/utils/logging.js","../../openchat-shared/lib/utils/map.js","../../openchat-shared/lib/utils/promise.js","../../openchat-shared/lib/utils/rng.js","../../openchat-shared/lib/utils/session.js","../../openchat-shared/lib/utils/string.js","../../openchat-shared/lib/domain/chat/chat.js","../../openchat-shared/lib/domain/error.js","../../openchat-shared/lib/domain/events.js","../../openchat-shared/lib/domain/inviteCodes.js","../../openchat-shared/lib/domain/optionUpdate.js","../../openchat-shared/lib/domain/permission.js","../../openchat-shared/lib/domain/response.js","../../openchat-shared/lib/domain/stream.js","../../openchat-shared/lib/domain/user/user.js","../../openchat-agent/lib/utils/caching.js","../../openchat-agent/lib/utils/network.js","../../openchat-agent/lib/utils/userCache.js","../../openchat-agent/lib/utils/registryCache.js","../../openchat-agent/lib/utils/list.js","../../openchat-agent/lib/services/error.js","../../node_modules/process/browser.js","../../openchat-agent/lib/services/canisterAgent/base.js","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/value/guard/guard.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/system/policy.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/registry/format.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/registry/type.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/guard/value.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/create/immutable.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/clone/value.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/create/type.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/symbols/symbols.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/error/error.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/mapped/mapped-result.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/discard/discard.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/array/array.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/async-iterator/async-iterator.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/constructor/constructor.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/function/function.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/computed/computed.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/never/never.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/guard/kind.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/optional/optional.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/optional/optional-from-mapped-result.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/intersect/intersect-create.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/intersect/intersect-evaluated.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/intersect/intersect.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/union/union-create.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/union/union-evaluated.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/union/union.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/template-literal/parse.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/template-literal/finite.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/template-literal/generate.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/literal/literal.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/boolean/boolean.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/bigint/bigint.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/number/number.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/string/string.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/template-literal/syntax.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/patterns/patterns.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/template-literal/pattern.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/template-literal/union.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/template-literal/template-literal.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-property-keys.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-from-mapped-result.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/indexed/indexed.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-from-mapped-key.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/iterator/iterator.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/object/object.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/promise/promise.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/readonly/readonly.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/readonly/readonly-from-mapped-result.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/tuple/tuple.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/mapped/mapped.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/sets/set.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/ref/ref.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/keyof/keyof-property-keys.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/keyof/keyof.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/keyof/keyof-from-mapped-result.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/keyof/keyof-property-entries.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/extends/extends-undefined.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/errors/function.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/value/deref/deref.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/value/hash/hash.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/any/any.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/unknown/unknown.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/guard/type.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/extends/extends-check.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/errors/errors.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/extends/extends-from-mapped-result.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/extends/extends.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/extends/extends-from-mapped-key.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/value/check/check.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/value/assert/assert.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/value/clone/clone.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/value/clean/clean.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/value/convert/convert.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/value/transform/decode.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/value/transform/encode.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/value/transform/has.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/value/default/default.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/value/parse/parse.mjs","../../openchat-agent/lib/utils/nullish.js","../../openchat-agent/lib/utils/typebox.js","../../openchat-agent/node_modules/msgpackr/unpack.js","../../openchat-agent/node_modules/msgpackr/pack.js","../../openchat-agent/lib/utils/msgpack.js","../../openchat-agent/lib/services/canisterAgent/msgpack.js","../../openchat-agent/lib/utils/mapping.js","../../openchat-agent/lib/services/common/pinNumberErrorMapper.js","../../openchat-agent/lib/services/common/chatMappersV2.js","../../openchat-agent/lib/services/common/commonResponseMapper.js","../../openchat-agent/lib/services/community/mappersV2.js","../../openchat-agent/lib/services/userIndex/mappers.js","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/awaited/awaited.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/composite/composite.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/date/date.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/null/null.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/symbol/symbol.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/undefined/undefined.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/uint8array/uint8array.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/const/const.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/exclude/exclude.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/exclude/exclude-from-template-literal.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/exclude/exclude-from-mapped-result.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/extract/extract.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/extract/extract-from-template-literal.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/extract/extract-from-mapped-result.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/intrinsic/intrinsic-from-mapped-key.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/intrinsic/intrinsic.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/omit/omit-from-mapped-result.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/omit/omit.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/omit/omit-from-mapped-key.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/pick/pick-from-mapped-result.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/pick/pick.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/pick/pick-from-mapped-key.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/partial/partial.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/partial/partial-from-mapped-result.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/record/record.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/required/required.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/required/required-from-mapped-result.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/module/compute.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/module/module.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/recursive/recursive.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/transform/transform.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/type/index.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/intrinsic/capitalize.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/constructor-parameters/constructor-parameters.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/enum/enum.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/instance-type/instance-type.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/integer/integer.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/intrinsic/lowercase.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/not/not.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/parameters/parameters.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/readonly-optional/readonly-optional.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/clone/type.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/regexp/regexp.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/rest/rest.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/return-type/return-type.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/intrinsic/uncapitalize.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/unsafe/unsafe.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/intrinsic/uppercase.mjs","../../openchat-agent/node_modules/@sinclair/typebox/build/esm/type/void/void.mjs","../../openchat-agent/lib/typebox.js","../../openchat-agent/lib/utils/id.js","../../openchat-agent/lib/services/userIndex/userIndex.client.js","../../openchat-agent/lib/services/common/replicaUpToDateChecker.js","../../openchat-agent/lib/services/user/mappersV2.js","../../node_modules/js-sha3/src/sha3.js","../../node_modules/identicon.js/pnglib.js","../../node_modules/identicon.js/identicon.js","../../node_modules/crypt/crypt.js","../../node_modules/charenc/charenc.js","../../node_modules/is-buffer/index.js","../../node_modules/md5/md5.js","../../openchat-agent/lib/utils/chat.js","../../openchat-agent/lib/services/storageIndex/candid/idl.js","../../openchat-agent/lib/services/canisterAgent/candid.js","../../openchat-agent/lib/services/storageIndex/mappers.js","../../openchat-agent/lib/services/storageIndex/storageIndex.client.js","../../openchat-agent/lib/services/storageBucket/candid/idl.js","../../openchat-agent/lib/services/storageBucket/mappers.js","../../openchat-agent/lib/services/storageBucket/storageBucket.client.js","../../openchat-agent/lib/services/data/data.client.js","../../openchat-agent/lib/utils/rng.js","../../openchat-agent/lib/services/common/chunked.js","../../openchat-agent/lib/services/notifications/mappers.js","../../openchat-agent/lib/services/user/user.client.js","../../openchat-shared/lib/domain/crypto.js","../../openchat-agent/lib/services/group/mappersV2.js","../../openchat-agent/lib/services/common/publicSummaryMapperV2.js","../../openchat-agent/lib/services/group/group.client.js","../../openchat-agent/lib/services/localUserIndex/mappers.js","../../openchat-agent/lib/services/localUserIndex/localUserIndex.client.js","../../openchat-agent/lib/services/notifications/notifications.client.js","../../openchat-agent/lib/services/proposalsBot/mappers.js","../../openchat-agent/lib/services/proposalsBot/proposalsBot.client.js","../../openchat-shared/lib/utils/time.js","../../openchat-agent/lib/services/online/mappers.js","../../openchat-agent/lib/services/online/online.client.js","../../openchat-agent/lib/services/ledger/candid/idl.js","../../openchat-agent/lib/services/ledger/ledger.client.js","../../openchat-agent/lib/services/ledgerIndex/candid/idl.js","../../openchat-agent/lib/services/ledgerIndex/mappers.js","../../openchat-agent/lib/services/common/chatMappers.js","../../openchat-agent/lib/services/ledgerIndex/ledgerIndex.client.js","../../openchat-agent/lib/services/groupIndex/mappers.js","../../openchat-agent/lib/services/groupIndex/groupIndex.client.js","../../openchat-agent/lib/services/marketMaker/candid/idl.js","../../openchat-agent/lib/services/marketMaker/mappers.js","../../openchat-agent/lib/services/marketMaker/marketMaker.client.js","../../openchat-agent/lib/services/registry/mappers.js","../../openchat-agent/lib/services/registry/registry.client.js","../../openchat-agent/lib/services/dexes/icpSwap/index/candid/idl.js","../../openchat-agent/lib/services/dexes/icpSwap/index/mappers.js","../../openchat-agent/lib/services/dexes/icpSwap/pool/candid/idl.js","../../openchat-agent/lib/services/dexes/icpSwap/pool/mappers.js","../../openchat-agent/lib/services/dexes/icpSwap/pool/icpSwap.pool.client.js","../../openchat-agent/lib/services/dexes/icpSwap/index/icpSwap.index.client.js","../../openchat-agent/lib/services/dexes/kongswap/candid/idl.js","../../openchat-agent/lib/services/dexes/kongswap/mappers.js","../../openchat-agent/lib/services/dexes/kongswap/kongswap.client.js","../../openchat-agent/lib/services/dexes/sonic/swaps/candid/idl.js","../../openchat-agent/lib/services/dexes/sonic/swaps/mappers.js","../../openchat-agent/lib/services/dexes/sonic/swaps/sonic.swaps.client.js","../../openchat-agent/lib/services/dexes/index.js","../../openchat-agent/lib/services/nnsGovernance/candid/idl.js","../../openchat-agent/lib/services/nnsGovernance/mappers.js","../../openchat-agent/lib/services/nnsGovernance/nns.governance.client.js","../../openchat-agent/lib/services/snsGovernance/candid/idl.js","../../openchat-agent/lib/services/snsGovernance/mappers.js","../../openchat-agent/lib/services/snsGovernance/sns.governance.client.js","../../openchat-agent/lib/utils/base64.js","../../openchat-agent/lib/utils/messageContext.js","../../openchat-agent/lib/services/community/community.client.js","../../openchat-agent/lib/utils/community.js","../../openchat-agent/lib/services/user/anonUser.client.js","../../openchat-agent/lib/services/icpcoins/candid/idl.js","../../openchat-agent/lib/services/icpcoins/mappers.js","../../openchat-agent/lib/services/icpcoins/icpCoinsClient.js","../../openchat-agent/lib/services/icpSwap/candid/idl.js","../../openchat-agent/lib/services/icpSwap/icpSwapClient.js","../../openchat-agent/lib/services/icpSwap/mappers.js","../../openchat-agent/lib/services/icpLedgerIndex/candid/idl.js","../../openchat-agent/lib/services/icpLedgerIndex/mappers.js","../../openchat-agent/lib/services/icpLedgerIndex/icpLedgerIndex.client.js","../../openchat-agent/lib/services/translations/candid/idl.js","../../openchat-agent/lib/services/translations/mappers.js","../../openchat-agent/lib/services/translations/translations.client.js","../../openchat-agent/lib/services/ckbtcMinter/candid/idl.js","../../openchat-agent/lib/services/bitcoin/mappers.js","../../openchat-agent/lib/services/ckbtcMinter/ckbtcMinter.client.js","../../openchat-agent/lib/services/signInWithEmail/candid/idl.js","../../openchat-agent/lib/services/signInWithEmail/mappers.js","../../openchat-agent/node_modules/@dfinity/identity/lib/esm/identity/delegation.js","../../openchat-agent/node_modules/@dfinity/identity/lib/esm/identity/webauthn.js","../../openchat-agent/lib/services/identity/mappers.js","../../openchat-agent/lib/services/signInWithEmail/signInWithEmail.client.js","../../openchat-agent/lib/services/signInWithEthereum/candid/idl.js","../../openchat-agent/lib/services/signInWithEthereum/mappers.js","../../openchat-agent/lib/services/signInWithEthereum/signInWithEthereum.client.js","../../openchat-agent/lib/services/signInWithSolana/candid/idl.js","../../openchat-agent/lib/services/signInWithSolana/mappers.js","../../openchat-agent/lib/services/signInWithSolana/signInWithSolana.client.js","../../openchat-agent/lib/utils/httpAgent.js","../../openchat-agent/lib/utils/referralCache.js","../../openchat-agent/lib/utils/maths.js","../../openchat-agent/lib/services/externalBot/externalBot.js","../../openchat-agent/lib/services/bitcoin/candid/idl.js","../../openchat-agent/lib/services/bitcoin/bitcoin.client.js","../../openchat-agent/lib/services/openchatAgent.js","../../openchat-agent/lib/services/common/profiling.js","../../openchat-agent/lib/services/identity/candid/idl.js","../../openchat-agent/lib/services/identity/identity.client.js","../../openchat-agent/lib/utils/webAuthnKeyCache.js","../../openchat-agent/lib/services/identityAgent.js","../src/worker.ts"],"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 * Codes used by the replica for rejecting a message.\n * See {@link https://sdk.dfinity.org/docs/interface-spec/#reject-codes | the interface spec}.\n */\nexport var ReplicaRejectCode;\n(function (ReplicaRejectCode) {\n ReplicaRejectCode[ReplicaRejectCode[\"SysFatal\"] = 1] = \"SysFatal\";\n ReplicaRejectCode[ReplicaRejectCode[\"SysTransient\"] = 2] = \"SysTransient\";\n ReplicaRejectCode[ReplicaRejectCode[\"DestinationInvalid\"] = 3] = \"DestinationInvalid\";\n ReplicaRejectCode[ReplicaRejectCode[\"CanisterReject\"] = 4] = \"CanisterReject\";\n ReplicaRejectCode[ReplicaRejectCode[\"CanisterError\"] = 5] = \"CanisterError\";\n})(ReplicaRejectCode || (ReplicaRejectCode = {}));\n//# sourceMappingURL=api.js.map","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \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 ''\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","const alphabet = 'abcdefghijklmnopqrstuvwxyz234567';\n// Build a lookup table for decoding.\nconst lookupTable = Object.create(null);\nfor (let i = 0; i < alphabet.length; i++) {\n lookupTable[alphabet[i]] = i;\n}\n// Add aliases for rfc4648.\nlookupTable['0'] = lookupTable.o;\nlookupTable['1'] = lookupTable.i;\n/**\n * @param input The input array to encode.\n * @returns A Base32 string encoding the input.\n */\nexport function encode(input) {\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 // The output string in base32.\n let output = '';\n function encodeByte(byte) {\n if (skip < 0) {\n // we have a carry from the previous byte\n bits |= byte >> -skip;\n }\n else {\n // no carry\n bits = (byte << skip) & 248;\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 if (skip < 4) {\n // produce a character\n output += alphabet[bits >> 3];\n skip += 5;\n }\n return 0;\n }\n for (let i = 0; i < input.length;) {\n i += encodeByte(input[i]);\n }\n return output + (skip < 0 ? alphabet[bits >> 3] : '');\n}\n/**\n * @param input The base32 encoded string to decode.\n */\nexport function decode(input) {\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 const output = new Uint8Array(((input.length * 4) / 3) | 0);\n let o = 0;\n function decodeChar(char) {\n // Consume a character from the stream, store\n // the output in this.output. As before, better\n // to use update().\n let val = lookupTable[char.toLowerCase()];\n if (val === undefined) {\n throw new Error(`Invalid character: ${JSON.stringify(char)}`);\n }\n // move to the high bits\n val <<= 3;\n byte |= val >>> skip;\n skip += 5;\n if (skip >= 8) {\n // We have enough bytes to produce an output\n output[o++] = byte;\n skip -= 8;\n if (skip > 0) {\n byte = (val << (5 - skip)) & 255;\n }\n else {\n byte = 0;\n }\n }\n }\n for (const c of input) {\n decodeChar(c);\n }\n return output.slice(0, o);\n}\n//# sourceMappingURL=base32.js.map","// This file is translated to JavaScript from\n// https://lxp32.github.io/docs/a-simple-example-crc32-calculation/\nconst lookUpTable = new Uint32Array([\n 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,\n 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,\n 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,\n 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,\n 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,\n 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,\n 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,\n 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,\n 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,\n 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,\n 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,\n 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,\n 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,\n 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,\n 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,\n 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,\n 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,\n 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,\n 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,\n 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,\n 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,\n 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,\n 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,\n 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,\n 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,\n 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,\n 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,\n 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,\n 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,\n 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,\n 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,\n 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,\n]);\n/**\n * Calculate the CRC32 of an ArrayBufferLike.\n * @param buf The BufferLike to calculate the CRC32 of.\n */\nexport function getCrc32(buf) {\n const b = new Uint8Array(buf);\n let crc = -1;\n for (let i = 0; i < b.length; i++) {\n const byte = b[i];\n const t = (byte ^ crc) & 0xff;\n crc = lookUpTable[t] ^ (crc >>> 8);\n }\n return (crc ^ -1) >>> 0;\n}\n//# sourceMappingURL=getCrc.js.map","function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`positive integer expected, not ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`boolean expected, not ${b}`);\n}\n// copied from utils\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nfunction bytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(h.outputLen);\n number(h.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","export const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n//# sourceMappingURL=crypto.js.map","/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { bytes as abytes } from './_assert.js';\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\n// The rotate left (circular left shift) operation for uint32\nexport const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0);\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\n// The byte swap operation for uint32\nexport const byteSwap = (word) => ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// Conditionally byte swap if on a big-endian platform\nexport const byteSwapIfBE = isLE ? (n) => n : (n) => byteSwap(n);\n// In place byte swap for Uint32Array\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// For runtime check if class implements interface\nexport class Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nconst toStr = {}.toString;\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nexport function wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","import { exists, output } from './_assert.js';\nimport { Hash, createView, toBytes } from './utils.js';\n// Polyfill for Safari 14\nfunction setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n// Choice: a ? b : c\nexport const Chi = (a, b, c) => (a & b) ^ (~a & c);\n// Majority function, true if any two inpust is true\nexport const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n exists(this);\n output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n}\n//# sourceMappingURL=_md.js.map","import { HashMD, Chi, Maj } from './_md.js';\nimport { rotr, wrapConstructor } from './utils.js';\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n// Initial state:\n// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nclass SHA256 extends HashMD {\n constructor() {\n super(64, 32, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n constructor() {\n super();\n this.A = 0xc1059ed8 | 0;\n this.B = 0x367cd507 | 0;\n this.C = 0x3070dd17 | 0;\n this.D = 0xf70e5939 | 0;\n this.E = 0xffc00b31 | 0;\n this.F = 0x68581511 | 0;\n this.G = 0x64f98fa7 | 0;\n this.H = 0xbefa4fa4 | 0;\n this.outputLen = 28;\n }\n}\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n//# sourceMappingURL=sha256.js.map","import { decode, encode } from './utils/base32';\nimport { getCrc32 } from './utils/getCrc';\nimport { sha224 } from './utils/sha224';\nexport const JSON_KEY_PRINCIPAL = '__principal__';\nconst SELF_AUTHENTICATING_SUFFIX = 2;\nconst ANONYMOUS_SUFFIX = 4;\nconst MANAGEMENT_CANISTER_PRINCIPAL_HEX_STR = 'aaaaa-aa';\nconst fromHexString = (hexString) => { var _a; return new Uint8Array(((_a = hexString.match(/.{1,2}/g)) !== null && _a !== void 0 ? _a : []).map(byte => parseInt(byte, 16))); };\nconst toHexString = (bytes) => bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\nexport class Principal {\n constructor(_arr) {\n this._arr = _arr;\n this._isPrincipal = true;\n }\n static anonymous() {\n return new this(new Uint8Array([ANONYMOUS_SUFFIX]));\n }\n /**\n * Utility method, returning the principal representing the management canister, decoded from the hex string `'aaaaa-aa'`\n * @returns {Principal} principal of the management canister\n */\n static managementCanister() {\n return this.fromHex(MANAGEMENT_CANISTER_PRINCIPAL_HEX_STR);\n }\n static selfAuthenticating(publicKey) {\n const sha = sha224(publicKey);\n return new this(new Uint8Array([...sha, SELF_AUTHENTICATING_SUFFIX]));\n }\n static from(other) {\n if (typeof other === 'string') {\n return Principal.fromText(other);\n }\n else if (Object.getPrototypeOf(other) === Uint8Array.prototype) {\n return new Principal(other);\n }\n else if (typeof other === 'object' &&\n other !== null &&\n other._isPrincipal === true) {\n return new Principal(other._arr);\n }\n throw new Error(`Impossible to convert ${JSON.stringify(other)} to Principal.`);\n }\n static fromHex(hex) {\n return new this(fromHexString(hex));\n }\n static fromText(text) {\n let maybePrincipal = text;\n // If formatted as JSON string, parse it first\n if (text.includes(JSON_KEY_PRINCIPAL)) {\n const obj = JSON.parse(text);\n if (JSON_KEY_PRINCIPAL in obj) {\n maybePrincipal = obj[JSON_KEY_PRINCIPAL];\n }\n }\n const canisterIdNoDash = maybePrincipal.toLowerCase().replace(/-/g, '');\n let arr = decode(canisterIdNoDash);\n arr = arr.slice(4, arr.length);\n const principal = new this(arr);\n if (principal.toText() !== maybePrincipal) {\n throw new Error(`Principal \"${principal.toText()}\" does not have a valid checksum (original value \"${maybePrincipal}\" may not be a valid Principal ID).`);\n }\n return principal;\n }\n static fromUint8Array(arr) {\n return new this(arr);\n }\n isAnonymous() {\n return this._arr.byteLength === 1 && this._arr[0] === ANONYMOUS_SUFFIX;\n }\n toUint8Array() {\n return this._arr;\n }\n toHex() {\n return toHexString(this._arr).toUpperCase();\n }\n toText() {\n const checksumArrayBuf = new ArrayBuffer(4);\n const view = new DataView(checksumArrayBuf);\n view.setUint32(0, getCrc32(this._arr));\n const checksum = new Uint8Array(checksumArrayBuf);\n const bytes = Uint8Array.from(this._arr);\n const array = new Uint8Array([...checksum, ...bytes]);\n const result = encode(array);\n const matches = result.match(/.{1,5}/g);\n if (!matches) {\n // This should only happen if there's no character, which is unreachable.\n throw new Error();\n }\n return matches.join('-');\n }\n toString() {\n return this.toText();\n }\n /**\n * Serializes to JSON\n * @returns {JsonnablePrincipal} a JSON object with a single key, {@link JSON_KEY_PRINCIPAL}, whose value is the principal as a string\n */\n toJSON() {\n return { [JSON_KEY_PRINCIPAL]: this.toText() };\n }\n /**\n * Utility method taking a Principal to compare against. Used for determining canister ranges in certificate verification\n * @param {Principal} other - a {@link Principal} to compare\n * @returns {'lt' | 'eq' | 'gt'} `'lt' | 'eq' | 'gt'` a string, representing less than, equal to, or greater than\n */\n compareTo(other) {\n for (let i = 0; i < Math.min(this._arr.length, other._arr.length); i++) {\n if (this._arr[i] < other._arr[i])\n return 'lt';\n else if (this._arr[i] > other._arr[i])\n return 'gt';\n }\n // Here, at least one principal is a prefix of the other principal (they could be the same)\n if (this._arr.length < other._arr.length)\n return 'lt';\n if (this._arr.length > other._arr.length)\n return 'gt';\n return 'eq';\n }\n /**\n * Utility method checking whether a provided Principal is less than or equal to the current one using the {@link Principal.compareTo} method\n * @param other a {@link Principal} to compare\n * @returns {boolean} boolean\n */\n ltEq(other) {\n const cmp = this.compareTo(other);\n return cmp == 'lt' || cmp == 'eq';\n }\n /**\n * Utility method checking whether a provided Principal is greater than or equal to the current one using the {@link Principal.compareTo} method\n * @param other a {@link Principal} to compare\n * @returns {boolean} boolean\n */\n gtEq(other) {\n const cmp = this.compareTo(other);\n return cmp == 'gt' || cmp == 'eq';\n }\n}\n//# sourceMappingURL=index.js.map","import { sha224 as jsSha224 } from '@noble/hashes/sha256';\n/**\n * Returns the SHA224 hash of the buffer.\n * @param data Arraybuffer to encode\n */\nexport function sha224(data) {\n return jsSha224.create().update(new Uint8Array(data)).digest();\n}\n//# sourceMappingURL=sha224.js.map","/**\n * Concatenate multiple array buffers.\n * @param buffers The buffers to concatenate.\n */\nexport function concat(...buffers) {\n const result = new Uint8Array(buffers.reduce((acc, curr) => acc + curr.byteLength, 0));\n let index = 0;\n for (const b of buffers) {\n result.set(new Uint8Array(b), index);\n index += b.byteLength;\n }\n return result.buffer;\n}\n/**\n * Transforms a buffer to an hexadecimal string. This will use the buffer as an Uint8Array.\n * @param buffer The buffer to return the hexadecimal string of.\n */\nexport function toHex(buffer) {\n return [...new Uint8Array(buffer)].map(x => x.toString(16).padStart(2, '0')).join('');\n}\nconst hexRe = new RegExp(/^[0-9a-fA-F]+$/);\n/**\n * Transforms a hexadecimal string into an array buffer.\n * @param hex The hexadecimal string to use.\n */\nexport function fromHex(hex) {\n if (!hexRe.test(hex)) {\n throw new Error('Invalid hexadecimal string.');\n }\n const buffer = [...hex]\n .reduce((acc, curr, i) => {\n acc[(i / 2) | 0] = (acc[(i / 2) | 0] || '') + curr;\n return acc;\n }, [])\n .map(x => Number.parseInt(x, 16));\n return new Uint8Array(buffer).buffer;\n}\n/**\n *\n * @param b1 array buffer 1\n * @param b2 array buffer 2\n * @returns number - negative if b1 < b2, positive if b1 > b2, 0 if b1 === b2\n */\nexport function compare(b1, b2) {\n if (b1.byteLength !== b2.byteLength) {\n return b1.byteLength - b2.byteLength;\n }\n const u1 = new Uint8Array(b1);\n const u2 = new Uint8Array(b2);\n for (let i = 0; i < u1.length; i++) {\n if (u1[i] !== u2[i]) {\n return u1[i] - u2[i];\n }\n }\n return 0;\n}\n/**\n * Checks two array buffers for equality.\n * @param b1 array buffer 1\n * @param b2 array buffer 2\n * @returns boolean\n */\nexport function bufEquals(b1, b2) {\n return compare(b1, b2) === 0;\n}\n/**\n * Returns a true ArrayBuffer from a Uint8Array, as Uint8Array.buffer is unsafe.\n * @param {Uint8Array} arr Uint8Array to convert\n * @returns ArrayBuffer\n */\nexport function uint8ToBuf(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength).buffer;\n}\n/**\n * Returns a true ArrayBuffer from an ArrayBufferLike object.\n * @param bufLike a buffer-like object\n * @returns ArrayBuffer\n */\nexport function bufFromBufLike(bufLike) {\n if (bufLike instanceof Uint8Array) {\n return uint8ToBuf(bufLike);\n }\n if (bufLike instanceof ArrayBuffer) {\n return bufLike;\n }\n if (Array.isArray(bufLike)) {\n return uint8ToBuf(new Uint8Array(bufLike));\n }\n if ('buffer' in bufLike) {\n return bufFromBufLike(bufLike.buffer);\n }\n return uint8ToBuf(new Uint8Array(bufLike));\n}\n//# sourceMappingURL=buffer.js.map","/**\n * Concatenate multiple array buffers.\n * @param buffers The buffers to concatenate.\n */\nexport function concat(...buffers) {\n const result = new Uint8Array(buffers.reduce((acc, curr) => acc + curr.byteLength, 0));\n let index = 0;\n for (const b of buffers) {\n result.set(new Uint8Array(b), index);\n index += b.byteLength;\n }\n return result;\n}\n/**\n * Returns an hexadecimal representation of an array buffer.\n * @param bytes The array buffer.\n */\nexport function toHexString(bytes) {\n return new Uint8Array(bytes).reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\n}\n/**\n * Return an array buffer from its hexadecimal representation.\n * @param hexString The hexadecimal string.\n */\nexport function fromHexString(hexString) {\n var _a;\n return new Uint8Array(((_a = hexString.match(/.{1,2}/g)) !== null && _a !== void 0 ? _a : []).map(byte => parseInt(byte, 16)));\n}\n/**\n * A class that abstracts a pipe-like ArrayBuffer.\n */\nexport class PipeArrayBuffer {\n /**\n * Creates a new instance of a pipe\n * @param buffer an optional buffer to start with\n * @param length an optional amount of bytes to use for the length.\n */\n constructor(buffer, length = (buffer === null || buffer === void 0 ? void 0 : buffer.byteLength) || 0) {\n this._buffer = bufFromBufLike(buffer || new ArrayBuffer(0));\n this._view = new Uint8Array(this._buffer, 0, length);\n }\n get buffer() {\n // Return a copy of the buffer.\n return bufFromBufLike(this._view.slice());\n }\n get byteLength() {\n return this._view.byteLength;\n }\n /**\n * Read `num` number of bytes from the front of the pipe.\n * @param num The number of bytes to read.\n */\n read(num) {\n const result = this._view.subarray(0, num);\n this._view = this._view.subarray(num);\n return result.slice().buffer;\n }\n readUint8() {\n const result = this._view[0];\n this._view = this._view.subarray(1);\n return result;\n }\n /**\n * Write a buffer to the end of the pipe.\n * @param buf The bytes to write.\n */\n write(buf) {\n const b = new Uint8Array(buf);\n const offset = this._view.byteLength;\n if (this._view.byteOffset + this._view.byteLength + b.byteLength >= this._buffer.byteLength) {\n // Alloc grow the view to include the new bytes.\n this.alloc(b.byteLength);\n }\n else {\n // Update the view to include the new bytes.\n this._view = new Uint8Array(this._buffer, this._view.byteOffset, this._view.byteLength + b.byteLength);\n }\n this._view.set(b, offset);\n }\n /**\n * Whether or not there is more data to read from the buffer\n */\n get end() {\n return this._view.byteLength === 0;\n }\n /**\n * Allocate a fixed amount of memory in the buffer. This does not affect the view.\n * @param amount A number of bytes to add to the buffer.\n */\n alloc(amount) {\n // Add a little bit of exponential growth.\n const b = new ArrayBuffer(((this._buffer.byteLength + amount) * 1.2) | 0);\n const v = new Uint8Array(b, 0, this._view.byteLength + amount);\n v.set(this._view);\n this._buffer = b;\n this._view = v;\n }\n}\n/**\n * Returns a true ArrayBuffer from a Uint8Array, as Uint8Array.buffer is unsafe.\n * @param {Uint8Array} arr Uint8Array to convert\n * @returns ArrayBuffer\n */\nexport function uint8ToBuf(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength).buffer;\n}\n/**\n * Returns a true ArrayBuffer from an ArrayBufferLike object.\n * @param bufLike a buffer-like object\n * @returns ArrayBuffer\n */\nexport function bufFromBufLike(bufLike) {\n if (bufLike instanceof Uint8Array) {\n return uint8ToBuf(bufLike);\n }\n if (bufLike instanceof ArrayBuffer) {\n return bufLike;\n }\n if (Array.isArray(bufLike)) {\n return uint8ToBuf(new Uint8Array(bufLike));\n }\n if ('buffer' in bufLike) {\n return bufFromBufLike(bufLike.buffer);\n }\n return uint8ToBuf(new Uint8Array(bufLike));\n}\n//# sourceMappingURL=buffer.js.map","/* eslint-disable no-constant-condition */\n// Note: this file uses buffer-pipe, which on Node only, uses the Node Buffer\n// implementation, which isn't compatible with the NPM buffer package\n// which we use everywhere else. This means that we have to transform\n// one into the other, hence why every function that returns a Buffer\n// actually return `new Buffer(pipe.buffer)`.\n// TODO: The best solution would be to have our own buffer type around\n// Uint8Array which is standard.\nimport { PipeArrayBuffer as Pipe } from './buffer';\nfunction eob() {\n throw new Error('unexpected end of buffer');\n}\n/**\n *\n * @param pipe Pipe from buffer-pipe\n * @param num number\n * @returns Buffer\n */\nexport function safeRead(pipe, num) {\n if (pipe.byteLength < num) {\n eob();\n }\n return pipe.read(num);\n}\n/**\n * @param pipe - PipeArrayBuffer simulating buffer-pipe api\n */\nexport function safeReadUint8(pipe) {\n const byte = pipe.readUint8();\n if (byte === undefined) {\n eob();\n }\n return byte;\n}\n/**\n * Encode a positive number (or bigint) into a Buffer. The number will be floored to the\n * nearest integer.\n * @param value The number to encode.\n */\nexport function lebEncode(value) {\n if (typeof value === 'number') {\n value = BigInt(value);\n }\n if (value < BigInt(0)) {\n throw new Error('Cannot leb encode negative values.');\n }\n const byteLength = (value === BigInt(0) ? 0 : Math.ceil(Math.log2(Number(value)))) + 1;\n const pipe = new Pipe(new ArrayBuffer(byteLength), 0);\n while (true) {\n const i = Number(value & BigInt(0x7f));\n value /= BigInt(0x80);\n if (value === BigInt(0)) {\n pipe.write(new Uint8Array([i]));\n break;\n }\n else {\n pipe.write(new Uint8Array([i | 0x80]));\n }\n }\n return pipe.buffer;\n}\n/**\n * Decode a leb encoded buffer into a bigint. The number will always be positive (does not\n * support signed leb encoding).\n * @param pipe A Buffer containing the leb encoded bits.\n */\nexport function lebDecode(pipe) {\n let weight = BigInt(1);\n let value = BigInt(0);\n let byte;\n do {\n byte = safeReadUint8(pipe);\n value += BigInt(byte & 0x7f).valueOf() * weight;\n weight *= BigInt(128);\n } while (byte >= 0x80);\n return value;\n}\n/**\n * Encode a number (or bigint) into a Buffer, with support for negative numbers. The number\n * will be floored to the nearest integer.\n * @param value The number to encode.\n */\nexport function slebEncode(value) {\n if (typeof value === 'number') {\n value = BigInt(value);\n }\n const isNeg = value < BigInt(0);\n if (isNeg) {\n value = -value - BigInt(1);\n }\n const byteLength = (value === BigInt(0) ? 0 : Math.ceil(Math.log2(Number(value)))) + 1;\n const pipe = new Pipe(new ArrayBuffer(byteLength), 0);\n while (true) {\n const i = getLowerBytes(value);\n value /= BigInt(0x80);\n // prettier-ignore\n if ((isNeg && value === BigInt(0) && (i & 0x40) !== 0)\n || (!isNeg && value === BigInt(0) && (i & 0x40) === 0)) {\n pipe.write(new Uint8Array([i]));\n break;\n }\n else {\n pipe.write(new Uint8Array([i | 0x80]));\n }\n }\n function getLowerBytes(num) {\n const bytes = num % BigInt(0x80);\n if (isNeg) {\n // We swap the bits here again, and remove 1 to do two's complement.\n return Number(BigInt(0x80) - bytes - BigInt(1));\n }\n else {\n return Number(bytes);\n }\n }\n return pipe.buffer;\n}\n/**\n * Decode a leb encoded buffer into a bigint. The number is decoded with support for negative\n * signed-leb encoding.\n * @param pipe A Buffer containing the signed leb encoded bits.\n */\nexport function slebDecode(pipe) {\n // Get the size of the buffer, then cut a buffer of that size.\n const pipeView = new Uint8Array(pipe.buffer);\n let len = 0;\n for (; len < pipeView.byteLength; len++) {\n if (pipeView[len] < 0x80) {\n // If it's a positive number, we reuse lebDecode.\n if ((pipeView[len] & 0x40) === 0) {\n return lebDecode(pipe);\n }\n break;\n }\n }\n const bytes = new Uint8Array(safeRead(pipe, len + 1));\n let value = BigInt(0);\n for (let i = bytes.byteLength - 1; i >= 0; i--) {\n value = value * BigInt(0x80) + BigInt(0x80 - (bytes[i] & 0x7f) - 1);\n }\n return -value - BigInt(1);\n}\n/**\n *\n * @param value bigint or number\n * @param byteLength number\n * @returns Buffer\n */\nexport function writeUIntLE(value, byteLength) {\n if (BigInt(value) < BigInt(0)) {\n throw new Error('Cannot write negative values.');\n }\n return writeIntLE(value, byteLength);\n}\n/**\n *\n * @param value - bigint or number\n * @param byteLength - number\n * @returns ArrayBuffer\n */\nexport function writeIntLE(value, byteLength) {\n value = BigInt(value);\n const pipe = new Pipe(new ArrayBuffer(Math.min(1, byteLength)), 0);\n let i = 0;\n let mul = BigInt(256);\n let sub = BigInt(0);\n let byte = Number(value % mul);\n pipe.write(new Uint8Array([byte]));\n while (++i < byteLength) {\n if (value < 0 && sub === BigInt(0) && byte !== 0) {\n sub = BigInt(1);\n }\n byte = Number((value / mul - sub) % BigInt(256));\n pipe.write(new Uint8Array([byte]));\n mul *= BigInt(256);\n }\n return pipe.buffer;\n}\n/**\n *\n * @param pipe Pipe from buffer-pipe\n * @param byteLength number\n * @returns bigint\n */\nexport function readUIntLE(pipe, byteLength) {\n let val = BigInt(safeReadUint8(pipe));\n let mul = BigInt(1);\n let i = 0;\n while (++i < byteLength) {\n mul *= BigInt(256);\n const byte = BigInt(safeReadUint8(pipe));\n val = val + mul * byte;\n }\n return val;\n}\n/**\n *\n * @param pipe Pipe from buffer-pipe\n * @param byteLength number\n * @returns bigint\n */\nexport function readIntLE(pipe, byteLength) {\n let val = readUIntLE(pipe, byteLength);\n const mul = BigInt(2) ** (BigInt(8) * BigInt(byteLength - 1) + BigInt(7));\n if (val >= mul) {\n val -= mul * BigInt(2);\n }\n return val;\n}\n//# sourceMappingURL=leb128.js.map","/**\n * Equivalent to `Math.log2(n)` with support for `BigInt` values\n * @param n bigint or integer\n * @returns integer\n */\nexport function ilog2(n) {\n const nBig = BigInt(n);\n if (n <= 0) {\n throw new RangeError('Input must be positive');\n }\n return nBig.toString(2).length - 1;\n}\n/**\n * Equivalent to `2 ** n` with support for `BigInt` values\n * (necessary for browser preprocessors which replace the `**` operator with `Math.pow`)\n * @param n bigint or integer\n * @returns bigint\n */\nexport function iexp2(n) {\n const nBig = BigInt(n);\n if (n < 0) {\n throw new RangeError('Input must be non-negative');\n }\n return BigInt(1) << nBig;\n}\n//# sourceMappingURL=bigint-math.js.map","/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Principal as PrincipalId } from '@dfinity/principal';\nimport { concat, PipeArrayBuffer as Pipe } from './utils/buffer';\nimport { idlLabelToId } from './utils/hash';\nimport { lebDecode, lebEncode, readIntLE, readUIntLE, safeRead, safeReadUint8, slebDecode, slebEncode, writeIntLE, writeUIntLE, } from './utils/leb128';\nimport { iexp2 } from './utils/bigint-math';\nconst magicNumber = 'DIDL';\nconst toReadableString_max = 400; // will not display arguments after 400chars. Makes sure 2mb blobs don't get inside the error\nfunction zipWith(xs, ys, f) {\n return xs.map((x, i) => f(x, ys[i]));\n}\n/**\n * An IDL Type Table, which precedes the data in the stream.\n */\nclass TypeTable {\n constructor() {\n // List of types. Needs to be an array as the index needs to be stable.\n this._typs = [];\n this._idx = new Map();\n }\n has(obj) {\n return this._idx.has(obj.name);\n }\n add(type, buf) {\n const idx = this._typs.length;\n this._idx.set(type.name, idx);\n this._typs.push(buf);\n }\n merge(obj, knot) {\n const idx = this._idx.get(obj.name);\n const knotIdx = this._idx.get(knot);\n if (idx === undefined) {\n throw new Error('Missing type index for ' + obj);\n }\n if (knotIdx === undefined) {\n throw new Error('Missing type index for ' + knot);\n }\n this._typs[idx] = this._typs[knotIdx];\n // Delete the type.\n this._typs.splice(knotIdx, 1);\n this._idx.delete(knot);\n }\n encode() {\n const len = lebEncode(this._typs.length);\n const buf = concat(...this._typs);\n return concat(len, buf);\n }\n indexOf(typeName) {\n if (!this._idx.has(typeName)) {\n throw new Error('Missing type index for ' + typeName);\n }\n return slebEncode(this._idx.get(typeName) || 0);\n }\n}\nexport class Visitor {\n visitType(t, data) {\n throw new Error('Not implemented');\n }\n visitPrimitive(t, data) {\n return this.visitType(t, data);\n }\n visitEmpty(t, data) {\n return this.visitPrimitive(t, data);\n }\n visitBool(t, data) {\n return this.visitPrimitive(t, data);\n }\n visitNull(t, data) {\n return this.visitPrimitive(t, data);\n }\n visitReserved(t, data) {\n return this.visitPrimitive(t, data);\n }\n visitText(t, data) {\n return this.visitPrimitive(t, data);\n }\n visitNumber(t, data) {\n return this.visitPrimitive(t, data);\n }\n visitInt(t, data) {\n return this.visitNumber(t, data);\n }\n visitNat(t, data) {\n return this.visitNumber(t, data);\n }\n visitFloat(t, data) {\n return this.visitPrimitive(t, data);\n }\n visitFixedInt(t, data) {\n return this.visitNumber(t, data);\n }\n visitFixedNat(t, data) {\n return this.visitNumber(t, data);\n }\n visitPrincipal(t, data) {\n return this.visitPrimitive(t, data);\n }\n visitConstruct(t, data) {\n return this.visitType(t, data);\n }\n visitVec(t, ty, data) {\n return this.visitConstruct(t, data);\n }\n visitOpt(t, ty, data) {\n return this.visitConstruct(t, data);\n }\n visitRecord(t, fields, data) {\n return this.visitConstruct(t, data);\n }\n visitTuple(t, components, data) {\n const fields = components.map((ty, i) => [`_${i}_`, ty]);\n return this.visitRecord(t, fields, data);\n }\n visitVariant(t, fields, data) {\n return this.visitConstruct(t, data);\n }\n visitRec(t, ty, data) {\n return this.visitConstruct(ty, data);\n }\n visitFunc(t, data) {\n return this.visitConstruct(t, data);\n }\n visitService(t, data) {\n return this.visitConstruct(t, data);\n }\n}\n/**\n * Represents an IDL type.\n */\nexport class Type {\n /* Display type name */\n display() {\n return this.name;\n }\n valueToString(x) {\n return toReadableString(x);\n }\n /* Implement `T` in the IDL spec, only needed for non-primitive types */\n buildTypeTable(typeTable) {\n if (!typeTable.has(this)) {\n this._buildTypeTableImpl(typeTable);\n }\n }\n}\nexport class PrimitiveType extends Type {\n checkType(t) {\n if (this.name !== t.name) {\n throw new Error(`type mismatch: type on the wire ${t.name}, expect type ${this.name}`);\n }\n return t;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _buildTypeTableImpl(typeTable) {\n // No type table encoding for Primitive types.\n return;\n }\n}\nexport class ConstructType extends Type {\n checkType(t) {\n if (t instanceof RecClass) {\n const ty = t.getType();\n if (typeof ty === 'undefined') {\n throw new Error('type mismatch with uninitialized type');\n }\n return ty;\n }\n throw new Error(`type mismatch: type on the wire ${t.name}, expect type ${this.name}`);\n }\n encodeType(typeTable) {\n return typeTable.indexOf(this.name);\n }\n}\n/**\n * Represents an IDL Empty, a type which has no inhabitants.\n * Since no values exist for this type, it cannot be serialised or deserialised.\n * Result types like `Result` should always succeed.\n */\nexport class EmptyClass extends PrimitiveType {\n accept(v, d) {\n return v.visitEmpty(this, d);\n }\n covariant(x) {\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue() {\n throw new Error('Empty cannot appear as a function argument');\n }\n valueToString() {\n throw new Error('Empty cannot appear as a value');\n }\n encodeType() {\n return slebEncode(-17 /* IDLTypeIds.Empty */);\n }\n decodeValue() {\n throw new Error('Empty cannot appear as an output');\n }\n get name() {\n return 'empty';\n }\n}\n/**\n * Represents an IDL Unknown, a placeholder type for deserialization only.\n * When decoding a value as Unknown, all fields will be retained but the names are only available in\n * hashed form.\n * A deserialized unknown will offer it's actual type by calling the `type()` function.\n * Unknown cannot be serialized and attempting to do so will throw an error.\n */\nexport class UnknownClass extends Type {\n checkType(t) {\n throw new Error('Method not implemented for unknown.');\n }\n accept(v, d) {\n throw v.visitType(this, d);\n }\n covariant(x) {\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue() {\n throw new Error('Unknown cannot appear as a function argument');\n }\n valueToString() {\n throw new Error('Unknown cannot appear as a value');\n }\n encodeType() {\n throw new Error('Unknown cannot be serialized');\n }\n decodeValue(b, t) {\n let decodedValue = t.decodeValue(b, t);\n if (Object(decodedValue) !== decodedValue) {\n // decodedValue is primitive. Box it, otherwise we cannot add the type() function.\n // The type() function is important for primitives because otherwise we cannot tell apart the\n // different number types.\n decodedValue = Object(decodedValue);\n }\n let typeFunc;\n if (t instanceof RecClass) {\n typeFunc = () => t.getType();\n }\n else {\n typeFunc = () => t;\n }\n // Do not use 'decodedValue.type = typeFunc' because this would lead to an enumerable property\n // 'type' which means it would be serialized if the value would be candid encoded again.\n // This in turn leads to problems if the decoded value is a variant because these values are\n // only allowed to have a single property.\n Object.defineProperty(decodedValue, 'type', {\n value: typeFunc,\n writable: true,\n enumerable: false,\n configurable: true,\n });\n return decodedValue;\n }\n _buildTypeTableImpl() {\n throw new Error('Unknown cannot be serialized');\n }\n get name() {\n return 'Unknown';\n }\n}\n/**\n * Represents an IDL Bool\n */\nexport class BoolClass extends PrimitiveType {\n accept(v, d) {\n return v.visitBool(this, d);\n }\n covariant(x) {\n if (typeof x === 'boolean')\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n return new Uint8Array([x ? 1 : 0]);\n }\n encodeType() {\n return slebEncode(-2 /* IDLTypeIds.Bool */);\n }\n decodeValue(b, t) {\n this.checkType(t);\n switch (safeReadUint8(b)) {\n case 0:\n return false;\n case 1:\n return true;\n default:\n throw new Error('Boolean value out of range');\n }\n }\n get name() {\n return 'bool';\n }\n}\n/**\n * Represents an IDL Null\n */\nexport class NullClass extends PrimitiveType {\n accept(v, d) {\n return v.visitNull(this, d);\n }\n covariant(x) {\n if (x === null)\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue() {\n return new ArrayBuffer(0);\n }\n encodeType() {\n return slebEncode(-1 /* IDLTypeIds.Null */);\n }\n decodeValue(b, t) {\n this.checkType(t);\n return null;\n }\n get name() {\n return 'null';\n }\n}\n/**\n * Represents an IDL Reserved\n */\nexport class ReservedClass extends PrimitiveType {\n accept(v, d) {\n return v.visitReserved(this, d);\n }\n covariant(x) {\n return true;\n }\n encodeValue() {\n return new ArrayBuffer(0);\n }\n encodeType() {\n return slebEncode(-16 /* IDLTypeIds.Reserved */);\n }\n decodeValue(b, t) {\n if (t.name !== this.name) {\n t.decodeValue(b, t);\n }\n return null;\n }\n get name() {\n return 'reserved';\n }\n}\n/**\n * Represents an IDL Text\n */\nexport class TextClass extends PrimitiveType {\n accept(v, d) {\n return v.visitText(this, d);\n }\n covariant(x) {\n if (typeof x === 'string')\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n const buf = new TextEncoder().encode(x);\n const len = lebEncode(buf.byteLength);\n return concat(len, buf);\n }\n encodeType() {\n return slebEncode(-15 /* IDLTypeIds.Text */);\n }\n decodeValue(b, t) {\n this.checkType(t);\n const len = lebDecode(b);\n const buf = safeRead(b, Number(len));\n const decoder = new TextDecoder('utf8', { fatal: true });\n return decoder.decode(buf);\n }\n get name() {\n return 'text';\n }\n valueToString(x) {\n return '\"' + x + '\"';\n }\n}\n/**\n * Represents an IDL Int\n */\nexport class IntClass extends PrimitiveType {\n accept(v, d) {\n return v.visitInt(this, d);\n }\n covariant(x) {\n // We allow encoding of JavaScript plain numbers.\n // But we will always decode to bigint.\n if (typeof x === 'bigint' || Number.isInteger(x))\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n return slebEncode(x);\n }\n encodeType() {\n return slebEncode(-4 /* IDLTypeIds.Int */);\n }\n decodeValue(b, t) {\n this.checkType(t);\n return slebDecode(b);\n }\n get name() {\n return 'int';\n }\n valueToString(x) {\n return x.toString();\n }\n}\n/**\n * Represents an IDL Nat\n */\nexport class NatClass extends PrimitiveType {\n accept(v, d) {\n return v.visitNat(this, d);\n }\n covariant(x) {\n // We allow encoding of JavaScript plain numbers.\n // But we will always decode to bigint.\n if ((typeof x === 'bigint' && x >= BigInt(0)) || (Number.isInteger(x) && x >= 0))\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n return lebEncode(x);\n }\n encodeType() {\n return slebEncode(-3 /* IDLTypeIds.Nat */);\n }\n decodeValue(b, t) {\n this.checkType(t);\n return lebDecode(b);\n }\n get name() {\n return 'nat';\n }\n valueToString(x) {\n return x.toString();\n }\n}\n/**\n * Represents an IDL Float\n */\nexport class FloatClass extends PrimitiveType {\n constructor(_bits) {\n super();\n this._bits = _bits;\n if (_bits !== 32 && _bits !== 64) {\n throw new Error('not a valid float type');\n }\n }\n accept(v, d) {\n return v.visitFloat(this, d);\n }\n covariant(x) {\n if (typeof x === 'number' || x instanceof Number)\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n const buf = new ArrayBuffer(this._bits / 8);\n const view = new DataView(buf);\n if (this._bits === 32) {\n view.setFloat32(0, x, true);\n }\n else {\n view.setFloat64(0, x, true);\n }\n return buf;\n }\n encodeType() {\n const opcode = this._bits === 32 ? -13 /* IDLTypeIds.Float32 */ : -14 /* IDLTypeIds.Float64 */;\n return slebEncode(opcode);\n }\n decodeValue(b, t) {\n this.checkType(t);\n const bytes = safeRead(b, this._bits / 8);\n const view = new DataView(bytes);\n if (this._bits === 32) {\n return view.getFloat32(0, true);\n }\n else {\n return view.getFloat64(0, true);\n }\n }\n get name() {\n return 'float' + this._bits;\n }\n valueToString(x) {\n return x.toString();\n }\n}\n/**\n * Represents an IDL fixed-width Int(n)\n */\nexport class FixedIntClass extends PrimitiveType {\n constructor(_bits) {\n super();\n this._bits = _bits;\n }\n accept(v, d) {\n return v.visitFixedInt(this, d);\n }\n covariant(x) {\n const min = iexp2(this._bits - 1) * BigInt(-1);\n const max = iexp2(this._bits - 1) - BigInt(1);\n let ok = false;\n if (typeof x === 'bigint') {\n ok = x >= min && x <= max;\n }\n else if (Number.isInteger(x)) {\n const v = BigInt(x);\n ok = v >= min && v <= max;\n }\n else {\n ok = false;\n }\n if (ok)\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n return writeIntLE(x, this._bits / 8);\n }\n encodeType() {\n const offset = Math.log2(this._bits) - 3;\n return slebEncode(-9 - offset);\n }\n decodeValue(b, t) {\n this.checkType(t);\n const num = readIntLE(b, this._bits / 8);\n if (this._bits <= 32) {\n return Number(num);\n }\n else {\n return num;\n }\n }\n get name() {\n return `int${this._bits}`;\n }\n valueToString(x) {\n return x.toString();\n }\n}\n/**\n * Represents an IDL fixed-width Nat(n)\n */\nexport class FixedNatClass extends PrimitiveType {\n constructor(_bits) {\n super();\n this._bits = _bits;\n }\n accept(v, d) {\n return v.visitFixedNat(this, d);\n }\n covariant(x) {\n const max = iexp2(this._bits);\n let ok = false;\n if (typeof x === 'bigint' && x >= BigInt(0)) {\n ok = x < max;\n }\n else if (Number.isInteger(x) && x >= 0) {\n const v = BigInt(x);\n ok = v < max;\n }\n else {\n ok = false;\n }\n if (ok)\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n return writeUIntLE(x, this._bits / 8);\n }\n encodeType() {\n const offset = Math.log2(this._bits) - 3;\n return slebEncode(-5 - offset);\n }\n decodeValue(b, t) {\n this.checkType(t);\n const num = readUIntLE(b, this._bits / 8);\n if (this._bits <= 32) {\n return Number(num);\n }\n else {\n return num;\n }\n }\n get name() {\n return `nat${this._bits}`;\n }\n valueToString(x) {\n return x.toString();\n }\n}\n/**\n * Represents an IDL Array\n *\n * Arrays of fixed-sized nat/int type (e.g. nat8), are encoded from and decoded to TypedArrays (e.g. Uint8Array).\n * Arrays of float or other non-primitive types are encoded/decoded as untyped array in Javascript.\n * @param {Type} t\n */\nexport class VecClass extends ConstructType {\n constructor(_type) {\n super();\n this._type = _type;\n // If true, this vector is really a blob and we can just use memcpy.\n //\n // NOTE:\n // With support of encoding/dencoding of TypedArrays, this optimization is\n // only used when plain array of bytes are passed as encoding input in order\n // to be backward compatible.\n this._blobOptimization = false;\n if (_type instanceof FixedNatClass && _type._bits === 8) {\n this._blobOptimization = true;\n }\n }\n accept(v, d) {\n return v.visitVec(this, this._type, d);\n }\n covariant(x) {\n // Special case for ArrayBuffer\n const bits = this._type instanceof FixedNatClass\n ? this._type._bits\n : this._type instanceof FixedIntClass\n ? this._type._bits\n : 0;\n if ((ArrayBuffer.isView(x) && bits == x.BYTES_PER_ELEMENT * 8) ||\n (Array.isArray(x) &&\n x.every((v, idx) => {\n try {\n return this._type.covariant(v);\n }\n catch (e) {\n throw new Error(`Invalid ${this.display()} argument: \\n\\nindex ${idx} -> ${e.message}`);\n }\n })))\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n const len = lebEncode(x.length);\n if (this._blobOptimization) {\n return concat(len, new Uint8Array(x));\n }\n if (ArrayBuffer.isView(x)) {\n return concat(len, new Uint8Array(x.buffer));\n }\n const buf = new Pipe(new ArrayBuffer(len.byteLength + x.length), 0);\n buf.write(len);\n for (const d of x) {\n const encoded = this._type.encodeValue(d);\n buf.write(new Uint8Array(encoded));\n }\n return buf.buffer;\n }\n _buildTypeTableImpl(typeTable) {\n this._type.buildTypeTable(typeTable);\n const opCode = slebEncode(-19 /* IDLTypeIds.Vector */);\n const buffer = this._type.encodeType(typeTable);\n typeTable.add(this, concat(opCode, buffer));\n }\n decodeValue(b, t) {\n const vec = this.checkType(t);\n if (!(vec instanceof VecClass)) {\n throw new Error('Not a vector type');\n }\n const len = Number(lebDecode(b));\n if (this._type instanceof FixedNatClass) {\n if (this._type._bits == 8) {\n return new Uint8Array(b.read(len));\n }\n if (this._type._bits == 16) {\n return new Uint16Array(b.read(len * 2));\n }\n if (this._type._bits == 32) {\n return new Uint32Array(b.read(len * 4));\n }\n if (this._type._bits == 64) {\n return new BigUint64Array(b.read(len * 8));\n }\n }\n if (this._type instanceof FixedIntClass) {\n if (this._type._bits == 8) {\n return new Int8Array(b.read(len));\n }\n if (this._type._bits == 16) {\n return new Int16Array(b.read(len * 2));\n }\n if (this._type._bits == 32) {\n return new Int32Array(b.read(len * 4));\n }\n if (this._type._bits == 64) {\n return new BigInt64Array(b.read(len * 8));\n }\n }\n const rets = [];\n for (let i = 0; i < len; i++) {\n rets.push(this._type.decodeValue(b, vec._type));\n }\n return rets;\n }\n get name() {\n return `vec ${this._type.name}`;\n }\n display() {\n return `vec ${this._type.display()}`;\n }\n valueToString(x) {\n const elements = x.map(e => this._type.valueToString(e));\n return 'vec {' + elements.join('; ') + '}';\n }\n}\n/**\n * Represents an IDL Option\n * @param {Type} t\n */\nexport class OptClass extends ConstructType {\n constructor(_type) {\n super();\n this._type = _type;\n }\n accept(v, d) {\n return v.visitOpt(this, this._type, d);\n }\n covariant(x) {\n try {\n if (Array.isArray(x) && (x.length === 0 || (x.length === 1 && this._type.covariant(x[0]))))\n return true;\n }\n catch (e) {\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)} \\n\\n-> ${e.message}`);\n }\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n if (x.length === 0) {\n return new Uint8Array([0]);\n }\n else {\n return concat(new Uint8Array([1]), this._type.encodeValue(x[0]));\n }\n }\n _buildTypeTableImpl(typeTable) {\n this._type.buildTypeTable(typeTable);\n const opCode = slebEncode(-18 /* IDLTypeIds.Opt */);\n const buffer = this._type.encodeType(typeTable);\n typeTable.add(this, concat(opCode, buffer));\n }\n decodeValue(b, t) {\n const opt = this.checkType(t);\n if (!(opt instanceof OptClass)) {\n throw new Error('Not an option type');\n }\n switch (safeReadUint8(b)) {\n case 0:\n return [];\n case 1:\n return [this._type.decodeValue(b, opt._type)];\n default:\n throw new Error('Not an option value');\n }\n }\n get name() {\n return `opt ${this._type.name}`;\n }\n display() {\n return `opt ${this._type.display()}`;\n }\n valueToString(x) {\n if (x.length === 0) {\n return 'null';\n }\n else {\n return `opt ${this._type.valueToString(x[0])}`;\n }\n }\n}\n/**\n * Represents an IDL Record\n * @param {object} [fields] - mapping of function name to Type\n */\nexport class RecordClass extends ConstructType {\n constructor(fields = {}) {\n super();\n this._fields = Object.entries(fields).sort((a, b) => idlLabelToId(a[0]) - idlLabelToId(b[0]));\n }\n accept(v, d) {\n return v.visitRecord(this, this._fields, d);\n }\n tryAsTuple() {\n const res = [];\n for (let i = 0; i < this._fields.length; i++) {\n const [key, type] = this._fields[i];\n if (key !== `_${i}_`) {\n return null;\n }\n res.push(type);\n }\n return res;\n }\n covariant(x) {\n if (typeof x === 'object' &&\n this._fields.every(([k, t]) => {\n // eslint-disable-next-line\n if (!x.hasOwnProperty(k)) {\n throw new Error(`Record is missing key \"${k}\".`);\n }\n try {\n return t.covariant(x[k]);\n }\n catch (e) {\n throw new Error(`Invalid ${this.display()} argument: \\n\\nfield ${k} -> ${e.message}`);\n }\n }))\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n const values = this._fields.map(([key]) => x[key]);\n const bufs = zipWith(this._fields, values, ([, c], d) => c.encodeValue(d));\n return concat(...bufs);\n }\n _buildTypeTableImpl(T) {\n this._fields.forEach(([_, value]) => value.buildTypeTable(T));\n const opCode = slebEncode(-20 /* IDLTypeIds.Record */);\n const len = lebEncode(this._fields.length);\n const fields = this._fields.map(([key, value]) => concat(lebEncode(idlLabelToId(key)), value.encodeType(T)));\n T.add(this, concat(opCode, len, concat(...fields)));\n }\n decodeValue(b, t) {\n const record = this.checkType(t);\n if (!(record instanceof RecordClass)) {\n throw new Error('Not a record type');\n }\n const x = {};\n let expectedRecordIdx = 0;\n let actualRecordIdx = 0;\n while (actualRecordIdx < record._fields.length) {\n const [hash, type] = record._fields[actualRecordIdx];\n if (expectedRecordIdx >= this._fields.length) {\n // skip unexpected left over fields present on the wire\n type.decodeValue(b, type);\n actualRecordIdx++;\n continue;\n }\n const [expectKey, expectType] = this._fields[expectedRecordIdx];\n const expectedId = idlLabelToId(this._fields[expectedRecordIdx][0]);\n const actualId = idlLabelToId(hash);\n if (expectedId === actualId) {\n // the current field on the wire matches the expected field\n x[expectKey] = expectType.decodeValue(b, type);\n expectedRecordIdx++;\n actualRecordIdx++;\n }\n else if (actualId > expectedId) {\n // The expected field does not exist on the wire\n if (expectType instanceof OptClass || expectType instanceof ReservedClass) {\n x[expectKey] = [];\n expectedRecordIdx++;\n }\n else {\n throw new Error('Cannot find required field ' + expectKey);\n }\n }\n else {\n // The field on the wire does not exist in the output type, so we can skip it\n type.decodeValue(b, type);\n actualRecordIdx++;\n }\n }\n // initialize left over expected optional fields\n for (const [expectKey, expectType] of this._fields.slice(expectedRecordIdx)) {\n if (expectType instanceof OptClass || expectType instanceof ReservedClass) {\n // TODO this assumes null value in opt is represented as []\n x[expectKey] = [];\n }\n else {\n throw new Error('Cannot find required field ' + expectKey);\n }\n }\n return x;\n }\n get name() {\n const fields = this._fields.map(([key, value]) => key + ':' + value.name);\n return `record {${fields.join('; ')}}`;\n }\n display() {\n const fields = this._fields.map(([key, value]) => key + ':' + value.display());\n return `record {${fields.join('; ')}}`;\n }\n valueToString(x) {\n const values = this._fields.map(([key]) => x[key]);\n const fields = zipWith(this._fields, values, ([k, c], d) => k + '=' + c.valueToString(d));\n return `record {${fields.join('; ')}}`;\n }\n}\n/**\n * Represents Tuple, a syntactic sugar for Record.\n * @param {Type} components\n */\nexport class TupleClass extends RecordClass {\n constructor(_components) {\n const x = {};\n _components.forEach((e, i) => (x['_' + i + '_'] = e));\n super(x);\n this._components = _components;\n }\n accept(v, d) {\n return v.visitTuple(this, this._components, d);\n }\n covariant(x) {\n // `>=` because tuples can be covariant when encoded.\n if (Array.isArray(x) &&\n x.length >= this._fields.length &&\n this._components.every((t, i) => {\n try {\n return t.covariant(x[i]);\n }\n catch (e) {\n throw new Error(`Invalid ${this.display()} argument: \\n\\nindex ${i} -> ${e.message}`);\n }\n }))\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n const bufs = zipWith(this._components, x, (c, d) => c.encodeValue(d));\n return concat(...bufs);\n }\n decodeValue(b, t) {\n const tuple = this.checkType(t);\n if (!(tuple instanceof TupleClass)) {\n throw new Error('not a tuple type');\n }\n if (tuple._components.length < this._components.length) {\n throw new Error('tuple mismatch');\n }\n const res = [];\n for (const [i, wireType] of tuple._components.entries()) {\n if (i >= this._components.length) {\n // skip value\n wireType.decodeValue(b, wireType);\n }\n else {\n res.push(this._components[i].decodeValue(b, wireType));\n }\n }\n return res;\n }\n display() {\n const fields = this._components.map(value => value.display());\n return `record {${fields.join('; ')}}`;\n }\n valueToString(values) {\n const fields = zipWith(this._components, values, (c, d) => c.valueToString(d));\n return `record {${fields.join('; ')}}`;\n }\n}\n/**\n * Represents an IDL Variant\n * @param {object} [fields] - mapping of function name to Type\n */\nexport class VariantClass extends ConstructType {\n constructor(fields = {}) {\n super();\n this._fields = Object.entries(fields).sort((a, b) => idlLabelToId(a[0]) - idlLabelToId(b[0]));\n }\n accept(v, d) {\n return v.visitVariant(this, this._fields, d);\n }\n covariant(x) {\n if (typeof x === 'object' &&\n Object.entries(x).length === 1 &&\n this._fields.every(([k, v]) => {\n try {\n // eslint-disable-next-line\n return !x.hasOwnProperty(k) || v.covariant(x[k]);\n }\n catch (e) {\n throw new Error(`Invalid ${this.display()} argument: \\n\\nvariant ${k} -> ${e.message}`);\n }\n }))\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n for (let i = 0; i < this._fields.length; i++) {\n const [name, type] = this._fields[i];\n // eslint-disable-next-line\n if (x.hasOwnProperty(name)) {\n const idx = lebEncode(i);\n const buf = type.encodeValue(x[name]);\n return concat(idx, buf);\n }\n }\n throw Error('Variant has no data: ' + x);\n }\n _buildTypeTableImpl(typeTable) {\n this._fields.forEach(([, type]) => {\n type.buildTypeTable(typeTable);\n });\n const opCode = slebEncode(-21 /* IDLTypeIds.Variant */);\n const len = lebEncode(this._fields.length);\n const fields = this._fields.map(([key, value]) => concat(lebEncode(idlLabelToId(key)), value.encodeType(typeTable)));\n typeTable.add(this, concat(opCode, len, ...fields));\n }\n decodeValue(b, t) {\n const variant = this.checkType(t);\n if (!(variant instanceof VariantClass)) {\n throw new Error('Not a variant type');\n }\n const idx = Number(lebDecode(b));\n if (idx >= variant._fields.length) {\n throw Error('Invalid variant index: ' + idx);\n }\n const [wireHash, wireType] = variant._fields[idx];\n for (const [key, expectType] of this._fields) {\n if (idlLabelToId(wireHash) === idlLabelToId(key)) {\n const value = expectType.decodeValue(b, wireType);\n return { [key]: value };\n }\n }\n throw new Error('Cannot find field hash ' + wireHash);\n }\n get name() {\n const fields = this._fields.map(([key, type]) => key + ':' + type.name);\n return `variant {${fields.join('; ')}}`;\n }\n display() {\n const fields = this._fields.map(([key, type]) => key + (type.name === 'null' ? '' : `:${type.display()}`));\n return `variant {${fields.join('; ')}}`;\n }\n valueToString(x) {\n for (const [name, type] of this._fields) {\n // eslint-disable-next-line\n if (x.hasOwnProperty(name)) {\n const value = type.valueToString(x[name]);\n if (value === 'null') {\n return `variant {${name}}`;\n }\n else {\n return `variant {${name}=${value}}`;\n }\n }\n }\n throw new Error('Variant has no data: ' + x);\n }\n}\n/**\n * Represents a reference to an IDL type, used for defining recursive data\n * types.\n */\nexport class RecClass extends ConstructType {\n constructor() {\n super(...arguments);\n this._id = RecClass._counter++;\n this._type = undefined;\n }\n accept(v, d) {\n if (!this._type) {\n throw Error('Recursive type uninitialized.');\n }\n return v.visitRec(this, this._type, d);\n }\n fill(t) {\n this._type = t;\n }\n getType() {\n return this._type;\n }\n covariant(x) {\n if (this._type ? this._type.covariant(x) : false)\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n if (!this._type) {\n throw Error('Recursive type uninitialized.');\n }\n return this._type.encodeValue(x);\n }\n _buildTypeTableImpl(typeTable) {\n if (!this._type) {\n throw Error('Recursive type uninitialized.');\n }\n typeTable.add(this, new Uint8Array([]));\n this._type.buildTypeTable(typeTable);\n typeTable.merge(this, this._type.name);\n }\n decodeValue(b, t) {\n if (!this._type) {\n throw Error('Recursive type uninitialized.');\n }\n return this._type.decodeValue(b, t);\n }\n get name() {\n return `rec_${this._id}`;\n }\n display() {\n if (!this._type) {\n throw Error('Recursive type uninitialized.');\n }\n return `μ${this.name}.${this._type.name}`;\n }\n valueToString(x) {\n if (!this._type) {\n throw Error('Recursive type uninitialized.');\n }\n return this._type.valueToString(x);\n }\n}\nRecClass._counter = 0;\nfunction decodePrincipalId(b) {\n const x = safeReadUint8(b);\n if (x !== 1) {\n throw new Error('Cannot decode principal');\n }\n const len = Number(lebDecode(b));\n return PrincipalId.fromUint8Array(new Uint8Array(safeRead(b, len)));\n}\n/**\n * Represents an IDL principal reference\n */\nexport class PrincipalClass extends PrimitiveType {\n accept(v, d) {\n return v.visitPrincipal(this, d);\n }\n covariant(x) {\n if (x && x._isPrincipal)\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n const buf = x.toUint8Array();\n const len = lebEncode(buf.byteLength);\n return concat(new Uint8Array([1]), len, buf);\n }\n encodeType() {\n return slebEncode(-24 /* IDLTypeIds.Principal */);\n }\n decodeValue(b, t) {\n this.checkType(t);\n return decodePrincipalId(b);\n }\n get name() {\n return 'principal';\n }\n valueToString(x) {\n return `${this.name} \"${x.toText()}\"`;\n }\n}\n/**\n * Represents an IDL function reference.\n * @param argTypes Argument types.\n * @param retTypes Return types.\n * @param annotations Function annotations.\n */\nexport class FuncClass extends ConstructType {\n constructor(argTypes, retTypes, annotations = []) {\n super();\n this.argTypes = argTypes;\n this.retTypes = retTypes;\n this.annotations = annotations;\n }\n static argsToString(types, v) {\n if (types.length !== v.length) {\n throw new Error('arity mismatch');\n }\n return '(' + types.map((t, i) => t.valueToString(v[i])).join(', ') + ')';\n }\n accept(v, d) {\n return v.visitFunc(this, d);\n }\n covariant(x) {\n if (Array.isArray(x) && x.length === 2 && x[0] && x[0]._isPrincipal && typeof x[1] === 'string')\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue([principal, methodName]) {\n const buf = principal.toUint8Array();\n const len = lebEncode(buf.byteLength);\n const canister = concat(new Uint8Array([1]), len, buf);\n const method = new TextEncoder().encode(methodName);\n const methodLen = lebEncode(method.byteLength);\n return concat(new Uint8Array([1]), canister, methodLen, method);\n }\n _buildTypeTableImpl(T) {\n this.argTypes.forEach(arg => arg.buildTypeTable(T));\n this.retTypes.forEach(arg => arg.buildTypeTable(T));\n const opCode = slebEncode(-22 /* IDLTypeIds.Func */);\n const argLen = lebEncode(this.argTypes.length);\n const args = concat(...this.argTypes.map(arg => arg.encodeType(T)));\n const retLen = lebEncode(this.retTypes.length);\n const rets = concat(...this.retTypes.map(arg => arg.encodeType(T)));\n const annLen = lebEncode(this.annotations.length);\n const anns = concat(...this.annotations.map(a => this.encodeAnnotation(a)));\n T.add(this, concat(opCode, argLen, args, retLen, rets, annLen, anns));\n }\n decodeValue(b) {\n const x = safeReadUint8(b);\n if (x !== 1) {\n throw new Error('Cannot decode function reference');\n }\n const canister = decodePrincipalId(b);\n const mLen = Number(lebDecode(b));\n const buf = safeRead(b, mLen);\n const decoder = new TextDecoder('utf8', { fatal: true });\n const method = decoder.decode(buf);\n return [canister, method];\n }\n get name() {\n const args = this.argTypes.map(arg => arg.name).join(', ');\n const rets = this.retTypes.map(arg => arg.name).join(', ');\n const annon = ' ' + this.annotations.join(' ');\n return `(${args}) -> (${rets})${annon}`;\n }\n valueToString([principal, str]) {\n return `func \"${principal.toText()}\".${str}`;\n }\n display() {\n const args = this.argTypes.map(arg => arg.display()).join(', ');\n const rets = this.retTypes.map(arg => arg.display()).join(', ');\n const annon = ' ' + this.annotations.join(' ');\n return `(${args}) → (${rets})${annon}`;\n }\n encodeAnnotation(ann) {\n if (ann === 'query') {\n return new Uint8Array([1]);\n }\n else if (ann === 'oneway') {\n return new Uint8Array([2]);\n }\n else if (ann === 'composite_query') {\n return new Uint8Array([3]);\n }\n else {\n throw new Error('Illegal function annotation');\n }\n }\n}\nexport class ServiceClass extends ConstructType {\n constructor(fields) {\n super();\n this._fields = Object.entries(fields).sort((a, b) => {\n if (a[0] < b[0]) {\n return -1;\n }\n if (a[0] > b[0]) {\n return 1;\n }\n return 0;\n });\n }\n accept(v, d) {\n return v.visitService(this, d);\n }\n covariant(x) {\n if (x && x._isPrincipal)\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n const buf = x.toUint8Array();\n const len = lebEncode(buf.length);\n return concat(new Uint8Array([1]), len, buf);\n }\n _buildTypeTableImpl(T) {\n this._fields.forEach(([_, func]) => func.buildTypeTable(T));\n const opCode = slebEncode(-23 /* IDLTypeIds.Service */);\n const len = lebEncode(this._fields.length);\n const meths = this._fields.map(([label, func]) => {\n const labelBuf = new TextEncoder().encode(label);\n const labelLen = lebEncode(labelBuf.length);\n return concat(labelLen, labelBuf, func.encodeType(T));\n });\n T.add(this, concat(opCode, len, ...meths));\n }\n decodeValue(b) {\n return decodePrincipalId(b);\n }\n get name() {\n const fields = this._fields.map(([key, value]) => key + ':' + value.name);\n return `service {${fields.join('; ')}}`;\n }\n valueToString(x) {\n return `service \"${x.toText()}\"`;\n }\n}\n/**\n * Takes an unknown value and returns a string representation of it.\n * @param x - unknown value\n * @returns {string} string representation of the value\n */\nfunction toReadableString(x) {\n const str = JSON.stringify(x, (_key, value) => typeof value === 'bigint' ? `BigInt(${value})` : value);\n return str && str.length > toReadableString_max\n ? str.substring(0, toReadableString_max - 3) + '...'\n : str;\n}\n/**\n * Encode a array of values\n * @param argTypes - array of Types\n * @param args - array of values\n * @returns {ArrayBuffer} serialised value\n */\nexport function encode(argTypes, args) {\n if (args.length < argTypes.length) {\n throw Error('Wrong number of message arguments');\n }\n const typeTable = new TypeTable();\n argTypes.forEach(t => t.buildTypeTable(typeTable));\n const magic = new TextEncoder().encode(magicNumber);\n const table = typeTable.encode();\n const len = lebEncode(args.length);\n const typs = concat(...argTypes.map(t => t.encodeType(typeTable)));\n const vals = concat(...zipWith(argTypes, args, (t, x) => {\n try {\n t.covariant(x);\n }\n catch (e) {\n const err = new Error(e.message + '\\n\\n');\n throw err;\n }\n return t.encodeValue(x);\n }));\n return concat(magic, table, len, typs, vals);\n}\n/**\n * Decode a binary value\n * @param retTypes - Types expected in the buffer.\n * @param bytes - hex-encoded string, or buffer.\n * @returns Value deserialised to JS type\n */\nexport function decode(retTypes, bytes) {\n const b = new Pipe(bytes);\n if (bytes.byteLength < magicNumber.length) {\n throw new Error('Message length smaller than magic number');\n }\n const magicBuffer = safeRead(b, magicNumber.length);\n const magic = new TextDecoder().decode(magicBuffer);\n if (magic !== magicNumber) {\n throw new Error('Wrong magic number: ' + JSON.stringify(magic));\n }\n function readTypeTable(pipe) {\n const typeTable = [];\n const len = Number(lebDecode(pipe));\n for (let i = 0; i < len; i++) {\n const ty = Number(slebDecode(pipe));\n switch (ty) {\n case -18 /* IDLTypeIds.Opt */:\n case -19 /* IDLTypeIds.Vector */: {\n const t = Number(slebDecode(pipe));\n typeTable.push([ty, t]);\n break;\n }\n case -20 /* IDLTypeIds.Record */:\n case -21 /* IDLTypeIds.Variant */: {\n const fields = [];\n let objectLength = Number(lebDecode(pipe));\n let prevHash;\n while (objectLength--) {\n const hash = Number(lebDecode(pipe));\n if (hash >= Math.pow(2, 32)) {\n throw new Error('field id out of 32-bit range');\n }\n if (typeof prevHash === 'number' && prevHash >= hash) {\n throw new Error('field id collision or not sorted');\n }\n prevHash = hash;\n const t = Number(slebDecode(pipe));\n fields.push([hash, t]);\n }\n typeTable.push([ty, fields]);\n break;\n }\n case -22 /* IDLTypeIds.Func */: {\n const args = [];\n let argLength = Number(lebDecode(pipe));\n while (argLength--) {\n args.push(Number(slebDecode(pipe)));\n }\n const returnValues = [];\n let returnValuesLength = Number(lebDecode(pipe));\n while (returnValuesLength--) {\n returnValues.push(Number(slebDecode(pipe)));\n }\n const annotations = [];\n let annotationLength = Number(lebDecode(pipe));\n while (annotationLength--) {\n const annotation = Number(lebDecode(pipe));\n switch (annotation) {\n case 1: {\n annotations.push('query');\n break;\n }\n case 2: {\n annotations.push('oneway');\n break;\n }\n case 3: {\n annotations.push('composite_query');\n break;\n }\n default:\n throw new Error('unknown annotation');\n }\n }\n typeTable.push([ty, [args, returnValues, annotations]]);\n break;\n }\n case -23 /* IDLTypeIds.Service */: {\n let servLength = Number(lebDecode(pipe));\n const methods = [];\n while (servLength--) {\n const nameLength = Number(lebDecode(pipe));\n const funcName = new TextDecoder().decode(safeRead(pipe, nameLength));\n const funcType = slebDecode(pipe);\n methods.push([funcName, funcType]);\n }\n typeTable.push([ty, methods]);\n break;\n }\n default:\n throw new Error('Illegal op_code: ' + ty);\n }\n }\n const rawList = [];\n const length = Number(lebDecode(pipe));\n for (let i = 0; i < length; i++) {\n rawList.push(Number(slebDecode(pipe)));\n }\n return [typeTable, rawList];\n }\n const [rawTable, rawTypes] = readTypeTable(b);\n if (rawTypes.length < retTypes.length) {\n throw new Error('Wrong number of return values');\n }\n const table = rawTable.map(_ => Rec());\n function getType(t) {\n if (t < -24) {\n throw new Error('future value not supported');\n }\n if (t < 0) {\n switch (t) {\n case -1:\n return Null;\n case -2:\n return Bool;\n case -3:\n return Nat;\n case -4:\n return Int;\n case -5:\n return Nat8;\n case -6:\n return Nat16;\n case -7:\n return Nat32;\n case -8:\n return Nat64;\n case -9:\n return Int8;\n case -10:\n return Int16;\n case -11:\n return Int32;\n case -12:\n return Int64;\n case -13:\n return Float32;\n case -14:\n return Float64;\n case -15:\n return Text;\n case -16:\n return Reserved;\n case -17:\n return Empty;\n case -24:\n return Principal;\n default:\n throw new Error('Illegal op_code: ' + t);\n }\n }\n if (t >= rawTable.length) {\n throw new Error('type index out of range');\n }\n return table[t];\n }\n function buildType(entry) {\n switch (entry[0]) {\n case -19 /* IDLTypeIds.Vector */: {\n const ty = getType(entry[1]);\n return Vec(ty);\n }\n case -18 /* IDLTypeIds.Opt */: {\n const ty = getType(entry[1]);\n return Opt(ty);\n }\n case -20 /* IDLTypeIds.Record */: {\n const fields = {};\n for (const [hash, ty] of entry[1]) {\n const name = `_${hash}_`;\n fields[name] = getType(ty);\n }\n const record = Record(fields);\n const tuple = record.tryAsTuple();\n if (Array.isArray(tuple)) {\n return Tuple(...tuple);\n }\n else {\n return record;\n }\n }\n case -21 /* IDLTypeIds.Variant */: {\n const fields = {};\n for (const [hash, ty] of entry[1]) {\n const name = `_${hash}_`;\n fields[name] = getType(ty);\n }\n return Variant(fields);\n }\n case -22 /* IDLTypeIds.Func */: {\n const [args, returnValues, annotations] = entry[1];\n return Func(args.map((t) => getType(t)), returnValues.map((t) => getType(t)), annotations);\n }\n case -23 /* IDLTypeIds.Service */: {\n const rec = {};\n const methods = entry[1];\n for (const [name, typeRef] of methods) {\n let type = getType(typeRef);\n if (type instanceof RecClass) {\n // unpack reference type\n type = type.getType();\n }\n if (!(type instanceof FuncClass)) {\n throw new Error('Illegal service definition: services can only contain functions');\n }\n rec[name] = type;\n }\n return Service(rec);\n }\n default:\n throw new Error('Illegal op_code: ' + entry[0]);\n }\n }\n rawTable.forEach((entry, i) => {\n // Process function type first, so that we can construct the correct service type\n if (entry[0] === -22 /* IDLTypeIds.Func */) {\n const t = buildType(entry);\n table[i].fill(t);\n }\n });\n rawTable.forEach((entry, i) => {\n if (entry[0] !== -22 /* IDLTypeIds.Func */) {\n const t = buildType(entry);\n table[i].fill(t);\n }\n });\n const types = rawTypes.map(t => getType(t));\n const output = retTypes.map((t, i) => {\n return t.decodeValue(b, types[i]);\n });\n // skip unused values\n for (let ind = retTypes.length; ind < types.length; ind++) {\n types[ind].decodeValue(b, types[ind]);\n }\n if (b.byteLength > 0) {\n throw new Error('decode: Left-over bytes');\n }\n return output;\n}\n// Export Types instances.\nexport const Empty = new EmptyClass();\nexport const Reserved = new ReservedClass();\n/**\n * Client-only type for deserializing unknown data. Not supported by Candid, and its use is discouraged.\n */\nexport const Unknown = new UnknownClass();\nexport const Bool = new BoolClass();\nexport const Null = new NullClass();\nexport const Text = new TextClass();\nexport const Int = new IntClass();\nexport const Nat = new NatClass();\nexport const Float32 = new FloatClass(32);\nexport const Float64 = new FloatClass(64);\nexport const Int8 = new FixedIntClass(8);\nexport const Int16 = new FixedIntClass(16);\nexport const Int32 = new FixedIntClass(32);\nexport const Int64 = new FixedIntClass(64);\nexport const Nat8 = new FixedNatClass(8);\nexport const Nat16 = new FixedNatClass(16);\nexport const Nat32 = new FixedNatClass(32);\nexport const Nat64 = new FixedNatClass(64);\nexport const Principal = new PrincipalClass();\n/**\n *\n * @param types array of any types\n * @returns TupleClass from those types\n */\nexport function Tuple(...types) {\n return new TupleClass(types);\n}\n/**\n *\n * @param t IDL Type\n * @returns VecClass from that type\n */\nexport function Vec(t) {\n return new VecClass(t);\n}\n/**\n *\n * @param t IDL Type\n * @returns OptClass of Type\n */\nexport function Opt(t) {\n return new OptClass(t);\n}\n/**\n *\n * @param t Record of string and IDL Type\n * @returns RecordClass of string and Type\n */\nexport function Record(t) {\n return new RecordClass(t);\n}\n/**\n *\n * @param fields Record of string and IDL Type\n * @returns VariantClass\n */\nexport function Variant(fields) {\n return new VariantClass(fields);\n}\n/**\n *\n * @returns new RecClass\n */\nexport function Rec() {\n return new RecClass();\n}\n/**\n *\n * @param args array of IDL Types\n * @param ret array of IDL Types\n * @param annotations array of strings, [] by default\n * @returns new FuncClass\n */\nexport function Func(args, ret, annotations = []) {\n return new FuncClass(args, ret, annotations);\n}\n/**\n *\n * @param t Record of string and FuncClass\n * @returns ServiceClass\n */\nexport function Service(t) {\n return new ServiceClass(t);\n}\n//# sourceMappingURL=idl.js.map","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar 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\nvar 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 var arr = new Uint8Array(1)\n var 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 var 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 var valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n var 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(\n value[Symbol.toPrimitive]('string'), encodingOrOffset, length\n )\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 var length = byteLength(string, encoding) | 0\n var buf = createBuffer(length)\n\n var 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 var length = array.length < 0 ? 0 : checked(array.length) | 0\n var buf = createBuffer(length)\n for (var 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 var 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 var 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 var len = checked(obj.length) | 0\n var 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 var x = a.length\n var y = b.length\n\n for (var 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 var 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 var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n if (pos + buf.length > buffer.length) {\n Buffer.from(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 var len = string.length\n var mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n var 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 var 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 var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var 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 var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var 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 var 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 var str = ''\n var 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 ''\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 var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var 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 var indexSize = 1\n var arrLength = arr.length\n var 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 var i\n if (dir) {\n var 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 var found = true\n for (var 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 var 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 var strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var 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 var 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 var 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 var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF)\n ? 4\n : (firstByte > 0xDF)\n ? 3\n : (firstByte > 0xBF)\n ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var 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\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var 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 var res = ''\n var 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 var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += hexSliceLookupTable[buf[i]]\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)\n for (var 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 var 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 var 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 var val = this[offset]\n var mul = 1\n var 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 var val = this[offset + --byteLength]\n var 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.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var 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 var i = byteLength\n var mul = 1\n var 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 var 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 var 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.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 var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var 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 var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var 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\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var 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 var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var 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\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 var 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 var 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 var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n var 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// HELPER FUNCTIONS\n// ================\n\nvar 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 var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var 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 var byteArray = []\n for (var 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 var c, hi, lo\n var byteArray = []\n for (var 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 for (var 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\nvar hexSliceLookupTable = (function () {\n var alphabet = '0123456789abcdef'\n var table = new Array(256)\n for (var i = 0; i < 16; ++i) {\n var i16 = i * 16\n for (var j = 0; j < 16; ++j) {\n table[i16 + j] = alphabet[i] + alphabet[j]\n }\n }\n return table\n})()\n",";(function (globalObject) {\r\n 'use strict';\r\n\r\n/*\r\n * bignumber.js v9.1.2\r\n * A JavaScript library for arbitrary-precision arithmetic.\r\n * https://github.com/MikeMcl/bignumber.js\r\n * Copyright (c) 2022 Michael Mclaughlin \r\n * MIT Licensed.\r\n *\r\n * BigNumber.prototype methods | BigNumber methods\r\n * |\r\n * absoluteValue abs | clone\r\n * comparedTo | config set\r\n * decimalPlaces dp | DECIMAL_PLACES\r\n * dividedBy div | ROUNDING_MODE\r\n * dividedToIntegerBy idiv | EXPONENTIAL_AT\r\n * exponentiatedBy pow | RANGE\r\n * integerValue | CRYPTO\r\n * isEqualTo eq | MODULO_MODE\r\n * isFinite | POW_PRECISION\r\n * isGreaterThan gt | FORMAT\r\n * isGreaterThanOrEqualTo gte | ALPHABET\r\n * isInteger | isBigNumber\r\n * isLessThan lt | maximum max\r\n * isLessThanOrEqualTo lte | minimum min\r\n * isNaN | random\r\n * isNegative | sum\r\n * isPositive |\r\n * isZero |\r\n * minus |\r\n * modulo mod |\r\n * multipliedBy times |\r\n * negated |\r\n * plus |\r\n * precision sd |\r\n * shiftedBy |\r\n * squareRoot sqrt |\r\n * toExponential |\r\n * toFixed |\r\n * toFormat |\r\n * toFraction |\r\n * toJSON |\r\n * toNumber |\r\n * toPrecision |\r\n * toString |\r\n * valueOf |\r\n *\r\n */\r\n\r\n\r\n var BigNumber,\r\n isNumeric = /^-?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i,\r\n mathceil = Math.ceil,\r\n mathfloor = Math.floor,\r\n\r\n bignumberError = '[BigNumber Error] ',\r\n tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ',\r\n\r\n BASE = 1e14,\r\n LOG_BASE = 14,\r\n MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1\r\n // MAX_INT32 = 0x7fffffff, // 2^31 - 1\r\n POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],\r\n SQRT_BASE = 1e7,\r\n\r\n // EDITABLE\r\n // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and\r\n // the arguments to toExponential, toFixed, toFormat, and toPrecision.\r\n MAX = 1E9; // 0 to MAX_INT32\r\n\r\n\r\n /*\r\n * Create and return a BigNumber constructor.\r\n */\r\n function clone(configObject) {\r\n var div, convertBase, parseNumeric,\r\n P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null },\r\n ONE = new BigNumber(1),\r\n\r\n\r\n //----------------------------- EDITABLE CONFIG DEFAULTS -------------------------------\r\n\r\n\r\n // The default values below must be integers within the inclusive ranges stated.\r\n // The values can also be changed at run-time using BigNumber.set.\r\n\r\n // The maximum number of decimal places for operations involving division.\r\n DECIMAL_PLACES = 20, // 0 to MAX\r\n\r\n // The rounding mode used when rounding to the above decimal places, and when using\r\n // toExponential, toFixed, toFormat and toPrecision, and round (default value).\r\n // UP 0 Away from zero.\r\n // DOWN 1 Towards zero.\r\n // CEIL 2 Towards +Infinity.\r\n // FLOOR 3 Towards -Infinity.\r\n // HALF_UP 4 Towards nearest neighbour. If equidistant, up.\r\n // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.\r\n // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.\r\n // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.\r\n // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.\r\n ROUNDING_MODE = 4, // 0 to 8\r\n\r\n // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]\r\n\r\n // The exponent value at and beneath which toString returns exponential notation.\r\n // Number type: -7\r\n TO_EXP_NEG = -7, // 0 to -MAX\r\n\r\n // The exponent value at and above which toString returns exponential notation.\r\n // Number type: 21\r\n TO_EXP_POS = 21, // 0 to MAX\r\n\r\n // RANGE : [MIN_EXP, MAX_EXP]\r\n\r\n // The minimum exponent value, beneath which underflow to zero occurs.\r\n // Number type: -324 (5e-324)\r\n MIN_EXP = -1e7, // -1 to -MAX\r\n\r\n // The maximum exponent value, above which overflow to Infinity occurs.\r\n // Number type: 308 (1.7976931348623157e+308)\r\n // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.\r\n MAX_EXP = 1e7, // 1 to MAX\r\n\r\n // Whether to use cryptographically-secure random number generation, if available.\r\n CRYPTO = false, // true or false\r\n\r\n // The modulo mode used when calculating the modulus: a mod n.\r\n // The quotient (q = a / n) is calculated according to the corresponding rounding mode.\r\n // The remainder (r) is calculated as: r = a - n * q.\r\n //\r\n // UP 0 The remainder is positive if the dividend is negative, else is negative.\r\n // DOWN 1 The remainder has the same sign as the dividend.\r\n // This modulo mode is commonly known as 'truncated division' and is\r\n // equivalent to (a % n) in JavaScript.\r\n // FLOOR 3 The remainder has the same sign as the divisor (Python %).\r\n // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.\r\n // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).\r\n // The remainder is always positive.\r\n //\r\n // The truncated division, floored division, Euclidian division and IEEE 754 remainder\r\n // modes are commonly used for the modulus operation.\r\n // Although the other rounding modes can also be used, they may not give useful results.\r\n MODULO_MODE = 1, // 0 to 9\r\n\r\n // The maximum number of significant digits of the result of the exponentiatedBy operation.\r\n // If POW_PRECISION is 0, there will be unlimited significant digits.\r\n POW_PRECISION = 0, // 0 to MAX\r\n\r\n // The format specification used by the BigNumber.prototype.toFormat method.\r\n FORMAT = {\r\n prefix: '',\r\n groupSize: 3,\r\n secondaryGroupSize: 0,\r\n groupSeparator: ',',\r\n decimalSeparator: '.',\r\n fractionGroupSize: 0,\r\n fractionGroupSeparator: '\\xA0', // non-breaking space\r\n suffix: ''\r\n },\r\n\r\n // The alphabet used for base conversion. It must be at least 2 characters long, with no '+',\r\n // '-', '.', whitespace, or repeated character.\r\n // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'\r\n ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz',\r\n alphabetHasNormalDecimalDigits = true;\r\n\r\n\r\n //------------------------------------------------------------------------------------------\r\n\r\n\r\n // CONSTRUCTOR\r\n\r\n\r\n /*\r\n * The BigNumber constructor and exported function.\r\n * Create and return a new instance of a BigNumber object.\r\n *\r\n * v {number|string|BigNumber} A numeric value.\r\n * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive.\r\n */\r\n function BigNumber(v, b) {\r\n var alphabet, c, caseChanged, e, i, isNum, len, str,\r\n x = this;\r\n\r\n // Enable constructor call without `new`.\r\n if (!(x instanceof BigNumber)) return new BigNumber(v, b);\r\n\r\n if (b == null) {\r\n\r\n if (v && v._isBigNumber === true) {\r\n x.s = v.s;\r\n\r\n if (!v.c || v.e > MAX_EXP) {\r\n x.c = x.e = null;\r\n } else if (v.e < MIN_EXP) {\r\n x.c = [x.e = 0];\r\n } else {\r\n x.e = v.e;\r\n x.c = v.c.slice();\r\n }\r\n\r\n return;\r\n }\r\n\r\n if ((isNum = typeof v == 'number') && v * 0 == 0) {\r\n\r\n // Use `1 / n` to handle minus zero also.\r\n x.s = 1 / v < 0 ? (v = -v, -1) : 1;\r\n\r\n // Fast path for integers, where n < 2147483648 (2**31).\r\n if (v === ~~v) {\r\n for (e = 0, i = v; i >= 10; i /= 10, e++);\r\n\r\n if (e > MAX_EXP) {\r\n x.c = x.e = null;\r\n } else {\r\n x.e = e;\r\n x.c = [v];\r\n }\r\n\r\n return;\r\n }\r\n\r\n str = String(v);\r\n } else {\r\n\r\n if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum);\r\n\r\n x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1;\r\n }\r\n\r\n // Decimal point?\r\n if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');\r\n\r\n // Exponential form?\r\n if ((i = str.search(/e/i)) > 0) {\r\n\r\n // Determine exponent.\r\n if (e < 0) e = i;\r\n e += +str.slice(i + 1);\r\n str = str.substring(0, i);\r\n } else if (e < 0) {\r\n\r\n // Integer.\r\n e = str.length;\r\n }\r\n\r\n } else {\r\n\r\n // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'\r\n intCheck(b, 2, ALPHABET.length, 'Base');\r\n\r\n // Allow exponential notation to be used with base 10 argument, while\r\n // also rounding to DECIMAL_PLACES as with other bases.\r\n if (b == 10 && alphabetHasNormalDecimalDigits) {\r\n x = new BigNumber(v);\r\n return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE);\r\n }\r\n\r\n str = String(v);\r\n\r\n if (isNum = typeof v == 'number') {\r\n\r\n // Avoid potential interpretation of Infinity and NaN as base 44+ values.\r\n if (v * 0 != 0) return parseNumeric(x, str, isNum, b);\r\n\r\n x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1;\r\n\r\n // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'\r\n if (BigNumber.DEBUG && str.replace(/^0\\.0*|\\./, '').length > 15) {\r\n throw Error\r\n (tooManyDigits + v);\r\n }\r\n } else {\r\n x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1;\r\n }\r\n\r\n alphabet = ALPHABET.slice(0, b);\r\n e = i = 0;\r\n\r\n // Check that str is a valid base b number.\r\n // Don't use RegExp, so alphabet can contain special characters.\r\n for (len = str.length; i < len; i++) {\r\n if (alphabet.indexOf(c = str.charAt(i)) < 0) {\r\n if (c == '.') {\r\n\r\n // If '.' is not the first character and it has not be found before.\r\n if (i > e) {\r\n e = len;\r\n continue;\r\n }\r\n } else if (!caseChanged) {\r\n\r\n // Allow e.g. hexadecimal 'FF' as well as 'ff'.\r\n if (str == str.toUpperCase() && (str = str.toLowerCase()) ||\r\n str == str.toLowerCase() && (str = str.toUpperCase())) {\r\n caseChanged = true;\r\n i = -1;\r\n e = 0;\r\n continue;\r\n }\r\n }\r\n\r\n return parseNumeric(x, String(v), isNum, b);\r\n }\r\n }\r\n\r\n // Prevent later check for length on converted number.\r\n isNum = false;\r\n str = convertBase(str, b, 10, x.s);\r\n\r\n // Decimal point?\r\n if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');\r\n else e = str.length;\r\n }\r\n\r\n // Determine leading zeros.\r\n for (i = 0; str.charCodeAt(i) === 48; i++);\r\n\r\n // Determine trailing zeros.\r\n for (len = str.length; str.charCodeAt(--len) === 48;);\r\n\r\n if (str = str.slice(i, ++len)) {\r\n len -= i;\r\n\r\n // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'\r\n if (isNum && BigNumber.DEBUG &&\r\n len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) {\r\n throw Error\r\n (tooManyDigits + (x.s * v));\r\n }\r\n\r\n // Overflow?\r\n if ((e = e - i - 1) > MAX_EXP) {\r\n\r\n // Infinity.\r\n x.c = x.e = null;\r\n\r\n // Underflow?\r\n } else if (e < MIN_EXP) {\r\n\r\n // Zero.\r\n x.c = [x.e = 0];\r\n } else {\r\n x.e = e;\r\n x.c = [];\r\n\r\n // Transform base\r\n\r\n // e is the base 10 exponent.\r\n // i is where to slice str to get the first element of the coefficient array.\r\n i = (e + 1) % LOG_BASE;\r\n if (e < 0) i += LOG_BASE; // i < 1\r\n\r\n if (i < len) {\r\n if (i) x.c.push(+str.slice(0, i));\r\n\r\n for (len -= LOG_BASE; i < len;) {\r\n x.c.push(+str.slice(i, i += LOG_BASE));\r\n }\r\n\r\n i = LOG_BASE - (str = str.slice(i)).length;\r\n } else {\r\n i -= len;\r\n }\r\n\r\n for (; i--; str += '0');\r\n x.c.push(+str);\r\n }\r\n } else {\r\n\r\n // Zero.\r\n x.c = [x.e = 0];\r\n }\r\n }\r\n\r\n\r\n // CONSTRUCTOR PROPERTIES\r\n\r\n\r\n BigNumber.clone = clone;\r\n\r\n BigNumber.ROUND_UP = 0;\r\n BigNumber.ROUND_DOWN = 1;\r\n BigNumber.ROUND_CEIL = 2;\r\n BigNumber.ROUND_FLOOR = 3;\r\n BigNumber.ROUND_HALF_UP = 4;\r\n BigNumber.ROUND_HALF_DOWN = 5;\r\n BigNumber.ROUND_HALF_EVEN = 6;\r\n BigNumber.ROUND_HALF_CEIL = 7;\r\n BigNumber.ROUND_HALF_FLOOR = 8;\r\n BigNumber.EUCLID = 9;\r\n\r\n\r\n /*\r\n * Configure infrequently-changing library-wide settings.\r\n *\r\n * Accept an object with the following optional properties (if the value of a property is\r\n * a number, it must be an integer within the inclusive range stated):\r\n *\r\n * DECIMAL_PLACES {number} 0 to MAX\r\n * ROUNDING_MODE {number} 0 to 8\r\n * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX]\r\n * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX]\r\n * CRYPTO {boolean} true or false\r\n * MODULO_MODE {number} 0 to 9\r\n * POW_PRECISION {number} 0 to MAX\r\n * ALPHABET {string} A string of two or more unique characters which does\r\n * not contain '.'.\r\n * FORMAT {object} An object with some of the following properties:\r\n * prefix {string}\r\n * groupSize {number}\r\n * secondaryGroupSize {number}\r\n * groupSeparator {string}\r\n * decimalSeparator {string}\r\n * fractionGroupSize {number}\r\n * fractionGroupSeparator {string}\r\n * suffix {string}\r\n *\r\n * (The values assigned to the above FORMAT object properties are not checked for validity.)\r\n *\r\n * E.g.\r\n * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })\r\n *\r\n * Ignore properties/parameters set to null or undefined, except for ALPHABET.\r\n *\r\n * Return an object with the properties current values.\r\n */\r\n BigNumber.config = BigNumber.set = function (obj) {\r\n var p, v;\r\n\r\n if (obj != null) {\r\n\r\n if (typeof obj == 'object') {\r\n\r\n // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.\r\n // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) {\r\n v = obj[p];\r\n intCheck(v, 0, MAX, p);\r\n DECIMAL_PLACES = v;\r\n }\r\n\r\n // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.\r\n // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) {\r\n v = obj[p];\r\n intCheck(v, 0, 8, p);\r\n ROUNDING_MODE = v;\r\n }\r\n\r\n // EXPONENTIAL_AT {number|number[]}\r\n // Integer, -MAX to MAX inclusive or\r\n // [integer -MAX to 0 inclusive, 0 to MAX inclusive].\r\n // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) {\r\n v = obj[p];\r\n if (v && v.pop) {\r\n intCheck(v[0], -MAX, 0, p);\r\n intCheck(v[1], 0, MAX, p);\r\n TO_EXP_NEG = v[0];\r\n TO_EXP_POS = v[1];\r\n } else {\r\n intCheck(v, -MAX, MAX, p);\r\n TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v);\r\n }\r\n }\r\n\r\n // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or\r\n // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].\r\n // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}'\r\n if (obj.hasOwnProperty(p = 'RANGE')) {\r\n v = obj[p];\r\n if (v && v.pop) {\r\n intCheck(v[0], -MAX, -1, p);\r\n intCheck(v[1], 1, MAX, p);\r\n MIN_EXP = v[0];\r\n MAX_EXP = v[1];\r\n } else {\r\n intCheck(v, -MAX, MAX, p);\r\n if (v) {\r\n MIN_EXP = -(MAX_EXP = v < 0 ? -v : v);\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' cannot be zero: ' + v);\r\n }\r\n }\r\n }\r\n\r\n // CRYPTO {boolean} true or false.\r\n // '[BigNumber Error] CRYPTO not true or false: {v}'\r\n // '[BigNumber Error] crypto unavailable'\r\n if (obj.hasOwnProperty(p = 'CRYPTO')) {\r\n v = obj[p];\r\n if (v === !!v) {\r\n if (v) {\r\n if (typeof crypto != 'undefined' && crypto &&\r\n (crypto.getRandomValues || crypto.randomBytes)) {\r\n CRYPTO = v;\r\n } else {\r\n CRYPTO = !v;\r\n throw Error\r\n (bignumberError + 'crypto unavailable');\r\n }\r\n } else {\r\n CRYPTO = v;\r\n }\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' not true or false: ' + v);\r\n }\r\n }\r\n\r\n // MODULO_MODE {number} Integer, 0 to 9 inclusive.\r\n // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'MODULO_MODE')) {\r\n v = obj[p];\r\n intCheck(v, 0, 9, p);\r\n MODULO_MODE = v;\r\n }\r\n\r\n // POW_PRECISION {number} Integer, 0 to MAX inclusive.\r\n // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'POW_PRECISION')) {\r\n v = obj[p];\r\n intCheck(v, 0, MAX, p);\r\n POW_PRECISION = v;\r\n }\r\n\r\n // FORMAT {object}\r\n // '[BigNumber Error] FORMAT not an object: {v}'\r\n if (obj.hasOwnProperty(p = 'FORMAT')) {\r\n v = obj[p];\r\n if (typeof v == 'object') FORMAT = v;\r\n else throw Error\r\n (bignumberError + p + ' not an object: ' + v);\r\n }\r\n\r\n // ALPHABET {string}\r\n // '[BigNumber Error] ALPHABET invalid: {v}'\r\n if (obj.hasOwnProperty(p = 'ALPHABET')) {\r\n v = obj[p];\r\n\r\n // Disallow if less than two characters,\r\n // or if it contains '+', '-', '.', whitespace, or a repeated character.\r\n if (typeof v == 'string' && !/^.?$|[+\\-.\\s]|(.).*\\1/.test(v)) {\r\n alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789';\r\n ALPHABET = v;\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' invalid: ' + v);\r\n }\r\n }\r\n\r\n } else {\r\n\r\n // '[BigNumber Error] Object expected: {v}'\r\n throw Error\r\n (bignumberError + 'Object expected: ' + obj);\r\n }\r\n }\r\n\r\n return {\r\n DECIMAL_PLACES: DECIMAL_PLACES,\r\n ROUNDING_MODE: ROUNDING_MODE,\r\n EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS],\r\n RANGE: [MIN_EXP, MAX_EXP],\r\n CRYPTO: CRYPTO,\r\n MODULO_MODE: MODULO_MODE,\r\n POW_PRECISION: POW_PRECISION,\r\n FORMAT: FORMAT,\r\n ALPHABET: ALPHABET\r\n };\r\n };\r\n\r\n\r\n /*\r\n * Return true if v is a BigNumber instance, otherwise return false.\r\n *\r\n * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed.\r\n *\r\n * v {any}\r\n *\r\n * '[BigNumber Error] Invalid BigNumber: {v}'\r\n */\r\n BigNumber.isBigNumber = function (v) {\r\n if (!v || v._isBigNumber !== true) return false;\r\n if (!BigNumber.DEBUG) return true;\r\n\r\n var i, n,\r\n c = v.c,\r\n e = v.e,\r\n s = v.s;\r\n\r\n out: if ({}.toString.call(c) == '[object Array]') {\r\n\r\n if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) {\r\n\r\n // If the first element is zero, the BigNumber value must be zero.\r\n if (c[0] === 0) {\r\n if (e === 0 && c.length === 1) return true;\r\n break out;\r\n }\r\n\r\n // Calculate number of digits that c[0] should have, based on the exponent.\r\n i = (e + 1) % LOG_BASE;\r\n if (i < 1) i += LOG_BASE;\r\n\r\n // Calculate number of digits of c[0].\r\n //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) {\r\n if (String(c[0]).length == i) {\r\n\r\n for (i = 0; i < c.length; i++) {\r\n n = c[i];\r\n if (n < 0 || n >= BASE || n !== mathfloor(n)) break out;\r\n }\r\n\r\n // Last element cannot be zero, unless it is the only element.\r\n if (n !== 0) return true;\r\n }\r\n }\r\n\r\n // Infinity/NaN\r\n } else if (c === null && e === null && (s === null || s === 1 || s === -1)) {\r\n return true;\r\n }\r\n\r\n throw Error\r\n (bignumberError + 'Invalid BigNumber: ' + v);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the maximum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.maximum = BigNumber.max = function () {\r\n return maxOrMin(arguments, -1);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the minimum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.minimum = BigNumber.min = function () {\r\n return maxOrMin(arguments, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,\r\n * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing\r\n * zeros are produced).\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}'\r\n * '[BigNumber Error] crypto unavailable'\r\n */\r\n BigNumber.random = (function () {\r\n var pow2_53 = 0x20000000000000;\r\n\r\n // Return a 53 bit integer n, where 0 <= n < 9007199254740992.\r\n // Check if Math.random() produces more than 32 bits of randomness.\r\n // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.\r\n // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.\r\n var random53bitInt = (Math.random() * pow2_53) & 0x1fffff\r\n ? function () { return mathfloor(Math.random() * pow2_53); }\r\n : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +\r\n (Math.random() * 0x800000 | 0); };\r\n\r\n return function (dp) {\r\n var a, b, e, k, v,\r\n i = 0,\r\n c = [],\r\n rand = new BigNumber(ONE);\r\n\r\n if (dp == null) dp = DECIMAL_PLACES;\r\n else intCheck(dp, 0, MAX);\r\n\r\n k = mathceil(dp / LOG_BASE);\r\n\r\n if (CRYPTO) {\r\n\r\n // Browsers supporting crypto.getRandomValues.\r\n if (crypto.getRandomValues) {\r\n\r\n a = crypto.getRandomValues(new Uint32Array(k *= 2));\r\n\r\n for (; i < k;) {\r\n\r\n // 53 bits:\r\n // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)\r\n // 11111 11111111 11111111 11111111 11100000 00000000 00000000\r\n // ((Math.pow(2, 32) - 1) >>> 11).toString(2)\r\n // 11111 11111111 11111111\r\n // 0x20000 is 2^21.\r\n v = a[i] * 0x20000 + (a[i + 1] >>> 11);\r\n\r\n // Rejection sampling:\r\n // 0 <= v < 9007199254740992\r\n // Probability that v >= 9e15, is\r\n // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251\r\n if (v >= 9e15) {\r\n b = crypto.getRandomValues(new Uint32Array(2));\r\n a[i] = b[0];\r\n a[i + 1] = b[1];\r\n } else {\r\n\r\n // 0 <= v <= 8999999999999999\r\n // 0 <= (v % 1e14) <= 99999999999999\r\n c.push(v % 1e14);\r\n i += 2;\r\n }\r\n }\r\n i = k / 2;\r\n\r\n // Node.js supporting crypto.randomBytes.\r\n } else if (crypto.randomBytes) {\r\n\r\n // buffer\r\n a = crypto.randomBytes(k *= 7);\r\n\r\n for (; i < k;) {\r\n\r\n // 0x1000000000000 is 2^48, 0x10000000000 is 2^40\r\n // 0x100000000 is 2^32, 0x1000000 is 2^24\r\n // 11111 11111111 11111111 11111111 11111111 11111111 11111111\r\n // 0 <= v < 9007199254740992\r\n v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) +\r\n (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) +\r\n (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6];\r\n\r\n if (v >= 9e15) {\r\n crypto.randomBytes(7).copy(a, i);\r\n } else {\r\n\r\n // 0 <= (v % 1e14) <= 99999999999999\r\n c.push(v % 1e14);\r\n i += 7;\r\n }\r\n }\r\n i = k / 7;\r\n } else {\r\n CRYPTO = false;\r\n throw Error\r\n (bignumberError + 'crypto unavailable');\r\n }\r\n }\r\n\r\n // Use Math.random.\r\n if (!CRYPTO) {\r\n\r\n for (; i < k;) {\r\n v = random53bitInt();\r\n if (v < 9e15) c[i++] = v % 1e14;\r\n }\r\n }\r\n\r\n k = c[--i];\r\n dp %= LOG_BASE;\r\n\r\n // Convert trailing digits to zeros according to dp.\r\n if (k && dp) {\r\n v = POWS_TEN[LOG_BASE - dp];\r\n c[i] = mathfloor(k / v) * v;\r\n }\r\n\r\n // Remove trailing elements which are zero.\r\n for (; c[i] === 0; c.pop(), i--);\r\n\r\n // Zero?\r\n if (i < 0) {\r\n c = [e = 0];\r\n } else {\r\n\r\n // Remove leading elements which are zero and adjust exponent accordingly.\r\n for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE);\r\n\r\n // Count the digits of the first element of c to determine leading zeros, and...\r\n for (i = 1, v = c[0]; v >= 10; v /= 10, i++);\r\n\r\n // adjust the exponent accordingly.\r\n if (i < LOG_BASE) e -= LOG_BASE - i;\r\n }\r\n\r\n rand.e = e;\r\n rand.c = c;\r\n return rand;\r\n };\r\n })();\r\n\r\n\r\n /*\r\n * Return a BigNumber whose value is the sum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.sum = function () {\r\n var i = 1,\r\n args = arguments,\r\n sum = new BigNumber(args[0]);\r\n for (; i < args.length;) sum = sum.plus(args[i++]);\r\n return sum;\r\n };\r\n\r\n\r\n // PRIVATE FUNCTIONS\r\n\r\n\r\n // Called by BigNumber and BigNumber.prototype.toString.\r\n convertBase = (function () {\r\n var decimal = '0123456789';\r\n\r\n /*\r\n * Convert string of baseIn to an array of numbers of baseOut.\r\n * Eg. toBaseOut('255', 10, 16) returns [15, 15].\r\n * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5].\r\n */\r\n function toBaseOut(str, baseIn, baseOut, alphabet) {\r\n var j,\r\n arr = [0],\r\n arrL,\r\n i = 0,\r\n len = str.length;\r\n\r\n for (; i < len;) {\r\n for (arrL = arr.length; arrL--; arr[arrL] *= baseIn);\r\n\r\n arr[0] += alphabet.indexOf(str.charAt(i++));\r\n\r\n for (j = 0; j < arr.length; j++) {\r\n\r\n if (arr[j] > baseOut - 1) {\r\n if (arr[j + 1] == null) arr[j + 1] = 0;\r\n arr[j + 1] += arr[j] / baseOut | 0;\r\n arr[j] %= baseOut;\r\n }\r\n }\r\n }\r\n\r\n return arr.reverse();\r\n }\r\n\r\n // Convert a numeric string of baseIn to a numeric string of baseOut.\r\n // If the caller is toString, we are converting from base 10 to baseOut.\r\n // If the caller is BigNumber, we are converting from baseIn to base 10.\r\n return function (str, baseIn, baseOut, sign, callerIsToString) {\r\n var alphabet, d, e, k, r, x, xc, y,\r\n i = str.indexOf('.'),\r\n dp = DECIMAL_PLACES,\r\n rm = ROUNDING_MODE;\r\n\r\n // Non-integer.\r\n if (i >= 0) {\r\n k = POW_PRECISION;\r\n\r\n // Unlimited precision.\r\n POW_PRECISION = 0;\r\n str = str.replace('.', '');\r\n y = new BigNumber(baseIn);\r\n x = y.pow(str.length - i);\r\n POW_PRECISION = k;\r\n\r\n // Convert str as if an integer, then restore the fraction part by dividing the\r\n // result by its base raised to a power.\r\n\r\n y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'),\r\n 10, baseOut, decimal);\r\n y.e = y.c.length;\r\n }\r\n\r\n // Convert the number as integer.\r\n\r\n xc = toBaseOut(str, baseIn, baseOut, callerIsToString\r\n ? (alphabet = ALPHABET, decimal)\r\n : (alphabet = decimal, ALPHABET));\r\n\r\n // xc now represents str as an integer and converted to baseOut. e is the exponent.\r\n e = k = xc.length;\r\n\r\n // Remove trailing zeros.\r\n for (; xc[--k] == 0; xc.pop());\r\n\r\n // Zero?\r\n if (!xc[0]) return alphabet.charAt(0);\r\n\r\n // Does str represent an integer? If so, no need for the division.\r\n if (i < 0) {\r\n --e;\r\n } else {\r\n x.c = xc;\r\n x.e = e;\r\n\r\n // The sign is needed for correct rounding.\r\n x.s = sign;\r\n x = div(x, y, dp, rm, baseOut);\r\n xc = x.c;\r\n r = x.r;\r\n e = x.e;\r\n }\r\n\r\n // xc now represents str converted to baseOut.\r\n\r\n // THe index of the rounding digit.\r\n d = e + dp + 1;\r\n\r\n // The rounding digit: the digit to the right of the digit that may be rounded up.\r\n i = xc[d];\r\n\r\n // Look at the rounding digits and mode to determine whether to round up.\r\n\r\n k = baseOut / 2;\r\n r = r || d < 0 || xc[d + 1] != null;\r\n\r\n r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))\r\n : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||\r\n rm == (x.s < 0 ? 8 : 7));\r\n\r\n // If the index of the rounding digit is not greater than zero, or xc represents\r\n // zero, then the result of the base conversion is zero or, if rounding up, a value\r\n // such as 0.00001.\r\n if (d < 1 || !xc[0]) {\r\n\r\n // 1^-dp or 0\r\n str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0);\r\n } else {\r\n\r\n // Truncate xc to the required number of decimal places.\r\n xc.length = d;\r\n\r\n // Round up?\r\n if (r) {\r\n\r\n // Rounding up may mean the previous digit has to be rounded up and so on.\r\n for (--baseOut; ++xc[--d] > baseOut;) {\r\n xc[d] = 0;\r\n\r\n if (!d) {\r\n ++e;\r\n xc = [1].concat(xc);\r\n }\r\n }\r\n }\r\n\r\n // Determine trailing zeros.\r\n for (k = xc.length; !xc[--k];);\r\n\r\n // E.g. [4, 11, 15] becomes 4bf.\r\n for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++]));\r\n\r\n // Add leading zeros, decimal point and trailing zeros as required.\r\n str = toFixedPoint(str, e, alphabet.charAt(0));\r\n }\r\n\r\n // The caller will add the sign.\r\n return str;\r\n };\r\n })();\r\n\r\n\r\n // Perform division in the specified base. Called by div and convertBase.\r\n div = (function () {\r\n\r\n // Assume non-zero x and k.\r\n function multiply(x, k, base) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for (x = x.slice(); i--;) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\r\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }\r\n\r\n function compare(a, b, aL, bL) {\r\n var i, cmp;\r\n\r\n if (aL != bL) {\r\n cmp = aL > bL ? 1 : -1;\r\n } else {\r\n\r\n for (i = cmp = 0; i < aL; i++) {\r\n\r\n if (a[i] != b[i]) {\r\n cmp = a[i] > b[i] ? 1 : -1;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n return cmp;\r\n }\r\n\r\n function subtract(a, b, aL, base) {\r\n var i = 0;\r\n\r\n // Subtract b from a.\r\n for (; aL--;) {\r\n a[aL] -= i;\r\n i = a[aL] < b[aL] ? 1 : 0;\r\n a[aL] = i * base + a[aL] - b[aL];\r\n }\r\n\r\n // Remove leading zeros.\r\n for (; !a[0] && a.length > 1; a.splice(0, 1));\r\n }\r\n\r\n // x: dividend, y: divisor.\r\n return function (x, y, dp, rm, base) {\r\n var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,\r\n yL, yz,\r\n s = x.s == y.s ? 1 : -1,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n // Either NaN, Infinity or 0?\r\n if (!xc || !xc[0] || !yc || !yc[0]) {\r\n\r\n return new BigNumber(\r\n\r\n // Return NaN if either NaN, or both Infinity or 0.\r\n !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN :\r\n\r\n // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.\r\n xc && xc[0] == 0 || !yc ? s * 0 : s / 0\r\n );\r\n }\r\n\r\n q = new BigNumber(s);\r\n qc = q.c = [];\r\n e = x.e - y.e;\r\n s = dp + e + 1;\r\n\r\n if (!base) {\r\n base = BASE;\r\n e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE);\r\n s = s / LOG_BASE | 0;\r\n }\r\n\r\n // Result exponent may be one less then the current value of e.\r\n // The coefficients of the BigNumbers from convertBase may have trailing zeros.\r\n for (i = 0; yc[i] == (xc[i] || 0); i++);\r\n\r\n if (yc[i] > (xc[i] || 0)) e--;\r\n\r\n if (s < 0) {\r\n qc.push(1);\r\n more = true;\r\n } else {\r\n xL = xc.length;\r\n yL = yc.length;\r\n i = 0;\r\n s += 2;\r\n\r\n // Normalise xc and yc so highest order digit of yc is >= base / 2.\r\n\r\n n = mathfloor(base / (yc[0] + 1));\r\n\r\n // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1.\r\n // if (n > 1 || n++ == 1 && yc[0] < base / 2) {\r\n if (n > 1) {\r\n yc = multiply(yc, n, base);\r\n xc = multiply(xc, n, base);\r\n yL = yc.length;\r\n xL = xc.length;\r\n }\r\n\r\n xi = yL;\r\n rem = xc.slice(0, yL);\r\n remL = rem.length;\r\n\r\n // Add zeros to make remainder as long as divisor.\r\n for (; remL < yL; rem[remL++] = 0);\r\n yz = yc.slice();\r\n yz = [0].concat(yz);\r\n yc0 = yc[0];\r\n if (yc[1] >= base / 2) yc0++;\r\n // Not necessary, but to prevent trial digit n > base, when using base 3.\r\n // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15;\r\n\r\n do {\r\n n = 0;\r\n\r\n // Compare divisor and remainder.\r\n cmp = compare(yc, rem, yL, remL);\r\n\r\n // If divisor < remainder.\r\n if (cmp < 0) {\r\n\r\n // Calculate trial digit, n.\r\n\r\n rem0 = rem[0];\r\n if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);\r\n\r\n // n is how many times the divisor goes into the current remainder.\r\n n = mathfloor(rem0 / yc0);\r\n\r\n // Algorithm:\r\n // product = divisor multiplied by trial digit (n).\r\n // Compare product and remainder.\r\n // If product is greater than remainder:\r\n // Subtract divisor from product, decrement trial digit.\r\n // Subtract product from remainder.\r\n // If product was less than remainder at the last compare:\r\n // Compare new remainder and divisor.\r\n // If remainder is greater than divisor:\r\n // Subtract divisor from remainder, increment trial digit.\r\n\r\n if (n > 1) {\r\n\r\n // n may be > base only when base is 3.\r\n if (n >= base) n = base - 1;\r\n\r\n // product = divisor * trial digit.\r\n prod = multiply(yc, n, base);\r\n prodL = prod.length;\r\n remL = rem.length;\r\n\r\n // Compare product and remainder.\r\n // If product > remainder then trial digit n too high.\r\n // n is 1 too high about 5% of the time, and is not known to have\r\n // ever been more than 1 too high.\r\n while (compare(prod, rem, prodL, remL) == 1) {\r\n n--;\r\n\r\n // Subtract divisor from product.\r\n subtract(prod, yL < prodL ? yz : yc, prodL, base);\r\n prodL = prod.length;\r\n cmp = 1;\r\n }\r\n } else {\r\n\r\n // n is 0 or 1, cmp is -1.\r\n // If n is 0, there is no need to compare yc and rem again below,\r\n // so change cmp to 1 to avoid it.\r\n // If n is 1, leave cmp as -1, so yc and rem are compared again.\r\n if (n == 0) {\r\n\r\n // divisor < remainder, so n must be at least 1.\r\n cmp = n = 1;\r\n }\r\n\r\n // product = divisor\r\n prod = yc.slice();\r\n prodL = prod.length;\r\n }\r\n\r\n if (prodL < remL) prod = [0].concat(prod);\r\n\r\n // Subtract product from remainder.\r\n subtract(rem, prod, remL, base);\r\n remL = rem.length;\r\n\r\n // If product was < remainder.\r\n if (cmp == -1) {\r\n\r\n // Compare divisor and new remainder.\r\n // If divisor < new remainder, subtract divisor from remainder.\r\n // Trial digit n too low.\r\n // n is 1 too low about 5% of the time, and very rarely 2 too low.\r\n while (compare(yc, rem, yL, remL) < 1) {\r\n n++;\r\n\r\n // Subtract divisor from remainder.\r\n subtract(rem, yL < remL ? yz : yc, remL, base);\r\n remL = rem.length;\r\n }\r\n }\r\n } else if (cmp === 0) {\r\n n++;\r\n rem = [0];\r\n } // else cmp === 1 and n will be 0\r\n\r\n // Add the next digit, n, to the result array.\r\n qc[i++] = n;\r\n\r\n // Update the remainder.\r\n if (rem[0]) {\r\n rem[remL++] = xc[xi] || 0;\r\n } else {\r\n rem = [xc[xi]];\r\n remL = 1;\r\n }\r\n } while ((xi++ < xL || rem[0] != null) && s--);\r\n\r\n more = rem[0] != null;\r\n\r\n // Leading zero?\r\n if (!qc[0]) qc.splice(0, 1);\r\n }\r\n\r\n if (base == BASE) {\r\n\r\n // To calculate q.e, first get the number of digits of qc[0].\r\n for (i = 1, s = qc[0]; s >= 10; s /= 10, i++);\r\n\r\n round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more);\r\n\r\n // Caller is convertBase.\r\n } else {\r\n q.e = e;\r\n q.r = +more;\r\n }\r\n\r\n return q;\r\n };\r\n })();\r\n\r\n\r\n /*\r\n * Return a string representing the value of BigNumber n in fixed-point or exponential\r\n * notation rounded to the specified decimal places or significant digits.\r\n *\r\n * n: a BigNumber.\r\n * i: the index of the last digit required (i.e. the digit that may be rounded up).\r\n * rm: the rounding mode.\r\n * id: 1 (toExponential) or 2 (toPrecision).\r\n */\r\n function format(n, i, rm, id) {\r\n var c0, e, ne, len, str;\r\n\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n if (!n.c) return n.toString();\r\n\r\n c0 = n.c[0];\r\n ne = n.e;\r\n\r\n if (i == null) {\r\n str = coeffToString(n.c);\r\n str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS)\r\n ? toExponential(str, ne)\r\n : toFixedPoint(str, ne, '0');\r\n } else {\r\n n = round(new BigNumber(n), i, rm);\r\n\r\n // n.e may have changed if the value was rounded up.\r\n e = n.e;\r\n\r\n str = coeffToString(n.c);\r\n len = str.length;\r\n\r\n // toPrecision returns exponential notation if the number of significant digits\r\n // specified is less than the number of digits necessary to represent the integer\r\n // part of the value in fixed-point notation.\r\n\r\n // Exponential notation.\r\n if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) {\r\n\r\n // Append zeros?\r\n for (; len < i; str += '0', len++);\r\n str = toExponential(str, e);\r\n\r\n // Fixed-point notation.\r\n } else {\r\n i -= ne;\r\n str = toFixedPoint(str, e, '0');\r\n\r\n // Append zeros?\r\n if (e + 1 > len) {\r\n if (--i > 0) for (str += '.'; i--; str += '0');\r\n } else {\r\n i += e - len;\r\n if (i > 0) {\r\n if (e + 1 == len) str += '.';\r\n for (; i--; str += '0');\r\n }\r\n }\r\n }\r\n }\r\n\r\n return n.s < 0 && c0 ? '-' + str : str;\r\n }\r\n\r\n\r\n // Handle BigNumber.max and BigNumber.min.\r\n // If any number is NaN, return NaN.\r\n function maxOrMin(args, n) {\r\n var k, y,\r\n i = 1,\r\n x = new BigNumber(args[0]);\r\n\r\n for (; i < args.length; i++) {\r\n y = new BigNumber(args[i]);\r\n if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) {\r\n x = y;\r\n }\r\n }\r\n\r\n return x;\r\n }\r\n\r\n\r\n /*\r\n * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.\r\n * Called by minus, plus and times.\r\n */\r\n function normalise(n, c, e) {\r\n var i = 1,\r\n j = c.length;\r\n\r\n // Remove trailing zeros.\r\n for (; !c[--j]; c.pop());\r\n\r\n // Calculate the base 10 exponent. First get the number of digits of c[0].\r\n for (j = c[0]; j >= 10; j /= 10, i++);\r\n\r\n // Overflow?\r\n if ((e = i + e * LOG_BASE - 1) > MAX_EXP) {\r\n\r\n // Infinity.\r\n n.c = n.e = null;\r\n\r\n // Underflow?\r\n } else if (e < MIN_EXP) {\r\n\r\n // Zero.\r\n n.c = [n.e = 0];\r\n } else {\r\n n.e = e;\r\n n.c = c;\r\n }\r\n\r\n return n;\r\n }\r\n\r\n\r\n // Handle values that fail the validity test in BigNumber.\r\n parseNumeric = (function () {\r\n var basePrefix = /^(-?)0([xbo])(?=\\w[\\w.]*$)/i,\r\n dotAfter = /^([^.]+)\\.$/,\r\n dotBefore = /^\\.([^.]+)$/,\r\n isInfinityOrNaN = /^-?(Infinity|NaN)$/,\r\n whitespaceOrPlus = /^\\s*\\+(?=[\\w.])|^\\s+|\\s+$/g;\r\n\r\n return function (x, str, isNum, b) {\r\n var base,\r\n s = isNum ? str : str.replace(whitespaceOrPlus, '');\r\n\r\n // No exception on ±Infinity or NaN.\r\n if (isInfinityOrNaN.test(s)) {\r\n x.s = isNaN(s) ? null : s < 0 ? -1 : 1;\r\n } else {\r\n if (!isNum) {\r\n\r\n // basePrefix = /^(-?)0([xbo])(?=\\w[\\w.]*$)/i\r\n s = s.replace(basePrefix, function (m, p1, p2) {\r\n base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8;\r\n return !b || b == base ? p1 : m;\r\n });\r\n\r\n if (b) {\r\n base = b;\r\n\r\n // E.g. '1.' to '1', '.1' to '0.1'\r\n s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1');\r\n }\r\n\r\n if (str != s) return new BigNumber(s, base);\r\n }\r\n\r\n // '[BigNumber Error] Not a number: {n}'\r\n // '[BigNumber Error] Not a base {b} number: {n}'\r\n if (BigNumber.DEBUG) {\r\n throw Error\r\n (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str);\r\n }\r\n\r\n // NaN\r\n x.s = null;\r\n }\r\n\r\n x.c = x.e = null;\r\n }\r\n })();\r\n\r\n\r\n /*\r\n * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.\r\n * If r is truthy, it is known that there are more digits after the rounding digit.\r\n */\r\n function round(x, sd, rm, r) {\r\n var d, i, j, k, n, ni, rd,\r\n xc = x.c,\r\n pows10 = POWS_TEN;\r\n\r\n // if x is not Infinity or NaN...\r\n if (xc) {\r\n\r\n // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.\r\n // n is a base 1e14 number, the value of the element of array x.c containing rd.\r\n // ni is the index of n within x.c.\r\n // d is the number of digits of n.\r\n // i is the index of rd within n including leading zeros.\r\n // j is the actual index of rd within n (if < 0, rd is a leading zero).\r\n out: {\r\n\r\n // Get the number of digits of the first element of xc.\r\n for (d = 1, k = xc[0]; k >= 10; k /= 10, d++);\r\n i = sd - d;\r\n\r\n // If the rounding digit is in the first element of xc...\r\n if (i < 0) {\r\n i += LOG_BASE;\r\n j = sd;\r\n n = xc[ni = 0];\r\n\r\n // Get the rounding digit at index j of n.\r\n rd = mathfloor(n / pows10[d - j - 1] % 10);\r\n } else {\r\n ni = mathceil((i + 1) / LOG_BASE);\r\n\r\n if (ni >= xc.length) {\r\n\r\n if (r) {\r\n\r\n // Needed by sqrt.\r\n for (; xc.length <= ni; xc.push(0));\r\n n = rd = 0;\r\n d = 1;\r\n i %= LOG_BASE;\r\n j = i - LOG_BASE + 1;\r\n } else {\r\n break out;\r\n }\r\n } else {\r\n n = k = xc[ni];\r\n\r\n // Get the number of digits of n.\r\n for (d = 1; k >= 10; k /= 10, d++);\r\n\r\n // Get the index of rd within n.\r\n i %= LOG_BASE;\r\n\r\n // Get the index of rd within n, adjusted for leading zeros.\r\n // The number of leading zeros of n is given by LOG_BASE - d.\r\n j = i - LOG_BASE + d;\r\n\r\n // Get the rounding digit at index j of n.\r\n rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10);\r\n }\r\n }\r\n\r\n r = r || sd < 0 ||\r\n\r\n // Are there any non-zero digits after the rounding digit?\r\n // The expression n % pows10[d - j - 1] returns all digits of n to the right\r\n // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.\r\n xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]);\r\n\r\n r = rm < 4\r\n ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))\r\n : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 &&\r\n\r\n // Check whether the digit to the left of the rounding digit is odd.\r\n ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 ||\r\n rm == (x.s < 0 ? 8 : 7));\r\n\r\n if (sd < 1 || !xc[0]) {\r\n xc.length = 0;\r\n\r\n if (r) {\r\n\r\n // Convert sd to decimal places.\r\n sd -= x.e + 1;\r\n\r\n // 1, 0.1, 0.01, 0.001, 0.0001 etc.\r\n xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE];\r\n x.e = -sd || 0;\r\n } else {\r\n\r\n // Zero.\r\n xc[0] = x.e = 0;\r\n }\r\n\r\n return x;\r\n }\r\n\r\n // Remove excess digits.\r\n if (i == 0) {\r\n xc.length = ni;\r\n k = 1;\r\n ni--;\r\n } else {\r\n xc.length = ni + 1;\r\n k = pows10[LOG_BASE - i];\r\n\r\n // E.g. 56700 becomes 56000 if 7 is the rounding digit.\r\n // j > 0 means i > number of leading zeros of n.\r\n xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0;\r\n }\r\n\r\n // Round up?\r\n if (r) {\r\n\r\n for (; ;) {\r\n\r\n // If the digit to be rounded up is in the first element of xc...\r\n if (ni == 0) {\r\n\r\n // i will be the length of xc[0] before k is added.\r\n for (i = 1, j = xc[0]; j >= 10; j /= 10, i++);\r\n j = xc[0] += k;\r\n for (k = 1; j >= 10; j /= 10, k++);\r\n\r\n // if i != k the length has increased.\r\n if (i != k) {\r\n x.e++;\r\n if (xc[0] == BASE) xc[0] = 1;\r\n }\r\n\r\n break;\r\n } else {\r\n xc[ni] += k;\r\n if (xc[ni] != BASE) break;\r\n xc[ni--] = 0;\r\n k = 1;\r\n }\r\n }\r\n }\r\n\r\n // Remove trailing zeros.\r\n for (i = xc.length; xc[--i] === 0; xc.pop());\r\n }\r\n\r\n // Overflow? Infinity.\r\n if (x.e > MAX_EXP) {\r\n x.c = x.e = null;\r\n\r\n // Underflow? Zero.\r\n } else if (x.e < MIN_EXP) {\r\n x.c = [x.e = 0];\r\n }\r\n }\r\n\r\n return x;\r\n }\r\n\r\n\r\n function valueOf(n) {\r\n var str,\r\n e = n.e;\r\n\r\n if (e === null) return n.toString();\r\n\r\n str = coeffToString(n.c);\r\n\r\n str = e <= TO_EXP_NEG || e >= TO_EXP_POS\r\n ? toExponential(str, e)\r\n : toFixedPoint(str, e, '0');\r\n\r\n return n.s < 0 ? '-' + str : str;\r\n }\r\n\r\n\r\n // PROTOTYPE/INSTANCE METHODS\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the absolute value of this BigNumber.\r\n */\r\n P.absoluteValue = P.abs = function () {\r\n var x = new BigNumber(this);\r\n if (x.s < 0) x.s = 1;\r\n return x;\r\n };\r\n\r\n\r\n /*\r\n * Return\r\n * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),\r\n * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),\r\n * 0 if they have the same value,\r\n * or null if the value of either is NaN.\r\n */\r\n P.comparedTo = function (y, b) {\r\n return compare(this, new BigNumber(y, b));\r\n };\r\n\r\n\r\n /*\r\n * If dp is undefined or null or true or false, return the number of decimal places of the\r\n * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN.\r\n *\r\n * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this\r\n * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or\r\n * ROUNDING_MODE if rm is omitted.\r\n *\r\n * [dp] {number} Decimal places: integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.decimalPlaces = P.dp = function (dp, rm) {\r\n var c, n, v,\r\n x = this;\r\n\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n return round(new BigNumber(x), dp + x.e + 1, rm);\r\n }\r\n\r\n if (!(c = x.c)) return null;\r\n n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE;\r\n\r\n // Subtract the number of trailing zeros of the last number.\r\n if (v = c[v]) for (; v % 10 == 0; v /= 10, n--);\r\n if (n < 0) n = 0;\r\n\r\n return n;\r\n };\r\n\r\n\r\n /*\r\n * n / 0 = I\r\n * n / N = N\r\n * n / I = 0\r\n * 0 / n = 0\r\n * 0 / 0 = N\r\n * 0 / N = N\r\n * 0 / I = 0\r\n * N / n = N\r\n * N / 0 = N\r\n * N / N = N\r\n * N / I = N\r\n * I / n = I\r\n * I / 0 = I\r\n * I / N = N\r\n * I / I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber divided by the value of\r\n * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.\r\n */\r\n P.dividedBy = P.div = function (y, b) {\r\n return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the integer part of dividing the value of this\r\n * BigNumber by the value of BigNumber(y, b).\r\n */\r\n P.dividedToIntegerBy = P.idiv = function (y, b) {\r\n return div(this, new BigNumber(y, b), 0, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a BigNumber whose value is the value of this BigNumber exponentiated by n.\r\n *\r\n * If m is present, return the result modulo m.\r\n * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.\r\n * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE.\r\n *\r\n * The modular power operation works efficiently when x, n, and m are integers, otherwise it\r\n * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0.\r\n *\r\n * n {number|string|BigNumber} The exponent. An integer.\r\n * [m] {number|string|BigNumber} The modulus.\r\n *\r\n * '[BigNumber Error] Exponent not an integer: {n}'\r\n */\r\n P.exponentiatedBy = P.pow = function (n, m) {\r\n var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y,\r\n x = this;\r\n\r\n n = new BigNumber(n);\r\n\r\n // Allow NaN and ±Infinity, but not other non-integers.\r\n if (n.c && !n.isInteger()) {\r\n throw Error\r\n (bignumberError + 'Exponent not an integer: ' + valueOf(n));\r\n }\r\n\r\n if (m != null) m = new BigNumber(m);\r\n\r\n // Exponent of MAX_SAFE_INTEGER is 15.\r\n nIsBig = n.e > 14;\r\n\r\n // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0.\r\n if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) {\r\n\r\n // The sign of the result of pow when x is negative depends on the evenness of n.\r\n // If +n overflows to ±Infinity, the evenness of n would be not be known.\r\n y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n)));\r\n return m ? y.mod(m) : y;\r\n }\r\n\r\n nIsNeg = n.s < 0;\r\n\r\n if (m) {\r\n\r\n // x % m returns NaN if abs(m) is zero, or m is NaN.\r\n if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN);\r\n\r\n isModExp = !nIsNeg && x.isInteger() && m.isInteger();\r\n\r\n if (isModExp) x = x.mod(m);\r\n\r\n // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15.\r\n // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15.\r\n } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0\r\n // [1, 240000000]\r\n ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7\r\n // [80000000000000] [99999750000000]\r\n : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) {\r\n\r\n // If x is negative and n is odd, k = -0, else k = 0.\r\n k = x.s < 0 && isOdd(n) ? -0 : 0;\r\n\r\n // If x >= 1, k = ±Infinity.\r\n if (x.e > -1) k = 1 / k;\r\n\r\n // If n is negative return ±0, else return ±Infinity.\r\n return new BigNumber(nIsNeg ? 1 / k : k);\r\n\r\n } else if (POW_PRECISION) {\r\n\r\n // Truncating each coefficient array to a length of k after each multiplication\r\n // equates to truncating significant digits to POW_PRECISION + [28, 41],\r\n // i.e. there will be a minimum of 28 guard digits retained.\r\n k = mathceil(POW_PRECISION / LOG_BASE + 2);\r\n }\r\n\r\n if (nIsBig) {\r\n half = new BigNumber(0.5);\r\n if (nIsNeg) n.s = 1;\r\n nIsOdd = isOdd(n);\r\n } else {\r\n i = Math.abs(+valueOf(n));\r\n nIsOdd = i % 2;\r\n }\r\n\r\n y = new BigNumber(ONE);\r\n\r\n // Performs 54 loop iterations for n of 9007199254740991.\r\n for (; ;) {\r\n\r\n if (nIsOdd) {\r\n y = y.times(x);\r\n if (!y.c) break;\r\n\r\n if (k) {\r\n if (y.c.length > k) y.c.length = k;\r\n } else if (isModExp) {\r\n y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m));\r\n }\r\n }\r\n\r\n if (i) {\r\n i = mathfloor(i / 2);\r\n if (i === 0) break;\r\n nIsOdd = i % 2;\r\n } else {\r\n n = n.times(half);\r\n round(n, n.e + 1, 1);\r\n\r\n if (n.e > 14) {\r\n nIsOdd = isOdd(n);\r\n } else {\r\n i = +valueOf(n);\r\n if (i === 0) break;\r\n nIsOdd = i % 2;\r\n }\r\n }\r\n\r\n x = x.times(x);\r\n\r\n if (k) {\r\n if (x.c && x.c.length > k) x.c.length = k;\r\n } else if (isModExp) {\r\n x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m));\r\n }\r\n }\r\n\r\n if (isModExp) return y;\r\n if (nIsNeg) y = ONE.div(y);\r\n\r\n return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y;\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer\r\n * using rounding mode rm, or ROUNDING_MODE if rm is omitted.\r\n *\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}'\r\n */\r\n P.integerValue = function (rm) {\r\n var n = new BigNumber(this);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n return round(n, n.e + 1, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isEqualTo = P.eq = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) === 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is a finite number, otherwise return false.\r\n */\r\n P.isFinite = function () {\r\n return !!this.c;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isGreaterThan = P.gt = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) > 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is greater than or equal to the value of\r\n * BigNumber(y, b), otherwise return false.\r\n */\r\n P.isGreaterThanOrEqualTo = P.gte = function (y, b) {\r\n return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0;\r\n\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is an integer, otherwise return false.\r\n */\r\n P.isInteger = function () {\r\n return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isLessThan = P.lt = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) < 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is less than or equal to the value of\r\n * BigNumber(y, b), otherwise return false.\r\n */\r\n P.isLessThanOrEqualTo = P.lte = function (y, b) {\r\n return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is NaN, otherwise return false.\r\n */\r\n P.isNaN = function () {\r\n return !this.s;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is negative, otherwise return false.\r\n */\r\n P.isNegative = function () {\r\n return this.s < 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is positive, otherwise return false.\r\n */\r\n P.isPositive = function () {\r\n return this.s > 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is 0 or -0, otherwise return false.\r\n */\r\n P.isZero = function () {\r\n return !!this.c && this.c[0] == 0;\r\n };\r\n\r\n\r\n /*\r\n * n - 0 = n\r\n * n - N = N\r\n * n - I = -I\r\n * 0 - n = -n\r\n * 0 - 0 = 0\r\n * 0 - N = N\r\n * 0 - I = -I\r\n * N - n = N\r\n * N - 0 = N\r\n * N - N = N\r\n * N - I = N\r\n * I - n = I\r\n * I - 0 = I\r\n * I - N = N\r\n * I - I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber minus the value of\r\n * BigNumber(y, b).\r\n */\r\n P.minus = function (y, b) {\r\n var i, j, t, xLTy,\r\n x = this,\r\n a = x.s;\r\n\r\n y = new BigNumber(y, b);\r\n b = y.s;\r\n\r\n // Either NaN?\r\n if (!a || !b) return new BigNumber(NaN);\r\n\r\n // Signs differ?\r\n if (a != b) {\r\n y.s = -b;\r\n return x.plus(y);\r\n }\r\n\r\n var xe = x.e / LOG_BASE,\r\n ye = y.e / LOG_BASE,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n if (!xe || !ye) {\r\n\r\n // Either Infinity?\r\n if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN);\r\n\r\n // Either zero?\r\n if (!xc[0] || !yc[0]) {\r\n\r\n // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.\r\n return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x :\r\n\r\n // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity\r\n ROUNDING_MODE == 3 ? -0 : 0);\r\n }\r\n }\r\n\r\n xe = bitFloor(xe);\r\n ye = bitFloor(ye);\r\n xc = xc.slice();\r\n\r\n // Determine which is the bigger number.\r\n if (a = xe - ye) {\r\n\r\n if (xLTy = a < 0) {\r\n a = -a;\r\n t = xc;\r\n } else {\r\n ye = xe;\r\n t = yc;\r\n }\r\n\r\n t.reverse();\r\n\r\n // Prepend zeros to equalise exponents.\r\n for (b = a; b--; t.push(0));\r\n t.reverse();\r\n } else {\r\n\r\n // Exponents equal. Check digit by digit.\r\n j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b;\r\n\r\n for (a = b = 0; b < j; b++) {\r\n\r\n if (xc[b] != yc[b]) {\r\n xLTy = xc[b] < yc[b];\r\n break;\r\n }\r\n }\r\n }\r\n\r\n // x < y? Point xc to the array of the bigger number.\r\n if (xLTy) {\r\n t = xc;\r\n xc = yc;\r\n yc = t;\r\n y.s = -y.s;\r\n }\r\n\r\n b = (j = yc.length) - (i = xc.length);\r\n\r\n // Append zeros to xc if shorter.\r\n // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.\r\n if (b > 0) for (; b--; xc[i++] = 0);\r\n b = BASE - 1;\r\n\r\n // Subtract yc from xc.\r\n for (; j > a;) {\r\n\r\n if (xc[--j] < yc[j]) {\r\n for (i = j; i && !xc[--i]; xc[i] = b);\r\n --xc[i];\r\n xc[j] += BASE;\r\n }\r\n\r\n xc[j] -= yc[j];\r\n }\r\n\r\n // Remove leading zeros and adjust exponent accordingly.\r\n for (; xc[0] == 0; xc.splice(0, 1), --ye);\r\n\r\n // Zero?\r\n if (!xc[0]) {\r\n\r\n // Following IEEE 754 (2008) 6.3,\r\n // n - n = +0 but n - n = -0 when rounding towards -Infinity.\r\n y.s = ROUNDING_MODE == 3 ? -1 : 1;\r\n y.c = [y.e = 0];\r\n return y;\r\n }\r\n\r\n // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity\r\n // for finite x and y.\r\n return normalise(y, xc, ye);\r\n };\r\n\r\n\r\n /*\r\n * n % 0 = N\r\n * n % N = N\r\n * n % I = n\r\n * 0 % n = 0\r\n * -0 % n = -0\r\n * 0 % 0 = N\r\n * 0 % N = N\r\n * 0 % I = 0\r\n * N % n = N\r\n * N % 0 = N\r\n * N % N = N\r\n * N % I = N\r\n * I % n = N\r\n * I % 0 = N\r\n * I % N = N\r\n * I % I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber modulo the value of\r\n * BigNumber(y, b). The result depends on the value of MODULO_MODE.\r\n */\r\n P.modulo = P.mod = function (y, b) {\r\n var q, s,\r\n x = this;\r\n\r\n y = new BigNumber(y, b);\r\n\r\n // Return NaN if x is Infinity or NaN, or y is NaN or zero.\r\n if (!x.c || !y.s || y.c && !y.c[0]) {\r\n return new BigNumber(NaN);\r\n\r\n // Return x if y is Infinity or x is zero.\r\n } else if (!y.c || x.c && !x.c[0]) {\r\n return new BigNumber(x);\r\n }\r\n\r\n if (MODULO_MODE == 9) {\r\n\r\n // Euclidian division: q = sign(y) * floor(x / abs(y))\r\n // r = x - qy where 0 <= r < abs(y)\r\n s = y.s;\r\n y.s = 1;\r\n q = div(x, y, 0, 3);\r\n y.s = s;\r\n q.s *= s;\r\n } else {\r\n q = div(x, y, 0, MODULO_MODE);\r\n }\r\n\r\n y = x.minus(q.times(y));\r\n\r\n // To match JavaScript %, ensure sign of zero is sign of dividend.\r\n if (!y.c[0] && MODULO_MODE == 1) y.s = x.s;\r\n\r\n return y;\r\n };\r\n\r\n\r\n /*\r\n * n * 0 = 0\r\n * n * N = N\r\n * n * I = I\r\n * 0 * n = 0\r\n * 0 * 0 = 0\r\n * 0 * N = N\r\n * 0 * I = N\r\n * N * n = N\r\n * N * 0 = N\r\n * N * N = N\r\n * N * I = N\r\n * I * n = I\r\n * I * 0 = N\r\n * I * N = N\r\n * I * I = I\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value\r\n * of BigNumber(y, b).\r\n */\r\n P.multipliedBy = P.times = function (y, b) {\r\n var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,\r\n base, sqrtBase,\r\n x = this,\r\n xc = x.c,\r\n yc = (y = new BigNumber(y, b)).c;\r\n\r\n // Either NaN, ±Infinity or ±0?\r\n if (!xc || !yc || !xc[0] || !yc[0]) {\r\n\r\n // Return NaN if either is NaN, or one is 0 and the other is Infinity.\r\n if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) {\r\n y.c = y.e = y.s = null;\r\n } else {\r\n y.s *= x.s;\r\n\r\n // Return ±Infinity if either is ±Infinity.\r\n if (!xc || !yc) {\r\n y.c = y.e = null;\r\n\r\n // Return ±0 if either is ±0.\r\n } else {\r\n y.c = [0];\r\n y.e = 0;\r\n }\r\n }\r\n\r\n return y;\r\n }\r\n\r\n e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE);\r\n y.s *= x.s;\r\n xcL = xc.length;\r\n ycL = yc.length;\r\n\r\n // Ensure xc points to longer array and xcL to its length.\r\n if (xcL < ycL) {\r\n zc = xc;\r\n xc = yc;\r\n yc = zc;\r\n i = xcL;\r\n xcL = ycL;\r\n ycL = i;\r\n }\r\n\r\n // Initialise the result array with zeros.\r\n for (i = xcL + ycL, zc = []; i--; zc.push(0));\r\n\r\n base = BASE;\r\n sqrtBase = SQRT_BASE;\r\n\r\n for (i = ycL; --i >= 0;) {\r\n c = 0;\r\n ylo = yc[i] % sqrtBase;\r\n yhi = yc[i] / sqrtBase | 0;\r\n\r\n for (k = xcL, j = i + k; j > i;) {\r\n xlo = xc[--k] % sqrtBase;\r\n xhi = xc[k] / sqrtBase | 0;\r\n m = yhi * xlo + xhi * ylo;\r\n xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c;\r\n c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi;\r\n zc[j--] = xlo % base;\r\n }\r\n\r\n zc[j] = c;\r\n }\r\n\r\n if (c) {\r\n ++e;\r\n } else {\r\n zc.splice(0, 1);\r\n }\r\n\r\n return normalise(y, zc, e);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber negated,\r\n * i.e. multiplied by -1.\r\n */\r\n P.negated = function () {\r\n var x = new BigNumber(this);\r\n x.s = -x.s || null;\r\n return x;\r\n };\r\n\r\n\r\n /*\r\n * n + 0 = n\r\n * n + N = N\r\n * n + I = I\r\n * 0 + n = n\r\n * 0 + 0 = 0\r\n * 0 + N = N\r\n * 0 + I = I\r\n * N + n = N\r\n * N + 0 = N\r\n * N + N = N\r\n * N + I = N\r\n * I + n = I\r\n * I + 0 = I\r\n * I + N = N\r\n * I + I = I\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber plus the value of\r\n * BigNumber(y, b).\r\n */\r\n P.plus = function (y, b) {\r\n var t,\r\n x = this,\r\n a = x.s;\r\n\r\n y = new BigNumber(y, b);\r\n b = y.s;\r\n\r\n // Either NaN?\r\n if (!a || !b) return new BigNumber(NaN);\r\n\r\n // Signs differ?\r\n if (a != b) {\r\n y.s = -b;\r\n return x.minus(y);\r\n }\r\n\r\n var xe = x.e / LOG_BASE,\r\n ye = y.e / LOG_BASE,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n if (!xe || !ye) {\r\n\r\n // Return ±Infinity if either ±Infinity.\r\n if (!xc || !yc) return new BigNumber(a / 0);\r\n\r\n // Either zero?\r\n // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.\r\n if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0);\r\n }\r\n\r\n xe = bitFloor(xe);\r\n ye = bitFloor(ye);\r\n xc = xc.slice();\r\n\r\n // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.\r\n if (a = xe - ye) {\r\n if (a > 0) {\r\n ye = xe;\r\n t = yc;\r\n } else {\r\n a = -a;\r\n t = xc;\r\n }\r\n\r\n t.reverse();\r\n for (; a--; t.push(0));\r\n t.reverse();\r\n }\r\n\r\n a = xc.length;\r\n b = yc.length;\r\n\r\n // Point xc to the longer array, and b to the shorter length.\r\n if (a - b < 0) {\r\n t = yc;\r\n yc = xc;\r\n xc = t;\r\n b = a;\r\n }\r\n\r\n // Only start adding at yc.length - 1 as the further digits of xc can be ignored.\r\n for (a = 0; b;) {\r\n a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0;\r\n xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;\r\n }\r\n\r\n if (a) {\r\n xc = [a].concat(xc);\r\n ++ye;\r\n }\r\n\r\n // No need to check for zero, as +x + +y != 0 && -x + -y != 0\r\n // ye = MAX_EXP + 1 possible\r\n return normalise(y, xc, ye);\r\n };\r\n\r\n\r\n /*\r\n * If sd is undefined or null or true or false, return the number of significant digits of\r\n * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN.\r\n * If sd is true include integer-part trailing zeros in the count.\r\n *\r\n * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this\r\n * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or\r\n * ROUNDING_MODE if rm is omitted.\r\n *\r\n * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive.\r\n * boolean: whether to count integer-part trailing zeros: true or false.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'\r\n */\r\n P.precision = P.sd = function (sd, rm) {\r\n var c, n, v,\r\n x = this;\r\n\r\n if (sd != null && sd !== !!sd) {\r\n intCheck(sd, 1, MAX);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n return round(new BigNumber(x), sd, rm);\r\n }\r\n\r\n if (!(c = x.c)) return null;\r\n v = c.length - 1;\r\n n = v * LOG_BASE + 1;\r\n\r\n if (v = c[v]) {\r\n\r\n // Subtract the number of trailing zeros of the last element.\r\n for (; v % 10 == 0; v /= 10, n--);\r\n\r\n // Add the number of digits of the first element.\r\n for (v = c[0]; v >= 10; v /= 10, n++);\r\n }\r\n\r\n if (sd && x.e + 1 > n) n = x.e + 1;\r\n\r\n return n;\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber shifted by k places\r\n * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.\r\n *\r\n * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}'\r\n */\r\n P.shiftedBy = function (k) {\r\n intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);\r\n return this.times('1e' + k);\r\n };\r\n\r\n\r\n /*\r\n * sqrt(-n) = N\r\n * sqrt(N) = N\r\n * sqrt(-I) = N\r\n * sqrt(I) = I\r\n * sqrt(0) = 0\r\n * sqrt(-0) = -0\r\n *\r\n * Return a new BigNumber whose value is the square root of the value of this BigNumber,\r\n * rounded according to DECIMAL_PLACES and ROUNDING_MODE.\r\n */\r\n P.squareRoot = P.sqrt = function () {\r\n var m, n, r, rep, t,\r\n x = this,\r\n c = x.c,\r\n s = x.s,\r\n e = x.e,\r\n dp = DECIMAL_PLACES + 4,\r\n half = new BigNumber('0.5');\r\n\r\n // Negative/NaN/Infinity/zero?\r\n if (s !== 1 || !c || !c[0]) {\r\n return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0);\r\n }\r\n\r\n // Initial estimate.\r\n s = Math.sqrt(+valueOf(x));\r\n\r\n // Math.sqrt underflow/overflow?\r\n // Pass x to Math.sqrt as integer, then adjust the exponent of the result.\r\n if (s == 0 || s == 1 / 0) {\r\n n = coeffToString(c);\r\n if ((n.length + e) % 2 == 0) n += '0';\r\n s = Math.sqrt(+n);\r\n e = bitFloor((e + 1) / 2) - (e < 0 || e % 2);\r\n\r\n if (s == 1 / 0) {\r\n n = '5e' + e;\r\n } else {\r\n n = s.toExponential();\r\n n = n.slice(0, n.indexOf('e') + 1) + e;\r\n }\r\n\r\n r = new BigNumber(n);\r\n } else {\r\n r = new BigNumber(s + '');\r\n }\r\n\r\n // Check for zero.\r\n // r could be zero if MIN_EXP is changed after the this value was created.\r\n // This would cause a division by zero (x/t) and hence Infinity below, which would cause\r\n // coeffToString to throw.\r\n if (r.c[0]) {\r\n e = r.e;\r\n s = e + dp;\r\n if (s < 3) s = 0;\r\n\r\n // Newton-Raphson iteration.\r\n for (; ;) {\r\n t = r;\r\n r = half.times(t.plus(div(x, t, dp, 1)));\r\n\r\n if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) {\r\n\r\n // The exponent of r may here be one less than the final result exponent,\r\n // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits\r\n // are indexed correctly.\r\n if (r.e < e) --s;\r\n n = n.slice(s - 3, s + 1);\r\n\r\n // The 4th rounding digit may be in error by -1 so if the 4 rounding digits\r\n // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the\r\n // iteration.\r\n if (n == '9999' || !rep && n == '4999') {\r\n\r\n // On the first iteration only, check to see if rounding up gives the\r\n // exact result as the nines may infinitely repeat.\r\n if (!rep) {\r\n round(t, t.e + DECIMAL_PLACES + 2, 0);\r\n\r\n if (t.times(t).eq(x)) {\r\n r = t;\r\n break;\r\n }\r\n }\r\n\r\n dp += 4;\r\n s += 4;\r\n rep = 1;\r\n } else {\r\n\r\n // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact\r\n // result. If not, then there are further digits and m will be truthy.\r\n if (!+n || !+n.slice(1) && n.charAt(0) == '5') {\r\n\r\n // Truncate to the first rounding digit.\r\n round(r, r.e + DECIMAL_PLACES + 2, 1);\r\n m = !r.times(r).eq(x);\r\n }\r\n\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n\r\n return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in exponential notation and\r\n * rounded using ROUNDING_MODE to dp fixed decimal places.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.toExponential = function (dp, rm) {\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n dp++;\r\n }\r\n return format(this, dp, rm, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in fixed-point notation rounding\r\n * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.\r\n *\r\n * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',\r\n * but e.g. (-0.00001).toFixed(0) is '-0'.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.toFixed = function (dp, rm) {\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n dp = dp + this.e + 1;\r\n }\r\n return format(this, dp, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in fixed-point notation rounded\r\n * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties\r\n * of the format or FORMAT object (see BigNumber.set).\r\n *\r\n * The formatting object may contain some or all of the properties shown below.\r\n *\r\n * FORMAT = {\r\n * prefix: '',\r\n * groupSize: 3,\r\n * secondaryGroupSize: 0,\r\n * groupSeparator: ',',\r\n * decimalSeparator: '.',\r\n * fractionGroupSize: 0,\r\n * fractionGroupSeparator: '\\xA0', // non-breaking space\r\n * suffix: ''\r\n * };\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n * [format] {object} Formatting options. See FORMAT pbject above.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n * '[BigNumber Error] Argument not an object: {format}'\r\n */\r\n P.toFormat = function (dp, rm, format) {\r\n var str,\r\n x = this;\r\n\r\n if (format == null) {\r\n if (dp != null && rm && typeof rm == 'object') {\r\n format = rm;\r\n rm = null;\r\n } else if (dp && typeof dp == 'object') {\r\n format = dp;\r\n dp = rm = null;\r\n } else {\r\n format = FORMAT;\r\n }\r\n } else if (typeof format != 'object') {\r\n throw Error\r\n (bignumberError + 'Argument not an object: ' + format);\r\n }\r\n\r\n str = x.toFixed(dp, rm);\r\n\r\n if (x.c) {\r\n var i,\r\n arr = str.split('.'),\r\n g1 = +format.groupSize,\r\n g2 = +format.secondaryGroupSize,\r\n groupSeparator = format.groupSeparator || '',\r\n intPart = arr[0],\r\n fractionPart = arr[1],\r\n isNeg = x.s < 0,\r\n intDigits = isNeg ? intPart.slice(1) : intPart,\r\n len = intDigits.length;\r\n\r\n if (g2) {\r\n i = g1;\r\n g1 = g2;\r\n g2 = i;\r\n len -= i;\r\n }\r\n\r\n if (g1 > 0 && len > 0) {\r\n i = len % g1 || g1;\r\n intPart = intDigits.substr(0, i);\r\n for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1);\r\n if (g2 > 0) intPart += groupSeparator + intDigits.slice(i);\r\n if (isNeg) intPart = '-' + intPart;\r\n }\r\n\r\n str = fractionPart\r\n ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize)\r\n ? fractionPart.replace(new RegExp('\\\\d{' + g2 + '}\\\\B', 'g'),\r\n '$&' + (format.fractionGroupSeparator || ''))\r\n : fractionPart)\r\n : intPart;\r\n }\r\n\r\n return (format.prefix || '') + str + (format.suffix || '');\r\n };\r\n\r\n\r\n /*\r\n * Return an array of two BigNumbers representing the value of this BigNumber as a simple\r\n * fraction with an integer numerator and an integer denominator.\r\n * The denominator will be a positive non-zero value less than or equal to the specified\r\n * maximum denominator. If a maximum denominator is not specified, the denominator will be\r\n * the lowest value necessary to represent the number exactly.\r\n *\r\n * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator.\r\n *\r\n * '[BigNumber Error] Argument {not an integer|out of range} : {md}'\r\n */\r\n P.toFraction = function (md) {\r\n var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s,\r\n x = this,\r\n xc = x.c;\r\n\r\n if (md != null) {\r\n n = new BigNumber(md);\r\n\r\n // Throw if md is less than one or is not an integer, unless it is Infinity.\r\n if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) {\r\n throw Error\r\n (bignumberError + 'Argument ' +\r\n (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n));\r\n }\r\n }\r\n\r\n if (!xc) return new BigNumber(x);\r\n\r\n d = new BigNumber(ONE);\r\n n1 = d0 = new BigNumber(ONE);\r\n d1 = n0 = new BigNumber(ONE);\r\n s = coeffToString(xc);\r\n\r\n // Determine initial denominator.\r\n // d is a power of 10 and the minimum max denominator that specifies the value exactly.\r\n e = d.e = s.length - x.e - 1;\r\n d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp];\r\n md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n;\r\n\r\n exp = MAX_EXP;\r\n MAX_EXP = 1 / 0;\r\n n = new BigNumber(s);\r\n\r\n // n0 = d1 = 0\r\n n0.c[0] = 0;\r\n\r\n for (; ;) {\r\n q = div(n, d, 0, 1);\r\n d2 = d0.plus(q.times(d1));\r\n if (d2.comparedTo(md) == 1) break;\r\n d0 = d1;\r\n d1 = d2;\r\n n1 = n0.plus(q.times(d2 = n1));\r\n n0 = d2;\r\n d = n.minus(q.times(d2 = d));\r\n n = d2;\r\n }\r\n\r\n d2 = div(md.minus(d0), d1, 0, 1);\r\n n0 = n0.plus(d2.times(n1));\r\n d0 = d0.plus(d2.times(d1));\r\n n0.s = n1.s = x.s;\r\n e = e * 2;\r\n\r\n // Determine which fraction is closer to x, n0/d0 or n1/d1\r\n r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo(\r\n div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0];\r\n\r\n MAX_EXP = exp;\r\n\r\n return r;\r\n };\r\n\r\n\r\n /*\r\n * Return the value of this BigNumber converted to a number primitive.\r\n */\r\n P.toNumber = function () {\r\n return +valueOf(this);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber rounded to sd significant digits\r\n * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits\r\n * necessary to represent the integer part of the value in fixed-point notation, then use\r\n * exponential notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'\r\n */\r\n P.toPrecision = function (sd, rm) {\r\n if (sd != null) intCheck(sd, 1, MAX);\r\n return format(this, sd, rm, 2);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in base b, or base 10 if b is\r\n * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and\r\n * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent\r\n * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than\r\n * TO_EXP_NEG, return exponential notation.\r\n *\r\n * [b] {number} Integer, 2 to ALPHABET.length inclusive.\r\n *\r\n * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'\r\n */\r\n P.toString = function (b) {\r\n var str,\r\n n = this,\r\n s = n.s,\r\n e = n.e;\r\n\r\n // Infinity or NaN?\r\n if (e === null) {\r\n if (s) {\r\n str = 'Infinity';\r\n if (s < 0) str = '-' + str;\r\n } else {\r\n str = 'NaN';\r\n }\r\n } else {\r\n if (b == null) {\r\n str = e <= TO_EXP_NEG || e >= TO_EXP_POS\r\n ? toExponential(coeffToString(n.c), e)\r\n : toFixedPoint(coeffToString(n.c), e, '0');\r\n } else if (b === 10 && alphabetHasNormalDecimalDigits) {\r\n n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE);\r\n str = toFixedPoint(coeffToString(n.c), n.e, '0');\r\n } else {\r\n intCheck(b, 2, ALPHABET.length, 'Base');\r\n str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true);\r\n }\r\n\r\n if (s < 0 && n.c[0]) str = '-' + str;\r\n }\r\n\r\n return str;\r\n };\r\n\r\n\r\n /*\r\n * Return as toString, but do not accept a base argument, and include the minus sign for\r\n * negative zero.\r\n */\r\n P.valueOf = P.toJSON = function () {\r\n return valueOf(this);\r\n };\r\n\r\n\r\n P._isBigNumber = true;\r\n\r\n if (configObject != null) BigNumber.set(configObject);\r\n\r\n return BigNumber;\r\n }\r\n\r\n\r\n // PRIVATE HELPER FUNCTIONS\r\n\r\n // These functions don't need access to variables,\r\n // e.g. DECIMAL_PLACES, in the scope of the `clone` function above.\r\n\r\n\r\n function bitFloor(n) {\r\n var i = n | 0;\r\n return n > 0 || n === i ? i : i - 1;\r\n }\r\n\r\n\r\n // Return a coefficient array as a string of base 10 digits.\r\n function coeffToString(a) {\r\n var s, z,\r\n i = 1,\r\n j = a.length,\r\n r = a[0] + '';\r\n\r\n for (; i < j;) {\r\n s = a[i++] + '';\r\n z = LOG_BASE - s.length;\r\n for (; z--; s = '0' + s);\r\n r += s;\r\n }\r\n\r\n // Determine trailing zeros.\r\n for (j = r.length; r.charCodeAt(--j) === 48;);\r\n\r\n return r.slice(0, j + 1 || 1);\r\n }\r\n\r\n\r\n // Compare the value of BigNumbers x and y.\r\n function compare(x, y) {\r\n var a, b,\r\n xc = x.c,\r\n yc = y.c,\r\n i = x.s,\r\n j = y.s,\r\n k = x.e,\r\n l = y.e;\r\n\r\n // Either NaN?\r\n if (!i || !j) return null;\r\n\r\n a = xc && !xc[0];\r\n b = yc && !yc[0];\r\n\r\n // Either zero?\r\n if (a || b) return a ? b ? 0 : -j : i;\r\n\r\n // Signs differ?\r\n if (i != j) return i;\r\n\r\n a = i < 0;\r\n b = k == l;\r\n\r\n // Either Infinity?\r\n if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1;\r\n\r\n // Compare exponents.\r\n if (!b) return k > l ^ a ? 1 : -1;\r\n\r\n j = (k = xc.length) < (l = yc.length) ? k : l;\r\n\r\n // Compare digit by digit.\r\n for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1;\r\n\r\n // Compare lengths.\r\n return k == l ? 0 : k > l ^ a ? 1 : -1;\r\n }\r\n\r\n\r\n /*\r\n * Check that n is a primitive number, an integer, and in range, otherwise throw.\r\n */\r\n function intCheck(n, min, max, name) {\r\n if (n < min || n > max || n !== mathfloor(n)) {\r\n throw Error\r\n (bignumberError + (name || 'Argument') + (typeof n == 'number'\r\n ? n < min || n > max ? ' out of range: ' : ' not an integer: '\r\n : ' not a primitive number: ') + String(n));\r\n }\r\n }\r\n\r\n\r\n // Assumes finite n.\r\n function isOdd(n) {\r\n var k = n.c.length - 1;\r\n return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0;\r\n }\r\n\r\n\r\n function toExponential(str, e) {\r\n return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) +\r\n (e < 0 ? 'e' : 'e+') + e;\r\n }\r\n\r\n\r\n function toFixedPoint(str, e, z) {\r\n var len, zs;\r\n\r\n // Negative exponent?\r\n if (e < 0) {\r\n\r\n // Prepend zeros.\r\n for (zs = z + '.'; ++e; zs += z);\r\n str = zs + str;\r\n\r\n // Positive exponent\r\n } else {\r\n len = str.length;\r\n\r\n // Append zeros.\r\n if (++e > len) {\r\n for (zs = z, e -= len; --e; zs += z);\r\n str += zs;\r\n } else if (e < len) {\r\n str = str.slice(0, e) + '.' + str.slice(e);\r\n }\r\n }\r\n\r\n return str;\r\n }\r\n\r\n\r\n // EXPORT\r\n\r\n\r\n BigNumber = clone();\r\n BigNumber['default'] = BigNumber.BigNumber = BigNumber;\r\n\r\n // AMD.\r\n if (typeof define == 'function' && define.amd) {\r\n define(function () { return BigNumber; });\r\n\r\n // Node.js and other environments that support module.exports.\r\n } else if (typeof module != 'undefined' && module.exports) {\r\n module.exports = BigNumber;\r\n\r\n // Browser.\r\n } else {\r\n if (!globalObject) {\r\n globalObject = typeof self != 'undefined' && self ? self : window;\r\n }\r\n\r\n globalObject.BigNumber = BigNumber;\r\n }\r\n})(this);\r\n","/* eslint-disable */\n\nmodule.exports = function decodeAsm (stdlib, foreign, buffer) {\n 'use asm'\n\n // -- Imports\n\n var heap = new stdlib.Uint8Array(buffer)\n // var log = foreign.log\n var pushInt = foreign.pushInt\n var pushInt32 = foreign.pushInt32\n var pushInt32Neg = foreign.pushInt32Neg\n var pushInt64 = foreign.pushInt64\n var pushInt64Neg = foreign.pushInt64Neg\n var pushFloat = foreign.pushFloat\n var pushFloatSingle = foreign.pushFloatSingle\n var pushFloatDouble = foreign.pushFloatDouble\n var pushTrue = foreign.pushTrue\n var pushFalse = foreign.pushFalse\n var pushUndefined = foreign.pushUndefined\n var pushNull = foreign.pushNull\n var pushInfinity = foreign.pushInfinity\n var pushInfinityNeg = foreign.pushInfinityNeg\n var pushNaN = foreign.pushNaN\n var pushNaNNeg = foreign.pushNaNNeg\n\n var pushArrayStart = foreign.pushArrayStart\n var pushArrayStartFixed = foreign.pushArrayStartFixed\n var pushArrayStartFixed32 = foreign.pushArrayStartFixed32\n var pushArrayStartFixed64 = foreign.pushArrayStartFixed64\n var pushObjectStart = foreign.pushObjectStart\n var pushObjectStartFixed = foreign.pushObjectStartFixed\n var pushObjectStartFixed32 = foreign.pushObjectStartFixed32\n var pushObjectStartFixed64 = foreign.pushObjectStartFixed64\n\n var pushByteString = foreign.pushByteString\n var pushByteStringStart = foreign.pushByteStringStart\n var pushUtf8String = foreign.pushUtf8String\n var pushUtf8StringStart = foreign.pushUtf8StringStart\n\n var pushSimpleUnassigned = foreign.pushSimpleUnassigned\n\n var pushTagStart = foreign.pushTagStart\n var pushTagStart4 = foreign.pushTagStart4\n var pushTagStart8 = foreign.pushTagStart8\n var pushTagUnassigned = foreign.pushTagUnassigned\n\n var pushBreak = foreign.pushBreak\n\n var pow = stdlib.Math.pow\n\n // -- Constants\n\n\n // -- Mutable Variables\n\n var offset = 0\n var inputLength = 0\n var code = 0\n\n // Decode a cbor string represented as Uint8Array\n // which is allocated on the heap from 0 to inputLength\n //\n // input - Int\n //\n // Returns Code - Int,\n // Success = 0\n // Error > 0\n function parse (input) {\n input = input | 0\n\n offset = 0\n inputLength = input\n\n while ((offset | 0) < (inputLength | 0)) {\n code = jumpTable[heap[offset] & 255](heap[offset] | 0) | 0\n\n if ((code | 0) > 0) {\n break\n }\n }\n\n return code | 0\n }\n\n // -- Helper Function\n\n function checkOffset (n) {\n n = n | 0\n\n if ((((offset | 0) + (n | 0)) | 0) < (inputLength | 0)) {\n return 0\n }\n\n return 1\n }\n\n function readUInt16 (n) {\n n = n | 0\n\n return (\n (heap[n | 0] << 8) | heap[(n + 1) | 0]\n ) | 0\n }\n\n function readUInt32 (n) {\n n = n | 0\n\n return (\n (heap[n | 0] << 24) | (heap[(n + 1) | 0] << 16) | (heap[(n + 2) | 0] << 8) | heap[(n + 3) | 0]\n ) | 0\n }\n\n // -- Initial Byte Handlers\n\n function INT_P (octet) {\n octet = octet | 0\n\n pushInt(octet | 0)\n\n offset = (offset + 1) | 0\n\n return 0\n }\n\n function UINT_P_8 (octet) {\n octet = octet | 0\n\n if (checkOffset(1) | 0) {\n return 1\n }\n\n pushInt(heap[(offset + 1) | 0] | 0)\n\n offset = (offset + 2) | 0\n\n return 0\n }\n\n function UINT_P_16 (octet) {\n octet = octet | 0\n\n if (checkOffset(2) | 0) {\n return 1\n }\n\n pushInt(\n readUInt16((offset + 1) | 0) | 0\n )\n\n offset = (offset + 3) | 0\n\n return 0\n }\n\n function UINT_P_32 (octet) {\n octet = octet | 0\n\n if (checkOffset(4) | 0) {\n return 1\n }\n\n pushInt32(\n readUInt16((offset + 1) | 0) | 0,\n readUInt16((offset + 3) | 0) | 0\n )\n\n offset = (offset + 5) | 0\n\n return 0\n }\n\n function UINT_P_64 (octet) {\n octet = octet | 0\n\n if (checkOffset(8) | 0) {\n return 1\n }\n\n pushInt64(\n readUInt16((offset + 1) | 0) | 0,\n readUInt16((offset + 3) | 0) | 0,\n readUInt16((offset + 5) | 0) | 0,\n readUInt16((offset + 7) | 0) | 0\n )\n\n offset = (offset + 9) | 0\n\n return 0\n }\n\n function INT_N (octet) {\n octet = octet | 0\n\n pushInt((-1 - ((octet - 32) | 0)) | 0)\n\n offset = (offset + 1) | 0\n\n return 0\n }\n\n function UINT_N_8 (octet) {\n octet = octet | 0\n\n if (checkOffset(1) | 0) {\n return 1\n }\n\n pushInt(\n (-1 - (heap[(offset + 1) | 0] | 0)) | 0\n )\n\n offset = (offset + 2) | 0\n\n return 0\n }\n\n function UINT_N_16 (octet) {\n octet = octet | 0\n\n var val = 0\n\n if (checkOffset(2) | 0) {\n return 1\n }\n\n val = readUInt16((offset + 1) | 0) | 0\n pushInt((-1 - (val | 0)) | 0)\n\n offset = (offset + 3) | 0\n\n return 0\n }\n\n function UINT_N_32 (octet) {\n octet = octet | 0\n\n if (checkOffset(4) | 0) {\n return 1\n }\n\n pushInt32Neg(\n readUInt16((offset + 1) | 0) | 0,\n readUInt16((offset + 3) | 0) | 0\n )\n\n offset = (offset + 5) | 0\n\n return 0\n }\n\n function UINT_N_64 (octet) {\n octet = octet | 0\n\n if (checkOffset(8) | 0) {\n return 1\n }\n\n pushInt64Neg(\n readUInt16((offset + 1) | 0) | 0,\n readUInt16((offset + 3) | 0) | 0,\n readUInt16((offset + 5) | 0) | 0,\n readUInt16((offset + 7) | 0) | 0\n )\n\n offset = (offset + 9) | 0\n\n return 0\n }\n\n function BYTE_STRING (octet) {\n octet = octet | 0\n\n var start = 0\n var end = 0\n var step = 0\n\n step = (octet - 64) | 0\n if (checkOffset(step | 0) | 0) {\n return 1\n }\n\n start = (offset + 1) | 0\n end = (((offset + 1) | 0) + (step | 0)) | 0\n\n pushByteString(start | 0, end | 0)\n\n offset = end | 0\n\n return 0\n }\n\n function BYTE_STRING_8 (octet) {\n octet = octet | 0\n\n var start = 0\n var end = 0\n var length = 0\n\n if (checkOffset(1) | 0) {\n return 1\n }\n\n length = heap[(offset + 1) | 0] | 0\n start = (offset + 2) | 0\n end = (((offset + 2) | 0) + (length | 0)) | 0\n\n if (checkOffset((length + 1) | 0) | 0) {\n return 1\n }\n\n pushByteString(start | 0, end | 0)\n\n offset = end | 0\n\n return 0\n }\n\n function BYTE_STRING_16 (octet) {\n octet = octet | 0\n\n var start = 0\n var end = 0\n var length = 0\n\n if (checkOffset(2) | 0) {\n return 1\n }\n\n length = readUInt16((offset + 1) | 0) | 0\n start = (offset + 3) | 0\n end = (((offset + 3) | 0) + (length | 0)) | 0\n\n\n if (checkOffset((length + 2) | 0) | 0) {\n return 1\n }\n\n pushByteString(start | 0, end | 0)\n\n offset = end | 0\n\n return 0\n }\n\n function BYTE_STRING_32 (octet) {\n octet = octet | 0\n\n var start = 0\n var end = 0\n var length = 0\n\n if (checkOffset(4) | 0) {\n return 1\n }\n\n length = readUInt32((offset + 1) | 0) | 0\n start = (offset + 5) | 0\n end = (((offset + 5) | 0) + (length | 0)) | 0\n\n\n if (checkOffset((length + 4) | 0) | 0) {\n return 1\n }\n\n pushByteString(start | 0, end | 0)\n\n offset = end | 0\n\n return 0\n }\n\n function BYTE_STRING_64 (octet) {\n // NOT IMPLEMENTED\n octet = octet | 0\n\n return 1\n }\n\n function BYTE_STRING_BREAK (octet) {\n octet = octet | 0\n\n pushByteStringStart()\n\n offset = (offset + 1) | 0\n\n return 0\n }\n\n function UTF8_STRING (octet) {\n octet = octet | 0\n\n var start = 0\n var end = 0\n var step = 0\n\n step = (octet - 96) | 0\n\n if (checkOffset(step | 0) | 0) {\n return 1\n }\n\n start = (offset + 1) | 0\n end = (((offset + 1) | 0) + (step | 0)) | 0\n\n pushUtf8String(start | 0, end | 0)\n\n offset = end | 0\n\n return 0\n }\n\n function UTF8_STRING_8 (octet) {\n octet = octet | 0\n\n var start = 0\n var end = 0\n var length = 0\n\n if (checkOffset(1) | 0) {\n return 1\n }\n\n length = heap[(offset + 1) | 0] | 0\n start = (offset + 2) | 0\n end = (((offset + 2) | 0) + (length | 0)) | 0\n\n if (checkOffset((length + 1) | 0) | 0) {\n return 1\n }\n\n pushUtf8String(start | 0, end | 0)\n\n offset = end | 0\n\n return 0\n }\n\n function UTF8_STRING_16 (octet) {\n octet = octet | 0\n\n var start = 0\n var end = 0\n var length = 0\n\n if (checkOffset(2) | 0) {\n return 1\n }\n\n length = readUInt16((offset + 1) | 0) | 0\n start = (offset + 3) | 0\n end = (((offset + 3) | 0) + (length | 0)) | 0\n\n if (checkOffset((length + 2) | 0) | 0) {\n return 1\n }\n\n pushUtf8String(start | 0, end | 0)\n\n offset = end | 0\n\n return 0\n }\n\n function UTF8_STRING_32 (octet) {\n octet = octet | 0\n\n var start = 0\n var end = 0\n var length = 0\n\n if (checkOffset(4) | 0) {\n return 1\n }\n\n length = readUInt32((offset + 1) | 0) | 0\n start = (offset + 5) | 0\n end = (((offset + 5) | 0) + (length | 0)) | 0\n\n if (checkOffset((length + 4) | 0) | 0) {\n return 1\n }\n\n pushUtf8String(start | 0, end | 0)\n\n offset = end | 0\n\n return 0\n }\n\n function UTF8_STRING_64 (octet) {\n // NOT IMPLEMENTED\n octet = octet | 0\n\n return 1\n }\n\n function UTF8_STRING_BREAK (octet) {\n octet = octet | 0\n\n pushUtf8StringStart()\n\n offset = (offset + 1) | 0\n\n return 0\n }\n\n function ARRAY (octet) {\n octet = octet | 0\n\n pushArrayStartFixed((octet - 128) | 0)\n\n offset = (offset + 1) | 0\n\n return 0\n }\n\n function ARRAY_8 (octet) {\n octet = octet | 0\n\n if (checkOffset(1) | 0) {\n return 1\n }\n\n pushArrayStartFixed(heap[(offset + 1) | 0] | 0)\n\n offset = (offset + 2) | 0\n\n return 0\n }\n\n function ARRAY_16 (octet) {\n octet = octet | 0\n\n if (checkOffset(2) | 0) {\n return 1\n }\n\n pushArrayStartFixed(\n readUInt16((offset + 1) | 0) | 0\n )\n\n offset = (offset + 3) | 0\n\n return 0\n }\n\n function ARRAY_32 (octet) {\n octet = octet | 0\n\n if (checkOffset(4) | 0) {\n return 1\n }\n\n pushArrayStartFixed32(\n readUInt16((offset + 1) | 0) | 0,\n readUInt16((offset + 3) | 0) | 0\n )\n\n offset = (offset + 5) | 0\n\n return 0\n }\n\n function ARRAY_64 (octet) {\n octet = octet | 0\n\n if (checkOffset(8) | 0) {\n return 1\n }\n\n pushArrayStartFixed64(\n readUInt16((offset + 1) | 0) | 0,\n readUInt16((offset + 3) | 0) | 0,\n readUInt16((offset + 5) | 0) | 0,\n readUInt16((offset + 7) | 0) | 0\n )\n\n offset = (offset + 9) | 0\n\n return 0\n }\n\n function ARRAY_BREAK (octet) {\n octet = octet | 0\n\n pushArrayStart()\n\n offset = (offset + 1) | 0\n\n return 0\n }\n\n function MAP (octet) {\n octet = octet | 0\n\n var step = 0\n\n step = (octet - 160) | 0\n\n if (checkOffset(step | 0) | 0) {\n return 1\n }\n\n pushObjectStartFixed(step | 0)\n\n offset = (offset + 1) | 0\n\n return 0\n }\n\n function MAP_8 (octet) {\n octet = octet | 0\n\n if (checkOffset(1) | 0) {\n return 1\n }\n\n pushObjectStartFixed(heap[(offset + 1) | 0] | 0)\n\n offset = (offset + 2) | 0\n\n return 0\n }\n\n function MAP_16 (octet) {\n octet = octet | 0\n\n if (checkOffset(2) | 0) {\n return 1\n }\n\n pushObjectStartFixed(\n readUInt16((offset + 1) | 0) | 0\n )\n\n offset = (offset + 3) | 0\n\n return 0\n }\n\n function MAP_32 (octet) {\n octet = octet | 0\n\n if (checkOffset(4) | 0) {\n return 1\n }\n\n pushObjectStartFixed32(\n readUInt16((offset + 1) | 0) | 0,\n readUInt16((offset + 3) | 0) | 0\n )\n\n offset = (offset + 5) | 0\n\n return 0\n }\n\n function MAP_64 (octet) {\n octet = octet | 0\n\n if (checkOffset(8) | 0) {\n return 1\n }\n\n pushObjectStartFixed64(\n readUInt16((offset + 1) | 0) | 0,\n readUInt16((offset + 3) | 0) | 0,\n readUInt16((offset + 5) | 0) | 0,\n readUInt16((offset + 7) | 0) | 0\n )\n\n offset = (offset + 9) | 0\n\n return 0\n }\n\n function MAP_BREAK (octet) {\n octet = octet | 0\n\n pushObjectStart()\n\n offset = (offset + 1) | 0\n\n return 0\n }\n\n function TAG_KNOWN (octet) {\n octet = octet | 0\n\n pushTagStart((octet - 192| 0) | 0)\n\n offset = (offset + 1 | 0)\n\n return 0\n }\n\n function TAG_BIGNUM_POS (octet) {\n octet = octet | 0\n\n pushTagStart(octet | 0)\n\n offset = (offset + 1 | 0)\n\n return 0\n }\n\n function TAG_BIGNUM_NEG (octet) {\n octet = octet | 0\n\n pushTagStart(octet | 0)\n\n offset = (offset + 1 | 0)\n\n return 0\n }\n\n function TAG_FRAC (octet) {\n octet = octet | 0\n\n pushTagStart(octet | 0)\n\n offset = (offset + 1 | 0)\n\n return 0\n }\n\n function TAG_BIGNUM_FLOAT (octet) {\n octet = octet | 0\n\n pushTagStart(octet | 0)\n\n offset = (offset + 1 | 0)\n\n return 0\n }\n\n function TAG_UNASSIGNED (octet) {\n octet = octet | 0\n\n pushTagStart((octet - 192| 0) | 0)\n\n offset = (offset + 1 | 0)\n\n return 0\n }\n\n function TAG_BASE64_URL (octet) {\n octet = octet | 0\n\n pushTagStart(octet | 0)\n\n offset = (offset + 1 | 0)\n\n return 0\n }\n\n function TAG_BASE64 (octet) {\n octet = octet | 0\n\n pushTagStart(octet | 0)\n\n offset = (offset + 1 | 0)\n\n return 0\n }\n\n function TAG_BASE16 (octet) {\n octet = octet | 0\n\n pushTagStart(octet | 0)\n\n offset = (offset + 1 | 0)\n\n return 0\n }\n\n function TAG_MORE_1 (octet) {\n octet = octet | 0\n\n if (checkOffset(1) | 0) {\n return 1\n }\n\n pushTagStart(heap[(offset + 1) | 0] | 0)\n\n offset = (offset + 2 | 0)\n\n return 0\n }\n\n function TAG_MORE_2 (octet) {\n octet = octet | 0\n\n if (checkOffset(2) | 0) {\n return 1\n }\n\n pushTagStart(\n readUInt16((offset + 1) | 0) | 0\n )\n\n offset = (offset + 3 | 0)\n\n return 0\n }\n\n function TAG_MORE_4 (octet) {\n octet = octet | 0\n\n if (checkOffset(4) | 0) {\n return 1\n }\n\n pushTagStart4(\n readUInt16((offset + 1) | 0) | 0,\n readUInt16((offset + 3) | 0) | 0\n )\n\n offset = (offset + 5 | 0)\n\n return 0\n }\n\n function TAG_MORE_8 (octet) {\n octet = octet | 0\n\n if (checkOffset(8) | 0) {\n return 1\n }\n\n pushTagStart8(\n readUInt16((offset + 1) | 0) | 0,\n readUInt16((offset + 3) | 0) | 0,\n readUInt16((offset + 5) | 0) | 0,\n readUInt16((offset + 7) | 0) | 0\n )\n\n offset = (offset + 9 | 0)\n\n return 0\n }\n\n function SIMPLE_UNASSIGNED (octet) {\n octet = octet | 0\n\n pushSimpleUnassigned(((octet | 0) - 224) | 0)\n\n offset = (offset + 1) | 0\n\n return 0\n }\n\n function SIMPLE_FALSE (octet) {\n octet = octet | 0\n\n pushFalse()\n\n offset = (offset + 1) | 0\n\n return 0\n }\n\n function SIMPLE_TRUE (octet) {\n octet = octet | 0\n\n pushTrue()\n\n offset = (offset + 1) | 0\n\n return 0\n }\n\n function SIMPLE_NULL (octet) {\n octet = octet | 0\n\n pushNull()\n\n offset = (offset + 1) | 0\n\n return 0\n }\n\n function SIMPLE_UNDEFINED (octet) {\n octet = octet | 0\n\n pushUndefined()\n\n offset = (offset + 1) | 0\n\n return 0\n }\n\n function SIMPLE_BYTE (octet) {\n octet = octet | 0\n\n if (checkOffset(1) | 0) {\n return 1\n }\n\n pushSimpleUnassigned(heap[(offset + 1) | 0] | 0)\n\n offset = (offset + 2) | 0\n\n return 0\n }\n\n function SIMPLE_FLOAT_HALF (octet) {\n octet = octet | 0\n\n var f = 0\n var g = 0\n var sign = 1.0\n var exp = 0.0\n var mant = 0.0\n var r = 0.0\n if (checkOffset(2) | 0) {\n return 1\n }\n\n f = heap[(offset + 1) | 0] | 0\n g = heap[(offset + 2) | 0] | 0\n\n if ((f | 0) & 0x80) {\n sign = -1.0\n }\n\n exp = +(((f | 0) & 0x7C) >> 2)\n mant = +((((f | 0) & 0x03) << 8) | g)\n\n if (+exp == 0.0) {\n pushFloat(+(\n (+sign) * +5.9604644775390625e-8 * (+mant)\n ))\n } else if (+exp == 31.0) {\n if (+sign == 1.0) {\n if (+mant > 0.0) {\n pushNaN()\n } else {\n pushInfinity()\n }\n } else {\n if (+mant > 0.0) {\n pushNaNNeg()\n } else {\n pushInfinityNeg()\n }\n }\n } else {\n pushFloat(+(\n +sign * pow(+2, +(+exp - 25.0)) * +(1024.0 + mant)\n ))\n }\n\n offset = (offset + 3) | 0\n\n return 0\n }\n\n function SIMPLE_FLOAT_SINGLE (octet) {\n octet = octet | 0\n\n if (checkOffset(4) | 0) {\n return 1\n }\n\n pushFloatSingle(\n heap[(offset + 1) | 0] | 0,\n heap[(offset + 2) | 0] | 0,\n heap[(offset + 3) | 0] | 0,\n heap[(offset + 4) | 0] | 0\n )\n\n offset = (offset + 5) | 0\n\n return 0\n }\n\n function SIMPLE_FLOAT_DOUBLE (octet) {\n octet = octet | 0\n\n if (checkOffset(8) | 0) {\n return 1\n }\n\n pushFloatDouble(\n heap[(offset + 1) | 0] | 0,\n heap[(offset + 2) | 0] | 0,\n heap[(offset + 3) | 0] | 0,\n heap[(offset + 4) | 0] | 0,\n heap[(offset + 5) | 0] | 0,\n heap[(offset + 6) | 0] | 0,\n heap[(offset + 7) | 0] | 0,\n heap[(offset + 8) | 0] | 0\n )\n\n offset = (offset + 9) | 0\n\n return 0\n }\n\n function ERROR (octet) {\n octet = octet | 0\n\n return 1\n }\n\n function BREAK (octet) {\n octet = octet | 0\n\n pushBreak()\n\n offset = (offset + 1) | 0\n\n return 0\n }\n\n // -- Jump Table\n\n var jumpTable = [\n // Integer 0x00..0x17 (0..23)\n INT_P, // 0x00\n INT_P, // 0x01\n INT_P, // 0x02\n INT_P, // 0x03\n INT_P, // 0x04\n INT_P, // 0x05\n INT_P, // 0x06\n INT_P, // 0x07\n INT_P, // 0x08\n INT_P, // 0x09\n INT_P, // 0x0A\n INT_P, // 0x0B\n INT_P, // 0x0C\n INT_P, // 0x0D\n INT_P, // 0x0E\n INT_P, // 0x0F\n INT_P, // 0x10\n INT_P, // 0x11\n INT_P, // 0x12\n INT_P, // 0x13\n INT_P, // 0x14\n INT_P, // 0x15\n INT_P, // 0x16\n INT_P, // 0x17\n // Unsigned integer (one-byte uint8_t follows)\n UINT_P_8, // 0x18\n // Unsigned integer (two-byte uint16_t follows)\n UINT_P_16, // 0x19\n // Unsigned integer (four-byte uint32_t follows)\n UINT_P_32, // 0x1a\n // Unsigned integer (eight-byte uint64_t follows)\n UINT_P_64, // 0x1b\n ERROR, // 0x1c\n ERROR, // 0x1d\n ERROR, // 0x1e\n ERROR, // 0x1f\n // Negative integer -1-0x00..-1-0x17 (-1..-24)\n INT_N, // 0x20\n INT_N, // 0x21\n INT_N, // 0x22\n INT_N, // 0x23\n INT_N, // 0x24\n INT_N, // 0x25\n INT_N, // 0x26\n INT_N, // 0x27\n INT_N, // 0x28\n INT_N, // 0x29\n INT_N, // 0x2A\n INT_N, // 0x2B\n INT_N, // 0x2C\n INT_N, // 0x2D\n INT_N, // 0x2E\n INT_N, // 0x2F\n INT_N, // 0x30\n INT_N, // 0x31\n INT_N, // 0x32\n INT_N, // 0x33\n INT_N, // 0x34\n INT_N, // 0x35\n INT_N, // 0x36\n INT_N, // 0x37\n // Negative integer -1-n (one-byte uint8_t for n follows)\n UINT_N_8, // 0x38\n // Negative integer -1-n (two-byte uint16_t for n follows)\n UINT_N_16, // 0x39\n // Negative integer -1-n (four-byte uint32_t for nfollows)\n UINT_N_32, // 0x3a\n // Negative integer -1-n (eight-byte uint64_t for n follows)\n UINT_N_64, // 0x3b\n ERROR, // 0x3c\n ERROR, // 0x3d\n ERROR, // 0x3e\n ERROR, // 0x3f\n // byte string (0x00..0x17 bytes follow)\n BYTE_STRING, // 0x40\n BYTE_STRING, // 0x41\n BYTE_STRING, // 0x42\n BYTE_STRING, // 0x43\n BYTE_STRING, // 0x44\n BYTE_STRING, // 0x45\n BYTE_STRING, // 0x46\n BYTE_STRING, // 0x47\n BYTE_STRING, // 0x48\n BYTE_STRING, // 0x49\n BYTE_STRING, // 0x4A\n BYTE_STRING, // 0x4B\n BYTE_STRING, // 0x4C\n BYTE_STRING, // 0x4D\n BYTE_STRING, // 0x4E\n BYTE_STRING, // 0x4F\n BYTE_STRING, // 0x50\n BYTE_STRING, // 0x51\n BYTE_STRING, // 0x52\n BYTE_STRING, // 0x53\n BYTE_STRING, // 0x54\n BYTE_STRING, // 0x55\n BYTE_STRING, // 0x56\n BYTE_STRING, // 0x57\n // byte string (one-byte uint8_t for n, and then n bytes follow)\n BYTE_STRING_8, // 0x58\n // byte string (two-byte uint16_t for n, and then n bytes follow)\n BYTE_STRING_16, // 0x59\n // byte string (four-byte uint32_t for n, and then n bytes follow)\n BYTE_STRING_32, // 0x5a\n // byte string (eight-byte uint64_t for n, and then n bytes follow)\n BYTE_STRING_64, // 0x5b\n ERROR, // 0x5c\n ERROR, // 0x5d\n ERROR, // 0x5e\n // byte string, byte strings follow, terminated by \"break\"\n BYTE_STRING_BREAK, // 0x5f\n // UTF-8 string (0x00..0x17 bytes follow)\n UTF8_STRING, // 0x60\n UTF8_STRING, // 0x61\n UTF8_STRING, // 0x62\n UTF8_STRING, // 0x63\n UTF8_STRING, // 0x64\n UTF8_STRING, // 0x65\n UTF8_STRING, // 0x66\n UTF8_STRING, // 0x67\n UTF8_STRING, // 0x68\n UTF8_STRING, // 0x69\n UTF8_STRING, // 0x6A\n UTF8_STRING, // 0x6B\n UTF8_STRING, // 0x6C\n UTF8_STRING, // 0x6D\n UTF8_STRING, // 0x6E\n UTF8_STRING, // 0x6F\n UTF8_STRING, // 0x70\n UTF8_STRING, // 0x71\n UTF8_STRING, // 0x72\n UTF8_STRING, // 0x73\n UTF8_STRING, // 0x74\n UTF8_STRING, // 0x75\n UTF8_STRING, // 0x76\n UTF8_STRING, // 0x77\n // UTF-8 string (one-byte uint8_t for n, and then n bytes follow)\n UTF8_STRING_8, // 0x78\n // UTF-8 string (two-byte uint16_t for n, and then n bytes follow)\n UTF8_STRING_16, // 0x79\n // UTF-8 string (four-byte uint32_t for n, and then n bytes follow)\n UTF8_STRING_32, // 0x7a\n // UTF-8 string (eight-byte uint64_t for n, and then n bytes follow)\n UTF8_STRING_64, // 0x7b\n // UTF-8 string, UTF-8 strings follow, terminated by \"break\"\n ERROR, // 0x7c\n ERROR, // 0x7d\n ERROR, // 0x7e\n UTF8_STRING_BREAK, // 0x7f\n // array (0x00..0x17 data items follow)\n ARRAY, // 0x80\n ARRAY, // 0x81\n ARRAY, // 0x82\n ARRAY, // 0x83\n ARRAY, // 0x84\n ARRAY, // 0x85\n ARRAY, // 0x86\n ARRAY, // 0x87\n ARRAY, // 0x88\n ARRAY, // 0x89\n ARRAY, // 0x8A\n ARRAY, // 0x8B\n ARRAY, // 0x8C\n ARRAY, // 0x8D\n ARRAY, // 0x8E\n ARRAY, // 0x8F\n ARRAY, // 0x90\n ARRAY, // 0x91\n ARRAY, // 0x92\n ARRAY, // 0x93\n ARRAY, // 0x94\n ARRAY, // 0x95\n ARRAY, // 0x96\n ARRAY, // 0x97\n // array (one-byte uint8_t fo, and then n data items follow)\n ARRAY_8, // 0x98\n // array (two-byte uint16_t for n, and then n data items follow)\n ARRAY_16, // 0x99\n // array (four-byte uint32_t for n, and then n data items follow)\n ARRAY_32, // 0x9a\n // array (eight-byte uint64_t for n, and then n data items follow)\n ARRAY_64, // 0x9b\n // array, data items follow, terminated by \"break\"\n ERROR, // 0x9c\n ERROR, // 0x9d\n ERROR, // 0x9e\n ARRAY_BREAK, // 0x9f\n // map (0x00..0x17 pairs of data items follow)\n MAP, // 0xa0\n MAP, // 0xa1\n MAP, // 0xa2\n MAP, // 0xa3\n MAP, // 0xa4\n MAP, // 0xa5\n MAP, // 0xa6\n MAP, // 0xa7\n MAP, // 0xa8\n MAP, // 0xa9\n MAP, // 0xaA\n MAP, // 0xaB\n MAP, // 0xaC\n MAP, // 0xaD\n MAP, // 0xaE\n MAP, // 0xaF\n MAP, // 0xb0\n MAP, // 0xb1\n MAP, // 0xb2\n MAP, // 0xb3\n MAP, // 0xb4\n MAP, // 0xb5\n MAP, // 0xb6\n MAP, // 0xb7\n // map (one-byte uint8_t for n, and then n pairs of data items follow)\n MAP_8, // 0xb8\n // map (two-byte uint16_t for n, and then n pairs of data items follow)\n MAP_16, // 0xb9\n // map (four-byte uint32_t for n, and then n pairs of data items follow)\n MAP_32, // 0xba\n // map (eight-byte uint64_t for n, and then n pairs of data items follow)\n MAP_64, // 0xbb\n ERROR, // 0xbc\n ERROR, // 0xbd\n ERROR, // 0xbe\n // map, pairs of data items follow, terminated by \"break\"\n MAP_BREAK, // 0xbf\n // Text-based date/time (data item follows; see Section 2.4.1)\n TAG_KNOWN, // 0xc0\n // Epoch-based date/time (data item follows; see Section 2.4.1)\n TAG_KNOWN, // 0xc1\n // Positive bignum (data item \"byte string\" follows)\n TAG_KNOWN, // 0xc2\n // Negative bignum (data item \"byte string\" follows)\n TAG_KNOWN, // 0xc3\n // Decimal Fraction (data item \"array\" follows; see Section 2.4.3)\n TAG_KNOWN, // 0xc4\n // Bigfloat (data item \"array\" follows; see Section 2.4.3)\n TAG_KNOWN, // 0xc5\n // (tagged item)\n TAG_UNASSIGNED, // 0xc6\n TAG_UNASSIGNED, // 0xc7\n TAG_UNASSIGNED, // 0xc8\n TAG_UNASSIGNED, // 0xc9\n TAG_UNASSIGNED, // 0xca\n TAG_UNASSIGNED, // 0xcb\n TAG_UNASSIGNED, // 0xcc\n TAG_UNASSIGNED, // 0xcd\n TAG_UNASSIGNED, // 0xce\n TAG_UNASSIGNED, // 0xcf\n TAG_UNASSIGNED, // 0xd0\n TAG_UNASSIGNED, // 0xd1\n TAG_UNASSIGNED, // 0xd2\n TAG_UNASSIGNED, // 0xd3\n TAG_UNASSIGNED, // 0xd4\n // Expected Conversion (data item follows; see Section 2.4.4.2)\n TAG_UNASSIGNED, // 0xd5\n TAG_UNASSIGNED, // 0xd6\n TAG_UNASSIGNED, // 0xd7\n // (more tagged items, 1/2/4/8 bytes and then a data item follow)\n TAG_MORE_1, // 0xd8\n TAG_MORE_2, // 0xd9\n TAG_MORE_4, // 0xda\n TAG_MORE_8, // 0xdb\n ERROR, // 0xdc\n ERROR, // 0xdd\n ERROR, // 0xde\n ERROR, // 0xdf\n // (simple value)\n SIMPLE_UNASSIGNED, // 0xe0\n SIMPLE_UNASSIGNED, // 0xe1\n SIMPLE_UNASSIGNED, // 0xe2\n SIMPLE_UNASSIGNED, // 0xe3\n SIMPLE_UNASSIGNED, // 0xe4\n SIMPLE_UNASSIGNED, // 0xe5\n SIMPLE_UNASSIGNED, // 0xe6\n SIMPLE_UNASSIGNED, // 0xe7\n SIMPLE_UNASSIGNED, // 0xe8\n SIMPLE_UNASSIGNED, // 0xe9\n SIMPLE_UNASSIGNED, // 0xea\n SIMPLE_UNASSIGNED, // 0xeb\n SIMPLE_UNASSIGNED, // 0xec\n SIMPLE_UNASSIGNED, // 0xed\n SIMPLE_UNASSIGNED, // 0xee\n SIMPLE_UNASSIGNED, // 0xef\n SIMPLE_UNASSIGNED, // 0xf0\n SIMPLE_UNASSIGNED, // 0xf1\n SIMPLE_UNASSIGNED, // 0xf2\n SIMPLE_UNASSIGNED, // 0xf3\n // False\n SIMPLE_FALSE, // 0xf4\n // True\n SIMPLE_TRUE, // 0xf5\n // Null\n SIMPLE_NULL, // 0xf6\n // Undefined\n SIMPLE_UNDEFINED, // 0xf7\n // (simple value, one byte follows)\n SIMPLE_BYTE, // 0xf8\n // Half-Precision Float (two-byte IEEE 754)\n SIMPLE_FLOAT_HALF, // 0xf9\n // Single-Precision Float (four-byte IEEE 754)\n SIMPLE_FLOAT_SINGLE, // 0xfa\n // Double-Precision Float (eight-byte IEEE 754)\n SIMPLE_FLOAT_DOUBLE, // 0xfb\n ERROR, // 0xfc\n ERROR, // 0xfd\n ERROR, // 0xfe\n // \"break\" stop code\n BREAK // 0xff\n ]\n\n // --\n\n return {\n parse: parse\n }\n}\n","'use strict'\n\nconst Bignumber = require('bignumber.js').BigNumber\n\nexports.MT = {\n POS_INT: 0,\n NEG_INT: 1,\n BYTE_STRING: 2,\n UTF8_STRING: 3,\n ARRAY: 4,\n MAP: 5,\n TAG: 6,\n SIMPLE_FLOAT: 7\n}\n\nexports.TAG = {\n DATE_STRING: 0,\n DATE_EPOCH: 1,\n POS_BIGINT: 2,\n NEG_BIGINT: 3,\n DECIMAL_FRAC: 4,\n BIGFLOAT: 5,\n BASE64URL_EXPECTED: 21,\n BASE64_EXPECTED: 22,\n BASE16_EXPECTED: 23,\n CBOR: 24,\n URI: 32,\n BASE64URL: 33,\n BASE64: 34,\n REGEXP: 35,\n MIME: 36\n}\n\nexports.NUMBYTES = {\n ZERO: 0,\n ONE: 24,\n TWO: 25,\n FOUR: 26,\n EIGHT: 27,\n INDEFINITE: 31\n}\n\nexports.SIMPLE = {\n FALSE: 20,\n TRUE: 21,\n NULL: 22,\n UNDEFINED: 23\n}\n\nexports.SYMS = {\n NULL: Symbol('null'),\n UNDEFINED: Symbol('undef'),\n PARENT: Symbol('parent'),\n BREAK: Symbol('break'),\n STREAM: Symbol('stream')\n}\n\nexports.SHIFT32 = Math.pow(2, 32)\nexports.SHIFT16 = Math.pow(2, 16)\n\nexports.MAX_SAFE_HIGH = 0x1fffff\nexports.NEG_ONE = new Bignumber(-1)\nexports.TEN = new Bignumber(10)\nexports.TWO = new Bignumber(2)\n\nexports.PARENT = {\n ARRAY: 0,\n OBJECT: 1,\n MAP: 2,\n TAG: 3,\n BYTE_STRING: 4,\n UTF8_STRING: 5\n}\n","'use strict'\n\nconst { Buffer } = require('buffer')\nconst Bignumber = require('bignumber.js').BigNumber\n\nconst constants = require('./constants')\nconst SHIFT32 = constants.SHIFT32\nconst SHIFT16 = constants.SHIFT16\nconst MAX_SAFE_HIGH = 0x1fffff\n\nexports.parseHalf = function parseHalf (buf) {\n var exp, mant, sign\n sign = buf[0] & 0x80 ? -1 : 1\n exp = (buf[0] & 0x7C) >> 2\n mant = ((buf[0] & 0x03) << 8) | buf[1]\n if (!exp) {\n return sign * 5.9604644775390625e-8 * mant\n } else if (exp === 0x1f) {\n return sign * (mant ? 0 / 0 : 2e308)\n } else {\n return sign * Math.pow(2, exp - 25) * (1024 + mant)\n }\n}\n\nfunction toHex (n) {\n if (n < 16) {\n return '0' + n.toString(16)\n }\n\n return n.toString(16)\n}\n\nexports.arrayBufferToBignumber = function (buf) {\n const len = buf.byteLength\n let res = ''\n for (let i = 0; i < len; i++) {\n res += toHex(buf[i])\n }\n\n return new Bignumber(res, 16)\n}\n\n// convert an Object into a Map\nexports.buildMap = (obj) => {\n const res = new Map()\n const keys = Object.keys(obj)\n const length = keys.length\n for (let i = 0; i < length; i++) {\n res.set(keys[i], obj[keys[i]])\n }\n return res\n}\n\nexports.buildInt32 = (f, g) => {\n return f * SHIFT16 + g\n}\n\nexports.buildInt64 = (f1, f2, g1, g2) => {\n const f = exports.buildInt32(f1, f2)\n const g = exports.buildInt32(g1, g2)\n\n if (f > MAX_SAFE_HIGH) {\n return new Bignumber(f).times(SHIFT32).plus(g)\n } else {\n return (f * SHIFT32) + g\n }\n}\n\nexports.writeHalf = function writeHalf (buf, half) {\n // assume 0, -0, NaN, Infinity, and -Infinity have already been caught\n\n // HACK: everyone settle in. This isn't going to be pretty.\n // Translate cn-cbor's C code (from Carsten Borman):\n\n // uint32_t be32;\n // uint16_t be16, u16;\n // union {\n // float f;\n // uint32_t u;\n // } u32;\n // u32.f = float_val;\n\n const u32 = Buffer.allocUnsafe(4)\n u32.writeFloatBE(half, 0)\n const u = u32.readUInt32BE(0)\n\n // if ((u32.u & 0x1FFF) == 0) { /* worth trying half */\n\n // hildjj: If the lower 13 bits are 0, we won't lose anything in the conversion\n if ((u & 0x1FFF) !== 0) {\n return false\n }\n\n // int s16 = (u32.u >> 16) & 0x8000;\n // int exp = (u32.u >> 23) & 0xff;\n // int mant = u32.u & 0x7fffff;\n\n var s16 = (u >> 16) & 0x8000 // top bit is sign\n const exp = (u >> 23) & 0xff // then 5 bits of exponent\n const mant = u & 0x7fffff\n\n // if (exp == 0 && mant == 0)\n // ; /* 0.0, -0.0 */\n\n // hildjj: zeros already handled. Assert if you don't believe me.\n\n // else if (exp >= 113 && exp <= 142) /* normalized */\n // s16 += ((exp - 112) << 10) + (mant >> 13);\n if ((exp >= 113) && (exp <= 142)) {\n s16 += ((exp - 112) << 10) + (mant >> 13)\n\n // else if (exp >= 103 && exp < 113) { /* denorm, exp16 = 0 */\n // if (mant & ((1 << (126 - exp)) - 1))\n // goto float32; /* loss of precision */\n // s16 += ((mant + 0x800000) >> (126 - exp));\n } else if ((exp >= 103) && (exp < 113)) {\n if (mant & ((1 << (126 - exp)) - 1)) {\n return false\n }\n s16 += ((mant + 0x800000) >> (126 - exp))\n\n // } else if (exp == 255 && mant == 0) { /* Inf */\n // s16 += 0x7c00;\n\n // hildjj: Infinity already handled\n\n // } else\n // goto float32; /* loss of range */\n } else {\n return false\n }\n\n // ensure_writable(3);\n // u16 = s16;\n // be16 = hton16p((const uint8_t*)&u16);\n buf.writeUInt16BE(s16, 0)\n return true\n}\n\nexports.keySorter = function (a, b) {\n var lenA = a[0].byteLength\n var lenB = b[0].byteLength\n\n if (lenA > lenB) {\n return 1\n }\n\n if (lenB > lenA) {\n return -1\n }\n\n return a[0].compare(b[0])\n}\n\n// Adapted from http://www.2ality.com/2012/03/signedzero.html\nexports.isNegativeZero = (x) => {\n return x === 0 && (1 / x < 0)\n}\n\nexports.nextPowerOf2 = (n) => {\n let count = 0\n // First n in the below condition is for\n // the case where n is 0\n if (n && !(n & (n - 1))) {\n return n\n }\n\n while (n !== 0) {\n n >>= 1\n count += 1\n }\n\n return 1 << count\n}\n","'use strict'\n\nconst constants = require('./constants')\nconst MT = constants.MT\nconst SIMPLE = constants.SIMPLE\nconst SYMS = constants.SYMS\n\n/**\n * A CBOR Simple Value that does not map onto a known constant.\n */\nclass Simple {\n /**\n * Creates an instance of Simple.\n *\n * @param {integer} value - the simple value's integer value\n */\n constructor (value) {\n if (typeof value !== 'number') {\n throw new Error('Invalid Simple type: ' + (typeof value))\n }\n if ((value < 0) || (value > 255) || ((value | 0) !== value)) {\n throw new Error('value must be a small positive integer: ' + value)\n }\n this.value = value\n }\n\n /**\n * Debug string for simple value\n *\n * @returns {string} simple(value)\n */\n toString () {\n return 'simple(' + this.value + ')'\n }\n\n /**\n * Debug string for simple value\n *\n * @returns {string} simple(value)\n */\n inspect () {\n return 'simple(' + this.value + ')'\n }\n\n /**\n * Push the simple value onto the CBOR stream\n *\n * @param {cbor.Encoder} gen The generator to push onto\n * @returns {number}\n */\n encodeCBOR (gen) {\n return gen._pushInt(this.value, MT.SIMPLE_FLOAT)\n }\n\n /**\n * Is the given object a Simple?\n *\n * @param {any} obj - object to test\n * @returns {bool} - is it Simple?\n */\n static isSimple (obj) {\n return obj instanceof Simple\n }\n\n /**\n * Decode from the CBOR additional information into a JavaScript value.\n * If the CBOR item has no parent, return a \"safe\" symbol instead of\n * `null` or `undefined`, so that the value can be passed through a\n * stream in object mode.\n *\n * @param {Number} val - the CBOR additional info to convert\n * @param {bool} hasParent - Does the CBOR item have a parent?\n * @returns {(null|undefined|Boolean|Symbol)} - the decoded value\n */\n static decode (val, hasParent) {\n if (hasParent == null) {\n hasParent = true\n }\n switch (val) {\n case SIMPLE.FALSE:\n return false\n case SIMPLE.TRUE:\n return true\n case SIMPLE.NULL:\n if (hasParent) {\n return null\n } else {\n return SYMS.NULL\n }\n case SIMPLE.UNDEFINED:\n if (hasParent) {\n return undefined\n } else {\n return SYMS.UNDEFINED\n }\n case -1:\n if (!hasParent) {\n throw new Error('Invalid BREAK')\n }\n return SYMS.BREAK\n default:\n return new Simple(val)\n }\n }\n}\n\nmodule.exports = Simple\n","'use strict'\n\n/**\n * A CBOR tagged item, where the tag does not have semantics specified at the\n * moment, or those semantics threw an error during parsing. Typically this will\n * be an extension point you're not yet expecting.\n */\nclass Tagged {\n /**\n * Creates an instance of Tagged.\n *\n * @param {Number} tag - the number of the tag\n * @param {any} value - the value inside the tag\n * @param {Error} err - the error that was thrown parsing the tag, or null\n */\n constructor (tag, value, err) {\n this.tag = tag\n this.value = value\n this.err = err\n if (typeof this.tag !== 'number') {\n throw new Error('Invalid tag type (' + (typeof this.tag) + ')')\n }\n if ((this.tag < 0) || ((this.tag | 0) !== this.tag)) {\n throw new Error('Tag must be a positive integer: ' + this.tag)\n }\n }\n\n /**\n * Convert to a String\n *\n * @returns {String} string of the form '1(2)'\n */\n toString () {\n return `${this.tag}(${JSON.stringify(this.value)})`\n }\n\n /**\n * Push the simple value onto the CBOR stream\n *\n * @param {cbor.Encoder} gen The generator to push onto\n * @returns {number}\n */\n encodeCBOR (gen) {\n gen._pushTag(this.tag)\n return gen.pushAny(this.value)\n }\n\n /**\n * If we have a converter for this type, do the conversion. Some converters\n * are built-in. Additional ones can be passed in. If you want to remove\n * a built-in converter, pass a converter in whose value is 'null' instead\n * of a function.\n *\n * @param {Object} converters - keys in the object are a tag number, the value\n * is a function that takes the decoded CBOR and returns a JavaScript value\n * of the appropriate type. Throw an exception in the function on errors.\n * @returns {any} - the converted item\n */\n convert (converters) {\n var er, f\n f = converters != null ? converters[this.tag] : undefined\n if (typeof f !== 'function') {\n f = Tagged['_tag' + this.tag]\n if (typeof f !== 'function') {\n return this\n }\n }\n try {\n return f.call(Tagged, this.value)\n } catch (error) {\n er = error\n this.err = er\n return this\n }\n }\n}\n\nmodule.exports = Tagged\n","'use strict';\n\nconst defaultBase = self.location ?\n self.location.protocol + '//' + self.location.host :\n '';\nconst URL = self.URL;\n\nclass URLWithLegacySupport {\n constructor(url = '', base = defaultBase) {\n this.super = new URL(url, base);\n this.path = this.pathname + this.search;\n this.auth =\n this.username && this.password ?\n this.username + ':' + this.password :\n null;\n\n this.query =\n this.search && this.search.startsWith('?') ?\n this.search.slice(1) :\n null;\n }\n\n get hash() {\n return this.super.hash;\n }\n get host() {\n return this.super.host;\n }\n get hostname() {\n return this.super.hostname;\n }\n get href() {\n return this.super.href;\n }\n get origin() {\n return this.super.origin;\n }\n get password() {\n return this.super.password;\n }\n get pathname() {\n return this.super.pathname;\n }\n get port() {\n return this.super.port;\n }\n get protocol() {\n return this.super.protocol;\n }\n get search() {\n return this.super.search;\n }\n get searchParams() {\n return this.super.searchParams;\n }\n get username() {\n return this.super.username;\n }\n\n set hash(hash) {\n this.super.hash = hash;\n }\n set host(host) {\n this.super.host = host;\n }\n set hostname(hostname) {\n this.super.hostname = hostname;\n }\n set href(href) {\n this.super.href = href;\n }\n set origin(origin) {\n this.super.origin = origin;\n }\n set password(password) {\n this.super.password = password;\n }\n set pathname(pathname) {\n this.super.pathname = pathname;\n }\n set port(port) {\n this.super.port = port;\n }\n set protocol(protocol) {\n this.super.protocol = protocol;\n }\n set search(search) {\n this.super.search = search;\n }\n set searchParams(searchParams) {\n this.super.searchParams = searchParams;\n }\n set username(username) {\n this.super.username = username;\n }\n\n createObjectURL(o) {\n return this.super.createObjectURL(o);\n }\n revokeObjectURL(o) {\n this.super.revokeObjectURL(o);\n }\n toJSON() {\n return this.super.toJSON();\n }\n toString() {\n return this.super.toString();\n }\n format() {\n return this.toString();\n }\n}\n\nfunction format(obj) {\n if (typeof obj === 'string') {\n const url = new URL(obj);\n\n return url.toString();\n }\n\n if (!(obj instanceof URL)) {\n const userPass =\n obj.username && obj.password ?\n `${obj.username}:${obj.password}@` :\n '';\n const auth = obj.auth ? obj.auth + '@' : '';\n const port = obj.port ? ':' + obj.port : '';\n const protocol = obj.protocol ? obj.protocol + '//' : '';\n const host = obj.host || '';\n const hostname = obj.hostname || '';\n const search = obj.search || (obj.query ? '?' + obj.query : '');\n const hash = obj.hash || '';\n const pathname = obj.pathname || '';\n const path = obj.path || pathname + search;\n\n return `${protocol}${userPass || auth}${host ||\n hostname + port}${path}${hash}`;\n }\n}\n\nmodule.exports = {\n URLWithLegacySupport,\n URLSearchParams: self.URLSearchParams,\n defaultBase,\n format\n};\n","'use strict';\n\nconst { URLWithLegacySupport, format } = require('./url');\n\nmodule.exports = (url, location = {}, protocolMap = {}, defaultProtocol) => {\n let protocol = location.protocol ?\n location.protocol.replace(':', '') :\n 'http';\n\n // Check protocol map\n protocol = (protocolMap[protocol] || defaultProtocol || protocol) + ':';\n let urlParsed;\n\n try {\n urlParsed = new URLWithLegacySupport(url);\n } catch (err) {\n urlParsed = {};\n }\n\n const base = Object.assign({}, location, {\n protocol: protocol || urlParsed.protocol,\n host: location.host || urlParsed.host\n });\n\n return new URLWithLegacySupport(url, format(base)).toString();\n};\n","'use strict';\n\nconst {\n URLWithLegacySupport,\n format,\n URLSearchParams,\n defaultBase\n} = require('./src/url');\nconst relative = require('./src/relative');\n\nmodule.exports = {\n URL: URLWithLegacySupport,\n URLSearchParams,\n format,\n relative,\n defaultBase\n};\n","'use strict'\n\nconst { Buffer } = require('buffer')\nconst ieee754 = require('ieee754')\nconst Bignumber = require('bignumber.js').BigNumber\n\nconst parser = require('./decoder.asm')\nconst utils = require('./utils')\nconst c = require('./constants')\nconst Simple = require('./simple')\nconst Tagged = require('./tagged')\nconst { URL } = require('iso-url')\n\n/**\n * Transform binary cbor data into JavaScript objects.\n */\nclass Decoder {\n /**\n * @param {Object} [opts={}]\n * @param {number} [opts.size=65536] - Size of the allocated heap.\n */\n constructor (opts) {\n opts = opts || {}\n\n if (!opts.size || opts.size < 0x10000) {\n opts.size = 0x10000\n } else {\n // Ensure the size is a power of 2\n opts.size = utils.nextPowerOf2(opts.size)\n }\n\n // Heap use to share the input with the parser\n this._heap = new ArrayBuffer(opts.size)\n this._heap8 = new Uint8Array(this._heap)\n this._buffer = Buffer.from(this._heap)\n\n this._reset()\n\n // Known tags\n this._knownTags = Object.assign({\n 0: (val) => new Date(val),\n 1: (val) => new Date(val * 1000),\n 2: (val) => utils.arrayBufferToBignumber(val),\n 3: (val) => c.NEG_ONE.minus(utils.arrayBufferToBignumber(val)),\n 4: (v) => {\n // const v = new Uint8Array(val)\n return c.TEN.pow(v[0]).times(v[1])\n },\n 5: (v) => {\n // const v = new Uint8Array(val)\n return c.TWO.pow(v[0]).times(v[1])\n },\n 32: (val) => new URL(val),\n 35: (val) => new RegExp(val)\n }, opts.tags)\n\n // Initialize asm based parser\n this.parser = parser(global, {\n // eslint-disable-next-line no-console\n log: console.log.bind(console),\n pushInt: this.pushInt.bind(this),\n pushInt32: this.pushInt32.bind(this),\n pushInt32Neg: this.pushInt32Neg.bind(this),\n pushInt64: this.pushInt64.bind(this),\n pushInt64Neg: this.pushInt64Neg.bind(this),\n pushFloat: this.pushFloat.bind(this),\n pushFloatSingle: this.pushFloatSingle.bind(this),\n pushFloatDouble: this.pushFloatDouble.bind(this),\n pushTrue: this.pushTrue.bind(this),\n pushFalse: this.pushFalse.bind(this),\n pushUndefined: this.pushUndefined.bind(this),\n pushNull: this.pushNull.bind(this),\n pushInfinity: this.pushInfinity.bind(this),\n pushInfinityNeg: this.pushInfinityNeg.bind(this),\n pushNaN: this.pushNaN.bind(this),\n pushNaNNeg: this.pushNaNNeg.bind(this),\n pushArrayStart: this.pushArrayStart.bind(this),\n pushArrayStartFixed: this.pushArrayStartFixed.bind(this),\n pushArrayStartFixed32: this.pushArrayStartFixed32.bind(this),\n pushArrayStartFixed64: this.pushArrayStartFixed64.bind(this),\n pushObjectStart: this.pushObjectStart.bind(this),\n pushObjectStartFixed: this.pushObjectStartFixed.bind(this),\n pushObjectStartFixed32: this.pushObjectStartFixed32.bind(this),\n pushObjectStartFixed64: this.pushObjectStartFixed64.bind(this),\n pushByteString: this.pushByteString.bind(this),\n pushByteStringStart: this.pushByteStringStart.bind(this),\n pushUtf8String: this.pushUtf8String.bind(this),\n pushUtf8StringStart: this.pushUtf8StringStart.bind(this),\n pushSimpleUnassigned: this.pushSimpleUnassigned.bind(this),\n pushTagUnassigned: this.pushTagUnassigned.bind(this),\n pushTagStart: this.pushTagStart.bind(this),\n pushTagStart4: this.pushTagStart4.bind(this),\n pushTagStart8: this.pushTagStart8.bind(this),\n pushBreak: this.pushBreak.bind(this)\n }, this._heap)\n }\n\n get _depth () {\n return this._parents.length\n }\n\n get _currentParent () {\n return this._parents[this._depth - 1]\n }\n\n get _ref () {\n return this._currentParent.ref\n }\n\n // Finish the current parent\n _closeParent () {\n var p = this._parents.pop()\n\n if (p.length > 0) {\n throw new Error(`Missing ${p.length} elements`)\n }\n\n switch (p.type) {\n case c.PARENT.TAG:\n this._push(\n this.createTag(p.ref[0], p.ref[1])\n )\n break\n case c.PARENT.BYTE_STRING:\n this._push(this.createByteString(p.ref, p.length))\n break\n case c.PARENT.UTF8_STRING:\n this._push(this.createUtf8String(p.ref, p.length))\n break\n case c.PARENT.MAP:\n if (p.values % 2 > 0) {\n throw new Error('Odd number of elements in the map')\n }\n this._push(this.createMap(p.ref, p.length))\n break\n case c.PARENT.OBJECT:\n if (p.values % 2 > 0) {\n throw new Error('Odd number of elements in the map')\n }\n this._push(this.createObject(p.ref, p.length))\n break\n case c.PARENT.ARRAY:\n this._push(this.createArray(p.ref, p.length))\n break\n default:\n break\n }\n\n if (this._currentParent && this._currentParent.type === c.PARENT.TAG) {\n this._dec()\n }\n }\n\n // Reduce the expected length of the current parent by one\n _dec () {\n const p = this._currentParent\n // The current parent does not know the epxected child length\n\n if (p.length < 0) {\n return\n }\n\n p.length--\n\n // All children were seen, we can close the current parent\n if (p.length === 0) {\n this._closeParent()\n }\n }\n\n // Push any value to the current parent\n _push (val, hasChildren) {\n const p = this._currentParent\n p.values++\n\n switch (p.type) {\n case c.PARENT.ARRAY:\n case c.PARENT.BYTE_STRING:\n case c.PARENT.UTF8_STRING:\n if (p.length > -1) {\n this._ref[this._ref.length - p.length] = val\n } else {\n this._ref.push(val)\n }\n this._dec()\n break\n case c.PARENT.OBJECT:\n if (p.tmpKey != null) {\n this._ref[p.tmpKey] = val\n p.tmpKey = null\n this._dec()\n } else {\n p.tmpKey = val\n\n if (typeof p.tmpKey !== 'string') {\n // too bad, convert to a Map\n p.type = c.PARENT.MAP\n p.ref = utils.buildMap(p.ref)\n }\n }\n break\n case c.PARENT.MAP:\n if (p.tmpKey != null) {\n this._ref.set(p.tmpKey, val)\n p.tmpKey = null\n this._dec()\n } else {\n p.tmpKey = val\n }\n break\n case c.PARENT.TAG:\n this._ref.push(val)\n if (!hasChildren) {\n this._dec()\n }\n break\n default:\n throw new Error('Unknown parent type')\n }\n }\n\n // Create a new parent in the parents list\n _createParent (obj, type, len) {\n this._parents[this._depth] = {\n type: type,\n length: len,\n ref: obj,\n values: 0,\n tmpKey: null\n }\n }\n\n // Reset all state back to the beginning, also used for initiatlization\n _reset () {\n this._res = []\n this._parents = [{\n type: c.PARENT.ARRAY,\n length: -1,\n ref: this._res,\n values: 0,\n tmpKey: null\n }]\n }\n\n // -- Interface to customize deoding behaviour\n createTag (tagNumber, value) {\n const typ = this._knownTags[tagNumber]\n\n if (!typ) {\n return new Tagged(tagNumber, value)\n }\n\n return typ(value)\n }\n\n createMap (obj, len) {\n return obj\n }\n\n createObject (obj, len) {\n return obj\n }\n\n createArray (arr, len) {\n return arr\n }\n\n createByteString (raw, len) {\n return Buffer.concat(raw)\n }\n\n createByteStringFromHeap (start, end) {\n if (start === end) {\n return Buffer.alloc(0)\n }\n\n return Buffer.from(this._heap.slice(start, end))\n }\n\n createInt (val) {\n return val\n }\n\n createInt32 (f, g) {\n return utils.buildInt32(f, g)\n }\n\n createInt64 (f1, f2, g1, g2) {\n return utils.buildInt64(f1, f2, g1, g2)\n }\n\n createFloat (val) {\n return val\n }\n\n createFloatSingle (a, b, c, d) {\n return ieee754.read([a, b, c, d], 0, false, 23, 4)\n }\n\n createFloatDouble (a, b, c, d, e, f, g, h) {\n return ieee754.read([a, b, c, d, e, f, g, h], 0, false, 52, 8)\n }\n\n createInt32Neg (f, g) {\n return -1 - utils.buildInt32(f, g)\n }\n\n createInt64Neg (f1, f2, g1, g2) {\n const f = utils.buildInt32(f1, f2)\n const g = utils.buildInt32(g1, g2)\n\n if (f > c.MAX_SAFE_HIGH) {\n return c.NEG_ONE.minus(new Bignumber(f).times(c.SHIFT32).plus(g))\n }\n\n return -1 - ((f * c.SHIFT32) + g)\n }\n\n createTrue () {\n return true\n }\n\n createFalse () {\n return false\n }\n\n createNull () {\n return null\n }\n\n createUndefined () {\n return undefined\n }\n\n createInfinity () {\n return Infinity\n }\n\n createInfinityNeg () {\n return -Infinity\n }\n\n createNaN () {\n return NaN\n }\n\n createNaNNeg () {\n return -NaN\n }\n\n createUtf8String (raw, len) {\n return raw.join('')\n }\n\n createUtf8StringFromHeap (start, end) {\n if (start === end) {\n return ''\n }\n\n return this._buffer.toString('utf8', start, end)\n }\n\n createSimpleUnassigned (val) {\n return new Simple(val)\n }\n\n // -- Interface for decoder.asm.js\n\n pushInt (val) {\n this._push(this.createInt(val))\n }\n\n pushInt32 (f, g) {\n this._push(this.createInt32(f, g))\n }\n\n pushInt64 (f1, f2, g1, g2) {\n this._push(this.createInt64(f1, f2, g1, g2))\n }\n\n pushFloat (val) {\n this._push(this.createFloat(val))\n }\n\n pushFloatSingle (a, b, c, d) {\n this._push(this.createFloatSingle(a, b, c, d))\n }\n\n pushFloatDouble (a, b, c, d, e, f, g, h) {\n this._push(this.createFloatDouble(a, b, c, d, e, f, g, h))\n }\n\n pushInt32Neg (f, g) {\n this._push(this.createInt32Neg(f, g))\n }\n\n pushInt64Neg (f1, f2, g1, g2) {\n this._push(this.createInt64Neg(f1, f2, g1, g2))\n }\n\n pushTrue () {\n this._push(this.createTrue())\n }\n\n pushFalse () {\n this._push(this.createFalse())\n }\n\n pushNull () {\n this._push(this.createNull())\n }\n\n pushUndefined () {\n this._push(this.createUndefined())\n }\n\n pushInfinity () {\n this._push(this.createInfinity())\n }\n\n pushInfinityNeg () {\n this._push(this.createInfinityNeg())\n }\n\n pushNaN () {\n this._push(this.createNaN())\n }\n\n pushNaNNeg () {\n this._push(this.createNaNNeg())\n }\n\n pushArrayStart () {\n this._createParent([], c.PARENT.ARRAY, -1)\n }\n\n pushArrayStartFixed (len) {\n this._createArrayStartFixed(len)\n }\n\n pushArrayStartFixed32 (len1, len2) {\n const len = utils.buildInt32(len1, len2)\n this._createArrayStartFixed(len)\n }\n\n pushArrayStartFixed64 (len1, len2, len3, len4) {\n const len = utils.buildInt64(len1, len2, len3, len4)\n this._createArrayStartFixed(len)\n }\n\n pushObjectStart () {\n this._createObjectStartFixed(-1)\n }\n\n pushObjectStartFixed (len) {\n this._createObjectStartFixed(len)\n }\n\n pushObjectStartFixed32 (len1, len2) {\n const len = utils.buildInt32(len1, len2)\n this._createObjectStartFixed(len)\n }\n\n pushObjectStartFixed64 (len1, len2, len3, len4) {\n const len = utils.buildInt64(len1, len2, len3, len4)\n this._createObjectStartFixed(len)\n }\n\n pushByteStringStart () {\n this._parents[this._depth] = {\n type: c.PARENT.BYTE_STRING,\n length: -1,\n ref: [],\n values: 0,\n tmpKey: null\n }\n }\n\n pushByteString (start, end) {\n this._push(this.createByteStringFromHeap(start, end))\n }\n\n pushUtf8StringStart () {\n this._parents[this._depth] = {\n type: c.PARENT.UTF8_STRING,\n length: -1,\n ref: [],\n values: 0,\n tmpKey: null\n }\n }\n\n pushUtf8String (start, end) {\n this._push(this.createUtf8StringFromHeap(start, end))\n }\n\n pushSimpleUnassigned (val) {\n this._push(this.createSimpleUnassigned(val))\n }\n\n pushTagStart (tag) {\n this._parents[this._depth] = {\n type: c.PARENT.TAG,\n length: 1,\n ref: [tag]\n }\n }\n\n pushTagStart4 (f, g) {\n this.pushTagStart(utils.buildInt32(f, g))\n }\n\n pushTagStart8 (f1, f2, g1, g2) {\n this.pushTagStart(utils.buildInt64(f1, f2, g1, g2))\n }\n\n pushTagUnassigned (tagNumber) {\n this._push(this.createTag(tagNumber))\n }\n\n pushBreak () {\n if (this._currentParent.length > -1) {\n throw new Error('Unexpected break')\n }\n\n this._closeParent()\n }\n\n _createObjectStartFixed (len) {\n if (len === 0) {\n this._push(this.createObject({}))\n return\n }\n\n this._createParent({}, c.PARENT.OBJECT, len)\n }\n\n _createArrayStartFixed (len) {\n if (len === 0) {\n this._push(this.createArray([]))\n return\n }\n\n this._createParent(new Array(len), c.PARENT.ARRAY, len)\n }\n\n _decode (input) {\n if (input.byteLength === 0) {\n throw new Error('Input too short')\n }\n\n this._reset()\n this._heap8.set(input)\n const code = this.parser.parse(input.byteLength)\n\n if (this._depth > 1) {\n while (this._currentParent.length === 0) {\n this._closeParent()\n }\n if (this._depth > 1) {\n throw new Error('Undeterminated nesting')\n }\n }\n\n if (code > 0) {\n throw new Error('Failed to parse')\n }\n\n if (this._res.length === 0) {\n throw new Error('No valid result')\n }\n }\n\n // -- Public Interface\n\n decodeFirst (input) {\n this._decode(input)\n\n return this._res[0]\n }\n\n decodeAll (input) {\n this._decode(input)\n\n return this._res\n }\n\n /**\n * Decode the first cbor object.\n *\n * @param {Buffer|string} input\n * @param {string} [enc='hex'] - Encoding used if a string is passed.\n * @returns {*}\n */\n static decode (input, enc) {\n if (typeof input === 'string') {\n input = Buffer.from(input, enc || 'hex')\n }\n\n const dec = new Decoder({ size: input.length })\n return dec.decodeFirst(input)\n }\n\n /**\n * Decode all cbor objects.\n *\n * @param {Buffer|string} input\n * @param {string} [enc='hex'] - Encoding used if a string is passed.\n * @returns {Array<*>}\n */\n static decodeAll (input, enc) {\n if (typeof input === 'string') {\n input = Buffer.from(input, enc || 'hex')\n }\n\n const dec = new Decoder({ size: input.length })\n return dec.decodeAll(input)\n }\n}\n\nDecoder.decodeFirst = Decoder.decode\n\nmodule.exports = Decoder\n","'use strict'\n\nconst { Buffer } = require('buffer')\nconst Decoder = require('./decoder')\nconst utils = require('./utils')\n\n/**\n * Output the diagnostic format from a stream of CBOR bytes.\n *\n */\nclass Diagnose extends Decoder {\n createTag (tagNumber, value) {\n return `${tagNumber}(${value})`\n }\n\n createInt (val) {\n return super.createInt(val).toString()\n }\n\n createInt32 (f, g) {\n return super.createInt32(f, g).toString()\n }\n\n createInt64 (f1, f2, g1, g2) {\n return super.createInt64(f1, f2, g1, g2).toString()\n }\n\n createInt32Neg (f, g) {\n return super.createInt32Neg(f, g).toString()\n }\n\n createInt64Neg (f1, f2, g1, g2) {\n return super.createInt64Neg(f1, f2, g1, g2).toString()\n }\n\n createTrue () {\n return 'true'\n }\n\n createFalse () {\n return 'false'\n }\n\n createFloat (val) {\n const fl = super.createFloat(val)\n if (utils.isNegativeZero(val)) {\n return '-0_1'\n }\n\n return `${fl}_1`\n }\n\n createFloatSingle (a, b, c, d) {\n const fl = super.createFloatSingle(a, b, c, d)\n return `${fl}_2`\n }\n\n createFloatDouble (a, b, c, d, e, f, g, h) {\n const fl = super.createFloatDouble(a, b, c, d, e, f, g, h)\n return `${fl}_3`\n }\n\n createByteString (raw, len) {\n const val = raw.join(', ')\n\n if (len === -1) {\n return `(_ ${val})`\n }\n return `h'${val}`\n }\n\n createByteStringFromHeap (start, end) {\n const val = (Buffer.from(\n super.createByteStringFromHeap(start, end)\n )).toString('hex')\n\n return `h'${val}'`\n }\n\n createInfinity () {\n return 'Infinity_1'\n }\n\n createInfinityNeg () {\n return '-Infinity_1'\n }\n\n createNaN () {\n return 'NaN_1'\n }\n\n createNaNNeg () {\n return '-NaN_1'\n }\n\n createNull () {\n return 'null'\n }\n\n createUndefined () {\n return 'undefined'\n }\n\n createSimpleUnassigned (val) {\n return `simple(${val})`\n }\n\n createArray (arr, len) {\n const val = super.createArray(arr, len)\n\n if (len === -1) {\n // indefinite\n return `[_ ${val.join(', ')}]`\n }\n\n return `[${val.join(', ')}]`\n }\n\n createMap (map, len) {\n const val = super.createMap(map)\n const list = Array.from(val.keys())\n .reduce(collectObject(val), '')\n\n if (len === -1) {\n return `{_ ${list}}`\n }\n\n return `{${list}}`\n }\n\n createObject (obj, len) {\n const val = super.createObject(obj)\n const map = Object.keys(val)\n .reduce(collectObject(val), '')\n\n if (len === -1) {\n return `{_ ${map}}`\n }\n\n return `{${map}}`\n }\n\n createUtf8String (raw, len) {\n const val = raw.join(', ')\n\n if (len === -1) {\n return `(_ ${val})`\n }\n\n return `\"${val}\"`\n }\n\n createUtf8StringFromHeap (start, end) {\n const val = (Buffer.from(\n super.createUtf8StringFromHeap(start, end)\n )).toString('utf8')\n\n return `\"${val}\"`\n }\n\n static diagnose (input, enc) {\n if (typeof input === 'string') {\n input = Buffer.from(input, enc || 'hex')\n }\n\n const dec = new Diagnose()\n return dec.decodeFirst(input)\n }\n}\n\nmodule.exports = Diagnose\n\nfunction collectObject (val) {\n return (acc, key) => {\n if (acc) {\n return `${acc}, ${key}: ${val[key]}`\n }\n return `${key}: ${val[key]}`\n }\n}\n","'use strict'\n\nconst { Buffer } = require('buffer')\nconst { URL } = require('iso-url')\nconst Bignumber = require('bignumber.js').BigNumber\n\nconst utils = require('./utils')\nconst constants = require('./constants')\nconst MT = constants.MT\nconst NUMBYTES = constants.NUMBYTES\nconst SHIFT32 = constants.SHIFT32\nconst SYMS = constants.SYMS\nconst TAG = constants.TAG\nconst HALF = (constants.MT.SIMPLE_FLOAT << 5) | constants.NUMBYTES.TWO\nconst FLOAT = (constants.MT.SIMPLE_FLOAT << 5) | constants.NUMBYTES.FOUR\nconst DOUBLE = (constants.MT.SIMPLE_FLOAT << 5) | constants.NUMBYTES.EIGHT\nconst TRUE = (constants.MT.SIMPLE_FLOAT << 5) | constants.SIMPLE.TRUE\nconst FALSE = (constants.MT.SIMPLE_FLOAT << 5) | constants.SIMPLE.FALSE\nconst UNDEFINED = (constants.MT.SIMPLE_FLOAT << 5) | constants.SIMPLE.UNDEFINED\nconst NULL = (constants.MT.SIMPLE_FLOAT << 5) | constants.SIMPLE.NULL\n\nconst MAXINT_BN = new Bignumber('0x20000000000000')\nconst BUF_NAN = Buffer.from('f97e00', 'hex')\nconst BUF_INF_NEG = Buffer.from('f9fc00', 'hex')\nconst BUF_INF_POS = Buffer.from('f97c00', 'hex')\n\nfunction toType (obj) {\n // [object Type]\n // --------8---1\n return ({}).toString.call(obj).slice(8, -1)\n}\n\n/**\n * Transform JavaScript values into CBOR bytes\n *\n */\nclass Encoder {\n /**\n * @param {Object} [options={}]\n * @param {function(Buffer)} options.stream\n */\n constructor (options) {\n options = options || {}\n\n this.streaming = typeof options.stream === 'function'\n this.onData = options.stream\n\n this.semanticTypes = [\n [URL, this._pushUrl],\n [Bignumber, this._pushBigNumber]\n ]\n\n const addTypes = options.genTypes || []\n const len = addTypes.length\n for (let i = 0; i < len; i++) {\n this.addSemanticType(\n addTypes[i][0],\n addTypes[i][1]\n )\n }\n\n this._reset()\n }\n\n addSemanticType (type, fun) {\n const len = this.semanticTypes.length\n for (let i = 0; i < len; i++) {\n const typ = this.semanticTypes[i][0]\n if (typ === type) {\n const old = this.semanticTypes[i][1]\n this.semanticTypes[i][1] = fun\n return old\n }\n }\n this.semanticTypes.push([type, fun])\n return null\n }\n\n push (val) {\n if (!val) {\n return true\n }\n\n this.result[this.offset] = val\n this.resultMethod[this.offset] = 0\n this.resultLength[this.offset] = val.length\n this.offset++\n\n if (this.streaming) {\n this.onData(this.finalize())\n }\n\n return true\n }\n\n pushWrite (val, method, len) {\n this.result[this.offset] = val\n this.resultMethod[this.offset] = method\n this.resultLength[this.offset] = len\n this.offset++\n\n if (this.streaming) {\n this.onData(this.finalize())\n }\n\n return true\n }\n\n _pushUInt8 (val) {\n return this.pushWrite(val, 1, 1)\n }\n\n _pushUInt16BE (val) {\n return this.pushWrite(val, 2, 2)\n }\n\n _pushUInt32BE (val) {\n return this.pushWrite(val, 3, 4)\n }\n\n _pushDoubleBE (val) {\n return this.pushWrite(val, 4, 8)\n }\n\n _pushNaN () {\n return this.push(BUF_NAN)\n }\n\n _pushInfinity (obj) {\n const half = (obj < 0) ? BUF_INF_NEG : BUF_INF_POS\n return this.push(half)\n }\n\n _pushFloat (obj) {\n const b2 = Buffer.allocUnsafe(2)\n\n if (utils.writeHalf(b2, obj)) {\n if (utils.parseHalf(b2) === obj) {\n return this._pushUInt8(HALF) && this.push(b2)\n }\n }\n\n const b4 = Buffer.allocUnsafe(4)\n b4.writeFloatBE(obj, 0)\n if (b4.readFloatBE(0) === obj) {\n return this._pushUInt8(FLOAT) && this.push(b4)\n }\n\n return this._pushUInt8(DOUBLE) && this._pushDoubleBE(obj)\n }\n\n _pushInt (obj, mt, orig) {\n const m = mt << 5\n if (obj < 24) {\n return this._pushUInt8(m | obj)\n }\n\n if (obj <= 0xff) {\n return this._pushUInt8(m | NUMBYTES.ONE) && this._pushUInt8(obj)\n }\n\n if (obj <= 0xffff) {\n return this._pushUInt8(m | NUMBYTES.TWO) && this._pushUInt16BE(obj)\n }\n\n if (obj <= 0xffffffff) {\n return this._pushUInt8(m | NUMBYTES.FOUR) && this._pushUInt32BE(obj)\n }\n\n if (obj <= Number.MAX_SAFE_INTEGER) {\n return this._pushUInt8(m | NUMBYTES.EIGHT) &&\n this._pushUInt32BE(Math.floor(obj / SHIFT32)) &&\n this._pushUInt32BE(obj % SHIFT32)\n }\n\n if (mt === MT.NEG_INT) {\n return this._pushFloat(orig)\n }\n\n return this._pushFloat(obj)\n }\n\n _pushIntNum (obj) {\n if (obj < 0) {\n return this._pushInt(-obj - 1, MT.NEG_INT, obj)\n } else {\n return this._pushInt(obj, MT.POS_INT)\n }\n }\n\n _pushNumber (obj) {\n switch (false) {\n case (obj === obj): // eslint-disable-line\n return this._pushNaN(obj)\n case isFinite(obj):\n return this._pushInfinity(obj)\n case ((obj % 1) !== 0):\n return this._pushIntNum(obj)\n default:\n return this._pushFloat(obj)\n }\n }\n\n _pushString (obj) {\n const len = Buffer.byteLength(obj, 'utf8')\n return this._pushInt(len, MT.UTF8_STRING) && this.pushWrite(obj, 5, len)\n }\n\n _pushBoolean (obj) {\n return this._pushUInt8(obj ? TRUE : FALSE)\n }\n\n _pushUndefined (obj) {\n return this._pushUInt8(UNDEFINED)\n }\n\n _pushArray (gen, obj) {\n const len = obj.length\n if (!gen._pushInt(len, MT.ARRAY)) {\n return false\n }\n for (let j = 0; j < len; j++) {\n if (!gen.pushAny(obj[j])) {\n return false\n }\n }\n return true\n }\n\n _pushTag (tag) {\n return this._pushInt(tag, MT.TAG)\n }\n\n _pushDate (gen, obj) {\n // Round date, to get seconds since 1970-01-01 00:00:00 as defined in\n // Sec. 2.4.1 and get a possibly more compact encoding. Note that it is\n // still allowed to encode fractions of seconds which can be achieved by\n // changing overwriting the encode function for Date objects.\n return gen._pushTag(TAG.DATE_EPOCH) && gen.pushAny(Math.round(obj / 1000))\n }\n\n _pushBuffer (gen, obj) {\n return gen._pushInt(obj.length, MT.BYTE_STRING) && gen.push(obj)\n }\n\n _pushNoFilter (gen, obj) {\n return gen._pushBuffer(gen, obj.slice())\n }\n\n _pushRegexp (gen, obj) {\n return gen._pushTag(TAG.REGEXP) && gen.pushAny(obj.source)\n }\n\n _pushSet (gen, obj) {\n if (!gen._pushInt(obj.size, MT.ARRAY)) {\n return false\n }\n for (const x of obj) {\n if (!gen.pushAny(x)) {\n return false\n }\n }\n return true\n }\n\n _pushUrl (gen, obj) {\n return gen._pushTag(TAG.URI) && gen.pushAny(obj.format())\n }\n\n _pushBigint (obj) {\n let tag = TAG.POS_BIGINT\n if (obj.isNegative()) {\n obj = obj.negated().minus(1)\n tag = TAG.NEG_BIGINT\n }\n let str = obj.toString(16)\n if (str.length % 2) {\n str = '0' + str\n }\n const buf = Buffer.from(str, 'hex')\n return this._pushTag(tag) && this._pushBuffer(this, buf)\n }\n\n _pushBigNumber (gen, obj) {\n if (obj.isNaN()) {\n return gen._pushNaN()\n }\n if (!obj.isFinite()) {\n return gen._pushInfinity(obj.isNegative() ? -Infinity : Infinity)\n }\n if (obj.isInteger()) {\n return gen._pushBigint(obj)\n }\n if (!(gen._pushTag(TAG.DECIMAL_FRAC) &&\n gen._pushInt(2, MT.ARRAY))) {\n return false\n }\n\n const dec = obj.decimalPlaces()\n const slide = obj.multipliedBy(new Bignumber(10).pow(dec))\n if (!gen._pushIntNum(-dec)) {\n return false\n }\n if (slide.abs().isLessThan(MAXINT_BN)) {\n return gen._pushIntNum(slide.toNumber())\n } else {\n return gen._pushBigint(slide)\n }\n }\n\n _pushMap (gen, obj) {\n if (!gen._pushInt(obj.size, MT.MAP)) {\n return false\n }\n\n return this._pushRawMap(\n obj.size,\n Array.from(obj)\n )\n }\n\n _pushObject (obj) {\n if (!obj) {\n return this._pushUInt8(NULL)\n }\n\n var len = this.semanticTypes.length\n for (var i = 0; i < len; i++) {\n if (obj instanceof this.semanticTypes[i][0]) {\n return this.semanticTypes[i][1].call(obj, this, obj)\n }\n }\n\n var f = obj.encodeCBOR\n if (typeof f === 'function') {\n return f.call(obj, this)\n }\n\n var keys = Object.keys(obj)\n var keyLength = keys.length\n if (!this._pushInt(keyLength, MT.MAP)) {\n return false\n }\n\n return this._pushRawMap(\n keyLength,\n keys.map((k) => [k, obj[k]])\n )\n }\n\n _pushRawMap (len, map) {\n // Sort keys for canoncialization\n // 1. encode key\n // 2. shorter key comes before longer key\n // 3. same length keys are sorted with lower\n // byte value before higher\n\n map = map.map(function (a) {\n a[0] = Encoder.encode(a[0])\n return a\n }).sort(utils.keySorter)\n\n for (var j = 0; j < len; j++) {\n if (!this.push(map[j][0])) {\n return false\n }\n\n if (!this.pushAny(map[j][1])) {\n return false\n }\n }\n\n return true\n }\n\n /**\n * Alias for `.pushAny`\n *\n * @param {*} obj\n * @returns {boolean} true on success\n */\n write (obj) {\n return this.pushAny(obj)\n }\n\n /**\n * Push any supported type onto the encoded stream\n *\n * @param {any} obj\n * @returns {boolean} true on success\n */\n pushAny (obj) {\n var typ = toType(obj)\n\n switch (typ) {\n case 'Number':\n return this._pushNumber(obj)\n case 'String':\n return this._pushString(obj)\n case 'Boolean':\n return this._pushBoolean(obj)\n case 'Object':\n return this._pushObject(obj)\n case 'Array':\n return this._pushArray(this, obj)\n case 'Uint8Array':\n return this._pushBuffer(this, Buffer.isBuffer(obj) ? obj : Buffer.from(obj))\n case 'Null':\n return this._pushUInt8(NULL)\n case 'Undefined':\n return this._pushUndefined(obj)\n case 'Map':\n return this._pushMap(this, obj)\n case 'Set':\n return this._pushSet(this, obj)\n case 'URL':\n return this._pushUrl(this, obj)\n case 'BigNumber':\n return this._pushBigNumber(this, obj)\n case 'Date':\n return this._pushDate(this, obj)\n case 'RegExp':\n return this._pushRegexp(this, obj)\n case 'Symbol':\n switch (obj) {\n case SYMS.NULL:\n return this._pushObject(null)\n case SYMS.UNDEFINED:\n return this._pushUndefined(undefined)\n // TODO: Add pluggable support for other symbols\n default:\n throw new Error('Unknown symbol: ' + obj.toString())\n }\n default:\n throw new Error('Unknown type: ' + typeof obj + ', ' + (obj ? obj.toString() : ''))\n }\n }\n\n finalize () {\n if (this.offset === 0) {\n return null\n }\n\n var result = this.result\n var resultLength = this.resultLength\n var resultMethod = this.resultMethod\n var offset = this.offset\n\n // Determine the size of the buffer\n var size = 0\n var i = 0\n\n for (; i < offset; i++) {\n size += resultLength[i]\n }\n\n var res = Buffer.allocUnsafe(size)\n var index = 0\n var length = 0\n\n // Write the content into the result buffer\n for (i = 0; i < offset; i++) {\n length = resultLength[i]\n\n switch (resultMethod[i]) {\n case 0:\n result[i].copy(res, index)\n break\n case 1:\n res.writeUInt8(result[i], index, true)\n break\n case 2:\n res.writeUInt16BE(result[i], index, true)\n break\n case 3:\n res.writeUInt32BE(result[i], index, true)\n break\n case 4:\n res.writeDoubleBE(result[i], index, true)\n break\n case 5:\n res.write(result[i], index, length, 'utf8')\n break\n default:\n throw new Error('unkown method')\n }\n\n index += length\n }\n\n var tmp = res\n\n this._reset()\n\n return tmp\n }\n\n _reset () {\n this.result = []\n this.resultMethod = []\n this.resultLength = []\n this.offset = 0\n }\n\n /**\n * Encode the given value\n * @param {*} o\n * @returns {Buffer}\n */\n static encode (o) {\n const enc = new Encoder()\n const ret = enc.pushAny(o)\n if (!ret) {\n throw new Error('Failed to encode input')\n }\n\n return enc.finalize()\n }\n}\n\nmodule.exports = Encoder\n","'use strict'\n\n// exports.Commented = require('./commented')\nexports.Diagnose = require('./diagnose')\nexports.Decoder = require('./decoder')\nexports.Encoder = require('./encoder')\nexports.Simple = require('./simple')\nexports.Tagged = require('./tagged')\n\n// exports.comment = exports.Commented.comment\nexports.decodeAll = exports.Decoder.decodeAll\nexports.decodeFirst = exports.Decoder.decodeFirst\nexports.diagnose = exports.Diagnose.diagnose\nexports.encode = exports.Encoder.encode\nexports.decode = exports.Decoder.decode\n\nexports.leveldb = {\n decode: exports.Decoder.decodeAll,\n encode: exports.Encoder.encode,\n buffer: true,\n name: 'cbor'\n}\n","import { lebEncode } from '@dfinity/candid';\nimport borc from 'borc';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { compare, concat, uint8ToBuf } from './utils/buffer';\n/**\n * sha256 hash the provided Buffer\n * @param data - input to hash function\n */\nexport function hash(data) {\n return uint8ToBuf(sha256.create().update(new Uint8Array(data)).digest());\n}\n/**\n *\n * @param value unknown value\n * @returns ArrayBuffer\n */\nexport function hashValue(value) {\n if (value instanceof borc.Tagged) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return hashValue(value.value);\n }\n else if (typeof value === 'string') {\n return hashString(value);\n }\n else if (typeof value === 'number') {\n return hash(lebEncode(value));\n }\n else if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {\n return hash(value);\n }\n else if (Array.isArray(value)) {\n const vals = value.map(hashValue);\n return hash(concat(...vals));\n }\n else if (value && typeof value === 'object' && value._isPrincipal) {\n return hash(value.toUint8Array());\n }\n else if (typeof value === 'object' &&\n value !== null &&\n typeof value.toHash === 'function') {\n return hashValue(value.toHash());\n // TODO This should be move to a specific async method as the webauthn flow required\n // the flow to be synchronous to ensure Safari touch id works.\n // } else if (value instanceof Promise) {\n // return value.then(x => hashValue(x));\n }\n else if (typeof value === 'object') {\n return hashOfMap(value);\n }\n else if (typeof value === 'bigint') {\n // Do this check much later than the other bigint check because this one is much less\n // type-safe.\n // So we want to try all the high-assurance type guards before this 'probable' one.\n return hash(lebEncode(value));\n }\n throw Object.assign(new Error(`Attempt to hash a value of unsupported type: ${value}`), {\n // include so logs/callers can understand the confusing value.\n // (when stringified in error message, prototype info is lost)\n value,\n });\n}\nconst hashString = (value) => {\n const encoded = new TextEncoder().encode(value);\n return hash(encoded);\n};\n/**\n * Get the RequestId of the provided ic-ref request.\n * RequestId is the result of the representation-independent-hash function.\n * https://sdk.dfinity.org/docs/interface-spec/index.html#hash-of-map\n * @param request - ic-ref request to hash into RequestId\n */\nexport function requestIdOf(request) {\n return hashOfMap(request);\n}\n/**\n * Hash a map into an ArrayBuffer using the representation-independent-hash function.\n * https://sdk.dfinity.org/docs/interface-spec/index.html#hash-of-map\n * @param map - Any non-nested object\n * @returns ArrayBuffer\n */\nexport function hashOfMap(map) {\n const hashed = Object.entries(map)\n .filter(([, value]) => value !== undefined)\n .map(([key, value]) => {\n const hashedKey = hashString(key);\n const hashedValue = hashValue(value);\n return [hashedKey, hashedValue];\n });\n const traversed = hashed;\n const sorted = traversed.sort(([k1], [k2]) => {\n return compare(k1, k2);\n });\n const concatenated = concat(...sorted.map(x => concat(...x)));\n const result = hash(concatenated);\n return result;\n}\n//# sourceMappingURL=request_id.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { Principal } from '@dfinity/principal';\nimport { requestIdOf } from './request_id';\nimport { concat, toHex } from './utils/buffer';\nconst domainSeparator = new TextEncoder().encode('\\x0Aic-request');\n/**\n * An Identity that can sign blobs.\n */\nexport class SignIdentity {\n /**\n * Get the principal represented by this identity. Normally should be a\n * `Principal.selfAuthenticating()`.\n */\n getPrincipal() {\n if (!this._principal) {\n this._principal = Principal.selfAuthenticating(new Uint8Array(this.getPublicKey().toDer()));\n }\n return this._principal;\n }\n /**\n * Transform a request into a signed version of the request. This is done last\n * after the transforms on the body of a request. The returned object can be\n * anything, but must be serializable to CBOR.\n * @param request - internet computer request to transform\n */\n async transformRequest(request) {\n const { body } = request, fields = __rest(request, [\"body\"]);\n const requestId = requestIdOf(body);\n return Object.assign(Object.assign({}, fields), { body: {\n content: body,\n sender_pubkey: this.getPublicKey().toDer(),\n sender_sig: await this.sign(concat(domainSeparator, requestId)),\n } });\n }\n}\nexport class AnonymousIdentity {\n getPrincipal() {\n return Principal.anonymous();\n }\n async transformRequest(request) {\n return Object.assign(Object.assign({}, request), { body: { content: request.body } });\n }\n}\n/**\n * Create an IdentityDescriptor from a @dfinity/identity Identity\n * @param identity - identity describe in returned descriptor\n */\nexport function createIdentityDescriptor(identity) {\n const identityIndicator = 'getPublicKey' in identity\n ? { type: 'PublicKeyIdentity', publicKey: toHex(identity.getPublicKey().toDer()) }\n : { type: 'AnonymousIdentity' };\n return identityIndicator;\n}\n//# sourceMappingURL=auth.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst MAX_U64_NUMBER = 0x20000000000000;\nfunction _concat(a, ...args) {\n const newBuffer = new Uint8Array(a.byteLength + args.reduce((acc, b) => acc + b.byteLength, 0));\n newBuffer.set(new Uint8Array(a), 0);\n let i = a.byteLength;\n for (const b of args) {\n newBuffer.set(new Uint8Array(b), i);\n i += b.byteLength;\n }\n return newBuffer.buffer;\n}\nfunction _serializeValue(major, minor, value) {\n // Remove everything that's not an hexadecimal character. These are not\n // considered errors since the value was already validated and they might\n // be number decimals or sign.\n value = value.replace(/[^0-9a-fA-F]/g, \"\");\n // Create the buffer from the value with left padding with 0.\n const length = 2 ** (minor - 24 /* Int8 */);\n value = value.slice(-length * 2).padStart(length * 2, \"0\");\n const bytes = [(major << 5) + minor].concat(value.match(/../g).map((byte) => parseInt(byte, 16)));\n return new Uint8Array(bytes).buffer;\n}\nfunction _serializeNumber(major, value) {\n if (value < 24) {\n return new Uint8Array([(major << 5) + value]).buffer;\n }\n else {\n const minor = value <= 0xff\n ? 24 /* Int8 */\n : value <= 0xffff\n ? 25 /* Int16 */\n : value <= 0xffffffff\n ? 26 /* Int32 */\n : 27 /* Int64 */;\n return _serializeValue(major, minor, value.toString(16));\n }\n}\nfunction _serializeString(str) {\n const utf8 = [];\n for (let i = 0; i < str.length; i++) {\n let charcode = str.charCodeAt(i);\n if (charcode < 0x80) {\n utf8.push(charcode);\n }\n else if (charcode < 0x800) {\n utf8.push(0xc0 | (charcode >> 6), 0x80 | (charcode & 0x3f));\n }\n else if (charcode < 0xd800 || charcode >= 0xe000) {\n utf8.push(0xe0 | (charcode >> 12), 0x80 | ((charcode >> 6) & 0x3f), 0x80 | (charcode & 0x3f));\n }\n else {\n // Surrogate pair\n i++;\n charcode = ((charcode & 0x3ff) << 10) | (str.charCodeAt(i) & 0x3ff);\n utf8.push(0xf0 | (charcode >> 18), 0x80 | ((charcode >> 12) & 0x3f), 0x80 | ((charcode >> 6) & 0x3f), 0x80 | (charcode & 0x3f));\n }\n }\n return _concat(new Uint8Array(_serializeNumber(3 /* TextString */, str.length)), new Uint8Array(utf8));\n}\n/**\n * Tag a value.\n */\nfunction tagged(tag, value) {\n if (tag == 0xd9d9f7) {\n return _concat(new Uint8Array([0xd9, 0xd9, 0xf7]), value);\n }\n if (tag < 24) {\n return _concat(new Uint8Array([(6 /* Tag */ << 5) + tag]), value);\n }\n else {\n const minor = tag <= 0xff\n ? 24 /* Int8 */\n : tag <= 0xffff\n ? 25 /* Int16 */\n : tag <= 0xffffffff\n ? 26 /* Int32 */\n : 27 /* Int64 */;\n const length = 2 ** (minor - 24 /* Int8 */);\n const value = tag\n .toString(16)\n .slice(-length * 2)\n .padStart(length * 2, \"0\");\n const bytes = [(6 /* Tag */ << 5) + minor].concat(value.match(/../g).map((byte) => parseInt(byte, 16)));\n return new Uint8Array(bytes).buffer;\n }\n}\nexports.tagged = tagged;\n/**\n * Set the raw bytes contained by this value. This should only be used with another\n * CborValue, or if you are implementing extensions to CBOR.\n * @param bytes A buffer containing the value.\n */\nfunction raw(bytes) {\n return new Uint8Array(bytes).buffer;\n}\nexports.raw = raw;\n/**\n * Encode a number that is between [0, 23].\n * @param n\n */\nfunction uSmall(n) {\n if (isNaN(n)) {\n throw new RangeError(\"Invalid number.\");\n }\n n = Math.min(Math.max(0, n), 23); // Clamp it.\n const bytes = [(0 /* UnsignedInteger */ << 5) + n];\n return new Uint8Array(bytes).buffer;\n}\nexports.uSmall = uSmall;\nfunction u8(u8, radix) {\n // Force u8 into a number, and validate it.\n u8 = parseInt(\"\" + u8, radix);\n if (isNaN(u8)) {\n throw new RangeError(\"Invalid number.\");\n }\n u8 = Math.min(Math.max(0, u8), 0xff); // Clamp it.\n u8 = u8.toString(16);\n return _serializeValue(0 /* UnsignedInteger */, 24 /* Int8 */, u8);\n}\nexports.u8 = u8;\nfunction u16(u16, radix) {\n // Force u16 into a number, and validate it.\n u16 = parseInt(\"\" + u16, radix);\n if (isNaN(u16)) {\n throw new RangeError(\"Invalid number.\");\n }\n u16 = Math.min(Math.max(0, u16), 0xffff); // Clamp it.\n u16 = u16.toString(16);\n return _serializeValue(0 /* UnsignedInteger */, 25 /* Int16 */, u16);\n}\nexports.u16 = u16;\nfunction u32(u32, radix) {\n // Force u32 into a number, and validate it.\n u32 = parseInt(\"\" + u32, radix);\n if (isNaN(u32)) {\n throw new RangeError(\"Invalid number.\");\n }\n u32 = Math.min(Math.max(0, u32), 0xffffffff); // Clamp it.\n u32 = u32.toString(16);\n return _serializeValue(0 /* UnsignedInteger */, 26 /* Int32 */, u32);\n}\nexports.u32 = u32;\nfunction u64(u64, radix) {\n // Special consideration for numbers that might be larger than expected.\n if (typeof u64 == \"string\" && radix == 16) {\n // This is the only case where we guarantee we'll encode the number directly.\n // Validate it's all hexadecimal first.\n if (u64.match(/[^0-9a-fA-F]/)) {\n throw new RangeError(\"Invalid number.\");\n }\n return _serializeValue(0 /* UnsignedInteger */, 27 /* Int64 */, u64);\n }\n // Force u64 into a number, and validate it.\n u64 = parseInt(\"\" + u64, radix);\n if (isNaN(u64)) {\n throw new RangeError(\"Invalid number.\");\n }\n u64 = Math.min(Math.max(0, u64), MAX_U64_NUMBER); // Clamp it to actual limit.\n u64 = u64.toString(16);\n return _serializeValue(0 /* UnsignedInteger */, 27 /* Int64 */, u64);\n}\nexports.u64 = u64;\n/**\n * Encode a negative number that is between [-24, -1].\n */\nfunction iSmall(n) {\n if (isNaN(n)) {\n throw new RangeError(\"Invalid number.\");\n }\n if (n === 0) {\n return uSmall(0);\n }\n // Negative n, clamped to [1, 24], minus 1 (there's no negative 0).\n n = Math.min(Math.max(0, -n), 24) - 1;\n const bytes = [(1 /* SignedInteger */ << 5) + n];\n return new Uint8Array(bytes).buffer;\n}\nexports.iSmall = iSmall;\nfunction i8(i8, radix) {\n // Force i8 into a number, and validate it.\n i8 = parseInt(\"\" + i8, radix);\n if (isNaN(i8)) {\n throw new RangeError(\"Invalid number.\");\n }\n // Negative n, clamped, minus 1 (there's no negative 0).\n i8 = Math.min(Math.max(0, -i8 - 1), 0xff);\n i8 = i8.toString(16);\n return _serializeValue(1 /* SignedInteger */, 24 /* Int8 */, i8);\n}\nexports.i8 = i8;\nfunction i16(i16, radix) {\n // Force i16 into a number, and validate it.\n i16 = parseInt(\"\" + i16, radix);\n if (isNaN(i16)) {\n throw new RangeError(\"Invalid number.\");\n }\n // Negative n, clamped, minus 1 (there's no negative 0).\n i16 = Math.min(Math.max(0, -i16 - 1), 0xffff);\n i16 = i16.toString(16);\n return _serializeValue(1 /* SignedInteger */, 25 /* Int16 */, i16);\n}\nexports.i16 = i16;\nfunction i32(i32, radix) {\n // Force i32 into a number, and validate it.\n i32 = parseInt(\"\" + i32, radix);\n if (isNaN(i32)) {\n throw new RangeError(\"Invalid number.\");\n }\n // Negative n, clamped, minus 1 (there's no negative 0).\n i32 = Math.min(Math.max(0, -i32 - 1), 0xffffffff);\n i32 = i32.toString(16);\n return _serializeValue(1 /* SignedInteger */, 26 /* Int32 */, i32);\n}\nexports.i32 = i32;\nfunction i64(i64, radix) {\n // Special consideration for numbers that might be larger than expected.\n if (typeof i64 == \"string\" && radix == 16) {\n if (i64.startsWith(\"-\")) {\n i64 = i64.slice(1);\n }\n else {\n // Clamp it.\n i64 = \"0\";\n }\n // This is the only case where we guarantee we'll encode the number directly.\n // Validate it's all hexadecimal first.\n if (i64.match(/[^0-9a-fA-F]/) || i64.length > 16) {\n throw new RangeError(\"Invalid number.\");\n }\n // We need to do -1 to the number.\n let done = false;\n let newI64 = i64.split(\"\").reduceRight((acc, x) => {\n if (done) {\n return x + acc;\n }\n let n = parseInt(x, 16) - 1;\n if (n >= 0) {\n done = true;\n return n.toString(16) + acc;\n }\n else {\n return \"f\" + acc;\n }\n }, \"\");\n if (!done) {\n // This number was 0.\n return u64(0);\n }\n return _serializeValue(1 /* SignedInteger */, 27 /* Int64 */, newI64);\n }\n // Force i64 into a number, and validate it.\n i64 = parseInt(\"\" + i64, radix);\n if (isNaN(i64)) {\n throw new RangeError(\"Invalid number.\");\n }\n i64 = Math.min(Math.max(0, -i64 - 1), 0x20000000000000); // Clamp it to actual.\n i64 = i64.toString(16);\n return _serializeValue(1 /* SignedInteger */, 27 /* Int64 */, i64);\n}\nexports.i64 = i64;\n/**\n * Encode a number using the smallest amount of bytes, by calling the methods\n * above. e.g. If the number fits in a u8, it will use that.\n */\nfunction number(n) {\n if (n >= 0) {\n if (n < 24) {\n return uSmall(n);\n }\n else if (n <= 0xff) {\n return u8(n);\n }\n else if (n <= 0xffff) {\n return u16(n);\n }\n else if (n <= 0xffffffff) {\n return u32(n);\n }\n else {\n return u64(n);\n }\n }\n else {\n if (n >= -24) {\n return iSmall(n);\n }\n else if (n >= -0xff) {\n return i8(n);\n }\n else if (n >= -0xffff) {\n return i16(n);\n }\n else if (n >= -0xffffffff) {\n return i32(n);\n }\n else {\n return i64(n);\n }\n }\n}\nexports.number = number;\n/**\n * Encode a byte array. This is different than the `raw()` method.\n */\nfunction bytes(bytes) {\n return _concat(_serializeNumber(2 /* ByteString */, bytes.byteLength), bytes);\n}\nexports.bytes = bytes;\n/**\n * Encode a JavaScript string.\n */\nfunction string(str) {\n return _serializeString(str);\n}\nexports.string = string;\n/**\n * Encode an array of cbor values.\n */\nfunction array(items) {\n return _concat(_serializeNumber(4 /* Array */, items.length), ...items);\n}\nexports.array = array;\n/**\n * Encode a map of key-value pairs. The keys are string, and the values are CBOR\n * encoded.\n */\nfunction map(items, stable = false) {\n if (!(items instanceof Map)) {\n items = new Map(Object.entries(items));\n }\n let entries = Array.from(items.entries());\n if (stable) {\n entries = entries.sort(([keyA], [keyB]) => keyA.localeCompare(keyB));\n }\n return _concat(_serializeNumber(5 /* Map */, items.size), ...entries.map(([k, v]) => _concat(_serializeString(k), v)));\n}\nexports.map = map;\n/**\n * Encode a single (32 bits) precision floating point number.\n */\nfunction singleFloat(f) {\n const single = new Float32Array([f]);\n return _concat(new Uint8Array([(7 /* SimpleValue */ << 5) + 26]), new Uint8Array(single.buffer));\n}\nexports.singleFloat = singleFloat;\n/**\n * Encode a double (64 bits) precision floating point number.\n */\nfunction doubleFloat(f) {\n const single = new Float64Array([f]);\n return _concat(new Uint8Array([(7 /* SimpleValue */ << 5) + 27]), new Uint8Array(single.buffer));\n}\nexports.doubleFloat = doubleFloat;\nfunction bool(v) {\n return v ? true_() : false_();\n}\nexports.bool = bool;\n/**\n * Encode the boolean true.\n */\nfunction true_() {\n return raw(new Uint8Array([(7 /* SimpleValue */ << 5) + 21]));\n}\nexports.true_ = true_;\n/**\n * Encode the boolean false.\n */\nfunction false_() {\n return raw(new Uint8Array([(7 /* SimpleValue */ << 5) + 20]));\n}\nexports.false_ = false_;\n/**\n * Encode the constant null.\n */\nfunction null_() {\n return raw(new Uint8Array([(7 /* SimpleValue */ << 5) + 22]));\n}\nexports.null_ = null_;\n/**\n * Encode the constant undefined.\n */\nfunction undefined_() {\n return raw(new Uint8Array([(7 /* SimpleValue */ << 5) + 23]));\n}\nexports.undefined_ = undefined_;\n//# sourceMappingURL=value.js.map","\"use strict\";\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst cbor = __importStar(require(\"./value\"));\nconst BufferClasses = [\n ArrayBuffer,\n Uint8Array,\n Uint16Array,\n Uint32Array,\n Int8Array,\n Int16Array,\n Int32Array,\n Float32Array,\n Float64Array,\n];\nclass JsonDefaultCborEncoder {\n // @param _serializer The CBOR Serializer to use.\n // @param _stable Whether or not keys from objects should be sorted (stable). This is\n // particularly useful when testing encodings between JSON objects.\n constructor(_serializer, _stable = false) {\n this._serializer = _serializer;\n this._stable = _stable;\n this.name = \"jsonDefault\";\n this.priority = -100;\n }\n match(value) {\n return [\"undefined\", \"boolean\", \"number\", \"string\", \"object\"].indexOf(typeof value) != -1;\n }\n encode(value) {\n switch (typeof value) {\n case \"undefined\":\n return cbor.undefined_();\n case \"boolean\":\n return cbor.bool(value);\n case \"number\":\n if (Math.floor(value) === value) {\n return cbor.number(value);\n }\n else {\n return cbor.doubleFloat(value);\n }\n case \"string\":\n return cbor.string(value);\n case \"object\":\n if (value === null) {\n return cbor.null_();\n }\n else if (Array.isArray(value)) {\n return cbor.array(value.map((x) => this._serializer.serializeValue(x)));\n }\n else if (BufferClasses.find((x) => value instanceof x)) {\n return cbor.bytes(value.buffer);\n }\n else if (Object.getOwnPropertyNames(value).indexOf(\"toJSON\") !== -1) {\n return this.encode(value.toJSON());\n }\n else if (value instanceof Map) {\n const m = new Map();\n for (const [key, item] of value.entries()) {\n m.set(key, this._serializer.serializeValue(item));\n }\n return cbor.map(m, this._stable);\n }\n else {\n const m = new Map();\n for (const [key, item] of Object.entries(value)) {\n m.set(key, this._serializer.serializeValue(item));\n }\n return cbor.map(m, this._stable);\n }\n default:\n throw new Error(\"Invalid value.\");\n }\n }\n}\nexports.JsonDefaultCborEncoder = JsonDefaultCborEncoder;\nclass ToCborEncoder {\n constructor() {\n this.name = \"cborEncoder\";\n this.priority = -90;\n }\n match(value) {\n return typeof value == \"object\" && typeof value[\"toCBOR\"] == \"function\";\n }\n encode(value) {\n return value.toCBOR();\n }\n}\nexports.ToCborEncoder = ToCborEncoder;\nclass CborSerializer {\n constructor() {\n this._encoders = new Set();\n }\n static withDefaultEncoders(stable = false) {\n const s = new this();\n s.addEncoder(new JsonDefaultCborEncoder(s, stable));\n s.addEncoder(new ToCborEncoder());\n return s;\n }\n removeEncoder(name) {\n // Has to make an extra call to values() to ensure it doesn't break on iteration.\n for (const encoder of this._encoders.values()) {\n if (encoder.name == name) {\n this._encoders.delete(encoder);\n }\n }\n }\n addEncoder(encoder) {\n this._encoders.add(encoder);\n }\n getEncoderFor(value) {\n let chosenEncoder = null;\n for (const encoder of this._encoders) {\n if (!chosenEncoder || encoder.priority > chosenEncoder.priority) {\n if (encoder.match(value)) {\n chosenEncoder = encoder;\n }\n }\n }\n if (chosenEncoder === null) {\n throw new Error(\"Could not find an encoder for value.\");\n }\n return chosenEncoder;\n }\n serializeValue(value) {\n return this.getEncoderFor(value).encode(value);\n }\n serialize(value) {\n return this.serializeValue(value);\n }\n}\nexports.CborSerializer = CborSerializer;\nclass SelfDescribeCborSerializer extends CborSerializer {\n serialize(value) {\n return cbor.raw(new Uint8Array([\n // Self describe CBOR.\n ...new Uint8Array([0xd9, 0xd9, 0xf7]),\n ...new Uint8Array(super.serializeValue(value)),\n ]));\n }\n}\nexports.SelfDescribeCborSerializer = SelfDescribeCborSerializer;\n//# sourceMappingURL=serializer.js.map","\"use strict\";\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__export(require(\"./serializer\"));\nconst value = __importStar(require(\"./value\"));\nexports.value = value;\n//# sourceMappingURL=index.js.map","// This file is based on:\n// https://github.com/dfinity-lab/dfinity/blob/9bca65f8edd65701ea6bdb00e0752f9186bbc893/docs/spec/public/index.adoc#cbor-encoding-of-requests-and-responses\nimport borc from 'borc';\nimport * as cbor from 'simple-cbor';\nimport { SelfDescribeCborSerializer } from 'simple-cbor';\nimport { concat, fromHex, toHex } from './utils/buffer';\n// We are using hansl/simple-cbor for CBOR serialization, to avoid issues with\n// encoding the uint64 values that the HTTP handler of the client expects for\n// canister IDs. However, simple-cbor does not yet provide deserialization so\n// we are using `Uint8Array` so that we can use the dignifiedquire/borc CBOR\n// decoder.\nclass PrincipalEncoder {\n get name() {\n return 'Principal';\n }\n get priority() {\n return 0;\n }\n match(value) {\n return value && value._isPrincipal === true;\n }\n encode(v) {\n return cbor.value.bytes(v.toUint8Array());\n }\n}\nclass BufferEncoder {\n get name() {\n return 'Buffer';\n }\n get priority() {\n return 1;\n }\n match(value) {\n return value instanceof ArrayBuffer || ArrayBuffer.isView(value);\n }\n encode(v) {\n return cbor.value.bytes(new Uint8Array(v));\n }\n}\nclass BigIntEncoder {\n get name() {\n return 'BigInt';\n }\n get priority() {\n return 1;\n }\n match(value) {\n return typeof value === `bigint`;\n }\n encode(v) {\n // Always use a bigint encoding.\n if (v > BigInt(0)) {\n return cbor.value.tagged(2, cbor.value.bytes(fromHex(v.toString(16))));\n }\n else {\n return cbor.value.tagged(3, cbor.value.bytes(fromHex((BigInt('-1') * v).toString(16))));\n }\n }\n}\nconst serializer = SelfDescribeCborSerializer.withDefaultEncoders(true);\nserializer.addEncoder(new PrincipalEncoder());\nserializer.addEncoder(new BufferEncoder());\nserializer.addEncoder(new BigIntEncoder());\nexport var CborTag;\n(function (CborTag) {\n CborTag[CborTag[\"Uint64LittleEndian\"] = 71] = \"Uint64LittleEndian\";\n CborTag[CborTag[\"Semantic\"] = 55799] = \"Semantic\";\n})(CborTag || (CborTag = {}));\n/**\n * Encode a JavaScript value into CBOR.\n */\nexport function encode(value) {\n return serializer.serialize(value);\n}\nfunction decodePositiveBigInt(buf) {\n const len = buf.byteLength;\n let res = BigInt(0);\n for (let i = 0; i < len; i++) {\n res = res * BigInt(0x100) + BigInt(buf[i]);\n }\n return res;\n}\n// A BORC subclass that decodes byte strings to ArrayBuffer instead of the Buffer class.\nclass Uint8ArrayDecoder extends borc.Decoder {\n createByteString(raw) {\n return concat(...raw);\n }\n createByteStringFromHeap(start, end) {\n if (start === end) {\n return new ArrayBuffer(0);\n }\n return new Uint8Array(this._heap.slice(start, end));\n }\n}\nexport function decode(input) {\n const buffer = new Uint8Array(input);\n const decoder = new Uint8ArrayDecoder({\n size: buffer.byteLength,\n tags: {\n // Override tags 2 and 3 for BigInt support (borc supports only BigNumber).\n 2: val => decodePositiveBigInt(val),\n 3: val => -decodePositiveBigInt(val),\n [CborTag.Semantic]: (value) => value,\n },\n });\n try {\n return decoder.decodeFirst(buffer);\n }\n catch (e) {\n throw new Error(`Failed to decode CBOR: ${e}, input: ${toHex(buffer)}`);\n }\n}\n//# sourceMappingURL=cbor.js.map","import { randomNumber } from '../../utils/random';\n// The types of values allowed in the `request_type` field for submit requests.\nexport var SubmitRequestType;\n(function (SubmitRequestType) {\n SubmitRequestType[\"Call\"] = \"call\";\n})(SubmitRequestType || (SubmitRequestType = {}));\n/**\n * Create a random Nonce, based on random values\n */\nexport function makeNonce() {\n // Encode 128 bits.\n const buffer = new ArrayBuffer(16);\n const view = new DataView(buffer);\n const rand1 = randomNumber();\n const rand2 = randomNumber();\n const rand3 = randomNumber();\n const rand4 = randomNumber();\n view.setUint32(0, rand1);\n view.setUint32(4, rand2);\n view.setUint32(8, rand3);\n view.setUint32(12, rand4);\n return buffer;\n}\n//# sourceMappingURL=types.js.map","import { lebEncode } from '@dfinity/candid';\nimport * as cbor from 'simple-cbor';\nimport { makeNonce, } from './types';\nconst NANOSECONDS_PER_MILLISECONDS = BigInt(1000000);\nconst REPLICA_PERMITTED_DRIFT_MILLISECONDS = 60 * 1000;\nexport class Expiry {\n constructor(deltaInMSec) {\n // if ingress as seconds is less than 90, round to nearest second\n if (deltaInMSec < 90 * 1000) {\n // Raw value without subtraction of REPLICA_PERMITTED_DRIFT_MILLISECONDS\n const raw_value = BigInt(Date.now() + deltaInMSec) * NANOSECONDS_PER_MILLISECONDS;\n const ingress_as_seconds = raw_value / BigInt(1000000000);\n this._value = ingress_as_seconds * BigInt(1000000000);\n return;\n }\n // Use bigint because it can overflow the maximum number allowed in a double float.\n const raw_value = BigInt(Math.floor(Date.now() + deltaInMSec - REPLICA_PERMITTED_DRIFT_MILLISECONDS)) *\n NANOSECONDS_PER_MILLISECONDS;\n // round down to the nearest second (since )\n const ingress_as_seconds = raw_value / BigInt(1000000000);\n // round down to nearest minute\n const ingress_as_minutes = ingress_as_seconds / BigInt(60);\n const rounded_down_nanos = ingress_as_minutes * BigInt(60) * BigInt(1000000000);\n this._value = rounded_down_nanos;\n }\n toCBOR() {\n // TODO: change this to take the minimum amount of space (it always takes 8 bytes now).\n return cbor.value.u64(this._value.toString(16), 16);\n }\n toHash() {\n return lebEncode(this._value);\n }\n}\n/**\n * Create a Nonce transform, which takes a function that returns a Buffer, and adds it\n * as the nonce to every call requests.\n * @param nonceFn A function that returns a buffer. By default uses a semi-random method.\n */\nexport function makeNonceTransform(nonceFn = makeNonce) {\n return async (request) => {\n // Nonce needs to be inserted into the header for all requests, to enable logs to be correlated with requests.\n const headers = request.request.headers;\n // TODO: uncomment this when the http proxy supports it.\n // headers.set('X-IC-Request-ID', toHex(new Uint8Array(nonce)));\n request.request.headers = headers;\n // Nonce only needs to be inserted into the body for async calls, to prevent replay attacks.\n if (request.endpoint === \"call\" /* Endpoint.Call */) {\n request.body.nonce = nonceFn();\n }\n };\n}\n/**\n * Create a transform that adds a delay (by default 5 minutes) to the expiry.\n *\n * @param delayInMilliseconds The delay to add to the call time, in milliseconds.\n */\nexport function makeExpiryTransform(delayInMilliseconds) {\n return async (request) => {\n request.body.ingress_expiry = new Expiry(delayInMilliseconds);\n };\n}\n/**\n * Maps the default fetch headers field to the serializable HttpHeaderField.\n *\n * @param headers Fetch definition of the headers type\n * @returns array of header fields\n */\nexport function httpHeadersTransform(headers) {\n const headerFields = [];\n headers.forEach((value, key) => {\n headerFields.push([key, value]);\n });\n return headerFields;\n}\n//# sourceMappingURL=transforms.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nexport function abytes(item) {\n if (!isBytes(item))\n throw new Error('Uint8Array expected');\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\nexport function numberToHexUnpadded(num) {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n abytes(bytes);\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n) {\n return hexToBytes(numberToHexUnpadded(n));\n}\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title, hex, expectedLength) {\n let res;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n }\n catch (e) {\n throw new Error(`${title} must be valid hex string, got \"${hex}\". Cause: ${e}`);\n }\n }\n else if (isBytes(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n }\n else {\n throw new Error(`${title} must be hex string or Uint8Array`);\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);\n return res;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1)\n ;\n return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n, pos) {\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n, pos, value) {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;\n// DRBG\nconst u8n = (data) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr) => Uint8Array.from(arr); // another shortcut\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n if (typeof hashLen !== 'number' || hashLen < 2)\n throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2)\n throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function')\n throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000)\n throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen())))\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n// Validating curves and fields\nconst validatorFns = {\n bigint: (val) => typeof val === 'bigint',\n function: (val) => typeof val === 'function',\n boolean: (val) => typeof val === 'boolean',\n string: (val) => typeof val === 'string',\n stringOrUint8Array: (val) => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val) => Number.isSafeInteger(val),\n array: (val) => Array.isArray(val),\n field: (val, object) => object.Fp.isValid(val),\n hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n};\n// type Record = { [P in K]: T; }\nexport function validateObject(object, validators, optValidators = {}) {\n const checkField = (fieldName, type, isOptional) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error(`Invalid validator \"${type}\", expected function`);\n const val = object[fieldName];\n if (isOptional && val === undefined)\n return;\n if (!checkVal(val, object)) {\n throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);\n }\n };\n for (const [fieldName, type] of Object.entries(validators))\n checkField(fieldName, type, false);\n for (const [fieldName, type] of Object.entries(optValidators))\n checkField(fieldName, type, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n//# sourceMappingURL=utils.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Utilities for modular arithmetics and finite fields\nimport { bitMask, numberToBytesBE, numberToBytesLE, bytesToNumberBE, bytesToNumberLE, ensureBytes, validateObject, } from './utils.js';\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);\n// prettier-ignore\nconst _9n = BigInt(9), _16n = BigInt(16);\n// Calculates a modulo b\nexport function mod(a, b) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\n// TODO: use field version && remove\nexport function pow(num, power, modulo) {\n if (modulo <= _0n || power < _0n)\n throw new Error('Expected power/modulo > 0');\n if (modulo === _1n)\n return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n)\n res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)\nexport function pow2(x, power, modulo) {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n// Inverses number over modulo\nexport function invert(number, modulo) {\n if (number === _0n || modulo <= _0n) {\n throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n }\n // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) ≡ 1 if a is a square (mod p)\n // (a | p) ≡ -1 if a is not a square (mod p)\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n let Q, S, Z;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++)\n ;\n // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++)\n ;\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast(Fp, n) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))\n throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO))\n return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE))\n break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\nexport function FpSqrt(P) {\n // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.\n // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n // P ≡ 3 (mod 4)\n // √n = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4(Fp, n) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8(Fp, n) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // P ≡ 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\nexport function validateField(field) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n };\n const opts = FIELD_FIELDS.reduce((map, val) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(f, num, power) {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n)\n throw new Error('Expected power > 0');\n if (power === _0n)\n return f.ONE;\n if (power === _1n)\n return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch(f, nums) {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\nexport function FpDiv(f, lhs, rhs) {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(f) {\n const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic\n return (x) => {\n const p = f.pow(x, legendreConst);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n// CURVE.n lengths\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n/**\n * Initializes a finite field over prime. **Non-primes are not supported.**\n * Do not init in loop: slow. Very fragile: always run a benchmark on a change.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER, bitLen, isLE = false, redef = {}) {\n if (ORDER <= _0n)\n throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048)\n throw new Error('Field lengths over 2048 bytes are not supported');\n const sqrtP = FpSqrt(ORDER);\n const f = Object.freeze({\n ORDER,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n inv: (num) => invert(num, ORDER),\n sqrt: redef.sqrt || ((n) => sqrtP(f, n)),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n });\n return Object.freeze(f);\n}\nexport function FpSqrtOdd(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\nexport function FpSqrtEven(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use mapKeyToField instead\n */\nexport function hashToPrivateScalar(hash, groupOrder, isLE = false) {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);\n const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map","import { mod } from './modular.js';\nimport { bytesToNumberBE, abytes, concatBytes, utf8ToBytes, validateObject } from './utils.js';\n// Octet Stream to Integer. \"spec\" implementation of os2ip is 2.5x slower vs bytesToNumberBE.\nconst os2ip = bytesToNumberBE;\n// Integer to Octet Stream (numberToBytesBE)\nfunction i2osp(value, length) {\n if (value < 0 || value >= 1 << (8 * length)) {\n throw new Error(`bad I2OSP call: value=${value} length=${length}`);\n }\n const res = Array.from({ length }).fill(0);\n for (let i = length - 1; i >= 0; i--) {\n res[i] = value & 0xff;\n value >>>= 8;\n }\n return new Uint8Array(res);\n}\nfunction strxor(a, b) {\n const arr = new Uint8Array(a.length);\n for (let i = 0; i < a.length; i++) {\n arr[i] = a[i] ^ b[i];\n }\n return arr;\n}\nfunction anum(item) {\n if (!Number.isSafeInteger(item))\n throw new Error('number expected');\n}\n// Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits\n// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1\nexport function expand_message_xmd(msg, DST, lenInBytes, H) {\n abytes(msg);\n abytes(DST);\n anum(lenInBytes);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n if (DST.length > 255)\n DST = H(concatBytes(utf8ToBytes('H2C-OVERSIZE-DST-'), DST));\n const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;\n const ell = Math.ceil(lenInBytes / b_in_bytes);\n if (ell > 255)\n throw new Error('Invalid xmd length');\n const DST_prime = concatBytes(DST, i2osp(DST.length, 1));\n const Z_pad = i2osp(0, r_in_bytes);\n const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str\n const b = new Array(ell);\n const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));\n b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));\n for (let i = 1; i <= ell; i++) {\n const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];\n b[i] = H(concatBytes(...args));\n }\n const pseudo_random_bytes = concatBytes(...b);\n return pseudo_random_bytes.slice(0, lenInBytes);\n}\n// Produces a uniformly random byte string using an extendable-output function (XOF) H.\n// 1. The collision resistance of H MUST be at least k bits.\n// 2. H MUST be an XOF that has been proved indifferentiable from\n// a random oracle under a reasonable cryptographic assumption.\n// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2\nexport function expand_message_xof(msg, DST, lenInBytes, k, H) {\n abytes(msg);\n abytes(DST);\n anum(lenInBytes);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));\n if (DST.length > 255) {\n const dkLen = Math.ceil((2 * k) / 8);\n DST = H.create({ dkLen }).update(utf8ToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();\n }\n if (lenInBytes > 65535 || DST.length > 255)\n throw new Error('expand_message_xof: invalid lenInBytes');\n return (H.create({ dkLen: lenInBytes })\n .update(msg)\n .update(i2osp(lenInBytes, 2))\n // 2. DST_prime = DST || I2OSP(len(DST), 1)\n .update(DST)\n .update(i2osp(DST.length, 1))\n .digest());\n}\n/**\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F\n * https://www.rfc-editor.org/rfc/rfc9380#section-5.2\n * @param msg a byte string containing the message to hash\n * @param count the number of elements of F to output\n * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above\n * @returns [u_0, ..., u_(count - 1)], a list of field elements.\n */\nexport function hash_to_field(msg, count, options) {\n validateObject(options, {\n DST: 'stringOrUint8Array',\n p: 'bigint',\n m: 'isSafeInteger',\n k: 'isSafeInteger',\n hash: 'hash',\n });\n const { p, k, m, hash, expand, DST: _DST } = options;\n abytes(msg);\n anum(count);\n const DST = typeof _DST === 'string' ? utf8ToBytes(_DST) : _DST;\n const log2p = p.toString(2).length;\n const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above\n const len_in_bytes = count * m * L;\n let prb; // pseudo_random_bytes\n if (expand === 'xmd') {\n prb = expand_message_xmd(msg, DST, len_in_bytes, hash);\n }\n else if (expand === 'xof') {\n prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);\n }\n else if (expand === '_internal_pass') {\n // for internal tests only\n prb = msg;\n }\n else {\n throw new Error('expand must be \"xmd\" or \"xof\"');\n }\n const u = new Array(count);\n for (let i = 0; i < count; i++) {\n const e = new Array(m);\n for (let j = 0; j < m; j++) {\n const elm_offset = L * (j + i * m);\n const tv = prb.subarray(elm_offset, elm_offset + L);\n e[j] = mod(os2ip(tv), p);\n }\n u[i] = e;\n }\n return u;\n}\nexport function isogenyMap(field, map) {\n // Make same order as in spec\n const COEFF = map.map((i) => Array.from(i).reverse());\n return (x, y) => {\n const [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));\n x = field.div(xNum, xDen); // xNum / xDen\n y = field.mul(y, field.div(yNum, yDen)); // y * (yNum / yDev)\n return { x, y };\n };\n}\nexport function createHasher(Point, mapToCurve, def) {\n if (typeof mapToCurve !== 'function')\n throw new Error('mapToCurve() must be defined');\n return {\n // Encodes byte string to elliptic curve.\n // hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3\n hashToCurve(msg, options) {\n const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options });\n const u0 = Point.fromAffine(mapToCurve(u[0]));\n const u1 = Point.fromAffine(mapToCurve(u[1]));\n const P = u0.add(u1).clearCofactor();\n P.assertValidity();\n return P;\n },\n // Encodes byte string to elliptic curve.\n // encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3\n encodeToCurve(msg, options) {\n const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options });\n const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor();\n P.assertValidity();\n return P;\n },\n };\n}\n//# sourceMappingURL=hash-to-curve.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Abelian group utilities\nimport { validateField, nLength } from './modular.js';\nimport { validateObject } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n// Elliptic curve multiplication of Point by scalar. Fragile.\n// Scalars should always be less than curve order: this should be checked inside of a curve itself.\n// Creates precomputation tables for fast multiplication:\n// - private scalar is split by fixed size windows of W bits\n// - every window point is collected from window's table & added to accumulator\n// - since windows are different, same point inside tables won't be accessed more than once per calc\n// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n// - +1 window is neccessary for wNAF\n// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow\n// windows to be in different memory locations\nexport function wNAF(c, bits) {\n const constTimeNegate = (condition, item) => {\n const neg = item.negate();\n return condition ? neg : item;\n };\n const opts = (W) => {\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n };\n return {\n constTimeNegate,\n // non-const time multiplication ladder\n unsafeLadder(elm, n) {\n let p = c.ZERO;\n let d = elm;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm, W) {\n const { windows, windowSize } = opts(W);\n const points = [];\n let p = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W, precomputes, n) {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = opts(W);\n let p = c.ZERO;\n let f = c.BASE;\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n // Shift number by W bits.\n n >>= shiftBy;\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n }\n else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n wNAFCached(P, precomputesMap, n, transform) {\n // @ts-ignore\n const W = P._WINDOW_SIZE || 1;\n // Calculate precomputes on a first run, reuse them after\n let comp = precomputesMap.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W);\n if (W !== 1) {\n precomputesMap.set(P, transform(comp));\n }\n }\n return this.wNAF(W, comp, n);\n },\n };\n}\nexport function validateBasic(curve) {\n validateField(curve.Fp);\n validateObject(curve, {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n }, {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n });\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n });\n}\n//# sourceMappingURL=curve.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Short Weierstrass curve. The formula is: y² = x³ + ax + b\nimport * as mod from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes } from './utils.js';\nimport { wNAF, validateBasic } from './curve.js';\nfunction validatePointOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n a: 'field',\n b: 'field',\n }, {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n });\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');\n }\n if (typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function') {\n throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts });\n}\n// ASN.1 DER encoding utilities\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;\nexport const DER = {\n // asn.1 DER encoding utils\n Err: class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n },\n _parseInt(data) {\n const { Err: E } = DER;\n if (data.length < 2 || data[0] !== 0x02)\n throw new E('Invalid signature integer tag');\n const len = data[1];\n const res = data.subarray(2, len + 2);\n if (!len || res.length !== len)\n throw new E('Invalid signature integer: wrong length');\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n if (res[0] & 0b10000000)\n throw new E('Invalid signature integer: negative');\n if (res[0] === 0x00 && !(res[1] & 0b10000000))\n throw new E('Invalid signature integer: unnecessary leading zero');\n return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left\n },\n toSig(hex) {\n // parse DER signature\n const { Err: E } = DER;\n const data = typeof hex === 'string' ? h2b(hex) : hex;\n ut.abytes(data);\n let l = data.length;\n if (l < 2 || data[0] != 0x30)\n throw new E('Invalid signature tag');\n if (data[1] !== l - 2)\n throw new E('Invalid signature: incorrect length');\n const { d: r, l: sBytes } = DER._parseInt(data.subarray(2));\n const { d: s, l: rBytesLeft } = DER._parseInt(sBytes);\n if (rBytesLeft.length)\n throw new E('Invalid signature: left bytes after parsing');\n return { r, s };\n },\n hexFromSig(sig) {\n // Add leading zero if first byte has negative bit enabled. More details in '_parseInt'\n const slice = (s) => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s);\n const h = (num) => {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n };\n const s = slice(h(sig.s));\n const r = slice(h(sig.r));\n const shl = s.length / 2;\n const rhl = r.length / 2;\n const sl = h(shl);\n const rl = h(rhl);\n return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;\n },\n};\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\nexport function weierstrassPoints(opts) {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n const toBytes = CURVE.toBytes ||\n ((_c, point, _isCompressed) => {\n const a = point.toAffine();\n return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes = CURVE.fromBytes ||\n ((bytes) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula\n * @returns y²\n */\n function weierstrassEquation(x) {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num) {\n return typeof num === 'bigint' && _0n < num && num < CURVE.n;\n }\n function assertGE(num) {\n if (!isWithinCurveOrder(num))\n throw new Error('Expected valid bigint: 0 < bigint < curve.n');\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key) {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (ut.isBytes(key))\n key = ut.bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length))\n throw new Error('Invalid key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n }\n catch (error) {\n throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);\n }\n if (wrapPrivateKey)\n num = mod.mod(num, n); // disabled by default, enabled for BLS\n assertGE(num); // num in range [1..N-1]\n return num;\n }\n const pointPrecomputes = new Map();\n function assertPrjPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ProjectivePoint expected');\n }\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point {\n constructor(px, py, pz) {\n this.px = px;\n this.py = py;\n this.pz = pz;\n if (px == null || !Fp.isValid(px))\n throw new Error('x required');\n if (py == null || !Fp.isValid(py))\n throw new Error('y required');\n if (pz == null || !Fp.isValid(pz))\n throw new Error('z required');\n }\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n throw new Error('projective point not allowed');\n const is0 = (i) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.pz));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex) {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n this._WINDOW_SIZE = windowSize;\n pointPrecomputes.delete(this);\n }\n // A point on curve is valid if it conforms to equation.\n assertValidity() {\n if (this.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is wrong representation of ZERO and is always invalid.\n if (CURVE.allowInfinityPoint && !Fp.is0(this.py))\n return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = this.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n if (!Fp.eql(left, right))\n throw new Error('bad point: equation left != right');\n if (!this.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (Fp.isOdd)\n return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n /**\n * Compare one point to another.\n */\n equals(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate() {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => {\n const toInv = Fp.invertBatch(comp.map((p) => p.pz));\n return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n });\n }\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(n) {\n const I = Point.ZERO;\n if (n === _0n)\n return I;\n assertGE(n); // Will throw on 0\n if (n === _1n)\n return this;\n const { endo } = CURVE;\n if (!endo)\n return wnaf.unsafeLadder(this, n);\n // Apply endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let k1p = I;\n let k2p = I;\n let d = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n k1p = k1p.add(d);\n if (k2 & _1n)\n k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg)\n k1p = k1p.negate();\n if (k2neg)\n k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\n assertGE(scalar);\n let n = scalar;\n let point, fake; // Fake point is used to const-time mult\n const { endo } = CURVE;\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n }\n else {\n const { p, f } = this.wNAF(n);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q, a, b) {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (P, a // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n toAffine(iz) {\n const { px: x, py: y, pz: z } = this;\n const is0 = this.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null)\n iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n }\n isTorsionFree() {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n)\n return true; // No subgroups, always torsion-free\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor() {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\n return this.multiplyUnsafe(CURVE.h);\n }\n toRawBytes(isCompressed = true) {\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n toHex(isCompressed = true) {\n return ut.bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n const _bits = CURVE.nBitLength;\n const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n // Validate if generator point is on curve\n return {\n CURVE,\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\nfunction validateOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n }, {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n });\n return Object.freeze({ lowS: true, ...opts });\n}\nexport function weierstrass(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n function isValidFieldElement(num) {\n return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE\n }\n function modN(a) {\n return mod.mod(a, CURVE_ORDER);\n }\n function invN(a) {\n return mod.invert(a, CURVE_ORDER);\n }\n const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed) {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = ut.concatBytes;\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n }\n else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = ut.bytesToNumberBE(tail);\n if (!isValidFieldElement(x))\n throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n }\n catch (sqrtError) {\n const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('Point is not on curve' + suffix);\n }\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd)\n y = Fp.neg(y);\n return { x, y };\n }\n else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n }\n else {\n throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);\n }\n },\n });\n const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));\n function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function normalizeS(s) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to));\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature {\n constructor(r, s, recovery) {\n this.r = r;\n this.s = s;\n this.recovery = recovery;\n this.assertValidity();\n }\n // pair (bytes of r, bytes of s)\n static fromCompact(hex) {\n const l = CURVE.nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n assertValidity() {\n // can use assertGE here\n if (!isWithinCurveOrder(this.r))\n throw new Error('r must be 0 < r < CURVE.n');\n if (!isWithinCurveOrder(this.s))\n throw new Error('s must be 0 < s < CURVE.n');\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\n }\n recoverPublicKey(msgHash) {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec))\n throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER)\n throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteStr(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q)\n throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n // DER-encoded\n toDERRawBytes() {\n return ut.hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig({ r: this.r, s: this.s });\n }\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return ut.hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteStr(this.r) + numToNByteStr(this.s);\n }\n }\n const utils = {\n isValidPrivateKey(privateKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n }\n catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: () => {\n const length = mod.getMinHashLength(CURVE.n);\n return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey, isCompressed = true) {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item) {\n const arr = ut.isBytes(item);\n const str = typeof item === 'string';\n const len = (arr || str) && item.length;\n if (arr)\n return len === compressedLen || len === uncompressedLen;\n if (str)\n return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point)\n return true;\n return false;\n }\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA, publicB, isCompressed = true) {\n if (isProbPub(privateA))\n throw new Error('first arg must be private key');\n if (!isProbPub(publicB))\n throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int = CURVE.bits2int ||\n function (bytes) {\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = ut.bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN = CURVE.bits2int_modN ||\n function (bytes) {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = ut.bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num) {\n if (typeof num !== 'bigint')\n throw new Error('bigint expected');\n if (!(_0n <= num && num < ORDER_MASK))\n throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);\n // works with order, can have different size than numToField!\n return ut.numberToBytesBE(num, CURVE.nByteLength);\n }\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.\n // Also it can be bigger for P224 + SHA256\n function prepSig(msgHash, privateKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null)\n lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n if (prehash)\n msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null && ent !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes) {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k))\n return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n)\n return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery); // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash, privKey, opts = defaultSigOpts) {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1⋅G - U2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n if ('strict' in opts)\n throw new Error('options.strict was renamed to lowS');\n const { lowS, prehash } = opts;\n let _sig = undefined;\n let P;\n try {\n if (typeof sg === 'string' || ut.isBytes(sg)) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n _sig = Signature.fromDER(sg);\n }\n catch (derError) {\n if (!(derError instanceof DER.Err))\n throw derError;\n _sig = Signature.fromCompact(sg);\n }\n }\n else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {\n const { r, s } = sg;\n _sig = new Signature(r, s);\n }\n else {\n throw new Error('PARSE');\n }\n P = Point.fromHex(publicKey);\n }\n catch (error) {\n if (error.message === 'PARSE')\n throw new Error(`signature must be Signature instance, Uint8Array or hex string`);\n return false;\n }\n if (lowS && _sig.hasHighS())\n return false;\n if (prehash)\n msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n if (!R)\n return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp, Z) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n)\n l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u, v) => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u, v) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(Fp, opts) {\n mod.validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd)\n throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u) => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n x = Fp.div(x, tv4); // 25. x = x / tv4\n return { x, y };\n };\n}\n//# sourceMappingURL=weierstrass.js.map","import { getMinHashLength, mapHashToField } from './modular.js';\nimport { bitLen, bitGet, ensureBytes } from './utils.js';\n// prettier-ignore\nimport { createHasher } from './hash-to-curve.js';\nimport { weierstrassPoints, } from './weierstrass.js';\n// prettier-ignore\nconst _2n = BigInt(2), _3n = BigInt(3);\nexport function bls(CURVE) {\n // Fields are specific for curve, so for now we'll need to pass them with opts\n const { Fp, Fr, Fp2, Fp6, Fp12 } = CURVE.fields;\n const BLS_X_LEN = bitLen(CURVE.params.x);\n // Pre-compute coefficients for sparse multiplication\n // Point addition and point double calculations is reused for coefficients\n function calcPairingPrecomputes(p) {\n const { x, y } = p;\n // prettier-ignore\n const Qx = x, Qy = y, Qz = Fp2.ONE;\n // prettier-ignore\n let Rx = Qx, Ry = Qy, Rz = Qz;\n let ell_coeff = [];\n for (let i = BLS_X_LEN - 2; i >= 0; i--) {\n // Double\n let t0 = Fp2.sqr(Ry); // Ry²\n let t1 = Fp2.sqr(Rz); // Rz²\n let t2 = Fp2.multiplyByB(Fp2.mul(t1, _3n)); // 3 * T1 * B\n let t3 = Fp2.mul(t2, _3n); // 3 * T2\n let t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0); // (Ry + Rz)² - T1 - T0\n ell_coeff.push([\n Fp2.sub(t2, t0), // T2 - T0\n Fp2.mul(Fp2.sqr(Rx), _3n), // 3 * Rx²\n Fp2.neg(t4), // -T4\n ]);\n Rx = Fp2.div(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), _2n); // ((T0 - T3) * Rx * Ry) / 2\n Ry = Fp2.sub(Fp2.sqr(Fp2.div(Fp2.add(t0, t3), _2n)), Fp2.mul(Fp2.sqr(t2), _3n)); // ((T0 + T3) / 2)² - 3 * T2²\n Rz = Fp2.mul(t0, t4); // T0 * T4\n if (bitGet(CURVE.params.x, i)) {\n // Addition\n let t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz)); // Ry - Qy * Rz\n let t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz)); // Rx - Qx * Rz\n ell_coeff.push([\n Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy)), // T0 * Qx - T1 * Qy\n Fp2.neg(t0), // -T0\n t1, // T1\n ]);\n let t2 = Fp2.sqr(t1); // T1²\n let t3 = Fp2.mul(t2, t1); // T2 * T1\n let t4 = Fp2.mul(t2, Rx); // T2 * Rx\n let t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n)), Fp2.mul(Fp2.sqr(t0), Rz)); // T3 - 2 * T4 + T0² * Rz\n Rx = Fp2.mul(t1, t5); // T1 * T5\n Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry)); // (T4 - T5) * T0 - T3 * Ry\n Rz = Fp2.mul(Rz, t3); // Rz * T3\n }\n }\n return ell_coeff;\n }\n function millerLoop(ell, g1) {\n const { x } = CURVE.params;\n const Px = g1[0];\n const Py = g1[1];\n let f12 = Fp12.ONE;\n for (let j = 0, i = BLS_X_LEN - 2; i >= 0; i--, j++) {\n const E = ell[j];\n f12 = Fp12.multiplyBy014(f12, E[0], Fp2.mul(E[1], Px), Fp2.mul(E[2], Py));\n if (bitGet(x, i)) {\n j += 1;\n const F = ell[j];\n f12 = Fp12.multiplyBy014(f12, F[0], Fp2.mul(F[1], Px), Fp2.mul(F[2], Py));\n }\n if (i !== 0)\n f12 = Fp12.sqr(f12);\n }\n return Fp12.conjugate(f12);\n }\n const utils = {\n randomPrivateKey: () => {\n const length = getMinHashLength(Fr.ORDER);\n return mapHashToField(CURVE.randomBytes(length), Fr.ORDER);\n },\n calcPairingPrecomputes,\n };\n // Point on G1 curve: (x, y)\n const G1_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G1 });\n const G1 = Object.assign(G1_, createHasher(G1_.ProjectivePoint, CURVE.G1.mapToCurve, {\n ...CURVE.htfDefaults,\n ...CURVE.G1.htfDefaults,\n }));\n function pairingPrecomputes(point) {\n const p = point;\n if (p._PPRECOMPUTES)\n return p._PPRECOMPUTES;\n p._PPRECOMPUTES = calcPairingPrecomputes(point.toAffine());\n return p._PPRECOMPUTES;\n }\n // TODO: export\n // function clearPairingPrecomputes(point: G2) {\n // const p = point as G2 & withPairingPrecomputes;\n // p._PPRECOMPUTES = undefined;\n // }\n // Point on G2 curve (complex numbers): (x₁, x₂+i), (y₁, y₂+i)\n const G2_ = weierstrassPoints({ n: Fr.ORDER, ...CURVE.G2 });\n const G2 = Object.assign(G2_, createHasher(G2_.ProjectivePoint, CURVE.G2.mapToCurve, {\n ...CURVE.htfDefaults,\n ...CURVE.G2.htfDefaults,\n }));\n const { ShortSignature } = CURVE.G1;\n const { Signature } = CURVE.G2;\n // Calculates bilinear pairing\n function pairing(Q, P, withFinalExponent = true) {\n if (Q.equals(G1.ProjectivePoint.ZERO) || P.equals(G2.ProjectivePoint.ZERO))\n throw new Error('pairing is not available for ZERO point');\n Q.assertValidity();\n P.assertValidity();\n // Performance: 9ms for millerLoop and ~14ms for exp.\n const Qa = Q.toAffine();\n const looped = millerLoop(pairingPrecomputes(P), [Qa.x, Qa.y]);\n return withFinalExponent ? Fp12.finalExponentiate(looped) : looped;\n }\n function normP1(point) {\n return point instanceof G1.ProjectivePoint ? point : G1.ProjectivePoint.fromHex(point);\n }\n function normP1Hash(point, htfOpts) {\n return point instanceof G1.ProjectivePoint\n ? point\n : G1.hashToCurve(ensureBytes('point', point), htfOpts);\n }\n function normP2(point) {\n return point instanceof G2.ProjectivePoint ? point : Signature.fromHex(point);\n }\n function normP2Hash(point, htfOpts) {\n return point instanceof G2.ProjectivePoint\n ? point\n : G2.hashToCurve(ensureBytes('point', point), htfOpts);\n }\n // Multiplies generator (G1) by private key.\n // P = pk x G\n function getPublicKey(privateKey) {\n return G1.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true);\n }\n // Multiplies generator (G2) by private key.\n // P = pk x G\n function getPublicKeyForShortSignatures(privateKey) {\n return G2.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(true);\n }\n function sign(message, privateKey, htfOpts) {\n const msgPoint = normP2Hash(message, htfOpts);\n msgPoint.assertValidity();\n const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey));\n if (message instanceof G2.ProjectivePoint)\n return sigPoint;\n return Signature.toRawBytes(sigPoint);\n }\n function signShortSignature(message, privateKey, htfOpts) {\n const msgPoint = normP1Hash(message, htfOpts);\n msgPoint.assertValidity();\n const sigPoint = msgPoint.multiply(G1.normPrivateKeyToScalar(privateKey));\n if (message instanceof G1.ProjectivePoint)\n return sigPoint;\n return ShortSignature.toRawBytes(sigPoint);\n }\n // Checks if pairing of public key & hash is equal to pairing of generator & signature.\n // e(P, H(m)) == e(G, S)\n function verify(signature, message, publicKey, htfOpts) {\n const P = normP1(publicKey);\n const Hm = normP2Hash(message, htfOpts);\n const G = G1.ProjectivePoint.BASE;\n const S = normP2(signature);\n // Instead of doing 2 exponentiations, we use property of billinear maps\n // and do one exp after multiplying 2 points.\n const ePHm = pairing(P.negate(), Hm, false);\n const eGS = pairing(G, S, false);\n const exp = Fp12.finalExponentiate(Fp12.mul(eGS, ePHm));\n return Fp12.eql(exp, Fp12.ONE);\n }\n // Checks if pairing of public key & hash is equal to pairing of generator & signature.\n // e(S, G) == e(H(m), P)\n function verifyShortSignature(signature, message, publicKey, htfOpts) {\n const P = normP2(publicKey);\n const Hm = normP1Hash(message, htfOpts);\n const G = G2.ProjectivePoint.BASE;\n const S = normP1(signature);\n // Instead of doing 2 exponentiations, we use property of billinear maps\n // and do one exp after multiplying 2 points.\n const eHmP = pairing(Hm, P, false);\n const eSG = pairing(S, G.negate(), false);\n const exp = Fp12.finalExponentiate(Fp12.mul(eSG, eHmP));\n return Fp12.eql(exp, Fp12.ONE);\n }\n function aggregatePublicKeys(publicKeys) {\n if (!publicKeys.length)\n throw new Error('Expected non-empty array');\n const agg = publicKeys.map(normP1).reduce((sum, p) => sum.add(p), G1.ProjectivePoint.ZERO);\n const aggAffine = agg; //.toAffine();\n if (publicKeys[0] instanceof G1.ProjectivePoint) {\n aggAffine.assertValidity();\n return aggAffine;\n }\n // toRawBytes ensures point validity\n return aggAffine.toRawBytes(true);\n }\n function aggregateSignatures(signatures) {\n if (!signatures.length)\n throw new Error('Expected non-empty array');\n const agg = signatures.map(normP2).reduce((sum, s) => sum.add(s), G2.ProjectivePoint.ZERO);\n const aggAffine = agg; //.toAffine();\n if (signatures[0] instanceof G2.ProjectivePoint) {\n aggAffine.assertValidity();\n return aggAffine;\n }\n return Signature.toRawBytes(aggAffine);\n }\n function aggregateShortSignatures(signatures) {\n if (!signatures.length)\n throw new Error('Expected non-empty array');\n const agg = signatures.map(normP1).reduce((sum, s) => sum.add(s), G1.ProjectivePoint.ZERO);\n const aggAffine = agg; //.toAffine();\n if (signatures[0] instanceof G1.ProjectivePoint) {\n aggAffine.assertValidity();\n return aggAffine;\n }\n return ShortSignature.toRawBytes(aggAffine);\n }\n // https://ethresear.ch/t/fast-verification-of-multiple-bls-signatures/5407\n // e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))\n function verifyBatch(signature, messages, publicKeys, htfOpts) {\n // @ts-ignore\n // console.log('verifyBatch', bytesToHex(signature as any), messages, publicKeys.map(bytesToHex));\n if (!messages.length)\n throw new Error('Expected non-empty messages array');\n if (publicKeys.length !== messages.length)\n throw new Error('Pubkey count should equal msg count');\n const sig = normP2(signature);\n const nMessages = messages.map((i) => normP2Hash(i, htfOpts));\n const nPublicKeys = publicKeys.map(normP1);\n try {\n const paired = [];\n for (const message of new Set(nMessages)) {\n const groupPublicKey = nMessages.reduce((groupPublicKey, subMessage, i) => subMessage === message ? groupPublicKey.add(nPublicKeys[i]) : groupPublicKey, G1.ProjectivePoint.ZERO);\n // const msg = message instanceof PointG2 ? message : await PointG2.hashToCurve(message);\n // Possible to batch pairing for same msg with different groupPublicKey here\n paired.push(pairing(groupPublicKey, message, false));\n }\n paired.push(pairing(G1.ProjectivePoint.BASE.negate(), sig, false));\n const product = paired.reduce((a, b) => Fp12.mul(a, b), Fp12.ONE);\n const exp = Fp12.finalExponentiate(product);\n return Fp12.eql(exp, Fp12.ONE);\n }\n catch {\n return false;\n }\n }\n G1.ProjectivePoint.BASE._setWindowSize(4);\n return {\n getPublicKey,\n getPublicKeyForShortSignatures,\n sign,\n signShortSignature,\n verify,\n verifyBatch,\n verifyShortSignature,\n aggregatePublicKeys,\n aggregateSignatures,\n aggregateShortSignatures,\n millerLoop,\n pairing,\n G1,\n G2,\n Signature,\n ShortSignature,\n fields: {\n Fr,\n Fp,\n Fp2,\n Fp6,\n Fp12,\n },\n params: {\n x: CURVE.params.x,\n r: CURVE.params.r,\n G1b: CURVE.G1.b,\n G2b: CURVE.G2.b,\n },\n utils,\n };\n}\n//# sourceMappingURL=bls.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// bls12-381 is pairing-friendly Barreto-Lynn-Scott elliptic curve construction allowing to:\n// - Construct zk-SNARKs at the 120-bit security\n// - Efficiently verify N aggregate signatures with 1 pairing and N ec additions:\n// the Boneh-Lynn-Shacham signature scheme is orders of magnitude more efficient than Schnorr\n//\n// ### Summary\n// 1. BLS Relies on Bilinear Pairing (expensive)\n// 2. Private Keys: 32 bytes\n// 3. Public Keys: 48 bytes: 381 bit affine x coordinate, encoded into 48 big-endian bytes.\n// 4. Signatures: 96 bytes: two 381 bit integers (affine x coordinate), encoded into two 48 big-endian byte arrays.\n// - The signature is a point on the G2 subgroup, which is defined over a finite field\n// with elements twice as big as the G1 curve (G2 is over Fp2 rather than Fp. Fp2 is analogous to the complex numbers).\n// 5. The 12 stands for the Embedding degree.\n//\n// ### Formulas\n// - `P = pk x G` - public keys\n// - `S = pk x H(m)` - signing\n// - `e(P, H(m)) == e(G, S)` - verification using pairings\n// - `e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))` - signature aggregation\n//\n// ### Compatibility and notes\n// 1. It is compatible with Algorand, Chia, Dfinity, Ethereum, Filecoin, ZEC\n// Filecoin uses little endian byte arrays for private keys - make sure to reverse byte order.\n// 2. Some projects use G2 for public keys and G1 for signatures. It's called \"short signature\"\n// 3. Curve security level is about 120 bits as per Barbulescu-Duquesne 2017\n// https://hal.science/hal-01534101/file/main.pdf\n// 4. Compatible with specs:\n// [cfrg-pairing-friendly-curves-11](https://tools.ietf.org/html/draft-irtf-cfrg-pairing-friendly-curves-11),\n// [cfrg-bls-signature-05](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-bls-signature-05),\n// [RFC 9380](https://www.rfc-editor.org/rfc/rfc9380).\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { bls } from './abstract/bls.js';\nimport * as mod from './abstract/modular.js';\nimport { concatBytes as concatB, ensureBytes, numberToBytesBE, bytesToNumberBE, bitLen, bitGet, bitMask, bytesToHex, } from './abstract/utils.js';\n// Types\nimport { mapToCurveSimpleSWU, } from './abstract/weierstrass.js';\nimport { isogenyMap } from './abstract/hash-to-curve.js';\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\n// prettier-ignore\nconst _8n = BigInt(8), _16n = BigInt(16);\n// CURVE FIELDS\n// Finite field over p.\nconst Fp_raw = BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab');\nconst Fp = mod.Field(Fp_raw);\n// Finite field over r.\n// This particular field is not used anywhere in bls12-381, but it is still useful.\nconst Fr = mod.Field(BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001'));\nconst Fp2Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({\n c0: Fp.add(c0, r0),\n c1: Fp.add(c1, r1),\n});\nconst Fp2Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({\n c0: Fp.sub(c0, r0),\n c1: Fp.sub(c1, r1),\n});\nconst Fp2Multiply = ({ c0, c1 }, rhs) => {\n if (typeof rhs === 'bigint')\n return { c0: Fp.mul(c0, rhs), c1: Fp.mul(c1, rhs) };\n // (a+bi)(c+di) = (ac−bd) + (ad+bc)i\n const { c0: r0, c1: r1 } = rhs;\n let t1 = Fp.mul(c0, r0); // c0 * o0\n let t2 = Fp.mul(c1, r1); // c1 * o1\n // (T1 - T2) + ((c0 + c1) * (r0 + r1) - (T1 + T2))*i\n const o0 = Fp.sub(t1, t2);\n const o1 = Fp.sub(Fp.mul(Fp.add(c0, c1), Fp.add(r0, r1)), Fp.add(t1, t2));\n return { c0: o0, c1: o1 };\n};\nconst Fp2Square = ({ c0, c1 }) => {\n const a = Fp.add(c0, c1);\n const b = Fp.sub(c0, c1);\n const c = Fp.add(c0, c0);\n return { c0: Fp.mul(a, b), c1: Fp.mul(c, c1) };\n};\n// G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1),\n// where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where\n// G² - 1\n// h2q\n// NOTE: ORDER was wrong!\nconst FP2_ORDER = Fp_raw * Fp_raw;\nconst Fp2 = {\n ORDER: FP2_ORDER,\n BITS: bitLen(FP2_ORDER),\n BYTES: Math.ceil(bitLen(FP2_ORDER) / 8),\n MASK: bitMask(bitLen(FP2_ORDER)),\n ZERO: { c0: Fp.ZERO, c1: Fp.ZERO },\n ONE: { c0: Fp.ONE, c1: Fp.ZERO },\n create: (num) => num,\n isValid: ({ c0, c1 }) => typeof c0 === 'bigint' && typeof c1 === 'bigint',\n is0: ({ c0, c1 }) => Fp.is0(c0) && Fp.is0(c1),\n eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp.eql(c0, r0) && Fp.eql(c1, r1),\n neg: ({ c0, c1 }) => ({ c0: Fp.neg(c0), c1: Fp.neg(c1) }),\n pow: (num, power) => mod.FpPow(Fp2, num, power),\n invertBatch: (nums) => mod.FpInvertBatch(Fp2, nums),\n // Normalized\n add: Fp2Add,\n sub: Fp2Subtract,\n mul: Fp2Multiply,\n sqr: Fp2Square,\n // NonNormalized stuff\n addN: Fp2Add,\n subN: Fp2Subtract,\n mulN: Fp2Multiply,\n sqrN: Fp2Square,\n // Why inversion for bigint inside Fp instead of Fp2? it is even used in that context?\n div: (lhs, rhs) => Fp2.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp2.inv(rhs)),\n inv: ({ c0: a, c1: b }) => {\n // We wish to find the multiplicative inverse of a nonzero\n // element a + bu in Fp2. We leverage an identity\n //\n // (a + bu)(a - bu) = a² + b²\n //\n // which holds because u² = -1. This can be rewritten as\n //\n // (a + bu)(a - bu)/(a² + b²) = 1\n //\n // because a² + b² = 0 has no nonzero solutions for (a, b).\n // This gives that (a - bu)/(a² + b²) is the inverse\n // of (a + bu). Importantly, this can be computing using\n // only a single inversion in Fp.\n const factor = Fp.inv(Fp.create(a * a + b * b));\n return { c0: Fp.mul(factor, Fp.create(a)), c1: Fp.mul(factor, Fp.create(-b)) };\n },\n sqrt: (num) => {\n if (Fp2.eql(num, Fp2.ZERO))\n return Fp2.ZERO; // Algo doesn't handles this case\n // TODO: Optimize this line. It's extremely slow.\n // Speeding this up would boost aggregateSignatures.\n // https://eprint.iacr.org/2012/685.pdf applicable?\n // https://github.com/zkcrypto/bls12_381/blob/080eaa74ec0e394377caa1ba302c8c121df08b07/src/fp2.rs#L250\n // https://github.com/supranational/blst/blob/aae0c7d70b799ac269ff5edf29d8191dbd357876/src/exp2.c#L1\n // Inspired by https://github.com/dalek-cryptography/curve25519-dalek/blob/17698df9d4c834204f83a3574143abacb4fc81a5/src/field.rs#L99\n const candidateSqrt = Fp2.pow(num, (Fp2.ORDER + _8n) / _16n);\n const check = Fp2.div(Fp2.sqr(candidateSqrt), num); // candidateSqrt.square().div(this);\n const R = FP2_ROOTS_OF_UNITY;\n const divisor = [R[0], R[2], R[4], R[6]].find((r) => Fp2.eql(r, check));\n if (!divisor)\n throw new Error('No root');\n const index = R.indexOf(divisor);\n const root = R[index / 2];\n if (!root)\n throw new Error('Invalid root');\n const x1 = Fp2.div(candidateSqrt, root);\n const x2 = Fp2.neg(x1);\n const { re: re1, im: im1 } = Fp2.reim(x1);\n const { re: re2, im: im2 } = Fp2.reim(x2);\n if (im1 > im2 || (im1 === im2 && re1 > re2))\n return x1;\n return x2;\n },\n // Same as sgn0_m_eq_2 in RFC 9380\n isOdd: (x) => {\n const { re: x0, im: x1 } = Fp2.reim(x);\n const sign_0 = x0 % _2n;\n const zero_0 = x0 === _0n;\n const sign_1 = x1 % _2n;\n return BigInt(sign_0 || (zero_0 && sign_1)) == _1n;\n },\n // Bytes util\n fromBytes(b) {\n if (b.length !== Fp2.BYTES)\n throw new Error(`fromBytes wrong length=${b.length}`);\n return { c0: Fp.fromBytes(b.subarray(0, Fp.BYTES)), c1: Fp.fromBytes(b.subarray(Fp.BYTES)) };\n },\n toBytes: ({ c0, c1 }) => concatB(Fp.toBytes(c0), Fp.toBytes(c1)),\n cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({\n c0: Fp.cmov(c0, r0, c),\n c1: Fp.cmov(c1, r1, c),\n }),\n // Specific utils\n // toString() {\n // return `Fp2(${this.c0} + ${this.c1}×i)`;\n // }\n reim: ({ c0, c1 }) => ({ re: c0, im: c1 }),\n // multiply by u + 1\n mulByNonresidue: ({ c0, c1 }) => ({ c0: Fp.sub(c0, c1), c1: Fp.add(c0, c1) }),\n multiplyByB: ({ c0, c1 }) => {\n let t0 = Fp.mul(c0, _4n); // 4 * c0\n let t1 = Fp.mul(c1, _4n); // 4 * c1\n // (T0-T1) + (T0+T1)*i\n return { c0: Fp.sub(t0, t1), c1: Fp.add(t0, t1) };\n },\n fromBigTuple: (tuple) => {\n if (tuple.length !== 2)\n throw new Error('Invalid tuple');\n const fps = tuple.map((n) => Fp.create(n));\n return { c0: fps[0], c1: fps[1] };\n },\n frobeniusMap: ({ c0, c1 }, power) => ({\n c0,\n c1: Fp.mul(c1, FP2_FROBENIUS_COEFFICIENTS[power % 2]),\n }),\n};\n// Finite extension field over irreducible polynominal.\n// Fp(u) / (u² - β) where β = -1\nconst FP2_FROBENIUS_COEFFICIENTS = [\n BigInt('0x1'),\n BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa'),\n].map((item) => Fp.create(item));\n// For Fp2 roots of unity.\nconst rv1 = BigInt('0x6af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09');\n// const ev1 =\n// BigInt('0x699be3b8c6870965e5bf892ad5d2cc7b0e85a117402dfd83b7f4a947e02d978498255a2aaec0ac627b5afbdf1bf1c90');\n// const ev2 =\n// BigInt('0x8157cd83046453f5dd0972b6e3949e4288020b5b8a9cc99ca07e27089a2ce2436d965026adad3ef7baba37f2183e9b5');\n// const ev3 =\n// BigInt('0xab1c2ffdd6c253ca155231eb3e71ba044fd562f6f72bc5bad5ec46a0b7a3b0247cf08ce6c6317f40edbc653a72dee17');\n// const ev4 =\n// BigInt('0xaa404866706722864480885d68ad0ccac1967c7544b447873cc37e0181271e006df72162a3d3e0287bf597fbf7f8fc1');\n// Eighth roots of unity, used for computing square roots in Fp2.\n// To verify or re-calculate:\n// Array(8).fill(new Fp2([1n, 1n])).map((fp2, k) => fp2.pow(Fp2.ORDER * BigInt(k) / 8n))\nconst FP2_ROOTS_OF_UNITY = [\n [_1n, _0n],\n [rv1, -rv1],\n [_0n, _1n],\n [rv1, rv1],\n [-_1n, _0n],\n [-rv1, rv1],\n [_0n, -_1n],\n [-rv1, -rv1],\n].map((pair) => Fp2.fromBigTuple(pair));\nconst Fp6Add = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({\n c0: Fp2.add(c0, r0),\n c1: Fp2.add(c1, r1),\n c2: Fp2.add(c2, r2),\n});\nconst Fp6Subtract = ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => ({\n c0: Fp2.sub(c0, r0),\n c1: Fp2.sub(c1, r1),\n c2: Fp2.sub(c2, r2),\n});\nconst Fp6Multiply = ({ c0, c1, c2 }, rhs) => {\n if (typeof rhs === 'bigint') {\n return {\n c0: Fp2.mul(c0, rhs),\n c1: Fp2.mul(c1, rhs),\n c2: Fp2.mul(c2, rhs),\n };\n }\n const { c0: r0, c1: r1, c2: r2 } = rhs;\n const t0 = Fp2.mul(c0, r0); // c0 * o0\n const t1 = Fp2.mul(c1, r1); // c1 * o1\n const t2 = Fp2.mul(c2, r2); // c2 * o2\n return {\n // t0 + (c1 + c2) * (r1 * r2) - (T1 + T2) * (u + 1)\n c0: Fp2.add(t0, Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), Fp2.add(r1, r2)), Fp2.add(t1, t2)))),\n // (c0 + c1) * (r0 + r1) - (T0 + T1) + T2 * (u + 1)\n c1: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c1), Fp2.add(r0, r1)), Fp2.add(t0, t1)), Fp2.mulByNonresidue(t2)),\n // T1 + (c0 + c2) * (r0 + r2) - T0 + T2\n c2: Fp2.sub(Fp2.add(t1, Fp2.mul(Fp2.add(c0, c2), Fp2.add(r0, r2))), Fp2.add(t0, t2)),\n };\n};\nconst Fp6Square = ({ c0, c1, c2 }) => {\n let t0 = Fp2.sqr(c0); // c0²\n let t1 = Fp2.mul(Fp2.mul(c0, c1), _2n); // 2 * c0 * c1\n let t3 = Fp2.mul(Fp2.mul(c1, c2), _2n); // 2 * c1 * c2\n let t4 = Fp2.sqr(c2); // c2²\n return {\n c0: Fp2.add(Fp2.mulByNonresidue(t3), t0), // T3 * (u + 1) + T0\n c1: Fp2.add(Fp2.mulByNonresidue(t4), t1), // T4 * (u + 1) + T1\n // T1 + (c0 - c1 + c2)² + T3 - T0 - T4\n c2: Fp2.sub(Fp2.sub(Fp2.add(Fp2.add(t1, Fp2.sqr(Fp2.add(Fp2.sub(c0, c1), c2))), t3), t0), t4),\n };\n};\nconst Fp6 = {\n ORDER: Fp2.ORDER, // TODO: unused, but need to verify\n BITS: 3 * Fp2.BITS,\n BYTES: 3 * Fp2.BYTES,\n MASK: bitMask(3 * Fp2.BITS),\n ZERO: { c0: Fp2.ZERO, c1: Fp2.ZERO, c2: Fp2.ZERO },\n ONE: { c0: Fp2.ONE, c1: Fp2.ZERO, c2: Fp2.ZERO },\n create: (num) => num,\n isValid: ({ c0, c1, c2 }) => Fp2.isValid(c0) && Fp2.isValid(c1) && Fp2.isValid(c2),\n is0: ({ c0, c1, c2 }) => Fp2.is0(c0) && Fp2.is0(c1) && Fp2.is0(c2),\n neg: ({ c0, c1, c2 }) => ({ c0: Fp2.neg(c0), c1: Fp2.neg(c1), c2: Fp2.neg(c2) }),\n eql: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) => Fp2.eql(c0, r0) && Fp2.eql(c1, r1) && Fp2.eql(c2, r2),\n sqrt: () => {\n throw new Error('Not implemented');\n },\n // Do we need division by bigint at all? Should be done via order:\n div: (lhs, rhs) => Fp6.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp6.inv(rhs)),\n pow: (num, power) => mod.FpPow(Fp6, num, power),\n invertBatch: (nums) => mod.FpInvertBatch(Fp6, nums),\n // Normalized\n add: Fp6Add,\n sub: Fp6Subtract,\n mul: Fp6Multiply,\n sqr: Fp6Square,\n // NonNormalized stuff\n addN: Fp6Add,\n subN: Fp6Subtract,\n mulN: Fp6Multiply,\n sqrN: Fp6Square,\n inv: ({ c0, c1, c2 }) => {\n let t0 = Fp2.sub(Fp2.sqr(c0), Fp2.mulByNonresidue(Fp2.mul(c2, c1))); // c0² - c2 * c1 * (u + 1)\n let t1 = Fp2.sub(Fp2.mulByNonresidue(Fp2.sqr(c2)), Fp2.mul(c0, c1)); // c2² * (u + 1) - c0 * c1\n let t2 = Fp2.sub(Fp2.sqr(c1), Fp2.mul(c0, c2)); // c1² - c0 * c2\n // 1/(((c2 * T1 + c1 * T2) * v) + c0 * T0)\n let t4 = Fp2.inv(Fp2.add(Fp2.mulByNonresidue(Fp2.add(Fp2.mul(c2, t1), Fp2.mul(c1, t2))), Fp2.mul(c0, t0)));\n return { c0: Fp2.mul(t4, t0), c1: Fp2.mul(t4, t1), c2: Fp2.mul(t4, t2) };\n },\n // Bytes utils\n fromBytes: (b) => {\n if (b.length !== Fp6.BYTES)\n throw new Error(`fromBytes wrong length=${b.length}`);\n return {\n c0: Fp2.fromBytes(b.subarray(0, Fp2.BYTES)),\n c1: Fp2.fromBytes(b.subarray(Fp2.BYTES, 2 * Fp2.BYTES)),\n c2: Fp2.fromBytes(b.subarray(2 * Fp2.BYTES)),\n };\n },\n toBytes: ({ c0, c1, c2 }) => concatB(Fp2.toBytes(c0), Fp2.toBytes(c1), Fp2.toBytes(c2)),\n cmov: ({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }, c) => ({\n c0: Fp2.cmov(c0, r0, c),\n c1: Fp2.cmov(c1, r1, c),\n c2: Fp2.cmov(c2, r2, c),\n }),\n // Utils\n // fromTriple(triple: [Fp2, Fp2, Fp2]) {\n // return new Fp6(...triple);\n // }\n // toString() {\n // return `Fp6(${this.c0} + ${this.c1} * v, ${this.c2} * v^2)`;\n // }\n fromBigSix: (t) => {\n if (!Array.isArray(t) || t.length !== 6)\n throw new Error('Invalid Fp6 usage');\n return {\n c0: Fp2.fromBigTuple(t.slice(0, 2)),\n c1: Fp2.fromBigTuple(t.slice(2, 4)),\n c2: Fp2.fromBigTuple(t.slice(4, 6)),\n };\n },\n frobeniusMap: ({ c0, c1, c2 }, power) => ({\n c0: Fp2.frobeniusMap(c0, power),\n c1: Fp2.mul(Fp2.frobeniusMap(c1, power), FP6_FROBENIUS_COEFFICIENTS_1[power % 6]),\n c2: Fp2.mul(Fp2.frobeniusMap(c2, power), FP6_FROBENIUS_COEFFICIENTS_2[power % 6]),\n }),\n mulByNonresidue: ({ c0, c1, c2 }) => ({ c0: Fp2.mulByNonresidue(c2), c1: c0, c2: c1 }),\n // Sparse multiplication\n multiplyBy1: ({ c0, c1, c2 }, b1) => ({\n c0: Fp2.mulByNonresidue(Fp2.mul(c2, b1)),\n c1: Fp2.mul(c0, b1),\n c2: Fp2.mul(c1, b1),\n }),\n // Sparse multiplication\n multiplyBy01({ c0, c1, c2 }, b0, b1) {\n let t0 = Fp2.mul(c0, b0); // c0 * b0\n let t1 = Fp2.mul(c1, b1); // c1 * b1\n return {\n // ((c1 + c2) * b1 - T1) * (u + 1) + T0\n c0: Fp2.add(Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), b1), t1)), t0),\n // (b0 + b1) * (c0 + c1) - T0 - T1\n c1: Fp2.sub(Fp2.sub(Fp2.mul(Fp2.add(b0, b1), Fp2.add(c0, c1)), t0), t1),\n // (c0 + c2) * b0 - T0 + T1\n c2: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c2), b0), t0), t1),\n };\n },\n multiplyByFp2: ({ c0, c1, c2 }, rhs) => ({\n c0: Fp2.mul(c0, rhs),\n c1: Fp2.mul(c1, rhs),\n c2: Fp2.mul(c2, rhs),\n }),\n};\nconst FP6_FROBENIUS_COEFFICIENTS_1 = [\n [BigInt('0x1'), BigInt('0x0')],\n [\n BigInt('0x0'),\n BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'),\n ],\n [\n BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'),\n BigInt('0x0'),\n ],\n [BigInt('0x0'), BigInt('0x1')],\n [\n BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'),\n BigInt('0x0'),\n ],\n [\n BigInt('0x0'),\n BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'),\n ],\n].map((pair) => Fp2.fromBigTuple(pair));\nconst FP6_FROBENIUS_COEFFICIENTS_2 = [\n [BigInt('0x1'), BigInt('0x0')],\n [\n BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad'),\n BigInt('0x0'),\n ],\n [\n BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'),\n BigInt('0x0'),\n ],\n [\n BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa'),\n BigInt('0x0'),\n ],\n [\n BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'),\n BigInt('0x0'),\n ],\n [\n BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff'),\n BigInt('0x0'),\n ],\n].map((pair) => Fp2.fromBigTuple(pair));\n// The BLS parameter x for BLS12-381\nconst BLS_X = BigInt('0xd201000000010000');\nconst BLS_X_LEN = bitLen(BLS_X);\nconst Fp12Add = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({\n c0: Fp6.add(c0, r0),\n c1: Fp6.add(c1, r1),\n});\nconst Fp12Subtract = ({ c0, c1 }, { c0: r0, c1: r1 }) => ({\n c0: Fp6.sub(c0, r0),\n c1: Fp6.sub(c1, r1),\n});\nconst Fp12Multiply = ({ c0, c1 }, rhs) => {\n if (typeof rhs === 'bigint')\n return { c0: Fp6.mul(c0, rhs), c1: Fp6.mul(c1, rhs) };\n let { c0: r0, c1: r1 } = rhs;\n let t1 = Fp6.mul(c0, r0); // c0 * r0\n let t2 = Fp6.mul(c1, r1); // c1 * r1\n return {\n c0: Fp6.add(t1, Fp6.mulByNonresidue(t2)), // T1 + T2 * v\n // (c0 + c1) * (r0 + r1) - (T1 + T2)\n c1: Fp6.sub(Fp6.mul(Fp6.add(c0, c1), Fp6.add(r0, r1)), Fp6.add(t1, t2)),\n };\n};\nconst Fp12Square = ({ c0, c1 }) => {\n let ab = Fp6.mul(c0, c1); // c0 * c1\n return {\n // (c1 * v + c0) * (c0 + c1) - AB - AB * v\n c0: Fp6.sub(Fp6.sub(Fp6.mul(Fp6.add(Fp6.mulByNonresidue(c1), c0), Fp6.add(c0, c1)), ab), Fp6.mulByNonresidue(ab)),\n c1: Fp6.add(ab, ab),\n }; // AB + AB\n};\nfunction Fp4Square(a, b) {\n const a2 = Fp2.sqr(a);\n const b2 = Fp2.sqr(b);\n return {\n first: Fp2.add(Fp2.mulByNonresidue(b2), a2), // b² * Nonresidue + a²\n second: Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(a, b)), a2), b2), // (a + b)² - a² - b²\n };\n}\nconst Fp12 = {\n ORDER: Fp2.ORDER, // TODO: unused, but need to verify\n BITS: 2 * Fp2.BITS,\n BYTES: 2 * Fp2.BYTES,\n MASK: bitMask(2 * Fp2.BITS),\n ZERO: { c0: Fp6.ZERO, c1: Fp6.ZERO },\n ONE: { c0: Fp6.ONE, c1: Fp6.ZERO },\n create: (num) => num,\n isValid: ({ c0, c1 }) => Fp6.isValid(c0) && Fp6.isValid(c1),\n is0: ({ c0, c1 }) => Fp6.is0(c0) && Fp6.is0(c1),\n neg: ({ c0, c1 }) => ({ c0: Fp6.neg(c0), c1: Fp6.neg(c1) }),\n eql: ({ c0, c1 }, { c0: r0, c1: r1 }) => Fp6.eql(c0, r0) && Fp6.eql(c1, r1),\n sqrt: () => {\n throw new Error('Not implemented');\n },\n inv: ({ c0, c1 }) => {\n let t = Fp6.inv(Fp6.sub(Fp6.sqr(c0), Fp6.mulByNonresidue(Fp6.sqr(c1)))); // 1 / (c0² - c1² * v)\n return { c0: Fp6.mul(c0, t), c1: Fp6.neg(Fp6.mul(c1, t)) }; // ((C0 * T) * T) + (-C1 * T) * w\n },\n div: (lhs, rhs) => Fp12.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : Fp12.inv(rhs)),\n pow: (num, power) => mod.FpPow(Fp12, num, power),\n invertBatch: (nums) => mod.FpInvertBatch(Fp12, nums),\n // Normalized\n add: Fp12Add,\n sub: Fp12Subtract,\n mul: Fp12Multiply,\n sqr: Fp12Square,\n // NonNormalized stuff\n addN: Fp12Add,\n subN: Fp12Subtract,\n mulN: Fp12Multiply,\n sqrN: Fp12Square,\n // Bytes utils\n fromBytes: (b) => {\n if (b.length !== Fp12.BYTES)\n throw new Error(`fromBytes wrong length=${b.length}`);\n return {\n c0: Fp6.fromBytes(b.subarray(0, Fp6.BYTES)),\n c1: Fp6.fromBytes(b.subarray(Fp6.BYTES)),\n };\n },\n toBytes: ({ c0, c1 }) => concatB(Fp6.toBytes(c0), Fp6.toBytes(c1)),\n cmov: ({ c0, c1 }, { c0: r0, c1: r1 }, c) => ({\n c0: Fp6.cmov(c0, r0, c),\n c1: Fp6.cmov(c1, r1, c),\n }),\n // Utils\n // toString() {\n // return `Fp12(${this.c0} + ${this.c1} * w)`;\n // },\n // fromTuple(c: [Fp6, Fp6]) {\n // return new Fp12(...c);\n // }\n fromBigTwelve: (t) => ({\n c0: Fp6.fromBigSix(t.slice(0, 6)),\n c1: Fp6.fromBigSix(t.slice(6, 12)),\n }),\n // Raises to q**i -th power\n frobeniusMap(lhs, power) {\n const r0 = Fp6.frobeniusMap(lhs.c0, power);\n const { c0, c1, c2 } = Fp6.frobeniusMap(lhs.c1, power);\n const coeff = FP12_FROBENIUS_COEFFICIENTS[power % 12];\n return {\n c0: r0,\n c1: Fp6.create({\n c0: Fp2.mul(c0, coeff),\n c1: Fp2.mul(c1, coeff),\n c2: Fp2.mul(c2, coeff),\n }),\n };\n },\n // Sparse multiplication\n multiplyBy014: ({ c0, c1 }, o0, o1, o4) => {\n let t0 = Fp6.multiplyBy01(c0, o0, o1);\n let t1 = Fp6.multiplyBy1(c1, o4);\n return {\n c0: Fp6.add(Fp6.mulByNonresidue(t1), t0), // T1 * v + T0\n // (c1 + c0) * [o0, o1+o4] - T0 - T1\n c1: Fp6.sub(Fp6.sub(Fp6.multiplyBy01(Fp6.add(c1, c0), o0, Fp2.add(o1, o4)), t0), t1),\n };\n },\n multiplyByFp2: ({ c0, c1 }, rhs) => ({\n c0: Fp6.multiplyByFp2(c0, rhs),\n c1: Fp6.multiplyByFp2(c1, rhs),\n }),\n conjugate: ({ c0, c1 }) => ({ c0, c1: Fp6.neg(c1) }),\n // A cyclotomic group is a subgroup of Fp^n defined by\n // GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1}\n // The result of any pairing is in a cyclotomic subgroup\n // https://eprint.iacr.org/2009/565.pdf\n _cyclotomicSquare: ({ c0, c1 }) => {\n const { c0: c0c0, c1: c0c1, c2: c0c2 } = c0;\n const { c0: c1c0, c1: c1c1, c2: c1c2 } = c1;\n const { first: t3, second: t4 } = Fp4Square(c0c0, c1c1);\n const { first: t5, second: t6 } = Fp4Square(c1c0, c0c2);\n const { first: t7, second: t8 } = Fp4Square(c0c1, c1c2);\n let t9 = Fp2.mulByNonresidue(t8); // T8 * (u + 1)\n return {\n c0: Fp6.create({\n c0: Fp2.add(Fp2.mul(Fp2.sub(t3, c0c0), _2n), t3), // 2 * (T3 - c0c0) + T3\n c1: Fp2.add(Fp2.mul(Fp2.sub(t5, c0c1), _2n), t5), // 2 * (T5 - c0c1) + T5\n c2: Fp2.add(Fp2.mul(Fp2.sub(t7, c0c2), _2n), t7),\n }), // 2 * (T7 - c0c2) + T7\n c1: Fp6.create({\n c0: Fp2.add(Fp2.mul(Fp2.add(t9, c1c0), _2n), t9), // 2 * (T9 + c1c0) + T9\n c1: Fp2.add(Fp2.mul(Fp2.add(t4, c1c1), _2n), t4), // 2 * (T4 + c1c1) + T4\n c2: Fp2.add(Fp2.mul(Fp2.add(t6, c1c2), _2n), t6),\n }),\n }; // 2 * (T6 + c1c2) + T6\n },\n _cyclotomicExp(num, n) {\n let z = Fp12.ONE;\n for (let i = BLS_X_LEN - 1; i >= 0; i--) {\n z = Fp12._cyclotomicSquare(z);\n if (bitGet(n, i))\n z = Fp12.mul(z, num);\n }\n return z;\n },\n // https://eprint.iacr.org/2010/354.pdf\n // https://eprint.iacr.org/2009/565.pdf\n finalExponentiate: (num) => {\n const x = BLS_X;\n // this^(q⁶) / this\n const t0 = Fp12.div(Fp12.frobeniusMap(num, 6), num);\n // t0^(q²) * t0\n const t1 = Fp12.mul(Fp12.frobeniusMap(t0, 2), t0);\n const t2 = Fp12.conjugate(Fp12._cyclotomicExp(t1, x));\n const t3 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicSquare(t1)), t2);\n const t4 = Fp12.conjugate(Fp12._cyclotomicExp(t3, x));\n const t5 = Fp12.conjugate(Fp12._cyclotomicExp(t4, x));\n const t6 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicExp(t5, x)), Fp12._cyclotomicSquare(t2));\n const t7 = Fp12.conjugate(Fp12._cyclotomicExp(t6, x));\n const t2_t5_pow_q2 = Fp12.frobeniusMap(Fp12.mul(t2, t5), 2);\n const t4_t1_pow_q3 = Fp12.frobeniusMap(Fp12.mul(t4, t1), 3);\n const t6_t1c_pow_q1 = Fp12.frobeniusMap(Fp12.mul(t6, Fp12.conjugate(t1)), 1);\n const t7_t3c_t1 = Fp12.mul(Fp12.mul(t7, Fp12.conjugate(t3)), t1);\n // (t2 * t5)^(q²) * (t4 * t1)^(q³) * (t6 * t1.conj)^(q^1) * t7 * t3.conj * t1\n return Fp12.mul(Fp12.mul(Fp12.mul(t2_t5_pow_q2, t4_t1_pow_q3), t6_t1c_pow_q1), t7_t3c_t1);\n },\n};\nconst FP12_FROBENIUS_COEFFICIENTS = [\n [BigInt('0x1'), BigInt('0x0')],\n [\n BigInt('0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8'),\n BigInt('0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3'),\n ],\n [\n BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffeffff'),\n BigInt('0x0'),\n ],\n [\n BigInt('0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2'),\n BigInt('0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09'),\n ],\n [\n BigInt('0x00000000000000005f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'),\n BigInt('0x0'),\n ],\n [\n BigInt('0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995'),\n BigInt('0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116'),\n ],\n [\n BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaaa'),\n BigInt('0x0'),\n ],\n [\n BigInt('0x00fc3e2b36c4e03288e9e902231f9fb854a14787b6c7b36fec0c8ec971f63c5f282d5ac14d6c7ec22cf78a126ddc4af3'),\n BigInt('0x1904d3bf02bb0667c231beb4202c0d1f0fd603fd3cbd5f4f7b2443d784bab9c4f67ea53d63e7813d8d0775ed92235fb8'),\n ],\n [\n BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac'),\n BigInt('0x0'),\n ],\n [\n BigInt('0x06af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09'),\n BigInt('0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2'),\n ],\n [\n BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaad'),\n BigInt('0x0'),\n ],\n [\n BigInt('0x05b2cfd9013a5fd8df47fa6b48b1e045f39816240c0b8fee8beadf4d8e9c0566c63a3e6e257f87329b18fae980078116'),\n BigInt('0x144e4211384586c16bd3ad4afa99cc9170df3560e77982d0db45f3536814f0bd5871c1908bd478cd1ee605167ff82995'),\n ],\n].map((n) => Fp2.fromBigTuple(n));\n// END OF CURVE FIELDS\n// HashToCurve\n// 3-isogeny map from E' to E https://www.rfc-editor.org/rfc/rfc9380#appendix-E.3\nconst isogenyMapG2 = isogenyMap(Fp2, [\n // xNum\n [\n [\n '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6',\n '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6',\n ],\n [\n '0x0',\n '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a',\n ],\n [\n '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e',\n '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d',\n ],\n [\n '0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1',\n '0x0',\n ],\n ],\n // xDen\n [\n [\n '0x0',\n '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63',\n ],\n [\n '0xc',\n '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f',\n ],\n ['0x1', '0x0'], // LAST 1\n ],\n // yNum\n [\n [\n '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706',\n '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706',\n ],\n [\n '0x0',\n '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be',\n ],\n [\n '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c',\n '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f',\n ],\n [\n '0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10',\n '0x0',\n ],\n ],\n // yDen\n [\n [\n '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb',\n '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb',\n ],\n [\n '0x0',\n '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3',\n ],\n [\n '0x12',\n '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99',\n ],\n ['0x1', '0x0'], // LAST 1\n ],\n].map((i) => i.map((pair) => Fp2.fromBigTuple(pair.map(BigInt)))));\n// 11-isogeny map from E' to E\nconst isogenyMapG1 = isogenyMap(Fp, [\n // xNum\n [\n '0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7',\n '0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb',\n '0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0',\n '0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861',\n '0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9',\n '0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983',\n '0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84',\n '0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e',\n '0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317',\n '0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e',\n '0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b',\n '0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229',\n ],\n // xDen\n [\n '0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c',\n '0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff',\n '0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19',\n '0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8',\n '0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e',\n '0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5',\n '0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a',\n '0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e',\n '0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641',\n '0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a',\n '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33',\n '0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696',\n '0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6',\n '0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb',\n '0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb',\n '0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0',\n '0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2',\n '0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29',\n '0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587',\n '0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30',\n '0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132',\n '0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e',\n '0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8',\n '0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133',\n '0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b',\n '0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604',\n ],\n // yDen\n [\n '0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1',\n '0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d',\n '0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2',\n '0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416',\n '0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d',\n '0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac',\n '0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c',\n '0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9',\n '0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a',\n '0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55',\n '0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8',\n '0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092',\n '0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc',\n '0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7',\n '0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f',\n '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n].map((i) => i.map((j) => BigInt(j))));\n// SWU Map - Fp2 to G2': y² = x³ + 240i * x + 1012 + 1012i\nconst G2_SWU = mapToCurveSimpleSWU(Fp2, {\n A: Fp2.create({ c0: Fp.create(_0n), c1: Fp.create(BigInt(240)) }), // A' = 240 * I\n B: Fp2.create({ c0: Fp.create(BigInt(1012)), c1: Fp.create(BigInt(1012)) }), // B' = 1012 * (1 + I)\n Z: Fp2.create({ c0: Fp.create(BigInt(-2)), c1: Fp.create(BigInt(-1)) }), // Z: -(2 + I)\n});\n// Optimized SWU Map - Fp to G1\nconst G1_SWU = mapToCurveSimpleSWU(Fp, {\n A: Fp.create(BigInt('0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d')),\n B: Fp.create(BigInt('0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0')),\n Z: Fp.create(BigInt(11)),\n});\n// Endomorphisms (for fast cofactor clearing)\n// Ψ(P) endomorphism\nconst ut_root = Fp6.create({ c0: Fp2.ZERO, c1: Fp2.ONE, c2: Fp2.ZERO });\nconst wsq = Fp12.create({ c0: ut_root, c1: Fp6.ZERO });\nconst wcu = Fp12.create({ c0: Fp6.ZERO, c1: ut_root });\nconst [wsq_inv, wcu_inv] = Fp12.invertBatch([wsq, wcu]);\nfunction psi(x, y) {\n // Untwist Fp2->Fp12 && frobenius(1) && twist back\n const x2 = Fp12.mul(Fp12.frobeniusMap(Fp12.multiplyByFp2(wsq_inv, x), 1), wsq).c0.c0;\n const y2 = Fp12.mul(Fp12.frobeniusMap(Fp12.multiplyByFp2(wcu_inv, y), 1), wcu).c0.c0;\n return [x2, y2];\n}\n// Ψ endomorphism\nfunction G2psi(c, P) {\n const affine = P.toAffine();\n const p = psi(affine.x, affine.y);\n return new c(p[0], p[1], Fp2.ONE);\n}\n// Ψ²(P) endomorphism\n// 1 / F2(2)^((p-1)/3) in GF(p²)\nconst PSI2_C1 = BigInt('0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac');\nfunction psi2(x, y) {\n return [Fp2.mul(x, PSI2_C1), Fp2.neg(y)];\n}\nfunction G2psi2(c, P) {\n const affine = P.toAffine();\n const p = psi2(affine.x, affine.y);\n return new c(p[0], p[1], Fp2.ONE);\n}\n// Default hash_to_field options are for hash to G2.\n//\n// Parameter definitions are in section 5.3 of the spec unless otherwise noted.\n// Parameter values come from section 8.8.2 of the spec.\n// https://www.rfc-editor.org/rfc/rfc9380#section-8.8.2\n//\n// Base field F is GF(p^m)\n// p = 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab\n// m = 2 (or 1 for G1 see section 8.8.1)\n// k = 128\nconst htfDefaults = Object.freeze({\n // DST: a domain separation tag\n // defined in section 2.2.5\n // Use utils.getDSTLabel(), utils.setDSTLabel(value)\n DST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_',\n encodeDST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_',\n // p: the characteristic of F\n // where F is a finite field of characteristic p and order q = p^m\n p: Fp.ORDER,\n // m: the extension degree of F, m >= 1\n // where F is a finite field of characteristic p and order q = p^m\n m: 2,\n // k: the target security level for the suite in bits\n // defined in section 5.1\n k: 128,\n // option to use a message that has already been processed by\n // expand_message_xmd\n expand: 'xmd',\n // Hash functions for: expand_message_xmd is appropriate for use with a\n // wide range of hash functions, including SHA-2, SHA-3, BLAKE2, and others.\n // BBS+ uses blake2: https://github.com/hyperledger/aries-framework-go/issues/2247\n hash: sha256,\n});\n// Encoding utils\n// Point on G1 curve: (x, y)\n// Compressed point of infinity\nconst COMPRESSED_ZERO = setMask(Fp.toBytes(_0n), { infinity: true, compressed: true }); // set compressed & point-at-infinity bits\nfunction parseMask(bytes) {\n // Copy, so we can remove mask data. It will be removed also later, when Fp.create will call modulo.\n bytes = bytes.slice();\n const mask = bytes[0] & 224;\n const compressed = !!((mask >> 7) & 1); // compression bit (0b1000_0000)\n const infinity = !!((mask >> 6) & 1); // point at infinity bit (0b0100_0000)\n const sort = !!((mask >> 5) & 1); // sort bit (0b0010_0000)\n bytes[0] &= 31; // clear mask (zero first 3 bits)\n return { compressed, infinity, sort, value: bytes };\n}\nfunction setMask(bytes, mask) {\n if (bytes[0] & 224)\n throw new Error('setMask: non-empty mask');\n if (mask.compressed)\n bytes[0] |= 128;\n if (mask.infinity)\n bytes[0] |= 64;\n if (mask.sort)\n bytes[0] |= 32;\n return bytes;\n}\nfunction signatureG1ToRawBytes(point) {\n point.assertValidity();\n const isZero = point.equals(bls12_381.G1.ProjectivePoint.ZERO);\n const { x, y } = point.toAffine();\n if (isZero)\n return COMPRESSED_ZERO.slice();\n const P = Fp.ORDER;\n const sort = Boolean((y * _2n) / P);\n return setMask(numberToBytesBE(x, Fp.BYTES), { compressed: true, sort });\n}\nfunction signatureG2ToRawBytes(point) {\n // NOTE: by some reasons it was missed in bls12-381, looks like bug\n point.assertValidity();\n const len = Fp.BYTES;\n if (point.equals(bls12_381.G2.ProjectivePoint.ZERO))\n return concatB(COMPRESSED_ZERO, numberToBytesBE(_0n, len));\n const { x, y } = point.toAffine();\n const { re: x0, im: x1 } = Fp2.reim(x);\n const { re: y0, im: y1 } = Fp2.reim(y);\n const tmp = y1 > _0n ? y1 * _2n : y0 * _2n;\n const sort = Boolean((tmp / Fp.ORDER) & _1n);\n const z2 = x0;\n return concatB(setMask(numberToBytesBE(x1, len), { sort, compressed: true }), numberToBytesBE(z2, len));\n}\n// To verify curve parameters, see pairing-friendly-curves spec:\n// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-11\n// Basic math is done over finite fields over p.\n// More complicated math is done over polynominal extension fields.\n// To simplify calculations in Fp12, we construct extension tower:\n// Fp₁₂ = Fp₆² => Fp₂³\n// Fp(u) / (u² - β) where β = -1\n// Fp₂(v) / (v³ - ξ) where ξ = u + 1\n// Fp₆(w) / (w² - γ) where γ = v\n// Here goes constants && point encoding format\nexport const bls12_381 = bls({\n // Fields\n fields: {\n Fp,\n Fp2,\n Fp6,\n Fp12,\n Fr,\n },\n // G1 is the order-q subgroup of E1(Fp) : y² = x³ + 4, #E1(Fp) = h1q, where\n // characteristic; z + (z⁴ - z² + 1)(z - 1)²/3\n G1: {\n Fp,\n // cofactor; (z - 1)²/3\n h: BigInt('0x396c8c005555e1568c00aaab0000aaab'),\n // generator's coordinates\n // x = 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507\n // y = 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569\n Gx: BigInt('0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb'),\n Gy: BigInt('0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1'),\n a: Fp.ZERO,\n b: _4n,\n htfDefaults: { ...htfDefaults, m: 1, DST: 'BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_' },\n wrapPrivateKey: true,\n allowInfinityPoint: true,\n // Checks is the point resides in prime-order subgroup.\n // point.isTorsionFree() should return true for valid points\n // It returns false for shitty points.\n // https://eprint.iacr.org/2021/1130.pdf\n isTorsionFree: (c, point) => {\n // φ endomorphism\n const cubicRootOfUnityModP = BigInt('0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe');\n const phi = new c(Fp.mul(point.px, cubicRootOfUnityModP), point.py, point.pz);\n // todo: unroll\n const xP = point.multiplyUnsafe(bls12_381.params.x).negate(); // [x]P\n const u2P = xP.multiplyUnsafe(bls12_381.params.x); // [u2]P\n return u2P.equals(phi);\n // https://eprint.iacr.org/2019/814.pdf\n // (z² − 1)/3\n // const c1 = BigInt('0x396c8c005555e1560000000055555555');\n // const P = this;\n // const S = P.sigma();\n // const Q = S.double();\n // const S2 = S.sigma();\n // // [(z² − 1)/3](2σ(P) − P − σ²(P)) − σ²(P) = O\n // const left = Q.subtract(P).subtract(S2).multiplyUnsafe(c1);\n // const C = left.subtract(S2);\n // return C.isZero();\n },\n // Clear cofactor of G1\n // https://eprint.iacr.org/2019/403\n clearCofactor: (_c, point) => {\n // return this.multiplyUnsafe(CURVE.h);\n return point.multiplyUnsafe(bls12_381.params.x).add(point); // x*P + P\n },\n mapToCurve: (scalars) => {\n const { x, y } = G1_SWU(Fp.create(scalars[0]));\n return isogenyMapG1(x, y);\n },\n fromBytes: (bytes) => {\n const { compressed, infinity, sort, value } = parseMask(bytes);\n if (value.length === 48 && compressed) {\n // TODO: Fp.bytes\n const P = Fp.ORDER;\n const compressedValue = bytesToNumberBE(value);\n // Zero\n const x = Fp.create(compressedValue & Fp.MASK);\n if (infinity) {\n if (x !== _0n)\n throw new Error('G1: non-empty compressed point at infinity');\n return { x: _0n, y: _0n };\n }\n const right = Fp.add(Fp.pow(x, _3n), Fp.create(bls12_381.params.G1b)); // y² = x³ + b\n let y = Fp.sqrt(right);\n if (!y)\n throw new Error('Invalid compressed G1 point');\n if ((y * _2n) / P !== BigInt(sort))\n y = Fp.neg(y);\n return { x: Fp.create(x), y: Fp.create(y) };\n }\n else if (value.length === 96 && !compressed) {\n // Check if the infinity flag is set\n const x = bytesToNumberBE(value.subarray(0, Fp.BYTES));\n const y = bytesToNumberBE(value.subarray(Fp.BYTES));\n if (infinity) {\n if (x !== _0n || y !== _0n)\n throw new Error('G1: non-empty point at infinity');\n return bls12_381.G1.ProjectivePoint.ZERO.toAffine();\n }\n return { x: Fp.create(x), y: Fp.create(y) };\n }\n else {\n throw new Error('Invalid point G1, expected 48/96 bytes');\n }\n },\n toBytes: (c, point, isCompressed) => {\n const isZero = point.equals(c.ZERO);\n const { x, y } = point.toAffine();\n if (isCompressed) {\n if (isZero)\n return COMPRESSED_ZERO.slice();\n const P = Fp.ORDER;\n const sort = Boolean((y * _2n) / P);\n return setMask(numberToBytesBE(x, Fp.BYTES), { compressed: true, sort });\n }\n else {\n if (isZero) {\n // 2x PUBLIC_KEY_LENGTH\n const x = concatB(new Uint8Array([0x40]), new Uint8Array(2 * Fp.BYTES - 1));\n return x;\n }\n else {\n return concatB(numberToBytesBE(x, Fp.BYTES), numberToBytesBE(y, Fp.BYTES));\n }\n }\n },\n ShortSignature: {\n fromHex(hex) {\n const { infinity, sort, value } = parseMask(ensureBytes('signatureHex', hex, 48));\n const P = Fp.ORDER;\n const compressedValue = bytesToNumberBE(value);\n // Zero\n if (infinity)\n return bls12_381.G1.ProjectivePoint.ZERO;\n const x = Fp.create(compressedValue & Fp.MASK);\n const right = Fp.add(Fp.pow(x, _3n), Fp.create(bls12_381.params.G1b)); // y² = x³ + b\n let y = Fp.sqrt(right);\n if (!y)\n throw new Error('Invalid compressed G1 point');\n const aflag = BigInt(sort);\n if ((y * _2n) / P !== aflag)\n y = Fp.neg(y);\n const point = bls12_381.G1.ProjectivePoint.fromAffine({ x, y });\n point.assertValidity();\n return point;\n },\n toRawBytes(point) {\n return signatureG1ToRawBytes(point);\n },\n toHex(point) {\n return bytesToHex(signatureG1ToRawBytes(point));\n },\n },\n },\n // G2 is the order-q subgroup of E2(Fp²) : y² = x³+4(1+√−1),\n // where Fp2 is Fp[√−1]/(x2+1). #E2(Fp2 ) = h2q, where\n // G² - 1\n // h2q\n G2: {\n Fp: Fp2,\n // cofactor\n h: BigInt('0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5'),\n Gx: Fp2.fromBigTuple([\n BigInt('0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8'),\n BigInt('0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e'),\n ]),\n // y =\n // 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582,\n // 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905\n Gy: Fp2.fromBigTuple([\n BigInt('0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801'),\n BigInt('0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be'),\n ]),\n a: Fp2.ZERO,\n b: Fp2.fromBigTuple([_4n, _4n]),\n hEff: BigInt('0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551'),\n htfDefaults: { ...htfDefaults },\n wrapPrivateKey: true,\n allowInfinityPoint: true,\n mapToCurve: (scalars) => {\n const { x, y } = G2_SWU(Fp2.fromBigTuple(scalars));\n return isogenyMapG2(x, y);\n },\n // Checks is the point resides in prime-order subgroup.\n // point.isTorsionFree() should return true for valid points\n // It returns false for shitty points.\n // https://eprint.iacr.org/2021/1130.pdf\n isTorsionFree: (c, P) => {\n return P.multiplyUnsafe(bls12_381.params.x).negate().equals(G2psi(c, P)); // ψ(P) == [u](P)\n // Older version: https://eprint.iacr.org/2019/814.pdf\n // Ψ²(P) => Ψ³(P) => [z]Ψ³(P) where z = -x => [z]Ψ³(P) - Ψ²(P) + P == O\n // return P.psi2().psi().mulNegX().subtract(psi2).add(P).isZero();\n },\n // Maps the point into the prime-order subgroup G2.\n // clear_cofactor_bls12381_g2 from cfrg-hash-to-curve-11\n // https://eprint.iacr.org/2017/419.pdf\n // prettier-ignore\n clearCofactor: (c, P) => {\n const x = bls12_381.params.x;\n let t1 = P.multiplyUnsafe(x).negate(); // [-x]P\n let t2 = G2psi(c, P); // Ψ(P)\n let t3 = P.double(); // 2P\n t3 = G2psi2(c, t3); // Ψ²(2P)\n t3 = t3.subtract(t2); // Ψ²(2P) - Ψ(P)\n t2 = t1.add(t2); // [-x]P + Ψ(P)\n t2 = t2.multiplyUnsafe(x).negate(); // [x²]P - [x]Ψ(P)\n t3 = t3.add(t2); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P)\n t3 = t3.subtract(t1); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P\n const Q = t3.subtract(P); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P - 1P\n return Q; // [x²-x-1]P + [x-1]Ψ(P) + Ψ²(2P)\n },\n fromBytes: (bytes) => {\n const { compressed, infinity, sort, value } = parseMask(bytes);\n if ((!compressed && !infinity && sort) || // 00100000\n (!compressed && infinity && sort) || // 01100000\n (sort && infinity && compressed) // 11100000\n ) {\n throw new Error('Invalid encoding flag: ' + (bytes[0] & 224));\n }\n const L = Fp.BYTES;\n const slc = (b, from, to) => bytesToNumberBE(b.slice(from, to));\n if (value.length === 96 && compressed) {\n const b = bls12_381.params.G2b;\n const P = Fp.ORDER;\n if (infinity) {\n // check that all bytes are 0\n if (value.reduce((p, c) => (p !== 0 ? c + 1 : c), 0) > 0) {\n throw new Error('Invalid compressed G2 point');\n }\n return { x: Fp2.ZERO, y: Fp2.ZERO };\n }\n const x_1 = slc(value, 0, L);\n const x_0 = slc(value, L, 2 * L);\n const x = Fp2.create({ c0: Fp.create(x_0), c1: Fp.create(x_1) });\n const right = Fp2.add(Fp2.pow(x, _3n), b); // y² = x³ + 4 * (u+1) = x³ + b\n let y = Fp2.sqrt(right);\n const Y_bit = y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P ? _1n : _0n;\n y = sort && Y_bit > 0 ? y : Fp2.neg(y);\n return { x, y };\n }\n else if (value.length === 192 && !compressed) {\n if (infinity) {\n if (value.reduce((p, c) => (p !== 0 ? c + 1 : c), 0) > 0) {\n throw new Error('Invalid uncompressed G2 point');\n }\n return { x: Fp2.ZERO, y: Fp2.ZERO };\n }\n const x1 = slc(value, 0, L);\n const x0 = slc(value, L, 2 * L);\n const y1 = slc(value, 2 * L, 3 * L);\n const y0 = slc(value, 3 * L, 4 * L);\n return { x: Fp2.fromBigTuple([x0, x1]), y: Fp2.fromBigTuple([y0, y1]) };\n }\n else {\n throw new Error('Invalid point G2, expected 96/192 bytes');\n }\n },\n toBytes: (c, point, isCompressed) => {\n const { BYTES: len, ORDER: P } = Fp;\n const isZero = point.equals(c.ZERO);\n const { x, y } = point.toAffine();\n if (isCompressed) {\n if (isZero)\n return concatB(COMPRESSED_ZERO, numberToBytesBE(_0n, len));\n const flag = Boolean(y.c1 === _0n ? (y.c0 * _2n) / P : (y.c1 * _2n) / P);\n return concatB(setMask(numberToBytesBE(x.c1, len), { compressed: true, sort: flag }), numberToBytesBE(x.c0, len));\n }\n else {\n if (isZero)\n return concatB(new Uint8Array([0x40]), new Uint8Array(4 * len - 1)); // bytes[0] |= 1 << 6;\n const { re: x0, im: x1 } = Fp2.reim(x);\n const { re: y0, im: y1 } = Fp2.reim(y);\n return concatB(numberToBytesBE(x1, len), numberToBytesBE(x0, len), numberToBytesBE(y1, len), numberToBytesBE(y0, len));\n }\n },\n Signature: {\n // TODO: Optimize, it's very slow because of sqrt.\n fromHex(hex) {\n const { infinity, sort, value } = parseMask(ensureBytes('signatureHex', hex));\n const P = Fp.ORDER;\n const half = value.length / 2;\n if (half !== 48 && half !== 96)\n throw new Error('Invalid compressed signature length, must be 96 or 192');\n const z1 = bytesToNumberBE(value.slice(0, half));\n const z2 = bytesToNumberBE(value.slice(half));\n // Indicates the infinity point\n if (infinity)\n return bls12_381.G2.ProjectivePoint.ZERO;\n const x1 = Fp.create(z1 & Fp.MASK);\n const x2 = Fp.create(z2);\n const x = Fp2.create({ c0: x2, c1: x1 });\n const y2 = Fp2.add(Fp2.pow(x, _3n), bls12_381.params.G2b); // y² = x³ + 4\n // The slow part\n let y = Fp2.sqrt(y2);\n if (!y)\n throw new Error('Failed to find a square root');\n // Choose the y whose leftmost bit of the imaginary part is equal to the a_flag1\n // If y1 happens to be zero, then use the bit of y0\n const { re: y0, im: y1 } = Fp2.reim(y);\n const aflag1 = BigInt(sort);\n const isGreater = y1 > _0n && (y1 * _2n) / P !== aflag1;\n const isZero = y1 === _0n && (y0 * _2n) / P !== aflag1;\n if (isGreater || isZero)\n y = Fp2.neg(y);\n const point = bls12_381.G2.ProjectivePoint.fromAffine({ x, y });\n point.assertValidity();\n return point;\n },\n toRawBytes(point) {\n return signatureG2ToRawBytes(point);\n },\n toHex(point) {\n return bytesToHex(signatureG2ToRawBytes(point));\n },\n },\n },\n params: {\n x: BLS_X, // The BLS parameter x for BLS12-381\n r: Fr.ORDER, // order; z⁴ − z² + 1; CURVE.n from other curves\n },\n htfDefaults,\n hash: sha256,\n randomBytes,\n});\n//# sourceMappingURL=bls12-381.js.map","import * as cbor from './cbor';\nimport { AgentError } from './errors';\nimport { hash } from './request_id';\nimport { bufEquals, concat, fromHex, toHex } from './utils/buffer';\nimport { Principal } from '@dfinity/principal';\nimport * as bls from './utils/bls';\nimport { decodeTime } from './utils/leb';\nimport { MANAGEMENT_CANISTER_ID } from './agent';\n/**\n * A certificate may fail verification with respect to the provided public key\n */\nexport class CertificateVerificationError extends AgentError {\n constructor(reason) {\n super(`Invalid certificate: ${reason}`);\n }\n}\nexport var NodeType;\n(function (NodeType) {\n NodeType[NodeType[\"Empty\"] = 0] = \"Empty\";\n NodeType[NodeType[\"Fork\"] = 1] = \"Fork\";\n NodeType[NodeType[\"Labeled\"] = 2] = \"Labeled\";\n NodeType[NodeType[\"Leaf\"] = 3] = \"Leaf\";\n NodeType[NodeType[\"Pruned\"] = 4] = \"Pruned\";\n})(NodeType || (NodeType = {}));\n/**\n * Make a human readable string out of a hash tree.\n * @param tree\n */\nexport function hashTreeToString(tree) {\n const indent = (s) => s\n .split('\\n')\n .map(x => ' ' + x)\n .join('\\n');\n function labelToString(label) {\n const decoder = new TextDecoder(undefined, { fatal: true });\n try {\n return JSON.stringify(decoder.decode(label));\n }\n catch (e) {\n return `data(...${label.byteLength} bytes)`;\n }\n }\n switch (tree[0]) {\n case NodeType.Empty:\n return '()';\n case NodeType.Fork: {\n if (tree[1] instanceof Array && tree[2] instanceof ArrayBuffer) {\n const left = hashTreeToString(tree[1]);\n const right = hashTreeToString(tree[2]);\n return `sub(\\n left:\\n${indent(left)}\\n---\\n right:\\n${indent(right)}\\n)`;\n }\n else {\n throw new Error('Invalid tree structure for fork');\n }\n }\n case NodeType.Labeled: {\n if (tree[1] instanceof ArrayBuffer && tree[2] instanceof ArrayBuffer) {\n const label = labelToString(tree[1]);\n const sub = hashTreeToString(tree[2]);\n return `label(\\n label:\\n${indent(label)}\\n sub:\\n${indent(sub)}\\n)`;\n }\n else {\n throw new Error('Invalid tree structure for labeled');\n }\n }\n case NodeType.Leaf: {\n if (!tree[1]) {\n throw new Error('Invalid tree structure for leaf');\n }\n else if (Array.isArray(tree[1])) {\n return JSON.stringify(tree[1]);\n }\n return `leaf(...${tree[1].byteLength} bytes)`;\n }\n case NodeType.Pruned: {\n if (!tree[1]) {\n throw new Error('Invalid tree structure for pruned');\n }\n else if (Array.isArray(tree[1])) {\n return JSON.stringify(tree[1]);\n }\n return `pruned(${toHex(new Uint8Array(tree[1]))}`;\n }\n default: {\n return `unknown(${JSON.stringify(tree[0])})`;\n }\n }\n}\nfunction isBufferGreaterThan(a, b) {\n const a8 = new Uint8Array(a);\n const b8 = new Uint8Array(b);\n for (let i = 0; i < a8.length; i++) {\n if (a8[i] > b8[i]) {\n return true;\n }\n }\n return false;\n}\nexport class Certificate {\n constructor(certificate, _rootKey, _canisterId, _blsVerify, \n // Default to 5 minutes\n _maxAgeInMinutes = 5) {\n this._rootKey = _rootKey;\n this._canisterId = _canisterId;\n this._blsVerify = _blsVerify;\n this._maxAgeInMinutes = _maxAgeInMinutes;\n this.cert = cbor.decode(new Uint8Array(certificate));\n }\n /**\n * Create a new instance of a certificate, automatically verifying it. Throws a\n * CertificateVerificationError if the certificate cannot be verified.\n * @constructs Certificate\n * @param {CreateCertificateOptions} options {@link CreateCertificateOptions}\n * @param {ArrayBuffer} options.certificate The bytes of the certificate\n * @param {ArrayBuffer} options.rootKey The root key to verify against\n * @param {Principal} options.canisterId The effective or signing canister ID\n * @param {number} options.maxAgeInMinutes The maximum age of the certificate in minutes. Default is 5 minutes.\n * @throws {CertificateVerificationError}\n */\n static async create(options) {\n const cert = Certificate.createUnverified(options);\n await cert.verify();\n return cert;\n }\n static createUnverified(options) {\n let blsVerify = options.blsVerify;\n if (!blsVerify) {\n blsVerify = bls.blsVerify;\n }\n return new Certificate(options.certificate, options.rootKey, options.canisterId, blsVerify, options.maxAgeInMinutes);\n }\n lookup(path) {\n // constrain the type of the result, so that empty HashTree is undefined\n return lookup_path(path, this.cert.tree);\n }\n lookup_label(label) {\n return this.lookup([label]);\n }\n async verify() {\n const rootHash = await reconstruct(this.cert.tree);\n const derKey = await this._checkDelegationAndGetKey(this.cert.delegation);\n const sig = this.cert.signature;\n const key = extractDER(derKey);\n const msg = concat(domain_sep('ic-state-root'), rootHash);\n let sigVer = false;\n const lookupTime = lookupResultToBuffer(this.lookup(['time']));\n if (!lookupTime) {\n // Should never happen - time is always present in IC certificates\n throw new CertificateVerificationError('Certificate does not contain a time');\n }\n const FIVE_MINUTES_IN_MSEC = 5 * 60 * 1000;\n const MAX_AGE_IN_MSEC = this._maxAgeInMinutes * 60 * 1000;\n const now = Date.now();\n const earliestCertificateTime = now - MAX_AGE_IN_MSEC;\n const fiveMinutesFromNow = now + FIVE_MINUTES_IN_MSEC;\n const certTime = decodeTime(lookupTime);\n if (certTime.getTime() < earliestCertificateTime) {\n throw new CertificateVerificationError(`Certificate is signed more than ${this._maxAgeInMinutes} minutes in the past. Certificate time: ` +\n certTime.toISOString() +\n ' Current time: ' +\n new Date(now).toISOString());\n }\n else if (certTime.getTime() > fiveMinutesFromNow) {\n throw new CertificateVerificationError('Certificate is signed more than 5 minutes in the future. Certificate time: ' +\n certTime.toISOString() +\n ' Current time: ' +\n new Date(now).toISOString());\n }\n try {\n sigVer = await this._blsVerify(new Uint8Array(key), new Uint8Array(sig), new Uint8Array(msg));\n }\n catch (err) {\n sigVer = false;\n }\n if (!sigVer) {\n throw new CertificateVerificationError('Signature verification failed');\n }\n }\n async _checkDelegationAndGetKey(d) {\n if (!d) {\n return this._rootKey;\n }\n const cert = await Certificate.createUnverified({\n certificate: d.certificate,\n rootKey: this._rootKey,\n canisterId: this._canisterId,\n blsVerify: this._blsVerify,\n // Do not check max age for delegation certificates\n maxAgeInMinutes: Infinity,\n });\n if (cert.cert.delegation) {\n throw new CertificateVerificationError('Delegation certificates cannot be nested');\n }\n await cert.verify();\n if (this._canisterId.toString() !== MANAGEMENT_CANISTER_ID) {\n const canisterInRange = check_canister_ranges({\n canisterId: this._canisterId,\n subnetId: Principal.fromUint8Array(new Uint8Array(d.subnet_id)),\n tree: cert.cert.tree,\n });\n if (!canisterInRange) {\n throw new CertificateVerificationError(`Canister ${this._canisterId} not in range of delegations for subnet 0x${toHex(d.subnet_id)}`);\n }\n }\n const publicKeyLookup = lookupResultToBuffer(cert.lookup(['subnet', d.subnet_id, 'public_key']));\n if (!publicKeyLookup) {\n throw new Error(`Could not find subnet key for subnet 0x${toHex(d.subnet_id)}`);\n }\n return publicKeyLookup;\n }\n}\nconst DER_PREFIX = fromHex('308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100');\nconst KEY_LENGTH = 96;\nfunction extractDER(buf) {\n const expectedLength = DER_PREFIX.byteLength + KEY_LENGTH;\n if (buf.byteLength !== expectedLength) {\n throw new TypeError(`BLS DER-encoded public key must be ${expectedLength} bytes long`);\n }\n const prefix = buf.slice(0, DER_PREFIX.byteLength);\n if (!bufEquals(prefix, DER_PREFIX)) {\n throw new TypeError(`BLS DER-encoded public key is invalid. Expect the following prefix: ${DER_PREFIX}, but get ${prefix}`);\n }\n return buf.slice(DER_PREFIX.byteLength);\n}\n/**\n * utility function to constrain the type of a path\n * @param {ArrayBuffer | HashTree | undefined} result - the result of a lookup\n * @returns ArrayBuffer or Undefined\n */\nexport function lookupResultToBuffer(result) {\n if (result.status !== LookupStatus.Found) {\n return undefined;\n }\n if (result.value instanceof ArrayBuffer) {\n return result.value;\n }\n if (result.value instanceof Uint8Array) {\n return result.value.buffer;\n }\n return undefined;\n}\n/**\n * @param t\n */\nexport async function reconstruct(t) {\n switch (t[0]) {\n case NodeType.Empty:\n return hash(domain_sep('ic-hashtree-empty'));\n case NodeType.Pruned:\n return t[1];\n case NodeType.Leaf:\n return hash(concat(domain_sep('ic-hashtree-leaf'), t[1]));\n case NodeType.Labeled:\n return hash(concat(domain_sep('ic-hashtree-labeled'), t[1], await reconstruct(t[2])));\n case NodeType.Fork:\n return hash(concat(domain_sep('ic-hashtree-fork'), await reconstruct(t[1]), await reconstruct(t[2])));\n default:\n throw new Error('unreachable');\n }\n}\nfunction domain_sep(s) {\n const len = new Uint8Array([s.length]);\n const str = new TextEncoder().encode(s);\n return concat(len, str);\n}\nexport var LookupStatus;\n(function (LookupStatus) {\n LookupStatus[\"Unknown\"] = \"unknown\";\n LookupStatus[\"Absent\"] = \"absent\";\n LookupStatus[\"Found\"] = \"found\";\n})(LookupStatus || (LookupStatus = {}));\nvar LabelLookupStatus;\n(function (LabelLookupStatus) {\n LabelLookupStatus[\"Less\"] = \"less\";\n LabelLookupStatus[\"Greater\"] = \"greater\";\n})(LabelLookupStatus || (LabelLookupStatus = {}));\nexport function lookup_path(path, tree) {\n if (path.length === 0) {\n switch (tree[0]) {\n case NodeType.Leaf: {\n if (!tree[1]) {\n throw new Error('Invalid tree structure for leaf');\n }\n if (tree[1] instanceof ArrayBuffer) {\n return {\n status: LookupStatus.Found,\n value: tree[1],\n };\n }\n if (tree[1] instanceof Uint8Array) {\n return {\n status: LookupStatus.Found,\n value: tree[1].buffer,\n };\n }\n return {\n status: LookupStatus.Found,\n value: tree[1],\n };\n }\n default: {\n return {\n status: LookupStatus.Found,\n value: tree,\n };\n }\n }\n }\n const label = typeof path[0] === 'string' ? new TextEncoder().encode(path[0]) : path[0];\n const lookupResult = find_label(label, tree);\n switch (lookupResult.status) {\n case LookupStatus.Found: {\n return lookup_path(path.slice(1), lookupResult.value);\n }\n case LabelLookupStatus.Greater:\n case LabelLookupStatus.Less: {\n return {\n status: LookupStatus.Absent,\n };\n }\n default: {\n return lookupResult;\n }\n }\n}\n/**\n * If the tree is a fork, flatten it into an array of trees\n * @param t - the tree to flatten\n * @returns HashTree[] - the flattened tree\n */\nexport function flatten_forks(t) {\n switch (t[0]) {\n case NodeType.Empty:\n return [];\n case NodeType.Fork:\n return flatten_forks(t[1]).concat(flatten_forks(t[2]));\n default:\n return [t];\n }\n}\nexport function find_label(label, tree) {\n switch (tree[0]) {\n // if we have a labelled node, compare the node's label to the one we are\n // looking for\n case NodeType.Labeled:\n // if the label we're searching for is greater than this node's label,\n // we need to keep searching\n if (isBufferGreaterThan(label, tree[1])) {\n return {\n status: LabelLookupStatus.Greater,\n };\n }\n // if the label we're searching for is equal this node's label, we can\n // stop searching and return the found node\n if (bufEquals(label, tree[1])) {\n return {\n status: LookupStatus.Found,\n value: tree[2],\n };\n }\n // if the label we're searching for is not greater than or equal to this\n // node's label, then it's less than this node's label, and we can stop\n // searching because we've looked too far\n return {\n status: LabelLookupStatus.Less,\n };\n // if we have a fork node, we need to search both sides, starting with the left\n case NodeType.Fork:\n // search in the left node\n const leftLookupResult = find_label(label, tree[1]);\n switch (leftLookupResult.status) {\n // if the label we're searching for is greater than the left node lookup,\n // we need to search the right node\n case LabelLookupStatus.Greater: {\n const rightLookupResult = find_label(label, tree[2]);\n // if the label we're searching for is less than the right node lookup,\n // then we can stop searching and say that the label is provably Absent\n if (rightLookupResult.status === LabelLookupStatus.Less) {\n return {\n status: LookupStatus.Absent,\n };\n }\n // if the label we're searching for is less than or equal to the right\n // node lookup, then we let the caller handle it\n return rightLookupResult;\n }\n // if the left node returns an uncertain result, we need to search the\n // right node\n case LookupStatus.Unknown: {\n let rightLookupResult = find_label(label, tree[2]);\n // if the label we're searching for is less than the right node lookup,\n // then we also need to return an uncertain result\n if (rightLookupResult.status === LabelLookupStatus.Less) {\n return {\n status: LookupStatus.Unknown,\n };\n }\n // if the label we're searching for is less than or equal to the right\n // node lookup, then we let the caller handle it\n return rightLookupResult;\n }\n // if the label we're searching for is not greater than the left node\n // lookup, or the result is not uncertain, we stop searching and return\n // whatever the result of the left node lookup was, which can be either\n // Found or Absent\n default: {\n return leftLookupResult;\n }\n }\n // if we encounter a Pruned node, we can't know for certain if the label\n // we're searching for is present or not\n case NodeType.Pruned:\n return {\n status: LookupStatus.Unknown,\n };\n // if the current node is Empty, or a Leaf, we can stop searching because\n // we know for sure that the label we're searching for is not present\n default:\n return {\n status: LookupStatus.Absent,\n };\n }\n}\n/**\n * Check if a canister falls within a range of canisters\n * @param canisterId Principal\n * @param ranges [Principal, Principal][]\n * @returns\n */\nexport function check_canister_ranges(params) {\n const { canisterId, subnetId, tree } = params;\n const rangeLookup = lookup_path(['subnet', subnetId.toUint8Array(), 'canister_ranges'], tree);\n if (rangeLookup.status !== LookupStatus.Found || !(rangeLookup.value instanceof ArrayBuffer)) {\n throw new Error(`Could not find canister ranges for subnet ${subnetId}`);\n }\n const ranges_arr = cbor.decode(rangeLookup.value);\n const ranges = ranges_arr.map(v => [\n Principal.fromUint8Array(v[0]),\n Principal.fromUint8Array(v[1]),\n ]);\n const canisterInRange = ranges.some(r => r[0].ltEq(canisterId) && r[1].gtEq(canisterId));\n return canisterInRange;\n}\n//# sourceMappingURL=certificate.js.map","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","import { HashMD } from './_md.js';\nimport u64 from './_u64.js';\nimport { wrapConstructor } from './utils.js';\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor() {\n super(128, 64, 16, false);\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x6a09e667 | 0;\n this.Al = 0xf3bcc908 | 0;\n this.Bh = 0xbb67ae85 | 0;\n this.Bl = 0x84caa73b | 0;\n this.Ch = 0x3c6ef372 | 0;\n this.Cl = 0xfe94f82b | 0;\n this.Dh = 0xa54ff53a | 0;\n this.Dl = 0x5f1d36f1 | 0;\n this.Eh = 0x510e527f | 0;\n this.El = 0xade682d1 | 0;\n this.Fh = 0x9b05688c | 0;\n this.Fl = 0x2b3e6c1f | 0;\n this.Gh = 0x1f83d9ab | 0;\n this.Gl = 0xfb41bd6b | 0;\n this.Hh = 0x5be0cd19 | 0;\n this.Hl = 0x137e2179 | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nclass SHA512_224 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x8c3d37c8 | 0;\n this.Al = 0x19544da2 | 0;\n this.Bh = 0x73e19966 | 0;\n this.Bl = 0x89dcd4d6 | 0;\n this.Ch = 0x1dfab7ae | 0;\n this.Cl = 0x32ff9c82 | 0;\n this.Dh = 0x679dd514 | 0;\n this.Dl = 0x582f9fcf | 0;\n this.Eh = 0x0f6d2b69 | 0;\n this.El = 0x7bd44da8 | 0;\n this.Fh = 0x77e36f73 | 0;\n this.Fl = 0x04c48942 | 0;\n this.Gh = 0x3f9d85a8 | 0;\n this.Gl = 0x6a1d36c8 | 0;\n this.Hh = 0x1112e6ad | 0;\n this.Hl = 0x91d692a1 | 0;\n this.outputLen = 28;\n }\n}\nclass SHA512_256 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x22312194 | 0;\n this.Al = 0xfc2bf72c | 0;\n this.Bh = 0x9f555fa3 | 0;\n this.Bl = 0xc84c64c2 | 0;\n this.Ch = 0x2393b86b | 0;\n this.Cl = 0x6f53b151 | 0;\n this.Dh = 0x96387719 | 0;\n this.Dl = 0x5940eabd | 0;\n this.Eh = 0x96283ee2 | 0;\n this.El = 0xa88effe3 | 0;\n this.Fh = 0xbe5e1e25 | 0;\n this.Fl = 0x53863992 | 0;\n this.Gh = 0x2b0199fc | 0;\n this.Gl = 0x2c85b8aa | 0;\n this.Hh = 0x0eb72ddc | 0;\n this.Hl = 0x81c52ca2 | 0;\n this.outputLen = 32;\n }\n}\nclass SHA384 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0xcbbb9d5d | 0;\n this.Al = 0xc1059ed8 | 0;\n this.Bh = 0x629a292a | 0;\n this.Bl = 0x367cd507 | 0;\n this.Ch = 0x9159015a | 0;\n this.Cl = 0x3070dd17 | 0;\n this.Dh = 0x152fecd8 | 0;\n this.Dl = 0xf70e5939 | 0;\n this.Eh = 0x67332667 | 0;\n this.El = 0xffc00b31 | 0;\n this.Fh = 0x8eb44a87 | 0;\n this.Fl = 0x68581511 | 0;\n this.Gh = 0xdb0c2e0d | 0;\n this.Gl = 0x64f98fa7 | 0;\n this.Hh = 0x47b5481d | 0;\n this.Hl = 0xbefa4fa4 | 0;\n this.outputLen = 48;\n }\n}\nexport const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());\nexport const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224());\nexport const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256());\nexport const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384());\n//# sourceMappingURL=sha512.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y²\nimport { mod } from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes } from './utils.js';\nimport { wNAF, validateBasic } from './curve.js';\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\nconst VERIFY_DEFAULT = { zip215: true };\nfunction validateOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(curve, {\n hash: 'function',\n a: 'bigint',\n d: 'bigint',\n randomBytes: 'function',\n }, {\n adjustScalarBytes: 'function',\n domain: 'function',\n uvRatio: 'function',\n mapToCurve: 'function',\n });\n // Set defaults\n return Object.freeze({ ...opts });\n}\n// It is not generic twisted curve for now, but ed25519/ed448 generic implementation\nexport function twistedEdwards(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE;\n const MASK = _2n << (BigInt(nByteLength * 8) - _1n);\n const modP = Fp.create; // Function overrides\n // sqrt(u/v)\n const uvRatio = CURVE.uvRatio ||\n ((u, v) => {\n try {\n return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };\n }\n catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP\n const domain = CURVE.domain ||\n ((data, ctx, phflag) => {\n if (ctx.length || phflag)\n throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n const inBig = (n) => typeof n === 'bigint' && _0n < n; // n in [1..]\n const inRange = (n, max) => inBig(n) && inBig(max) && n < max; // n in [1..max-1]\n const in0MaskRange = (n) => n === _0n || inRange(n, MASK); // n in [0..MASK-1]\n function assertInRange(n, max) {\n // n in [1..max-1]\n if (inRange(n, max))\n return n;\n throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`);\n }\n function assertGE0(n) {\n // n in [0..CURVE_ORDER-1]\n return n === _0n ? n : assertInRange(n, CURVE_ORDER); // GE = prime subgroup, not full group\n }\n const pointPrecomputes = new Map();\n function isPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ExtendedPoint expected');\n }\n // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point {\n constructor(ex, ey, ez, et) {\n this.ex = ex;\n this.ey = ey;\n this.ez = ez;\n this.et = et;\n if (!in0MaskRange(ex))\n throw new Error('x required');\n if (!in0MaskRange(ey))\n throw new Error('y required');\n if (!in0MaskRange(ez))\n throw new Error('z required');\n if (!in0MaskRange(et))\n throw new Error('t required');\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n static fromAffine(p) {\n if (p instanceof Point)\n throw new Error('extended point not allowed');\n const { x, y } = p || {};\n if (!in0MaskRange(x) || !in0MaskRange(y))\n throw new Error('invalid affine point');\n return new Point(x, y, _1n, modP(x * y));\n }\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.ez));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n this._WINDOW_SIZE = windowSize;\n pointPrecomputes.delete(this);\n }\n // Not required for fromHex(), which always creates valid points.\n // Could be useful for fromAffine().\n assertValidity() {\n const { a, d } = CURVE;\n if (this.is0())\n throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { ex: X, ey: Y, ez: Z, et: T } = this;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right)\n throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT)\n throw new Error('bad point: equation left != right (2)');\n }\n // Compare one point to another.\n equals(other) {\n isPoint(other);\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n negate() {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));\n }\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double() {\n const { a } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other) {\n isPoint(other);\n const { a, d } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;\n // Faster algo for adding 2 Extended Points when curve's a=-1.\n // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4\n // Cost: 8M + 8add + 2*2.\n // Note: It does not check whether the `other` point is valid.\n if (a === BigInt(-1)) {\n const A = modP((Y1 - X1) * (Y2 + X2));\n const B = modP((Y1 + X1) * (Y2 - X2));\n const F = modP(B - A);\n if (F === _0n)\n return this.double(); // Same point. Tests say it doesn't affect timing\n const C = modP(Z1 * _2n * T2);\n const D = modP(T1 * _2n * Z2);\n const E = D + C;\n const G = B + A;\n const H = D - C;\n const X3 = modP(E * F);\n const Y3 = modP(G * H);\n const T3 = modP(E * H);\n const Z3 = modP(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, pointPrecomputes, n, Point.normalizeZ);\n }\n // Constant-time multiplication.\n multiply(scalar) {\n const { p, f } = this.wNAF(assertInRange(scalar, CURVE_ORDER));\n return Point.normalizeZ([p, f])[0];\n }\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n multiplyUnsafe(scalar) {\n let n = assertGE0(scalar); // 0 <= scalar < CURVE.n\n if (n === _0n)\n return I;\n if (this.equals(I) || n === _1n)\n return this;\n if (this.equals(G))\n return this.wNAF(n).p;\n return wnaf.unsafeLadder(this, n);\n }\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder() {\n return this.multiplyUnsafe(cofactor).is0();\n }\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree() {\n return wnaf.unsafeLadder(this, CURVE_ORDER).is0();\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(iz) {\n const { ex: x, ey: y, ez: z } = this;\n const is0 = this.is0();\n if (iz == null)\n iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily\n const ax = modP(x * iz);\n const ay = modP(y * iz);\n const zz = modP(z * iz);\n if (is0)\n return { x: _0n, y: _1n };\n if (zz !== _1n)\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n }\n clearCofactor() {\n const { h: cofactor } = CURVE;\n if (cofactor === _1n)\n return this;\n return this.multiplyUnsafe(cofactor);\n }\n // Converts hash string or Uint8Array to Point.\n // Uses algo from RFC8032 5.1.3.\n static fromHex(hex, zip215 = false) {\n const { d, a } = CURVE;\n const len = Fp.BYTES;\n hex = ensureBytes('pointHex', hex, len); // copy hex to a new array\n const normed = hex.slice(); // copy again, we'll manipulate it\n const lastByte = hex[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = ut.bytesToNumberLE(normed);\n if (y === _0n) {\n // y=0 is allowed\n }\n else {\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n if (zip215)\n assertInRange(y, MASK); // zip215=true [1..P-1] (2^255-19-1 for ed25519)\n else\n assertInRange(y, Fp.ORDER); // zip215=false [1..MASK-1] (2^256-1 for ed25519)\n }\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid)\n throw new Error('Point.fromHex: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('Point.fromHex: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd)\n x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromPrivateKey(privKey) {\n return getExtendedPublicKey(privKey).point;\n }\n toRawBytes() {\n const { x, y } = this.toAffine();\n const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y\n return bytes; // and use the last byte to encode sign of x\n }\n toHex() {\n return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n const { BASE: G, ZERO: I } = Point;\n const wnaf = wNAF(Point, nByteLength * 8);\n function modN(a) {\n return mod(a, CURVE_ORDER);\n }\n // Little-endian SHA512 with modulo n\n function modN_LE(hash) {\n return modN(ut.bytesToNumberLE(hash));\n }\n /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */\n function getExtendedPublicKey(key) {\n const len = nByteLength;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n const point = G.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toRawBytes(); // Uint8Array representation\n return { head, prefix, scalar, point, pointBytes };\n }\n // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared\n function getPublicKey(privKey) {\n return getExtendedPublicKey(privKey).pointBytes;\n }\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context = new Uint8Array(), ...msgs) {\n const msg = ut.concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg, privKey, options = {}) {\n msg = ensureBytes('message', msg);\n if (prehash)\n msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = G.multiply(r).toRawBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = modN(r + k * scalar); // S = (r + k * s) mod L\n assertGE0(s); // 0 <= s < l\n const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES));\n return ensureBytes('result', res, nByteLength * 2); // 64-byte signature\n }\n const verifyOpts = VERIFY_DEFAULT;\n function verify(sig, msg, publicKey, options = verifyOpts) {\n const { context, zip215 } = options;\n const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.\n msg = ensureBytes('message', msg);\n if (prehash)\n msg = prehash(msg); // for ed25519ph, etc\n const s = ut.bytesToNumberLE(sig.slice(len, 2 * len));\n // zip215: true is good for consensus-critical apps and allows points < 2^256\n // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p\n let A, R, SB;\n try {\n A = Point.fromHex(publicKey, zip215);\n R = Point.fromHex(sig.slice(0, len), zip215);\n SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside\n }\n catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder())\n return false;\n const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);\n }\n G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n const utils = {\n getExtendedPublicKey,\n // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.\n randomPrivateKey: () => randomBytes(Fp.BYTES),\n /**\n * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT\n * values. This slows down first getPublicKey() by milliseconds (see Speed section),\n * but allows to speed-up subsequent getPublicKey() calls up to 20x.\n * @param windowSize 2, 4, 8, 16\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3));\n return point;\n },\n };\n return {\n CURVE,\n getPublicKey,\n sign,\n verify,\n ExtendedPoint: Point,\n utils,\n };\n}\n//# sourceMappingURL=edwards.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha512';\nimport { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils';\nimport { twistedEdwards } from './abstract/edwards.js';\nimport { montgomery } from './abstract/montgomery.js';\nimport { Field, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.js';\nimport { bytesToHex, bytesToNumberLE, ensureBytes, equalBytes, numberToBytesLE, } from './abstract/utils.js';\nimport { createHasher, expand_message_xmd } from './abstract/hash-to-curve.js';\n/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n */\nconst ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949');\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst ED25519_SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _5n = BigInt(5);\n// prettier-ignore\nconst _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\nfunction ed25519_pow_2_252_3(x) {\n const P = ED25519_P;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\nfunction adjustScalarBytes(bytes) {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n// sqrt(u/v)\nfunction uvRatio(u, v) {\n const P = ED25519_P;\n const v3 = mod(v * v * v, P); // v³\n const v7 = mod(v3 * v3 * v, P); // v⁷\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P))\n x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n// Just in case\nexport const ED25519_TORSION_SUBGROUP = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\nconst Fp = Field(ED25519_P, undefined, true);\nconst ed25519Defaults = {\n // Param: a\n a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster\n // d is equal to -121665/121666 over finite field.\n // Negative number is P - number, and division is invert(number, P)\n d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),\n // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n\n Fp,\n // Subgroup order: how many points curve has\n // 2n**252n + 27742317777372353535851937790883648493n;\n n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),\n // Cofactor\n h: BigInt(8),\n // Base point (x, y) aka generator point\n Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),\n Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),\n hash: sha512,\n randomBytes,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/√v\n uvRatio,\n};\nexport const ed25519 = /* @__PURE__ */ twistedEdwards(ed25519Defaults);\nfunction ed25519_domain(data, ctx, phflag) {\n if (ctx.length > 255)\n throw new Error('Context is too big');\n return concatBytes(utf8ToBytes('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);\n}\nexport const ed25519ctx = /* @__PURE__ */ twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n});\nexport const ed25519ph = /* @__PURE__ */ twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n prehash: sha512,\n});\nexport const x25519 = /* @__PURE__ */ (() => montgomery({\n P: ED25519_P,\n a: BigInt(486662),\n montgomeryBits: 255, // n is 253 bits\n nByteLength: 32,\n Gu: BigInt(9),\n powPminus2: (x) => {\n const P = ED25519_P;\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, BigInt(3), P) * b2, P);\n },\n adjustScalarBytes,\n randomBytes,\n}))();\n/**\n * Converts ed25519 public key to x25519 public key. Uses formula:\n * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * @example\n * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());\n * const aPriv = x25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub))\n */\nexport function edwardsToMontgomeryPub(edwardsPub) {\n const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub);\n const _1n = BigInt(1);\n return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y)));\n}\nexport const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated\n/**\n * Converts ed25519 secret key to x25519 secret key.\n * @example\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey());\n * const aPriv = ed25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub)\n */\nexport function edwardsToMontgomeryPriv(edwardsPriv) {\n const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32));\n return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32);\n}\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\nconst ELL2_C1 = (Fp.ORDER + BigInt(3)) / BigInt(8); // 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C2 = Fp.pow(_2n, ELL2_C1); // 2. c2 = 2^c1\nconst ELL2_C3 = Fp.sqrt(Fp.neg(Fp.ONE)); // 3. c3 = sqrt(-1)\nconst ELL2_C4 = (Fp.ORDER - BigInt(5)) / BigInt(8); // 4. c4 = (q - 5) / 8 # Integer arithmetic\nconst ELL2_J = BigInt(486662);\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u) {\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\nconst ELL2_C1_EDWARDS = FpSqrtEven(Fp, Fp.neg(BigInt(486664))); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u) {\n const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n const inv = Fp.invertBatch([xd, yd]); // batch division\n return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd)\n}\nconst htf = /* @__PURE__ */ (() => createHasher(ed25519.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\nfunction assertRstPoint(other) {\n if (!(other instanceof RistPoint))\n throw new Error('RistrettoPoint expected');\n}\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// √(ad - 1)\nconst SQRT_AD_MINUS_ONE = BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');\n// 1 / √(a-d)\nconst INVSQRT_A_MINUS_D = BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');\n// 1-d²\nconst ONE_MINUS_D_SQ = BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');\n// (d-1)²\nconst D_MINUS_ONE_SQ = BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');\n// Calculates 1/√(number)\nconst invertSqrt = (number) => uvRatio(_1n, number);\nconst MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst bytes255ToNumberLE = (bytes) => ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n// Computes Elligator map for Ristretto\n// https://ristretto.group/formulas/elligator.html\nfunction calcElligatorRistrettoMap(r0) {\n const { d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P))\n s_ = mod(-s_);\n if (!Ns_D_is_sq)\n s = s_; // 7\n if (!Ns_D_is_sq)\n c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n/**\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448\n */\nclass RistPoint {\n // Private property to discourage combining ExtendedPoint + RistrettoPoint\n // Always use Ristretto encoding/decoding instead.\n constructor(ep) {\n this.ep = ep;\n }\n static fromAffine(ap) {\n return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap));\n }\n /**\n * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`.\n * The hash-to-group operation applies Elligator twice and adds the results.\n * **Note:** this is one-way map, there is no conversion from point to hash.\n * https://ristretto.group/formulas/elligator.html\n * @param hex 64-byte output of a hash function\n */\n static hashToCurve(hex) {\n hex = ensureBytes('ristrettoHash', hex, 64);\n const r1 = bytes255ToNumberLE(hex.slice(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(hex.slice(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new RistPoint(R1.add(R2));\n }\n /**\n * Converts ristretto-encoded string to ristretto point.\n * https://ristretto.group/formulas/decoding.html\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex) {\n hex = ensureBytes('ristrettoHex', hex, 32);\n const { a, d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';\n const s = bytes255ToNumberLE(hex);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P))\n throw new Error(emsg);\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P))\n x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n)\n throw new Error(emsg);\n return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t));\n }\n /**\n * Encodes ristretto point to Uint8Array.\n * https://ristretto.group/formulas/encoding.html\n */\n toRawBytes() {\n let { ex: x, ey: y, ez: z, et: t } = this.ep;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const u1 = mod(mod(z + y) * mod(z - y)); // 1\n const u2 = mod(x * y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * t); // 6\n let D; // 7\n if (isNegativeLE(t * zInv, P)) {\n let _x = mod(y * SQRT_M1);\n let _y = mod(x * SQRT_M1);\n x = _x;\n y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n }\n else {\n D = D2; // 8\n }\n if (isNegativeLE(x * zInv, P))\n y = mod(-y); // 9\n let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P))\n s = mod(-s);\n return numberToBytesLE(s, 32); // 11\n }\n toHex() {\n return bytesToHex(this.toRawBytes());\n }\n toString() {\n return this.toHex();\n }\n // Compare one point to another.\n equals(other) {\n assertRstPoint(other);\n const { ex: X1, ey: Y1 } = this.ep;\n const { ex: X2, ey: Y2 } = other.ep;\n const mod = ed25519.CURVE.Fp.create;\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n add(other) {\n assertRstPoint(other);\n return new RistPoint(this.ep.add(other.ep));\n }\n subtract(other) {\n assertRstPoint(other);\n return new RistPoint(this.ep.subtract(other.ep));\n }\n multiply(scalar) {\n return new RistPoint(this.ep.multiply(scalar));\n }\n multiplyUnsafe(scalar) {\n return new RistPoint(this.ep.multiplyUnsafe(scalar));\n }\n double() {\n return new RistPoint(this.ep.double());\n }\n negate() {\n return new RistPoint(this.ep.negate());\n }\n}\nexport const RistrettoPoint = /* @__PURE__ */ (() => {\n if (!RistPoint.BASE)\n RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE);\n if (!RistPoint.ZERO)\n RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO);\n return RistPoint;\n})();\n// Hashing to ristretto255. https://www.rfc-editor.org/rfc/rfc9380#appendix-B\nexport const hashToRistretto255 = (msg, options) => {\n const d = options.DST;\n const DST = typeof d === 'string' ? utf8ToBytes(d) : d;\n const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512);\n const P = RistPoint.hashToCurve(uniform_bytes);\n return P;\n};\nexport const hash_to_ristretto255 = hashToRistretto255; // legacy\n//# sourceMappingURL=ed25519.js.map","var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _HttpAgent_instances, _HttpAgent_identity, _HttpAgent_fetch, _HttpAgent_fetchOptions, _HttpAgent_callOptions, _HttpAgent_timeDiffMsecs, _HttpAgent_credentials, _HttpAgent_rootKeyFetched, _HttpAgent_retryTimes, _HttpAgent_backoffStrategy, _HttpAgent_maxIngressExpiryInMinutes, _HttpAgent_waterMark, _HttpAgent_queryPipeline, _HttpAgent_updatePipeline, _HttpAgent_subnetKeys, _HttpAgent_verifyQuerySignatures, _HttpAgent_requestAndRetryQuery, _HttpAgent_requestAndRetry, _HttpAgent_verifyQueryResponse;\nimport { Principal } from '@dfinity/principal';\nimport { AgentError } from '../../errors';\nimport { AnonymousIdentity } from '../../auth';\nimport * as cbor from '../../cbor';\nimport { hashOfMap, requestIdOf } from '../../request_id';\nimport { bufFromBufLike, concat, fromHex } from '../../utils/buffer';\nimport { Expiry, httpHeadersTransform, makeNonceTransform } from './transforms';\nimport { makeNonce, SubmitRequestType, } from './types';\nimport { AgentHTTPResponseError } from './errors';\nimport { request } from '../../canisterStatus';\nimport { CertificateVerificationError, LookupStatus, lookup_path, } from '../../certificate';\nimport { ed25519 } from '@noble/curves/ed25519';\nimport { ExpirableMap } from '../../utils/expirableMap';\nimport { Ed25519PublicKey } from '../../public_key';\nimport { decodeTime } from '../../utils/leb';\nimport { ObservableLog } from '../../observable';\nimport { ExponentialBackoff } from '../../polling/backoff';\nimport { DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS } from '../../constants';\nexport * from './transforms';\nexport { makeNonce } from './types';\nexport var RequestStatusResponseStatus;\n(function (RequestStatusResponseStatus) {\n RequestStatusResponseStatus[\"Received\"] = \"received\";\n RequestStatusResponseStatus[\"Processing\"] = \"processing\";\n RequestStatusResponseStatus[\"Replied\"] = \"replied\";\n RequestStatusResponseStatus[\"Rejected\"] = \"rejected\";\n RequestStatusResponseStatus[\"Unknown\"] = \"unknown\";\n RequestStatusResponseStatus[\"Done\"] = \"done\";\n})(RequestStatusResponseStatus || (RequestStatusResponseStatus = {}));\nconst MINUTE_TO_MSECS = 60 * 1000;\n// Root public key for the IC, encoded as hex\nexport const IC_ROOT_KEY = '308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814' +\n 'c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d968' +\n '5f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484' +\n 'b01291091c5f87b98883463f98091a0baaae';\nexport const MANAGEMENT_CANISTER_ID = 'aaaaa-aa';\n// IC0 domain info\nconst IC0_DOMAIN = 'ic0.app';\nconst IC0_SUB_DOMAIN = '.ic0.app';\nconst ICP0_DOMAIN = 'icp0.io';\nconst ICP0_SUB_DOMAIN = '.icp0.io';\nconst ICP_API_DOMAIN = 'icp-api.io';\nconst ICP_API_SUB_DOMAIN = '.icp-api.io';\nclass HttpDefaultFetchError extends AgentError {\n constructor(message) {\n super(message);\n this.message = message;\n }\n}\nexport class IdentityInvalidError extends AgentError {\n constructor(message) {\n super(message);\n this.message = message;\n }\n}\nfunction getDefaultFetch() {\n let defaultFetch;\n if (typeof window !== 'undefined') {\n // Browser context\n if (window.fetch) {\n defaultFetch = window.fetch.bind(window);\n }\n else {\n throw new HttpDefaultFetchError('Fetch implementation was not available. You appear to be in a browser context, but window.fetch was not present.');\n }\n }\n else if (typeof global !== 'undefined') {\n // Node context\n if (global.fetch) {\n defaultFetch = global.fetch.bind(global);\n }\n else {\n throw new HttpDefaultFetchError('Fetch implementation was not available. You appear to be in a Node.js context, but global.fetch was not available.');\n }\n }\n else if (typeof self !== 'undefined') {\n if (self.fetch) {\n defaultFetch = self.fetch.bind(self);\n }\n }\n if (defaultFetch) {\n return defaultFetch;\n }\n throw new HttpDefaultFetchError('Fetch implementation was not available. Please provide fetch to the HttpAgent constructor, or ensure it is available in the window or global context.');\n}\nfunction determineHost(configuredHost) {\n let host;\n if (configuredHost !== undefined) {\n if (!configuredHost.match(/^[a-z]+:/) && typeof window !== 'undefined') {\n host = new URL(window.location.protocol + '//' + configuredHost);\n }\n else {\n host = new URL(configuredHost);\n }\n }\n else {\n // Mainnet, local, and remote environments will have the api route available\n const knownHosts = ['ic0.app', 'icp0.io', '127.0.0.1', 'localhost'];\n const remoteHosts = ['.github.dev', '.gitpod.io'];\n const location = typeof window !== 'undefined' ? window.location : undefined;\n const hostname = location === null || location === void 0 ? void 0 : location.hostname;\n let knownHost;\n if (hostname && typeof hostname === 'string') {\n if (remoteHosts.some(host => hostname.endsWith(host))) {\n knownHost = hostname;\n }\n else {\n knownHost = knownHosts.find(host => hostname.endsWith(host));\n }\n }\n if (location && knownHost) {\n // If the user is on a boundary-node provided host, we can use the same host for the agent\n host = new URL(`${location.protocol}//${knownHost}${location.port ? ':' + location.port : ''}`);\n }\n else {\n host = new URL('https://icp-api.io');\n }\n }\n return host.toString();\n}\n/**\n * A HTTP agent allows users to interact with a client of the internet computer\nusing the available methods. It exposes an API that closely follows the\npublic view of the internet computer, and is not intended to be exposed\ndirectly to the majority of users due to its low-level interface.\n * There is a pipeline to apply transformations to the request before sending\nit to the client. This is to decouple signature, nonce generation and\nother computations so that this class can stay as simple as possible while\nallowing extensions.\n */\nexport class HttpAgent {\n /**\n * @param options - Options for the HttpAgent\n * @deprecated Use `HttpAgent.create` or `HttpAgent.createSync` instead\n */\n constructor(options = {}) {\n var _a;\n _HttpAgent_instances.add(this);\n _HttpAgent_identity.set(this, void 0);\n _HttpAgent_fetch.set(this, void 0);\n _HttpAgent_fetchOptions.set(this, void 0);\n _HttpAgent_callOptions.set(this, void 0);\n _HttpAgent_timeDiffMsecs.set(this, 0);\n _HttpAgent_credentials.set(this, void 0);\n _HttpAgent_rootKeyFetched.set(this, false);\n _HttpAgent_retryTimes.set(this, void 0); // Retry requests N times before erroring by default\n _HttpAgent_backoffStrategy.set(this, void 0);\n _HttpAgent_maxIngressExpiryInMinutes.set(this, void 0);\n // Public signature to help with type checking.\n this._isAgent = true;\n this.config = {};\n // The UTC time in milliseconds when the latest request was made\n _HttpAgent_waterMark.set(this, 0);\n this.log = new ObservableLog();\n _HttpAgent_queryPipeline.set(this, []);\n _HttpAgent_updatePipeline.set(this, []);\n _HttpAgent_subnetKeys.set(this, new ExpirableMap({\n expirationTime: 5 * 60 * 1000, // 5 minutes\n }));\n _HttpAgent_verifyQuerySignatures.set(this, true);\n /**\n * See https://internetcomputer.org/docs/current/references/ic-interface-spec/#http-query for details on validation\n * @param queryResponse - The response from the query\n * @param subnetStatus - The subnet status, including all node keys\n * @returns ApiQueryResponse\n */\n _HttpAgent_verifyQueryResponse.set(this, (queryResponse, subnetStatus) => {\n if (__classPrivateFieldGet(this, _HttpAgent_verifyQuerySignatures, \"f\") === false) {\n // This should not be called if the user has disabled verification\n return queryResponse;\n }\n if (!subnetStatus) {\n throw new CertificateVerificationError('Invalid signature from replica signed query: no matching node key found.');\n }\n const { status, signatures = [], requestId } = queryResponse;\n const domainSeparator = new TextEncoder().encode('\\x0Bic-response');\n for (const sig of signatures) {\n const { timestamp, identity } = sig;\n const nodeId = Principal.fromUint8Array(identity).toText();\n let hash;\n // Hash is constructed differently depending on the status\n if (status === 'replied') {\n const { reply } = queryResponse;\n hash = hashOfMap({\n status: status,\n reply: reply,\n timestamp: BigInt(timestamp),\n request_id: requestId,\n });\n }\n else if (status === 'rejected') {\n const { reject_code, reject_message, error_code } = queryResponse;\n hash = hashOfMap({\n status: status,\n reject_code: reject_code,\n reject_message: reject_message,\n error_code: error_code,\n timestamp: BigInt(timestamp),\n request_id: requestId,\n });\n }\n else {\n throw new Error(`Unknown status: ${status}`);\n }\n const separatorWithHash = concat(domainSeparator, new Uint8Array(hash));\n // FIX: check for match without verifying N times\n const pubKey = subnetStatus === null || subnetStatus === void 0 ? void 0 : subnetStatus.nodeKeys.get(nodeId);\n if (!pubKey) {\n throw new CertificateVerificationError('Invalid signature from replica signed query: no matching node key found.');\n }\n const rawKey = Ed25519PublicKey.fromDer(pubKey).rawKey;\n const valid = ed25519.verify(sig.signature, new Uint8Array(separatorWithHash), new Uint8Array(rawKey));\n if (valid)\n return queryResponse;\n throw new CertificateVerificationError(`Invalid signature from replica ${nodeId} signed query.`);\n }\n return queryResponse;\n });\n this.config = options;\n __classPrivateFieldSet(this, _HttpAgent_fetch, options.fetch || getDefaultFetch() || fetch.bind(global), \"f\");\n __classPrivateFieldSet(this, _HttpAgent_fetchOptions, options.fetchOptions, \"f\");\n __classPrivateFieldSet(this, _HttpAgent_callOptions, options.callOptions, \"f\");\n this.rootKey = options.rootKey ? options.rootKey : fromHex(IC_ROOT_KEY);\n const host = determineHost(options.host);\n this.host = new URL(host);\n if (options.verifyQuerySignatures !== undefined) {\n __classPrivateFieldSet(this, _HttpAgent_verifyQuerySignatures, options.verifyQuerySignatures, \"f\");\n }\n // Default is 3\n __classPrivateFieldSet(this, _HttpAgent_retryTimes, (_a = options.retryTimes) !== null && _a !== void 0 ? _a : 3, \"f\");\n // Delay strategy for retries. Default is exponential backoff\n const defaultBackoffFactory = () => new ExponentialBackoff({\n maxIterations: __classPrivateFieldGet(this, _HttpAgent_retryTimes, \"f\"),\n });\n __classPrivateFieldSet(this, _HttpAgent_backoffStrategy, options.backoffStrategy || defaultBackoffFactory, \"f\");\n // Rewrite to avoid redirects\n if (this.host.hostname.endsWith(IC0_SUB_DOMAIN)) {\n this.host.hostname = IC0_DOMAIN;\n }\n else if (this.host.hostname.endsWith(ICP0_SUB_DOMAIN)) {\n this.host.hostname = ICP0_DOMAIN;\n }\n else if (this.host.hostname.endsWith(ICP_API_SUB_DOMAIN)) {\n this.host.hostname = ICP_API_DOMAIN;\n }\n if (options.credentials) {\n const { name, password } = options.credentials;\n __classPrivateFieldSet(this, _HttpAgent_credentials, `${name}${password ? ':' + password : ''}`, \"f\");\n }\n __classPrivateFieldSet(this, _HttpAgent_identity, Promise.resolve(options.identity || new AnonymousIdentity()), \"f\");\n if (options.ingressExpiryInMinutes && options.ingressExpiryInMinutes > 5) {\n throw new AgentError(`The maximum ingress expiry time is 5 minutes. Provided ingress expiry time is ${options.ingressExpiryInMinutes} minutes.`);\n }\n if (options.ingressExpiryInMinutes && options.ingressExpiryInMinutes <= 0) {\n throw new AgentError(`Ingress expiry time must be greater than 0. Provided ingress expiry time is ${options.ingressExpiryInMinutes} minutes.`);\n }\n __classPrivateFieldSet(this, _HttpAgent_maxIngressExpiryInMinutes, options.ingressExpiryInMinutes || 5, \"f\");\n // Add a nonce transform to ensure calls are unique\n this.addTransform('update', makeNonceTransform(makeNonce));\n if (options.useQueryNonces) {\n this.addTransform('query', makeNonceTransform(makeNonce));\n }\n if (options.logToConsole) {\n this.log.subscribe(log => {\n if (log.level === 'error') {\n console.error(log.message);\n }\n else if (log.level === 'warn') {\n console.warn(log.message);\n }\n else {\n console.log(log.message);\n }\n });\n }\n }\n get waterMark() {\n return __classPrivateFieldGet(this, _HttpAgent_waterMark, \"f\");\n }\n static createSync(options = {}) {\n return new this(Object.assign({}, options));\n }\n static async create(options = {\n shouldFetchRootKey: false,\n }) {\n const agent = HttpAgent.createSync(options);\n const initPromises = [agent.syncTime()];\n if (agent.host.toString() !== 'https://icp-api.io' && options.shouldFetchRootKey) {\n initPromises.push(agent.fetchRootKey());\n }\n await Promise.all(initPromises);\n return agent;\n }\n static async from(agent) {\n var _a;\n try {\n if ('config' in agent) {\n return await HttpAgent.create(agent.config);\n }\n return await HttpAgent.create({\n fetch: agent._fetch,\n fetchOptions: agent._fetchOptions,\n callOptions: agent._callOptions,\n host: agent._host.toString(),\n identity: (_a = agent._identity) !== null && _a !== void 0 ? _a : undefined,\n });\n }\n catch (_b) {\n throw new AgentError('Failed to create agent from provided agent');\n }\n }\n isLocal() {\n const hostname = this.host.hostname;\n return hostname === '127.0.0.1' || hostname.endsWith('127.0.0.1');\n }\n addTransform(type, fn, priority = fn.priority || 0) {\n if (type === 'update') {\n // Keep the pipeline sorted at all time, by priority.\n const i = __classPrivateFieldGet(this, _HttpAgent_updatePipeline, \"f\").findIndex(x => (x.priority || 0) < priority);\n __classPrivateFieldGet(this, _HttpAgent_updatePipeline, \"f\").splice(i >= 0 ? i : __classPrivateFieldGet(this, _HttpAgent_updatePipeline, \"f\").length, 0, Object.assign(fn, { priority }));\n }\n else if (type === 'query') {\n // Keep the pipeline sorted at all time, by priority.\n const i = __classPrivateFieldGet(this, _HttpAgent_queryPipeline, \"f\").findIndex(x => (x.priority || 0) < priority);\n __classPrivateFieldGet(this, _HttpAgent_queryPipeline, \"f\").splice(i >= 0 ? i : __classPrivateFieldGet(this, _HttpAgent_queryPipeline, \"f\").length, 0, Object.assign(fn, { priority }));\n }\n }\n async getPrincipal() {\n if (!__classPrivateFieldGet(this, _HttpAgent_identity, \"f\")) {\n throw new IdentityInvalidError(\"This identity has expired due this application's security policy. Please refresh your authentication.\");\n }\n return (await __classPrivateFieldGet(this, _HttpAgent_identity, \"f\")).getPrincipal();\n }\n async call(canisterId, options, identity) {\n var _a;\n // TODO - restore this value\n const callSync = (_a = options.callSync) !== null && _a !== void 0 ? _a : true;\n const id = await (identity !== undefined ? await identity : await __classPrivateFieldGet(this, _HttpAgent_identity, \"f\"));\n if (!id) {\n throw new IdentityInvalidError(\"This identity has expired due this application's security policy. Please refresh your authentication.\");\n }\n const canister = Principal.from(canisterId);\n const ecid = options.effectiveCanisterId\n ? Principal.from(options.effectiveCanisterId)\n : canister;\n const sender = id.getPrincipal() || Principal.anonymous();\n let ingress_expiry = new Expiry(__classPrivateFieldGet(this, _HttpAgent_maxIngressExpiryInMinutes, \"f\") * MINUTE_TO_MSECS);\n // If the value is off by more than 30 seconds, reconcile system time with the network\n if (Math.abs(__classPrivateFieldGet(this, _HttpAgent_timeDiffMsecs, \"f\")) > 1000 * 30) {\n ingress_expiry = new Expiry(__classPrivateFieldGet(this, _HttpAgent_maxIngressExpiryInMinutes, \"f\") * MINUTE_TO_MSECS + __classPrivateFieldGet(this, _HttpAgent_timeDiffMsecs, \"f\"));\n }\n const submit = {\n request_type: SubmitRequestType.Call,\n canister_id: canister,\n method_name: options.methodName,\n arg: options.arg,\n sender,\n ingress_expiry,\n };\n let transformedRequest = (await this._transform({\n request: {\n body: null,\n method: 'POST',\n headers: Object.assign({ 'Content-Type': 'application/cbor' }, (__classPrivateFieldGet(this, _HttpAgent_credentials, \"f\") ? { Authorization: 'Basic ' + btoa(__classPrivateFieldGet(this, _HttpAgent_credentials, \"f\")) } : {})),\n },\n endpoint: \"call\" /* Endpoint.Call */,\n body: submit,\n }));\n const nonce = transformedRequest.body.nonce\n ? toNonce(transformedRequest.body.nonce)\n : undefined;\n submit.nonce = nonce;\n function toNonce(buf) {\n return new Uint8Array(buf);\n }\n // Apply transform for identity.\n transformedRequest = (await id.transformRequest(transformedRequest));\n const body = cbor.encode(transformedRequest.body);\n const backoff = __classPrivateFieldGet(this, _HttpAgent_backoffStrategy, \"f\").call(this);\n try {\n // Attempt v3 sync call\n const requestSync = () => {\n this.log.print(`fetching \"/api/v3/canister/${ecid.toText()}/call\" with request:`, transformedRequest);\n return __classPrivateFieldGet(this, _HttpAgent_fetch, \"f\").call(this, '' + new URL(`/api/v3/canister/${ecid.toText()}/call`, this.host), Object.assign(Object.assign(Object.assign({}, __classPrivateFieldGet(this, _HttpAgent_callOptions, \"f\")), transformedRequest.request), { body }));\n };\n const requestAsync = () => {\n this.log.print(`fetching \"/api/v2/canister/${ecid.toText()}/call\" with request:`, transformedRequest);\n return __classPrivateFieldGet(this, _HttpAgent_fetch, \"f\").call(this, '' + new URL(`/api/v2/canister/${ecid.toText()}/call`, this.host), Object.assign(Object.assign(Object.assign({}, __classPrivateFieldGet(this, _HttpAgent_callOptions, \"f\")), transformedRequest.request), { body }));\n };\n const request = __classPrivateFieldGet(this, _HttpAgent_instances, \"m\", _HttpAgent_requestAndRetry).call(this, {\n request: callSync ? requestSync : requestAsync,\n backoff,\n tries: 0,\n });\n const requestId = requestIdOf(submit);\n const response = await request;\n const responseBuffer = await response.arrayBuffer();\n const responseBody = (response.status === 200 && responseBuffer.byteLength > 0\n ? cbor.decode(responseBuffer)\n : null);\n // Update the watermark with the latest time from consensus\n if (responseBody && 'certificate' in responseBody) {\n const time = await this.parseTimeFromResponse({\n certificate: responseBody.certificate,\n });\n __classPrivateFieldSet(this, _HttpAgent_waterMark, time, \"f\");\n }\n return {\n requestId,\n response: {\n ok: response.ok,\n status: response.status,\n statusText: response.statusText,\n body: responseBody,\n headers: httpHeadersTransform(response.headers),\n },\n requestDetails: submit,\n };\n }\n catch (error) {\n // If the error is due to the v3 api not being supported, fall back to v2\n if (error.message.includes('v3 api not supported.')) {\n this.log.warn('v3 api not supported. Fall back to v2');\n return this.call(canisterId, Object.assign(Object.assign({}, options), { \n // disable v3 api\n callSync: false }), identity);\n }\n this.log.error('Error while making call:', error);\n throw error;\n }\n }\n async query(canisterId, fields, identity) {\n const backoff = __classPrivateFieldGet(this, _HttpAgent_backoffStrategy, \"f\").call(this);\n const ecid = fields.effectiveCanisterId\n ? Principal.from(fields.effectiveCanisterId)\n : Principal.from(canisterId);\n this.log.print(`ecid ${ecid.toString()}`);\n this.log.print(`canisterId ${canisterId.toString()}`);\n const makeQuery = async () => {\n const id = await (identity !== undefined ? identity : __classPrivateFieldGet(this, _HttpAgent_identity, \"f\"));\n if (!id) {\n throw new IdentityInvalidError(\"This identity has expired due this application's security policy. Please refresh your authentication.\");\n }\n const canister = Principal.from(canisterId);\n const sender = (id === null || id === void 0 ? void 0 : id.getPrincipal()) || Principal.anonymous();\n const request = {\n request_type: \"query\" /* ReadRequestType.Query */,\n canister_id: canister,\n method_name: fields.methodName,\n arg: fields.arg,\n sender,\n ingress_expiry: new Expiry(__classPrivateFieldGet(this, _HttpAgent_maxIngressExpiryInMinutes, \"f\") * MINUTE_TO_MSECS),\n };\n const requestId = requestIdOf(request);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let transformedRequest = await this._transform({\n request: {\n method: 'POST',\n headers: Object.assign({ 'Content-Type': 'application/cbor' }, (__classPrivateFieldGet(this, _HttpAgent_credentials, \"f\") ? { Authorization: 'Basic ' + btoa(__classPrivateFieldGet(this, _HttpAgent_credentials, \"f\")) } : {})),\n },\n endpoint: \"read\" /* Endpoint.Query */,\n body: request,\n });\n // Apply transform for identity.\n transformedRequest = (await (id === null || id === void 0 ? void 0 : id.transformRequest(transformedRequest)));\n const body = cbor.encode(transformedRequest.body);\n const args = {\n canister: canister.toText(),\n ecid,\n transformedRequest,\n body,\n requestId,\n backoff,\n tries: 0,\n };\n return {\n requestDetails: request,\n query: await __classPrivateFieldGet(this, _HttpAgent_instances, \"m\", _HttpAgent_requestAndRetryQuery).call(this, args),\n };\n };\n const getSubnetStatus = async () => {\n if (!__classPrivateFieldGet(this, _HttpAgent_verifyQuerySignatures, \"f\")) {\n return undefined;\n }\n const subnetStatus = __classPrivateFieldGet(this, _HttpAgent_subnetKeys, \"f\").get(ecid.toString());\n if (subnetStatus) {\n return subnetStatus;\n }\n await this.fetchSubnetKeys(ecid.toString());\n return __classPrivateFieldGet(this, _HttpAgent_subnetKeys, \"f\").get(ecid.toString());\n };\n // Attempt to make the query i=retryTimes times\n // Make query and fetch subnet keys in parallel\n const [queryResult, subnetStatus] = await Promise.all([makeQuery(), getSubnetStatus()]);\n const { requestDetails, query } = queryResult;\n const queryWithDetails = Object.assign(Object.assign({}, query), { requestDetails });\n this.log.print('Query response:', queryWithDetails);\n // Skip verification if the user has disabled it\n if (!__classPrivateFieldGet(this, _HttpAgent_verifyQuerySignatures, \"f\")) {\n return queryWithDetails;\n }\n try {\n return __classPrivateFieldGet(this, _HttpAgent_verifyQueryResponse, \"f\").call(this, queryWithDetails, subnetStatus);\n }\n catch (_a) {\n // In case the node signatures have changed, refresh the subnet keys and try again\n this.log.warn('Query response verification failed. Retrying with fresh subnet keys.');\n __classPrivateFieldGet(this, _HttpAgent_subnetKeys, \"f\").delete(canisterId.toString());\n await this.fetchSubnetKeys(ecid.toString());\n const updatedSubnetStatus = __classPrivateFieldGet(this, _HttpAgent_subnetKeys, \"f\").get(canisterId.toString());\n if (!updatedSubnetStatus) {\n throw new CertificateVerificationError('Invalid signature from replica signed query: no matching node key found.');\n }\n return __classPrivateFieldGet(this, _HttpAgent_verifyQueryResponse, \"f\").call(this, queryWithDetails, updatedSubnetStatus);\n }\n }\n async createReadStateRequest(fields, identity) {\n const id = await (identity !== undefined ? await identity : await __classPrivateFieldGet(this, _HttpAgent_identity, \"f\"));\n if (!id) {\n throw new IdentityInvalidError(\"This identity has expired due this application's security policy. Please refresh your authentication.\");\n }\n const sender = (id === null || id === void 0 ? void 0 : id.getPrincipal()) || Principal.anonymous();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const transformedRequest = await this._transform({\n request: {\n method: 'POST',\n headers: Object.assign({ 'Content-Type': 'application/cbor' }, (__classPrivateFieldGet(this, _HttpAgent_credentials, \"f\") ? { Authorization: 'Basic ' + btoa(__classPrivateFieldGet(this, _HttpAgent_credentials, \"f\")) } : {})),\n },\n endpoint: \"read_state\" /* Endpoint.ReadState */,\n body: {\n request_type: \"read_state\" /* ReadRequestType.ReadState */,\n paths: fields.paths,\n sender,\n ingress_expiry: new Expiry(__classPrivateFieldGet(this, _HttpAgent_maxIngressExpiryInMinutes, \"f\") * MINUTE_TO_MSECS),\n },\n });\n // Apply transform for identity.\n return id === null || id === void 0 ? void 0 : id.transformRequest(transformedRequest);\n }\n async readState(canisterId, fields, identity, \n // eslint-disable-next-line\n request) {\n const canister = typeof canisterId === 'string' ? Principal.fromText(canisterId) : canisterId;\n const transformedRequest = request !== null && request !== void 0 ? request : (await this.createReadStateRequest(fields, identity));\n // With read_state, we should always use a fresh expiry, even beyond the point where the initial request would have expired\n const bodyWithAdjustedExpiry = Object.assign(Object.assign({}, transformedRequest.body), { ingress_expiry: new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS) });\n const body = cbor.encode(bodyWithAdjustedExpiry);\n this.log.print(`fetching \"/api/v2/canister/${canister}/read_state\" with request:`, transformedRequest);\n // TODO - https://dfinity.atlassian.net/browse/SDK-1092\n const backoff = __classPrivateFieldGet(this, _HttpAgent_backoffStrategy, \"f\").call(this);\n try {\n const response = await __classPrivateFieldGet(this, _HttpAgent_instances, \"m\", _HttpAgent_requestAndRetry).call(this, {\n request: () => __classPrivateFieldGet(this, _HttpAgent_fetch, \"f\").call(this, '' + new URL(`/api/v2/canister/${canister.toString()}/read_state`, this.host), Object.assign(Object.assign(Object.assign({}, __classPrivateFieldGet(this, _HttpAgent_fetchOptions, \"f\")), transformedRequest.request), { body })),\n backoff,\n tries: 0,\n });\n if (!response.ok) {\n throw new Error(`Server returned an error:\\n` +\n ` Code: ${response.status} (${response.statusText})\\n` +\n ` Body: ${await response.text()}\\n`);\n }\n const decodedResponse = cbor.decode(await response.arrayBuffer());\n this.log.print('Read state response:', decodedResponse);\n const parsedTime = await this.parseTimeFromResponse(decodedResponse);\n if (parsedTime > 0) {\n this.log.print('Read state response time:', parsedTime);\n __classPrivateFieldSet(this, _HttpAgent_waterMark, parsedTime, \"f\");\n }\n return decodedResponse;\n }\n catch (error) {\n this.log.error('Caught exception while attempting to read state', error);\n throw error;\n }\n }\n async parseTimeFromResponse(response) {\n let tree;\n if (response.certificate) {\n const decoded = cbor.decode(response.certificate);\n if (decoded && 'tree' in decoded) {\n tree = decoded.tree;\n }\n else {\n throw new Error('Could not decode time from response');\n }\n const timeLookup = lookup_path(['time'], tree);\n if (timeLookup.status !== LookupStatus.Found) {\n throw new Error('Time was not found in the response or was not in its expected format.');\n }\n if (!(timeLookup.value instanceof ArrayBuffer) && !ArrayBuffer.isView(timeLookup)) {\n throw new Error('Time was not found in the response or was not in its expected format.');\n }\n const date = decodeTime(bufFromBufLike(timeLookup.value));\n this.log.print('Time from response:', date);\n this.log.print('Time from response in milliseconds:', Number(date));\n return Number(date);\n }\n else {\n this.log.warn('No certificate found in response');\n }\n return 0;\n }\n /**\n * Allows agent to sync its time with the network. Can be called during intialization or mid-lifecycle if the device's clock has drifted away from the network time. This is necessary to set the Expiry for a request\n * @param {Principal} canisterId - Pass a canister ID if you need to sync the time with a particular replica. Uses the management canister by default\n */\n async syncTime(canisterId) {\n const CanisterStatus = await import('../../canisterStatus');\n const callTime = Date.now();\n try {\n if (!canisterId) {\n this.log.print('Syncing time with the IC. No canisterId provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai');\n }\n const status = await CanisterStatus.request({\n // Fall back with canisterId of the ICP Ledger\n canisterId: canisterId !== null && canisterId !== void 0 ? canisterId : Principal.from('ryjl3-tyaaa-aaaaa-aaaba-cai'),\n agent: this,\n paths: ['time'],\n });\n const replicaTime = status.get('time');\n if (replicaTime) {\n __classPrivateFieldSet(this, _HttpAgent_timeDiffMsecs, Number(replicaTime) - Number(callTime), \"f\");\n }\n }\n catch (error) {\n this.log.error('Caught exception while attempting to sync time', error);\n }\n }\n async status() {\n const headers = __classPrivateFieldGet(this, _HttpAgent_credentials, \"f\")\n ? {\n Authorization: 'Basic ' + btoa(__classPrivateFieldGet(this, _HttpAgent_credentials, \"f\")),\n }\n : {};\n this.log.print(`fetching \"/api/v2/status\"`);\n const backoff = __classPrivateFieldGet(this, _HttpAgent_backoffStrategy, \"f\").call(this);\n const response = await __classPrivateFieldGet(this, _HttpAgent_instances, \"m\", _HttpAgent_requestAndRetry).call(this, {\n backoff,\n request: () => __classPrivateFieldGet(this, _HttpAgent_fetch, \"f\").call(this, '' + new URL(`/api/v2/status`, this.host), Object.assign({ headers }, __classPrivateFieldGet(this, _HttpAgent_fetchOptions, \"f\"))),\n tries: 0,\n });\n return cbor.decode(await response.arrayBuffer());\n }\n async fetchRootKey() {\n if (!__classPrivateFieldGet(this, _HttpAgent_rootKeyFetched, \"f\")) {\n const status = await this.status();\n // Hex-encoded version of the replica root key\n this.rootKey = status.root_key;\n __classPrivateFieldSet(this, _HttpAgent_rootKeyFetched, true, \"f\");\n }\n return this.rootKey;\n }\n invalidateIdentity() {\n __classPrivateFieldSet(this, _HttpAgent_identity, null, \"f\");\n }\n replaceIdentity(identity) {\n __classPrivateFieldSet(this, _HttpAgent_identity, Promise.resolve(identity), \"f\");\n }\n async fetchSubnetKeys(canisterId) {\n const effectiveCanisterId = Principal.from(canisterId);\n const response = await request({\n canisterId: effectiveCanisterId,\n paths: ['subnet'],\n agent: this,\n });\n const subnetResponse = response.get('subnet');\n if (subnetResponse && typeof subnetResponse === 'object' && 'nodeKeys' in subnetResponse) {\n __classPrivateFieldGet(this, _HttpAgent_subnetKeys, \"f\").set(effectiveCanisterId.toText(), subnetResponse);\n return subnetResponse;\n }\n // If the subnet status is not returned, return undefined\n return undefined;\n }\n _transform(request) {\n let p = Promise.resolve(request);\n if (request.endpoint === \"call\" /* Endpoint.Call */) {\n for (const fn of __classPrivateFieldGet(this, _HttpAgent_updatePipeline, \"f\")) {\n p = p.then(r => fn(r).then(r2 => r2 || r));\n }\n }\n else {\n for (const fn of __classPrivateFieldGet(this, _HttpAgent_queryPipeline, \"f\")) {\n p = p.then(r => fn(r).then(r2 => r2 || r));\n }\n }\n return p;\n }\n}\n_HttpAgent_identity = new WeakMap(), _HttpAgent_fetch = new WeakMap(), _HttpAgent_fetchOptions = new WeakMap(), _HttpAgent_callOptions = new WeakMap(), _HttpAgent_timeDiffMsecs = new WeakMap(), _HttpAgent_credentials = new WeakMap(), _HttpAgent_rootKeyFetched = new WeakMap(), _HttpAgent_retryTimes = new WeakMap(), _HttpAgent_backoffStrategy = new WeakMap(), _HttpAgent_maxIngressExpiryInMinutes = new WeakMap(), _HttpAgent_waterMark = new WeakMap(), _HttpAgent_queryPipeline = new WeakMap(), _HttpAgent_updatePipeline = new WeakMap(), _HttpAgent_subnetKeys = new WeakMap(), _HttpAgent_verifyQuerySignatures = new WeakMap(), _HttpAgent_verifyQueryResponse = new WeakMap(), _HttpAgent_instances = new WeakSet(), _HttpAgent_requestAndRetryQuery = async function _HttpAgent_requestAndRetryQuery(args) {\n var _a, _b;\n const { ecid, transformedRequest, body, requestId, backoff, tries } = args;\n const delay = tries === 0 ? 0 : backoff.next();\n this.log.print(`fetching \"/api/v2/canister/${ecid.toString()}/query\" with tries:`, {\n tries,\n backoff,\n delay,\n });\n // If delay is null, the backoff strategy is exhausted due to a maximum number of retries, duration, or other reason\n if (delay === null) {\n throw new AgentError(`Timestamp failed to pass the watermark after retrying the configured ${__classPrivateFieldGet(this, _HttpAgent_retryTimes, \"f\")} times. We cannot guarantee the integrity of the response since it could be a replay attack.`);\n }\n if (delay > 0) {\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n let response;\n // Make the request and retry if it throws an error\n try {\n this.log.print(`fetching \"/api/v2/canister/${ecid.toString()}/query\" with request:`, transformedRequest);\n const fetchResponse = await __classPrivateFieldGet(this, _HttpAgent_fetch, \"f\").call(this, '' + new URL(`/api/v2/canister/${ecid.toString()}/query`, this.host), Object.assign(Object.assign(Object.assign({}, __classPrivateFieldGet(this, _HttpAgent_fetchOptions, \"f\")), transformedRequest.request), { body }));\n if (fetchResponse.status === 200) {\n const queryResponse = cbor.decode(await fetchResponse.arrayBuffer());\n response = Object.assign(Object.assign({}, queryResponse), { httpDetails: {\n ok: fetchResponse.ok,\n status: fetchResponse.status,\n statusText: fetchResponse.statusText,\n headers: httpHeadersTransform(fetchResponse.headers),\n }, requestId });\n }\n else {\n throw new AgentHTTPResponseError(`Gateway returned an error:\\n` +\n ` Code: ${fetchResponse.status} (${fetchResponse.statusText})\\n` +\n ` Body: ${await fetchResponse.text()}\\n`, {\n ok: fetchResponse.ok,\n status: fetchResponse.status,\n statusText: fetchResponse.statusText,\n headers: httpHeadersTransform(fetchResponse.headers),\n });\n }\n }\n catch (error) {\n if (tries < __classPrivateFieldGet(this, _HttpAgent_retryTimes, \"f\")) {\n this.log.warn(`Caught exception while attempting to make query:\\n` +\n ` ${error}\\n` +\n ` Retrying query.`);\n return await __classPrivateFieldGet(this, _HttpAgent_instances, \"m\", _HttpAgent_requestAndRetryQuery).call(this, Object.assign(Object.assign({}, args), { tries: tries + 1 }));\n }\n throw error;\n }\n const timestamp = (_b = (_a = response.signatures) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.timestamp;\n // Skip watermark verification if the user has set verifyQuerySignatures to false\n if (!__classPrivateFieldGet(this, _HttpAgent_verifyQuerySignatures, \"f\")) {\n return response;\n }\n if (!timestamp) {\n throw new Error('Timestamp not found in query response. This suggests a malformed or malicious response.');\n }\n // Convert the timestamp to milliseconds\n const timeStampInMs = Number(BigInt(timestamp) / BigInt(1000000));\n this.log.print('watermark and timestamp', {\n waterMark: this.waterMark,\n timestamp: timeStampInMs,\n });\n // If the timestamp is less than the watermark, retry the request up to the retry limit\n if (Number(this.waterMark) > timeStampInMs) {\n const error = new AgentError('Timestamp is below the watermark. Retrying query.');\n this.log.error('Timestamp is below', error, {\n timestamp,\n waterMark: this.waterMark,\n });\n if (tries < __classPrivateFieldGet(this, _HttpAgent_retryTimes, \"f\")) {\n return await __classPrivateFieldGet(this, _HttpAgent_instances, \"m\", _HttpAgent_requestAndRetryQuery).call(this, Object.assign(Object.assign({}, args), { tries: tries + 1 }));\n }\n {\n throw new AgentError(`Timestamp failed to pass the watermark after retrying the configured ${__classPrivateFieldGet(this, _HttpAgent_retryTimes, \"f\")} times. We cannot guarantee the integrity of the response since it could be a replay attack.`);\n }\n }\n return response;\n}, _HttpAgent_requestAndRetry = async function _HttpAgent_requestAndRetry(args) {\n const { request, backoff, tries } = args;\n const delay = tries === 0 ? 0 : backoff.next();\n // If delay is null, the backoff strategy is exhausted due to a maximum number of retries, duration, or other reason\n if (delay === null) {\n throw new AgentError(`Timestamp failed to pass the watermark after retrying the configured ${__classPrivateFieldGet(this, _HttpAgent_retryTimes, \"f\")} times. We cannot guarantee the integrity of the response since it could be a replay attack.`);\n }\n if (delay > 0) {\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n let response;\n try {\n response = await request();\n }\n catch (error) {\n if (__classPrivateFieldGet(this, _HttpAgent_retryTimes, \"f\") > tries) {\n this.log.warn(`Caught exception while attempting to make request:\\n` +\n ` ${error}\\n` +\n ` Retrying request.`);\n // Delay the request by the configured backoff strategy\n return await __classPrivateFieldGet(this, _HttpAgent_instances, \"m\", _HttpAgent_requestAndRetry).call(this, { request, backoff, tries: tries + 1 });\n }\n throw error;\n }\n if (response.ok) {\n return response;\n }\n const responseText = await response.clone().text();\n const errorMessage = `Server returned an error:\\n` +\n ` Code: ${response.status} (${response.statusText})\\n` +\n ` Body: ${responseText}\\n`;\n if (response.status === 404 && response.url.includes('api/v3')) {\n throw new AgentHTTPResponseError('v3 api not supported. Fall back to v2', {\n ok: response.ok,\n status: response.status,\n statusText: response.statusText,\n headers: httpHeadersTransform(response.headers),\n });\n }\n if (tries < __classPrivateFieldGet(this, _HttpAgent_retryTimes, \"f\")) {\n return await __classPrivateFieldGet(this, _HttpAgent_instances, \"m\", _HttpAgent_requestAndRetry).call(this, { request, backoff, tries: tries + 1 });\n }\n throw new AgentHTTPResponseError(errorMessage, {\n ok: response.ok,\n status: response.status,\n statusText: response.statusText,\n headers: httpHeadersTransform(response.headers),\n });\n};\n//# sourceMappingURL=index.js.map","import { Principal } from '@dfinity/principal';\nexport var ProxyMessageKind;\n(function (ProxyMessageKind) {\n ProxyMessageKind[\"Error\"] = \"err\";\n ProxyMessageKind[\"GetPrincipal\"] = \"gp\";\n ProxyMessageKind[\"GetPrincipalResponse\"] = \"gpr\";\n ProxyMessageKind[\"Query\"] = \"q\";\n ProxyMessageKind[\"QueryResponse\"] = \"qr\";\n ProxyMessageKind[\"Call\"] = \"c\";\n ProxyMessageKind[\"CallResponse\"] = \"cr\";\n ProxyMessageKind[\"ReadState\"] = \"rs\";\n ProxyMessageKind[\"ReadStateResponse\"] = \"rsr\";\n ProxyMessageKind[\"Status\"] = \"s\";\n ProxyMessageKind[\"StatusResponse\"] = \"sr\";\n})(ProxyMessageKind || (ProxyMessageKind = {}));\n// A Stub Agent that forwards calls to another Agent implementation.\nexport class ProxyStubAgent {\n constructor(_frontend, _agent) {\n this._frontend = _frontend;\n this._agent = _agent;\n }\n onmessage(msg) {\n switch (msg.type) {\n case ProxyMessageKind.GetPrincipal:\n this._agent.getPrincipal().then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.GetPrincipalResponse,\n response: response.toText(),\n });\n });\n break;\n case ProxyMessageKind.Query:\n this._agent.query(...msg.args).then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.QueryResponse,\n response,\n });\n });\n break;\n case ProxyMessageKind.Call:\n this._agent.call(...msg.args).then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.CallResponse,\n response,\n });\n });\n break;\n case ProxyMessageKind.ReadState:\n this._agent.readState(...msg.args).then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.ReadStateResponse,\n response,\n });\n });\n break;\n case ProxyMessageKind.Status:\n this._agent.status().then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.StatusResponse,\n response,\n });\n });\n break;\n default:\n throw new Error(`Invalid message received: ${JSON.stringify(msg)}`);\n }\n }\n}\n// An Agent that forwards calls to a backend. The calls are serialized\nexport class ProxyAgent {\n constructor(_backend) {\n this._backend = _backend;\n this._nextId = 0;\n this._pendingCalls = new Map();\n this.rootKey = null;\n }\n onmessage(msg) {\n const id = msg.id;\n const maybePromise = this._pendingCalls.get(id);\n if (!maybePromise) {\n throw new Error('A proxy get the same message twice...');\n }\n this._pendingCalls.delete(id);\n const [resolve, reject] = maybePromise;\n switch (msg.type) {\n case ProxyMessageKind.Error:\n return reject(msg.error);\n case ProxyMessageKind.GetPrincipalResponse:\n case ProxyMessageKind.CallResponse:\n case ProxyMessageKind.QueryResponse:\n case ProxyMessageKind.ReadStateResponse:\n case ProxyMessageKind.StatusResponse:\n return resolve(msg.response);\n default:\n throw new Error(`Invalid message being sent to ProxyAgent: ${JSON.stringify(msg)}`);\n }\n }\n async getPrincipal() {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.GetPrincipal,\n }).then(principal => {\n if (typeof principal !== 'string') {\n throw new Error('Invalid principal received.');\n }\n return Principal.fromText(principal);\n });\n }\n readState(canisterId, fields) {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.ReadState,\n args: [canisterId.toString(), fields],\n });\n }\n call(canisterId, fields) {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.Call,\n args: [canisterId.toString(), fields],\n });\n }\n status() {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.Status,\n });\n }\n query(canisterId, fields) {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.Query,\n args: [canisterId.toString(), fields],\n });\n }\n async _sendAndWait(msg) {\n return new Promise((resolve, reject) => {\n this._pendingCalls.set(msg.id, [resolve, reject]);\n this._backend(msg);\n });\n }\n async fetchRootKey() {\n // Hex-encoded version of the replica root key\n const rootKey = (await this.status()).root_key;\n this.rootKey = rootKey;\n return rootKey;\n }\n}\n//# sourceMappingURL=proxy.js.map","import { bufEquals } from './utils/buffer';\nexport const encodeLenBytes = (len) => {\n if (len <= 0x7f) {\n return 1;\n }\n else if (len <= 0xff) {\n return 2;\n }\n else if (len <= 0xffff) {\n return 3;\n }\n else if (len <= 0xffffff) {\n return 4;\n }\n else {\n throw new Error('Length too long (> 4 bytes)');\n }\n};\nexport const encodeLen = (buf, offset, len) => {\n if (len <= 0x7f) {\n buf[offset] = len;\n return 1;\n }\n else if (len <= 0xff) {\n buf[offset] = 0x81;\n buf[offset + 1] = len;\n return 2;\n }\n else if (len <= 0xffff) {\n buf[offset] = 0x82;\n buf[offset + 1] = len >> 8;\n buf[offset + 2] = len;\n return 3;\n }\n else if (len <= 0xffffff) {\n buf[offset] = 0x83;\n buf[offset + 1] = len >> 16;\n buf[offset + 2] = len >> 8;\n buf[offset + 3] = len;\n return 4;\n }\n else {\n throw new Error('Length too long (> 4 bytes)');\n }\n};\nexport const decodeLenBytes = (buf, offset) => {\n if (buf[offset] < 0x80)\n return 1;\n if (buf[offset] === 0x80)\n throw new Error('Invalid length 0');\n if (buf[offset] === 0x81)\n return 2;\n if (buf[offset] === 0x82)\n return 3;\n if (buf[offset] === 0x83)\n return 4;\n throw new Error('Length too long (> 4 bytes)');\n};\nexport const decodeLen = (buf, offset) => {\n const lenBytes = decodeLenBytes(buf, offset);\n if (lenBytes === 1)\n return buf[offset];\n else if (lenBytes === 2)\n return buf[offset + 1];\n else if (lenBytes === 3)\n return (buf[offset + 1] << 8) + buf[offset + 2];\n else if (lenBytes === 4)\n return (buf[offset + 1] << 16) + (buf[offset + 2] << 8) + buf[offset + 3];\n throw new Error('Length too long (> 4 bytes)');\n};\n/**\n * A DER encoded `SEQUENCE(OID)` for DER-encoded-COSE\n */\nexport const DER_COSE_OID = Uint8Array.from([\n ...[0x30, 0x0c],\n ...[0x06, 0x0a],\n ...[0x2b, 0x06, 0x01, 0x04, 0x01, 0x83, 0xb8, 0x43, 0x01, 0x01], // DER encoded COSE\n]);\n/**\n * A DER encoded `SEQUENCE(OID)` for the Ed25519 algorithm\n */\nexport const ED25519_OID = Uint8Array.from([\n ...[0x30, 0x05],\n ...[0x06, 0x03],\n ...[0x2b, 0x65, 0x70], // id-Ed25519 OID\n]);\n/**\n * A DER encoded `SEQUENCE(OID)` for secp256k1 with the ECDSA algorithm\n */\nexport const SECP256K1_OID = Uint8Array.from([\n ...[0x30, 0x10],\n ...[0x06, 0x07],\n ...[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01],\n ...[0x06, 0x05],\n ...[0x2b, 0x81, 0x04, 0x00, 0x0a], // OID secp256k1\n]);\n/**\n * Wraps the given `payload` in a DER encoding tagged with the given encoded `oid` like so:\n * `SEQUENCE(oid, BITSTRING(payload))`\n *\n * @param payload The payload to encode as the bit string\n * @param oid The DER encoded (and SEQUENCE wrapped!) OID to tag the payload with\n */\nexport function wrapDER(payload, oid) {\n // The Bit String header needs to include the unused bit count byte in its length\n const bitStringHeaderLength = 2 + encodeLenBytes(payload.byteLength + 1);\n const len = oid.byteLength + bitStringHeaderLength + payload.byteLength;\n let offset = 0;\n const buf = new Uint8Array(1 + encodeLenBytes(len) + len);\n // Sequence\n buf[offset++] = 0x30;\n // Sequence Length\n offset += encodeLen(buf, offset, len);\n // OID\n buf.set(oid, offset);\n offset += oid.byteLength;\n // Bit String Header\n buf[offset++] = 0x03;\n offset += encodeLen(buf, offset, payload.byteLength + 1);\n // 0 padding\n buf[offset++] = 0x00;\n buf.set(new Uint8Array(payload), offset);\n return buf;\n}\n/**\n * Extracts a payload from the given `derEncoded` data, and checks that it was tagged with the given `oid`.\n *\n * `derEncoded = SEQUENCE(oid, BITSTRING(payload))`\n *\n * @param derEncoded The DER encoded and tagged data\n * @param oid The DER encoded (and SEQUENCE wrapped!) expected OID\n * @returns The unwrapped payload\n */\nexport const unwrapDER = (derEncoded, oid) => {\n let offset = 0;\n const expect = (n, msg) => {\n if (buf[offset++] !== n) {\n throw new Error('Expected: ' + msg);\n }\n };\n const buf = new Uint8Array(derEncoded);\n expect(0x30, 'sequence');\n offset += decodeLenBytes(buf, offset);\n if (!bufEquals(buf.slice(offset, offset + oid.byteLength), oid)) {\n throw new Error('Not the expected OID.');\n }\n offset += oid.byteLength;\n expect(0x03, 'bit string');\n const payloadLen = decodeLen(buf, offset) - 1; // Subtracting 1 to account for the 0 padding\n offset += decodeLenBytes(buf, offset);\n expect(0x00, '0 padding');\n const result = buf.slice(offset);\n if (payloadLen !== result.length) {\n throw new Error(`DER payload mismatch: Expected length ${payloadLen} actual length ${result.length}`);\n }\n return result;\n};\n//# sourceMappingURL=der.js.map","var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _Ed25519PublicKey_rawKey, _Ed25519PublicKey_derKey, _Ed25519KeyIdentity_publicKey, _Ed25519KeyIdentity_privateKey;\nimport { bufEquals } from '@dfinity/agent';\nimport { SignIdentity, uint8ToBuf, ED25519_OID, unwrapDER, wrapDER, fromHex, toHex, bufFromBufLike, } from '@dfinity/agent';\nimport { ed25519 } from '@noble/curves/ed25519';\nfunction isObject(value) {\n return value !== null && typeof value === 'object';\n}\nexport class Ed25519PublicKey {\n // `fromRaw` and `fromDer` should be used for instantiation, not this constructor.\n constructor(key) {\n _Ed25519PublicKey_rawKey.set(this, void 0);\n _Ed25519PublicKey_derKey.set(this, void 0);\n if (key.byteLength !== Ed25519PublicKey.RAW_KEY_LENGTH) {\n throw new Error('An Ed25519 public key must be exactly 32bytes long');\n }\n __classPrivateFieldSet(this, _Ed25519PublicKey_rawKey, key, \"f\");\n __classPrivateFieldSet(this, _Ed25519PublicKey_derKey, Ed25519PublicKey.derEncode(key), \"f\");\n }\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 static from(maybeKey) {\n if (typeof maybeKey === 'string') {\n const key = fromHex(maybeKey);\n return this.fromRaw(key);\n }\n else if (isObject(maybeKey)) {\n const key = maybeKey;\n if (isObject(key) && Object.hasOwnProperty.call(key, '__derEncodedPublicKey__')) {\n return this.fromDer(key);\n }\n else if (ArrayBuffer.isView(key)) {\n const view = key;\n return this.fromRaw(bufFromBufLike(view.buffer));\n }\n else if (key instanceof ArrayBuffer) {\n return this.fromRaw(key);\n }\n else if ('rawKey' in key) {\n return this.fromRaw(key.rawKey);\n }\n else if ('derKey' in key) {\n return this.fromDer(key.derKey);\n }\n else if ('toDer' in key) {\n return this.fromDer(key.toDer());\n }\n }\n throw new Error('Cannot construct Ed25519PublicKey from the provided key.');\n }\n static fromRaw(rawKey) {\n return new Ed25519PublicKey(rawKey);\n }\n static fromDer(derKey) {\n return new Ed25519PublicKey(this.derDecode(derKey));\n }\n static derEncode(publicKey) {\n const key = wrapDER(publicKey, ED25519_OID).buffer;\n key.__derEncodedPublicKey__ = undefined;\n return key;\n }\n static derDecode(key) {\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 get rawKey() {\n return __classPrivateFieldGet(this, _Ed25519PublicKey_rawKey, \"f\");\n }\n get derKey() {\n return __classPrivateFieldGet(this, _Ed25519PublicKey_derKey, \"f\");\n }\n toDer() {\n return this.derKey;\n }\n toRaw() {\n return this.rawKey;\n }\n}\n_Ed25519PublicKey_rawKey = new WeakMap(), _Ed25519PublicKey_derKey = new WeakMap();\n// The length of Ed25519 public keys is always 32 bytes.\nEd25519PublicKey.RAW_KEY_LENGTH = 32;\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 // `fromRaw` and `fromDer` should be used for instantiation, not this constructor.\n constructor(publicKey, privateKey) {\n super();\n _Ed25519KeyIdentity_publicKey.set(this, void 0);\n _Ed25519KeyIdentity_privateKey.set(this, void 0);\n __classPrivateFieldSet(this, _Ed25519KeyIdentity_publicKey, Ed25519PublicKey.from(publicKey), \"f\");\n __classPrivateFieldSet(this, _Ed25519KeyIdentity_privateKey, new Uint8Array(privateKey), \"f\");\n }\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 static generate(seed) {\n if (seed && seed.length !== 32) {\n throw new Error('Ed25519 Seed needs to be 32 bytes long.');\n }\n if (!seed)\n 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++)\n sk[i] = new Uint8Array(seed)[i];\n const pk = ed25519.getPublicKey(sk);\n return Ed25519KeyIdentity.fromKeyPair(pk, sk);\n }\n static fromParsedJson(obj) {\n const [publicKeyDer, privateKeyRaw] = obj;\n return new Ed25519KeyIdentity(Ed25519PublicKey.fromDer(fromHex(publicKeyDer)), fromHex(privateKeyRaw));\n }\n static fromJSON(json) {\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 }\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 static fromKeyPair(publicKey, privateKey) {\n return new Ed25519KeyIdentity(Ed25519PublicKey.fromRaw(publicKey), privateKey);\n }\n static fromSecretKey(secretKey) {\n const publicKey = ed25519.getPublicKey(new Uint8Array(secretKey));\n return Ed25519KeyIdentity.fromKeyPair(publicKey, secretKey);\n }\n /**\n * Serialize this key to JSON.\n */\n toJSON() {\n return [toHex(__classPrivateFieldGet(this, _Ed25519KeyIdentity_publicKey, \"f\").toDer()), toHex(__classPrivateFieldGet(this, _Ed25519KeyIdentity_privateKey, \"f\"))];\n }\n /**\n * Return a copy of the key pair.\n */\n getKeyPair() {\n return {\n secretKey: __classPrivateFieldGet(this, _Ed25519KeyIdentity_privateKey, \"f\"),\n publicKey: __classPrivateFieldGet(this, _Ed25519KeyIdentity_publicKey, \"f\"),\n };\n }\n /**\n * Return the public key.\n */\n getPublicKey() {\n return __classPrivateFieldGet(this, _Ed25519KeyIdentity_publicKey, \"f\");\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 async sign(challenge) {\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, __classPrivateFieldGet(this, _Ed25519KeyIdentity_privateKey, \"f\").slice(0, 32)));\n // add { __signature__: void; } to the signature to make it compatible with the agent\n Object.defineProperty(signature, '__signature__', {\n enumerable: false,\n value: undefined,\n });\n return signature;\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 static verify(sig, msg, pk) {\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_Ed25519KeyIdentity_publicKey = new WeakMap(), _Ed25519KeyIdentity_privateKey = new WeakMap();\n//# sourceMappingURL=ed25519.js.map","import { SignIdentity } from '@dfinity/agent';\nexport class CryptoError extends Error {\n constructor(message) {\n super(message);\n this.message = message;\n Object.setPrototypeOf(this, CryptoError.prototype);\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) {\n if (typeof global !== 'undefined' && global['crypto'] && global['crypto']['subtle']) {\n return global['crypto']['subtle'];\n }\n if (subtleCrypto) {\n return subtleCrypto;\n }\n else if (typeof crypto !== 'undefined' && crypto['subtle']) {\n return crypto.subtle;\n }\n else {\n throw new CryptoError('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 * 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 // `fromKeyPair` and `generate` should be used for instantiation, not this constructor.\n constructor(keyPair, derKey, subtleCrypto) {\n super();\n this._keyPair = keyPair;\n this._derKey = derKey;\n this._subtleCrypto = subtleCrypto;\n }\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 static async generate(options) {\n const { extractable = false, keyUsages = ['sign', 'verify'], subtleCrypto } = options !== null && options !== void 0 ? options : {};\n const effectiveCrypto = _getEffectiveCrypto(subtleCrypto);\n const keyPair = await effectiveCrypto.generateKey({\n name: 'ECDSA',\n namedCurve: 'P-256',\n }, extractable, keyUsages);\n const derKey = (await effectiveCrypto.exportKey('spki', keyPair.publicKey));\n return new this(keyPair, derKey, effectiveCrypto);\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 static async fromKeyPair(keyPair, subtleCrypto) {\n const effectiveCrypto = _getEffectiveCrypto(subtleCrypto);\n const derKey = (await effectiveCrypto.exportKey('spki', keyPair.publicKey));\n return new ECDSAKeyIdentity(keyPair, derKey, effectiveCrypto);\n }\n /**\n * Return the internally-used key pair.\n * @returns a CryptoKeyPair\n */\n getKeyPair() {\n return this._keyPair;\n }\n /**\n * Return the public key.\n * @returns an {@link PublicKey & DerCryptoKey}\n */\n getPublicKey() {\n const derKey = this._derKey;\n const key = Object.create(this._keyPair.publicKey);\n key.toDer = function () {\n return derKey;\n };\n return key;\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\n */\n async sign(challenge) {\n const params = {\n name: 'ECDSA',\n hash: { name: 'SHA-256' },\n };\n const signature = await this._subtleCrypto.sign(params, this._keyPair.privateKey, challenge);\n return signature;\n }\n}\nexport default ECDSAKeyIdentity;\n//# sourceMappingURL=ecdsa.js.map","var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nvar _PartialDelegationIdentity_delegation;\nimport { fromHex, requestIdOf, SignIdentity, toHex, } from '@dfinity/agent';\nimport { Principal } from '@dfinity/principal';\nimport * as cbor from 'simple-cbor';\nimport { PartialIdentity } from './partial';\nconst domainSeparator = new TextEncoder().encode('\\x1Aic-request-auth-delegation');\nconst requestDomainSeparator = new TextEncoder().encode('\\x0Aic-request');\nfunction _parseBlob(value) {\n if (typeof value !== 'string' || value.length < 64) {\n throw new Error('Invalid public key.');\n }\n return fromHex(value);\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(pubkey, expiration, targets) {\n this.pubkey = pubkey;\n this.expiration = expiration;\n this.targets = targets;\n }\n toCBOR() {\n // Expiration field needs to be encoded as a u64 specifically.\n return cbor.value.map(Object.assign({ pubkey: cbor.value.bytes(this.pubkey), expiration: cbor.value.u64(this.expiration.toString(16), 16) }, (this.targets && {\n targets: cbor.value.array(this.targets.map(t => cbor.value.bytes(t.toUint8Array()))),\n })));\n }\n toJSON() {\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 Object.assign({ expiration: this.expiration.toString(16), pubkey: toHex(this.pubkey) }, (this.targets && { targets: this.targets.map(p => p.toHex()) }));\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(from, to, expiration, targets) {\n const delegation = new Delegation(to.toDer(), BigInt(+expiration) * BigInt(1000000), // In nanoseconds.\n targets);\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(Object.assign({}, delegation))),\n ]);\n const signature = await from.sign(challenge);\n return {\n delegation,\n signature,\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 constructor(delegations, publicKey) {\n this.delegations = delegations;\n this.publicKey = publicKey;\n }\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 static async create(from, to, expiration = new Date(Date.now() + 15 * 60 * 1000), options = {}) {\n var _a, _b;\n const delegation = await _createSingleDelegation(from, to, expiration, options.targets);\n return new DelegationChain([...(((_a = options.previous) === null || _a === void 0 ? void 0 : _a.delegations) || []), delegation], ((_b = options.previous) === null || _b === void 0 ? void 0 : _b.publicKey) || from.getPublicKey().toDer());\n }\n /**\n * Creates a DelegationChain object from a JSON string.\n * @param json The JSON string to parse.\n */\n static fromJSON(json) {\n const { publicKey, delegations } = typeof json === 'string' ? JSON.parse(json) : json;\n if (!Array.isArray(delegations)) {\n throw new Error('Invalid delegations.');\n }\n const parsedDelegations = 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 return {\n delegation: new Delegation(_parseBlob(pubkey), BigInt('0x' + expiration), // expiration in JSON is an hexa string (See toJSON() below).\n targets &&\n targets.map((t) => {\n if (typeof t !== 'string') {\n throw new Error('Invalid target.');\n }\n return Principal.fromHex(t);\n })),\n signature: _parseBlob(signature),\n };\n });\n return new this(parsedDelegations, _parseBlob(publicKey));\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 static fromDelegations(delegations, publicKey) {\n return new this(delegations, publicKey);\n }\n toJSON() {\n return {\n delegations: this.delegations.map(signedDelegation => {\n const { delegation, signature } = signedDelegation;\n const { targets } = delegation;\n return {\n delegation: Object.assign({ expiration: delegation.expiration.toString(16), pubkey: toHex(delegation.pubkey) }, (targets && {\n targets: targets.map(t => t.toHex()),\n })),\n signature: toHex(signature),\n };\n }),\n publicKey: toHex(this.publicKey),\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 constructor(_inner, _delegation) {\n super();\n this._inner = _inner;\n this._delegation = _delegation;\n }\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 static fromDelegation(key, delegation) {\n return new this(key, delegation);\n }\n getDelegation() {\n return this._delegation;\n }\n getPublicKey() {\n return {\n derKey: this._delegation.publicKey,\n toDer: () => this._delegation.publicKey,\n };\n }\n sign(blob) {\n return this._inner.sign(blob);\n }\n async transformRequest(request) {\n const { body } = request, fields = __rest(request, [\"body\"]);\n const requestId = await requestIdOf(body);\n return Object.assign(Object.assign({}, fields), { body: {\n content: body,\n sender_sig: await this.sign(new Uint8Array([...requestDomainSeparator, ...new Uint8Array(requestId)])),\n sender_delegation: this._delegation.delegations,\n sender_pubkey: this._delegation.publicKey,\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 constructor(inner, delegation) {\n super(inner);\n _PartialDelegationIdentity_delegation.set(this, void 0);\n __classPrivateFieldSet(this, _PartialDelegationIdentity_delegation, delegation, \"f\");\n }\n /**\n * The Delegation Chain of this identity.\n */\n get delegation() {\n return __classPrivateFieldGet(this, _PartialDelegationIdentity_delegation, \"f\");\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 static fromDelegation(key, delegation) {\n return new PartialDelegationIdentity(key, delegation);\n }\n}\n_PartialDelegationIdentity_delegation = new WeakMap();\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, checks) {\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 // Check the scopes.\n const scopes = [];\n const maybeScope = checks === null || checks === void 0 ? void 0 : checks.scope;\n if (maybeScope) {\n if (Array.isArray(maybeScope)) {\n scopes.push(...maybeScope.map(s => (typeof s === 'string' ? Principal.fromText(s) : s)));\n }\n else {\n scopes.push(typeof maybeScope === 'string' ? Principal.fromText(maybeScope) : maybeScope);\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 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 return true;\n}\n//# sourceMappingURL=delegation.js.map","import { SignIdentity, wrapDER, DER_COSE_OID, fromHex, toHex, } from '@dfinity/agent';\nimport borc from 'borc';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { bufFromBufLike } from '@dfinity/candid';\nfunction _coseToDerEncodedBlob(cose) {\n return wrapDER(cose, DER_COSE_OID).buffer;\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) {\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 // Get the public key object.\n return authData.slice(55 + credentialIdLength);\n}\nexport class CosePublicKey {\n constructor(_cose) {\n this._cose = _cose;\n this._encodedKey = _coseToDerEncodedBlob(_cose);\n }\n toDer() {\n return this._encodedKey;\n }\n getCose() {\n return this._cose;\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 = '') {\n if (typeof challenge === 'string') {\n return Uint8Array.from(challenge, c => c.charCodeAt(0));\n }\n else {\n return challenge;\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(credentialCreationOptions) {\n const creds = (await navigator.credentials.create(credentialCreationOptions !== null && credentialCreationOptions !== void 0 ? 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 if (creds === null) {\n return null;\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// 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.\nvar PubKeyCoseAlgo;\n(function (PubKeyCoseAlgo) {\n PubKeyCoseAlgo[PubKeyCoseAlgo[\"ECDSA_WITH_SHA256\"] = -7] = \"ECDSA_WITH_SHA256\";\n})(PubKeyCoseAlgo || (PubKeyCoseAlgo = {}));\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 constructor(rawId, cose, authenticatorAttachment) {\n super();\n this.rawId = rawId;\n this.authenticatorAttachment = authenticatorAttachment;\n this._publicKey = new CosePublicKey(cose);\n }\n /**\n * Create an identity from a JSON serialization.\n * @param json - json to parse\n */\n static fromJSON(json) {\n const { publicKey, rawId } = JSON.parse(json);\n if (typeof publicKey !== 'string' || typeof rawId !== 'string') {\n throw new Error('Invalid JSON string.');\n }\n return new this(fromHex(rawId), fromHex(publicKey), undefined);\n }\n /**\n * Create an identity.\n * @param credentialCreationOptions an optional CredentialCreationOptions Challenge\n */\n static async create(credentialCreationOptions) {\n var _a;\n const creds = await _createCredential(credentialCreationOptions);\n if (!creds || creds.type !== 'public-key') {\n throw new Error('Could not create credentials.');\n }\n const response = creds.response;\n if (response.attestationObject === undefined) {\n throw new Error('Was expecting an attestation response.');\n }\n // Parse the attestationObject as CBOR.\n const attObject = borc.decodeFirst(new Uint8Array(response.attestationObject));\n return new this(creds.rawId, _authDataToCose(attObject.authData), (_a = creds.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined);\n }\n getPublicKey() {\n return this._publicKey;\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 getAuthenticatorAttachment() {\n return this.authenticatorAttachment;\n }\n async sign(blob) {\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 }));\n if (result.authenticatorAttachment !== null) {\n this.authenticatorAttachment = result.authenticatorAttachment;\n }\n const response = result.response;\n const cbor = borc.encode(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 if (!cbor) {\n throw new Error('failed to encode cbor');\n }\n return cbor.buffer;\n }\n /**\n * Allow for JSON serialization of all information needed to reuse this identity.\n */\n toJSON() {\n return {\n publicKey: toHex(this._publicKey.getCose()),\n rawId: toHex(this.rawId),\n };\n }\n}\n//# sourceMappingURL=webauthn.js.map","/**\n * Codes used by the replica for rejecting a message.\n * See {@link https://sdk.dfinity.org/docs/interface-spec/#reject-codes | the interface spec}.\n */\nexport var ReplicaRejectCode;\n(function (ReplicaRejectCode) {\n ReplicaRejectCode[ReplicaRejectCode[\"SysFatal\"] = 1] = \"SysFatal\";\n ReplicaRejectCode[ReplicaRejectCode[\"SysTransient\"] = 2] = \"SysTransient\";\n ReplicaRejectCode[ReplicaRejectCode[\"DestinationInvalid\"] = 3] = \"DestinationInvalid\";\n ReplicaRejectCode[ReplicaRejectCode[\"CanisterReject\"] = 4] = \"CanisterReject\";\n ReplicaRejectCode[ReplicaRejectCode[\"CanisterError\"] = 5] = \"CanisterError\";\n})(ReplicaRejectCode || (ReplicaRejectCode = {}));\n//# sourceMappingURL=api.js.map","const alphabet = 'abcdefghijklmnopqrstuvwxyz234567';\n// Build a lookup table for decoding.\nconst lookupTable = Object.create(null);\nfor (let i = 0; i < alphabet.length; i++) {\n lookupTable[alphabet[i]] = i;\n}\n// Add aliases for rfc4648.\nlookupTable['0'] = lookupTable.o;\nlookupTable['1'] = lookupTable.i;\n/**\n * @param input The input array to encode.\n * @returns A Base32 string encoding the input.\n */\nexport function encode(input) {\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 // The output string in base32.\n let output = '';\n function encodeByte(byte) {\n if (skip < 0) {\n // we have a carry from the previous byte\n bits |= byte >> -skip;\n }\n else {\n // no carry\n bits = (byte << skip) & 248;\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 if (skip < 4) {\n // produce a character\n output += alphabet[bits >> 3];\n skip += 5;\n }\n return 0;\n }\n for (let i = 0; i < input.length;) {\n i += encodeByte(input[i]);\n }\n return output + (skip < 0 ? alphabet[bits >> 3] : '');\n}\n/**\n * @param input The base32 encoded string to decode.\n */\nexport function decode(input) {\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 const output = new Uint8Array(((input.length * 4) / 3) | 0);\n let o = 0;\n function decodeChar(char) {\n // Consume a character from the stream, store\n // the output in this.output. As before, better\n // to use update().\n let val = lookupTable[char.toLowerCase()];\n if (val === undefined) {\n throw new Error(`Invalid character: ${JSON.stringify(char)}`);\n }\n // move to the high bits\n val <<= 3;\n byte |= val >>> skip;\n skip += 5;\n if (skip >= 8) {\n // We have enough bytes to produce an output\n output[o++] = byte;\n skip -= 8;\n if (skip > 0) {\n byte = (val << (5 - skip)) & 255;\n }\n else {\n byte = 0;\n }\n }\n }\n for (const c of input) {\n decodeChar(c);\n }\n return output.slice(0, o);\n}\n//# sourceMappingURL=base32.js.map","// This file is translated to JavaScript from\n// https://lxp32.github.io/docs/a-simple-example-crc32-calculation/\nconst lookUpTable = new Uint32Array([\n 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,\n 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,\n 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,\n 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,\n 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,\n 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,\n 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,\n 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,\n 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,\n 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,\n 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,\n 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,\n 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,\n 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,\n 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,\n 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,\n 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,\n 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,\n 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,\n 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,\n 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,\n 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,\n 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,\n 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,\n 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,\n 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,\n 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,\n 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,\n 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,\n 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,\n 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,\n 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,\n]);\n/**\n * Calculate the CRC32 of an ArrayBufferLike.\n * @param buf The BufferLike to calculate the CRC32 of.\n */\nexport function getCrc32(buf) {\n const b = new Uint8Array(buf);\n let crc = -1;\n for (let i = 0; i < b.length; i++) {\n const byte = b[i];\n const t = (byte ^ crc) & 0xff;\n crc = lookUpTable[t] ^ (crc >>> 8);\n }\n return (crc ^ -1) >>> 0;\n}\n//# sourceMappingURL=getCrc.js.map","import { decode, encode } from './utils/base32';\nimport { getCrc32 } from './utils/getCrc';\nimport { sha224 } from './utils/sha224';\nexport const JSON_KEY_PRINCIPAL = '__principal__';\nconst SELF_AUTHENTICATING_SUFFIX = 2;\nconst ANONYMOUS_SUFFIX = 4;\nconst MANAGEMENT_CANISTER_PRINCIPAL_HEX_STR = 'aaaaa-aa';\nconst fromHexString = (hexString) => { var _a; return new Uint8Array(((_a = hexString.match(/.{1,2}/g)) !== null && _a !== void 0 ? _a : []).map(byte => parseInt(byte, 16))); };\nconst toHexString = (bytes) => bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\nexport class Principal {\n constructor(_arr) {\n this._arr = _arr;\n this._isPrincipal = true;\n }\n static anonymous() {\n return new this(new Uint8Array([ANONYMOUS_SUFFIX]));\n }\n /**\n * Utility method, returning the principal representing the management canister, decoded from the hex string `'aaaaa-aa'`\n * @returns {Principal} principal of the management canister\n */\n static managementCanister() {\n return this.fromHex(MANAGEMENT_CANISTER_PRINCIPAL_HEX_STR);\n }\n static selfAuthenticating(publicKey) {\n const sha = sha224(publicKey);\n return new this(new Uint8Array([...sha, SELF_AUTHENTICATING_SUFFIX]));\n }\n static from(other) {\n if (typeof other === 'string') {\n return Principal.fromText(other);\n }\n else if (Object.getPrototypeOf(other) === Uint8Array.prototype) {\n return new Principal(other);\n }\n else if (typeof other === 'object' &&\n other !== null &&\n other._isPrincipal === true) {\n return new Principal(other._arr);\n }\n throw new Error(`Impossible to convert ${JSON.stringify(other)} to Principal.`);\n }\n static fromHex(hex) {\n return new this(fromHexString(hex));\n }\n static fromText(text) {\n let maybePrincipal = text;\n // If formatted as JSON string, parse it first\n if (text.includes(JSON_KEY_PRINCIPAL)) {\n const obj = JSON.parse(text);\n if (JSON_KEY_PRINCIPAL in obj) {\n maybePrincipal = obj[JSON_KEY_PRINCIPAL];\n }\n }\n const canisterIdNoDash = maybePrincipal.toLowerCase().replace(/-/g, '');\n let arr = decode(canisterIdNoDash);\n arr = arr.slice(4, arr.length);\n const principal = new this(arr);\n if (principal.toText() !== maybePrincipal) {\n throw new Error(`Principal \"${principal.toText()}\" does not have a valid checksum (original value \"${maybePrincipal}\" may not be a valid Principal ID).`);\n }\n return principal;\n }\n static fromUint8Array(arr) {\n return new this(arr);\n }\n isAnonymous() {\n return this._arr.byteLength === 1 && this._arr[0] === ANONYMOUS_SUFFIX;\n }\n toUint8Array() {\n return this._arr;\n }\n toHex() {\n return toHexString(this._arr).toUpperCase();\n }\n toText() {\n const checksumArrayBuf = new ArrayBuffer(4);\n const view = new DataView(checksumArrayBuf);\n view.setUint32(0, getCrc32(this._arr));\n const checksum = new Uint8Array(checksumArrayBuf);\n const bytes = Uint8Array.from(this._arr);\n const array = new Uint8Array([...checksum, ...bytes]);\n const result = encode(array);\n const matches = result.match(/.{1,5}/g);\n if (!matches) {\n // This should only happen if there's no character, which is unreachable.\n throw new Error();\n }\n return matches.join('-');\n }\n toString() {\n return this.toText();\n }\n /**\n * Serializes to JSON\n * @returns {JsonnablePrincipal} a JSON object with a single key, {@link JSON_KEY_PRINCIPAL}, whose value is the principal as a string\n */\n toJSON() {\n return { [JSON_KEY_PRINCIPAL]: this.toText() };\n }\n /**\n * Utility method taking a Principal to compare against. Used for determining canister ranges in certificate verification\n * @param {Principal} other - a {@link Principal} to compare\n * @returns {'lt' | 'eq' | 'gt'} `'lt' | 'eq' | 'gt'` a string, representing less than, equal to, or greater than\n */\n compareTo(other) {\n for (let i = 0; i < Math.min(this._arr.length, other._arr.length); i++) {\n if (this._arr[i] < other._arr[i])\n return 'lt';\n else if (this._arr[i] > other._arr[i])\n return 'gt';\n }\n // Here, at least one principal is a prefix of the other principal (they could be the same)\n if (this._arr.length < other._arr.length)\n return 'lt';\n if (this._arr.length > other._arr.length)\n return 'gt';\n return 'eq';\n }\n /**\n * Utility method checking whether a provided Principal is less than or equal to the current one using the {@link Principal.compareTo} method\n * @param other a {@link Principal} to compare\n * @returns {boolean} boolean\n */\n ltEq(other) {\n const cmp = this.compareTo(other);\n return cmp == 'lt' || cmp == 'eq';\n }\n /**\n * Utility method checking whether a provided Principal is greater than or equal to the current one using the {@link Principal.compareTo} method\n * @param other a {@link Principal} to compare\n * @returns {boolean} boolean\n */\n gtEq(other) {\n const cmp = this.compareTo(other);\n return cmp == 'gt' || cmp == 'eq';\n }\n}\n//# sourceMappingURL=index.js.map","import { sha224 as jsSha224 } from '@noble/hashes/sha256';\n/**\n * Returns the SHA224 hash of the buffer.\n * @param data Arraybuffer to encode\n */\nexport function sha224(data) {\n return jsSha224.create().update(new Uint8Array(data)).digest();\n}\n//# sourceMappingURL=sha224.js.map","/**\n * Concatenate multiple array buffers.\n * @param buffers The buffers to concatenate.\n */\nexport function concat(...buffers) {\n const result = new Uint8Array(buffers.reduce((acc, curr) => acc + curr.byteLength, 0));\n let index = 0;\n for (const b of buffers) {\n result.set(new Uint8Array(b), index);\n index += b.byteLength;\n }\n return result.buffer;\n}\n/**\n * Transforms a buffer to an hexadecimal string. This will use the buffer as an Uint8Array.\n * @param buffer The buffer to return the hexadecimal string of.\n */\nexport function toHex(buffer) {\n return [...new Uint8Array(buffer)].map(x => x.toString(16).padStart(2, '0')).join('');\n}\nconst hexRe = new RegExp(/^[0-9a-fA-F]+$/);\n/**\n * Transforms a hexadecimal string into an array buffer.\n * @param hex The hexadecimal string to use.\n */\nexport function fromHex(hex) {\n if (!hexRe.test(hex)) {\n throw new Error('Invalid hexadecimal string.');\n }\n const buffer = [...hex]\n .reduce((acc, curr, i) => {\n acc[(i / 2) | 0] = (acc[(i / 2) | 0] || '') + curr;\n return acc;\n }, [])\n .map(x => Number.parseInt(x, 16));\n return new Uint8Array(buffer).buffer;\n}\n/**\n *\n * @param b1 array buffer 1\n * @param b2 array buffer 2\n * @returns number - negative if b1 < b2, positive if b1 > b2, 0 if b1 === b2\n */\nexport function compare(b1, b2) {\n if (b1.byteLength !== b2.byteLength) {\n return b1.byteLength - b2.byteLength;\n }\n const u1 = new Uint8Array(b1);\n const u2 = new Uint8Array(b2);\n for (let i = 0; i < u1.length; i++) {\n if (u1[i] !== u2[i]) {\n return u1[i] - u2[i];\n }\n }\n return 0;\n}\n/**\n * Checks two array buffers for equality.\n * @param b1 array buffer 1\n * @param b2 array buffer 2\n * @returns boolean\n */\nexport function bufEquals(b1, b2) {\n return compare(b1, b2) === 0;\n}\n/**\n * Returns a true ArrayBuffer from a Uint8Array, as Uint8Array.buffer is unsafe.\n * @param {Uint8Array} arr Uint8Array to convert\n * @returns ArrayBuffer\n */\nexport function uint8ToBuf(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength).buffer;\n}\n/**\n * Returns a true ArrayBuffer from an ArrayBufferLike object.\n * @param bufLike a buffer-like object\n * @returns ArrayBuffer\n */\nexport function bufFromBufLike(bufLike) {\n if (bufLike instanceof Uint8Array) {\n return uint8ToBuf(bufLike);\n }\n if (bufLike instanceof ArrayBuffer) {\n return bufLike;\n }\n if (Array.isArray(bufLike)) {\n return uint8ToBuf(new Uint8Array(bufLike));\n }\n if ('buffer' in bufLike) {\n return bufFromBufLike(bufLike.buffer);\n }\n return uint8ToBuf(new Uint8Array(bufLike));\n}\n//# sourceMappingURL=buffer.js.map","import { Principal } from '@dfinity/principal';\nimport { ReplicaRejectCode, } from './agent/api';\nimport { toHex } from './utils/buffer';\n/**\n * An error that happens in the Agent. This is the root of all errors and should be used\n * everywhere in the Agent code (this package).\n * @todo https://github.com/dfinity/agent-js/issues/420\n */\nexport class AgentError extends Error {\n constructor(message) {\n super(message);\n this.message = message;\n this.name = 'AgentError';\n this.__proto__ = AgentError.prototype;\n Object.setPrototypeOf(this, AgentError.prototype);\n }\n}\nexport class ActorCallError extends AgentError {\n constructor(canisterId, methodName, type, props) {\n const cid = Principal.from(canisterId);\n super([\n `Call failed:`,\n ` Canister: ${cid.toText()}`,\n ` Method: ${methodName} (${type})`,\n ...Object.getOwnPropertyNames(props).map(n => ` \"${n}\": ${JSON.stringify(props[n])}`),\n ].join('\\n'));\n this.canisterId = canisterId;\n this.methodName = methodName;\n this.type = type;\n this.props = props;\n this.name = 'ActorCallError';\n this.__proto__ = ActorCallError.prototype;\n Object.setPrototypeOf(this, ActorCallError.prototype);\n }\n}\nexport class QueryCallRejectedError extends ActorCallError {\n constructor(canisterId, methodName, result) {\n var _a;\n const cid = Principal.from(canisterId);\n super(cid, methodName, 'query', {\n Status: result.status,\n Code: (_a = ReplicaRejectCode[result.reject_code]) !== null && _a !== void 0 ? _a : `Unknown Code \"${result.reject_code}\"`,\n Message: result.reject_message,\n });\n this.result = result;\n this.name = 'QueryCallRejectedError';\n this.__proto__ = QueryCallRejectedError.prototype;\n Object.setPrototypeOf(this, QueryCallRejectedError.prototype);\n }\n}\nexport class UpdateCallRejectedError extends ActorCallError {\n constructor(canisterId, methodName, requestId, response) {\n const cid = Principal.from(canisterId);\n super(cid, methodName, 'update', Object.assign({ 'Request ID': toHex(requestId) }, (response.body\n ? Object.assign(Object.assign({}, (response.body.error_code\n ? {\n 'Error code': response.body.error_code,\n }\n : {})), { 'Reject code': String(response.body.reject_code), 'Reject message': response.body.reject_message }) : {\n 'HTTP status code': response.status.toString(),\n 'HTTP status text': response.statusText,\n })));\n this.requestId = requestId;\n this.response = response;\n this.name = 'UpdateCallRejectedError';\n this.__proto__ = UpdateCallRejectedError.prototype;\n Object.setPrototypeOf(this, UpdateCallRejectedError.prototype);\n }\n}\n//# sourceMappingURL=errors.js.map","/**\n * Concatenate multiple array buffers.\n * @param buffers The buffers to concatenate.\n */\nexport function concat(...buffers) {\n const result = new Uint8Array(buffers.reduce((acc, curr) => acc + curr.byteLength, 0));\n let index = 0;\n for (const b of buffers) {\n result.set(new Uint8Array(b), index);\n index += b.byteLength;\n }\n return result;\n}\n/**\n * Returns an hexadecimal representation of an array buffer.\n * @param bytes The array buffer.\n */\nexport function toHexString(bytes) {\n return new Uint8Array(bytes).reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\n}\n/**\n * Return an array buffer from its hexadecimal representation.\n * @param hexString The hexadecimal string.\n */\nexport function fromHexString(hexString) {\n var _a;\n return new Uint8Array(((_a = hexString.match(/.{1,2}/g)) !== null && _a !== void 0 ? _a : []).map(byte => parseInt(byte, 16)));\n}\n/**\n * A class that abstracts a pipe-like ArrayBuffer.\n */\nexport class PipeArrayBuffer {\n /**\n * Creates a new instance of a pipe\n * @param buffer an optional buffer to start with\n * @param length an optional amount of bytes to use for the length.\n */\n constructor(buffer, length = (buffer === null || buffer === void 0 ? void 0 : buffer.byteLength) || 0) {\n this._buffer = bufFromBufLike(buffer || new ArrayBuffer(0));\n this._view = new Uint8Array(this._buffer, 0, length);\n }\n get buffer() {\n // Return a copy of the buffer.\n return bufFromBufLike(this._view.slice());\n }\n get byteLength() {\n return this._view.byteLength;\n }\n /**\n * Read `num` number of bytes from the front of the pipe.\n * @param num The number of bytes to read.\n */\n read(num) {\n const result = this._view.subarray(0, num);\n this._view = this._view.subarray(num);\n return result.slice().buffer;\n }\n readUint8() {\n const result = this._view[0];\n this._view = this._view.subarray(1);\n return result;\n }\n /**\n * Write a buffer to the end of the pipe.\n * @param buf The bytes to write.\n */\n write(buf) {\n const b = new Uint8Array(buf);\n const offset = this._view.byteLength;\n if (this._view.byteOffset + this._view.byteLength + b.byteLength >= this._buffer.byteLength) {\n // Alloc grow the view to include the new bytes.\n this.alloc(b.byteLength);\n }\n else {\n // Update the view to include the new bytes.\n this._view = new Uint8Array(this._buffer, this._view.byteOffset, this._view.byteLength + b.byteLength);\n }\n this._view.set(b, offset);\n }\n /**\n * Whether or not there is more data to read from the buffer\n */\n get end() {\n return this._view.byteLength === 0;\n }\n /**\n * Allocate a fixed amount of memory in the buffer. This does not affect the view.\n * @param amount A number of bytes to add to the buffer.\n */\n alloc(amount) {\n // Add a little bit of exponential growth.\n const b = new ArrayBuffer(((this._buffer.byteLength + amount) * 1.2) | 0);\n const v = new Uint8Array(b, 0, this._view.byteLength + amount);\n v.set(this._view);\n this._buffer = b;\n this._view = v;\n }\n}\n/**\n * Returns a true ArrayBuffer from a Uint8Array, as Uint8Array.buffer is unsafe.\n * @param {Uint8Array} arr Uint8Array to convert\n * @returns ArrayBuffer\n */\nexport function uint8ToBuf(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength).buffer;\n}\n/**\n * Returns a true ArrayBuffer from an ArrayBufferLike object.\n * @param bufLike a buffer-like object\n * @returns ArrayBuffer\n */\nexport function bufFromBufLike(bufLike) {\n if (bufLike instanceof Uint8Array) {\n return uint8ToBuf(bufLike);\n }\n if (bufLike instanceof ArrayBuffer) {\n return bufLike;\n }\n if (Array.isArray(bufLike)) {\n return uint8ToBuf(new Uint8Array(bufLike));\n }\n if ('buffer' in bufLike) {\n return bufFromBufLike(bufLike.buffer);\n }\n return uint8ToBuf(new Uint8Array(bufLike));\n}\n//# sourceMappingURL=buffer.js.map","/**\n * Hashes a string to a number. Algorithm can be found here:\n * https://caml.inria.fr/pub/papers/garrigue-polymorphic_variants-ml98.pdf\n * @param s - string to hash\n * @returns number representing hashed string\n */\nfunction idlHash(s) {\n const utf8encoder = new TextEncoder();\n const array = utf8encoder.encode(s);\n let h = 0;\n for (const c of array) {\n h = (h * 223 + c) % 2 ** 32;\n }\n return h;\n}\n/**\n *\n * @param label string\n * @returns number representing hashed label\n */\nexport function idlLabelToId(label) {\n if (/^_\\d+_$/.test(label) || /^_0x[0-9a-fA-F]+_$/.test(label)) {\n const num = +label.slice(1, -1);\n if (Number.isSafeInteger(num) && num >= 0 && num < 2 ** 32) {\n return num;\n }\n }\n return idlHash(label);\n}\n//# sourceMappingURL=hash.js.map","/* eslint-disable no-constant-condition */\n// Note: this file uses buffer-pipe, which on Node only, uses the Node Buffer\n// implementation, which isn't compatible with the NPM buffer package\n// which we use everywhere else. This means that we have to transform\n// one into the other, hence why every function that returns a Buffer\n// actually return `new Buffer(pipe.buffer)`.\n// TODO: The best solution would be to have our own buffer type around\n// Uint8Array which is standard.\nimport { PipeArrayBuffer as Pipe } from './buffer';\nfunction eob() {\n throw new Error('unexpected end of buffer');\n}\n/**\n *\n * @param pipe Pipe from buffer-pipe\n * @param num number\n * @returns Buffer\n */\nexport function safeRead(pipe, num) {\n if (pipe.byteLength < num) {\n eob();\n }\n return pipe.read(num);\n}\n/**\n * @param pipe - PipeArrayBuffer simulating buffer-pipe api\n */\nexport function safeReadUint8(pipe) {\n const byte = pipe.readUint8();\n if (byte === undefined) {\n eob();\n }\n return byte;\n}\n/**\n * Encode a positive number (or bigint) into a Buffer. The number will be floored to the\n * nearest integer.\n * @param value The number to encode.\n */\nexport function lebEncode(value) {\n if (typeof value === 'number') {\n value = BigInt(value);\n }\n if (value < BigInt(0)) {\n throw new Error('Cannot leb encode negative values.');\n }\n const byteLength = (value === BigInt(0) ? 0 : Math.ceil(Math.log2(Number(value)))) + 1;\n const pipe = new Pipe(new ArrayBuffer(byteLength), 0);\n while (true) {\n const i = Number(value & BigInt(0x7f));\n value /= BigInt(0x80);\n if (value === BigInt(0)) {\n pipe.write(new Uint8Array([i]));\n break;\n }\n else {\n pipe.write(new Uint8Array([i | 0x80]));\n }\n }\n return pipe.buffer;\n}\n/**\n * Decode a leb encoded buffer into a bigint. The number will always be positive (does not\n * support signed leb encoding).\n * @param pipe A Buffer containing the leb encoded bits.\n */\nexport function lebDecode(pipe) {\n let weight = BigInt(1);\n let value = BigInt(0);\n let byte;\n do {\n byte = safeReadUint8(pipe);\n value += BigInt(byte & 0x7f).valueOf() * weight;\n weight *= BigInt(128);\n } while (byte >= 0x80);\n return value;\n}\n/**\n * Encode a number (or bigint) into a Buffer, with support for negative numbers. The number\n * will be floored to the nearest integer.\n * @param value The number to encode.\n */\nexport function slebEncode(value) {\n if (typeof value === 'number') {\n value = BigInt(value);\n }\n const isNeg = value < BigInt(0);\n if (isNeg) {\n value = -value - BigInt(1);\n }\n const byteLength = (value === BigInt(0) ? 0 : Math.ceil(Math.log2(Number(value)))) + 1;\n const pipe = new Pipe(new ArrayBuffer(byteLength), 0);\n while (true) {\n const i = getLowerBytes(value);\n value /= BigInt(0x80);\n // prettier-ignore\n if ((isNeg && value === BigInt(0) && (i & 0x40) !== 0)\n || (!isNeg && value === BigInt(0) && (i & 0x40) === 0)) {\n pipe.write(new Uint8Array([i]));\n break;\n }\n else {\n pipe.write(new Uint8Array([i | 0x80]));\n }\n }\n function getLowerBytes(num) {\n const bytes = num % BigInt(0x80);\n if (isNeg) {\n // We swap the bits here again, and remove 1 to do two's complement.\n return Number(BigInt(0x80) - bytes - BigInt(1));\n }\n else {\n return Number(bytes);\n }\n }\n return pipe.buffer;\n}\n/**\n * Decode a leb encoded buffer into a bigint. The number is decoded with support for negative\n * signed-leb encoding.\n * @param pipe A Buffer containing the signed leb encoded bits.\n */\nexport function slebDecode(pipe) {\n // Get the size of the buffer, then cut a buffer of that size.\n const pipeView = new Uint8Array(pipe.buffer);\n let len = 0;\n for (; len < pipeView.byteLength; len++) {\n if (pipeView[len] < 0x80) {\n // If it's a positive number, we reuse lebDecode.\n if ((pipeView[len] & 0x40) === 0) {\n return lebDecode(pipe);\n }\n break;\n }\n }\n const bytes = new Uint8Array(safeRead(pipe, len + 1));\n let value = BigInt(0);\n for (let i = bytes.byteLength - 1; i >= 0; i--) {\n value = value * BigInt(0x80) + BigInt(0x80 - (bytes[i] & 0x7f) - 1);\n }\n return -value - BigInt(1);\n}\n/**\n *\n * @param value bigint or number\n * @param byteLength number\n * @returns Buffer\n */\nexport function writeUIntLE(value, byteLength) {\n if (BigInt(value) < BigInt(0)) {\n throw new Error('Cannot write negative values.');\n }\n return writeIntLE(value, byteLength);\n}\n/**\n *\n * @param value - bigint or number\n * @param byteLength - number\n * @returns ArrayBuffer\n */\nexport function writeIntLE(value, byteLength) {\n value = BigInt(value);\n const pipe = new Pipe(new ArrayBuffer(Math.min(1, byteLength)), 0);\n let i = 0;\n let mul = BigInt(256);\n let sub = BigInt(0);\n let byte = Number(value % mul);\n pipe.write(new Uint8Array([byte]));\n while (++i < byteLength) {\n if (value < 0 && sub === BigInt(0) && byte !== 0) {\n sub = BigInt(1);\n }\n byte = Number((value / mul - sub) % BigInt(256));\n pipe.write(new Uint8Array([byte]));\n mul *= BigInt(256);\n }\n return pipe.buffer;\n}\n/**\n *\n * @param pipe Pipe from buffer-pipe\n * @param byteLength number\n * @returns bigint\n */\nexport function readUIntLE(pipe, byteLength) {\n let val = BigInt(safeReadUint8(pipe));\n let mul = BigInt(1);\n let i = 0;\n while (++i < byteLength) {\n mul *= BigInt(256);\n const byte = BigInt(safeReadUint8(pipe));\n val = val + mul * byte;\n }\n return val;\n}\n/**\n *\n * @param pipe Pipe from buffer-pipe\n * @param byteLength number\n * @returns bigint\n */\nexport function readIntLE(pipe, byteLength) {\n let val = readUIntLE(pipe, byteLength);\n const mul = BigInt(2) ** (BigInt(8) * BigInt(byteLength - 1) + BigInt(7));\n if (val >= mul) {\n val -= mul * BigInt(2);\n }\n return val;\n}\n//# sourceMappingURL=leb128.js.map","/**\n * Equivalent to `Math.log2(n)` with support for `BigInt` values\n * @param n bigint or integer\n * @returns integer\n */\nexport function ilog2(n) {\n const nBig = BigInt(n);\n if (n <= 0) {\n throw new RangeError('Input must be positive');\n }\n return nBig.toString(2).length - 1;\n}\n/**\n * Equivalent to `2 ** n` with support for `BigInt` values\n * (necessary for browser preprocessors which replace the `**` operator with `Math.pow`)\n * @param n bigint or integer\n * @returns bigint\n */\nexport function iexp2(n) {\n const nBig = BigInt(n);\n if (n < 0) {\n throw new RangeError('Input must be non-negative');\n }\n return BigInt(1) << nBig;\n}\n//# sourceMappingURL=bigint-math.js.map","/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Principal as PrincipalId } from '@dfinity/principal';\nimport { concat, PipeArrayBuffer as Pipe } from './utils/buffer';\nimport { idlLabelToId } from './utils/hash';\nimport { lebDecode, lebEncode, readIntLE, readUIntLE, safeRead, safeReadUint8, slebDecode, slebEncode, writeIntLE, writeUIntLE, } from './utils/leb128';\nimport { iexp2 } from './utils/bigint-math';\nconst magicNumber = 'DIDL';\nconst toReadableString_max = 400; // will not display arguments after 400chars. Makes sure 2mb blobs don't get inside the error\nfunction zipWith(xs, ys, f) {\n return xs.map((x, i) => f(x, ys[i]));\n}\n/**\n * An IDL Type Table, which precedes the data in the stream.\n */\nclass TypeTable {\n constructor() {\n // List of types. Needs to be an array as the index needs to be stable.\n this._typs = [];\n this._idx = new Map();\n }\n has(obj) {\n return this._idx.has(obj.name);\n }\n add(type, buf) {\n const idx = this._typs.length;\n this._idx.set(type.name, idx);\n this._typs.push(buf);\n }\n merge(obj, knot) {\n const idx = this._idx.get(obj.name);\n const knotIdx = this._idx.get(knot);\n if (idx === undefined) {\n throw new Error('Missing type index for ' + obj);\n }\n if (knotIdx === undefined) {\n throw new Error('Missing type index for ' + knot);\n }\n this._typs[idx] = this._typs[knotIdx];\n // Delete the type.\n this._typs.splice(knotIdx, 1);\n this._idx.delete(knot);\n }\n encode() {\n const len = lebEncode(this._typs.length);\n const buf = concat(...this._typs);\n return concat(len, buf);\n }\n indexOf(typeName) {\n if (!this._idx.has(typeName)) {\n throw new Error('Missing type index for ' + typeName);\n }\n return slebEncode(this._idx.get(typeName) || 0);\n }\n}\nexport class Visitor {\n visitType(t, data) {\n throw new Error('Not implemented');\n }\n visitPrimitive(t, data) {\n return this.visitType(t, data);\n }\n visitEmpty(t, data) {\n return this.visitPrimitive(t, data);\n }\n visitBool(t, data) {\n return this.visitPrimitive(t, data);\n }\n visitNull(t, data) {\n return this.visitPrimitive(t, data);\n }\n visitReserved(t, data) {\n return this.visitPrimitive(t, data);\n }\n visitText(t, data) {\n return this.visitPrimitive(t, data);\n }\n visitNumber(t, data) {\n return this.visitPrimitive(t, data);\n }\n visitInt(t, data) {\n return this.visitNumber(t, data);\n }\n visitNat(t, data) {\n return this.visitNumber(t, data);\n }\n visitFloat(t, data) {\n return this.visitPrimitive(t, data);\n }\n visitFixedInt(t, data) {\n return this.visitNumber(t, data);\n }\n visitFixedNat(t, data) {\n return this.visitNumber(t, data);\n }\n visitPrincipal(t, data) {\n return this.visitPrimitive(t, data);\n }\n visitConstruct(t, data) {\n return this.visitType(t, data);\n }\n visitVec(t, ty, data) {\n return this.visitConstruct(t, data);\n }\n visitOpt(t, ty, data) {\n return this.visitConstruct(t, data);\n }\n visitRecord(t, fields, data) {\n return this.visitConstruct(t, data);\n }\n visitTuple(t, components, data) {\n const fields = components.map((ty, i) => [`_${i}_`, ty]);\n return this.visitRecord(t, fields, data);\n }\n visitVariant(t, fields, data) {\n return this.visitConstruct(t, data);\n }\n visitRec(t, ty, data) {\n return this.visitConstruct(ty, data);\n }\n visitFunc(t, data) {\n return this.visitConstruct(t, data);\n }\n visitService(t, data) {\n return this.visitConstruct(t, data);\n }\n}\n/**\n * Represents an IDL type.\n */\nexport class Type {\n /* Display type name */\n display() {\n return this.name;\n }\n valueToString(x) {\n return toReadableString(x);\n }\n /* Implement `T` in the IDL spec, only needed for non-primitive types */\n buildTypeTable(typeTable) {\n if (!typeTable.has(this)) {\n this._buildTypeTableImpl(typeTable);\n }\n }\n}\nexport class PrimitiveType extends Type {\n checkType(t) {\n if (this.name !== t.name) {\n throw new Error(`type mismatch: type on the wire ${t.name}, expect type ${this.name}`);\n }\n return t;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _buildTypeTableImpl(typeTable) {\n // No type table encoding for Primitive types.\n return;\n }\n}\nexport class ConstructType extends Type {\n checkType(t) {\n if (t instanceof RecClass) {\n const ty = t.getType();\n if (typeof ty === 'undefined') {\n throw new Error('type mismatch with uninitialized type');\n }\n return ty;\n }\n throw new Error(`type mismatch: type on the wire ${t.name}, expect type ${this.name}`);\n }\n encodeType(typeTable) {\n return typeTable.indexOf(this.name);\n }\n}\n/**\n * Represents an IDL Empty, a type which has no inhabitants.\n * Since no values exist for this type, it cannot be serialised or deserialised.\n * Result types like `Result` should always succeed.\n */\nexport class EmptyClass extends PrimitiveType {\n accept(v, d) {\n return v.visitEmpty(this, d);\n }\n covariant(x) {\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue() {\n throw new Error('Empty cannot appear as a function argument');\n }\n valueToString() {\n throw new Error('Empty cannot appear as a value');\n }\n encodeType() {\n return slebEncode(-17 /* IDLTypeIds.Empty */);\n }\n decodeValue() {\n throw new Error('Empty cannot appear as an output');\n }\n get name() {\n return 'empty';\n }\n}\n/**\n * Represents an IDL Unknown, a placeholder type for deserialization only.\n * When decoding a value as Unknown, all fields will be retained but the names are only available in\n * hashed form.\n * A deserialized unknown will offer it's actual type by calling the `type()` function.\n * Unknown cannot be serialized and attempting to do so will throw an error.\n */\nexport class UnknownClass extends Type {\n checkType(t) {\n throw new Error('Method not implemented for unknown.');\n }\n accept(v, d) {\n throw v.visitType(this, d);\n }\n covariant(x) {\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue() {\n throw new Error('Unknown cannot appear as a function argument');\n }\n valueToString() {\n throw new Error('Unknown cannot appear as a value');\n }\n encodeType() {\n throw new Error('Unknown cannot be serialized');\n }\n decodeValue(b, t) {\n let decodedValue = t.decodeValue(b, t);\n if (Object(decodedValue) !== decodedValue) {\n // decodedValue is primitive. Box it, otherwise we cannot add the type() function.\n // The type() function is important for primitives because otherwise we cannot tell apart the\n // different number types.\n decodedValue = Object(decodedValue);\n }\n let typeFunc;\n if (t instanceof RecClass) {\n typeFunc = () => t.getType();\n }\n else {\n typeFunc = () => t;\n }\n // Do not use 'decodedValue.type = typeFunc' because this would lead to an enumerable property\n // 'type' which means it would be serialized if the value would be candid encoded again.\n // This in turn leads to problems if the decoded value is a variant because these values are\n // only allowed to have a single property.\n Object.defineProperty(decodedValue, 'type', {\n value: typeFunc,\n writable: true,\n enumerable: false,\n configurable: true,\n });\n return decodedValue;\n }\n _buildTypeTableImpl() {\n throw new Error('Unknown cannot be serialized');\n }\n get name() {\n return 'Unknown';\n }\n}\n/**\n * Represents an IDL Bool\n */\nexport class BoolClass extends PrimitiveType {\n accept(v, d) {\n return v.visitBool(this, d);\n }\n covariant(x) {\n if (typeof x === 'boolean')\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n return new Uint8Array([x ? 1 : 0]);\n }\n encodeType() {\n return slebEncode(-2 /* IDLTypeIds.Bool */);\n }\n decodeValue(b, t) {\n this.checkType(t);\n switch (safeReadUint8(b)) {\n case 0:\n return false;\n case 1:\n return true;\n default:\n throw new Error('Boolean value out of range');\n }\n }\n get name() {\n return 'bool';\n }\n}\n/**\n * Represents an IDL Null\n */\nexport class NullClass extends PrimitiveType {\n accept(v, d) {\n return v.visitNull(this, d);\n }\n covariant(x) {\n if (x === null)\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue() {\n return new ArrayBuffer(0);\n }\n encodeType() {\n return slebEncode(-1 /* IDLTypeIds.Null */);\n }\n decodeValue(b, t) {\n this.checkType(t);\n return null;\n }\n get name() {\n return 'null';\n }\n}\n/**\n * Represents an IDL Reserved\n */\nexport class ReservedClass extends PrimitiveType {\n accept(v, d) {\n return v.visitReserved(this, d);\n }\n covariant(x) {\n return true;\n }\n encodeValue() {\n return new ArrayBuffer(0);\n }\n encodeType() {\n return slebEncode(-16 /* IDLTypeIds.Reserved */);\n }\n decodeValue(b, t) {\n if (t.name !== this.name) {\n t.decodeValue(b, t);\n }\n return null;\n }\n get name() {\n return 'reserved';\n }\n}\n/**\n * Represents an IDL Text\n */\nexport class TextClass extends PrimitiveType {\n accept(v, d) {\n return v.visitText(this, d);\n }\n covariant(x) {\n if (typeof x === 'string')\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n const buf = new TextEncoder().encode(x);\n const len = lebEncode(buf.byteLength);\n return concat(len, buf);\n }\n encodeType() {\n return slebEncode(-15 /* IDLTypeIds.Text */);\n }\n decodeValue(b, t) {\n this.checkType(t);\n const len = lebDecode(b);\n const buf = safeRead(b, Number(len));\n const decoder = new TextDecoder('utf8', { fatal: true });\n return decoder.decode(buf);\n }\n get name() {\n return 'text';\n }\n valueToString(x) {\n return '\"' + x + '\"';\n }\n}\n/**\n * Represents an IDL Int\n */\nexport class IntClass extends PrimitiveType {\n accept(v, d) {\n return v.visitInt(this, d);\n }\n covariant(x) {\n // We allow encoding of JavaScript plain numbers.\n // But we will always decode to bigint.\n if (typeof x === 'bigint' || Number.isInteger(x))\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n return slebEncode(x);\n }\n encodeType() {\n return slebEncode(-4 /* IDLTypeIds.Int */);\n }\n decodeValue(b, t) {\n this.checkType(t);\n return slebDecode(b);\n }\n get name() {\n return 'int';\n }\n valueToString(x) {\n return x.toString();\n }\n}\n/**\n * Represents an IDL Nat\n */\nexport class NatClass extends PrimitiveType {\n accept(v, d) {\n return v.visitNat(this, d);\n }\n covariant(x) {\n // We allow encoding of JavaScript plain numbers.\n // But we will always decode to bigint.\n if ((typeof x === 'bigint' && x >= BigInt(0)) || (Number.isInteger(x) && x >= 0))\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n return lebEncode(x);\n }\n encodeType() {\n return slebEncode(-3 /* IDLTypeIds.Nat */);\n }\n decodeValue(b, t) {\n this.checkType(t);\n return lebDecode(b);\n }\n get name() {\n return 'nat';\n }\n valueToString(x) {\n return x.toString();\n }\n}\n/**\n * Represents an IDL Float\n */\nexport class FloatClass extends PrimitiveType {\n constructor(_bits) {\n super();\n this._bits = _bits;\n if (_bits !== 32 && _bits !== 64) {\n throw new Error('not a valid float type');\n }\n }\n accept(v, d) {\n return v.visitFloat(this, d);\n }\n covariant(x) {\n if (typeof x === 'number' || x instanceof Number)\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n const buf = new ArrayBuffer(this._bits / 8);\n const view = new DataView(buf);\n if (this._bits === 32) {\n view.setFloat32(0, x, true);\n }\n else {\n view.setFloat64(0, x, true);\n }\n return buf;\n }\n encodeType() {\n const opcode = this._bits === 32 ? -13 /* IDLTypeIds.Float32 */ : -14 /* IDLTypeIds.Float64 */;\n return slebEncode(opcode);\n }\n decodeValue(b, t) {\n this.checkType(t);\n const bytes = safeRead(b, this._bits / 8);\n const view = new DataView(bytes);\n if (this._bits === 32) {\n return view.getFloat32(0, true);\n }\n else {\n return view.getFloat64(0, true);\n }\n }\n get name() {\n return 'float' + this._bits;\n }\n valueToString(x) {\n return x.toString();\n }\n}\n/**\n * Represents an IDL fixed-width Int(n)\n */\nexport class FixedIntClass extends PrimitiveType {\n constructor(_bits) {\n super();\n this._bits = _bits;\n }\n accept(v, d) {\n return v.visitFixedInt(this, d);\n }\n covariant(x) {\n const min = iexp2(this._bits - 1) * BigInt(-1);\n const max = iexp2(this._bits - 1) - BigInt(1);\n let ok = false;\n if (typeof x === 'bigint') {\n ok = x >= min && x <= max;\n }\n else if (Number.isInteger(x)) {\n const v = BigInt(x);\n ok = v >= min && v <= max;\n }\n else {\n ok = false;\n }\n if (ok)\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n return writeIntLE(x, this._bits / 8);\n }\n encodeType() {\n const offset = Math.log2(this._bits) - 3;\n return slebEncode(-9 - offset);\n }\n decodeValue(b, t) {\n this.checkType(t);\n const num = readIntLE(b, this._bits / 8);\n if (this._bits <= 32) {\n return Number(num);\n }\n else {\n return num;\n }\n }\n get name() {\n return `int${this._bits}`;\n }\n valueToString(x) {\n return x.toString();\n }\n}\n/**\n * Represents an IDL fixed-width Nat(n)\n */\nexport class FixedNatClass extends PrimitiveType {\n constructor(_bits) {\n super();\n this._bits = _bits;\n }\n accept(v, d) {\n return v.visitFixedNat(this, d);\n }\n covariant(x) {\n const max = iexp2(this._bits);\n let ok = false;\n if (typeof x === 'bigint' && x >= BigInt(0)) {\n ok = x < max;\n }\n else if (Number.isInteger(x) && x >= 0) {\n const v = BigInt(x);\n ok = v < max;\n }\n else {\n ok = false;\n }\n if (ok)\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n return writeUIntLE(x, this._bits / 8);\n }\n encodeType() {\n const offset = Math.log2(this._bits) - 3;\n return slebEncode(-5 - offset);\n }\n decodeValue(b, t) {\n this.checkType(t);\n const num = readUIntLE(b, this._bits / 8);\n if (this._bits <= 32) {\n return Number(num);\n }\n else {\n return num;\n }\n }\n get name() {\n return `nat${this._bits}`;\n }\n valueToString(x) {\n return x.toString();\n }\n}\n/**\n * Represents an IDL Array\n *\n * Arrays of fixed-sized nat/int type (e.g. nat8), are encoded from and decoded to TypedArrays (e.g. Uint8Array).\n * Arrays of float or other non-primitive types are encoded/decoded as untyped array in Javascript.\n * @param {Type} t\n */\nexport class VecClass extends ConstructType {\n constructor(_type) {\n super();\n this._type = _type;\n // If true, this vector is really a blob and we can just use memcpy.\n //\n // NOTE:\n // With support of encoding/dencoding of TypedArrays, this optimization is\n // only used when plain array of bytes are passed as encoding input in order\n // to be backward compatible.\n this._blobOptimization = false;\n if (_type instanceof FixedNatClass && _type._bits === 8) {\n this._blobOptimization = true;\n }\n }\n accept(v, d) {\n return v.visitVec(this, this._type, d);\n }\n covariant(x) {\n // Special case for ArrayBuffer\n const bits = this._type instanceof FixedNatClass\n ? this._type._bits\n : this._type instanceof FixedIntClass\n ? this._type._bits\n : 0;\n if ((ArrayBuffer.isView(x) && bits == x.BYTES_PER_ELEMENT * 8) ||\n (Array.isArray(x) &&\n x.every((v, idx) => {\n try {\n return this._type.covariant(v);\n }\n catch (e) {\n throw new Error(`Invalid ${this.display()} argument: \\n\\nindex ${idx} -> ${e.message}`);\n }\n })))\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n const len = lebEncode(x.length);\n if (this._blobOptimization) {\n return concat(len, new Uint8Array(x));\n }\n if (ArrayBuffer.isView(x)) {\n return concat(len, new Uint8Array(x.buffer));\n }\n const buf = new Pipe(new ArrayBuffer(len.byteLength + x.length), 0);\n buf.write(len);\n for (const d of x) {\n const encoded = this._type.encodeValue(d);\n buf.write(new Uint8Array(encoded));\n }\n return buf.buffer;\n }\n _buildTypeTableImpl(typeTable) {\n this._type.buildTypeTable(typeTable);\n const opCode = slebEncode(-19 /* IDLTypeIds.Vector */);\n const buffer = this._type.encodeType(typeTable);\n typeTable.add(this, concat(opCode, buffer));\n }\n decodeValue(b, t) {\n const vec = this.checkType(t);\n if (!(vec instanceof VecClass)) {\n throw new Error('Not a vector type');\n }\n const len = Number(lebDecode(b));\n if (this._type instanceof FixedNatClass) {\n if (this._type._bits == 8) {\n return new Uint8Array(b.read(len));\n }\n if (this._type._bits == 16) {\n return new Uint16Array(b.read(len * 2));\n }\n if (this._type._bits == 32) {\n return new Uint32Array(b.read(len * 4));\n }\n if (this._type._bits == 64) {\n return new BigUint64Array(b.read(len * 8));\n }\n }\n if (this._type instanceof FixedIntClass) {\n if (this._type._bits == 8) {\n return new Int8Array(b.read(len));\n }\n if (this._type._bits == 16) {\n return new Int16Array(b.read(len * 2));\n }\n if (this._type._bits == 32) {\n return new Int32Array(b.read(len * 4));\n }\n if (this._type._bits == 64) {\n return new BigInt64Array(b.read(len * 8));\n }\n }\n const rets = [];\n for (let i = 0; i < len; i++) {\n rets.push(this._type.decodeValue(b, vec._type));\n }\n return rets;\n }\n get name() {\n return `vec ${this._type.name}`;\n }\n display() {\n return `vec ${this._type.display()}`;\n }\n valueToString(x) {\n const elements = x.map(e => this._type.valueToString(e));\n return 'vec {' + elements.join('; ') + '}';\n }\n}\n/**\n * Represents an IDL Option\n * @param {Type} t\n */\nexport class OptClass extends ConstructType {\n constructor(_type) {\n super();\n this._type = _type;\n }\n accept(v, d) {\n return v.visitOpt(this, this._type, d);\n }\n covariant(x) {\n try {\n if (Array.isArray(x) && (x.length === 0 || (x.length === 1 && this._type.covariant(x[0]))))\n return true;\n }\n catch (e) {\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)} \\n\\n-> ${e.message}`);\n }\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n if (x.length === 0) {\n return new Uint8Array([0]);\n }\n else {\n return concat(new Uint8Array([1]), this._type.encodeValue(x[0]));\n }\n }\n _buildTypeTableImpl(typeTable) {\n this._type.buildTypeTable(typeTable);\n const opCode = slebEncode(-18 /* IDLTypeIds.Opt */);\n const buffer = this._type.encodeType(typeTable);\n typeTable.add(this, concat(opCode, buffer));\n }\n decodeValue(b, t) {\n const opt = this.checkType(t);\n if (!(opt instanceof OptClass)) {\n throw new Error('Not an option type');\n }\n switch (safeReadUint8(b)) {\n case 0:\n return [];\n case 1:\n return [this._type.decodeValue(b, opt._type)];\n default:\n throw new Error('Not an option value');\n }\n }\n get name() {\n return `opt ${this._type.name}`;\n }\n display() {\n return `opt ${this._type.display()}`;\n }\n valueToString(x) {\n if (x.length === 0) {\n return 'null';\n }\n else {\n return `opt ${this._type.valueToString(x[0])}`;\n }\n }\n}\n/**\n * Represents an IDL Record\n * @param {object} [fields] - mapping of function name to Type\n */\nexport class RecordClass extends ConstructType {\n constructor(fields = {}) {\n super();\n this._fields = Object.entries(fields).sort((a, b) => idlLabelToId(a[0]) - idlLabelToId(b[0]));\n }\n accept(v, d) {\n return v.visitRecord(this, this._fields, d);\n }\n tryAsTuple() {\n const res = [];\n for (let i = 0; i < this._fields.length; i++) {\n const [key, type] = this._fields[i];\n if (key !== `_${i}_`) {\n return null;\n }\n res.push(type);\n }\n return res;\n }\n covariant(x) {\n if (typeof x === 'object' &&\n this._fields.every(([k, t]) => {\n // eslint-disable-next-line\n if (!x.hasOwnProperty(k)) {\n throw new Error(`Record is missing key \"${k}\".`);\n }\n try {\n return t.covariant(x[k]);\n }\n catch (e) {\n throw new Error(`Invalid ${this.display()} argument: \\n\\nfield ${k} -> ${e.message}`);\n }\n }))\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n const values = this._fields.map(([key]) => x[key]);\n const bufs = zipWith(this._fields, values, ([, c], d) => c.encodeValue(d));\n return concat(...bufs);\n }\n _buildTypeTableImpl(T) {\n this._fields.forEach(([_, value]) => value.buildTypeTable(T));\n const opCode = slebEncode(-20 /* IDLTypeIds.Record */);\n const len = lebEncode(this._fields.length);\n const fields = this._fields.map(([key, value]) => concat(lebEncode(idlLabelToId(key)), value.encodeType(T)));\n T.add(this, concat(opCode, len, concat(...fields)));\n }\n decodeValue(b, t) {\n const record = this.checkType(t);\n if (!(record instanceof RecordClass)) {\n throw new Error('Not a record type');\n }\n const x = {};\n let expectedRecordIdx = 0;\n let actualRecordIdx = 0;\n while (actualRecordIdx < record._fields.length) {\n const [hash, type] = record._fields[actualRecordIdx];\n if (expectedRecordIdx >= this._fields.length) {\n // skip unexpected left over fields present on the wire\n type.decodeValue(b, type);\n actualRecordIdx++;\n continue;\n }\n const [expectKey, expectType] = this._fields[expectedRecordIdx];\n const expectedId = idlLabelToId(this._fields[expectedRecordIdx][0]);\n const actualId = idlLabelToId(hash);\n if (expectedId === actualId) {\n // the current field on the wire matches the expected field\n x[expectKey] = expectType.decodeValue(b, type);\n expectedRecordIdx++;\n actualRecordIdx++;\n }\n else if (actualId > expectedId) {\n // The expected field does not exist on the wire\n if (expectType instanceof OptClass || expectType instanceof ReservedClass) {\n x[expectKey] = [];\n expectedRecordIdx++;\n }\n else {\n throw new Error('Cannot find required field ' + expectKey);\n }\n }\n else {\n // The field on the wire does not exist in the output type, so we can skip it\n type.decodeValue(b, type);\n actualRecordIdx++;\n }\n }\n // initialize left over expected optional fields\n for (const [expectKey, expectType] of this._fields.slice(expectedRecordIdx)) {\n if (expectType instanceof OptClass || expectType instanceof ReservedClass) {\n // TODO this assumes null value in opt is represented as []\n x[expectKey] = [];\n }\n else {\n throw new Error('Cannot find required field ' + expectKey);\n }\n }\n return x;\n }\n get name() {\n const fields = this._fields.map(([key, value]) => key + ':' + value.name);\n return `record {${fields.join('; ')}}`;\n }\n display() {\n const fields = this._fields.map(([key, value]) => key + ':' + value.display());\n return `record {${fields.join('; ')}}`;\n }\n valueToString(x) {\n const values = this._fields.map(([key]) => x[key]);\n const fields = zipWith(this._fields, values, ([k, c], d) => k + '=' + c.valueToString(d));\n return `record {${fields.join('; ')}}`;\n }\n}\n/**\n * Represents Tuple, a syntactic sugar for Record.\n * @param {Type} components\n */\nexport class TupleClass extends RecordClass {\n constructor(_components) {\n const x = {};\n _components.forEach((e, i) => (x['_' + i + '_'] = e));\n super(x);\n this._components = _components;\n }\n accept(v, d) {\n return v.visitTuple(this, this._components, d);\n }\n covariant(x) {\n // `>=` because tuples can be covariant when encoded.\n if (Array.isArray(x) &&\n x.length >= this._fields.length &&\n this._components.every((t, i) => {\n try {\n return t.covariant(x[i]);\n }\n catch (e) {\n throw new Error(`Invalid ${this.display()} argument: \\n\\nindex ${i} -> ${e.message}`);\n }\n }))\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n const bufs = zipWith(this._components, x, (c, d) => c.encodeValue(d));\n return concat(...bufs);\n }\n decodeValue(b, t) {\n const tuple = this.checkType(t);\n if (!(tuple instanceof TupleClass)) {\n throw new Error('not a tuple type');\n }\n if (tuple._components.length < this._components.length) {\n throw new Error('tuple mismatch');\n }\n const res = [];\n for (const [i, wireType] of tuple._components.entries()) {\n if (i >= this._components.length) {\n // skip value\n wireType.decodeValue(b, wireType);\n }\n else {\n res.push(this._components[i].decodeValue(b, wireType));\n }\n }\n return res;\n }\n display() {\n const fields = this._components.map(value => value.display());\n return `record {${fields.join('; ')}}`;\n }\n valueToString(values) {\n const fields = zipWith(this._components, values, (c, d) => c.valueToString(d));\n return `record {${fields.join('; ')}}`;\n }\n}\n/**\n * Represents an IDL Variant\n * @param {object} [fields] - mapping of function name to Type\n */\nexport class VariantClass extends ConstructType {\n constructor(fields = {}) {\n super();\n this._fields = Object.entries(fields).sort((a, b) => idlLabelToId(a[0]) - idlLabelToId(b[0]));\n }\n accept(v, d) {\n return v.visitVariant(this, this._fields, d);\n }\n covariant(x) {\n if (typeof x === 'object' &&\n Object.entries(x).length === 1 &&\n this._fields.every(([k, v]) => {\n try {\n // eslint-disable-next-line\n return !x.hasOwnProperty(k) || v.covariant(x[k]);\n }\n catch (e) {\n throw new Error(`Invalid ${this.display()} argument: \\n\\nvariant ${k} -> ${e.message}`);\n }\n }))\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n for (let i = 0; i < this._fields.length; i++) {\n const [name, type] = this._fields[i];\n // eslint-disable-next-line\n if (x.hasOwnProperty(name)) {\n const idx = lebEncode(i);\n const buf = type.encodeValue(x[name]);\n return concat(idx, buf);\n }\n }\n throw Error('Variant has no data: ' + x);\n }\n _buildTypeTableImpl(typeTable) {\n this._fields.forEach(([, type]) => {\n type.buildTypeTable(typeTable);\n });\n const opCode = slebEncode(-21 /* IDLTypeIds.Variant */);\n const len = lebEncode(this._fields.length);\n const fields = this._fields.map(([key, value]) => concat(lebEncode(idlLabelToId(key)), value.encodeType(typeTable)));\n typeTable.add(this, concat(opCode, len, ...fields));\n }\n decodeValue(b, t) {\n const variant = this.checkType(t);\n if (!(variant instanceof VariantClass)) {\n throw new Error('Not a variant type');\n }\n const idx = Number(lebDecode(b));\n if (idx >= variant._fields.length) {\n throw Error('Invalid variant index: ' + idx);\n }\n const [wireHash, wireType] = variant._fields[idx];\n for (const [key, expectType] of this._fields) {\n if (idlLabelToId(wireHash) === idlLabelToId(key)) {\n const value = expectType.decodeValue(b, wireType);\n return { [key]: value };\n }\n }\n throw new Error('Cannot find field hash ' + wireHash);\n }\n get name() {\n const fields = this._fields.map(([key, type]) => key + ':' + type.name);\n return `variant {${fields.join('; ')}}`;\n }\n display() {\n const fields = this._fields.map(([key, type]) => key + (type.name === 'null' ? '' : `:${type.display()}`));\n return `variant {${fields.join('; ')}}`;\n }\n valueToString(x) {\n for (const [name, type] of this._fields) {\n // eslint-disable-next-line\n if (x.hasOwnProperty(name)) {\n const value = type.valueToString(x[name]);\n if (value === 'null') {\n return `variant {${name}}`;\n }\n else {\n return `variant {${name}=${value}}`;\n }\n }\n }\n throw new Error('Variant has no data: ' + x);\n }\n}\n/**\n * Represents a reference to an IDL type, used for defining recursive data\n * types.\n */\nexport class RecClass extends ConstructType {\n constructor() {\n super(...arguments);\n this._id = RecClass._counter++;\n this._type = undefined;\n }\n accept(v, d) {\n if (!this._type) {\n throw Error('Recursive type uninitialized.');\n }\n return v.visitRec(this, this._type, d);\n }\n fill(t) {\n this._type = t;\n }\n getType() {\n return this._type;\n }\n covariant(x) {\n if (this._type ? this._type.covariant(x) : false)\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n if (!this._type) {\n throw Error('Recursive type uninitialized.');\n }\n return this._type.encodeValue(x);\n }\n _buildTypeTableImpl(typeTable) {\n if (!this._type) {\n throw Error('Recursive type uninitialized.');\n }\n typeTable.add(this, new Uint8Array([]));\n this._type.buildTypeTable(typeTable);\n typeTable.merge(this, this._type.name);\n }\n decodeValue(b, t) {\n if (!this._type) {\n throw Error('Recursive type uninitialized.');\n }\n return this._type.decodeValue(b, t);\n }\n get name() {\n return `rec_${this._id}`;\n }\n display() {\n if (!this._type) {\n throw Error('Recursive type uninitialized.');\n }\n return `μ${this.name}.${this._type.name}`;\n }\n valueToString(x) {\n if (!this._type) {\n throw Error('Recursive type uninitialized.');\n }\n return this._type.valueToString(x);\n }\n}\nRecClass._counter = 0;\nfunction decodePrincipalId(b) {\n const x = safeReadUint8(b);\n if (x !== 1) {\n throw new Error('Cannot decode principal');\n }\n const len = Number(lebDecode(b));\n return PrincipalId.fromUint8Array(new Uint8Array(safeRead(b, len)));\n}\n/**\n * Represents an IDL principal reference\n */\nexport class PrincipalClass extends PrimitiveType {\n accept(v, d) {\n return v.visitPrincipal(this, d);\n }\n covariant(x) {\n if (x && x._isPrincipal)\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n const buf = x.toUint8Array();\n const len = lebEncode(buf.byteLength);\n return concat(new Uint8Array([1]), len, buf);\n }\n encodeType() {\n return slebEncode(-24 /* IDLTypeIds.Principal */);\n }\n decodeValue(b, t) {\n this.checkType(t);\n return decodePrincipalId(b);\n }\n get name() {\n return 'principal';\n }\n valueToString(x) {\n return `${this.name} \"${x.toText()}\"`;\n }\n}\n/**\n * Represents an IDL function reference.\n * @param argTypes Argument types.\n * @param retTypes Return types.\n * @param annotations Function annotations.\n */\nexport class FuncClass extends ConstructType {\n constructor(argTypes, retTypes, annotations = []) {\n super();\n this.argTypes = argTypes;\n this.retTypes = retTypes;\n this.annotations = annotations;\n }\n static argsToString(types, v) {\n if (types.length !== v.length) {\n throw new Error('arity mismatch');\n }\n return '(' + types.map((t, i) => t.valueToString(v[i])).join(', ') + ')';\n }\n accept(v, d) {\n return v.visitFunc(this, d);\n }\n covariant(x) {\n if (Array.isArray(x) && x.length === 2 && x[0] && x[0]._isPrincipal && typeof x[1] === 'string')\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue([principal, methodName]) {\n const buf = principal.toUint8Array();\n const len = lebEncode(buf.byteLength);\n const canister = concat(new Uint8Array([1]), len, buf);\n const method = new TextEncoder().encode(methodName);\n const methodLen = lebEncode(method.byteLength);\n return concat(new Uint8Array([1]), canister, methodLen, method);\n }\n _buildTypeTableImpl(T) {\n this.argTypes.forEach(arg => arg.buildTypeTable(T));\n this.retTypes.forEach(arg => arg.buildTypeTable(T));\n const opCode = slebEncode(-22 /* IDLTypeIds.Func */);\n const argLen = lebEncode(this.argTypes.length);\n const args = concat(...this.argTypes.map(arg => arg.encodeType(T)));\n const retLen = lebEncode(this.retTypes.length);\n const rets = concat(...this.retTypes.map(arg => arg.encodeType(T)));\n const annLen = lebEncode(this.annotations.length);\n const anns = concat(...this.annotations.map(a => this.encodeAnnotation(a)));\n T.add(this, concat(opCode, argLen, args, retLen, rets, annLen, anns));\n }\n decodeValue(b) {\n const x = safeReadUint8(b);\n if (x !== 1) {\n throw new Error('Cannot decode function reference');\n }\n const canister = decodePrincipalId(b);\n const mLen = Number(lebDecode(b));\n const buf = safeRead(b, mLen);\n const decoder = new TextDecoder('utf8', { fatal: true });\n const method = decoder.decode(buf);\n return [canister, method];\n }\n get name() {\n const args = this.argTypes.map(arg => arg.name).join(', ');\n const rets = this.retTypes.map(arg => arg.name).join(', ');\n const annon = ' ' + this.annotations.join(' ');\n return `(${args}) -> (${rets})${annon}`;\n }\n valueToString([principal, str]) {\n return `func \"${principal.toText()}\".${str}`;\n }\n display() {\n const args = this.argTypes.map(arg => arg.display()).join(', ');\n const rets = this.retTypes.map(arg => arg.display()).join(', ');\n const annon = ' ' + this.annotations.join(' ');\n return `(${args}) → (${rets})${annon}`;\n }\n encodeAnnotation(ann) {\n if (ann === 'query') {\n return new Uint8Array([1]);\n }\n else if (ann === 'oneway') {\n return new Uint8Array([2]);\n }\n else if (ann === 'composite_query') {\n return new Uint8Array([3]);\n }\n else {\n throw new Error('Illegal function annotation');\n }\n }\n}\nexport class ServiceClass extends ConstructType {\n constructor(fields) {\n super();\n this._fields = Object.entries(fields).sort((a, b) => {\n if (a[0] < b[0]) {\n return -1;\n }\n if (a[0] > b[0]) {\n return 1;\n }\n return 0;\n });\n }\n accept(v, d) {\n return v.visitService(this, d);\n }\n covariant(x) {\n if (x && x._isPrincipal)\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n const buf = x.toUint8Array();\n const len = lebEncode(buf.length);\n return concat(new Uint8Array([1]), len, buf);\n }\n _buildTypeTableImpl(T) {\n this._fields.forEach(([_, func]) => func.buildTypeTable(T));\n const opCode = slebEncode(-23 /* IDLTypeIds.Service */);\n const len = lebEncode(this._fields.length);\n const meths = this._fields.map(([label, func]) => {\n const labelBuf = new TextEncoder().encode(label);\n const labelLen = lebEncode(labelBuf.length);\n return concat(labelLen, labelBuf, func.encodeType(T));\n });\n T.add(this, concat(opCode, len, ...meths));\n }\n decodeValue(b) {\n return decodePrincipalId(b);\n }\n get name() {\n const fields = this._fields.map(([key, value]) => key + ':' + value.name);\n return `service {${fields.join('; ')}}`;\n }\n valueToString(x) {\n return `service \"${x.toText()}\"`;\n }\n}\n/**\n * Takes an unknown value and returns a string representation of it.\n * @param x - unknown value\n * @returns {string} string representation of the value\n */\nfunction toReadableString(x) {\n const str = JSON.stringify(x, (_key, value) => typeof value === 'bigint' ? `BigInt(${value})` : value);\n return str && str.length > toReadableString_max\n ? str.substring(0, toReadableString_max - 3) + '...'\n : str;\n}\n/**\n * Encode a array of values\n * @param argTypes - array of Types\n * @param args - array of values\n * @returns {ArrayBuffer} serialised value\n */\nexport function encode(argTypes, args) {\n if (args.length < argTypes.length) {\n throw Error('Wrong number of message arguments');\n }\n const typeTable = new TypeTable();\n argTypes.forEach(t => t.buildTypeTable(typeTable));\n const magic = new TextEncoder().encode(magicNumber);\n const table = typeTable.encode();\n const len = lebEncode(args.length);\n const typs = concat(...argTypes.map(t => t.encodeType(typeTable)));\n const vals = concat(...zipWith(argTypes, args, (t, x) => {\n try {\n t.covariant(x);\n }\n catch (e) {\n const err = new Error(e.message + '\\n\\n');\n throw err;\n }\n return t.encodeValue(x);\n }));\n return concat(magic, table, len, typs, vals);\n}\n/**\n * Decode a binary value\n * @param retTypes - Types expected in the buffer.\n * @param bytes - hex-encoded string, or buffer.\n * @returns Value deserialised to JS type\n */\nexport function decode(retTypes, bytes) {\n const b = new Pipe(bytes);\n if (bytes.byteLength < magicNumber.length) {\n throw new Error('Message length smaller than magic number');\n }\n const magicBuffer = safeRead(b, magicNumber.length);\n const magic = new TextDecoder().decode(magicBuffer);\n if (magic !== magicNumber) {\n throw new Error('Wrong magic number: ' + JSON.stringify(magic));\n }\n function readTypeTable(pipe) {\n const typeTable = [];\n const len = Number(lebDecode(pipe));\n for (let i = 0; i < len; i++) {\n const ty = Number(slebDecode(pipe));\n switch (ty) {\n case -18 /* IDLTypeIds.Opt */:\n case -19 /* IDLTypeIds.Vector */: {\n const t = Number(slebDecode(pipe));\n typeTable.push([ty, t]);\n break;\n }\n case -20 /* IDLTypeIds.Record */:\n case -21 /* IDLTypeIds.Variant */: {\n const fields = [];\n let objectLength = Number(lebDecode(pipe));\n let prevHash;\n while (objectLength--) {\n const hash = Number(lebDecode(pipe));\n if (hash >= Math.pow(2, 32)) {\n throw new Error('field id out of 32-bit range');\n }\n if (typeof prevHash === 'number' && prevHash >= hash) {\n throw new Error('field id collision or not sorted');\n }\n prevHash = hash;\n const t = Number(slebDecode(pipe));\n fields.push([hash, t]);\n }\n typeTable.push([ty, fields]);\n break;\n }\n case -22 /* IDLTypeIds.Func */: {\n const args = [];\n let argLength = Number(lebDecode(pipe));\n while (argLength--) {\n args.push(Number(slebDecode(pipe)));\n }\n const returnValues = [];\n let returnValuesLength = Number(lebDecode(pipe));\n while (returnValuesLength--) {\n returnValues.push(Number(slebDecode(pipe)));\n }\n const annotations = [];\n let annotationLength = Number(lebDecode(pipe));\n while (annotationLength--) {\n const annotation = Number(lebDecode(pipe));\n switch (annotation) {\n case 1: {\n annotations.push('query');\n break;\n }\n case 2: {\n annotations.push('oneway');\n break;\n }\n case 3: {\n annotations.push('composite_query');\n break;\n }\n default:\n throw new Error('unknown annotation');\n }\n }\n typeTable.push([ty, [args, returnValues, annotations]]);\n break;\n }\n case -23 /* IDLTypeIds.Service */: {\n let servLength = Number(lebDecode(pipe));\n const methods = [];\n while (servLength--) {\n const nameLength = Number(lebDecode(pipe));\n const funcName = new TextDecoder().decode(safeRead(pipe, nameLength));\n const funcType = slebDecode(pipe);\n methods.push([funcName, funcType]);\n }\n typeTable.push([ty, methods]);\n break;\n }\n default:\n throw new Error('Illegal op_code: ' + ty);\n }\n }\n const rawList = [];\n const length = Number(lebDecode(pipe));\n for (let i = 0; i < length; i++) {\n rawList.push(Number(slebDecode(pipe)));\n }\n return [typeTable, rawList];\n }\n const [rawTable, rawTypes] = readTypeTable(b);\n if (rawTypes.length < retTypes.length) {\n throw new Error('Wrong number of return values');\n }\n const table = rawTable.map(_ => Rec());\n function getType(t) {\n if (t < -24) {\n throw new Error('future value not supported');\n }\n if (t < 0) {\n switch (t) {\n case -1:\n return Null;\n case -2:\n return Bool;\n case -3:\n return Nat;\n case -4:\n return Int;\n case -5:\n return Nat8;\n case -6:\n return Nat16;\n case -7:\n return Nat32;\n case -8:\n return Nat64;\n case -9:\n return Int8;\n case -10:\n return Int16;\n case -11:\n return Int32;\n case -12:\n return Int64;\n case -13:\n return Float32;\n case -14:\n return Float64;\n case -15:\n return Text;\n case -16:\n return Reserved;\n case -17:\n return Empty;\n case -24:\n return Principal;\n default:\n throw new Error('Illegal op_code: ' + t);\n }\n }\n if (t >= rawTable.length) {\n throw new Error('type index out of range');\n }\n return table[t];\n }\n function buildType(entry) {\n switch (entry[0]) {\n case -19 /* IDLTypeIds.Vector */: {\n const ty = getType(entry[1]);\n return Vec(ty);\n }\n case -18 /* IDLTypeIds.Opt */: {\n const ty = getType(entry[1]);\n return Opt(ty);\n }\n case -20 /* IDLTypeIds.Record */: {\n const fields = {};\n for (const [hash, ty] of entry[1]) {\n const name = `_${hash}_`;\n fields[name] = getType(ty);\n }\n const record = Record(fields);\n const tuple = record.tryAsTuple();\n if (Array.isArray(tuple)) {\n return Tuple(...tuple);\n }\n else {\n return record;\n }\n }\n case -21 /* IDLTypeIds.Variant */: {\n const fields = {};\n for (const [hash, ty] of entry[1]) {\n const name = `_${hash}_`;\n fields[name] = getType(ty);\n }\n return Variant(fields);\n }\n case -22 /* IDLTypeIds.Func */: {\n const [args, returnValues, annotations] = entry[1];\n return Func(args.map((t) => getType(t)), returnValues.map((t) => getType(t)), annotations);\n }\n case -23 /* IDLTypeIds.Service */: {\n const rec = {};\n const methods = entry[1];\n for (const [name, typeRef] of methods) {\n let type = getType(typeRef);\n if (type instanceof RecClass) {\n // unpack reference type\n type = type.getType();\n }\n if (!(type instanceof FuncClass)) {\n throw new Error('Illegal service definition: services can only contain functions');\n }\n rec[name] = type;\n }\n return Service(rec);\n }\n default:\n throw new Error('Illegal op_code: ' + entry[0]);\n }\n }\n rawTable.forEach((entry, i) => {\n // Process function type first, so that we can construct the correct service type\n if (entry[0] === -22 /* IDLTypeIds.Func */) {\n const t = buildType(entry);\n table[i].fill(t);\n }\n });\n rawTable.forEach((entry, i) => {\n if (entry[0] !== -22 /* IDLTypeIds.Func */) {\n const t = buildType(entry);\n table[i].fill(t);\n }\n });\n const types = rawTypes.map(t => getType(t));\n const output = retTypes.map((t, i) => {\n return t.decodeValue(b, types[i]);\n });\n // skip unused values\n for (let ind = retTypes.length; ind < types.length; ind++) {\n types[ind].decodeValue(b, types[ind]);\n }\n if (b.byteLength > 0) {\n throw new Error('decode: Left-over bytes');\n }\n return output;\n}\n// Export Types instances.\nexport const Empty = new EmptyClass();\nexport const Reserved = new ReservedClass();\n/**\n * Client-only type for deserializing unknown data. Not supported by Candid, and its use is discouraged.\n */\nexport const Unknown = new UnknownClass();\nexport const Bool = new BoolClass();\nexport const Null = new NullClass();\nexport const Text = new TextClass();\nexport const Int = new IntClass();\nexport const Nat = new NatClass();\nexport const Float32 = new FloatClass(32);\nexport const Float64 = new FloatClass(64);\nexport const Int8 = new FixedIntClass(8);\nexport const Int16 = new FixedIntClass(16);\nexport const Int32 = new FixedIntClass(32);\nexport const Int64 = new FixedIntClass(64);\nexport const Nat8 = new FixedNatClass(8);\nexport const Nat16 = new FixedNatClass(16);\nexport const Nat32 = new FixedNatClass(32);\nexport const Nat64 = new FixedNatClass(64);\nexport const Principal = new PrincipalClass();\n/**\n *\n * @param types array of any types\n * @returns TupleClass from those types\n */\nexport function Tuple(...types) {\n return new TupleClass(types);\n}\n/**\n *\n * @param t IDL Type\n * @returns VecClass from that type\n */\nexport function Vec(t) {\n return new VecClass(t);\n}\n/**\n *\n * @param t IDL Type\n * @returns OptClass of Type\n */\nexport function Opt(t) {\n return new OptClass(t);\n}\n/**\n *\n * @param t Record of string and IDL Type\n * @returns RecordClass of string and Type\n */\nexport function Record(t) {\n return new RecordClass(t);\n}\n/**\n *\n * @param fields Record of string and IDL Type\n * @returns VariantClass\n */\nexport function Variant(fields) {\n return new VariantClass(fields);\n}\n/**\n *\n * @returns new RecClass\n */\nexport function Rec() {\n return new RecClass();\n}\n/**\n *\n * @param args array of IDL Types\n * @param ret array of IDL Types\n * @param annotations array of strings, [] by default\n * @returns new FuncClass\n */\nexport function Func(args, ret, annotations = []) {\n return new FuncClass(args, ret, annotations);\n}\n/**\n *\n * @param t Record of string and FuncClass\n * @returns ServiceClass\n */\nexport function Service(t) {\n return new ServiceClass(t);\n}\n//# sourceMappingURL=idl.js.map","import { lebEncode } from '@dfinity/candid';\nimport borc from 'borc';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { compare, concat, uint8ToBuf } from './utils/buffer';\n/**\n * sha256 hash the provided Buffer\n * @param data - input to hash function\n */\nexport function hash(data) {\n return uint8ToBuf(sha256.create().update(new Uint8Array(data)).digest());\n}\n/**\n *\n * @param value unknown value\n * @returns ArrayBuffer\n */\nexport function hashValue(value) {\n if (value instanceof borc.Tagged) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return hashValue(value.value);\n }\n else if (typeof value === 'string') {\n return hashString(value);\n }\n else if (typeof value === 'number') {\n return hash(lebEncode(value));\n }\n else if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {\n return hash(value);\n }\n else if (Array.isArray(value)) {\n const vals = value.map(hashValue);\n return hash(concat(...vals));\n }\n else if (value && typeof value === 'object' && value._isPrincipal) {\n return hash(value.toUint8Array());\n }\n else if (typeof value === 'object' &&\n value !== null &&\n typeof value.toHash === 'function') {\n return hashValue(value.toHash());\n // TODO This should be move to a specific async method as the webauthn flow required\n // the flow to be synchronous to ensure Safari touch id works.\n // } else if (value instanceof Promise) {\n // return value.then(x => hashValue(x));\n }\n else if (typeof value === 'object') {\n return hashOfMap(value);\n }\n else if (typeof value === 'bigint') {\n // Do this check much later than the other bigint check because this one is much less\n // type-safe.\n // So we want to try all the high-assurance type guards before this 'probable' one.\n return hash(lebEncode(value));\n }\n throw Object.assign(new Error(`Attempt to hash a value of unsupported type: ${value}`), {\n // include so logs/callers can understand the confusing value.\n // (when stringified in error message, prototype info is lost)\n value,\n });\n}\nconst hashString = (value) => {\n const encoded = new TextEncoder().encode(value);\n return hash(encoded);\n};\n/**\n * Get the RequestId of the provided ic-ref request.\n * RequestId is the result of the representation-independent-hash function.\n * https://sdk.dfinity.org/docs/interface-spec/index.html#hash-of-map\n * @param request - ic-ref request to hash into RequestId\n */\nexport function requestIdOf(request) {\n return hashOfMap(request);\n}\n/**\n * Hash a map into an ArrayBuffer using the representation-independent-hash function.\n * https://sdk.dfinity.org/docs/interface-spec/index.html#hash-of-map\n * @param map - Any non-nested object\n * @returns ArrayBuffer\n */\nexport function hashOfMap(map) {\n const hashed = Object.entries(map)\n .filter(([, value]) => value !== undefined)\n .map(([key, value]) => {\n const hashedKey = hashString(key);\n const hashedValue = hashValue(value);\n return [hashedKey, hashedValue];\n });\n const traversed = hashed;\n const sorted = traversed.sort(([k1], [k2]) => {\n return compare(k1, k2);\n });\n const concatenated = concat(...sorted.map(x => concat(...x)));\n const result = hash(concatenated);\n return result;\n}\n//# sourceMappingURL=request_id.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { Principal } from '@dfinity/principal';\nimport { requestIdOf } from './request_id';\nimport { concat, toHex } from './utils/buffer';\nconst domainSeparator = new TextEncoder().encode('\\x0Aic-request');\n/**\n * An Identity that can sign blobs.\n */\nexport class SignIdentity {\n /**\n * Get the principal represented by this identity. Normally should be a\n * `Principal.selfAuthenticating()`.\n */\n getPrincipal() {\n if (!this._principal) {\n this._principal = Principal.selfAuthenticating(new Uint8Array(this.getPublicKey().toDer()));\n }\n return this._principal;\n }\n /**\n * Transform a request into a signed version of the request. This is done last\n * after the transforms on the body of a request. The returned object can be\n * anything, but must be serializable to CBOR.\n * @param request - internet computer request to transform\n */\n async transformRequest(request) {\n const { body } = request, fields = __rest(request, [\"body\"]);\n const requestId = requestIdOf(body);\n return Object.assign(Object.assign({}, fields), { body: {\n content: body,\n sender_pubkey: this.getPublicKey().toDer(),\n sender_sig: await this.sign(concat(domainSeparator, requestId)),\n } });\n }\n}\nexport class AnonymousIdentity {\n getPrincipal() {\n return Principal.anonymous();\n }\n async transformRequest(request) {\n return Object.assign(Object.assign({}, request), { body: { content: request.body } });\n }\n}\n/**\n * Create an IdentityDescriptor from a @dfinity/identity Identity\n * @param identity - identity describe in returned descriptor\n */\nexport function createIdentityDescriptor(identity) {\n const identityIndicator = 'getPublicKey' in identity\n ? { type: 'PublicKeyIdentity', publicKey: toHex(identity.getPublicKey().toDer()) }\n : { type: 'AnonymousIdentity' };\n return identityIndicator;\n}\n//# sourceMappingURL=auth.js.map","// This file is based on:\n// https://github.com/dfinity-lab/dfinity/blob/9bca65f8edd65701ea6bdb00e0752f9186bbc893/docs/spec/public/index.adoc#cbor-encoding-of-requests-and-responses\nimport borc from 'borc';\nimport * as cbor from 'simple-cbor';\nimport { SelfDescribeCborSerializer } from 'simple-cbor';\nimport { concat, fromHex, toHex } from './utils/buffer';\n// We are using hansl/simple-cbor for CBOR serialization, to avoid issues with\n// encoding the uint64 values that the HTTP handler of the client expects for\n// canister IDs. However, simple-cbor does not yet provide deserialization so\n// we are using `Uint8Array` so that we can use the dignifiedquire/borc CBOR\n// decoder.\nclass PrincipalEncoder {\n get name() {\n return 'Principal';\n }\n get priority() {\n return 0;\n }\n match(value) {\n return value && value._isPrincipal === true;\n }\n encode(v) {\n return cbor.value.bytes(v.toUint8Array());\n }\n}\nclass BufferEncoder {\n get name() {\n return 'Buffer';\n }\n get priority() {\n return 1;\n }\n match(value) {\n return value instanceof ArrayBuffer || ArrayBuffer.isView(value);\n }\n encode(v) {\n return cbor.value.bytes(new Uint8Array(v));\n }\n}\nclass BigIntEncoder {\n get name() {\n return 'BigInt';\n }\n get priority() {\n return 1;\n }\n match(value) {\n return typeof value === `bigint`;\n }\n encode(v) {\n // Always use a bigint encoding.\n if (v > BigInt(0)) {\n return cbor.value.tagged(2, cbor.value.bytes(fromHex(v.toString(16))));\n }\n else {\n return cbor.value.tagged(3, cbor.value.bytes(fromHex((BigInt('-1') * v).toString(16))));\n }\n }\n}\nconst serializer = SelfDescribeCborSerializer.withDefaultEncoders(true);\nserializer.addEncoder(new PrincipalEncoder());\nserializer.addEncoder(new BufferEncoder());\nserializer.addEncoder(new BigIntEncoder());\nexport var CborTag;\n(function (CborTag) {\n CborTag[CborTag[\"Uint64LittleEndian\"] = 71] = \"Uint64LittleEndian\";\n CborTag[CborTag[\"Semantic\"] = 55799] = \"Semantic\";\n})(CborTag || (CborTag = {}));\n/**\n * Encode a JavaScript value into CBOR.\n */\nexport function encode(value) {\n return serializer.serialize(value);\n}\nfunction decodePositiveBigInt(buf) {\n const len = buf.byteLength;\n let res = BigInt(0);\n for (let i = 0; i < len; i++) {\n res = res * BigInt(0x100) + BigInt(buf[i]);\n }\n return res;\n}\n// A BORC subclass that decodes byte strings to ArrayBuffer instead of the Buffer class.\nclass Uint8ArrayDecoder extends borc.Decoder {\n createByteString(raw) {\n return concat(...raw);\n }\n createByteStringFromHeap(start, end) {\n if (start === end) {\n return new ArrayBuffer(0);\n }\n return new Uint8Array(this._heap.slice(start, end));\n }\n}\nexport function decode(input) {\n const buffer = new Uint8Array(input);\n const decoder = new Uint8ArrayDecoder({\n size: buffer.byteLength,\n tags: {\n // Override tags 2 and 3 for BigInt support (borc supports only BigNumber).\n 2: val => decodePositiveBigInt(val),\n 3: val => -decodePositiveBigInt(val),\n [CborTag.Semantic]: (value) => value,\n },\n });\n try {\n return decoder.decodeFirst(buffer);\n }\n catch (e) {\n throw new Error(`Failed to decode CBOR: ${e}, input: ${toHex(buffer)}`);\n }\n}\n//# sourceMappingURL=cbor.js.map","/**\n * Generates a random unsigned 32-bit integer between 0 and 0xffffffff\n * @returns {number} a random number\n */\nexport const randomNumber = () => {\n // determine whether browser crypto is available\n if (typeof window !== 'undefined' && !!window.crypto && !!window.crypto.getRandomValues) {\n const array = new Uint32Array(1);\n window.crypto.getRandomValues(array);\n return array[0];\n }\n // A second check for webcrypto, in case it is loaded under global instead of window\n if (typeof crypto !== 'undefined' && crypto.getRandomValues) {\n const array = new Uint32Array(1);\n crypto.getRandomValues(array);\n return array[0];\n }\n // determine whether node crypto is available\n if (typeof crypto !== 'undefined' && crypto.randomInt) {\n return crypto.randomInt(0, 0xffffffff);\n }\n // fall back to Math.random\n return Math.floor(Math.random() * 0xffffffff);\n};\n//# sourceMappingURL=random.js.map","import { randomNumber } from '../../utils/random';\n// The types of values allowed in the `request_type` field for submit requests.\nexport var SubmitRequestType;\n(function (SubmitRequestType) {\n SubmitRequestType[\"Call\"] = \"call\";\n})(SubmitRequestType || (SubmitRequestType = {}));\n/**\n * Create a random Nonce, based on random values\n */\nexport function makeNonce() {\n // Encode 128 bits.\n const buffer = new ArrayBuffer(16);\n const view = new DataView(buffer);\n const rand1 = randomNumber();\n const rand2 = randomNumber();\n const rand3 = randomNumber();\n const rand4 = randomNumber();\n view.setUint32(0, rand1);\n view.setUint32(4, rand2);\n view.setUint32(8, rand3);\n view.setUint32(12, rand4);\n return buffer;\n}\n//# sourceMappingURL=types.js.map","import { lebEncode } from '@dfinity/candid';\nimport * as cbor from 'simple-cbor';\nimport { makeNonce, } from './types';\nconst NANOSECONDS_PER_MILLISECONDS = BigInt(1000000);\nconst REPLICA_PERMITTED_DRIFT_MILLISECONDS = 60 * 1000;\nexport class Expiry {\n constructor(deltaInMSec) {\n // if ingress as seconds is less than 90, round to nearest second\n if (deltaInMSec < 90 * 1000) {\n // Raw value without subtraction of REPLICA_PERMITTED_DRIFT_MILLISECONDS\n const raw_value = BigInt(Date.now() + deltaInMSec) * NANOSECONDS_PER_MILLISECONDS;\n const ingress_as_seconds = raw_value / BigInt(1000000000);\n this._value = ingress_as_seconds * BigInt(1000000000);\n return;\n }\n // Use bigint because it can overflow the maximum number allowed in a double float.\n const raw_value = BigInt(Math.floor(Date.now() + deltaInMSec - REPLICA_PERMITTED_DRIFT_MILLISECONDS)) *\n NANOSECONDS_PER_MILLISECONDS;\n // round down to the nearest second (since )\n const ingress_as_seconds = raw_value / BigInt(1000000000);\n // round down to nearest minute\n const ingress_as_minutes = ingress_as_seconds / BigInt(60);\n const rounded_down_nanos = ingress_as_minutes * BigInt(60) * BigInt(1000000000);\n this._value = rounded_down_nanos;\n }\n toCBOR() {\n // TODO: change this to take the minimum amount of space (it always takes 8 bytes now).\n return cbor.value.u64(this._value.toString(16), 16);\n }\n toHash() {\n return lebEncode(this._value);\n }\n}\n/**\n * Create a Nonce transform, which takes a function that returns a Buffer, and adds it\n * as the nonce to every call requests.\n * @param nonceFn A function that returns a buffer. By default uses a semi-random method.\n */\nexport function makeNonceTransform(nonceFn = makeNonce) {\n return async (request) => {\n // Nonce needs to be inserted into the header for all requests, to enable logs to be correlated with requests.\n const headers = request.request.headers;\n // TODO: uncomment this when the http proxy supports it.\n // headers.set('X-IC-Request-ID', toHex(new Uint8Array(nonce)));\n request.request.headers = headers;\n // Nonce only needs to be inserted into the body for async calls, to prevent replay attacks.\n if (request.endpoint === \"call\" /* Endpoint.Call */) {\n request.body.nonce = nonceFn();\n }\n };\n}\n/**\n * Create a transform that adds a delay (by default 5 minutes) to the expiry.\n *\n * @param delayInMilliseconds The delay to add to the call time, in milliseconds.\n */\nexport function makeExpiryTransform(delayInMilliseconds) {\n return async (request) => {\n request.body.ingress_expiry = new Expiry(delayInMilliseconds);\n };\n}\n/**\n * Maps the default fetch headers field to the serializable HttpHeaderField.\n *\n * @param headers Fetch definition of the headers type\n * @returns array of header fields\n */\nexport function httpHeadersTransform(headers) {\n const headerFields = [];\n headers.forEach((value, key) => {\n headerFields.push([key, value]);\n });\n return headerFields;\n}\n//# sourceMappingURL=transforms.js.map","import { AgentError } from '../../errors';\nexport class AgentHTTPResponseError extends AgentError {\n constructor(message, response) {\n super(message);\n this.response = response;\n this.name = this.constructor.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n//# sourceMappingURL=errors.js.map","import { bls12_381 } from '@noble/curves/bls12-381';\nimport { toHex } from './buffer';\nexport let verify;\n/**\n *\n * @param pk primary key: Uint8Array\n * @param sig signature: Uint8Array\n * @param msg message: Uint8Array\n * @returns boolean\n */\nexport function blsVerify(pk, sig, msg) {\n const primaryKey = typeof pk === 'string' ? pk : toHex(pk);\n const signature = typeof sig === 'string' ? sig : toHex(sig);\n const message = typeof msg === 'string' ? msg : toHex(msg);\n return bls12_381.verifyShortSignature(signature, message, primaryKey);\n}\n//# sourceMappingURL=bls.js.map","import { PipeArrayBuffer, lebDecode } from '@dfinity/candid';\nexport const decodeLeb128 = (buf) => {\n return lebDecode(new PipeArrayBuffer(buf));\n};\n// time is a LEB128-encoded Nat\nexport const decodeTime = (buf) => {\n const decoded = decodeLeb128(buf);\n // nanoseconds to milliseconds\n return new Date(Number(decoded) / 1000000);\n};\n//# sourceMappingURL=leb.js.map","import * as cbor from './cbor';\nimport { AgentError } from './errors';\nimport { hash } from './request_id';\nimport { bufEquals, concat, fromHex, toHex } from './utils/buffer';\nimport { Principal } from '@dfinity/principal';\nimport * as bls from './utils/bls';\nimport { decodeTime } from './utils/leb';\nimport { MANAGEMENT_CANISTER_ID } from './agent';\n/**\n * A certificate may fail verification with respect to the provided public key\n */\nexport class CertificateVerificationError extends AgentError {\n constructor(reason) {\n super(`Invalid certificate: ${reason}`);\n }\n}\nexport var NodeType;\n(function (NodeType) {\n NodeType[NodeType[\"Empty\"] = 0] = \"Empty\";\n NodeType[NodeType[\"Fork\"] = 1] = \"Fork\";\n NodeType[NodeType[\"Labeled\"] = 2] = \"Labeled\";\n NodeType[NodeType[\"Leaf\"] = 3] = \"Leaf\";\n NodeType[NodeType[\"Pruned\"] = 4] = \"Pruned\";\n})(NodeType || (NodeType = {}));\n/**\n * Make a human readable string out of a hash tree.\n * @param tree\n */\nexport function hashTreeToString(tree) {\n const indent = (s) => s\n .split('\\n')\n .map(x => ' ' + x)\n .join('\\n');\n function labelToString(label) {\n const decoder = new TextDecoder(undefined, { fatal: true });\n try {\n return JSON.stringify(decoder.decode(label));\n }\n catch (e) {\n return `data(...${label.byteLength} bytes)`;\n }\n }\n switch (tree[0]) {\n case NodeType.Empty:\n return '()';\n case NodeType.Fork: {\n if (tree[1] instanceof Array && tree[2] instanceof ArrayBuffer) {\n const left = hashTreeToString(tree[1]);\n const right = hashTreeToString(tree[2]);\n return `sub(\\n left:\\n${indent(left)}\\n---\\n right:\\n${indent(right)}\\n)`;\n }\n else {\n throw new Error('Invalid tree structure for fork');\n }\n }\n case NodeType.Labeled: {\n if (tree[1] instanceof ArrayBuffer && tree[2] instanceof ArrayBuffer) {\n const label = labelToString(tree[1]);\n const sub = hashTreeToString(tree[2]);\n return `label(\\n label:\\n${indent(label)}\\n sub:\\n${indent(sub)}\\n)`;\n }\n else {\n throw new Error('Invalid tree structure for labeled');\n }\n }\n case NodeType.Leaf: {\n if (!tree[1]) {\n throw new Error('Invalid tree structure for leaf');\n }\n else if (Array.isArray(tree[1])) {\n return JSON.stringify(tree[1]);\n }\n return `leaf(...${tree[1].byteLength} bytes)`;\n }\n case NodeType.Pruned: {\n if (!tree[1]) {\n throw new Error('Invalid tree structure for pruned');\n }\n else if (Array.isArray(tree[1])) {\n return JSON.stringify(tree[1]);\n }\n return `pruned(${toHex(new Uint8Array(tree[1]))}`;\n }\n default: {\n return `unknown(${JSON.stringify(tree[0])})`;\n }\n }\n}\nfunction isBufferGreaterThan(a, b) {\n const a8 = new Uint8Array(a);\n const b8 = new Uint8Array(b);\n for (let i = 0; i < a8.length; i++) {\n if (a8[i] > b8[i]) {\n return true;\n }\n }\n return false;\n}\nexport class Certificate {\n constructor(certificate, _rootKey, _canisterId, _blsVerify, \n // Default to 5 minutes\n _maxAgeInMinutes = 5) {\n this._rootKey = _rootKey;\n this._canisterId = _canisterId;\n this._blsVerify = _blsVerify;\n this._maxAgeInMinutes = _maxAgeInMinutes;\n this.cert = cbor.decode(new Uint8Array(certificate));\n }\n /**\n * Create a new instance of a certificate, automatically verifying it. Throws a\n * CertificateVerificationError if the certificate cannot be verified.\n * @constructs Certificate\n * @param {CreateCertificateOptions} options {@link CreateCertificateOptions}\n * @param {ArrayBuffer} options.certificate The bytes of the certificate\n * @param {ArrayBuffer} options.rootKey The root key to verify against\n * @param {Principal} options.canisterId The effective or signing canister ID\n * @param {number} options.maxAgeInMinutes The maximum age of the certificate in minutes. Default is 5 minutes.\n * @throws {CertificateVerificationError}\n */\n static async create(options) {\n const cert = Certificate.createUnverified(options);\n await cert.verify();\n return cert;\n }\n static createUnverified(options) {\n let blsVerify = options.blsVerify;\n if (!blsVerify) {\n blsVerify = bls.blsVerify;\n }\n return new Certificate(options.certificate, options.rootKey, options.canisterId, blsVerify, options.maxAgeInMinutes);\n }\n lookup(path) {\n // constrain the type of the result, so that empty HashTree is undefined\n return lookup_path(path, this.cert.tree);\n }\n lookup_label(label) {\n return this.lookup([label]);\n }\n async verify() {\n const rootHash = await reconstruct(this.cert.tree);\n const derKey = await this._checkDelegationAndGetKey(this.cert.delegation);\n const sig = this.cert.signature;\n const key = extractDER(derKey);\n const msg = concat(domain_sep('ic-state-root'), rootHash);\n let sigVer = false;\n const lookupTime = lookupResultToBuffer(this.lookup(['time']));\n if (!lookupTime) {\n // Should never happen - time is always present in IC certificates\n throw new CertificateVerificationError('Certificate does not contain a time');\n }\n const FIVE_MINUTES_IN_MSEC = 5 * 60 * 1000;\n const MAX_AGE_IN_MSEC = this._maxAgeInMinutes * 60 * 1000;\n const now = Date.now();\n const earliestCertificateTime = now - MAX_AGE_IN_MSEC;\n const fiveMinutesFromNow = now + FIVE_MINUTES_IN_MSEC;\n const certTime = decodeTime(lookupTime);\n if (certTime.getTime() < earliestCertificateTime) {\n throw new CertificateVerificationError(`Certificate is signed more than ${this._maxAgeInMinutes} minutes in the past. Certificate time: ` +\n certTime.toISOString() +\n ' Current time: ' +\n new Date(now).toISOString());\n }\n else if (certTime.getTime() > fiveMinutesFromNow) {\n throw new CertificateVerificationError('Certificate is signed more than 5 minutes in the future. Certificate time: ' +\n certTime.toISOString() +\n ' Current time: ' +\n new Date(now).toISOString());\n }\n try {\n sigVer = await this._blsVerify(new Uint8Array(key), new Uint8Array(sig), new Uint8Array(msg));\n }\n catch (err) {\n sigVer = false;\n }\n if (!sigVer) {\n throw new CertificateVerificationError('Signature verification failed');\n }\n }\n async _checkDelegationAndGetKey(d) {\n if (!d) {\n return this._rootKey;\n }\n const cert = await Certificate.createUnverified({\n certificate: d.certificate,\n rootKey: this._rootKey,\n canisterId: this._canisterId,\n blsVerify: this._blsVerify,\n // Do not check max age for delegation certificates\n maxAgeInMinutes: Infinity,\n });\n if (cert.cert.delegation) {\n throw new CertificateVerificationError('Delegation certificates cannot be nested');\n }\n await cert.verify();\n if (this._canisterId.toString() !== MANAGEMENT_CANISTER_ID) {\n const canisterInRange = check_canister_ranges({\n canisterId: this._canisterId,\n subnetId: Principal.fromUint8Array(new Uint8Array(d.subnet_id)),\n tree: cert.cert.tree,\n });\n if (!canisterInRange) {\n throw new CertificateVerificationError(`Canister ${this._canisterId} not in range of delegations for subnet 0x${toHex(d.subnet_id)}`);\n }\n }\n const publicKeyLookup = lookupResultToBuffer(cert.lookup(['subnet', d.subnet_id, 'public_key']));\n if (!publicKeyLookup) {\n throw new Error(`Could not find subnet key for subnet 0x${toHex(d.subnet_id)}`);\n }\n return publicKeyLookup;\n }\n}\nconst DER_PREFIX = fromHex('308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100');\nconst KEY_LENGTH = 96;\nfunction extractDER(buf) {\n const expectedLength = DER_PREFIX.byteLength + KEY_LENGTH;\n if (buf.byteLength !== expectedLength) {\n throw new TypeError(`BLS DER-encoded public key must be ${expectedLength} bytes long`);\n }\n const prefix = buf.slice(0, DER_PREFIX.byteLength);\n if (!bufEquals(prefix, DER_PREFIX)) {\n throw new TypeError(`BLS DER-encoded public key is invalid. Expect the following prefix: ${DER_PREFIX}, but get ${prefix}`);\n }\n return buf.slice(DER_PREFIX.byteLength);\n}\n/**\n * utility function to constrain the type of a path\n * @param {ArrayBuffer | HashTree | undefined} result - the result of a lookup\n * @returns ArrayBuffer or Undefined\n */\nexport function lookupResultToBuffer(result) {\n if (result.status !== LookupStatus.Found) {\n return undefined;\n }\n if (result.value instanceof ArrayBuffer) {\n return result.value;\n }\n if (result.value instanceof Uint8Array) {\n return result.value.buffer;\n }\n return undefined;\n}\n/**\n * @param t\n */\nexport async function reconstruct(t) {\n switch (t[0]) {\n case NodeType.Empty:\n return hash(domain_sep('ic-hashtree-empty'));\n case NodeType.Pruned:\n return t[1];\n case NodeType.Leaf:\n return hash(concat(domain_sep('ic-hashtree-leaf'), t[1]));\n case NodeType.Labeled:\n return hash(concat(domain_sep('ic-hashtree-labeled'), t[1], await reconstruct(t[2])));\n case NodeType.Fork:\n return hash(concat(domain_sep('ic-hashtree-fork'), await reconstruct(t[1]), await reconstruct(t[2])));\n default:\n throw new Error('unreachable');\n }\n}\nfunction domain_sep(s) {\n const len = new Uint8Array([s.length]);\n const str = new TextEncoder().encode(s);\n return concat(len, str);\n}\nexport var LookupStatus;\n(function (LookupStatus) {\n LookupStatus[\"Unknown\"] = \"unknown\";\n LookupStatus[\"Absent\"] = \"absent\";\n LookupStatus[\"Found\"] = \"found\";\n})(LookupStatus || (LookupStatus = {}));\nvar LabelLookupStatus;\n(function (LabelLookupStatus) {\n LabelLookupStatus[\"Less\"] = \"less\";\n LabelLookupStatus[\"Greater\"] = \"greater\";\n})(LabelLookupStatus || (LabelLookupStatus = {}));\nexport function lookup_path(path, tree) {\n if (path.length === 0) {\n switch (tree[0]) {\n case NodeType.Leaf: {\n if (!tree[1]) {\n throw new Error('Invalid tree structure for leaf');\n }\n if (tree[1] instanceof ArrayBuffer) {\n return {\n status: LookupStatus.Found,\n value: tree[1],\n };\n }\n if (tree[1] instanceof Uint8Array) {\n return {\n status: LookupStatus.Found,\n value: tree[1].buffer,\n };\n }\n return {\n status: LookupStatus.Found,\n value: tree[1],\n };\n }\n default: {\n return {\n status: LookupStatus.Found,\n value: tree,\n };\n }\n }\n }\n const label = typeof path[0] === 'string' ? new TextEncoder().encode(path[0]) : path[0];\n const lookupResult = find_label(label, tree);\n switch (lookupResult.status) {\n case LookupStatus.Found: {\n return lookup_path(path.slice(1), lookupResult.value);\n }\n case LabelLookupStatus.Greater:\n case LabelLookupStatus.Less: {\n return {\n status: LookupStatus.Absent,\n };\n }\n default: {\n return lookupResult;\n }\n }\n}\n/**\n * If the tree is a fork, flatten it into an array of trees\n * @param t - the tree to flatten\n * @returns HashTree[] - the flattened tree\n */\nexport function flatten_forks(t) {\n switch (t[0]) {\n case NodeType.Empty:\n return [];\n case NodeType.Fork:\n return flatten_forks(t[1]).concat(flatten_forks(t[2]));\n default:\n return [t];\n }\n}\nexport function find_label(label, tree) {\n switch (tree[0]) {\n // if we have a labelled node, compare the node's label to the one we are\n // looking for\n case NodeType.Labeled:\n // if the label we're searching for is greater than this node's label,\n // we need to keep searching\n if (isBufferGreaterThan(label, tree[1])) {\n return {\n status: LabelLookupStatus.Greater,\n };\n }\n // if the label we're searching for is equal this node's label, we can\n // stop searching and return the found node\n if (bufEquals(label, tree[1])) {\n return {\n status: LookupStatus.Found,\n value: tree[2],\n };\n }\n // if the label we're searching for is not greater than or equal to this\n // node's label, then it's less than this node's label, and we can stop\n // searching because we've looked too far\n return {\n status: LabelLookupStatus.Less,\n };\n // if we have a fork node, we need to search both sides, starting with the left\n case NodeType.Fork:\n // search in the left node\n const leftLookupResult = find_label(label, tree[1]);\n switch (leftLookupResult.status) {\n // if the label we're searching for is greater than the left node lookup,\n // we need to search the right node\n case LabelLookupStatus.Greater: {\n const rightLookupResult = find_label(label, tree[2]);\n // if the label we're searching for is less than the right node lookup,\n // then we can stop searching and say that the label is provably Absent\n if (rightLookupResult.status === LabelLookupStatus.Less) {\n return {\n status: LookupStatus.Absent,\n };\n }\n // if the label we're searching for is less than or equal to the right\n // node lookup, then we let the caller handle it\n return rightLookupResult;\n }\n // if the left node returns an uncertain result, we need to search the\n // right node\n case LookupStatus.Unknown: {\n let rightLookupResult = find_label(label, tree[2]);\n // if the label we're searching for is less than the right node lookup,\n // then we also need to return an uncertain result\n if (rightLookupResult.status === LabelLookupStatus.Less) {\n return {\n status: LookupStatus.Unknown,\n };\n }\n // if the label we're searching for is less than or equal to the right\n // node lookup, then we let the caller handle it\n return rightLookupResult;\n }\n // if the label we're searching for is not greater than the left node\n // lookup, or the result is not uncertain, we stop searching and return\n // whatever the result of the left node lookup was, which can be either\n // Found or Absent\n default: {\n return leftLookupResult;\n }\n }\n // if we encounter a Pruned node, we can't know for certain if the label\n // we're searching for is present or not\n case NodeType.Pruned:\n return {\n status: LookupStatus.Unknown,\n };\n // if the current node is Empty, or a Leaf, we can stop searching because\n // we know for sure that the label we're searching for is not present\n default:\n return {\n status: LookupStatus.Absent,\n };\n }\n}\n/**\n * Check if a canister falls within a range of canisters\n * @param canisterId Principal\n * @param ranges [Principal, Principal][]\n * @returns\n */\nexport function check_canister_ranges(params) {\n const { canisterId, subnetId, tree } = params;\n const rangeLookup = lookup_path(['subnet', subnetId.toUint8Array(), 'canister_ranges'], tree);\n if (rangeLookup.status !== LookupStatus.Found || !(rangeLookup.value instanceof ArrayBuffer)) {\n throw new Error(`Could not find canister ranges for subnet ${subnetId}`);\n }\n const ranges_arr = cbor.decode(rangeLookup.value);\n const ranges = ranges_arr.map(v => [\n Principal.fromUint8Array(v[0]),\n Principal.fromUint8Array(v[1]),\n ]);\n const canisterInRange = ranges.some(r => r[0].ltEq(canisterId) && r[1].gtEq(canisterId));\n return canisterInRange;\n}\n//# sourceMappingURL=certificate.js.map","/** @module CanisterStatus */\nimport { Principal } from '@dfinity/principal';\nimport { AgentError } from '../errors';\nimport { Certificate, flatten_forks, check_canister_ranges, LookupStatus, lookup_path, lookupResultToBuffer, } from '../certificate';\nimport { toHex } from '../utils/buffer';\nimport * as Cbor from '../cbor';\nimport { decodeLeb128, decodeTime } from '../utils/leb';\n/**\n * Interface to define a custom path. Nested paths will be represented as individual buffers, and can be created from text using TextEncoder.\n * @param {string} key the key to use to access the returned value in the canisterStatus map\n * @param {ArrayBuffer[]} path the path to the desired value, represented as an array of buffers\n * @param {string} decodeStrategy the strategy to use to decode the returned value\n */\nexport class CustomPath {\n constructor(key, path, decodeStrategy) {\n this.key = key;\n this.path = path;\n this.decodeStrategy = decodeStrategy;\n }\n}\n/**\n * Request information in the request_status state tree for a given canister.\n * Can be used to request information about the canister's controllers, time, module hash, candid interface, and more.\n * @param {CanisterStatusOptions} options {@link CanisterStatusOptions}\n * @param {CanisterStatusOptions['canisterId']} options.canisterId {@link Principal}\n * @param {CanisterStatusOptions['agent']} options.agent {@link HttpAgent} optional authenticated agent to use to make the canister request. Useful for accessing private metadata under icp:private\n * @param {CanisterStatusOptions['paths']} options.paths {@link Path[]}\n * @returns {Status} object populated with data from the requested paths\n * @example\n * const status = await canisterStatus({\n * paths: ['controllers', 'candid'],\n * ...options\n * });\n *\n * const controllers = status.get('controllers');\n */\nexport const request = async (options) => {\n const { agent, paths } = options;\n const canisterId = Principal.from(options.canisterId);\n const uniquePaths = [...new Set(paths)];\n // Map path options to their correct formats\n const encodedPaths = uniquePaths.map(path => {\n return encodePath(path, canisterId);\n });\n const status = new Map();\n const promises = uniquePaths.map((path, index) => {\n return (async () => {\n var _a;\n try {\n const response = await agent.readState(canisterId, {\n paths: [encodedPaths[index]],\n });\n const cert = await Certificate.create({\n certificate: response.certificate,\n rootKey: agent.rootKey,\n canisterId: canisterId,\n });\n const lookup = (cert, path) => {\n if (path === 'subnet') {\n const data = fetchNodeKeys(response.certificate, canisterId, agent.rootKey);\n return {\n path: path,\n data,\n };\n }\n else {\n return {\n path: path,\n data: lookupResultToBuffer(cert.lookup(encodePath(path, canisterId))),\n };\n }\n };\n // must pass in the rootKey if we have no delegation\n const { path, data } = lookup(cert, uniquePaths[index]);\n if (!data) {\n // Typically, the cert lookup will throw\n console.warn(`Expected to find result for path ${path}, but instead found nothing.`);\n if (typeof path === 'string') {\n status.set(path, null);\n }\n else {\n status.set(path.key, null);\n }\n }\n else {\n switch (path) {\n case 'time': {\n status.set(path, decodeTime(data));\n break;\n }\n case 'controllers': {\n status.set(path, decodeControllers(data));\n break;\n }\n case 'module_hash': {\n status.set(path, decodeHex(data));\n break;\n }\n case 'subnet': {\n status.set(path, data);\n break;\n }\n case 'candid': {\n status.set(path, new TextDecoder().decode(data));\n break;\n }\n default: {\n // Check for CustomPath signature\n if (typeof path !== 'string' && 'key' in path && 'path' in path) {\n switch (path.decodeStrategy) {\n case 'raw':\n status.set(path.key, data);\n break;\n case 'leb128': {\n status.set(path.key, decodeLeb128(data));\n break;\n }\n case 'cbor': {\n status.set(path.key, decodeCbor(data));\n break;\n }\n case 'hex': {\n status.set(path.key, decodeHex(data));\n break;\n }\n case 'utf-8': {\n status.set(path.key, decodeUtf8(data));\n }\n }\n }\n }\n }\n }\n }\n catch (error) {\n // Break on signature verification errors\n if ((_a = error === null || error === void 0 ? void 0 : error.message) === null || _a === void 0 ? void 0 : _a.includes('Invalid certificate')) {\n throw new AgentError(error.message);\n }\n if (typeof path !== 'string' && 'key' in path && 'path' in path) {\n status.set(path.key, null);\n }\n else {\n status.set(path, null);\n }\n console.group();\n console.warn(`Expected to find result for path ${path}, but instead found nothing.`);\n console.warn(error);\n console.groupEnd();\n }\n })();\n });\n // Fetch all values separately, as each option can fail\n await Promise.all(promises);\n return status;\n};\nexport const fetchNodeKeys = (certificate, canisterId, root_key) => {\n if (!canisterId._isPrincipal) {\n throw new Error('Invalid canisterId');\n }\n const cert = Cbor.decode(new Uint8Array(certificate));\n const tree = cert.tree;\n let delegation = cert.delegation;\n let subnetId;\n if (delegation && delegation.subnet_id) {\n subnetId = Principal.fromUint8Array(new Uint8Array(delegation.subnet_id));\n }\n // On local replica, with System type subnet, there is no delegation\n else if (!delegation && typeof root_key !== 'undefined') {\n subnetId = Principal.selfAuthenticating(new Uint8Array(root_key));\n delegation = {\n subnet_id: subnetId.toUint8Array(),\n certificate: new ArrayBuffer(0),\n };\n }\n // otherwise use default NNS subnet id\n else {\n subnetId = Principal.selfAuthenticating(Principal.fromText('tdb26-jop6k-aogll-7ltgs-eruif-6kk7m-qpktf-gdiqx-mxtrf-vb5e6-eqe').toUint8Array());\n delegation = {\n subnet_id: subnetId.toUint8Array(),\n certificate: new ArrayBuffer(0),\n };\n }\n const canisterInRange = check_canister_ranges({ canisterId, subnetId, tree });\n if (!canisterInRange) {\n throw new Error('Canister not in range');\n }\n const subnetLookupResult = lookup_path(['subnet', delegation.subnet_id, 'node'], tree);\n if (subnetLookupResult.status !== LookupStatus.Found) {\n throw new Error('Node not found');\n }\n if (subnetLookupResult.value instanceof ArrayBuffer) {\n throw new Error('Invalid node tree');\n }\n const nodeForks = flatten_forks(subnetLookupResult.value);\n const nodeKeys = new Map();\n nodeForks.forEach(fork => {\n const node_id = Principal.from(new Uint8Array(fork[1])).toText();\n const publicKeyLookupResult = lookup_path(['public_key'], fork[2]);\n if (publicKeyLookupResult.status !== LookupStatus.Found) {\n throw new Error('Public key not found');\n }\n const derEncodedPublicKey = publicKeyLookupResult.value;\n if (derEncodedPublicKey.byteLength !== 44) {\n throw new Error('Invalid public key length');\n }\n else {\n nodeKeys.set(node_id, derEncodedPublicKey);\n }\n });\n return {\n subnetId: Principal.fromUint8Array(new Uint8Array(delegation.subnet_id)).toText(),\n nodeKeys,\n };\n};\nexport const encodePath = (path, canisterId) => {\n const encoder = new TextEncoder();\n const encode = (arg) => {\n return new DataView(encoder.encode(arg).buffer).buffer;\n };\n const canisterBuffer = new DataView(canisterId.toUint8Array().buffer).buffer;\n switch (path) {\n case 'time':\n return [encode('time')];\n case 'controllers':\n return [encode('canister'), canisterBuffer, encode('controllers')];\n case 'module_hash':\n return [encode('canister'), canisterBuffer, encode('module_hash')];\n case 'subnet':\n return [encode('subnet')];\n case 'candid':\n return [encode('canister'), canisterBuffer, encode('metadata'), encode('candid:service')];\n default: {\n // Check for CustomPath signature\n if ('key' in path && 'path' in path) {\n // For simplified metadata queries\n if (typeof path['path'] === 'string' || path['path'] instanceof ArrayBuffer) {\n const metaPath = path.path;\n const encoded = typeof metaPath === 'string' ? encode(metaPath) : metaPath;\n return [encode('canister'), canisterBuffer, encode('metadata'), encoded];\n // For non-metadata, return the provided custompath\n }\n else {\n return path['path'];\n }\n }\n }\n }\n throw new Error(`An unexpeected error was encountered while encoding your path for canister status. Please ensure that your path, ${path} was formatted correctly.`);\n};\nconst decodeHex = (buf) => {\n return toHex(buf);\n};\nconst decodeCbor = (buf) => {\n return Cbor.decode(buf);\n};\nconst decodeUtf8 = (buf) => {\n return new TextDecoder().decode(buf);\n};\n// Controllers are CBOR-encoded buffers\nconst decodeControllers = (buf) => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const controllersRaw = decodeCbor(buf);\n return controllersRaw.map((buf) => {\n return Principal.fromUint8Array(new Uint8Array(buf));\n });\n};\n//# sourceMappingURL=index.js.map","var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _ExpirableMap_inner, _ExpirableMap_expirationTime, _a, _b;\n/**\n * A map that expires entries after a given time.\n * Defaults to 10 minutes.\n */\nexport class ExpirableMap {\n /**\n * Create a new ExpirableMap.\n * @param {ExpirableMapOptions} options - options for the map.\n * @param {Iterable<[any, any]>} options.source - an optional source of entries to initialize the map with.\n * @param {number} options.expirationTime - the time in milliseconds after which entries will expire.\n */\n constructor(options = {}) {\n // Internals\n _ExpirableMap_inner.set(this, void 0);\n _ExpirableMap_expirationTime.set(this, void 0);\n this[_a] = this.entries.bind(this);\n this[_b] = 'ExpirableMap';\n const { source = [], expirationTime = 10 * 60 * 1000 } = options;\n const currentTime = Date.now();\n __classPrivateFieldSet(this, _ExpirableMap_inner, new Map([...source].map(([key, value]) => [key, { value, timestamp: currentTime }])), \"f\");\n __classPrivateFieldSet(this, _ExpirableMap_expirationTime, expirationTime, \"f\");\n }\n /**\n * Prune removes all expired entries.\n */\n prune() {\n const currentTime = Date.now();\n for (const [key, entry] of __classPrivateFieldGet(this, _ExpirableMap_inner, \"f\").entries()) {\n if (currentTime - entry.timestamp > __classPrivateFieldGet(this, _ExpirableMap_expirationTime, \"f\")) {\n __classPrivateFieldGet(this, _ExpirableMap_inner, \"f\").delete(key);\n }\n }\n return this;\n }\n // Implementing the Map interface\n /**\n * Set the value for the given key. Prunes expired entries.\n * @param key for the entry\n * @param value of the entry\n * @returns this\n */\n set(key, value) {\n this.prune();\n const entry = {\n value,\n timestamp: Date.now(),\n };\n __classPrivateFieldGet(this, _ExpirableMap_inner, \"f\").set(key, entry);\n return this;\n }\n /**\n * Get the value associated with the key, if it exists and has not expired.\n * @param key K\n * @returns the value associated with the key, or undefined if the key is not present or has expired.\n */\n get(key) {\n const entry = __classPrivateFieldGet(this, _ExpirableMap_inner, \"f\").get(key);\n if (entry === undefined) {\n return undefined;\n }\n if (Date.now() - entry.timestamp > __classPrivateFieldGet(this, _ExpirableMap_expirationTime, \"f\")) {\n __classPrivateFieldGet(this, _ExpirableMap_inner, \"f\").delete(key);\n return undefined;\n }\n return entry.value;\n }\n /**\n * Clear all entries.\n */\n clear() {\n __classPrivateFieldGet(this, _ExpirableMap_inner, \"f\").clear();\n }\n /**\n * Entries returns the entries of the map, without the expiration time.\n * @returns an iterator over the entries of the map.\n */\n entries() {\n const iterator = __classPrivateFieldGet(this, _ExpirableMap_inner, \"f\").entries();\n const generator = function* () {\n for (const [key, value] of iterator) {\n yield [key, value.value];\n }\n };\n return generator();\n }\n /**\n * Values returns the values of the map, without the expiration time.\n * @returns an iterator over the values of the map.\n */\n values() {\n const iterator = __classPrivateFieldGet(this, _ExpirableMap_inner, \"f\").values();\n const generator = function* () {\n for (const value of iterator) {\n yield value.value;\n }\n };\n return generator();\n }\n /**\n * Keys returns the keys of the map\n * @returns an iterator over the keys of the map.\n */\n keys() {\n return __classPrivateFieldGet(this, _ExpirableMap_inner, \"f\").keys();\n }\n /**\n * forEach calls the callbackfn on each entry of the map.\n * @param callbackfn to call on each entry\n * @param thisArg to use as this when calling the callbackfn\n */\n forEach(callbackfn, thisArg) {\n for (const [key, value] of __classPrivateFieldGet(this, _ExpirableMap_inner, \"f\").entries()) {\n callbackfn.call(thisArg, value.value, key, this);\n }\n }\n /**\n * has returns true if the key exists and has not expired.\n * @param key K\n * @returns true if the key exists and has not expired.\n */\n has(key) {\n return __classPrivateFieldGet(this, _ExpirableMap_inner, \"f\").has(key);\n }\n /**\n * delete the entry for the given key.\n * @param key K\n * @returns true if the key existed and has been deleted.\n */\n delete(key) {\n return __classPrivateFieldGet(this, _ExpirableMap_inner, \"f\").delete(key);\n }\n /**\n * get size of the map.\n * @returns the size of the map.\n */\n get size() {\n return __classPrivateFieldGet(this, _ExpirableMap_inner, \"f\").size;\n }\n}\n_ExpirableMap_inner = new WeakMap(), _ExpirableMap_expirationTime = new WeakMap(), _a = Symbol.iterator, _b = Symbol.toStringTag;\n//# sourceMappingURL=expirableMap.js.map","import { bufEquals } from './utils/buffer';\nexport const encodeLenBytes = (len) => {\n if (len <= 0x7f) {\n return 1;\n }\n else if (len <= 0xff) {\n return 2;\n }\n else if (len <= 0xffff) {\n return 3;\n }\n else if (len <= 0xffffff) {\n return 4;\n }\n else {\n throw new Error('Length too long (> 4 bytes)');\n }\n};\nexport const encodeLen = (buf, offset, len) => {\n if (len <= 0x7f) {\n buf[offset] = len;\n return 1;\n }\n else if (len <= 0xff) {\n buf[offset] = 0x81;\n buf[offset + 1] = len;\n return 2;\n }\n else if (len <= 0xffff) {\n buf[offset] = 0x82;\n buf[offset + 1] = len >> 8;\n buf[offset + 2] = len;\n return 3;\n }\n else if (len <= 0xffffff) {\n buf[offset] = 0x83;\n buf[offset + 1] = len >> 16;\n buf[offset + 2] = len >> 8;\n buf[offset + 3] = len;\n return 4;\n }\n else {\n throw new Error('Length too long (> 4 bytes)');\n }\n};\nexport const decodeLenBytes = (buf, offset) => {\n if (buf[offset] < 0x80)\n return 1;\n if (buf[offset] === 0x80)\n throw new Error('Invalid length 0');\n if (buf[offset] === 0x81)\n return 2;\n if (buf[offset] === 0x82)\n return 3;\n if (buf[offset] === 0x83)\n return 4;\n throw new Error('Length too long (> 4 bytes)');\n};\nexport const decodeLen = (buf, offset) => {\n const lenBytes = decodeLenBytes(buf, offset);\n if (lenBytes === 1)\n return buf[offset];\n else if (lenBytes === 2)\n return buf[offset + 1];\n else if (lenBytes === 3)\n return (buf[offset + 1] << 8) + buf[offset + 2];\n else if (lenBytes === 4)\n return (buf[offset + 1] << 16) + (buf[offset + 2] << 8) + buf[offset + 3];\n throw new Error('Length too long (> 4 bytes)');\n};\n/**\n * A DER encoded `SEQUENCE(OID)` for DER-encoded-COSE\n */\nexport const DER_COSE_OID = Uint8Array.from([\n ...[0x30, 0x0c],\n ...[0x06, 0x0a],\n ...[0x2b, 0x06, 0x01, 0x04, 0x01, 0x83, 0xb8, 0x43, 0x01, 0x01], // DER encoded COSE\n]);\n/**\n * A DER encoded `SEQUENCE(OID)` for the Ed25519 algorithm\n */\nexport const ED25519_OID = Uint8Array.from([\n ...[0x30, 0x05],\n ...[0x06, 0x03],\n ...[0x2b, 0x65, 0x70], // id-Ed25519 OID\n]);\n/**\n * A DER encoded `SEQUENCE(OID)` for secp256k1 with the ECDSA algorithm\n */\nexport const SECP256K1_OID = Uint8Array.from([\n ...[0x30, 0x10],\n ...[0x06, 0x07],\n ...[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01],\n ...[0x06, 0x05],\n ...[0x2b, 0x81, 0x04, 0x00, 0x0a], // OID secp256k1\n]);\n/**\n * Wraps the given `payload` in a DER encoding tagged with the given encoded `oid` like so:\n * `SEQUENCE(oid, BITSTRING(payload))`\n *\n * @param payload The payload to encode as the bit string\n * @param oid The DER encoded (and SEQUENCE wrapped!) OID to tag the payload with\n */\nexport function wrapDER(payload, oid) {\n // The Bit String header needs to include the unused bit count byte in its length\n const bitStringHeaderLength = 2 + encodeLenBytes(payload.byteLength + 1);\n const len = oid.byteLength + bitStringHeaderLength + payload.byteLength;\n let offset = 0;\n const buf = new Uint8Array(1 + encodeLenBytes(len) + len);\n // Sequence\n buf[offset++] = 0x30;\n // Sequence Length\n offset += encodeLen(buf, offset, len);\n // OID\n buf.set(oid, offset);\n offset += oid.byteLength;\n // Bit String Header\n buf[offset++] = 0x03;\n offset += encodeLen(buf, offset, payload.byteLength + 1);\n // 0 padding\n buf[offset++] = 0x00;\n buf.set(new Uint8Array(payload), offset);\n return buf;\n}\n/**\n * Extracts a payload from the given `derEncoded` data, and checks that it was tagged with the given `oid`.\n *\n * `derEncoded = SEQUENCE(oid, BITSTRING(payload))`\n *\n * @param derEncoded The DER encoded and tagged data\n * @param oid The DER encoded (and SEQUENCE wrapped!) expected OID\n * @returns The unwrapped payload\n */\nexport const unwrapDER = (derEncoded, oid) => {\n let offset = 0;\n const expect = (n, msg) => {\n if (buf[offset++] !== n) {\n throw new Error('Expected: ' + msg);\n }\n };\n const buf = new Uint8Array(derEncoded);\n expect(0x30, 'sequence');\n offset += decodeLenBytes(buf, offset);\n if (!bufEquals(buf.slice(offset, offset + oid.byteLength), oid)) {\n throw new Error('Not the expected OID.');\n }\n offset += oid.byteLength;\n expect(0x03, 'bit string');\n const payloadLen = decodeLen(buf, offset) - 1; // Subtracting 1 to account for the 0 padding\n offset += decodeLenBytes(buf, offset);\n expect(0x00, '0 padding');\n const result = buf.slice(offset);\n if (payloadLen !== result.length) {\n throw new Error(`DER payload mismatch: Expected length ${payloadLen} actual length ${result.length}`);\n }\n return result;\n};\n//# sourceMappingURL=der.js.map","var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _Ed25519PublicKey_rawKey, _Ed25519PublicKey_derKey;\nimport { ED25519_OID, unwrapDER, wrapDER } from './der';\nexport class Ed25519PublicKey {\n // `fromRaw` and `fromDer` should be used for instantiation, not this constructor.\n constructor(key) {\n _Ed25519PublicKey_rawKey.set(this, void 0);\n _Ed25519PublicKey_derKey.set(this, void 0);\n if (key.byteLength !== Ed25519PublicKey.RAW_KEY_LENGTH) {\n throw new Error('An Ed25519 public key must be exactly 32bytes long');\n }\n __classPrivateFieldSet(this, _Ed25519PublicKey_rawKey, key, \"f\");\n __classPrivateFieldSet(this, _Ed25519PublicKey_derKey, Ed25519PublicKey.derEncode(key), \"f\");\n }\n static from(key) {\n return this.fromDer(key.toDer());\n }\n static fromRaw(rawKey) {\n return new Ed25519PublicKey(rawKey);\n }\n static fromDer(derKey) {\n return new Ed25519PublicKey(this.derDecode(derKey));\n }\n static derEncode(publicKey) {\n return wrapDER(publicKey, ED25519_OID).buffer;\n }\n static derDecode(key) {\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 get rawKey() {\n return __classPrivateFieldGet(this, _Ed25519PublicKey_rawKey, \"f\");\n }\n get derKey() {\n return __classPrivateFieldGet(this, _Ed25519PublicKey_derKey, \"f\");\n }\n toDer() {\n return this.derKey;\n }\n toRaw() {\n return this.rawKey;\n }\n}\n_Ed25519PublicKey_rawKey = new WeakMap(), _Ed25519PublicKey_derKey = new WeakMap();\n// The length of Ed25519 public keys is always 32 bytes.\nEd25519PublicKey.RAW_KEY_LENGTH = 32;\n//# sourceMappingURL=public_key.js.map","export class Observable {\n constructor() {\n this.observers = [];\n }\n subscribe(func) {\n this.observers.push(func);\n }\n unsubscribe(func) {\n this.observers = this.observers.filter(observer => observer !== func);\n }\n notify(data, ...rest) {\n this.observers.forEach(observer => observer(data, ...rest));\n }\n}\nexport class ObservableLog extends Observable {\n constructor() {\n super();\n }\n print(message, ...rest) {\n this.notify({ message, level: 'info' }, ...rest);\n }\n warn(message, ...rest) {\n this.notify({ message, level: 'warn' }, ...rest);\n }\n error(message, error, ...rest) {\n this.notify({ message, level: 'error', error }, ...rest);\n }\n}\n//# sourceMappingURL=observable.js.map","var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _ExponentialBackoff_currentInterval, _ExponentialBackoff_randomizationFactor, _ExponentialBackoff_multiplier, _ExponentialBackoff_maxInterval, _ExponentialBackoff_startTime, _ExponentialBackoff_maxElapsedTime, _ExponentialBackoff_maxIterations, _ExponentialBackoff_date, _ExponentialBackoff_count;\nconst RANDOMIZATION_FACTOR = 0.5;\nconst MULTIPLIER = 1.5;\nconst INITIAL_INTERVAL_MSEC = 500;\nconst MAX_INTERVAL_MSEC = 60000;\nconst MAX_ELAPSED_TIME_MSEC = 900000;\nconst MAX_ITERATIONS = 10;\n/**\n * Exponential backoff strategy.\n */\nexport class ExponentialBackoff {\n constructor(options = ExponentialBackoff.default) {\n _ExponentialBackoff_currentInterval.set(this, void 0);\n _ExponentialBackoff_randomizationFactor.set(this, void 0);\n _ExponentialBackoff_multiplier.set(this, void 0);\n _ExponentialBackoff_maxInterval.set(this, void 0);\n _ExponentialBackoff_startTime.set(this, void 0);\n _ExponentialBackoff_maxElapsedTime.set(this, void 0);\n _ExponentialBackoff_maxIterations.set(this, void 0);\n _ExponentialBackoff_date.set(this, void 0);\n _ExponentialBackoff_count.set(this, 0);\n const { initialInterval = INITIAL_INTERVAL_MSEC, randomizationFactor = RANDOMIZATION_FACTOR, multiplier = MULTIPLIER, maxInterval = MAX_INTERVAL_MSEC, maxElapsedTime = MAX_ELAPSED_TIME_MSEC, maxIterations = MAX_ITERATIONS, date = Date, } = options;\n __classPrivateFieldSet(this, _ExponentialBackoff_currentInterval, initialInterval, \"f\");\n __classPrivateFieldSet(this, _ExponentialBackoff_randomizationFactor, randomizationFactor, \"f\");\n __classPrivateFieldSet(this, _ExponentialBackoff_multiplier, multiplier, \"f\");\n __classPrivateFieldSet(this, _ExponentialBackoff_maxInterval, maxInterval, \"f\");\n __classPrivateFieldSet(this, _ExponentialBackoff_date, date, \"f\");\n __classPrivateFieldSet(this, _ExponentialBackoff_startTime, date.now(), \"f\");\n __classPrivateFieldSet(this, _ExponentialBackoff_maxElapsedTime, maxElapsedTime, \"f\");\n __classPrivateFieldSet(this, _ExponentialBackoff_maxIterations, maxIterations, \"f\");\n }\n get ellapsedTimeInMsec() {\n return __classPrivateFieldGet(this, _ExponentialBackoff_date, \"f\").now() - __classPrivateFieldGet(this, _ExponentialBackoff_startTime, \"f\");\n }\n get currentInterval() {\n return __classPrivateFieldGet(this, _ExponentialBackoff_currentInterval, \"f\");\n }\n get count() {\n return __classPrivateFieldGet(this, _ExponentialBackoff_count, \"f\");\n }\n get randomValueFromInterval() {\n const delta = __classPrivateFieldGet(this, _ExponentialBackoff_randomizationFactor, \"f\") * __classPrivateFieldGet(this, _ExponentialBackoff_currentInterval, \"f\");\n const min = __classPrivateFieldGet(this, _ExponentialBackoff_currentInterval, \"f\") - delta;\n const max = __classPrivateFieldGet(this, _ExponentialBackoff_currentInterval, \"f\") + delta;\n return Math.random() * (max - min) + min;\n }\n incrementCurrentInterval() {\n var _a;\n __classPrivateFieldSet(this, _ExponentialBackoff_currentInterval, Math.min(__classPrivateFieldGet(this, _ExponentialBackoff_currentInterval, \"f\") * __classPrivateFieldGet(this, _ExponentialBackoff_multiplier, \"f\"), __classPrivateFieldGet(this, _ExponentialBackoff_maxInterval, \"f\")), \"f\");\n __classPrivateFieldSet(this, _ExponentialBackoff_count, (_a = __classPrivateFieldGet(this, _ExponentialBackoff_count, \"f\"), _a++, _a), \"f\");\n return __classPrivateFieldGet(this, _ExponentialBackoff_currentInterval, \"f\");\n }\n next() {\n if (this.ellapsedTimeInMsec >= __classPrivateFieldGet(this, _ExponentialBackoff_maxElapsedTime, \"f\") || __classPrivateFieldGet(this, _ExponentialBackoff_count, \"f\") >= __classPrivateFieldGet(this, _ExponentialBackoff_maxIterations, \"f\")) {\n return null;\n }\n else {\n this.incrementCurrentInterval();\n return this.randomValueFromInterval;\n }\n }\n}\n_ExponentialBackoff_currentInterval = new WeakMap(), _ExponentialBackoff_randomizationFactor = new WeakMap(), _ExponentialBackoff_multiplier = new WeakMap(), _ExponentialBackoff_maxInterval = new WeakMap(), _ExponentialBackoff_startTime = new WeakMap(), _ExponentialBackoff_maxElapsedTime = new WeakMap(), _ExponentialBackoff_maxIterations = new WeakMap(), _ExponentialBackoff_date = new WeakMap(), _ExponentialBackoff_count = new WeakMap();\nExponentialBackoff.default = {\n initialInterval: INITIAL_INTERVAL_MSEC,\n randomizationFactor: RANDOMIZATION_FACTOR,\n multiplier: MULTIPLIER,\n maxInterval: MAX_INTERVAL_MSEC,\n // 1 minute\n maxElapsedTime: MAX_ELAPSED_TIME_MSEC,\n maxIterations: MAX_ITERATIONS,\n date: Date,\n};\n/**\n * Utility function to create an exponential backoff iterator.\n * @param options - for the exponential backoff\n * @returns an iterator that yields the next delay in the exponential backoff\n * @yields the next delay in the exponential backoff\n */\nexport function* exponentialBackoff(options = ExponentialBackoff.default) {\n const backoff = new ExponentialBackoff(options);\n let next = backoff.next();\n while (next) {\n yield next;\n next = backoff.next();\n }\n}\n//# sourceMappingURL=backoff.js.map","// Default delta for ingress expiry is 5 minutes.\nexport const DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS = 5 * 60 * 1000;\n//# sourceMappingURL=constants.js.map","var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _HttpAgent_instances, _HttpAgent_identity, _HttpAgent_fetch, _HttpAgent_fetchOptions, _HttpAgent_callOptions, _HttpAgent_timeDiffMsecs, _HttpAgent_credentials, _HttpAgent_rootKeyFetched, _HttpAgent_retryTimes, _HttpAgent_backoffStrategy, _HttpAgent_maxIngressExpiryInMinutes, _HttpAgent_waterMark, _HttpAgent_queryPipeline, _HttpAgent_updatePipeline, _HttpAgent_subnetKeys, _HttpAgent_verifyQuerySignatures, _HttpAgent_requestAndRetryQuery, _HttpAgent_requestAndRetry, _HttpAgent_verifyQueryResponse;\nimport { Principal } from '@dfinity/principal';\nimport { AgentError } from '../../errors';\nimport { AnonymousIdentity } from '../../auth';\nimport * as cbor from '../../cbor';\nimport { hashOfMap, requestIdOf } from '../../request_id';\nimport { bufFromBufLike, concat, fromHex } from '../../utils/buffer';\nimport { Expiry, httpHeadersTransform, makeNonceTransform } from './transforms';\nimport { makeNonce, SubmitRequestType, } from './types';\nimport { AgentHTTPResponseError } from './errors';\nimport { request } from '../../canisterStatus';\nimport { CertificateVerificationError, LookupStatus, lookup_path, } from '../../certificate';\nimport { ed25519 } from '@noble/curves/ed25519';\nimport { ExpirableMap } from '../../utils/expirableMap';\nimport { Ed25519PublicKey } from '../../public_key';\nimport { decodeTime } from '../../utils/leb';\nimport { ObservableLog } from '../../observable';\nimport { ExponentialBackoff } from '../../polling/backoff';\nimport { DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS } from '../../constants';\nexport * from './transforms';\nexport { makeNonce } from './types';\nexport var RequestStatusResponseStatus;\n(function (RequestStatusResponseStatus) {\n RequestStatusResponseStatus[\"Received\"] = \"received\";\n RequestStatusResponseStatus[\"Processing\"] = \"processing\";\n RequestStatusResponseStatus[\"Replied\"] = \"replied\";\n RequestStatusResponseStatus[\"Rejected\"] = \"rejected\";\n RequestStatusResponseStatus[\"Unknown\"] = \"unknown\";\n RequestStatusResponseStatus[\"Done\"] = \"done\";\n})(RequestStatusResponseStatus || (RequestStatusResponseStatus = {}));\nconst MINUTE_TO_MSECS = 60 * 1000;\n// Root public key for the IC, encoded as hex\nexport const IC_ROOT_KEY = '308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814' +\n 'c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d968' +\n '5f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484' +\n 'b01291091c5f87b98883463f98091a0baaae';\nexport const MANAGEMENT_CANISTER_ID = 'aaaaa-aa';\n// IC0 domain info\nconst IC0_DOMAIN = 'ic0.app';\nconst IC0_SUB_DOMAIN = '.ic0.app';\nconst ICP0_DOMAIN = 'icp0.io';\nconst ICP0_SUB_DOMAIN = '.icp0.io';\nconst ICP_API_DOMAIN = 'icp-api.io';\nconst ICP_API_SUB_DOMAIN = '.icp-api.io';\nclass HttpDefaultFetchError extends AgentError {\n constructor(message) {\n super(message);\n this.message = message;\n }\n}\nexport class IdentityInvalidError extends AgentError {\n constructor(message) {\n super(message);\n this.message = message;\n }\n}\nfunction getDefaultFetch() {\n let defaultFetch;\n if (typeof window !== 'undefined') {\n // Browser context\n if (window.fetch) {\n defaultFetch = window.fetch.bind(window);\n }\n else {\n throw new HttpDefaultFetchError('Fetch implementation was not available. You appear to be in a browser context, but window.fetch was not present.');\n }\n }\n else if (typeof global !== 'undefined') {\n // Node context\n if (global.fetch) {\n defaultFetch = global.fetch.bind(global);\n }\n else {\n throw new HttpDefaultFetchError('Fetch implementation was not available. You appear to be in a Node.js context, but global.fetch was not available.');\n }\n }\n else if (typeof self !== 'undefined') {\n if (self.fetch) {\n defaultFetch = self.fetch.bind(self);\n }\n }\n if (defaultFetch) {\n return defaultFetch;\n }\n throw new HttpDefaultFetchError('Fetch implementation was not available. Please provide fetch to the HttpAgent constructor, or ensure it is available in the window or global context.');\n}\nfunction determineHost(configuredHost) {\n let host;\n if (configuredHost !== undefined) {\n if (!configuredHost.match(/^[a-z]+:/) && typeof window !== 'undefined') {\n host = new URL(window.location.protocol + '//' + configuredHost);\n }\n else {\n host = new URL(configuredHost);\n }\n }\n else {\n // Mainnet, local, and remote environments will have the api route available\n const knownHosts = ['ic0.app', 'icp0.io', '127.0.0.1', 'localhost'];\n const remoteHosts = ['.github.dev', '.gitpod.io'];\n const location = typeof window !== 'undefined' ? window.location : undefined;\n const hostname = location === null || location === void 0 ? void 0 : location.hostname;\n let knownHost;\n if (hostname && typeof hostname === 'string') {\n if (remoteHosts.some(host => hostname.endsWith(host))) {\n knownHost = hostname;\n }\n else {\n knownHost = knownHosts.find(host => hostname.endsWith(host));\n }\n }\n if (location && knownHost) {\n // If the user is on a boundary-node provided host, we can use the same host for the agent\n host = new URL(`${location.protocol}//${knownHost}${location.port ? ':' + location.port : ''}`);\n }\n else {\n host = new URL('https://icp-api.io');\n }\n }\n return host.toString();\n}\n/**\n * A HTTP agent allows users to interact with a client of the internet computer\nusing the available methods. It exposes an API that closely follows the\npublic view of the internet computer, and is not intended to be exposed\ndirectly to the majority of users due to its low-level interface.\n * There is a pipeline to apply transformations to the request before sending\nit to the client. This is to decouple signature, nonce generation and\nother computations so that this class can stay as simple as possible while\nallowing extensions.\n */\nexport class HttpAgent {\n /**\n * @param options - Options for the HttpAgent\n * @deprecated Use `HttpAgent.create` or `HttpAgent.createSync` instead\n */\n constructor(options = {}) {\n var _a;\n _HttpAgent_instances.add(this);\n _HttpAgent_identity.set(this, void 0);\n _HttpAgent_fetch.set(this, void 0);\n _HttpAgent_fetchOptions.set(this, void 0);\n _HttpAgent_callOptions.set(this, void 0);\n _HttpAgent_timeDiffMsecs.set(this, 0);\n _HttpAgent_credentials.set(this, void 0);\n _HttpAgent_rootKeyFetched.set(this, false);\n _HttpAgent_retryTimes.set(this, void 0); // Retry requests N times before erroring by default\n _HttpAgent_backoffStrategy.set(this, void 0);\n _HttpAgent_maxIngressExpiryInMinutes.set(this, void 0);\n // Public signature to help with type checking.\n this._isAgent = true;\n this.config = {};\n // The UTC time in milliseconds when the latest request was made\n _HttpAgent_waterMark.set(this, 0);\n this.log = new ObservableLog();\n _HttpAgent_queryPipeline.set(this, []);\n _HttpAgent_updatePipeline.set(this, []);\n _HttpAgent_subnetKeys.set(this, new ExpirableMap({\n expirationTime: 5 * 60 * 1000, // 5 minutes\n }));\n _HttpAgent_verifyQuerySignatures.set(this, true);\n /**\n * See https://internetcomputer.org/docs/current/references/ic-interface-spec/#http-query for details on validation\n * @param queryResponse - The response from the query\n * @param subnetStatus - The subnet status, including all node keys\n * @returns ApiQueryResponse\n */\n _HttpAgent_verifyQueryResponse.set(this, (queryResponse, subnetStatus) => {\n if (__classPrivateFieldGet(this, _HttpAgent_verifyQuerySignatures, \"f\") === false) {\n // This should not be called if the user has disabled verification\n return queryResponse;\n }\n if (!subnetStatus) {\n throw new CertificateVerificationError('Invalid signature from replica signed query: no matching node key found.');\n }\n const { status, signatures = [], requestId } = queryResponse;\n const domainSeparator = new TextEncoder().encode('\\x0Bic-response');\n for (const sig of signatures) {\n const { timestamp, identity } = sig;\n const nodeId = Principal.fromUint8Array(identity).toText();\n let hash;\n // Hash is constructed differently depending on the status\n if (status === 'replied') {\n const { reply } = queryResponse;\n hash = hashOfMap({\n status: status,\n reply: reply,\n timestamp: BigInt(timestamp),\n request_id: requestId,\n });\n }\n else if (status === 'rejected') {\n const { reject_code, reject_message, error_code } = queryResponse;\n hash = hashOfMap({\n status: status,\n reject_code: reject_code,\n reject_message: reject_message,\n error_code: error_code,\n timestamp: BigInt(timestamp),\n request_id: requestId,\n });\n }\n else {\n throw new Error(`Unknown status: ${status}`);\n }\n const separatorWithHash = concat(domainSeparator, new Uint8Array(hash));\n // FIX: check for match without verifying N times\n const pubKey = subnetStatus === null || subnetStatus === void 0 ? void 0 : subnetStatus.nodeKeys.get(nodeId);\n if (!pubKey) {\n throw new CertificateVerificationError('Invalid signature from replica signed query: no matching node key found.');\n }\n const rawKey = Ed25519PublicKey.fromDer(pubKey).rawKey;\n const valid = ed25519.verify(sig.signature, new Uint8Array(separatorWithHash), new Uint8Array(rawKey));\n if (valid)\n return queryResponse;\n throw new CertificateVerificationError(`Invalid signature from replica ${nodeId} signed query.`);\n }\n return queryResponse;\n });\n this.config = options;\n __classPrivateFieldSet(this, _HttpAgent_fetch, options.fetch || getDefaultFetch() || fetch.bind(global), \"f\");\n __classPrivateFieldSet(this, _HttpAgent_fetchOptions, options.fetchOptions, \"f\");\n __classPrivateFieldSet(this, _HttpAgent_callOptions, options.callOptions, \"f\");\n this.rootKey = options.rootKey ? options.rootKey : fromHex(IC_ROOT_KEY);\n const host = determineHost(options.host);\n this.host = new URL(host);\n if (options.verifyQuerySignatures !== undefined) {\n __classPrivateFieldSet(this, _HttpAgent_verifyQuerySignatures, options.verifyQuerySignatures, \"f\");\n }\n // Default is 3\n __classPrivateFieldSet(this, _HttpAgent_retryTimes, (_a = options.retryTimes) !== null && _a !== void 0 ? _a : 3, \"f\");\n // Delay strategy for retries. Default is exponential backoff\n const defaultBackoffFactory = () => new ExponentialBackoff({\n maxIterations: __classPrivateFieldGet(this, _HttpAgent_retryTimes, \"f\"),\n });\n __classPrivateFieldSet(this, _HttpAgent_backoffStrategy, options.backoffStrategy || defaultBackoffFactory, \"f\");\n // Rewrite to avoid redirects\n if (this.host.hostname.endsWith(IC0_SUB_DOMAIN)) {\n this.host.hostname = IC0_DOMAIN;\n }\n else if (this.host.hostname.endsWith(ICP0_SUB_DOMAIN)) {\n this.host.hostname = ICP0_DOMAIN;\n }\n else if (this.host.hostname.endsWith(ICP_API_SUB_DOMAIN)) {\n this.host.hostname = ICP_API_DOMAIN;\n }\n if (options.credentials) {\n const { name, password } = options.credentials;\n __classPrivateFieldSet(this, _HttpAgent_credentials, `${name}${password ? ':' + password : ''}`, \"f\");\n }\n __classPrivateFieldSet(this, _HttpAgent_identity, Promise.resolve(options.identity || new AnonymousIdentity()), \"f\");\n if (options.ingressExpiryInMinutes && options.ingressExpiryInMinutes > 5) {\n throw new AgentError(`The maximum ingress expiry time is 5 minutes. Provided ingress expiry time is ${options.ingressExpiryInMinutes} minutes.`);\n }\n if (options.ingressExpiryInMinutes && options.ingressExpiryInMinutes <= 0) {\n throw new AgentError(`Ingress expiry time must be greater than 0. Provided ingress expiry time is ${options.ingressExpiryInMinutes} minutes.`);\n }\n __classPrivateFieldSet(this, _HttpAgent_maxIngressExpiryInMinutes, options.ingressExpiryInMinutes || 5, \"f\");\n // Add a nonce transform to ensure calls are unique\n this.addTransform('update', makeNonceTransform(makeNonce));\n if (options.useQueryNonces) {\n this.addTransform('query', makeNonceTransform(makeNonce));\n }\n if (options.logToConsole) {\n this.log.subscribe(log => {\n if (log.level === 'error') {\n console.error(log.message);\n }\n else if (log.level === 'warn') {\n console.warn(log.message);\n }\n else {\n console.log(log.message);\n }\n });\n }\n }\n get waterMark() {\n return __classPrivateFieldGet(this, _HttpAgent_waterMark, \"f\");\n }\n static createSync(options = {}) {\n return new this(Object.assign({}, options));\n }\n static async create(options = {\n shouldFetchRootKey: false,\n }) {\n const agent = HttpAgent.createSync(options);\n const initPromises = [agent.syncTime()];\n if (agent.host.toString() !== 'https://icp-api.io' && options.shouldFetchRootKey) {\n initPromises.push(agent.fetchRootKey());\n }\n await Promise.all(initPromises);\n return agent;\n }\n static async from(agent) {\n var _a;\n try {\n if ('config' in agent) {\n return await HttpAgent.create(agent.config);\n }\n return await HttpAgent.create({\n fetch: agent._fetch,\n fetchOptions: agent._fetchOptions,\n callOptions: agent._callOptions,\n host: agent._host.toString(),\n identity: (_a = agent._identity) !== null && _a !== void 0 ? _a : undefined,\n });\n }\n catch (_b) {\n throw new AgentError('Failed to create agent from provided agent');\n }\n }\n isLocal() {\n const hostname = this.host.hostname;\n return hostname === '127.0.0.1' || hostname.endsWith('127.0.0.1');\n }\n addTransform(type, fn, priority = fn.priority || 0) {\n if (type === 'update') {\n // Keep the pipeline sorted at all time, by priority.\n const i = __classPrivateFieldGet(this, _HttpAgent_updatePipeline, \"f\").findIndex(x => (x.priority || 0) < priority);\n __classPrivateFieldGet(this, _HttpAgent_updatePipeline, \"f\").splice(i >= 0 ? i : __classPrivateFieldGet(this, _HttpAgent_updatePipeline, \"f\").length, 0, Object.assign(fn, { priority }));\n }\n else if (type === 'query') {\n // Keep the pipeline sorted at all time, by priority.\n const i = __classPrivateFieldGet(this, _HttpAgent_queryPipeline, \"f\").findIndex(x => (x.priority || 0) < priority);\n __classPrivateFieldGet(this, _HttpAgent_queryPipeline, \"f\").splice(i >= 0 ? i : __classPrivateFieldGet(this, _HttpAgent_queryPipeline, \"f\").length, 0, Object.assign(fn, { priority }));\n }\n }\n async getPrincipal() {\n if (!__classPrivateFieldGet(this, _HttpAgent_identity, \"f\")) {\n throw new IdentityInvalidError(\"This identity has expired due this application's security policy. Please refresh your authentication.\");\n }\n return (await __classPrivateFieldGet(this, _HttpAgent_identity, \"f\")).getPrincipal();\n }\n async call(canisterId, options, identity) {\n var _a;\n // TODO - restore this value\n const callSync = (_a = options.callSync) !== null && _a !== void 0 ? _a : true;\n const id = await (identity !== undefined ? await identity : await __classPrivateFieldGet(this, _HttpAgent_identity, \"f\"));\n if (!id) {\n throw new IdentityInvalidError(\"This identity has expired due this application's security policy. Please refresh your authentication.\");\n }\n const canister = Principal.from(canisterId);\n const ecid = options.effectiveCanisterId\n ? Principal.from(options.effectiveCanisterId)\n : canister;\n const sender = id.getPrincipal() || Principal.anonymous();\n let ingress_expiry = new Expiry(__classPrivateFieldGet(this, _HttpAgent_maxIngressExpiryInMinutes, \"f\") * MINUTE_TO_MSECS);\n // If the value is off by more than 30 seconds, reconcile system time with the network\n if (Math.abs(__classPrivateFieldGet(this, _HttpAgent_timeDiffMsecs, \"f\")) > 1000 * 30) {\n ingress_expiry = new Expiry(__classPrivateFieldGet(this, _HttpAgent_maxIngressExpiryInMinutes, \"f\") * MINUTE_TO_MSECS + __classPrivateFieldGet(this, _HttpAgent_timeDiffMsecs, \"f\"));\n }\n const submit = {\n request_type: SubmitRequestType.Call,\n canister_id: canister,\n method_name: options.methodName,\n arg: options.arg,\n sender,\n ingress_expiry,\n };\n let transformedRequest = (await this._transform({\n request: {\n body: null,\n method: 'POST',\n headers: Object.assign({ 'Content-Type': 'application/cbor' }, (__classPrivateFieldGet(this, _HttpAgent_credentials, \"f\") ? { Authorization: 'Basic ' + btoa(__classPrivateFieldGet(this, _HttpAgent_credentials, \"f\")) } : {})),\n },\n endpoint: \"call\" /* Endpoint.Call */,\n body: submit,\n }));\n const nonce = transformedRequest.body.nonce\n ? toNonce(transformedRequest.body.nonce)\n : undefined;\n submit.nonce = nonce;\n function toNonce(buf) {\n return new Uint8Array(buf);\n }\n // Apply transform for identity.\n transformedRequest = (await id.transformRequest(transformedRequest));\n const body = cbor.encode(transformedRequest.body);\n const backoff = __classPrivateFieldGet(this, _HttpAgent_backoffStrategy, \"f\").call(this);\n try {\n // Attempt v3 sync call\n const requestSync = () => {\n this.log.print(`fetching \"/api/v3/canister/${ecid.toText()}/call\" with request:`, transformedRequest);\n return __classPrivateFieldGet(this, _HttpAgent_fetch, \"f\").call(this, '' + new URL(`/api/v3/canister/${ecid.toText()}/call`, this.host), Object.assign(Object.assign(Object.assign({}, __classPrivateFieldGet(this, _HttpAgent_callOptions, \"f\")), transformedRequest.request), { body }));\n };\n const requestAsync = () => {\n this.log.print(`fetching \"/api/v2/canister/${ecid.toText()}/call\" with request:`, transformedRequest);\n return __classPrivateFieldGet(this, _HttpAgent_fetch, \"f\").call(this, '' + new URL(`/api/v2/canister/${ecid.toText()}/call`, this.host), Object.assign(Object.assign(Object.assign({}, __classPrivateFieldGet(this, _HttpAgent_callOptions, \"f\")), transformedRequest.request), { body }));\n };\n const request = __classPrivateFieldGet(this, _HttpAgent_instances, \"m\", _HttpAgent_requestAndRetry).call(this, {\n request: callSync ? requestSync : requestAsync,\n backoff,\n tries: 0,\n });\n const requestId = requestIdOf(submit);\n const response = await request;\n const responseBuffer = await response.arrayBuffer();\n const responseBody = (response.status === 200 && responseBuffer.byteLength > 0\n ? cbor.decode(responseBuffer)\n : null);\n // Update the watermark with the latest time from consensus\n if (responseBody && 'certificate' in responseBody) {\n const time = await this.parseTimeFromResponse({\n certificate: responseBody.certificate,\n });\n __classPrivateFieldSet(this, _HttpAgent_waterMark, time, \"f\");\n }\n return {\n requestId,\n response: {\n ok: response.ok,\n status: response.status,\n statusText: response.statusText,\n body: responseBody,\n headers: httpHeadersTransform(response.headers),\n },\n requestDetails: submit,\n };\n }\n catch (error) {\n // If the error is due to the v3 api not being supported, fall back to v2\n if (error.message.includes('v3 api not supported.')) {\n this.log.warn('v3 api not supported. Fall back to v2');\n return this.call(canisterId, Object.assign(Object.assign({}, options), { \n // disable v3 api\n callSync: false }), identity);\n }\n this.log.error('Error while making call:', error);\n throw error;\n }\n }\n async query(canisterId, fields, identity) {\n const backoff = __classPrivateFieldGet(this, _HttpAgent_backoffStrategy, \"f\").call(this);\n const ecid = fields.effectiveCanisterId\n ? Principal.from(fields.effectiveCanisterId)\n : Principal.from(canisterId);\n this.log.print(`ecid ${ecid.toString()}`);\n this.log.print(`canisterId ${canisterId.toString()}`);\n const makeQuery = async () => {\n const id = await (identity !== undefined ? identity : __classPrivateFieldGet(this, _HttpAgent_identity, \"f\"));\n if (!id) {\n throw new IdentityInvalidError(\"This identity has expired due this application's security policy. Please refresh your authentication.\");\n }\n const canister = Principal.from(canisterId);\n const sender = (id === null || id === void 0 ? void 0 : id.getPrincipal()) || Principal.anonymous();\n const request = {\n request_type: \"query\" /* ReadRequestType.Query */,\n canister_id: canister,\n method_name: fields.methodName,\n arg: fields.arg,\n sender,\n ingress_expiry: new Expiry(__classPrivateFieldGet(this, _HttpAgent_maxIngressExpiryInMinutes, \"f\") * MINUTE_TO_MSECS),\n };\n const requestId = requestIdOf(request);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let transformedRequest = await this._transform({\n request: {\n method: 'POST',\n headers: Object.assign({ 'Content-Type': 'application/cbor' }, (__classPrivateFieldGet(this, _HttpAgent_credentials, \"f\") ? { Authorization: 'Basic ' + btoa(__classPrivateFieldGet(this, _HttpAgent_credentials, \"f\")) } : {})),\n },\n endpoint: \"read\" /* Endpoint.Query */,\n body: request,\n });\n // Apply transform for identity.\n transformedRequest = (await (id === null || id === void 0 ? void 0 : id.transformRequest(transformedRequest)));\n const body = cbor.encode(transformedRequest.body);\n const args = {\n canister: canister.toText(),\n ecid,\n transformedRequest,\n body,\n requestId,\n backoff,\n tries: 0,\n };\n return {\n requestDetails: request,\n query: await __classPrivateFieldGet(this, _HttpAgent_instances, \"m\", _HttpAgent_requestAndRetryQuery).call(this, args),\n };\n };\n const getSubnetStatus = async () => {\n if (!__classPrivateFieldGet(this, _HttpAgent_verifyQuerySignatures, \"f\")) {\n return undefined;\n }\n const subnetStatus = __classPrivateFieldGet(this, _HttpAgent_subnetKeys, \"f\").get(ecid.toString());\n if (subnetStatus) {\n return subnetStatus;\n }\n await this.fetchSubnetKeys(ecid.toString());\n return __classPrivateFieldGet(this, _HttpAgent_subnetKeys, \"f\").get(ecid.toString());\n };\n // Attempt to make the query i=retryTimes times\n // Make query and fetch subnet keys in parallel\n const [queryResult, subnetStatus] = await Promise.all([makeQuery(), getSubnetStatus()]);\n const { requestDetails, query } = queryResult;\n const queryWithDetails = Object.assign(Object.assign({}, query), { requestDetails });\n this.log.print('Query response:', queryWithDetails);\n // Skip verification if the user has disabled it\n if (!__classPrivateFieldGet(this, _HttpAgent_verifyQuerySignatures, \"f\")) {\n return queryWithDetails;\n }\n try {\n return __classPrivateFieldGet(this, _HttpAgent_verifyQueryResponse, \"f\").call(this, queryWithDetails, subnetStatus);\n }\n catch (_a) {\n // In case the node signatures have changed, refresh the subnet keys and try again\n this.log.warn('Query response verification failed. Retrying with fresh subnet keys.');\n __classPrivateFieldGet(this, _HttpAgent_subnetKeys, \"f\").delete(canisterId.toString());\n await this.fetchSubnetKeys(ecid.toString());\n const updatedSubnetStatus = __classPrivateFieldGet(this, _HttpAgent_subnetKeys, \"f\").get(canisterId.toString());\n if (!updatedSubnetStatus) {\n throw new CertificateVerificationError('Invalid signature from replica signed query: no matching node key found.');\n }\n return __classPrivateFieldGet(this, _HttpAgent_verifyQueryResponse, \"f\").call(this, queryWithDetails, updatedSubnetStatus);\n }\n }\n async createReadStateRequest(fields, identity) {\n const id = await (identity !== undefined ? await identity : await __classPrivateFieldGet(this, _HttpAgent_identity, \"f\"));\n if (!id) {\n throw new IdentityInvalidError(\"This identity has expired due this application's security policy. Please refresh your authentication.\");\n }\n const sender = (id === null || id === void 0 ? void 0 : id.getPrincipal()) || Principal.anonymous();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const transformedRequest = await this._transform({\n request: {\n method: 'POST',\n headers: Object.assign({ 'Content-Type': 'application/cbor' }, (__classPrivateFieldGet(this, _HttpAgent_credentials, \"f\") ? { Authorization: 'Basic ' + btoa(__classPrivateFieldGet(this, _HttpAgent_credentials, \"f\")) } : {})),\n },\n endpoint: \"read_state\" /* Endpoint.ReadState */,\n body: {\n request_type: \"read_state\" /* ReadRequestType.ReadState */,\n paths: fields.paths,\n sender,\n ingress_expiry: new Expiry(__classPrivateFieldGet(this, _HttpAgent_maxIngressExpiryInMinutes, \"f\") * MINUTE_TO_MSECS),\n },\n });\n // Apply transform for identity.\n return id === null || id === void 0 ? void 0 : id.transformRequest(transformedRequest);\n }\n async readState(canisterId, fields, identity, \n // eslint-disable-next-line\n request) {\n const canister = typeof canisterId === 'string' ? Principal.fromText(canisterId) : canisterId;\n const transformedRequest = request !== null && request !== void 0 ? request : (await this.createReadStateRequest(fields, identity));\n // With read_state, we should always use a fresh expiry, even beyond the point where the initial request would have expired\n const bodyWithAdjustedExpiry = Object.assign(Object.assign({}, transformedRequest.body), { ingress_expiry: new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS) });\n const body = cbor.encode(bodyWithAdjustedExpiry);\n this.log.print(`fetching \"/api/v2/canister/${canister}/read_state\" with request:`, transformedRequest);\n // TODO - https://dfinity.atlassian.net/browse/SDK-1092\n const backoff = __classPrivateFieldGet(this, _HttpAgent_backoffStrategy, \"f\").call(this);\n try {\n const response = await __classPrivateFieldGet(this, _HttpAgent_instances, \"m\", _HttpAgent_requestAndRetry).call(this, {\n request: () => __classPrivateFieldGet(this, _HttpAgent_fetch, \"f\").call(this, '' + new URL(`/api/v2/canister/${canister.toString()}/read_state`, this.host), Object.assign(Object.assign(Object.assign({}, __classPrivateFieldGet(this, _HttpAgent_fetchOptions, \"f\")), transformedRequest.request), { body })),\n backoff,\n tries: 0,\n });\n if (!response.ok) {\n throw new Error(`Server returned an error:\\n` +\n ` Code: ${response.status} (${response.statusText})\\n` +\n ` Body: ${await response.text()}\\n`);\n }\n const decodedResponse = cbor.decode(await response.arrayBuffer());\n this.log.print('Read state response:', decodedResponse);\n const parsedTime = await this.parseTimeFromResponse(decodedResponse);\n if (parsedTime > 0) {\n this.log.print('Read state response time:', parsedTime);\n __classPrivateFieldSet(this, _HttpAgent_waterMark, parsedTime, \"f\");\n }\n return decodedResponse;\n }\n catch (error) {\n this.log.error('Caught exception while attempting to read state', error);\n throw error;\n }\n }\n async parseTimeFromResponse(response) {\n let tree;\n if (response.certificate) {\n const decoded = cbor.decode(response.certificate);\n if (decoded && 'tree' in decoded) {\n tree = decoded.tree;\n }\n else {\n throw new Error('Could not decode time from response');\n }\n const timeLookup = lookup_path(['time'], tree);\n if (timeLookup.status !== LookupStatus.Found) {\n throw new Error('Time was not found in the response or was not in its expected format.');\n }\n if (!(timeLookup.value instanceof ArrayBuffer) && !ArrayBuffer.isView(timeLookup)) {\n throw new Error('Time was not found in the response or was not in its expected format.');\n }\n const date = decodeTime(bufFromBufLike(timeLookup.value));\n this.log.print('Time from response:', date);\n this.log.print('Time from response in milliseconds:', Number(date));\n return Number(date);\n }\n else {\n this.log.warn('No certificate found in response');\n }\n return 0;\n }\n /**\n * Allows agent to sync its time with the network. Can be called during intialization or mid-lifecycle if the device's clock has drifted away from the network time. This is necessary to set the Expiry for a request\n * @param {Principal} canisterId - Pass a canister ID if you need to sync the time with a particular replica. Uses the management canister by default\n */\n async syncTime(canisterId) {\n const CanisterStatus = await import('../../canisterStatus');\n const callTime = Date.now();\n try {\n if (!canisterId) {\n this.log.print('Syncing time with the IC. No canisterId provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai');\n }\n const status = await CanisterStatus.request({\n // Fall back with canisterId of the ICP Ledger\n canisterId: canisterId !== null && canisterId !== void 0 ? canisterId : Principal.from('ryjl3-tyaaa-aaaaa-aaaba-cai'),\n agent: this,\n paths: ['time'],\n });\n const replicaTime = status.get('time');\n if (replicaTime) {\n __classPrivateFieldSet(this, _HttpAgent_timeDiffMsecs, Number(replicaTime) - Number(callTime), \"f\");\n }\n }\n catch (error) {\n this.log.error('Caught exception while attempting to sync time', error);\n }\n }\n async status() {\n const headers = __classPrivateFieldGet(this, _HttpAgent_credentials, \"f\")\n ? {\n Authorization: 'Basic ' + btoa(__classPrivateFieldGet(this, _HttpAgent_credentials, \"f\")),\n }\n : {};\n this.log.print(`fetching \"/api/v2/status\"`);\n const backoff = __classPrivateFieldGet(this, _HttpAgent_backoffStrategy, \"f\").call(this);\n const response = await __classPrivateFieldGet(this, _HttpAgent_instances, \"m\", _HttpAgent_requestAndRetry).call(this, {\n backoff,\n request: () => __classPrivateFieldGet(this, _HttpAgent_fetch, \"f\").call(this, '' + new URL(`/api/v2/status`, this.host), Object.assign({ headers }, __classPrivateFieldGet(this, _HttpAgent_fetchOptions, \"f\"))),\n tries: 0,\n });\n return cbor.decode(await response.arrayBuffer());\n }\n async fetchRootKey() {\n if (!__classPrivateFieldGet(this, _HttpAgent_rootKeyFetched, \"f\")) {\n const status = await this.status();\n // Hex-encoded version of the replica root key\n this.rootKey = status.root_key;\n __classPrivateFieldSet(this, _HttpAgent_rootKeyFetched, true, \"f\");\n }\n return this.rootKey;\n }\n invalidateIdentity() {\n __classPrivateFieldSet(this, _HttpAgent_identity, null, \"f\");\n }\n replaceIdentity(identity) {\n __classPrivateFieldSet(this, _HttpAgent_identity, Promise.resolve(identity), \"f\");\n }\n async fetchSubnetKeys(canisterId) {\n const effectiveCanisterId = Principal.from(canisterId);\n const response = await request({\n canisterId: effectiveCanisterId,\n paths: ['subnet'],\n agent: this,\n });\n const subnetResponse = response.get('subnet');\n if (subnetResponse && typeof subnetResponse === 'object' && 'nodeKeys' in subnetResponse) {\n __classPrivateFieldGet(this, _HttpAgent_subnetKeys, \"f\").set(effectiveCanisterId.toText(), subnetResponse);\n return subnetResponse;\n }\n // If the subnet status is not returned, return undefined\n return undefined;\n }\n _transform(request) {\n let p = Promise.resolve(request);\n if (request.endpoint === \"call\" /* Endpoint.Call */) {\n for (const fn of __classPrivateFieldGet(this, _HttpAgent_updatePipeline, \"f\")) {\n p = p.then(r => fn(r).then(r2 => r2 || r));\n }\n }\n else {\n for (const fn of __classPrivateFieldGet(this, _HttpAgent_queryPipeline, \"f\")) {\n p = p.then(r => fn(r).then(r2 => r2 || r));\n }\n }\n return p;\n }\n}\n_HttpAgent_identity = new WeakMap(), _HttpAgent_fetch = new WeakMap(), _HttpAgent_fetchOptions = new WeakMap(), _HttpAgent_callOptions = new WeakMap(), _HttpAgent_timeDiffMsecs = new WeakMap(), _HttpAgent_credentials = new WeakMap(), _HttpAgent_rootKeyFetched = new WeakMap(), _HttpAgent_retryTimes = new WeakMap(), _HttpAgent_backoffStrategy = new WeakMap(), _HttpAgent_maxIngressExpiryInMinutes = new WeakMap(), _HttpAgent_waterMark = new WeakMap(), _HttpAgent_queryPipeline = new WeakMap(), _HttpAgent_updatePipeline = new WeakMap(), _HttpAgent_subnetKeys = new WeakMap(), _HttpAgent_verifyQuerySignatures = new WeakMap(), _HttpAgent_verifyQueryResponse = new WeakMap(), _HttpAgent_instances = new WeakSet(), _HttpAgent_requestAndRetryQuery = async function _HttpAgent_requestAndRetryQuery(args) {\n var _a, _b;\n const { ecid, transformedRequest, body, requestId, backoff, tries } = args;\n const delay = tries === 0 ? 0 : backoff.next();\n this.log.print(`fetching \"/api/v2/canister/${ecid.toString()}/query\" with tries:`, {\n tries,\n backoff,\n delay,\n });\n // If delay is null, the backoff strategy is exhausted due to a maximum number of retries, duration, or other reason\n if (delay === null) {\n throw new AgentError(`Timestamp failed to pass the watermark after retrying the configured ${__classPrivateFieldGet(this, _HttpAgent_retryTimes, \"f\")} times. We cannot guarantee the integrity of the response since it could be a replay attack.`);\n }\n if (delay > 0) {\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n let response;\n // Make the request and retry if it throws an error\n try {\n this.log.print(`fetching \"/api/v2/canister/${ecid.toString()}/query\" with request:`, transformedRequest);\n const fetchResponse = await __classPrivateFieldGet(this, _HttpAgent_fetch, \"f\").call(this, '' + new URL(`/api/v2/canister/${ecid.toString()}/query`, this.host), Object.assign(Object.assign(Object.assign({}, __classPrivateFieldGet(this, _HttpAgent_fetchOptions, \"f\")), transformedRequest.request), { body }));\n if (fetchResponse.status === 200) {\n const queryResponse = cbor.decode(await fetchResponse.arrayBuffer());\n response = Object.assign(Object.assign({}, queryResponse), { httpDetails: {\n ok: fetchResponse.ok,\n status: fetchResponse.status,\n statusText: fetchResponse.statusText,\n headers: httpHeadersTransform(fetchResponse.headers),\n }, requestId });\n }\n else {\n throw new AgentHTTPResponseError(`Gateway returned an error:\\n` +\n ` Code: ${fetchResponse.status} (${fetchResponse.statusText})\\n` +\n ` Body: ${await fetchResponse.text()}\\n`, {\n ok: fetchResponse.ok,\n status: fetchResponse.status,\n statusText: fetchResponse.statusText,\n headers: httpHeadersTransform(fetchResponse.headers),\n });\n }\n }\n catch (error) {\n if (tries < __classPrivateFieldGet(this, _HttpAgent_retryTimes, \"f\")) {\n this.log.warn(`Caught exception while attempting to make query:\\n` +\n ` ${error}\\n` +\n ` Retrying query.`);\n return await __classPrivateFieldGet(this, _HttpAgent_instances, \"m\", _HttpAgent_requestAndRetryQuery).call(this, Object.assign(Object.assign({}, args), { tries: tries + 1 }));\n }\n throw error;\n }\n const timestamp = (_b = (_a = response.signatures) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.timestamp;\n // Skip watermark verification if the user has set verifyQuerySignatures to false\n if (!__classPrivateFieldGet(this, _HttpAgent_verifyQuerySignatures, \"f\")) {\n return response;\n }\n if (!timestamp) {\n throw new Error('Timestamp not found in query response. This suggests a malformed or malicious response.');\n }\n // Convert the timestamp to milliseconds\n const timeStampInMs = Number(BigInt(timestamp) / BigInt(1000000));\n this.log.print('watermark and timestamp', {\n waterMark: this.waterMark,\n timestamp: timeStampInMs,\n });\n // If the timestamp is less than the watermark, retry the request up to the retry limit\n if (Number(this.waterMark) > timeStampInMs) {\n const error = new AgentError('Timestamp is below the watermark. Retrying query.');\n this.log.error('Timestamp is below', error, {\n timestamp,\n waterMark: this.waterMark,\n });\n if (tries < __classPrivateFieldGet(this, _HttpAgent_retryTimes, \"f\")) {\n return await __classPrivateFieldGet(this, _HttpAgent_instances, \"m\", _HttpAgent_requestAndRetryQuery).call(this, Object.assign(Object.assign({}, args), { tries: tries + 1 }));\n }\n {\n throw new AgentError(`Timestamp failed to pass the watermark after retrying the configured ${__classPrivateFieldGet(this, _HttpAgent_retryTimes, \"f\")} times. We cannot guarantee the integrity of the response since it could be a replay attack.`);\n }\n }\n return response;\n}, _HttpAgent_requestAndRetry = async function _HttpAgent_requestAndRetry(args) {\n const { request, backoff, tries } = args;\n const delay = tries === 0 ? 0 : backoff.next();\n // If delay is null, the backoff strategy is exhausted due to a maximum number of retries, duration, or other reason\n if (delay === null) {\n throw new AgentError(`Timestamp failed to pass the watermark after retrying the configured ${__classPrivateFieldGet(this, _HttpAgent_retryTimes, \"f\")} times. We cannot guarantee the integrity of the response since it could be a replay attack.`);\n }\n if (delay > 0) {\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n let response;\n try {\n response = await request();\n }\n catch (error) {\n if (__classPrivateFieldGet(this, _HttpAgent_retryTimes, \"f\") > tries) {\n this.log.warn(`Caught exception while attempting to make request:\\n` +\n ` ${error}\\n` +\n ` Retrying request.`);\n // Delay the request by the configured backoff strategy\n return await __classPrivateFieldGet(this, _HttpAgent_instances, \"m\", _HttpAgent_requestAndRetry).call(this, { request, backoff, tries: tries + 1 });\n }\n throw error;\n }\n if (response.ok) {\n return response;\n }\n const responseText = await response.clone().text();\n const errorMessage = `Server returned an error:\\n` +\n ` Code: ${response.status} (${response.statusText})\\n` +\n ` Body: ${responseText}\\n`;\n if (response.status === 404 && response.url.includes('api/v3')) {\n throw new AgentHTTPResponseError('v3 api not supported. Fall back to v2', {\n ok: response.ok,\n status: response.status,\n statusText: response.statusText,\n headers: httpHeadersTransform(response.headers),\n });\n }\n if (tries < __classPrivateFieldGet(this, _HttpAgent_retryTimes, \"f\")) {\n return await __classPrivateFieldGet(this, _HttpAgent_instances, \"m\", _HttpAgent_requestAndRetry).call(this, { request, backoff, tries: tries + 1 });\n }\n throw new AgentHTTPResponseError(errorMessage, {\n ok: response.ok,\n status: response.status,\n statusText: response.statusText,\n headers: httpHeadersTransform(response.headers),\n });\n};\n//# sourceMappingURL=index.js.map","import { Principal } from '@dfinity/principal';\nexport var ProxyMessageKind;\n(function (ProxyMessageKind) {\n ProxyMessageKind[\"Error\"] = \"err\";\n ProxyMessageKind[\"GetPrincipal\"] = \"gp\";\n ProxyMessageKind[\"GetPrincipalResponse\"] = \"gpr\";\n ProxyMessageKind[\"Query\"] = \"q\";\n ProxyMessageKind[\"QueryResponse\"] = \"qr\";\n ProxyMessageKind[\"Call\"] = \"c\";\n ProxyMessageKind[\"CallResponse\"] = \"cr\";\n ProxyMessageKind[\"ReadState\"] = \"rs\";\n ProxyMessageKind[\"ReadStateResponse\"] = \"rsr\";\n ProxyMessageKind[\"Status\"] = \"s\";\n ProxyMessageKind[\"StatusResponse\"] = \"sr\";\n})(ProxyMessageKind || (ProxyMessageKind = {}));\n// A Stub Agent that forwards calls to another Agent implementation.\nexport class ProxyStubAgent {\n constructor(_frontend, _agent) {\n this._frontend = _frontend;\n this._agent = _agent;\n }\n onmessage(msg) {\n switch (msg.type) {\n case ProxyMessageKind.GetPrincipal:\n this._agent.getPrincipal().then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.GetPrincipalResponse,\n response: response.toText(),\n });\n });\n break;\n case ProxyMessageKind.Query:\n this._agent.query(...msg.args).then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.QueryResponse,\n response,\n });\n });\n break;\n case ProxyMessageKind.Call:\n this._agent.call(...msg.args).then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.CallResponse,\n response,\n });\n });\n break;\n case ProxyMessageKind.ReadState:\n this._agent.readState(...msg.args).then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.ReadStateResponse,\n response,\n });\n });\n break;\n case ProxyMessageKind.Status:\n this._agent.status().then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.StatusResponse,\n response,\n });\n });\n break;\n default:\n throw new Error(`Invalid message received: ${JSON.stringify(msg)}`);\n }\n }\n}\n// An Agent that forwards calls to a backend. The calls are serialized\nexport class ProxyAgent {\n constructor(_backend) {\n this._backend = _backend;\n this._nextId = 0;\n this._pendingCalls = new Map();\n this.rootKey = null;\n }\n onmessage(msg) {\n const id = msg.id;\n const maybePromise = this._pendingCalls.get(id);\n if (!maybePromise) {\n throw new Error('A proxy get the same message twice...');\n }\n this._pendingCalls.delete(id);\n const [resolve, reject] = maybePromise;\n switch (msg.type) {\n case ProxyMessageKind.Error:\n return reject(msg.error);\n case ProxyMessageKind.GetPrincipalResponse:\n case ProxyMessageKind.CallResponse:\n case ProxyMessageKind.QueryResponse:\n case ProxyMessageKind.ReadStateResponse:\n case ProxyMessageKind.StatusResponse:\n return resolve(msg.response);\n default:\n throw new Error(`Invalid message being sent to ProxyAgent: ${JSON.stringify(msg)}`);\n }\n }\n async getPrincipal() {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.GetPrincipal,\n }).then(principal => {\n if (typeof principal !== 'string') {\n throw new Error('Invalid principal received.');\n }\n return Principal.fromText(principal);\n });\n }\n readState(canisterId, fields) {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.ReadState,\n args: [canisterId.toString(), fields],\n });\n }\n call(canisterId, fields) {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.Call,\n args: [canisterId.toString(), fields],\n });\n }\n status() {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.Status,\n });\n }\n query(canisterId, fields) {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.Query,\n args: [canisterId.toString(), fields],\n });\n }\n async _sendAndWait(msg) {\n return new Promise((resolve, reject) => {\n this._pendingCalls.set(msg.id, [resolve, reject]);\n this._backend(msg);\n });\n }\n async fetchRootKey() {\n // Hex-encoded version of the replica root key\n const rootKey = (await this.status()).root_key;\n this.rootKey = rootKey;\n return rootKey;\n }\n}\n//# sourceMappingURL=proxy.js.map","export * from './api';\nexport * from './http';\nexport * from './http/errors';\nexport * from './proxy';\nexport function getDefaultAgent() {\n const agent = typeof window === 'undefined'\n ? typeof global === 'undefined'\n ? typeof self === 'undefined'\n ? undefined\n : self.ic.agent\n : global.ic.agent\n : window.ic.agent;\n if (!agent) {\n throw new Error('No Agent could be found.');\n }\n return agent;\n}\n//# sourceMappingURL=index.js.map","import { toHex } from '../utils/buffer';\nconst FIVE_MINUTES_IN_MSEC = 5 * 60 * 1000;\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() {\n return chain(conditionalDelay(once(), 1000), backoff(1000, 1.2), timeout(FIVE_MINUTES_IN_MSEC));\n}\n/**\n * Predicate that returns true once.\n */\nexport function once() {\n let first = true;\n return async () => {\n if (first) {\n first = false;\n return true;\n }\n return false;\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, timeInMsec) {\n return async (canisterId, requestId, status) => {\n if (await condition(canisterId, requestId, status)) {\n return new Promise(resolve => setTimeout(resolve, timeInMsec));\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) {\n let attempts = count;\n return async (canisterId, requestId, status) => {\n if (--attempts <= 0) {\n throw new Error(`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 * Throttle polling.\n * @param throttleInMsec Amount in millisecond to wait between each polling.\n */\nexport function throttle(throttleInMsec) {\n return () => new Promise(resolve => setTimeout(resolve, throttleInMsec));\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) {\n const end = Date.now() + timeInMsec;\n return async (canisterId, requestId, status) => {\n if (Date.now() > end) {\n throw new Error(`Request timed out after ${timeInMsec} msec:\\n` +\n ` Request ID: ${toHex(requestId)}\\n` +\n ` Request status: ${status}\\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, backoffFactor) {\n let currentThrottling = startingThrottleInMsec;\n return () => new Promise(resolve => setTimeout(() => {\n currentThrottling *= backoffFactor;\n resolve();\n }, currentThrottling));\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) {\n return async (canisterId, requestId, status) => {\n for (const a of strategies) {\n await a(canisterId, requestId, status);\n }\n };\n}\n//# sourceMappingURL=strategy.js.map","import { Expiry, RequestStatusResponseStatus } from '../agent';\nimport { Certificate, lookupResultToBuffer } from '../certificate';\nimport { toHex } from '../utils/buffer';\nexport * as strategy from './strategy';\nimport { defaultStrategy } from './strategy';\nimport { DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS } from '../constants';\nexport { defaultStrategy } from './strategy';\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(value, property) {\n return Object.prototype.hasOwnProperty.call(value, property);\n}\n/**\n * Check if value is a signed read state request with expiry\n * @param value to check\n */\nfunction isSignedReadStateRequestWithExpiry(value) {\n return (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 === \"read_state\" /* 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 * 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(agent, canisterId, requestId, strategy = defaultStrategy(), request, blsVerify) {\n var _a;\n const path = [new TextEncoder().encode('request_status'), requestId];\n const currentRequest = request !== null && request !== void 0 ? request : (await ((_a = agent.createReadStateRequest) === null || _a === void 0 ? void 0 : _a.call(agent, { paths: [path] })));\n // Use a fresh expiry for the repeated readState call\n if (request && isSignedReadStateRequestWithExpiry(currentRequest)) {\n currentRequest.body.content.ingress_expiry = new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS);\n }\n const state = await agent.readState(canisterId, { paths: [path] }, undefined, currentRequest);\n if (agent.rootKey == null)\n throw new Error('Agent root key not initialized before polling');\n const cert = await Certificate.create({\n certificate: state.certificate,\n rootKey: agent.rootKey,\n canisterId: canisterId,\n blsVerify,\n });\n const maybeBuf = lookupResultToBuffer(cert.lookup([...path, new TextEncoder().encode('status')]));\n let status;\n if (typeof maybeBuf === 'undefined') {\n // Missing requestId means we need to wait\n status = RequestStatusResponseStatus.Unknown;\n }\n else {\n status = new TextDecoder().decode(maybeBuf);\n }\n switch (status) {\n case RequestStatusResponseStatus.Replied: {\n return {\n reply: lookupResultToBuffer(cert.lookup([...path, 'reply'])),\n certificate: cert,\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 case RequestStatusResponseStatus.Rejected: {\n const rejectCode = new Uint8Array(lookupResultToBuffer(cert.lookup([...path, 'reject_code'])))[0];\n const rejectMessage = new TextDecoder().decode(lookupResultToBuffer(cert.lookup([...path, 'reject_message'])));\n throw new Error(`Call was rejected:\\n` +\n ` Request ID: ${toHex(requestId)}\\n` +\n ` Reject code: ${rejectCode}\\n` +\n ` Reject text: ${rejectMessage}\\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(`Call was marked as done but we never saw the reply:\\n` +\n ` Request ID: ${toHex(requestId)}\\n`);\n }\n throw new Error('unreachable');\n}\n//# sourceMappingURL=index.js.map","/*\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\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(IDL.Variant({\n page: IDL.Vec(IDL.Nat8),\n min_confirmations: IDL.Nat32,\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 });\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(IDL.Record({\n function: IDL.Func([\n IDL.Record({\n context: IDL.Vec(IDL.Nat8),\n response: http_request_result,\n }),\n ], [http_request_result], ['query']),\n context: IDL.Vec(IDL.Nat8),\n })),\n headers: IDL.Vec(http_header),\n });\n const canister_install_mode = IDL.Variant({\n reinstall: IDL.Null,\n upgrade: IDL.Opt(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 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(IDL.Record({\n timestamp_nanos: IDL.Nat64,\n node_metrics: IDL.Vec(node_metrics),\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 sign_with_schnorr_args = IDL.Record({\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 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([bitcoin_get_block_headers_args], [bitcoin_get_block_headers_result], []),\n bitcoin_get_current_fee_percentiles: IDL.Func([bitcoin_get_current_fee_percentiles_args], [bitcoin_get_current_fee_percentiles_result], []),\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([fetch_canister_logs_args], [fetch_canister_logs_result], ['query']),\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([list_canister_snapshots_args], [list_canister_snapshots_result], []),\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([provisional_create_canister_with_cycles_args], [provisional_create_canister_with_cycles_result], []),\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 take_canister_snapshot: IDL.Func([take_canister_snapshot_args], [take_canister_snapshot_result], []),\n uninstall_code: IDL.Func([uninstall_code_args], [], []),\n update_settings: IDL.Func([update_settings_args], [], []),\n upload_chunk: IDL.Func([upload_chunk_args], [upload_chunk_result], []),\n });\n};\n//# sourceMappingURL=management_idl.js.map","import { Buffer } from 'buffer/';\nimport { getDefaultAgent, ReplicaRejectCode, } from './agent';\nimport { AgentError } from './errors';\nimport { bufFromBufLike, IDL } from '@dfinity/candid';\nimport { pollForResponse, strategy } from './polling';\nimport { Principal } from '@dfinity/principal';\nimport { toHex } from './utils/buffer';\nimport { Certificate, lookupResultToBuffer } from './certificate';\nimport managementCanisterIdl from './canisters/management_idl';\nexport class ActorCallError extends AgentError {\n constructor(canisterId, methodName, type, props) {\n super([\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 this.canisterId = canisterId;\n this.methodName = methodName;\n this.type = type;\n this.props = props;\n }\n}\nexport class QueryCallRejectedError extends ActorCallError {\n constructor(canisterId, methodName, result) {\n var _a;\n super(canisterId, methodName, 'query', {\n Status: result.status,\n Code: (_a = ReplicaRejectCode[result.reject_code]) !== null && _a !== void 0 ? _a : `Unknown Code \"${result.reject_code}\"`,\n Message: result.reject_message,\n });\n this.result = result;\n }\n}\nexport class UpdateCallRejectedError extends ActorCallError {\n constructor(canisterId, methodName, requestId, response, reject_code, reject_message, error_code) {\n super(canisterId, methodName, 'update', Object.assign({ 'Request ID': toHex(requestId) }, (response.body\n ? Object.assign(Object.assign({}, (error_code\n ? {\n 'Error code': error_code,\n }\n : {})), { 'Reject code': String(reject_code), 'Reject message': reject_message }) : {\n 'HTTP status code': response.status.toString(),\n 'HTTP status text': response.statusText,\n })));\n this.requestId = requestId;\n this.response = response;\n this.reject_code = reject_code;\n this.reject_message = reject_message;\n this.error_code = error_code;\n }\n}\nconst metadataSymbol = Symbol.for('ic-agent-metadata');\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 constructor(metadata) {\n this[metadataSymbol] = Object.freeze(metadata);\n }\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 static agentOf(actor) {\n return actor[metadataSymbol].config.agent;\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 static interfaceOf(actor) {\n return actor[metadataSymbol].service;\n }\n static canisterIdOf(actor) {\n return Principal.from(actor[metadataSymbol].config.canisterId);\n }\n static async install(fields, config) {\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 = typeof config.canisterId === 'string'\n ? Principal.fromText(config.canisterId)\n : config.canisterId;\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 static async createCanister(config, settings) {\n function settingsToCanisterSettings(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 const { canister_id: canisterId } = await getManagementCanister(config || {}).provisional_create_canister_with_cycles({\n amount: [],\n settings: settingsToCanisterSettings(settings || {}),\n specified_id: [],\n sender_canister_version: [],\n });\n return canisterId;\n }\n static async createAndInstallCanister(interfaceFactory, fields, config) {\n const canisterId = await this.createCanister(config);\n await this.install(Object.assign({}, fields), Object.assign(Object.assign({}, config), { canisterId }));\n return this.createActor(interfaceFactory, Object.assign(Object.assign({}, config), { canisterId }));\n }\n static createActorClass(interfaceFactory, options) {\n const service = interfaceFactory({ IDL });\n class CanisterActor extends Actor {\n constructor(config) {\n if (!config.canisterId)\n throw new AgentError(`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 const canisterId = typeof config.canisterId === 'string'\n ? Principal.fromText(config.canisterId)\n : config.canisterId;\n super({\n config: Object.assign(Object.assign(Object.assign({}, DEFAULT_ACTOR_CONFIG), config), { canisterId }),\n service,\n });\n for (const [methodName, func] of service._fields) {\n if (options === null || options === void 0 ? void 0 : options.httpDetails) {\n func.annotations.push(ACTOR_METHOD_WITH_HTTP_DETAILS);\n }\n if (options === null || options === void 0 ? void 0 : options.certificate) {\n func.annotations.push(ACTOR_METHOD_WITH_CERTIFICATE);\n }\n this[methodName] = _createActorMethod(this, methodName, func, config.blsVerify);\n }\n }\n }\n return CanisterActor;\n }\n static createActor(interfaceFactory, configuration) {\n if (!configuration.canisterId) {\n throw new AgentError(`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 return new (this.createActorClass(interfaceFactory))(configuration);\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 static createActorWithHttpDetails(interfaceFactory, configuration) {\n return new (this.createActorClass(interfaceFactory, { httpDetails: true }))(configuration);\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 static createActorWithExtendedDetails(interfaceFactory, configuration, actorClassOptions = {\n httpDetails: true,\n certificate: true,\n }) {\n return new (this.createActorClass(interfaceFactory, actorClassOptions))(configuration);\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, msg) {\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}\nconst DEFAULT_ACTOR_CONFIG = {\n pollingStrategyFactory: strategy.defaultStrategy,\n};\nexport const ACTOR_METHOD_WITH_HTTP_DETAILS = 'http-details';\nexport const ACTOR_METHOD_WITH_CERTIFICATE = 'certificate';\nfunction _createActorMethod(actor, methodName, func, blsVerify) {\n let caller;\n if (func.annotations.includes('query') || func.annotations.includes('composite_query')) {\n caller = async (options, ...args) => {\n var _a, _b;\n // First, if there's a config transformation, call it.\n options = Object.assign(Object.assign({}, options), (_b = (_a = actor[metadataSymbol].config).queryTransform) === null || _b === void 0 ? void 0 : _b.call(_a, methodName, args, Object.assign(Object.assign({}, actor[metadataSymbol].config), options)));\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 const result = await agent.query(cid, {\n methodName,\n arg,\n effectiveCanisterId: options.effectiveCanisterId,\n });\n const httpDetails = Object.assign(Object.assign({}, result.httpDetails), { requestDetails: result.requestDetails });\n switch (result.status) {\n case \"rejected\" /* QueryResponseStatus.Rejected */:\n throw new QueryCallRejectedError(cid, methodName, result);\n case \"replied\" /* 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 }\n else {\n caller = async (options, ...args) => {\n var _a, _b;\n // First, if there's a config transformation, call it.\n options = Object.assign(Object.assign({}, options), (_b = (_a = actor[metadataSymbol].config).callTransform) === null || _b === void 0 ? void 0 : _b.call(_a, methodName, args, Object.assign(Object.assign({}, actor[metadataSymbol].config), options)));\n const agent = options.agent || actor[metadataSymbol].config.agent || getDefaultAgent();\n const { canisterId, effectiveCanisterId, pollingStrategyFactory } = Object.assign(Object.assign(Object.assign({}, DEFAULT_ACTOR_CONFIG), actor[metadataSymbol].config), options);\n const cid = Principal.from(canisterId);\n const ecid = effectiveCanisterId !== undefined ? Principal.from(effectiveCanisterId) : cid;\n const arg = IDL.encode(func.argTypes, args);\n if (agent.rootKey == null)\n throw new AgentError('Agent root key not initialized before making call');\n const { requestId, response, requestDetails } = await agent.call(cid, {\n methodName,\n arg,\n effectiveCanisterId: ecid,\n });\n let reply;\n let certificate;\n if (response.body && response.body.certificate) {\n const cert = response.body.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(lookupResultToBuffer(certificate.lookup([...path, 'status'])));\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(lookupResultToBuffer(certificate.lookup([...path, 'reject_code'])))[0];\n const rejectMessage = new TextDecoder().decode(lookupResultToBuffer(certificate.lookup([...path, 'reject_message'])));\n const error_code_buf = lookupResultToBuffer(certificate.lookup([...path, 'error_code']));\n const error_code = error_code_buf\n ? new TextDecoder().decode(error_code_buf)\n : undefined;\n throw new UpdateCallRejectedError(cid, methodName, requestId, response, rejectCode, rejectMessage, 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;\n throw new UpdateCallRejectedError(cid, methodName, requestId, response, reject_code, reject_message, error_code);\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 const httpDetails = Object.assign(Object.assign({}, response), { requestDetails });\n if (reply !== undefined) {\n if (shouldIncludeHttpDetails && shouldIncludeCertificate) {\n return {\n httpDetails,\n certificate,\n result: decodeReturnValue(func.retTypes, reply),\n };\n }\n else if (shouldIncludeCertificate) {\n return {\n certificate,\n result: decodeReturnValue(func.retTypes, reply),\n };\n }\n else if (shouldIncludeHttpDetails) {\n return {\n httpDetails,\n result: decodeReturnValue(func.retTypes, reply),\n };\n }\n return decodeReturnValue(func.retTypes, reply);\n }\n else if (func.retTypes.length === 0) {\n return shouldIncludeHttpDetails\n ? {\n httpDetails: response,\n result: undefined,\n }\n : undefined;\n }\n else {\n throw new Error(`Call was returned undefined, but type [${func.retTypes.join(',')}].`);\n }\n };\n }\n const handler = (...args) => caller({}, ...args);\n handler.withOptions =\n (options) => (...args) => caller(options, ...args);\n return handler;\n}\n/**\n * Create a management canister actor\n * @param config - a CallConfig\n */\nexport function getManagementCanister(config) {\n function transform(methodName, args) {\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);\n }\n return { effectiveCanisterId };\n }\n return Actor.createActor(managementCanisterIdl, Object.assign(Object.assign(Object.assign({}, config), { canisterId: Principal.fromHex('') }), {\n callTransform: transform,\n queryTransform: transform,\n }));\n}\nexport class AdvancedActor extends Actor {\n constructor(metadata) {\n super(metadata);\n }\n}\n//# sourceMappingURL=actor.js.map","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","export var AuthProvider;\n(function (AuthProvider) {\n AuthProvider[\"II\"] = \"Internet Identity\";\n AuthProvider[\"EMAIL\"] = \"Email\";\n AuthProvider[\"ETH\"] = \"Ethereum\";\n AuthProvider[\"SOL\"] = \"Solana\";\n AuthProvider[\"NFID\"] = \"Google via NFID\";\n AuthProvider[\"PASSKEY\"] = \"Passkey\";\n})(AuthProvider || (AuthProvider = {}));\nexport class InMemoryAuthClientStorage {\n constructor() {\n this._map = new Map();\n }\n get(key) {\n return Promise.resolve(this._map.get(key) ?? null);\n }\n set(key, value) {\n this._map.set(key, value);\n return Promise.resolve();\n }\n remove(key) {\n this._map.delete(key);\n return Promise.resolve();\n }\n}\n","/**\n * Codes used by the replica for rejecting a message.\n * See {@link https://sdk.dfinity.org/docs/interface-spec/#reject-codes | the interface spec}.\n */\nexport var ReplicaRejectCode;\n(function (ReplicaRejectCode) {\n ReplicaRejectCode[ReplicaRejectCode[\"SysFatal\"] = 1] = \"SysFatal\";\n ReplicaRejectCode[ReplicaRejectCode[\"SysTransient\"] = 2] = \"SysTransient\";\n ReplicaRejectCode[ReplicaRejectCode[\"DestinationInvalid\"] = 3] = \"DestinationInvalid\";\n ReplicaRejectCode[ReplicaRejectCode[\"CanisterReject\"] = 4] = \"CanisterReject\";\n ReplicaRejectCode[ReplicaRejectCode[\"CanisterError\"] = 5] = \"CanisterError\";\n})(ReplicaRejectCode || (ReplicaRejectCode = {}));\n//# sourceMappingURL=api.js.map","export function bigIntMax(...args) {\n return args.reduce((m, e) => (e > m ? e : m));\n}\nexport function bigIntMin(...args) {\n return args.reduce((m, e) => (e < m ? e : m));\n}\nexport function toBigInt32(value) {\n return BigInt(value) % BigInt(4294967296);\n}\nexport function toBigInt64(value) {\n return BigInt(value) % BigInt(\"18446744073709551616\");\n}\nexport function numberToBigInt(value) {\n return BigInt(Math.trunc(value));\n}\nconst integerRegex = /^-?[0-9]+$/;\nexport function parseBigInt(value) {\n if (value == null)\n return undefined;\n if (value.length === 0)\n return BigInt(0);\n return integerRegex.test(value) ? BigInt(value) : undefined;\n}\n","import { extractUserIdsFromMentions, UnsupportedValueError } from \"../domain\";\nexport function userIdsFromTransactions(transactions) {\n return transactions.reduce((userIds, t) => {\n // these are not necessarily userIds, but they *might* be\n if (t.from !== undefined) {\n userIds.add(t.from);\n }\n if (t.to !== undefined) {\n userIds.add(t.to);\n }\n return userIds;\n }, new Set());\n}\nexport function userIdsFromEvents(events) {\n const fakeFormatter = (k) => k;\n return events.reduce((userIds, e) => {\n if (\"userIds\" in e.event) {\n e.event.userIds.forEach((u) => userIds.add(u));\n }\n switch (e.event.kind) {\n case \"message\":\n userIds.add(e.event.sender);\n if (e.event.repliesTo !== undefined &&\n e.event.repliesTo.kind === \"rehydrated_reply_context\") {\n userIds.add(e.event.repliesTo.senderId);\n extractUserIdsFromMentions(getContentAsFormattedText(fakeFormatter, e.event.repliesTo.content, {})).forEach((id) => userIds.add(id));\n }\n if (e.event.content.kind === \"crypto_content\") {\n userIds.add(e.event.content.transfer.recipient);\n }\n else if (e.event.content.kind === \"reported_message_content\") {\n e.event.content.reports.forEach((r) => userIds.add(r.reportedBy));\n }\n else if (e.event.content.kind === \"prize_winner_content\") {\n userIds.add(e.event.content.transaction.recipient);\n }\n e.event.reactions.forEach((r) => r.userIds.forEach((u) => userIds.add(u)));\n extractUserIdsFromMentions(getContentAsFormattedText(fakeFormatter, e.event.content, {})).forEach((id) => userIds.add(id));\n break;\n case \"member_joined\":\n case \"member_left\":\n userIds.add(e.event.userId);\n break;\n case \"name_changed\":\n case \"desc_changed\":\n case \"rules_changed\":\n case \"avatar_changed\":\n case \"role_changed\":\n case \"permissions_changed\":\n case \"group_visibility_changed\":\n case \"group_invite_code_changed\":\n userIds.add(e.event.changedBy);\n break;\n case \"group_chat_created\":\n userIds.add(e.event.created_by);\n break;\n case \"members_added\":\n userIds.add(e.event.addedBy);\n break;\n case \"members_removed\":\n userIds.add(e.event.removedBy);\n break;\n case \"users_blocked\":\n userIds.add(e.event.blockedBy);\n break;\n case \"users_unblocked\":\n userIds.add(e.event.unblockedBy);\n break;\n case \"message_pinned\":\n userIds.add(e.event.pinnedBy);\n break;\n case \"message_unpinned\":\n userIds.add(e.event.unpinnedBy);\n break;\n case \"events_ttl_updated\":\n case \"external_url_updated\":\n case \"gate_updated\":\n userIds.add(e.event.updatedBy);\n break;\n case \"users_invited\":\n userIds.add(e.event.invitedBy);\n e.event.userIds.forEach((id) => userIds.add(id));\n break;\n case \"chat_frozen\":\n userIds.add(e.event.frozenBy);\n break;\n case \"chat_unfrozen\":\n userIds.add(e.event.unfrozenBy);\n break;\n case \"bot_added\":\n userIds.add(e.event.userId);\n userIds.add(e.event.addedBy);\n break;\n case \"bot_removed\":\n userIds.add(e.event.removedBy);\n break;\n case \"bot_updated\":\n userIds.add(e.event.userId);\n userIds.add(e.event.updatedBy);\n break;\n case \"aggregate_common_events\":\n case \"direct_chat_created\":\n case \"empty\":\n case \"members_added_to_default_channel\":\n break;\n default:\n console.warn(\"Unexpected ChatEvent type received\", e.event);\n }\n return userIds;\n }, new Set());\n}\nexport function getContentAsFormattedText(formatter, content, cryptoLookup) {\n let text;\n if (content.kind === \"text_content\") {\n text = content.text;\n }\n else if (content.kind === \"image_content\") {\n text = captionedContent(\"image\", content.caption);\n }\n else if (content.kind === \"video_content\") {\n text = captionedContent(\"video\", content.caption);\n }\n else if (content.kind === \"audio_content\") {\n text = captionedContent(\"audio\", content.caption);\n }\n else if (content.kind === \"file_content\") {\n text = captionedContent(content.name, content.caption);\n }\n else if (content.kind === \"crypto_content\") {\n text = captionedContent(formatter(\"tokenTransfer.transfer\", {\n values: { token: cryptoLookup[content.transfer.ledger]?.symbol ?? \"Unknown\" },\n }), content.caption);\n }\n else if (content.kind === \"deleted_content\" || content.kind === \"blocked_content\") {\n text = \"deleted message\";\n }\n else if (content.kind === \"placeholder_content\") {\n text = \"placeholder content\";\n }\n else if (content.kind === \"bot_placeholder_content\") {\n text = \"Bot working ...\";\n }\n else if (content.kind === \"poll_content\") {\n text = content.config.text ?? \"poll\";\n }\n else if (content.kind === \"proposal_content\") {\n text = content.proposal.title;\n }\n else if (content.kind === \"giphy_content\") {\n text = captionedContent(formatter(\"giphyMessage\"), content.caption);\n }\n else if (content.kind === \"p2p_swap_content\" || content.kind === \"p2p_swap_content_initial\") {\n text = captionedContent(\"p2p swap\", content.caption);\n }\n else if (content.kind === \"prize_content\" || content.kind === \"prize_content_initial\") {\n text = captionedContent(formatter(\"prizeMessage\"), content.caption);\n }\n else if (content.kind === \"prize_winner_content\") {\n text = \"Prize winner message\";\n }\n else if (content.kind === \"message_reminder_content\") {\n text = content.notes ?? \"Message reminder\";\n }\n else if (content.kind === \"message_reminder_created_content\") {\n text = content.notes ?? \"Message reminder\";\n }\n else if (content.kind === \"user_referral_card\") {\n text = formatter(\"referralHeader\");\n }\n else if (content.kind === \"reported_message_content\") {\n text = \"Reported message\";\n }\n else if (content.kind === \"meme_fighter_content\") {\n text = \"Meme Fighter message\";\n }\n else if (content.kind === \"video_call_content\") {\n text = \"Video call\";\n }\n else {\n throw new UnsupportedValueError(\"Unrecognised content type\", content);\n }\n return text.trim();\n}\nexport function getContentAsText(content) {\n if (\"text\" in content) {\n return content.text;\n }\n else if (\"caption\" in content) {\n return content.caption;\n }\n else if (content.kind === \"poll_content\") {\n return content.config.text;\n }\n}\nfunction captionedContent(type, caption) {\n if (caption) {\n return type + \" - \" + caption;\n }\n else {\n return type;\n }\n}\nexport function indexRangeForChat(chat) {\n return [getMinVisibleEventIndex(chat), chat.latestEventIndex];\n}\nexport function getMinVisibleEventIndex(chat) {\n if (chat.kind === \"direct_chat\")\n return 0;\n return chat.minVisibleEventIndex;\n}\nexport function getDisplayDate(chat) {\n let latestUpdate = BigInt(0);\n switch (chat.kind) {\n case \"direct_chat\":\n latestUpdate = chat.dateCreated;\n break;\n case \"group_chat\":\n case \"channel\":\n if (chat.membership?.joined !== undefined) {\n latestUpdate = chat.membership.joined;\n }\n break;\n }\n if (chat.latestMessage !== undefined && chat.latestMessage.timestamp > latestUpdate) {\n latestUpdate = chat.latestMessage.timestamp;\n }\n if (chat.eventsTtlLastUpdated > latestUpdate) {\n latestUpdate = chat.eventsTtlLastUpdated;\n }\n return latestUpdate;\n}\nexport function compareChats(a, b) {\n return Number(getDisplayDate(b) - getDisplayDate(a));\n}\nexport function emptyChatMetrics() {\n return {\n audioMessages: 0,\n edits: 0,\n icpMessages: 0,\n sns1Messages: 0,\n ckbtcMessages: 0,\n giphyMessages: 0,\n deletedMessages: 0,\n reportedMessages: 0,\n fileMessages: 0,\n pollVotes: 0,\n textMessages: 0,\n imageMessages: 0,\n replies: 0,\n videoMessages: 0,\n polls: 0,\n reactions: 0,\n };\n}\nexport function emptyRules() {\n return {\n text: \"\",\n enabled: false,\n version: 0,\n };\n}\nexport function compareRoles(a, b) {\n if (a === b)\n return 0;\n if (a === \"owner\")\n return 1;\n if (b === \"owner\")\n return -1;\n if (a === \"admin\")\n return 1;\n if (b === \"admin\")\n return -1;\n if (a === \"moderator\")\n return 1;\n if (b === \"moderator\")\n return -1;\n if (a === \"member\")\n return 1;\n return -1;\n}\nexport function routeForMessage(scope, ctx, messageIndex) {\n return ctx.threadRootMessageIndex === undefined\n ? `${routeForMessageContext(scope, ctx)}/${messageIndex}`\n : `${routeForMessageContext(scope, ctx)}/${messageIndex}?open=true`;\n}\nexport function routeForMessageContext(scope, { chatId, threadRootMessageIndex }, open = false) {\n return threadRootMessageIndex === undefined\n ? routeForChatIdentifier(scope, chatId)\n : `${routeForChatIdentifier(scope, chatId)}/${threadRootMessageIndex}${open ? \"?open=true\" : \"\"}`;\n}\nexport function routeForChatIdentifier(scope, id) {\n const prefix = scope === \"favourite\" ? \"/favourite\" : \"\";\n switch (id.kind) {\n case \"direct_chat\":\n return `${prefix}/user/${id.userId}`;\n case \"group_chat\":\n return `${prefix}/group/${id.groupId}`;\n case \"channel\":\n return `${prefix}/community/${id.communityId}/channel/${id.channelId}`;\n }\n}\nexport function chatIdentifierToString(chatId) {\n switch (chatId.kind) {\n case \"direct_chat\":\n return chatId.userId;\n case \"group_chat\":\n return chatId.groupId;\n case \"channel\":\n return `${chatId.communityId}_${chatId.channelId}`;\n default:\n throw new UnsupportedValueError(\"Unknown chatId kind\", chatId);\n }\n}\nexport function contentTypeToPermission(contentType) {\n switch (contentType) {\n case \"image_content\":\n return \"image\";\n case \"video_content\":\n return \"video\";\n case \"audio_content\":\n return \"audio\";\n case \"file_content\":\n return \"file\";\n default:\n throw new UnsupportedValueError(\"Unknown attachment content type\", contentType);\n }\n}\nexport function mapAcceptP2PSwapResponseToStatus(response, userId) {\n switch (response.kind) {\n case \"success\":\n return {\n kind: \"p2p_swap_accepted\",\n acceptedBy: userId,\n token1TxnIn: response.token1TxnIn,\n };\n case \"already_reserved\":\n return {\n kind: \"p2p_swap_reserved\",\n reservedBy: response.reservedBy,\n };\n case \"already_accepted\":\n return {\n kind: \"p2p_swap_accepted\",\n acceptedBy: response.acceptedBy,\n token1TxnIn: response.token1TxnIn,\n };\n case \"already_completed\":\n return {\n kind: \"p2p_swap_completed\",\n acceptedBy: response.acceptedBy,\n token1TxnIn: response.token1TxnIn,\n token0TxnOut: response.token0TxnOut,\n token1TxnOut: response.token1TxnOut,\n };\n case \"swap_cancelled\":\n return {\n kind: \"p2p_swap_cancelled\",\n token0TxnOut: response.token0TxnOut,\n };\n case \"swap_expired\":\n return {\n kind: \"p2p_swap_expired\",\n token0TxnOut: response.token0TxnOut,\n };\n default:\n return {\n kind: \"p2p_swap_open\",\n };\n }\n}\nexport function mapCancelP2PSwapResponseToStatus(response) {\n switch (response.kind) {\n case \"success\":\n return {\n kind: \"p2p_swap_cancelled\",\n };\n case \"already_reserved\":\n return {\n kind: \"p2p_swap_reserved\",\n reservedBy: response.reservedBy,\n };\n case \"already_accepted\":\n return {\n kind: \"p2p_swap_accepted\",\n acceptedBy: response.acceptedBy,\n token1TxnIn: response.token1TxnIn,\n };\n case \"already_completed\":\n return {\n kind: \"p2p_swap_completed\",\n acceptedBy: response.acceptedBy,\n token1TxnIn: response.token1TxnIn,\n token0TxnOut: response.token0TxnOut,\n token1TxnOut: response.token1TxnOut,\n };\n case \"swap_cancelled\":\n return {\n kind: \"p2p_swap_cancelled\",\n token0TxnOut: response.token0TxnOut,\n };\n case \"swap_expired\":\n return {\n kind: \"p2p_swap_expired\",\n token0TxnOut: response.token0TxnOut,\n };\n default:\n return {\n kind: \"p2p_swap_open\",\n };\n }\n}\n","const alphabet = 'abcdefghijklmnopqrstuvwxyz234567';\n// Build a lookup table for decoding.\nconst lookupTable = Object.create(null);\nfor (let i = 0; i < alphabet.length; i++) {\n lookupTable[alphabet[i]] = i;\n}\n// Add aliases for rfc4648.\nlookupTable['0'] = lookupTable.o;\nlookupTable['1'] = lookupTable.i;\n/**\n * @param input The input array to encode.\n * @returns A Base32 string encoding the input.\n */\nexport function encode(input) {\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 // The output string in base32.\n let output = '';\n function encodeByte(byte) {\n if (skip < 0) {\n // we have a carry from the previous byte\n bits |= byte >> -skip;\n }\n else {\n // no carry\n bits = (byte << skip) & 248;\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 if (skip < 4) {\n // produce a character\n output += alphabet[bits >> 3];\n skip += 5;\n }\n return 0;\n }\n for (let i = 0; i < input.length;) {\n i += encodeByte(input[i]);\n }\n return output + (skip < 0 ? alphabet[bits >> 3] : '');\n}\n/**\n * @param input The base32 encoded string to decode.\n */\nexport function decode(input) {\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 const output = new Uint8Array(((input.length * 4) / 3) | 0);\n let o = 0;\n function decodeChar(char) {\n // Consume a character from the stream, store\n // the output in this.output. As before, better\n // to use update().\n let val = lookupTable[char.toLowerCase()];\n if (val === undefined) {\n throw new Error(`Invalid character: ${JSON.stringify(char)}`);\n }\n // move to the high bits\n val <<= 3;\n byte |= val >>> skip;\n skip += 5;\n if (skip >= 8) {\n // We have enough bytes to produce an output\n output[o++] = byte;\n skip -= 8;\n if (skip > 0) {\n byte = (val << (5 - skip)) & 255;\n }\n else {\n byte = 0;\n }\n }\n }\n for (const c of input) {\n decodeChar(c);\n }\n return output.slice(0, o);\n}\n//# sourceMappingURL=base32.js.map","// This file is translated to JavaScript from\n// https://lxp32.github.io/docs/a-simple-example-crc32-calculation/\nconst lookUpTable = new Uint32Array([\n 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,\n 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,\n 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,\n 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,\n 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,\n 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,\n 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,\n 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,\n 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,\n 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,\n 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,\n 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,\n 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,\n 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,\n 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,\n 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,\n 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,\n 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,\n 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,\n 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,\n 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,\n 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,\n 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,\n 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,\n 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,\n 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,\n 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,\n 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,\n 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,\n 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,\n 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,\n 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,\n]);\n/**\n * Calculate the CRC32 of an ArrayBufferLike.\n * @param buf The BufferLike to calculate the CRC32 of.\n */\nexport function getCrc32(buf) {\n const b = new Uint8Array(buf);\n let crc = -1;\n for (let i = 0; i < b.length; i++) {\n const byte = b[i];\n const t = (byte ^ crc) & 0xff;\n crc = lookUpTable[t] ^ (crc >>> 8);\n }\n return (crc ^ -1) >>> 0;\n}\n//# sourceMappingURL=getCrc.js.map","import { decode, encode } from './utils/base32';\nimport { getCrc32 } from './utils/getCrc';\nimport { sha224 } from './utils/sha224';\nexport const JSON_KEY_PRINCIPAL = '__principal__';\nconst SELF_AUTHENTICATING_SUFFIX = 2;\nconst ANONYMOUS_SUFFIX = 4;\nconst MANAGEMENT_CANISTER_PRINCIPAL_HEX_STR = 'aaaaa-aa';\nconst fromHexString = (hexString) => { var _a; return new Uint8Array(((_a = hexString.match(/.{1,2}/g)) !== null && _a !== void 0 ? _a : []).map(byte => parseInt(byte, 16))); };\nconst toHexString = (bytes) => bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\nexport class Principal {\n constructor(_arr) {\n this._arr = _arr;\n this._isPrincipal = true;\n }\n static anonymous() {\n return new this(new Uint8Array([ANONYMOUS_SUFFIX]));\n }\n /**\n * Utility method, returning the principal representing the management canister, decoded from the hex string `'aaaaa-aa'`\n * @returns {Principal} principal of the management canister\n */\n static managementCanister() {\n return this.fromHex(MANAGEMENT_CANISTER_PRINCIPAL_HEX_STR);\n }\n static selfAuthenticating(publicKey) {\n const sha = sha224(publicKey);\n return new this(new Uint8Array([...sha, SELF_AUTHENTICATING_SUFFIX]));\n }\n static from(other) {\n if (typeof other === 'string') {\n return Principal.fromText(other);\n }\n else if (Object.getPrototypeOf(other) === Uint8Array.prototype) {\n return new Principal(other);\n }\n else if (typeof other === 'object' &&\n other !== null &&\n other._isPrincipal === true) {\n return new Principal(other._arr);\n }\n throw new Error(`Impossible to convert ${JSON.stringify(other)} to Principal.`);\n }\n static fromHex(hex) {\n return new this(fromHexString(hex));\n }\n static fromText(text) {\n let maybePrincipal = text;\n // If formatted as JSON string, parse it first\n if (text.includes(JSON_KEY_PRINCIPAL)) {\n const obj = JSON.parse(text);\n if (JSON_KEY_PRINCIPAL in obj) {\n maybePrincipal = obj[JSON_KEY_PRINCIPAL];\n }\n }\n const canisterIdNoDash = maybePrincipal.toLowerCase().replace(/-/g, '');\n let arr = decode(canisterIdNoDash);\n arr = arr.slice(4, arr.length);\n const principal = new this(arr);\n if (principal.toText() !== maybePrincipal) {\n throw new Error(`Principal \"${principal.toText()}\" does not have a valid checksum (original value \"${maybePrincipal}\" may not be a valid Principal ID).`);\n }\n return principal;\n }\n static fromUint8Array(arr) {\n return new this(arr);\n }\n isAnonymous() {\n return this._arr.byteLength === 1 && this._arr[0] === ANONYMOUS_SUFFIX;\n }\n toUint8Array() {\n return this._arr;\n }\n toHex() {\n return toHexString(this._arr).toUpperCase();\n }\n toText() {\n const checksumArrayBuf = new ArrayBuffer(4);\n const view = new DataView(checksumArrayBuf);\n view.setUint32(0, getCrc32(this._arr));\n const checksum = new Uint8Array(checksumArrayBuf);\n const bytes = Uint8Array.from(this._arr);\n const array = new Uint8Array([...checksum, ...bytes]);\n const result = encode(array);\n const matches = result.match(/.{1,5}/g);\n if (!matches) {\n // This should only happen if there's no character, which is unreachable.\n throw new Error();\n }\n return matches.join('-');\n }\n toString() {\n return this.toText();\n }\n /**\n * Serializes to JSON\n * @returns {JsonnablePrincipal} a JSON object with a single key, {@link JSON_KEY_PRINCIPAL}, whose value is the principal as a string\n */\n toJSON() {\n return { [JSON_KEY_PRINCIPAL]: this.toText() };\n }\n /**\n * Utility method taking a Principal to compare against. Used for determining canister ranges in certificate verification\n * @param {Principal} other - a {@link Principal} to compare\n * @returns {'lt' | 'eq' | 'gt'} `'lt' | 'eq' | 'gt'` a string, representing less than, equal to, or greater than\n */\n compareTo(other) {\n for (let i = 0; i < Math.min(this._arr.length, other._arr.length); i++) {\n if (this._arr[i] < other._arr[i])\n return 'lt';\n else if (this._arr[i] > other._arr[i])\n return 'gt';\n }\n // Here, at least one principal is a prefix of the other principal (they could be the same)\n if (this._arr.length < other._arr.length)\n return 'lt';\n if (this._arr.length > other._arr.length)\n return 'gt';\n return 'eq';\n }\n /**\n * Utility method checking whether a provided Principal is less than or equal to the current one using the {@link Principal.compareTo} method\n * @param other a {@link Principal} to compare\n * @returns {boolean} boolean\n */\n ltEq(other) {\n const cmp = this.compareTo(other);\n return cmp == 'lt' || cmp == 'eq';\n }\n /**\n * Utility method checking whether a provided Principal is greater than or equal to the current one using the {@link Principal.compareTo} method\n * @param other a {@link Principal} to compare\n * @returns {boolean} boolean\n */\n gtEq(other) {\n const cmp = this.compareTo(other);\n return cmp == 'gt' || cmp == 'eq';\n }\n}\n//# sourceMappingURL=index.js.map","import { sha224 as jsSha224 } from '@noble/hashes/sha256';\n/**\n * Returns the SHA224 hash of the buffer.\n * @param data Arraybuffer to encode\n */\nexport function sha224(data) {\n return jsSha224.create().update(new Uint8Array(data)).digest();\n}\n//# sourceMappingURL=sha224.js.map","/**\n * Concatenate multiple array buffers.\n * @param buffers The buffers to concatenate.\n */\nexport function concat(...buffers) {\n const result = new Uint8Array(buffers.reduce((acc, curr) => acc + curr.byteLength, 0));\n let index = 0;\n for (const b of buffers) {\n result.set(new Uint8Array(b), index);\n index += b.byteLength;\n }\n return result.buffer;\n}\n/**\n * Transforms a buffer to an hexadecimal string. This will use the buffer as an Uint8Array.\n * @param buffer The buffer to return the hexadecimal string of.\n */\nexport function toHex(buffer) {\n return [...new Uint8Array(buffer)].map(x => x.toString(16).padStart(2, '0')).join('');\n}\nconst hexRe = new RegExp(/^[0-9a-fA-F]+$/);\n/**\n * Transforms a hexadecimal string into an array buffer.\n * @param hex The hexadecimal string to use.\n */\nexport function fromHex(hex) {\n if (!hexRe.test(hex)) {\n throw new Error('Invalid hexadecimal string.');\n }\n const buffer = [...hex]\n .reduce((acc, curr, i) => {\n acc[(i / 2) | 0] = (acc[(i / 2) | 0] || '') + curr;\n return acc;\n }, [])\n .map(x => Number.parseInt(x, 16));\n return new Uint8Array(buffer).buffer;\n}\n/**\n *\n * @param b1 array buffer 1\n * @param b2 array buffer 2\n * @returns number - negative if b1 < b2, positive if b1 > b2, 0 if b1 === b2\n */\nexport function compare(b1, b2) {\n if (b1.byteLength !== b2.byteLength) {\n return b1.byteLength - b2.byteLength;\n }\n const u1 = new Uint8Array(b1);\n const u2 = new Uint8Array(b2);\n for (let i = 0; i < u1.length; i++) {\n if (u1[i] !== u2[i]) {\n return u1[i] - u2[i];\n }\n }\n return 0;\n}\n/**\n * Checks two array buffers for equality.\n * @param b1 array buffer 1\n * @param b2 array buffer 2\n * @returns boolean\n */\nexport function bufEquals(b1, b2) {\n return compare(b1, b2) === 0;\n}\n/**\n * Returns a true ArrayBuffer from a Uint8Array, as Uint8Array.buffer is unsafe.\n * @param {Uint8Array} arr Uint8Array to convert\n * @returns ArrayBuffer\n */\nexport function uint8ToBuf(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength).buffer;\n}\n/**\n * Returns a true ArrayBuffer from an ArrayBufferLike object.\n * @param bufLike a buffer-like object\n * @returns ArrayBuffer\n */\nexport function bufFromBufLike(bufLike) {\n if (bufLike instanceof Uint8Array) {\n return uint8ToBuf(bufLike);\n }\n if (bufLike instanceof ArrayBuffer) {\n return bufLike;\n }\n if (Array.isArray(bufLike)) {\n return uint8ToBuf(new Uint8Array(bufLike));\n }\n if ('buffer' in bufLike) {\n return bufFromBufLike(bufLike.buffer);\n }\n return uint8ToBuf(new Uint8Array(bufLike));\n}\n//# sourceMappingURL=buffer.js.map","/**\n * Concatenate multiple array buffers.\n * @param buffers The buffers to concatenate.\n */\nexport function concat(...buffers) {\n const result = new Uint8Array(buffers.reduce((acc, curr) => acc + curr.byteLength, 0));\n let index = 0;\n for (const b of buffers) {\n result.set(new Uint8Array(b), index);\n index += b.byteLength;\n }\n return result;\n}\n/**\n * Returns an hexadecimal representation of an array buffer.\n * @param bytes The array buffer.\n */\nexport function toHexString(bytes) {\n return new Uint8Array(bytes).reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');\n}\n/**\n * Return an array buffer from its hexadecimal representation.\n * @param hexString The hexadecimal string.\n */\nexport function fromHexString(hexString) {\n var _a;\n return new Uint8Array(((_a = hexString.match(/.{1,2}/g)) !== null && _a !== void 0 ? _a : []).map(byte => parseInt(byte, 16)));\n}\n/**\n * A class that abstracts a pipe-like ArrayBuffer.\n */\nexport class PipeArrayBuffer {\n /**\n * Creates a new instance of a pipe\n * @param buffer an optional buffer to start with\n * @param length an optional amount of bytes to use for the length.\n */\n constructor(buffer, length = (buffer === null || buffer === void 0 ? void 0 : buffer.byteLength) || 0) {\n this._buffer = bufFromBufLike(buffer || new ArrayBuffer(0));\n this._view = new Uint8Array(this._buffer, 0, length);\n }\n get buffer() {\n // Return a copy of the buffer.\n return bufFromBufLike(this._view.slice());\n }\n get byteLength() {\n return this._view.byteLength;\n }\n /**\n * Read `num` number of bytes from the front of the pipe.\n * @param num The number of bytes to read.\n */\n read(num) {\n const result = this._view.subarray(0, num);\n this._view = this._view.subarray(num);\n return result.slice().buffer;\n }\n readUint8() {\n const result = this._view[0];\n this._view = this._view.subarray(1);\n return result;\n }\n /**\n * Write a buffer to the end of the pipe.\n * @param buf The bytes to write.\n */\n write(buf) {\n const b = new Uint8Array(buf);\n const offset = this._view.byteLength;\n if (this._view.byteOffset + this._view.byteLength + b.byteLength >= this._buffer.byteLength) {\n // Alloc grow the view to include the new bytes.\n this.alloc(b.byteLength);\n }\n else {\n // Update the view to include the new bytes.\n this._view = new Uint8Array(this._buffer, this._view.byteOffset, this._view.byteLength + b.byteLength);\n }\n this._view.set(b, offset);\n }\n /**\n * Whether or not there is more data to read from the buffer\n */\n get end() {\n return this._view.byteLength === 0;\n }\n /**\n * Allocate a fixed amount of memory in the buffer. This does not affect the view.\n * @param amount A number of bytes to add to the buffer.\n */\n alloc(amount) {\n // Add a little bit of exponential growth.\n const b = new ArrayBuffer(((this._buffer.byteLength + amount) * 1.2) | 0);\n const v = new Uint8Array(b, 0, this._view.byteLength + amount);\n v.set(this._view);\n this._buffer = b;\n this._view = v;\n }\n}\n/**\n * Returns a true ArrayBuffer from a Uint8Array, as Uint8Array.buffer is unsafe.\n * @param {Uint8Array} arr Uint8Array to convert\n * @returns ArrayBuffer\n */\nexport function uint8ToBuf(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength).buffer;\n}\n/**\n * Returns a true ArrayBuffer from an ArrayBufferLike object.\n * @param bufLike a buffer-like object\n * @returns ArrayBuffer\n */\nexport function bufFromBufLike(bufLike) {\n if (bufLike instanceof Uint8Array) {\n return uint8ToBuf(bufLike);\n }\n if (bufLike instanceof ArrayBuffer) {\n return bufLike;\n }\n if (Array.isArray(bufLike)) {\n return uint8ToBuf(new Uint8Array(bufLike));\n }\n if ('buffer' in bufLike) {\n return bufFromBufLike(bufLike.buffer);\n }\n return uint8ToBuf(new Uint8Array(bufLike));\n}\n//# sourceMappingURL=buffer.js.map","/* eslint-disable no-constant-condition */\n// Note: this file uses buffer-pipe, which on Node only, uses the Node Buffer\n// implementation, which isn't compatible with the NPM buffer package\n// which we use everywhere else. This means that we have to transform\n// one into the other, hence why every function that returns a Buffer\n// actually return `new Buffer(pipe.buffer)`.\n// TODO: The best solution would be to have our own buffer type around\n// Uint8Array which is standard.\nimport { PipeArrayBuffer as Pipe } from './buffer';\nfunction eob() {\n throw new Error('unexpected end of buffer');\n}\n/**\n *\n * @param pipe Pipe from buffer-pipe\n * @param num number\n * @returns Buffer\n */\nexport function safeRead(pipe, num) {\n if (pipe.byteLength < num) {\n eob();\n }\n return pipe.read(num);\n}\n/**\n * @param pipe - PipeArrayBuffer simulating buffer-pipe api\n */\nexport function safeReadUint8(pipe) {\n const byte = pipe.readUint8();\n if (byte === undefined) {\n eob();\n }\n return byte;\n}\n/**\n * Encode a positive number (or bigint) into a Buffer. The number will be floored to the\n * nearest integer.\n * @param value The number to encode.\n */\nexport function lebEncode(value) {\n if (typeof value === 'number') {\n value = BigInt(value);\n }\n if (value < BigInt(0)) {\n throw new Error('Cannot leb encode negative values.');\n }\n const byteLength = (value === BigInt(0) ? 0 : Math.ceil(Math.log2(Number(value)))) + 1;\n const pipe = new Pipe(new ArrayBuffer(byteLength), 0);\n while (true) {\n const i = Number(value & BigInt(0x7f));\n value /= BigInt(0x80);\n if (value === BigInt(0)) {\n pipe.write(new Uint8Array([i]));\n break;\n }\n else {\n pipe.write(new Uint8Array([i | 0x80]));\n }\n }\n return pipe.buffer;\n}\n/**\n * Decode a leb encoded buffer into a bigint. The number will always be positive (does not\n * support signed leb encoding).\n * @param pipe A Buffer containing the leb encoded bits.\n */\nexport function lebDecode(pipe) {\n let weight = BigInt(1);\n let value = BigInt(0);\n let byte;\n do {\n byte = safeReadUint8(pipe);\n value += BigInt(byte & 0x7f).valueOf() * weight;\n weight *= BigInt(128);\n } while (byte >= 0x80);\n return value;\n}\n/**\n * Encode a number (or bigint) into a Buffer, with support for negative numbers. The number\n * will be floored to the nearest integer.\n * @param value The number to encode.\n */\nexport function slebEncode(value) {\n if (typeof value === 'number') {\n value = BigInt(value);\n }\n const isNeg = value < BigInt(0);\n if (isNeg) {\n value = -value - BigInt(1);\n }\n const byteLength = (value === BigInt(0) ? 0 : Math.ceil(Math.log2(Number(value)))) + 1;\n const pipe = new Pipe(new ArrayBuffer(byteLength), 0);\n while (true) {\n const i = getLowerBytes(value);\n value /= BigInt(0x80);\n // prettier-ignore\n if ((isNeg && value === BigInt(0) && (i & 0x40) !== 0)\n || (!isNeg && value === BigInt(0) && (i & 0x40) === 0)) {\n pipe.write(new Uint8Array([i]));\n break;\n }\n else {\n pipe.write(new Uint8Array([i | 0x80]));\n }\n }\n function getLowerBytes(num) {\n const bytes = num % BigInt(0x80);\n if (isNeg) {\n // We swap the bits here again, and remove 1 to do two's complement.\n return Number(BigInt(0x80) - bytes - BigInt(1));\n }\n else {\n return Number(bytes);\n }\n }\n return pipe.buffer;\n}\n/**\n * Decode a leb encoded buffer into a bigint. The number is decoded with support for negative\n * signed-leb encoding.\n * @param pipe A Buffer containing the signed leb encoded bits.\n */\nexport function slebDecode(pipe) {\n // Get the size of the buffer, then cut a buffer of that size.\n const pipeView = new Uint8Array(pipe.buffer);\n let len = 0;\n for (; len < pipeView.byteLength; len++) {\n if (pipeView[len] < 0x80) {\n // If it's a positive number, we reuse lebDecode.\n if ((pipeView[len] & 0x40) === 0) {\n return lebDecode(pipe);\n }\n break;\n }\n }\n const bytes = new Uint8Array(safeRead(pipe, len + 1));\n let value = BigInt(0);\n for (let i = bytes.byteLength - 1; i >= 0; i--) {\n value = value * BigInt(0x80) + BigInt(0x80 - (bytes[i] & 0x7f) - 1);\n }\n return -value - BigInt(1);\n}\n/**\n *\n * @param value bigint or number\n * @param byteLength number\n * @returns Buffer\n */\nexport function writeUIntLE(value, byteLength) {\n if (BigInt(value) < BigInt(0)) {\n throw new Error('Cannot write negative values.');\n }\n return writeIntLE(value, byteLength);\n}\n/**\n *\n * @param value - bigint or number\n * @param byteLength - number\n * @returns ArrayBuffer\n */\nexport function writeIntLE(value, byteLength) {\n value = BigInt(value);\n const pipe = new Pipe(new ArrayBuffer(Math.min(1, byteLength)), 0);\n let i = 0;\n let mul = BigInt(256);\n let sub = BigInt(0);\n let byte = Number(value % mul);\n pipe.write(new Uint8Array([byte]));\n while (++i < byteLength) {\n if (value < 0 && sub === BigInt(0) && byte !== 0) {\n sub = BigInt(1);\n }\n byte = Number((value / mul - sub) % BigInt(256));\n pipe.write(new Uint8Array([byte]));\n mul *= BigInt(256);\n }\n return pipe.buffer;\n}\n/**\n *\n * @param pipe Pipe from buffer-pipe\n * @param byteLength number\n * @returns bigint\n */\nexport function readUIntLE(pipe, byteLength) {\n let val = BigInt(safeReadUint8(pipe));\n let mul = BigInt(1);\n let i = 0;\n while (++i < byteLength) {\n mul *= BigInt(256);\n const byte = BigInt(safeReadUint8(pipe));\n val = val + mul * byte;\n }\n return val;\n}\n/**\n *\n * @param pipe Pipe from buffer-pipe\n * @param byteLength number\n * @returns bigint\n */\nexport function readIntLE(pipe, byteLength) {\n let val = readUIntLE(pipe, byteLength);\n const mul = BigInt(2) ** (BigInt(8) * BigInt(byteLength - 1) + BigInt(7));\n if (val >= mul) {\n val -= mul * BigInt(2);\n }\n return val;\n}\n//# sourceMappingURL=leb128.js.map","/**\n * Equivalent to `Math.log2(n)` with support for `BigInt` values\n * @param n bigint or integer\n * @returns integer\n */\nexport function ilog2(n) {\n const nBig = BigInt(n);\n if (n <= 0) {\n throw new RangeError('Input must be positive');\n }\n return nBig.toString(2).length - 1;\n}\n/**\n * Equivalent to `2 ** n` with support for `BigInt` values\n * (necessary for browser preprocessors which replace the `**` operator with `Math.pow`)\n * @param n bigint or integer\n * @returns bigint\n */\nexport function iexp2(n) {\n const nBig = BigInt(n);\n if (n < 0) {\n throw new RangeError('Input must be non-negative');\n }\n return BigInt(1) << nBig;\n}\n//# sourceMappingURL=bigint-math.js.map","/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Principal as PrincipalId } from '@dfinity/principal';\nimport { concat, PipeArrayBuffer as Pipe } from './utils/buffer';\nimport { idlLabelToId } from './utils/hash';\nimport { lebDecode, lebEncode, readIntLE, readUIntLE, safeRead, safeReadUint8, slebDecode, slebEncode, writeIntLE, writeUIntLE, } from './utils/leb128';\nimport { iexp2 } from './utils/bigint-math';\nconst magicNumber = 'DIDL';\nconst toReadableString_max = 400; // will not display arguments after 400chars. Makes sure 2mb blobs don't get inside the error\nfunction zipWith(xs, ys, f) {\n return xs.map((x, i) => f(x, ys[i]));\n}\n/**\n * An IDL Type Table, which precedes the data in the stream.\n */\nclass TypeTable {\n constructor() {\n // List of types. Needs to be an array as the index needs to be stable.\n this._typs = [];\n this._idx = new Map();\n }\n has(obj) {\n return this._idx.has(obj.name);\n }\n add(type, buf) {\n const idx = this._typs.length;\n this._idx.set(type.name, idx);\n this._typs.push(buf);\n }\n merge(obj, knot) {\n const idx = this._idx.get(obj.name);\n const knotIdx = this._idx.get(knot);\n if (idx === undefined) {\n throw new Error('Missing type index for ' + obj);\n }\n if (knotIdx === undefined) {\n throw new Error('Missing type index for ' + knot);\n }\n this._typs[idx] = this._typs[knotIdx];\n // Delete the type.\n this._typs.splice(knotIdx, 1);\n this._idx.delete(knot);\n }\n encode() {\n const len = lebEncode(this._typs.length);\n const buf = concat(...this._typs);\n return concat(len, buf);\n }\n indexOf(typeName) {\n if (!this._idx.has(typeName)) {\n throw new Error('Missing type index for ' + typeName);\n }\n return slebEncode(this._idx.get(typeName) || 0);\n }\n}\nexport class Visitor {\n visitType(t, data) {\n throw new Error('Not implemented');\n }\n visitPrimitive(t, data) {\n return this.visitType(t, data);\n }\n visitEmpty(t, data) {\n return this.visitPrimitive(t, data);\n }\n visitBool(t, data) {\n return this.visitPrimitive(t, data);\n }\n visitNull(t, data) {\n return this.visitPrimitive(t, data);\n }\n visitReserved(t, data) {\n return this.visitPrimitive(t, data);\n }\n visitText(t, data) {\n return this.visitPrimitive(t, data);\n }\n visitNumber(t, data) {\n return this.visitPrimitive(t, data);\n }\n visitInt(t, data) {\n return this.visitNumber(t, data);\n }\n visitNat(t, data) {\n return this.visitNumber(t, data);\n }\n visitFloat(t, data) {\n return this.visitPrimitive(t, data);\n }\n visitFixedInt(t, data) {\n return this.visitNumber(t, data);\n }\n visitFixedNat(t, data) {\n return this.visitNumber(t, data);\n }\n visitPrincipal(t, data) {\n return this.visitPrimitive(t, data);\n }\n visitConstruct(t, data) {\n return this.visitType(t, data);\n }\n visitVec(t, ty, data) {\n return this.visitConstruct(t, data);\n }\n visitOpt(t, ty, data) {\n return this.visitConstruct(t, data);\n }\n visitRecord(t, fields, data) {\n return this.visitConstruct(t, data);\n }\n visitTuple(t, components, data) {\n const fields = components.map((ty, i) => [`_${i}_`, ty]);\n return this.visitRecord(t, fields, data);\n }\n visitVariant(t, fields, data) {\n return this.visitConstruct(t, data);\n }\n visitRec(t, ty, data) {\n return this.visitConstruct(ty, data);\n }\n visitFunc(t, data) {\n return this.visitConstruct(t, data);\n }\n visitService(t, data) {\n return this.visitConstruct(t, data);\n }\n}\n/**\n * Represents an IDL type.\n */\nexport class Type {\n /* Display type name */\n display() {\n return this.name;\n }\n valueToString(x) {\n return toReadableString(x);\n }\n /* Implement `T` in the IDL spec, only needed for non-primitive types */\n buildTypeTable(typeTable) {\n if (!typeTable.has(this)) {\n this._buildTypeTableImpl(typeTable);\n }\n }\n}\nexport class PrimitiveType extends Type {\n checkType(t) {\n if (this.name !== t.name) {\n throw new Error(`type mismatch: type on the wire ${t.name}, expect type ${this.name}`);\n }\n return t;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _buildTypeTableImpl(typeTable) {\n // No type table encoding for Primitive types.\n return;\n }\n}\nexport class ConstructType extends Type {\n checkType(t) {\n if (t instanceof RecClass) {\n const ty = t.getType();\n if (typeof ty === 'undefined') {\n throw new Error('type mismatch with uninitialized type');\n }\n return ty;\n }\n throw new Error(`type mismatch: type on the wire ${t.name}, expect type ${this.name}`);\n }\n encodeType(typeTable) {\n return typeTable.indexOf(this.name);\n }\n}\n/**\n * Represents an IDL Empty, a type which has no inhabitants.\n * Since no values exist for this type, it cannot be serialised or deserialised.\n * Result types like `Result` should always succeed.\n */\nexport class EmptyClass extends PrimitiveType {\n accept(v, d) {\n return v.visitEmpty(this, d);\n }\n covariant(x) {\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue() {\n throw new Error('Empty cannot appear as a function argument');\n }\n valueToString() {\n throw new Error('Empty cannot appear as a value');\n }\n encodeType() {\n return slebEncode(-17 /* IDLTypeIds.Empty */);\n }\n decodeValue() {\n throw new Error('Empty cannot appear as an output');\n }\n get name() {\n return 'empty';\n }\n}\n/**\n * Represents an IDL Unknown, a placeholder type for deserialization only.\n * When decoding a value as Unknown, all fields will be retained but the names are only available in\n * hashed form.\n * A deserialized unknown will offer it's actual type by calling the `type()` function.\n * Unknown cannot be serialized and attempting to do so will throw an error.\n */\nexport class UnknownClass extends Type {\n checkType(t) {\n throw new Error('Method not implemented for unknown.');\n }\n accept(v, d) {\n throw v.visitType(this, d);\n }\n covariant(x) {\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue() {\n throw new Error('Unknown cannot appear as a function argument');\n }\n valueToString() {\n throw new Error('Unknown cannot appear as a value');\n }\n encodeType() {\n throw new Error('Unknown cannot be serialized');\n }\n decodeValue(b, t) {\n let decodedValue = t.decodeValue(b, t);\n if (Object(decodedValue) !== decodedValue) {\n // decodedValue is primitive. Box it, otherwise we cannot add the type() function.\n // The type() function is important for primitives because otherwise we cannot tell apart the\n // different number types.\n decodedValue = Object(decodedValue);\n }\n let typeFunc;\n if (t instanceof RecClass) {\n typeFunc = () => t.getType();\n }\n else {\n typeFunc = () => t;\n }\n // Do not use 'decodedValue.type = typeFunc' because this would lead to an enumerable property\n // 'type' which means it would be serialized if the value would be candid encoded again.\n // This in turn leads to problems if the decoded value is a variant because these values are\n // only allowed to have a single property.\n Object.defineProperty(decodedValue, 'type', {\n value: typeFunc,\n writable: true,\n enumerable: false,\n configurable: true,\n });\n return decodedValue;\n }\n _buildTypeTableImpl() {\n throw new Error('Unknown cannot be serialized');\n }\n get name() {\n return 'Unknown';\n }\n}\n/**\n * Represents an IDL Bool\n */\nexport class BoolClass extends PrimitiveType {\n accept(v, d) {\n return v.visitBool(this, d);\n }\n covariant(x) {\n if (typeof x === 'boolean')\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n return new Uint8Array([x ? 1 : 0]);\n }\n encodeType() {\n return slebEncode(-2 /* IDLTypeIds.Bool */);\n }\n decodeValue(b, t) {\n this.checkType(t);\n switch (safeReadUint8(b)) {\n case 0:\n return false;\n case 1:\n return true;\n default:\n throw new Error('Boolean value out of range');\n }\n }\n get name() {\n return 'bool';\n }\n}\n/**\n * Represents an IDL Null\n */\nexport class NullClass extends PrimitiveType {\n accept(v, d) {\n return v.visitNull(this, d);\n }\n covariant(x) {\n if (x === null)\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue() {\n return new ArrayBuffer(0);\n }\n encodeType() {\n return slebEncode(-1 /* IDLTypeIds.Null */);\n }\n decodeValue(b, t) {\n this.checkType(t);\n return null;\n }\n get name() {\n return 'null';\n }\n}\n/**\n * Represents an IDL Reserved\n */\nexport class ReservedClass extends PrimitiveType {\n accept(v, d) {\n return v.visitReserved(this, d);\n }\n covariant(x) {\n return true;\n }\n encodeValue() {\n return new ArrayBuffer(0);\n }\n encodeType() {\n return slebEncode(-16 /* IDLTypeIds.Reserved */);\n }\n decodeValue(b, t) {\n if (t.name !== this.name) {\n t.decodeValue(b, t);\n }\n return null;\n }\n get name() {\n return 'reserved';\n }\n}\n/**\n * Represents an IDL Text\n */\nexport class TextClass extends PrimitiveType {\n accept(v, d) {\n return v.visitText(this, d);\n }\n covariant(x) {\n if (typeof x === 'string')\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n const buf = new TextEncoder().encode(x);\n const len = lebEncode(buf.byteLength);\n return concat(len, buf);\n }\n encodeType() {\n return slebEncode(-15 /* IDLTypeIds.Text */);\n }\n decodeValue(b, t) {\n this.checkType(t);\n const len = lebDecode(b);\n const buf = safeRead(b, Number(len));\n const decoder = new TextDecoder('utf8', { fatal: true });\n return decoder.decode(buf);\n }\n get name() {\n return 'text';\n }\n valueToString(x) {\n return '\"' + x + '\"';\n }\n}\n/**\n * Represents an IDL Int\n */\nexport class IntClass extends PrimitiveType {\n accept(v, d) {\n return v.visitInt(this, d);\n }\n covariant(x) {\n // We allow encoding of JavaScript plain numbers.\n // But we will always decode to bigint.\n if (typeof x === 'bigint' || Number.isInteger(x))\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n return slebEncode(x);\n }\n encodeType() {\n return slebEncode(-4 /* IDLTypeIds.Int */);\n }\n decodeValue(b, t) {\n this.checkType(t);\n return slebDecode(b);\n }\n get name() {\n return 'int';\n }\n valueToString(x) {\n return x.toString();\n }\n}\n/**\n * Represents an IDL Nat\n */\nexport class NatClass extends PrimitiveType {\n accept(v, d) {\n return v.visitNat(this, d);\n }\n covariant(x) {\n // We allow encoding of JavaScript plain numbers.\n // But we will always decode to bigint.\n if ((typeof x === 'bigint' && x >= BigInt(0)) || (Number.isInteger(x) && x >= 0))\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n return lebEncode(x);\n }\n encodeType() {\n return slebEncode(-3 /* IDLTypeIds.Nat */);\n }\n decodeValue(b, t) {\n this.checkType(t);\n return lebDecode(b);\n }\n get name() {\n return 'nat';\n }\n valueToString(x) {\n return x.toString();\n }\n}\n/**\n * Represents an IDL Float\n */\nexport class FloatClass extends PrimitiveType {\n constructor(_bits) {\n super();\n this._bits = _bits;\n if (_bits !== 32 && _bits !== 64) {\n throw new Error('not a valid float type');\n }\n }\n accept(v, d) {\n return v.visitFloat(this, d);\n }\n covariant(x) {\n if (typeof x === 'number' || x instanceof Number)\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n const buf = new ArrayBuffer(this._bits / 8);\n const view = new DataView(buf);\n if (this._bits === 32) {\n view.setFloat32(0, x, true);\n }\n else {\n view.setFloat64(0, x, true);\n }\n return buf;\n }\n encodeType() {\n const opcode = this._bits === 32 ? -13 /* IDLTypeIds.Float32 */ : -14 /* IDLTypeIds.Float64 */;\n return slebEncode(opcode);\n }\n decodeValue(b, t) {\n this.checkType(t);\n const bytes = safeRead(b, this._bits / 8);\n const view = new DataView(bytes);\n if (this._bits === 32) {\n return view.getFloat32(0, true);\n }\n else {\n return view.getFloat64(0, true);\n }\n }\n get name() {\n return 'float' + this._bits;\n }\n valueToString(x) {\n return x.toString();\n }\n}\n/**\n * Represents an IDL fixed-width Int(n)\n */\nexport class FixedIntClass extends PrimitiveType {\n constructor(_bits) {\n super();\n this._bits = _bits;\n }\n accept(v, d) {\n return v.visitFixedInt(this, d);\n }\n covariant(x) {\n const min = iexp2(this._bits - 1) * BigInt(-1);\n const max = iexp2(this._bits - 1) - BigInt(1);\n let ok = false;\n if (typeof x === 'bigint') {\n ok = x >= min && x <= max;\n }\n else if (Number.isInteger(x)) {\n const v = BigInt(x);\n ok = v >= min && v <= max;\n }\n else {\n ok = false;\n }\n if (ok)\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n return writeIntLE(x, this._bits / 8);\n }\n encodeType() {\n const offset = Math.log2(this._bits) - 3;\n return slebEncode(-9 - offset);\n }\n decodeValue(b, t) {\n this.checkType(t);\n const num = readIntLE(b, this._bits / 8);\n if (this._bits <= 32) {\n return Number(num);\n }\n else {\n return num;\n }\n }\n get name() {\n return `int${this._bits}`;\n }\n valueToString(x) {\n return x.toString();\n }\n}\n/**\n * Represents an IDL fixed-width Nat(n)\n */\nexport class FixedNatClass extends PrimitiveType {\n constructor(_bits) {\n super();\n this._bits = _bits;\n }\n accept(v, d) {\n return v.visitFixedNat(this, d);\n }\n covariant(x) {\n const max = iexp2(this._bits);\n let ok = false;\n if (typeof x === 'bigint' && x >= BigInt(0)) {\n ok = x < max;\n }\n else if (Number.isInteger(x) && x >= 0) {\n const v = BigInt(x);\n ok = v < max;\n }\n else {\n ok = false;\n }\n if (ok)\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n return writeUIntLE(x, this._bits / 8);\n }\n encodeType() {\n const offset = Math.log2(this._bits) - 3;\n return slebEncode(-5 - offset);\n }\n decodeValue(b, t) {\n this.checkType(t);\n const num = readUIntLE(b, this._bits / 8);\n if (this._bits <= 32) {\n return Number(num);\n }\n else {\n return num;\n }\n }\n get name() {\n return `nat${this._bits}`;\n }\n valueToString(x) {\n return x.toString();\n }\n}\n/**\n * Represents an IDL Array\n *\n * Arrays of fixed-sized nat/int type (e.g. nat8), are encoded from and decoded to TypedArrays (e.g. Uint8Array).\n * Arrays of float or other non-primitive types are encoded/decoded as untyped array in Javascript.\n * @param {Type} t\n */\nexport class VecClass extends ConstructType {\n constructor(_type) {\n super();\n this._type = _type;\n // If true, this vector is really a blob and we can just use memcpy.\n //\n // NOTE:\n // With support of encoding/dencoding of TypedArrays, this optimization is\n // only used when plain array of bytes are passed as encoding input in order\n // to be backward compatible.\n this._blobOptimization = false;\n if (_type instanceof FixedNatClass && _type._bits === 8) {\n this._blobOptimization = true;\n }\n }\n accept(v, d) {\n return v.visitVec(this, this._type, d);\n }\n covariant(x) {\n // Special case for ArrayBuffer\n const bits = this._type instanceof FixedNatClass\n ? this._type._bits\n : this._type instanceof FixedIntClass\n ? this._type._bits\n : 0;\n if ((ArrayBuffer.isView(x) && bits == x.BYTES_PER_ELEMENT * 8) ||\n (Array.isArray(x) &&\n x.every((v, idx) => {\n try {\n return this._type.covariant(v);\n }\n catch (e) {\n throw new Error(`Invalid ${this.display()} argument: \\n\\nindex ${idx} -> ${e.message}`);\n }\n })))\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n const len = lebEncode(x.length);\n if (this._blobOptimization) {\n return concat(len, new Uint8Array(x));\n }\n if (ArrayBuffer.isView(x)) {\n return concat(len, new Uint8Array(x.buffer));\n }\n const buf = new Pipe(new ArrayBuffer(len.byteLength + x.length), 0);\n buf.write(len);\n for (const d of x) {\n const encoded = this._type.encodeValue(d);\n buf.write(new Uint8Array(encoded));\n }\n return buf.buffer;\n }\n _buildTypeTableImpl(typeTable) {\n this._type.buildTypeTable(typeTable);\n const opCode = slebEncode(-19 /* IDLTypeIds.Vector */);\n const buffer = this._type.encodeType(typeTable);\n typeTable.add(this, concat(opCode, buffer));\n }\n decodeValue(b, t) {\n const vec = this.checkType(t);\n if (!(vec instanceof VecClass)) {\n throw new Error('Not a vector type');\n }\n const len = Number(lebDecode(b));\n if (this._type instanceof FixedNatClass) {\n if (this._type._bits == 8) {\n return new Uint8Array(b.read(len));\n }\n if (this._type._bits == 16) {\n return new Uint16Array(b.read(len * 2));\n }\n if (this._type._bits == 32) {\n return new Uint32Array(b.read(len * 4));\n }\n if (this._type._bits == 64) {\n return new BigUint64Array(b.read(len * 8));\n }\n }\n if (this._type instanceof FixedIntClass) {\n if (this._type._bits == 8) {\n return new Int8Array(b.read(len));\n }\n if (this._type._bits == 16) {\n return new Int16Array(b.read(len * 2));\n }\n if (this._type._bits == 32) {\n return new Int32Array(b.read(len * 4));\n }\n if (this._type._bits == 64) {\n return new BigInt64Array(b.read(len * 8));\n }\n }\n const rets = [];\n for (let i = 0; i < len; i++) {\n rets.push(this._type.decodeValue(b, vec._type));\n }\n return rets;\n }\n get name() {\n return `vec ${this._type.name}`;\n }\n display() {\n return `vec ${this._type.display()}`;\n }\n valueToString(x) {\n const elements = x.map(e => this._type.valueToString(e));\n return 'vec {' + elements.join('; ') + '}';\n }\n}\n/**\n * Represents an IDL Option\n * @param {Type} t\n */\nexport class OptClass extends ConstructType {\n constructor(_type) {\n super();\n this._type = _type;\n }\n accept(v, d) {\n return v.visitOpt(this, this._type, d);\n }\n covariant(x) {\n try {\n if (Array.isArray(x) && (x.length === 0 || (x.length === 1 && this._type.covariant(x[0]))))\n return true;\n }\n catch (e) {\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)} \\n\\n-> ${e.message}`);\n }\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n if (x.length === 0) {\n return new Uint8Array([0]);\n }\n else {\n return concat(new Uint8Array([1]), this._type.encodeValue(x[0]));\n }\n }\n _buildTypeTableImpl(typeTable) {\n this._type.buildTypeTable(typeTable);\n const opCode = slebEncode(-18 /* IDLTypeIds.Opt */);\n const buffer = this._type.encodeType(typeTable);\n typeTable.add(this, concat(opCode, buffer));\n }\n decodeValue(b, t) {\n const opt = this.checkType(t);\n if (!(opt instanceof OptClass)) {\n throw new Error('Not an option type');\n }\n switch (safeReadUint8(b)) {\n case 0:\n return [];\n case 1:\n return [this._type.decodeValue(b, opt._type)];\n default:\n throw new Error('Not an option value');\n }\n }\n get name() {\n return `opt ${this._type.name}`;\n }\n display() {\n return `opt ${this._type.display()}`;\n }\n valueToString(x) {\n if (x.length === 0) {\n return 'null';\n }\n else {\n return `opt ${this._type.valueToString(x[0])}`;\n }\n }\n}\n/**\n * Represents an IDL Record\n * @param {object} [fields] - mapping of function name to Type\n */\nexport class RecordClass extends ConstructType {\n constructor(fields = {}) {\n super();\n this._fields = Object.entries(fields).sort((a, b) => idlLabelToId(a[0]) - idlLabelToId(b[0]));\n }\n accept(v, d) {\n return v.visitRecord(this, this._fields, d);\n }\n tryAsTuple() {\n const res = [];\n for (let i = 0; i < this._fields.length; i++) {\n const [key, type] = this._fields[i];\n if (key !== `_${i}_`) {\n return null;\n }\n res.push(type);\n }\n return res;\n }\n covariant(x) {\n if (typeof x === 'object' &&\n this._fields.every(([k, t]) => {\n // eslint-disable-next-line\n if (!x.hasOwnProperty(k)) {\n throw new Error(`Record is missing key \"${k}\".`);\n }\n try {\n return t.covariant(x[k]);\n }\n catch (e) {\n throw new Error(`Invalid ${this.display()} argument: \\n\\nfield ${k} -> ${e.message}`);\n }\n }))\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n const values = this._fields.map(([key]) => x[key]);\n const bufs = zipWith(this._fields, values, ([, c], d) => c.encodeValue(d));\n return concat(...bufs);\n }\n _buildTypeTableImpl(T) {\n this._fields.forEach(([_, value]) => value.buildTypeTable(T));\n const opCode = slebEncode(-20 /* IDLTypeIds.Record */);\n const len = lebEncode(this._fields.length);\n const fields = this._fields.map(([key, value]) => concat(lebEncode(idlLabelToId(key)), value.encodeType(T)));\n T.add(this, concat(opCode, len, concat(...fields)));\n }\n decodeValue(b, t) {\n const record = this.checkType(t);\n if (!(record instanceof RecordClass)) {\n throw new Error('Not a record type');\n }\n const x = {};\n let expectedRecordIdx = 0;\n let actualRecordIdx = 0;\n while (actualRecordIdx < record._fields.length) {\n const [hash, type] = record._fields[actualRecordIdx];\n if (expectedRecordIdx >= this._fields.length) {\n // skip unexpected left over fields present on the wire\n type.decodeValue(b, type);\n actualRecordIdx++;\n continue;\n }\n const [expectKey, expectType] = this._fields[expectedRecordIdx];\n const expectedId = idlLabelToId(this._fields[expectedRecordIdx][0]);\n const actualId = idlLabelToId(hash);\n if (expectedId === actualId) {\n // the current field on the wire matches the expected field\n x[expectKey] = expectType.decodeValue(b, type);\n expectedRecordIdx++;\n actualRecordIdx++;\n }\n else if (actualId > expectedId) {\n // The expected field does not exist on the wire\n if (expectType instanceof OptClass || expectType instanceof ReservedClass) {\n x[expectKey] = [];\n expectedRecordIdx++;\n }\n else {\n throw new Error('Cannot find required field ' + expectKey);\n }\n }\n else {\n // The field on the wire does not exist in the output type, so we can skip it\n type.decodeValue(b, type);\n actualRecordIdx++;\n }\n }\n // initialize left over expected optional fields\n for (const [expectKey, expectType] of this._fields.slice(expectedRecordIdx)) {\n if (expectType instanceof OptClass || expectType instanceof ReservedClass) {\n // TODO this assumes null value in opt is represented as []\n x[expectKey] = [];\n }\n else {\n throw new Error('Cannot find required field ' + expectKey);\n }\n }\n return x;\n }\n get name() {\n const fields = this._fields.map(([key, value]) => key + ':' + value.name);\n return `record {${fields.join('; ')}}`;\n }\n display() {\n const fields = this._fields.map(([key, value]) => key + ':' + value.display());\n return `record {${fields.join('; ')}}`;\n }\n valueToString(x) {\n const values = this._fields.map(([key]) => x[key]);\n const fields = zipWith(this._fields, values, ([k, c], d) => k + '=' + c.valueToString(d));\n return `record {${fields.join('; ')}}`;\n }\n}\n/**\n * Represents Tuple, a syntactic sugar for Record.\n * @param {Type} components\n */\nexport class TupleClass extends RecordClass {\n constructor(_components) {\n const x = {};\n _components.forEach((e, i) => (x['_' + i + '_'] = e));\n super(x);\n this._components = _components;\n }\n accept(v, d) {\n return v.visitTuple(this, this._components, d);\n }\n covariant(x) {\n // `>=` because tuples can be covariant when encoded.\n if (Array.isArray(x) &&\n x.length >= this._fields.length &&\n this._components.every((t, i) => {\n try {\n return t.covariant(x[i]);\n }\n catch (e) {\n throw new Error(`Invalid ${this.display()} argument: \\n\\nindex ${i} -> ${e.message}`);\n }\n }))\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n const bufs = zipWith(this._components, x, (c, d) => c.encodeValue(d));\n return concat(...bufs);\n }\n decodeValue(b, t) {\n const tuple = this.checkType(t);\n if (!(tuple instanceof TupleClass)) {\n throw new Error('not a tuple type');\n }\n if (tuple._components.length < this._components.length) {\n throw new Error('tuple mismatch');\n }\n const res = [];\n for (const [i, wireType] of tuple._components.entries()) {\n if (i >= this._components.length) {\n // skip value\n wireType.decodeValue(b, wireType);\n }\n else {\n res.push(this._components[i].decodeValue(b, wireType));\n }\n }\n return res;\n }\n display() {\n const fields = this._components.map(value => value.display());\n return `record {${fields.join('; ')}}`;\n }\n valueToString(values) {\n const fields = zipWith(this._components, values, (c, d) => c.valueToString(d));\n return `record {${fields.join('; ')}}`;\n }\n}\n/**\n * Represents an IDL Variant\n * @param {object} [fields] - mapping of function name to Type\n */\nexport class VariantClass extends ConstructType {\n constructor(fields = {}) {\n super();\n this._fields = Object.entries(fields).sort((a, b) => idlLabelToId(a[0]) - idlLabelToId(b[0]));\n }\n accept(v, d) {\n return v.visitVariant(this, this._fields, d);\n }\n covariant(x) {\n if (typeof x === 'object' &&\n Object.entries(x).length === 1 &&\n this._fields.every(([k, v]) => {\n try {\n // eslint-disable-next-line\n return !x.hasOwnProperty(k) || v.covariant(x[k]);\n }\n catch (e) {\n throw new Error(`Invalid ${this.display()} argument: \\n\\nvariant ${k} -> ${e.message}`);\n }\n }))\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n for (let i = 0; i < this._fields.length; i++) {\n const [name, type] = this._fields[i];\n // eslint-disable-next-line\n if (x.hasOwnProperty(name)) {\n const idx = lebEncode(i);\n const buf = type.encodeValue(x[name]);\n return concat(idx, buf);\n }\n }\n throw Error('Variant has no data: ' + x);\n }\n _buildTypeTableImpl(typeTable) {\n this._fields.forEach(([, type]) => {\n type.buildTypeTable(typeTable);\n });\n const opCode = slebEncode(-21 /* IDLTypeIds.Variant */);\n const len = lebEncode(this._fields.length);\n const fields = this._fields.map(([key, value]) => concat(lebEncode(idlLabelToId(key)), value.encodeType(typeTable)));\n typeTable.add(this, concat(opCode, len, ...fields));\n }\n decodeValue(b, t) {\n const variant = this.checkType(t);\n if (!(variant instanceof VariantClass)) {\n throw new Error('Not a variant type');\n }\n const idx = Number(lebDecode(b));\n if (idx >= variant._fields.length) {\n throw Error('Invalid variant index: ' + idx);\n }\n const [wireHash, wireType] = variant._fields[idx];\n for (const [key, expectType] of this._fields) {\n if (idlLabelToId(wireHash) === idlLabelToId(key)) {\n const value = expectType.decodeValue(b, wireType);\n return { [key]: value };\n }\n }\n throw new Error('Cannot find field hash ' + wireHash);\n }\n get name() {\n const fields = this._fields.map(([key, type]) => key + ':' + type.name);\n return `variant {${fields.join('; ')}}`;\n }\n display() {\n const fields = this._fields.map(([key, type]) => key + (type.name === 'null' ? '' : `:${type.display()}`));\n return `variant {${fields.join('; ')}}`;\n }\n valueToString(x) {\n for (const [name, type] of this._fields) {\n // eslint-disable-next-line\n if (x.hasOwnProperty(name)) {\n const value = type.valueToString(x[name]);\n if (value === 'null') {\n return `variant {${name}}`;\n }\n else {\n return `variant {${name}=${value}}`;\n }\n }\n }\n throw new Error('Variant has no data: ' + x);\n }\n}\n/**\n * Represents a reference to an IDL type, used for defining recursive data\n * types.\n */\nexport class RecClass extends ConstructType {\n constructor() {\n super(...arguments);\n this._id = RecClass._counter++;\n this._type = undefined;\n }\n accept(v, d) {\n if (!this._type) {\n throw Error('Recursive type uninitialized.');\n }\n return v.visitRec(this, this._type, d);\n }\n fill(t) {\n this._type = t;\n }\n getType() {\n return this._type;\n }\n covariant(x) {\n if (this._type ? this._type.covariant(x) : false)\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n if (!this._type) {\n throw Error('Recursive type uninitialized.');\n }\n return this._type.encodeValue(x);\n }\n _buildTypeTableImpl(typeTable) {\n if (!this._type) {\n throw Error('Recursive type uninitialized.');\n }\n typeTable.add(this, new Uint8Array([]));\n this._type.buildTypeTable(typeTable);\n typeTable.merge(this, this._type.name);\n }\n decodeValue(b, t) {\n if (!this._type) {\n throw Error('Recursive type uninitialized.');\n }\n return this._type.decodeValue(b, t);\n }\n get name() {\n return `rec_${this._id}`;\n }\n display() {\n if (!this._type) {\n throw Error('Recursive type uninitialized.');\n }\n return `μ${this.name}.${this._type.name}`;\n }\n valueToString(x) {\n if (!this._type) {\n throw Error('Recursive type uninitialized.');\n }\n return this._type.valueToString(x);\n }\n}\nRecClass._counter = 0;\nfunction decodePrincipalId(b) {\n const x = safeReadUint8(b);\n if (x !== 1) {\n throw new Error('Cannot decode principal');\n }\n const len = Number(lebDecode(b));\n return PrincipalId.fromUint8Array(new Uint8Array(safeRead(b, len)));\n}\n/**\n * Represents an IDL principal reference\n */\nexport class PrincipalClass extends PrimitiveType {\n accept(v, d) {\n return v.visitPrincipal(this, d);\n }\n covariant(x) {\n if (x && x._isPrincipal)\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n const buf = x.toUint8Array();\n const len = lebEncode(buf.byteLength);\n return concat(new Uint8Array([1]), len, buf);\n }\n encodeType() {\n return slebEncode(-24 /* IDLTypeIds.Principal */);\n }\n decodeValue(b, t) {\n this.checkType(t);\n return decodePrincipalId(b);\n }\n get name() {\n return 'principal';\n }\n valueToString(x) {\n return `${this.name} \"${x.toText()}\"`;\n }\n}\n/**\n * Represents an IDL function reference.\n * @param argTypes Argument types.\n * @param retTypes Return types.\n * @param annotations Function annotations.\n */\nexport class FuncClass extends ConstructType {\n constructor(argTypes, retTypes, annotations = []) {\n super();\n this.argTypes = argTypes;\n this.retTypes = retTypes;\n this.annotations = annotations;\n }\n static argsToString(types, v) {\n if (types.length !== v.length) {\n throw new Error('arity mismatch');\n }\n return '(' + types.map((t, i) => t.valueToString(v[i])).join(', ') + ')';\n }\n accept(v, d) {\n return v.visitFunc(this, d);\n }\n covariant(x) {\n if (Array.isArray(x) && x.length === 2 && x[0] && x[0]._isPrincipal && typeof x[1] === 'string')\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue([principal, methodName]) {\n const buf = principal.toUint8Array();\n const len = lebEncode(buf.byteLength);\n const canister = concat(new Uint8Array([1]), len, buf);\n const method = new TextEncoder().encode(methodName);\n const methodLen = lebEncode(method.byteLength);\n return concat(new Uint8Array([1]), canister, methodLen, method);\n }\n _buildTypeTableImpl(T) {\n this.argTypes.forEach(arg => arg.buildTypeTable(T));\n this.retTypes.forEach(arg => arg.buildTypeTable(T));\n const opCode = slebEncode(-22 /* IDLTypeIds.Func */);\n const argLen = lebEncode(this.argTypes.length);\n const args = concat(...this.argTypes.map(arg => arg.encodeType(T)));\n const retLen = lebEncode(this.retTypes.length);\n const rets = concat(...this.retTypes.map(arg => arg.encodeType(T)));\n const annLen = lebEncode(this.annotations.length);\n const anns = concat(...this.annotations.map(a => this.encodeAnnotation(a)));\n T.add(this, concat(opCode, argLen, args, retLen, rets, annLen, anns));\n }\n decodeValue(b) {\n const x = safeReadUint8(b);\n if (x !== 1) {\n throw new Error('Cannot decode function reference');\n }\n const canister = decodePrincipalId(b);\n const mLen = Number(lebDecode(b));\n const buf = safeRead(b, mLen);\n const decoder = new TextDecoder('utf8', { fatal: true });\n const method = decoder.decode(buf);\n return [canister, method];\n }\n get name() {\n const args = this.argTypes.map(arg => arg.name).join(', ');\n const rets = this.retTypes.map(arg => arg.name).join(', ');\n const annon = ' ' + this.annotations.join(' ');\n return `(${args}) -> (${rets})${annon}`;\n }\n valueToString([principal, str]) {\n return `func \"${principal.toText()}\".${str}`;\n }\n display() {\n const args = this.argTypes.map(arg => arg.display()).join(', ');\n const rets = this.retTypes.map(arg => arg.display()).join(', ');\n const annon = ' ' + this.annotations.join(' ');\n return `(${args}) → (${rets})${annon}`;\n }\n encodeAnnotation(ann) {\n if (ann === 'query') {\n return new Uint8Array([1]);\n }\n else if (ann === 'oneway') {\n return new Uint8Array([2]);\n }\n else if (ann === 'composite_query') {\n return new Uint8Array([3]);\n }\n else {\n throw new Error('Illegal function annotation');\n }\n }\n}\nexport class ServiceClass extends ConstructType {\n constructor(fields) {\n super();\n this._fields = Object.entries(fields).sort((a, b) => {\n if (a[0] < b[0]) {\n return -1;\n }\n if (a[0] > b[0]) {\n return 1;\n }\n return 0;\n });\n }\n accept(v, d) {\n return v.visitService(this, d);\n }\n covariant(x) {\n if (x && x._isPrincipal)\n return true;\n throw new Error(`Invalid ${this.display()} argument: ${toReadableString(x)}`);\n }\n encodeValue(x) {\n const buf = x.toUint8Array();\n const len = lebEncode(buf.length);\n return concat(new Uint8Array([1]), len, buf);\n }\n _buildTypeTableImpl(T) {\n this._fields.forEach(([_, func]) => func.buildTypeTable(T));\n const opCode = slebEncode(-23 /* IDLTypeIds.Service */);\n const len = lebEncode(this._fields.length);\n const meths = this._fields.map(([label, func]) => {\n const labelBuf = new TextEncoder().encode(label);\n const labelLen = lebEncode(labelBuf.length);\n return concat(labelLen, labelBuf, func.encodeType(T));\n });\n T.add(this, concat(opCode, len, ...meths));\n }\n decodeValue(b) {\n return decodePrincipalId(b);\n }\n get name() {\n const fields = this._fields.map(([key, value]) => key + ':' + value.name);\n return `service {${fields.join('; ')}}`;\n }\n valueToString(x) {\n return `service \"${x.toText()}\"`;\n }\n}\n/**\n * Takes an unknown value and returns a string representation of it.\n * @param x - unknown value\n * @returns {string} string representation of the value\n */\nfunction toReadableString(x) {\n const str = JSON.stringify(x, (_key, value) => typeof value === 'bigint' ? `BigInt(${value})` : value);\n return str && str.length > toReadableString_max\n ? str.substring(0, toReadableString_max - 3) + '...'\n : str;\n}\n/**\n * Encode a array of values\n * @param argTypes - array of Types\n * @param args - array of values\n * @returns {ArrayBuffer} serialised value\n */\nexport function encode(argTypes, args) {\n if (args.length < argTypes.length) {\n throw Error('Wrong number of message arguments');\n }\n const typeTable = new TypeTable();\n argTypes.forEach(t => t.buildTypeTable(typeTable));\n const magic = new TextEncoder().encode(magicNumber);\n const table = typeTable.encode();\n const len = lebEncode(args.length);\n const typs = concat(...argTypes.map(t => t.encodeType(typeTable)));\n const vals = concat(...zipWith(argTypes, args, (t, x) => {\n try {\n t.covariant(x);\n }\n catch (e) {\n const err = new Error(e.message + '\\n\\n');\n throw err;\n }\n return t.encodeValue(x);\n }));\n return concat(magic, table, len, typs, vals);\n}\n/**\n * Decode a binary value\n * @param retTypes - Types expected in the buffer.\n * @param bytes - hex-encoded string, or buffer.\n * @returns Value deserialised to JS type\n */\nexport function decode(retTypes, bytes) {\n const b = new Pipe(bytes);\n if (bytes.byteLength < magicNumber.length) {\n throw new Error('Message length smaller than magic number');\n }\n const magicBuffer = safeRead(b, magicNumber.length);\n const magic = new TextDecoder().decode(magicBuffer);\n if (magic !== magicNumber) {\n throw new Error('Wrong magic number: ' + JSON.stringify(magic));\n }\n function readTypeTable(pipe) {\n const typeTable = [];\n const len = Number(lebDecode(pipe));\n for (let i = 0; i < len; i++) {\n const ty = Number(slebDecode(pipe));\n switch (ty) {\n case -18 /* IDLTypeIds.Opt */:\n case -19 /* IDLTypeIds.Vector */: {\n const t = Number(slebDecode(pipe));\n typeTable.push([ty, t]);\n break;\n }\n case -20 /* IDLTypeIds.Record */:\n case -21 /* IDLTypeIds.Variant */: {\n const fields = [];\n let objectLength = Number(lebDecode(pipe));\n let prevHash;\n while (objectLength--) {\n const hash = Number(lebDecode(pipe));\n if (hash >= Math.pow(2, 32)) {\n throw new Error('field id out of 32-bit range');\n }\n if (typeof prevHash === 'number' && prevHash >= hash) {\n throw new Error('field id collision or not sorted');\n }\n prevHash = hash;\n const t = Number(slebDecode(pipe));\n fields.push([hash, t]);\n }\n typeTable.push([ty, fields]);\n break;\n }\n case -22 /* IDLTypeIds.Func */: {\n const args = [];\n let argLength = Number(lebDecode(pipe));\n while (argLength--) {\n args.push(Number(slebDecode(pipe)));\n }\n const returnValues = [];\n let returnValuesLength = Number(lebDecode(pipe));\n while (returnValuesLength--) {\n returnValues.push(Number(slebDecode(pipe)));\n }\n const annotations = [];\n let annotationLength = Number(lebDecode(pipe));\n while (annotationLength--) {\n const annotation = Number(lebDecode(pipe));\n switch (annotation) {\n case 1: {\n annotations.push('query');\n break;\n }\n case 2: {\n annotations.push('oneway');\n break;\n }\n case 3: {\n annotations.push('composite_query');\n break;\n }\n default:\n throw new Error('unknown annotation');\n }\n }\n typeTable.push([ty, [args, returnValues, annotations]]);\n break;\n }\n case -23 /* IDLTypeIds.Service */: {\n let servLength = Number(lebDecode(pipe));\n const methods = [];\n while (servLength--) {\n const nameLength = Number(lebDecode(pipe));\n const funcName = new TextDecoder().decode(safeRead(pipe, nameLength));\n const funcType = slebDecode(pipe);\n methods.push([funcName, funcType]);\n }\n typeTable.push([ty, methods]);\n break;\n }\n default:\n throw new Error('Illegal op_code: ' + ty);\n }\n }\n const rawList = [];\n const length = Number(lebDecode(pipe));\n for (let i = 0; i < length; i++) {\n rawList.push(Number(slebDecode(pipe)));\n }\n return [typeTable, rawList];\n }\n const [rawTable, rawTypes] = readTypeTable(b);\n if (rawTypes.length < retTypes.length) {\n throw new Error('Wrong number of return values');\n }\n const table = rawTable.map(_ => Rec());\n function getType(t) {\n if (t < -24) {\n throw new Error('future value not supported');\n }\n if (t < 0) {\n switch (t) {\n case -1:\n return Null;\n case -2:\n return Bool;\n case -3:\n return Nat;\n case -4:\n return Int;\n case -5:\n return Nat8;\n case -6:\n return Nat16;\n case -7:\n return Nat32;\n case -8:\n return Nat64;\n case -9:\n return Int8;\n case -10:\n return Int16;\n case -11:\n return Int32;\n case -12:\n return Int64;\n case -13:\n return Float32;\n case -14:\n return Float64;\n case -15:\n return Text;\n case -16:\n return Reserved;\n case -17:\n return Empty;\n case -24:\n return Principal;\n default:\n throw new Error('Illegal op_code: ' + t);\n }\n }\n if (t >= rawTable.length) {\n throw new Error('type index out of range');\n }\n return table[t];\n }\n function buildType(entry) {\n switch (entry[0]) {\n case -19 /* IDLTypeIds.Vector */: {\n const ty = getType(entry[1]);\n return Vec(ty);\n }\n case -18 /* IDLTypeIds.Opt */: {\n const ty = getType(entry[1]);\n return Opt(ty);\n }\n case -20 /* IDLTypeIds.Record */: {\n const fields = {};\n for (const [hash, ty] of entry[1]) {\n const name = `_${hash}_`;\n fields[name] = getType(ty);\n }\n const record = Record(fields);\n const tuple = record.tryAsTuple();\n if (Array.isArray(tuple)) {\n return Tuple(...tuple);\n }\n else {\n return record;\n }\n }\n case -21 /* IDLTypeIds.Variant */: {\n const fields = {};\n for (const [hash, ty] of entry[1]) {\n const name = `_${hash}_`;\n fields[name] = getType(ty);\n }\n return Variant(fields);\n }\n case -22 /* IDLTypeIds.Func */: {\n const [args, returnValues, annotations] = entry[1];\n return Func(args.map((t) => getType(t)), returnValues.map((t) => getType(t)), annotations);\n }\n case -23 /* IDLTypeIds.Service */: {\n const rec = {};\n const methods = entry[1];\n for (const [name, typeRef] of methods) {\n let type = getType(typeRef);\n if (type instanceof RecClass) {\n // unpack reference type\n type = type.getType();\n }\n if (!(type instanceof FuncClass)) {\n throw new Error('Illegal service definition: services can only contain functions');\n }\n rec[name] = type;\n }\n return Service(rec);\n }\n default:\n throw new Error('Illegal op_code: ' + entry[0]);\n }\n }\n rawTable.forEach((entry, i) => {\n // Process function type first, so that we can construct the correct service type\n if (entry[0] === -22 /* IDLTypeIds.Func */) {\n const t = buildType(entry);\n table[i].fill(t);\n }\n });\n rawTable.forEach((entry, i) => {\n if (entry[0] !== -22 /* IDLTypeIds.Func */) {\n const t = buildType(entry);\n table[i].fill(t);\n }\n });\n const types = rawTypes.map(t => getType(t));\n const output = retTypes.map((t, i) => {\n return t.decodeValue(b, types[i]);\n });\n // skip unused values\n for (let ind = retTypes.length; ind < types.length; ind++) {\n types[ind].decodeValue(b, types[ind]);\n }\n if (b.byteLength > 0) {\n throw new Error('decode: Left-over bytes');\n }\n return output;\n}\n// Export Types instances.\nexport const Empty = new EmptyClass();\nexport const Reserved = new ReservedClass();\n/**\n * Client-only type for deserializing unknown data. Not supported by Candid, and its use is discouraged.\n */\nexport const Unknown = new UnknownClass();\nexport const Bool = new BoolClass();\nexport const Null = new NullClass();\nexport const Text = new TextClass();\nexport const Int = new IntClass();\nexport const Nat = new NatClass();\nexport const Float32 = new FloatClass(32);\nexport const Float64 = new FloatClass(64);\nexport const Int8 = new FixedIntClass(8);\nexport const Int16 = new FixedIntClass(16);\nexport const Int32 = new FixedIntClass(32);\nexport const Int64 = new FixedIntClass(64);\nexport const Nat8 = new FixedNatClass(8);\nexport const Nat16 = new FixedNatClass(16);\nexport const Nat32 = new FixedNatClass(32);\nexport const Nat64 = new FixedNatClass(64);\nexport const Principal = new PrincipalClass();\n/**\n *\n * @param types array of any types\n * @returns TupleClass from those types\n */\nexport function Tuple(...types) {\n return new TupleClass(types);\n}\n/**\n *\n * @param t IDL Type\n * @returns VecClass from that type\n */\nexport function Vec(t) {\n return new VecClass(t);\n}\n/**\n *\n * @param t IDL Type\n * @returns OptClass of Type\n */\nexport function Opt(t) {\n return new OptClass(t);\n}\n/**\n *\n * @param t Record of string and IDL Type\n * @returns RecordClass of string and Type\n */\nexport function Record(t) {\n return new RecordClass(t);\n}\n/**\n *\n * @param fields Record of string and IDL Type\n * @returns VariantClass\n */\nexport function Variant(fields) {\n return new VariantClass(fields);\n}\n/**\n *\n * @returns new RecClass\n */\nexport function Rec() {\n return new RecClass();\n}\n/**\n *\n * @param args array of IDL Types\n * @param ret array of IDL Types\n * @param annotations array of strings, [] by default\n * @returns new FuncClass\n */\nexport function Func(args, ret, annotations = []) {\n return new FuncClass(args, ret, annotations);\n}\n/**\n *\n * @param t Record of string and FuncClass\n * @returns ServiceClass\n */\nexport function Service(t) {\n return new ServiceClass(t);\n}\n//# sourceMappingURL=idl.js.map","import { lebEncode } from '@dfinity/candid';\nimport borc from 'borc';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { compare, concat, uint8ToBuf } from './utils/buffer';\n/**\n * sha256 hash the provided Buffer\n * @param data - input to hash function\n */\nexport function hash(data) {\n return uint8ToBuf(sha256.create().update(new Uint8Array(data)).digest());\n}\n/**\n *\n * @param value unknown value\n * @returns ArrayBuffer\n */\nexport function hashValue(value) {\n if (value instanceof borc.Tagged) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return hashValue(value.value);\n }\n else if (typeof value === 'string') {\n return hashString(value);\n }\n else if (typeof value === 'number') {\n return hash(lebEncode(value));\n }\n else if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {\n return hash(value);\n }\n else if (Array.isArray(value)) {\n const vals = value.map(hashValue);\n return hash(concat(...vals));\n }\n else if (value && typeof value === 'object' && value._isPrincipal) {\n return hash(value.toUint8Array());\n }\n else if (typeof value === 'object' &&\n value !== null &&\n typeof value.toHash === 'function') {\n return hashValue(value.toHash());\n // TODO This should be move to a specific async method as the webauthn flow required\n // the flow to be synchronous to ensure Safari touch id works.\n // } else if (value instanceof Promise) {\n // return value.then(x => hashValue(x));\n }\n else if (typeof value === 'object') {\n return hashOfMap(value);\n }\n else if (typeof value === 'bigint') {\n // Do this check much later than the other bigint check because this one is much less\n // type-safe.\n // So we want to try all the high-assurance type guards before this 'probable' one.\n return hash(lebEncode(value));\n }\n throw Object.assign(new Error(`Attempt to hash a value of unsupported type: ${value}`), {\n // include so logs/callers can understand the confusing value.\n // (when stringified in error message, prototype info is lost)\n value,\n });\n}\nconst hashString = (value) => {\n const encoded = new TextEncoder().encode(value);\n return hash(encoded);\n};\n/**\n * Get the RequestId of the provided ic-ref request.\n * RequestId is the result of the representation-independent-hash function.\n * https://sdk.dfinity.org/docs/interface-spec/index.html#hash-of-map\n * @param request - ic-ref request to hash into RequestId\n */\nexport function requestIdOf(request) {\n return hashOfMap(request);\n}\n/**\n * Hash a map into an ArrayBuffer using the representation-independent-hash function.\n * https://sdk.dfinity.org/docs/interface-spec/index.html#hash-of-map\n * @param map - Any non-nested object\n * @returns ArrayBuffer\n */\nexport function hashOfMap(map) {\n const hashed = Object.entries(map)\n .filter(([, value]) => value !== undefined)\n .map(([key, value]) => {\n const hashedKey = hashString(key);\n const hashedValue = hashValue(value);\n return [hashedKey, hashedValue];\n });\n const traversed = hashed;\n const sorted = traversed.sort(([k1], [k2]) => {\n return compare(k1, k2);\n });\n const concatenated = concat(...sorted.map(x => concat(...x)));\n const result = hash(concatenated);\n return result;\n}\n//# sourceMappingURL=request_id.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { Principal } from '@dfinity/principal';\nimport { requestIdOf } from './request_id';\nimport { concat, toHex } from './utils/buffer';\nconst domainSeparator = new TextEncoder().encode('\\x0Aic-request');\n/**\n * An Identity that can sign blobs.\n */\nexport class SignIdentity {\n /**\n * Get the principal represented by this identity. Normally should be a\n * `Principal.selfAuthenticating()`.\n */\n getPrincipal() {\n if (!this._principal) {\n this._principal = Principal.selfAuthenticating(new Uint8Array(this.getPublicKey().toDer()));\n }\n return this._principal;\n }\n /**\n * Transform a request into a signed version of the request. This is done last\n * after the transforms on the body of a request. The returned object can be\n * anything, but must be serializable to CBOR.\n * @param request - internet computer request to transform\n */\n async transformRequest(request) {\n const { body } = request, fields = __rest(request, [\"body\"]);\n const requestId = requestIdOf(body);\n return Object.assign(Object.assign({}, fields), { body: {\n content: body,\n sender_pubkey: this.getPublicKey().toDer(),\n sender_sig: await this.sign(concat(domainSeparator, requestId)),\n } });\n }\n}\nexport class AnonymousIdentity {\n getPrincipal() {\n return Principal.anonymous();\n }\n async transformRequest(request) {\n return Object.assign(Object.assign({}, request), { body: { content: request.body } });\n }\n}\n/**\n * Create an IdentityDescriptor from a @dfinity/identity Identity\n * @param identity - identity describe in returned descriptor\n */\nexport function createIdentityDescriptor(identity) {\n const identityIndicator = 'getPublicKey' in identity\n ? { type: 'PublicKeyIdentity', publicKey: toHex(identity.getPublicKey().toDer()) }\n : { type: 'AnonymousIdentity' };\n return identityIndicator;\n}\n//# sourceMappingURL=auth.js.map","// This file is based on:\n// https://github.com/dfinity-lab/dfinity/blob/9bca65f8edd65701ea6bdb00e0752f9186bbc893/docs/spec/public/index.adoc#cbor-encoding-of-requests-and-responses\nimport borc from 'borc';\nimport * as cbor from 'simple-cbor';\nimport { SelfDescribeCborSerializer } from 'simple-cbor';\nimport { concat, fromHex, toHex } from './utils/buffer';\n// We are using hansl/simple-cbor for CBOR serialization, to avoid issues with\n// encoding the uint64 values that the HTTP handler of the client expects for\n// canister IDs. However, simple-cbor does not yet provide deserialization so\n// we are using `Uint8Array` so that we can use the dignifiedquire/borc CBOR\n// decoder.\nclass PrincipalEncoder {\n get name() {\n return 'Principal';\n }\n get priority() {\n return 0;\n }\n match(value) {\n return value && value._isPrincipal === true;\n }\n encode(v) {\n return cbor.value.bytes(v.toUint8Array());\n }\n}\nclass BufferEncoder {\n get name() {\n return 'Buffer';\n }\n get priority() {\n return 1;\n }\n match(value) {\n return value instanceof ArrayBuffer || ArrayBuffer.isView(value);\n }\n encode(v) {\n return cbor.value.bytes(new Uint8Array(v));\n }\n}\nclass BigIntEncoder {\n get name() {\n return 'BigInt';\n }\n get priority() {\n return 1;\n }\n match(value) {\n return typeof value === `bigint`;\n }\n encode(v) {\n // Always use a bigint encoding.\n if (v > BigInt(0)) {\n return cbor.value.tagged(2, cbor.value.bytes(fromHex(v.toString(16))));\n }\n else {\n return cbor.value.tagged(3, cbor.value.bytes(fromHex((BigInt('-1') * v).toString(16))));\n }\n }\n}\nconst serializer = SelfDescribeCborSerializer.withDefaultEncoders(true);\nserializer.addEncoder(new PrincipalEncoder());\nserializer.addEncoder(new BufferEncoder());\nserializer.addEncoder(new BigIntEncoder());\nexport var CborTag;\n(function (CborTag) {\n CborTag[CborTag[\"Uint64LittleEndian\"] = 71] = \"Uint64LittleEndian\";\n CborTag[CborTag[\"Semantic\"] = 55799] = \"Semantic\";\n})(CborTag || (CborTag = {}));\n/**\n * Encode a JavaScript value into CBOR.\n */\nexport function encode(value) {\n return serializer.serialize(value);\n}\nfunction decodePositiveBigInt(buf) {\n const len = buf.byteLength;\n let res = BigInt(0);\n for (let i = 0; i < len; i++) {\n res = res * BigInt(0x100) + BigInt(buf[i]);\n }\n return res;\n}\n// A BORC subclass that decodes byte strings to ArrayBuffer instead of the Buffer class.\nclass Uint8ArrayDecoder extends borc.Decoder {\n createByteString(raw) {\n return concat(...raw);\n }\n createByteStringFromHeap(start, end) {\n if (start === end) {\n return new ArrayBuffer(0);\n }\n return new Uint8Array(this._heap.slice(start, end));\n }\n}\nexport function decode(input) {\n const buffer = new Uint8Array(input);\n const decoder = new Uint8ArrayDecoder({\n size: buffer.byteLength,\n tags: {\n // Override tags 2 and 3 for BigInt support (borc supports only BigNumber).\n 2: val => decodePositiveBigInt(val),\n 3: val => -decodePositiveBigInt(val),\n [CborTag.Semantic]: (value) => value,\n },\n });\n try {\n return decoder.decodeFirst(buffer);\n }\n catch (e) {\n throw new Error(`Failed to decode CBOR: ${e}, input: ${toHex(buffer)}`);\n }\n}\n//# sourceMappingURL=cbor.js.map","import { randomNumber } from '../../utils/random';\n// The types of values allowed in the `request_type` field for submit requests.\nexport var SubmitRequestType;\n(function (SubmitRequestType) {\n SubmitRequestType[\"Call\"] = \"call\";\n})(SubmitRequestType || (SubmitRequestType = {}));\n/**\n * Create a random Nonce, based on random values\n */\nexport function makeNonce() {\n // Encode 128 bits.\n const buffer = new ArrayBuffer(16);\n const view = new DataView(buffer);\n const rand1 = randomNumber();\n const rand2 = randomNumber();\n const rand3 = randomNumber();\n const rand4 = randomNumber();\n view.setUint32(0, rand1);\n view.setUint32(4, rand2);\n view.setUint32(8, rand3);\n view.setUint32(12, rand4);\n return buffer;\n}\n//# sourceMappingURL=types.js.map","import * as cbor from './cbor';\nimport { AgentError } from './errors';\nimport { hash } from './request_id';\nimport { bufEquals, concat, fromHex, toHex } from './utils/buffer';\nimport { Principal } from '@dfinity/principal';\nimport * as bls from './utils/bls';\nimport { decodeTime } from './utils/leb';\nimport { MANAGEMENT_CANISTER_ID } from './agent';\n/**\n * A certificate may fail verification with respect to the provided public key\n */\nexport class CertificateVerificationError extends AgentError {\n constructor(reason) {\n super(`Invalid certificate: ${reason}`);\n }\n}\nexport var NodeType;\n(function (NodeType) {\n NodeType[NodeType[\"Empty\"] = 0] = \"Empty\";\n NodeType[NodeType[\"Fork\"] = 1] = \"Fork\";\n NodeType[NodeType[\"Labeled\"] = 2] = \"Labeled\";\n NodeType[NodeType[\"Leaf\"] = 3] = \"Leaf\";\n NodeType[NodeType[\"Pruned\"] = 4] = \"Pruned\";\n})(NodeType || (NodeType = {}));\n/**\n * Make a human readable string out of a hash tree.\n * @param tree\n */\nexport function hashTreeToString(tree) {\n const indent = (s) => s\n .split('\\n')\n .map(x => ' ' + x)\n .join('\\n');\n function labelToString(label) {\n const decoder = new TextDecoder(undefined, { fatal: true });\n try {\n return JSON.stringify(decoder.decode(label));\n }\n catch (e) {\n return `data(...${label.byteLength} bytes)`;\n }\n }\n switch (tree[0]) {\n case NodeType.Empty:\n return '()';\n case NodeType.Fork: {\n if (tree[1] instanceof Array && tree[2] instanceof ArrayBuffer) {\n const left = hashTreeToString(tree[1]);\n const right = hashTreeToString(tree[2]);\n return `sub(\\n left:\\n${indent(left)}\\n---\\n right:\\n${indent(right)}\\n)`;\n }\n else {\n throw new Error('Invalid tree structure for fork');\n }\n }\n case NodeType.Labeled: {\n if (tree[1] instanceof ArrayBuffer && tree[2] instanceof ArrayBuffer) {\n const label = labelToString(tree[1]);\n const sub = hashTreeToString(tree[2]);\n return `label(\\n label:\\n${indent(label)}\\n sub:\\n${indent(sub)}\\n)`;\n }\n else {\n throw new Error('Invalid tree structure for labeled');\n }\n }\n case NodeType.Leaf: {\n if (!tree[1]) {\n throw new Error('Invalid tree structure for leaf');\n }\n else if (Array.isArray(tree[1])) {\n return JSON.stringify(tree[1]);\n }\n return `leaf(...${tree[1].byteLength} bytes)`;\n }\n case NodeType.Pruned: {\n if (!tree[1]) {\n throw new Error('Invalid tree structure for pruned');\n }\n else if (Array.isArray(tree[1])) {\n return JSON.stringify(tree[1]);\n }\n return `pruned(${toHex(new Uint8Array(tree[1]))}`;\n }\n default: {\n return `unknown(${JSON.stringify(tree[0])})`;\n }\n }\n}\nfunction isBufferGreaterThan(a, b) {\n const a8 = new Uint8Array(a);\n const b8 = new Uint8Array(b);\n for (let i = 0; i < a8.length; i++) {\n if (a8[i] > b8[i]) {\n return true;\n }\n }\n return false;\n}\nexport class Certificate {\n constructor(certificate, _rootKey, _canisterId, _blsVerify, \n // Default to 5 minutes\n _maxAgeInMinutes = 5) {\n this._rootKey = _rootKey;\n this._canisterId = _canisterId;\n this._blsVerify = _blsVerify;\n this._maxAgeInMinutes = _maxAgeInMinutes;\n this.cert = cbor.decode(new Uint8Array(certificate));\n }\n /**\n * Create a new instance of a certificate, automatically verifying it. Throws a\n * CertificateVerificationError if the certificate cannot be verified.\n * @constructs Certificate\n * @param {CreateCertificateOptions} options {@link CreateCertificateOptions}\n * @param {ArrayBuffer} options.certificate The bytes of the certificate\n * @param {ArrayBuffer} options.rootKey The root key to verify against\n * @param {Principal} options.canisterId The effective or signing canister ID\n * @param {number} options.maxAgeInMinutes The maximum age of the certificate in minutes. Default is 5 minutes.\n * @throws {CertificateVerificationError}\n */\n static async create(options) {\n const cert = Certificate.createUnverified(options);\n await cert.verify();\n return cert;\n }\n static createUnverified(options) {\n let blsVerify = options.blsVerify;\n if (!blsVerify) {\n blsVerify = bls.blsVerify;\n }\n return new Certificate(options.certificate, options.rootKey, options.canisterId, blsVerify, options.maxAgeInMinutes);\n }\n lookup(path) {\n // constrain the type of the result, so that empty HashTree is undefined\n return lookup_path(path, this.cert.tree);\n }\n lookup_label(label) {\n return this.lookup([label]);\n }\n async verify() {\n const rootHash = await reconstruct(this.cert.tree);\n const derKey = await this._checkDelegationAndGetKey(this.cert.delegation);\n const sig = this.cert.signature;\n const key = extractDER(derKey);\n const msg = concat(domain_sep('ic-state-root'), rootHash);\n let sigVer = false;\n const lookupTime = lookupResultToBuffer(this.lookup(['time']));\n if (!lookupTime) {\n // Should never happen - time is always present in IC certificates\n throw new CertificateVerificationError('Certificate does not contain a time');\n }\n const FIVE_MINUTES_IN_MSEC = 5 * 60 * 1000;\n const MAX_AGE_IN_MSEC = this._maxAgeInMinutes * 60 * 1000;\n const now = Date.now();\n const earliestCertificateTime = now - MAX_AGE_IN_MSEC;\n const fiveMinutesFromNow = now + FIVE_MINUTES_IN_MSEC;\n const certTime = decodeTime(lookupTime);\n if (certTime.getTime() < earliestCertificateTime) {\n throw new CertificateVerificationError(`Certificate is signed more than ${this._maxAgeInMinutes} minutes in the past. Certificate time: ` +\n certTime.toISOString() +\n ' Current time: ' +\n new Date(now).toISOString());\n }\n else if (certTime.getTime() > fiveMinutesFromNow) {\n throw new CertificateVerificationError('Certificate is signed more than 5 minutes in the future. Certificate time: ' +\n certTime.toISOString() +\n ' Current time: ' +\n new Date(now).toISOString());\n }\n try {\n sigVer = await this._blsVerify(new Uint8Array(key), new Uint8Array(sig), new Uint8Array(msg));\n }\n catch (err) {\n sigVer = false;\n }\n if (!sigVer) {\n throw new CertificateVerificationError('Signature verification failed');\n }\n }\n async _checkDelegationAndGetKey(d) {\n if (!d) {\n return this._rootKey;\n }\n const cert = await Certificate.createUnverified({\n certificate: d.certificate,\n rootKey: this._rootKey,\n canisterId: this._canisterId,\n blsVerify: this._blsVerify,\n // Do not check max age for delegation certificates\n maxAgeInMinutes: Infinity,\n });\n if (cert.cert.delegation) {\n throw new CertificateVerificationError('Delegation certificates cannot be nested');\n }\n await cert.verify();\n if (this._canisterId.toString() !== MANAGEMENT_CANISTER_ID) {\n const canisterInRange = check_canister_ranges({\n canisterId: this._canisterId,\n subnetId: Principal.fromUint8Array(new Uint8Array(d.subnet_id)),\n tree: cert.cert.tree,\n });\n if (!canisterInRange) {\n throw new CertificateVerificationError(`Canister ${this._canisterId} not in range of delegations for subnet 0x${toHex(d.subnet_id)}`);\n }\n }\n const publicKeyLookup = lookupResultToBuffer(cert.lookup(['subnet', d.subnet_id, 'public_key']));\n if (!publicKeyLookup) {\n throw new Error(`Could not find subnet key for subnet 0x${toHex(d.subnet_id)}`);\n }\n return publicKeyLookup;\n }\n}\nconst DER_PREFIX = fromHex('308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100');\nconst KEY_LENGTH = 96;\nfunction extractDER(buf) {\n const expectedLength = DER_PREFIX.byteLength + KEY_LENGTH;\n if (buf.byteLength !== expectedLength) {\n throw new TypeError(`BLS DER-encoded public key must be ${expectedLength} bytes long`);\n }\n const prefix = buf.slice(0, DER_PREFIX.byteLength);\n if (!bufEquals(prefix, DER_PREFIX)) {\n throw new TypeError(`BLS DER-encoded public key is invalid. Expect the following prefix: ${DER_PREFIX}, but get ${prefix}`);\n }\n return buf.slice(DER_PREFIX.byteLength);\n}\n/**\n * utility function to constrain the type of a path\n * @param {ArrayBuffer | HashTree | undefined} result - the result of a lookup\n * @returns ArrayBuffer or Undefined\n */\nexport function lookupResultToBuffer(result) {\n if (result.status !== LookupStatus.Found) {\n return undefined;\n }\n if (result.value instanceof ArrayBuffer) {\n return result.value;\n }\n if (result.value instanceof Uint8Array) {\n return result.value.buffer;\n }\n return undefined;\n}\n/**\n * @param t\n */\nexport async function reconstruct(t) {\n switch (t[0]) {\n case NodeType.Empty:\n return hash(domain_sep('ic-hashtree-empty'));\n case NodeType.Pruned:\n return t[1];\n case NodeType.Leaf:\n return hash(concat(domain_sep('ic-hashtree-leaf'), t[1]));\n case NodeType.Labeled:\n return hash(concat(domain_sep('ic-hashtree-labeled'), t[1], await reconstruct(t[2])));\n case NodeType.Fork:\n return hash(concat(domain_sep('ic-hashtree-fork'), await reconstruct(t[1]), await reconstruct(t[2])));\n default:\n throw new Error('unreachable');\n }\n}\nfunction domain_sep(s) {\n const len = new Uint8Array([s.length]);\n const str = new TextEncoder().encode(s);\n return concat(len, str);\n}\nexport var LookupStatus;\n(function (LookupStatus) {\n LookupStatus[\"Unknown\"] = \"unknown\";\n LookupStatus[\"Absent\"] = \"absent\";\n LookupStatus[\"Found\"] = \"found\";\n})(LookupStatus || (LookupStatus = {}));\nvar LabelLookupStatus;\n(function (LabelLookupStatus) {\n LabelLookupStatus[\"Less\"] = \"less\";\n LabelLookupStatus[\"Greater\"] = \"greater\";\n})(LabelLookupStatus || (LabelLookupStatus = {}));\nexport function lookup_path(path, tree) {\n if (path.length === 0) {\n switch (tree[0]) {\n case NodeType.Leaf: {\n if (!tree[1]) {\n throw new Error('Invalid tree structure for leaf');\n }\n if (tree[1] instanceof ArrayBuffer) {\n return {\n status: LookupStatus.Found,\n value: tree[1],\n };\n }\n if (tree[1] instanceof Uint8Array) {\n return {\n status: LookupStatus.Found,\n value: tree[1].buffer,\n };\n }\n return {\n status: LookupStatus.Found,\n value: tree[1],\n };\n }\n default: {\n return {\n status: LookupStatus.Found,\n value: tree,\n };\n }\n }\n }\n const label = typeof path[0] === 'string' ? new TextEncoder().encode(path[0]) : path[0];\n const lookupResult = find_label(label, tree);\n switch (lookupResult.status) {\n case LookupStatus.Found: {\n return lookup_path(path.slice(1), lookupResult.value);\n }\n case LabelLookupStatus.Greater:\n case LabelLookupStatus.Less: {\n return {\n status: LookupStatus.Absent,\n };\n }\n default: {\n return lookupResult;\n }\n }\n}\n/**\n * If the tree is a fork, flatten it into an array of trees\n * @param t - the tree to flatten\n * @returns HashTree[] - the flattened tree\n */\nexport function flatten_forks(t) {\n switch (t[0]) {\n case NodeType.Empty:\n return [];\n case NodeType.Fork:\n return flatten_forks(t[1]).concat(flatten_forks(t[2]));\n default:\n return [t];\n }\n}\nexport function find_label(label, tree) {\n switch (tree[0]) {\n // if we have a labelled node, compare the node's label to the one we are\n // looking for\n case NodeType.Labeled:\n // if the label we're searching for is greater than this node's label,\n // we need to keep searching\n if (isBufferGreaterThan(label, tree[1])) {\n return {\n status: LabelLookupStatus.Greater,\n };\n }\n // if the label we're searching for is equal this node's label, we can\n // stop searching and return the found node\n if (bufEquals(label, tree[1])) {\n return {\n status: LookupStatus.Found,\n value: tree[2],\n };\n }\n // if the label we're searching for is not greater than or equal to this\n // node's label, then it's less than this node's label, and we can stop\n // searching because we've looked too far\n return {\n status: LabelLookupStatus.Less,\n };\n // if we have a fork node, we need to search both sides, starting with the left\n case NodeType.Fork:\n // search in the left node\n const leftLookupResult = find_label(label, tree[1]);\n switch (leftLookupResult.status) {\n // if the label we're searching for is greater than the left node lookup,\n // we need to search the right node\n case LabelLookupStatus.Greater: {\n const rightLookupResult = find_label(label, tree[2]);\n // if the label we're searching for is less than the right node lookup,\n // then we can stop searching and say that the label is provably Absent\n if (rightLookupResult.status === LabelLookupStatus.Less) {\n return {\n status: LookupStatus.Absent,\n };\n }\n // if the label we're searching for is less than or equal to the right\n // node lookup, then we let the caller handle it\n return rightLookupResult;\n }\n // if the left node returns an uncertain result, we need to search the\n // right node\n case LookupStatus.Unknown: {\n let rightLookupResult = find_label(label, tree[2]);\n // if the label we're searching for is less than the right node lookup,\n // then we also need to return an uncertain result\n if (rightLookupResult.status === LabelLookupStatus.Less) {\n return {\n status: LookupStatus.Unknown,\n };\n }\n // if the label we're searching for is less than or equal to the right\n // node lookup, then we let the caller handle it\n return rightLookupResult;\n }\n // if the label we're searching for is not greater than the left node\n // lookup, or the result is not uncertain, we stop searching and return\n // whatever the result of the left node lookup was, which can be either\n // Found or Absent\n default: {\n return leftLookupResult;\n }\n }\n // if we encounter a Pruned node, we can't know for certain if the label\n // we're searching for is present or not\n case NodeType.Pruned:\n return {\n status: LookupStatus.Unknown,\n };\n // if the current node is Empty, or a Leaf, we can stop searching because\n // we know for sure that the label we're searching for is not present\n default:\n return {\n status: LookupStatus.Absent,\n };\n }\n}\n/**\n * Check if a canister falls within a range of canisters\n * @param canisterId Principal\n * @param ranges [Principal, Principal][]\n * @returns\n */\nexport function check_canister_ranges(params) {\n const { canisterId, subnetId, tree } = params;\n const rangeLookup = lookup_path(['subnet', subnetId.toUint8Array(), 'canister_ranges'], tree);\n if (rangeLookup.status !== LookupStatus.Found || !(rangeLookup.value instanceof ArrayBuffer)) {\n throw new Error(`Could not find canister ranges for subnet ${subnetId}`);\n }\n const ranges_arr = cbor.decode(rangeLookup.value);\n const ranges = ranges_arr.map(v => [\n Principal.fromUint8Array(v[0]),\n Principal.fromUint8Array(v[1]),\n ]);\n const canisterInRange = ranges.some(r => r[0].ltEq(canisterId) && r[1].gtEq(canisterId));\n return canisterInRange;\n}\n//# sourceMappingURL=certificate.js.map","var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _HttpAgent_instances, _HttpAgent_identity, _HttpAgent_fetch, _HttpAgent_fetchOptions, _HttpAgent_callOptions, _HttpAgent_timeDiffMsecs, _HttpAgent_credentials, _HttpAgent_rootKeyFetched, _HttpAgent_retryTimes, _HttpAgent_backoffStrategy, _HttpAgent_maxIngressExpiryInMinutes, _HttpAgent_waterMark, _HttpAgent_queryPipeline, _HttpAgent_updatePipeline, _HttpAgent_subnetKeys, _HttpAgent_verifyQuerySignatures, _HttpAgent_requestAndRetryQuery, _HttpAgent_requestAndRetry, _HttpAgent_verifyQueryResponse;\nimport { Principal } from '@dfinity/principal';\nimport { AgentError } from '../../errors';\nimport { AnonymousIdentity } from '../../auth';\nimport * as cbor from '../../cbor';\nimport { hashOfMap, requestIdOf } from '../../request_id';\nimport { bufFromBufLike, concat, fromHex } from '../../utils/buffer';\nimport { Expiry, httpHeadersTransform, makeNonceTransform } from './transforms';\nimport { makeNonce, SubmitRequestType, } from './types';\nimport { AgentHTTPResponseError } from './errors';\nimport { request } from '../../canisterStatus';\nimport { CertificateVerificationError, LookupStatus, lookup_path, } from '../../certificate';\nimport { ed25519 } from '@noble/curves/ed25519';\nimport { ExpirableMap } from '../../utils/expirableMap';\nimport { Ed25519PublicKey } from '../../public_key';\nimport { decodeTime } from '../../utils/leb';\nimport { ObservableLog } from '../../observable';\nimport { ExponentialBackoff } from '../../polling/backoff';\nimport { DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS } from '../../constants';\nexport * from './transforms';\nexport { makeNonce } from './types';\nexport var RequestStatusResponseStatus;\n(function (RequestStatusResponseStatus) {\n RequestStatusResponseStatus[\"Received\"] = \"received\";\n RequestStatusResponseStatus[\"Processing\"] = \"processing\";\n RequestStatusResponseStatus[\"Replied\"] = \"replied\";\n RequestStatusResponseStatus[\"Rejected\"] = \"rejected\";\n RequestStatusResponseStatus[\"Unknown\"] = \"unknown\";\n RequestStatusResponseStatus[\"Done\"] = \"done\";\n})(RequestStatusResponseStatus || (RequestStatusResponseStatus = {}));\nconst MINUTE_TO_MSECS = 60 * 1000;\n// Root public key for the IC, encoded as hex\nexport const IC_ROOT_KEY = '308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814' +\n 'c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d968' +\n '5f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484' +\n 'b01291091c5f87b98883463f98091a0baaae';\nexport const MANAGEMENT_CANISTER_ID = 'aaaaa-aa';\n// IC0 domain info\nconst IC0_DOMAIN = 'ic0.app';\nconst IC0_SUB_DOMAIN = '.ic0.app';\nconst ICP0_DOMAIN = 'icp0.io';\nconst ICP0_SUB_DOMAIN = '.icp0.io';\nconst ICP_API_DOMAIN = 'icp-api.io';\nconst ICP_API_SUB_DOMAIN = '.icp-api.io';\nclass HttpDefaultFetchError extends AgentError {\n constructor(message) {\n super(message);\n this.message = message;\n }\n}\nexport class IdentityInvalidError extends AgentError {\n constructor(message) {\n super(message);\n this.message = message;\n }\n}\nfunction getDefaultFetch() {\n let defaultFetch;\n if (typeof window !== 'undefined') {\n // Browser context\n if (window.fetch) {\n defaultFetch = window.fetch.bind(window);\n }\n else {\n throw new HttpDefaultFetchError('Fetch implementation was not available. You appear to be in a browser context, but window.fetch was not present.');\n }\n }\n else if (typeof global !== 'undefined') {\n // Node context\n if (global.fetch) {\n defaultFetch = global.fetch.bind(global);\n }\n else {\n throw new HttpDefaultFetchError('Fetch implementation was not available. You appear to be in a Node.js context, but global.fetch was not available.');\n }\n }\n else if (typeof self !== 'undefined') {\n if (self.fetch) {\n defaultFetch = self.fetch.bind(self);\n }\n }\n if (defaultFetch) {\n return defaultFetch;\n }\n throw new HttpDefaultFetchError('Fetch implementation was not available. Please provide fetch to the HttpAgent constructor, or ensure it is available in the window or global context.');\n}\nfunction determineHost(configuredHost) {\n let host;\n if (configuredHost !== undefined) {\n if (!configuredHost.match(/^[a-z]+:/) && typeof window !== 'undefined') {\n host = new URL(window.location.protocol + '//' + configuredHost);\n }\n else {\n host = new URL(configuredHost);\n }\n }\n else {\n // Mainnet, local, and remote environments will have the api route available\n const knownHosts = ['ic0.app', 'icp0.io', '127.0.0.1', 'localhost'];\n const remoteHosts = ['.github.dev', '.gitpod.io'];\n const location = typeof window !== 'undefined' ? window.location : undefined;\n const hostname = location === null || location === void 0 ? void 0 : location.hostname;\n let knownHost;\n if (hostname && typeof hostname === 'string') {\n if (remoteHosts.some(host => hostname.endsWith(host))) {\n knownHost = hostname;\n }\n else {\n knownHost = knownHosts.find(host => hostname.endsWith(host));\n }\n }\n if (location && knownHost) {\n // If the user is on a boundary-node provided host, we can use the same host for the agent\n host = new URL(`${location.protocol}//${knownHost}${location.port ? ':' + location.port : ''}`);\n }\n else {\n host = new URL('https://icp-api.io');\n }\n }\n return host.toString();\n}\n/**\n * A HTTP agent allows users to interact with a client of the internet computer\nusing the available methods. It exposes an API that closely follows the\npublic view of the internet computer, and is not intended to be exposed\ndirectly to the majority of users due to its low-level interface.\n * There is a pipeline to apply transformations to the request before sending\nit to the client. This is to decouple signature, nonce generation and\nother computations so that this class can stay as simple as possible while\nallowing extensions.\n */\nexport class HttpAgent {\n /**\n * @param options - Options for the HttpAgent\n * @deprecated Use `HttpAgent.create` or `HttpAgent.createSync` instead\n */\n constructor(options = {}) {\n var _a;\n _HttpAgent_instances.add(this);\n _HttpAgent_identity.set(this, void 0);\n _HttpAgent_fetch.set(this, void 0);\n _HttpAgent_fetchOptions.set(this, void 0);\n _HttpAgent_callOptions.set(this, void 0);\n _HttpAgent_timeDiffMsecs.set(this, 0);\n _HttpAgent_credentials.set(this, void 0);\n _HttpAgent_rootKeyFetched.set(this, false);\n _HttpAgent_retryTimes.set(this, void 0); // Retry requests N times before erroring by default\n _HttpAgent_backoffStrategy.set(this, void 0);\n _HttpAgent_maxIngressExpiryInMinutes.set(this, void 0);\n // Public signature to help with type checking.\n this._isAgent = true;\n this.config = {};\n // The UTC time in milliseconds when the latest request was made\n _HttpAgent_waterMark.set(this, 0);\n this.log = new ObservableLog();\n _HttpAgent_queryPipeline.set(this, []);\n _HttpAgent_updatePipeline.set(this, []);\n _HttpAgent_subnetKeys.set(this, new ExpirableMap({\n expirationTime: 5 * 60 * 1000, // 5 minutes\n }));\n _HttpAgent_verifyQuerySignatures.set(this, true);\n /**\n * See https://internetcomputer.org/docs/current/references/ic-interface-spec/#http-query for details on validation\n * @param queryResponse - The response from the query\n * @param subnetStatus - The subnet status, including all node keys\n * @returns ApiQueryResponse\n */\n _HttpAgent_verifyQueryResponse.set(this, (queryResponse, subnetStatus) => {\n if (__classPrivateFieldGet(this, _HttpAgent_verifyQuerySignatures, \"f\") === false) {\n // This should not be called if the user has disabled verification\n return queryResponse;\n }\n if (!subnetStatus) {\n throw new CertificateVerificationError('Invalid signature from replica signed query: no matching node key found.');\n }\n const { status, signatures = [], requestId } = queryResponse;\n const domainSeparator = new TextEncoder().encode('\\x0Bic-response');\n for (const sig of signatures) {\n const { timestamp, identity } = sig;\n const nodeId = Principal.fromUint8Array(identity).toText();\n let hash;\n // Hash is constructed differently depending on the status\n if (status === 'replied') {\n const { reply } = queryResponse;\n hash = hashOfMap({\n status: status,\n reply: reply,\n timestamp: BigInt(timestamp),\n request_id: requestId,\n });\n }\n else if (status === 'rejected') {\n const { reject_code, reject_message, error_code } = queryResponse;\n hash = hashOfMap({\n status: status,\n reject_code: reject_code,\n reject_message: reject_message,\n error_code: error_code,\n timestamp: BigInt(timestamp),\n request_id: requestId,\n });\n }\n else {\n throw new Error(`Unknown status: ${status}`);\n }\n const separatorWithHash = concat(domainSeparator, new Uint8Array(hash));\n // FIX: check for match without verifying N times\n const pubKey = subnetStatus === null || subnetStatus === void 0 ? void 0 : subnetStatus.nodeKeys.get(nodeId);\n if (!pubKey) {\n throw new CertificateVerificationError('Invalid signature from replica signed query: no matching node key found.');\n }\n const rawKey = Ed25519PublicKey.fromDer(pubKey).rawKey;\n const valid = ed25519.verify(sig.signature, new Uint8Array(separatorWithHash), new Uint8Array(rawKey));\n if (valid)\n return queryResponse;\n throw new CertificateVerificationError(`Invalid signature from replica ${nodeId} signed query.`);\n }\n return queryResponse;\n });\n this.config = options;\n __classPrivateFieldSet(this, _HttpAgent_fetch, options.fetch || getDefaultFetch() || fetch.bind(global), \"f\");\n __classPrivateFieldSet(this, _HttpAgent_fetchOptions, options.fetchOptions, \"f\");\n __classPrivateFieldSet(this, _HttpAgent_callOptions, options.callOptions, \"f\");\n this.rootKey = options.rootKey ? options.rootKey : fromHex(IC_ROOT_KEY);\n const host = determineHost(options.host);\n this.host = new URL(host);\n if (options.verifyQuerySignatures !== undefined) {\n __classPrivateFieldSet(this, _HttpAgent_verifyQuerySignatures, options.verifyQuerySignatures, \"f\");\n }\n // Default is 3\n __classPrivateFieldSet(this, _HttpAgent_retryTimes, (_a = options.retryTimes) !== null && _a !== void 0 ? _a : 3, \"f\");\n // Delay strategy for retries. Default is exponential backoff\n const defaultBackoffFactory = () => new ExponentialBackoff({\n maxIterations: __classPrivateFieldGet(this, _HttpAgent_retryTimes, \"f\"),\n });\n __classPrivateFieldSet(this, _HttpAgent_backoffStrategy, options.backoffStrategy || defaultBackoffFactory, \"f\");\n // Rewrite to avoid redirects\n if (this.host.hostname.endsWith(IC0_SUB_DOMAIN)) {\n this.host.hostname = IC0_DOMAIN;\n }\n else if (this.host.hostname.endsWith(ICP0_SUB_DOMAIN)) {\n this.host.hostname = ICP0_DOMAIN;\n }\n else if (this.host.hostname.endsWith(ICP_API_SUB_DOMAIN)) {\n this.host.hostname = ICP_API_DOMAIN;\n }\n if (options.credentials) {\n const { name, password } = options.credentials;\n __classPrivateFieldSet(this, _HttpAgent_credentials, `${name}${password ? ':' + password : ''}`, \"f\");\n }\n __classPrivateFieldSet(this, _HttpAgent_identity, Promise.resolve(options.identity || new AnonymousIdentity()), \"f\");\n if (options.ingressExpiryInMinutes && options.ingressExpiryInMinutes > 5) {\n throw new AgentError(`The maximum ingress expiry time is 5 minutes. Provided ingress expiry time is ${options.ingressExpiryInMinutes} minutes.`);\n }\n if (options.ingressExpiryInMinutes && options.ingressExpiryInMinutes <= 0) {\n throw new AgentError(`Ingress expiry time must be greater than 0. Provided ingress expiry time is ${options.ingressExpiryInMinutes} minutes.`);\n }\n __classPrivateFieldSet(this, _HttpAgent_maxIngressExpiryInMinutes, options.ingressExpiryInMinutes || 5, \"f\");\n // Add a nonce transform to ensure calls are unique\n this.addTransform('update', makeNonceTransform(makeNonce));\n if (options.useQueryNonces) {\n this.addTransform('query', makeNonceTransform(makeNonce));\n }\n if (options.logToConsole) {\n this.log.subscribe(log => {\n if (log.level === 'error') {\n console.error(log.message);\n }\n else if (log.level === 'warn') {\n console.warn(log.message);\n }\n else {\n console.log(log.message);\n }\n });\n }\n }\n get waterMark() {\n return __classPrivateFieldGet(this, _HttpAgent_waterMark, \"f\");\n }\n static createSync(options = {}) {\n return new this(Object.assign({}, options));\n }\n static async create(options = {\n shouldFetchRootKey: false,\n }) {\n const agent = HttpAgent.createSync(options);\n const initPromises = [agent.syncTime()];\n if (agent.host.toString() !== 'https://icp-api.io' && options.shouldFetchRootKey) {\n initPromises.push(agent.fetchRootKey());\n }\n await Promise.all(initPromises);\n return agent;\n }\n static async from(agent) {\n var _a;\n try {\n if ('config' in agent) {\n return await HttpAgent.create(agent.config);\n }\n return await HttpAgent.create({\n fetch: agent._fetch,\n fetchOptions: agent._fetchOptions,\n callOptions: agent._callOptions,\n host: agent._host.toString(),\n identity: (_a = agent._identity) !== null && _a !== void 0 ? _a : undefined,\n });\n }\n catch (_b) {\n throw new AgentError('Failed to create agent from provided agent');\n }\n }\n isLocal() {\n const hostname = this.host.hostname;\n return hostname === '127.0.0.1' || hostname.endsWith('127.0.0.1');\n }\n addTransform(type, fn, priority = fn.priority || 0) {\n if (type === 'update') {\n // Keep the pipeline sorted at all time, by priority.\n const i = __classPrivateFieldGet(this, _HttpAgent_updatePipeline, \"f\").findIndex(x => (x.priority || 0) < priority);\n __classPrivateFieldGet(this, _HttpAgent_updatePipeline, \"f\").splice(i >= 0 ? i : __classPrivateFieldGet(this, _HttpAgent_updatePipeline, \"f\").length, 0, Object.assign(fn, { priority }));\n }\n else if (type === 'query') {\n // Keep the pipeline sorted at all time, by priority.\n const i = __classPrivateFieldGet(this, _HttpAgent_queryPipeline, \"f\").findIndex(x => (x.priority || 0) < priority);\n __classPrivateFieldGet(this, _HttpAgent_queryPipeline, \"f\").splice(i >= 0 ? i : __classPrivateFieldGet(this, _HttpAgent_queryPipeline, \"f\").length, 0, Object.assign(fn, { priority }));\n }\n }\n async getPrincipal() {\n if (!__classPrivateFieldGet(this, _HttpAgent_identity, \"f\")) {\n throw new IdentityInvalidError(\"This identity has expired due this application's security policy. Please refresh your authentication.\");\n }\n return (await __classPrivateFieldGet(this, _HttpAgent_identity, \"f\")).getPrincipal();\n }\n async call(canisterId, options, identity) {\n var _a;\n // TODO - restore this value\n const callSync = (_a = options.callSync) !== null && _a !== void 0 ? _a : true;\n const id = await (identity !== undefined ? await identity : await __classPrivateFieldGet(this, _HttpAgent_identity, \"f\"));\n if (!id) {\n throw new IdentityInvalidError(\"This identity has expired due this application's security policy. Please refresh your authentication.\");\n }\n const canister = Principal.from(canisterId);\n const ecid = options.effectiveCanisterId\n ? Principal.from(options.effectiveCanisterId)\n : canister;\n const sender = id.getPrincipal() || Principal.anonymous();\n let ingress_expiry = new Expiry(__classPrivateFieldGet(this, _HttpAgent_maxIngressExpiryInMinutes, \"f\") * MINUTE_TO_MSECS);\n // If the value is off by more than 30 seconds, reconcile system time with the network\n if (Math.abs(__classPrivateFieldGet(this, _HttpAgent_timeDiffMsecs, \"f\")) > 1000 * 30) {\n ingress_expiry = new Expiry(__classPrivateFieldGet(this, _HttpAgent_maxIngressExpiryInMinutes, \"f\") * MINUTE_TO_MSECS + __classPrivateFieldGet(this, _HttpAgent_timeDiffMsecs, \"f\"));\n }\n const submit = {\n request_type: SubmitRequestType.Call,\n canister_id: canister,\n method_name: options.methodName,\n arg: options.arg,\n sender,\n ingress_expiry,\n };\n let transformedRequest = (await this._transform({\n request: {\n body: null,\n method: 'POST',\n headers: Object.assign({ 'Content-Type': 'application/cbor' }, (__classPrivateFieldGet(this, _HttpAgent_credentials, \"f\") ? { Authorization: 'Basic ' + btoa(__classPrivateFieldGet(this, _HttpAgent_credentials, \"f\")) } : {})),\n },\n endpoint: \"call\" /* Endpoint.Call */,\n body: submit,\n }));\n const nonce = transformedRequest.body.nonce\n ? toNonce(transformedRequest.body.nonce)\n : undefined;\n submit.nonce = nonce;\n function toNonce(buf) {\n return new Uint8Array(buf);\n }\n // Apply transform for identity.\n transformedRequest = (await id.transformRequest(transformedRequest));\n const body = cbor.encode(transformedRequest.body);\n const backoff = __classPrivateFieldGet(this, _HttpAgent_backoffStrategy, \"f\").call(this);\n try {\n // Attempt v3 sync call\n const requestSync = () => {\n this.log.print(`fetching \"/api/v3/canister/${ecid.toText()}/call\" with request:`, transformedRequest);\n return __classPrivateFieldGet(this, _HttpAgent_fetch, \"f\").call(this, '' + new URL(`/api/v3/canister/${ecid.toText()}/call`, this.host), Object.assign(Object.assign(Object.assign({}, __classPrivateFieldGet(this, _HttpAgent_callOptions, \"f\")), transformedRequest.request), { body }));\n };\n const requestAsync = () => {\n this.log.print(`fetching \"/api/v2/canister/${ecid.toText()}/call\" with request:`, transformedRequest);\n return __classPrivateFieldGet(this, _HttpAgent_fetch, \"f\").call(this, '' + new URL(`/api/v2/canister/${ecid.toText()}/call`, this.host), Object.assign(Object.assign(Object.assign({}, __classPrivateFieldGet(this, _HttpAgent_callOptions, \"f\")), transformedRequest.request), { body }));\n };\n const request = __classPrivateFieldGet(this, _HttpAgent_instances, \"m\", _HttpAgent_requestAndRetry).call(this, {\n request: callSync ? requestSync : requestAsync,\n backoff,\n tries: 0,\n });\n const requestId = requestIdOf(submit);\n const response = await request;\n const responseBuffer = await response.arrayBuffer();\n const responseBody = (response.status === 200 && responseBuffer.byteLength > 0\n ? cbor.decode(responseBuffer)\n : null);\n // Update the watermark with the latest time from consensus\n if (responseBody && 'certificate' in responseBody) {\n const time = await this.parseTimeFromResponse({\n certificate: responseBody.certificate,\n });\n __classPrivateFieldSet(this, _HttpAgent_waterMark, time, \"f\");\n }\n return {\n requestId,\n response: {\n ok: response.ok,\n status: response.status,\n statusText: response.statusText,\n body: responseBody,\n headers: httpHeadersTransform(response.headers),\n },\n requestDetails: submit,\n };\n }\n catch (error) {\n // If the error is due to the v3 api not being supported, fall back to v2\n if (error.message.includes('v3 api not supported.')) {\n this.log.warn('v3 api not supported. Fall back to v2');\n return this.call(canisterId, Object.assign(Object.assign({}, options), { \n // disable v3 api\n callSync: false }), identity);\n }\n this.log.error('Error while making call:', error);\n throw error;\n }\n }\n async query(canisterId, fields, identity) {\n const backoff = __classPrivateFieldGet(this, _HttpAgent_backoffStrategy, \"f\").call(this);\n const ecid = fields.effectiveCanisterId\n ? Principal.from(fields.effectiveCanisterId)\n : Principal.from(canisterId);\n this.log.print(`ecid ${ecid.toString()}`);\n this.log.print(`canisterId ${canisterId.toString()}`);\n const makeQuery = async () => {\n const id = await (identity !== undefined ? identity : __classPrivateFieldGet(this, _HttpAgent_identity, \"f\"));\n if (!id) {\n throw new IdentityInvalidError(\"This identity has expired due this application's security policy. Please refresh your authentication.\");\n }\n const canister = Principal.from(canisterId);\n const sender = (id === null || id === void 0 ? void 0 : id.getPrincipal()) || Principal.anonymous();\n const request = {\n request_type: \"query\" /* ReadRequestType.Query */,\n canister_id: canister,\n method_name: fields.methodName,\n arg: fields.arg,\n sender,\n ingress_expiry: new Expiry(__classPrivateFieldGet(this, _HttpAgent_maxIngressExpiryInMinutes, \"f\") * MINUTE_TO_MSECS),\n };\n const requestId = requestIdOf(request);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let transformedRequest = await this._transform({\n request: {\n method: 'POST',\n headers: Object.assign({ 'Content-Type': 'application/cbor' }, (__classPrivateFieldGet(this, _HttpAgent_credentials, \"f\") ? { Authorization: 'Basic ' + btoa(__classPrivateFieldGet(this, _HttpAgent_credentials, \"f\")) } : {})),\n },\n endpoint: \"read\" /* Endpoint.Query */,\n body: request,\n });\n // Apply transform for identity.\n transformedRequest = (await (id === null || id === void 0 ? void 0 : id.transformRequest(transformedRequest)));\n const body = cbor.encode(transformedRequest.body);\n const args = {\n canister: canister.toText(),\n ecid,\n transformedRequest,\n body,\n requestId,\n backoff,\n tries: 0,\n };\n return {\n requestDetails: request,\n query: await __classPrivateFieldGet(this, _HttpAgent_instances, \"m\", _HttpAgent_requestAndRetryQuery).call(this, args),\n };\n };\n const getSubnetStatus = async () => {\n if (!__classPrivateFieldGet(this, _HttpAgent_verifyQuerySignatures, \"f\")) {\n return undefined;\n }\n const subnetStatus = __classPrivateFieldGet(this, _HttpAgent_subnetKeys, \"f\").get(ecid.toString());\n if (subnetStatus) {\n return subnetStatus;\n }\n await this.fetchSubnetKeys(ecid.toString());\n return __classPrivateFieldGet(this, _HttpAgent_subnetKeys, \"f\").get(ecid.toString());\n };\n // Attempt to make the query i=retryTimes times\n // Make query and fetch subnet keys in parallel\n const [queryResult, subnetStatus] = await Promise.all([makeQuery(), getSubnetStatus()]);\n const { requestDetails, query } = queryResult;\n const queryWithDetails = Object.assign(Object.assign({}, query), { requestDetails });\n this.log.print('Query response:', queryWithDetails);\n // Skip verification if the user has disabled it\n if (!__classPrivateFieldGet(this, _HttpAgent_verifyQuerySignatures, \"f\")) {\n return queryWithDetails;\n }\n try {\n return __classPrivateFieldGet(this, _HttpAgent_verifyQueryResponse, \"f\").call(this, queryWithDetails, subnetStatus);\n }\n catch (_a) {\n // In case the node signatures have changed, refresh the subnet keys and try again\n this.log.warn('Query response verification failed. Retrying with fresh subnet keys.');\n __classPrivateFieldGet(this, _HttpAgent_subnetKeys, \"f\").delete(canisterId.toString());\n await this.fetchSubnetKeys(ecid.toString());\n const updatedSubnetStatus = __classPrivateFieldGet(this, _HttpAgent_subnetKeys, \"f\").get(canisterId.toString());\n if (!updatedSubnetStatus) {\n throw new CertificateVerificationError('Invalid signature from replica signed query: no matching node key found.');\n }\n return __classPrivateFieldGet(this, _HttpAgent_verifyQueryResponse, \"f\").call(this, queryWithDetails, updatedSubnetStatus);\n }\n }\n async createReadStateRequest(fields, identity) {\n const id = await (identity !== undefined ? await identity : await __classPrivateFieldGet(this, _HttpAgent_identity, \"f\"));\n if (!id) {\n throw new IdentityInvalidError(\"This identity has expired due this application's security policy. Please refresh your authentication.\");\n }\n const sender = (id === null || id === void 0 ? void 0 : id.getPrincipal()) || Principal.anonymous();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const transformedRequest = await this._transform({\n request: {\n method: 'POST',\n headers: Object.assign({ 'Content-Type': 'application/cbor' }, (__classPrivateFieldGet(this, _HttpAgent_credentials, \"f\") ? { Authorization: 'Basic ' + btoa(__classPrivateFieldGet(this, _HttpAgent_credentials, \"f\")) } : {})),\n },\n endpoint: \"read_state\" /* Endpoint.ReadState */,\n body: {\n request_type: \"read_state\" /* ReadRequestType.ReadState */,\n paths: fields.paths,\n sender,\n ingress_expiry: new Expiry(__classPrivateFieldGet(this, _HttpAgent_maxIngressExpiryInMinutes, \"f\") * MINUTE_TO_MSECS),\n },\n });\n // Apply transform for identity.\n return id === null || id === void 0 ? void 0 : id.transformRequest(transformedRequest);\n }\n async readState(canisterId, fields, identity, \n // eslint-disable-next-line\n request) {\n const canister = typeof canisterId === 'string' ? Principal.fromText(canisterId) : canisterId;\n const transformedRequest = request !== null && request !== void 0 ? request : (await this.createReadStateRequest(fields, identity));\n // With read_state, we should always use a fresh expiry, even beyond the point where the initial request would have expired\n const bodyWithAdjustedExpiry = Object.assign(Object.assign({}, transformedRequest.body), { ingress_expiry: new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS) });\n const body = cbor.encode(bodyWithAdjustedExpiry);\n this.log.print(`fetching \"/api/v2/canister/${canister}/read_state\" with request:`, transformedRequest);\n // TODO - https://dfinity.atlassian.net/browse/SDK-1092\n const backoff = __classPrivateFieldGet(this, _HttpAgent_backoffStrategy, \"f\").call(this);\n try {\n const response = await __classPrivateFieldGet(this, _HttpAgent_instances, \"m\", _HttpAgent_requestAndRetry).call(this, {\n request: () => __classPrivateFieldGet(this, _HttpAgent_fetch, \"f\").call(this, '' + new URL(`/api/v2/canister/${canister.toString()}/read_state`, this.host), Object.assign(Object.assign(Object.assign({}, __classPrivateFieldGet(this, _HttpAgent_fetchOptions, \"f\")), transformedRequest.request), { body })),\n backoff,\n tries: 0,\n });\n if (!response.ok) {\n throw new Error(`Server returned an error:\\n` +\n ` Code: ${response.status} (${response.statusText})\\n` +\n ` Body: ${await response.text()}\\n`);\n }\n const decodedResponse = cbor.decode(await response.arrayBuffer());\n this.log.print('Read state response:', decodedResponse);\n const parsedTime = await this.parseTimeFromResponse(decodedResponse);\n if (parsedTime > 0) {\n this.log.print('Read state response time:', parsedTime);\n __classPrivateFieldSet(this, _HttpAgent_waterMark, parsedTime, \"f\");\n }\n return decodedResponse;\n }\n catch (error) {\n this.log.error('Caught exception while attempting to read state', error);\n throw error;\n }\n }\n async parseTimeFromResponse(response) {\n let tree;\n if (response.certificate) {\n const decoded = cbor.decode(response.certificate);\n if (decoded && 'tree' in decoded) {\n tree = decoded.tree;\n }\n else {\n throw new Error('Could not decode time from response');\n }\n const timeLookup = lookup_path(['time'], tree);\n if (timeLookup.status !== LookupStatus.Found) {\n throw new Error('Time was not found in the response or was not in its expected format.');\n }\n if (!(timeLookup.value instanceof ArrayBuffer) && !ArrayBuffer.isView(timeLookup)) {\n throw new Error('Time was not found in the response or was not in its expected format.');\n }\n const date = decodeTime(bufFromBufLike(timeLookup.value));\n this.log.print('Time from response:', date);\n this.log.print('Time from response in milliseconds:', Number(date));\n return Number(date);\n }\n else {\n this.log.warn('No certificate found in response');\n }\n return 0;\n }\n /**\n * Allows agent to sync its time with the network. Can be called during intialization or mid-lifecycle if the device's clock has drifted away from the network time. This is necessary to set the Expiry for a request\n * @param {Principal} canisterId - Pass a canister ID if you need to sync the time with a particular replica. Uses the management canister by default\n */\n async syncTime(canisterId) {\n const CanisterStatus = await import('../../canisterStatus');\n const callTime = Date.now();\n try {\n if (!canisterId) {\n this.log.print('Syncing time with the IC. No canisterId provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai');\n }\n const status = await CanisterStatus.request({\n // Fall back with canisterId of the ICP Ledger\n canisterId: canisterId !== null && canisterId !== void 0 ? canisterId : Principal.from('ryjl3-tyaaa-aaaaa-aaaba-cai'),\n agent: this,\n paths: ['time'],\n });\n const replicaTime = status.get('time');\n if (replicaTime) {\n __classPrivateFieldSet(this, _HttpAgent_timeDiffMsecs, Number(replicaTime) - Number(callTime), \"f\");\n }\n }\n catch (error) {\n this.log.error('Caught exception while attempting to sync time', error);\n }\n }\n async status() {\n const headers = __classPrivateFieldGet(this, _HttpAgent_credentials, \"f\")\n ? {\n Authorization: 'Basic ' + btoa(__classPrivateFieldGet(this, _HttpAgent_credentials, \"f\")),\n }\n : {};\n this.log.print(`fetching \"/api/v2/status\"`);\n const backoff = __classPrivateFieldGet(this, _HttpAgent_backoffStrategy, \"f\").call(this);\n const response = await __classPrivateFieldGet(this, _HttpAgent_instances, \"m\", _HttpAgent_requestAndRetry).call(this, {\n backoff,\n request: () => __classPrivateFieldGet(this, _HttpAgent_fetch, \"f\").call(this, '' + new URL(`/api/v2/status`, this.host), Object.assign({ headers }, __classPrivateFieldGet(this, _HttpAgent_fetchOptions, \"f\"))),\n tries: 0,\n });\n return cbor.decode(await response.arrayBuffer());\n }\n async fetchRootKey() {\n if (!__classPrivateFieldGet(this, _HttpAgent_rootKeyFetched, \"f\")) {\n const status = await this.status();\n // Hex-encoded version of the replica root key\n this.rootKey = status.root_key;\n __classPrivateFieldSet(this, _HttpAgent_rootKeyFetched, true, \"f\");\n }\n return this.rootKey;\n }\n invalidateIdentity() {\n __classPrivateFieldSet(this, _HttpAgent_identity, null, \"f\");\n }\n replaceIdentity(identity) {\n __classPrivateFieldSet(this, _HttpAgent_identity, Promise.resolve(identity), \"f\");\n }\n async fetchSubnetKeys(canisterId) {\n const effectiveCanisterId = Principal.from(canisterId);\n const response = await request({\n canisterId: effectiveCanisterId,\n paths: ['subnet'],\n agent: this,\n });\n const subnetResponse = response.get('subnet');\n if (subnetResponse && typeof subnetResponse === 'object' && 'nodeKeys' in subnetResponse) {\n __classPrivateFieldGet(this, _HttpAgent_subnetKeys, \"f\").set(effectiveCanisterId.toText(), subnetResponse);\n return subnetResponse;\n }\n // If the subnet status is not returned, return undefined\n return undefined;\n }\n _transform(request) {\n let p = Promise.resolve(request);\n if (request.endpoint === \"call\" /* Endpoint.Call */) {\n for (const fn of __classPrivateFieldGet(this, _HttpAgent_updatePipeline, \"f\")) {\n p = p.then(r => fn(r).then(r2 => r2 || r));\n }\n }\n else {\n for (const fn of __classPrivateFieldGet(this, _HttpAgent_queryPipeline, \"f\")) {\n p = p.then(r => fn(r).then(r2 => r2 || r));\n }\n }\n return p;\n }\n}\n_HttpAgent_identity = new WeakMap(), _HttpAgent_fetch = new WeakMap(), _HttpAgent_fetchOptions = new WeakMap(), _HttpAgent_callOptions = new WeakMap(), _HttpAgent_timeDiffMsecs = new WeakMap(), _HttpAgent_credentials = new WeakMap(), _HttpAgent_rootKeyFetched = new WeakMap(), _HttpAgent_retryTimes = new WeakMap(), _HttpAgent_backoffStrategy = new WeakMap(), _HttpAgent_maxIngressExpiryInMinutes = new WeakMap(), _HttpAgent_waterMark = new WeakMap(), _HttpAgent_queryPipeline = new WeakMap(), _HttpAgent_updatePipeline = new WeakMap(), _HttpAgent_subnetKeys = new WeakMap(), _HttpAgent_verifyQuerySignatures = new WeakMap(), _HttpAgent_verifyQueryResponse = new WeakMap(), _HttpAgent_instances = new WeakSet(), _HttpAgent_requestAndRetryQuery = async function _HttpAgent_requestAndRetryQuery(args) {\n var _a, _b;\n const { ecid, transformedRequest, body, requestId, backoff, tries } = args;\n const delay = tries === 0 ? 0 : backoff.next();\n this.log.print(`fetching \"/api/v2/canister/${ecid.toString()}/query\" with tries:`, {\n tries,\n backoff,\n delay,\n });\n // If delay is null, the backoff strategy is exhausted due to a maximum number of retries, duration, or other reason\n if (delay === null) {\n throw new AgentError(`Timestamp failed to pass the watermark after retrying the configured ${__classPrivateFieldGet(this, _HttpAgent_retryTimes, \"f\")} times. We cannot guarantee the integrity of the response since it could be a replay attack.`);\n }\n if (delay > 0) {\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n let response;\n // Make the request and retry if it throws an error\n try {\n this.log.print(`fetching \"/api/v2/canister/${ecid.toString()}/query\" with request:`, transformedRequest);\n const fetchResponse = await __classPrivateFieldGet(this, _HttpAgent_fetch, \"f\").call(this, '' + new URL(`/api/v2/canister/${ecid.toString()}/query`, this.host), Object.assign(Object.assign(Object.assign({}, __classPrivateFieldGet(this, _HttpAgent_fetchOptions, \"f\")), transformedRequest.request), { body }));\n if (fetchResponse.status === 200) {\n const queryResponse = cbor.decode(await fetchResponse.arrayBuffer());\n response = Object.assign(Object.assign({}, queryResponse), { httpDetails: {\n ok: fetchResponse.ok,\n status: fetchResponse.status,\n statusText: fetchResponse.statusText,\n headers: httpHeadersTransform(fetchResponse.headers),\n }, requestId });\n }\n else {\n throw new AgentHTTPResponseError(`Gateway returned an error:\\n` +\n ` Code: ${fetchResponse.status} (${fetchResponse.statusText})\\n` +\n ` Body: ${await fetchResponse.text()}\\n`, {\n ok: fetchResponse.ok,\n status: fetchResponse.status,\n statusText: fetchResponse.statusText,\n headers: httpHeadersTransform(fetchResponse.headers),\n });\n }\n }\n catch (error) {\n if (tries < __classPrivateFieldGet(this, _HttpAgent_retryTimes, \"f\")) {\n this.log.warn(`Caught exception while attempting to make query:\\n` +\n ` ${error}\\n` +\n ` Retrying query.`);\n return await __classPrivateFieldGet(this, _HttpAgent_instances, \"m\", _HttpAgent_requestAndRetryQuery).call(this, Object.assign(Object.assign({}, args), { tries: tries + 1 }));\n }\n throw error;\n }\n const timestamp = (_b = (_a = response.signatures) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.timestamp;\n // Skip watermark verification if the user has set verifyQuerySignatures to false\n if (!__classPrivateFieldGet(this, _HttpAgent_verifyQuerySignatures, \"f\")) {\n return response;\n }\n if (!timestamp) {\n throw new Error('Timestamp not found in query response. This suggests a malformed or malicious response.');\n }\n // Convert the timestamp to milliseconds\n const timeStampInMs = Number(BigInt(timestamp) / BigInt(1000000));\n this.log.print('watermark and timestamp', {\n waterMark: this.waterMark,\n timestamp: timeStampInMs,\n });\n // If the timestamp is less than the watermark, retry the request up to the retry limit\n if (Number(this.waterMark) > timeStampInMs) {\n const error = new AgentError('Timestamp is below the watermark. Retrying query.');\n this.log.error('Timestamp is below', error, {\n timestamp,\n waterMark: this.waterMark,\n });\n if (tries < __classPrivateFieldGet(this, _HttpAgent_retryTimes, \"f\")) {\n return await __classPrivateFieldGet(this, _HttpAgent_instances, \"m\", _HttpAgent_requestAndRetryQuery).call(this, Object.assign(Object.assign({}, args), { tries: tries + 1 }));\n }\n {\n throw new AgentError(`Timestamp failed to pass the watermark after retrying the configured ${__classPrivateFieldGet(this, _HttpAgent_retryTimes, \"f\")} times. We cannot guarantee the integrity of the response since it could be a replay attack.`);\n }\n }\n return response;\n}, _HttpAgent_requestAndRetry = async function _HttpAgent_requestAndRetry(args) {\n const { request, backoff, tries } = args;\n const delay = tries === 0 ? 0 : backoff.next();\n // If delay is null, the backoff strategy is exhausted due to a maximum number of retries, duration, or other reason\n if (delay === null) {\n throw new AgentError(`Timestamp failed to pass the watermark after retrying the configured ${__classPrivateFieldGet(this, _HttpAgent_retryTimes, \"f\")} times. We cannot guarantee the integrity of the response since it could be a replay attack.`);\n }\n if (delay > 0) {\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n let response;\n try {\n response = await request();\n }\n catch (error) {\n if (__classPrivateFieldGet(this, _HttpAgent_retryTimes, \"f\") > tries) {\n this.log.warn(`Caught exception while attempting to make request:\\n` +\n ` ${error}\\n` +\n ` Retrying request.`);\n // Delay the request by the configured backoff strategy\n return await __classPrivateFieldGet(this, _HttpAgent_instances, \"m\", _HttpAgent_requestAndRetry).call(this, { request, backoff, tries: tries + 1 });\n }\n throw error;\n }\n if (response.ok) {\n return response;\n }\n const responseText = await response.clone().text();\n const errorMessage = `Server returned an error:\\n` +\n ` Code: ${response.status} (${response.statusText})\\n` +\n ` Body: ${responseText}\\n`;\n if (response.status === 404 && response.url.includes('api/v3')) {\n throw new AgentHTTPResponseError('v3 api not supported. Fall back to v2', {\n ok: response.ok,\n status: response.status,\n statusText: response.statusText,\n headers: httpHeadersTransform(response.headers),\n });\n }\n if (tries < __classPrivateFieldGet(this, _HttpAgent_retryTimes, \"f\")) {\n return await __classPrivateFieldGet(this, _HttpAgent_instances, \"m\", _HttpAgent_requestAndRetry).call(this, { request, backoff, tries: tries + 1 });\n }\n throw new AgentHTTPResponseError(errorMessage, {\n ok: response.ok,\n status: response.status,\n statusText: response.statusText,\n headers: httpHeadersTransform(response.headers),\n });\n};\n//# sourceMappingURL=index.js.map","import { Principal } from '@dfinity/principal';\nexport var ProxyMessageKind;\n(function (ProxyMessageKind) {\n ProxyMessageKind[\"Error\"] = \"err\";\n ProxyMessageKind[\"GetPrincipal\"] = \"gp\";\n ProxyMessageKind[\"GetPrincipalResponse\"] = \"gpr\";\n ProxyMessageKind[\"Query\"] = \"q\";\n ProxyMessageKind[\"QueryResponse\"] = \"qr\";\n ProxyMessageKind[\"Call\"] = \"c\";\n ProxyMessageKind[\"CallResponse\"] = \"cr\";\n ProxyMessageKind[\"ReadState\"] = \"rs\";\n ProxyMessageKind[\"ReadStateResponse\"] = \"rsr\";\n ProxyMessageKind[\"Status\"] = \"s\";\n ProxyMessageKind[\"StatusResponse\"] = \"sr\";\n})(ProxyMessageKind || (ProxyMessageKind = {}));\n// A Stub Agent that forwards calls to another Agent implementation.\nexport class ProxyStubAgent {\n constructor(_frontend, _agent) {\n this._frontend = _frontend;\n this._agent = _agent;\n }\n onmessage(msg) {\n switch (msg.type) {\n case ProxyMessageKind.GetPrincipal:\n this._agent.getPrincipal().then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.GetPrincipalResponse,\n response: response.toText(),\n });\n });\n break;\n case ProxyMessageKind.Query:\n this._agent.query(...msg.args).then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.QueryResponse,\n response,\n });\n });\n break;\n case ProxyMessageKind.Call:\n this._agent.call(...msg.args).then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.CallResponse,\n response,\n });\n });\n break;\n case ProxyMessageKind.ReadState:\n this._agent.readState(...msg.args).then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.ReadStateResponse,\n response,\n });\n });\n break;\n case ProxyMessageKind.Status:\n this._agent.status().then(response => {\n this._frontend({\n id: msg.id,\n type: ProxyMessageKind.StatusResponse,\n response,\n });\n });\n break;\n default:\n throw new Error(`Invalid message received: ${JSON.stringify(msg)}`);\n }\n }\n}\n// An Agent that forwards calls to a backend. The calls are serialized\nexport class ProxyAgent {\n constructor(_backend) {\n this._backend = _backend;\n this._nextId = 0;\n this._pendingCalls = new Map();\n this.rootKey = null;\n }\n onmessage(msg) {\n const id = msg.id;\n const maybePromise = this._pendingCalls.get(id);\n if (!maybePromise) {\n throw new Error('A proxy get the same message twice...');\n }\n this._pendingCalls.delete(id);\n const [resolve, reject] = maybePromise;\n switch (msg.type) {\n case ProxyMessageKind.Error:\n return reject(msg.error);\n case ProxyMessageKind.GetPrincipalResponse:\n case ProxyMessageKind.CallResponse:\n case ProxyMessageKind.QueryResponse:\n case ProxyMessageKind.ReadStateResponse:\n case ProxyMessageKind.StatusResponse:\n return resolve(msg.response);\n default:\n throw new Error(`Invalid message being sent to ProxyAgent: ${JSON.stringify(msg)}`);\n }\n }\n async getPrincipal() {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.GetPrincipal,\n }).then(principal => {\n if (typeof principal !== 'string') {\n throw new Error('Invalid principal received.');\n }\n return Principal.fromText(principal);\n });\n }\n readState(canisterId, fields) {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.ReadState,\n args: [canisterId.toString(), fields],\n });\n }\n call(canisterId, fields) {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.Call,\n args: [canisterId.toString(), fields],\n });\n }\n status() {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.Status,\n });\n }\n query(canisterId, fields) {\n return this._sendAndWait({\n id: this._nextId++,\n type: ProxyMessageKind.Query,\n args: [canisterId.toString(), fields],\n });\n }\n async _sendAndWait(msg) {\n return new Promise((resolve, reject) => {\n this._pendingCalls.set(msg.id, [resolve, reject]);\n this._backend(msg);\n });\n }\n async fetchRootKey() {\n // Hex-encoded version of the replica root key\n const rootKey = (await this.status()).root_key;\n this.rootKey = rootKey;\n return rootKey;\n }\n}\n//# sourceMappingURL=proxy.js.map","import { lebEncode } from '@dfinity/candid';\nimport * as cbor from 'simple-cbor';\nimport { makeNonce, } from './types';\nconst NANOSECONDS_PER_MILLISECONDS = BigInt(1000000);\nconst REPLICA_PERMITTED_DRIFT_MILLISECONDS = 60 * 1000;\nexport class Expiry {\n constructor(deltaInMSec) {\n // if ingress as seconds is less than 90, round to nearest second\n if (deltaInMSec < 90 * 1000) {\n // Raw value without subtraction of REPLICA_PERMITTED_DRIFT_MILLISECONDS\n const raw_value = BigInt(Date.now() + deltaInMSec) * NANOSECONDS_PER_MILLISECONDS;\n const ingress_as_seconds = raw_value / BigInt(1000000000);\n this._value = ingress_as_seconds * BigInt(1000000000);\n return;\n }\n // Use bigint because it can overflow the maximum number allowed in a double float.\n const raw_value = BigInt(Math.floor(Date.now() + deltaInMSec - REPLICA_PERMITTED_DRIFT_MILLISECONDS)) *\n NANOSECONDS_PER_MILLISECONDS;\n // round down to the nearest second (since )\n const ingress_as_seconds = raw_value / BigInt(1000000000);\n // round down to nearest minute\n const ingress_as_minutes = ingress_as_seconds / BigInt(60);\n const rounded_down_nanos = ingress_as_minutes * BigInt(60) * BigInt(1000000000);\n this._value = rounded_down_nanos;\n }\n toCBOR() {\n // TODO: change this to take the minimum amount of space (it always takes 8 bytes now).\n return cbor.value.u64(this._value.toString(16), 16);\n }\n toHash() {\n return lebEncode(this._value);\n }\n}\n/**\n * Create a Nonce transform, which takes a function that returns a Buffer, and adds it\n * as the nonce to every call requests.\n * @param nonceFn A function that returns a buffer. By default uses a semi-random method.\n */\nexport function makeNonceTransform(nonceFn = makeNonce) {\n return async (request) => {\n // Nonce needs to be inserted into the header for all requests, to enable logs to be correlated with requests.\n const headers = request.request.headers;\n // TODO: uncomment this when the http proxy supports it.\n // headers.set('X-IC-Request-ID', toHex(new Uint8Array(nonce)));\n request.request.headers = headers;\n // Nonce only needs to be inserted into the body for async calls, to prevent replay attacks.\n if (request.endpoint === \"call\" /* Endpoint.Call */) {\n request.body.nonce = nonceFn();\n }\n };\n}\n/**\n * Create a transform that adds a delay (by default 5 minutes) to the expiry.\n *\n * @param delayInMilliseconds The delay to add to the call time, in milliseconds.\n */\nexport function makeExpiryTransform(delayInMilliseconds) {\n return async (request) => {\n request.body.ingress_expiry = new Expiry(delayInMilliseconds);\n };\n}\n/**\n * Maps the default fetch headers field to the serializable HttpHeaderField.\n *\n * @param headers Fetch definition of the headers type\n * @returns array of header fields\n */\nexport function httpHeadersTransform(headers) {\n const headerFields = [];\n headers.forEach((value, key) => {\n headerFields.push([key, value]);\n });\n return headerFields;\n}\n//# sourceMappingURL=transforms.js.map","import { bufEquals } from './utils/buffer';\nexport const encodeLenBytes = (len) => {\n if (len <= 0x7f) {\n return 1;\n }\n else if (len <= 0xff) {\n return 2;\n }\n else if (len <= 0xffff) {\n return 3;\n }\n else if (len <= 0xffffff) {\n return 4;\n }\n else {\n throw new Error('Length too long (> 4 bytes)');\n }\n};\nexport const encodeLen = (buf, offset, len) => {\n if (len <= 0x7f) {\n buf[offset] = len;\n return 1;\n }\n else if (len <= 0xff) {\n buf[offset] = 0x81;\n buf[offset + 1] = len;\n return 2;\n }\n else if (len <= 0xffff) {\n buf[offset] = 0x82;\n buf[offset + 1] = len >> 8;\n buf[offset + 2] = len;\n return 3;\n }\n else if (len <= 0xffffff) {\n buf[offset] = 0x83;\n buf[offset + 1] = len >> 16;\n buf[offset + 2] = len >> 8;\n buf[offset + 3] = len;\n return 4;\n }\n else {\n throw new Error('Length too long (> 4 bytes)');\n }\n};\nexport const decodeLenBytes = (buf, offset) => {\n if (buf[offset] < 0x80)\n return 1;\n if (buf[offset] === 0x80)\n throw new Error('Invalid length 0');\n if (buf[offset] === 0x81)\n return 2;\n if (buf[offset] === 0x82)\n return 3;\n if (buf[offset] === 0x83)\n return 4;\n throw new Error('Length too long (> 4 bytes)');\n};\nexport const decodeLen = (buf, offset) => {\n const lenBytes = decodeLenBytes(buf, offset);\n if (lenBytes === 1)\n return buf[offset];\n else if (lenBytes === 2)\n return buf[offset + 1];\n else if (lenBytes === 3)\n return (buf[offset + 1] << 8) + buf[offset + 2];\n else if (lenBytes === 4)\n return (buf[offset + 1] << 16) + (buf[offset + 2] << 8) + buf[offset + 3];\n throw new Error('Length too long (> 4 bytes)');\n};\n/**\n * A DER encoded `SEQUENCE(OID)` for DER-encoded-COSE\n */\nexport const DER_COSE_OID = Uint8Array.from([\n ...[0x30, 0x0c],\n ...[0x06, 0x0a],\n ...[0x2b, 0x06, 0x01, 0x04, 0x01, 0x83, 0xb8, 0x43, 0x01, 0x01], // DER encoded COSE\n]);\n/**\n * A DER encoded `SEQUENCE(OID)` for the Ed25519 algorithm\n */\nexport const ED25519_OID = Uint8Array.from([\n ...[0x30, 0x05],\n ...[0x06, 0x03],\n ...[0x2b, 0x65, 0x70], // id-Ed25519 OID\n]);\n/**\n * A DER encoded `SEQUENCE(OID)` for secp256k1 with the ECDSA algorithm\n */\nexport const SECP256K1_OID = Uint8Array.from([\n ...[0x30, 0x10],\n ...[0x06, 0x07],\n ...[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01],\n ...[0x06, 0x05],\n ...[0x2b, 0x81, 0x04, 0x00, 0x0a], // OID secp256k1\n]);\n/**\n * Wraps the given `payload` in a DER encoding tagged with the given encoded `oid` like so:\n * `SEQUENCE(oid, BITSTRING(payload))`\n *\n * @param payload The payload to encode as the bit string\n * @param oid The DER encoded (and SEQUENCE wrapped!) OID to tag the payload with\n */\nexport function wrapDER(payload, oid) {\n // The Bit String header needs to include the unused bit count byte in its length\n const bitStringHeaderLength = 2 + encodeLenBytes(payload.byteLength + 1);\n const len = oid.byteLength + bitStringHeaderLength + payload.byteLength;\n let offset = 0;\n const buf = new Uint8Array(1 + encodeLenBytes(len) + len);\n // Sequence\n buf[offset++] = 0x30;\n // Sequence Length\n offset += encodeLen(buf, offset, len);\n // OID\n buf.set(oid, offset);\n offset += oid.byteLength;\n // Bit String Header\n buf[offset++] = 0x03;\n offset += encodeLen(buf, offset, payload.byteLength + 1);\n // 0 padding\n buf[offset++] = 0x00;\n buf.set(new Uint8Array(payload), offset);\n return buf;\n}\n/**\n * Extracts a payload from the given `derEncoded` data, and checks that it was tagged with the given `oid`.\n *\n * `derEncoded = SEQUENCE(oid, BITSTRING(payload))`\n *\n * @param derEncoded The DER encoded and tagged data\n * @param oid The DER encoded (and SEQUENCE wrapped!) expected OID\n * @returns The unwrapped payload\n */\nexport const unwrapDER = (derEncoded, oid) => {\n let offset = 0;\n const expect = (n, msg) => {\n if (buf[offset++] !== n) {\n throw new Error('Expected: ' + msg);\n }\n };\n const buf = new Uint8Array(derEncoded);\n expect(0x30, 'sequence');\n offset += decodeLenBytes(buf, offset);\n if (!bufEquals(buf.slice(offset, offset + oid.byteLength), oid)) {\n throw new Error('Not the expected OID.');\n }\n offset += oid.byteLength;\n expect(0x03, 'bit string');\n const payloadLen = decodeLen(buf, offset) - 1; // Subtracting 1 to account for the 0 padding\n offset += decodeLenBytes(buf, offset);\n expect(0x00, '0 padding');\n const result = buf.slice(offset);\n if (payloadLen !== result.length) {\n throw new Error(`DER payload mismatch: Expected length ${payloadLen} actual length ${result.length}`);\n }\n return result;\n};\n//# sourceMappingURL=der.js.map","import { SignIdentity } from '@dfinity/agent';\nexport class CryptoError extends Error {\n constructor(message) {\n super(message);\n this.message = message;\n Object.setPrototypeOf(this, CryptoError.prototype);\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) {\n if (typeof global !== 'undefined' && global['crypto'] && global['crypto']['subtle']) {\n return global['crypto']['subtle'];\n }\n if (subtleCrypto) {\n return subtleCrypto;\n }\n else if (typeof crypto !== 'undefined' && crypto['subtle']) {\n return crypto.subtle;\n }\n else {\n throw new CryptoError('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 * 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 // `fromKeyPair` and `generate` should be used for instantiation, not this constructor.\n constructor(keyPair, derKey, subtleCrypto) {\n super();\n this._keyPair = keyPair;\n this._derKey = derKey;\n this._subtleCrypto = subtleCrypto;\n }\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 static async generate(options) {\n const { extractable = false, keyUsages = ['sign', 'verify'], subtleCrypto } = options !== null && options !== void 0 ? options : {};\n const effectiveCrypto = _getEffectiveCrypto(subtleCrypto);\n const keyPair = await effectiveCrypto.generateKey({\n name: 'ECDSA',\n namedCurve: 'P-256',\n }, extractable, keyUsages);\n const derKey = (await effectiveCrypto.exportKey('spki', keyPair.publicKey));\n return new this(keyPair, derKey, effectiveCrypto);\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 static async fromKeyPair(keyPair, subtleCrypto) {\n const effectiveCrypto = _getEffectiveCrypto(subtleCrypto);\n const derKey = (await effectiveCrypto.exportKey('spki', keyPair.publicKey));\n return new ECDSAKeyIdentity(keyPair, derKey, effectiveCrypto);\n }\n /**\n * Return the internally-used key pair.\n * @returns a CryptoKeyPair\n */\n getKeyPair() {\n return this._keyPair;\n }\n /**\n * Return the public key.\n * @returns an {@link PublicKey & DerCryptoKey}\n */\n getPublicKey() {\n const derKey = this._derKey;\n const key = Object.create(this._keyPair.publicKey);\n key.toDer = function () {\n return derKey;\n };\n return key;\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\n */\n async sign(challenge) {\n const params = {\n name: 'ECDSA',\n hash: { name: 'SHA-256' },\n };\n const signature = await this._subtleCrypto.sign(params, this._keyPair.privateKey, challenge);\n return signature;\n }\n}\nexport default ECDSAKeyIdentity;\n//# sourceMappingURL=ecdsa.js.map","var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nvar _PartialDelegationIdentity_delegation;\nimport { fromHex, requestIdOf, SignIdentity, toHex, } from '@dfinity/agent';\nimport { Principal } from '@dfinity/principal';\nimport * as cbor from 'simple-cbor';\nimport { PartialIdentity } from './partial';\nconst domainSeparator = new TextEncoder().encode('\\x1Aic-request-auth-delegation');\nconst requestDomainSeparator = new TextEncoder().encode('\\x0Aic-request');\nfunction _parseBlob(value) {\n if (typeof value !== 'string' || value.length < 64) {\n throw new Error('Invalid public key.');\n }\n return fromHex(value);\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(pubkey, expiration, targets) {\n this.pubkey = pubkey;\n this.expiration = expiration;\n this.targets = targets;\n }\n toCBOR() {\n // Expiration field needs to be encoded as a u64 specifically.\n return cbor.value.map(Object.assign({ pubkey: cbor.value.bytes(this.pubkey), expiration: cbor.value.u64(this.expiration.toString(16), 16) }, (this.targets && {\n targets: cbor.value.array(this.targets.map(t => cbor.value.bytes(t.toUint8Array()))),\n })));\n }\n toJSON() {\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 Object.assign({ expiration: this.expiration.toString(16), pubkey: toHex(this.pubkey) }, (this.targets && { targets: this.targets.map(p => p.toHex()) }));\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(from, to, expiration, targets) {\n const delegation = new Delegation(to.toDer(), BigInt(+expiration) * BigInt(1000000), // In nanoseconds.\n targets);\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(Object.assign({}, delegation))),\n ]);\n const signature = await from.sign(challenge);\n return {\n delegation,\n signature,\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 constructor(delegations, publicKey) {\n this.delegations = delegations;\n this.publicKey = publicKey;\n }\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 static async create(from, to, expiration = new Date(Date.now() + 15 * 60 * 1000), options = {}) {\n var _a, _b;\n const delegation = await _createSingleDelegation(from, to, expiration, options.targets);\n return new DelegationChain([...(((_a = options.previous) === null || _a === void 0 ? void 0 : _a.delegations) || []), delegation], ((_b = options.previous) === null || _b === void 0 ? void 0 : _b.publicKey) || from.getPublicKey().toDer());\n }\n /**\n * Creates a DelegationChain object from a JSON string.\n * @param json The JSON string to parse.\n */\n static fromJSON(json) {\n const { publicKey, delegations } = typeof json === 'string' ? JSON.parse(json) : json;\n if (!Array.isArray(delegations)) {\n throw new Error('Invalid delegations.');\n }\n const parsedDelegations = 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 return {\n delegation: new Delegation(_parseBlob(pubkey), BigInt('0x' + expiration), // expiration in JSON is an hexa string (See toJSON() below).\n targets &&\n targets.map((t) => {\n if (typeof t !== 'string') {\n throw new Error('Invalid target.');\n }\n return Principal.fromHex(t);\n })),\n signature: _parseBlob(signature),\n };\n });\n return new this(parsedDelegations, _parseBlob(publicKey));\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 static fromDelegations(delegations, publicKey) {\n return new this(delegations, publicKey);\n }\n toJSON() {\n return {\n delegations: this.delegations.map(signedDelegation => {\n const { delegation, signature } = signedDelegation;\n const { targets } = delegation;\n return {\n delegation: Object.assign({ expiration: delegation.expiration.toString(16), pubkey: toHex(delegation.pubkey) }, (targets && {\n targets: targets.map(t => t.toHex()),\n })),\n signature: toHex(signature),\n };\n }),\n publicKey: toHex(this.publicKey),\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 constructor(_inner, _delegation) {\n super();\n this._inner = _inner;\n this._delegation = _delegation;\n }\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 static fromDelegation(key, delegation) {\n return new this(key, delegation);\n }\n getDelegation() {\n return this._delegation;\n }\n getPublicKey() {\n return {\n derKey: this._delegation.publicKey,\n toDer: () => this._delegation.publicKey,\n };\n }\n sign(blob) {\n return this._inner.sign(blob);\n }\n async transformRequest(request) {\n const { body } = request, fields = __rest(request, [\"body\"]);\n const requestId = await requestIdOf(body);\n return Object.assign(Object.assign({}, fields), { body: {\n content: body,\n sender_sig: await this.sign(new Uint8Array([...requestDomainSeparator, ...new Uint8Array(requestId)])),\n sender_delegation: this._delegation.delegations,\n sender_pubkey: this._delegation.publicKey,\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 constructor(inner, delegation) {\n super(inner);\n _PartialDelegationIdentity_delegation.set(this, void 0);\n __classPrivateFieldSet(this, _PartialDelegationIdentity_delegation, delegation, \"f\");\n }\n /**\n * The Delegation Chain of this identity.\n */\n get delegation() {\n return __classPrivateFieldGet(this, _PartialDelegationIdentity_delegation, \"f\");\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 static fromDelegation(key, delegation) {\n return new PartialDelegationIdentity(key, delegation);\n }\n}\n_PartialDelegationIdentity_delegation = new WeakMap();\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, checks) {\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 // Check the scopes.\n const scopes = [];\n const maybeScope = checks === null || checks === void 0 ? void 0 : checks.scope;\n if (maybeScope) {\n if (Array.isArray(maybeScope)) {\n scopes.push(...maybeScope.map(s => (typeof s === 'string' ? Principal.fromText(s) : s)));\n }\n else {\n scopes.push(typeof maybeScope === 'string' ? Principal.fromText(maybeScope) : maybeScope);\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 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 return true;\n}\n//# sourceMappingURL=delegation.js.map","import { SignIdentity, wrapDER, DER_COSE_OID, fromHex, toHex, } from '@dfinity/agent';\nimport borc from 'borc';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { bufFromBufLike } from '@dfinity/candid';\nfunction _coseToDerEncodedBlob(cose) {\n return wrapDER(cose, DER_COSE_OID).buffer;\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) {\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 // Get the public key object.\n return authData.slice(55 + credentialIdLength);\n}\nexport class CosePublicKey {\n constructor(_cose) {\n this._cose = _cose;\n this._encodedKey = _coseToDerEncodedBlob(_cose);\n }\n toDer() {\n return this._encodedKey;\n }\n getCose() {\n return this._cose;\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 = '') {\n if (typeof challenge === 'string') {\n return Uint8Array.from(challenge, c => c.charCodeAt(0));\n }\n else {\n return challenge;\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(credentialCreationOptions) {\n const creds = (await navigator.credentials.create(credentialCreationOptions !== null && credentialCreationOptions !== void 0 ? 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 if (creds === null) {\n return null;\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// 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.\nvar PubKeyCoseAlgo;\n(function (PubKeyCoseAlgo) {\n PubKeyCoseAlgo[PubKeyCoseAlgo[\"ECDSA_WITH_SHA256\"] = -7] = \"ECDSA_WITH_SHA256\";\n})(PubKeyCoseAlgo || (PubKeyCoseAlgo = {}));\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 constructor(rawId, cose, authenticatorAttachment) {\n super();\n this.rawId = rawId;\n this.authenticatorAttachment = authenticatorAttachment;\n this._publicKey = new CosePublicKey(cose);\n }\n /**\n * Create an identity from a JSON serialization.\n * @param json - json to parse\n */\n static fromJSON(json) {\n const { publicKey, rawId } = JSON.parse(json);\n if (typeof publicKey !== 'string' || typeof rawId !== 'string') {\n throw new Error('Invalid JSON string.');\n }\n return new this(fromHex(rawId), fromHex(publicKey), undefined);\n }\n /**\n * Create an identity.\n * @param credentialCreationOptions an optional CredentialCreationOptions Challenge\n */\n static async create(credentialCreationOptions) {\n var _a;\n const creds = await _createCredential(credentialCreationOptions);\n if (!creds || creds.type !== 'public-key') {\n throw new Error('Could not create credentials.');\n }\n const response = creds.response;\n if (response.attestationObject === undefined) {\n throw new Error('Was expecting an attestation response.');\n }\n // Parse the attestationObject as CBOR.\n const attObject = borc.decodeFirst(new Uint8Array(response.attestationObject));\n return new this(creds.rawId, _authDataToCose(attObject.authData), (_a = creds.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined);\n }\n getPublicKey() {\n return this._publicKey;\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 getAuthenticatorAttachment() {\n return this.authenticatorAttachment;\n }\n async sign(blob) {\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 }));\n if (result.authenticatorAttachment !== null) {\n this.authenticatorAttachment = result.authenticatorAttachment;\n }\n const response = result.response;\n const cbor = borc.encode(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 if (!cbor) {\n throw new Error('failed to encode cbor');\n }\n return cbor.buffer;\n }\n /**\n * Allow for JSON serialization of all information needed to reuse this identity.\n */\n toJSON() {\n return {\n publicKey: toHex(this._publicKey.getCose()),\n rawId: toHex(this.rawId),\n };\n }\n}\n//# sourceMappingURL=webauthn.js.map","import { DelegationChain, DelegationIdentity } from \"@dfinity/identity\";\nimport { SignIdentity } from \"@dfinity/agent\";\nexport function buildDelegationIdentity(userKey, sessionKey, delegation, signature) {\n const delegations = [\n {\n delegation,\n signature,\n },\n ];\n const delegationChain = DelegationChain.fromDelegations(delegations, userKey.buffer);\n return DelegationIdentity.fromDelegation(sessionKey, delegationChain);\n}\nexport function toDer(key) {\n return new Uint8Array(key.getPublicKey().toDer());\n}\n","import { openDB } from 'idb';\nimport { DB_VERSION, isBrowser, KEY_STORAGE_DELEGATION, KEY_STORAGE_KEY } from './storage';\nconst AUTH_DB_NAME = 'auth-client-db';\nconst OBJECT_STORE_NAME = 'ic-keyval';\nconst _openDbStore = async (dbName = AUTH_DB_NAME, storeName = OBJECT_STORE_NAME, version) => {\n // Clear legacy stored delegations\n if (isBrowser && (localStorage === null || localStorage === void 0 ? void 0 : 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};\nasync function _getValue(db, storeName, key) {\n return await db.get(storeName, key);\n}\nasync function _setValue(db, storeName, key, value) {\n return await db.put(storeName, value, key);\n}\nasync function _removeValue(db, storeName, key) {\n return await db.delete(storeName, key);\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 // Do not use - instead prefer create\n constructor(_db, _storeName) {\n this._db = _db;\n this._storeName = _storeName;\n }\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 static async create(options) {\n const { dbName = AUTH_DB_NAME, storeName = OBJECT_STORE_NAME, version = DB_VERSION } = options !== null && options !== void 0 ? options : {};\n const db = await _openDbStore(dbName, storeName, version);\n return new IdbKeyVal(db, storeName);\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 async set(key, value) {\n return await _setValue(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`\n * @example\n * await get('exampleKey') -> 'exampleValue'\n */\n async get(key) {\n var _a;\n return (_a = (await _getValue(this._db, this._storeName, key))) !== null && _a !== void 0 ? _a : null;\n }\n /**\n * Remove a key\n * @param key {@link IDBValidKey}\n * @returns void\n */\n async remove(key) {\n return await _removeValue(this._db, this._storeName, key);\n }\n}\n//# sourceMappingURL=db.js.map","var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _IdbStorage_options;\nimport { IdbKeyVal } from './db';\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;\nexport const isBrowser = typeof window !== 'undefined';\n/**\n * Legacy implementation of AuthClientStorage, for use where IndexedDb is not available\n */\nexport class LocalStorage {\n constructor(prefix = 'ic-', _localStorage) {\n this.prefix = prefix;\n this._localStorage = _localStorage;\n }\n get(key) {\n return Promise.resolve(this._getLocalStorage().getItem(this.prefix + key));\n }\n set(key, value) {\n this._getLocalStorage().setItem(this.prefix + key, value);\n return Promise.resolve();\n }\n remove(key) {\n this._getLocalStorage().removeItem(this.prefix + key);\n return Promise.resolve();\n }\n _getLocalStorage() {\n if (this._localStorage) {\n return this._localStorage;\n }\n const ls = typeof window === 'undefined'\n ? typeof global === 'undefined'\n ? typeof self === 'undefined'\n ? undefined\n : self.localStorage\n : global.localStorage\n : window.localStorage;\n if (!ls) {\n throw new Error('Could not find local storage.');\n }\n return ls;\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 {\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) {\n _IdbStorage_options.set(this, void 0);\n __classPrivateFieldSet(this, _IdbStorage_options, options !== null && options !== void 0 ? options : {}, \"f\");\n }\n get _db() {\n return new Promise(resolve => {\n if (this.initializedDb) {\n resolve(this.initializedDb);\n return;\n }\n IdbKeyVal.create(__classPrivateFieldGet(this, _IdbStorage_options, \"f\")).then(db => {\n this.initializedDb = db;\n resolve(db);\n });\n });\n }\n async get(key) {\n const db = await this._db;\n return await db.get(key);\n // return (await db.get(key)) ?? null;\n }\n async set(key, value) {\n const db = await this._db;\n await db.set(key, value);\n }\n async remove(key) {\n const db = await this._db;\n await db.remove(key);\n }\n}\n_IdbStorage_options = new WeakMap();\n//# sourceMappingURL=storage.js.map","import { SignIdentity } from \"@dfinity/agent\";\nimport { IdbStorage } from \"@dfinity/auth-client\";\nimport { DelegationChain, DelegationIdentity, ECDSAKeyIdentity, isDelegationValid } from \"@dfinity/identity\";\nconst KEY_STORAGE_AUTH_PRINCIPAL = \"auth_principal\";\nconst KEY_STORAGE_KEY = \"identity\";\nconst KEY_STORAGE_DELEGATION = \"delegation\";\nexport class IdentityStorage {\n constructor(dbName) {\n this.storage = new IdbStorage({ dbName });\n }\n static createForAuthIdentity() {\n return new IdentityStorage(\"auth-client-db\");\n }\n static createForOcIdentity() {\n return new IdentityStorage(\"oc-auth-db\");\n }\n async get(authPrincipal) {\n if (authPrincipal !== undefined) {\n const storedAuthPrincipal = await this.storage.get(KEY_STORAGE_AUTH_PRINCIPAL);\n if (storedAuthPrincipal == null)\n return undefined;\n if (storedAuthPrincipal !== authPrincipal) {\n this.remove();\n return undefined;\n }\n }\n const key = await this.storage.get(KEY_STORAGE_KEY);\n if (key == null)\n return undefined;\n const chainJson = await this.storage.get(KEY_STORAGE_DELEGATION);\n if (chainJson == null)\n return undefined;\n const chain = DelegationChain.fromJSON(chainJson);\n if (!isDelegationValid(chain)) {\n this.remove();\n return undefined;\n }\n const id = await ECDSAKeyIdentity.fromKeyPair(key);\n return DelegationIdentity.fromDelegation(id, chain);\n }\n async set(key, chain, authPrincipal) {\n if (authPrincipal !== undefined) {\n await this.storage.set(KEY_STORAGE_AUTH_PRINCIPAL, authPrincipal);\n }\n await this.storage.set(KEY_STORAGE_KEY, key.getKeyPair());\n await this.storage.set(KEY_STORAGE_DELEGATION, JSON.stringify(chain.toJSON()));\n }\n async remove() {\n await this.storage.remove(KEY_STORAGE_AUTH_PRINCIPAL);\n await this.storage.remove(KEY_STORAGE_KEY);\n await this.storage.remove(KEY_STORAGE_DELEGATION);\n }\n}\n","export class Lazy {\n #value;\n constructor(initFn) {\n this.initFn = initFn;\n }\n get() {\n return this.#value ??= this.initFn();\n }\n}\n","!function(t,e){\"object\"==typeof exports&&\"object\"==typeof module?module.exports=e():\"function\"==typeof define&&define.amd?define([],e):\"object\"==typeof exports?exports.rollbar=e():t.rollbar=e()}(this,(function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){\"undefined\"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:\"Module\"}),Object.defineProperty(t,\"__esModule\",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&\"object\"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,\"default\",{enumerable:!0,value:t}),2&e&&\"string\"!=typeof t)for(var o in t)r.d(n,o,function(e){return t[e]}.bind(null,o));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,\"a\",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p=\"\",r(r.s=6)}([function(t,e,r){\"use strict\";var n=r(12),o={};function i(t,e){return e===s(t)}function s(t){var e=typeof t;return\"object\"!==e?e:t?t instanceof Error?\"error\":{}.toString.call(t).match(/\\s([a-zA-Z]+)/)[1].toLowerCase():\"null\"}function a(t){return i(t,\"function\")}function u(t){var e=Function.prototype.toString.call(Object.prototype.hasOwnProperty).replace(/[\\\\^$.*+?()[\\]{}|]/g,\"\\\\$&\").replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g,\"$1.*?\"),r=RegExp(\"^\"+e+\"$\");return c(t)&&r.test(t)}function c(t){var e=typeof t;return null!=t&&(\"object\"==e||\"function\"==e)}function l(){var t=y();return\"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g,(function(e){var r=(t+16*Math.random())%16|0;return t=Math.floor(t/16),(\"x\"===e?r:7&r|8).toString(16)}))}var p={strictMode:!1,key:[\"source\",\"protocol\",\"authority\",\"userInfo\",\"user\",\"password\",\"host\",\"port\",\"relative\",\"path\",\"directory\",\"file\",\"query\",\"anchor\"],q:{name:\"queryKey\",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\\/?#]+):)?(?:\\/\\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\\/?#]*)(?::(\\d*))?))?((((?:[^?#\\/]*\\/)*)([^?#]*))(?:\\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\\/]*@)([^:\\/?#.]+):)?(?:\\/\\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\\/?#]*)(?::(\\d*))?)(((\\/(?:[^?#](?![^?#\\/]*\\.[^?#\\/.]+(?:[?#]|$)))*\\/?)?([^?#\\/]*))(?:\\?([^#]*))?(?:#(.*))?)/}};function f(t,e){var r,n;try{r=o.stringify(t)}catch(o){if(e&&a(e))try{r=e(t)}catch(t){n=t}else n=o}return{error:n,value:r}}function h(t,e){return function(r,n){try{e(r,n)}catch(e){t.error(e)}}}function d(t){return function t(e,r){var n,o,a,u={};try{for(o in e)(n=e[o])&&(i(n,\"object\")||i(n,\"array\"))?r.includes(n)?u[o]=\"Removed circular reference: \"+s(n):((a=r.slice()).push(n),u[o]=t(n,a)):u[o]=n}catch(t){u=\"Failed cloning custom data: \"+t.message}return u}(t,[t])}var m=[\"log\",\"network\",\"dom\",\"navigation\",\"error\",\"manual\"],g=[\"critical\",\"error\",\"warning\",\"info\",\"debug\"];function v(t,e){for(var r=0;ra)?(s=e.path,e.path=s.substring(0,a)+i+\"&\"+s.substring(a+1)):-1!==u?(s=e.path,e.path=s.substring(0,u)+i+s.substring(u)):e.path=e.path+i},createItem:function(t,e,r,n,o){for(var i,a,u,c,p,f,m=[],g=[],v=0,b=t.length;v0&&(u||(u=d({})),u.extraArgs=d(m));var k={message:i,err:a,custom:u,timestamp:y(),callback:c,notifier:r,diagnostic:{},uuid:l()};return function(t,e){e&&void 0!==e.level&&(t.level=e.level,delete e.level);e&&void 0!==e.skipFrames&&(t.skipFrames=e.skipFrames,delete e.skipFrames)}(k,u),n&&p&&(k.request=p),o&&(k.lambdaContext=o),k._originalArgs=t,k.diagnostic.original_arg_types=g,k},addErrorContext:function(t,e){var r=t.data.custom||{},o=!1;try{for(var i=0;i2){var o=n.slice(0,3),i=o[2].indexOf(\"/\");-1!==i&&(o[2]=o[2].substring(0,i));r=o.concat(\"0000:0000:0000:0000:0000\").join(\":\")}}else r=null}catch(t){r=null}else r=null;t.user_ip=r}},formatArgsAsString:function(t){var e,r,n,o=[];for(e=0,r=t.length;e500&&(n=n.substr(0,497)+\"...\");break;case\"null\":n=\"null\";break;case\"undefined\":n=\"undefined\";break;case\"symbol\":n=n.toString()}o.push(n)}return o.join(\" \")},formatUrl:function(t,e){if(!(e=e||t.protocol)&&t.port&&(80===t.port?e=\"http:\":443===t.port&&(e=\"https:\")),e=e||\"https:\",!t.hostname)return null;var r=e+\"//\"+t.hostname;return t.port&&(r=r+\":\"+t.port),t.path&&(r+=t.path),r},get:function(t,e){if(t){var r=e.split(\".\"),n=t;try{for(var o=0,i=r.length;o=1&&r>e}function s(t,e,r,n,o,i,s){var a=null;return r&&(r=new Error(r)),r||n||(a=function(t,e,r,n,o){var i,s=e.environment||e.payload&&e.payload.environment;i=o?\"item per minute limit reached, ignoring errors until timeout\":\"maxItems has been hit, ignoring errors until reset.\";var a={body:{message:{body:i,extra:{maxItems:r,itemsPerMinute:n}}},language:\"javascript\",environment:s,notifier:{version:e.notifier&&e.notifier.version||e.version}};\"browser\"===t?(a.platform=\"browser\",a.framework=\"browser-js\",a.notifier.name=\"rollbar-browser-js\"):\"server\"===t?(a.framework=e.framework||\"node-js\",a.notifier.name=e.notifier.name):\"react-native\"===t&&(a.framework=e.framework||\"react-native\",a.notifier.name=e.notifier.name);return a}(t,e,o,i,s)),{error:r,shouldSend:n,payload:a}}o.globalSettings={startTime:n.now(),maxItems:void 0,itemsPerMinute:void 0},o.prototype.configureGlobal=function(t){void 0!==t.startTime&&(o.globalSettings.startTime=t.startTime),void 0!==t.maxItems&&(o.globalSettings.maxItems=t.maxItems),void 0!==t.itemsPerMinute&&(o.globalSettings.itemsPerMinute=t.itemsPerMinute)},o.prototype.shouldSend=function(t,e){var r=(e=e||n.now())-this.startTime;(r<0||r>=6e4)&&(this.startTime=e,this.perMinCounter=0);var a=o.globalSettings.maxItems,u=o.globalSettings.itemsPerMinute;if(i(t,a,this.counter))return s(this.platform,this.platformOptions,a+\" max items reached\",!1);if(i(t,u,this.perMinCounter))return s(this.platform,this.platformOptions,u+\" items per minute reached\",!1);this.counter++,this.perMinCounter++;var c=!i(t,a,this.counter),l=c;return c=c&&!i(t,u,this.perMinCounter),s(this.platform,this.platformOptions,null,c,a,u,l)},o.prototype.setPlatformOptions=function(t,e){this.platform=t,this.platformOptions=e},t.exports=o},function(t,e,r){\"use strict\";var n=Object.prototype.hasOwnProperty,o=Object.prototype.toString,i=function(t){if(!t||\"[object Object]\"!==o.call(t))return!1;var e,r=n.call(t,\"constructor\"),i=t.constructor&&t.constructor.prototype&&n.call(t.constructor.prototype,\"isPrototypeOf\");if(t.constructor&&!r&&!i)return!1;for(e in t);return void 0===e||n.call(t,e)};t.exports=function t(){var e,r,n,o,s,a={},u=null,c=arguments.length;for(e=0;ethis.options.maxRetries&&(o=!1))}o?this._retryApiRequest(e,r):r(t)},o.prototype._retryApiRequest=function(t,e){this.retryQueue.push({item:t,callback:e}),this.retryHandle||(this.retryHandle=setInterval(function(){for(;this.retryQueue.length;){var t=this.retryQueue.shift();this._makeApiRequest(t.item,t.callback)}}.bind(this),this.options.retryInterval))},o.prototype._dequeuePendingRequest=function(t){var e=this.pendingRequests.indexOf(t);-1!==e&&(this.pendingRequests.splice(e,1),this._maybeCallWait())},o.prototype._maybeLog=function(t,e){if(this.logger&&this.options.verbose){var r=e;if(r=(r=r||n.get(t,\"body.trace.exception.message\"))||n.get(t,\"body.trace_chain.0.exception.message\"))return void this.logger.error(r);(r=n.get(t,\"body.message.body\"))&&this.logger.log(r)}},o.prototype._maybeCallWait=function(){return!(!n.isFunction(this.waitCallback)||0!==this.pendingItems.length||0!==this.pendingRequests.length)&&(this.waitIntervalID&&(this.waitIntervalID=clearInterval(this.waitIntervalID)),this.waitCallback(),!0)},t.exports=o},function(t,e,r){\"use strict\";var n=r(0);function o(t,e){this.queue=t,this.options=e,this.transforms=[],this.diagnostic={}}o.prototype.configure=function(t){this.queue&&this.queue.configure(t);var e=this.options;return this.options=n.merge(e,t),this},o.prototype.addTransform=function(t){return n.isFunction(t)&&this.transforms.push(t),this},o.prototype.log=function(t,e){if(e&&n.isFunction(e)||(e=function(){}),!this.options.enabled)return e(new Error(\"Rollbar is not enabled\"));this.queue.addPendingItem(t);var r=t.err;this._applyTransforms(t,function(n,o){if(n)return this.queue.removePendingItem(t),e(n,null);this.queue.addItem(o,e,r,t)}.bind(this))},o.prototype._applyTransforms=function(t,e){var r=-1,n=this.transforms.length,o=this.transforms,i=this.options,s=function(t,a){t?e(t,null):++r!==n?o[r](a,i,s):e(null,a)};s(null,t)},t.exports=o},function(t,e,r){\"use strict\";var n=r(0),o=r(16),i={hostname:\"api.rollbar.com\",path:\"/api/1/item/\",search:null,version:\"1\",protocol:\"https:\",port:443};function s(t,e,r,n,o){this.options=t,this.transport=e,this.url=r,this.truncation=n,this.jsonBackup=o,this.accessToken=t.accessToken,this.transportOptions=a(t,r)}function a(t,e){return o.getTransportFromOptions(t,i,e)}s.prototype.postItem=function(t,e){var r=o.transportOptions(this.transportOptions,\"POST\"),n=o.buildPayload(this.accessToken,t,this.jsonBackup),i=this;setTimeout((function(){i.transport.post(i.accessToken,r,n,e)}),0)},s.prototype.buildJsonPayload=function(t,e){var r,i=o.buildPayload(this.accessToken,t,this.jsonBackup);return(r=this.truncation?this.truncation.truncate(i):n.stringify(i)).error?(e&&e(r.error),null):r.value},s.prototype.postJsonPayload=function(t,e){var r=o.transportOptions(this.transportOptions,\"POST\");this.transport.postJsonPayload(this.accessToken,r,t,e)},s.prototype.configure=function(t){var e=this.oldOptions;return this.options=n.merge(e,t),this.transportOptions=a(this.options,this.url),void 0!==this.options.accessToken&&(this.accessToken=this.options.accessToken),this},t.exports=s},function(t,e,r){\"use strict\";var n=r(0);t.exports={buildPayload:function(t,e,r){if(!n.isType(e.context,\"string\")){var o=n.stringify(e.context,r);o.error?e.context=\"Error: could not serialize 'context'\":e.context=o.value||\"\",e.context.length>255&&(e.context=e.context.substr(0,255))}return{access_token:t,data:e}},getTransportFromOptions:function(t,e,r){var n=e.hostname,o=e.protocol,i=e.port,s=e.path,a=e.search,u=t.timeout,c=function(t){var e=\"undefined\"!=typeof window&&window||\"undefined\"!=typeof self&&self,r=t.defaultTransport||\"xhr\";void 0===e.fetch&&(r=\"xhr\");void 0===e.XMLHttpRequest&&(r=\"fetch\");return r}(t),l=t.proxy;if(t.endpoint){var p=r.parse(t.endpoint);n=p.hostname,o=p.protocol,i=p.port,s=p.pathname,a=p.search}return{timeout:u,hostname:n,protocol:o,port:i,path:s,search:a,proxy:l,transport:c}},transportOptions:function(t,e){var r=t.protocol||\"https:\",n=t.port||(\"http:\"===r?80:\"https:\"===r?443:void 0),o=t.hostname,i=t.path,s=t.timeout,a=t.transport;return t.search&&(i+=t.search),t.proxy&&(i=r+\"//\"+o+i,o=t.proxy.host||t.proxy.hostname,n=t.proxy.port,r=t.proxy.protocol||r),{timeout:s,protocol:r,hostname:o,path:i,port:n,method:e,transport:a}},appendPathToPath:function(t,e){var r=/\\/$/.test(t),n=/^\\//.test(e);return r&&n?e=e.substring(1):r||n||(e=\"/\"+e),t+e}}},function(t,e){!function(t){\"use strict\";t.console||(t.console={});for(var e,r,n=t.console,o=function(){},i=[\"memory\"],s=\"assert,clear,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profiles,profileEnd,show,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn\".split(\",\");e=i.pop();)n[e]||(n[e]={});for(;r=s.pop();)n[r]||(n[r]=o)}(\"undefined\"==typeof window?this:window)},function(t,e,r){\"use strict\";var n={ieVersion:function(){if(\"undefined\"!=typeof document){for(var t=3,e=document.createElement(\"div\"),r=e.getElementsByTagName(\"i\");e.innerHTML=\"\\x3c!--[if gt IE \"+ ++t+\"]>4?t:void 0}}};t.exports=n},function(t,e,r){\"use strict\";function n(t,e,r,n){t._rollbarWrappedError&&(n[4]||(n[4]=t._rollbarWrappedError),n[5]||(n[5]=t._rollbarWrappedError._rollbarContext),t._rollbarWrappedError=null);var o=e.handleUncaughtException.apply(e,n);r&&r.apply(t,n),\"anonymous\"===o&&(e.anonymousErrorsPending+=1)}t.exports={captureUncaughtExceptions:function(t,e,r){if(t){var o;if(\"function\"==typeof e._rollbarOldOnError)o=e._rollbarOldOnError;else if(t.onerror){for(o=t.onerror;o._rollbarOldOnError;)o=o._rollbarOldOnError;e._rollbarOldOnError=o}e.handleAnonymousErrors();var i=function(){var r=Array.prototype.slice.call(arguments,0);n(t,e,o,r)};r&&(i._rollbarOldOnError=o),t.onerror=i}},captureUnhandledRejections:function(t,e,r){if(t){\"function\"==typeof t._rollbarURH&&t._rollbarURH.belongsToShim&&t.removeEventListener(\"unhandledrejection\",t._rollbarURH);var n=function(t){var r,n,o;try{r=t.reason}catch(t){r=void 0}try{n=t.promise}catch(t){n=\"[unhandledrejection] error getting `promise` from event\"}try{o=t.detail,!r&&o&&(r=o.reason,n=o.promise)}catch(t){}r||(r=\"[unhandledrejection] error getting `reason` from event\"),e&&e.handleUnhandledRejection&&e.handleUnhandledRejection(r,n)};n.belongsToShim=r,t._rollbarURH=n,t.addEventListener(\"unhandledrejection\",n)}}}},function(t,e,r){\"use strict\";var n=r(0),o=r(21),i=r(22);function s(t){this.truncation=t}s.prototype.get=function(t,e,r,o,i){o&&n.isFunction(o)||(o=function(){}),n.addParamsAndAccessTokenToPath(t,e,r);var s=n.formatUrl(e);this._makeZoneRequest(t,s,\"GET\",null,o,i,e.timeout,e.transport)},s.prototype.post=function(t,e,r,o,i){if(o&&n.isFunction(o)||(o=function(){}),!r)return o(new Error(\"Cannot send empty request\"));var s;if((s=this.truncation?this.truncation.truncate(r):n.stringify(r)).error)return o(s.error);var a=s.value,u=n.formatUrl(e);this._makeZoneRequest(t,u,\"POST\",a,o,i,e.timeout,e.transport)},s.prototype.postJsonPayload=function(t,e,r,o,i){o&&n.isFunction(o)||(o=function(){});var s=n.formatUrl(e);this._makeZoneRequest(t,s,\"POST\",r,o,i,e.timeout,e.transport)},s.prototype._makeZoneRequest=function(){var t=\"undefined\"!=typeof window&&window||void 0!==o&&o,e=t&&t.Zone&&t.Zone.current,r=Array.prototype.slice.call(arguments);if(e&&\"angular\"===e._name){var n=e._parent,o=this;n.run((function(){o._makeRequest.apply(void 0,r)}))}else this._makeRequest.apply(void 0,r)},s.prototype._makeRequest=function(t,e,r,n,s,a,u,c){if(\"undefined\"!=typeof RollbarProxy)return function(t,e){(new RollbarProxy).sendJsonPayload(t,(function(t){}),(function(t){e(new Error(t))}))}(n,s);\"fetch\"===c?o(t,e,r,n,s,u):i(t,e,r,n,s,a,u)},t.exports=s},function(t,e,r){\"use strict\";var n=r(1),o=r(0);t.exports=function(t,e,r,i,s,a){var u,c;o.isFiniteNumber(a)&&(u=new AbortController,c=setTimeout((function(){u.abort()}),a)),fetch(e,{method:r,headers:{\"Content-Type\":\"application/json\",\"X-Rollbar-Access-Token\":t,signal:u&&u.signal},body:i}).then((function(t){return c&&clearTimeout(c),t.json()})).then((function(t){s(null,t)})).catch((function(t){n.error(t.message),s(t)}))}},function(t,e,r){\"use strict\";var n=r(0),o=r(1);function i(t,e){var r=new Error(t);return r.code=e||\"ENOTFOUND\",r}t.exports=function(t,e,r,s,a,u,c){var l;if(!(l=u?u():function(){var t,e,r=[function(){return new XMLHttpRequest},function(){return new ActiveXObject(\"Msxml2.XMLHTTP\")},function(){return new ActiveXObject(\"Msxml3.XMLHTTP\")},function(){return new ActiveXObject(\"Microsoft.XMLHTTP\")}],n=r.length;for(e=0;e=400&&t.status<600}(l)){if(403===l.status){var e=t.value&&t.value.message;o.error(e)}a(new Error(String(l.status)))}else{a(i(\"XHR response had no status code (likely connection failure)\"))}}}catch(t){var r;r=t&&t.stack?t:new Error(t),a(r)}var s};l.open(r,e,!0),l.setRequestHeader&&(l.setRequestHeader(\"Content-Type\",\"application/json\"),l.setRequestHeader(\"X-Rollbar-Access-Token\",t)),n.isFiniteNumber(c)&&(l.timeout=c),l.onreadystatechange=p,l.send(s)}catch(t){if(\"undefined\"!=typeof XDomainRequest){if(!window||!window.location)return a(new Error(\"No window available during request, unknown environment\"));\"http:\"===window.location.href.substring(0,5)&&\"https\"===e.substring(0,5)&&(e=\"http\"+e.substring(5));var f=new XDomainRequest;f.onprogress=function(){},f.ontimeout=function(){a(i(\"Request timed out\",\"ETIMEDOUT\"))},f.onerror=function(){a(new Error(\"Error during request\"))},f.onload=function(){var t=n.jsonParse(f.responseText);a(t.error,t.value)},f.open(r,e,!0),f.send(s)}else a(new Error(\"Cannot find a method to transport a request\"))}}catch(t){a(t)}}},function(t,e,r){\"use strict\";var n=r(0),o=r(3),i=r(1);function s(t,e,r){var o=t.message,i=t.custom;o||(o=\"Item sent with null or missing arguments.\");var s={body:o};i&&(s.extra=n.merge(i)),n.set(t,\"data.body\",{message:s}),r(null,t)}function a(t){var e=t.stackInfo.stack;return e&&0===e.length&&t._unhandledStackInfo&&t._unhandledStackInfo.stack&&(e=t._unhandledStackInfo.stack),e}function u(t,e,r){var i=t&&t.data.description,s=t&&t.custom,u=a(t),l=o.guessErrorClass(e.message),p={exception:{class:c(e,l[0],r),message:l[1]}};if(i&&(p.exception.description=i),u){var f,h,d,m,g,v,y,b;for(0===u.length&&(p.exception.stack=e.rawStack,p.exception.raw=String(e.rawException)),p.frames=[],y=0;y0&&n.set(e,\"data.request\",i),o(null,e)}},addClientInfo:function(t){return function(e,r,o){if(!t)return o(null,e);var i=t.navigator||{},s=t.screen||{};n.set(e,\"data.client\",{runtime_ms:e.timestamp-t._rollbarStartTime,timestamp:Math.round(e.timestamp/1e3),javascript:{browser:i.userAgent,language:i.language,cookie_enabled:i.cookieEnabled,screen:{width:s.width,height:s.height}}}),o(null,e)}},addPluginInfo:function(t){return function(e,r,o){if(!t||!t.navigator)return o(null,e);for(var i,s=[],a=t.navigator.plugins||[],u=0,c=a.length;u-1&&(e=e.replace(/eval code/g,\"eval\").replace(/(\\(eval at [^()]*)|(,.*$)/g,\"\"));var r=e.replace(/^\\s+/,\"\").replace(/\\(eval code/g,\"(\").replace(/^.*?\\s+/,\"\"),n=r.match(/ (\\(.+\\)$)/);r=n?r.replace(n[0],\"\"):r;var o=this.extractLocation(n?n[1]:r),i=n&&r||void 0,s=[\"eval\",\"\"].indexOf(o[0])>-1?void 0:o[0];return new t({functionName:i,fileName:s,lineNumber:o[1],columnNumber:o[2],source:e})}),this)},parseFFOrSafari:function(e){return e.stack.split(\"\\n\").filter((function(t){return!t.match(n)}),this).map((function(e){if(e.indexOf(\" > eval\")>-1&&(e=e.replace(/ line (\\d+)(?: > eval line \\d+)* > eval:\\d+:\\d+/g,\":$1\")),-1===e.indexOf(\"@\")&&-1===e.indexOf(\":\"))return new t({functionName:e});var r=/((.*\".+\"[^@]*)?[^@]*)(?:@)/,n=e.match(r),o=n&&n[1]?n[1]:void 0,i=this.extractLocation(e.replace(r,\"\"));return new t({functionName:o,fileName:i[0],lineNumber:i[1],columnNumber:i[2],source:e})}),this)},parseOpera:function(t){return!t.stacktrace||t.message.indexOf(\"\\n\")>-1&&t.message.split(\"\\n\").length>t.stacktrace.split(\"\\n\").length?this.parseOpera9(t):t.stack?this.parseOpera11(t):this.parseOpera10(t)},parseOpera9:function(e){for(var r=/Line (\\d+).*script (?:in )?(\\S+)/i,n=e.message.split(\"\\n\"),o=[],i=2,s=n.length;i/,\"$2\").replace(/\\([^)]*\\)/g,\"\")||void 0;i.match(/\\(([^)]*)\\)/)&&(r=i.replace(/^[^(]+\\(([^)]*)\\)$/,\"$1\"));var a=void 0===r||\"[arguments not available]\"===r?void 0:r.split(\",\");return new t({functionName:s,args:a,fileName:o[0],lineNumber:o[1],columnNumber:o[2],source:e})}),this)}}})?n.apply(e,o):n)||(t.exports=i)}()},function(t,e,r){var n,o,i;!function(r,s){\"use strict\";o=[],void 0===(i=\"function\"==typeof(n=function(){function t(t){return t.charAt(0).toUpperCase()+t.substring(1)}function e(t){return function(){return this[t]}}var r=[\"isConstructor\",\"isEval\",\"isNative\",\"isToplevel\"],n=[\"columnNumber\",\"lineNumber\"],o=[\"fileName\",\"functionName\",\"source\"],i=r.concat(n,o,[\"args\"],[\"evalOrigin\"]);function s(e){if(e)for(var r=0;ro&&(i=this.queue.length-o),this.maxQueueSize=o,this.queue.splice(0,i)},o.prototype.copyEvents=function(){var t=Array.prototype.slice.call(this.queue,0);if(n.isFunction(this.options.filterTelemetry))try{for(var e=t.length;e--;)this.options.filterTelemetry(t[e])&&t.splice(e,1)}catch(t){this.options.filterTelemetry=null}return t},o.prototype.capture=function(t,e,r,o,s){var a={level:i(t,r),type:t,timestamp_ms:s||n.now(),body:e,source:\"client\"};o&&(a.uuid=o);try{if(n.isFunction(this.options.filterTelemetry)&&this.options.filterTelemetry(a))return!1}catch(t){this.options.filterTelemetry=null}return this.push(a),a},o.prototype.captureEvent=function(t,e,r,n){return this.capture(t,e,r,n)},o.prototype.captureError=function(t,e,r,n){var o={message:t.message||String(t)};return t.stack&&(o.stack=t.stack),this.capture(\"error\",o,e,r,n)},o.prototype.captureLog=function(t,e,r,n){return this.capture(\"log\",{message:t},e,r,n)},o.prototype.captureNetwork=function(t,e,r,n){e=e||\"xhr\",t.subtype=t.subtype||e,n&&(t.request=n);var o=this.levelFromStatus(t.status_code);return this.capture(\"network\",t,o,r)},o.prototype.levelFromStatus=function(t){return t>=200&&t<400?\"info\":0===t||t>=400?\"error\":\"info\"},o.prototype.captureDom=function(t,e,r,n,o){var i={subtype:t,element:e};return void 0!==r&&(i.value=r),void 0!==n&&(i.checked=n),this.capture(\"dom\",i,\"info\",o)},o.prototype.captureNavigation=function(t,e,r){return this.capture(\"navigation\",{from:t,to:e},\"info\",r)},o.prototype.captureDomContentLoaded=function(t){return this.capture(\"navigation\",{subtype:\"DOMContentLoaded\"},\"info\",void 0,t&&t.getTime())},o.prototype.captureLoad=function(t){return this.capture(\"navigation\",{subtype:\"load\"},\"info\",void 0,t&&t.getTime())},o.prototype.captureConnectivityChange=function(t,e){return this.captureNetwork({change:t},\"connectivity\",e)},o.prototype._captureRollbarItem=function(t){if(this.options.includeItemsInTelemetry)return t.err?this.captureError(t.err,t.level,t.uuid,t.timestamp):t.message?this.captureLog(t.message,t.level,t.uuid,t.timestamp):t.custom?this.capture(\"log\",t.custom,t.level,t.uuid,t.timestamp):void 0},o.prototype.push=function(t){this.queue.push(t),this.queue.length>this.maxQueueSize&&this.queue.shift()},t.exports=o},function(t,e,r){\"use strict\";var n=r(0),o=r(33),i=r(4),s=r(2),a=r(34),u={network:!0,networkResponseHeaders:!1,networkResponseBody:!1,networkRequestHeaders:!1,networkRequestBody:!1,networkErrorOnHttp5xx:!1,networkErrorOnHttp4xx:!1,networkErrorOnHttp0:!1,log:!0,dom:!0,navigation:!0,connectivity:!0,contentSecurityPolicy:!0,errorOnContentSecurityPolicy:!1};function c(t,e,r,n,o){var i=t[e];t[e]=r(i),n&&n[o].push([t,e,i])}function l(t,e){for(var r;t[e].length;)(r=t[e].shift())[0][r[1]]=r[2]}function p(t,e,r,o,i){this.options=t;var s=t.autoInstrument;!1===t.enabled||!1===s?this.autoInstrument={}:(n.isType(s,\"object\")||(s=u),this.autoInstrument=n.merge(u,s)),this.scrubTelemetryInputs=!!t.scrubTelemetryInputs,this.telemetryScrubber=t.telemetryScrubber,this.defaultValueScrubber=function(t){for(var e=[],r=0;r3)){i.__rollbar_xhr.end_time_ms=n.now();var e=null;if(i.__rollbar_xhr.response_content_type=i.getResponseHeader(\"Content-Type\"),t.autoInstrument.networkResponseHeaders){var r=t.autoInstrument.networkResponseHeaders;e={};try{var s,a;if(!0===r){var u=i.getAllResponseHeaders();if(u){var c,l,p=u.trim().split(/[\\r\\n]+/);for(a=0;a=500&&this.autoInstrument.networkErrorOnHttp5xx||e>=400&&this.autoInstrument.networkErrorOnHttp4xx||0===e&&this.autoInstrument.networkErrorOnHttp0){var r=new Error(\"HTTP request failed with Status \"+e);r.stack=t.stack,this.rollbar.error(r,{skipFrames:1})}},p.prototype.deinstrumentConsole=function(){if(\"console\"in this._window&&this._window.console.log)for(var t;this.replacements.log.length;)t=this.replacements.log.shift(),this._window.console[t[0]]=t[1]},p.prototype.instrumentConsole=function(){if(\"console\"in this._window&&this._window.console.log){var t=this,e=this._window.console,r=[\"debug\",\"info\",\"warn\",\"error\",\"log\"];try{for(var o=0,i=r.length;o=0&&t.options[t.selectedIndex]&&this.captureDomEvent(\"input\",t,t.options[t.selectedIndex].value)},p.prototype.captureDomEvent=function(t,e,r,n){if(void 0!==r)if(this.scrubTelemetryInputs||\"password\"===a.getElementType(e))r=\"[scrubbed]\";else{var o=a.describeElement(e);this.telemetryScrubber?this.telemetryScrubber(o)&&(r=\"[scrubbed]\"):this.defaultValueScrubber(o)&&(r=\"[scrubbed]\")}var i=a.elementArrayToString(a.treeToArray(e));this.telemeter.captureDom(t,i,r,n)},p.prototype.deinstrumentNavigation=function(){var t=this._window.chrome;!(t&&t.app&&t.app.runtime)&&this._window.history&&this._window.history.pushState&&l(this.replacements,\"navigation\")},p.prototype.instrumentNavigation=function(){var t=this._window.chrome;if(!(t&&t.app&&t.app.runtime)&&this._window.history&&this._window.history.pushState){var e=this;c(this._window,\"onpopstate\",(function(t){return function(){var r=e._location.href;e.handleUrlChange(e._lastHref,r),t&&t.apply(this,arguments)}}),this.replacements,\"navigation\"),c(this._window.history,\"pushState\",(function(t){return function(){var r=arguments.length>2?arguments[2]:void 0;return r&&e.handleUrlChange(e._lastHref,r+\"\"),t.apply(this,arguments)}}),this.replacements,\"navigation\")}},p.prototype.handleUrlChange=function(t,e){var r=s.parse(this._location.href),n=s.parse(e),o=s.parse(t);this._lastHref=e,r.protocol===n.protocol&&r.host===n.host&&(e=n.path+(n.hash||\"\")),r.protocol===o.protocol&&r.host===o.host&&(t=o.path+(o.hash||\"\")),this.telemeter.captureNavigation(t,e)},p.prototype.deinstrumentConnectivity=function(){(\"addEventListener\"in this._window||\"body\"in this._document)&&(this._window.addEventListener?this.removeListeners(\"connectivity\"):l(this.replacements,\"connectivity\"))},p.prototype.instrumentConnectivity=function(){if(\"addEventListener\"in this._window||\"body\"in this._document)if(this._window.addEventListener)this.addListener(\"connectivity\",this._window,\"online\",void 0,function(){this.telemeter.captureConnectivityChange(\"online\")}.bind(this),!0),this.addListener(\"connectivity\",this._window,\"offline\",void 0,function(){this.telemeter.captureConnectivityChange(\"offline\")}.bind(this),!0);else{var t=this;c(this._document.body,\"ononline\",(function(e){return function(){t.telemeter.captureConnectivityChange(\"online\"),e&&e.apply(this,arguments)}}),this.replacements,\"connectivity\"),c(this._document.body,\"onoffline\",(function(e){return function(){t.telemeter.captureConnectivityChange(\"offline\"),e&&e.apply(this,arguments)}}),this.replacements,\"connectivity\")}},p.prototype.handleCspEvent=function(t){var e=\"Security Policy Violation: blockedURI: \"+t.blockedURI+\", violatedDirective: \"+t.violatedDirective+\", effectiveDirective: \"+t.effectiveDirective+\", \";t.sourceFile&&(e+=\"location: \"+t.sourceFile+\", line: \"+t.lineNumber+\", col: \"+t.columnNumber+\", \"),e+=\"originalPolicy: \"+t.originalPolicy,this.telemeter.captureLog(e,\"error\"),this.handleCspError(e)},p.prototype.handleCspError=function(t){this.autoInstrument.errorOnContentSecurityPolicy&&this.rollbar.error(t)},p.prototype.deinstrumentContentSecurityPolicy=function(){\"addEventListener\"in this._document&&this.removeListeners(\"contentsecuritypolicy\")},p.prototype.instrumentContentSecurityPolicy=function(){if(\"addEventListener\"in this._document){var t=this.handleCspEvent.bind(this);this.addListener(\"contentsecuritypolicy\",this._document,\"securitypolicyviolation\",null,t,!1)}},p.prototype.addListener=function(t,e,r,n,o,i){e.addEventListener?(e.addEventListener(r,o,i),this.eventRemovers[t].push((function(){e.removeEventListener(r,o,i)}))):n&&(e.attachEvent(n,o),this.eventRemovers[t].push((function(){e.detachEvent(n,o)})))},p.prototype.removeListeners=function(t){for(;this.eventRemovers[t].length;)this.eventRemovers[t].shift()()},t.exports=p},function(t,e,r){\"use strict\";function n(t){return\"string\"!=typeof t&&(t=String(t)),t.toLowerCase()}function o(t){this.map={},t instanceof o?t.forEach((function(t,e){this.append(e,t)}),this):Array.isArray(t)?t.forEach((function(t){this.append(t[0],t[1])}),this):t&&Object.getOwnPropertyNames(t).forEach((function(e){this.append(e,t[e])}),this)}o.prototype.append=function(t,e){t=n(t),e=function(t){return\"string\"!=typeof t&&(t=String(t)),t}(e);var r=this.map[t];this.map[t]=r?r+\", \"+e:e},o.prototype.get=function(t){return t=n(t),this.has(t)?this.map[t]:null},o.prototype.has=function(t){return this.map.hasOwnProperty(n(t))},o.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)},o.prototype.entries=function(){var t=[];return this.forEach((function(e,r){t.push([r,e])})),function(t){return{next:function(){var e=t.shift();return{done:void 0===e,value:e}}}}(t)},t.exports=function(t){return\"undefined\"==typeof Headers?new o(t):new Headers(t)}},function(t,e,r){\"use strict\";function n(t){return(t.getAttribute(\"type\")||\"\").toLowerCase()}function o(t){if(!t||!t.tagName)return\"\";var e=[t.tagName];t.id&&e.push(\"#\"+t.id),t.classes&&e.push(\".\"+t.classes.join(\".\"));for(var r=0;r \".length,i=[],s=0,a=t.length-1;a>=0;a--){if(e=o(t[a]),r=s+i.length*n+e.length,a=83){i.unshift(\"...\");break}i.unshift(e),s+=e.length}return i.join(\" > \")},treeToArray:function(t){for(var e,r=[],n=0;t&&n<5&&\"html\"!==(e=i(t)).tagName;n++)r.unshift(e),t=t.parentNode;return r},getElementFromEvent:function(t,e){return t.target?t.target:e&&e.elementFromPoint?e.elementFromPoint(t.clientX,t.clientY):void 0},isDescribedElement:function(t,e,r){if(t.tagName.toLowerCase()!==e.toLowerCase())return!1;if(!r)return!0;t=n(t);for(var o=0;o2*e?t.slice(0,e).concat(t.slice(r-e)):t}function a(t,e,r){r=void 0===r?30:r;var o,i=t.data.body;if(i.trace_chain)for(var a=i.trace_chain,u=0;ut?e.slice(0,t-3).concat(\"...\"):e}function c(t,e,r){return[e=o(e,(function e(r,i,s){switch(n.typeName(i)){case\"string\":return u(t,i);case\"object\":case\"array\":return o(i,e,s);default:return i}})),n.stringify(e,r)]}function l(t){return t.exception&&(delete t.exception.description,t.exception.message=u(255,t.exception.message)),t.frames=s(t.frames,1),t}function p(t,e){var r=t.data.body;if(r.trace_chain)for(var o=r.trace_chain,i=0;ie}t.exports={truncate:function(t,e,r){r=void 0===r?524288:r;for(var n,o,s,u=[i,a,c.bind(null,1024),c.bind(null,512),c.bind(null,256),p];n=u.shift();)if(t=(o=n(t,e))[0],(s=o[1]).error||!f(s.value,r))return s;return s},raw:i,truncateFrames:a,truncateStrings:c,maybeTruncateValue:u}}])}));\n//# sourceMappingURL=rollbar.umd.min.js.map","export const ONLINE_THRESHOLD = 120;\nexport const MAX_MESSAGES = 100;\nexport const MAX_EVENTS = 500;\nexport const MAX_ACTIVITY_EVENTS = 1000;\nexport const MAX_MISSING = 30;\nexport const OPENCHAT_VIDEO_CALL_USER_ID = \"wp3oc-ig6b4-6xvef-yoj27-qt3kw-u2xmp-qbvuv-2grco-s2ndy-wv3ud-7qe\";\nexport const OPENCHAT_VIDEO_CALL_USERNAME = \"VideoCallBot\";\nexport const OPENCHAT_VIDEO_CALL_AVATAR_URL = \"/assets/video_call.svg\";\nexport const OPENCHAT_BOT_USER_ID = \"zzyk3-openc-hatbo-tq7my-cai\";\nexport const OPENCHAT_BOT_USERNAME = \"OpenChatBot\";\nexport const OPENCHAT_BOT_AVATAR_URL = \"/assets/robot.svg\";\nexport const AIRDROP_BOT_USERNAME = \"AirdropBot\";\nexport const AIRDROP_BOT_AVATAR_URL = \"/assets/airdrop_bot.svg\";\nexport const WEBAUTHN_ORIGINATING_CANISTER = \"zzzxd-webau-thnke-yr7oc-cai\";\n// downlink is the effective bandwidth estimate in megabits per second, rounded to the nearest multiple of 25 kilobits per seconds.\nexport const MIN_DOWNLINK = 0.05;\nexport const ONE_MINUTE_MILLIS = 60 * 1000;\nexport const ONE_HOUR = 60 * ONE_MINUTE_MILLIS;\nexport const ONE_DAY = 24 * ONE_HOUR;\nexport const ONE_WEEK = ONE_DAY * 7;\nexport const ONE_MONTH = ONE_WEEK * 4;\nexport const ONE_YEAR = 365 * ONE_DAY;\nexport const LARGE_GROUP_THRESHOLD = 1000;\n","import { MIN_DOWNLINK } from \"../constants\";\nexport function offline() {\n return !navigator.onLine || criticalBandwith();\n}\nfunction criticalBandwith() {\n return (\"connection\" in navigator &&\n navigator.connection !== undefined &&\n navigator.connection.downlink < MIN_DOWNLINK);\n}\n","import Rollbar, {} from \"rollbar\";\nimport { offline } from \"./network\";\nimport { AnonymousOperationError } from \"../domain\";\nlet rollbar;\nexport function inititaliseLogger(apikey, version, env) {\n if (env === \"production\") {\n rollbar = Rollbar.init({\n accessToken: apikey,\n captureUncaught: true,\n autoInstrument: false,\n logLevel: \"error\",\n environment: env,\n enabled: env === \"production\",\n captureUnhandledRejections: true,\n payload: {\n environment: env,\n client: {\n javascript: {\n source_map_enabled: true,\n code_version: version,\n guess_uncaught_frames: true,\n },\n },\n },\n });\n }\n return {\n error(message, error, ...optionalParams) {\n if (error instanceof AnonymousOperationError)\n return;\n console.error(message, error, optionalParams);\n if (!offline()) {\n rollbar?.error(error, message, optionalParams);\n }\n },\n log(message, ...optionalParams) {\n console.log(message, optionalParams);\n },\n debug(message, ...optionalParams) {\n console.debug(message, optionalParams);\n },\n };\n}\nexport function debug(data, msg) {\n if (msg) {\n console.log(msg, data);\n }\n else {\n console.log(data);\n }\n return data;\n}\nexport function logDuration(msg, started) {\n console.debug(`PERF: ${msg}`, Date.now() - started);\n}\n","/**\n * we have quite a few maps that are keyed on chatId\n * These are usually Record\n * But that doesn't work with ChatIdentifier\n * */\nexport class SafeMap {\n constructor(toString, fromString, _map = new Map()) {\n this.toString = toString;\n this.fromString = fromString;\n this._map = _map;\n }\n map(fn) {\n const mapped = [...this._map.entries()].map(([k, v]) => {\n return [k, fn(this.fromString(k), v)];\n });\n return new SafeMap(this.toString, this.fromString, new Map(mapped));\n }\n merge(other) {\n other.forEach((val, key) => {\n this.set(key, val);\n });\n return this;\n }\n filter(fn) {\n return this.entries()\n .filter(([k, v]) => {\n return fn(v, k);\n })\n .reduce((agg, [k, v]) => {\n agg.set(k, v);\n return agg;\n }, new SafeMap(this.toString, this.fromString));\n }\n clone() {\n const clone = new SafeMap(this.toString, this.fromString, new Map(this._map));\n return clone;\n }\n empty() {\n return new SafeMap(this.toString, this.fromString);\n }\n clear() {\n this._map.clear();\n }\n values() {\n return [...this._map.values()];\n }\n keys() {\n return [...this._map.keys()].map((k) => this.fromString(k));\n }\n entries() {\n return [...this._map.entries()].map(([key, value]) => [\n this.fromString(key),\n value,\n ]);\n }\n delete(key) {\n if (this._map.size === 0)\n return false;\n return this._map.delete(this.toString(key));\n }\n forEach(callbackfn) {\n this._map.forEach((value, key) => {\n callbackfn(value, this.fromString(key));\n });\n }\n get(key) {\n if (this._map.size === 0)\n return undefined;\n return this._map.get(this.toString(key));\n }\n has(key) {\n if (this._map.size === 0)\n return false;\n return this._map.has(this.toString(key));\n }\n set(key, value) {\n this._map.set(this.toString(key), value);\n return this;\n }\n get size() {\n return this._map.size;\n }\n toMap() {\n return this._map;\n }\n}\n// This is a bit weird\nexport class GlobalMap extends SafeMap {\n constructor(_map = new Map()) {\n super((_) => \"global\", (_) => \"global\", _map);\n }\n}\nexport class ChatMap extends SafeMap {\n constructor(_map = new Map()) {\n super((k) => JSON.stringify(k), (k) => JSON.parse(k), _map);\n }\n static fromList(things) {\n return things.reduce((map, c) => {\n map.set(c.id, c);\n return map;\n }, new ChatMap());\n }\n static fromMap(map) {\n return new ChatMap(map);\n }\n static fromJSON(json) {\n return new ChatMap(new Map(JSON.parse(json)));\n }\n}\nexport class MessageContextMap extends SafeMap {\n constructor(_map = new Map()) {\n super((k) => JSON.stringify(k), (k) => JSON.parse(k), _map);\n }\n static fromMap(map) {\n return new MessageContextMap(map);\n }\n}\nexport class CommunityMap extends SafeMap {\n constructor() {\n super((k) => k.communityId, (k) => ({ kind: \"community\", communityId: k }));\n }\n static fromList(things) {\n return things.reduce((map, c) => {\n map.set(c.id, c);\n return map;\n }, new CommunityMap());\n }\n}\nexport class MessageMap extends SafeMap {\n constructor(entries) {\n super((k) => k.toString(), (k) => BigInt(k));\n if (entries !== undefined) {\n for (const [k, v] of entries) {\n this.set(k, v);\n }\n }\n }\n}\nexport function getOrAdd(map, key, value) {\n const existing = map.get(key);\n if (existing !== undefined) {\n return existing;\n }\n map.set(key, value);\n return value;\n}\n","export async function waitAll(promises) {\n const results = await Promise.allSettled(promises);\n const success = [];\n const errors = [];\n for (const result of results) {\n if (result.status === \"fulfilled\") {\n success.push(result.value);\n }\n else {\n errors.push(result.reason);\n }\n }\n return {\n success,\n errors,\n };\n}\n","export function random32() {\n const bytes = new Uint32Array(1);\n crypto.getRandomValues(bytes);\n return bytes[0];\n}\nexport function random64() {\n const bytes = new BigUint64Array(1);\n crypto.getRandomValues(bytes);\n return bytes[0];\n}\nexport function random128() {\n const bytes = new BigUint64Array(2);\n crypto.getRandomValues(bytes);\n return (bytes[0] << BigInt(64)) + bytes[1];\n}\n","export function getTimeUntilSessionExpiryMs(identity) {\n if (!(\"getDelegation\" in identity)) {\n return 0;\n }\n const expiryDateTimestampMs = Number(identity\n .getDelegation()\n .delegations.map((d) => d.delegation.expiration)\n .reduce((current, next) => (next < current ? next : current)) / BigInt(1_000_000));\n return expiryDateTimestampMs - Date.now();\n}\n","import { Principal } from \"@dfinity/principal\";\nexport const HEX_REGEX = new RegExp(\"^[A-Fa-f0-9]+$\");\nexport function toTitleCase(str) {\n return str.replace(/\\w\\S*/g, (txt) => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase());\n}\nexport function isPrincipalValid(text) {\n try {\n Principal.fromText(text);\n return true;\n }\n catch (_e) {\n return false;\n }\n}\nexport function isSubAccountValid(text) {\n return text.length <= 64 && isHexString(text);\n}\nexport function isAccountIdentifierValid(text) {\n return text.length === 64 && isHexString(text);\n}\nexport function isHexString(text) {\n return HEX_REGEX.test(text);\n}\nexport function isUrl(text) {\n try {\n new URL(text);\n return true;\n }\n catch {\n return false;\n }\n}\n","import { emptyChatMetrics } from \"../../utils\";\nexport function isAttachmentContent(content) {\n switch (content.kind) {\n case \"image_content\":\n case \"video_content\":\n case \"audio_content\":\n case \"file_content\":\n return true;\n default:\n return false;\n }\n}\nexport function isEditableContent(kind) {\n switch (kind) {\n case \"file_content\":\n case \"text_content\":\n case \"image_content\":\n case \"video_content\":\n case \"audio_content\":\n case \"giphy_content\":\n return true;\n default:\n return false;\n }\n}\nexport function isCaptionedContent(content) {\n switch (content.kind) {\n case \"image_content\":\n case \"video_content\":\n case \"audio_content\":\n case \"file_content\":\n case \"crypto_content\":\n case \"giphy_content\":\n case \"prize_content\":\n case \"p2p_swap_content\":\n return true;\n default:\n return false;\n }\n}\nexport function isTransfer(content) {\n return (content.kind === \"crypto_content\" ||\n content.kind === \"prize_content_initial\" ||\n content.kind === \"p2p_swap_content_initial\");\n}\nexport function canRetryMessage(content) {\n return (content.kind !== \"poll_content\" &&\n content.kind !== \"crypto_content\" &&\n content.kind !== \"prize_content_initial\" &&\n content.kind !== \"p2p_swap_content_initial\");\n}\nexport var ProposalDecisionStatus;\n(function (ProposalDecisionStatus) {\n ProposalDecisionStatus[ProposalDecisionStatus[\"Unspecified\"] = 0] = \"Unspecified\";\n ProposalDecisionStatus[ProposalDecisionStatus[\"Failed\"] = 1] = \"Failed\";\n ProposalDecisionStatus[ProposalDecisionStatus[\"Open\"] = 2] = \"Open\";\n ProposalDecisionStatus[ProposalDecisionStatus[\"Rejected\"] = 3] = \"Rejected\";\n ProposalDecisionStatus[ProposalDecisionStatus[\"Executed\"] = 4] = \"Executed\";\n ProposalDecisionStatus[ProposalDecisionStatus[\"Adopted\"] = 5] = \"Adopted\";\n})(ProposalDecisionStatus || (ProposalDecisionStatus = {}));\nexport var ProposalRewardStatus;\n(function (ProposalRewardStatus) {\n ProposalRewardStatus[ProposalRewardStatus[\"Unspecified\"] = 0] = \"Unspecified\";\n ProposalRewardStatus[ProposalRewardStatus[\"AcceptVotes\"] = 1] = \"AcceptVotes\";\n ProposalRewardStatus[ProposalRewardStatus[\"ReadyToSettle\"] = 2] = \"ReadyToSettle\";\n ProposalRewardStatus[ProposalRewardStatus[\"Settled\"] = 3] = \"Settled\";\n})(ProposalRewardStatus || (ProposalRewardStatus = {}));\nexport var NnsProposalTopic;\n(function (NnsProposalTopic) {\n NnsProposalTopic[NnsProposalTopic[\"Unspecified\"] = 0] = \"Unspecified\";\n NnsProposalTopic[NnsProposalTopic[\"NeuronManagement\"] = 1] = \"NeuronManagement\";\n NnsProposalTopic[NnsProposalTopic[\"ExchangeRate\"] = 2] = \"ExchangeRate\";\n NnsProposalTopic[NnsProposalTopic[\"NetworkEconomics\"] = 3] = \"NetworkEconomics\";\n NnsProposalTopic[NnsProposalTopic[\"Governance\"] = 4] = \"Governance\";\n NnsProposalTopic[NnsProposalTopic[\"NodeAdmin\"] = 5] = \"NodeAdmin\";\n NnsProposalTopic[NnsProposalTopic[\"ParticipantManagement\"] = 6] = \"ParticipantManagement\";\n NnsProposalTopic[NnsProposalTopic[\"SubnetManagement\"] = 7] = \"SubnetManagement\";\n NnsProposalTopic[NnsProposalTopic[\"NetworkCanisterManagement\"] = 8] = \"NetworkCanisterManagement\";\n NnsProposalTopic[NnsProposalTopic[\"KYC\"] = 9] = \"KYC\";\n NnsProposalTopic[NnsProposalTopic[\"NodeProviderRewards\"] = 10] = \"NodeProviderRewards\";\n NnsProposalTopic[NnsProposalTopic[\"SnsDecentralizationSale\"] = 11] = \"SnsDecentralizationSale\";\n NnsProposalTopic[NnsProposalTopic[\"SubnetReplicaVersionManagement\"] = 12] = \"SubnetReplicaVersionManagement\";\n NnsProposalTopic[NnsProposalTopic[\"ReplicaVersionManagement\"] = 13] = \"ReplicaVersionManagement\";\n NnsProposalTopic[NnsProposalTopic[\"SnsAndCommunityFund\"] = 14] = \"SnsAndCommunityFund\";\n})(NnsProposalTopic || (NnsProposalTopic = {}));\nexport function messageContextFromString(ctxStr) {\n return JSON.parse(ctxStr);\n}\nexport function messageContextToString(ctx) {\n return JSON.stringify(ctx);\n}\nexport function messageContextsEqual(a, b) {\n if (a === undefined && b === undefined) {\n return true;\n }\n if (a === undefined || b === undefined) {\n return false;\n }\n return (chatIdentifiersEqual(a.chatId, b.chatId) &&\n a.threadRootMessageIndex === b.threadRootMessageIndex);\n}\nexport function chatIdentifierUnset(id) {\n if (id === undefined)\n return true;\n switch (id.kind) {\n case \"channel\":\n return id.channelId === 0;\n case \"direct_chat\":\n return id.userId === \"\";\n case \"group_chat\":\n return id.groupId === \"\";\n }\n}\nexport function chatScopesEqual(a, b) {\n if (a.kind === \"community\" && b.kind === \"community\")\n return a.id.communityId === b.id.communityId;\n if (a.kind === \"favourite\" && b.kind === \"favourite\")\n return a.communityId === b.communityId;\n return a.kind === b.kind;\n}\nexport function chatIdentifiersEqual(a, b) {\n if (a === undefined && b === undefined) {\n return true;\n }\n if (a === undefined || b === undefined) {\n return false;\n }\n if (a.kind !== b.kind) {\n return false;\n }\n switch (a.kind) {\n case \"channel\":\n return (b.kind === \"channel\" &&\n a.communityId === b.communityId &&\n a.channelId === b.channelId);\n case \"direct_chat\":\n return b.kind === \"direct_chat\" && a.userId === b.userId;\n case \"group_chat\":\n return b.kind === \"group_chat\" && a.groupId === b.groupId;\n }\n}\nexport function nullMembership() {\n return {\n joined: BigInt(0),\n role: \"none\",\n mentions: [],\n latestThreads: [],\n myMetrics: emptyChatMetrics(),\n notificationsMuted: false,\n readByMeUpTo: undefined,\n archived: false,\n rulesAccepted: false,\n lapsed: false,\n };\n}\n","export class UnsupportedValueError extends Error {\n constructor(msg, value) {\n super(`${msg}: ${value}`);\n }\n}\nexport class HttpError extends Error {\n constructor(code, error) {\n super(error.message);\n this.code = code;\n this.stack = error.stack;\n this.name = \"HttpError\";\n }\n}\nexport class NoMeetingToJoin extends Error {\n}\nexport class AuthError extends HttpError {\n constructor(code, error) {\n super(code, error);\n this.code = code;\n this.name = \"AuthError\";\n }\n}\nexport class SessionExpiryError extends HttpError {\n constructor(code, error) {\n super(code, error);\n this.code = code;\n this.name = \"SessionExpiryError\";\n }\n}\nexport class DestinationInvalidError extends HttpError {\n constructor(error) {\n super(404, error);\n this.name = \"DestinationInvalidError\";\n }\n}\nexport class ResponseTooLargeError extends HttpError {\n constructor(error, size, maxSize) {\n super(500, error);\n this.size = size;\n this.maxSize = maxSize;\n this.name = \"ResponseTooLargeError\";\n }\n}\nexport class InvalidDelegationError extends HttpError {\n constructor(error) {\n super(403, error);\n this.name = \"InvalidDelegationError\";\n }\n}\nexport class TypeboxValidationError extends Error {\n constructor(error) {\n super();\n this.name = \"TypeboxValidationError\";\n this.message = error?.message ?? \"\";\n this.stack = error?.stack;\n }\n}\n// We'll use this is the front end tries to do something that the anonymous user should not be able to do\nexport class AnonymousOperationError extends Error {\n constructor() {\n super();\n this.name = \"AnonymousOperationError\";\n }\n}\n","export class StorageUpdated extends CustomEvent {\n constructor(detail) {\n super(\"openchat_event\", { detail });\n }\n}\nexport class UsersLoaded extends CustomEvent {\n constructor(detail) {\n super(\"openchat_event\", { detail });\n }\n}\nexport class MessagesReadFromServer extends CustomEvent {\n constructor(chatId, readByMeUpTo, threadsRead, dateReadPinned) {\n super(\"openchat_event\", {\n detail: {\n chatId,\n readByMeUpTo,\n threadsRead,\n dateReadPinned,\n },\n });\n }\n}\n","export function codeToText(code) {\n return code.toString(16).padStart(16, \"0\");\n}\nexport function textToCode(codeStr) {\n // This also decodes potentially extant old-style base64 encoded invite codes\n return codeStr.length === 16 ? BigInt(\"0x\" + codeStr) : base64ToBigint(codeStr);\n}\nfunction base64ToBigint(b64) {\n const bin = atob(b64);\n const hex = [];\n bin.split(\"\").forEach(function (ch) {\n let h = ch.charCodeAt(0).toString(16);\n if (h.length % 2) {\n h = \"0\" + h;\n }\n hex.push(h);\n });\n return BigInt(\"0x\" + hex.join(\"\"));\n}\n","export function applyOptionUpdate(original, update) {\n if (update === undefined)\n return original;\n if (update === \"set_to_none\")\n return undefined;\n return update.value;\n}\nexport function mapOptionUpdate(original, mapper) {\n if (original === undefined || original === \"set_to_none\")\n return original;\n return { value: mapper(original.value) };\n}\nexport function updateFromOptions(original, updated) {\n return original === updated\n ? undefined\n : updated === undefined\n ? \"set_to_none\"\n : { value: updated };\n}\n","export const allRoles = [\"none\", \"owner\", \"admin\", \"moderator\", \"member\"];\nexport const chatRoles = allRoles;\nexport const communityRoles = [\"owner\", \"admin\", \"member\"];\nexport const messagePermissionsList = [\n \"text\",\n \"image\",\n \"video\",\n \"audio\",\n \"file\",\n \"poll\",\n \"crypto\",\n \"giphy\",\n \"prize\",\n \"memeFighter\",\n \"p2pSwap\",\n];\nexport const chatPermissionsList = [\n \"changeRoles\",\n \"updateGroup\",\n \"inviteUsers\",\n \"addMembers\",\n \"removeMembers\",\n \"deleteMessages\",\n \"pinMessages\",\n \"reactToMessages\",\n \"mentionAllMembers\",\n \"startVideoCall\",\n];\nexport const communityPermissionsList = [\n \"changeRoles\",\n \"updateDetails\",\n \"inviteUsers\",\n \"removeMembers\",\n \"createPublicChannel\",\n \"createPrivateChannel\",\n \"manageUserGroups\",\n];\nexport const botChatPermissionList = [\n \"changeRoles\",\n \"updateGroup\",\n \"addMembers\",\n \"inviteUsers\",\n \"removeMembers\",\n \"deleteMessages\",\n \"pinMessages\",\n \"reactToMessages\",\n \"mentionAllMembers\",\n \"startVideoCall\",\n \"readMessages\",\n \"readMembership\",\n \"readChatDetails\",\n];\nexport const botCommunityPermissionList = [\n \"changeRoles\",\n \"updateDetails\",\n \"inviteUsers\",\n \"removeMembers\",\n \"createPublicChannel\",\n \"createPrivateChannel\",\n \"manageUserGroups\",\n];\nexport function defaultOptionalChatPermissions() {\n return {\n messagePermissions: undefined,\n threadPermissions: undefined,\n };\n}\nexport function defaultOptionalMessagePermissions() {\n return {\n default: undefined,\n text: undefined,\n image: undefined,\n video: undefined,\n audio: undefined,\n file: undefined,\n poll: undefined,\n crypto: undefined,\n giphy: undefined,\n prize: undefined,\n memeFighter: undefined,\n p2pSwap: undefined,\n };\n}\n","export const CommonResponses = {\n userNotInChannel: () => ({ kind: \"user_not_in_channel\" }),\n chatNotFound: () => ({ kind: \"chat_not_found\" }),\n userLimitReached: () => ({ kind: \"user_limit_reached\" }),\n notAuthorized: () => ({ kind: \"not_authorized\" }),\n success: () => ({ kind: \"success\" }),\n successNoUpdates: () => ({ kind: \"success_no_updates\" }),\n userNotInCommunity: () => ({ kind: \"user_not_in_community\" }),\n userSuspended: () => ({ kind: \"user_suspended\" }),\n userLapsed: () => ({ kind: \"user_lapsed\" }),\n communityFrozen: () => ({ kind: \"community_frozen\" }),\n communityPublic: () => ({ kind: \"community_public\" }),\n messageNotFound: () => ({ kind: \"message_not_found\" }),\n noChange: () => ({ kind: \"no_change\" }),\n communityNotPublic: () => ({ kind: \"community_not_public\" }),\n internalError: (error) => ({ kind: \"internal_error\", error }),\n invalid: () => ({ kind: \"invalid\" }),\n targetUserNotInCommunity: () => ({ kind: \"target_user_not_in_community\" }),\n notPlatformModerator: () => ({ kind: \"not_platform_moderator\" }),\n userBlocked: () => ({ kind: \"user_blocked\" }),\n failure: () => ({ kind: \"failure\" }),\n offline: () => ({ kind: \"offline\" }),\n blocked: () => ({ kind: \"blocked\" }),\n userNotFound: () => ({ kind: \"unknown_user\" }),\n};\n","/**\n * This class offers a Promise-like interface but replaces `then` with `subscribe`.\n * The function passed into subscribe will then be called each time new data is available.\n * The onResult fn will also be given a `final` param in case the calling code needs to know\n * if the final chunk of data has been received.\n */\nexport class Stream {\n constructor(initialiser) {\n this.subscribed = false;\n initialiser((val, final) => {\n if (this.onResult) {\n this.onResult(val, final);\n }\n if (final && this.onEnd) {\n this.onEnd();\n }\n }, (reason) => {\n if (this.onError) {\n this.onError(reason);\n }\n });\n }\n subscribe(subscription) {\n if (this.subscribed) {\n throw new Error(\"Already subscribed\");\n }\n this.subscribed = true;\n this.onResult = subscription.onResult;\n this.onError = subscription.onError;\n this.onEnd = subscription.onEnd;\n }\n}\n","export function deletedUser(userId) {\n return {\n kind: \"user\",\n userId,\n blobUrl: \"/assets/deletedUser.svg\",\n username: \"Deleted User\",\n displayName: undefined,\n updated: BigInt(Number.MAX_VALUE), // we want to *never* request updates for a deleted user\n suspended: false,\n diamondStatus: \"inactive\",\n chitBalance: 0,\n streak: 0,\n isUniquePerson: false,\n totalChitEarned: 0,\n };\n}\n// Note this *has* to return UserSummary | undefined because of the types, but we would not expect it to ever do so in practice\nexport function mergeUserSummaryWithUpdates(cached, updates, timestamp) {\n if (cached === undefined) {\n if (updates.stable === undefined || updates.volatile === undefined) {\n // in this case we cannot construct a valid UserSummary - this should not happen\n return undefined;\n }\n return {\n kind: updates.stable.isBot ? \"bot\" : \"user\",\n userId: updates.userId,\n ...updates.stable,\n ...updates.volatile,\n updated: timestamp,\n };\n }\n if (cached.userId !== updates.userId) {\n return undefined;\n }\n return {\n ...cached,\n ...updates.stable,\n ...updates.volatile,\n };\n}\n// problem - we can no longer create a UserSummary from a CurrentUserSummary\nexport function userSummaryFromCurrentUserSummary(chitState, currentSummary) {\n return {\n kind: currentSummary.isBot ? \"bot\" : \"user\",\n userId: currentSummary.userId,\n username: currentSummary.username,\n displayName: currentSummary.displayName,\n updated: currentSummary.updated,\n suspended: currentSummary.suspensionDetails !== undefined,\n diamondStatus: currentSummary.diamondStatus.kind,\n chitBalance: chitState.chitBalance,\n totalChitEarned: chitState.totalChitEarned,\n streak: chitState.streak,\n blobReference: currentSummary.blobReference,\n blobData: currentSummary.blobData,\n blobUrl: currentSummary.blobUrl,\n isUniquePerson: currentSummary.isUniquePerson,\n };\n}\nexport function updateCreatedUser(created, summary) {\n return {\n ...created,\n ...summary,\n kind: \"created_user\",\n };\n}\nexport var UserStatus;\n(function (UserStatus) {\n UserStatus[UserStatus[\"Offline\"] = 0] = \"Offline\";\n UserStatus[UserStatus[\"Online\"] = 1] = \"Online\";\n UserStatus[UserStatus[\"None\"] = 2] = \"None\";\n})(UserStatus || (UserStatus = {}));\nexport var AvatarSize;\n(function (AvatarSize) {\n AvatarSize[AvatarSize[\"Tiny\"] = 0] = \"Tiny\";\n AvatarSize[AvatarSize[\"Small\"] = 1] = \"Small\";\n AvatarSize[AvatarSize[\"Default\"] = 2] = \"Default\";\n AvatarSize[AvatarSize[\"Large\"] = 3] = \"Large\";\n})(AvatarSize || (AvatarSize = {}));\nexport const ANON_USER_ID = \"does_this_need_to_be_a_principal\";\nexport const ANON_USERNAME = \"guest_user\";\nexport const ANON_DISPLAY_NAME = \"Guest user\";\nexport const ANON_AVATAR_URL = \"/assets/anon.svg\";\nexport function anonymousUser() {\n return {\n kind: \"created_user\",\n username: ANON_USERNAME,\n dateCreated: BigInt(0),\n displayName: ANON_DISPLAY_NAME, // TODO probably need to translate this\n cryptoAccount: \"\", // TODO - will this be a problem?\n userId: ANON_USER_ID,\n isPlatformModerator: false,\n isPlatformOperator: false,\n suspensionDetails: undefined,\n isSuspectedBot: false,\n diamondStatus: { kind: \"inactive\" },\n moderationFlagsEnabled: 0,\n isBot: false,\n updated: 0n,\n isUniquePerson: false,\n };\n}\nexport const ModerationFlags = {\n Offensive: 1,\n Adult: 2,\n UnderReview: 4,\n};\n","import { deleteDB, openDB, } from \"idb\";\nimport { canRetryMessage, chatIdentifiersEqual, chatIdentifierToString, ChatMap, MessageContextMap, MAX_EVENTS, MAX_MESSAGES, ONE_DAY, updateCreatedUser, } from \"openchat-shared\";\nconst CACHE_VERSION = 129;\nconst EARLIEST_SUPPORTED_MIGRATION = 125;\nconst MAX_INDEX = 9999999999;\n// async function createBotsStore(\n// db: IDBPDatabase,\n// _principal: Principal,\n// _tx: IDBPTransaction[], \"versionchange\">,\n// ) {\n// if (db.objectStoreNames.contains(\"bots\")) {\n// db.deleteObjectStore(\"bots\");\n// }\n// db.createObjectStore(\"bots\");\n// }\n//\n// async function createActivityFeed(\n// db: IDBPDatabase,\n// _principal: Principal,\n// _tx: IDBPTransaction[], \"versionchange\">,\n// ) {\n// if (db.objectStoreNames.contains(\"activityFeed\")) {\n// db.deleteObjectStore(\"activityFeed\");\n// }\n// db.createObjectStore(\"activityFeed\");\n// }\n//\nasync function clearChatsStore(_db, _principal, tx) {\n await tx.objectStore(\"chats\").clear();\n}\n//\n// async function clearGroupDetailsStore(\n// _db: IDBPDatabase,\n// _principal: Principal,\n// tx: IDBPTransaction[], \"versionchange\">,\n// ) {\n// await tx.objectStore(\"group_details\").clear();\n// }\n//\nasync function clearCommunityDetailsStore(_db, _principal, tx) {\n await tx.objectStore(\"community_details\").clear();\n}\n//\n// async function clearEverything(\n// db: IDBPDatabase,\n// _principal: Principal,\n// _tx: IDBPTransaction[], \"versionchange\">,\n// ) {\n// nuke(db);\n// }\n//\n// async function clearEvents(\n// _db: IDBPDatabase,\n// _principal: Principal,\n// tx: IDBPTransaction[], \"versionchange\">,\n// ) {\n// await tx.objectStore(\"chat_events\").clear();\n// }\n//\n// async function clearChatAndGroups(\n// _db: IDBPDatabase,\n// _principal: Principal,\n// tx: IDBPTransaction[], \"versionchange\">,\n// ) {\n// await clearChatsStore(_db, _principal, tx);\n// await clearGroupDetailsStore(_db, _principal, tx);\n// }\n//\n// async function clearExternalAchievements(\n// _db: IDBPDatabase,\n// _principal: Principal,\n// tx: IDBPTransaction[], \"versionchange\">,\n// ) {\n// await tx.objectStore(\"externalAchievements\").clear();\n// }\nconst migrations = {\n 126: clearChatsStore,\n 127: clearChatsStore,\n 128: clearCommunityDetailsStore,\n 129: clearChatsStore,\n};\nasync function migrate(db, principal, from, to, transaction) {\n for (let version = from + 1; version <= to; version++) {\n if (migrations[version]) {\n console.debug(`DB: applying migration for version ${version}`);\n await migrations[version](db, principal, transaction);\n }\n }\n}\nfunction nuke(db) {\n if (db.objectStoreNames.contains(\"chat_events\")) {\n db.deleteObjectStore(\"chat_events\");\n }\n if (db.objectStoreNames.contains(\"thread_events\")) {\n db.deleteObjectStore(\"thread_events\");\n }\n if (db.objectStoreNames.contains(\"expiredMessageRanges\")) {\n db.deleteObjectStore(\"expiredMessageRanges\");\n }\n if (db.objectStoreNames.contains(\"chats\")) {\n db.deleteObjectStore(\"chats\");\n }\n if (db.objectStoreNames.contains(\"bots\")) {\n db.deleteObjectStore(\"bots\");\n }\n if (db.objectStoreNames.contains(\"group_details\")) {\n db.deleteObjectStore(\"group_details\");\n }\n if (db.objectStoreNames.contains(\"community_details\")) {\n db.deleteObjectStore(\"community_details\");\n }\n if (db.objectStoreNames.contains(\"failed_chat_messages\")) {\n db.deleteObjectStore(\"failed_chat_messages\");\n }\n if (db.objectStoreNames.contains(\"failed_thread_messages\")) {\n db.deleteObjectStore(\"failed_thread_messages\");\n }\n if (db.objectStoreNames.contains(\"cachePrimer\")) {\n db.deleteObjectStore(\"cachePrimer\");\n }\n if (db.objectStoreNames.contains(\"currentUser\")) {\n db.deleteObjectStore(\"currentUser\");\n }\n if (db.objectStoreNames.contains(\"localUserIndex\")) {\n db.deleteObjectStore(\"localUserIndex\");\n }\n if (db.objectStoreNames.contains(\"externalAchievements\")) {\n db.deleteObjectStore(\"externalAchievements\");\n }\n if (db.objectStoreNames.contains(\"activityFeed\")) {\n db.deleteObjectStore(\"activityFeed\");\n }\n const chatEvents = db.createObjectStore(\"chat_events\");\n chatEvents.createIndex(\"messageIdx\", \"messageKey\");\n chatEvents.createIndex(\"expiresAt\", \"expiresAt\");\n const threadEvents = db.createObjectStore(\"thread_events\");\n threadEvents.createIndex(\"messageIdx\", \"messageKey\");\n db.createObjectStore(\"chats\");\n db.createObjectStore(\"group_details\");\n db.createObjectStore(\"community_details\");\n db.createObjectStore(\"failed_chat_messages\");\n db.createObjectStore(\"failed_thread_messages\");\n db.createObjectStore(\"cachePrimer\");\n db.createObjectStore(\"currentUser\");\n db.createObjectStore(\"localUserIndex\");\n db.createObjectStore(\"externalAchievements\");\n db.createObjectStore(\"activityFeed\");\n db.createObjectStore(\"bots\");\n}\nfunction padMessageIndex(i) {\n return i.toString().padStart(10, \"0\");\n}\nexport function createFailedCacheKey(context, messageId) {\n return JSON.stringify({\n ...context,\n messageId,\n });\n}\nfunction messageContextToString({ chatId, threadRootMessageIndex }) {\n return threadRootMessageIndex === undefined\n ? chatIdentifierToString(chatId)\n : `${chatIdentifierToString(chatId)}_${threadRootMessageIndex}`;\n}\nexport function createCacheKey(context, index) {\n return `${messageContextToString(context)}_${padMessageIndex(index)}`;\n}\nexport function openCache(principal) {\n return openDB(`openchat_db_${principal}`, CACHE_VERSION, {\n upgrade(db, previousVersion, newVersion, transaction) {\n if (previousVersion == null ||\n previousVersion < EARLIEST_SUPPORTED_MIGRATION ||\n newVersion == null) {\n nuke(db);\n }\n else {\n console.debug(`DB: migrating database from ${previousVersion} to ${newVersion}`);\n migrate(db, principal, previousVersion, newVersion, transaction).then(() => {\n console.debug(`DB: migration from ${previousVersion} to ${newVersion} complete`);\n });\n }\n },\n });\n}\nexport async function openDbAndGetCachedChats(principal) {\n const db = openCache(principal);\n if (db !== undefined) {\n return getCachedChats(db, principal);\n }\n}\nexport async function getCachedBots(db, principal) {\n return (await db).get(\"bots\", principal.toString());\n}\nexport async function setCachedBots(db, principal, bots) {\n (await db).put(\"bots\", bots, principal.toString());\n}\nexport async function getCachedChats(db, principal) {\n const resolvedDb = await db;\n const chats = await resolvedDb.get(\"chats\", principal.toString());\n if (chats !== undefined &&\n chats.latestUserCanisterUpdates < BigInt(Date.now() - 30 * ONE_DAY)) {\n // If the cache was last updated more than 30 days ago, clear the cache and return undefined\n const storeNames = resolvedDb.objectStoreNames;\n for (let i = 0; i < storeNames.length; i++) {\n await resolvedDb.clear(storeNames[i]);\n }\n return undefined;\n }\n return chats;\n}\nexport async function setCachedChats(db, principal, chatState, updatedEvents) {\n const directChats = chatState.directChats.map(makeChatSummarySerializable);\n const groupChats = chatState.groupChats.map(makeChatSummarySerializable);\n const communities = chatState.communities.map(makeCommunitySerializable);\n const stateToCache = {\n ...chatState,\n directChats,\n groupChats,\n communities,\n };\n const tx = (await db).transaction([\"chats\", \"chat_events\", \"thread_events\"], \"readwrite\");\n const chatsStore = tx.objectStore(\"chats\");\n const eventsStore = tx.objectStore(\"chat_events\");\n const threadsStore = tx.objectStore(\"thread_events\");\n const deleteRequests = updatedEvents.entries().flatMap(([chatId, indexes]) => {\n return indexes.map((i) => {\n const key = createCacheKey({ chatId, threadRootMessageIndex: i.threadRootMessageIndex }, i.eventIndex);\n return i.threadRootMessageIndex === undefined\n ? eventsStore.delete(key)\n : threadsStore.delete(key);\n });\n });\n const promises = [chatsStore.put(stateToCache, principal.toString()), ...deleteRequests];\n await Promise.all(promises);\n await tx.done;\n}\nexport async function deleteEventsForChat(db, chatId) {\n const tx = (await db).transaction(\"chat_events\", \"readwrite\");\n const store = tx.objectStore(\"chat_events\");\n const cursor = await store.openCursor(IDBKeyRange.lowerBound(chatId));\n while (cursor?.key !== undefined) {\n if (cursor.key.startsWith(chatId)) {\n await store.delete(cursor.key);\n }\n await cursor.continue();\n }\n await tx.done;\n}\nexport async function getCachedEvents(db, eventIndexRange, context, startIndex, ascending, maxEvents = MAX_EVENTS, maxMessages = MAX_MESSAGES, maxMissing = 50) {\n console.debug(\"CACHE: \", context, eventIndexRange, startIndex, ascending);\n const start = Date.now();\n const [events, expiredEventRanges, missing] = await iterateCachedEvents(await db, eventIndexRange, context, startIndex, ascending, maxEvents, maxMessages, maxMissing);\n if (missing.size === 0) {\n console.debug(\"CACHE: hit: \", events.length, Date.now() - start);\n }\n else {\n console.debug(\"CACHE: miss: \", missing);\n }\n return [\n {\n events: events,\n expiredEventRanges,\n expiredMessageRanges: [],\n latestEventIndex: undefined,\n },\n missing,\n ];\n}\nexport async function getCachedEventsWindowByMessageIndex(db, eventIndexRange, context, messageIndex, maxEvents = MAX_EVENTS, maxMessages = MAX_MESSAGES, maxMissing = 50) {\n const eventIndex = await getNearestCachedEventIndexForMessageIndex(db, context, messageIndex);\n if (eventIndex === undefined) {\n return [\n {\n events: [],\n expiredEventRanges: [],\n expiredMessageRanges: [],\n latestEventIndex: undefined,\n },\n new Set(),\n true,\n ];\n }\n const [events, missing] = await getCachedEventsWindow(db, eventIndexRange, context, eventIndex, maxEvents, maxMessages, maxMissing);\n return [events, missing, false];\n}\nexport async function getCachedEventsWindow(db, eventIndexRange, context, startIndex, maxEvents = MAX_EVENTS, maxMessages = MAX_MESSAGES, maxMissing = 50) {\n console.debug(\"CACHE: window: \", eventIndexRange, startIndex);\n const start = Date.now();\n const resolvedDb = await db;\n const promises = [];\n if (eventIndexRange[0] <= startIndex - 1) {\n promises.push(iterateCachedEvents(resolvedDb, eventIndexRange, context, startIndex - 1, false, maxEvents / 2, maxMessages / 2, maxMissing / 2));\n }\n if (eventIndexRange[1] >= startIndex) {\n promises.push(iterateCachedEvents(resolvedDb, eventIndexRange, context, startIndex, true, maxEvents / 2, maxMessages / 2, maxMissing / 2));\n }\n const results = {\n events: [],\n expiredEventRanges: [],\n expiredMessageRanges: [],\n latestEventIndex: undefined,\n };\n const combinedMissing = new Set();\n for (const [events, expiredEventRanges, missing] of await Promise.all(promises)) {\n events.forEach((e) => results.events.push(e));\n expiredEventRanges.forEach((r) => results.expiredEventRanges.push(r));\n missing.forEach((m) => combinedMissing.add(m));\n }\n if (combinedMissing.size === 0) {\n console.debug(\"CACHE: hit: \", results.events.length, Date.now() - start);\n }\n return [results, combinedMissing];\n}\nexport async function getCachedEventByIndex(db, eventIndex, context, now = Date.now()) {\n const storeName = context.threadRootMessageIndex === undefined ? \"chat_events\" : \"thread_events\";\n const key = createCacheKey(context, eventIndex);\n const upperBound = createCacheKey(context, MAX_INDEX);\n const event = processEventExpiry(await db.get(storeName, IDBKeyRange.bound(key, upperBound)), now);\n if ((event?.kind === \"event\" && event.index === eventIndex) ||\n (event?.kind === \"expired_events_range\" && event.start <= eventIndex)) {\n return event;\n }\n return undefined;\n}\nexport async function getCachedEventsByIndex(db, eventIndexes, context) {\n const events = [];\n const expiredEventRanges = [];\n const missing = new Set();\n const resolvedDb = await db;\n const now = Date.now();\n await Promise.all(eventIndexes.map(async (idx) => {\n const evt = await getCachedEventByIndex(resolvedDb, idx, context, now);\n if (evt === undefined) {\n missing.add(idx);\n }\n else if (evt.kind === \"event\") {\n events.push(evt);\n }\n else {\n expiredEventRanges.push(evt);\n }\n }));\n return [\n {\n events: events,\n expiredEventRanges,\n expiredMessageRanges: [],\n latestEventIndex: undefined,\n },\n missing,\n ];\n}\n// If we don't find the precise index we are looking for, look for the previous index\n// This optimises the case where we looking for the next unread message. We won't have that\n// but we probably *will* have the message before.\nexport async function getNearestCachedEventIndexForMessageIndex(db, context, messageIndex, iterations = 0) {\n const eventIndex = await getCachedEventIndexByMessageIndex(db, context, messageIndex);\n if (eventIndex === undefined && iterations === 0 && messageIndex > 0) {\n console.debug(\"EV: we didn't find the event index for \", messageIndex, \" recursing to look for event index for \", messageIndex - 1);\n return getNearestCachedEventIndexForMessageIndex(db, context, messageIndex - 1, iterations + 1);\n }\n return eventIndex;\n}\nasync function getCachedEventIndexByMessageIndex(db, context, messageIndex) {\n const store = context.threadRootMessageIndex !== undefined ? \"thread_events\" : \"chat_events\";\n const cacheKey = createCacheKey(context, messageIndex);\n const cacheKeyUpperBound = createCacheKey(context, MAX_INDEX);\n const resolvedDb = await db;\n const value = await resolvedDb.getFromIndex(store, \"messageIdx\", IDBKeyRange.bound(cacheKey, cacheKeyUpperBound));\n if (value !== undefined &&\n value.kind === \"event\" &&\n value.event.kind === \"message\" &&\n value.event.messageIndex === messageIndex) {\n return value.index;\n }\n return undefined;\n}\nexport function mergeSuccessResponses(a, b) {\n return {\n events: [...a.events, ...b.events].sort((a, b) => getIndex(a) - getIndex(b)),\n expiredEventRanges: [...a.expiredEventRanges, ...b.expiredEventRanges],\n expiredMessageRanges: [...a.expiredMessageRanges, ...b.expiredMessageRanges],\n latestEventIndex: a.latestEventIndex === undefined && b.latestEventIndex === undefined\n ? undefined\n : Math.max(a.latestEventIndex ?? -1, b.latestEventIndex ?? -1),\n };\n}\nfunction getIndex(event) {\n if (\"index\" in event)\n return event.index;\n return event.start;\n}\n// we need to strip out the blobData promise from any media content because that cannot be serialised\nfunction makeSerialisable(ev, chatId, removeBlobs, threadRootMessageIndex) {\n if (ev.event.kind !== \"message\")\n return { ...ev, kind: \"event\", chatId: { ...chatId }, messageKey: undefined };\n return {\n ...ev,\n kind: \"event\",\n chatId: { ...chatId },\n messageKey: createCacheKey({ chatId, threadRootMessageIndex }, ev.event.messageIndex),\n event: {\n ...ev.event,\n content: removeBlobs ? removeBlobData(ev.event.content) : ev.event.content,\n repliesTo: removeReplyContent(ev.event.repliesTo, chatId),\n },\n };\n}\nfunction dataToBlobUrl(data, type) {\n const options = type ? { type } : undefined;\n const blob = new Blob([data], options);\n return URL.createObjectURL(blob);\n}\nfunction removeBlobData(content) {\n if (\"blobData\" in content && content.blobData !== undefined) {\n return {\n ...content,\n blobData: undefined,\n };\n }\n return content;\n}\nfunction removeReplyContent(repliesTo, chatId) {\n if (repliesTo?.kind === \"rehydrated_reply_context\") {\n return {\n kind: \"raw_reply_context\",\n sourceContext: chatIdentifiersEqual(repliesTo.sourceContext.chatId, chatId)\n ? undefined\n : repliesTo.sourceContext,\n eventIndex: repliesTo.eventIndex,\n };\n }\n return repliesTo;\n}\nexport async function removeFailedMessage(db, chatId, messageId, threadRootMessageIndex) {\n const store = threadRootMessageIndex !== undefined ? \"failed_thread_messages\" : \"failed_chat_messages\";\n (await db).delete(store, createFailedCacheKey({ chatId, threadRootMessageIndex }, messageId));\n}\nexport async function recordFailedMessage(db, chatId, event, threadRootMessageIndex) {\n if (!canRetryMessage(event.event.content)) {\n return;\n }\n const store = threadRootMessageIndex !== undefined ? \"failed_thread_messages\" : \"failed_chat_messages\";\n const key = createFailedCacheKey({ chatId, threadRootMessageIndex }, event.event.messageId);\n (await db).put(store, {\n ...makeSerialisable(event, chatId, false, threadRootMessageIndex),\n messageKey: key,\n }, key);\n}\nfunction rebuildBlobUrls(content) {\n if ((content.kind === \"image_content\" ||\n content.kind === \"file_content\" ||\n content.kind === \"audio_content\") &&\n content.blobData !== undefined) {\n content.blobUrl = dataToBlobUrl(content.blobData);\n }\n if (content.kind === \"video_content\") {\n if (content.imageData.blobData !== undefined) {\n content.imageData.blobUrl = dataToBlobUrl(content.imageData.blobData);\n }\n if (content.videoData.blobData !== undefined) {\n content.videoData.blobUrl = dataToBlobUrl(content.videoData.blobData);\n }\n }\n return content;\n}\nexport async function loadFailedMessages(db) {\n const chatMessages = await (await db).getAll(\"failed_chat_messages\");\n const threadMessages = await (await db).getAll(\"failed_thread_messages\");\n return [...chatMessages, ...threadMessages].reduce((res, ev) => {\n if (ev.messageKey === undefined)\n return res;\n const parsedKey = JSON.parse(ev.messageKey);\n const context = {\n chatId: parsedKey.chatId,\n threadRootMessageIndex: parsedKey.threadRootMessageIndex,\n };\n const val = res.get(context) ?? {};\n ev.event.content = rebuildBlobUrls(ev.event.content);\n val[ev.event.messageId.toString()] = ev;\n res.set(context, val);\n return res;\n }, new MessageContextMap());\n}\nexport async function setCachedEvents(db, chatId, resp, threadRootMessageIndex) {\n if (resp === \"events_failed\")\n return;\n const store = threadRootMessageIndex !== undefined ? \"thread_events\" : \"chat_events\";\n const tx = (await db).transaction([store], \"readwrite\", {\n durability: \"relaxed\",\n });\n const eventStore = tx.objectStore(store);\n const promises = resp.events.map((event) => eventStore\n .put(makeSerialisable(event, chatId, true, threadRootMessageIndex), createCacheKey({ chatId, threadRootMessageIndex }, event.index))\n .then((_) => { }));\n // If there are any expired event ranges, insert the range details at either end of the range and delete all\n // cache entries within the range\n if (resp.expiredEventRanges.length > 0) {\n for (const range of resp.expiredEventRanges) {\n const boundaryKeys = [createCacheKey({ chatId, threadRootMessageIndex }, range.start)];\n if (range.start !== range.end) {\n boundaryKeys.push(createCacheKey({ chatId, threadRootMessageIndex }, range.end));\n }\n promises.push(...boundaryKeys.map((k) => eventStore.put(range, k).then((_) => { })));\n if (range.start < range.end - 1) {\n // Delete all cache entries within the range\n promises.push(eventStore.delete(IDBKeyRange.bound(createCacheKey({ chatId, threadRootMessageIndex }, range.start + 1), createCacheKey({ chatId, threadRootMessageIndex }, range.end - 1))));\n }\n }\n }\n await Promise.all(promises);\n await tx.done;\n}\nexport function setCachedMessageFromSendResponse(db, chatId, sentEvent, threadRootMessageIndex) {\n return ([resp, message]) => {\n if (resp.kind !== \"success\" && resp.kind !== \"transfer_success\") {\n recordFailedMessage(db, chatId, sentEvent, threadRootMessageIndex);\n return [resp, message];\n }\n const event = messageToEvent(message, resp);\n setCachedMessageIfNotExists(db, chatId, event, threadRootMessageIndex);\n return [resp, event.event];\n };\n}\nexport async function setCachedMessageIfNotExists(db, chatId, messageEvent, threadRootMessageIndex) {\n const key = createCacheKey({ chatId, threadRootMessageIndex }, messageEvent.index);\n const store = threadRootMessageIndex !== undefined ? \"thread_events\" : \"chat_events\";\n const tx = (await db).transaction([store], \"readwrite\", {\n durability: \"relaxed\",\n });\n const eventStore = tx.objectStore(store);\n if ((await eventStore.count(key)) === 0) {\n await eventStore.add(makeSerialisable(messageEvent, chatId, true, threadRootMessageIndex), key);\n }\n await tx.done;\n}\nexport function getCachePrimerTimestamps(db) {\n return readAll(db, \"cachePrimer\");\n}\nexport async function setCachePrimerTimestamp(db, chatId, timestamp) {\n await (await db).put(\"cachePrimer\", timestamp, chatIdentifierToString(chatId));\n}\nfunction messageToEvent(message, resp) {\n let content = message.content;\n if (resp.kind === \"transfer_success\") {\n switch (message.content.kind) {\n case \"crypto_content\":\n content = { ...message.content, transfer: resp.transfer };\n break;\n case \"prize_content_initial\":\n content = {\n kind: \"prize_content\",\n prizesRemaining: message.content.prizes.length,\n prizesPending: 0,\n winners: [],\n token: message.content.transfer.token,\n endDate: message.content.endDate,\n caption: message.content.caption,\n diamondOnly: message.content.diamondOnly,\n lifetimeDiamondOnly: message.content.lifetimeDiamondOnly,\n uniquePersonOnly: message.content.uniquePersonOnly,\n streakOnly: message.content.streakOnly,\n };\n break;\n case \"p2p_swap_content_initial\":\n content = {\n kind: \"p2p_swap_content\",\n token0: message.content.token0,\n token0Amount: message.content.token0Amount,\n token1: message.content.token1,\n token1Amount: message.content.token1Amount,\n caption: message.content.caption,\n expiresAt: BigInt(Date.now()) + message.content.expiresIn,\n status: { kind: \"p2p_swap_open\" },\n token0TxnIn: resp.transfer.blockIndex,\n // Note: we don't have this in the response but actually we don't use it on the FE\n swapId: 0,\n };\n break;\n }\n }\n return {\n event: {\n ...message,\n messageIndex: resp.messageIndex,\n content,\n },\n index: resp.eventIndex,\n timestamp: resp.timestamp,\n expiresAt: resp.expiresAt,\n };\n}\nexport async function getCachedCommunityDetails(db, communityId) {\n return (await db).get(\"community_details\", communityId);\n}\nexport async function getCachedGroupDetails(db, chatId) {\n return (await db).get(\"group_details\", chatId);\n}\nexport async function setCachedCommunityDetails(db, communityId, communityDetails) {\n await (await db).put(\"community_details\", communityDetails, communityId);\n}\nexport async function setCachedGroupDetails(db, chatId, groupDetails) {\n await (await db).put(\"group_details\", groupDetails, chatId);\n}\nlet db;\nexport function getDb() {\n return db;\n}\nexport function initDb(principal) {\n db = openCache(principal);\n return db;\n}\nexport function closeDb() {\n db = undefined;\n}\n// for now this is only used for loading pinned messages so we can ignore the idea of\n// thread root message index, but it might come up later\nexport async function loadMessagesByMessageIndex(db, chatId, messagesIndexes) {\n const resolvedDb = await db;\n const missing = new Set();\n const messages = [];\n await Promise.all([...messagesIndexes].map(async (msgIdx) => {\n const evt = await resolvedDb.getFromIndex(\"chat_events\", \"messageIdx\", createCacheKey({ chatId }, msgIdx));\n if (evt?.kind === \"event\" && evt.event.kind === \"message\") {\n messages.push(evt);\n return evt.event;\n }\n missing.add(msgIdx);\n return undefined;\n }));\n return {\n messageEvents: messages,\n missing,\n };\n}\nfunction makeCommunitySerializable(community) {\n const channels = community.channels.map(makeChatSummarySerializable);\n const avatar = removeBlobData(community.avatar);\n const banner = removeBlobData(community.banner);\n return {\n ...community,\n channels,\n avatar,\n banner,\n };\n}\nfunction makeChatSummarySerializable(chat) {\n if (chat.latestMessage === undefined)\n return chat;\n return {\n ...chat,\n latestMessage: makeSerialisable(chat.latestMessage, chat.id, true),\n };\n}\nasync function readAll(db, storeName) {\n const transaction = (await db).transaction([storeName]);\n const store = transaction.objectStore(storeName);\n const cursor = await store.openCursor();\n const values = {};\n while (cursor?.key !== undefined) {\n values[cursor.key] = cursor.value;\n try {\n await cursor.continue();\n }\n catch {\n break;\n }\n }\n return values;\n}\nasync function iterateCachedEvents(db, eventIndexRange, context, startIndex, ascending, maxEvents, maxMessages, maxMissing) {\n const bound = ascending ? eventIndexRange[1] : eventIndexRange[0];\n const iterator = await EventsIterator.create(db, context, startIndex, ascending, bound);\n const events = [];\n const expiredEventRanges = [];\n const missing = new Set();\n let messageCount = 0;\n let expectedNextIndex = startIndex;\n while (events.length < maxEvents) {\n const next = await iterator.getNext();\n if (next === undefined) {\n let remainingMissingCount = Math.min(maxMessages - messageCount, maxEvents - events.length);\n if (ascending) {\n for (let i = expectedNextIndex; i <= bound; i++) {\n missing.add(i);\n if (--remainingMissingCount === 0)\n break;\n }\n }\n else {\n for (let i = expectedNextIndex; i >= bound; i--) {\n missing.add(i);\n if (--remainingMissingCount === 0)\n break;\n }\n }\n break;\n }\n if (ascending) {\n const [startIndex, endIndex] = next.kind === \"event\" ? [next.index, next.index] : [next.start, next.end];\n for (let i = expectedNextIndex; i < startIndex; i++) {\n missing.add(i);\n if (missing.size > maxMissing) {\n break;\n }\n }\n expectedNextIndex = endIndex + 1;\n }\n else {\n const [startIndex, endIndex] = next.kind === \"event\" ? [next.index, next.index] : [next.end, next.start];\n for (let i = expectedNextIndex; i > startIndex; i--) {\n missing.add(i);\n if (missing.size > maxMissing) {\n break;\n }\n }\n expectedNextIndex = endIndex - 1;\n }\n if (next.kind === \"event\") {\n events.push(next);\n if (next.event.kind === \"message\") {\n if (++messageCount == maxMessages) {\n break;\n }\n }\n }\n else {\n expiredEventRanges.push(next);\n }\n }\n return [events, expiredEventRanges, missing];\n}\nfunction mergeRanges(left, right) {\n return {\n kind: \"expired_events_range\",\n start: Math.min(left.start, right.start),\n end: Math.max(left.end, right.end),\n };\n}\nfunction isContiguous(left, right) {\n if (left.start <= right.start) {\n return right.start >= left.end + 1;\n }\n else {\n return left.start <= right.end + 1;\n }\n}\nclass EventsIterator {\n constructor(cursor, onComplete) {\n this.cursor = cursor;\n this.onComplete = onComplete;\n this.now = Date.now();\n this.current = processEventExpiry(cursor?.value, this.now);\n }\n static async create(db, messageContext, startIndex, ascending, bound) {\n if ((ascending && startIndex > bound) || (!ascending && startIndex < bound)) {\n throw new Error(`Start index exceeds bound. ${JSON.stringify({\n messageContext,\n startIndex,\n ascending,\n bound,\n })}`);\n }\n const storeName = messageContext.threadRootMessageIndex === undefined ? \"chat_events\" : \"thread_events\";\n const transaction = db.transaction([storeName]);\n const store = transaction.objectStore(storeName);\n const startKey = createCacheKey(messageContext, startIndex);\n const [lower, upper] = ascending\n ? [startKey, createCacheKey(messageContext, bound)]\n : [createCacheKey(messageContext, bound), startKey];\n const cursor = await store.openCursor(IDBKeyRange.bound(lower, upper), ascending ? \"next\" : \"prev\");\n return new EventsIterator(cursor, () => transaction.done);\n }\n async getNext() {\n const current = this.current;\n if (current === undefined) {\n return undefined;\n }\n await this.advance();\n const next = processEventExpiry(this.cursor?.value, this.now);\n // If this value matches the previous value, skip it, and yield the next value instead\n if (next?.kind === \"expired_events_range\" &&\n current?.kind === \"expired_events_range\" &&\n isContiguous(current, next)) {\n this.current = mergeRanges(current, next);\n return await this.getNext();\n }\n this.current = next;\n return current;\n }\n async advance() {\n try {\n await this.cursor?.advance(1);\n return true;\n }\n catch {\n this.cursor = undefined;\n if (this.onComplete !== undefined) {\n await this.onComplete();\n }\n return false;\n }\n }\n}\nfunction processEventExpiry(event, now) {\n if (event === undefined ||\n event.kind === \"expired_events_range\" ||\n event.expiresAt === undefined ||\n event.expiresAt > now) {\n return event;\n }\n tryStartExpiredEventSweeper();\n return {\n kind: \"expired_events_range\",\n start: event.index,\n end: event.index,\n };\n}\nlet expiredEventSweeperJob;\nfunction tryStartExpiredEventSweeper() {\n if (expiredEventSweeperJob !== undefined)\n return;\n expiredEventSweeperJob = setTimeout(runExpiredEventSweeper, 5000);\n}\n// TODO we can improve this by replacing these events with expired event ranges\nasync function runExpiredEventSweeper() {\n if (db === undefined)\n return;\n const transaction = (await db).transaction([\"chat_events\", \"thread_events\"], \"readwrite\");\n const eventsStore = transaction.objectStore(\"chat_events\");\n const threadEventsStore = transaction.objectStore(\"thread_events\");\n const index = eventsStore.index(\"expiresAt\");\n const batchSize = 100;\n const expiredKeys = await index.getAllKeys(IDBKeyRange.upperBound(Date.now()), batchSize);\n async function deleteKey(key) {\n const value = await eventsStore.get(key);\n if (value?.kind !== \"event\") {\n return;\n }\n const promises = [eventsStore.delete(key)];\n if (value.event.kind === \"message\" &&\n value.event.thread !== undefined &&\n value.messageKey !== undefined) {\n const threadKey = value.messageKey.replace(/_0+/, \"_\"); // Remove the 0's which pad the message index\n promises.push(threadEventsStore.delete(IDBKeyRange.bound(threadKey + \"_\", threadKey + \"_Z\")));\n }\n await Promise.all(promises);\n }\n await Promise.all(expiredKeys.map(deleteKey));\n expiredEventSweeperJob = undefined;\n // If the batch was full, run the job again\n if (expiredKeys.length === batchSize) {\n tryStartExpiredEventSweeper();\n }\n}\nexport async function getCachedCurrentUser(principal) {\n if (db === undefined)\n return;\n return (await db).get(\"currentUser\", principal);\n}\nexport async function mergeCachedCurrentUser(principal, updated) {\n if (db === undefined)\n return;\n const current = await getCachedCurrentUser(principal);\n if (current) {\n const merged = updateCreatedUser(current, updated);\n (await db).put(\"currentUser\", merged, principal);\n }\n}\nexport async function setCachedCurrentUser(principal, user) {\n if (db === undefined)\n return;\n (await db).put(\"currentUser\", user, principal);\n}\nexport async function setCurrentUserDiamondStatusInCache(principal, diamondStatus) {\n const user = await getCachedCurrentUser(principal);\n if (user === undefined || db === undefined)\n return;\n (await db).put(\"currentUser\", {\n ...user,\n diamondStatus,\n }, principal);\n}\nexport async function getLocalUserIndexForUser(userId) {\n if (db === undefined)\n return;\n return (await db).get(\"localUserIndex\", userId);\n}\nexport async function cacheLocalUserIndexForUser(userId, localUserIndex) {\n if (db === undefined)\n return localUserIndex;\n (await db).put(\"localUserIndex\", localUserIndex, userId);\n return localUserIndex;\n}\nexport async function clearCache(principal) {\n const name = `openchat_db_${principal}`;\n try {\n if (db !== undefined) {\n (await db).close();\n }\n await deleteDB(name);\n console.log(\"deleted db: \", name);\n }\n catch (err) {\n console.error(\"Unable to delete db: \", name, err);\n }\n}\nexport async function getCachedExternalAchievements() {\n if (db === undefined)\n return undefined;\n return (await db).get(\"externalAchievements\", \"value\");\n}\nexport async function setCachedExternalAchievements(lastUpdated, achievements) {\n if (db === undefined)\n return;\n (await db).put(\"externalAchievements\", { lastUpdated, achievements }, \"value\");\n}\nexport async function getActivityFeedEvents() {\n if (db === undefined)\n return [];\n const result = await (await db).get(\"activityFeed\", \"value\");\n return result ?? [];\n}\nexport async function setActivityFeedEvents(activity) {\n if (db === undefined)\n return;\n (await db).put(\"activityFeed\", activity, \"value\");\n}\n/**\n * When a bot is uninstalled from a community we need to remove all of the api keys for each\n * of the channels in the community. This is unfortunately a bit messy.\n */\nexport async function removeCachedChannelApiKeys(principal, communityId, botId) {\n if (db === undefined)\n return;\n const chats = await getCachedChats(db, principal);\n if (chats !== undefined) {\n const community = chats.communities.find((c) => c.id.communityId === communityId);\n if (community !== undefined) {\n const tx = (await db).transaction([\"group_details\"], \"readwrite\");\n for (const { id } of community.channels) {\n const cacheKey = `${id.communityId}_${id.channelId}`;\n if (db === undefined)\n return;\n const details = await getCachedGroupDetails(db, cacheKey);\n if (details !== undefined) {\n details.apiKeys.delete(botId);\n await setCachedGroupDetails(db, cacheKey, details);\n }\n }\n tx.commit();\n }\n }\n}\n","export function isMainnet(icUrl) {\n return icUrl.includes(\"icp-api.io\");\n}\n","import { deleteDB, openDB } from \"idb\";\nimport { deletedUser } from \"openchat-shared\";\nconst CACHE_VERSION = 11;\nlet db;\nexport function lazyOpenUserCache() {\n if (db)\n return db;\n console.log(\"user db undefined, opening db\");\n db = openUserCache();\n return db;\n}\nfunction openUserCache() {\n return openDB(`openchat_users`, CACHE_VERSION, {\n upgrade(db, _oldVersion, _newVersion, _transaction) {\n if (db.objectStoreNames.contains(\"users\")) {\n db.deleteObjectStore(\"users\");\n }\n if (db.objectStoreNames.contains(\"suspendedUsersSyncedUpTo\")) {\n db.deleteObjectStore(\"suspendedUsersSyncedUpTo\");\n }\n if (db.objectStoreNames.contains(\"deletedUserIds\")) {\n db.deleteObjectStore(\"deletedUserIds\");\n }\n db.createObjectStore(\"users\");\n db.createObjectStore(\"suspendedUsersSyncedUpTo\");\n db.createObjectStore(\"deletedUserIds\");\n },\n });\n}\nexport async function getCachedUsers(userIds) {\n const resolvedDb = await lazyOpenUserCache();\n const fromCache = await Promise.all(userIds.map((u) => resolvedDb.get(\"users\", u)));\n return fromCache.reduce((users, next) => {\n if (next !== undefined)\n users.push(next);\n return users;\n }, []);\n}\nexport async function getAllUsers() {\n const users = await (await lazyOpenUserCache()).getAll(\"users\");\n const deleted = await getDeletedUserIdsList();\n const userIds = new Set(users.map((u) => u.userId));\n // only consider records from the deleted list that do not exist in the real users list\n // this is necessary because a userId can be resurrected by being re-used\n const reallyDeleted = deleted.filter((u) => !userIds.has(u));\n return [...users, ...reallyDeleted.map(deletedUser)];\n}\nasync function getDeletedUserIdsList() {\n return (await lazyOpenUserCache()).getAll(\"deletedUserIds\");\n}\nexport async function getCachedDeletedUserIds() {\n return getDeletedUserIdsList().then((list) => new Set(list));\n}\nexport async function isUserIdDeleted(userId) {\n const user = await (await lazyOpenUserCache()).get(\"deletedUserIds\", userId);\n return user !== undefined;\n}\nexport async function setCachedUsers(users) {\n if (users.length === 0)\n return;\n writeCachedUsersToDatabase(lazyOpenUserCache(), users);\n}\nexport async function setCachedDeletedUserIds(deletedUserIds) {\n if (deletedUserIds.size === 0)\n return;\n const db = await lazyOpenUserCache();\n const tx = (await db).transaction([\"deletedUserIds\", \"users\"], \"readwrite\", {\n durability: \"relaxed\",\n });\n const deletedStore = tx.objectStore(\"deletedUserIds\");\n const userStore = tx.objectStore(\"users\");\n // insert all the deletedIds into the deletedUserIds store\n const inserts = [...deletedUserIds].map((userId) => deletedStore.put(userId, userId));\n // delete all the deletedIds from the main userStore\n const deletes = [...deletedUserIds].map((userId) => userStore.delete(userId));\n Promise.all([...inserts, ...deletes]);\n await tx.done;\n}\nexport async function writeCachedUsersToDatabase(db, users) {\n // in this one case we will open the db every time because we expect this to be done from the service worker\n const tx = (await db).transaction(\"users\", \"readwrite\", {\n durability: \"relaxed\",\n });\n const store = tx.objectStore(\"users\");\n Promise.all(users.map((u) => store.put(u, u.userId)));\n await tx.done;\n}\nexport async function setUsernameInCache(userId, username) {\n const tx = (await lazyOpenUserCache()).transaction(\"users\", \"readwrite\", {\n durability: \"relaxed\",\n });\n const store = tx.objectStore(\"users\");\n const user = await store.get(userId);\n if (user !== undefined) {\n user.username = username;\n await store.put(user, userId);\n }\n await tx.done;\n}\nexport async function setDisplayNameInCache(userId, displayName) {\n const tx = (await lazyOpenUserCache()).transaction(\"users\", \"readwrite\", {\n durability: \"relaxed\",\n });\n const store = tx.objectStore(\"users\");\n const user = await store.get(userId);\n if (user !== undefined) {\n user.displayName = displayName;\n await store.put(user, userId);\n }\n await tx.done;\n}\nexport async function setUserDiamondStatusInCache(userId, status) {\n const tx = (await lazyOpenUserCache()).transaction(\"users\", \"readwrite\", {\n durability: \"relaxed\",\n });\n const store = tx.objectStore(\"users\");\n const user = await store.get(userId);\n if (user !== undefined) {\n user.diamondStatus = status.kind;\n await store.put(user, userId);\n }\n await tx.done;\n}\nexport async function getSuspendedUsersSyncedUpTo() {\n const resolvedDb = await lazyOpenUserCache();\n return await resolvedDb.get(\"suspendedUsersSyncedUpTo\", \"value\");\n}\nexport async function setSuspendedUsersSyncedUpTo(value) {\n const resolvedDb = await lazyOpenUserCache();\n await resolvedDb.put(\"suspendedUsersSyncedUpTo\", value, \"value\");\n}\nexport async function setChitInfoInCache(userId, chitBalance, streak) {\n const tx = (await lazyOpenUserCache()).transaction(\"users\", \"readwrite\", {\n durability: \"relaxed\",\n });\n const store = tx.objectStore(\"users\");\n const user = await store.get(userId);\n if (user !== undefined) {\n user.chitBalance = chitBalance;\n user.streak = streak;\n await store.put(user, userId);\n }\n await tx.done;\n}\nexport async function clearCache() {\n const name = `openchat_users`;\n try {\n if (db !== undefined) {\n (await db).close();\n }\n await deleteDB(name);\n console.log(\"deleted db: \", name);\n }\n catch (err) {\n console.error(\"Unable to delete db: \", name, err);\n }\n}\n","import { openDB } from \"idb\";\nconst CACHE_VERSION = 15;\nconst KEY = \"registry\";\nlet db;\nexport function lazyOpenRegistryCache() {\n if (db)\n return db;\n console.log(\"registry db undefined, opening db\");\n db = openRegistryCache();\n return db;\n}\nfunction openRegistryCache() {\n return openDB(`openchat_registry`, CACHE_VERSION, {\n upgrade(db, _oldVersion, _newVersion, _transaction) {\n if (db.objectStoreNames.contains(\"registry\")) {\n db.deleteObjectStore(\"registry\");\n }\n db.createObjectStore(\"registry\");\n },\n });\n}\nexport async function getCachedRegistry() {\n const resolvedDb = await lazyOpenRegistryCache();\n return await resolvedDb.get(KEY, KEY);\n}\nexport async function setCachedRegistry(value) {\n const resolvedDb = await lazyOpenRegistryCache();\n await resolvedDb.put(KEY, value, KEY);\n}\n","export function groupWhile(predicate, items) {\n if (items.length === 0)\n return [];\n const [, grouped] = items.reduce(([prev, groups], item) => {\n if (!prev) {\n return [item, [[item]]];\n }\n if (predicate(prev, item)) {\n const lastGroup = groups[groups.length - 1];\n lastGroup.push(item);\n return [item, groups];\n }\n else {\n groups.push([item]);\n return [item, groups];\n }\n }, [undefined, [[]]]);\n return grouped;\n}\nexport function groupBy(items, keySelector) {\n const grouped = new Map();\n for (const item of items) {\n const key = keySelector(item);\n const existing = grouped.get(key);\n if (existing !== undefined) {\n existing.push(item);\n }\n else {\n grouped.set(key, [item]);\n }\n }\n return grouped;\n}\nexport function flatMap(things, fn) {\n return things.reduce((agg, thing) => {\n agg.push(...fn(thing));\n return agg;\n }, []);\n}\nexport function distinctBy(things, keyFn) {\n if (things.length == 0)\n return things;\n const set = new Set();\n const output = [];\n for (const thing of things) {\n const key = keyFn(thing);\n if (!set.has(key)) {\n set.add(key);\n output.push(thing);\n }\n }\n return output;\n}\nexport function zip(a, b) {\n const l = Math.min(a.length, b.length);\n const res = [];\n for (let i = 0; i < l; i++) {\n res.push([a[i], b[i]]);\n }\n return res;\n}\nexport function chunk(array, size) {\n const chunkCount = Math.floor((array.length - 1) / size) + 1;\n const chunks = [];\n for (let chunkIndex = 0; chunkIndex < chunkCount; chunkIndex++) {\n const start = chunkIndex * size;\n const end = start + size;\n chunks.push(array.slice(start, end));\n }\n return chunks;\n}\nexport function findLast(array, predicate) {\n for (let i = array.length - 1; i >= 0; i--) {\n const item = array[i];\n if (predicate(item))\n return item;\n }\n return undefined;\n}\nexport function toRecord(xs, keyFn) {\n return xs.reduce((rec, x) => {\n rec[keyFn(x)] = x;\n return rec;\n }, {});\n}\nexport function toRecord2(xs, keyFn, valFn) {\n return xs.reduce((rec, x) => {\n rec[keyFn(x)] = valFn(x);\n return rec;\n }, {});\n}\n","import { ResponseTooLargeError } from \"openchat-shared\";\nimport { getTimeUntilSessionExpiryMs, HttpError, SessionExpiryError, AuthError, DestinationInvalidError, InvalidDelegationError, TypeboxValidationError, } from \"openchat-shared\";\nexport class ReplicaNotUpToDateError extends Error {\n static byTimestamp(replicaTimestamp, clientTimestamp, failedPostCheck) {\n const message = `Replica not up to date (timestamp). Client: ${clientTimestamp}. Replica: ${replicaTimestamp}. FailedPostCheck: ${failedPostCheck}`;\n return new ReplicaNotUpToDateError(message);\n }\n constructor(message) {\n super(message);\n }\n}\nfunction responseTooLarge(error) {\n const regex = /application payload size \\((\\d+)\\) cannot be larger than (\\d+)/;\n const match = error.message.match(regex);\n if (match) {\n const size = parseInt(match[1]);\n const maxSize = parseInt(match[2]);\n return new ResponseTooLargeError(error, size, maxSize);\n }\n return undefined;\n}\nexport function toCanisterResponseError(error, identity) {\n if (error instanceof ReplicaNotUpToDateError || error instanceof TypeboxValidationError) {\n return error;\n }\n let code = 500;\n if (error.message.includes(\"DestinationInvalid\")) {\n // this will allow us to short-circuit the retry mechanism in this circumstance\n return new DestinationInvalidError(error);\n }\n const tooLarge = responseTooLarge(error);\n if (tooLarge) {\n return tooLarge;\n }\n const statusLine = error.message\n .split(\"\\n\")\n .map((l) => l.trim().toLowerCase())\n .find((l) => l.startsWith(\"code:\") || l.startsWith(\"http status code:\"));\n if (statusLine) {\n const parts = statusLine.split(\":\");\n if (parts && parts.length > 1) {\n let valueText = parts[1].trim();\n const valueParts = valueText.split(\" \");\n if (valueParts && valueParts.length > 1) {\n valueText = valueParts[0].trim();\n }\n code = parseInt(valueText, 10);\n if (isNaN(code)) {\n code = 500;\n }\n }\n }\n // if we make an api call after the session has expired (which should not happen) it will manifest as a 400 error\n if (code === 400) {\n if (getTimeUntilSessionExpiryMs(identity) < 0) {\n console.debug(\"SESSION: we received a 400 response and the session has timed out: \", getTimeUntilSessionExpiryMs(identity));\n return new SessionExpiryError(code, error);\n }\n else if (error.message.includes(\"Invalid delegation\")) {\n return new InvalidDelegationError(error);\n }\n }\n return code === 401 || code === 403 ? new AuthError(code, error) : new HttpError(code, error);\n}\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","import { HttpAgent } from \"@dfinity/agent\";\nimport { Principal } from \"@dfinity/principal\";\nimport { AuthError, DestinationInvalidError, ResponseTooLargeError, SessionExpiryError, TypeboxValidationError, } from \"openchat-shared\";\nimport { ReplicaNotUpToDateError, toCanisterResponseError } from \"../error\";\nconst MAX_RETRIES = process.env.NODE_ENV === \"production\" ? 7 : 3;\nconst RETRY_DELAY = 100;\nfunction debug(msg) {\n console.log(msg);\n}\nexport class CanisterAgent {\n constructor(identity, agent, canisterId, canisterName) {\n this.identity = identity;\n this.agent = agent;\n this.canisterId = canisterId;\n this.canisterName = canisterName;\n }\n get principal() {\n return this.identity.getPrincipal();\n }\n executeQuery(serviceCall, mapper, args, retries = 0) {\n return serviceCall()\n .then(mapper)\n .catch((err) => {\n const responseErr = toCanisterResponseError(err, this.identity);\n const debugInfo = `error: ${JSON.stringify(responseErr, Object.getOwnPropertyNames(responseErr))}, args: ${JSON.stringify(args)}`;\n if (!(responseErr instanceof ResponseTooLargeError) &&\n !(responseErr instanceof SessionExpiryError) &&\n !(responseErr instanceof DestinationInvalidError) &&\n !(responseErr instanceof AuthError) &&\n !(responseErr instanceof TypeboxValidationError) &&\n retries < MAX_RETRIES) {\n const delay = RETRY_DELAY * Math.pow(2, retries);\n if (responseErr instanceof ReplicaNotUpToDateError) {\n debug(`query: replica not up to date, retrying in ${delay}ms. retries: ${retries}. ${debugInfo}`);\n }\n else {\n debug(`query: error occurred, retrying in ${delay}ms. retries: ${retries}. ${debugInfo}`);\n }\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n this.executeQuery(serviceCall, mapper, args, retries + 1)\n .then(resolve)\n .catch(reject);\n }, delay);\n });\n }\n else {\n debug(`query: Error performing query request, exiting retry loop. retries: ${retries}. ${debugInfo}`);\n throw responseErr;\n }\n });\n }\n writeTrace(methodName, update, duration, isError) {\n if (!isError) {\n console.debug(`TRACE: ${update ? \"Update\" : \"Query\"} call to ${this.canisterName}.${methodName} took ${Math.trunc(duration)}ms`);\n }\n }\n}\n","// --------------------------------------------------------------------------\n// Iterators\n// --------------------------------------------------------------------------\n/** Returns true if this value is an async iterator */\nexport function IsAsyncIterator(value) {\n return IsObject(value) && globalThis.Symbol.asyncIterator in value;\n}\n/** Returns true if this value is an iterator */\nexport function IsIterator(value) {\n return IsObject(value) && globalThis.Symbol.iterator in value;\n}\n// --------------------------------------------------------------------------\n// Object Instances\n// --------------------------------------------------------------------------\n/** Returns true if this value is not an instance of a class */\nexport function IsStandardObject(value) {\n return IsObject(value) && (globalThis.Object.getPrototypeOf(value) === Object.prototype || globalThis.Object.getPrototypeOf(value) === null);\n}\n/** Returns true if this value is an instance of a class */\nexport function IsInstanceObject(value) {\n return IsObject(value) && !IsArray(value) && IsFunction(value.constructor) && value.constructor.name !== 'Object';\n}\n// --------------------------------------------------------------------------\n// JavaScript\n// --------------------------------------------------------------------------\n/** Returns true if this value is a Promise */\nexport function IsPromise(value) {\n return value instanceof globalThis.Promise;\n}\n/** Returns true if this value is a Date */\nexport function IsDate(value) {\n return value instanceof Date && globalThis.Number.isFinite(value.getTime());\n}\n/** Returns true if this value is an instance of Map */\nexport function IsMap(value) {\n return value instanceof globalThis.Map;\n}\n/** Returns true if this value is an instance of Set */\nexport function IsSet(value) {\n return value instanceof globalThis.Set;\n}\n/** Returns true if this value is RegExp */\nexport function IsRegExp(value) {\n return value instanceof globalThis.RegExp;\n}\n/** Returns true if this value is a typed array */\nexport function IsTypedArray(value) {\n return globalThis.ArrayBuffer.isView(value);\n}\n/** Returns true if the value is a Int8Array */\nexport function IsInt8Array(value) {\n return value instanceof globalThis.Int8Array;\n}\n/** Returns true if the value is a Uint8Array */\nexport function IsUint8Array(value) {\n return value instanceof globalThis.Uint8Array;\n}\n/** Returns true if the value is a Uint8ClampedArray */\nexport function IsUint8ClampedArray(value) {\n return value instanceof globalThis.Uint8ClampedArray;\n}\n/** Returns true if the value is a Int16Array */\nexport function IsInt16Array(value) {\n return value instanceof globalThis.Int16Array;\n}\n/** Returns true if the value is a Uint16Array */\nexport function IsUint16Array(value) {\n return value instanceof globalThis.Uint16Array;\n}\n/** Returns true if the value is a Int32Array */\nexport function IsInt32Array(value) {\n return value instanceof globalThis.Int32Array;\n}\n/** Returns true if the value is a Uint32Array */\nexport function IsUint32Array(value) {\n return value instanceof globalThis.Uint32Array;\n}\n/** Returns true if the value is a Float32Array */\nexport function IsFloat32Array(value) {\n return value instanceof globalThis.Float32Array;\n}\n/** Returns true if the value is a Float64Array */\nexport function IsFloat64Array(value) {\n return value instanceof globalThis.Float64Array;\n}\n/** Returns true if the value is a BigInt64Array */\nexport function IsBigInt64Array(value) {\n return value instanceof globalThis.BigInt64Array;\n}\n/** Returns true if the value is a BigUint64Array */\nexport function IsBigUint64Array(value) {\n return value instanceof globalThis.BigUint64Array;\n}\n// --------------------------------------------------------------------------\n// PropertyKey\n// --------------------------------------------------------------------------\n/** Returns true if this value has this property key */\nexport function HasPropertyKey(value, key) {\n return key in value;\n}\n// --------------------------------------------------------------------------\n// Standard\n// --------------------------------------------------------------------------\n/** Returns true of this value is an object type */\nexport function IsObject(value) {\n return value !== null && typeof value === 'object';\n}\n/** Returns true if this value is an array, but not a typed array */\nexport function IsArray(value) {\n return globalThis.Array.isArray(value) && !globalThis.ArrayBuffer.isView(value);\n}\n/** Returns true if this value is an undefined */\nexport function IsUndefined(value) {\n return value === undefined;\n}\n/** Returns true if this value is an null */\nexport function IsNull(value) {\n return value === null;\n}\n/** Returns true if this value is an boolean */\nexport function IsBoolean(value) {\n return typeof value === 'boolean';\n}\n/** Returns true if this value is an number */\nexport function IsNumber(value) {\n return typeof value === 'number';\n}\n/** Returns true if this value is an integer */\nexport function IsInteger(value) {\n return globalThis.Number.isInteger(value);\n}\n/** Returns true if this value is bigint */\nexport function IsBigInt(value) {\n return typeof value === 'bigint';\n}\n/** Returns true if this value is string */\nexport function IsString(value) {\n return typeof value === 'string';\n}\n/** Returns true if this value is a function */\nexport function IsFunction(value) {\n return typeof value === 'function';\n}\n/** Returns true if this value is a symbol */\nexport function IsSymbol(value) {\n return typeof value === 'symbol';\n}\n/** Returns true if this value is a value type such as number, string, boolean */\nexport function IsValueType(value) {\n // prettier-ignore\n return (IsBigInt(value) ||\n IsBoolean(value) ||\n IsNull(value) ||\n IsNumber(value) ||\n IsString(value) ||\n IsSymbol(value) ||\n IsUndefined(value));\n}\n","import { IsObject, IsArray, IsNumber, IsUndefined } from '../value/guard/index.mjs';\nexport var TypeSystemPolicy;\n(function (TypeSystemPolicy) {\n // ------------------------------------------------------------------\n // TypeSystemPolicy: Instancing\n // ------------------------------------------------------------------\n /**\n * Configures the instantiation behavior of TypeBox types. The `default` option assigns raw JavaScript\n * references for embedded types, which may cause side effects if type properties are explicitly updated\n * outside the TypeBox type builder. The `clone` option creates copies of any shared types upon creation,\n * preventing unintended side effects. The `freeze` option applies `Object.freeze()` to the type, making\n * it fully readonly and immutable. Implementations should use `default` whenever possible, as it is the\n * fastest way to instantiate types. The default setting is `default`.\n */\n TypeSystemPolicy.InstanceMode = 'default';\n // ------------------------------------------------------------------\n // TypeSystemPolicy: Checking\n // ------------------------------------------------------------------\n /** Sets whether TypeBox should assert optional properties using the TypeScript `exactOptionalPropertyTypes` assertion policy. The default is `false` */\n TypeSystemPolicy.ExactOptionalPropertyTypes = false;\n /** Sets whether arrays should be treated as a kind of objects. The default is `false` */\n TypeSystemPolicy.AllowArrayObject = false;\n /** Sets whether `NaN` or `Infinity` should be treated as valid numeric values. The default is `false` */\n TypeSystemPolicy.AllowNaN = false;\n /** Sets whether `null` should validate for void types. The default is `false` */\n TypeSystemPolicy.AllowNullVoid = false;\n /** Checks this value using the ExactOptionalPropertyTypes policy */\n function IsExactOptionalProperty(value, key) {\n return TypeSystemPolicy.ExactOptionalPropertyTypes ? key in value : value[key] !== undefined;\n }\n TypeSystemPolicy.IsExactOptionalProperty = IsExactOptionalProperty;\n /** Checks this value using the AllowArrayObjects policy */\n function IsObjectLike(value) {\n const isObject = IsObject(value);\n return TypeSystemPolicy.AllowArrayObject ? isObject : isObject && !IsArray(value);\n }\n TypeSystemPolicy.IsObjectLike = IsObjectLike;\n /** Checks this value as a record using the AllowArrayObjects policy */\n function IsRecordLike(value) {\n return IsObjectLike(value) && !(value instanceof Date) && !(value instanceof Uint8Array);\n }\n TypeSystemPolicy.IsRecordLike = IsRecordLike;\n /** Checks this value using the AllowNaN policy */\n function IsNumberLike(value) {\n return TypeSystemPolicy.AllowNaN ? IsNumber(value) : Number.isFinite(value);\n }\n TypeSystemPolicy.IsNumberLike = IsNumberLike;\n /** Checks this value using the AllowVoidNull policy */\n function IsVoidLike(value) {\n const isUndefined = IsUndefined(value);\n return TypeSystemPolicy.AllowNullVoid ? isUndefined || value === null : isUndefined;\n }\n TypeSystemPolicy.IsVoidLike = IsVoidLike;\n})(TypeSystemPolicy || (TypeSystemPolicy = {}));\n","/** A registry for user defined string formats */\nconst map = new Map();\n/** Returns the entries in this registry */\nexport function Entries() {\n return new Map(map);\n}\n/** Clears all user defined string formats */\nexport function Clear() {\n return map.clear();\n}\n/** Deletes a registered format */\nexport function Delete(format) {\n return map.delete(format);\n}\n/** Returns true if the user defined string format exists */\nexport function Has(format) {\n return map.has(format);\n}\n/** Sets a validation function for a user defined string format */\nexport function Set(format, func) {\n map.set(format, func);\n}\n/** Gets a validation function for a user defined string format */\nexport function Get(format) {\n return map.get(format);\n}\n","/** A registry for user defined types */\nconst map = new Map();\n/** Returns the entries in this registry */\nexport function Entries() {\n return new Map(map);\n}\n/** Clears all user defined types */\nexport function Clear() {\n return map.clear();\n}\n/** Deletes a registered type */\nexport function Delete(kind) {\n return map.delete(kind);\n}\n/** Returns true if this registry contains this kind */\nexport function Has(kind) {\n return map.has(kind);\n}\n/** Sets a validation function for a user defined type */\nexport function Set(kind, func) {\n map.set(kind, func);\n}\n/** Gets a custom validation function for a user defined type */\nexport function Get(kind) {\n return map.get(kind);\n}\n","// --------------------------------------------------------------------------\n// PropertyKey\n// --------------------------------------------------------------------------\n/** Returns true if this value has this property key */\nexport function HasPropertyKey(value, key) {\n return key in value;\n}\n// --------------------------------------------------------------------------\n// Object Instances\n// --------------------------------------------------------------------------\n/** Returns true if this value is an async iterator */\nexport function IsAsyncIterator(value) {\n return IsObject(value) && !IsArray(value) && !IsUint8Array(value) && Symbol.asyncIterator in value;\n}\n/** Returns true if this value is an array */\nexport function IsArray(value) {\n return Array.isArray(value);\n}\n/** Returns true if this value is bigint */\nexport function IsBigInt(value) {\n return typeof value === 'bigint';\n}\n/** Returns true if this value is a boolean */\nexport function IsBoolean(value) {\n return typeof value === 'boolean';\n}\n/** Returns true if this value is a Date object */\nexport function IsDate(value) {\n return value instanceof globalThis.Date;\n}\n/** Returns true if this value is a function */\nexport function IsFunction(value) {\n return typeof value === 'function';\n}\n/** Returns true if this value is an iterator */\nexport function IsIterator(value) {\n return IsObject(value) && !IsArray(value) && !IsUint8Array(value) && Symbol.iterator in value;\n}\n/** Returns true if this value is null */\nexport function IsNull(value) {\n return value === null;\n}\n/** Returns true if this value is number */\nexport function IsNumber(value) {\n return typeof value === 'number';\n}\n/** Returns true if this value is an object */\nexport function IsObject(value) {\n return typeof value === 'object' && value !== null;\n}\n/** Returns true if this value is RegExp */\nexport function IsRegExp(value) {\n return value instanceof globalThis.RegExp;\n}\n/** Returns true if this value is string */\nexport function IsString(value) {\n return typeof value === 'string';\n}\n/** Returns true if this value is symbol */\nexport function IsSymbol(value) {\n return typeof value === 'symbol';\n}\n/** Returns true if this value is a Uint8Array */\nexport function IsUint8Array(value) {\n return value instanceof globalThis.Uint8Array;\n}\n/** Returns true if this value is undefined */\nexport function IsUndefined(value) {\n return value === undefined;\n}\n","import * as ValueGuard from '../guard/value.mjs';\nfunction ImmutableArray(value) {\n return globalThis.Object.freeze(value).map((value) => Immutable(value));\n}\nfunction ImmutableDate(value) {\n return value;\n}\nfunction ImmutableUint8Array(value) {\n return value;\n}\nfunction ImmutableRegExp(value) {\n return value;\n}\nfunction ImmutableObject(value) {\n const result = {};\n for (const key of Object.getOwnPropertyNames(value)) {\n result[key] = Immutable(value[key]);\n }\n for (const key of Object.getOwnPropertySymbols(value)) {\n result[key] = Immutable(value[key]);\n }\n return globalThis.Object.freeze(result);\n}\n/** Specialized deep immutable value. Applies freeze recursively to the given value */\n// prettier-ignore\nexport function Immutable(value) {\n return (ValueGuard.IsArray(value) ? ImmutableArray(value) :\n ValueGuard.IsDate(value) ? ImmutableDate(value) :\n ValueGuard.IsUint8Array(value) ? ImmutableUint8Array(value) :\n ValueGuard.IsRegExp(value) ? ImmutableRegExp(value) :\n ValueGuard.IsObject(value) ? ImmutableObject(value) :\n value);\n}\n","import * as ValueGuard from '../guard/value.mjs';\nfunction ArrayType(value) {\n return value.map((value) => Visit(value));\n}\nfunction DateType(value) {\n return new Date(value.getTime());\n}\nfunction Uint8ArrayType(value) {\n return new Uint8Array(value);\n}\nfunction RegExpType(value) {\n return new RegExp(value.source, value.flags);\n}\nfunction ObjectType(value) {\n const result = {};\n for (const key of Object.getOwnPropertyNames(value)) {\n result[key] = Visit(value[key]);\n }\n for (const key of Object.getOwnPropertySymbols(value)) {\n result[key] = Visit(value[key]);\n }\n return result;\n}\n// prettier-ignore\nfunction Visit(value) {\n return (ValueGuard.IsArray(value) ? ArrayType(value) :\n ValueGuard.IsDate(value) ? DateType(value) :\n ValueGuard.IsUint8Array(value) ? Uint8ArrayType(value) :\n ValueGuard.IsRegExp(value) ? RegExpType(value) :\n ValueGuard.IsObject(value) ? ObjectType(value) :\n value);\n}\n/** Clones a value */\nexport function Clone(value) {\n return Visit(value);\n}\n","import { TypeSystemPolicy } from '../../system/policy.mjs';\nimport { Immutable } from './immutable.mjs';\nimport { Clone } from '../clone/value.mjs';\n/** Creates TypeBox schematics using the configured InstanceMode */\nexport function CreateType(schema, options) {\n const result = options !== undefined ? { ...options, ...schema } : schema;\n switch (TypeSystemPolicy.InstanceMode) {\n case 'freeze':\n return Immutable(result);\n case 'clone':\n return Clone(result);\n default:\n return result;\n }\n}\n","/** Symbol key applied to transform types */\nexport const TransformKind = Symbol.for('TypeBox.Transform');\n/** Symbol key applied to readonly types */\nexport const ReadonlyKind = Symbol.for('TypeBox.Readonly');\n/** Symbol key applied to optional types */\nexport const OptionalKind = Symbol.for('TypeBox.Optional');\n/** Symbol key applied to types */\nexport const Hint = Symbol.for('TypeBox.Hint');\n/** Symbol key applied to types */\nexport const Kind = Symbol.for('TypeBox.Kind');\n","/** The base Error type thrown for all TypeBox exceptions */\nexport class TypeBoxError extends Error {\n constructor(message) {\n super(message);\n }\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n// prettier-ignore\nexport function MappedResult(properties) {\n return CreateType({\n [Kind]: 'MappedResult',\n properties\n });\n}\n","function DiscardKey(value, key) {\n const { [key]: _, ...rest } = value;\n return rest;\n}\n/** Discards property keys from the given value. This function returns a shallow Clone. */\nexport function Discard(value, keys) {\n return keys.reduce((acc, key) => DiscardKey(acc, key), value);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates an Array type */\nexport function Array(items, options) {\n return CreateType({ [Kind]: 'Array', type: 'array', items }, options);\n}\n","import { Kind } from '../symbols/index.mjs';\nimport { CreateType } from '../create/type.mjs';\n/** `[JavaScript]` Creates a AsyncIterator type */\nexport function AsyncIterator(items, options) {\n return CreateType({ [Kind]: 'AsyncIterator', type: 'AsyncIterator', items }, options);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[JavaScript]` Creates a Constructor type */\nexport function Constructor(parameters, returns, options) {\n return CreateType({ [Kind]: 'Constructor', type: 'Constructor', parameters, returns }, options);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[JavaScript]` Creates a Function type */\nexport function Function(parameters, returns, options) {\n return CreateType({ [Kind]: 'Function', type: 'Function', parameters, returns }, options);\n}\n","import { CreateType } from '../create/index.mjs';\nimport { Kind } from '../symbols/symbols.mjs';\n/** `[Internal]` Creates a deferred computed type. This type is used exclusively in modules to defer resolution of computable types that contain interior references */\nexport function Computed(target, parameters, options) {\n return CreateType({ [Kind]: 'Computed', target, parameters }, options);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates a Never type */\nexport function Never(options) {\n return CreateType({ [Kind]: 'Never', not: {} }, options);\n}\n","import * as ValueGuard from './value.mjs';\nimport { Kind, Hint, TransformKind, ReadonlyKind, OptionalKind } from '../symbols/index.mjs';\n/** `[Kind-Only]` Returns true if this value has a Readonly symbol */\nexport function IsReadonly(value) {\n return ValueGuard.IsObject(value) && value[ReadonlyKind] === 'Readonly';\n}\n/** `[Kind-Only]` Returns true if this value has a Optional symbol */\nexport function IsOptional(value) {\n return ValueGuard.IsObject(value) && value[OptionalKind] === 'Optional';\n}\n/** `[Kind-Only]` Returns true if the given value is TAny */\nexport function IsAny(value) {\n return IsKindOf(value, 'Any');\n}\n/** `[Kind-Only]` Returns true if the given value is TArray */\nexport function IsArray(value) {\n return IsKindOf(value, 'Array');\n}\n/** `[Kind-Only]` Returns true if the given value is TAsyncIterator */\nexport function IsAsyncIterator(value) {\n return IsKindOf(value, 'AsyncIterator');\n}\n/** `[Kind-Only]` Returns true if the given value is TBigInt */\nexport function IsBigInt(value) {\n return IsKindOf(value, 'BigInt');\n}\n/** `[Kind-Only]` Returns true if the given value is TBoolean */\nexport function IsBoolean(value) {\n return IsKindOf(value, 'Boolean');\n}\n/** `[Kind-Only]` Returns true if the given value is TComputed */\nexport function IsComputed(value) {\n return IsKindOf(value, 'Computed');\n}\n/** `[Kind-Only]` Returns true if the given value is TConstructor */\nexport function IsConstructor(value) {\n return IsKindOf(value, 'Constructor');\n}\n/** `[Kind-Only]` Returns true if the given value is TDate */\nexport function IsDate(value) {\n return IsKindOf(value, 'Date');\n}\n/** `[Kind-Only]` Returns true if the given value is TFunction */\nexport function IsFunction(value) {\n return IsKindOf(value, 'Function');\n}\n/** `[Kind-Only]` Returns true if the given value is TInteger */\nexport function IsImport(value) {\n return IsKindOf(value, 'Import');\n}\n/** `[Kind-Only]` Returns true if the given value is TInteger */\nexport function IsInteger(value) {\n return IsKindOf(value, 'Integer');\n}\n/** `[Kind-Only]` Returns true if the given schema is TProperties */\nexport function IsProperties(value) {\n return ValueGuard.IsObject(value);\n}\n/** `[Kind-Only]` Returns true if the given value is TIntersect */\nexport function IsIntersect(value) {\n return IsKindOf(value, 'Intersect');\n}\n/** `[Kind-Only]` Returns true if the given value is TIterator */\nexport function IsIterator(value) {\n return IsKindOf(value, 'Iterator');\n}\n/** `[Kind-Only]` Returns true if the given value is a TKind with the given name. */\nexport function IsKindOf(value, kind) {\n return ValueGuard.IsObject(value) && Kind in value && value[Kind] === kind;\n}\n/** `[Kind-Only]` Returns true if the given value is TLiteral */\nexport function IsLiteralString(value) {\n return IsLiteral(value) && ValueGuard.IsString(value.const);\n}\n/** `[Kind-Only]` Returns true if the given value is TLiteral */\nexport function IsLiteralNumber(value) {\n return IsLiteral(value) && ValueGuard.IsNumber(value.const);\n}\n/** `[Kind-Only]` Returns true if the given value is TLiteral */\nexport function IsLiteralBoolean(value) {\n return IsLiteral(value) && ValueGuard.IsBoolean(value.const);\n}\n/** `[Kind-Only]` Returns true if the given value is TLiteralValue */\nexport function IsLiteralValue(value) {\n return ValueGuard.IsBoolean(value) || ValueGuard.IsNumber(value) || ValueGuard.IsString(value);\n}\n/** `[Kind-Only]` Returns true if the given value is TLiteral */\nexport function IsLiteral(value) {\n return IsKindOf(value, 'Literal');\n}\n/** `[Kind-Only]` Returns true if the given value is a TMappedKey */\nexport function IsMappedKey(value) {\n return IsKindOf(value, 'MappedKey');\n}\n/** `[Kind-Only]` Returns true if the given value is TMappedResult */\nexport function IsMappedResult(value) {\n return IsKindOf(value, 'MappedResult');\n}\n/** `[Kind-Only]` Returns true if the given value is TNever */\nexport function IsNever(value) {\n return IsKindOf(value, 'Never');\n}\n/** `[Kind-Only]` Returns true if the given value is TNot */\nexport function IsNot(value) {\n return IsKindOf(value, 'Not');\n}\n/** `[Kind-Only]` Returns true if the given value is TNull */\nexport function IsNull(value) {\n return IsKindOf(value, 'Null');\n}\n/** `[Kind-Only]` Returns true if the given value is TNumber */\nexport function IsNumber(value) {\n return IsKindOf(value, 'Number');\n}\n/** `[Kind-Only]` Returns true if the given value is TObject */\nexport function IsObject(value) {\n return IsKindOf(value, 'Object');\n}\n/** `[Kind-Only]` Returns true if the given value is TPromise */\nexport function IsPromise(value) {\n return IsKindOf(value, 'Promise');\n}\n/** `[Kind-Only]` Returns true if the given value is TRecord */\nexport function IsRecord(value) {\n return IsKindOf(value, 'Record');\n}\n/** `[Kind-Only]` Returns true if this value is TRecursive */\nexport function IsRecursive(value) {\n return ValueGuard.IsObject(value) && Hint in value && value[Hint] === 'Recursive';\n}\n/** `[Kind-Only]` Returns true if the given value is TRef */\nexport function IsRef(value) {\n return IsKindOf(value, 'Ref');\n}\n/** `[Kind-Only]` Returns true if the given value is TRegExp */\nexport function IsRegExp(value) {\n return IsKindOf(value, 'RegExp');\n}\n/** `[Kind-Only]` Returns true if the given value is TString */\nexport function IsString(value) {\n return IsKindOf(value, 'String');\n}\n/** `[Kind-Only]` Returns true if the given value is TSymbol */\nexport function IsSymbol(value) {\n return IsKindOf(value, 'Symbol');\n}\n/** `[Kind-Only]` Returns true if the given value is TTemplateLiteral */\nexport function IsTemplateLiteral(value) {\n return IsKindOf(value, 'TemplateLiteral');\n}\n/** `[Kind-Only]` Returns true if the given value is TThis */\nexport function IsThis(value) {\n return IsKindOf(value, 'This');\n}\n/** `[Kind-Only]` Returns true of this value is TTransform */\nexport function IsTransform(value) {\n return ValueGuard.IsObject(value) && TransformKind in value;\n}\n/** `[Kind-Only]` Returns true if the given value is TTuple */\nexport function IsTuple(value) {\n return IsKindOf(value, 'Tuple');\n}\n/** `[Kind-Only]` Returns true if the given value is TUndefined */\nexport function IsUndefined(value) {\n return IsKindOf(value, 'Undefined');\n}\n/** `[Kind-Only]` Returns true if the given value is TUnion */\nexport function IsUnion(value) {\n return IsKindOf(value, 'Union');\n}\n/** `[Kind-Only]` Returns true if the given value is TUint8Array */\nexport function IsUint8Array(value) {\n return IsKindOf(value, 'Uint8Array');\n}\n/** `[Kind-Only]` Returns true if the given value is TUnknown */\nexport function IsUnknown(value) {\n return IsKindOf(value, 'Unknown');\n}\n/** `[Kind-Only]` Returns true if the given value is a raw TUnsafe */\nexport function IsUnsafe(value) {\n return IsKindOf(value, 'Unsafe');\n}\n/** `[Kind-Only]` Returns true if the given value is TVoid */\nexport function IsVoid(value) {\n return IsKindOf(value, 'Void');\n}\n/** `[Kind-Only]` Returns true if the given value is TKind */\nexport function IsKind(value) {\n return ValueGuard.IsObject(value) && Kind in value && ValueGuard.IsString(value[Kind]);\n}\n/** `[Kind-Only]` Returns true if the given value is TSchema */\nexport function IsSchema(value) {\n // prettier-ignore\n return (IsAny(value) ||\n IsArray(value) ||\n IsBoolean(value) ||\n IsBigInt(value) ||\n IsAsyncIterator(value) ||\n IsComputed(value) ||\n IsConstructor(value) ||\n IsDate(value) ||\n IsFunction(value) ||\n IsInteger(value) ||\n IsIntersect(value) ||\n IsIterator(value) ||\n IsLiteral(value) ||\n IsMappedKey(value) ||\n IsMappedResult(value) ||\n IsNever(value) ||\n IsNot(value) ||\n IsNull(value) ||\n IsNumber(value) ||\n IsObject(value) ||\n IsPromise(value) ||\n IsRecord(value) ||\n IsRef(value) ||\n IsRegExp(value) ||\n IsString(value) ||\n IsSymbol(value) ||\n IsTemplateLiteral(value) ||\n IsThis(value) ||\n IsTuple(value) ||\n IsUndefined(value) ||\n IsUnion(value) ||\n IsUint8Array(value) ||\n IsUnknown(value) ||\n IsUnsafe(value) ||\n IsVoid(value) ||\n IsKind(value));\n}\n","import { CreateType } from '../create/type.mjs';\nimport { OptionalKind } from '../symbols/index.mjs';\nimport { Discard } from '../discard/index.mjs';\nimport { OptionalFromMappedResult } from './optional-from-mapped-result.mjs';\nimport { IsMappedResult } from '../guard/kind.mjs';\nfunction RemoveOptional(schema) {\n return CreateType(Discard(schema, [OptionalKind]));\n}\nfunction AddOptional(schema) {\n return CreateType({ ...schema, [OptionalKind]: 'Optional' });\n}\n// prettier-ignore\nfunction OptionalWithFlag(schema, F) {\n return (F === false\n ? RemoveOptional(schema)\n : AddOptional(schema));\n}\n/** `[Json]` Creates a Optional property */\nexport function Optional(schema, enable) {\n const F = enable ?? true;\n return IsMappedResult(schema) ? OptionalFromMappedResult(schema, F) : OptionalWithFlag(schema, F);\n}\n","import { MappedResult } from '../mapped/index.mjs';\nimport { Optional } from './optional.mjs';\n// prettier-ignore\nfunction FromProperties(P, F) {\n const Acc = {};\n for (const K2 of globalThis.Object.getOwnPropertyNames(P))\n Acc[K2] = Optional(P[K2], F);\n return Acc;\n}\n// prettier-ignore\nfunction FromMappedResult(R, F) {\n return FromProperties(R.properties, F);\n}\n// prettier-ignore\nexport function OptionalFromMappedResult(R, F) {\n const P = FromMappedResult(R, F);\n return MappedResult(P);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsObject, IsSchema } from '../guard/kind.mjs';\n// ------------------------------------------------------------------\n// IntersectCreate\n// ------------------------------------------------------------------\n// prettier-ignore\nexport function IntersectCreate(T, options = {}) {\n const allObjects = T.every((schema) => IsObject(schema));\n const clonedUnevaluatedProperties = IsSchema(options.unevaluatedProperties)\n ? { unevaluatedProperties: options.unevaluatedProperties }\n : {};\n return CreateType((options.unevaluatedProperties === false || IsSchema(options.unevaluatedProperties) || allObjects\n ? { ...clonedUnevaluatedProperties, [Kind]: 'Intersect', type: 'object', allOf: T }\n : { ...clonedUnevaluatedProperties, [Kind]: 'Intersect', allOf: T }), options);\n}\n","import { OptionalKind } from '../symbols/index.mjs';\nimport { CreateType } from '../create/type.mjs';\nimport { Discard } from '../discard/index.mjs';\nimport { Never } from '../never/index.mjs';\nimport { Optional } from '../optional/index.mjs';\nimport { IntersectCreate } from './intersect-create.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsOptional, IsTransform } from '../guard/kind.mjs';\n// prettier-ignore\nfunction IsIntersectOptional(types) {\n return types.every(left => IsOptional(left));\n}\n// prettier-ignore\nfunction RemoveOptionalFromType(type) {\n return (Discard(type, [OptionalKind]));\n}\n// prettier-ignore\nfunction RemoveOptionalFromRest(types) {\n return types.map(left => IsOptional(left) ? RemoveOptionalFromType(left) : left);\n}\n// prettier-ignore\nfunction ResolveIntersect(types, options) {\n return (IsIntersectOptional(types)\n ? Optional(IntersectCreate(RemoveOptionalFromRest(types), options))\n : IntersectCreate(RemoveOptionalFromRest(types), options));\n}\n/** `[Json]` Creates an evaluated Intersect type */\nexport function IntersectEvaluated(types, options = {}) {\n if (types.length === 1)\n return CreateType(types[0], options);\n if (types.length === 0)\n return Never(options);\n if (types.some((schema) => IsTransform(schema)))\n throw new Error('Cannot intersect transform types');\n return ResolveIntersect(types, options);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Never } from '../never/index.mjs';\nimport { IntersectCreate } from './intersect-create.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsTransform } from '../guard/kind.mjs';\n/** `[Json]` Creates an evaluated Intersect type */\nexport function Intersect(types, options) {\n if (types.length === 1)\n return CreateType(types[0], options);\n if (types.length === 0)\n return Never(options);\n if (types.some((schema) => IsTransform(schema)))\n throw new Error('Cannot intersect transform types');\n return IntersectCreate(types, options);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\nexport function UnionCreate(T, options) {\n return CreateType({ [Kind]: 'Union', anyOf: T }, options);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { OptionalKind } from '../symbols/index.mjs';\nimport { Discard } from '../discard/index.mjs';\nimport { Never } from '../never/index.mjs';\nimport { Optional } from '../optional/index.mjs';\nimport { UnionCreate } from './union-create.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsOptional } from '../guard/kind.mjs';\n// prettier-ignore\nfunction IsUnionOptional(types) {\n return types.some(type => IsOptional(type));\n}\n// prettier-ignore\nfunction RemoveOptionalFromRest(types) {\n return types.map(left => IsOptional(left) ? RemoveOptionalFromType(left) : left);\n}\n// prettier-ignore\nfunction RemoveOptionalFromType(T) {\n return (Discard(T, [OptionalKind]));\n}\n// prettier-ignore\nfunction ResolveUnion(types, options) {\n const isOptional = IsUnionOptional(types);\n return (isOptional\n ? Optional(UnionCreate(RemoveOptionalFromRest(types), options))\n : UnionCreate(RemoveOptionalFromRest(types), options));\n}\n/** `[Json]` Creates an evaluated Union type */\nexport function UnionEvaluated(T, options) {\n // prettier-ignore\n return (T.length === 1 ? CreateType(T[0], options) :\n T.length === 0 ? Never(options) :\n ResolveUnion(T, options));\n}\n","import { Never } from '../never/index.mjs';\nimport { CreateType } from '../create/type.mjs';\nimport { UnionCreate } from './union-create.mjs';\n/** `[Json]` Creates a Union type */\nexport function Union(types, options) {\n // prettier-ignore\n return (types.length === 0 ? Never(options) :\n types.length === 1 ? CreateType(types[0], options) :\n UnionCreate(types, options));\n}\n","import { TypeBoxError } from '../error/index.mjs';\n// ------------------------------------------------------------------\n// TemplateLiteralParserError\n// ------------------------------------------------------------------\nexport class TemplateLiteralParserError extends TypeBoxError {\n}\n// -------------------------------------------------------------------\n// Unescape\n//\n// Unescape for these control characters specifically. Note that this\n// function is only called on non union group content, and where we\n// still want to allow the user to embed control characters in that\n// content. For review.\n// -------------------------------------------------------------------\n// prettier-ignore\nfunction Unescape(pattern) {\n return pattern\n .replace(/\\\\\\$/g, '$')\n .replace(/\\\\\\*/g, '*')\n .replace(/\\\\\\^/g, '^')\n .replace(/\\\\\\|/g, '|')\n .replace(/\\\\\\(/g, '(')\n .replace(/\\\\\\)/g, ')');\n}\n// -------------------------------------------------------------------\n// Control Characters\n// -------------------------------------------------------------------\nfunction IsNonEscaped(pattern, index, char) {\n return pattern[index] === char && pattern.charCodeAt(index - 1) !== 92;\n}\nfunction IsOpenParen(pattern, index) {\n return IsNonEscaped(pattern, index, '(');\n}\nfunction IsCloseParen(pattern, index) {\n return IsNonEscaped(pattern, index, ')');\n}\nfunction IsSeparator(pattern, index) {\n return IsNonEscaped(pattern, index, '|');\n}\n// -------------------------------------------------------------------\n// Control Groups\n// -------------------------------------------------------------------\nfunction IsGroup(pattern) {\n if (!(IsOpenParen(pattern, 0) && IsCloseParen(pattern, pattern.length - 1)))\n return false;\n let count = 0;\n for (let index = 0; index < pattern.length; index++) {\n if (IsOpenParen(pattern, index))\n count += 1;\n if (IsCloseParen(pattern, index))\n count -= 1;\n if (count === 0 && index !== pattern.length - 1)\n return false;\n }\n return true;\n}\n// prettier-ignore\nfunction InGroup(pattern) {\n return pattern.slice(1, pattern.length - 1);\n}\n// prettier-ignore\nfunction IsPrecedenceOr(pattern) {\n let count = 0;\n for (let index = 0; index < pattern.length; index++) {\n if (IsOpenParen(pattern, index))\n count += 1;\n if (IsCloseParen(pattern, index))\n count -= 1;\n if (IsSeparator(pattern, index) && count === 0)\n return true;\n }\n return false;\n}\n// prettier-ignore\nfunction IsPrecedenceAnd(pattern) {\n for (let index = 0; index < pattern.length; index++) {\n if (IsOpenParen(pattern, index))\n return true;\n }\n return false;\n}\n// prettier-ignore\nfunction Or(pattern) {\n let [count, start] = [0, 0];\n const expressions = [];\n for (let index = 0; index < pattern.length; index++) {\n if (IsOpenParen(pattern, index))\n count += 1;\n if (IsCloseParen(pattern, index))\n count -= 1;\n if (IsSeparator(pattern, index) && count === 0) {\n const range = pattern.slice(start, index);\n if (range.length > 0)\n expressions.push(TemplateLiteralParse(range));\n start = index + 1;\n }\n }\n const range = pattern.slice(start);\n if (range.length > 0)\n expressions.push(TemplateLiteralParse(range));\n if (expressions.length === 0)\n return { type: 'const', const: '' };\n if (expressions.length === 1)\n return expressions[0];\n return { type: 'or', expr: expressions };\n}\n// prettier-ignore\nfunction And(pattern) {\n function Group(value, index) {\n if (!IsOpenParen(value, index))\n throw new TemplateLiteralParserError(`TemplateLiteralParser: Index must point to open parens`);\n let count = 0;\n for (let scan = index; scan < value.length; scan++) {\n if (IsOpenParen(value, scan))\n count += 1;\n if (IsCloseParen(value, scan))\n count -= 1;\n if (count === 0)\n return [index, scan];\n }\n throw new TemplateLiteralParserError(`TemplateLiteralParser: Unclosed group parens in expression`);\n }\n function Range(pattern, index) {\n for (let scan = index; scan < pattern.length; scan++) {\n if (IsOpenParen(pattern, scan))\n return [index, scan];\n }\n return [index, pattern.length];\n }\n const expressions = [];\n for (let index = 0; index < pattern.length; index++) {\n if (IsOpenParen(pattern, index)) {\n const [start, end] = Group(pattern, index);\n const range = pattern.slice(start, end + 1);\n expressions.push(TemplateLiteralParse(range));\n index = end;\n }\n else {\n const [start, end] = Range(pattern, index);\n const range = pattern.slice(start, end);\n if (range.length > 0)\n expressions.push(TemplateLiteralParse(range));\n index = end - 1;\n }\n }\n return ((expressions.length === 0) ? { type: 'const', const: '' } :\n (expressions.length === 1) ? expressions[0] :\n { type: 'and', expr: expressions });\n}\n// ------------------------------------------------------------------\n// TemplateLiteralParse\n// ------------------------------------------------------------------\n/** Parses a pattern and returns an expression tree */\nexport function TemplateLiteralParse(pattern) {\n // prettier-ignore\n return (IsGroup(pattern) ? TemplateLiteralParse(InGroup(pattern)) :\n IsPrecedenceOr(pattern) ? Or(pattern) :\n IsPrecedenceAnd(pattern) ? And(pattern) :\n { type: 'const', const: Unescape(pattern) });\n}\n// ------------------------------------------------------------------\n// TemplateLiteralParseExact\n// ------------------------------------------------------------------\n/** Parses a pattern and strips forward and trailing ^ and $ */\nexport function TemplateLiteralParseExact(pattern) {\n return TemplateLiteralParse(pattern.slice(1, pattern.length - 1));\n}\n","import { TemplateLiteralParseExact } from './parse.mjs';\nimport { TypeBoxError } from '../error/index.mjs';\n// ------------------------------------------------------------------\n// TemplateLiteralFiniteError\n// ------------------------------------------------------------------\nexport class TemplateLiteralFiniteError extends TypeBoxError {\n}\n// ------------------------------------------------------------------\n// IsTemplateLiteralFiniteCheck\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction IsNumberExpression(expression) {\n return (expression.type === 'or' &&\n expression.expr.length === 2 &&\n expression.expr[0].type === 'const' &&\n expression.expr[0].const === '0' &&\n expression.expr[1].type === 'const' &&\n expression.expr[1].const === '[1-9][0-9]*');\n}\n// prettier-ignore\nfunction IsBooleanExpression(expression) {\n return (expression.type === 'or' &&\n expression.expr.length === 2 &&\n expression.expr[0].type === 'const' &&\n expression.expr[0].const === 'true' &&\n expression.expr[1].type === 'const' &&\n expression.expr[1].const === 'false');\n}\n// prettier-ignore\nfunction IsStringExpression(expression) {\n return expression.type === 'const' && expression.const === '.*';\n}\n// ------------------------------------------------------------------\n// IsTemplateLiteralExpressionFinite\n// ------------------------------------------------------------------\n// prettier-ignore\nexport function IsTemplateLiteralExpressionFinite(expression) {\n return (IsNumberExpression(expression) || IsStringExpression(expression) ? false :\n IsBooleanExpression(expression) ? true :\n (expression.type === 'and') ? expression.expr.every((expr) => IsTemplateLiteralExpressionFinite(expr)) :\n (expression.type === 'or') ? expression.expr.every((expr) => IsTemplateLiteralExpressionFinite(expr)) :\n (expression.type === 'const') ? true :\n (() => { throw new TemplateLiteralFiniteError(`Unknown expression type`); })());\n}\n/** Returns true if this TemplateLiteral resolves to a finite set of values */\nexport function IsTemplateLiteralFinite(schema) {\n const expression = TemplateLiteralParseExact(schema.pattern);\n return IsTemplateLiteralExpressionFinite(expression);\n}\n","import { IsTemplateLiteralExpressionFinite } from './finite.mjs';\nimport { TemplateLiteralParseExact } from './parse.mjs';\nimport { TypeBoxError } from '../error/index.mjs';\n// ------------------------------------------------------------------\n// TemplateLiteralGenerateError\n// ------------------------------------------------------------------\nexport class TemplateLiteralGenerateError extends TypeBoxError {\n}\n// ------------------------------------------------------------------\n// TemplateLiteralExpressionGenerate\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction* GenerateReduce(buffer) {\n if (buffer.length === 1)\n return yield* buffer[0];\n for (const left of buffer[0]) {\n for (const right of GenerateReduce(buffer.slice(1))) {\n yield `${left}${right}`;\n }\n }\n}\n// prettier-ignore\nfunction* GenerateAnd(expression) {\n return yield* GenerateReduce(expression.expr.map((expr) => [...TemplateLiteralExpressionGenerate(expr)]));\n}\n// prettier-ignore\nfunction* GenerateOr(expression) {\n for (const expr of expression.expr)\n yield* TemplateLiteralExpressionGenerate(expr);\n}\n// prettier-ignore\nfunction* GenerateConst(expression) {\n return yield expression.const;\n}\nexport function* TemplateLiteralExpressionGenerate(expression) {\n return expression.type === 'and'\n ? yield* GenerateAnd(expression)\n : expression.type === 'or'\n ? yield* GenerateOr(expression)\n : expression.type === 'const'\n ? yield* GenerateConst(expression)\n : (() => {\n throw new TemplateLiteralGenerateError('Unknown expression');\n })();\n}\n/** Generates a tuple of strings from the given TemplateLiteral. Returns an empty tuple if infinite. */\nexport function TemplateLiteralGenerate(schema) {\n const expression = TemplateLiteralParseExact(schema.pattern);\n // prettier-ignore\n return (IsTemplateLiteralExpressionFinite(expression)\n ? [...TemplateLiteralExpressionGenerate(expression)]\n : []);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates a Literal type */\nexport function Literal(value, options) {\n return CreateType({\n [Kind]: 'Literal',\n const: value,\n type: typeof value,\n }, options);\n}\n","import { Kind } from '../symbols/index.mjs';\nimport { CreateType } from '../create/index.mjs';\n/** `[Json]` Creates a Boolean type */\nexport function Boolean(options) {\n return CreateType({ [Kind]: 'Boolean', type: 'boolean' }, options);\n}\n","import { Kind } from '../symbols/index.mjs';\nimport { CreateType } from '../create/index.mjs';\n/** `[JavaScript]` Creates a BigInt type */\nexport function BigInt(options) {\n return CreateType({ [Kind]: 'BigInt', type: 'bigint' }, options);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates a Number type */\nexport function Number(options) {\n return CreateType({ [Kind]: 'Number', type: 'number' }, options);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates a String type */\nexport function String(options) {\n return CreateType({ [Kind]: 'String', type: 'string' }, options);\n}\n","import { Literal } from '../literal/index.mjs';\nimport { Boolean } from '../boolean/index.mjs';\nimport { BigInt } from '../bigint/index.mjs';\nimport { Number } from '../number/index.mjs';\nimport { String } from '../string/index.mjs';\nimport { UnionEvaluated } from '../union/index.mjs';\nimport { Never } from '../never/index.mjs';\n// ------------------------------------------------------------------\n// SyntaxParsers\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction* FromUnion(syntax) {\n const trim = syntax.trim().replace(/\"|'/g, '');\n return (trim === 'boolean' ? yield Boolean() :\n trim === 'number' ? yield Number() :\n trim === 'bigint' ? yield BigInt() :\n trim === 'string' ? yield String() :\n yield (() => {\n const literals = trim.split('|').map((literal) => Literal(literal.trim()));\n return (literals.length === 0 ? Never() :\n literals.length === 1 ? literals[0] :\n UnionEvaluated(literals));\n })());\n}\n// prettier-ignore\nfunction* FromTerminal(syntax) {\n if (syntax[1] !== '{') {\n const L = Literal('$');\n const R = FromSyntax(syntax.slice(1));\n return yield* [L, ...R];\n }\n for (let i = 2; i < syntax.length; i++) {\n if (syntax[i] === '}') {\n const L = FromUnion(syntax.slice(2, i));\n const R = FromSyntax(syntax.slice(i + 1));\n return yield* [...L, ...R];\n }\n }\n yield Literal(syntax);\n}\n// prettier-ignore\nfunction* FromSyntax(syntax) {\n for (let i = 0; i < syntax.length; i++) {\n if (syntax[i] === '$') {\n const L = Literal(syntax.slice(0, i));\n const R = FromTerminal(syntax.slice(i));\n return yield* [L, ...R];\n }\n }\n yield Literal(syntax);\n}\n/** Parses TemplateLiteralSyntax and returns a tuple of TemplateLiteralKinds */\nexport function TemplateLiteralSyntax(syntax) {\n return [...FromSyntax(syntax)];\n}\n","export const PatternBoolean = '(true|false)';\nexport const PatternNumber = '(0|[1-9][0-9]*)';\nexport const PatternString = '(.*)';\nexport const PatternNever = '(?!.*)';\nexport const PatternBooleanExact = `^${PatternBoolean}$`;\nexport const PatternNumberExact = `^${PatternNumber}$`;\nexport const PatternStringExact = `^${PatternString}$`;\nexport const PatternNeverExact = `^${PatternNever}$`;\n","import { PatternNumber, PatternString, PatternBoolean } from '../patterns/index.mjs';\nimport { Kind } from '../symbols/index.mjs';\nimport { TypeBoxError } from '../error/index.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsTemplateLiteral, IsUnion, IsNumber, IsInteger, IsBigInt, IsString, IsLiteral, IsBoolean } from '../guard/kind.mjs';\n// ------------------------------------------------------------------\n// TemplateLiteralPatternError\n// ------------------------------------------------------------------\nexport class TemplateLiteralPatternError extends TypeBoxError {\n}\n// ------------------------------------------------------------------\n// TemplateLiteralPattern\n// ------------------------------------------------------------------\nfunction Escape(value) {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n// prettier-ignore\nfunction Visit(schema, acc) {\n return (IsTemplateLiteral(schema) ? schema.pattern.slice(1, schema.pattern.length - 1) :\n IsUnion(schema) ? `(${schema.anyOf.map((schema) => Visit(schema, acc)).join('|')})` :\n IsNumber(schema) ? `${acc}${PatternNumber}` :\n IsInteger(schema) ? `${acc}${PatternNumber}` :\n IsBigInt(schema) ? `${acc}${PatternNumber}` :\n IsString(schema) ? `${acc}${PatternString}` :\n IsLiteral(schema) ? `${acc}${Escape(schema.const.toString())}` :\n IsBoolean(schema) ? `${acc}${PatternBoolean}` :\n (() => { throw new TemplateLiteralPatternError(`Unexpected Kind '${schema[Kind]}'`); })());\n}\nexport function TemplateLiteralPattern(kinds) {\n return `^${kinds.map((schema) => Visit(schema, '')).join('')}\\$`;\n}\n","import { UnionEvaluated } from '../union/index.mjs';\nimport { Literal } from '../literal/index.mjs';\nimport { TemplateLiteralGenerate } from './generate.mjs';\n/** Returns a Union from the given TemplateLiteral */\nexport function TemplateLiteralToUnion(schema) {\n const R = TemplateLiteralGenerate(schema);\n const L = R.map((S) => Literal(S));\n return UnionEvaluated(L);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { TemplateLiteralSyntax } from './syntax.mjs';\nimport { TemplateLiteralPattern } from './pattern.mjs';\nimport { IsString } from '../guard/value.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates a TemplateLiteral type */\n// prettier-ignore\nexport function TemplateLiteral(unresolved, options) {\n const pattern = IsString(unresolved)\n ? TemplateLiteralPattern(TemplateLiteralSyntax(unresolved))\n : TemplateLiteralPattern(unresolved);\n return CreateType({ [Kind]: 'TemplateLiteral', type: 'string', pattern }, options);\n}\n","import { TemplateLiteralGenerate } from '../template-literal/index.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsTemplateLiteral, IsUnion, IsLiteral, IsNumber, IsInteger } from '../guard/kind.mjs';\n// prettier-ignore\nfunction FromTemplateLiteral(templateLiteral) {\n const keys = TemplateLiteralGenerate(templateLiteral);\n return keys.map(key => key.toString());\n}\n// prettier-ignore\nfunction FromUnion(types) {\n const result = [];\n for (const type of types)\n result.push(...IndexPropertyKeys(type));\n return result;\n}\n// prettier-ignore\nfunction FromLiteral(literalValue) {\n return ([literalValue.toString()] // TS 5.4 observes TLiteralValue as not having a toString()\n );\n}\n/** Returns a tuple of PropertyKeys derived from the given TSchema */\n// prettier-ignore\nexport function IndexPropertyKeys(type) {\n return [...new Set((IsTemplateLiteral(type) ? FromTemplateLiteral(type) :\n IsUnion(type) ? FromUnion(type.anyOf) :\n IsLiteral(type) ? FromLiteral(type.const) :\n IsNumber(type) ? ['[number]'] :\n IsInteger(type) ? ['[number]'] :\n []))];\n}\n","import { MappedResult } from '../mapped/index.mjs';\nimport { IndexPropertyKeys } from './indexed-property-keys.mjs';\nimport { Index } from './index.mjs';\n// prettier-ignore\nfunction FromProperties(type, properties, options) {\n const result = {};\n for (const K2 of Object.getOwnPropertyNames(properties)) {\n result[K2] = Index(type, IndexPropertyKeys(properties[K2]), options);\n }\n return result;\n}\n// prettier-ignore\nfunction FromMappedResult(type, mappedResult, options) {\n return FromProperties(type, mappedResult.properties, options);\n}\n// prettier-ignore\nexport function IndexFromMappedResult(type, mappedResult, options) {\n const properties = FromMappedResult(type, mappedResult, options);\n return MappedResult(properties);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { TypeBoxError } from '../error/index.mjs';\nimport { Computed } from '../computed/index.mjs';\nimport { Never } from '../never/index.mjs';\nimport { IntersectEvaluated } from '../intersect/index.mjs';\nimport { UnionEvaluated } from '../union/index.mjs';\nimport { IndexPropertyKeys } from './indexed-property-keys.mjs';\nimport { IndexFromMappedKey } from './indexed-from-mapped-key.mjs';\nimport { IndexFromMappedResult } from './indexed-from-mapped-result.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsArray, IsIntersect, IsObject, IsMappedKey, IsMappedResult, IsNever, IsSchema, IsTuple, IsUnion, IsRef } from '../guard/kind.mjs';\n// prettier-ignore\nfunction FromRest(types, key) {\n return types.map(type => IndexFromPropertyKey(type, key));\n}\n// prettier-ignore\nfunction FromIntersectRest(types) {\n return types.filter(type => !IsNever(type));\n}\n// prettier-ignore\nfunction FromIntersect(types, key) {\n return (IntersectEvaluated(FromIntersectRest(FromRest(types, key))));\n}\n// prettier-ignore\nfunction FromUnionRest(types) {\n return (types.some(L => IsNever(L))\n ? []\n : types);\n}\n// prettier-ignore\nfunction FromUnion(types, key) {\n return (UnionEvaluated(FromUnionRest(FromRest(types, key))));\n}\n// prettier-ignore\nfunction FromTuple(types, key) {\n return (key in types ? types[key] :\n key === '[number]' ? UnionEvaluated(types) :\n Never());\n}\n// prettier-ignore\nfunction FromArray(type, key) {\n return (key === '[number]'\n ? type\n : Never());\n}\n// prettier-ignore\nfunction FromProperty(properties, propertyKey) {\n return (propertyKey in properties ? properties[propertyKey] : Never());\n}\n// prettier-ignore\nexport function IndexFromPropertyKey(type, propertyKey) {\n return (IsIntersect(type) ? FromIntersect(type.allOf, propertyKey) :\n IsUnion(type) ? FromUnion(type.anyOf, propertyKey) :\n IsTuple(type) ? FromTuple(type.items ?? [], propertyKey) :\n IsArray(type) ? FromArray(type.items, propertyKey) :\n IsObject(type) ? FromProperty(type.properties, propertyKey) :\n Never());\n}\n// prettier-ignore\nexport function IndexFromPropertyKeys(type, propertyKeys) {\n return propertyKeys.map(propertyKey => IndexFromPropertyKey(type, propertyKey));\n}\n// prettier-ignore\nfunction FromSchema(type, propertyKeys) {\n return (UnionEvaluated(IndexFromPropertyKeys(type, propertyKeys)));\n}\n// prettier-ignore\nexport function IndexFromComputed(type, key) {\n return Computed('Index', [type, key]);\n}\n/** `[Json]` Returns an Indexed property type for the given keys */\nexport function Index(type, key, options) {\n // computed-type\n if (IsRef(type) || IsRef(key)) {\n const error = `Index types using Ref parameters require both Type and Key to be of TSchema`;\n if (!IsSchema(type) || !IsSchema(key))\n throw new TypeBoxError(error);\n return Computed('Index', [type, key]);\n }\n // mapped-types\n if (IsMappedResult(key))\n return IndexFromMappedResult(type, key, options);\n if (IsMappedKey(key))\n return IndexFromMappedKey(type, key, options);\n // prettier-ignore\n return CreateType(IsSchema(key)\n ? FromSchema(type, IndexPropertyKeys(key))\n : FromSchema(type, key), options);\n}\n","import { Index } from './indexed.mjs';\nimport { MappedResult } from '../mapped/index.mjs';\nimport { Clone } from '../clone/value.mjs';\n// prettier-ignore\nfunction MappedIndexPropertyKey(type, key, options) {\n return { [key]: Index(type, [key], Clone(options)) };\n}\n// prettier-ignore\nfunction MappedIndexPropertyKeys(type, propertyKeys, options) {\n return propertyKeys.reduce((result, left) => {\n return { ...result, ...MappedIndexPropertyKey(type, left, options) };\n }, {});\n}\n// prettier-ignore\nfunction MappedIndexProperties(type, mappedKey, options) {\n return MappedIndexPropertyKeys(type, mappedKey.keys, options);\n}\n// prettier-ignore\nexport function IndexFromMappedKey(type, mappedKey, options) {\n const properties = MappedIndexProperties(type, mappedKey, options);\n return MappedResult(properties);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[JavaScript]` Creates an Iterator type */\nexport function Iterator(items, options) {\n return CreateType({ [Kind]: 'Iterator', type: 'Iterator', items }, options);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsOptional } from '../guard/kind.mjs';\nfunction RequiredKeys(properties) {\n const keys = [];\n for (let key in properties) {\n if (!IsOptional(properties[key]))\n keys.push(key);\n }\n return keys;\n}\n/** `[Json]` Creates an Object type */\nfunction _Object(properties, options) {\n const required = RequiredKeys(properties);\n const schematic = required.length > 0 ? { [Kind]: 'Object', type: 'object', properties, required } : { [Kind]: 'Object', type: 'object', properties };\n return CreateType(schematic, options);\n}\n/** `[Json]` Creates an Object type */\nexport var Object = _Object;\n","import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[JavaScript]` Creates a Promise type */\nexport function Promise(item, options) {\n return CreateType({ [Kind]: 'Promise', type: 'Promise', item }, options);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { ReadonlyKind } from '../symbols/index.mjs';\nimport { Discard } from '../discard/index.mjs';\nimport { ReadonlyFromMappedResult } from './readonly-from-mapped-result.mjs';\nimport { IsMappedResult } from '../guard/kind.mjs';\nfunction RemoveReadonly(schema) {\n return CreateType(Discard(schema, [ReadonlyKind]));\n}\nfunction AddReadonly(schema) {\n return CreateType({ ...schema, [ReadonlyKind]: 'Readonly' });\n}\n// prettier-ignore\nfunction ReadonlyWithFlag(schema, F) {\n return (F === false\n ? RemoveReadonly(schema)\n : AddReadonly(schema));\n}\n/** `[Json]` Creates a Readonly property */\nexport function Readonly(schema, enable) {\n const F = enable ?? true;\n return IsMappedResult(schema) ? ReadonlyFromMappedResult(schema, F) : ReadonlyWithFlag(schema, F);\n}\n","import { MappedResult } from '../mapped/index.mjs';\nimport { Readonly } from './readonly.mjs';\n// prettier-ignore\nfunction FromProperties(K, F) {\n const Acc = {};\n for (const K2 of globalThis.Object.getOwnPropertyNames(K))\n Acc[K2] = Readonly(K[K2], F);\n return Acc;\n}\n// prettier-ignore\nfunction FromMappedResult(R, F) {\n return FromProperties(R.properties, F);\n}\n// prettier-ignore\nexport function ReadonlyFromMappedResult(R, F) {\n const P = FromMappedResult(R, F);\n return MappedResult(P);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates a Tuple type */\nexport function Tuple(types, options) {\n // prettier-ignore\n return CreateType(types.length > 0 ?\n { [Kind]: 'Tuple', type: 'array', items: types, additionalItems: false, minItems: types.length, maxItems: types.length } :\n { [Kind]: 'Tuple', type: 'array', minItems: types.length, maxItems: types.length }, options);\n}\n","import { Kind, OptionalKind, ReadonlyKind } from '../symbols/index.mjs';\nimport { Discard } from '../discard/index.mjs';\n// evaluation types\nimport { Array } from '../array/index.mjs';\nimport { AsyncIterator } from '../async-iterator/index.mjs';\nimport { Constructor } from '../constructor/index.mjs';\nimport { Function as FunctionType } from '../function/index.mjs';\nimport { IndexPropertyKeys } from '../indexed/index.mjs';\nimport { Intersect } from '../intersect/index.mjs';\nimport { Iterator } from '../iterator/index.mjs';\nimport { Literal } from '../literal/index.mjs';\nimport { Object } from '../object/index.mjs';\nimport { Optional } from '../optional/index.mjs';\nimport { Promise } from '../promise/index.mjs';\nimport { Readonly } from '../readonly/index.mjs';\nimport { Tuple } from '../tuple/index.mjs';\nimport { Union } from '../union/index.mjs';\n// operator\nimport { SetIncludes } from '../sets/index.mjs';\n// mapping types\nimport { MappedResult } from './mapped-result.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsArray, IsAsyncIterator, IsConstructor, IsFunction, IsIntersect, IsIterator, IsReadonly, IsMappedResult, IsMappedKey, IsObject, IsOptional, IsPromise, IsSchema, IsTuple, IsUnion } from '../guard/kind.mjs';\n// prettier-ignore\nfunction FromMappedResult(K, P) {\n return (K in P\n ? FromSchemaType(K, P[K])\n : MappedResult(P));\n}\n// prettier-ignore\nfunction MappedKeyToKnownMappedResultProperties(K) {\n return { [K]: Literal(K) };\n}\n// prettier-ignore\nfunction MappedKeyToUnknownMappedResultProperties(P) {\n const Acc = {};\n for (const L of P)\n Acc[L] = Literal(L);\n return Acc;\n}\n// prettier-ignore\nfunction MappedKeyToMappedResultProperties(K, P) {\n return (SetIncludes(P, K)\n ? MappedKeyToKnownMappedResultProperties(K)\n : MappedKeyToUnknownMappedResultProperties(P));\n}\n// prettier-ignore\nfunction FromMappedKey(K, P) {\n const R = MappedKeyToMappedResultProperties(K, P);\n return FromMappedResult(K, R);\n}\n// prettier-ignore\nfunction FromRest(K, T) {\n return T.map(L => FromSchemaType(K, L));\n}\n// prettier-ignore\nfunction FromProperties(K, T) {\n const Acc = {};\n for (const K2 of globalThis.Object.getOwnPropertyNames(T))\n Acc[K2] = FromSchemaType(K, T[K2]);\n return Acc;\n}\n// prettier-ignore\nfunction FromSchemaType(K, T) {\n // required to retain user defined options for mapped type\n const options = { ...T };\n return (\n // unevaluated modifier types\n IsOptional(T) ? Optional(FromSchemaType(K, Discard(T, [OptionalKind]))) :\n IsReadonly(T) ? Readonly(FromSchemaType(K, Discard(T, [ReadonlyKind]))) :\n // unevaluated mapped types\n IsMappedResult(T) ? FromMappedResult(K, T.properties) :\n IsMappedKey(T) ? FromMappedKey(K, T.keys) :\n // unevaluated types\n IsConstructor(T) ? Constructor(FromRest(K, T.parameters), FromSchemaType(K, T.returns), options) :\n IsFunction(T) ? FunctionType(FromRest(K, T.parameters), FromSchemaType(K, T.returns), options) :\n IsAsyncIterator(T) ? AsyncIterator(FromSchemaType(K, T.items), options) :\n IsIterator(T) ? Iterator(FromSchemaType(K, T.items), options) :\n IsIntersect(T) ? Intersect(FromRest(K, T.allOf), options) :\n IsUnion(T) ? Union(FromRest(K, T.anyOf), options) :\n IsTuple(T) ? Tuple(FromRest(K, T.items ?? []), options) :\n IsObject(T) ? Object(FromProperties(K, T.properties), options) :\n IsArray(T) ? Array(FromSchemaType(K, T.items), options) :\n IsPromise(T) ? Promise(FromSchemaType(K, T.item), options) :\n T);\n}\n// prettier-ignore\nexport function MappedFunctionReturnType(K, T) {\n const Acc = {};\n for (const L of K)\n Acc[L] = FromSchemaType(L, T);\n return Acc;\n}\n/** `[Json]` Creates a Mapped object type */\nexport function Mapped(key, map, options) {\n const K = IsSchema(key) ? IndexPropertyKeys(key) : key;\n const RT = map({ [Kind]: 'MappedKey', keys: K });\n const R = MappedFunctionReturnType(K, RT);\n return Object(R, options);\n}\n","/** Returns true if element right is in the set of left */\n// prettier-ignore\nexport function SetIncludes(T, S) {\n return T.includes(S);\n}\n/** Returns true if left is a subset of right */\nexport function SetIsSubset(T, S) {\n return T.every((L) => SetIncludes(S, L));\n}\n/** Returns a distinct set of elements */\nexport function SetDistinct(T) {\n return [...new Set(T)];\n}\n/** Returns the Intersect of the given sets */\nexport function SetIntersect(T, S) {\n return T.filter((L) => S.includes(L));\n}\n/** Returns the Union of the given sets */\nexport function SetUnion(T, S) {\n return [...T, ...S];\n}\n/** Returns the Complement by omitting elements in T that are in S */\n// prettier-ignore\nexport function SetComplement(T, S) {\n return T.filter(L => !S.includes(L));\n}\n// prettier-ignore\nfunction SetIntersectManyResolve(T, Init) {\n return T.reduce((Acc, L) => {\n return SetIntersect(Acc, L);\n }, Init);\n}\n// prettier-ignore\nexport function SetIntersectMany(T) {\n return (T.length === 1\n ? T[0]\n // Use left to initialize the accumulator for resolve\n : T.length > 1\n ? SetIntersectManyResolve(T.slice(1), T[0])\n : []);\n}\n/** Returns the Union of multiple sets */\nexport function SetUnionMany(T) {\n const Acc = [];\n for (const L of T)\n Acc.push(...L);\n return Acc;\n}\n","import { TypeBoxError } from '../error/index.mjs';\nimport { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates a Ref type. The referenced type must contain a $id */\nexport function Ref(...args) {\n const [$ref, options] = typeof args[0] === 'string' ? [args[0], args[1]] : [args[0].$id, args[1]];\n if (typeof $ref !== 'string')\n throw new TypeBoxError('Ref: $ref must be a string');\n return CreateType({ [Kind]: 'Ref', $ref }, options);\n}\n","import { SetUnionMany, SetIntersectMany } from '../sets/index.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsIntersect, IsUnion, IsTuple, IsArray, IsObject, IsRecord } from '../guard/kind.mjs';\n// prettier-ignore\nfunction FromRest(types) {\n const result = [];\n for (const L of types)\n result.push(KeyOfPropertyKeys(L));\n return result;\n}\n// prettier-ignore\nfunction FromIntersect(types) {\n const propertyKeysArray = FromRest(types);\n const propertyKeys = SetUnionMany(propertyKeysArray);\n return propertyKeys;\n}\n// prettier-ignore\nfunction FromUnion(types) {\n const propertyKeysArray = FromRest(types);\n const propertyKeys = SetIntersectMany(propertyKeysArray);\n return propertyKeys;\n}\n// prettier-ignore\nfunction FromTuple(types) {\n return types.map((_, indexer) => indexer.toString());\n}\n// prettier-ignore\nfunction FromArray(_) {\n return (['[number]']);\n}\n// prettier-ignore\nfunction FromProperties(T) {\n return (globalThis.Object.getOwnPropertyNames(T));\n}\n// ------------------------------------------------------------------\n// FromPatternProperties\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromPatternProperties(patternProperties) {\n if (!includePatternProperties)\n return [];\n const patternPropertyKeys = globalThis.Object.getOwnPropertyNames(patternProperties);\n return patternPropertyKeys.map(key => {\n return (key[0] === '^' && key[key.length - 1] === '$')\n ? key.slice(1, key.length - 1)\n : key;\n });\n}\n/** Returns a tuple of PropertyKeys derived from the given TSchema. */\n// prettier-ignore\nexport function KeyOfPropertyKeys(type) {\n return (IsIntersect(type) ? FromIntersect(type.allOf) :\n IsUnion(type) ? FromUnion(type.anyOf) :\n IsTuple(type) ? FromTuple(type.items ?? []) :\n IsArray(type) ? FromArray(type.items) :\n IsObject(type) ? FromProperties(type.properties) :\n IsRecord(type) ? FromPatternProperties(type.patternProperties) :\n []);\n}\n// ----------------------------------------------------------------\n// KeyOfPattern\n// ----------------------------------------------------------------\nlet includePatternProperties = false;\n/** Returns a regular expression pattern derived from the given TSchema */\nexport function KeyOfPattern(schema) {\n includePatternProperties = true;\n const keys = KeyOfPropertyKeys(schema);\n includePatternProperties = false;\n const pattern = keys.map((key) => `(${key})`);\n return `^(${pattern.join('|')})$`;\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Literal } from '../literal/index.mjs';\nimport { Number } from '../number/index.mjs';\nimport { Computed } from '../computed/index.mjs';\nimport { Ref } from '../ref/index.mjs';\nimport { KeyOfPropertyKeys } from './keyof-property-keys.mjs';\nimport { UnionEvaluated } from '../union/index.mjs';\nimport { KeyOfFromMappedResult } from './keyof-from-mapped-result.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsMappedResult, IsRef, IsComputed } from '../guard/kind.mjs';\n// prettier-ignore\nfunction FromComputed(target, parameters) {\n return Computed('KeyOf', [Computed(target, parameters)]);\n}\n// prettier-ignore\nfunction FromRef($ref) {\n return Computed('KeyOf', [Ref($ref)]);\n}\n// prettier-ignore\nfunction KeyOfFromType(type, options) {\n const propertyKeys = KeyOfPropertyKeys(type);\n const propertyKeyTypes = KeyOfPropertyKeysToRest(propertyKeys);\n const result = UnionEvaluated(propertyKeyTypes);\n return CreateType(result, options);\n}\n// prettier-ignore\nexport function KeyOfPropertyKeysToRest(propertyKeys) {\n return propertyKeys.map(L => L === '[number]' ? Number() : Literal(L));\n}\n/** `[Json]` Creates a KeyOf type */\nexport function KeyOf(type, options) {\n return (IsComputed(type) ? FromComputed(type.target, type.parameters) : IsRef(type) ? FromRef(type.$ref) : IsMappedResult(type) ? KeyOfFromMappedResult(type, options) : KeyOfFromType(type, options));\n}\n","import { MappedResult } from '../mapped/index.mjs';\nimport { KeyOf } from './keyof.mjs';\nimport { Clone } from '../clone/value.mjs';\n// prettier-ignore\nfunction FromProperties(properties, options) {\n const result = {};\n for (const K2 of globalThis.Object.getOwnPropertyNames(properties))\n result[K2] = KeyOf(properties[K2], Clone(options));\n return result;\n}\n// prettier-ignore\nfunction FromMappedResult(mappedResult, options) {\n return FromProperties(mappedResult.properties, options);\n}\n// prettier-ignore\nexport function KeyOfFromMappedResult(mappedResult, options) {\n const properties = FromMappedResult(mappedResult, options);\n return MappedResult(properties);\n}\n","import { IndexFromPropertyKeys } from '../indexed/indexed.mjs';\nimport { KeyOfPropertyKeys } from './keyof-property-keys.mjs';\n/**\n * `[Utility]` Resolves an array of keys and schemas from the given schema. This method is faster\n * than obtaining the keys and resolving each individually via indexing. This method was written\n * accellerate Intersect and Union encoding.\n */\nexport function KeyOfPropertyEntries(schema) {\n const keys = KeyOfPropertyKeys(schema);\n const schemas = IndexFromPropertyKeys(schema, keys);\n return keys.map((_, index) => [keys[index], schemas[index]]);\n}\n","import { Kind } from '../symbols/index.mjs';\n/** Fast undefined check used for properties of type undefined */\nfunction Intersect(schema) {\n return schema.allOf.every((schema) => ExtendsUndefinedCheck(schema));\n}\nfunction Union(schema) {\n return schema.anyOf.some((schema) => ExtendsUndefinedCheck(schema));\n}\nfunction Not(schema) {\n return !ExtendsUndefinedCheck(schema.not);\n}\n/** Fast undefined check used for properties of type undefined */\n// prettier-ignore\nexport function ExtendsUndefinedCheck(schema) {\n return (schema[Kind] === 'Intersect' ? Intersect(schema) :\n schema[Kind] === 'Union' ? Union(schema) :\n schema[Kind] === 'Not' ? Not(schema) :\n schema[Kind] === 'Undefined' ? true :\n false);\n}\n","import { Kind } from '../type/symbols/index.mjs';\nimport { ValueErrorType } from './errors.mjs';\n/** Creates an error message using en-US as the default locale */\nexport function DefaultErrorFunction(error) {\n switch (error.errorType) {\n case ValueErrorType.ArrayContains:\n return 'Expected array to contain at least one matching value';\n case ValueErrorType.ArrayMaxContains:\n return `Expected array to contain no more than ${error.schema.maxContains} matching values`;\n case ValueErrorType.ArrayMinContains:\n return `Expected array to contain at least ${error.schema.minContains} matching values`;\n case ValueErrorType.ArrayMaxItems:\n return `Expected array length to be less or equal to ${error.schema.maxItems}`;\n case ValueErrorType.ArrayMinItems:\n return `Expected array length to be greater or equal to ${error.schema.minItems}`;\n case ValueErrorType.ArrayUniqueItems:\n return 'Expected array elements to be unique';\n case ValueErrorType.Array:\n return 'Expected array';\n case ValueErrorType.AsyncIterator:\n return 'Expected AsyncIterator';\n case ValueErrorType.BigIntExclusiveMaximum:\n return `Expected bigint to be less than ${error.schema.exclusiveMaximum}`;\n case ValueErrorType.BigIntExclusiveMinimum:\n return `Expected bigint to be greater than ${error.schema.exclusiveMinimum}`;\n case ValueErrorType.BigIntMaximum:\n return `Expected bigint to be less or equal to ${error.schema.maximum}`;\n case ValueErrorType.BigIntMinimum:\n return `Expected bigint to be greater or equal to ${error.schema.minimum}`;\n case ValueErrorType.BigIntMultipleOf:\n return `Expected bigint to be a multiple of ${error.schema.multipleOf}`;\n case ValueErrorType.BigInt:\n return 'Expected bigint';\n case ValueErrorType.Boolean:\n return 'Expected boolean';\n case ValueErrorType.DateExclusiveMinimumTimestamp:\n return `Expected Date timestamp to be greater than ${error.schema.exclusiveMinimumTimestamp}`;\n case ValueErrorType.DateExclusiveMaximumTimestamp:\n return `Expected Date timestamp to be less than ${error.schema.exclusiveMaximumTimestamp}`;\n case ValueErrorType.DateMinimumTimestamp:\n return `Expected Date timestamp to be greater or equal to ${error.schema.minimumTimestamp}`;\n case ValueErrorType.DateMaximumTimestamp:\n return `Expected Date timestamp to be less or equal to ${error.schema.maximumTimestamp}`;\n case ValueErrorType.DateMultipleOfTimestamp:\n return `Expected Date timestamp to be a multiple of ${error.schema.multipleOfTimestamp}`;\n case ValueErrorType.Date:\n return 'Expected Date';\n case ValueErrorType.Function:\n return 'Expected function';\n case ValueErrorType.IntegerExclusiveMaximum:\n return `Expected integer to be less than ${error.schema.exclusiveMaximum}`;\n case ValueErrorType.IntegerExclusiveMinimum:\n return `Expected integer to be greater than ${error.schema.exclusiveMinimum}`;\n case ValueErrorType.IntegerMaximum:\n return `Expected integer to be less or equal to ${error.schema.maximum}`;\n case ValueErrorType.IntegerMinimum:\n return `Expected integer to be greater or equal to ${error.schema.minimum}`;\n case ValueErrorType.IntegerMultipleOf:\n return `Expected integer to be a multiple of ${error.schema.multipleOf}`;\n case ValueErrorType.Integer:\n return 'Expected integer';\n case ValueErrorType.IntersectUnevaluatedProperties:\n return 'Unexpected property';\n case ValueErrorType.Intersect:\n return 'Expected all values to match';\n case ValueErrorType.Iterator:\n return 'Expected Iterator';\n case ValueErrorType.Literal:\n return `Expected ${typeof error.schema.const === 'string' ? `'${error.schema.const}'` : error.schema.const}`;\n case ValueErrorType.Never:\n return 'Never';\n case ValueErrorType.Not:\n return 'Value should not match';\n case ValueErrorType.Null:\n return 'Expected null';\n case ValueErrorType.NumberExclusiveMaximum:\n return `Expected number to be less than ${error.schema.exclusiveMaximum}`;\n case ValueErrorType.NumberExclusiveMinimum:\n return `Expected number to be greater than ${error.schema.exclusiveMinimum}`;\n case ValueErrorType.NumberMaximum:\n return `Expected number to be less or equal to ${error.schema.maximum}`;\n case ValueErrorType.NumberMinimum:\n return `Expected number to be greater or equal to ${error.schema.minimum}`;\n case ValueErrorType.NumberMultipleOf:\n return `Expected number to be a multiple of ${error.schema.multipleOf}`;\n case ValueErrorType.Number:\n return 'Expected number';\n case ValueErrorType.Object:\n return 'Expected object';\n case ValueErrorType.ObjectAdditionalProperties:\n return 'Unexpected property';\n case ValueErrorType.ObjectMaxProperties:\n return `Expected object to have no more than ${error.schema.maxProperties} properties`;\n case ValueErrorType.ObjectMinProperties:\n return `Expected object to have at least ${error.schema.minProperties} properties`;\n case ValueErrorType.ObjectRequiredProperty:\n return 'Expected required property';\n case ValueErrorType.Promise:\n return 'Expected Promise';\n case ValueErrorType.RegExp:\n return 'Expected string to match regular expression';\n case ValueErrorType.StringFormatUnknown:\n return `Unknown format '${error.schema.format}'`;\n case ValueErrorType.StringFormat:\n return `Expected string to match '${error.schema.format}' format`;\n case ValueErrorType.StringMaxLength:\n return `Expected string length less or equal to ${error.schema.maxLength}`;\n case ValueErrorType.StringMinLength:\n return `Expected string length greater or equal to ${error.schema.minLength}`;\n case ValueErrorType.StringPattern:\n return `Expected string to match '${error.schema.pattern}'`;\n case ValueErrorType.String:\n return 'Expected string';\n case ValueErrorType.Symbol:\n return 'Expected symbol';\n case ValueErrorType.TupleLength:\n return `Expected tuple to have ${error.schema.maxItems || 0} elements`;\n case ValueErrorType.Tuple:\n return 'Expected tuple';\n case ValueErrorType.Uint8ArrayMaxByteLength:\n return `Expected byte length less or equal to ${error.schema.maxByteLength}`;\n case ValueErrorType.Uint8ArrayMinByteLength:\n return `Expected byte length greater or equal to ${error.schema.minByteLength}`;\n case ValueErrorType.Uint8Array:\n return 'Expected Uint8Array';\n case ValueErrorType.Undefined:\n return 'Expected undefined';\n case ValueErrorType.Union:\n return 'Expected union value';\n case ValueErrorType.Void:\n return 'Expected void';\n case ValueErrorType.Kind:\n return `Expected kind '${error.schema[Kind]}'`;\n default:\n return 'Unknown error type';\n }\n}\n/** Manages error message providers */\nlet errorFunction = DefaultErrorFunction;\n/** Sets the error function used to generate error messages. */\nexport function SetErrorFunction(callback) {\n errorFunction = callback;\n}\n/** Gets the error function used to generate error messages */\nexport function GetErrorFunction() {\n return errorFunction;\n}\n","import { TypeBoxError } from '../../type/error/index.mjs';\nimport { Kind } from '../../type/symbols/index.mjs';\nimport { IsString } from '../guard/guard.mjs';\nexport class TypeDereferenceError extends TypeBoxError {\n constructor(schema) {\n super(`Unable to dereference schema with $id '${schema.$ref}'`);\n this.schema = schema;\n }\n}\nfunction Resolve(schema, references) {\n const target = references.find((target) => target.$id === schema.$ref);\n if (target === undefined)\n throw new TypeDereferenceError(schema);\n return Deref(target, references);\n}\n/** `[Internal]` Pushes a schema onto references if the schema has an $id and does not exist on references */\nexport function Pushref(schema, references) {\n if (!IsString(schema.$id) || references.some((target) => target.$id === schema.$id))\n return references;\n references.push(schema);\n return references;\n}\n/** `[Internal]` Dereferences a schema from the references array or throws if not found */\nexport function Deref(schema, references) {\n // prettier-ignore\n return (schema[Kind] === 'This' || schema[Kind] === 'Ref')\n ? Resolve(schema, references)\n : schema;\n}\n","import { IsArray, IsBoolean, IsBigInt, IsDate, IsNull, IsNumber, IsObject, IsString, IsSymbol, IsUint8Array, IsUndefined } from '../guard/index.mjs';\nimport { TypeBoxError } from '../../type/error/index.mjs';\n// ------------------------------------------------------------------\n// Errors\n// ------------------------------------------------------------------\nexport class ValueHashError extends TypeBoxError {\n constructor(value) {\n super(`Unable to hash value`);\n this.value = value;\n }\n}\n// ------------------------------------------------------------------\n// ByteMarker\n// ------------------------------------------------------------------\nvar ByteMarker;\n(function (ByteMarker) {\n ByteMarker[ByteMarker[\"Undefined\"] = 0] = \"Undefined\";\n ByteMarker[ByteMarker[\"Null\"] = 1] = \"Null\";\n ByteMarker[ByteMarker[\"Boolean\"] = 2] = \"Boolean\";\n ByteMarker[ByteMarker[\"Number\"] = 3] = \"Number\";\n ByteMarker[ByteMarker[\"String\"] = 4] = \"String\";\n ByteMarker[ByteMarker[\"Object\"] = 5] = \"Object\";\n ByteMarker[ByteMarker[\"Array\"] = 6] = \"Array\";\n ByteMarker[ByteMarker[\"Date\"] = 7] = \"Date\";\n ByteMarker[ByteMarker[\"Uint8Array\"] = 8] = \"Uint8Array\";\n ByteMarker[ByteMarker[\"Symbol\"] = 9] = \"Symbol\";\n ByteMarker[ByteMarker[\"BigInt\"] = 10] = \"BigInt\";\n})(ByteMarker || (ByteMarker = {}));\n// ------------------------------------------------------------------\n// State\n// ------------------------------------------------------------------\nlet Accumulator = BigInt('14695981039346656037');\nconst [Prime, Size] = [BigInt('1099511628211'), BigInt('18446744073709551616' /* 2 ^ 64 */)];\nconst Bytes = Array.from({ length: 256 }).map((_, i) => BigInt(i));\nconst F64 = new Float64Array(1);\nconst F64In = new DataView(F64.buffer);\nconst F64Out = new Uint8Array(F64.buffer);\n// ------------------------------------------------------------------\n// NumberToBytes\n// ------------------------------------------------------------------\nfunction* NumberToBytes(value) {\n const byteCount = value === 0 ? 1 : Math.ceil(Math.floor(Math.log2(value) + 1) / 8);\n for (let i = 0; i < byteCount; i++) {\n yield (value >> (8 * (byteCount - 1 - i))) & 0xff;\n }\n}\n// ------------------------------------------------------------------\n// Hashing Functions\n// ------------------------------------------------------------------\nfunction ArrayType(value) {\n FNV1A64(ByteMarker.Array);\n for (const item of value) {\n Visit(item);\n }\n}\nfunction BooleanType(value) {\n FNV1A64(ByteMarker.Boolean);\n FNV1A64(value ? 1 : 0);\n}\nfunction BigIntType(value) {\n FNV1A64(ByteMarker.BigInt);\n F64In.setBigInt64(0, value);\n for (const byte of F64Out) {\n FNV1A64(byte);\n }\n}\nfunction DateType(value) {\n FNV1A64(ByteMarker.Date);\n Visit(value.getTime());\n}\nfunction NullType(value) {\n FNV1A64(ByteMarker.Null);\n}\nfunction NumberType(value) {\n FNV1A64(ByteMarker.Number);\n F64In.setFloat64(0, value);\n for (const byte of F64Out) {\n FNV1A64(byte);\n }\n}\nfunction ObjectType(value) {\n FNV1A64(ByteMarker.Object);\n for (const key of globalThis.Object.getOwnPropertyNames(value).sort()) {\n Visit(key);\n Visit(value[key]);\n }\n}\nfunction StringType(value) {\n FNV1A64(ByteMarker.String);\n for (let i = 0; i < value.length; i++) {\n for (const byte of NumberToBytes(value.charCodeAt(i))) {\n FNV1A64(byte);\n }\n }\n}\nfunction SymbolType(value) {\n FNV1A64(ByteMarker.Symbol);\n Visit(value.description);\n}\nfunction Uint8ArrayType(value) {\n FNV1A64(ByteMarker.Uint8Array);\n for (let i = 0; i < value.length; i++) {\n FNV1A64(value[i]);\n }\n}\nfunction UndefinedType(value) {\n return FNV1A64(ByteMarker.Undefined);\n}\nfunction Visit(value) {\n if (IsArray(value))\n return ArrayType(value);\n if (IsBoolean(value))\n return BooleanType(value);\n if (IsBigInt(value))\n return BigIntType(value);\n if (IsDate(value))\n return DateType(value);\n if (IsNull(value))\n return NullType(value);\n if (IsNumber(value))\n return NumberType(value);\n if (IsObject(value))\n return ObjectType(value);\n if (IsString(value))\n return StringType(value);\n if (IsSymbol(value))\n return SymbolType(value);\n if (IsUint8Array(value))\n return Uint8ArrayType(value);\n if (IsUndefined(value))\n return UndefinedType(value);\n throw new ValueHashError(value);\n}\nfunction FNV1A64(byte) {\n Accumulator = Accumulator ^ Bytes[byte];\n Accumulator = (Accumulator * Prime) % Size;\n}\n// ------------------------------------------------------------------\n// Hash\n// ------------------------------------------------------------------\n/** Creates a FNV1A-64 non cryptographic hash of the given value */\nexport function Hash(value) {\n Accumulator = BigInt('14695981039346656037');\n Visit(value);\n return Accumulator;\n}\n","import { CreateType } from '../create/index.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates an Any type */\nexport function Any(options) {\n return CreateType({ [Kind]: 'Any' }, options);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates an Unknown type */\nexport function Unknown(options) {\n return CreateType({ [Kind]: 'Unknown' }, options);\n}\n","import * as ValueGuard from './value.mjs';\nimport { Kind, Hint, TransformKind, ReadonlyKind, OptionalKind } from '../symbols/index.mjs';\nimport { TypeBoxError } from '../error/index.mjs';\nexport class TypeGuardUnknownTypeError extends TypeBoxError {\n}\nconst KnownTypes = [\n 'Any',\n 'Array',\n 'AsyncIterator',\n 'BigInt',\n 'Boolean',\n 'Computed',\n 'Constructor',\n 'Date',\n 'Enum',\n 'Function',\n 'Integer',\n 'Intersect',\n 'Iterator',\n 'Literal',\n 'MappedKey',\n 'MappedResult',\n 'Not',\n 'Null',\n 'Number',\n 'Object',\n 'Promise',\n 'Record',\n 'Ref',\n 'RegExp',\n 'String',\n 'Symbol',\n 'TemplateLiteral',\n 'This',\n 'Tuple',\n 'Undefined',\n 'Union',\n 'Uint8Array',\n 'Unknown',\n 'Void',\n];\nfunction IsPattern(value) {\n try {\n new RegExp(value);\n return true;\n }\n catch {\n return false;\n }\n}\nfunction IsControlCharacterFree(value) {\n if (!ValueGuard.IsString(value))\n return false;\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if ((code >= 7 && code <= 13) || code === 27 || code === 127) {\n return false;\n }\n }\n return true;\n}\nfunction IsAdditionalProperties(value) {\n return IsOptionalBoolean(value) || IsSchema(value);\n}\nfunction IsOptionalBigInt(value) {\n return ValueGuard.IsUndefined(value) || ValueGuard.IsBigInt(value);\n}\nfunction IsOptionalNumber(value) {\n return ValueGuard.IsUndefined(value) || ValueGuard.IsNumber(value);\n}\nfunction IsOptionalBoolean(value) {\n return ValueGuard.IsUndefined(value) || ValueGuard.IsBoolean(value);\n}\nfunction IsOptionalString(value) {\n return ValueGuard.IsUndefined(value) || ValueGuard.IsString(value);\n}\nfunction IsOptionalPattern(value) {\n return ValueGuard.IsUndefined(value) || (ValueGuard.IsString(value) && IsControlCharacterFree(value) && IsPattern(value));\n}\nfunction IsOptionalFormat(value) {\n return ValueGuard.IsUndefined(value) || (ValueGuard.IsString(value) && IsControlCharacterFree(value));\n}\nfunction IsOptionalSchema(value) {\n return ValueGuard.IsUndefined(value) || IsSchema(value);\n}\n// ------------------------------------------------------------------\n// Modifiers\n// ------------------------------------------------------------------\n/** Returns true if this value has a Readonly symbol */\nexport function IsReadonly(value) {\n return ValueGuard.IsObject(value) && value[ReadonlyKind] === 'Readonly';\n}\n/** Returns true if this value has a Optional symbol */\nexport function IsOptional(value) {\n return ValueGuard.IsObject(value) && value[OptionalKind] === 'Optional';\n}\n// ------------------------------------------------------------------\n// Types\n// ------------------------------------------------------------------\n/** Returns true if the given value is TAny */\nexport function IsAny(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Any') &&\n IsOptionalString(value.$id));\n}\n/** Returns true if the given value is TArray */\nexport function IsArray(value) {\n return (IsKindOf(value, 'Array') &&\n value.type === 'array' &&\n IsOptionalString(value.$id) &&\n IsSchema(value.items) &&\n IsOptionalNumber(value.minItems) &&\n IsOptionalNumber(value.maxItems) &&\n IsOptionalBoolean(value.uniqueItems) &&\n IsOptionalSchema(value.contains) &&\n IsOptionalNumber(value.minContains) &&\n IsOptionalNumber(value.maxContains));\n}\n/** Returns true if the given value is TAsyncIterator */\nexport function IsAsyncIterator(value) {\n // prettier-ignore\n return (IsKindOf(value, 'AsyncIterator') &&\n value.type === 'AsyncIterator' &&\n IsOptionalString(value.$id) &&\n IsSchema(value.items));\n}\n/** Returns true if the given value is TBigInt */\nexport function IsBigInt(value) {\n // prettier-ignore\n return (IsKindOf(value, 'BigInt') &&\n value.type === 'bigint' &&\n IsOptionalString(value.$id) &&\n IsOptionalBigInt(value.exclusiveMaximum) &&\n IsOptionalBigInt(value.exclusiveMinimum) &&\n IsOptionalBigInt(value.maximum) &&\n IsOptionalBigInt(value.minimum) &&\n IsOptionalBigInt(value.multipleOf));\n}\n/** Returns true if the given value is TBoolean */\nexport function IsBoolean(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Boolean') &&\n value.type === 'boolean' &&\n IsOptionalString(value.$id));\n}\n/** Returns true if the given value is TComputed */\nexport function IsComputed(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Computed') &&\n ValueGuard.IsString(value.target) &&\n ValueGuard.IsArray(value.parameters) &&\n value.parameters.every((schema) => IsSchema(schema)));\n}\n/** Returns true if the given value is TConstructor */\nexport function IsConstructor(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Constructor') &&\n value.type === 'Constructor' &&\n IsOptionalString(value.$id) &&\n ValueGuard.IsArray(value.parameters) &&\n value.parameters.every(schema => IsSchema(schema)) &&\n IsSchema(value.returns));\n}\n/** Returns true if the given value is TDate */\nexport function IsDate(value) {\n return (IsKindOf(value, 'Date') &&\n value.type === 'Date' &&\n IsOptionalString(value.$id) &&\n IsOptionalNumber(value.exclusiveMaximumTimestamp) &&\n IsOptionalNumber(value.exclusiveMinimumTimestamp) &&\n IsOptionalNumber(value.maximumTimestamp) &&\n IsOptionalNumber(value.minimumTimestamp) &&\n IsOptionalNumber(value.multipleOfTimestamp));\n}\n/** Returns true if the given value is TFunction */\nexport function IsFunction(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Function') &&\n value.type === 'Function' &&\n IsOptionalString(value.$id) &&\n ValueGuard.IsArray(value.parameters) &&\n value.parameters.every(schema => IsSchema(schema)) &&\n IsSchema(value.returns));\n}\n/** Returns true if the given value is TImport */\nexport function IsImport(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Import') &&\n ValueGuard.HasPropertyKey(value, '$defs') &&\n ValueGuard.IsObject(value.$defs) &&\n IsProperties(value.$defs) &&\n ValueGuard.HasPropertyKey(value, '$ref') &&\n ValueGuard.IsString(value.$ref) &&\n value.$ref in value.$defs // required\n );\n}\n/** Returns true if the given value is TInteger */\nexport function IsInteger(value) {\n return (IsKindOf(value, 'Integer') &&\n value.type === 'integer' &&\n IsOptionalString(value.$id) &&\n IsOptionalNumber(value.exclusiveMaximum) &&\n IsOptionalNumber(value.exclusiveMinimum) &&\n IsOptionalNumber(value.maximum) &&\n IsOptionalNumber(value.minimum) &&\n IsOptionalNumber(value.multipleOf));\n}\n/** Returns true if the given schema is TProperties */\nexport function IsProperties(value) {\n // prettier-ignore\n return (ValueGuard.IsObject(value) &&\n Object.entries(value).every(([key, schema]) => IsControlCharacterFree(key) && IsSchema(schema)));\n}\n/** Returns true if the given value is TIntersect */\nexport function IsIntersect(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Intersect') &&\n (ValueGuard.IsString(value.type) && value.type !== 'object' ? false : true) &&\n ValueGuard.IsArray(value.allOf) &&\n value.allOf.every(schema => IsSchema(schema) && !IsTransform(schema)) &&\n IsOptionalString(value.type) &&\n (IsOptionalBoolean(value.unevaluatedProperties) || IsOptionalSchema(value.unevaluatedProperties)) &&\n IsOptionalString(value.$id));\n}\n/** Returns true if the given value is TIterator */\nexport function IsIterator(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Iterator') &&\n value.type === 'Iterator' &&\n IsOptionalString(value.$id) &&\n IsSchema(value.items));\n}\n/** Returns true if the given value is a TKind with the given name. */\nexport function IsKindOf(value, kind) {\n return ValueGuard.IsObject(value) && Kind in value && value[Kind] === kind;\n}\n/** Returns true if the given value is TLiteral */\nexport function IsLiteralString(value) {\n return IsLiteral(value) && ValueGuard.IsString(value.const);\n}\n/** Returns true if the given value is TLiteral */\nexport function IsLiteralNumber(value) {\n return IsLiteral(value) && ValueGuard.IsNumber(value.const);\n}\n/** Returns true if the given value is TLiteral */\nexport function IsLiteralBoolean(value) {\n return IsLiteral(value) && ValueGuard.IsBoolean(value.const);\n}\n/** Returns true if the given value is TLiteral */\nexport function IsLiteral(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Literal') &&\n IsOptionalString(value.$id) && IsLiteralValue(value.const));\n}\n/** Returns true if the given value is a TLiteralValue */\nexport function IsLiteralValue(value) {\n return ValueGuard.IsBoolean(value) || ValueGuard.IsNumber(value) || ValueGuard.IsString(value);\n}\n/** Returns true if the given value is a TMappedKey */\nexport function IsMappedKey(value) {\n // prettier-ignore\n return (IsKindOf(value, 'MappedKey') &&\n ValueGuard.IsArray(value.keys) &&\n value.keys.every(key => ValueGuard.IsNumber(key) || ValueGuard.IsString(key)));\n}\n/** Returns true if the given value is TMappedResult */\nexport function IsMappedResult(value) {\n // prettier-ignore\n return (IsKindOf(value, 'MappedResult') &&\n IsProperties(value.properties));\n}\n/** Returns true if the given value is TNever */\nexport function IsNever(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Never') &&\n ValueGuard.IsObject(value.not) &&\n Object.getOwnPropertyNames(value.not).length === 0);\n}\n/** Returns true if the given value is TNot */\nexport function IsNot(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Not') &&\n IsSchema(value.not));\n}\n/** Returns true if the given value is TNull */\nexport function IsNull(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Null') &&\n value.type === 'null' &&\n IsOptionalString(value.$id));\n}\n/** Returns true if the given value is TNumber */\nexport function IsNumber(value) {\n return (IsKindOf(value, 'Number') &&\n value.type === 'number' &&\n IsOptionalString(value.$id) &&\n IsOptionalNumber(value.exclusiveMaximum) &&\n IsOptionalNumber(value.exclusiveMinimum) &&\n IsOptionalNumber(value.maximum) &&\n IsOptionalNumber(value.minimum) &&\n IsOptionalNumber(value.multipleOf));\n}\n/** Returns true if the given value is TObject */\nexport function IsObject(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Object') &&\n value.type === 'object' &&\n IsOptionalString(value.$id) &&\n IsProperties(value.properties) &&\n IsAdditionalProperties(value.additionalProperties) &&\n IsOptionalNumber(value.minProperties) &&\n IsOptionalNumber(value.maxProperties));\n}\n/** Returns true if the given value is TPromise */\nexport function IsPromise(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Promise') &&\n value.type === 'Promise' &&\n IsOptionalString(value.$id) &&\n IsSchema(value.item));\n}\n/** Returns true if the given value is TRecord */\nexport function IsRecord(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Record') &&\n value.type === 'object' &&\n IsOptionalString(value.$id) &&\n IsAdditionalProperties(value.additionalProperties) &&\n ValueGuard.IsObject(value.patternProperties) &&\n ((schema) => {\n const keys = Object.getOwnPropertyNames(schema.patternProperties);\n return (keys.length === 1 &&\n IsPattern(keys[0]) &&\n ValueGuard.IsObject(schema.patternProperties) &&\n IsSchema(schema.patternProperties[keys[0]]));\n })(value));\n}\n/** Returns true if this value is TRecursive */\nexport function IsRecursive(value) {\n return ValueGuard.IsObject(value) && Hint in value && value[Hint] === 'Recursive';\n}\n/** Returns true if the given value is TRef */\nexport function IsRef(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Ref') &&\n IsOptionalString(value.$id) &&\n ValueGuard.IsString(value.$ref));\n}\n/** Returns true if the given value is TRegExp */\nexport function IsRegExp(value) {\n // prettier-ignore\n return (IsKindOf(value, 'RegExp') &&\n IsOptionalString(value.$id) &&\n ValueGuard.IsString(value.source) &&\n ValueGuard.IsString(value.flags) &&\n IsOptionalNumber(value.maxLength) &&\n IsOptionalNumber(value.minLength));\n}\n/** Returns true if the given value is TString */\nexport function IsString(value) {\n // prettier-ignore\n return (IsKindOf(value, 'String') &&\n value.type === 'string' &&\n IsOptionalString(value.$id) &&\n IsOptionalNumber(value.minLength) &&\n IsOptionalNumber(value.maxLength) &&\n IsOptionalPattern(value.pattern) &&\n IsOptionalFormat(value.format));\n}\n/** Returns true if the given value is TSymbol */\nexport function IsSymbol(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Symbol') &&\n value.type === 'symbol' &&\n IsOptionalString(value.$id));\n}\n/** Returns true if the given value is TTemplateLiteral */\nexport function IsTemplateLiteral(value) {\n // prettier-ignore\n return (IsKindOf(value, 'TemplateLiteral') &&\n value.type === 'string' &&\n ValueGuard.IsString(value.pattern) &&\n value.pattern[0] === '^' &&\n value.pattern[value.pattern.length - 1] === '$');\n}\n/** Returns true if the given value is TThis */\nexport function IsThis(value) {\n // prettier-ignore\n return (IsKindOf(value, 'This') &&\n IsOptionalString(value.$id) &&\n ValueGuard.IsString(value.$ref));\n}\n/** Returns true of this value is TTransform */\nexport function IsTransform(value) {\n return ValueGuard.IsObject(value) && TransformKind in value;\n}\n/** Returns true if the given value is TTuple */\nexport function IsTuple(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Tuple') &&\n value.type === 'array' &&\n IsOptionalString(value.$id) &&\n ValueGuard.IsNumber(value.minItems) &&\n ValueGuard.IsNumber(value.maxItems) &&\n value.minItems === value.maxItems &&\n (( // empty\n ValueGuard.IsUndefined(value.items) &&\n ValueGuard.IsUndefined(value.additionalItems) &&\n value.minItems === 0) || (ValueGuard.IsArray(value.items) &&\n value.items.every(schema => IsSchema(schema)))));\n}\n/** Returns true if the given value is TUndefined */\nexport function IsUndefined(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Undefined') &&\n value.type === 'undefined' &&\n IsOptionalString(value.$id));\n}\n/** Returns true if the given value is TUnion[]> */\nexport function IsUnionLiteral(value) {\n return IsUnion(value) && value.anyOf.every((schema) => IsLiteralString(schema) || IsLiteralNumber(schema));\n}\n/** Returns true if the given value is TUnion */\nexport function IsUnion(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Union') &&\n IsOptionalString(value.$id) &&\n ValueGuard.IsObject(value) &&\n ValueGuard.IsArray(value.anyOf) &&\n value.anyOf.every(schema => IsSchema(schema)));\n}\n/** Returns true if the given value is TUint8Array */\nexport function IsUint8Array(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Uint8Array') &&\n value.type === 'Uint8Array' &&\n IsOptionalString(value.$id) &&\n IsOptionalNumber(value.minByteLength) &&\n IsOptionalNumber(value.maxByteLength));\n}\n/** Returns true if the given value is TUnknown */\nexport function IsUnknown(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Unknown') &&\n IsOptionalString(value.$id));\n}\n/** Returns true if the given value is a raw TUnsafe */\nexport function IsUnsafe(value) {\n return IsKindOf(value, 'Unsafe');\n}\n/** Returns true if the given value is TVoid */\nexport function IsVoid(value) {\n // prettier-ignore\n return (IsKindOf(value, 'Void') &&\n value.type === 'void' &&\n IsOptionalString(value.$id));\n}\n/** Returns true if the given value is TKind */\nexport function IsKind(value) {\n return ValueGuard.IsObject(value) && Kind in value && ValueGuard.IsString(value[Kind]) && !KnownTypes.includes(value[Kind]);\n}\n/** Returns true if the given value is TSchema */\nexport function IsSchema(value) {\n // prettier-ignore\n return (ValueGuard.IsObject(value)) && (IsAny(value) ||\n IsArray(value) ||\n IsBoolean(value) ||\n IsBigInt(value) ||\n IsAsyncIterator(value) ||\n IsComputed(value) ||\n IsConstructor(value) ||\n IsDate(value) ||\n IsFunction(value) ||\n IsInteger(value) ||\n IsIntersect(value) ||\n IsIterator(value) ||\n IsLiteral(value) ||\n IsMappedKey(value) ||\n IsMappedResult(value) ||\n IsNever(value) ||\n IsNot(value) ||\n IsNull(value) ||\n IsNumber(value) ||\n IsObject(value) ||\n IsPromise(value) ||\n IsRecord(value) ||\n IsRef(value) ||\n IsRegExp(value) ||\n IsString(value) ||\n IsSymbol(value) ||\n IsTemplateLiteral(value) ||\n IsThis(value) ||\n IsTuple(value) ||\n IsUndefined(value) ||\n IsUnion(value) ||\n IsUint8Array(value) ||\n IsUnknown(value) ||\n IsUnsafe(value) ||\n IsVoid(value) ||\n IsKind(value));\n}\n","import { Any } from '../any/index.mjs';\nimport { Function as FunctionType } from '../function/index.mjs';\nimport { Number } from '../number/index.mjs';\nimport { String } from '../string/index.mjs';\nimport { Unknown } from '../unknown/index.mjs';\nimport { TemplateLiteralToUnion } from '../template-literal/index.mjs';\nimport { PatternNumberExact, PatternStringExact } from '../patterns/index.mjs';\nimport { Kind, Hint } from '../symbols/index.mjs';\nimport { TypeBoxError } from '../error/index.mjs';\nimport { TypeGuard, ValueGuard } from '../guard/index.mjs';\nexport class ExtendsResolverError extends TypeBoxError {\n}\nexport var ExtendsResult;\n(function (ExtendsResult) {\n ExtendsResult[ExtendsResult[\"Union\"] = 0] = \"Union\";\n ExtendsResult[ExtendsResult[\"True\"] = 1] = \"True\";\n ExtendsResult[ExtendsResult[\"False\"] = 2] = \"False\";\n})(ExtendsResult || (ExtendsResult = {}));\n// ------------------------------------------------------------------\n// IntoBooleanResult\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction IntoBooleanResult(result) {\n return result === ExtendsResult.False ? result : ExtendsResult.True;\n}\n// ------------------------------------------------------------------\n// Throw\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction Throw(message) {\n throw new ExtendsResolverError(message);\n}\n// ------------------------------------------------------------------\n// StructuralRight\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction IsStructuralRight(right) {\n return (TypeGuard.IsNever(right) ||\n TypeGuard.IsIntersect(right) ||\n TypeGuard.IsUnion(right) ||\n TypeGuard.IsUnknown(right) ||\n TypeGuard.IsAny(right));\n}\n// prettier-ignore\nfunction StructuralRight(left, right) {\n return (TypeGuard.IsNever(right) ? FromNeverRight(left, right) :\n TypeGuard.IsIntersect(right) ? FromIntersectRight(left, right) :\n TypeGuard.IsUnion(right) ? FromUnionRight(left, right) :\n TypeGuard.IsUnknown(right) ? FromUnknownRight(left, right) :\n TypeGuard.IsAny(right) ? FromAnyRight(left, right) :\n Throw('StructuralRight'));\n}\n// ------------------------------------------------------------------\n// Any\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromAnyRight(left, right) {\n return ExtendsResult.True;\n}\n// prettier-ignore\nfunction FromAny(left, right) {\n return (TypeGuard.IsIntersect(right) ? FromIntersectRight(left, right) :\n (TypeGuard.IsUnion(right) && right.anyOf.some((schema) => TypeGuard.IsAny(schema) || TypeGuard.IsUnknown(schema))) ? ExtendsResult.True :\n TypeGuard.IsUnion(right) ? ExtendsResult.Union :\n TypeGuard.IsUnknown(right) ? ExtendsResult.True :\n TypeGuard.IsAny(right) ? ExtendsResult.True :\n ExtendsResult.Union);\n}\n// ------------------------------------------------------------------\n// Array\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromArrayRight(left, right) {\n return (TypeGuard.IsUnknown(left) ? ExtendsResult.False :\n TypeGuard.IsAny(left) ? ExtendsResult.Union :\n TypeGuard.IsNever(left) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// prettier-ignore\nfunction FromArray(left, right) {\n return (TypeGuard.IsObject(right) && IsObjectArrayLike(right) ? ExtendsResult.True :\n IsStructuralRight(right) ? StructuralRight(left, right) :\n !TypeGuard.IsArray(right) ? ExtendsResult.False :\n IntoBooleanResult(Visit(left.items, right.items)));\n}\n// ------------------------------------------------------------------\n// AsyncIterator\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromAsyncIterator(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n !TypeGuard.IsAsyncIterator(right) ? ExtendsResult.False :\n IntoBooleanResult(Visit(left.items, right.items)));\n}\n// ------------------------------------------------------------------\n// BigInt\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromBigInt(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsRecord(right) ? FromRecordRight(left, right) :\n TypeGuard.IsBigInt(right) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// Boolean\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromBooleanRight(left, right) {\n return (TypeGuard.IsLiteralBoolean(left) ? ExtendsResult.True :\n TypeGuard.IsBoolean(left) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// prettier-ignore\nfunction FromBoolean(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsRecord(right) ? FromRecordRight(left, right) :\n TypeGuard.IsBoolean(right) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// Constructor\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromConstructor(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n !TypeGuard.IsConstructor(right) ? ExtendsResult.False :\n left.parameters.length > right.parameters.length ? ExtendsResult.False :\n (!left.parameters.every((schema, index) => IntoBooleanResult(Visit(right.parameters[index], schema)) === ExtendsResult.True)) ? ExtendsResult.False :\n IntoBooleanResult(Visit(left.returns, right.returns)));\n}\n// ------------------------------------------------------------------\n// Date\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromDate(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsRecord(right) ? FromRecordRight(left, right) :\n TypeGuard.IsDate(right) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// Function\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromFunction(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n !TypeGuard.IsFunction(right) ? ExtendsResult.False :\n left.parameters.length > right.parameters.length ? ExtendsResult.False :\n (!left.parameters.every((schema, index) => IntoBooleanResult(Visit(right.parameters[index], schema)) === ExtendsResult.True)) ? ExtendsResult.False :\n IntoBooleanResult(Visit(left.returns, right.returns)));\n}\n// ------------------------------------------------------------------\n// Integer\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromIntegerRight(left, right) {\n return (TypeGuard.IsLiteral(left) && ValueGuard.IsNumber(left.const) ? ExtendsResult.True :\n TypeGuard.IsNumber(left) || TypeGuard.IsInteger(left) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// prettier-ignore\nfunction FromInteger(left, right) {\n return (TypeGuard.IsInteger(right) || TypeGuard.IsNumber(right) ? ExtendsResult.True :\n IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsRecord(right) ? FromRecordRight(left, right) :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// Intersect\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromIntersectRight(left, right) {\n return right.allOf.every((schema) => Visit(left, schema) === ExtendsResult.True)\n ? ExtendsResult.True\n : ExtendsResult.False;\n}\n// prettier-ignore\nfunction FromIntersect(left, right) {\n return left.allOf.some((schema) => Visit(schema, right) === ExtendsResult.True)\n ? ExtendsResult.True\n : ExtendsResult.False;\n}\n// ------------------------------------------------------------------\n// Iterator\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromIterator(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n !TypeGuard.IsIterator(right) ? ExtendsResult.False :\n IntoBooleanResult(Visit(left.items, right.items)));\n}\n// ------------------------------------------------------------------\n// Literal\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromLiteral(left, right) {\n return (TypeGuard.IsLiteral(right) && right.const === left.const ? ExtendsResult.True :\n IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsRecord(right) ? FromRecordRight(left, right) :\n TypeGuard.IsString(right) ? FromStringRight(left, right) :\n TypeGuard.IsNumber(right) ? FromNumberRight(left, right) :\n TypeGuard.IsInteger(right) ? FromIntegerRight(left, right) :\n TypeGuard.IsBoolean(right) ? FromBooleanRight(left, right) :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// Never\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromNeverRight(left, right) {\n return ExtendsResult.False;\n}\n// prettier-ignore\nfunction FromNever(left, right) {\n return ExtendsResult.True;\n}\n// ------------------------------------------------------------------\n// Not\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction UnwrapTNot(schema) {\n let [current, depth] = [schema, 0];\n while (true) {\n if (!TypeGuard.IsNot(current))\n break;\n current = current.not;\n depth += 1;\n }\n return depth % 2 === 0 ? current : Unknown();\n}\n// prettier-ignore\nfunction FromNot(left, right) {\n // TypeScript has no concept of negated types, and attempts to correctly check the negated\n // type at runtime would put TypeBox at odds with TypeScripts ability to statically infer\n // the type. Instead we unwrap to either unknown or T and continue evaluating.\n // prettier-ignore\n return (TypeGuard.IsNot(left) ? Visit(UnwrapTNot(left), right) :\n TypeGuard.IsNot(right) ? Visit(left, UnwrapTNot(right)) :\n Throw('Invalid fallthrough for Not'));\n}\n// ------------------------------------------------------------------\n// Null\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromNull(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsRecord(right) ? FromRecordRight(left, right) :\n TypeGuard.IsNull(right) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// Number\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromNumberRight(left, right) {\n return (TypeGuard.IsLiteralNumber(left) ? ExtendsResult.True :\n TypeGuard.IsNumber(left) || TypeGuard.IsInteger(left) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// prettier-ignore\nfunction FromNumber(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsRecord(right) ? FromRecordRight(left, right) :\n TypeGuard.IsInteger(right) || TypeGuard.IsNumber(right) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// Object\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction IsObjectPropertyCount(schema, count) {\n return Object.getOwnPropertyNames(schema.properties).length === count;\n}\n// prettier-ignore\nfunction IsObjectStringLike(schema) {\n return IsObjectArrayLike(schema);\n}\n// prettier-ignore\nfunction IsObjectSymbolLike(schema) {\n return IsObjectPropertyCount(schema, 0) || (IsObjectPropertyCount(schema, 1) && 'description' in schema.properties && TypeGuard.IsUnion(schema.properties.description) && schema.properties.description.anyOf.length === 2 && ((TypeGuard.IsString(schema.properties.description.anyOf[0]) &&\n TypeGuard.IsUndefined(schema.properties.description.anyOf[1])) || (TypeGuard.IsString(schema.properties.description.anyOf[1]) &&\n TypeGuard.IsUndefined(schema.properties.description.anyOf[0]))));\n}\n// prettier-ignore\nfunction IsObjectNumberLike(schema) {\n return IsObjectPropertyCount(schema, 0);\n}\n// prettier-ignore\nfunction IsObjectBooleanLike(schema) {\n return IsObjectPropertyCount(schema, 0);\n}\n// prettier-ignore\nfunction IsObjectBigIntLike(schema) {\n return IsObjectPropertyCount(schema, 0);\n}\n// prettier-ignore\nfunction IsObjectDateLike(schema) {\n return IsObjectPropertyCount(schema, 0);\n}\n// prettier-ignore\nfunction IsObjectUint8ArrayLike(schema) {\n return IsObjectArrayLike(schema);\n}\n// prettier-ignore\nfunction IsObjectFunctionLike(schema) {\n const length = Number();\n return IsObjectPropertyCount(schema, 0) || (IsObjectPropertyCount(schema, 1) && 'length' in schema.properties && IntoBooleanResult(Visit(schema.properties['length'], length)) === ExtendsResult.True);\n}\n// prettier-ignore\nfunction IsObjectConstructorLike(schema) {\n return IsObjectPropertyCount(schema, 0);\n}\n// prettier-ignore\nfunction IsObjectArrayLike(schema) {\n const length = Number();\n return IsObjectPropertyCount(schema, 0) || (IsObjectPropertyCount(schema, 1) && 'length' in schema.properties && IntoBooleanResult(Visit(schema.properties['length'], length)) === ExtendsResult.True);\n}\n// prettier-ignore\nfunction IsObjectPromiseLike(schema) {\n const then = FunctionType([Any()], Any());\n return IsObjectPropertyCount(schema, 0) || (IsObjectPropertyCount(schema, 1) && 'then' in schema.properties && IntoBooleanResult(Visit(schema.properties['then'], then)) === ExtendsResult.True);\n}\n// ------------------------------------------------------------------\n// Property\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction Property(left, right) {\n return (Visit(left, right) === ExtendsResult.False ? ExtendsResult.False :\n TypeGuard.IsOptional(left) && !TypeGuard.IsOptional(right) ? ExtendsResult.False :\n ExtendsResult.True);\n}\n// prettier-ignore\nfunction FromObjectRight(left, right) {\n return (TypeGuard.IsUnknown(left) ? ExtendsResult.False :\n TypeGuard.IsAny(left) ? ExtendsResult.Union : (TypeGuard.IsNever(left) ||\n (TypeGuard.IsLiteralString(left) && IsObjectStringLike(right)) ||\n (TypeGuard.IsLiteralNumber(left) && IsObjectNumberLike(right)) ||\n (TypeGuard.IsLiteralBoolean(left) && IsObjectBooleanLike(right)) ||\n (TypeGuard.IsSymbol(left) && IsObjectSymbolLike(right)) ||\n (TypeGuard.IsBigInt(left) && IsObjectBigIntLike(right)) ||\n (TypeGuard.IsString(left) && IsObjectStringLike(right)) ||\n (TypeGuard.IsSymbol(left) && IsObjectSymbolLike(right)) ||\n (TypeGuard.IsNumber(left) && IsObjectNumberLike(right)) ||\n (TypeGuard.IsInteger(left) && IsObjectNumberLike(right)) ||\n (TypeGuard.IsBoolean(left) && IsObjectBooleanLike(right)) ||\n (TypeGuard.IsUint8Array(left) && IsObjectUint8ArrayLike(right)) ||\n (TypeGuard.IsDate(left) && IsObjectDateLike(right)) ||\n (TypeGuard.IsConstructor(left) && IsObjectConstructorLike(right)) ||\n (TypeGuard.IsFunction(left) && IsObjectFunctionLike(right))) ? ExtendsResult.True :\n (TypeGuard.IsRecord(left) && TypeGuard.IsString(RecordKey(left))) ? (() => {\n // When expressing a Record with literal key values, the Record is converted into a Object with\n // the Hint assigned as `Record`. This is used to invert the extends logic.\n return right[Hint] === 'Record' ? ExtendsResult.True : ExtendsResult.False;\n })() :\n (TypeGuard.IsRecord(left) && TypeGuard.IsNumber(RecordKey(left))) ? (() => {\n return IsObjectPropertyCount(right, 0) ? ExtendsResult.True : ExtendsResult.False;\n })() :\n ExtendsResult.False);\n}\n// prettier-ignore\nfunction FromObject(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsRecord(right) ? FromRecordRight(left, right) :\n !TypeGuard.IsObject(right) ? ExtendsResult.False :\n (() => {\n for (const key of Object.getOwnPropertyNames(right.properties)) {\n if (!(key in left.properties) && !TypeGuard.IsOptional(right.properties[key])) {\n return ExtendsResult.False;\n }\n if (TypeGuard.IsOptional(right.properties[key])) {\n return ExtendsResult.True;\n }\n if (Property(left.properties[key], right.properties[key]) === ExtendsResult.False) {\n return ExtendsResult.False;\n }\n }\n return ExtendsResult.True;\n })());\n}\n// ------------------------------------------------------------------\n// Promise\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromPromise(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) && IsObjectPromiseLike(right) ? ExtendsResult.True :\n !TypeGuard.IsPromise(right) ? ExtendsResult.False :\n IntoBooleanResult(Visit(left.item, right.item)));\n}\n// ------------------------------------------------------------------\n// Record\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction RecordKey(schema) {\n return (PatternNumberExact in schema.patternProperties ? Number() :\n PatternStringExact in schema.patternProperties ? String() :\n Throw('Unknown record key pattern'));\n}\n// prettier-ignore\nfunction RecordValue(schema) {\n return (PatternNumberExact in schema.patternProperties ? schema.patternProperties[PatternNumberExact] :\n PatternStringExact in schema.patternProperties ? schema.patternProperties[PatternStringExact] :\n Throw('Unable to get record value schema'));\n}\n// prettier-ignore\nfunction FromRecordRight(left, right) {\n const [Key, Value] = [RecordKey(right), RecordValue(right)];\n return ((TypeGuard.IsLiteralString(left) && TypeGuard.IsNumber(Key) && IntoBooleanResult(Visit(left, Value)) === ExtendsResult.True) ? ExtendsResult.True :\n TypeGuard.IsUint8Array(left) && TypeGuard.IsNumber(Key) ? Visit(left, Value) :\n TypeGuard.IsString(left) && TypeGuard.IsNumber(Key) ? Visit(left, Value) :\n TypeGuard.IsArray(left) && TypeGuard.IsNumber(Key) ? Visit(left, Value) :\n TypeGuard.IsObject(left) ? (() => {\n for (const key of Object.getOwnPropertyNames(left.properties)) {\n if (Property(Value, left.properties[key]) === ExtendsResult.False) {\n return ExtendsResult.False;\n }\n }\n return ExtendsResult.True;\n })() :\n ExtendsResult.False);\n}\n// prettier-ignore\nfunction FromRecord(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n !TypeGuard.IsRecord(right) ? ExtendsResult.False :\n Visit(RecordValue(left), RecordValue(right)));\n}\n// ------------------------------------------------------------------\n// RegExp\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromRegExp(left, right) {\n // Note: RegExp types evaluate as strings, not RegExp objects.\n // Here we remap either into string and continue evaluating.\n const L = TypeGuard.IsRegExp(left) ? String() : left;\n const R = TypeGuard.IsRegExp(right) ? String() : right;\n return Visit(L, R);\n}\n// ------------------------------------------------------------------\n// String\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromStringRight(left, right) {\n return (TypeGuard.IsLiteral(left) && ValueGuard.IsString(left.const) ? ExtendsResult.True :\n TypeGuard.IsString(left) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// prettier-ignore\nfunction FromString(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsRecord(right) ? FromRecordRight(left, right) :\n TypeGuard.IsString(right) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// Symbol\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromSymbol(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsRecord(right) ? FromRecordRight(left, right) :\n TypeGuard.IsSymbol(right) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// TemplateLiteral\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromTemplateLiteral(left, right) {\n // TemplateLiteral types are resolved to either unions for finite expressions or string\n // for infinite expressions. Here we call to TemplateLiteralResolver to resolve for\n // either type and continue evaluating.\n return (TypeGuard.IsTemplateLiteral(left) ? Visit(TemplateLiteralToUnion(left), right) :\n TypeGuard.IsTemplateLiteral(right) ? Visit(left, TemplateLiteralToUnion(right)) :\n Throw('Invalid fallthrough for TemplateLiteral'));\n}\n// ------------------------------------------------------------------\n// Tuple\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction IsArrayOfTuple(left, right) {\n return (TypeGuard.IsArray(right) &&\n left.items !== undefined &&\n left.items.every((schema) => Visit(schema, right.items) === ExtendsResult.True));\n}\n// prettier-ignore\nfunction FromTupleRight(left, right) {\n return (TypeGuard.IsNever(left) ? ExtendsResult.True :\n TypeGuard.IsUnknown(left) ? ExtendsResult.False :\n TypeGuard.IsAny(left) ? ExtendsResult.Union :\n ExtendsResult.False);\n}\n// prettier-ignore\nfunction FromTuple(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) && IsObjectArrayLike(right) ? ExtendsResult.True :\n TypeGuard.IsArray(right) && IsArrayOfTuple(left, right) ? ExtendsResult.True :\n !TypeGuard.IsTuple(right) ? ExtendsResult.False :\n (ValueGuard.IsUndefined(left.items) && !ValueGuard.IsUndefined(right.items)) || (!ValueGuard.IsUndefined(left.items) && ValueGuard.IsUndefined(right.items)) ? ExtendsResult.False :\n (ValueGuard.IsUndefined(left.items) && !ValueGuard.IsUndefined(right.items)) ? ExtendsResult.True :\n left.items.every((schema, index) => Visit(schema, right.items[index]) === ExtendsResult.True) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// Uint8Array\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromUint8Array(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsRecord(right) ? FromRecordRight(left, right) :\n TypeGuard.IsUint8Array(right) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// Undefined\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromUndefined(left, right) {\n return (IsStructuralRight(right) ? StructuralRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsRecord(right) ? FromRecordRight(left, right) :\n TypeGuard.IsVoid(right) ? FromVoidRight(left, right) :\n TypeGuard.IsUndefined(right) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// Union\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromUnionRight(left, right) {\n return right.anyOf.some((schema) => Visit(left, schema) === ExtendsResult.True)\n ? ExtendsResult.True\n : ExtendsResult.False;\n}\n// prettier-ignore\nfunction FromUnion(left, right) {\n return left.anyOf.every((schema) => Visit(schema, right) === ExtendsResult.True)\n ? ExtendsResult.True\n : ExtendsResult.False;\n}\n// ------------------------------------------------------------------\n// Unknown\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromUnknownRight(left, right) {\n return ExtendsResult.True;\n}\n// prettier-ignore\nfunction FromUnknown(left, right) {\n return (TypeGuard.IsNever(right) ? FromNeverRight(left, right) :\n TypeGuard.IsIntersect(right) ? FromIntersectRight(left, right) :\n TypeGuard.IsUnion(right) ? FromUnionRight(left, right) :\n TypeGuard.IsAny(right) ? FromAnyRight(left, right) :\n TypeGuard.IsString(right) ? FromStringRight(left, right) :\n TypeGuard.IsNumber(right) ? FromNumberRight(left, right) :\n TypeGuard.IsInteger(right) ? FromIntegerRight(left, right) :\n TypeGuard.IsBoolean(right) ? FromBooleanRight(left, right) :\n TypeGuard.IsArray(right) ? FromArrayRight(left, right) :\n TypeGuard.IsTuple(right) ? FromTupleRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsUnknown(right) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// ------------------------------------------------------------------\n// Void\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromVoidRight(left, right) {\n return (TypeGuard.IsUndefined(left) ? ExtendsResult.True :\n TypeGuard.IsUndefined(left) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// prettier-ignore\nfunction FromVoid(left, right) {\n return (TypeGuard.IsIntersect(right) ? FromIntersectRight(left, right) :\n TypeGuard.IsUnion(right) ? FromUnionRight(left, right) :\n TypeGuard.IsUnknown(right) ? FromUnknownRight(left, right) :\n TypeGuard.IsAny(right) ? FromAnyRight(left, right) :\n TypeGuard.IsObject(right) ? FromObjectRight(left, right) :\n TypeGuard.IsVoid(right) ? ExtendsResult.True :\n ExtendsResult.False);\n}\n// prettier-ignore\nfunction Visit(left, right) {\n return (\n // resolvable\n (TypeGuard.IsTemplateLiteral(left) || TypeGuard.IsTemplateLiteral(right)) ? FromTemplateLiteral(left, right) :\n (TypeGuard.IsRegExp(left) || TypeGuard.IsRegExp(right)) ? FromRegExp(left, right) :\n (TypeGuard.IsNot(left) || TypeGuard.IsNot(right)) ? FromNot(left, right) :\n // standard\n TypeGuard.IsAny(left) ? FromAny(left, right) :\n TypeGuard.IsArray(left) ? FromArray(left, right) :\n TypeGuard.IsBigInt(left) ? FromBigInt(left, right) :\n TypeGuard.IsBoolean(left) ? FromBoolean(left, right) :\n TypeGuard.IsAsyncIterator(left) ? FromAsyncIterator(left, right) :\n TypeGuard.IsConstructor(left) ? FromConstructor(left, right) :\n TypeGuard.IsDate(left) ? FromDate(left, right) :\n TypeGuard.IsFunction(left) ? FromFunction(left, right) :\n TypeGuard.IsInteger(left) ? FromInteger(left, right) :\n TypeGuard.IsIntersect(left) ? FromIntersect(left, right) :\n TypeGuard.IsIterator(left) ? FromIterator(left, right) :\n TypeGuard.IsLiteral(left) ? FromLiteral(left, right) :\n TypeGuard.IsNever(left) ? FromNever(left, right) :\n TypeGuard.IsNull(left) ? FromNull(left, right) :\n TypeGuard.IsNumber(left) ? FromNumber(left, right) :\n TypeGuard.IsObject(left) ? FromObject(left, right) :\n TypeGuard.IsRecord(left) ? FromRecord(left, right) :\n TypeGuard.IsString(left) ? FromString(left, right) :\n TypeGuard.IsSymbol(left) ? FromSymbol(left, right) :\n TypeGuard.IsTuple(left) ? FromTuple(left, right) :\n TypeGuard.IsPromise(left) ? FromPromise(left, right) :\n TypeGuard.IsUint8Array(left) ? FromUint8Array(left, right) :\n TypeGuard.IsUndefined(left) ? FromUndefined(left, right) :\n TypeGuard.IsUnion(left) ? FromUnion(left, right) :\n TypeGuard.IsUnknown(left) ? FromUnknown(left, right) :\n TypeGuard.IsVoid(left) ? FromVoid(left, right) :\n Throw(`Unknown left type operand '${left[Kind]}'`));\n}\nexport function ExtendsCheck(left, right) {\n return Visit(left, right);\n}\n","import { TypeSystemPolicy } from '../system/index.mjs';\nimport { KeyOfPattern } from '../type/keyof/index.mjs';\nimport { TypeRegistry, FormatRegistry } from '../type/registry/index.mjs';\nimport { ExtendsUndefinedCheck } from '../type/extends/extends-undefined.mjs';\nimport { GetErrorFunction } from './function.mjs';\nimport { TypeBoxError } from '../type/error/index.mjs';\nimport { Deref } from '../value/deref/index.mjs';\nimport { Hash } from '../value/hash/index.mjs';\nimport { Check } from '../value/check/index.mjs';\nimport { Kind } from '../type/symbols/index.mjs';\nimport { Never } from '../type/never/index.mjs';\n// ------------------------------------------------------------------\n// ValueGuard\n// ------------------------------------------------------------------\n// prettier-ignore\nimport { IsArray, IsUint8Array, IsDate, IsPromise, IsFunction, IsAsyncIterator, IsIterator, IsBoolean, IsNumber, IsBigInt, IsString, IsSymbol, IsInteger, IsNull, IsUndefined } from '../value/guard/index.mjs';\n// ------------------------------------------------------------------\n// ValueErrorType\n// ------------------------------------------------------------------\nexport var ValueErrorType;\n(function (ValueErrorType) {\n ValueErrorType[ValueErrorType[\"ArrayContains\"] = 0] = \"ArrayContains\";\n ValueErrorType[ValueErrorType[\"ArrayMaxContains\"] = 1] = \"ArrayMaxContains\";\n ValueErrorType[ValueErrorType[\"ArrayMaxItems\"] = 2] = \"ArrayMaxItems\";\n ValueErrorType[ValueErrorType[\"ArrayMinContains\"] = 3] = \"ArrayMinContains\";\n ValueErrorType[ValueErrorType[\"ArrayMinItems\"] = 4] = \"ArrayMinItems\";\n ValueErrorType[ValueErrorType[\"ArrayUniqueItems\"] = 5] = \"ArrayUniqueItems\";\n ValueErrorType[ValueErrorType[\"Array\"] = 6] = \"Array\";\n ValueErrorType[ValueErrorType[\"AsyncIterator\"] = 7] = \"AsyncIterator\";\n ValueErrorType[ValueErrorType[\"BigIntExclusiveMaximum\"] = 8] = \"BigIntExclusiveMaximum\";\n ValueErrorType[ValueErrorType[\"BigIntExclusiveMinimum\"] = 9] = \"BigIntExclusiveMinimum\";\n ValueErrorType[ValueErrorType[\"BigIntMaximum\"] = 10] = \"BigIntMaximum\";\n ValueErrorType[ValueErrorType[\"BigIntMinimum\"] = 11] = \"BigIntMinimum\";\n ValueErrorType[ValueErrorType[\"BigIntMultipleOf\"] = 12] = \"BigIntMultipleOf\";\n ValueErrorType[ValueErrorType[\"BigInt\"] = 13] = \"BigInt\";\n ValueErrorType[ValueErrorType[\"Boolean\"] = 14] = \"Boolean\";\n ValueErrorType[ValueErrorType[\"DateExclusiveMaximumTimestamp\"] = 15] = \"DateExclusiveMaximumTimestamp\";\n ValueErrorType[ValueErrorType[\"DateExclusiveMinimumTimestamp\"] = 16] = \"DateExclusiveMinimumTimestamp\";\n ValueErrorType[ValueErrorType[\"DateMaximumTimestamp\"] = 17] = \"DateMaximumTimestamp\";\n ValueErrorType[ValueErrorType[\"DateMinimumTimestamp\"] = 18] = \"DateMinimumTimestamp\";\n ValueErrorType[ValueErrorType[\"DateMultipleOfTimestamp\"] = 19] = \"DateMultipleOfTimestamp\";\n ValueErrorType[ValueErrorType[\"Date\"] = 20] = \"Date\";\n ValueErrorType[ValueErrorType[\"Function\"] = 21] = \"Function\";\n ValueErrorType[ValueErrorType[\"IntegerExclusiveMaximum\"] = 22] = \"IntegerExclusiveMaximum\";\n ValueErrorType[ValueErrorType[\"IntegerExclusiveMinimum\"] = 23] = \"IntegerExclusiveMinimum\";\n ValueErrorType[ValueErrorType[\"IntegerMaximum\"] = 24] = \"IntegerMaximum\";\n ValueErrorType[ValueErrorType[\"IntegerMinimum\"] = 25] = \"IntegerMinimum\";\n ValueErrorType[ValueErrorType[\"IntegerMultipleOf\"] = 26] = \"IntegerMultipleOf\";\n ValueErrorType[ValueErrorType[\"Integer\"] = 27] = \"Integer\";\n ValueErrorType[ValueErrorType[\"IntersectUnevaluatedProperties\"] = 28] = \"IntersectUnevaluatedProperties\";\n ValueErrorType[ValueErrorType[\"Intersect\"] = 29] = \"Intersect\";\n ValueErrorType[ValueErrorType[\"Iterator\"] = 30] = \"Iterator\";\n ValueErrorType[ValueErrorType[\"Kind\"] = 31] = \"Kind\";\n ValueErrorType[ValueErrorType[\"Literal\"] = 32] = \"Literal\";\n ValueErrorType[ValueErrorType[\"Never\"] = 33] = \"Never\";\n ValueErrorType[ValueErrorType[\"Not\"] = 34] = \"Not\";\n ValueErrorType[ValueErrorType[\"Null\"] = 35] = \"Null\";\n ValueErrorType[ValueErrorType[\"NumberExclusiveMaximum\"] = 36] = \"NumberExclusiveMaximum\";\n ValueErrorType[ValueErrorType[\"NumberExclusiveMinimum\"] = 37] = \"NumberExclusiveMinimum\";\n ValueErrorType[ValueErrorType[\"NumberMaximum\"] = 38] = \"NumberMaximum\";\n ValueErrorType[ValueErrorType[\"NumberMinimum\"] = 39] = \"NumberMinimum\";\n ValueErrorType[ValueErrorType[\"NumberMultipleOf\"] = 40] = \"NumberMultipleOf\";\n ValueErrorType[ValueErrorType[\"Number\"] = 41] = \"Number\";\n ValueErrorType[ValueErrorType[\"ObjectAdditionalProperties\"] = 42] = \"ObjectAdditionalProperties\";\n ValueErrorType[ValueErrorType[\"ObjectMaxProperties\"] = 43] = \"ObjectMaxProperties\";\n ValueErrorType[ValueErrorType[\"ObjectMinProperties\"] = 44] = \"ObjectMinProperties\";\n ValueErrorType[ValueErrorType[\"ObjectRequiredProperty\"] = 45] = \"ObjectRequiredProperty\";\n ValueErrorType[ValueErrorType[\"Object\"] = 46] = \"Object\";\n ValueErrorType[ValueErrorType[\"Promise\"] = 47] = \"Promise\";\n ValueErrorType[ValueErrorType[\"RegExp\"] = 48] = \"RegExp\";\n ValueErrorType[ValueErrorType[\"StringFormatUnknown\"] = 49] = \"StringFormatUnknown\";\n ValueErrorType[ValueErrorType[\"StringFormat\"] = 50] = \"StringFormat\";\n ValueErrorType[ValueErrorType[\"StringMaxLength\"] = 51] = \"StringMaxLength\";\n ValueErrorType[ValueErrorType[\"StringMinLength\"] = 52] = \"StringMinLength\";\n ValueErrorType[ValueErrorType[\"StringPattern\"] = 53] = \"StringPattern\";\n ValueErrorType[ValueErrorType[\"String\"] = 54] = \"String\";\n ValueErrorType[ValueErrorType[\"Symbol\"] = 55] = \"Symbol\";\n ValueErrorType[ValueErrorType[\"TupleLength\"] = 56] = \"TupleLength\";\n ValueErrorType[ValueErrorType[\"Tuple\"] = 57] = \"Tuple\";\n ValueErrorType[ValueErrorType[\"Uint8ArrayMaxByteLength\"] = 58] = \"Uint8ArrayMaxByteLength\";\n ValueErrorType[ValueErrorType[\"Uint8ArrayMinByteLength\"] = 59] = \"Uint8ArrayMinByteLength\";\n ValueErrorType[ValueErrorType[\"Uint8Array\"] = 60] = \"Uint8Array\";\n ValueErrorType[ValueErrorType[\"Undefined\"] = 61] = \"Undefined\";\n ValueErrorType[ValueErrorType[\"Union\"] = 62] = \"Union\";\n ValueErrorType[ValueErrorType[\"Void\"] = 63] = \"Void\";\n})(ValueErrorType || (ValueErrorType = {}));\n// ------------------------------------------------------------------\n// ValueErrors\n// ------------------------------------------------------------------\nexport class ValueErrorsUnknownTypeError extends TypeBoxError {\n constructor(schema) {\n super('Unknown type');\n this.schema = schema;\n }\n}\n// ------------------------------------------------------------------\n// EscapeKey\n// ------------------------------------------------------------------\nfunction EscapeKey(key) {\n return key.replace(/~/g, '~0').replace(/\\//g, '~1'); // RFC6901 Path\n}\n// ------------------------------------------------------------------\n// Guards\n// ------------------------------------------------------------------\nfunction IsDefined(value) {\n return value !== undefined;\n}\n// ------------------------------------------------------------------\n// ValueErrorIterator\n// ------------------------------------------------------------------\nexport class ValueErrorIterator {\n constructor(iterator) {\n this.iterator = iterator;\n }\n [Symbol.iterator]() {\n return this.iterator;\n }\n /** Returns the first value error or undefined if no errors */\n First() {\n const next = this.iterator.next();\n return next.done ? undefined : next.value;\n }\n}\n// --------------------------------------------------------------------------\n// Create\n// --------------------------------------------------------------------------\nfunction Create(errorType, schema, path, value, errors = []) {\n return {\n type: errorType,\n schema,\n path,\n value,\n message: GetErrorFunction()({ errorType, path, schema, value, errors }),\n errors,\n };\n}\n// --------------------------------------------------------------------------\n// Types\n// --------------------------------------------------------------------------\nfunction* FromAny(schema, references, path, value) { }\nfunction* FromArray(schema, references, path, value) {\n if (!IsArray(value)) {\n return yield Create(ValueErrorType.Array, schema, path, value);\n }\n if (IsDefined(schema.minItems) && !(value.length >= schema.minItems)) {\n yield Create(ValueErrorType.ArrayMinItems, schema, path, value);\n }\n if (IsDefined(schema.maxItems) && !(value.length <= schema.maxItems)) {\n yield Create(ValueErrorType.ArrayMaxItems, schema, path, value);\n }\n for (let i = 0; i < value.length; i++) {\n yield* Visit(schema.items, references, `${path}/${i}`, value[i]);\n }\n // prettier-ignore\n if (schema.uniqueItems === true && !((function () { const set = new Set(); for (const element of value) {\n const hashed = Hash(element);\n if (set.has(hashed)) {\n return false;\n }\n else {\n set.add(hashed);\n }\n } return true; })())) {\n yield Create(ValueErrorType.ArrayUniqueItems, schema, path, value);\n }\n // contains\n if (!(IsDefined(schema.contains) || IsDefined(schema.minContains) || IsDefined(schema.maxContains))) {\n return;\n }\n const containsSchema = IsDefined(schema.contains) ? schema.contains : Never();\n const containsCount = value.reduce((acc, value, index) => (Visit(containsSchema, references, `${path}${index}`, value).next().done === true ? acc + 1 : acc), 0);\n if (containsCount === 0) {\n yield Create(ValueErrorType.ArrayContains, schema, path, value);\n }\n if (IsNumber(schema.minContains) && containsCount < schema.minContains) {\n yield Create(ValueErrorType.ArrayMinContains, schema, path, value);\n }\n if (IsNumber(schema.maxContains) && containsCount > schema.maxContains) {\n yield Create(ValueErrorType.ArrayMaxContains, schema, path, value);\n }\n}\nfunction* FromAsyncIterator(schema, references, path, value) {\n if (!IsAsyncIterator(value))\n yield Create(ValueErrorType.AsyncIterator, schema, path, value);\n}\nfunction* FromBigInt(schema, references, path, value) {\n if (!IsBigInt(value))\n return yield Create(ValueErrorType.BigInt, schema, path, value);\n if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {\n yield Create(ValueErrorType.BigIntExclusiveMaximum, schema, path, value);\n }\n if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {\n yield Create(ValueErrorType.BigIntExclusiveMinimum, schema, path, value);\n }\n if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {\n yield Create(ValueErrorType.BigIntMaximum, schema, path, value);\n }\n if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {\n yield Create(ValueErrorType.BigIntMinimum, schema, path, value);\n }\n if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === BigInt(0))) {\n yield Create(ValueErrorType.BigIntMultipleOf, schema, path, value);\n }\n}\nfunction* FromBoolean(schema, references, path, value) {\n if (!IsBoolean(value))\n yield Create(ValueErrorType.Boolean, schema, path, value);\n}\nfunction* FromConstructor(schema, references, path, value) {\n yield* Visit(schema.returns, references, path, value.prototype);\n}\nfunction* FromDate(schema, references, path, value) {\n if (!IsDate(value))\n return yield Create(ValueErrorType.Date, schema, path, value);\n if (IsDefined(schema.exclusiveMaximumTimestamp) && !(value.getTime() < schema.exclusiveMaximumTimestamp)) {\n yield Create(ValueErrorType.DateExclusiveMaximumTimestamp, schema, path, value);\n }\n if (IsDefined(schema.exclusiveMinimumTimestamp) && !(value.getTime() > schema.exclusiveMinimumTimestamp)) {\n yield Create(ValueErrorType.DateExclusiveMinimumTimestamp, schema, path, value);\n }\n if (IsDefined(schema.maximumTimestamp) && !(value.getTime() <= schema.maximumTimestamp)) {\n yield Create(ValueErrorType.DateMaximumTimestamp, schema, path, value);\n }\n if (IsDefined(schema.minimumTimestamp) && !(value.getTime() >= schema.minimumTimestamp)) {\n yield Create(ValueErrorType.DateMinimumTimestamp, schema, path, value);\n }\n if (IsDefined(schema.multipleOfTimestamp) && !(value.getTime() % schema.multipleOfTimestamp === 0)) {\n yield Create(ValueErrorType.DateMultipleOfTimestamp, schema, path, value);\n }\n}\nfunction* FromFunction(schema, references, path, value) {\n if (!IsFunction(value))\n yield Create(ValueErrorType.Function, schema, path, value);\n}\nfunction* FromImport(schema, references, path, value) {\n const definitions = globalThis.Object.values(schema.$defs);\n const target = schema.$defs[schema.$ref];\n yield* Visit(target, [...references, ...definitions], path, value);\n}\nfunction* FromInteger(schema, references, path, value) {\n if (!IsInteger(value))\n return yield Create(ValueErrorType.Integer, schema, path, value);\n if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {\n yield Create(ValueErrorType.IntegerExclusiveMaximum, schema, path, value);\n }\n if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {\n yield Create(ValueErrorType.IntegerExclusiveMinimum, schema, path, value);\n }\n if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {\n yield Create(ValueErrorType.IntegerMaximum, schema, path, value);\n }\n if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {\n yield Create(ValueErrorType.IntegerMinimum, schema, path, value);\n }\n if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) {\n yield Create(ValueErrorType.IntegerMultipleOf, schema, path, value);\n }\n}\nfunction* FromIntersect(schema, references, path, value) {\n let hasError = false;\n for (const inner of schema.allOf) {\n for (const error of Visit(inner, references, path, value)) {\n hasError = true;\n yield error;\n }\n }\n if (hasError) {\n return yield Create(ValueErrorType.Intersect, schema, path, value);\n }\n if (schema.unevaluatedProperties === false) {\n const keyCheck = new RegExp(KeyOfPattern(schema));\n for (const valueKey of Object.getOwnPropertyNames(value)) {\n if (!keyCheck.test(valueKey)) {\n yield Create(ValueErrorType.IntersectUnevaluatedProperties, schema, `${path}/${valueKey}`, value);\n }\n }\n }\n if (typeof schema.unevaluatedProperties === 'object') {\n const keyCheck = new RegExp(KeyOfPattern(schema));\n for (const valueKey of Object.getOwnPropertyNames(value)) {\n if (!keyCheck.test(valueKey)) {\n const next = Visit(schema.unevaluatedProperties, references, `${path}/${valueKey}`, value[valueKey]).next();\n if (!next.done)\n yield next.value; // yield interior\n }\n }\n }\n}\nfunction* FromIterator(schema, references, path, value) {\n if (!IsIterator(value))\n yield Create(ValueErrorType.Iterator, schema, path, value);\n}\nfunction* FromLiteral(schema, references, path, value) {\n if (!(value === schema.const))\n yield Create(ValueErrorType.Literal, schema, path, value);\n}\nfunction* FromNever(schema, references, path, value) {\n yield Create(ValueErrorType.Never, schema, path, value);\n}\nfunction* FromNot(schema, references, path, value) {\n if (Visit(schema.not, references, path, value).next().done === true)\n yield Create(ValueErrorType.Not, schema, path, value);\n}\nfunction* FromNull(schema, references, path, value) {\n if (!IsNull(value))\n yield Create(ValueErrorType.Null, schema, path, value);\n}\nfunction* FromNumber(schema, references, path, value) {\n if (!TypeSystemPolicy.IsNumberLike(value))\n return yield Create(ValueErrorType.Number, schema, path, value);\n if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {\n yield Create(ValueErrorType.NumberExclusiveMaximum, schema, path, value);\n }\n if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {\n yield Create(ValueErrorType.NumberExclusiveMinimum, schema, path, value);\n }\n if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {\n yield Create(ValueErrorType.NumberMaximum, schema, path, value);\n }\n if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {\n yield Create(ValueErrorType.NumberMinimum, schema, path, value);\n }\n if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) {\n yield Create(ValueErrorType.NumberMultipleOf, schema, path, value);\n }\n}\nfunction* FromObject(schema, references, path, value) {\n if (!TypeSystemPolicy.IsObjectLike(value))\n return yield Create(ValueErrorType.Object, schema, path, value);\n if (IsDefined(schema.minProperties) && !(Object.getOwnPropertyNames(value).length >= schema.minProperties)) {\n yield Create(ValueErrorType.ObjectMinProperties, schema, path, value);\n }\n if (IsDefined(schema.maxProperties) && !(Object.getOwnPropertyNames(value).length <= schema.maxProperties)) {\n yield Create(ValueErrorType.ObjectMaxProperties, schema, path, value);\n }\n const requiredKeys = Array.isArray(schema.required) ? schema.required : [];\n const knownKeys = Object.getOwnPropertyNames(schema.properties);\n const unknownKeys = Object.getOwnPropertyNames(value);\n for (const requiredKey of requiredKeys) {\n if (unknownKeys.includes(requiredKey))\n continue;\n yield Create(ValueErrorType.ObjectRequiredProperty, schema.properties[requiredKey], `${path}/${EscapeKey(requiredKey)}`, undefined);\n }\n if (schema.additionalProperties === false) {\n for (const valueKey of unknownKeys) {\n if (!knownKeys.includes(valueKey)) {\n yield Create(ValueErrorType.ObjectAdditionalProperties, schema, `${path}/${EscapeKey(valueKey)}`, value[valueKey]);\n }\n }\n }\n if (typeof schema.additionalProperties === 'object') {\n for (const valueKey of unknownKeys) {\n if (knownKeys.includes(valueKey))\n continue;\n yield* Visit(schema.additionalProperties, references, `${path}/${EscapeKey(valueKey)}`, value[valueKey]);\n }\n }\n for (const knownKey of knownKeys) {\n const property = schema.properties[knownKey];\n if (schema.required && schema.required.includes(knownKey)) {\n yield* Visit(property, references, `${path}/${EscapeKey(knownKey)}`, value[knownKey]);\n if (ExtendsUndefinedCheck(schema) && !(knownKey in value)) {\n yield Create(ValueErrorType.ObjectRequiredProperty, property, `${path}/${EscapeKey(knownKey)}`, undefined);\n }\n }\n else {\n if (TypeSystemPolicy.IsExactOptionalProperty(value, knownKey)) {\n yield* Visit(property, references, `${path}/${EscapeKey(knownKey)}`, value[knownKey]);\n }\n }\n }\n}\nfunction* FromPromise(schema, references, path, value) {\n if (!IsPromise(value))\n yield Create(ValueErrorType.Promise, schema, path, value);\n}\nfunction* FromRecord(schema, references, path, value) {\n if (!TypeSystemPolicy.IsRecordLike(value))\n return yield Create(ValueErrorType.Object, schema, path, value);\n if (IsDefined(schema.minProperties) && !(Object.getOwnPropertyNames(value).length >= schema.minProperties)) {\n yield Create(ValueErrorType.ObjectMinProperties, schema, path, value);\n }\n if (IsDefined(schema.maxProperties) && !(Object.getOwnPropertyNames(value).length <= schema.maxProperties)) {\n yield Create(ValueErrorType.ObjectMaxProperties, schema, path, value);\n }\n const [patternKey, patternSchema] = Object.entries(schema.patternProperties)[0];\n const regex = new RegExp(patternKey);\n for (const [propertyKey, propertyValue] of Object.entries(value)) {\n if (regex.test(propertyKey))\n yield* Visit(patternSchema, references, `${path}/${EscapeKey(propertyKey)}`, propertyValue);\n }\n if (typeof schema.additionalProperties === 'object') {\n for (const [propertyKey, propertyValue] of Object.entries(value)) {\n if (!regex.test(propertyKey))\n yield* Visit(schema.additionalProperties, references, `${path}/${EscapeKey(propertyKey)}`, propertyValue);\n }\n }\n if (schema.additionalProperties === false) {\n for (const [propertyKey, propertyValue] of Object.entries(value)) {\n if (regex.test(propertyKey))\n continue;\n return yield Create(ValueErrorType.ObjectAdditionalProperties, schema, `${path}/${EscapeKey(propertyKey)}`, propertyValue);\n }\n }\n}\nfunction* FromRef(schema, references, path, value) {\n yield* Visit(Deref(schema, references), references, path, value);\n}\nfunction* FromRegExp(schema, references, path, value) {\n if (!IsString(value))\n return yield Create(ValueErrorType.String, schema, path, value);\n if (IsDefined(schema.minLength) && !(value.length >= schema.minLength)) {\n yield Create(ValueErrorType.StringMinLength, schema, path, value);\n }\n if (IsDefined(schema.maxLength) && !(value.length <= schema.maxLength)) {\n yield Create(ValueErrorType.StringMaxLength, schema, path, value);\n }\n const regex = new RegExp(schema.source, schema.flags);\n if (!regex.test(value)) {\n return yield Create(ValueErrorType.RegExp, schema, path, value);\n }\n}\nfunction* FromString(schema, references, path, value) {\n if (!IsString(value))\n return yield Create(ValueErrorType.String, schema, path, value);\n if (IsDefined(schema.minLength) && !(value.length >= schema.minLength)) {\n yield Create(ValueErrorType.StringMinLength, schema, path, value);\n }\n if (IsDefined(schema.maxLength) && !(value.length <= schema.maxLength)) {\n yield Create(ValueErrorType.StringMaxLength, schema, path, value);\n }\n if (IsString(schema.pattern)) {\n const regex = new RegExp(schema.pattern);\n if (!regex.test(value)) {\n yield Create(ValueErrorType.StringPattern, schema, path, value);\n }\n }\n if (IsString(schema.format)) {\n if (!FormatRegistry.Has(schema.format)) {\n yield Create(ValueErrorType.StringFormatUnknown, schema, path, value);\n }\n else {\n const format = FormatRegistry.Get(schema.format);\n if (!format(value)) {\n yield Create(ValueErrorType.StringFormat, schema, path, value);\n }\n }\n }\n}\nfunction* FromSymbol(schema, references, path, value) {\n if (!IsSymbol(value))\n yield Create(ValueErrorType.Symbol, schema, path, value);\n}\nfunction* FromTemplateLiteral(schema, references, path, value) {\n if (!IsString(value))\n return yield Create(ValueErrorType.String, schema, path, value);\n const regex = new RegExp(schema.pattern);\n if (!regex.test(value)) {\n yield Create(ValueErrorType.StringPattern, schema, path, value);\n }\n}\nfunction* FromThis(schema, references, path, value) {\n yield* Visit(Deref(schema, references), references, path, value);\n}\nfunction* FromTuple(schema, references, path, value) {\n if (!IsArray(value))\n return yield Create(ValueErrorType.Tuple, schema, path, value);\n if (schema.items === undefined && !(value.length === 0)) {\n return yield Create(ValueErrorType.TupleLength, schema, path, value);\n }\n if (!(value.length === schema.maxItems)) {\n return yield Create(ValueErrorType.TupleLength, schema, path, value);\n }\n if (!schema.items) {\n return;\n }\n for (let i = 0; i < schema.items.length; i++) {\n yield* Visit(schema.items[i], references, `${path}/${i}`, value[i]);\n }\n}\nfunction* FromUndefined(schema, references, path, value) {\n if (!IsUndefined(value))\n yield Create(ValueErrorType.Undefined, schema, path, value);\n}\nfunction* FromUnion(schema, references, path, value) {\n if (Check(schema, references, value))\n return;\n const errors = schema.anyOf.map((variant) => new ValueErrorIterator(Visit(variant, references, path, value)));\n yield Create(ValueErrorType.Union, schema, path, value, errors);\n}\nfunction* FromUint8Array(schema, references, path, value) {\n if (!IsUint8Array(value))\n return yield Create(ValueErrorType.Uint8Array, schema, path, value);\n if (IsDefined(schema.maxByteLength) && !(value.length <= schema.maxByteLength)) {\n yield Create(ValueErrorType.Uint8ArrayMaxByteLength, schema, path, value);\n }\n if (IsDefined(schema.minByteLength) && !(value.length >= schema.minByteLength)) {\n yield Create(ValueErrorType.Uint8ArrayMinByteLength, schema, path, value);\n }\n}\nfunction* FromUnknown(schema, references, path, value) { }\nfunction* FromVoid(schema, references, path, value) {\n if (!TypeSystemPolicy.IsVoidLike(value))\n yield Create(ValueErrorType.Void, schema, path, value);\n}\nfunction* FromKind(schema, references, path, value) {\n const check = TypeRegistry.Get(schema[Kind]);\n if (!check(schema, value))\n yield Create(ValueErrorType.Kind, schema, path, value);\n}\nfunction* Visit(schema, references, path, value) {\n const references_ = IsDefined(schema.$id) ? [...references, schema] : references;\n const schema_ = schema;\n switch (schema_[Kind]) {\n case 'Any':\n return yield* FromAny(schema_, references_, path, value);\n case 'Array':\n return yield* FromArray(schema_, references_, path, value);\n case 'AsyncIterator':\n return yield* FromAsyncIterator(schema_, references_, path, value);\n case 'BigInt':\n return yield* FromBigInt(schema_, references_, path, value);\n case 'Boolean':\n return yield* FromBoolean(schema_, references_, path, value);\n case 'Constructor':\n return yield* FromConstructor(schema_, references_, path, value);\n case 'Date':\n return yield* FromDate(schema_, references_, path, value);\n case 'Function':\n return yield* FromFunction(schema_, references_, path, value);\n case 'Import':\n return yield* FromImport(schema_, references_, path, value);\n case 'Integer':\n return yield* FromInteger(schema_, references_, path, value);\n case 'Intersect':\n return yield* FromIntersect(schema_, references_, path, value);\n case 'Iterator':\n return yield* FromIterator(schema_, references_, path, value);\n case 'Literal':\n return yield* FromLiteral(schema_, references_, path, value);\n case 'Never':\n return yield* FromNever(schema_, references_, path, value);\n case 'Not':\n return yield* FromNot(schema_, references_, path, value);\n case 'Null':\n return yield* FromNull(schema_, references_, path, value);\n case 'Number':\n return yield* FromNumber(schema_, references_, path, value);\n case 'Object':\n return yield* FromObject(schema_, references_, path, value);\n case 'Promise':\n return yield* FromPromise(schema_, references_, path, value);\n case 'Record':\n return yield* FromRecord(schema_, references_, path, value);\n case 'Ref':\n return yield* FromRef(schema_, references_, path, value);\n case 'RegExp':\n return yield* FromRegExp(schema_, references_, path, value);\n case 'String':\n return yield* FromString(schema_, references_, path, value);\n case 'Symbol':\n return yield* FromSymbol(schema_, references_, path, value);\n case 'TemplateLiteral':\n return yield* FromTemplateLiteral(schema_, references_, path, value);\n case 'This':\n return yield* FromThis(schema_, references_, path, value);\n case 'Tuple':\n return yield* FromTuple(schema_, references_, path, value);\n case 'Undefined':\n return yield* FromUndefined(schema_, references_, path, value);\n case 'Union':\n return yield* FromUnion(schema_, references_, path, value);\n case 'Uint8Array':\n return yield* FromUint8Array(schema_, references_, path, value);\n case 'Unknown':\n return yield* FromUnknown(schema_, references_, path, value);\n case 'Void':\n return yield* FromVoid(schema_, references_, path, value);\n default:\n if (!TypeRegistry.Has(schema_[Kind]))\n throw new ValueErrorsUnknownTypeError(schema);\n return yield* FromKind(schema_, references_, path, value);\n }\n}\n/** Returns an iterator for each error in this value. */\nexport function Errors(...args) {\n const iterator = args.length === 3 ? Visit(args[0], args[1], '', args[2]) : Visit(args[0], [], '', args[1]);\n return new ValueErrorIterator(iterator);\n}\n","import { MappedResult } from '../mapped/index.mjs';\nimport { Extends } from './extends.mjs';\nimport { Clone } from '../clone/value.mjs';\n// prettier-ignore\nfunction FromProperties(P, Right, True, False, options) {\n const Acc = {};\n for (const K2 of globalThis.Object.getOwnPropertyNames(P))\n Acc[K2] = Extends(P[K2], Right, True, False, Clone(options));\n return Acc;\n}\n// prettier-ignore\nfunction FromMappedResult(Left, Right, True, False, options) {\n return FromProperties(Left.properties, Right, True, False, options);\n}\n// prettier-ignore\nexport function ExtendsFromMappedResult(Left, Right, True, False, options) {\n const P = FromMappedResult(Left, Right, True, False, options);\n return MappedResult(P);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Union } from '../union/index.mjs';\nimport { ExtendsCheck, ExtendsResult } from './extends-check.mjs';\nimport { ExtendsFromMappedKey } from './extends-from-mapped-key.mjs';\nimport { ExtendsFromMappedResult } from './extends-from-mapped-result.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsMappedKey, IsMappedResult } from '../guard/kind.mjs';\n// prettier-ignore\nfunction ExtendsResolve(left, right, trueType, falseType) {\n const R = ExtendsCheck(left, right);\n return (R === ExtendsResult.Union ? Union([trueType, falseType]) :\n R === ExtendsResult.True ? trueType :\n falseType);\n}\n/** `[Json]` Creates a Conditional type */\nexport function Extends(L, R, T, F, options) {\n // prettier-ignore\n return (IsMappedResult(L) ? ExtendsFromMappedResult(L, R, T, F, options) :\n IsMappedKey(L) ? CreateType(ExtendsFromMappedKey(L, R, T, F, options)) :\n CreateType(ExtendsResolve(L, R, T, F), options));\n}\n","import { MappedResult } from '../mapped/index.mjs';\nimport { Literal } from '../literal/index.mjs';\nimport { Extends } from './extends.mjs';\nimport { Clone } from '../clone/value.mjs';\n// prettier-ignore\nfunction FromPropertyKey(K, U, L, R, options) {\n return {\n [K]: Extends(Literal(K), U, L, R, Clone(options))\n };\n}\n// prettier-ignore\nfunction FromPropertyKeys(K, U, L, R, options) {\n return K.reduce((Acc, LK) => {\n return { ...Acc, ...FromPropertyKey(LK, U, L, R, options) };\n }, {});\n}\n// prettier-ignore\nfunction FromMappedKey(K, U, L, R, options) {\n return FromPropertyKeys(K.keys, U, L, R, options);\n}\n// prettier-ignore\nexport function ExtendsFromMappedKey(T, U, L, R, options) {\n const P = FromMappedKey(T, U, L, R, options);\n return MappedResult(P);\n}\n","import { TypeSystemPolicy } from '../../system/index.mjs';\nimport { Deref, Pushref } from '../deref/index.mjs';\nimport { Hash } from '../hash/index.mjs';\nimport { Kind } from '../../type/symbols/index.mjs';\nimport { KeyOfPattern } from '../../type/keyof/index.mjs';\nimport { ExtendsUndefinedCheck } from '../../type/extends/index.mjs';\nimport { TypeRegistry, FormatRegistry } from '../../type/registry/index.mjs';\nimport { TypeBoxError } from '../../type/error/index.mjs';\nimport { Never } from '../../type/never/index.mjs';\n// ------------------------------------------------------------------\n// ValueGuard\n// ------------------------------------------------------------------\nimport { IsArray, IsUint8Array, IsDate, IsPromise, IsFunction, IsAsyncIterator, IsIterator, IsBoolean, IsNumber, IsBigInt, IsString, IsSymbol, IsInteger, IsNull, IsUndefined } from '../guard/index.mjs';\n// ------------------------------------------------------------------\n// KindGuard\n// ------------------------------------------------------------------\nimport { IsSchema } from '../../type/guard/kind.mjs';\n// ------------------------------------------------------------------\n// Errors\n// ------------------------------------------------------------------\nexport class ValueCheckUnknownTypeError extends TypeBoxError {\n constructor(schema) {\n super(`Unknown type`);\n this.schema = schema;\n }\n}\n// ------------------------------------------------------------------\n// TypeGuards\n// ------------------------------------------------------------------\nfunction IsAnyOrUnknown(schema) {\n return schema[Kind] === 'Any' || schema[Kind] === 'Unknown';\n}\n// ------------------------------------------------------------------\n// Guards\n// ------------------------------------------------------------------\nfunction IsDefined(value) {\n return value !== undefined;\n}\n// ------------------------------------------------------------------\n// Types\n// ------------------------------------------------------------------\nfunction FromAny(schema, references, value) {\n return true;\n}\nfunction FromArray(schema, references, value) {\n if (!IsArray(value))\n return false;\n if (IsDefined(schema.minItems) && !(value.length >= schema.minItems)) {\n return false;\n }\n if (IsDefined(schema.maxItems) && !(value.length <= schema.maxItems)) {\n return false;\n }\n if (!value.every((value) => Visit(schema.items, references, value))) {\n return false;\n }\n // prettier-ignore\n if (schema.uniqueItems === true && !((function () { const set = new Set(); for (const element of value) {\n const hashed = Hash(element);\n if (set.has(hashed)) {\n return false;\n }\n else {\n set.add(hashed);\n }\n } return true; })())) {\n return false;\n }\n // contains\n if (!(IsDefined(schema.contains) || IsNumber(schema.minContains) || IsNumber(schema.maxContains))) {\n return true; // exit\n }\n const containsSchema = IsDefined(schema.contains) ? schema.contains : Never();\n const containsCount = value.reduce((acc, value) => (Visit(containsSchema, references, value) ? acc + 1 : acc), 0);\n if (containsCount === 0) {\n return false;\n }\n if (IsNumber(schema.minContains) && containsCount < schema.minContains) {\n return false;\n }\n if (IsNumber(schema.maxContains) && containsCount > schema.maxContains) {\n return false;\n }\n return true;\n}\nfunction FromAsyncIterator(schema, references, value) {\n return IsAsyncIterator(value);\n}\nfunction FromBigInt(schema, references, value) {\n if (!IsBigInt(value))\n return false;\n if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {\n return false;\n }\n if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {\n return false;\n }\n if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {\n return false;\n }\n if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {\n return false;\n }\n if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === BigInt(0))) {\n return false;\n }\n return true;\n}\nfunction FromBoolean(schema, references, value) {\n return IsBoolean(value);\n}\nfunction FromConstructor(schema, references, value) {\n return Visit(schema.returns, references, value.prototype);\n}\nfunction FromDate(schema, references, value) {\n if (!IsDate(value))\n return false;\n if (IsDefined(schema.exclusiveMaximumTimestamp) && !(value.getTime() < schema.exclusiveMaximumTimestamp)) {\n return false;\n }\n if (IsDefined(schema.exclusiveMinimumTimestamp) && !(value.getTime() > schema.exclusiveMinimumTimestamp)) {\n return false;\n }\n if (IsDefined(schema.maximumTimestamp) && !(value.getTime() <= schema.maximumTimestamp)) {\n return false;\n }\n if (IsDefined(schema.minimumTimestamp) && !(value.getTime() >= schema.minimumTimestamp)) {\n return false;\n }\n if (IsDefined(schema.multipleOfTimestamp) && !(value.getTime() % schema.multipleOfTimestamp === 0)) {\n return false;\n }\n return true;\n}\nfunction FromFunction(schema, references, value) {\n return IsFunction(value);\n}\nfunction FromImport(schema, references, value) {\n const definitions = globalThis.Object.values(schema.$defs);\n const target = schema.$defs[schema.$ref];\n return Visit(target, [...references, ...definitions], value);\n}\nfunction FromInteger(schema, references, value) {\n if (!IsInteger(value)) {\n return false;\n }\n if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {\n return false;\n }\n if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {\n return false;\n }\n if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {\n return false;\n }\n if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {\n return false;\n }\n if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) {\n return false;\n }\n return true;\n}\nfunction FromIntersect(schema, references, value) {\n const check1 = schema.allOf.every((schema) => Visit(schema, references, value));\n if (schema.unevaluatedProperties === false) {\n const keyPattern = new RegExp(KeyOfPattern(schema));\n const check2 = Object.getOwnPropertyNames(value).every((key) => keyPattern.test(key));\n return check1 && check2;\n }\n else if (IsSchema(schema.unevaluatedProperties)) {\n const keyCheck = new RegExp(KeyOfPattern(schema));\n const check2 = Object.getOwnPropertyNames(value).every((key) => keyCheck.test(key) || Visit(schema.unevaluatedProperties, references, value[key]));\n return check1 && check2;\n }\n else {\n return check1;\n }\n}\nfunction FromIterator(schema, references, value) {\n return IsIterator(value);\n}\nfunction FromLiteral(schema, references, value) {\n return value === schema.const;\n}\nfunction FromNever(schema, references, value) {\n return false;\n}\nfunction FromNot(schema, references, value) {\n return !Visit(schema.not, references, value);\n}\nfunction FromNull(schema, references, value) {\n return IsNull(value);\n}\nfunction FromNumber(schema, references, value) {\n if (!TypeSystemPolicy.IsNumberLike(value))\n return false;\n if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {\n return false;\n }\n if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {\n return false;\n }\n if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {\n return false;\n }\n if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {\n return false;\n }\n if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) {\n return false;\n }\n return true;\n}\nfunction FromObject(schema, references, value) {\n if (!TypeSystemPolicy.IsObjectLike(value))\n return false;\n if (IsDefined(schema.minProperties) && !(Object.getOwnPropertyNames(value).length >= schema.minProperties)) {\n return false;\n }\n if (IsDefined(schema.maxProperties) && !(Object.getOwnPropertyNames(value).length <= schema.maxProperties)) {\n return false;\n }\n const knownKeys = Object.getOwnPropertyNames(schema.properties);\n for (const knownKey of knownKeys) {\n const property = schema.properties[knownKey];\n if (schema.required && schema.required.includes(knownKey)) {\n if (!Visit(property, references, value[knownKey])) {\n return false;\n }\n if ((ExtendsUndefinedCheck(property) || IsAnyOrUnknown(property)) && !(knownKey in value)) {\n return false;\n }\n }\n else {\n if (TypeSystemPolicy.IsExactOptionalProperty(value, knownKey) && !Visit(property, references, value[knownKey])) {\n return false;\n }\n }\n }\n if (schema.additionalProperties === false) {\n const valueKeys = Object.getOwnPropertyNames(value);\n // optimization: value is valid if schemaKey length matches the valueKey length\n if (schema.required && schema.required.length === knownKeys.length && valueKeys.length === knownKeys.length) {\n return true;\n }\n else {\n return valueKeys.every((valueKey) => knownKeys.includes(valueKey));\n }\n }\n else if (typeof schema.additionalProperties === 'object') {\n const valueKeys = Object.getOwnPropertyNames(value);\n return valueKeys.every((key) => knownKeys.includes(key) || Visit(schema.additionalProperties, references, value[key]));\n }\n else {\n return true;\n }\n}\nfunction FromPromise(schema, references, value) {\n return IsPromise(value);\n}\nfunction FromRecord(schema, references, value) {\n if (!TypeSystemPolicy.IsRecordLike(value)) {\n return false;\n }\n if (IsDefined(schema.minProperties) && !(Object.getOwnPropertyNames(value).length >= schema.minProperties)) {\n return false;\n }\n if (IsDefined(schema.maxProperties) && !(Object.getOwnPropertyNames(value).length <= schema.maxProperties)) {\n return false;\n }\n const [patternKey, patternSchema] = Object.entries(schema.patternProperties)[0];\n const regex = new RegExp(patternKey);\n // prettier-ignore\n const check1 = Object.entries(value).every(([key, value]) => {\n return (regex.test(key)) ? Visit(patternSchema, references, value) : true;\n });\n // prettier-ignore\n const check2 = typeof schema.additionalProperties === 'object' ? Object.entries(value).every(([key, value]) => {\n return (!regex.test(key)) ? Visit(schema.additionalProperties, references, value) : true;\n }) : true;\n const check3 = schema.additionalProperties === false\n ? Object.getOwnPropertyNames(value).every((key) => {\n return regex.test(key);\n })\n : true;\n return check1 && check2 && check3;\n}\nfunction FromRef(schema, references, value) {\n return Visit(Deref(schema, references), references, value);\n}\nfunction FromRegExp(schema, references, value) {\n const regex = new RegExp(schema.source, schema.flags);\n if (IsDefined(schema.minLength)) {\n if (!(value.length >= schema.minLength))\n return false;\n }\n if (IsDefined(schema.maxLength)) {\n if (!(value.length <= schema.maxLength))\n return false;\n }\n return regex.test(value);\n}\nfunction FromString(schema, references, value) {\n if (!IsString(value)) {\n return false;\n }\n if (IsDefined(schema.minLength)) {\n if (!(value.length >= schema.minLength))\n return false;\n }\n if (IsDefined(schema.maxLength)) {\n if (!(value.length <= schema.maxLength))\n return false;\n }\n if (IsDefined(schema.pattern)) {\n const regex = new RegExp(schema.pattern);\n if (!regex.test(value))\n return false;\n }\n if (IsDefined(schema.format)) {\n if (!FormatRegistry.Has(schema.format))\n return false;\n const func = FormatRegistry.Get(schema.format);\n return func(value);\n }\n return true;\n}\nfunction FromSymbol(schema, references, value) {\n return IsSymbol(value);\n}\nfunction FromTemplateLiteral(schema, references, value) {\n return IsString(value) && new RegExp(schema.pattern).test(value);\n}\nfunction FromThis(schema, references, value) {\n return Visit(Deref(schema, references), references, value);\n}\nfunction FromTuple(schema, references, value) {\n if (!IsArray(value)) {\n return false;\n }\n if (schema.items === undefined && !(value.length === 0)) {\n return false;\n }\n if (!(value.length === schema.maxItems)) {\n return false;\n }\n if (!schema.items) {\n return true;\n }\n for (let i = 0; i < schema.items.length; i++) {\n if (!Visit(schema.items[i], references, value[i]))\n return false;\n }\n return true;\n}\nfunction FromUndefined(schema, references, value) {\n return IsUndefined(value);\n}\nfunction FromUnion(schema, references, value) {\n return schema.anyOf.some((inner) => Visit(inner, references, value));\n}\nfunction FromUint8Array(schema, references, value) {\n if (!IsUint8Array(value)) {\n return false;\n }\n if (IsDefined(schema.maxByteLength) && !(value.length <= schema.maxByteLength)) {\n return false;\n }\n if (IsDefined(schema.minByteLength) && !(value.length >= schema.minByteLength)) {\n return false;\n }\n return true;\n}\nfunction FromUnknown(schema, references, value) {\n return true;\n}\nfunction FromVoid(schema, references, value) {\n return TypeSystemPolicy.IsVoidLike(value);\n}\nfunction FromKind(schema, references, value) {\n if (!TypeRegistry.Has(schema[Kind]))\n return false;\n const func = TypeRegistry.Get(schema[Kind]);\n return func(schema, value);\n}\nfunction Visit(schema, references, value) {\n const references_ = IsDefined(schema.$id) ? Pushref(schema, references) : references;\n const schema_ = schema;\n switch (schema_[Kind]) {\n case 'Any':\n return FromAny(schema_, references_, value);\n case 'Array':\n return FromArray(schema_, references_, value);\n case 'AsyncIterator':\n return FromAsyncIterator(schema_, references_, value);\n case 'BigInt':\n return FromBigInt(schema_, references_, value);\n case 'Boolean':\n return FromBoolean(schema_, references_, value);\n case 'Constructor':\n return FromConstructor(schema_, references_, value);\n case 'Date':\n return FromDate(schema_, references_, value);\n case 'Function':\n return FromFunction(schema_, references_, value);\n case 'Import':\n return FromImport(schema_, references_, value);\n case 'Integer':\n return FromInteger(schema_, references_, value);\n case 'Intersect':\n return FromIntersect(schema_, references_, value);\n case 'Iterator':\n return FromIterator(schema_, references_, value);\n case 'Literal':\n return FromLiteral(schema_, references_, value);\n case 'Never':\n return FromNever(schema_, references_, value);\n case 'Not':\n return FromNot(schema_, references_, value);\n case 'Null':\n return FromNull(schema_, references_, value);\n case 'Number':\n return FromNumber(schema_, references_, value);\n case 'Object':\n return FromObject(schema_, references_, value);\n case 'Promise':\n return FromPromise(schema_, references_, value);\n case 'Record':\n return FromRecord(schema_, references_, value);\n case 'Ref':\n return FromRef(schema_, references_, value);\n case 'RegExp':\n return FromRegExp(schema_, references_, value);\n case 'String':\n return FromString(schema_, references_, value);\n case 'Symbol':\n return FromSymbol(schema_, references_, value);\n case 'TemplateLiteral':\n return FromTemplateLiteral(schema_, references_, value);\n case 'This':\n return FromThis(schema_, references_, value);\n case 'Tuple':\n return FromTuple(schema_, references_, value);\n case 'Undefined':\n return FromUndefined(schema_, references_, value);\n case 'Union':\n return FromUnion(schema_, references_, value);\n case 'Uint8Array':\n return FromUint8Array(schema_, references_, value);\n case 'Unknown':\n return FromUnknown(schema_, references_, value);\n case 'Void':\n return FromVoid(schema_, references_, value);\n default:\n if (!TypeRegistry.Has(schema_[Kind]))\n throw new ValueCheckUnknownTypeError(schema_);\n return FromKind(schema_, references_, value);\n }\n}\n/** Returns true if the value matches the given type. */\nexport function Check(...args) {\n return args.length === 3 ? Visit(args[0], args[1], args[2]) : Visit(args[0], [], args[1]);\n}\n","var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _AssertError_instances, _AssertError_iterator, _AssertError_Iterator;\nimport { Errors, ValueErrorIterator } from '../../errors/index.mjs';\nimport { TypeBoxError } from '../../type/error/error.mjs';\nimport { Check } from '../check/check.mjs';\n// ------------------------------------------------------------------\n// AssertError\n// ------------------------------------------------------------------\nexport class AssertError extends TypeBoxError {\n constructor(iterator) {\n const error = iterator.First();\n super(error === undefined ? 'Invalid Value' : error.message);\n _AssertError_instances.add(this);\n _AssertError_iterator.set(this, void 0);\n __classPrivateFieldSet(this, _AssertError_iterator, iterator, \"f\");\n this.error = error;\n }\n /** Returns an iterator for each error in this value. */\n Errors() {\n return new ValueErrorIterator(__classPrivateFieldGet(this, _AssertError_instances, \"m\", _AssertError_Iterator).call(this));\n }\n}\n_AssertError_iterator = new WeakMap(), _AssertError_instances = new WeakSet(), _AssertError_Iterator = function* _AssertError_Iterator() {\n if (this.error)\n yield this.error;\n yield* __classPrivateFieldGet(this, _AssertError_iterator, \"f\");\n};\n// ------------------------------------------------------------------\n// AssertValue\n// ------------------------------------------------------------------\nfunction AssertValue(schema, references, value) {\n if (Check(schema, references, value))\n return;\n throw new AssertError(Errors(schema, references, value));\n}\n/** Asserts a value matches the given type or throws an `AssertError` if invalid */\nexport function Assert(...args) {\n return args.length === 3 ? AssertValue(args[0], args[1], args[2]) : AssertValue(args[0], [], args[1]);\n}\n","// ------------------------------------------------------------------\n// ValueGuard\n// ------------------------------------------------------------------\nimport { IsArray, IsDate, IsMap, IsSet, IsObject, IsTypedArray, IsValueType } from '../guard/index.mjs';\n// ------------------------------------------------------------------\n// Clonable\n// ------------------------------------------------------------------\nfunction FromObject(value) {\n const Acc = {};\n for (const key of Object.getOwnPropertyNames(value)) {\n Acc[key] = Clone(value[key]);\n }\n for (const key of Object.getOwnPropertySymbols(value)) {\n Acc[key] = Clone(value[key]);\n }\n return Acc;\n}\nfunction FromArray(value) {\n return value.map((element) => Clone(element));\n}\nfunction FromTypedArray(value) {\n return value.slice();\n}\nfunction FromMap(value) {\n return new Map(Clone([...value.entries()]));\n}\nfunction FromSet(value) {\n return new Set(Clone([...value.entries()]));\n}\nfunction FromDate(value) {\n return new Date(value.toISOString());\n}\nfunction FromValue(value) {\n return value;\n}\n// ------------------------------------------------------------------\n// Clone\n// ------------------------------------------------------------------\n/** Returns a clone of the given value */\nexport function Clone(value) {\n if (IsArray(value))\n return FromArray(value);\n if (IsDate(value))\n return FromDate(value);\n if (IsTypedArray(value))\n return FromTypedArray(value);\n if (IsMap(value))\n return FromMap(value);\n if (IsSet(value))\n return FromSet(value);\n if (IsObject(value))\n return FromObject(value);\n if (IsValueType(value))\n return FromValue(value);\n throw new Error('ValueClone: Unable to clone value');\n}\n","import { KeyOfPropertyKeys } from '../../type/keyof/index.mjs';\nimport { Check } from '../check/index.mjs';\nimport { Clone } from '../clone/index.mjs';\nimport { Deref, Pushref } from '../deref/index.mjs';\nimport { Kind } from '../../type/symbols/index.mjs';\n// ------------------------------------------------------------------\n// ValueGuard\n// ------------------------------------------------------------------\n// prettier-ignore\nimport { HasPropertyKey, IsString, IsObject, IsArray, IsUndefined } from '../guard/index.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\n// prettier-ignore\nimport { IsKind } from '../../type/guard/kind.mjs';\n// ------------------------------------------------------------------\n// IsCheckable\n// ------------------------------------------------------------------\nfunction IsCheckable(schema) {\n return IsKind(schema) && schema[Kind] !== 'Unsafe';\n}\n// ------------------------------------------------------------------\n// Types\n// ------------------------------------------------------------------\nfunction FromArray(schema, references, value) {\n if (!IsArray(value))\n return value;\n return value.map((value) => Visit(schema.items, references, value));\n}\nfunction FromImport(schema, references, value) {\n const definitions = globalThis.Object.values(schema.$defs);\n const target = schema.$defs[schema.$ref];\n return Visit(target, [...references, ...definitions], value);\n}\nfunction FromIntersect(schema, references, value) {\n const unevaluatedProperties = schema.unevaluatedProperties;\n const intersections = schema.allOf.map((schema) => Visit(schema, references, Clone(value)));\n const composite = intersections.reduce((acc, value) => (IsObject(value) ? { ...acc, ...value } : value), {});\n if (!IsObject(value) || !IsObject(composite) || !IsKind(unevaluatedProperties))\n return composite;\n const knownkeys = KeyOfPropertyKeys(schema);\n for (const key of Object.getOwnPropertyNames(value)) {\n if (knownkeys.includes(key))\n continue;\n if (Check(unevaluatedProperties, references, value[key])) {\n composite[key] = Visit(unevaluatedProperties, references, value[key]);\n }\n }\n return composite;\n}\nfunction FromObject(schema, references, value) {\n if (!IsObject(value) || IsArray(value))\n return value; // Check IsArray for AllowArrayObject configuration\n const additionalProperties = schema.additionalProperties;\n for (const key of Object.getOwnPropertyNames(value)) {\n if (HasPropertyKey(schema.properties, key)) {\n value[key] = Visit(schema.properties[key], references, value[key]);\n continue;\n }\n if (IsKind(additionalProperties) && Check(additionalProperties, references, value[key])) {\n value[key] = Visit(additionalProperties, references, value[key]);\n continue;\n }\n delete value[key];\n }\n return value;\n}\nfunction FromRecord(schema, references, value) {\n if (!IsObject(value))\n return value;\n const additionalProperties = schema.additionalProperties;\n const propertyKeys = Object.getOwnPropertyNames(value);\n const [propertyKey, propertySchema] = Object.entries(schema.patternProperties)[0];\n const propertyKeyTest = new RegExp(propertyKey);\n for (const key of propertyKeys) {\n if (propertyKeyTest.test(key)) {\n value[key] = Visit(propertySchema, references, value[key]);\n continue;\n }\n if (IsKind(additionalProperties) && Check(additionalProperties, references, value[key])) {\n value[key] = Visit(additionalProperties, references, value[key]);\n continue;\n }\n delete value[key];\n }\n return value;\n}\nfunction FromRef(schema, references, value) {\n return Visit(Deref(schema, references), references, value);\n}\nfunction FromThis(schema, references, value) {\n return Visit(Deref(schema, references), references, value);\n}\nfunction FromTuple(schema, references, value) {\n if (!IsArray(value))\n return value;\n if (IsUndefined(schema.items))\n return [];\n const length = Math.min(value.length, schema.items.length);\n for (let i = 0; i < length; i++) {\n value[i] = Visit(schema.items[i], references, value[i]);\n }\n // prettier-ignore\n return value.length > length\n ? value.slice(0, length)\n : value;\n}\nfunction FromUnion(schema, references, value) {\n for (const inner of schema.anyOf) {\n if (IsCheckable(inner) && Check(inner, references, value)) {\n return Visit(inner, references, value);\n }\n }\n return value;\n}\nfunction Visit(schema, references, value) {\n const references_ = IsString(schema.$id) ? Pushref(schema, references) : references;\n const schema_ = schema;\n switch (schema_[Kind]) {\n case 'Array':\n return FromArray(schema_, references_, value);\n case 'Import':\n return FromImport(schema_, references_, value);\n case 'Intersect':\n return FromIntersect(schema_, references_, value);\n case 'Object':\n return FromObject(schema_, references_, value);\n case 'Record':\n return FromRecord(schema_, references_, value);\n case 'Ref':\n return FromRef(schema_, references_, value);\n case 'This':\n return FromThis(schema_, references_, value);\n case 'Tuple':\n return FromTuple(schema_, references_, value);\n case 'Union':\n return FromUnion(schema_, references_, value);\n default:\n return value;\n }\n}\n/** `[Mutable]` Removes excess properties from a value and returns the result. This function does not check the value and returns an unknown type. You should Check the result before use. Clean is a mutable operation. To avoid mutation, Clone the value first. */\nexport function Clean(...args) {\n return args.length === 3 ? Visit(args[0], args[1], args[2]) : Visit(args[0], [], args[1]);\n}\n","import { Clone } from '../clone/index.mjs';\nimport { Check } from '../check/index.mjs';\nimport { Deref, Pushref } from '../deref/index.mjs';\nimport { Kind } from '../../type/symbols/index.mjs';\n// ------------------------------------------------------------------\n// ValueGuard\n// ------------------------------------------------------------------\nimport { IsArray, IsObject, IsDate, IsUndefined, IsString, IsNumber, IsBoolean, IsBigInt, IsSymbol, HasPropertyKey } from '../guard/index.mjs';\n// ------------------------------------------------------------------\n// Conversions\n// ------------------------------------------------------------------\nfunction IsStringNumeric(value) {\n return IsString(value) && !isNaN(value) && !isNaN(parseFloat(value));\n}\nfunction IsValueToString(value) {\n return IsBigInt(value) || IsBoolean(value) || IsNumber(value);\n}\nfunction IsValueTrue(value) {\n return value === true || (IsNumber(value) && value === 1) || (IsBigInt(value) && value === BigInt('1')) || (IsString(value) && (value.toLowerCase() === 'true' || value === '1'));\n}\nfunction IsValueFalse(value) {\n return value === false || (IsNumber(value) && (value === 0 || Object.is(value, -0))) || (IsBigInt(value) && value === BigInt('0')) || (IsString(value) && (value.toLowerCase() === 'false' || value === '0' || value === '-0'));\n}\nfunction IsTimeStringWithTimeZone(value) {\n return IsString(value) && /^(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)$/i.test(value);\n}\nfunction IsTimeStringWithoutTimeZone(value) {\n return IsString(value) && /^(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)?$/i.test(value);\n}\nfunction IsDateTimeStringWithTimeZone(value) {\n return IsString(value) && /^\\d\\d\\d\\d-[0-1]\\d-[0-3]\\dt(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)$/i.test(value);\n}\nfunction IsDateTimeStringWithoutTimeZone(value) {\n return IsString(value) && /^\\d\\d\\d\\d-[0-1]\\d-[0-3]\\dt(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)?$/i.test(value);\n}\nfunction IsDateString(value) {\n return IsString(value) && /^\\d\\d\\d\\d-[0-1]\\d-[0-3]\\d$/i.test(value);\n}\n// ------------------------------------------------------------------\n// Convert\n// ------------------------------------------------------------------\nfunction TryConvertLiteralString(value, target) {\n const conversion = TryConvertString(value);\n return conversion === target ? conversion : value;\n}\nfunction TryConvertLiteralNumber(value, target) {\n const conversion = TryConvertNumber(value);\n return conversion === target ? conversion : value;\n}\nfunction TryConvertLiteralBoolean(value, target) {\n const conversion = TryConvertBoolean(value);\n return conversion === target ? conversion : value;\n}\n// prettier-ignore\nfunction TryConvertLiteral(schema, value) {\n return (IsString(schema.const) ? TryConvertLiteralString(value, schema.const) :\n IsNumber(schema.const) ? TryConvertLiteralNumber(value, schema.const) :\n IsBoolean(schema.const) ? TryConvertLiteralBoolean(value, schema.const) :\n value);\n}\nfunction TryConvertBoolean(value) {\n return IsValueTrue(value) ? true : IsValueFalse(value) ? false : value;\n}\nfunction TryConvertBigInt(value) {\n const truncateInteger = (value) => value.split('.')[0];\n return IsStringNumeric(value) ? BigInt(truncateInteger(value)) : IsNumber(value) ? BigInt(Math.trunc(value)) : IsValueFalse(value) ? BigInt(0) : IsValueTrue(value) ? BigInt(1) : value;\n}\nfunction TryConvertString(value) {\n return IsSymbol(value) && value.description !== undefined ? value.description.toString() : IsValueToString(value) ? value.toString() : value;\n}\nfunction TryConvertNumber(value) {\n return IsStringNumeric(value) ? parseFloat(value) : IsValueTrue(value) ? 1 : IsValueFalse(value) ? 0 : value;\n}\nfunction TryConvertInteger(value) {\n return IsStringNumeric(value) ? parseInt(value) : IsNumber(value) ? Math.trunc(value) : IsValueTrue(value) ? 1 : IsValueFalse(value) ? 0 : value;\n}\nfunction TryConvertNull(value) {\n return IsString(value) && value.toLowerCase() === 'null' ? null : value;\n}\nfunction TryConvertUndefined(value) {\n return IsString(value) && value === 'undefined' ? undefined : value;\n}\n// ------------------------------------------------------------------\n// note: this function may return an invalid dates for the regex\n// tests above. Invalid dates will however be checked during the\n// casting function and will return a epoch date if invalid.\n// Consider better string parsing for the iso dates in future\n// revisions.\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction TryConvertDate(value) {\n return (IsDate(value) ? value :\n IsNumber(value) ? new Date(value) :\n IsValueTrue(value) ? new Date(1) :\n IsValueFalse(value) ? new Date(0) :\n IsStringNumeric(value) ? new Date(parseInt(value)) :\n IsTimeStringWithoutTimeZone(value) ? new Date(`1970-01-01T${value}.000Z`) :\n IsTimeStringWithTimeZone(value) ? new Date(`1970-01-01T${value}`) :\n IsDateTimeStringWithoutTimeZone(value) ? new Date(`${value}.000Z`) :\n IsDateTimeStringWithTimeZone(value) ? new Date(value) :\n IsDateString(value) ? new Date(`${value}T00:00:00.000Z`) :\n value);\n}\n// ------------------------------------------------------------------\n// Default\n// ------------------------------------------------------------------\nfunction Default(value) {\n return value;\n}\n// ------------------------------------------------------------------\n// Convert\n// ------------------------------------------------------------------\nfunction FromArray(schema, references, value) {\n const elements = IsArray(value) ? value : [value];\n return elements.map((element) => Visit(schema.items, references, element));\n}\nfunction FromBigInt(schema, references, value) {\n return TryConvertBigInt(value);\n}\nfunction FromBoolean(schema, references, value) {\n return TryConvertBoolean(value);\n}\nfunction FromDate(schema, references, value) {\n return TryConvertDate(value);\n}\nfunction FromImport(schema, references, value) {\n const definitions = globalThis.Object.values(schema.$defs);\n const target = schema.$defs[schema.$ref];\n return Visit(target, [...references, ...definitions], value);\n}\nfunction FromInteger(schema, references, value) {\n return TryConvertInteger(value);\n}\nfunction FromIntersect(schema, references, value) {\n return schema.allOf.reduce((value, schema) => Visit(schema, references, value), value);\n}\nfunction FromLiteral(schema, references, value) {\n return TryConvertLiteral(schema, value);\n}\nfunction FromNull(schema, references, value) {\n return TryConvertNull(value);\n}\nfunction FromNumber(schema, references, value) {\n return TryConvertNumber(value);\n}\n// prettier-ignore\nfunction FromObject(schema, references, value) {\n if (!IsObject(value))\n return value;\n for (const propertyKey of Object.getOwnPropertyNames(schema.properties)) {\n if (!HasPropertyKey(value, propertyKey))\n continue;\n value[propertyKey] = Visit(schema.properties[propertyKey], references, value[propertyKey]);\n }\n return value;\n}\nfunction FromRecord(schema, references, value) {\n const isConvertable = IsObject(value);\n if (!isConvertable)\n return value;\n const propertyKey = Object.getOwnPropertyNames(schema.patternProperties)[0];\n const property = schema.patternProperties[propertyKey];\n for (const [propKey, propValue] of Object.entries(value)) {\n value[propKey] = Visit(property, references, propValue);\n }\n return value;\n}\nfunction FromRef(schema, references, value) {\n return Visit(Deref(schema, references), references, value);\n}\nfunction FromString(schema, references, value) {\n return TryConvertString(value);\n}\nfunction FromSymbol(schema, references, value) {\n return IsString(value) || IsNumber(value) ? Symbol(value) : value;\n}\nfunction FromThis(schema, references, value) {\n return Visit(Deref(schema, references), references, value);\n}\n// prettier-ignore\nfunction FromTuple(schema, references, value) {\n const isConvertable = IsArray(value) && !IsUndefined(schema.items);\n if (!isConvertable)\n return value;\n return value.map((value, index) => {\n return (index < schema.items.length)\n ? Visit(schema.items[index], references, value)\n : value;\n });\n}\nfunction FromUndefined(schema, references, value) {\n return TryConvertUndefined(value);\n}\nfunction FromUnion(schema, references, value) {\n for (const subschema of schema.anyOf) {\n const converted = Visit(subschema, references, Clone(value));\n if (!Check(subschema, references, converted))\n continue;\n return converted;\n }\n return value;\n}\nfunction Visit(schema, references, value) {\n const references_ = Pushref(schema, references);\n const schema_ = schema;\n switch (schema[Kind]) {\n case 'Array':\n return FromArray(schema_, references_, value);\n case 'BigInt':\n return FromBigInt(schema_, references_, value);\n case 'Boolean':\n return FromBoolean(schema_, references_, value);\n case 'Date':\n return FromDate(schema_, references_, value);\n case 'Import':\n return FromImport(schema_, references_, value);\n case 'Integer':\n return FromInteger(schema_, references_, value);\n case 'Intersect':\n return FromIntersect(schema_, references_, value);\n case 'Literal':\n return FromLiteral(schema_, references_, value);\n case 'Null':\n return FromNull(schema_, references_, value);\n case 'Number':\n return FromNumber(schema_, references_, value);\n case 'Object':\n return FromObject(schema_, references_, value);\n case 'Record':\n return FromRecord(schema_, references_, value);\n case 'Ref':\n return FromRef(schema_, references_, value);\n case 'String':\n return FromString(schema_, references_, value);\n case 'Symbol':\n return FromSymbol(schema_, references_, value);\n case 'This':\n return FromThis(schema_, references_, value);\n case 'Tuple':\n return FromTuple(schema_, references_, value);\n case 'Undefined':\n return FromUndefined(schema_, references_, value);\n case 'Union':\n return FromUnion(schema_, references_, value);\n default:\n return Default(value);\n }\n}\n/** `[Mutable]` Converts any type mismatched values to their target type if a reasonable conversion is possible. */\n// prettier-ignore\nexport function Convert(...args) {\n return args.length === 3 ? Visit(args[0], args[1], args[2]) : Visit(args[0], [], args[1]);\n}\n","import { TypeSystemPolicy } from '../../system/policy.mjs';\nimport { Kind, TransformKind } from '../../type/symbols/index.mjs';\nimport { TypeBoxError } from '../../type/error/index.mjs';\nimport { KeyOfPropertyKeys, KeyOfPropertyEntries } from '../../type/keyof/index.mjs';\nimport { Deref, Pushref } from '../deref/index.mjs';\nimport { Check } from '../check/index.mjs';\n// ------------------------------------------------------------------\n// ValueGuard\n// ------------------------------------------------------------------\nimport { HasPropertyKey, IsObject, IsArray, IsValueType, IsUndefined as IsUndefinedValue } from '../guard/index.mjs';\n// ------------------------------------------------------------------\n// KindGuard\n// ------------------------------------------------------------------\nimport { IsTransform, IsSchema, IsUndefined } from '../../type/guard/kind.mjs';\n// ------------------------------------------------------------------\n// Errors\n// ------------------------------------------------------------------\n// thrown externally\n// prettier-ignore\nexport class TransformDecodeCheckError extends TypeBoxError {\n constructor(schema, value, error) {\n super(`Unable to decode value as it does not match the expected schema`);\n this.schema = schema;\n this.value = value;\n this.error = error;\n }\n}\n// prettier-ignore\nexport class TransformDecodeError extends TypeBoxError {\n constructor(schema, path, value, error) {\n super(error instanceof Error ? error.message : 'Unknown error');\n this.schema = schema;\n this.path = path;\n this.value = value;\n this.error = error;\n }\n}\n// ------------------------------------------------------------------\n// Decode\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction Default(schema, path, value) {\n try {\n return IsTransform(schema) ? schema[TransformKind].Decode(value) : value;\n }\n catch (error) {\n throw new TransformDecodeError(schema, path, value, error);\n }\n}\n// prettier-ignore\nfunction FromArray(schema, references, path, value) {\n return (IsArray(value))\n ? Default(schema, path, value.map((value, index) => Visit(schema.items, references, `${path}/${index}`, value)))\n : Default(schema, path, value);\n}\n// prettier-ignore\nfunction FromIntersect(schema, references, path, value) {\n if (!IsObject(value) || IsValueType(value))\n return Default(schema, path, value);\n const knownEntries = KeyOfPropertyEntries(schema);\n const knownKeys = knownEntries.map(entry => entry[0]);\n const knownProperties = { ...value };\n for (const [knownKey, knownSchema] of knownEntries)\n if (knownKey in knownProperties) {\n knownProperties[knownKey] = Visit(knownSchema, references, `${path}/${knownKey}`, knownProperties[knownKey]);\n }\n if (!IsTransform(schema.unevaluatedProperties)) {\n return Default(schema, path, knownProperties);\n }\n const unknownKeys = Object.getOwnPropertyNames(knownProperties);\n const unevaluatedProperties = schema.unevaluatedProperties;\n const unknownProperties = { ...knownProperties };\n for (const key of unknownKeys)\n if (!knownKeys.includes(key)) {\n unknownProperties[key] = Default(unevaluatedProperties, `${path}/${key}`, unknownProperties[key]);\n }\n return Default(schema, path, unknownProperties);\n}\n// prettier-ignore\nfunction FromImport(schema, references, path, value) {\n const definitions = globalThis.Object.values(schema.$defs);\n const target = schema.$defs[schema.$ref];\n const transform = schema[TransformKind];\n // Note: we need to re-spec the target as TSchema + [TransformKind]\n const transformTarget = { [TransformKind]: transform, ...target };\n return Visit(transformTarget, [...references, ...definitions], path, value);\n}\nfunction FromNot(schema, references, path, value) {\n return Default(schema, path, Visit(schema.not, references, path, value));\n}\n// prettier-ignore\nfunction FromObject(schema, references, path, value) {\n if (!IsObject(value))\n return Default(schema, path, value);\n const knownKeys = KeyOfPropertyKeys(schema);\n const knownProperties = { ...value };\n for (const key of knownKeys) {\n if (!HasPropertyKey(knownProperties, key))\n continue;\n // if the property value is undefined, but the target is not, nor does it satisfy exact optional \n // property policy, then we need to continue. This is a special case for optional property handling \n // where a transforms wrapped in a optional modifiers should not run.\n if (IsUndefinedValue(knownProperties[key]) && (!IsUndefined(schema.properties[key]) ||\n TypeSystemPolicy.IsExactOptionalProperty(knownProperties, key)))\n continue;\n // decode property\n knownProperties[key] = Visit(schema.properties[key], references, `${path}/${key}`, knownProperties[key]);\n }\n if (!IsSchema(schema.additionalProperties)) {\n return Default(schema, path, knownProperties);\n }\n const unknownKeys = Object.getOwnPropertyNames(knownProperties);\n const additionalProperties = schema.additionalProperties;\n const unknownProperties = { ...knownProperties };\n for (const key of unknownKeys)\n if (!knownKeys.includes(key)) {\n unknownProperties[key] = Default(additionalProperties, `${path}/${key}`, unknownProperties[key]);\n }\n return Default(schema, path, unknownProperties);\n}\n// prettier-ignore\nfunction FromRecord(schema, references, path, value) {\n if (!IsObject(value))\n return Default(schema, path, value);\n const pattern = Object.getOwnPropertyNames(schema.patternProperties)[0];\n const knownKeys = new RegExp(pattern);\n const knownProperties = { ...value };\n for (const key of Object.getOwnPropertyNames(value))\n if (knownKeys.test(key)) {\n knownProperties[key] = Visit(schema.patternProperties[pattern], references, `${path}/${key}`, knownProperties[key]);\n }\n if (!IsSchema(schema.additionalProperties)) {\n return Default(schema, path, knownProperties);\n }\n const unknownKeys = Object.getOwnPropertyNames(knownProperties);\n const additionalProperties = schema.additionalProperties;\n const unknownProperties = { ...knownProperties };\n for (const key of unknownKeys)\n if (!knownKeys.test(key)) {\n unknownProperties[key] = Default(additionalProperties, `${path}/${key}`, unknownProperties[key]);\n }\n return Default(schema, path, unknownProperties);\n}\n// prettier-ignore\nfunction FromRef(schema, references, path, value) {\n const target = Deref(schema, references);\n return Default(schema, path, Visit(target, references, path, value));\n}\n// prettier-ignore\nfunction FromThis(schema, references, path, value) {\n const target = Deref(schema, references);\n return Default(schema, path, Visit(target, references, path, value));\n}\n// prettier-ignore\nfunction FromTuple(schema, references, path, value) {\n return (IsArray(value) && IsArray(schema.items))\n ? Default(schema, path, schema.items.map((schema, index) => Visit(schema, references, `${path}/${index}`, value[index])))\n : Default(schema, path, value);\n}\n// prettier-ignore\nfunction FromUnion(schema, references, path, value) {\n for (const subschema of schema.anyOf) {\n if (!Check(subschema, references, value))\n continue;\n // note: ensure interior is decoded first\n const decoded = Visit(subschema, references, path, value);\n return Default(schema, path, decoded);\n }\n return Default(schema, path, value);\n}\n// prettier-ignore\nfunction Visit(schema, references, path, value) {\n const references_ = Pushref(schema, references);\n const schema_ = schema;\n switch (schema[Kind]) {\n case 'Array':\n return FromArray(schema_, references_, path, value);\n case 'Import':\n return FromImport(schema_, references_, path, value);\n case 'Intersect':\n return FromIntersect(schema_, references_, path, value);\n case 'Not':\n return FromNot(schema_, references_, path, value);\n case 'Object':\n return FromObject(schema_, references_, path, value);\n case 'Record':\n return FromRecord(schema_, references_, path, value);\n case 'Ref':\n return FromRef(schema_, references_, path, value);\n case 'Symbol':\n return Default(schema_, path, value);\n case 'This':\n return FromThis(schema_, references_, path, value);\n case 'Tuple':\n return FromTuple(schema_, references_, path, value);\n case 'Union':\n return FromUnion(schema_, references_, path, value);\n default:\n return Default(schema_, path, value);\n }\n}\n/**\n * `[Internal]` Decodes the value and returns the result. This function requires that\n * the caller `Check` the value before use. Passing unchecked values may result in\n * undefined behavior. Refer to the `Value.Decode()` for implementation details.\n */\nexport function TransformDecode(schema, references, value) {\n return Visit(schema, references, '', value);\n}\n","import { TypeSystemPolicy } from '../../system/policy.mjs';\nimport { Kind, TransformKind } from '../../type/symbols/index.mjs';\nimport { TypeBoxError } from '../../type/error/index.mjs';\nimport { KeyOfPropertyKeys, KeyOfPropertyEntries } from '../../type/keyof/index.mjs';\nimport { Deref, Pushref } from '../deref/index.mjs';\nimport { Check } from '../check/index.mjs';\n// ------------------------------------------------------------------\n// ValueGuard\n// ------------------------------------------------------------------\nimport { HasPropertyKey, IsObject, IsArray, IsValueType, IsUndefined as IsUndefinedValue } from '../guard/index.mjs';\n// ------------------------------------------------------------------\n// KindGuard\n// ------------------------------------------------------------------\nimport { IsTransform, IsSchema, IsUndefined } from '../../type/guard/kind.mjs';\n// ------------------------------------------------------------------\n// Errors\n// ------------------------------------------------------------------\n// prettier-ignore\nexport class TransformEncodeCheckError extends TypeBoxError {\n constructor(schema, value, error) {\n super(`The encoded value does not match the expected schema`);\n this.schema = schema;\n this.value = value;\n this.error = error;\n }\n}\n// prettier-ignore\nexport class TransformEncodeError extends TypeBoxError {\n constructor(schema, path, value, error) {\n super(`${error instanceof Error ? error.message : 'Unknown error'}`);\n this.schema = schema;\n this.path = path;\n this.value = value;\n this.error = error;\n }\n}\n// ------------------------------------------------------------------\n// Encode\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction Default(schema, path, value) {\n try {\n return IsTransform(schema) ? schema[TransformKind].Encode(value) : value;\n }\n catch (error) {\n throw new TransformEncodeError(schema, path, value, error);\n }\n}\n// prettier-ignore\nfunction FromArray(schema, references, path, value) {\n const defaulted = Default(schema, path, value);\n return IsArray(defaulted)\n ? defaulted.map((value, index) => Visit(schema.items, references, `${path}/${index}`, value))\n : defaulted;\n}\n// prettier-ignore\nfunction FromImport(schema, references, path, value) {\n const definitions = globalThis.Object.values(schema.$defs);\n const target = schema.$defs[schema.$ref];\n const transform = schema[TransformKind];\n // Note: we need to re-spec the target as TSchema + [TransformKind]\n const transformTarget = { [TransformKind]: transform, ...target };\n return Visit(transformTarget, [...references, ...definitions], path, value);\n}\n// prettier-ignore\nfunction FromIntersect(schema, references, path, value) {\n const defaulted = Default(schema, path, value);\n if (!IsObject(value) || IsValueType(value))\n return defaulted;\n const knownEntries = KeyOfPropertyEntries(schema);\n const knownKeys = knownEntries.map(entry => entry[0]);\n const knownProperties = { ...defaulted };\n for (const [knownKey, knownSchema] of knownEntries)\n if (knownKey in knownProperties) {\n knownProperties[knownKey] = Visit(knownSchema, references, `${path}/${knownKey}`, knownProperties[knownKey]);\n }\n if (!IsTransform(schema.unevaluatedProperties)) {\n return knownProperties;\n }\n const unknownKeys = Object.getOwnPropertyNames(knownProperties);\n const unevaluatedProperties = schema.unevaluatedProperties;\n const properties = { ...knownProperties };\n for (const key of unknownKeys)\n if (!knownKeys.includes(key)) {\n properties[key] = Default(unevaluatedProperties, `${path}/${key}`, properties[key]);\n }\n return properties;\n}\n// prettier-ignore\nfunction FromNot(schema, references, path, value) {\n return Default(schema.not, path, Default(schema, path, value));\n}\n// prettier-ignore\nfunction FromObject(schema, references, path, value) {\n const defaulted = Default(schema, path, value);\n if (!IsObject(defaulted))\n return defaulted;\n const knownKeys = KeyOfPropertyKeys(schema);\n const knownProperties = { ...defaulted };\n for (const key of knownKeys) {\n if (!HasPropertyKey(knownProperties, key))\n continue;\n // if the property value is undefined, but the target is not, nor does it satisfy exact optional \n // property policy, then we need to continue. This is a special case for optional property handling \n // where a transforms wrapped in a optional modifiers should not run.\n if (IsUndefinedValue(knownProperties[key]) && (!IsUndefined(schema.properties[key]) ||\n TypeSystemPolicy.IsExactOptionalProperty(knownProperties, key)))\n continue;\n // encode property\n knownProperties[key] = Visit(schema.properties[key], references, `${path}/${key}`, knownProperties[key]);\n }\n if (!IsSchema(schema.additionalProperties)) {\n return knownProperties;\n }\n const unknownKeys = Object.getOwnPropertyNames(knownProperties);\n const additionalProperties = schema.additionalProperties;\n const properties = { ...knownProperties };\n for (const key of unknownKeys)\n if (!knownKeys.includes(key)) {\n properties[key] = Default(additionalProperties, `${path}/${key}`, properties[key]);\n }\n return properties;\n}\n// prettier-ignore\nfunction FromRecord(schema, references, path, value) {\n const defaulted = Default(schema, path, value);\n if (!IsObject(value))\n return defaulted;\n const pattern = Object.getOwnPropertyNames(schema.patternProperties)[0];\n const knownKeys = new RegExp(pattern);\n const knownProperties = { ...defaulted };\n for (const key of Object.getOwnPropertyNames(value))\n if (knownKeys.test(key)) {\n knownProperties[key] = Visit(schema.patternProperties[pattern], references, `${path}/${key}`, knownProperties[key]);\n }\n if (!IsSchema(schema.additionalProperties)) {\n return knownProperties;\n }\n const unknownKeys = Object.getOwnPropertyNames(knownProperties);\n const additionalProperties = schema.additionalProperties;\n const properties = { ...knownProperties };\n for (const key of unknownKeys)\n if (!knownKeys.test(key)) {\n properties[key] = Default(additionalProperties, `${path}/${key}`, properties[key]);\n }\n return properties;\n}\n// prettier-ignore\nfunction FromRef(schema, references, path, value) {\n const target = Deref(schema, references);\n const resolved = Visit(target, references, path, value);\n return Default(schema, path, resolved);\n}\n// prettier-ignore\nfunction FromThis(schema, references, path, value) {\n const target = Deref(schema, references);\n const resolved = Visit(target, references, path, value);\n return Default(schema, path, resolved);\n}\n// prettier-ignore\nfunction FromTuple(schema, references, path, value) {\n const value1 = Default(schema, path, value);\n return IsArray(schema.items) ? schema.items.map((schema, index) => Visit(schema, references, `${path}/${index}`, value1[index])) : [];\n}\n// prettier-ignore\nfunction FromUnion(schema, references, path, value) {\n // test value against union variants\n for (const subschema of schema.anyOf) {\n if (!Check(subschema, references, value))\n continue;\n const value1 = Visit(subschema, references, path, value);\n return Default(schema, path, value1);\n }\n // test transformed value against union variants\n for (const subschema of schema.anyOf) {\n const value1 = Visit(subschema, references, path, value);\n if (!Check(schema, references, value1))\n continue;\n return Default(schema, path, value1);\n }\n return Default(schema, path, value);\n}\n// prettier-ignore\nfunction Visit(schema, references, path, value) {\n const references_ = Pushref(schema, references);\n const schema_ = schema;\n switch (schema[Kind]) {\n case 'Array':\n return FromArray(schema_, references_, path, value);\n case 'Import':\n return FromImport(schema_, references_, path, value);\n case 'Intersect':\n return FromIntersect(schema_, references_, path, value);\n case 'Not':\n return FromNot(schema_, references_, path, value);\n case 'Object':\n return FromObject(schema_, references_, path, value);\n case 'Record':\n return FromRecord(schema_, references_, path, value);\n case 'Ref':\n return FromRef(schema_, references_, path, value);\n case 'This':\n return FromThis(schema_, references_, path, value);\n case 'Tuple':\n return FromTuple(schema_, references_, path, value);\n case 'Union':\n return FromUnion(schema_, references_, path, value);\n default:\n return Default(schema_, path, value);\n }\n}\n/**\n * `[Internal]` Encodes the value and returns the result. This function expects the\n * caller to pass a statically checked value. This function does not check the encoded\n * result, meaning the result should be passed to `Check` before use. Refer to the\n * `Value.Encode()` function for implementation details.\n */\nexport function TransformEncode(schema, references, value) {\n return Visit(schema, references, '', value);\n}\n","import { Deref, Pushref } from '../deref/index.mjs';\nimport { Kind } from '../../type/symbols/index.mjs';\n// ------------------------------------------------------------------\n// KindGuard\n// ------------------------------------------------------------------\nimport { IsTransform, IsSchema } from '../../type/guard/kind.mjs';\n// ------------------------------------------------------------------\n// ValueGuard\n// ------------------------------------------------------------------\nimport { IsUndefined } from '../guard/index.mjs';\n// prettier-ignore\nfunction FromArray(schema, references) {\n return IsTransform(schema) || Visit(schema.items, references);\n}\n// prettier-ignore\nfunction FromAsyncIterator(schema, references) {\n return IsTransform(schema) || Visit(schema.items, references);\n}\n// prettier-ignore\nfunction FromConstructor(schema, references) {\n return IsTransform(schema) || Visit(schema.returns, references) || schema.parameters.some((schema) => Visit(schema, references));\n}\n// prettier-ignore\nfunction FromFunction(schema, references) {\n return IsTransform(schema) || Visit(schema.returns, references) || schema.parameters.some((schema) => Visit(schema, references));\n}\n// prettier-ignore\nfunction FromIntersect(schema, references) {\n return IsTransform(schema) || IsTransform(schema.unevaluatedProperties) || schema.allOf.some((schema) => Visit(schema, references));\n}\n// prettier-ignore\nfunction FromIterator(schema, references) {\n return IsTransform(schema) || Visit(schema.items, references);\n}\n// prettier-ignore\nfunction FromNot(schema, references) {\n return IsTransform(schema) || Visit(schema.not, references);\n}\n// prettier-ignore\nfunction FromObject(schema, references) {\n return (IsTransform(schema) ||\n Object.values(schema.properties).some((schema) => Visit(schema, references)) ||\n (IsSchema(schema.additionalProperties) && Visit(schema.additionalProperties, references)));\n}\n// prettier-ignore\nfunction FromPromise(schema, references) {\n return IsTransform(schema) || Visit(schema.item, references);\n}\n// prettier-ignore\nfunction FromRecord(schema, references) {\n const pattern = Object.getOwnPropertyNames(schema.patternProperties)[0];\n const property = schema.patternProperties[pattern];\n return IsTransform(schema) || Visit(property, references) || (IsSchema(schema.additionalProperties) && IsTransform(schema.additionalProperties));\n}\n// prettier-ignore\nfunction FromRef(schema, references) {\n if (IsTransform(schema))\n return true;\n return Visit(Deref(schema, references), references);\n}\n// prettier-ignore\nfunction FromThis(schema, references) {\n if (IsTransform(schema))\n return true;\n return Visit(Deref(schema, references), references);\n}\n// prettier-ignore\nfunction FromTuple(schema, references) {\n return IsTransform(schema) || (!IsUndefined(schema.items) && schema.items.some((schema) => Visit(schema, references)));\n}\n// prettier-ignore\nfunction FromUnion(schema, references) {\n return IsTransform(schema) || schema.anyOf.some((schema) => Visit(schema, references));\n}\n// prettier-ignore\nfunction Visit(schema, references) {\n const references_ = Pushref(schema, references);\n const schema_ = schema;\n if (schema.$id && visited.has(schema.$id))\n return false;\n if (schema.$id)\n visited.add(schema.$id);\n switch (schema[Kind]) {\n case 'Array':\n return FromArray(schema_, references_);\n case 'AsyncIterator':\n return FromAsyncIterator(schema_, references_);\n case 'Constructor':\n return FromConstructor(schema_, references_);\n case 'Function':\n return FromFunction(schema_, references_);\n case 'Intersect':\n return FromIntersect(schema_, references_);\n case 'Iterator':\n return FromIterator(schema_, references_);\n case 'Not':\n return FromNot(schema_, references_);\n case 'Object':\n return FromObject(schema_, references_);\n case 'Promise':\n return FromPromise(schema_, references_);\n case 'Record':\n return FromRecord(schema_, references_);\n case 'Ref':\n return FromRef(schema_, references_);\n case 'This':\n return FromThis(schema_, references_);\n case 'Tuple':\n return FromTuple(schema_, references_);\n case 'Union':\n return FromUnion(schema_, references_);\n default:\n return IsTransform(schema);\n }\n}\nconst visited = new Set();\n/** Returns true if this schema contains a transform codec */\nexport function HasTransform(schema, references) {\n visited.clear();\n return Visit(schema, references);\n}\n","import { Check } from '../check/index.mjs';\nimport { Clone } from '../clone/index.mjs';\nimport { Deref, Pushref } from '../deref/index.mjs';\nimport { Kind } from '../../type/symbols/index.mjs';\n// ------------------------------------------------------------------\n// ValueGuard\n// ------------------------------------------------------------------\nimport { IsArray, IsDate, IsFunction, IsObject, IsUndefined, HasPropertyKey } from '../guard/index.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsKind } from '../../type/guard/kind.mjs';\n// ------------------------------------------------------------------\n// ValueOrDefault\n// ------------------------------------------------------------------\nfunction ValueOrDefault(schema, value) {\n const defaultValue = HasPropertyKey(schema, 'default') ? schema.default : undefined;\n const clone = IsFunction(defaultValue) ? defaultValue() : Clone(defaultValue);\n return IsUndefined(value) ? clone : IsObject(value) && IsObject(clone) ? Object.assign(clone, value) : value;\n}\n// ------------------------------------------------------------------\n// HasDefaultProperty\n// ------------------------------------------------------------------\nfunction HasDefaultProperty(schema) {\n return IsKind(schema) && 'default' in schema;\n}\n// ------------------------------------------------------------------\n// Types\n// ------------------------------------------------------------------\nfunction FromArray(schema, references, value) {\n // if the value is an array, we attempt to initialize it's elements\n if (IsArray(value)) {\n for (let i = 0; i < value.length; i++) {\n value[i] = Visit(schema.items, references, value[i]);\n }\n return value;\n }\n // ... otherwise use default initialization\n const defaulted = ValueOrDefault(schema, value);\n if (!IsArray(defaulted))\n return defaulted;\n for (let i = 0; i < defaulted.length; i++) {\n defaulted[i] = Visit(schema.items, references, defaulted[i]);\n }\n return defaulted;\n}\nfunction FromDate(schema, references, value) {\n // special case intercept for dates\n return IsDate(value) ? value : ValueOrDefault(schema, value);\n}\nfunction FromImport(schema, references, value) {\n const definitions = globalThis.Object.values(schema.$defs);\n const target = schema.$defs[schema.$ref];\n return Visit(target, [...references, ...definitions], value);\n}\nfunction FromIntersect(schema, references, value) {\n const defaulted = ValueOrDefault(schema, value);\n return schema.allOf.reduce((acc, schema) => {\n const next = Visit(schema, references, defaulted);\n return IsObject(next) ? { ...acc, ...next } : next;\n }, {});\n}\nfunction FromObject(schema, references, value) {\n const defaulted = ValueOrDefault(schema, value);\n // return defaulted\n if (!IsObject(defaulted))\n return defaulted;\n const knownPropertyKeys = Object.getOwnPropertyNames(schema.properties);\n // properties\n for (const key of knownPropertyKeys) {\n // note: we need to traverse into the object and test if the return value\n // yielded a non undefined result. Here we interpret an undefined result as\n // a non assignable property and continue.\n const propertyValue = Visit(schema.properties[key], references, defaulted[key]);\n if (IsUndefined(propertyValue))\n continue;\n defaulted[key] = Visit(schema.properties[key], references, defaulted[key]);\n }\n // return if not additional properties\n if (!HasDefaultProperty(schema.additionalProperties))\n return defaulted;\n // additional properties\n for (const key of Object.getOwnPropertyNames(defaulted)) {\n if (knownPropertyKeys.includes(key))\n continue;\n defaulted[key] = Visit(schema.additionalProperties, references, defaulted[key]);\n }\n return defaulted;\n}\nfunction FromRecord(schema, references, value) {\n const defaulted = ValueOrDefault(schema, value);\n if (!IsObject(defaulted))\n return defaulted;\n const additionalPropertiesSchema = schema.additionalProperties;\n const [propertyKeyPattern, propertySchema] = Object.entries(schema.patternProperties)[0];\n const knownPropertyKey = new RegExp(propertyKeyPattern);\n // properties\n for (const key of Object.getOwnPropertyNames(defaulted)) {\n if (!(knownPropertyKey.test(key) && HasDefaultProperty(propertySchema)))\n continue;\n defaulted[key] = Visit(propertySchema, references, defaulted[key]);\n }\n // return if not additional properties\n if (!HasDefaultProperty(additionalPropertiesSchema))\n return defaulted;\n // additional properties\n for (const key of Object.getOwnPropertyNames(defaulted)) {\n if (knownPropertyKey.test(key))\n continue;\n defaulted[key] = Visit(additionalPropertiesSchema, references, defaulted[key]);\n }\n return defaulted;\n}\nfunction FromRef(schema, references, value) {\n return Visit(Deref(schema, references), references, ValueOrDefault(schema, value));\n}\nfunction FromThis(schema, references, value) {\n return Visit(Deref(schema, references), references, value);\n}\nfunction FromTuple(schema, references, value) {\n const defaulted = ValueOrDefault(schema, value);\n if (!IsArray(defaulted) || IsUndefined(schema.items))\n return defaulted;\n const [items, max] = [schema.items, Math.max(schema.items.length, defaulted.length)];\n for (let i = 0; i < max; i++) {\n if (i < items.length)\n defaulted[i] = Visit(items[i], references, defaulted[i]);\n }\n return defaulted;\n}\nfunction FromUnion(schema, references, value) {\n const defaulted = ValueOrDefault(schema, value);\n for (const inner of schema.anyOf) {\n const result = Visit(inner, references, Clone(defaulted));\n if (Check(inner, references, result)) {\n return result;\n }\n }\n return defaulted;\n}\nfunction Visit(schema, references, value) {\n const references_ = Pushref(schema, references);\n const schema_ = schema;\n switch (schema_[Kind]) {\n case 'Array':\n return FromArray(schema_, references_, value);\n case 'Date':\n return FromDate(schema_, references_, value);\n case 'Import':\n return FromImport(schema_, references_, value);\n case 'Intersect':\n return FromIntersect(schema_, references_, value);\n case 'Object':\n return FromObject(schema_, references_, value);\n case 'Record':\n return FromRecord(schema_, references_, value);\n case 'Ref':\n return FromRef(schema_, references_, value);\n case 'This':\n return FromThis(schema_, references_, value);\n case 'Tuple':\n return FromTuple(schema_, references_, value);\n case 'Union':\n return FromUnion(schema_, references_, value);\n default:\n return ValueOrDefault(schema_, value);\n }\n}\n/** `[Mutable]` Generates missing properties on a value using default schema annotations if available. This function does not check the value and returns an unknown type. You should Check the result before use. Default is a mutable operation. To avoid mutation, Clone the value first. */\nexport function Default(...args) {\n return args.length === 3 ? Visit(args[0], args[1], args[2]) : Visit(args[0], [], args[1]);\n}\n","import { TypeBoxError } from '../../type/error/index.mjs';\nimport { TransformDecode, TransformEncode, HasTransform } from '../transform/index.mjs';\nimport { Assert } from '../assert/index.mjs';\nimport { Default } from '../default/index.mjs';\nimport { Convert } from '../convert/index.mjs';\nimport { Clean } from '../clean/index.mjs';\nimport { Clone } from '../clone/index.mjs';\n// ------------------------------------------------------------------\n// Guards\n// ------------------------------------------------------------------\nimport { IsArray, IsUndefined } from '../guard/index.mjs';\n// ------------------------------------------------------------------\n// Error\n// ------------------------------------------------------------------\nexport class ParseError extends TypeBoxError {\n constructor(message) {\n super(message);\n }\n}\n// prettier-ignore\nexport var ParseRegistry;\n(function (ParseRegistry) {\n const registry = new Map([\n ['Clone', (_type, _references, value) => Clone(value)],\n ['Clean', (type, references, value) => Clean(type, references, value)],\n ['Default', (type, references, value) => Default(type, references, value)],\n ['Convert', (type, references, value) => Convert(type, references, value)],\n ['Assert', (type, references, value) => { Assert(type, references, value); return value; }],\n ['Decode', (type, references, value) => (HasTransform(type, references) ? TransformDecode(type, references, value) : value)],\n ['Encode', (type, references, value) => (HasTransform(type, references) ? TransformEncode(type, references, value) : value)],\n ]);\n // Deletes an entry from the registry\n function Delete(key) {\n registry.delete(key);\n }\n ParseRegistry.Delete = Delete;\n // Sets an entry in the registry\n function Set(key, callback) {\n registry.set(key, callback);\n }\n ParseRegistry.Set = Set;\n // Gets an entry in the registry\n function Get(key) {\n return registry.get(key);\n }\n ParseRegistry.Get = Get;\n})(ParseRegistry || (ParseRegistry = {}));\n// ------------------------------------------------------------------\n// Default Parse Sequence\n// ------------------------------------------------------------------\n// prettier-ignore\nexport const ParseDefault = [\n 'Clone',\n 'Clean',\n 'Default',\n 'Convert',\n 'Assert',\n 'Decode'\n];\n// ------------------------------------------------------------------\n// ParseValue\n// ------------------------------------------------------------------\nfunction ParseValue(operations, type, references, value) {\n return operations.reduce((value, operationKey) => {\n const operation = ParseRegistry.Get(operationKey);\n if (IsUndefined(operation))\n throw new ParseError(`Unable to find Parse operation '${operationKey}'`);\n return operation(type, references, value);\n }, value);\n}\n/** Parses a value */\nexport function Parse(...args) {\n // prettier-ignore\n const [operations, schema, references, value] = (args.length === 4 ? [args[0], args[1], args[2], args[3]] :\n args.length === 3 ? IsArray(args[0]) ? [args[0], args[1], [], args[2]] : [ParseDefault, args[0], args[1], args[2]] :\n args.length === 2 ? [ParseDefault, args[0], [], args[1]] :\n (() => { throw new ParseError('Invalid Arguments'); })());\n return ParseValue(operations, schema, references, value);\n}\n","export function deepRemoveNullishFields(value, depth = 0) {\n if (depth >= 100)\n throw new Error(\"Failed to remove nullish fields after 100 loops\");\n if (value == null)\n return value;\n if (Array.isArray(value)) {\n for (const v of value) {\n deepRemoveNullishFields(v, depth + 1);\n }\n }\n else if (typeof value === \"object\") {\n for (const [k, v] of Object.entries(value)) {\n if (v == null) {\n // Delete the key if it is a field (lower case name), else set it to\n // undefined if it is a variant name (upper case name).\n if (k[0].toUpperCase() !== k[0]) {\n delete value[k];\n }\n else {\n value[k] = null;\n }\n }\n else {\n deepRemoveNullishFields(v, depth + 1);\n }\n }\n }\n return value;\n}\n","import { Value } from \"@sinclair/typebox/value\";\nimport { deepRemoveNullishFields } from \"./nullish\";\nimport { TypeboxValidationError } from \"openchat-shared\";\nexport function typeboxValidate(value, validator) {\n try {\n return Value.Parse([\"Default\", \"Convert\", \"Assert\"], validator, deepRemoveNullishFields(value));\n }\n catch (err) {\n console.error(\"Typebox validation failed: \", value, err);\n throw new TypeboxValidationError(err instanceof Error ? err : undefined);\n }\n}\n","var decoder\ntry {\n\tdecoder = new TextDecoder()\n} catch(error) {}\nvar src\nvar srcEnd\nvar position = 0\nvar alreadySet\nconst EMPTY_ARRAY = []\nvar strings = EMPTY_ARRAY\nvar stringPosition = 0\nvar currentUnpackr = {}\nvar currentStructures\nvar srcString\nvar srcStringStart = 0\nvar srcStringEnd = 0\nvar bundledStrings\nvar referenceMap\nvar currentExtensions = []\nvar dataView\nvar defaultOptions = {\n\tuseRecords: false,\n\tmapsAsObjects: true\n}\nexport class C1Type {}\nexport const C1 = new C1Type()\nC1.name = 'MessagePack 0xC1'\nvar sequentialMode = false\nvar inlineObjectReadThreshold = 2\nvar readStruct, onLoadedStructures, onSaveState\nvar BlockedFunction // we use search and replace to change the next call to BlockedFunction to avoid CSP issues for\n// no-eval build\ntry {\n\tnew Function('')\n} catch(error) {\n\t// if eval variants are not supported, do not create inline object readers ever\n\tinlineObjectReadThreshold = Infinity\n}\n\nexport class Unpackr {\n\tconstructor(options) {\n\t\tif (options) {\n\t\t\tif (options.useRecords === false && options.mapsAsObjects === undefined)\n\t\t\t\toptions.mapsAsObjects = true\n\t\t\tif (options.sequential && options.trusted !== false) {\n\t\t\t\toptions.trusted = true;\n\t\t\t\tif (!options.structures && options.useRecords != false) {\n\t\t\t\t\toptions.structures = []\n\t\t\t\t\tif (!options.maxSharedStructures)\n\t\t\t\t\t\toptions.maxSharedStructures = 0\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (options.structures)\n\t\t\t\toptions.structures.sharedLength = options.structures.length\n\t\t\telse if (options.getStructures) {\n\t\t\t\t(options.structures = []).uninitialized = true // this is what we use to denote an uninitialized structures\n\t\t\t\toptions.structures.sharedLength = 0\n\t\t\t}\n\t\t\tif (options.int64AsNumber) {\n\t\t\t\toptions.int64AsType = 'number'\n\t\t\t}\n\t\t}\n\t\tObject.assign(this, options)\n\t}\n\tunpack(source, options) {\n\t\tif (src) {\n\t\t\t// re-entrant execution, save the state and restore it after we do this unpack\n\t\t\treturn saveState(() => {\n\t\t\t\tclearSource()\n\t\t\t\treturn this ? this.unpack(source, options) : Unpackr.prototype.unpack.call(defaultOptions, source, options)\n\t\t\t})\n\t\t}\n\t\tif (!source.buffer && source.constructor === ArrayBuffer)\n\t\t\tsource = typeof Buffer !== 'undefined' ? Buffer.from(source) : new Uint8Array(source);\n\t\tif (typeof options === 'object') {\n\t\t\tsrcEnd = options.end || source.length\n\t\t\tposition = options.start || 0\n\t\t} else {\n\t\t\tposition = 0\n\t\t\tsrcEnd = options > -1 ? options : source.length\n\t\t}\n\t\tstringPosition = 0\n\t\tsrcStringEnd = 0\n\t\tsrcString = null\n\t\tstrings = EMPTY_ARRAY\n\t\tbundledStrings = null\n\t\tsrc = source\n\t\t// this provides cached access to the data view for a buffer if it is getting reused, which is a recommend\n\t\t// technique for getting data from a database where it can be copied into an existing buffer instead of creating\n\t\t// new ones\n\t\ttry {\n\t\t\tdataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength))\n\t\t} catch(error) {\n\t\t\t// if it doesn't have a buffer, maybe it is the wrong type of object\n\t\t\tsrc = null\n\t\t\tif (source instanceof Uint8Array)\n\t\t\t\tthrow error\n\t\t\tthrow new Error('Source must be a Uint8Array or Buffer but was a ' + ((source && typeof source == 'object') ? source.constructor.name : typeof source))\n\t\t}\n\t\tif (this instanceof Unpackr) {\n\t\t\tcurrentUnpackr = this\n\t\t\tif (this.structures) {\n\t\t\t\tcurrentStructures = this.structures\n\t\t\t\treturn checkedRead(options)\n\t\t\t} else if (!currentStructures || currentStructures.length > 0) {\n\t\t\t\tcurrentStructures = []\n\t\t\t}\n\t\t} else {\n\t\t\tcurrentUnpackr = defaultOptions\n\t\t\tif (!currentStructures || currentStructures.length > 0)\n\t\t\t\tcurrentStructures = []\n\t\t}\n\t\treturn checkedRead(options)\n\t}\n\tunpackMultiple(source, forEach) {\n\t\tlet values, lastPosition = 0\n\t\ttry {\n\t\t\tsequentialMode = true\n\t\t\tlet size = source.length\n\t\t\tlet value = this ? this.unpack(source, size) : defaultUnpackr.unpack(source, size)\n\t\t\tif (forEach) {\n\t\t\t\tif (forEach(value, lastPosition, position) === false) return;\n\t\t\t\twhile(position < size) {\n\t\t\t\t\tlastPosition = position\n\t\t\t\t\tif (forEach(checkedRead(), lastPosition, position) === false) {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tvalues = [ value ]\n\t\t\t\twhile(position < size) {\n\t\t\t\t\tlastPosition = position\n\t\t\t\t\tvalues.push(checkedRead())\n\t\t\t\t}\n\t\t\t\treturn values\n\t\t\t}\n\t\t} catch(error) {\n\t\t\terror.lastPosition = lastPosition\n\t\t\terror.values = values\n\t\t\tthrow error\n\t\t} finally {\n\t\t\tsequentialMode = false\n\t\t\tclearSource()\n\t\t}\n\t}\n\t_mergeStructures(loadedStructures, existingStructures) {\n\t\tif (onLoadedStructures)\n\t\t\tloadedStructures = onLoadedStructures.call(this, loadedStructures);\n\t\tloadedStructures = loadedStructures || []\n\t\tif (Object.isFrozen(loadedStructures))\n\t\t\tloadedStructures = loadedStructures.map(structure => structure.slice(0))\n\t\tfor (let i = 0, l = loadedStructures.length; i < l; i++) {\n\t\t\tlet structure = loadedStructures[i]\n\t\t\tif (structure) {\n\t\t\t\tstructure.isShared = true\n\t\t\t\tif (i >= 32)\n\t\t\t\t\tstructure.highByte = (i - 32) >> 5\n\t\t\t}\n\t\t}\n\t\tloadedStructures.sharedLength = loadedStructures.length\n\t\tfor (let id in existingStructures || []) {\n\t\t\tif (id >= 0) {\n\t\t\t\tlet structure = loadedStructures[id]\n\t\t\t\tlet existing = existingStructures[id]\n\t\t\t\tif (existing) {\n\t\t\t\t\tif (structure)\n\t\t\t\t\t\t(loadedStructures.restoreStructures || (loadedStructures.restoreStructures = []))[id] = structure\n\t\t\t\t\tloadedStructures[id] = existing\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn this.structures = loadedStructures\n\t}\n\tdecode(source, options) {\n\t\treturn this.unpack(source, options)\n\t}\n}\nexport function getPosition() {\n\treturn position\n}\nexport function checkedRead(options) {\n\ttry {\n\t\tif (!currentUnpackr.trusted && !sequentialMode) {\n\t\t\tlet sharedLength = currentStructures.sharedLength || 0\n\t\t\tif (sharedLength < currentStructures.length)\n\t\t\t\tcurrentStructures.length = sharedLength\n\t\t}\n\t\tlet result\n\t\tif (currentUnpackr.randomAccessStructure && src[position] < 0x40 && src[position] >= 0x20 && readStruct) {\n\t\t\tresult = readStruct(src, position, srcEnd, currentUnpackr)\n\t\t\tsrc = null // dispose of this so that recursive unpack calls don't save state\n\t\t\tif (!(options && options.lazy) && result)\n\t\t\t\tresult = result.toJSON()\n\t\t\tposition = srcEnd\n\t\t} else\n\t\t\tresult = read()\n\t\tif (bundledStrings) { // bundled strings to skip past\n\t\t\tposition = bundledStrings.postBundlePosition\n\t\t\tbundledStrings = null\n\t\t}\n\t\tif (sequentialMode)\n\t\t\t// we only need to restore the structures if there was an error, but if we completed a read,\n\t\t\t// we can clear this out and keep the structures we read\n\t\t\tcurrentStructures.restoreStructures = null\n\n\t\tif (position == srcEnd) {\n\t\t\t// finished reading this source, cleanup references\n\t\t\tif (currentStructures && currentStructures.restoreStructures)\n\t\t\t\trestoreStructures()\n\t\t\tcurrentStructures = null\n\t\t\tsrc = null\n\t\t\tif (referenceMap)\n\t\t\t\treferenceMap = null\n\t\t} else if (position > srcEnd) {\n\t\t\t// over read\n\t\t\tthrow new Error('Unexpected end of MessagePack data')\n\t\t} else if (!sequentialMode) {\n\t\t\tlet jsonView;\n\t\t\ttry {\n\t\t\t\tjsonView = JSON.stringify(result, (_, value) => typeof value === \"bigint\" ? `${value}n` : value).slice(0, 100)\n\t\t\t} catch(error) {\n\t\t\t\tjsonView = '(JSON view not available ' + error + ')'\n\t\t\t}\n\t\t\tthrow new Error('Data read, but end of buffer not reached ' + jsonView)\n\t\t}\n\t\t// else more to read, but we are reading sequentially, so don't clear source yet\n\t\treturn result\n\t} catch(error) {\n\t\tif (currentStructures && currentStructures.restoreStructures)\n\t\t\trestoreStructures()\n\t\tclearSource()\n\t\tif (error instanceof RangeError || error.message.startsWith('Unexpected end of buffer') || position > srcEnd) {\n\t\t\terror.incomplete = true\n\t\t}\n\t\tthrow error\n\t}\n}\n\nfunction restoreStructures() {\n\tfor (let id in currentStructures.restoreStructures) {\n\t\tcurrentStructures[id] = currentStructures.restoreStructures[id]\n\t}\n\tcurrentStructures.restoreStructures = null\n}\n\nexport function read() {\n\tlet token = src[position++]\n\tif (token < 0xa0) {\n\t\tif (token < 0x80) {\n\t\t\tif (token < 0x40)\n\t\t\t\treturn token\n\t\t\telse {\n\t\t\t\tlet structure = currentStructures[token & 0x3f] ||\n\t\t\t\t\tcurrentUnpackr.getStructures && loadStructures()[token & 0x3f]\n\t\t\t\tif (structure) {\n\t\t\t\t\tif (!structure.read) {\n\t\t\t\t\t\tstructure.read = createStructureReader(structure, token & 0x3f)\n\t\t\t\t\t}\n\t\t\t\t\treturn structure.read()\n\t\t\t\t} else\n\t\t\t\t\treturn token\n\t\t\t}\n\t\t} else if (token < 0x90) {\n\t\t\t// map\n\t\t\ttoken -= 0x80\n\t\t\tif (currentUnpackr.mapsAsObjects) {\n\t\t\t\tlet object = {}\n\t\t\t\tfor (let i = 0; i < token; i++) {\n\t\t\t\t\tlet key = readKey()\n\t\t\t\t\tif (key === '__proto__')\n\t\t\t\t\t\tkey = '__proto_'\n\t\t\t\t\tobject[key] = read()\n\t\t\t\t}\n\t\t\t\treturn object\n\t\t\t} else {\n\t\t\t\tlet map = new Map()\n\t\t\t\tfor (let i = 0; i < token; i++) {\n\t\t\t\t\tmap.set(read(), read())\n\t\t\t\t}\n\t\t\t\treturn map\n\t\t\t}\n\t\t} else {\n\t\t\ttoken -= 0x90\n\t\t\tlet array = new Array(token)\n\t\t\tfor (let i = 0; i < token; i++) {\n\t\t\t\tarray[i] = read()\n\t\t\t}\n\t\t\tif (currentUnpackr.freezeData)\n\t\t\t\treturn Object.freeze(array)\n\t\t\treturn array\n\t\t}\n\t} else if (token < 0xc0) {\n\t\t// fixstr\n\t\tlet length = token - 0xa0\n\t\tif (srcStringEnd >= position) {\n\t\t\treturn srcString.slice(position - srcStringStart, (position += length) - srcStringStart)\n\t\t}\n\t\tif (srcStringEnd == 0 && srcEnd < 140) {\n\t\t\t// for small blocks, avoiding the overhead of the extract call is helpful\n\t\t\tlet string = length < 16 ? shortStringInJS(length) : longStringInJS(length)\n\t\t\tif (string != null)\n\t\t\t\treturn string\n\t\t}\n\t\treturn readFixedString(length)\n\t} else {\n\t\tlet value\n\t\tswitch (token) {\n\t\t\tcase 0xc0: return null\n\t\t\tcase 0xc1:\n\t\t\t\tif (bundledStrings) {\n\t\t\t\t\tvalue = read() // followed by the length of the string in characters (not bytes!)\n\t\t\t\t\tif (value > 0)\n\t\t\t\t\t\treturn bundledStrings[1].slice(bundledStrings.position1, bundledStrings.position1 += value)\n\t\t\t\t\telse\n\t\t\t\t\t\treturn bundledStrings[0].slice(bundledStrings.position0, bundledStrings.position0 -= value)\n\t\t\t\t}\n\t\t\t\treturn C1; // \"never-used\", return special object to denote that\n\t\t\tcase 0xc2: return false\n\t\t\tcase 0xc3: return true\n\t\t\tcase 0xc4:\n\t\t\t\t// bin 8\n\t\t\t\tvalue = src[position++]\n\t\t\t\tif (value === undefined)\n\t\t\t\t\tthrow new Error('Unexpected end of buffer')\n\t\t\t\treturn readBin(value)\n\t\t\tcase 0xc5:\n\t\t\t\t// bin 16\n\t\t\t\tvalue = dataView.getUint16(position)\n\t\t\t\tposition += 2\n\t\t\t\treturn readBin(value)\n\t\t\tcase 0xc6:\n\t\t\t\t// bin 32\n\t\t\t\tvalue = dataView.getUint32(position)\n\t\t\t\tposition += 4\n\t\t\t\treturn readBin(value)\n\t\t\tcase 0xc7:\n\t\t\t\t// ext 8\n\t\t\t\treturn readExt(src[position++])\n\t\t\tcase 0xc8:\n\t\t\t\t// ext 16\n\t\t\t\tvalue = dataView.getUint16(position)\n\t\t\t\tposition += 2\n\t\t\t\treturn readExt(value)\n\t\t\tcase 0xc9:\n\t\t\t\t// ext 32\n\t\t\t\tvalue = dataView.getUint32(position)\n\t\t\t\tposition += 4\n\t\t\t\treturn readExt(value)\n\t\t\tcase 0xca:\n\t\t\t\tvalue = dataView.getFloat32(position)\n\t\t\t\tif (currentUnpackr.useFloat32 > 2) {\n\t\t\t\t\t// this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved\n\t\t\t\t\tlet multiplier = mult10[((src[position] & 0x7f) << 1) | (src[position + 1] >> 7)]\n\t\t\t\t\tposition += 4\n\t\t\t\t\treturn ((multiplier * value + (value > 0 ? 0.5 : -0.5)) >> 0) / multiplier\n\t\t\t\t}\n\t\t\t\tposition += 4\n\t\t\t\treturn value\n\t\t\tcase 0xcb:\n\t\t\t\tvalue = dataView.getFloat64(position)\n\t\t\t\tposition += 8\n\t\t\t\treturn value\n\t\t\t// uint handlers\n\t\t\tcase 0xcc:\n\t\t\t\treturn src[position++]\n\t\t\tcase 0xcd:\n\t\t\t\tvalue = dataView.getUint16(position)\n\t\t\t\tposition += 2\n\t\t\t\treturn value\n\t\t\tcase 0xce:\n\t\t\t\tvalue = dataView.getUint32(position)\n\t\t\t\tposition += 4\n\t\t\t\treturn value\n\t\t\tcase 0xcf:\n\t\t\t\tif (currentUnpackr.int64AsType === 'number') {\n\t\t\t\t\tvalue = dataView.getUint32(position) * 0x100000000\n\t\t\t\t\tvalue += dataView.getUint32(position + 4)\n\t\t\t\t} else if (currentUnpackr.int64AsType === 'string') {\n\t\t\t\t\tvalue = dataView.getBigUint64(position).toString()\n\t\t\t\t} else if (currentUnpackr.int64AsType === 'auto') {\n\t\t\t\t\tvalue = dataView.getBigUint64(position)\n\t\t\t\t\tif (value<=BigInt(2)<=BigInt(-2)<= position) {\n\t\t\t\t\treturn srcString.slice(position - srcStringStart, (position += value) - srcStringStart)\n\t\t\t\t}\n\t\t\t\treturn readString8(value)\n\t\t\tcase 0xda:\n\t\t\t// str 16\n\t\t\t\tvalue = dataView.getUint16(position)\n\t\t\t\tposition += 2\n\t\t\t\tif (srcStringEnd >= position) {\n\t\t\t\t\treturn srcString.slice(position - srcStringStart, (position += value) - srcStringStart)\n\t\t\t\t}\n\t\t\t\treturn readString16(value)\n\t\t\tcase 0xdb:\n\t\t\t// str 32\n\t\t\t\tvalue = dataView.getUint32(position)\n\t\t\t\tposition += 4\n\t\t\t\tif (srcStringEnd >= position) {\n\t\t\t\t\treturn srcString.slice(position - srcStringStart, (position += value) - srcStringStart)\n\t\t\t\t}\n\t\t\t\treturn readString32(value)\n\t\t\tcase 0xdc:\n\t\t\t// array 16\n\t\t\t\tvalue = dataView.getUint16(position)\n\t\t\t\tposition += 2\n\t\t\t\treturn readArray(value)\n\t\t\tcase 0xdd:\n\t\t\t// array 32\n\t\t\t\tvalue = dataView.getUint32(position)\n\t\t\t\tposition += 4\n\t\t\t\treturn readArray(value)\n\t\t\tcase 0xde:\n\t\t\t// map 16\n\t\t\t\tvalue = dataView.getUint16(position)\n\t\t\t\tposition += 2\n\t\t\t\treturn readMap(value)\n\t\t\tcase 0xdf:\n\t\t\t// map 32\n\t\t\t\tvalue = dataView.getUint32(position)\n\t\t\t\tposition += 4\n\t\t\t\treturn readMap(value)\n\t\t\tdefault: // negative int\n\t\t\t\tif (token >= 0xe0)\n\t\t\t\t\treturn token - 0x100\n\t\t\t\tif (token === undefined) {\n\t\t\t\t\tlet error = new Error('Unexpected end of MessagePack data')\n\t\t\t\t\terror.incomplete = true\n\t\t\t\t\tthrow error\n\t\t\t\t}\n\t\t\t\tthrow new Error('Unknown MessagePack token ' + token)\n\n\t\t}\n\t}\n}\nconst validName = /^[a-zA-Z_$][a-zA-Z\\d_$]*$/\nfunction createStructureReader(structure, firstId) {\n\tfunction readObject() {\n\t\t// This initial function is quick to instantiate, but runs slower. After several iterations pay the cost to build the faster function\n\t\tif (readObject.count++ > inlineObjectReadThreshold) {\n\t\t\tlet readObject = structure.read = (new Function('r', 'return function(){return ' + (currentUnpackr.freezeData ? 'Object.freeze' : '') +\n\t\t\t\t'({' + structure.map(key => key === '__proto__' ? '__proto_:r()' : validName.test(key) ? key + ':r()' : ('[' + JSON.stringify(key) + ']:r()')).join(',') + '})}'))(read)\n\t\t\tif (structure.highByte === 0)\n\t\t\t\tstructure.read = createSecondByteReader(firstId, structure.read)\n\t\t\treturn readObject() // second byte is already read, if there is one so immediately read object\n\t\t}\n\t\tlet object = {}\n\t\tfor (let i = 0, l = structure.length; i < l; i++) {\n\t\t\tlet key = structure[i]\n\t\t\tif (key === '__proto__')\n\t\t\t\tkey = '__proto_'\n\t\t\tobject[key] = read()\n\t\t}\n\t\tif (currentUnpackr.freezeData)\n\t\t\treturn Object.freeze(object);\n\t\treturn object\n\t}\n\treadObject.count = 0\n\tif (structure.highByte === 0) {\n\t\treturn createSecondByteReader(firstId, readObject)\n\t}\n\treturn readObject\n}\n\nconst createSecondByteReader = (firstId, read0) => {\n\treturn function() {\n\t\tlet highByte = src[position++]\n\t\tif (highByte === 0)\n\t\t\treturn read0()\n\t\tlet id = firstId < 32 ? -(firstId + (highByte << 5)) : firstId + (highByte << 5)\n\t\tlet structure = currentStructures[id] || loadStructures()[id]\n\t\tif (!structure) {\n\t\t\tthrow new Error('Record id is not defined for ' + id)\n\t\t}\n\t\tif (!structure.read)\n\t\t\tstructure.read = createStructureReader(structure, firstId)\n\t\treturn structure.read()\n\t}\n}\n\nexport function loadStructures() {\n\tlet loadedStructures = saveState(() => {\n\t\t// save the state in case getStructures modifies our buffer\n\t\tsrc = null\n\t\treturn currentUnpackr.getStructures()\n\t})\n\treturn currentStructures = currentUnpackr._mergeStructures(loadedStructures, currentStructures)\n}\n\nvar readFixedString = readStringJS\nvar readString8 = readStringJS\nvar readString16 = readStringJS\nvar readString32 = readStringJS\nexport let isNativeAccelerationEnabled = false\n\nexport function setExtractor(extractStrings) {\n\tisNativeAccelerationEnabled = true\n\treadFixedString = readString(1)\n\treadString8 = readString(2)\n\treadString16 = readString(3)\n\treadString32 = readString(5)\n\tfunction readString(headerLength) {\n\t\treturn function readString(length) {\n\t\t\tlet string = strings[stringPosition++]\n\t\t\tif (string == null) {\n\t\t\t\tif (bundledStrings)\n\t\t\t\t\treturn readStringJS(length)\n\t\t\t\tlet byteOffset = src.byteOffset\n\t\t\t\tlet extraction = extractStrings(position - headerLength + byteOffset, srcEnd + byteOffset, src.buffer)\n\t\t\t\tif (typeof extraction == 'string') {\n\t\t\t\t\tstring = extraction\n\t\t\t\t\tstrings = EMPTY_ARRAY\n\t\t\t\t} else {\n\t\t\t\t\tstrings = extraction\n\t\t\t\t\tstringPosition = 1\n\t\t\t\t\tsrcStringEnd = 1 // even if a utf-8 string was decoded, must indicate we are in the midst of extracted strings and can't skip strings\n\t\t\t\t\tstring = strings[0]\n\t\t\t\t\tif (string === undefined)\n\t\t\t\t\t\tthrow new Error('Unexpected end of buffer')\n\t\t\t\t}\n\t\t\t}\n\t\t\tlet srcStringLength = string.length\n\t\t\tif (srcStringLength <= length) {\n\t\t\t\tposition += length\n\t\t\t\treturn string\n\t\t\t}\n\t\t\tsrcString = string\n\t\t\tsrcStringStart = position\n\t\t\tsrcStringEnd = position + srcStringLength\n\t\t\tposition += length\n\t\t\treturn string.slice(0, length) // we know we just want the beginning\n\t\t}\n\t}\n}\nfunction readStringJS(length) {\n\tlet result\n\tif (length < 16) {\n\t\tif (result = shortStringInJS(length))\n\t\t\treturn result\n\t}\n\tif (length > 64 && decoder)\n\t\treturn decoder.decode(src.subarray(position, position += length))\n\tconst end = position + length\n\tconst units = []\n\tresult = ''\n\twhile (position < end) {\n\t\tconst byte1 = src[position++]\n\t\tif ((byte1 & 0x80) === 0) {\n\t\t\t// 1 byte\n\t\t\tunits.push(byte1)\n\t\t} else if ((byte1 & 0xe0) === 0xc0) {\n\t\t\t// 2 bytes\n\t\t\tconst byte2 = src[position++] & 0x3f\n\t\t\tunits.push(((byte1 & 0x1f) << 6) | byte2)\n\t\t} else if ((byte1 & 0xf0) === 0xe0) {\n\t\t\t// 3 bytes\n\t\t\tconst byte2 = src[position++] & 0x3f\n\t\t\tconst byte3 = src[position++] & 0x3f\n\t\t\tunits.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3)\n\t\t} else if ((byte1 & 0xf8) === 0xf0) {\n\t\t\t// 4 bytes\n\t\t\tconst byte2 = src[position++] & 0x3f\n\t\t\tconst byte3 = src[position++] & 0x3f\n\t\t\tconst byte4 = src[position++] & 0x3f\n\t\t\tlet unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4\n\t\t\tif (unit > 0xffff) {\n\t\t\t\tunit -= 0x10000\n\t\t\t\tunits.push(((unit >>> 10) & 0x3ff) | 0xd800)\n\t\t\t\tunit = 0xdc00 | (unit & 0x3ff)\n\t\t\t}\n\t\t\tunits.push(unit)\n\t\t} else {\n\t\t\tunits.push(byte1)\n\t\t}\n\n\t\tif (units.length >= 0x1000) {\n\t\t\tresult += fromCharCode.apply(String, units)\n\t\t\tunits.length = 0\n\t\t}\n\t}\n\n\tif (units.length > 0) {\n\t\tresult += fromCharCode.apply(String, units)\n\t}\n\n\treturn result\n}\nexport function readString(source, start, length) {\n\tlet existingSrc = src;\n\tsrc = source;\n\tposition = start;\n\ttry {\n\t\treturn readStringJS(length);\n\t} finally {\n\t\tsrc = existingSrc;\n\t}\n}\n\nfunction readArray(length) {\n\tlet array = new Array(length)\n\tfor (let i = 0; i < length; i++) {\n\t\tarray[i] = read()\n\t}\n\tif (currentUnpackr.freezeData)\n\t\treturn Object.freeze(array)\n\treturn array\n}\n\nfunction readMap(length) {\n\tif (currentUnpackr.mapsAsObjects) {\n\t\tlet object = {}\n\t\tfor (let i = 0; i < length; i++) {\n\t\t\tlet key = readKey()\n\t\t\tif (key === '__proto__')\n\t\t\t\tkey = '__proto_';\n\t\t\tobject[key] = read()\n\t\t}\n\t\treturn object\n\t} else {\n\t\tlet map = new Map()\n\t\tfor (let i = 0; i < length; i++) {\n\t\t\tmap.set(read(), read())\n\t\t}\n\t\treturn map\n\t}\n}\n\nvar fromCharCode = String.fromCharCode\nfunction longStringInJS(length) {\n\tlet start = position\n\tlet bytes = new Array(length)\n\tfor (let i = 0; i < length; i++) {\n\t\tconst byte = src[position++];\n\t\tif ((byte & 0x80) > 0) {\n\t\t\t\tposition = start\n\t\t\t\treturn\n\t\t\t}\n\t\t\tbytes[i] = byte\n\t\t}\n\t\treturn fromCharCode.apply(String, bytes)\n}\nfunction shortStringInJS(length) {\n\tif (length < 4) {\n\t\tif (length < 2) {\n\t\t\tif (length === 0)\n\t\t\t\treturn ''\n\t\t\telse {\n\t\t\t\tlet a = src[position++]\n\t\t\t\tif ((a & 0x80) > 1) {\n\t\t\t\t\tposition -= 1\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\treturn fromCharCode(a)\n\t\t\t}\n\t\t} else {\n\t\t\tlet a = src[position++]\n\t\t\tlet b = src[position++]\n\t\t\tif ((a & 0x80) > 0 || (b & 0x80) > 0) {\n\t\t\t\tposition -= 2\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (length < 3)\n\t\t\t\treturn fromCharCode(a, b)\n\t\t\tlet c = src[position++]\n\t\t\tif ((c & 0x80) > 0) {\n\t\t\t\tposition -= 3\n\t\t\t\treturn\n\t\t\t}\n\t\t\treturn fromCharCode(a, b, c)\n\t\t}\n\t} else {\n\t\tlet a = src[position++]\n\t\tlet b = src[position++]\n\t\tlet c = src[position++]\n\t\tlet d = src[position++]\n\t\tif ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) {\n\t\t\tposition -= 4\n\t\t\treturn\n\t\t}\n\t\tif (length < 6) {\n\t\t\tif (length === 4)\n\t\t\t\treturn fromCharCode(a, b, c, d)\n\t\t\telse {\n\t\t\t\tlet e = src[position++]\n\t\t\t\tif ((e & 0x80) > 0) {\n\t\t\t\t\tposition -= 5\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\treturn fromCharCode(a, b, c, d, e)\n\t\t\t}\n\t\t} else if (length < 8) {\n\t\t\tlet e = src[position++]\n\t\t\tlet f = src[position++]\n\t\t\tif ((e & 0x80) > 0 || (f & 0x80) > 0) {\n\t\t\t\tposition -= 6\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (length < 7)\n\t\t\t\treturn fromCharCode(a, b, c, d, e, f)\n\t\t\tlet g = src[position++]\n\t\t\tif ((g & 0x80) > 0) {\n\t\t\t\tposition -= 7\n\t\t\t\treturn\n\t\t\t}\n\t\t\treturn fromCharCode(a, b, c, d, e, f, g)\n\t\t} else {\n\t\t\tlet e = src[position++]\n\t\t\tlet f = src[position++]\n\t\t\tlet g = src[position++]\n\t\t\tlet h = src[position++]\n\t\t\tif ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) {\n\t\t\t\tposition -= 8\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (length < 10) {\n\t\t\t\tif (length === 8)\n\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h)\n\t\t\t\telse {\n\t\t\t\t\tlet i = src[position++]\n\t\t\t\t\tif ((i & 0x80) > 0) {\n\t\t\t\t\t\tposition -= 9\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i)\n\t\t\t\t}\n\t\t\t} else if (length < 12) {\n\t\t\t\tlet i = src[position++]\n\t\t\t\tlet j = src[position++]\n\t\t\t\tif ((i & 0x80) > 0 || (j & 0x80) > 0) {\n\t\t\t\t\tposition -= 10\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif (length < 11)\n\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j)\n\t\t\t\tlet k = src[position++]\n\t\t\t\tif ((k & 0x80) > 0) {\n\t\t\t\t\tposition -= 11\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k)\n\t\t\t} else {\n\t\t\t\tlet i = src[position++]\n\t\t\t\tlet j = src[position++]\n\t\t\t\tlet k = src[position++]\n\t\t\t\tlet l = src[position++]\n\t\t\t\tif ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) {\n\t\t\t\t\tposition -= 12\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif (length < 14) {\n\t\t\t\t\tif (length === 12)\n\t\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l)\n\t\t\t\t\telse {\n\t\t\t\t\t\tlet m = src[position++]\n\t\t\t\t\t\tif ((m & 0x80) > 0) {\n\t\t\t\t\t\t\tposition -= 13\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlet m = src[position++]\n\t\t\t\t\tlet n = src[position++]\n\t\t\t\t\tif ((m & 0x80) > 0 || (n & 0x80) > 0) {\n\t\t\t\t\t\tposition -= 14\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tif (length < 15)\n\t\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n)\n\t\t\t\t\tlet o = src[position++]\n\t\t\t\t\tif ((o & 0x80) > 0) {\n\t\t\t\t\t\tposition -= 15\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction readOnlyJSString() {\n\tlet token = src[position++]\n\tlet length\n\tif (token < 0xc0) {\n\t\t// fixstr\n\t\tlength = token - 0xa0\n\t} else {\n\t\tswitch(token) {\n\t\t\tcase 0xd9:\n\t\t\t// str 8\n\t\t\t\tlength = src[position++]\n\t\t\t\tbreak\n\t\t\tcase 0xda:\n\t\t\t// str 16\n\t\t\t\tlength = dataView.getUint16(position)\n\t\t\t\tposition += 2\n\t\t\t\tbreak\n\t\t\tcase 0xdb:\n\t\t\t// str 32\n\t\t\t\tlength = dataView.getUint32(position)\n\t\t\t\tposition += 4\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tthrow new Error('Expected string')\n\t\t}\n\t}\n\treturn readStringJS(length)\n}\n\n\nfunction readBin(length) {\n\treturn currentUnpackr.copyBuffers ?\n\t\t// specifically use the copying slice (not the node one)\n\t\tUint8Array.prototype.slice.call(src, position, position += length) :\n\t\tsrc.subarray(position, position += length)\n}\nfunction readExt(length) {\n\tlet type = src[position++]\n\tif (currentExtensions[type]) {\n\t\tlet end\n\t\treturn currentExtensions[type](src.subarray(position, end = (position += length)), (readPosition) => {\n\t\t\tposition = readPosition;\n\t\t\ttry {\n\t\t\t\treturn read();\n\t\t\t} finally {\n\t\t\t\tposition = end;\n\t\t\t}\n\t\t})\n\t}\n\telse\n\t\tthrow new Error('Unknown extension type ' + type)\n}\n\nvar keyCache = new Array(4096)\nfunction readKey() {\n\tlet length = src[position++]\n\tif (length >= 0xa0 && length < 0xc0) {\n\t\t// fixstr, potentially use key cache\n\t\tlength = length - 0xa0\n\t\tif (srcStringEnd >= position) // if it has been extracted, must use it (and faster anyway)\n\t\t\treturn srcString.slice(position - srcStringStart, (position += length) - srcStringStart)\n\t\telse if (!(srcStringEnd == 0 && srcEnd < 180))\n\t\t\treturn readFixedString(length)\n\t} else { // not cacheable, go back and do a standard read\n\t\tposition--\n\t\treturn asSafeString(read())\n\t}\n\tlet key = ((length << 5) ^ (length > 1 ? dataView.getUint16(position) : length > 0 ? src[position] : 0)) & 0xfff\n\tlet entry = keyCache[key]\n\tlet checkPosition = position\n\tlet end = position + length - 3\n\tlet chunk\n\tlet i = 0\n\tif (entry && entry.bytes == length) {\n\t\twhile (checkPosition < end) {\n\t\t\tchunk = dataView.getUint32(checkPosition)\n\t\t\tif (chunk != entry[i++]) {\n\t\t\t\tcheckPosition = 0x70000000\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcheckPosition += 4\n\t\t}\n\t\tend += 3\n\t\twhile (checkPosition < end) {\n\t\t\tchunk = src[checkPosition++]\n\t\t\tif (chunk != entry[i++]) {\n\t\t\t\tcheckPosition = 0x70000000\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif (checkPosition === end) {\n\t\t\tposition = checkPosition\n\t\t\treturn entry.string\n\t\t}\n\t\tend -= 3\n\t\tcheckPosition = position\n\t}\n\tentry = []\n\tkeyCache[key] = entry\n\tentry.bytes = length\n\twhile (checkPosition < end) {\n\t\tchunk = dataView.getUint32(checkPosition)\n\t\tentry.push(chunk)\n\t\tcheckPosition += 4\n\t}\n\tend += 3\n\twhile (checkPosition < end) {\n\t\tchunk = src[checkPosition++]\n\t\tentry.push(chunk)\n\t}\n\t// for small blocks, avoiding the overhead of the extract call is helpful\n\tlet string = length < 16 ? shortStringInJS(length) : longStringInJS(length)\n\tif (string != null)\n\t\treturn entry.string = string\n\treturn entry.string = readFixedString(length)\n}\n\nfunction asSafeString(property) {\n\t// protect against expensive (DoS) string conversions\n\tif (typeof property === 'string') return property;\n\tif (typeof property === 'number' || typeof property === 'boolean' || typeof property === 'bigint') return property.toString();\n\tif (property == null) return property + '';\n\tthrow new Error('Invalid property type for record', typeof property);\n}\n// the registration of the record definition extension (as \"r\")\nconst recordDefinition = (id, highByte) => {\n\tlet structure = read().map(asSafeString) // ensure that all keys are strings and\n\t// that the array is mutable\n\tlet firstByte = id\n\tif (highByte !== undefined) {\n\t\tid = id < 32 ? -((highByte << 5) + id) : ((highByte << 5) + id)\n\t\tstructure.highByte = highByte\n\t}\n\tlet existingStructure = currentStructures[id]\n\t// If it is a shared structure, we need to restore any changes after reading.\n\t// Also in sequential mode, we may get incomplete reads and thus errors, and we need to restore\n\t// to the state prior to an incomplete read in order to properly resume.\n\tif (existingStructure && (existingStructure.isShared || sequentialMode)) {\n\t\t(currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure\n\t}\n\tcurrentStructures[id] = structure\n\tstructure.read = createStructureReader(structure, firstByte)\n\treturn structure.read()\n}\ncurrentExtensions[0] = () => {} // notepack defines extension 0 to mean undefined, so use that as the default here\ncurrentExtensions[0].noBuffer = true\n\ncurrentExtensions[0x42] = (data) => {\n\t// decode bigint\n\tlet length = data.length;\n\tlet value = BigInt(data[0] & 0x80 ? data[0] - 0x100 : data[0]);\n\tfor (let i = 1; i < length; i++) {\n\t\tvalue <<= BigInt(8);\n\t\tvalue += BigInt(data[i]);\n\t}\n\treturn value;\n}\n\nlet errors = { Error, TypeError, ReferenceError };\ncurrentExtensions[0x65] = () => {\n\tlet data = read()\n\treturn (errors[data[0]] || Error)(data[1], { cause: data[2] })\n}\n\ncurrentExtensions[0x69] = (data) => {\n\t// id extension (for structured clones)\n\tif (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled')\n\tlet id = dataView.getUint32(position - 4)\n\tif (!referenceMap)\n\t\treferenceMap = new Map()\n\tlet token = src[position]\n\tlet target\n\t// TODO: handle Maps, Sets, and other types that can cycle; this is complicated, because you potentially need to read\n\t// ahead past references to record structure definitions\n\tif (token >= 0x90 && token < 0xa0 || token == 0xdc || token == 0xdd)\n\t\ttarget = []\n\telse\n\t\ttarget = {}\n\n\tlet refEntry = { target } // a placeholder object\n\treferenceMap.set(id, refEntry)\n\tlet targetProperties = read() // read the next value as the target object to id\n\tif (refEntry.used) // there is a cycle, so we have to assign properties to original target\n\t\treturn Object.assign(target, targetProperties)\n\trefEntry.target = targetProperties // the placeholder wasn't used, replace with the deserialized one\n\treturn targetProperties // no cycle, can just use the returned read object\n}\n\ncurrentExtensions[0x70] = (data) => {\n\t// pointer extension (for structured clones)\n\tif (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled')\n\tlet id = dataView.getUint32(position - 4)\n\tlet refEntry = referenceMap.get(id)\n\trefEntry.used = true\n\treturn refEntry.target\n}\n\ncurrentExtensions[0x73] = () => new Set(read())\n\nexport const typedArrays = ['Int8','Uint8','Uint8Clamped','Int16','Uint16','Int32','Uint32','Float32','Float64','BigInt64','BigUint64'].map(type => type + 'Array')\n\nlet glbl = typeof globalThis === 'object' ? globalThis : window;\ncurrentExtensions[0x74] = (data) => {\n\tlet typeCode = data[0]\n\tlet typedArrayName = typedArrays[typeCode]\n\tif (!typedArrayName) {\n\t\tif (typeCode === 16) {\n\t\t\tlet ab = new ArrayBuffer(data.length - 1)\n\t\t\tlet u8 = new Uint8Array(ab)\n\t\t\tu8.set(data.subarray(1))\n\t\t\treturn ab;\n\t\t}\n\t\tthrow new Error('Could not find typed array for code ' + typeCode)\n\t}\n\t// we have to always slice/copy here to get a new ArrayBuffer that is word/byte aligned\n\treturn new glbl[typedArrayName](Uint8Array.prototype.slice.call(data, 1).buffer)\n}\ncurrentExtensions[0x78] = () => {\n\tlet data = read()\n\treturn new RegExp(data[0], data[1])\n}\nconst TEMP_BUNDLE = []\ncurrentExtensions[0x62] = (data) => {\n\tlet dataSize = (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]\n\tlet dataPosition = position\n\tposition += dataSize - data.length\n\tbundledStrings = TEMP_BUNDLE\n\tbundledStrings = [readOnlyJSString(), readOnlyJSString()]\n\tbundledStrings.position0 = 0\n\tbundledStrings.position1 = 0\n\tbundledStrings.postBundlePosition = position\n\tposition = dataPosition\n\treturn read()\n}\n\ncurrentExtensions[0xff] = (data) => {\n\t// 32-bit date extension\n\tif (data.length == 4)\n\t\treturn new Date((data[0] * 0x1000000 + (data[1] << 16) + (data[2] << 8) + data[3]) * 1000)\n\telse if (data.length == 8)\n\t\treturn new Date(\n\t\t\t((data[0] << 22) + (data[1] << 14) + (data[2] << 6) + (data[3] >> 2)) / 1000000 +\n\t\t\t((data[3] & 0x3) * 0x100000000 + data[4] * 0x1000000 + (data[5] << 16) + (data[6] << 8) + data[7]) * 1000)\n\telse if (data.length == 12)// TODO: Implement support for negative\n\t\treturn new Date(\n\t\t\t((data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]) / 1000000 +\n\t\t\t(((data[4] & 0x80) ? -0x1000000000000 : 0) + data[6] * 0x10000000000 + data[7] * 0x100000000 + data[8] * 0x1000000 + (data[9] << 16) + (data[10] << 8) + data[11]) * 1000)\n\telse\n\t\treturn new Date('invalid')\n} // notepack defines extension 0 to mean undefined, so use that as the default here\n// registration of bulk record definition?\n// currentExtensions[0x52] = () =>\n\nfunction saveState(callback) {\n\tif (onSaveState)\n\t\tonSaveState();\n\tlet savedSrcEnd = srcEnd\n\tlet savedPosition = position\n\tlet savedStringPosition = stringPosition\n\tlet savedSrcStringStart = srcStringStart\n\tlet savedSrcStringEnd = srcStringEnd\n\tlet savedSrcString = srcString\n\tlet savedStrings = strings\n\tlet savedReferenceMap = referenceMap\n\tlet savedBundledStrings = bundledStrings\n\n\t// TODO: We may need to revisit this if we do more external calls to user code (since it could be slow)\n\tlet savedSrc = new Uint8Array(src.slice(0, srcEnd)) // we copy the data in case it changes while external data is processed\n\tlet savedStructures = currentStructures\n\tlet savedStructuresContents = currentStructures.slice(0, currentStructures.length)\n\tlet savedPackr = currentUnpackr\n\tlet savedSequentialMode = sequentialMode\n\tlet value = callback()\n\tsrcEnd = savedSrcEnd\n\tposition = savedPosition\n\tstringPosition = savedStringPosition\n\tsrcStringStart = savedSrcStringStart\n\tsrcStringEnd = savedSrcStringEnd\n\tsrcString = savedSrcString\n\tstrings = savedStrings\n\treferenceMap = savedReferenceMap\n\tbundledStrings = savedBundledStrings\n\tsrc = savedSrc\n\tsequentialMode = savedSequentialMode\n\tcurrentStructures = savedStructures\n\tcurrentStructures.splice(0, currentStructures.length, ...savedStructuresContents)\n\tcurrentUnpackr = savedPackr\n\tdataView = new DataView(src.buffer, src.byteOffset, src.byteLength)\n\treturn value\n}\nexport function clearSource() {\n\tsrc = null\n\treferenceMap = null\n\tcurrentStructures = null\n}\n\nexport function addExtension(extension) {\n\tif (extension.unpack)\n\t\tcurrentExtensions[extension.type] = extension.unpack\n\telse\n\t\tcurrentExtensions[extension.type] = extension\n}\n\nexport const mult10 = new Array(147) // this is a table matching binary exponents to the multiplier to determine significant digit rounding\nfor (let i = 0; i < 256; i++) {\n\tmult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103))\n}\nexport const Decoder = Unpackr\nvar defaultUnpackr = new Unpackr({ useRecords: false })\nexport const unpack = defaultUnpackr.unpack\nexport const unpackMultiple = defaultUnpackr.unpackMultiple\nexport const decode = defaultUnpackr.unpack\nexport const FLOAT32_OPTIONS = {\n\tNEVER: 0,\n\tALWAYS: 1,\n\tDECIMAL_ROUND: 3,\n\tDECIMAL_FIT: 4\n}\nlet f32Array = new Float32Array(1)\nlet u8Array = new Uint8Array(f32Array.buffer, 0, 4)\nexport function roundFloat32(float32Number) {\n\tf32Array[0] = float32Number\n\tlet multiplier = mult10[((u8Array[3] & 0x7f) << 1) | (u8Array[2] >> 7)]\n\treturn ((multiplier * float32Number + (float32Number > 0 ? 0.5 : -0.5)) >> 0) / multiplier\n}\nexport function setReadStruct(updatedReadStruct, loadedStructs, saveState) {\n\treadStruct = updatedReadStruct;\n\tonLoadedStructures = loadedStructs;\n\tonSaveState = saveState;\n}\n","import { Unpackr, mult10, C1Type, typedArrays, addExtension as unpackAddExtension } from './unpack.js'\nlet textEncoder\ntry {\n\ttextEncoder = new TextEncoder()\n} catch (error) {}\nlet extensions, extensionClasses\nconst hasNodeBuffer = typeof Buffer !== 'undefined'\nconst ByteArrayAllocate = hasNodeBuffer ?\n\tfunction(length) { return Buffer.allocUnsafeSlow(length) } : Uint8Array\nconst ByteArray = hasNodeBuffer ? Buffer : Uint8Array\nconst MAX_BUFFER_SIZE = hasNodeBuffer ? 0x100000000 : 0x7fd00000\nlet target, keysTarget\nlet targetView\nlet position = 0\nlet safeEnd\nlet bundledStrings = null\nlet writeStructSlots\nconst MAX_BUNDLE_SIZE = 0x5500 // maximum characters such that the encoded bytes fits in 16 bits.\nconst hasNonLatin = /[\\u0080-\\uFFFF]/\nexport const RECORD_SYMBOL = Symbol('record-id')\nexport class Packr extends Unpackr {\n\tconstructor(options) {\n\t\tsuper(options)\n\t\tthis.offset = 0\n\t\tlet typeBuffer\n\t\tlet start\n\t\tlet hasSharedUpdate\n\t\tlet structures\n\t\tlet referenceMap\n\t\tlet encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position) {\n\t\t\treturn target.utf8Write(string, position, target.byteLength - position)\n\t\t} : (textEncoder && textEncoder.encodeInto) ?\n\t\t\tfunction(string, position) {\n\t\t\t\treturn textEncoder.encodeInto(string, target.subarray(position)).written\n\t\t\t} : false\n\n\t\tlet packr = this\n\t\tif (!options)\n\t\t\toptions = {}\n\t\tlet isSequential = options && options.sequential\n\t\tlet hasSharedStructures = options.structures || options.saveStructures\n\t\tlet maxSharedStructures = options.maxSharedStructures\n\t\tif (maxSharedStructures == null)\n\t\t\tmaxSharedStructures = hasSharedStructures ? 32 : 0\n\t\tif (maxSharedStructures > 8160)\n\t\t\tthrow new Error('Maximum maxSharedStructure is 8160')\n\t\tif (options.structuredClone && options.moreTypes == undefined) {\n\t\t\tthis.moreTypes = true\n\t\t}\n\t\tlet maxOwnStructures = options.maxOwnStructures\n\t\tif (maxOwnStructures == null)\n\t\t\tmaxOwnStructures = hasSharedStructures ? 32 : 64\n\t\tif (!this.structures && options.useRecords != false)\n\t\t\tthis.structures = []\n\t\t// two byte record ids for shared structures\n\t\tlet useTwoByteRecords = maxSharedStructures > 32 || (maxOwnStructures + maxSharedStructures > 64)\n\t\tlet sharedLimitId = maxSharedStructures + 0x40\n\t\tlet maxStructureId = maxSharedStructures + maxOwnStructures + 0x40\n\t\tif (maxStructureId > 8256) {\n\t\t\tthrow new Error('Maximum maxSharedStructure + maxOwnStructure is 8192')\n\t\t}\n\t\tlet recordIdsToRemove = []\n\t\tlet transitionsCount = 0\n\t\tlet serializationsSinceTransitionRebuild = 0\n\n\t\tthis.pack = this.encode = function(value, encodeOptions) {\n\t\t\tif (!target) {\n\t\t\t\ttarget = new ByteArrayAllocate(8192)\n\t\t\t\ttargetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, 8192))\n\t\t\t\tposition = 0\n\t\t\t}\n\t\t\tsafeEnd = target.length - 10\n\t\t\tif (safeEnd - position < 0x800) {\n\t\t\t\t// don't start too close to the end,\n\t\t\t\ttarget = new ByteArrayAllocate(target.length)\n\t\t\t\ttargetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, target.length))\n\t\t\t\tsafeEnd = target.length - 10\n\t\t\t\tposition = 0\n\t\t\t} else\n\t\t\t\tposition = (position + 7) & 0x7ffffff8 // Word align to make any future copying of this buffer faster\n\t\t\tstart = position\n\t\t\tif (encodeOptions & RESERVE_START_SPACE) position += (encodeOptions & 0xff)\n\t\t\treferenceMap = packr.structuredClone ? new Map() : null\n\t\t\tif (packr.bundleStrings && typeof value !== 'string') {\n\t\t\t\tbundledStrings = []\n\t\t\t\tbundledStrings.size = Infinity // force a new bundle start on first string\n\t\t\t} else\n\t\t\t\tbundledStrings = null\n\t\t\tstructures = packr.structures\n\t\t\tif (structures) {\n\t\t\t\tif (structures.uninitialized)\n\t\t\t\t\tstructures = packr._mergeStructures(packr.getStructures())\n\t\t\t\tlet sharedLength = structures.sharedLength || 0\n\t\t\t\tif (sharedLength > maxSharedStructures) {\n\t\t\t\t\t//if (maxSharedStructures <= 32 && structures.sharedLength > 32) // TODO: could support this, but would need to update the limit ids\n\t\t\t\t\tthrow new Error('Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to ' + structures.sharedLength)\n\t\t\t\t}\n\t\t\t\tif (!structures.transitions) {\n\t\t\t\t\t// rebuild our structure transitions\n\t\t\t\t\tstructures.transitions = Object.create(null)\n\t\t\t\t\tfor (let i = 0; i < sharedLength; i++) {\n\t\t\t\t\t\tlet keys = structures[i]\n\t\t\t\t\t\tif (!keys)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tlet nextTransition, transition = structures.transitions\n\t\t\t\t\t\tfor (let j = 0, l = keys.length; j < l; j++) {\n\t\t\t\t\t\t\tlet key = keys[j]\n\t\t\t\t\t\t\tnextTransition = transition[key]\n\t\t\t\t\t\t\tif (!nextTransition) {\n\t\t\t\t\t\t\t\tnextTransition = transition[key] = Object.create(null)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttransition = nextTransition\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttransition[RECORD_SYMBOL] = i + 0x40\n\t\t\t\t\t}\n\t\t\t\t\tthis.lastNamedStructuresLength = sharedLength\n\t\t\t\t}\n\t\t\t\tif (!isSequential) {\n\t\t\t\t\tstructures.nextId = sharedLength + 0x40\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hasSharedUpdate)\n\t\t\t\thasSharedUpdate = false\n\t\t\tlet encodingError;\n\t\t\ttry {\n\t\t\t\tif (packr.randomAccessStructure && value && value.constructor && value.constructor === Object)\n\t\t\t\t\twriteStruct(value);\n\t\t\t\telse\n\t\t\t\t\tpack(value)\n\t\t\t\tlet lastBundle = bundledStrings;\n\t\t\t\tif (bundledStrings)\n\t\t\t\t\twriteBundles(start, pack, 0)\n\t\t\t\tif (referenceMap && referenceMap.idsToInsert) {\n\t\t\t\t\tlet idsToInsert = referenceMap.idsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1);\n\t\t\t\t\tlet i = idsToInsert.length;\n\t\t\t\t\tlet incrementPosition = -1;\n\t\t\t\t\twhile (lastBundle && i > 0) {\n\t\t\t\t\t\tlet insertionPoint = idsToInsert[--i].offset + start;\n\t\t\t\t\t\tif (insertionPoint < (lastBundle.stringsPosition + start) && incrementPosition === -1)\n\t\t\t\t\t\t\tincrementPosition = 0;\n\t\t\t\t\t\tif (insertionPoint > (lastBundle.position + start)) {\n\t\t\t\t\t\t\tif (incrementPosition >= 0)\n\t\t\t\t\t\t\t\tincrementPosition += 6;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (incrementPosition >= 0) {\n\t\t\t\t\t\t\t\t// update the bundle reference now\n\t\t\t\t\t\t\t\ttargetView.setUint32(lastBundle.position + start,\n\t\t\t\t\t\t\t\t\ttargetView.getUint32(lastBundle.position + start) + incrementPosition)\n\t\t\t\t\t\t\t\tincrementPosition = -1; // reset\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tlastBundle = lastBundle.previous;\n\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (incrementPosition >= 0 && lastBundle) {\n\t\t\t\t\t\t// update the bundle reference now\n\t\t\t\t\t\ttargetView.setUint32(lastBundle.position + start,\n\t\t\t\t\t\t\ttargetView.getUint32(lastBundle.position + start) + incrementPosition)\n\t\t\t\t\t}\n\t\t\t\t\tposition += idsToInsert.length * 6;\n\t\t\t\t\tif (position > safeEnd)\n\t\t\t\t\t\tmakeRoom(position)\n\t\t\t\t\tpackr.offset = position\n\t\t\t\t\tlet serialized = insertIds(target.subarray(start, position), idsToInsert)\n\t\t\t\t\treferenceMap = null\n\t\t\t\t\treturn serialized\n\t\t\t\t}\n\t\t\t\tpackr.offset = position // update the offset so next serialization doesn't write over our buffer, but can continue writing to same buffer sequentially\n\t\t\t\tif (encodeOptions & REUSE_BUFFER_MODE) {\n\t\t\t\t\ttarget.start = start\n\t\t\t\t\ttarget.end = position\n\t\t\t\t\treturn target\n\t\t\t\t}\n\t\t\t\treturn target.subarray(start, position) // position can change if we call pack again in saveStructures, so we get the buffer now\n\t\t\t} catch(error) {\n\t\t\t\tencodingError = error;\n\t\t\t\tthrow error;\n\t\t\t} finally {\n\t\t\t\tif (structures) {\n\t\t\t\t\tresetStructures();\n\t\t\t\t\tif (hasSharedUpdate && packr.saveStructures) {\n\t\t\t\t\t\tlet sharedLength = structures.sharedLength || 0\n\t\t\t\t\t\t// we can't rely on start/end with REUSE_BUFFER_MODE since they will (probably) change when we save\n\t\t\t\t\t\tlet returnBuffer = target.subarray(start, position)\n\t\t\t\t\t\tlet newSharedData = prepareStructures(structures, packr);\n\t\t\t\t\t\tif (!encodingError) { // TODO: If there is an encoding error, should make the structures as uninitialized so they get rebuilt next time\n\t\t\t\t\t\t\tif (packr.saveStructures(newSharedData, newSharedData.isCompatible) === false) {\n\t\t\t\t\t\t\t\t// get updated structures and try again if the update failed\n\t\t\t\t\t\t\t\treturn packr.pack(value, encodeOptions)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpackr.lastNamedStructuresLength = sharedLength\n\t\t\t\t\t\t\t// don't keep large buffers around\n\t\t\t\t\t\t\tif (target.length > 0x40000000) target = null\n\t\t\t\t\t\t\treturn returnBuffer\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// don't keep large buffers around, they take too much memory and cause problems (limit at 1GB)\n\t\t\t\tif (target.length > 0x40000000) target = null\n\t\t\t\tif (encodeOptions & RESET_BUFFER_MODE)\n\t\t\t\t\tposition = start\n\t\t\t}\n\t\t}\n\t\tconst resetStructures = () => {\n\t\t\tif (serializationsSinceTransitionRebuild < 10)\n\t\t\t\tserializationsSinceTransitionRebuild++\n\t\t\tlet sharedLength = structures.sharedLength || 0\n\t\t\tif (structures.length > sharedLength && !isSequential)\n\t\t\t\tstructures.length = sharedLength\n\t\t\tif (transitionsCount > 10000) {\n\t\t\t\t// force a rebuild occasionally after a lot of transitions so it can get cleaned up\n\t\t\t\tstructures.transitions = null\n\t\t\t\tserializationsSinceTransitionRebuild = 0\n\t\t\t\ttransitionsCount = 0\n\t\t\t\tif (recordIdsToRemove.length > 0)\n\t\t\t\t\trecordIdsToRemove = []\n\t\t\t} else if (recordIdsToRemove.length > 0 && !isSequential) {\n\t\t\t\tfor (let i = 0, l = recordIdsToRemove.length; i < l; i++) {\n\t\t\t\t\trecordIdsToRemove[i][RECORD_SYMBOL] = 0\n\t\t\t\t}\n\t\t\t\trecordIdsToRemove = []\n\t\t\t}\n\t\t}\n\t\tconst packArray = (value) => {\n\t\t\tvar length = value.length\n\t\t\tif (length < 0x10) {\n\t\t\t\ttarget[position++] = 0x90 | length\n\t\t\t} else if (length < 0x10000) {\n\t\t\t\ttarget[position++] = 0xdc\n\t\t\t\ttarget[position++] = length >> 8\n\t\t\t\ttarget[position++] = length & 0xff\n\t\t\t} else {\n\t\t\t\ttarget[position++] = 0xdd\n\t\t\t\ttargetView.setUint32(position, length)\n\t\t\t\tposition += 4\n\t\t\t}\n\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\tpack(value[i])\n\t\t\t}\n\t\t}\n\t\tconst pack = (value) => {\n\t\t\tif (position > safeEnd)\n\t\t\t\ttarget = makeRoom(position)\n\n\t\t\tvar type = typeof value\n\t\t\tvar length\n\t\t\tif (type === 'string') {\n\t\t\t\tlet strLength = value.length\n\t\t\t\tif (bundledStrings && strLength >= 4 && strLength < 0x1000) {\n\t\t\t\t\tif ((bundledStrings.size += strLength) > MAX_BUNDLE_SIZE) {\n\t\t\t\t\t\tlet extStart\n\t\t\t\t\t\tlet maxBytes = (bundledStrings[0] ? bundledStrings[0].length * 3 + bundledStrings[1].length : 0) + 10\n\t\t\t\t\t\tif (position + maxBytes > safeEnd)\n\t\t\t\t\t\t\ttarget = makeRoom(position + maxBytes)\n\t\t\t\t\t\tlet lastBundle\n\t\t\t\t\t\tif (bundledStrings.position) { // here we use the 0x62 extension to write the last bundle and reserve space for the reference pointer to the next/current bundle\n\t\t\t\t\t\t\tlastBundle = bundledStrings\n\t\t\t\t\t\t\ttarget[position] = 0xc8 // ext 16\n\t\t\t\t\t\t\tposition += 3 // reserve for the writing bundle size\n\t\t\t\t\t\t\ttarget[position++] = 0x62 // 'b'\n\t\t\t\t\t\t\textStart = position - start\n\t\t\t\t\t\t\tposition += 4 // reserve for writing bundle reference\n\t\t\t\t\t\t\twriteBundles(start, pack, 0) // write the last bundles\n\t\t\t\t\t\t\ttargetView.setUint16(extStart + start - 3, position - start - extStart)\n\t\t\t\t\t\t} else { // here we use the 0x62 extension just to reserve the space for the reference pointer to the bundle (will be updated once the bundle is written)\n\t\t\t\t\t\t\ttarget[position++] = 0xd6 // fixext 4\n\t\t\t\t\t\t\ttarget[position++] = 0x62 // 'b'\n\t\t\t\t\t\t\textStart = position - start\n\t\t\t\t\t\t\tposition += 4 // reserve for writing bundle reference\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbundledStrings = ['', ''] // create new ones\n\t\t\t\t\t\tbundledStrings.previous = lastBundle;\n\t\t\t\t\t\tbundledStrings.size = 0\n\t\t\t\t\t\tbundledStrings.position = extStart\n\t\t\t\t\t}\n\t\t\t\t\tlet twoByte = hasNonLatin.test(value)\n\t\t\t\t\tbundledStrings[twoByte ? 0 : 1] += value\n\t\t\t\t\ttarget[position++] = 0xc1\n\t\t\t\t\tpack(twoByte ? -strLength : strLength);\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tlet headerSize\n\t\t\t\t// first we estimate the header size, so we can write to the correct location\n\t\t\t\tif (strLength < 0x20) {\n\t\t\t\t\theaderSize = 1\n\t\t\t\t} else if (strLength < 0x100) {\n\t\t\t\t\theaderSize = 2\n\t\t\t\t} else if (strLength < 0x10000) {\n\t\t\t\t\theaderSize = 3\n\t\t\t\t} else {\n\t\t\t\t\theaderSize = 5\n\t\t\t\t}\n\t\t\t\tlet maxBytes = strLength * 3\n\t\t\t\tif (position + maxBytes > safeEnd)\n\t\t\t\t\ttarget = makeRoom(position + maxBytes)\n\n\t\t\t\tif (strLength < 0x40 || !encodeUtf8) {\n\t\t\t\t\tlet i, c1, c2, strPosition = position + headerSize\n\t\t\t\t\tfor (i = 0; i < strLength; i++) {\n\t\t\t\t\t\tc1 = value.charCodeAt(i)\n\t\t\t\t\t\tif (c1 < 0x80) {\n\t\t\t\t\t\t\ttarget[strPosition++] = c1\n\t\t\t\t\t\t} else if (c1 < 0x800) {\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 6 | 0xc0\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 & 0x3f | 0x80\n\t\t\t\t\t\t} else if (\n\t\t\t\t\t\t\t(c1 & 0xfc00) === 0xd800 &&\n\t\t\t\t\t\t\t((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tc1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff)\n\t\t\t\t\t\t\ti++\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 18 | 0xf0\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 12 & 0x3f | 0x80\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 6 & 0x3f | 0x80\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 & 0x3f | 0x80\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 12 | 0xe0\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 6 & 0x3f | 0x80\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 & 0x3f | 0x80\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlength = strPosition - position - headerSize\n\t\t\t\t} else {\n\t\t\t\t\tlength = encodeUtf8(value, position + headerSize)\n\t\t\t\t}\n\n\t\t\t\tif (length < 0x20) {\n\t\t\t\t\ttarget[position++] = 0xa0 | length\n\t\t\t\t} else if (length < 0x100) {\n\t\t\t\t\tif (headerSize < 2) {\n\t\t\t\t\t\ttarget.copyWithin(position + 2, position + 1, position + 1 + length)\n\t\t\t\t\t}\n\t\t\t\t\ttarget[position++] = 0xd9\n\t\t\t\t\ttarget[position++] = length\n\t\t\t\t} else if (length < 0x10000) {\n\t\t\t\t\tif (headerSize < 3) {\n\t\t\t\t\t\ttarget.copyWithin(position + 3, position + 2, position + 2 + length)\n\t\t\t\t\t}\n\t\t\t\t\ttarget[position++] = 0xda\n\t\t\t\t\ttarget[position++] = length >> 8\n\t\t\t\t\ttarget[position++] = length & 0xff\n\t\t\t\t} else {\n\t\t\t\t\tif (headerSize < 5) {\n\t\t\t\t\t\ttarget.copyWithin(position + 5, position + 3, position + 3 + length)\n\t\t\t\t\t}\n\t\t\t\t\ttarget[position++] = 0xdb\n\t\t\t\t\ttargetView.setUint32(position, length)\n\t\t\t\t\tposition += 4\n\t\t\t\t}\n\t\t\t\tposition += length\n\t\t\t} else if (type === 'number') {\n\t\t\t\tif (value >>> 0 === value) {// positive integer, 32-bit or less\n\t\t\t\t\t// positive uint\n\t\t\t\t\tif (value < 0x20 || (value < 0x80 && this.useRecords === false) || (value < 0x40 && !this.randomAccessStructure)) {\n\t\t\t\t\t\ttarget[position++] = value\n\t\t\t\t\t} else if (value < 0x100) {\n\t\t\t\t\t\ttarget[position++] = 0xcc\n\t\t\t\t\t\ttarget[position++] = value\n\t\t\t\t\t} else if (value < 0x10000) {\n\t\t\t\t\t\ttarget[position++] = 0xcd\n\t\t\t\t\t\ttarget[position++] = value >> 8\n\t\t\t\t\t\ttarget[position++] = value & 0xff\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttarget[position++] = 0xce\n\t\t\t\t\t\ttargetView.setUint32(position, value)\n\t\t\t\t\t\tposition += 4\n\t\t\t\t\t}\n\t\t\t\t} else if (value >> 0 === value) { // negative integer\n\t\t\t\t\tif (value >= -0x20) {\n\t\t\t\t\t\ttarget[position++] = 0x100 + value\n\t\t\t\t\t} else if (value >= -0x80) {\n\t\t\t\t\t\ttarget[position++] = 0xd0\n\t\t\t\t\t\ttarget[position++] = value + 0x100\n\t\t\t\t\t} else if (value >= -0x8000) {\n\t\t\t\t\t\ttarget[position++] = 0xd1\n\t\t\t\t\t\ttargetView.setInt16(position, value)\n\t\t\t\t\t\tposition += 2\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttarget[position++] = 0xd2\n\t\t\t\t\t\ttargetView.setInt32(position, value)\n\t\t\t\t\t\tposition += 4\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlet useFloat32\n\t\t\t\t\tif ((useFloat32 = this.useFloat32) > 0 && value < 0x100000000 && value >= -0x80000000) {\n\t\t\t\t\t\ttarget[position++] = 0xca\n\t\t\t\t\t\ttargetView.setFloat32(position, value)\n\t\t\t\t\t\tlet xShifted\n\t\t\t\t\t\tif (useFloat32 < 4 ||\n\t\t\t\t\t\t\t\t// this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved\n\t\t\t\t\t\t\t\t((xShifted = value * mult10[((target[position] & 0x7f) << 1) | (target[position + 1] >> 7)]) >> 0) === xShifted) {\n\t\t\t\t\t\t\tposition += 4\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\tposition-- // move back into position for writing a double\n\t\t\t\t\t}\n\t\t\t\t\ttarget[position++] = 0xcb\n\t\t\t\t\ttargetView.setFloat64(position, value)\n\t\t\t\t\tposition += 8\n\t\t\t\t}\n\t\t\t} else if (type === 'object' || type === 'function') {\n\t\t\t\tif (!value)\n\t\t\t\t\ttarget[position++] = 0xc0\n\t\t\t\telse {\n\t\t\t\t\tif (referenceMap) {\n\t\t\t\t\t\tlet referee = referenceMap.get(value)\n\t\t\t\t\t\tif (referee) {\n\t\t\t\t\t\t\tif (!referee.id) {\n\t\t\t\t\t\t\t\tlet idsToInsert = referenceMap.idsToInsert || (referenceMap.idsToInsert = [])\n\t\t\t\t\t\t\t\treferee.id = idsToInsert.push(referee)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttarget[position++] = 0xd6 // fixext 4\n\t\t\t\t\t\t\ttarget[position++] = 0x70 // \"p\" for pointer\n\t\t\t\t\t\t\ttargetView.setUint32(position, referee.id)\n\t\t\t\t\t\t\tposition += 4\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\treferenceMap.set(value, { offset: position - start })\n\t\t\t\t\t}\n\t\t\t\t\tlet constructor = value.constructor\n\t\t\t\t\tif (constructor === Object) {\n\t\t\t\t\t\twriteObject(value)\n\t\t\t\t\t} else if (constructor === Array) {\n\t\t\t\t\t\tpackArray(value)\n\t\t\t\t\t} else if (constructor === Map) {\n\t\t\t\t\t\tif (this.mapAsEmptyObject) target[position++] = 0x80\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tlength = value.size\n\t\t\t\t\t\t\tif (length < 0x10) {\n\t\t\t\t\t\t\t\ttarget[position++] = 0x80 | length\n\t\t\t\t\t\t\t} else if (length < 0x10000) {\n\t\t\t\t\t\t\t\ttarget[position++] = 0xde\n\t\t\t\t\t\t\t\ttarget[position++] = length >> 8\n\t\t\t\t\t\t\t\ttarget[position++] = length & 0xff\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\ttarget[position++] = 0xdf\n\t\t\t\t\t\t\t\ttargetView.setUint32(position, length)\n\t\t\t\t\t\t\t\tposition += 4\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfor (let [key, entryValue] of value) {\n\t\t\t\t\t\t\t\tpack(key)\n\t\t\t\t\t\t\t\tpack(entryValue)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfor (let i = 0, l = extensions.length; i < l; i++) {\n\t\t\t\t\t\t\tlet extensionClass = extensionClasses[i]\n\t\t\t\t\t\t\tif (value instanceof extensionClass) {\n\t\t\t\t\t\t\t\tlet extension = extensions[i]\n\t\t\t\t\t\t\t\tif (extension.write) {\n\t\t\t\t\t\t\t\t\tif (extension.type) {\n\t\t\t\t\t\t\t\t\t\ttarget[position++] = 0xd4 // one byte \"tag\" extension\n\t\t\t\t\t\t\t\t\t\ttarget[position++] = extension.type\n\t\t\t\t\t\t\t\t\t\ttarget[position++] = 0\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tlet writeResult = extension.write.call(this, value)\n\t\t\t\t\t\t\t\t\tif (writeResult === value) { // avoid infinite recursion\n\t\t\t\t\t\t\t\t\t\tif (Array.isArray(value)) {\n\t\t\t\t\t\t\t\t\t\t\tpackArray(value)\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\twriteObject(value)\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tpack(writeResult)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tlet currentTarget = target\n\t\t\t\t\t\t\t\tlet currentTargetView = targetView\n\t\t\t\t\t\t\t\tlet currentPosition = position\n\t\t\t\t\t\t\t\ttarget = null\n\t\t\t\t\t\t\t\tlet result\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tresult = extension.pack.call(this, value, (size) => {\n\t\t\t\t\t\t\t\t\t\t// restore target and use it\n\t\t\t\t\t\t\t\t\t\ttarget = currentTarget\n\t\t\t\t\t\t\t\t\t\tcurrentTarget = null\n\t\t\t\t\t\t\t\t\t\tposition += size\n\t\t\t\t\t\t\t\t\t\tif (position > safeEnd)\n\t\t\t\t\t\t\t\t\t\t\tmakeRoom(position)\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\ttarget, targetView, position: position - size\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}, pack)\n\t\t\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\t\t\t// restore current target information (unless already restored)\n\t\t\t\t\t\t\t\t\tif (currentTarget) {\n\t\t\t\t\t\t\t\t\t\ttarget = currentTarget\n\t\t\t\t\t\t\t\t\t\ttargetView = currentTargetView\n\t\t\t\t\t\t\t\t\t\tposition = currentPosition\n\t\t\t\t\t\t\t\t\t\tsafeEnd = target.length - 10\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (result) {\n\t\t\t\t\t\t\t\t\tif (result.length + position > safeEnd)\n\t\t\t\t\t\t\t\t\t\tmakeRoom(result.length + position)\n\t\t\t\t\t\t\t\t\tposition = writeExtensionData(result, target, position, extension.type)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// check isArray after extensions, because extensions can extend Array\n\t\t\t\t\t\tif (Array.isArray(value)) {\n\t\t\t\t\t\t\tpackArray(value)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// use this as an alternate mechanism for expressing how to serialize\n\t\t\t\t\t\t\tif (value.toJSON) {\n\t\t\t\t\t\t\t\tconst json = value.toJSON()\n\t\t\t\t\t\t\t\t// if for some reason value.toJSON returns itself it'll loop forever\n\t\t\t\t\t\t\t\tif (json !== value)\n\t\t\t\t\t\t\t\t\treturn pack(json)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// if there is a writeFunction, use it, otherwise just encode as undefined\n\t\t\t\t\t\t\tif (type === 'function')\n\t\t\t\t\t\t\t\treturn pack(this.writeFunction && this.writeFunction(value));\n\n\t\t\t\t\t\t\t// no extension found, write as plain object\n\t\t\t\t\t\t\twriteObject(value)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (type === 'boolean') {\n\t\t\t\ttarget[position++] = value ? 0xc3 : 0xc2\n\t\t\t} else if (type === 'bigint') {\n\t\t\t\tif (value < (BigInt(1)<= -(BigInt(1)< 0) {\n\t\t\t\t\t// if we can fit an unsigned int, use that\n\t\t\t\t\ttarget[position++] = 0xcf\n\t\t\t\t\ttargetView.setBigUint64(position, value)\n\t\t\t\t} else {\n\t\t\t\t\t// overflow\n\t\t\t\t\tif (this.largeBigIntToFloat) {\n\t\t\t\t\t\ttarget[position++] = 0xcb\n\t\t\t\t\t\ttargetView.setFloat64(position, Number(value))\n\t\t\t\t\t} else if (this.largeBigIntToString) {\n\t\t\t\t\t\treturn pack(value.toString());\n\t\t\t\t\t} else if (this.useBigIntExtension && value < BigInt(2)**BigInt(1023) && value > -(BigInt(2)**BigInt(1023))) {\n\t\t\t\t\t\ttarget[position++] = 0xc7\n\t\t\t\t\t\tposition++;\n\t\t\t\t\t\ttarget[position++] = 0x42 // \"B\" for BigInt\n\t\t\t\t\t\tlet bytes = [];\n\t\t\t\t\t\tlet alignedSign;\n\t\t\t\t\t\tdo {\n\t\t\t\t\t\t\tlet byte = value & BigInt(0xff);\n\t\t\t\t\t\t\talignedSign = (byte & BigInt(0x80)) === (value < BigInt(0) ? BigInt(0x80) : BigInt(0));\n\t\t\t\t\t\t\tbytes.push(byte);\n\t\t\t\t\t\t\tvalue >>= BigInt(8);\n\t\t\t\t\t\t} while (!((value === BigInt(0) || value === BigInt(-1)) && alignedSign));\n\t\t\t\t\t\ttarget[position-2] = bytes.length;\n\t\t\t\t\t\tfor (let i = bytes.length; i > 0;) {\n\t\t\t\t\t\t\ttarget[position++] = Number(bytes[--i]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow new RangeError(value + ' was too large to fit in MessagePack 64-bit integer format, use' +\n\t\t\t\t\t\t\t' useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set' +\n\t\t\t\t\t\t\t' largeBigIntToString to convert to string')\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tposition += 8\n\t\t\t} else if (type === 'undefined') {\n\t\t\t\tif (this.encodeUndefinedAsNil)\n\t\t\t\t\ttarget[position++] = 0xc0\n\t\t\t\telse {\n\t\t\t\t\ttarget[position++] = 0xd4 // a number of implementations use fixext1 with type 0, data 0 to denote undefined, so we follow suite\n\t\t\t\t\ttarget[position++] = 0\n\t\t\t\t\ttarget[position++] = 0\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow new Error('Unknown type: ' + type)\n\t\t\t}\n\t\t}\n\n\t\tconst writePlainObject = (this.variableMapSize || this.coercibleKeyAsNumber || this.skipValues) ? (object) => {\n\t\t\t// this method is slightly slower, but generates \"preferred serialization\" (optimally small for smaller objects)\n\t\t\tlet keys;\n\t\t\tif (this.skipValues) {\n\t\t\t\tkeys = [];\n\t\t\t\tfor (let key in object) {\n\t\t\t\t\tif ((typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) &&\n\t\t\t\t\t\t!this.skipValues.includes(object[key]))\n\t\t\t\t\t\tkeys.push(key);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tkeys = Object.keys(object)\n\t\t\t}\n\t\t\tlet length = keys.length\n\t\t\tif (length < 0x10) {\n\t\t\t\ttarget[position++] = 0x80 | length\n\t\t\t} else if (length < 0x10000) {\n\t\t\t\ttarget[position++] = 0xde\n\t\t\t\ttarget[position++] = length >> 8\n\t\t\t\ttarget[position++] = length & 0xff\n\t\t\t} else {\n\t\t\t\ttarget[position++] = 0xdf\n\t\t\t\ttargetView.setUint32(position, length)\n\t\t\t\tposition += 4\n\t\t\t}\n\t\t\tlet key\n\t\t\tif (this.coercibleKeyAsNumber) {\n\t\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\t\tkey = keys[i]\n\t\t\t\t\tlet num = Number(key)\n\t\t\t\t\tpack(isNaN(num) ? key : num)\n\t\t\t\t\tpack(object[key])\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\t\tpack(key = keys[i])\n\t\t\t\t\tpack(object[key])\n\t\t\t\t}\n\t\t\t}\n\t\t} :\n\t\t(object) => {\n\t\t\ttarget[position++] = 0xde // always using map 16, so we can preallocate and set the length afterwards\n\t\t\tlet objectOffset = position - start\n\t\t\tposition += 2\n\t\t\tlet size = 0\n\t\t\tfor (let key in object) {\n\t\t\t\tif (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {\n\t\t\t\t\tpack(key)\n\t\t\t\t\tpack(object[key])\n\t\t\t\t\tsize++\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (size > 0xffff) {\n\t\t\t\tthrow new Error('Object is too large to serialize with fast 16-bit map size,' +\n\t\t\t\t' use the \"variableMapSize\" option to serialize this object');\n\t\t\t}\n\t\t\ttarget[objectOffset++ + start] = size >> 8\n\t\t\ttarget[objectOffset + start] = size & 0xff\n\t\t}\n\n\t\tconst writeRecord = this.useRecords === false ? writePlainObject :\n\t\t(options.progressiveRecords && !useTwoByteRecords) ? // this is about 2% faster for highly stable structures, since it only requires one for-in loop (but much more expensive when new structure needs to be written)\n\t\t(object) => {\n\t\t\tlet nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null))\n\t\t\tlet objectOffset = position++ - start\n\t\t\tlet wroteKeys\n\t\t\tfor (let key in object) {\n\t\t\t\tif (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {\n\t\t\t\t\tnextTransition = transition[key]\n\t\t\t\t\tif (nextTransition)\n\t\t\t\t\t\ttransition = nextTransition\n\t\t\t\t\telse {\n\t\t\t\t\t\t// record doesn't exist, create full new record and insert it\n\t\t\t\t\t\tlet keys = Object.keys(object)\n\t\t\t\t\t\tlet lastTransition = transition\n\t\t\t\t\t\ttransition = structures.transitions\n\t\t\t\t\t\tlet newTransitions = 0\n\t\t\t\t\t\tfor (let i = 0, l = keys.length; i < l; i++) {\n\t\t\t\t\t\t\tlet key = keys[i]\n\t\t\t\t\t\t\tnextTransition = transition[key]\n\t\t\t\t\t\t\tif (!nextTransition) {\n\t\t\t\t\t\t\t\tnextTransition = transition[key] = Object.create(null)\n\t\t\t\t\t\t\t\tnewTransitions++\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttransition = nextTransition\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (objectOffset + start + 1 == position) {\n\t\t\t\t\t\t\t// first key, so we don't need to insert, we can just write record directly\n\t\t\t\t\t\t\tposition--\n\t\t\t\t\t\t\tnewRecord(transition, keys, newTransitions)\n\t\t\t\t\t\t} else // otherwise we need to insert the record, moving existing data after the record\n\t\t\t\t\t\t\tinsertNewRecord(transition, keys, objectOffset, newTransitions)\n\t\t\t\t\t\twroteKeys = true\n\t\t\t\t\t\ttransition = lastTransition[key]\n\t\t\t\t\t}\n\t\t\t\t\tpack(object[key])\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!wroteKeys) {\n\t\t\t\tlet recordId = transition[RECORD_SYMBOL]\n\t\t\t\tif (recordId)\n\t\t\t\t\ttarget[objectOffset + start] = recordId\n\t\t\t\telse\n\t\t\t\t\tinsertNewRecord(transition, Object.keys(object), objectOffset, 0)\n\t\t\t}\n\t\t} :\n\t\t(object) => {\n\t\t\tlet nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null))\n\t\t\tlet newTransitions = 0\n\t\t\tfor (let key in object) if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {\n\t\t\t\tnextTransition = transition[key]\n\t\t\t\tif (!nextTransition) {\n\t\t\t\t\tnextTransition = transition[key] = Object.create(null)\n\t\t\t\t\tnewTransitions++\n\t\t\t\t}\n\t\t\t\ttransition = nextTransition\n\t\t\t}\n\t\t\tlet recordId = transition[RECORD_SYMBOL]\n\t\t\tif (recordId) {\n\t\t\t\tif (recordId >= 0x60 && useTwoByteRecords) {\n\t\t\t\t\ttarget[position++] = ((recordId -= 0x60) & 0x1f) + 0x60\n\t\t\t\t\ttarget[position++] = recordId >> 5\n\t\t\t\t} else\n\t\t\t\t\ttarget[position++] = recordId\n\t\t\t} else {\n\t\t\t\tnewRecord(transition, transition.__keys__ || Object.keys(object), newTransitions)\n\t\t\t}\n\t\t\t// now write the values\n\t\t\tfor (let key in object)\n\t\t\t\tif (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {\n\t\t\t\t\tpack(object[key])\n\t\t\t\t}\n\t\t}\n\n\t\t// create reference to useRecords if useRecords is a function\n\t\tconst checkUseRecords = typeof this.useRecords == 'function' && this.useRecords;\n\n\t\tconst writeObject = checkUseRecords ? (object) => {\n\t\t\tcheckUseRecords(object) ? writeRecord(object) : writePlainObject(object)\n\t\t} : writeRecord\n\n\t\tconst makeRoom = (end) => {\n\t\t\tlet newSize\n\t\t\tif (end > 0x1000000) {\n\t\t\t\t// special handling for really large buffers\n\t\t\t\tif ((end - start) > MAX_BUFFER_SIZE)\n\t\t\t\t\tthrow new Error('Packed buffer would be larger than maximum buffer size')\n\t\t\t\tnewSize = Math.min(MAX_BUFFER_SIZE,\n\t\t\t\t\tMath.round(Math.max((end - start) * (end > 0x4000000 ? 1.25 : 2), 0x400000) / 0x1000) * 0x1000)\n\t\t\t} else // faster handling for smaller buffers\n\t\t\t\tnewSize = ((Math.max((end - start) << 2, target.length - 1) >> 12) + 1) << 12\n\t\t\tlet newBuffer = new ByteArrayAllocate(newSize)\n\t\t\ttargetView = newBuffer.dataView || (newBuffer.dataView = new DataView(newBuffer.buffer, 0, newSize))\n\t\t\tend = Math.min(end, target.length)\n\t\t\tif (target.copy)\n\t\t\t\ttarget.copy(newBuffer, 0, start, end)\n\t\t\telse\n\t\t\t\tnewBuffer.set(target.slice(start, end))\n\t\t\tposition -= start\n\t\t\tstart = 0\n\t\t\tsafeEnd = newBuffer.length - 10\n\t\t\treturn target = newBuffer\n\t\t}\n\t\tconst newRecord = (transition, keys, newTransitions) => {\n\t\t\tlet recordId = structures.nextId\n\t\t\tif (!recordId)\n\t\t\t\trecordId = 0x40\n\t\t\tif (recordId < sharedLimitId && this.shouldShareStructure && !this.shouldShareStructure(keys)) {\n\t\t\t\trecordId = structures.nextOwnId\n\t\t\t\tif (!(recordId < maxStructureId))\n\t\t\t\t\trecordId = sharedLimitId\n\t\t\t\tstructures.nextOwnId = recordId + 1\n\t\t\t} else {\n\t\t\t\tif (recordId >= maxStructureId)// cycle back around\n\t\t\t\t\trecordId = sharedLimitId\n\t\t\t\tstructures.nextId = recordId + 1\n\t\t\t}\n\t\t\tlet highByte = keys.highByte = recordId >= 0x60 && useTwoByteRecords ? (recordId - 0x60) >> 5 : -1\n\t\t\ttransition[RECORD_SYMBOL] = recordId\n\t\t\ttransition.__keys__ = keys\n\t\t\tstructures[recordId - 0x40] = keys\n\n\t\t\tif (recordId < sharedLimitId) {\n\t\t\t\tkeys.isShared = true\n\t\t\t\tstructures.sharedLength = recordId - 0x3f\n\t\t\t\thasSharedUpdate = true\n\t\t\t\tif (highByte >= 0) {\n\t\t\t\t\ttarget[position++] = (recordId & 0x1f) + 0x60\n\t\t\t\t\ttarget[position++] = highByte\n\t\t\t\t} else {\n\t\t\t\t\ttarget[position++] = recordId\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (highByte >= 0) {\n\t\t\t\t\ttarget[position++] = 0xd5 // fixext 2\n\t\t\t\t\ttarget[position++] = 0x72 // \"r\" record defintion extension type\n\t\t\t\t\ttarget[position++] = (recordId & 0x1f) + 0x60\n\t\t\t\t\ttarget[position++] = highByte\n\t\t\t\t} else {\n\t\t\t\t\ttarget[position++] = 0xd4 // fixext 1\n\t\t\t\t\ttarget[position++] = 0x72 // \"r\" record defintion extension type\n\t\t\t\t\ttarget[position++] = recordId\n\t\t\t\t}\n\n\t\t\t\tif (newTransitions)\n\t\t\t\t\ttransitionsCount += serializationsSinceTransitionRebuild * newTransitions\n\t\t\t\t// record the removal of the id, we can maintain our shared structure\n\t\t\t\tif (recordIdsToRemove.length >= maxOwnStructures)\n\t\t\t\t\trecordIdsToRemove.shift()[RECORD_SYMBOL] = 0 // we are cycling back through, and have to remove old ones\n\t\t\t\trecordIdsToRemove.push(transition)\n\t\t\t\tpack(keys)\n\t\t\t}\n\t\t}\n\t\tconst insertNewRecord = (transition, keys, insertionOffset, newTransitions) => {\n\t\t\tlet mainTarget = target\n\t\t\tlet mainPosition = position\n\t\t\tlet mainSafeEnd = safeEnd\n\t\t\tlet mainStart = start\n\t\t\ttarget = keysTarget\n\t\t\tposition = 0\n\t\t\tstart = 0\n\t\t\tif (!target)\n\t\t\t\tkeysTarget = target = new ByteArrayAllocate(8192)\n\t\t\tsafeEnd = target.length - 10\n\t\t\tnewRecord(transition, keys, newTransitions)\n\t\t\tkeysTarget = target\n\t\t\tlet keysPosition = position\n\t\t\ttarget = mainTarget\n\t\t\tposition = mainPosition\n\t\t\tsafeEnd = mainSafeEnd\n\t\t\tstart = mainStart\n\t\t\tif (keysPosition > 1) {\n\t\t\t\tlet newEnd = position + keysPosition - 1\n\t\t\t\tif (newEnd > safeEnd)\n\t\t\t\t\tmakeRoom(newEnd)\n\t\t\t\tlet insertionPosition = insertionOffset + start\n\t\t\t\ttarget.copyWithin(insertionPosition + keysPosition, insertionPosition + 1, position)\n\t\t\t\ttarget.set(keysTarget.slice(0, keysPosition), insertionPosition)\n\t\t\t\tposition = newEnd\n\t\t\t} else {\n\t\t\t\ttarget[insertionOffset + start] = keysTarget[0]\n\t\t\t}\n\t\t}\n\t\tconst writeStruct = (object) => {\n\t\t\tlet newPosition = writeStructSlots(object, target, start, position, structures, makeRoom, (value, newPosition, notifySharedUpdate) => {\n\t\t\t\tif (notifySharedUpdate)\n\t\t\t\t\treturn hasSharedUpdate = true;\n\t\t\t\tposition = newPosition;\n\t\t\t\tlet startTarget = target;\n\t\t\t\tpack(value);\n\t\t\t\tresetStructures();\n\t\t\t\tif (startTarget !== target) {\n\t\t\t\t\treturn { position, targetView, target }; // indicate the buffer was re-allocated\n\t\t\t\t}\n\t\t\t\treturn position;\n\t\t\t}, this);\n\t\t\tif (newPosition === 0) // bail and go to a msgpack object\n\t\t\t\treturn writeObject(object);\n\t\t\tposition = newPosition;\n\t\t}\n\t}\n\tuseBuffer(buffer) {\n\t\t// this means we are finished using our own buffer and we can write over it safely\n\t\ttarget = buffer\n\t\ttarget.dataView || (target.dataView = new DataView(target.buffer, target.byteOffset, target.byteLength))\n\t\tposition = 0\n\t}\n\tset position (value) {\n\t\tposition = value;\n\t}\n\tget position() {\n\t\treturn position;\n\t}\n\tclearSharedData() {\n\t\tif (this.structures)\n\t\t\tthis.structures = []\n\t\tif (this.typedStructs)\n\t\t\tthis.typedStructs = []\n\t}\n}\n\nextensionClasses = [ Date, Set, Error, RegExp, ArrayBuffer, Object.getPrototypeOf(Uint8Array.prototype).constructor /*TypedArray*/, C1Type ]\nextensions = [{\n\tpack(date, allocateForWrite, pack) {\n\t\tlet seconds = date.getTime() / 1000\n\t\tif ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 0x100000000) {\n\t\t\t// Timestamp 32\n\t\t\tlet { target, targetView, position} = allocateForWrite(6)\n\t\t\ttarget[position++] = 0xd6\n\t\t\ttarget[position++] = 0xff\n\t\t\ttargetView.setUint32(position, seconds)\n\t\t} else if (seconds > 0 && seconds < 0x100000000) {\n\t\t\t// Timestamp 64\n\t\t\tlet { target, targetView, position} = allocateForWrite(10)\n\t\t\ttarget[position++] = 0xd7\n\t\t\ttarget[position++] = 0xff\n\t\t\ttargetView.setUint32(position, date.getMilliseconds() * 4000000 + ((seconds / 1000 / 0x100000000) >> 0))\n\t\t\ttargetView.setUint32(position + 4, seconds)\n\t\t} else if (isNaN(seconds)) {\n\t\t\tif (this.onInvalidDate) {\n\t\t\t\tallocateForWrite(0)\n\t\t\t\treturn pack(this.onInvalidDate())\n\t\t\t}\n\t\t\t// Intentionally invalid timestamp\n\t\t\tlet { target, targetView, position} = allocateForWrite(3)\n\t\t\ttarget[position++] = 0xd4\n\t\t\ttarget[position++] = 0xff\n\t\t\ttarget[position++] = 0xff\n\t\t} else {\n\t\t\t// Timestamp 96\n\t\t\tlet { target, targetView, position} = allocateForWrite(15)\n\t\t\ttarget[position++] = 0xc7\n\t\t\ttarget[position++] = 12\n\t\t\ttarget[position++] = 0xff\n\t\t\ttargetView.setUint32(position, date.getMilliseconds() * 1000000)\n\t\t\ttargetView.setBigInt64(position + 4, BigInt(Math.floor(seconds)))\n\t\t}\n\t}\n}, {\n\tpack(set, allocateForWrite, pack) {\n\t\tif (this.setAsEmptyObject) {\n\t\t\tallocateForWrite(0);\n\t\t\treturn pack({})\n\t\t}\n\t\tlet array = Array.from(set)\n\t\tlet { target, position} = allocateForWrite(this.moreTypes ? 3 : 0)\n\t\tif (this.moreTypes) {\n\t\t\ttarget[position++] = 0xd4\n\t\t\ttarget[position++] = 0x73 // 's' for Set\n\t\t\ttarget[position++] = 0\n\t\t}\n\t\tpack(array)\n\t}\n}, {\n\tpack(error, allocateForWrite, pack) {\n\t\tlet { target, position} = allocateForWrite(this.moreTypes ? 3 : 0)\n\t\tif (this.moreTypes) {\n\t\t\ttarget[position++] = 0xd4\n\t\t\ttarget[position++] = 0x65 // 'e' for error\n\t\t\ttarget[position++] = 0\n\t\t}\n\t\tpack([ error.name, error.message, error.cause ])\n\t}\n}, {\n\tpack(regex, allocateForWrite, pack) {\n\t\tlet { target, position} = allocateForWrite(this.moreTypes ? 3 : 0)\n\t\tif (this.moreTypes) {\n\t\t\ttarget[position++] = 0xd4\n\t\t\ttarget[position++] = 0x78 // 'x' for regeXp\n\t\t\ttarget[position++] = 0\n\t\t}\n\t\tpack([ regex.source, regex.flags ])\n\t}\n}, {\n\tpack(arrayBuffer, allocateForWrite) {\n\t\tif (this.moreTypes)\n\t\t\twriteExtBuffer(arrayBuffer, 0x10, allocateForWrite)\n\t\telse\n\t\t\twriteBuffer(hasNodeBuffer ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite)\n\t}\n}, {\n\tpack(typedArray, allocateForWrite) {\n\t\tlet constructor = typedArray.constructor\n\t\tif (constructor !== ByteArray && this.moreTypes)\n\t\t\twriteExtBuffer(typedArray, typedArrays.indexOf(constructor.name), allocateForWrite)\n\t\telse\n\t\t\twriteBuffer(typedArray, allocateForWrite)\n\t}\n}, {\n\tpack(c1, allocateForWrite) { // specific 0xC1 object\n\t\tlet { target, position} = allocateForWrite(1)\n\t\ttarget[position] = 0xc1\n\t}\n}]\n\nfunction writeExtBuffer(typedArray, type, allocateForWrite, encode) {\n\tlet length = typedArray.byteLength\n\tif (length + 1 < 0x100) {\n\t\tvar { target, position } = allocateForWrite(4 + length)\n\t\ttarget[position++] = 0xc7\n\t\ttarget[position++] = length + 1\n\t} else if (length + 1 < 0x10000) {\n\t\tvar { target, position } = allocateForWrite(5 + length)\n\t\ttarget[position++] = 0xc8\n\t\ttarget[position++] = (length + 1) >> 8\n\t\ttarget[position++] = (length + 1) & 0xff\n\t} else {\n\t\tvar { target, position, targetView } = allocateForWrite(7 + length)\n\t\ttarget[position++] = 0xc9\n\t\ttargetView.setUint32(position, length + 1) // plus one for the type byte\n\t\tposition += 4\n\t}\n\ttarget[position++] = 0x74 // \"t\" for typed array\n\ttarget[position++] = type\n\tif (!typedArray.buffer) typedArray = new Uint8Array(typedArray)\n\ttarget.set(new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength), position)\n}\nfunction writeBuffer(buffer, allocateForWrite) {\n\tlet length = buffer.byteLength\n\tvar target, position\n\tif (length < 0x100) {\n\t\tvar { target, position } = allocateForWrite(length + 2)\n\t\ttarget[position++] = 0xc4\n\t\ttarget[position++] = length\n\t} else if (length < 0x10000) {\n\t\tvar { target, position } = allocateForWrite(length + 3)\n\t\ttarget[position++] = 0xc5\n\t\ttarget[position++] = length >> 8\n\t\ttarget[position++] = length & 0xff\n\t} else {\n\t\tvar { target, position, targetView } = allocateForWrite(length + 5)\n\t\ttarget[position++] = 0xc6\n\t\ttargetView.setUint32(position, length)\n\t\tposition += 4\n\t}\n\ttarget.set(buffer, position)\n}\n\nfunction writeExtensionData(result, target, position, type) {\n\tlet length = result.length\n\tswitch (length) {\n\t\tcase 1:\n\t\t\ttarget[position++] = 0xd4\n\t\t\tbreak\n\t\tcase 2:\n\t\t\ttarget[position++] = 0xd5\n\t\t\tbreak\n\t\tcase 4:\n\t\t\ttarget[position++] = 0xd6\n\t\t\tbreak\n\t\tcase 8:\n\t\t\ttarget[position++] = 0xd7\n\t\t\tbreak\n\t\tcase 16:\n\t\t\ttarget[position++] = 0xd8\n\t\t\tbreak\n\t\tdefault:\n\t\t\tif (length < 0x100) {\n\t\t\t\ttarget[position++] = 0xc7\n\t\t\t\ttarget[position++] = length\n\t\t\t} else if (length < 0x10000) {\n\t\t\t\ttarget[position++] = 0xc8\n\t\t\t\ttarget[position++] = length >> 8\n\t\t\t\ttarget[position++] = length & 0xff\n\t\t\t} else {\n\t\t\t\ttarget[position++] = 0xc9\n\t\t\t\ttarget[position++] = length >> 24\n\t\t\t\ttarget[position++] = (length >> 16) & 0xff\n\t\t\t\ttarget[position++] = (length >> 8) & 0xff\n\t\t\t\ttarget[position++] = length & 0xff\n\t\t\t}\n\t}\n\ttarget[position++] = type\n\ttarget.set(result, position)\n\tposition += length\n\treturn position\n}\n\nfunction insertIds(serialized, idsToInsert) {\n\t// insert the ids that need to be referenced for structured clones\n\tlet nextId\n\tlet distanceToMove = idsToInsert.length * 6\n\tlet lastEnd = serialized.length - distanceToMove\n\twhile (nextId = idsToInsert.pop()) {\n\t\tlet offset = nextId.offset\n\t\tlet id = nextId.id\n\t\tserialized.copyWithin(offset + distanceToMove, offset, lastEnd)\n\t\tdistanceToMove -= 6\n\t\tlet position = offset + distanceToMove\n\t\tserialized[position++] = 0xd6\n\t\tserialized[position++] = 0x69 // 'i'\n\t\tserialized[position++] = id >> 24\n\t\tserialized[position++] = (id >> 16) & 0xff\n\t\tserialized[position++] = (id >> 8) & 0xff\n\t\tserialized[position++] = id & 0xff\n\t\tlastEnd = offset\n\t}\n\treturn serialized\n}\n\nfunction writeBundles(start, pack, incrementPosition) {\n\tif (bundledStrings.length > 0) {\n\t\ttargetView.setUint32(bundledStrings.position + start, position + incrementPosition - bundledStrings.position - start)\n\t\tbundledStrings.stringsPosition = position - start;\n\t\tlet writeStrings = bundledStrings\n\t\tbundledStrings = null\n\t\tpack(writeStrings[0])\n\t\tpack(writeStrings[1])\n\t}\n}\n\nexport function addExtension(extension) {\n\tif (extension.Class) {\n\t\tif (!extension.pack && !extension.write)\n\t\t\tthrow new Error('Extension has no pack or write function')\n\t\tif (extension.pack && !extension.type)\n\t\t\tthrow new Error('Extension has no type (numeric code to identify the extension)')\n\t\textensionClasses.unshift(extension.Class)\n\t\textensions.unshift(extension)\n\t}\n\tunpackAddExtension(extension)\n}\nfunction prepareStructures(structures, packr) {\n\tstructures.isCompatible = (existingStructures) => {\n\t\tlet compatible = !existingStructures || ((packr.lastNamedStructuresLength || 0) === existingStructures.length)\n\t\tif (!compatible) // we want to merge these existing structures immediately since we already have it and we are in the right transaction\n\t\t\tpackr._mergeStructures(existingStructures);\n\t\treturn compatible;\n\t}\n\treturn structures\n}\nexport function setWriteStructSlots(writeSlots, makeStructures) {\n\twriteStructSlots = writeSlots;\n\tprepareStructures = makeStructures;\n}\n\nlet defaultPackr = new Packr({ useRecords: false })\nexport const pack = defaultPackr.pack\nexport const encode = defaultPackr.pack\nexport const Encoder = Packr\nexport { FLOAT32_OPTIONS } from './unpack.js'\nimport { FLOAT32_OPTIONS } from './unpack.js'\nexport const { NEVER, ALWAYS, DECIMAL_ROUND, DECIMAL_FIT } = FLOAT32_OPTIONS\nexport const REUSE_BUFFER_MODE = 512\nexport const RESET_BUFFER_MODE = 1024\nexport const RESERVE_START_SPACE = 2048","import { Packr } from \"msgpackr\";\nconst Packer = new Packr({\n useRecords: false,\n skipValues: [null, undefined],\n largeBigIntToString: true,\n});\nexport function serializeToMsgPack(value) {\n return Packer.pack(value);\n}\nexport function deserializeFromMsgPack(bytes) {\n return Packer.unpack(bytes);\n}\n","import { bufFromBufLike, Certificate, HttpAgent, lookupResultToBuffer, polling, QueryCallRejectedError, ReplicaRejectCode, UpdateCallRejectedError, } from \"@dfinity/agent\";\nimport { Principal } from \"@dfinity/principal\";\nimport { toCanisterResponseError } from \"../error\";\nimport { CanisterAgent } from \"./base\";\nimport { typeboxValidate } from \"../../utils/typebox\";\nimport { deserializeFromMsgPack, serializeToMsgPack } from \"../../utils/msgpack\";\nexport class MsgpackCanisterAgent extends CanisterAgent {\n constructor(identity, agent, canisterId, canisterName) {\n super(identity, agent, canisterId, canisterName);\n }\n async executeMsgpackQuery(methodName, args, mapper, requestValidator, responseValidator) {\n const start = performance.now();\n let isError = false;\n try {\n const payload = MsgpackCanisterAgent.prepareMsgpackArgs(args, requestValidator);\n return await this.executeQuery(() => this.agent.query(this.canisterId, {\n methodName: methodName + \"_msgpack\",\n arg: payload,\n }), (resp) => {\n if (resp.status === \"replied\") {\n return Promise.resolve(MsgpackCanisterAgent.processMsgpackResponse(resp.reply.arg, mapper, responseValidator));\n }\n else {\n throw new QueryCallRejectedError(Principal.fromText(this.canisterId), methodName, resp);\n }\n }, args);\n }\n catch (err) {\n isError = true;\n throw err;\n }\n finally {\n this.writeTrace(methodName, false, performance.now() - start, isError);\n }\n }\n async executeMsgpackUpdate(methodName, args, mapper, requestValidator, responseValidator, onRequestAccepted) {\n const start = performance.now();\n let isError = false;\n try {\n const payload = MsgpackCanisterAgent.prepareMsgpackArgs(args, requestValidator);\n const { requestId, response } = await this.agent.call(this.canisterId, {\n methodName: methodName + \"_msgpack\",\n arg: payload,\n callSync: onRequestAccepted === undefined,\n });\n const canisterId = Principal.fromText(this.canisterId);\n if (response.ok && response.body?.certificate) {\n const cert = response.body.certificate;\n // const certTime = this.agent.replicaTime;\n const certificate = await Certificate.create({\n certificate: bufFromBufLike(cert),\n rootKey: this.agent.rootKey,\n canisterId: Principal.from(canisterId),\n blsVerify: undefined,\n });\n const path = [new TextEncoder().encode(\"request_status\"), requestId];\n const status = new TextDecoder().decode(lookupResultToBuffer(certificate.lookup([...path, \"status\"])));\n switch (status) {\n case \"replied\": {\n const reply = lookupResultToBuffer(certificate.lookup([...path, \"reply\"]));\n if (reply) {\n return Promise.resolve(MsgpackCanisterAgent.processMsgpackResponse(reply, mapper, responseValidator));\n }\n break;\n }\n case \"rejected\": {\n // Find rejection details in the certificate\n const rejectCode = new Uint8Array(lookupResultToBuffer(certificate.lookup([...path, \"reject_code\"])))[0];\n const rejectMessage = new TextDecoder().decode(lookupResultToBuffer(certificate.lookup([...path, \"reject_message\"])));\n const error_code_buf = lookupResultToBuffer(certificate.lookup([...path, \"error_code\"]));\n const error_code = error_code_buf\n ? new TextDecoder().decode(error_code_buf)\n : undefined;\n throw new UpdateCallRejectedError(canisterId, methodName, requestId, response, rejectCode, rejectMessage, error_code);\n }\n }\n }\n if (response.status === 202) {\n if (onRequestAccepted !== undefined) {\n onRequestAccepted();\n }\n const { reply } = await polling.pollForResponse(this.agent, canisterId, requestId, polling.defaultStrategy());\n return Promise.resolve(MsgpackCanisterAgent.processMsgpackResponse(reply, mapper, responseValidator));\n }\n else {\n throw new UpdateCallRejectedError(canisterId, methodName, requestId, response, ReplicaRejectCode.CanisterReject, \"\");\n }\n }\n catch (err) {\n isError = true;\n console.log(err, args);\n throw toCanisterResponseError(err, this.identity);\n }\n finally {\n this.writeTrace(methodName, true, performance.now() - start, isError);\n }\n }\n static prepareMsgpackArgs(value, validator) {\n const validated = typeboxValidate(value, validator);\n return serializeToMsgPack(validated);\n }\n static processMsgpackResponse(responseBytes, mapper, validator) {\n const response = deserializeFromMsgPack(new Uint8Array(responseBytes));\n const validated = typeboxValidate(response, validator);\n return mapper(validated);\n }\n}\n","import { UnsupportedValueError, } from \"openchat-shared\";\nimport { Principal } from \"@dfinity/principal\";\n// takes a type of the form [] | [A] and a mapper from A -> B and returns a B or undefined\nexport function optional(candid, mapper) {\n return candid[0] !== undefined ? mapper(candid[0]) : undefined;\n}\nexport function mapOptional(input, mapper) {\n return input != null ? mapper(input) : undefined;\n}\nexport function optionUpdate(candid, mapper) {\n if (\"NoChange\" in candid)\n return undefined;\n if (\"SetToNone\" in candid)\n return \"set_to_none\";\n if (\"SetToSome\" in candid)\n return { value: mapper(candid.SetToSome) };\n throw new UnsupportedValueError(\"Unexpected ApiOptionUpdate type returned\", candid);\n}\nexport function optionUpdateV2(value, mapper) {\n if (value === \"NoChange\")\n return undefined;\n if (value === \"SetToNone\")\n return \"set_to_none\";\n if (\"SetToSome\" in value)\n return { value: mapper(value.SetToSome) };\n throw new UnsupportedValueError(\"Unexpected ApiOptionUpdate type returned\", value);\n}\nexport function apiOptionUpdate(mapper, domain) {\n if (domain === undefined)\n return { NoChange: null };\n if (domain === \"set_to_none\")\n return { SetToNone: null };\n return { SetToSome: mapper(domain.value) };\n}\nexport function apiOptionUpdateV2(mapper, domain) {\n if (domain === undefined)\n return \"NoChange\";\n if (domain === \"set_to_none\")\n return \"SetToNone\";\n return { SetToSome: mapper(domain.value) };\n}\nexport function identity(x) {\n return x;\n}\n// todo - this maps *any* response to void and should only be used temporarily\nexport function toVoid(_x) {\n return;\n}\n// Convert a hex string to a byte array\nexport function hexStringToBytes(hex) {\n const bytes = [];\n for (let c = 0; c < hex.length; c += 2)\n bytes.push(parseInt(hex.substr(c, 2), 16));\n return new Uint8Array(bytes);\n}\nexport function consolidateBytes(bytes) {\n return Array.isArray(bytes) ? new Uint8Array(bytes) : bytes;\n}\n// Convert a byte array to a hex string\nexport function bytesToHexString(bytes) {\n return consolidateBytes(bytes).reduce((str, byte) => str + byte.toString(16).padStart(2, \"0\"), \"\");\n}\nexport function principalBytesToString(value) {\n // When serialized to JSON principals become strings, in all other cases they are serialized as byte arrays\n if (typeof value === \"string\") {\n return value;\n }\n return Principal.fromUint8Array(consolidateBytes(value)).toString();\n}\nexport function principalStringToBytes(principal) {\n return Principal.fromText(principal).toUint8Array();\n}\nexport function maybePrincipalStringToBytes(principal) {\n if (principal === undefined)\n return undefined;\n try {\n return principalStringToBytes(principal);\n }\n catch (err) {\n console.warn(\"Unable to convert principal string to bytes\", principal, err);\n }\n return undefined;\n}\nexport function bigintToBytes(value) {\n return hexStringToBytes(value.toString(16));\n}\nexport function bytesToBigint(bytes) {\n return BigInt(\"0x\" + bytesToHexString(bytes));\n}\nexport function durationToTimestamp(duration) {\n return BigInt(Date.now() + Number(duration));\n}\n","import { durationToTimestamp } from \"../../utils/mapping\";\nexport function pinNumberFailureResponseV2(value) {\n if (value === \"PinRequired\") {\n return {\n kind: \"pin_required\",\n };\n }\n if (\"PinIncorrect\" in value) {\n return {\n kind: \"pin_incorrect\",\n nextRetryAt: value.PinIncorrect > 0n ? durationToTimestamp(value.PinIncorrect) : 0n,\n };\n }\n if (\"TooManyFailedPinAttempts\" in value) {\n return {\n kind: \"too_main_failed_pin_attempts\",\n nextRetryAt: durationToTimestamp(value.TooManyFailedPinAttempts),\n };\n }\n throw new Error(\"Unexpected ApiPinNumberResponse type received\");\n}\n","import { bigintToBytes, bytesToBigint, bytesToHexString, consolidateBytes, hexStringToBytes, identity, mapOptional, principalBytesToString, principalStringToBytes, } from \"../../utils/mapping\";\nimport { ProposalDecisionStatus, ProposalRewardStatus, UnsupportedValueError, CommonResponses, chatIdentifiersEqual, codeToText, emptyChatMetrics, isAccountIdentifierValid, toBigInt32, toBigInt64, ICP_SYMBOL, communityPermissionsList, botChatPermissionList, messagePermissionsList, } from \"openchat-shared\";\nimport { pinNumberFailureResponseV2 } from \"./pinNumberErrorMapper\";\nimport { toRecord2 } from \"../../utils/list\";\nimport { ReplicaNotUpToDateError } from \"../error\";\nconst E8S_AS_BIGINT = BigInt(100_000_000);\nexport function generateApiKeyResponse(value) {\n console.log(\"Bot api key: \", value);\n if (typeof value === \"object\" && \"Success\" in value) {\n return { kind: \"success\", apiKey: value.Success.api_key };\n }\n return CommonResponses.failure();\n}\nexport function eventsSuccessResponse(value) {\n return {\n events: value.events.map(eventWrapper),\n expiredEventRanges: value.expired_event_ranges.map(expiredEventsRange),\n expiredMessageRanges: value.expired_message_ranges.map(expiredMessagesRange),\n latestEventIndex: value.latest_event_index,\n };\n}\nexport function eventWrapper(value) {\n return {\n event: event(value.event),\n index: value.index,\n timestamp: value.timestamp,\n expiresAt: mapOptional(value.expires_at, Number),\n };\n}\nexport function event(value) {\n if (value === \"Empty\" || value === \"FailedToDeserialize\") {\n return { kind: \"empty\" };\n }\n if (\"Message\" in value) {\n return message(value.Message);\n }\n if (\"GroupChatCreated\" in value) {\n return {\n kind: \"group_chat_created\",\n name: value.GroupChatCreated.name,\n description: value.GroupChatCreated.description,\n created_by: principalBytesToString(value.GroupChatCreated.created_by),\n };\n }\n if (\"DirectChatCreated\" in value) {\n return {\n kind: \"direct_chat_created\",\n };\n }\n if (\"ParticipantsAdded\" in value) {\n return {\n kind: \"members_added\",\n userIds: value.ParticipantsAdded.user_ids.map(principalBytesToString),\n addedBy: principalBytesToString(value.ParticipantsAdded.added_by),\n };\n }\n if (\"UsersInvited\" in value) {\n return {\n kind: \"users_invited\",\n userIds: value.UsersInvited.user_ids.map(principalBytesToString),\n invitedBy: principalBytesToString(value.UsersInvited.invited_by),\n };\n }\n if (\"ParticipantJoined\" in value) {\n return {\n kind: \"member_joined\",\n userId: principalBytesToString(value.ParticipantJoined.user_id),\n };\n }\n if (\"ParticipantsRemoved\" in value) {\n return {\n kind: \"members_removed\",\n userIds: value.ParticipantsRemoved.user_ids.map(principalBytesToString),\n removedBy: principalBytesToString(value.ParticipantsRemoved.removed_by),\n };\n }\n if (\"ParticipantLeft\" in value) {\n return {\n kind: \"member_left\",\n userId: principalBytesToString(value.ParticipantLeft.user_id),\n };\n }\n if (\"GroupNameChanged\" in value) {\n return {\n kind: \"name_changed\",\n changedBy: principalBytesToString(value.GroupNameChanged.changed_by),\n };\n }\n if (\"GroupDescriptionChanged\" in value) {\n return {\n kind: \"desc_changed\",\n changedBy: principalBytesToString(value.GroupDescriptionChanged.changed_by),\n };\n }\n if (\"GroupRulesChanged\" in value) {\n return {\n kind: \"rules_changed\",\n enabled: value.GroupRulesChanged.enabled,\n enabledPrev: value.GroupRulesChanged.prev_enabled,\n changedBy: principalBytesToString(value.GroupRulesChanged.changed_by),\n };\n }\n if (\"AvatarChanged\" in value) {\n return {\n kind: \"avatar_changed\",\n changedBy: principalBytesToString(value.AvatarChanged.changed_by),\n };\n }\n if (\"UsersBlocked\" in value) {\n return {\n kind: \"users_blocked\",\n userIds: value.UsersBlocked.user_ids.map(principalBytesToString),\n blockedBy: principalBytesToString(value.UsersBlocked.blocked_by),\n };\n }\n if (\"UsersUnblocked\" in value) {\n return {\n kind: \"users_unblocked\",\n userIds: value.UsersUnblocked.user_ids.map(principalBytesToString),\n unblockedBy: principalBytesToString(value.UsersUnblocked.unblocked_by),\n };\n }\n if (\"RoleChanged\" in value) {\n return {\n kind: \"role_changed\",\n userIds: value.RoleChanged.user_ids.map(principalBytesToString),\n changedBy: principalBytesToString(value.RoleChanged.changed_by),\n oldRole: memberRole(value.RoleChanged.old_role),\n newRole: memberRole(value.RoleChanged.new_role),\n };\n }\n if (\"MessagePinned\" in value) {\n return {\n kind: \"message_pinned\",\n pinnedBy: principalBytesToString(value.MessagePinned.pinned_by),\n messageIndex: value.MessagePinned.message_index,\n };\n }\n if (\"MessageUnpinned\" in value) {\n return {\n kind: \"message_unpinned\",\n unpinnedBy: principalBytesToString(value.MessageUnpinned.unpinned_by),\n messageIndex: value.MessageUnpinned.message_index,\n };\n }\n if (\"PermissionsChanged\" in value) {\n return {\n kind: \"permissions_changed\",\n oldPermissions: groupPermissions(value.PermissionsChanged.old_permissions_v2),\n newPermissions: groupPermissions(value.PermissionsChanged.new_permissions_v2),\n changedBy: principalBytesToString(value.PermissionsChanged.changed_by),\n };\n }\n if (\"GroupVisibilityChanged\" in value) {\n return {\n kind: \"group_visibility_changed\",\n public: mapOptional(value.GroupVisibilityChanged.public, identity),\n messagesVisibleToNonMembers: mapOptional(value.GroupVisibilityChanged.messages_visible_to_non_members, identity),\n changedBy: principalBytesToString(value.GroupVisibilityChanged.changed_by),\n };\n }\n if (\"GroupInviteCodeChanged\" in value) {\n let change = \"disabled\";\n if (value.GroupInviteCodeChanged.change === \"Enabled\") {\n change = \"enabled\";\n }\n else if (value.GroupInviteCodeChanged.change === \"Reset\") {\n change = \"reset\";\n }\n return {\n kind: \"group_invite_code_changed\",\n change,\n changedBy: principalBytesToString(value.GroupInviteCodeChanged.changed_by),\n };\n }\n if (\"ChatFrozen\" in value) {\n return {\n kind: \"chat_frozen\",\n frozenBy: principalBytesToString(value.ChatFrozen.frozen_by),\n reason: mapOptional(value.ChatFrozen.reason, identity),\n };\n }\n if (\"ChatUnfrozen\" in value) {\n return {\n kind: \"chat_unfrozen\",\n unfrozenBy: principalBytesToString(value.ChatUnfrozen.unfrozen_by),\n };\n }\n if (\"EventsTimeToLiveUpdated\" in value) {\n return {\n kind: \"events_ttl_updated\",\n updatedBy: principalBytesToString(value.EventsTimeToLiveUpdated.updated_by),\n newTimeToLive: mapOptional(value.EventsTimeToLiveUpdated.new_ttl, identity),\n };\n }\n if (\"GroupGateUpdated\" in value) {\n return {\n kind: \"gate_updated\",\n updatedBy: principalBytesToString(value.GroupGateUpdated.updated_by),\n };\n }\n if (\"MembersAddedToDefaultChannel\" in value) {\n return {\n kind: \"members_added_to_default_channel\",\n count: value.MembersAddedToDefaultChannel.count,\n };\n }\n if (\"ExternalUrlUpdated\" in value) {\n return {\n kind: \"external_url_updated\",\n newUrl: mapOptional(value.ExternalUrlUpdated.new_url, identity),\n updatedBy: principalBytesToString(value.ExternalUrlUpdated.updated_by),\n };\n }\n if (\"BotAdded\" in value) {\n return {\n kind: \"bot_added\",\n userId: principalBytesToString(value.BotAdded.user_id),\n addedBy: principalBytesToString(value.BotAdded.added_by),\n };\n }\n if (\"BotRemoved\" in value) {\n return {\n kind: \"bot_removed\",\n userId: principalBytesToString(value.BotRemoved.user_id),\n removedBy: principalBytesToString(value.BotRemoved.removed_by),\n };\n }\n if (\"BotUpdated\" in value) {\n return {\n kind: \"bot_updated\",\n userId: principalBytesToString(value.BotUpdated.user_id),\n updatedBy: principalBytesToString(value.BotUpdated.updated_by),\n };\n }\n throw new UnsupportedValueError(\"Unexpected ApiEventWrapper type received\", value);\n}\nexport function message(value) {\n const sender = principalBytesToString(value.sender);\n const content = messageContent(value.content, sender);\n return {\n kind: \"message\",\n content,\n sender,\n repliesTo: mapOptional(value.replies_to, replyContext),\n messageId: toBigInt64(value.message_id),\n messageIndex: value.message_index,\n reactions: reactions(value.reactions),\n tips: tips(value.tips),\n edited: value.edited,\n forwarded: value.forwarded,\n deleted: content.kind === \"deleted_content\",\n thread: mapOptional(value.thread_summary, threadSummary),\n blockLevelMarkdown: value.block_level_markdown,\n botContext: mapOptional(value.bot_context, botMessageContext),\n };\n}\nexport function botMessageContext(value) {\n return {\n finalised: value.finalised,\n command: mapOptional(value.command, (command) => ({\n name: command.name,\n args: command.args.map(botCommandArg),\n initiator: principalBytesToString(command.initiator),\n })),\n };\n}\nexport function botCommandArg(api) {\n const { name, value } = api;\n if (\"Boolean\" in value) {\n return {\n kind: \"boolean\",\n name,\n value: value.Boolean,\n };\n }\n else if (\"Integer\" in value) {\n return {\n kind: \"integer\",\n name,\n value: value.Integer,\n };\n }\n else if (\"Decimal\" in value) {\n return {\n kind: \"decimal\",\n name,\n value: value.Decimal,\n };\n }\n else if (\"String\" in value) {\n return {\n kind: \"string\",\n name,\n value: value.String,\n };\n }\n else if (\"User\" in value) {\n return {\n kind: \"user\",\n name,\n userId: principalBytesToString(value.User),\n };\n }\n else if (\"DateTime\" in value) {\n return {\n kind: \"dateTime\",\n name,\n value: value.DateTime,\n };\n }\n throw new Error(`Unexpected ApiBotCommandArg type received, ${api}`);\n}\nexport function tips(value) {\n return value.reduce((agg, [ledger, tips]) => {\n agg[principalBytesToString(ledger)] = tips.reduce((userTips, [userId, amount]) => {\n userTips[principalBytesToString(userId)] = amount;\n return userTips;\n }, {});\n return agg;\n }, {});\n}\nexport function threadSummary(value) {\n return {\n participantIds: new Set(value.participant_ids.map(principalBytesToString)),\n followedByMe: value.followed_by_me,\n numberOfReplies: Number(value.reply_count),\n latestEventIndex: Number(value.latest_event_index),\n latestEventTimestamp: value.latest_event_timestamp,\n };\n}\nexport function messageContent(value, sender) {\n if (\"File\" in value) {\n return fileContent(value.File);\n }\n if (\"Text\" in value) {\n return textContent(value.Text);\n }\n if (\"Image\" in value) {\n return imageContent(value.Image);\n }\n if (\"Video\" in value) {\n return videoContent(value.Video);\n }\n if (\"Audio\" in value) {\n return audioContent(value.Audio);\n }\n if (\"Deleted\" in value) {\n return deletedContent(value.Deleted);\n }\n if (\"Crypto\" in value) {\n return cryptoContent(value.Crypto, sender);\n }\n if (\"Poll\" in value) {\n return pollContent(value.Poll);\n }\n if (\"Giphy\" in value) {\n return giphyContent(value.Giphy);\n }\n if (\"GovernanceProposal\" in value) {\n return proposalContent(value.GovernanceProposal);\n }\n if (\"Prize\" in value) {\n return prizeContent(value.Prize);\n }\n if (\"PrizeWinner\" in value) {\n return prizeWinnerContent(sender, value.PrizeWinner);\n }\n if (\"MessageReminderCreated\" in value) {\n return messageReminderCreated(value.MessageReminderCreated);\n }\n if (\"MessageReminder\" in value) {\n return messageReminder(value.MessageReminder);\n }\n if (\"Custom\" in value) {\n return customContent(value.Custom);\n }\n if (\"ReportedMessage\" in value) {\n return reportedMessage(value.ReportedMessage);\n }\n if (\"P2PSwap\" in value) {\n return p2pSwapContent(value.P2PSwap);\n }\n if (\"VideoCall\" in value) {\n return videoCallContent(value.VideoCall);\n }\n throw new UnsupportedValueError(\"Unexpected ApiMessageContent type received\", value);\n}\nfunction reportedMessage(value) {\n return {\n kind: \"reported_message_content\",\n total: value.count,\n reports: value.reports.map((r) => ({\n notes: r.notes,\n reasonCode: r.reason_code,\n timestamp: Number(r.timestamp),\n reportedBy: principalBytesToString(r.reported_by),\n })),\n };\n}\nfunction customContent(value) {\n if (value.kind === \"meme_fighter\") {\n const decoder = new TextDecoder();\n const json = decoder.decode(consolidateBytes(value.data));\n const decoded = JSON.parse(json);\n return {\n kind: \"meme_fighter_content\",\n ...decoded,\n };\n }\n if (value.kind === \"user_referral_card\") {\n return {\n kind: \"user_referral_card\",\n };\n }\n throw new Error(`Unknown custom content kind received: ${value.kind}`);\n}\nfunction messageReminderCreated(value) {\n return {\n kind: \"message_reminder_created_content\",\n notes: value.notes,\n remindAt: Number(value.remind_at),\n reminderId: value.reminder_id,\n hidden: value.hidden,\n };\n}\nfunction messageReminder(value) {\n return {\n kind: \"message_reminder_content\",\n notes: value.notes,\n reminderId: value.reminder_id,\n };\n}\nfunction prizeWinnerContent(senderId, value) {\n return {\n kind: \"prize_winner_content\",\n transaction: completedCryptoTransfer(value.transaction, senderId, principalBytesToString(value.winner)),\n prizeMessageIndex: value.prize_message,\n };\n}\nfunction prizeContent(value) {\n return {\n kind: \"prize_content\",\n prizesRemaining: value.prizes_remaining,\n prizesPending: value.prizes_pending,\n diamondOnly: value.diamond_only,\n lifetimeDiamondOnly: value.lifetime_diamond_only,\n uniquePersonOnly: value.unique_person_only,\n streakOnly: value.streak_only,\n winners: value.winners.map(principalBytesToString),\n token: value.token_symbol,\n endDate: value.end_date,\n caption: value.caption,\n };\n}\nfunction videoCallContent(value) {\n return {\n kind: \"video_call_content\",\n ended: value.ended,\n participants: value.participants.map(videoCallParticipant),\n callType: videoCallType(value.call_type),\n };\n}\nfunction videoCallParticipant(value) {\n return {\n userId: principalBytesToString(value.user_id),\n joined: value.joined,\n };\n}\nfunction videoCallType(value) {\n if (value === \"Default\") {\n return \"default\";\n }\n if (value === \"Broadcast\") {\n return \"broadcast\";\n }\n throw new UnsupportedValueError(\"Unexpected ApiVideoCallTypye type received\", value);\n}\nfunction p2pSwapContent(value) {\n return {\n kind: \"p2p_swap_content\",\n token0: tokenInfo(value.token0),\n token1: tokenInfo(value.token1),\n token0Amount: value.token0_amount,\n token1Amount: value.token1_amount,\n caption: value.caption,\n expiresAt: value.expires_at,\n status: p2pTradeStatus(value.status),\n swapId: value.swap_id,\n token0TxnIn: value.token0_txn_in,\n };\n}\nfunction tokenInfo(value) {\n return {\n fee: value.fee,\n decimals: value.decimals,\n symbol: value.symbol,\n ledger: principalBytesToString(value.ledger),\n };\n}\nfunction p2pTradeStatus(value) {\n if (value === \"Open\") {\n return { kind: \"p2p_swap_open\" };\n }\n if (\"Reserved\" in value) {\n return {\n kind: \"p2p_swap_reserved\",\n reservedBy: principalBytesToString(value.Reserved.reserved_by),\n };\n }\n if (\"Accepted\" in value) {\n return {\n kind: \"p2p_swap_accepted\",\n acceptedBy: principalBytesToString(value.Accepted.accepted_by),\n token1TxnIn: value.Accepted.token1_txn_in,\n };\n }\n if (\"Cancelled\" in value) {\n return {\n kind: \"p2p_swap_cancelled\",\n token0TxnOut: value.Cancelled.token0_txn_out,\n };\n }\n if (\"Expired\" in value) {\n return {\n kind: \"p2p_swap_expired\",\n token0TxnOut: value.Expired.token0_txn_out,\n };\n }\n if (\"Completed\" in value) {\n const { accepted_by, token1_txn_in, token0_txn_out, token1_txn_out } = value.Completed;\n return {\n kind: \"p2p_swap_completed\",\n acceptedBy: principalBytesToString(accepted_by),\n token1TxnIn: token1_txn_in,\n token0TxnOut: token0_txn_out,\n token1TxnOut: token1_txn_out,\n };\n }\n throw new UnsupportedValueError(\"Unexpected ApiP2PSwapStatus type received\", value);\n}\nexport function apiUser(domain) {\n return {\n user_id: principalStringToBytes(domain.userId),\n username: domain.username,\n };\n}\nfunction proposalContent(value) {\n return {\n kind: \"proposal_content\",\n governanceCanisterId: principalBytesToString(value.governance_canister_id),\n proposal: proposal(value.proposal),\n myVote: value.my_vote,\n };\n}\nfunction proposal(value) {\n if (\"NNS\" in value) {\n const p = value.NNS;\n return {\n kind: \"nns\",\n id: p.id,\n topic: p.topic,\n proposer: p.proposer.toString(),\n title: p.title,\n summary: p.summary,\n url: p.url,\n status: proposalDecisionStatus(p.status),\n rewardStatus: proposalRewardStatus(p.reward_status),\n tally: {\n yes: Number(p.tally.yes / E8S_AS_BIGINT),\n no: Number(p.tally.no / E8S_AS_BIGINT),\n total: Number(p.tally.total / E8S_AS_BIGINT),\n timestamp: p.tally.timestamp,\n },\n lastUpdated: Number(p.last_updated),\n created: Number(p.created),\n deadline: Number(p.deadline),\n payloadTextRendering: p.payload_text_rendering,\n minYesPercentageOfTotal: 3,\n minYesPercentageOfExercised: 50,\n };\n }\n else if (\"SNS\" in value) {\n const p = value.SNS;\n return {\n kind: \"sns\",\n id: p.id,\n action: Number(p.action),\n proposer: bytesToHexString(p.proposer),\n title: p.title,\n summary: p.summary,\n url: p.url,\n status: proposalDecisionStatus(p.status),\n rewardStatus: proposalRewardStatus(p.reward_status),\n tally: {\n yes: Number(p.tally.yes / E8S_AS_BIGINT),\n no: Number(p.tally.no / E8S_AS_BIGINT),\n total: Number(p.tally.total / E8S_AS_BIGINT),\n timestamp: p.tally.timestamp,\n },\n lastUpdated: Number(p.last_updated),\n created: Number(p.created),\n deadline: Number(p.deadline),\n payloadTextRendering: p.payload_text_rendering,\n minYesPercentageOfTotal: p.minimum_yes_proportion_of_total / 100,\n minYesPercentageOfExercised: p.minimum_yes_proportion_of_exercised / 100,\n };\n }\n throw new UnsupportedValueError(\"Unexpected ApiProposal type received\", value);\n}\nfunction proposalDecisionStatus(value) {\n if (value === \"Failed\")\n return ProposalDecisionStatus.Failed;\n if (value === \"Open\")\n return ProposalDecisionStatus.Open;\n if (value === \"Rejected\")\n return ProposalDecisionStatus.Rejected;\n if (value === \"Executed\")\n return ProposalDecisionStatus.Executed;\n if (value === \"Adopted\")\n return ProposalDecisionStatus.Adopted;\n return ProposalDecisionStatus.Unspecified;\n}\nfunction proposalRewardStatus(value) {\n if (value === \"AcceptVotes\")\n return ProposalRewardStatus.AcceptVotes;\n if (value === \"ReadyToSettle\")\n return ProposalRewardStatus.ReadyToSettle;\n if (value === \"Settled\")\n return ProposalRewardStatus.Settled;\n return ProposalRewardStatus.Unspecified;\n}\nfunction giphyContent(value) {\n return {\n kind: \"giphy_content\",\n title: value.title,\n caption: value.caption,\n desktop: giphyImageVariant(value.desktop),\n mobile: giphyImageVariant(value.mobile),\n };\n}\nfunction giphyImageVariant(value) {\n return {\n width: value.width,\n height: value.height,\n url: value.url,\n mimeType: value.mime_type,\n };\n}\nfunction pollContent(value) {\n return {\n kind: \"poll_content\",\n votes: pollVotes(value.votes),\n config: pollConfig(value.config),\n ended: value.ended,\n };\n}\nfunction pollConfig(value) {\n return {\n allowMultipleVotesPerUser: value.allow_multiple_votes_per_user,\n allowUserToChangeVote: value.allow_user_to_change_vote,\n text: value.text,\n showVotesBeforeEndDate: value.show_votes_before_end_date,\n endDate: value.end_date,\n anonymous: value.anonymous,\n options: value.options,\n };\n}\nfunction pollVotes(value) {\n return {\n total: totalPollVotes(value.total),\n user: value.user,\n };\n}\nfunction totalPollVotes(value) {\n if (\"Anonymous\" in value) {\n return {\n kind: \"anonymous_poll_votes\",\n votes: Object.entries(value.Anonymous).reduce((agg, [idx, num]) => {\n agg[Number(idx)] = num;\n return agg;\n }, {}),\n };\n }\n if (\"Visible\" in value) {\n return {\n kind: \"visible_poll_votes\",\n votes: Object.entries(value.Visible).reduce((agg, [idx, userIds]) => {\n agg[Number(idx)] = userIds.map(principalBytesToString);\n return agg;\n }, {}),\n };\n }\n if (\"Hidden\" in value) {\n return {\n kind: \"hidden_poll_votes\",\n votes: value.Hidden,\n };\n }\n throw new UnsupportedValueError(\"Unexpected ApiTotalPollVotes type received\", value);\n}\nfunction deletedContent(value) {\n return {\n kind: \"deleted_content\",\n deletedBy: principalBytesToString(value.deleted_by),\n timestamp: value.timestamp,\n };\n}\nfunction cryptoContent(value, sender) {\n return {\n kind: \"crypto_content\",\n caption: mapOptional(value.caption, identity),\n transfer: cryptoTransfer(value.transfer, sender, principalBytesToString(value.recipient)),\n };\n}\nfunction cryptoTransfer(value, sender, recipient) {\n if (\"Pending\" in value) {\n return pendingCryptoTransfer(value.Pending, recipient);\n }\n if (\"Completed\" in value) {\n return completedCryptoTransfer(value.Completed, sender, recipient);\n }\n if (\"Failed\" in value) {\n return failedCryptoTransfer(value.Failed, recipient);\n }\n throw new UnsupportedValueError(\"Unexpected ApiCryptoTransaction type received\", value);\n}\nfunction pendingCryptoTransfer(value, recipient) {\n if (\"NNS\" in value) {\n const trans = value.NNS;\n return {\n kind: \"pending\",\n ledger: principalBytesToString(trans.ledger),\n token: trans.token_symbol,\n recipient,\n amountE8s: trans.amount.e8s,\n feeE8s: mapOptional(trans.fee, (f) => f.e8s),\n memo: trans.memo,\n createdAtNanos: trans.created,\n };\n }\n if (\"ICRC1\" in value) {\n return {\n kind: \"pending\",\n ledger: principalBytesToString(value.ICRC1.ledger),\n token: value.ICRC1.token_symbol,\n recipient,\n amountE8s: value.ICRC1.amount,\n feeE8s: value.ICRC1.fee,\n memo: mapOptional(value.ICRC1.memo, bytesToBigint),\n createdAtNanos: value.ICRC1.created,\n };\n }\n if (\"ICRC2\" in value) {\n throw new Error(\"ICRC2 is not supported yet\");\n }\n throw new UnsupportedValueError(\"Unexpected ApiPendingCryptoTransaction type received\", value);\n}\nexport function completedCryptoTransfer(value, sender, recipient) {\n if (\"NNS\" in value) {\n const trans = value.NNS;\n return {\n kind: \"completed\",\n ledger: principalBytesToString(trans.ledger),\n recipient,\n sender,\n amountE8s: trans.amount.e8s,\n feeE8s: trans.fee.e8s,\n memo: trans.memo,\n blockIndex: trans.block_index,\n };\n }\n const trans = \"ICRC1\" in value ? value.ICRC1 : value.ICRC2;\n return {\n kind: \"completed\",\n ledger: principalBytesToString(trans.ledger),\n recipient,\n sender,\n amountE8s: trans.amount,\n feeE8s: trans.fee,\n memo: mapOptional(trans.memo, bytesToBigint) ?? BigInt(0),\n blockIndex: trans.block_index,\n };\n}\nexport function failedCryptoTransfer(value, recipient) {\n if (\"NNS\" in value) {\n const trans = value.NNS;\n return {\n kind: \"failed\",\n ledger: principalBytesToString(trans.ledger),\n recipient,\n amountE8s: trans.amount.e8s,\n feeE8s: trans.fee.e8s,\n memo: trans.memo,\n errorMessage: trans.error_message,\n };\n }\n const trans = \"ICRC1\" in value ? value.ICRC1 : value.ICRC2;\n return {\n kind: \"failed\",\n ledger: principalBytesToString(trans.ledger),\n recipient,\n amountE8s: trans.amount,\n feeE8s: trans.fee,\n memo: mapOptional(trans.memo, bytesToBigint) ?? BigInt(0),\n errorMessage: trans.error_message,\n };\n}\nfunction imageContent(value) {\n return {\n kind: \"image_content\",\n height: value.height,\n mimeType: value.mime_type,\n blobReference: mapOptional(value.blob_reference, blobReference),\n thumbnailData: value.thumbnail_data,\n caption: mapOptional(value.caption, identity),\n width: value.width,\n };\n}\nfunction videoContent(value) {\n return {\n kind: \"video_content\",\n height: value.height,\n mimeType: value.mime_type,\n videoData: {\n blobReference: mapOptional(value.video_blob_reference, blobReference),\n },\n imageData: {\n blobReference: mapOptional(value.image_blob_reference, blobReference),\n },\n thumbnailData: value.thumbnail_data,\n caption: mapOptional(value.caption, identity),\n width: value.width,\n };\n}\nfunction audioContent(value) {\n return {\n kind: \"audio_content\",\n mimeType: value.mime_type,\n blobReference: mapOptional(value.blob_reference, blobReference),\n caption: mapOptional(value.caption, identity),\n };\n}\nfunction textContent(value) {\n return {\n kind: \"text_content\",\n text: value.text,\n };\n}\nfunction fileContent(value) {\n return {\n kind: \"file_content\",\n name: value.name,\n mimeType: value.mime_type,\n blobReference: mapOptional(value.blob_reference, blobReference),\n caption: mapOptional(value.caption, identity),\n fileSize: value.file_size,\n };\n}\nfunction blobReference(value) {\n return {\n blobId: value.blob_id,\n canisterId: principalBytesToString(value.canister_id),\n };\n}\nfunction replyContext(value) {\n return {\n kind: \"raw_reply_context\",\n eventIndex: value.event_index,\n sourceContext: mapOptional(value.chat_if_other, replySourceContext),\n };\n}\nfunction replySourceContext([chatId, maybeThreadRoot]) {\n if (\"Direct\" in chatId) {\n return {\n chatId: { kind: \"direct_chat\", userId: principalBytesToString(chatId.Direct) },\n threadRootMessageIndex: undefined,\n };\n }\n if (\"Group\" in chatId) {\n return {\n chatId: { kind: \"group_chat\", groupId: principalBytesToString(chatId.Group) },\n threadRootMessageIndex: mapOptional(maybeThreadRoot, identity),\n };\n }\n if (\"Channel\" in chatId) {\n const [communityId, channelId] = chatId.Channel;\n return {\n chatId: {\n kind: \"channel\",\n communityId: principalBytesToString(communityId),\n channelId: Number(toBigInt32(channelId)),\n },\n threadRootMessageIndex: mapOptional(maybeThreadRoot, identity),\n };\n }\n throw new UnsupportedValueError(\"Unexpected ApiMultiUserChat type received\", chatId);\n}\nfunction reactions(value) {\n return value.map(([reaction, userIds]) => ({\n reaction,\n userIds: new Set(userIds.map(principalBytesToString)),\n }));\n}\nexport function groupPermissions(value) {\n return {\n changeRoles: permissionRole(value.change_roles),\n updateGroup: permissionRole(value.update_group),\n inviteUsers: permissionRole(value.invite_users),\n addMembers: permissionRole(value.add_members),\n removeMembers: permissionRole(value.remove_members),\n deleteMessages: permissionRole(value.delete_messages),\n pinMessages: permissionRole(value.pin_messages),\n reactToMessages: permissionRole(value.react_to_messages),\n mentionAllMembers: permissionRole(value.mention_all_members),\n startVideoCall: permissionRole(value.start_video_call),\n messagePermissions: messagePermissions(value.message_permissions),\n threadPermissions: mapOptional(value.thread_permissions, messagePermissions),\n };\n}\nfunction messagePermissions(value) {\n const mf = value.custom.find((cp) => cp.subtype === \"meme_fighter\")?.role;\n return {\n default: permissionRole(value.default),\n text: mapOptional(value.text, permissionRole),\n image: mapOptional(value.image, permissionRole),\n video: mapOptional(value.video, permissionRole),\n audio: mapOptional(value.audio, permissionRole),\n file: mapOptional(value.file, permissionRole),\n poll: mapOptional(value.poll, permissionRole),\n crypto: mapOptional(value.crypto, permissionRole),\n giphy: mapOptional(value.giphy, permissionRole),\n prize: mapOptional(value.prize, permissionRole),\n p2pSwap: mapOptional(value.p2p_swap, permissionRole),\n memeFighter: mf !== undefined ? permissionRole(mf) : undefined,\n };\n}\nexport function communityPermissions(value) {\n return {\n changeRoles: communityPermissionRole(value.change_roles),\n updateDetails: communityPermissionRole(value.update_details),\n inviteUsers: communityPermissionRole(value.invite_users),\n removeMembers: communityPermissionRole(value.remove_members),\n createPublicChannel: communityPermissionRole(value.create_public_channel),\n createPrivateChannel: communityPermissionRole(value.create_private_channel),\n manageUserGroups: communityPermissionRole(value.manage_user_groups),\n };\n}\nexport function communityPermissionRole(value) {\n if (value === \"Owners\")\n return \"owner\";\n if (value === \"Admins\")\n return \"admin\";\n return \"member\";\n}\nexport function apiCommunityPermissions(permissions) {\n return {\n create_public_channel: apiCommunityPermissionRole(permissions.createPublicChannel),\n update_details: apiCommunityPermissionRole(permissions.updateDetails),\n invite_users: apiCommunityPermissionRole(permissions.inviteUsers),\n remove_members: apiCommunityPermissionRole(permissions.removeMembers),\n change_roles: apiCommunityPermissionRole(permissions.changeRoles),\n create_private_channel: apiCommunityPermissionRole(permissions.createPrivateChannel),\n manage_user_groups: apiCommunityPermissionRole(permissions.manageUserGroups),\n };\n}\nexport function apiCommunityPermissionRole(permissionRole) {\n switch (permissionRole) {\n case \"owner\":\n return \"Owners\";\n case \"admin\":\n return \"Admins\";\n case \"member\":\n return \"Members\";\n }\n}\nexport function apiGroupPermissions(permissions) {\n return {\n change_roles: apiPermissionRole(permissions.changeRoles),\n update_group: apiPermissionRole(permissions.updateGroup),\n invite_users: apiPermissionRole(permissions.inviteUsers),\n add_members: apiPermissionRole(permissions.addMembers),\n remove_members: apiPermissionRole(permissions.removeMembers),\n delete_messages: apiPermissionRole(permissions.deleteMessages),\n pin_messages: apiPermissionRole(permissions.pinMessages),\n react_to_messages: apiPermissionRole(permissions.reactToMessages),\n mention_all_members: apiPermissionRole(permissions.mentionAllMembers),\n start_video_call: apiPermissionRole(permissions.startVideoCall),\n message_permissions: apiMessagePermissions(permissions.messagePermissions),\n thread_permissions: mapOptional(permissions.threadPermissions, apiMessagePermissions),\n };\n}\nfunction apiMessagePermissions(permissions) {\n return {\n default: apiPermissionRole(permissions.default),\n text: mapOptional(permissions.text, apiPermissionRole),\n image: mapOptional(permissions.image, apiPermissionRole),\n video: mapOptional(permissions.video, apiPermissionRole),\n audio: mapOptional(permissions.audio, apiPermissionRole),\n file: mapOptional(permissions.file, apiPermissionRole),\n poll: mapOptional(permissions.poll, apiPermissionRole),\n crypto: mapOptional(permissions.crypto, apiPermissionRole),\n giphy: mapOptional(permissions.giphy, apiPermissionRole),\n prize: mapOptional(permissions.prize, apiPermissionRole),\n p2p_swap: mapOptional(permissions.p2pSwap, apiPermissionRole),\n video_call: mapOptional(\"none\", apiPermissionRole),\n custom: permissions.memeFighter !== undefined\n ? [{ subtype: \"meme_fighter\", role: apiPermissionRole(permissions.memeFighter) }]\n : [],\n };\n}\nexport function apiPermissionRole(permissionRole) {\n switch (permissionRole) {\n case \"none\":\n return \"None\";\n case \"owner\":\n return \"Owner\";\n case \"admin\":\n return \"Admins\";\n case \"moderator\":\n return \"Moderators\";\n default:\n return \"Members\";\n }\n}\nexport function permissionRole(value) {\n if (value === \"None\")\n return \"none\";\n if (value === \"Owner\")\n return \"owner\";\n if (value === \"Admins\")\n return \"admin\";\n if (value === \"Moderators\")\n return \"moderator\";\n return \"member\";\n}\nexport function chatMetrics(value) {\n return {\n audioMessages: Number(value.audio_messages),\n edits: Number(value.edits),\n icpMessages: Number(value.icp_messages),\n sns1Messages: Number(value.sns1_messages),\n ckbtcMessages: Number(value.ckbtc_messages),\n giphyMessages: Number(value.giphy_messages),\n deletedMessages: Number(value.deleted_messages),\n fileMessages: Number(value.file_messages),\n pollVotes: Number(value.poll_votes),\n textMessages: Number(value.text_messages),\n imageMessages: Number(value.image_messages),\n replies: Number(value.replies),\n videoMessages: Number(value.video_messages),\n polls: Number(value.polls),\n reactions: Number(value.reactions),\n reportedMessages: Number(value.reported_messages),\n };\n}\nexport function memberRole(value) {\n if (value === \"Admin\") {\n return \"admin\";\n }\n if (value === \"Moderator\") {\n return \"moderator\";\n }\n if (value === \"Participant\" || value === \"Member\") {\n return \"member\";\n }\n if (value === \"Owner\") {\n return \"owner\";\n }\n throw new UnsupportedValueError(\"Unexpected ApiRole type received\", value);\n}\nexport function apiMultiUserChat(chatId) {\n switch (chatId.kind) {\n case \"group_chat\":\n return {\n Group: principalStringToBytes(chatId.groupId),\n };\n case \"channel\":\n return {\n Channel: [principalStringToBytes(chatId.communityId), toBigInt32(chatId.channelId)],\n };\n default:\n throw new Error(\"Cannot convert a DirectChatIdentifier into an ApiMultiUserChat\");\n }\n}\nexport function apiReplyContextArgs(chatId, domain) {\n if (domain.sourceContext !== undefined &&\n !chatIdentifiersEqual(chatId, domain.sourceContext.chatId)) {\n return {\n chat_if_other: [\n apiMultiUserChat(domain.sourceContext.chatId),\n domain.sourceContext.threadRootMessageIndex ?? null,\n ],\n event_index: domain.eventIndex,\n };\n }\n else {\n return {\n chat_if_other: undefined,\n event_index: domain.eventIndex,\n };\n }\n}\nexport function apiMessageContent(domain) {\n switch (domain.kind) {\n case \"text_content\":\n return { Text: apiTextContent(domain) };\n case \"image_content\":\n return { Image: apiImageContent(domain) };\n case \"video_content\":\n return { Video: apiVideoContent(domain) };\n case \"audio_content\":\n return { Audio: apiAudioContent(domain) };\n case \"file_content\":\n return { File: apiFileContent(domain) };\n case \"crypto_content\":\n return { Crypto: apiPendingCryptoContent(domain) };\n case \"poll_content\":\n return { Poll: apiPollContent(domain) };\n case \"giphy_content\":\n return { Giphy: apiGiphyContent(domain) };\n case \"prize_content_initial\":\n return { Prize: apiPrizeContentInitial(domain) };\n case \"p2p_swap_content_initial\":\n return { P2PSwap: apiP2PSwapContentInitial(domain) };\n case \"meme_fighter_content\":\n // eslint-disable-next-line no-case-declarations\n const encoder = new TextEncoder();\n return {\n Custom: {\n kind: \"meme_fighter\",\n data: encoder.encode(JSON.stringify({\n url: domain.url,\n width: domain.width,\n height: domain.height,\n })),\n },\n };\n case \"user_referral_card\":\n return {\n Custom: {\n kind: \"user_referral_card\",\n data: new Uint8Array(),\n },\n };\n case \"video_call_content\":\n case \"deleted_content\":\n case \"blocked_content\":\n case \"prize_content\":\n case \"prize_winner_content\":\n case \"placeholder_content\":\n case \"bot_placeholder_content\":\n case \"proposal_content\":\n case \"message_reminder_content\":\n case \"message_reminder_created_content\":\n case \"reported_message_content\":\n case \"p2p_swap_content\":\n throw new Error(`Incorrectly attempting to send {domain.kind} content to the server`);\n }\n}\nfunction apiGiphyContent(domain) {\n return {\n title: domain.title,\n caption: domain.caption,\n desktop: apiGiphyImageVariant(domain.desktop),\n mobile: apiGiphyImageVariant(domain.mobile),\n };\n}\nfunction apiGiphyImageVariant(domain) {\n return {\n height: domain.height,\n width: domain.width,\n url: domain.url,\n mime_type: domain.mimeType,\n };\n}\nfunction apiPollContent(domain) {\n return {\n votes: apiPollVotes(domain.votes),\n config: apiPollConfig(domain.config),\n ended: domain.ended,\n };\n}\nfunction apiPollConfig(domain) {\n return {\n allow_multiple_votes_per_user: domain.allowMultipleVotesPerUser,\n allow_user_to_change_vote: domain.allowUserToChangeVote,\n text: domain.text,\n show_votes_before_end_date: domain.showVotesBeforeEndDate,\n end_date: domain.endDate,\n anonymous: domain.anonymous,\n options: domain.options,\n };\n}\nfunction apiPollVotes(domain) {\n return {\n total: apiTotalPollVotes(domain.total),\n user: domain.user,\n };\n}\nfunction apiTotalPollVotes(domain) {\n if (domain.kind === \"anonymous_poll_votes\") {\n return {\n Anonymous: domain.votes,\n };\n }\n if (domain.kind === \"hidden_poll_votes\") {\n return {\n Hidden: domain.votes,\n };\n }\n if (domain.kind === \"visible_poll_votes\") {\n return {\n Visible: toRecord2(Object.entries(domain.votes), ([idx, _]) => Number(idx), ([_, userIds]) => userIds.map(principalStringToBytes)),\n };\n }\n throw new UnsupportedValueError(\"Unexpected TotalPollVotes type received\", domain);\n}\nfunction apiImageContent(domain) {\n return {\n height: domain.height,\n mime_type: domain.mimeType,\n blob_reference: apiBlobReference(domain.blobReference),\n thumbnail_data: domain.thumbnailData,\n caption: domain.caption,\n width: domain.width,\n };\n}\nfunction apiVideoContent(domain) {\n return {\n height: domain.height,\n mime_type: domain.mimeType,\n video_blob_reference: apiBlobReference(domain.videoData.blobReference),\n image_blob_reference: apiBlobReference(domain.imageData.blobReference),\n thumbnail_data: domain.thumbnailData,\n caption: domain.caption,\n width: domain.width,\n };\n}\nfunction apiAudioContent(domain) {\n return {\n mime_type: domain.mimeType,\n blob_reference: apiBlobReference(domain.blobReference),\n caption: domain.caption,\n };\n}\nexport function apiMaybeAccessGateConfig(domain) {\n const gate = apiMaybeAccessGate(domain.gate);\n if (gate === undefined) {\n return undefined;\n }\n return {\n gate,\n expiry: domain.expiry,\n };\n}\nexport function apiMaybeAccessGate(domain) {\n if (domain.kind === \"composite_gate\") {\n return {\n Composite: {\n inner: domain.gates.map(apiLeafAccessGate),\n and: domain.operator === \"and\",\n },\n };\n }\n if (domain.kind === \"no_gate\")\n return undefined;\n if (domain.kind === \"nft_gate\")\n return undefined; // TODO\n if (domain.kind === \"unique_person_gate\")\n return \"UniquePerson\";\n if (domain.kind === \"diamond_gate\")\n return \"DiamondMember\";\n if (domain.kind === \"locked_gate\")\n return \"Locked\";\n if (domain.kind === \"credential_gate\") {\n return {\n VerifiedCredential: {\n credential_name: domain.credential.credentialName,\n issuer_canister_id: principalStringToBytes(domain.credential.issuerCanisterId),\n issuer_origin: domain.credential.issuerOrigin,\n credential_type: domain.credential.credentialType,\n credential_arguments: apiCredentialArguments(domain.credential.credentialArguments),\n },\n };\n }\n if (domain.kind === \"neuron_gate\") {\n return {\n SnsNeuron: {\n governance_canister_id: principalStringToBytes(domain.governanceCanister),\n min_dissolve_delay: mapOptional(domain.minDissolveDelay, BigInt),\n min_stake_e8s: mapOptional(domain.minStakeE8s, BigInt),\n },\n };\n }\n if (domain.kind === \"payment_gate\") {\n return {\n Payment: {\n ledger_canister_id: principalStringToBytes(domain.ledgerCanister),\n amount: domain.amount,\n fee: domain.fee,\n },\n };\n }\n if (domain.kind === \"token_balance_gate\") {\n return {\n TokenBalance: {\n ledger_canister_id: principalStringToBytes(domain.ledgerCanister),\n min_balance: domain.minBalance,\n },\n };\n }\n return undefined;\n}\nexport function apiAccessGateConfig(domain) {\n return {\n gate: apiAccessGate(domain.gate),\n expiry: domain.expiry,\n };\n}\nexport function apiAccessGate(domain) {\n if (domain.kind === \"composite_gate\") {\n return {\n Composite: {\n and: domain.operator === \"and\",\n inner: domain.gates.map(apiLeafAccessGate),\n },\n };\n }\n return apiLeafAccessGate(domain);\n}\nfunction apiLeafAccessGate(domain) {\n if (domain.kind === \"locked_gate\")\n return \"Locked\";\n if (domain.kind === \"diamond_gate\")\n return \"DiamondMember\";\n if (domain.kind === \"lifetime_diamond_gate\")\n return \"LifetimeDiamondMember\";\n if (domain.kind === \"unique_person_gate\")\n return \"UniquePerson\";\n if (domain.kind === \"credential_gate\")\n return {\n VerifiedCredential: {\n credential_name: domain.credential.credentialName,\n issuer_canister_id: principalStringToBytes(domain.credential.issuerCanisterId),\n issuer_origin: domain.credential.issuerOrigin,\n credential_type: domain.credential.credentialType,\n credential_arguments: apiCredentialArguments(domain.credential.credentialArguments),\n },\n };\n if (domain.kind === \"neuron_gate\") {\n return {\n SnsNeuron: {\n governance_canister_id: principalStringToBytes(domain.governanceCanister),\n min_dissolve_delay: mapOptional(domain.minDissolveDelay, BigInt),\n min_stake_e8s: mapOptional(domain.minStakeE8s, BigInt),\n },\n };\n }\n if (domain.kind === \"payment_gate\") {\n return {\n Payment: {\n ledger_canister_id: principalStringToBytes(domain.ledgerCanister),\n amount: domain.amount,\n fee: domain.fee,\n },\n };\n }\n if (domain.kind === \"token_balance_gate\") {\n return {\n TokenBalance: {\n ledger_canister_id: principalStringToBytes(domain.ledgerCanister),\n min_balance: domain.minBalance,\n },\n };\n }\n throw new Error(`Received a domain level group gate that we cannot parse: ${domain}`);\n}\nexport function credentialArguments(value) {\n return toRecord2(value, ([k, _]) => k, ([_, v]) => {\n if (\"String\" in v) {\n return v.String;\n }\n else {\n return v.Int;\n }\n });\n}\nfunction apiCredentialArguments(domain) {\n return toRecord2(Object.entries(domain ?? {}), ([k, _]) => k, ([_, v]) => {\n if (typeof v === \"number\") {\n return { Int: v };\n }\n else {\n return { String: v };\n }\n });\n}\nexport function accessGateConfig(value) {\n return {\n gate: accessGate(value.gate),\n expiry: value.expiry,\n };\n}\nexport function accessGate(value) {\n if (value === \"DiamondMember\") {\n return {\n kind: \"diamond_gate\",\n };\n }\n if (value === \"LifetimeDiamondMember\") {\n return {\n kind: \"lifetime_diamond_gate\",\n };\n }\n if (value === \"UniquePerson\") {\n return {\n kind: \"unique_person_gate\",\n };\n }\n if (value === \"Locked\") {\n return {\n kind: \"locked_gate\",\n };\n }\n if (value === \"ReferredByMember\") {\n return {\n kind: \"referred_by_member_gate\",\n };\n }\n if (\"Composite\" in value) {\n return {\n kind: \"composite_gate\",\n operator: value.Composite.and ? \"and\" : \"or\",\n gates: value.Composite.inner.map(accessGate),\n };\n }\n if (\"SnsNeuron\" in value) {\n return {\n kind: \"neuron_gate\",\n minDissolveDelay: mapOptional(value.SnsNeuron.min_dissolve_delay, Number),\n minStakeE8s: mapOptional(value.SnsNeuron.min_stake_e8s, Number),\n governanceCanister: principalBytesToString(value.SnsNeuron.governance_canister_id),\n };\n }\n if (\"VerifiedCredential\" in value) {\n const credentialArgs = Object.entries(value.VerifiedCredential.credential_arguments);\n return {\n kind: \"credential_gate\",\n credential: {\n issuerCanisterId: principalBytesToString(value.VerifiedCredential.issuer_canister_id),\n issuerOrigin: value.VerifiedCredential.issuer_origin,\n credentialType: value.VerifiedCredential.credential_type,\n credentialName: value.VerifiedCredential.credential_name,\n credentialArguments: credentialArgs.length === 0 ? undefined : credentialArguments(credentialArgs),\n },\n };\n }\n if (\"Payment\" in value) {\n return {\n kind: \"payment_gate\",\n ledgerCanister: principalBytesToString(value.Payment.ledger_canister_id),\n amount: value.Payment.amount,\n fee: value.Payment.fee,\n };\n }\n if (\"TokenBalance\" in value) {\n return {\n kind: \"token_balance_gate\",\n ledgerCanister: principalBytesToString(value.TokenBalance.ledger_canister_id),\n minBalance: value.TokenBalance.min_balance,\n };\n }\n throw new UnsupportedValueError(\"Unexpected ApiGroupGate type received\", value);\n}\nfunction apiBlobReference(domain) {\n return mapOptional(domain, (b) => ({\n blob_id: b.blobId,\n canister_id: principalStringToBytes(b.canisterId),\n }));\n}\nexport function apiPrizeContentInitial(domain) {\n return {\n caption: domain.caption,\n transfer: apiPendingCryptoTransaction(domain.transfer),\n end_date: domain.endDate,\n diamond_only: domain.diamondOnly,\n lifetime_diamond_only: domain.lifetimeDiamondOnly,\n unique_person_only: domain.uniquePersonOnly,\n streak_only: domain.streakOnly,\n prizes_v2: domain.prizes,\n };\n}\nexport function apiP2PSwapContentInitial(domain) {\n return {\n token0: apiTokenInfo(domain.token0),\n token1: apiTokenInfo(domain.token1),\n token0_amount: domain.token0Amount,\n token1_amount: domain.token1Amount,\n caption: domain.caption,\n expires_in: domain.expiresIn,\n };\n}\nfunction apiTokenInfo(domain) {\n return {\n fee: domain.fee,\n decimals: domain.decimals,\n symbol: domain.symbol,\n ledger: principalStringToBytes(domain.ledger),\n };\n}\nexport function apiPendingCryptoContent(domain) {\n return {\n recipient: principalStringToBytes(domain.transfer.recipient),\n caption: domain.caption,\n transfer: apiPendingCryptoTransaction(domain.transfer),\n };\n}\nexport function apiPendingCryptoTransaction(domain) {\n if (domain.kind === \"pending\") {\n if (domain.token === \"ICP\") {\n return {\n Pending: {\n NNS: {\n ledger: principalStringToBytes(domain.ledger),\n token_symbol: domain.token,\n to: {\n User: principalStringToBytes(domain.recipient),\n },\n amount: apiICP(domain.amountE8s),\n fee: undefined,\n memo: domain.memo,\n created: domain.createdAtNanos,\n },\n },\n };\n }\n else {\n return {\n Pending: {\n ICRC1: {\n ledger: principalStringToBytes(domain.ledger),\n token_symbol: domain.token,\n to: principalToIcrcAccount(domain.recipient),\n amount: domain.amountE8s,\n fee: domain.feeE8s ?? BigInt(0),\n memo: mapOptional(domain.memo, bigintToBytes),\n created: domain.createdAtNanos,\n },\n },\n };\n }\n }\n throw new Error(\"Transaction is not of type 'Pending': \" + JSON.stringify(domain));\n}\nexport function apiPendingCryptocurrencyWithdrawal(domain, pin) {\n if (domain.token === ICP_SYMBOL && isAccountIdentifierValid(domain.to)) {\n return {\n withdrawal: {\n NNS: {\n ledger: principalStringToBytes(domain.ledger),\n token_symbol: domain.token,\n to: {\n Account: [...hexStringToBytes(domain.to)],\n },\n amount: apiICP(domain.amountE8s),\n fee: undefined,\n memo: domain.memo,\n created: domain.createdAtNanos,\n },\n },\n pin,\n };\n }\n else {\n return {\n withdrawal: {\n ICRC1: {\n ledger: principalStringToBytes(domain.ledger),\n token_symbol: domain.token,\n to: principalToIcrcAccount(domain.to),\n amount: domain.amountE8s,\n fee: domain.feeE8s ?? BigInt(0),\n memo: mapOptional(domain.memo, bigintToBytes),\n created: domain.createdAtNanos,\n },\n },\n pin,\n };\n }\n}\nexport function proposalVote(vote) {\n if (vote === 1)\n return true;\n if (vote === 2)\n return false;\n return undefined;\n}\nexport function apiProposalVote(vote) {\n return vote ? 1 : 2;\n}\nfunction apiTextContent(domain) {\n return {\n text: domain.text,\n };\n}\nfunction apiFileContent(domain) {\n return {\n name: domain.name,\n mime_type: domain.mimeType,\n blob_reference: apiBlobReference(domain.blobReference),\n caption: domain.caption,\n file_size: domain.fileSize,\n };\n}\nfunction apiICP(amountE8s) {\n return {\n e8s: amountE8s,\n };\n}\nexport function groupChatSummary(value) {\n const groupId = principalBytesToString(value.chat_id);\n const latestMessage = mapOptional(value.latest_message, messageEvent);\n return {\n kind: \"group_chat\",\n id: { kind: \"group_chat\", groupId },\n latestMessage,\n name: value.name,\n description: value.description,\n public: value.is_public,\n historyVisible: value.history_visible_to_new_joiners,\n minVisibleEventIndex: value.min_visible_event_index,\n minVisibleMessageIndex: value.min_visible_message_index,\n latestEventIndex: value.latest_event_index,\n latestMessageIndex: value.latest_message_index,\n lastUpdated: value.last_updated,\n blobReference: mapOptional(value.avatar_id, (blobId) => ({\n blobId,\n canisterId: groupId,\n })),\n memberCount: value.participant_count,\n permissions: groupPermissions(value.permissions_v2),\n metrics: chatMetrics(value.metrics),\n subtype: mapOptional(value.subtype, groupSubtype),\n previewed: false,\n frozen: value.frozen !== undefined,\n dateLastPinned: value.date_last_pinned,\n dateReadPinned: undefined,\n gateConfig: mapOptional(value.gate_config, accessGateConfig) ?? {\n gate: { kind: \"no_gate\" },\n expiry: undefined,\n },\n level: \"group\",\n eventsTTL: value.events_ttl,\n eventsTtlLastUpdated: value.events_ttl_last_updated,\n membership: {\n joined: value.joined,\n role: memberRole(value.role),\n mentions: [],\n latestThreads: [],\n myMetrics: chatMetrics(value.my_metrics),\n notificationsMuted: value.notifications_muted,\n readByMeUpTo: latestMessage?.event.messageIndex,\n archived: false,\n rulesAccepted: value.rules_accepted,\n lapsed: value.membership?.lapsed ?? false,\n },\n localUserIndex: principalBytesToString(value.local_user_index_canister_id),\n isInvited: false, // this is only applicable when we are not a member\n messagesVisibleToNonMembers: value.messages_visible_to_non_members,\n verified: value.verified,\n };\n}\nexport function communitySummary(value) {\n const communityId = principalBytesToString(value.community_id);\n const localUserIndex = principalBytesToString(value.local_user_index_canister_id);\n return {\n kind: \"community\",\n id: { kind: \"community\", communityId },\n name: value.name,\n description: value.description,\n public: value.is_public,\n historyVisible: false,\n latestEventIndex: value.latest_event_index,\n lastUpdated: value.last_updated,\n metrics: chatMetrics(value.metrics),\n avatar: {\n blobReference: mapOptional(value.avatar_id, (blobId) => ({\n blobId,\n canisterId: communityId,\n })),\n },\n banner: {\n blobReference: mapOptional(value.banner_id, (blobId) => ({\n blobId,\n canisterId: communityId,\n })),\n },\n memberCount: value.member_count,\n frozen: value.frozen !== undefined,\n gateConfig: mapOptional(value.gate_config, accessGateConfig) ?? {\n gate: { kind: \"no_gate\" },\n expiry: undefined,\n },\n level: \"community\",\n permissions: communityPermissions(value.permissions),\n membership: {\n joined: mapOptional(value.membership, (m) => m.joined) ?? BigInt(0),\n role: mapOptional(value.membership, (m) => memberRole(m.role)) ?? \"none\",\n archived: false,\n pinned: [],\n index: 0,\n displayName: mapOptional(value.membership, (m) => m.display_name),\n rulesAccepted: mapOptional(value.membership, (m) => m.rules_accepted) ?? false,\n lapsed: mapOptional(value.membership, (m) => m.lapsed) ?? false,\n },\n channels: value.channels.map((c) => communityChannelSummary(c, communityId)),\n primaryLanguage: value.primary_language,\n userGroups: new Map(value.user_groups.map(userGroup)),\n localUserIndex,\n isInvited: value.is_invited ?? false,\n verified: value.verified,\n };\n}\nexport function userGroup(value) {\n return [\n value.user_group_id,\n {\n kind: \"user_group\",\n id: value.user_group_id,\n name: value.name,\n memberCount: value.members,\n },\n ];\n}\nexport function communityChannelSummary(value, communityId) {\n const latestMessage = mapOptional(value.latest_message, messageEvent);\n return {\n kind: \"channel\",\n id: { kind: \"channel\", communityId, channelId: Number(toBigInt32(value.channel_id)) },\n latestMessage,\n name: value.name,\n description: value.description,\n public: value.is_public,\n historyVisible: value.history_visible_to_new_joiners,\n minVisibleEventIndex: value.min_visible_event_index,\n minVisibleMessageIndex: value.min_visible_message_index,\n latestEventIndex: value.latest_event_index,\n latestMessageIndex: value.latest_message_index,\n lastUpdated: value.last_updated,\n blobReference: mapOptional(value.avatar_id, (blobId) => ({\n blobId,\n canisterId: communityId,\n })),\n memberCount: value.member_count,\n permissions: groupPermissions(value.permissions_v2),\n metrics: chatMetrics(value.metrics),\n subtype: mapOptional(value.subtype, groupSubtype),\n frozen: false, // TODO - doesn't exist\n dateLastPinned: value.date_last_pinned,\n dateReadPinned: undefined,\n gateConfig: mapOptional(value.gate_config, accessGateConfig) ?? {\n gate: { kind: \"no_gate\" },\n expiry: undefined,\n },\n level: \"channel\",\n eventsTTL: value.events_ttl,\n eventsTtlLastUpdated: value.events_ttl_last_updated,\n videoCallInProgress: mapOptional(value.video_call_in_progress, (v) => v.message_index),\n membership: {\n joined: mapOptional(value.membership, (m) => m.joined) ?? BigInt(0),\n notificationsMuted: mapOptional(value.membership, (m) => m.notifications_muted) ?? false,\n role: mapOptional(value.membership, (m) => memberRole(m.role)) ?? \"none\",\n myMetrics: mapOptional(value.membership, (m) => chatMetrics(m.my_metrics)) ??\n emptyChatMetrics(),\n readByMeUpTo: latestMessage?.event.messageIndex,\n latestThreads: mapOptional(value.membership, (m) => m.latest_threads.map(threadSyncDetails)) ?? [],\n mentions: mapOptional(value.membership, (m) => mentions(m.mentions)) ?? [],\n archived: false,\n rulesAccepted: mapOptional(value.membership, (m) => m.rules_accepted) ?? false,\n lapsed: mapOptional(value.membership, (m) => m.lapsed) ?? false,\n },\n isInvited: value.is_invited ?? false,\n messagesVisibleToNonMembers: value.messages_visible_to_non_members,\n externalUrl: value.external_url,\n };\n}\nexport function threadSyncDetails(value) {\n return {\n threadRootMessageIndex: value.root_message_index,\n lastUpdated: value.last_updated,\n latestEventIndex: value.latest_event,\n latestMessageIndex: value.latest_message,\n };\n}\nexport function updatedEvent([threadRootMessageIndex, eventIndex, timestamp]) {\n return {\n eventIndex,\n threadRootMessageIndex: mapOptional(threadRootMessageIndex, identity),\n timestamp,\n };\n}\nexport function gateCheckFailedReason(value) {\n if (value === \"NoUniquePersonProof\") {\n return \"no_unique_person_proof\";\n }\n if (value === \"NotLifetimeDiamondMember\") {\n return \"not_lifetime_diamond\";\n }\n if (value === \"NotDiamondMember\") {\n return \"not_diamond\";\n }\n if (value === \"NoSnsNeuronsFound\") {\n return \"no_sns_neuron_found\";\n }\n if (value === \"NoSnsNeuronsWithRequiredDissolveDelayFound\") {\n return \"dissolve_delay_not_met\";\n }\n if (value === \"NoSnsNeuronsWithRequiredStakeFound\") {\n return \"min_stake_not_met\";\n }\n if (value === \"NotReferredByMember\") {\n return \"not_referred_by_member\";\n }\n if (value === \"Locked\") {\n return \"locked\";\n }\n if (typeof value !== \"string\") {\n if (\"PaymentFailed\" in value) {\n console.warn(\"PaymentFailed: \", value);\n return \"payment_failed\";\n }\n if (\"InsufficientBalance\" in value) {\n return \"insufficient_balance\";\n }\n if (\"FailedVerifiedCredentialCheck\" in value) {\n console.warn(\"FailedVerifiedCredentialCheck: \", value);\n return \"failed_verified_credential_check\";\n }\n }\n throw new UnsupportedValueError(\"Unexpected ApiGateCheckFailedReason type received\", value);\n}\nexport function addRemoveReactionResponse(value) {\n if (value === \"Success\" ||\n value === \"NoChange\" ||\n (typeof value === \"object\" && \"SuccessV2\" in value)) {\n return CommonResponses.success();\n }\n else {\n console.warn(\"AddRemoveReaction failed with: \", value);\n return CommonResponses.failure();\n }\n}\nexport function groupSubtype(subtype) {\n return {\n kind: \"governance_proposals\",\n isNns: subtype.GovernanceProposals.is_nns,\n governanceCanisterId: principalBytesToString(subtype.GovernanceProposals.governance_canister_id),\n };\n}\nexport function messagesSuccessResponse(value) {\n return {\n events: value.messages.map(messageEvent),\n expiredEventRanges: [],\n expiredMessageRanges: [],\n latestEventIndex: value.latest_event_index,\n };\n}\nexport function messageEvent(value) {\n return {\n event: message(value.event),\n index: value.index,\n timestamp: value.timestamp,\n expiresAt: mapOptional(value.expires_at, Number),\n };\n}\nexport function mention(value) {\n return {\n messageId: toBigInt64(value.message_id),\n messageIndex: value.message_index,\n eventIndex: value.event_index,\n };\n}\nexport function mentions(value) {\n return value.filter((m) => m.thread_root_message_index === undefined).map(mention);\n}\nexport function expiredEventsRange([start, end]) {\n return {\n kind: \"expired_events_range\",\n start,\n end,\n };\n}\nexport function expiredMessagesRange([start, end]) {\n return {\n kind: \"expired_messages_range\",\n start,\n end,\n };\n}\nexport function updateGroupResponse(value) {\n if (typeof value === \"object\") {\n if (\"SuccessV2\" in value) {\n return {\n kind: \"success\",\n rulesVersion: value.SuccessV2.rules_version,\n };\n }\n if (\"DescriptionTooLong\" in value) {\n return { kind: \"desc_too_long\" };\n }\n if (\"NameTooLong\" in value) {\n return { kind: \"name_too_long\" };\n }\n if (\"NameTooShort\" in value) {\n return { kind: \"name_too_short\" };\n }\n if (\"AvatarTooBig\" in value) {\n return { kind: \"avatar_too_big\" };\n }\n if (\"RulesTooLong\" in value) {\n return { kind: \"rules_too_long\" };\n }\n if (\"RulesTooShort\" in value) {\n return { kind: \"rules_too_short\" };\n }\n if (\"Error\" in value) {\n return ocError(value.Error);\n }\n }\n console.log(\"Failed to update group: \", value);\n if (value === \"NameReserved\") {\n return { kind: \"name_reserved\" };\n }\n if (value === \"NotAuthorized\") {\n return { kind: \"not_authorized\" };\n }\n if (value === \"NameTaken\") {\n return { kind: \"name_taken\" };\n }\n if (value === \"CallerNotInGroup\") {\n return { kind: \"not_in_group\" };\n }\n if (value === \"UserSuspended\") {\n return { kind: \"user_suspended\" };\n }\n if (value === \"UserLapsed\") {\n return { kind: \"user_lapsed\" };\n }\n if (value === \"ChatFrozen\") {\n return { kind: \"chat_frozen\" };\n }\n if (value === \"AccessGateInvalid\") {\n return { kind: \"access_gate_invalid\" };\n }\n if (value === \"UserNotInChannel\" ||\n value === \"ChannelNotFound\" ||\n value === \"UserNotInCommunity\" ||\n value === \"CommunityFrozen\" ||\n value === \"ExternalUrlInvalid\") {\n console.warn(\"UpdateGroupResponse failed with: \", value);\n return { kind: \"failure\" };\n }\n if (value === \"InternalError\") {\n return { kind: \"internal_error\" };\n }\n throw new UnsupportedValueError(\"Unexpected ApiUpdateGroupResponse type received\", value);\n}\nexport function createGroupResponse(value, id) {\n if (typeof value === \"object\") {\n if (\"Success\" in value) {\n if (\"channel_id\" in value.Success && id.kind === \"channel\") {\n const canisterId = {\n kind: \"channel\",\n communityId: id.communityId,\n channelId: Number(toBigInt32(value.Success.channel_id)),\n };\n return { kind: \"success\", canisterId };\n }\n if (\"chat_id\" in value.Success && id.kind === \"group_chat\") {\n const canisterId = {\n kind: \"group_chat\",\n groupId: principalBytesToString(value.Success.chat_id),\n };\n return { kind: \"success\", canisterId };\n }\n throw new Error(\"Unexpected CreateGroup success response: \" + value.Success);\n }\n if (\"NameTooLong\" in value) {\n return { kind: \"name_too_long\" };\n }\n if (\"NameTooShort\" in value) {\n return { kind: \"name_too_short\" };\n }\n if (\"DescriptionTooLong\" in value) {\n return { kind: \"description_too_long\" };\n }\n if (\"InternalError\" in value || \"Error\" in value) {\n return { kind: \"internal_error\" };\n }\n if (\"RulesTooLong\" in value) {\n return { kind: \"rules_too_long\" };\n }\n if (\"RulesTooShort\" in value) {\n return { kind: \"rules_too_short\" };\n }\n if (\"AvatarTooBig\" in value) {\n return { kind: \"avatar_too_big\" };\n }\n if (\"MaxGroupsCreated\" in value || \"MaxChannelsCreated\" in value) {\n // todo - make sure we handle this in the UI\n return { kind: \"max_groups_created\" };\n }\n }\n if (value === \"NameTaken\") {\n return { kind: \"group_name_taken\" };\n }\n if (value === \"NameReserved\") {\n return { kind: \"name_reserved\" };\n }\n if (value === \"Throttled\") {\n return { kind: \"throttled\" };\n }\n if (value === \"UserSuspended\") {\n return { kind: \"user_suspended\" };\n }\n if (value === \"UserLapsed\") {\n return { kind: \"user_lapsed\" };\n }\n if (value === \"UnauthorizedToCreatePublicGroup\") {\n return { kind: \"unauthorized_to_create_public_group\" };\n }\n if (value === \"NotAuthorized\") {\n return CommonResponses.notAuthorized();\n }\n if (value === \"CommunityFrozen\") {\n return CommonResponses.communityFrozen();\n }\n if (value === \"AccessGateInvalid\") {\n return { kind: \"access_gate_invalid\" };\n }\n if (value === \"ExternalUrlInvalid\") {\n return { kind: \"external_url_invalid\" };\n }\n if (value === \"InternalError\") {\n return { kind: \"internal_error\" };\n }\n throw new UnsupportedValueError(\"Unexpected ApiCreateGroupResponse type received\", value);\n}\nexport function deleteGroupResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n else {\n console.warn(\"DeleteGroupResponse failed with: \", value);\n return \"failure\";\n }\n}\nexport function pinMessageResponse(value) {\n if (typeof value === \"object\" && \"Success\" in value) {\n return {\n kind: \"success\",\n eventIndex: value.Success.index,\n timestamp: value.Success.timestamp,\n };\n }\n else if (value === \"NoChange\") {\n return CommonResponses.noChange();\n }\n else {\n console.warn(\"PinMessageResponse failed with: \", value);\n return CommonResponses.failure();\n }\n}\nexport function unpinMessageResponse(value) {\n if (typeof value === \"object\") {\n if (\"Success\" in value || \"SuccessV2\" in value) {\n return \"success\";\n }\n }\n if (value === \"NoChange\") {\n return \"success\";\n }\n else {\n console.warn(\"UnpinMessageResponse failed with: \", value);\n return \"failure\";\n }\n}\nexport function groupDetailsResponse(value) {\n if (value === \"CallerNotInGroup\" ||\n value === \"PrivateCommunity\" ||\n value === \"PrivateChannel\" ||\n value === \"ChannelNotFound\" ||\n \"UserNotInChannel\" in value ||\n \"UserNotInCommunity\" in value ||\n \"Error\" in value) {\n console.warn(\"GetGroupDetails failed with \", value);\n return \"failure\";\n }\n if (\"Success\" in value) {\n console.log(\"Group details: \", value.Success);\n const members = (\"participants\" in value.Success ? value.Success.participants : value.Success.members).map(member);\n const basicMembers = \"basic_members\" in value.Success ? value.Success.basic_members : [];\n const membersSet = new Set();\n members.forEach((m) => membersSet.add(m.userId));\n for (const id of basicMembers) {\n const userId = principalBytesToString(id);\n if (membersSet.add(userId)) {\n members.push({\n role: \"member\",\n userId,\n displayName: undefined,\n lapsed: false,\n });\n }\n }\n const bots = \"bots\" in value.Success ? value.Success.bots : [];\n return {\n members,\n blockedUsers: new Set(value.Success.blocked_users.map(principalBytesToString)),\n invitedUsers: new Set(value.Success.invited_users.map(principalBytesToString)),\n pinnedMessages: new Set(value.Success.pinned_messages),\n rules: value.Success.chat_rules,\n timestamp: value.Success.timestamp,\n bots: bots.map(installedBotDetails),\n apiKeys: value.Success.api_keys.map(publicApiKeyDetails).reduce((m, k) => {\n m.set(k.botId, k);\n return m;\n }, new Map()),\n };\n }\n throw new UnsupportedValueError(\"Unexpected ApiDeleteMessageResponse type received\", value);\n}\nexport function publicApiKeyDetails(value) {\n return {\n botId: principalBytesToString(value.bot_id),\n grantedPermissions: externalBotPermissions(value.granted_permissions),\n generatedBy: principalBytesToString(value.generated_by),\n generatedAt: value.generated_at,\n };\n}\nexport function groupDetailsUpdatesResponse(value) {\n if (typeof value === \"object\") {\n if (\"Success\" in value) {\n return {\n kind: \"success\",\n membersAddedOrUpdated: value.Success.members_added_or_updated.map(member),\n membersRemoved: new Set(value.Success.members_removed.map(principalBytesToString)),\n blockedUsersAdded: new Set(value.Success.blocked_users_added.map(principalBytesToString)),\n blockedUsersRemoved: new Set(value.Success.blocked_users_removed.map(principalBytesToString)),\n pinnedMessagesAdded: new Set(value.Success.pinned_messages_added),\n pinnedMessagesRemoved: new Set(value.Success.pinned_messages_removed),\n rules: value.Success.chat_rules,\n invitedUsers: mapOptional(value.Success.invited_users, (invited_users) => new Set(invited_users.map(principalBytesToString))),\n timestamp: value.Success.timestamp,\n botsAddedOrUpdated: value.Success.bots_added_or_updated.map(installedBotDetails),\n botsRemoved: new Set(value.Success.bots_removed.map(principalBytesToString)),\n apiKeysGenerated: value.Success.api_keys_generated.map(publicApiKeyDetails),\n };\n }\n else if (\"SuccessNoUpdates\" in value) {\n return {\n kind: \"success_no_updates\",\n timestamp: value.SuccessNoUpdates,\n };\n }\n }\n console.warn(\"Unexpected ApiSelectedUpdatesResponse type received\", value);\n return CommonResponses.failure();\n}\nexport function member(value) {\n return {\n role: memberRole(value.role),\n userId: principalBytesToString(value.user_id),\n displayName: undefined,\n lapsed: value.lapsed,\n };\n}\nexport function editMessageResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n else {\n console.warn(\"EditMessageResponse failed with: \", value);\n return \"failure\";\n }\n}\nexport function declineInvitationResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n else {\n console.warn(\"DeclineInvitationResponse failed with: \", value);\n return \"failure\";\n }\n}\nexport function leaveGroupResponse(value) {\n if (value === \"Success\" ||\n value === \"GroupNotFound\" ||\n value === \"CallerNotInGroup\" ||\n value === \"UserNotInChannel\" ||\n value === \"ChannelNotFound\") {\n return \"success\";\n }\n if (value === \"LastOwnerCannotLeave\") {\n return \"owner_cannot_leave\";\n }\n return \"failure\";\n}\nexport function deleteMessageResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n else {\n console.warn(\"DeleteMessageResponse failed with: \", value);\n return \"failure\";\n }\n}\nexport function deletedMessageResponse(value) {\n if (typeof value === \"object\" && \"Success\" in value) {\n return {\n kind: \"success\",\n content: messageContent(value.Success.content, \"unknown\"),\n };\n }\n else {\n console.warn(\"DeletedMessageResponse failed with: \", value);\n return CommonResponses.failure();\n }\n}\nexport function undeleteMessageResponse(value) {\n if (typeof value === \"object\" && \"Success\" in value) {\n if (value.Success.messages.length == 0) {\n return CommonResponses.failure();\n }\n else {\n return {\n kind: \"success\",\n message: message(value.Success.messages[0]),\n };\n }\n }\n else {\n console.warn(\"UndeleteMessageResponse failed with: \", value);\n return CommonResponses.failure();\n }\n}\nexport function threadPreviewsResponse(value, chatId, latestClientThreadUpdate) {\n if (typeof value === \"object\") {\n if (\"Success\" in value) {\n return {\n kind: \"thread_previews_success\",\n threads: value.Success.threads.map((t) => threadPreview(chatId, t)),\n };\n }\n if (\"ReplicaNotUpToDate\" in value) {\n throw ReplicaNotUpToDateError.byTimestamp(value.ReplicaNotUpToDate, latestClientThreadUpdate ?? BigInt(-1), false);\n }\n }\n console.warn(\"ThreadPreviewsResponse failed with: \", value);\n return CommonResponses.failure();\n}\nexport function threadPreview(chatId, value) {\n return {\n chatId: { ...chatId },\n latestReplies: value.latest_replies.map(messageEvent).sort((e1, e2) => e1.index - e2.index),\n totalReplies: value.total_replies,\n rootMessage: messageEvent(value.root_message),\n };\n}\nexport function changeRoleResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n else {\n console.warn(\"ChangeRoleResponse failed with: \", value);\n return \"failure\";\n }\n}\nexport function registerPollVoteResponse(value) {\n if (typeof value === \"object\" && \"Success\" in value) {\n return \"success\";\n }\n else {\n console.warn(\"RegisterPollVoteResponse failed with: \", value);\n return \"failure\";\n }\n}\nexport function apiChatIdentifier(chatId) {\n switch (chatId.kind) {\n case \"group_chat\":\n return { Group: principalStringToBytes(chatId.groupId) };\n case \"direct_chat\":\n return { Direct: principalStringToBytes(chatId.userId) };\n case \"channel\":\n return {\n Channel: [principalStringToBytes(chatId.communityId), toBigInt32(chatId.channelId)],\n };\n }\n}\nexport function joinGroupResponse(value) {\n if (typeof value === \"object\") {\n if (\"Success\" in value) {\n return { kind: \"success\", group: groupChatSummary(value.Success) };\n }\n else if (\"AlreadyInGroupV2\" in value) {\n return { kind: \"success\", group: groupChatSummary(value.AlreadyInGroupV2) };\n }\n else if (\"GateCheckFailed\" in value) {\n return {\n kind: \"gate_check_failed\",\n reason: gateCheckFailedReason(value.GateCheckFailed),\n };\n }\n }\n if (value === \"Blocked\") {\n return CommonResponses.userBlocked();\n }\n else {\n console.warn(\"Join group failed with: \", value);\n return CommonResponses.failure();\n }\n}\nexport function searchGroupChatResponse(value, chatId) {\n if (typeof value === \"object\" && \"Success\" in value) {\n return {\n kind: \"success\",\n matches: value.Success.matches.map((m) => messageMatch(m, chatId)),\n };\n }\n else {\n console.warn(\"SearchChat failed with \", value);\n return CommonResponses.failure();\n }\n}\nexport function messageMatch(value, chatId) {\n return {\n chatId,\n messageIndex: value.message_index,\n score: value.score,\n };\n}\nexport function inviteCodeResponse(value) {\n if (typeof value === \"object\") {\n if (\"Success\" in value) {\n return {\n kind: \"success\",\n code: mapOptional(value.Success.code, codeToText),\n };\n }\n }\n if (value === \"NotAuthorized\") {\n return {\n kind: \"not_authorized\",\n };\n }\n else {\n console.warn(\"InviteCode failed with \", value);\n return CommonResponses.failure();\n }\n}\nexport function enableOrResetInviteCodeResponse(value) {\n if (typeof value === \"object\") {\n if (\"Success\" in value) {\n return {\n kind: \"success\",\n code: codeToText(value.Success.code),\n };\n }\n else if (\"NotAuthorized\" in value) {\n return {\n kind: \"not_authorized\",\n };\n }\n }\n console.warn(\"ResetInviteCode failed with \", value);\n return CommonResponses.failure();\n}\nexport function disableInviteCodeResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n else if (value === \"NotAuthorized\") {\n return \"not_authorized\";\n }\n console.warn(\"DisableInviteCode failed with \", value);\n return \"failure\";\n}\nexport function registerProposalVoteResponse(value) {\n if (typeof value === \"object\") {\n if (\"AlreadyVoted\" in value) {\n return \"already_voted\";\n }\n if (\"InternalError\" in value) {\n return \"internal_error\";\n }\n if (\"Error\" in value) {\n return \"internal_error\";\n }\n }\n if (value === \"Success\") {\n return \"success\";\n }\n if (value === \"CallerNotInGroup\") {\n return \"caller_not_in_group\";\n }\n if (value === \"UserNotInChannel\") {\n return \"user_not_in_channel\";\n }\n if (value === \"ChannelNotFound\") {\n return \"channel_not_found\";\n }\n if (value === \"UserNotInCommunity\") {\n return \"user_not_in_community\";\n }\n if (value === \"CommunityFrozen\") {\n return \"community_frozen\";\n }\n if (value === \"NoEligibleNeurons\") {\n return \"no_eligible_neurons\";\n }\n if (value === \"ProposalNotAcceptingVotes\") {\n return \"proposal_not_accepting_votes\";\n }\n if (value === \"ProposalNotFound\") {\n return \"proposal_not_found\";\n }\n if (value === \"ProposalMessageNotFound\") {\n return \"proposal_message_not_found\";\n }\n if (value === \"UserSuspended\") {\n return \"user_suspended\";\n }\n if (value === \"UserLapsed\") {\n return \"user_lapsed\";\n }\n if (value === \"ChatFrozen\") {\n return \"chat_frozen\";\n }\n throw new UnsupportedValueError(\"Unexpected ApiRegisterProposalVoteResponse type received\", value);\n}\nexport function claimPrizeResponse(value) {\n if (value === \"Success\") {\n return CommonResponses.success();\n }\n else {\n console.warn(\"ClaimPrize failed with \", value);\n return CommonResponses.failure();\n }\n}\nexport function statusError(value) {\n if (\"Reserved\" in value) {\n return {\n kind: \"already_reserved\",\n reservedBy: principalBytesToString(value.Reserved.reserved_by),\n };\n }\n if (\"Accepted\" in value) {\n return {\n kind: \"already_accepted\",\n acceptedBy: principalBytesToString(value.Accepted.accepted_by),\n token1TxnIn: value.Accepted.token1_txn_in,\n };\n }\n if (\"Completed\" in value) {\n const { accepted_by, token1_txn_in, token0_txn_out, token1_txn_out } = value.Completed;\n return {\n kind: \"already_completed\",\n acceptedBy: principalBytesToString(accepted_by),\n token1TxnIn: token1_txn_in,\n token0TxnOut: token0_txn_out,\n token1TxnOut: token1_txn_out,\n };\n }\n if (\"Cancelled\" in value) {\n return {\n kind: \"swap_cancelled\",\n token0TxnOut: value.Cancelled.token0_txn_out,\n };\n }\n if (\"Expired\" in value) {\n return {\n kind: \"swap_expired\",\n token0TxnOut: value.Expired.token0_txn_out,\n };\n }\n throw new UnsupportedValueError(\"Unexpected SwapStatusError type received\", value);\n}\nexport function acceptP2PSwapResponse(value) {\n if (typeof value === \"object\") {\n if (\"Success\" in value) {\n return { kind: \"success\", token1TxnIn: value.Success.token1_txn_in };\n }\n if (\"StatusError\" in value) {\n return statusError(value.StatusError);\n }\n if (\"InternalError\" in value) {\n return { kind: \"internal_error\", text: value.InternalError };\n }\n if (\"PinIncorrect\" in value || \"TooManyFailedPinAttempts\" in value) {\n return pinNumberFailureResponseV2(value);\n }\n if (\"Error\" in value) {\n return ocError(value.Error);\n }\n }\n if (value === \"ChatNotFound\")\n return { kind: \"chat_not_found\" };\n if (value === \"UserNotInGroup\")\n return { kind: \"user_not_in_group\" };\n if (value === \"UserNotInCommunity\")\n return { kind: \"user_not_in_community\" };\n if (value === \"UserNotInChannel\")\n return { kind: \"user_not_in_channel\" };\n if (value === \"ChannelNotFound\")\n return { kind: \"channel_not_found\" };\n if (value === \"SwapNotFound\")\n return { kind: \"swap_not_found\" };\n if (value === \"ChatFrozen\")\n return { kind: \"chat_frozen\" };\n if (value === \"UserSuspended\")\n return { kind: \"user_suspended\" };\n if (value === \"UserLapsed\")\n return { kind: \"user_lapsed\" };\n if (value === \"InsufficientFunds\")\n return { kind: \"insufficient_funds\" };\n if (value === \"PinRequired\")\n return { kind: \"pin_required\" };\n throw new UnsupportedValueError(\"Unexpected ApiAcceptP2PSwapResponse type received\", value);\n}\nexport function cancelP2PSwapResponse(value) {\n if (value === \"Success\") {\n return { kind: \"success\" };\n }\n if (typeof value === \"object\" && \"StatusError\" in value) {\n return statusError(value.StatusError);\n }\n if (typeof value === \"object\" && \"Error\" in value) {\n return ocError(value.Error);\n }\n if (value === \"ChatNotFound\")\n return { kind: \"chat_not_found\" };\n if (value === \"UserNotInGroup\")\n return { kind: \"user_not_in_group\" };\n if (value === \"UserNotInCommunity\")\n return { kind: \"user_not_in_community\" };\n if (value === \"UserNotInChannel\")\n return { kind: \"user_not_in_channel\" };\n if (value === \"ChannelNotFound\")\n return { kind: \"channel_not_found\" };\n if (value === \"ChatFrozen\")\n return { kind: \"chat_frozen\" };\n if (value === \"SwapNotFound\")\n return { kind: \"swap_not_found\" };\n if (value === \"UserSuspended\")\n return { kind: \"user_suspended\" };\n throw new UnsupportedValueError(\"Unexpected ApiCancelP2PSwapResponse type received\", value);\n}\nexport function joinVideoCallResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n if (value === \"AlreadyEnded\") {\n return \"ended\";\n }\n console.warn(\"JoinVideoCall failed with \", value);\n return \"failure\";\n}\nexport function apiVideoCallPresence(domain) {\n switch (domain) {\n case \"default\":\n return \"Default\";\n case \"hidden\":\n return \"Hidden\";\n case \"owner\":\n return \"Owner\";\n }\n}\nexport function setVideoCallPresence(value) {\n if (value === \"Success\")\n return \"success\";\n console.warn(\"SetVideoCallPresence failed with: \", value);\n return \"failure\";\n}\nexport function videoCallParticipantsResponse(value) {\n if (typeof value === \"object\" && \"Success\" in value) {\n return {\n kind: \"success\",\n participants: value.Success.participants.map(videoCallParticipant),\n hidden: value.Success.hidden.map(videoCallParticipant),\n lastUpdated: value.Success.last_updated,\n };\n }\n console.warn(\"VideoCallParticipants failed with: \", value);\n return CommonResponses.failure();\n}\nexport function setPinNumberResponse(value) {\n if (value === \"Success\") {\n return CommonResponses.success();\n }\n if (typeof value === \"object\") {\n if (\"PinIncorrect\" in value || \"TooManyFailedPinAttempts\" in value) {\n return pinNumberFailureResponseV2(value);\n }\n if (\"TooShort\" in value) {\n return { kind: \"too_short\", minLength: value.TooShort.min_length };\n }\n if (\"TooLong\" in value) {\n return { kind: \"too_long\", maxLength: value.TooLong.max_length };\n }\n if (\"MalformedSignature\" in value) {\n return { kind: \"malformed_signature\" };\n }\n if (\"Error\" in value) {\n return ocError(value.Error);\n }\n }\n if (value === \"PinRequired\") {\n return { kind: \"pin_required\" };\n }\n if (value === \"DelegationTooOld\") {\n return { kind: \"delegation_too_old\" };\n }\n throw new UnsupportedValueError(\"Unexpected ApiSetPinNumberResponse type received\", value);\n}\nexport function apiDexId(dex) {\n switch (dex) {\n case \"icpswap\":\n return \"ICPSwap\";\n case \"kongswap\":\n return \"KongSwap\";\n case \"sonic\":\n throw new Error(\"Unsupported dex sonic\");\n // return \"Sonic\";\n }\n}\nexport function externalBotPermissions(value) {\n return {\n communityPermissions: permissionsFromBits(value.community ?? 0, [\n ...communityPermissionsList,\n ]),\n chatPermissions: permissionsFromBits(value.chat ?? 0, [...botChatPermissionList]),\n messagePermissions: permissionsFromBits(value.message ?? 0, [...messagePermissionsList]),\n };\n}\nexport function apiExternalBotPermissions(value) {\n return {\n community: permissionsToBits(value.communityPermissions, [...communityPermissionsList]),\n chat: permissionsToBits(value.chatPermissions, [...botChatPermissionList]),\n message: permissionsToBits(value.messagePermissions, [...messagePermissionsList]),\n };\n}\nfunction permissionsFromBits(bits, allPermissions) {\n const permissions = [];\n for (let i = 0; i < allPermissions.length; i++) {\n if ((bits & (1 << i)) !== 0) {\n permissions.push(allPermissions[i]);\n }\n }\n return permissions;\n}\nfunction permissionsToBits(permissions, allPermissions) {\n let bits = 0;\n for (let i = 0; i < allPermissions.length; i++) {\n if (permissions.includes(allPermissions[i])) {\n bits += 1 << i;\n }\n }\n return bits;\n}\nexport function updateBotResponse(value) {\n if (value === \"Success\") {\n return true;\n }\n console.warn(\"Community|GroupUpdateBotResponse|UserUpdateBotResponse failed with \", value);\n return false;\n}\nexport function installedBotDetails(value) {\n return {\n id: principalBytesToString(value.user_id),\n permissions: externalBotPermissions(value.permissions),\n };\n}\nexport function externalBotDefinition(value) {\n return {\n kind: \"bot_definition\",\n description: value.description,\n commands: value.commands.map(externalBotCommand),\n autonomousConfig: mapOptional(value.autonomous_config, (c) => ({\n syncApiKey: c.sync_api_key,\n permissions: externalBotPermissions(c.permissions),\n })),\n };\n}\nexport function externalBotCommand(command) {\n return {\n name: command.name,\n description: command.description,\n placeholder: mapOptional(command.placeholder, identity),\n params: command.params.map(externalBotParam),\n permissions: externalBotPermissions(command.permissions),\n defaultRole: mapOptional(command.default_role, memberRole) ?? \"member\",\n directMessages: command.direct_messages ?? false,\n };\n}\nexport function externalBotParam(param) {\n return {\n ...param,\n ...customParamFields(param.param_type),\n };\n}\nexport function customParamFields(paramType) {\n if (paramType === \"UserParam\") {\n return {\n kind: \"user\",\n };\n }\n else if (paramType === \"BooleanParam\") {\n return { kind: \"boolean\" };\n }\n else if (\"StringParam\" in paramType) {\n return {\n kind: \"string\",\n minLength: paramType.StringParam.min_length,\n maxLength: paramType.StringParam.max_length,\n choices: paramType.StringParam.choices,\n multi_line: paramType.StringParam.multi_line,\n };\n }\n else if (\"IntegerParam\" in paramType) {\n return {\n kind: \"integer\",\n minValue: paramType.IntegerParam.min_value,\n maxValue: paramType.IntegerParam.max_value,\n choices: paramType.IntegerParam.choices.map((c) => ({\n name: c.name,\n value: c.value,\n })),\n };\n }\n else if (\"DecimalParam\" in paramType) {\n return {\n kind: \"decimal\",\n minValue: paramType.DecimalParam.min_value,\n maxValue: paramType.DecimalParam.max_value,\n choices: paramType.DecimalParam.choices,\n };\n }\n else if (\"DateTimeParam\" in paramType) {\n return {\n kind: \"dateTime\",\n future_only: paramType.DateTimeParam.future_only,\n };\n }\n throw new UnsupportedValueError(\"Unexpected ApiCommandParamType value\", paramType);\n}\nexport function principalToIcrcAccount(principal) {\n return {\n owner: principalStringToBytes(principal),\n subaccount: undefined,\n };\n}\nexport function ocError(error) {\n return {\n kind: \"error\",\n code: error[0],\n message: error[1] ?? undefined,\n };\n}\n","import { UnsupportedValueError } from \"openchat-shared\";\nexport function mapCommonResponses(value, name) {\n return mapCommonResponsesInner(value, name);\n}\nfunction mapCommonResponsesInner(value, name) {\n if (typeof value === \"string\") {\n switch (value) {\n case \"Success\":\n case \"SuccessV2\":\n return \"success\";\n case \"SuccessNoUpdates\":\n return \"success_no_updates\";\n case \"AlreadyEnded\":\n return \"already_ended\";\n case \"CallerNotInGroup\":\n return \"caller_not_in_group\";\n case \"ChannelNotFound\":\n return \"channel_not_found\";\n case \"ChatFrozen\":\n return \"chat_frozen\";\n case \"ChatNotFound\":\n return \"chat_not_found\";\n case \"CommunityFrozen\":\n return \"community_frozen\";\n case \"CommunityPublic\":\n return \"community_public\";\n case \"GroupFrozen\":\n return \"group_frozen\";\n case \"GroupNotPublic\":\n return \"group_not_public\";\n case \"InternalError\":\n return \"internal_error\";\n case \"Invalid\":\n return \"invalid\";\n case \"MessageNotFound\":\n return \"message_not_found\";\n case \"MessageAlreadyExists\":\n return \"message_already_exists\";\n case \"NotAuthorized\":\n return \"not_authorized\";\n case \"ThreadMessageNotFound\":\n return \"thread_message_not_found\";\n case \"ThreadNotFound\":\n return \"thread_not_found\";\n case \"UserLapsed\":\n return \"user_lapsed\";\n case \"UserNotFound\":\n return \"user_not_found\";\n case \"UserNotInChannel\":\n return \"user_not_in_channel\";\n case \"UserNotInCommunity\":\n return \"user_not_in_community\";\n case \"UserNotInGroup\":\n return \"user_not_in_group\";\n case \"UserSuspended\":\n return \"user_suspended\";\n }\n }\n else if (typeof value === \"object\") {\n if (\"InternalError\" in value) {\n return \"internal_error\";\n }\n }\n throw new UnsupportedValueError(`Unexpected ${name} type received`, value);\n}\n","import { toBigInt32, CommonResponses, UnsupportedValueError } from \"openchat-shared\";\nimport { mapOptional, optionUpdateV2, principalBytesToString } from \"../../utils/mapping\";\nimport { accessGateConfig, apiCommunityPermissionRole, installedBotDetails, chatMetrics, communityChannelSummary, communityPermissions, communitySummary, groupPermissions, groupSubtype, memberRole, mentions, messageEvent, ocError, publicApiKeyDetails, threadSyncDetails, updatedEvent, userGroup, } from \"../common/chatMappersV2\";\nimport { identity } from \"../../utils/mapping\";\nimport { mapCommonResponses } from \"../common/commonResponseMapper\";\nexport function addMembersToChannelResponse(value) {\n if (typeof value === \"object\") {\n if (\"PartialSuccess\" in value) {\n return addToChannelPartialSuccess(value.PartialSuccess);\n }\n if (\"Failed\" in value) {\n return addToChannelFailed(value.Failed);\n }\n if (\"UserLimitReached\" in value) {\n return CommonResponses.userLimitReached();\n }\n if (\"Error\" in value) {\n return ocError(value.Error);\n }\n }\n return {\n kind: mapCommonResponses(value, \"AddMembersToChannel\"),\n };\n}\nfunction addToChannelFailed(value) {\n return {\n kind: \"add_to_channel_failed\",\n usersLimitReached: value.users_limit_reached.map(principalBytesToString),\n usersAlreadyInChannel: value.users_already_in_channel.map(principalBytesToString),\n usersFailedWithError: value.users_failed_with_error.map(userFailedWithError),\n };\n}\nfunction userFailedWithError(value) {\n return {\n userId: principalBytesToString(value.user_id),\n error: value.error,\n };\n}\nfunction addToChannelPartialSuccess(value) {\n return {\n kind: \"add_to_channel_partial_success\",\n usersLimitReached: value.users_limit_reached.map(principalBytesToString),\n usersAlreadyInChannel: value.users_already_in_channel.map(principalBytesToString),\n usersFailedWithError: value.users_failed_with_error.map(userFailedWithError),\n usersAdded: value.users_added.map(principalBytesToString),\n };\n}\nexport function blockUserResponse(value) {\n if (value === \"Success\") {\n return CommonResponses.success();\n }\n else {\n console.warn(\"BlockCommunityUser failed with \", value);\n return CommonResponses.failure();\n }\n}\nexport function changeRoleResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n else {\n console.warn(\"Unexpected ApiChangeRoleResponse type received\", value);\n return \"failure\";\n }\n}\nexport function removeMemberResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n else {\n console.warn(\"RemoveCommunityMember failed with\", value);\n return \"failure\";\n }\n}\nexport function removeMemberFromChannelResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n else {\n console.warn(\"RemoveChannelMember failed with\", value);\n return \"failure\";\n }\n}\nexport function sendMessageResponse(value) {\n if (typeof value === \"object\") {\n if (\"Success\" in value) {\n return {\n kind: \"success\",\n timestamp: value.Success.timestamp,\n messageIndex: value.Success.message_index,\n eventIndex: value.Success.event_index,\n expiresAt: mapOptional(value.Success.expires_at, Number),\n };\n }\n }\n if (value === \"RulesNotAccepted\") {\n return { kind: \"rules_not_accepted\" };\n }\n else if (value === \"CommunityRulesNotAccepted\") {\n return { kind: \"community_rules_not_accepted\" };\n }\n else {\n console.warn(\"SendMessage failed with\", value);\n return CommonResponses.failure();\n }\n}\nexport function exploreChannelsResponse(value, communityId) {\n if (typeof value === \"object\" && \"Success\" in value) {\n return {\n kind: \"success\",\n matches: value.Success.matches.map((m) => channelMatch(m, communityId)),\n total: value.Success.total,\n };\n }\n else {\n console.warn(\"ExploreChannels failed with\", value);\n return CommonResponses.failure();\n }\n}\nexport function channelMatch(value, communityId) {\n return {\n id: { kind: \"channel\", communityId, channelId: Number(toBigInt32(value.id)) },\n gateConfig: mapOptional(value.gate_config, accessGateConfig) ?? {\n expiry: undefined,\n gate: { kind: \"no_gate\" },\n },\n name: value.name,\n description: value.description,\n memberCount: value.member_count,\n public: value.is_public,\n avatar: {\n blobReference: mapOptional(value.avatar_id, (blobId) => ({\n blobId,\n canisterId: communityId,\n })),\n },\n };\n}\nexport function communityChannelSummaryResponse(value, communityId) {\n console.log(\"Channel summary: \", value);\n if (typeof value === \"object\" && \"Success\" in value) {\n return communityChannelSummary(value.Success, communityId);\n }\n else {\n console.warn(\"CommunityChannelSummary failed with\", value);\n return CommonResponses.failure();\n }\n}\nexport function importGroupResponse(communityId, value) {\n if (typeof value === \"object\" && \"Success\" in value) {\n return {\n kind: \"success\",\n channelId: {\n kind: \"channel\",\n communityId,\n channelId: Number(toBigInt32(value.Success.channel_id)),\n },\n };\n }\n else {\n console.warn(\"ImportGroup failed with\", value);\n return CommonResponses.failure();\n }\n}\nexport function summaryResponse(value) {\n if (typeof value === \"object\" && \"Success\" in value) {\n return communitySummary(value.Success);\n }\n else {\n console.warn(\"CommunitySummary failed with\", value);\n return CommonResponses.failure();\n }\n}\nexport function summaryUpdatesResponse(value) {\n if (typeof value === \"object\" && \"Success\" in value) {\n return communitySummaryUpdates(value.Success);\n }\n if (typeof value === \"object\" && \"Error\" in value) {\n return ocError(value.Error);\n }\n if (value === \"SuccessNoUpdates\") {\n return CommonResponses.successNoUpdates();\n }\n if (value === \"PrivateCommunity\") {\n return CommonResponses.failure();\n }\n throw new UnsupportedValueError(\"invalid ApiSummaryUpdatesResponse received\", value);\n}\nexport function communitySummaryUpdates(value) {\n const communityId = principalBytesToString(value.community_id);\n return {\n id: { kind: \"community\", communityId },\n public: value.is_public,\n permissions: mapOptional(value.permissions, communityPermissions),\n channelsUpdated: value.channels_updated.map((c) => communityChannelUpdates(c, communityId)),\n metrics: mapOptional(value.metrics, chatMetrics),\n gateConfig: optionUpdateV2(value.gate_config, accessGateConfig),\n name: value.name,\n description: value.description,\n lastUpdated: value.last_updated,\n channelsRemoved: value.channels_removed.map((c) => ({\n kind: \"channel\",\n communityId,\n channelId: Number(toBigInt32(c)),\n })),\n avatarId: optionUpdateV2(value.avatar_id, identity),\n channelsAdded: value.channels_added.map((c) => communityChannelSummary(c, communityId)),\n membership: mapOptional(value.membership, communityMembershipUpdates),\n frozen: optionUpdateV2(value.frozen, (_) => true),\n latestEventIndex: value.latest_event_index,\n bannerId: optionUpdateV2(value.banner_id, identity),\n memberCount: value.member_count,\n primaryLanguage: value.primary_language,\n userGroups: value.user_groups.map(userGroup).map(([_, g]) => g),\n userGroupsDeleted: new Set(value.user_groups_deleted),\n verified: mapOptional(value.verified, identity),\n };\n}\nexport function communityMembershipUpdates(value) {\n return {\n role: mapOptional(value.role, memberRole),\n displayName: optionUpdateV2(value.display_name, identity),\n rulesAccepted: value.rules_accepted,\n lapsed: value.lapsed,\n };\n}\nexport function communityChannelUpdates(value, communityId) {\n return {\n id: { kind: \"channel\", communityId, channelId: Number(toBigInt32(value.channel_id)) },\n public: value.is_public,\n permissions: mapOptional(value.permissions_v2, groupPermissions),\n metrics: mapOptional(value.metrics, chatMetrics),\n subtype: optionUpdateV2(value.subtype, groupSubtype),\n dateLastPinned: value.date_last_pinned,\n gateConfig: optionUpdateV2(value.gate_config, accessGateConfig),\n name: value.name,\n description: value.description,\n externalUrl: optionUpdateV2(value.external_url, identity),\n lastUpdated: value.last_updated,\n avatarId: optionUpdateV2(value.avatar_id, identity),\n membership: mapOptional(value.membership, groupMembershipUpdates),\n updatedEvents: value.updated_events.map(updatedEvent),\n latestEventIndex: value.latest_event_index,\n latestMessageIndex: value.latest_message_index,\n memberCount: value.member_count,\n latestMessage: mapOptional(value.latest_message, messageEvent),\n eventsTTL: optionUpdateV2(value.events_ttl, identity),\n eventsTtlLastUpdated: value.events_ttl_last_updated,\n videoCallInProgress: optionUpdateV2(value.video_call_in_progress, (v) => v.message_index),\n messageVisibleToNonMembers: value.messages_visible_to_non_members,\n };\n}\nexport function groupMembershipUpdates(value) {\n return {\n myRole: mapOptional(value.role, memberRole),\n notificationsMuted: value.notifications_muted,\n latestThreads: value.latest_threads.map(threadSyncDetails),\n unfollowedThreads: Array.from(value.unfollowed_threads),\n mentions: mentions(value.mentions),\n myMetrics: mapOptional(value.my_metrics, chatMetrics),\n rulesAccepted: value.rules_accepted,\n lapsed: value.lapsed,\n };\n}\nexport function unblockUserResponse(value) {\n if (value === \"Success\") {\n return CommonResponses.success();\n }\n else {\n console.warn(\"UnblockCommunityUser failed with\", value);\n return CommonResponses.failure();\n }\n}\nexport function updateCommunityResponse(value) {\n if (typeof value === \"object\" && \"SuccessV2\" in value) {\n return {\n kind: \"success\",\n rulesVersion: value.SuccessV2.rules_version,\n };\n }\n else {\n console.warn(\"UpdateCommunity failed with\", value);\n return CommonResponses.failure();\n }\n}\nexport function apiMemberRole(domain) {\n switch (domain) {\n case \"owner\":\n return \"Owner\";\n case \"admin\":\n return \"Admin\";\n case \"moderator\":\n return \"Moderator\";\n default:\n return \"Participant\";\n }\n}\nexport function apiCommunityRole(newRole) {\n switch (newRole) {\n case \"owner\":\n return \"Owner\";\n case \"admin\":\n return \"Admin\";\n default:\n return \"Member\";\n }\n}\nexport function apiOptionalCommunityPermissions(permissions) {\n return {\n create_public_channel: mapOptional(permissions.createPublicChannel, apiCommunityPermissionRole),\n update_details: mapOptional(permissions.updateDetails, apiCommunityPermissionRole),\n remove_members: mapOptional(permissions.removeMembers, apiCommunityPermissionRole),\n invite_users: mapOptional(permissions.inviteUsers, apiCommunityPermissionRole),\n change_roles: mapOptional(permissions.changeRoles, apiCommunityPermissionRole),\n create_private_channel: mapOptional(permissions.createPrivateChannel, apiCommunityPermissionRole),\n manage_user_groups: mapOptional(permissions.manageUserGroups, apiCommunityPermissionRole),\n };\n}\nexport function communityDetailsResponse(value) {\n if (typeof value === \"object\" && \"Success\" in value) {\n console.log(\"Community details: \", value.Success);\n return {\n members: value.Success.members\n .map((m) => ({\n role: memberRole(m.role),\n userId: principalBytesToString(m.user_id),\n displayName: m.display_name,\n lapsed: m.lapsed,\n }))\n .concat(value.Success.basic_members.map((id) => ({\n role: \"member\",\n userId: principalBytesToString(id),\n displayName: undefined,\n lapsed: false,\n }))),\n blockedUsers: new Set(value.Success.blocked_users.map(principalBytesToString)),\n invitedUsers: new Set(value.Success.invited_users.map(principalBytesToString)),\n rules: value.Success.chat_rules,\n lastUpdated: value.Success.timestamp,\n userGroups: new Map(value.Success.user_groups.map(userGroupDetails)),\n referrals: new Set(value.Success.referrals.map(principalBytesToString)),\n bots: value.Success.bots.map(installedBotDetails),\n apiKeys: value.Success.api_keys.map(publicApiKeyDetails).reduce((m, k) => {\n m.set(k.botId, k);\n return m;\n }, new Map()),\n };\n }\n else {\n console.warn(\"CommunityDetails failed with\", value);\n return \"failure\";\n }\n}\nexport function userGroupDetails(value) {\n return [\n value.user_group_id,\n {\n id: value.user_group_id,\n kind: \"user_group\",\n members: new Set(value.members.map(principalBytesToString)),\n name: value.name,\n },\n ];\n}\nexport function communityDetailsUpdatesResponse(value) {\n if (typeof value === \"object\") {\n if (\"Success\" in value) {\n return {\n kind: \"success\",\n membersAddedOrUpdated: value.Success.members_added_or_updated.map((m) => ({\n role: memberRole(m.role),\n userId: principalBytesToString(m.user_id),\n displayName: m.display_name,\n lapsed: m.lapsed,\n })),\n membersRemoved: new Set(value.Success.members_removed.map(principalBytesToString)),\n blockedUsersAdded: new Set(value.Success.blocked_users_added.map(principalBytesToString)),\n blockedUsersRemoved: new Set(value.Success.blocked_users_removed.map(principalBytesToString)),\n rules: value.Success.chat_rules,\n invitedUsers: mapOptional(value.Success.invited_users, (invited_users) => new Set(invited_users.map(principalBytesToString))),\n lastUpdated: value.Success.timestamp,\n userGroups: value.Success.user_groups.map(userGroupDetails).map(([_, g]) => g),\n userGroupsDeleted: new Set(value.Success.user_groups_deleted),\n referralsRemoved: new Set(value.Success.referrals_removed.map(principalBytesToString)),\n referralsAdded: new Set(value.Success.referrals_added.map(principalBytesToString)),\n botsAddedOrUpdated: value.Success.bots_added_or_updated.map(installedBotDetails),\n botsRemoved: new Set(value.Success.bots_removed.map(principalBytesToString)),\n apiKeysGenerated: value.Success.api_keys_generated.map(publicApiKeyDetails),\n };\n }\n else if (\"SuccessNoUpdates\" in value) {\n return {\n kind: \"success_no_updates\",\n lastUpdated: value.SuccessNoUpdates,\n };\n }\n }\n console.warn(\"Unexpected ApiSelectedUpdatesResponse type received\", value);\n return CommonResponses.failure();\n}\nexport function createUserGroupResponse(value) {\n if (typeof value === \"object\" && \"Success\" in value) {\n return {\n kind: \"success\",\n userGroupId: value.Success.user_group_id,\n };\n }\n if (value === \"NameTaken\") {\n return {\n kind: \"name_taken\",\n };\n }\n else {\n console.warn(\"CreateUserGroup failed with\", value);\n return CommonResponses.failure();\n }\n}\nexport function updateUserGroupResponse(value) {\n if (value === \"Success\") {\n return CommonResponses.success();\n }\n else if (value === \"NameTaken\") {\n return {\n kind: \"name_taken\",\n };\n }\n else {\n console.warn(\"UpdateUserGroup failed with\", value);\n return CommonResponses.failure();\n }\n}\nexport function deleteUserGroupsResponse(value) {\n if (value === \"Success\") {\n return CommonResponses.success();\n }\n else {\n console.warn(\"DeleteUserGroups failed with\", value);\n return CommonResponses.failure();\n }\n}\nexport function setMemberDisplayNameResponse(value) {\n if (typeof value === \"object\") {\n if (\"DisplayNameTooShort\" in value) {\n return \"display_name_too_short\";\n }\n if (\"DisplayNameTooLong\" in value) {\n return \"display_name_too_long\";\n }\n if (\"Error\" in value) {\n return ocError(value.Error);\n }\n }\n if (value === \"DisplayNameInvalid\") {\n return \"display_name_invalid\";\n }\n return mapCommonResponses(value, \"SetMemberDisplayName\");\n}\nexport function followThreadResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n if (value === \"AlreadyFollowing\" || value === \"NotFollowing\") {\n return \"unchanged\";\n }\n else {\n console.warn(\"followThread failed with\", value);\n return \"failed\";\n }\n}\nexport function reportMessageResponse(value) {\n return value === \"Success\" || value === \"AlreadyReported\";\n}\n","import { CommonResponses, UnsupportedValueError } from \"openchat-shared\";\nimport { bytesToHexString, identity, mapOptional, principalBytesToString, principalStringToBytes, } from \"../../utils/mapping\";\nimport { apiExternalBotPermissions, externalBotDefinition, ocError } from \"../common/chatMappersV2\";\nimport { toRecord } from \"../../utils/list\";\nimport { apiMemberRole } from \"../community/mappersV2\";\nexport function apiBotInstallLocation(domain) {\n switch (domain.kind) {\n case \"community\":\n return { Community: principalStringToBytes(domain.communityId) };\n case \"group_chat\":\n return { Group: principalStringToBytes(domain.groupId) };\n case \"direct_chat\":\n return { User: principalStringToBytes(domain.userId) };\n }\n}\nexport function botUpdatesResponse(value, current, blobUrlPattern, canisterId) {\n if (value === \"SuccessNoUpdates\") {\n return current ?? { timestamp: 0n, bots: [] };\n }\n if (\"Success\" in value) {\n const map = toRecord(current?.bots ?? [], (b) => b.id);\n value.Success.removed.forEach((d) => {\n delete map[principalBytesToString(d)];\n });\n return {\n timestamp: value.Success.timestamp,\n bots: Object.values(value.Success.added_or_updated.reduce((all, bot) => {\n const mapped = botSchema(bot, blobUrlPattern, canisterId);\n all[mapped.id] = mapped;\n return all;\n }, map)),\n };\n }\n throw new UnsupportedValueError(\"Unexpected UserIndexBotUpdatesResponse received\", value);\n}\nexport function botSchema(bot, blobUrlPattern, canisterId) {\n const botId = principalBytesToString(bot.id);\n return {\n kind: \"external_bot\",\n id: botId,\n name: bot.name,\n avatarUrl: mapOptional(bot.avatar_id, (id) => `${blobUrlPattern\n .replace(\"{canisterId}\", canisterId)\n .replace(\"{blobType}\", \"avatar\")}/${botId}/${id}`),\n ownerId: principalBytesToString(bot.owner),\n endpoint: bot.endpoint,\n definition: externalBotDefinition(bot),\n registrationStatus: botRegistrationStatus(bot.registration_status),\n };\n}\nexport function botRegistrationStatus(value) {\n if (value === \"Public\") {\n return { kind: \"public\" };\n }\n else if (\"Private\" in value) {\n return {\n kind: \"private\",\n location: mapOptional(value.Private, botInstallationLocation),\n };\n }\n throw new Error(`Unknown BotRegistrationStatus of ${value}`);\n}\nexport function botInstallationLocation(api) {\n if (\"Community\" in api) {\n return { kind: \"community\", communityId: principalBytesToString(api.Community) };\n }\n else if (\"Group\" in api) {\n return { kind: \"group_chat\", groupId: principalBytesToString(api.Group) };\n }\n throw new Error(`Unknown BotInstallationLocation of ${api}`);\n}\nexport function userSearchResponse(value) {\n if (\"Success\" in value) {\n const timestamp = value.Success.timestamp;\n return value.Success.users.map((u) => userSummary(u, timestamp));\n }\n throw new Error(`Unknown UserIndex.SearchResponse of ${value}`);\n}\nexport function usersApiResponse(value) {\n if (\"Success\" in value) {\n const timestamp = value.Success.timestamp;\n return {\n serverTimestamp: timestamp,\n users: value.Success.users.map(userSummaryUpdate),\n deletedUserIds: new Set(value.Success.deleted.map(principalBytesToString)),\n currentUser: mapOptional(value.Success.current_user, (u) => currentUserSummary(u, timestamp)),\n };\n }\n throw new Error(`Unknown UserIndex.UsersResponse of ${value}`);\n}\nexport function currentUserSummary(value, timestamp) {\n return {\n kind: \"current_user_summary\",\n username: value.username,\n isPlatformOperator: value.is_platform_operator,\n diamondStatus: diamondMembershipStatus(value.diamond_membership_status),\n userId: principalBytesToString(value.user_id),\n isBot: value.is_bot,\n displayName: mapOptional(value.display_name, identity),\n moderationFlagsEnabled: value.moderation_flags_enabled,\n isSuspectedBot: value.is_suspected_bot,\n suspensionDetails: mapOptional(value.suspension_details, suspensionDetails),\n isPlatformModerator: value.is_platform_moderator,\n diamondDetails: mapOptional(value.diamond_membership_details, diamondMembership),\n updated: timestamp,\n blobReference: mapOptional(value.avatar_id, (id) => ({\n blobId: id,\n canisterId: principalBytesToString(value.user_id),\n })),\n isUniquePerson: value.is_unique_person,\n };\n}\nexport function userSummaryUpdate(value) {\n return {\n userId: principalBytesToString(value.user_id),\n stable: mapOptional(value.stable, (s) => ({\n username: s.username,\n diamondStatus: diamondStatus(s.diamond_membership_status),\n isBot: s.is_bot,\n displayName: mapOptional(s.display_name, identity),\n blobReference: mapOptional(s.avatar_id, (id) => ({\n blobId: id,\n canisterId: principalBytesToString(value.user_id),\n })),\n suspended: s.suspended,\n isUniquePerson: s.is_unique_person,\n })),\n volatile: mapOptional(value.volatile, (v) => ({\n chitBalance: v.chit_balance,\n streak: v.streak,\n totalChitEarned: v.total_chit_earned,\n })),\n };\n}\nexport function userSummary(value, timestamp) {\n return {\n kind: value.is_bot ? \"bot\" : \"user\",\n userId: principalBytesToString(value.user_id),\n username: value.username,\n displayName: mapOptional(value.display_name, identity),\n blobReference: mapOptional(value.avatar_id, (id) => ({\n blobId: id,\n canisterId: principalBytesToString(value.user_id),\n })),\n updated: timestamp,\n suspended: value.suspended,\n diamondStatus: diamondStatus(value.diamond_membership_status),\n chitBalance: value.chit_balance,\n totalChitEarned: value.total_chit_earned,\n streak: value.streak,\n isUniquePerson: value.is_unique_person,\n };\n}\nexport function diamondStatus(value) {\n if (value === \"Inactive\") {\n return \"inactive\";\n }\n if (value === \"Active\") {\n return \"active\";\n }\n if (value === \"Lifetime\") {\n return \"lifetime\";\n }\n throw new UnsupportedValueError(\"Unexpected DiamondMembershipStatus type received\", value);\n}\nexport function userRegistrationCanisterResponse(value) {\n if (value !== \"NewRegistrationsClosed\" && \"Success\" in value) {\n return principalBytesToString(value.Success);\n }\n throw new Error(`Unexpected UserRegistrationCanisterResponse type received: ${value}`);\n}\nexport function currentUserResponse(value) {\n if (value === \"UserNotFound\") {\n return { kind: \"unknown_user\" };\n }\n if (\"Success\" in value) {\n const r = value.Success;\n console.log(\"User: \", r);\n return {\n kind: \"created_user\",\n userId: principalBytesToString(r.user_id),\n username: r.username,\n dateCreated: r.date_created,\n displayName: r.display_name ?? undefined,\n cryptoAccount: bytesToHexString(r.icp_account),\n isPlatformModerator: r.is_platform_moderator,\n isPlatformOperator: r.is_platform_operator,\n suspensionDetails: mapOptional(r.suspension_details, suspensionDetails),\n isSuspectedBot: r.is_suspected_bot,\n diamondStatus: diamondMembershipStatus(r.diamond_membership_status),\n moderationFlagsEnabled: r.moderation_flags_enabled,\n isBot: false,\n updated: BigInt(Date.now()),\n isUniquePerson: value.Success.is_unique_person,\n };\n }\n throw new Error(`Unexpected CurrentUserResponse type received: ${value}`);\n}\nfunction diamondMembershipStatus(value) {\n if (value === \"Inactive\") {\n return { kind: \"inactive\" };\n }\n if (value === \"Lifetime\") {\n return { kind: \"lifetime\" };\n }\n if (\"Active\" in value) {\n return {\n kind: \"active\",\n ...diamondMembership(value.Active),\n };\n }\n throw new UnsupportedValueError(\"Unexpected DiamondMembershipStatusFullJson type received\", value);\n}\nfunction diamondMembership(value) {\n return {\n expiresAt: value.expires_at,\n subscription: diamondMembershipSubscription(value.subscription),\n payInChat: value.pay_in_chat,\n };\n}\nfunction diamondMembershipSubscription(value) {\n if (value === \"OneMonth\") {\n return \"one_month\";\n }\n if (value === \"ThreeMonths\") {\n return \"three_months\";\n }\n if (value === \"OneYear\") {\n return \"one_year\";\n }\n if (value === \"Disabled\") {\n return \"disabled\";\n }\n throw new UnsupportedValueError(\"Unexpected DiamondMembershipSubscriptionJson type received\", value);\n}\nfunction suspensionDetails(value) {\n return {\n reason: value.reason,\n action: suspensionAction(value.action),\n suspendedBy: principalBytesToString(value.suspended_by),\n };\n}\nfunction suspensionAction(value) {\n if (\"Unsuspend\" in value) {\n return {\n kind: \"unsuspend_action\",\n timestamp: value.Unsuspend,\n };\n }\n else if (\"Delete\" in value) {\n return {\n kind: \"delete_action\",\n timestamp: value.Delete,\n };\n }\n throw new Error(`Unexpected SuspensionAction type received: ${value}`);\n}\nexport function checkUsernameResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n if (value === \"UsernameTaken\") {\n return \"username_taken\";\n }\n if (value === \"UsernameInvalid\") {\n return \"username_invalid\";\n }\n if (\"UsernameTooShort\" in value) {\n return \"username_too_short\";\n }\n if (\"UsernameTooLong\" in value) {\n return \"username_too_long\";\n }\n if (\"Error\" in value) {\n return ocError(value.Error);\n }\n throw new UnsupportedValueError(\"Unexpected CheckUsernameResponse type received\", value);\n}\nexport function setUsernameResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n if (value === \"UsernameTaken\") {\n return \"username_taken\";\n }\n if (value === \"UserNotFound\") {\n return \"user_not_found\";\n }\n if (value === \"UsernameInvalid\") {\n return \"username_invalid\";\n }\n if (\"UsernameTooShort\" in value) {\n return \"username_too_short\";\n }\n if (\"UsernameTooLong\" in value) {\n return \"username_too_long\";\n }\n if (\"Error\" in value) {\n return ocError(value.Error);\n }\n throw new UnsupportedValueError(\"Unexpected SetUsernameResponse type received\", value);\n}\nexport function setDisplayNameResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n if (value === \"UserNotFound\") {\n return \"user_not_found\";\n }\n if (value === \"DisplayNameInvalid\") {\n return \"display_name_invalid\";\n }\n if (\"DisplayNameTooShort\" in value) {\n return \"display_name_too_short\";\n }\n if (\"DisplayNameTooLong\" in value) {\n return \"display_name_too_long\";\n }\n if (\"Error\" in value) {\n return ocError(value.Error);\n }\n throw new UnsupportedValueError(\"Unexpected SetDisplayNameResponse type received\", value);\n}\nexport function suspendUserResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n if (value === \"UserAlreadySuspended\") {\n return \"user_already_suspended\";\n }\n if (value === \"UserNotFound\") {\n return \"user_not_found\";\n }\n if (\"InternalError\" in value || \"Error\" in value) {\n return \"internal_error\";\n }\n throw new UnsupportedValueError(\"Unexpected SuspendUserResponse type received\", value);\n}\nexport function unsuspendUserResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n if (value === \"UserNotFound\") {\n return \"user_not_found\";\n }\n if (value === \"UserNotSuspended\") {\n return \"user_not_suspended\";\n }\n if (\"InternalError\" in value || \"Error\" in value) {\n return \"internal_error\";\n }\n throw new UnsupportedValueError(\"Unexpected UnsuspendUserResponse type received\", value);\n}\nexport function payForDiamondMembershipResponse(duration, value) {\n if (value === \"PaymentAlreadyInProgress\") {\n return { kind: \"payment_already_in_progress\" };\n }\n if (value === \"CurrencyNotSupported\") {\n return { kind: \"currency_not_supported\" };\n }\n if (value === \"UserNotFound\") {\n return { kind: \"user_not_found\" };\n }\n if (value === \"PriceMismatch\") {\n return { kind: \"price_mismatch\" };\n }\n if (value === \"AlreadyLifetimeDiamondMember\") {\n return { kind: \"already_lifetime_diamond_member\" };\n }\n if (\"Success\" in value) {\n return {\n kind: \"success\",\n proof: value.Success.proof_jwt,\n status: duration === \"lifetime\"\n ? { kind: \"lifetime\" }\n : { kind: \"active\", ...diamondMembership(value.Success) },\n };\n }\n if (\"TransferFailed\" in value) {\n return { kind: \"transfer_failed\" };\n }\n if (\"InternalError\" in value) {\n return { kind: \"internal_error\" };\n }\n if (\"InsufficientFunds\" in value) {\n return { kind: \"insufficient_funds\" };\n }\n if (\"Error\" in value) {\n return ocError(value.Error);\n }\n throw new UnsupportedValueError(\"Unexpected ApiPayForDiamondMembershipResponse type received\", value);\n}\nexport function apiJsonDiamondDuration(domain) {\n if (domain === \"one_month\") {\n return \"OneMonth\";\n }\n if (domain === \"three_months\") {\n return \"ThreeMonths\";\n }\n if (domain === \"one_year\") {\n return \"OneYear\";\n }\n if (domain === \"lifetime\") {\n return \"Lifetime\";\n }\n throw new UnsupportedValueError(\"Unexpected DiamondMembershipDuration type received\", domain);\n}\nexport function diamondMembershipFeesResponse(value) {\n if (\"Success\" in value) {\n return value.Success.map((f) => ({\n token: f.token_symbol,\n oneMonth: f.one_month,\n threeMonths: f.three_months,\n oneYear: f.one_year,\n lifetime: f.lifetime,\n }));\n }\n throw new UnsupportedValueError(\"Unexpected DiamondMembershipFeesResponse type received\", value);\n}\nexport function chitLeaderboardResponse(value) {\n if (\"SuccessV2\" in value) {\n return {\n allTime: value.SuccessV2.all_time.map(chitUserBalance),\n lastMonth: value.SuccessV2.last_month.map(chitUserBalance),\n thisMonth: value.SuccessV2.this_month.map(chitUserBalance),\n };\n }\n throw new UnsupportedValueError(\"Unexpected ChitLeaderboardResponse type received\", value);\n}\nfunction chitUserBalance(value) {\n return {\n userId: principalBytesToString(value.user_id),\n balance: value.balance,\n username: value.username,\n };\n}\nexport function submitProofOfUniquePersonhoodResponse(value) {\n if (value === \"Success\") {\n return CommonResponses.success();\n }\n if (value === \"UserNotFound\") {\n return CommonResponses.userNotFound();\n }\n if (\"Invalid\" in value) {\n return CommonResponses.invalid();\n }\n if (\"Error\" in value) {\n return ocError(value.Error);\n }\n throw new UnsupportedValueError(\"Unexpected SubmitProofOfUniquePersonhoodResponse type received\", value);\n}\nexport function externalAchievementsResponse(value) {\n if (value === \"SuccessNoUpdates\") {\n return { kind: \"success_no_updates\" };\n }\n if (\"Success\" in value) {\n return {\n kind: \"success\",\n addedOrUpdated: value.Success.added_or_updated.map(externalAchievement),\n lastUpdated: value.Success.last_updated,\n };\n }\n throw new UnsupportedValueError(\"Unexpected ExternalAchievementsResponse type received\", value);\n}\nfunction externalAchievement(value) {\n return {\n id: value.id,\n url: value.url,\n name: value.name,\n chitReward: value.chit_reward,\n expires: value.expires,\n budgetExhausted: value.budget_exhausted,\n };\n}\nexport function apiCustomParamFields(param) {\n switch (param.kind) {\n case \"user\":\n return \"UserParam\";\n case \"boolean\":\n return \"BooleanParam\";\n case \"integer\":\n return {\n IntegerParam: {\n min_value: param.minValue,\n max_value: param.maxValue,\n choices: param.choices.map((c) => ({\n name: c.name,\n value: c.value,\n })),\n },\n };\n case \"decimal\":\n return {\n DecimalParam: {\n min_value: param.minValue,\n max_value: param.maxValue,\n choices: param.choices,\n },\n };\n case \"string\":\n return {\n StringParam: {\n min_length: param.minLength,\n max_length: param.maxLength,\n choices: param.choices,\n multi_line: param.multi_line,\n },\n };\n case \"dateTime\":\n return {\n DateTimeParam: {\n future_only: param.future_only,\n },\n };\n }\n}\nexport function apiExternalBotParam(param) {\n return {\n ...param,\n param_type: apiCustomParamFields(param),\n };\n}\nexport function apiBotDefinition(domain) {\n return {\n description: domain.description ?? \"\",\n commands: domain.commands.map(apiExternalBotCommand),\n autonomous_config: mapOptional(domain.autonomousConfig, apiAutonomousConfig),\n };\n}\nexport function apiAutonomousConfig(domain) {\n return {\n sync_api_key: domain.syncApiKey,\n permissions: apiExternalBotPermissions(domain.permissions),\n };\n}\nexport function apiExternalBotCommand(command) {\n return {\n name: command.name,\n description: command.description,\n placeholder: command.placeholder,\n params: command.params.map(apiExternalBotParam),\n default_role: apiMemberRole(command.defaultRole),\n permissions: apiExternalBotPermissions(command.permissions),\n direct_messages: command.directMessages,\n };\n}\nexport function externalBotMatch(match, blobUrlPattern, canisterId) {\n const botId = principalBytesToString(match.id);\n return {\n kind: \"bot_match\",\n name: match.name,\n avatarUrl: mapOptional(match.avatar_id, (id) => `${blobUrlPattern\n .replace(\"{canisterId}\", canisterId)\n .replace(\"{blobType}\", \"avatar\")}/${botId}/${id}`),\n id: botId,\n ownerId: principalBytesToString(match.owner),\n definition: externalBotDefinition(match),\n endpoint: match.endpoint,\n };\n}\nexport function exploreBotsResponse(value, blobUrlPattern, canisterId) {\n if (value === \"InvalidTerm\") {\n return { kind: \"term_invalid\" };\n }\n if (\"TermTooLong\" in value) {\n return { kind: \"term_invalid\" };\n }\n if (\"TermTooShort\" in value) {\n return { kind: \"term_invalid\" };\n }\n if (\"Success\" in value) {\n return {\n kind: \"success\",\n matches: value.Success.matches.map((m) => externalBotMatch(m, blobUrlPattern, canisterId)),\n total: value.Success.total,\n };\n }\n if (\"Error\" in value) {\n return ocError(value.Error);\n }\n throw new UnsupportedValueError(\"Unexpected ExploreBotsResponse type received\", value);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Computed } from '../computed/index.mjs';\nimport { Intersect } from '../intersect/index.mjs';\nimport { Union } from '../union/index.mjs';\nimport { Ref } from '../ref/index.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsIntersect, IsUnion, IsPromise, IsRef, IsComputed } from '../guard/kind.mjs';\n// prettier-ignore\nfunction FromComputed(target, parameters) {\n return Computed('Awaited', [Computed(target, parameters)]);\n}\n// prettier-ignore\nfunction FromRef($ref) {\n return Computed('Awaited', [Ref($ref)]);\n}\n// prettier-ignore\nfunction FromIntersect(types) {\n return Intersect(FromRest(types));\n}\n// prettier-ignore\nfunction FromUnion(types) {\n return Union(FromRest(types));\n}\n// prettier-ignore\nfunction FromPromise(type) {\n return Awaited(type);\n}\n// prettier-ignore\nfunction FromRest(types) {\n return types.map(type => Awaited(type));\n}\n/** `[JavaScript]` Constructs a type by recursively unwrapping Promise types */\nexport function Awaited(type, options) {\n return CreateType(IsComputed(type) ? FromComputed(type.target, type.parameters) : IsIntersect(type) ? FromIntersect(type.allOf) : IsUnion(type) ? FromUnion(type.anyOf) : IsPromise(type) ? FromPromise(type.item) : IsRef(type) ? FromRef(type.$ref) : type, options);\n}\n","import { IntersectEvaluated } from '../intersect/index.mjs';\nimport { IndexFromPropertyKeys } from '../indexed/index.mjs';\nimport { KeyOfPropertyKeys } from '../keyof/index.mjs';\nimport { Object } from '../object/index.mjs';\nimport { SetDistinct } from '../sets/index.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsNever } from '../guard/kind.mjs';\n// prettier-ignore\nfunction CompositeKeys(T) {\n const Acc = [];\n for (const L of T)\n Acc.push(...KeyOfPropertyKeys(L));\n return SetDistinct(Acc);\n}\n// prettier-ignore\nfunction FilterNever(T) {\n return T.filter(L => !IsNever(L));\n}\n// prettier-ignore\nfunction CompositeProperty(T, K) {\n const Acc = [];\n for (const L of T)\n Acc.push(...IndexFromPropertyKeys(L, [K]));\n return FilterNever(Acc);\n}\n// prettier-ignore\nfunction CompositeProperties(T, K) {\n const Acc = {};\n for (const L of K) {\n Acc[L] = IntersectEvaluated(CompositeProperty(T, L));\n }\n return Acc;\n}\n// prettier-ignore\nexport function Composite(T, options) {\n const K = CompositeKeys(T);\n const P = CompositeProperties(T, K);\n const R = Object(P, options);\n return R;\n}\n","import { Kind } from '../symbols/index.mjs';\nimport { CreateType } from '../create/type.mjs';\n/** `[JavaScript]` Creates a Date type */\nexport function Date(options) {\n return CreateType({ [Kind]: 'Date', type: 'Date' }, options);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates a Null type */\nexport function Null(options) {\n return CreateType({ [Kind]: 'Null', type: 'null' }, options);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[JavaScript]` Creates a Symbol type */\nexport function Symbol(options) {\n return CreateType({ [Kind]: 'Symbol', type: 'symbol' }, options);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[JavaScript]` Creates a Undefined type */\nexport function Undefined(options) {\n return CreateType({ [Kind]: 'Undefined', type: 'undefined' }, options);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[JavaScript]` Creates a Uint8Array type */\nexport function Uint8Array(options) {\n return CreateType({ [Kind]: 'Uint8Array', type: 'Uint8Array' }, options);\n}\n","import { Any } from '../any/index.mjs';\nimport { BigInt } from '../bigint/index.mjs';\nimport { Date } from '../date/index.mjs';\nimport { Function as FunctionType } from '../function/index.mjs';\nimport { Literal } from '../literal/index.mjs';\nimport { Null } from '../null/index.mjs';\nimport { Object } from '../object/index.mjs';\nimport { Symbol } from '../symbol/index.mjs';\nimport { Tuple } from '../tuple/index.mjs';\nimport { Readonly } from '../readonly/index.mjs';\nimport { Undefined } from '../undefined/index.mjs';\nimport { Uint8Array } from '../uint8array/index.mjs';\nimport { Unknown } from '../unknown/index.mjs';\nimport { CreateType } from '../create/index.mjs';\n// ------------------------------------------------------------------\n// ValueGuard\n// ------------------------------------------------------------------\nimport { IsArray, IsNumber, IsBigInt, IsUint8Array, IsDate, IsIterator, IsObject, IsAsyncIterator, IsFunction, IsUndefined, IsNull, IsSymbol, IsBoolean, IsString } from '../guard/value.mjs';\n// prettier-ignore\nfunction FromArray(T) {\n return T.map(L => FromValue(L, false));\n}\n// prettier-ignore\nfunction FromProperties(value) {\n const Acc = {};\n for (const K of globalThis.Object.getOwnPropertyNames(value))\n Acc[K] = Readonly(FromValue(value[K], false));\n return Acc;\n}\nfunction ConditionalReadonly(T, root) {\n return (root === true ? T : Readonly(T));\n}\n// prettier-ignore\nfunction FromValue(value, root) {\n return (IsAsyncIterator(value) ? ConditionalReadonly(Any(), root) :\n IsIterator(value) ? ConditionalReadonly(Any(), root) :\n IsArray(value) ? Readonly(Tuple(FromArray(value))) :\n IsUint8Array(value) ? Uint8Array() :\n IsDate(value) ? Date() :\n IsObject(value) ? ConditionalReadonly(Object(FromProperties(value)), root) :\n IsFunction(value) ? ConditionalReadonly(FunctionType([], Unknown()), root) :\n IsUndefined(value) ? Undefined() :\n IsNull(value) ? Null() :\n IsSymbol(value) ? Symbol() :\n IsBigInt(value) ? BigInt() :\n IsNumber(value) ? Literal(value) :\n IsBoolean(value) ? Literal(value) :\n IsString(value) ? Literal(value) :\n Object({}));\n}\n/** `[JavaScript]` Creates a readonly const type from the given value. */\nexport function Const(T, options) {\n return CreateType(FromValue(T, true), options);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Union } from '../union/index.mjs';\nimport { Never } from '../never/index.mjs';\nimport { ExtendsCheck, ExtendsResult } from '../extends/index.mjs';\nimport { ExcludeFromMappedResult } from './exclude-from-mapped-result.mjs';\nimport { ExcludeFromTemplateLiteral } from './exclude-from-template-literal.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsMappedResult, IsTemplateLiteral, IsUnion } from '../guard/kind.mjs';\nfunction ExcludeRest(L, R) {\n const excluded = L.filter((inner) => ExtendsCheck(inner, R) === ExtendsResult.False);\n return excluded.length === 1 ? excluded[0] : Union(excluded);\n}\n/** `[Json]` Constructs a type by excluding from unionType all union members that are assignable to excludedMembers */\nexport function Exclude(L, R, options = {}) {\n // overloads\n if (IsTemplateLiteral(L))\n return CreateType(ExcludeFromTemplateLiteral(L, R), options);\n if (IsMappedResult(L))\n return CreateType(ExcludeFromMappedResult(L, R), options);\n // prettier-ignore\n return CreateType(IsUnion(L) ? ExcludeRest(L.anyOf, R) :\n ExtendsCheck(L, R) !== ExtendsResult.False ? Never() : L, options);\n}\n","import { Exclude } from './exclude.mjs';\nimport { TemplateLiteralToUnion } from '../template-literal/index.mjs';\nexport function ExcludeFromTemplateLiteral(L, R) {\n return Exclude(TemplateLiteralToUnion(L), R);\n}\n","import { MappedResult } from '../mapped/index.mjs';\nimport { Exclude } from './exclude.mjs';\n// prettier-ignore\nfunction FromProperties(P, U) {\n const Acc = {};\n for (const K2 of globalThis.Object.getOwnPropertyNames(P))\n Acc[K2] = Exclude(P[K2], U);\n return Acc;\n}\n// prettier-ignore\nfunction FromMappedResult(R, T) {\n return FromProperties(R.properties, T);\n}\n// prettier-ignore\nexport function ExcludeFromMappedResult(R, T) {\n const P = FromMappedResult(R, T);\n return MappedResult(P);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Union } from '../union/index.mjs';\nimport { Never } from '../never/index.mjs';\nimport { ExtendsCheck, ExtendsResult } from '../extends/index.mjs';\nimport { ExtractFromMappedResult } from './extract-from-mapped-result.mjs';\nimport { ExtractFromTemplateLiteral } from './extract-from-template-literal.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsMappedResult, IsTemplateLiteral, IsUnion } from '../guard/kind.mjs';\nfunction ExtractRest(L, R) {\n const extracted = L.filter((inner) => ExtendsCheck(inner, R) !== ExtendsResult.False);\n return extracted.length === 1 ? extracted[0] : Union(extracted);\n}\n/** `[Json]` Constructs a type by extracting from type all union members that are assignable to union */\nexport function Extract(L, R, options) {\n // overloads\n if (IsTemplateLiteral(L))\n return CreateType(ExtractFromTemplateLiteral(L, R), options);\n if (IsMappedResult(L))\n return CreateType(ExtractFromMappedResult(L, R), options);\n // prettier-ignore\n return CreateType(IsUnion(L) ? ExtractRest(L.anyOf, R) :\n ExtendsCheck(L, R) !== ExtendsResult.False ? L : Never(), options);\n}\n","import { Extract } from './extract.mjs';\nimport { TemplateLiteralToUnion } from '../template-literal/index.mjs';\nexport function ExtractFromTemplateLiteral(L, R) {\n return Extract(TemplateLiteralToUnion(L), R);\n}\n","import { MappedResult } from '../mapped/index.mjs';\nimport { Extract } from './extract.mjs';\n// prettier-ignore\nfunction FromProperties(P, T) {\n const Acc = {};\n for (const K2 of globalThis.Object.getOwnPropertyNames(P))\n Acc[K2] = Extract(P[K2], T);\n return Acc;\n}\n// prettier-ignore\nfunction FromMappedResult(R, T) {\n return FromProperties(R.properties, T);\n}\n// prettier-ignore\nexport function ExtractFromMappedResult(R, T) {\n const P = FromMappedResult(R, T);\n return MappedResult(P);\n}\n","import { MappedResult } from '../mapped/index.mjs';\nimport { Intrinsic } from './intrinsic.mjs';\nimport { Literal } from '../literal/index.mjs';\nimport { Clone } from '../clone/value.mjs';\n// prettier-ignore\nfunction MappedIntrinsicPropertyKey(K, M, options) {\n return {\n [K]: Intrinsic(Literal(K), M, Clone(options))\n };\n}\n// prettier-ignore\nfunction MappedIntrinsicPropertyKeys(K, M, options) {\n const result = K.reduce((Acc, L) => {\n return { ...Acc, ...MappedIntrinsicPropertyKey(L, M, options) };\n }, {});\n return result;\n}\n// prettier-ignore\nfunction MappedIntrinsicProperties(T, M, options) {\n return MappedIntrinsicPropertyKeys(T['keys'], M, options);\n}\n// prettier-ignore\nexport function IntrinsicFromMappedKey(T, M, options) {\n const P = MappedIntrinsicProperties(T, M, options);\n return MappedResult(P);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { TemplateLiteral, TemplateLiteralParseExact, IsTemplateLiteralExpressionFinite, TemplateLiteralExpressionGenerate } from '../template-literal/index.mjs';\nimport { IntrinsicFromMappedKey } from './intrinsic-from-mapped-key.mjs';\nimport { Literal } from '../literal/index.mjs';\nimport { Union } from '../union/index.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsMappedKey, IsTemplateLiteral, IsUnion, IsLiteral } from '../guard/kind.mjs';\n// ------------------------------------------------------------------\n// Apply\n// ------------------------------------------------------------------\nfunction ApplyUncapitalize(value) {\n const [first, rest] = [value.slice(0, 1), value.slice(1)];\n return [first.toLowerCase(), rest].join('');\n}\nfunction ApplyCapitalize(value) {\n const [first, rest] = [value.slice(0, 1), value.slice(1)];\n return [first.toUpperCase(), rest].join('');\n}\nfunction ApplyUppercase(value) {\n return value.toUpperCase();\n}\nfunction ApplyLowercase(value) {\n return value.toLowerCase();\n}\nfunction FromTemplateLiteral(schema, mode, options) {\n // note: template literals require special runtime handling as they are encoded in string patterns.\n // This diverges from the mapped type which would otherwise map on the template literal kind.\n const expression = TemplateLiteralParseExact(schema.pattern);\n const finite = IsTemplateLiteralExpressionFinite(expression);\n if (!finite)\n return { ...schema, pattern: FromLiteralValue(schema.pattern, mode) };\n const strings = [...TemplateLiteralExpressionGenerate(expression)];\n const literals = strings.map((value) => Literal(value));\n const mapped = FromRest(literals, mode);\n const union = Union(mapped);\n return TemplateLiteral([union], options);\n}\n// prettier-ignore\nfunction FromLiteralValue(value, mode) {\n return (typeof value === 'string' ? (mode === 'Uncapitalize' ? ApplyUncapitalize(value) :\n mode === 'Capitalize' ? ApplyCapitalize(value) :\n mode === 'Uppercase' ? ApplyUppercase(value) :\n mode === 'Lowercase' ? ApplyLowercase(value) :\n value) : value.toString());\n}\n// prettier-ignore\nfunction FromRest(T, M) {\n return T.map(L => Intrinsic(L, M));\n}\n/** Applies an intrinsic string manipulation to the given type. */\nexport function Intrinsic(schema, mode, options = {}) {\n // prettier-ignore\n return (\n // Intrinsic-Mapped-Inference\n IsMappedKey(schema) ? IntrinsicFromMappedKey(schema, mode, options) :\n // Standard-Inference\n IsTemplateLiteral(schema) ? FromTemplateLiteral(schema, mode, options) :\n IsUnion(schema) ? Union(FromRest(schema.anyOf, mode), options) :\n IsLiteral(schema) ? Literal(FromLiteralValue(schema.const, mode), options) :\n // Default Type\n CreateType(schema, options));\n}\n","import { MappedResult } from '../mapped/index.mjs';\nimport { Omit } from './omit.mjs';\nimport { Clone } from '../clone/value.mjs';\n// prettier-ignore\nfunction FromProperties(properties, propertyKeys, options) {\n const result = {};\n for (const K2 of globalThis.Object.getOwnPropertyNames(properties))\n result[K2] = Omit(properties[K2], propertyKeys, Clone(options));\n return result;\n}\n// prettier-ignore\nfunction FromMappedResult(mappedResult, propertyKeys, options) {\n return FromProperties(mappedResult.properties, propertyKeys, options);\n}\n// prettier-ignore\nexport function OmitFromMappedResult(mappedResult, propertyKeys, options) {\n const properties = FromMappedResult(mappedResult, propertyKeys, options);\n return MappedResult(properties);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Discard } from '../discard/discard.mjs';\nimport { TransformKind } from '../symbols/symbols.mjs';\nimport { Computed } from '../computed/index.mjs';\nimport { Literal } from '../literal/index.mjs';\nimport { IndexPropertyKeys } from '../indexed/index.mjs';\nimport { Intersect } from '../intersect/index.mjs';\nimport { Union } from '../union/index.mjs';\nimport { Object } from '../object/index.mjs';\n// ------------------------------------------------------------------\n// Mapped\n// ------------------------------------------------------------------\nimport { OmitFromMappedKey } from './omit-from-mapped-key.mjs';\nimport { OmitFromMappedResult } from './omit-from-mapped-result.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsMappedKey, IsIntersect, IsUnion, IsObject, IsSchema, IsMappedResult, IsLiteralValue, IsRef } from '../guard/kind.mjs';\nimport { IsArray as IsArrayValue } from '../guard/value.mjs';\n// prettier-ignore\nfunction FromIntersect(types, propertyKeys) {\n return types.map((type) => OmitResolve(type, propertyKeys));\n}\n// prettier-ignore\nfunction FromUnion(types, propertyKeys) {\n return types.map((type) => OmitResolve(type, propertyKeys));\n}\n// ------------------------------------------------------------------\n// FromProperty\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction FromProperty(properties, key) {\n const { [key]: _, ...R } = properties;\n return R;\n}\n// prettier-ignore\nfunction FromProperties(properties, propertyKeys) {\n return propertyKeys.reduce((T, K2) => FromProperty(T, K2), properties);\n}\n// prettier-ignore\nfunction FromObject(properties, propertyKeys) {\n const options = Discard(properties, [TransformKind, '$id', 'required', 'properties']);\n const omittedProperties = FromProperties(properties['properties'], propertyKeys);\n return Object(omittedProperties, options);\n}\n// prettier-ignore\nfunction UnionFromPropertyKeys(propertyKeys) {\n const result = propertyKeys.reduce((result, key) => IsLiteralValue(key) ? [...result, Literal(key)] : result, []);\n return Union(result);\n}\n// prettier-ignore\nfunction OmitResolve(properties, propertyKeys) {\n return (IsIntersect(properties) ? Intersect(FromIntersect(properties.allOf, propertyKeys)) :\n IsUnion(properties) ? Union(FromUnion(properties.anyOf, propertyKeys)) :\n IsObject(properties) ? FromObject(properties, propertyKeys) :\n Object({}));\n}\n/** `[Json]` Constructs a type whose keys are picked from the given type */\n// prettier-ignore\nexport function Omit(type, key, options) {\n const typeKey = IsArrayValue(key) ? UnionFromPropertyKeys(key) : key;\n const propertyKeys = IsSchema(key) ? IndexPropertyKeys(key) : key;\n const isTypeRef = IsRef(type);\n const isKeyRef = IsRef(key);\n return (IsMappedResult(type) ? OmitFromMappedResult(type, propertyKeys, options) :\n IsMappedKey(key) ? OmitFromMappedKey(type, key, options) :\n (isTypeRef && isKeyRef) ? Computed('Omit', [type, typeKey], options) :\n (!isTypeRef && isKeyRef) ? Computed('Omit', [type, typeKey], options) :\n (isTypeRef && !isKeyRef) ? Computed('Omit', [type, typeKey], options) :\n CreateType({ ...OmitResolve(type, propertyKeys), ...options }));\n}\n","import { MappedResult } from '../mapped/index.mjs';\nimport { Omit } from './omit.mjs';\nimport { Clone } from '../clone/value.mjs';\n// prettier-ignore\nfunction FromPropertyKey(type, key, options) {\n return { [key]: Omit(type, [key], Clone(options)) };\n}\n// prettier-ignore\nfunction FromPropertyKeys(type, propertyKeys, options) {\n return propertyKeys.reduce((Acc, LK) => {\n return { ...Acc, ...FromPropertyKey(type, LK, options) };\n }, {});\n}\n// prettier-ignore\nfunction FromMappedKey(type, mappedKey, options) {\n return FromPropertyKeys(type, mappedKey.keys, options);\n}\n// prettier-ignore\nexport function OmitFromMappedKey(type, mappedKey, options) {\n const properties = FromMappedKey(type, mappedKey, options);\n return MappedResult(properties);\n}\n","import { MappedResult } from '../mapped/index.mjs';\nimport { Pick } from './pick.mjs';\nimport { Clone } from '../clone/value.mjs';\n// prettier-ignore\nfunction FromProperties(properties, propertyKeys, options) {\n const result = {};\n for (const K2 of globalThis.Object.getOwnPropertyNames(properties))\n result[K2] = Pick(properties[K2], propertyKeys, Clone(options));\n return result;\n}\n// prettier-ignore\nfunction FromMappedResult(mappedResult, propertyKeys, options) {\n return FromProperties(mappedResult.properties, propertyKeys, options);\n}\n// prettier-ignore\nexport function PickFromMappedResult(mappedResult, propertyKeys, options) {\n const properties = FromMappedResult(mappedResult, propertyKeys, options);\n return MappedResult(properties);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Discard } from '../discard/discard.mjs';\nimport { Computed } from '../computed/index.mjs';\nimport { Intersect } from '../intersect/index.mjs';\nimport { Literal } from '../literal/index.mjs';\nimport { Object } from '../object/index.mjs';\nimport { Union } from '../union/index.mjs';\nimport { IndexPropertyKeys } from '../indexed/index.mjs';\nimport { TransformKind } from '../symbols/symbols.mjs';\n// ------------------------------------------------------------------\n// Guards\n// ------------------------------------------------------------------\nimport { IsMappedKey, IsMappedResult, IsIntersect, IsUnion, IsObject, IsSchema, IsLiteralValue, IsRef } from '../guard/kind.mjs';\nimport { IsArray as IsArrayValue } from '../guard/value.mjs';\n// ------------------------------------------------------------------\n// Infrastructure\n// ------------------------------------------------------------------\nimport { PickFromMappedKey } from './pick-from-mapped-key.mjs';\nimport { PickFromMappedResult } from './pick-from-mapped-result.mjs';\nfunction FromIntersect(types, propertyKeys) {\n return types.map((type) => PickResolve(type, propertyKeys));\n}\n// prettier-ignore\nfunction FromUnion(types, propertyKeys) {\n return types.map((type) => PickResolve(type, propertyKeys));\n}\n// prettier-ignore\nfunction FromProperties(properties, propertyKeys) {\n const result = {};\n for (const K2 of propertyKeys)\n if (K2 in properties)\n result[K2] = properties[K2];\n return result;\n}\n// prettier-ignore\nfunction FromObject(T, K) {\n const options = Discard(T, [TransformKind, '$id', 'required', 'properties']);\n const properties = FromProperties(T['properties'], K);\n return Object(properties, options);\n}\n// prettier-ignore\nfunction UnionFromPropertyKeys(propertyKeys) {\n const result = propertyKeys.reduce((result, key) => IsLiteralValue(key) ? [...result, Literal(key)] : result, []);\n return Union(result);\n}\n// prettier-ignore\nfunction PickResolve(properties, propertyKeys) {\n return (IsIntersect(properties) ? Intersect(FromIntersect(properties.allOf, propertyKeys)) :\n IsUnion(properties) ? Union(FromUnion(properties.anyOf, propertyKeys)) :\n IsObject(properties) ? FromObject(properties, propertyKeys) :\n Object({}));\n}\n/** `[Json]` Constructs a type whose keys are picked from the given type */\n// prettier-ignore\nexport function Pick(type, key, options) {\n const typeKey = IsArrayValue(key) ? UnionFromPropertyKeys(key) : key;\n const propertyKeys = IsSchema(key) ? IndexPropertyKeys(key) : key;\n const isTypeRef = IsRef(type);\n const isKeyRef = IsRef(key);\n return (IsMappedResult(type) ? PickFromMappedResult(type, propertyKeys, options) :\n IsMappedKey(key) ? PickFromMappedKey(type, key, options) :\n (isTypeRef && isKeyRef) ? Computed('Pick', [type, typeKey], options) :\n (!isTypeRef && isKeyRef) ? Computed('Pick', [type, typeKey], options) :\n (isTypeRef && !isKeyRef) ? Computed('Pick', [type, typeKey], options) :\n CreateType({ ...PickResolve(type, propertyKeys), ...options }));\n}\n","import { MappedResult } from '../mapped/index.mjs';\nimport { Pick } from './pick.mjs';\nimport { Clone } from '../clone/value.mjs';\n// prettier-ignore\nfunction FromPropertyKey(type, key, options) {\n return {\n [key]: Pick(type, [key], Clone(options))\n };\n}\n// prettier-ignore\nfunction FromPropertyKeys(type, propertyKeys, options) {\n return propertyKeys.reduce((result, leftKey) => {\n return { ...result, ...FromPropertyKey(type, leftKey, options) };\n }, {});\n}\n// prettier-ignore\nfunction FromMappedKey(type, mappedKey, options) {\n return FromPropertyKeys(type, mappedKey.keys, options);\n}\n// prettier-ignore\nexport function PickFromMappedKey(type, mappedKey, options) {\n const properties = FromMappedKey(type, mappedKey, options);\n return MappedResult(properties);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Computed } from '../computed/index.mjs';\nimport { Optional } from '../optional/index.mjs';\nimport { Object } from '../object/index.mjs';\nimport { Intersect } from '../intersect/index.mjs';\nimport { Union } from '../union/index.mjs';\nimport { Ref } from '../ref/index.mjs';\nimport { Discard } from '../discard/index.mjs';\nimport { TransformKind } from '../symbols/index.mjs';\nimport { PartialFromMappedResult } from './partial-from-mapped-result.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsMappedResult, IsIntersect, IsUnion, IsObject, IsRef, IsComputed } from '../guard/kind.mjs';\n// prettier-ignore\nfunction FromComputed(target, parameters) {\n return Computed('Partial', [Computed(target, parameters)]);\n}\n// prettier-ignore\nfunction FromRef($ref) {\n return Computed('Partial', [Ref($ref)]);\n}\n// prettier-ignore\nfunction FromProperties(properties) {\n const partialProperties = {};\n for (const K of globalThis.Object.getOwnPropertyNames(properties))\n partialProperties[K] = Optional(properties[K]);\n return partialProperties;\n}\n// prettier-ignore\nfunction FromObject(T) {\n const options = Discard(T, [TransformKind, '$id', 'required', 'properties']);\n const properties = FromProperties(T['properties']);\n return Object(properties, options);\n}\n// prettier-ignore\nfunction FromRest(types) {\n return types.map(type => PartialResolve(type));\n}\n// ------------------------------------------------------------------\n// PartialResolve\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction PartialResolve(type) {\n return (IsComputed(type) ? FromComputed(type.target, type.parameters) :\n IsRef(type) ? FromRef(type.$ref) :\n IsIntersect(type) ? Intersect(FromRest(type.allOf)) :\n IsUnion(type) ? Union(FromRest(type.anyOf)) :\n IsObject(type) ? FromObject(type) :\n Object({}));\n}\n/** `[Json]` Constructs a type where all properties are optional */\nexport function Partial(type, options) {\n if (IsMappedResult(type)) {\n return PartialFromMappedResult(type, options);\n }\n else {\n // special: mapping types require overridable options\n return CreateType({ ...PartialResolve(type), ...options });\n }\n}\n","import { MappedResult } from '../mapped/index.mjs';\nimport { Partial } from './partial.mjs';\nimport { Clone } from '../clone/value.mjs';\n// prettier-ignore\nfunction FromProperties(K, options) {\n const Acc = {};\n for (const K2 of globalThis.Object.getOwnPropertyNames(K))\n Acc[K2] = Partial(K[K2], Clone(options));\n return Acc;\n}\n// prettier-ignore\nfunction FromMappedResult(R, options) {\n return FromProperties(R.properties, options);\n}\n// prettier-ignore\nexport function PartialFromMappedResult(R, options) {\n const P = FromMappedResult(R, options);\n return MappedResult(P);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Kind, Hint } from '../symbols/index.mjs';\nimport { Computed } from '../computed/index.mjs';\nimport { Never } from '../never/index.mjs';\nimport { Object } from '../object/index.mjs';\nimport { Ref } from '../ref/index.mjs';\nimport { Union } from '../union/index.mjs';\nimport { IsTemplateLiteralFinite } from '../template-literal/index.mjs';\nimport { PatternStringExact, PatternNumberExact, PatternNeverExact } from '../patterns/index.mjs';\nimport { IndexPropertyKeys } from '../indexed/index.mjs';\n// ------------------------------------------------------------------\n// ValueGuard\n// ------------------------------------------------------------------\nimport { IsUndefined } from '../guard/value.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsInteger, IsLiteral, IsAny, IsNever, IsNumber, IsString, IsRegExp, IsTemplateLiteral, IsUnion, IsRef, IsComputed } from '../guard/kind.mjs';\n// ------------------------------------------------------------------\n// RecordCreateFromPattern\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction RecordCreateFromPattern(pattern, T, options) {\n return CreateType({ [Kind]: 'Record', type: 'object', patternProperties: { [pattern]: T } }, options);\n}\n// ------------------------------------------------------------------\n// RecordCreateFromKeys\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction RecordCreateFromKeys(K, T, options) {\n const result = {};\n for (const K2 of K)\n result[K2] = T;\n return Object(result, { ...options, [Hint]: 'Record' });\n}\n// prettier-ignore\nfunction FromTemplateLiteralKey(K, T, options) {\n return (IsTemplateLiteralFinite(K)\n ? RecordCreateFromKeys(IndexPropertyKeys(K), T, options)\n : RecordCreateFromPattern(K.pattern, T, options));\n}\n// prettier-ignore\nfunction FromUnionKey(key, type, options) {\n return RecordCreateFromKeys(IndexPropertyKeys(Union(key)), type, options);\n}\n// prettier-ignore\nfunction FromLiteralKey(key, type, options) {\n return RecordCreateFromKeys([key.toString()], type, options);\n}\n// prettier-ignore\nfunction FromRegExpKey(key, type, options) {\n return RecordCreateFromPattern(key.source, type, options);\n}\n// prettier-ignore\nfunction FromStringKey(key, type, options) {\n const pattern = IsUndefined(key.pattern) ? PatternStringExact : key.pattern;\n return RecordCreateFromPattern(pattern, type, options);\n}\n// prettier-ignore\nfunction FromAnyKey(_, type, options) {\n return RecordCreateFromPattern(PatternStringExact, type, options);\n}\n// prettier-ignore\nfunction FromNeverKey(_key, type, options) {\n return RecordCreateFromPattern(PatternNeverExact, type, options);\n}\n// prettier-ignore\nfunction FromIntegerKey(_key, type, options) {\n return RecordCreateFromPattern(PatternNumberExact, type, options);\n}\n// prettier-ignore\nfunction FromNumberKey(_, type, options) {\n return RecordCreateFromPattern(PatternNumberExact, type, options);\n}\n// ------------------------------------------------------------------\n// TRecordOrObject\n// ------------------------------------------------------------------\n/** `[Json]` Creates a Record type */\nexport function Record(key, type, options = {}) {\n // prettier-ignore\n return (IsComputed(type) ? Computed('Record', [key, Computed(type.target, type.parameters)], options) :\n IsComputed(key) ? Computed('Record', [Computed(type.target, type.parameters), type], options) :\n IsRef(key) ? Computed('Record', [Ref(key.$ref), type]) :\n IsUnion(key) ? FromUnionKey(key.anyOf, type, options) :\n IsTemplateLiteral(key) ? FromTemplateLiteralKey(key, type, options) :\n IsLiteral(key) ? FromLiteralKey(key.const, type, options) :\n IsInteger(key) ? FromIntegerKey(key, type, options) :\n IsNumber(key) ? FromNumberKey(key, type, options) :\n IsRegExp(key) ? FromRegExpKey(key, type, options) :\n IsString(key) ? FromStringKey(key, type, options) :\n IsAny(key) ? FromAnyKey(key, type, options) :\n IsNever(key) ? FromNeverKey(key, type, options) :\n Never(options));\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Computed } from '../computed/index.mjs';\nimport { Object } from '../object/index.mjs';\nimport { Intersect } from '../intersect/index.mjs';\nimport { Union } from '../union/index.mjs';\nimport { Ref } from '../ref/index.mjs';\nimport { OptionalKind, TransformKind } from '../symbols/index.mjs';\nimport { Discard } from '../discard/index.mjs';\nimport { RequiredFromMappedResult } from './required-from-mapped-result.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsMappedResult, IsIntersect, IsUnion, IsObject, IsRef, IsComputed } from '../guard/kind.mjs';\n// prettier-ignore\nfunction FromComputed(target, parameters) {\n return Computed('Required', [Computed(target, parameters)]);\n}\n// prettier-ignore\nfunction FromRef($ref) {\n return Computed('Required', [Ref($ref)]);\n}\n// prettier-ignore\nfunction FromProperties(properties) {\n const requiredProperties = {};\n for (const K of globalThis.Object.getOwnPropertyNames(properties))\n requiredProperties[K] = Discard(properties[K], [OptionalKind]);\n return requiredProperties;\n}\n// prettier-ignore\nfunction FromObject(type) {\n const options = Discard(type, [TransformKind, '$id', 'required', 'properties']);\n const properties = FromProperties(type['properties']);\n return Object(properties, options);\n}\n// prettier-ignore\nfunction FromRest(types) {\n return types.map(type => RequiredResolve(type));\n}\n// ------------------------------------------------------------------\n// RequiredResolve\n// ------------------------------------------------------------------\n// prettier-ignore\nfunction RequiredResolve(type) {\n return (IsComputed(type) ? FromComputed(type.target, type.parameters) :\n IsRef(type) ? FromRef(type.$ref) :\n IsIntersect(type) ? Intersect(FromRest(type.allOf)) :\n IsUnion(type) ? Union(FromRest(type.anyOf)) :\n IsObject(type) ? FromObject(type) :\n Object({}));\n}\n/** `[Json]` Constructs a type where all properties are required */\nexport function Required(type, options) {\n if (IsMappedResult(type)) {\n return RequiredFromMappedResult(type, options);\n }\n else {\n // special: mapping types require overridable options\n return CreateType({ ...RequiredResolve(type), ...options });\n }\n}\n","import { MappedResult } from '../mapped/index.mjs';\nimport { Required } from './required.mjs';\n// prettier-ignore\nfunction FromProperties(P, options) {\n const Acc = {};\n for (const K2 of globalThis.Object.getOwnPropertyNames(P))\n Acc[K2] = Required(P[K2], options);\n return Acc;\n}\n// prettier-ignore\nfunction FromMappedResult(R, options) {\n return FromProperties(R.properties, options);\n}\n// prettier-ignore\nexport function RequiredFromMappedResult(R, options) {\n const P = FromMappedResult(R, options);\n return MappedResult(P);\n}\n","import { CreateType } from '../create/index.mjs';\nimport { Discard } from '../discard/index.mjs';\nimport { Array } from '../array/index.mjs';\nimport { Awaited } from '../awaited/index.mjs';\nimport { AsyncIterator } from '../async-iterator/index.mjs';\nimport { Constructor } from '../constructor/index.mjs';\nimport { Index } from '../indexed/index.mjs';\nimport { Function as FunctionType } from '../function/index.mjs';\nimport { Intersect } from '../intersect/index.mjs';\nimport { Iterator } from '../iterator/index.mjs';\nimport { KeyOf } from '../keyof/index.mjs';\nimport { Object } from '../object/index.mjs';\nimport { Omit } from '../omit/index.mjs';\nimport { Pick } from '../pick/index.mjs';\nimport { Never } from '../never/index.mjs';\nimport { Partial } from '../partial/index.mjs';\nimport { Record } from '../record/index.mjs';\nimport { Required } from '../required/index.mjs';\nimport { Tuple } from '../tuple/index.mjs';\nimport { Union } from '../union/index.mjs';\nimport { OptionalKind, ReadonlyKind } from '../symbols/index.mjs';\n// ------------------------------------------------------------------\n// KindGuard\n// ------------------------------------------------------------------\nimport * as KindGuard from '../guard/kind.mjs';\n// prettier-ignore\nfunction DerefParameters(moduleProperties, types) {\n return types.map((type) => {\n return KindGuard.IsRef(type)\n ? Deref(moduleProperties, type.$ref)\n : FromType(moduleProperties, type);\n });\n}\n// prettier-ignore\nfunction Deref(moduleProperties, ref) {\n return (ref in moduleProperties\n ? KindGuard.IsRef(moduleProperties[ref])\n ? Deref(moduleProperties, moduleProperties[ref].$ref)\n : FromType(moduleProperties, moduleProperties[ref])\n : Never());\n}\n// prettier-ignore\nfunction FromAwaited(parameters) {\n return Awaited(parameters[0]);\n}\n// prettier-ignore\nfunction FromIndex(parameters) {\n return Index(parameters[0], parameters[1]);\n}\n// prettier-ignore\nfunction FromKeyOf(parameters) {\n return KeyOf(parameters[0]);\n}\n// prettier-ignore\nfunction FromPartial(parameters) {\n return Partial(parameters[0]);\n}\n// prettier-ignore\nfunction FromOmit(parameters) {\n return Omit(parameters[0], parameters[1]);\n}\n// prettier-ignore\nfunction FromPick(parameters) {\n return Pick(parameters[0], parameters[1]);\n}\n// prettier-ignore\nfunction FromRecord(parameters) {\n return Record(parameters[0], parameters[1]);\n}\n// prettier-ignore\nfunction FromRequired(parameters) {\n return Required(parameters[0]);\n}\n// prettier-ignore\nfunction FromComputed(moduleProperties, target, parameters) {\n const dereferenced = DerefParameters(moduleProperties, parameters);\n return (target === 'Awaited' ? FromAwaited(dereferenced) :\n target === 'Index' ? FromIndex(dereferenced) :\n target === 'KeyOf' ? FromKeyOf(dereferenced) :\n target === 'Partial' ? FromPartial(dereferenced) :\n target === 'Omit' ? FromOmit(dereferenced) :\n target === 'Pick' ? FromPick(dereferenced) :\n target === 'Record' ? FromRecord(dereferenced) :\n target === 'Required' ? FromRequired(dereferenced) :\n Never());\n}\nfunction FromObject(moduleProperties, properties) {\n return Object(globalThis.Object.keys(properties).reduce((result, key) => {\n return { ...result, [key]: FromType(moduleProperties, properties[key]) };\n }, {}));\n}\n// prettier-ignore\nfunction FromConstructor(moduleProperties, parameters, instanceType) {\n return Constructor(FromRest(moduleProperties, parameters), FromType(moduleProperties, instanceType));\n}\n// prettier-ignore\nfunction FromFunction(moduleProperties, parameters, returnType) {\n return FunctionType(FromRest(moduleProperties, parameters), FromType(moduleProperties, returnType));\n}\nfunction FromTuple(moduleProperties, types) {\n return Tuple(FromRest(moduleProperties, types));\n}\nfunction FromIntersect(moduleProperties, types) {\n return Intersect(FromRest(moduleProperties, types));\n}\nfunction FromUnion(moduleProperties, types) {\n return Union(FromRest(moduleProperties, types));\n}\nfunction FromArray(moduleProperties, type) {\n return Array(FromType(moduleProperties, type));\n}\nfunction FromAsyncIterator(moduleProperties, type) {\n return AsyncIterator(FromType(moduleProperties, type));\n}\nfunction FromIterator(moduleProperties, type) {\n return Iterator(FromType(moduleProperties, type));\n}\nfunction FromRest(moduleProperties, types) {\n return types.map((type) => FromType(moduleProperties, type));\n}\n// prettier-ignore\nexport function FromType(moduleProperties, type) {\n return (\n // Modifier Unwrap - Reapplied via CreateType Options\n KindGuard.IsOptional(type) ? CreateType(FromType(moduleProperties, Discard(type, [OptionalKind])), type) :\n KindGuard.IsReadonly(type) ? CreateType(FromType(moduleProperties, Discard(type, [ReadonlyKind])), type) :\n // Traveral\n KindGuard.IsArray(type) ? CreateType(FromArray(moduleProperties, type.items), type) :\n KindGuard.IsAsyncIterator(type) ? CreateType(FromAsyncIterator(moduleProperties, type.items), type) :\n KindGuard.IsComputed(type) ? CreateType(FromComputed(moduleProperties, type.target, type.parameters)) :\n KindGuard.IsConstructor(type) ? CreateType(FromConstructor(moduleProperties, type.parameters, type.returns), type) :\n KindGuard.IsFunction(type) ? CreateType(FromFunction(moduleProperties, type.parameters, type.returns), type) :\n KindGuard.IsIntersect(type) ? CreateType(FromIntersect(moduleProperties, type.allOf), type) :\n KindGuard.IsIterator(type) ? CreateType(FromIterator(moduleProperties, type.items), type) :\n KindGuard.IsObject(type) ? CreateType(FromObject(moduleProperties, type.properties), type) :\n KindGuard.IsTuple(type) ? CreateType(FromTuple(moduleProperties, type.items || []), type) :\n KindGuard.IsUnion(type) ? CreateType(FromUnion(moduleProperties, type.anyOf), type) :\n type);\n}\n// prettier-ignore\nexport function ComputeType(moduleProperties, key) {\n return (key in moduleProperties\n ? FromType(moduleProperties, moduleProperties[key])\n : Never());\n}\n// prettier-ignore\nexport function ComputeModuleProperties(moduleProperties) {\n return globalThis.Object.getOwnPropertyNames(moduleProperties).reduce((result, key) => {\n return { ...result, [key]: ComputeType(moduleProperties, key) };\n }, {});\n}\n","import { CreateType } from '../create/index.mjs';\nimport { Kind } from '../symbols/index.mjs';\n// ------------------------------------------------------------------\n// Module Infrastructure Types\n// ------------------------------------------------------------------\nimport { ComputeModuleProperties } from './compute.mjs';\n// ------------------------------------------------------------------\n// Module\n// ------------------------------------------------------------------\n// prettier-ignore\nexport class TModule {\n constructor($defs) {\n const computed = ComputeModuleProperties($defs);\n const identified = this.WithIdentifiers(computed);\n this.$defs = identified;\n }\n /** `[Json]` Imports a Type by Key. */\n Import(key, options) {\n const $defs = { ...this.$defs, [key]: CreateType(this.$defs[key], options) };\n return CreateType({ [Kind]: 'Import', $defs, $ref: key });\n }\n // prettier-ignore\n WithIdentifiers($defs) {\n return globalThis.Object.getOwnPropertyNames($defs).reduce((result, key) => {\n return { ...result, [key]: { ...$defs[key], $id: key } };\n }, {});\n }\n}\n/** `[Json]` Creates a Type Definition Module. */\nexport function Module(properties) {\n return new TModule(properties);\n}\n","import { CloneType } from '../clone/type.mjs';\nimport { CreateType } from '../create/type.mjs';\nimport { IsUndefined } from '../guard/value.mjs';\nimport { Kind, Hint } from '../symbols/index.mjs';\n// Auto Tracked For Recursive Types without ID's\nlet Ordinal = 0;\n/** `[Json]` Creates a Recursive type */\nexport function Recursive(callback, options = {}) {\n if (IsUndefined(options.$id))\n options.$id = `T${Ordinal++}`;\n const thisType = CloneType(callback({ [Kind]: 'This', $ref: `${options.$id}` }));\n thisType.$id = options.$id;\n // prettier-ignore\n return CreateType({ [Hint]: 'Recursive', ...thisType }, options);\n}\n","import { TransformKind } from '../symbols/index.mjs';\n// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsTransform } from '../guard/kind.mjs';\n// ------------------------------------------------------------------\n// TransformBuilders\n// ------------------------------------------------------------------\nexport class TransformDecodeBuilder {\n constructor(schema) {\n this.schema = schema;\n }\n Decode(decode) {\n return new TransformEncodeBuilder(this.schema, decode);\n }\n}\n// prettier-ignore\nexport class TransformEncodeBuilder {\n constructor(schema, decode) {\n this.schema = schema;\n this.decode = decode;\n }\n EncodeTransform(encode, schema) {\n const Encode = (value) => schema[TransformKind].Encode(encode(value));\n const Decode = (value) => this.decode(schema[TransformKind].Decode(value));\n const Codec = { Encode: Encode, Decode: Decode };\n return { ...schema, [TransformKind]: Codec };\n }\n EncodeSchema(encode, schema) {\n const Codec = { Decode: this.decode, Encode: encode };\n return { ...schema, [TransformKind]: Codec };\n }\n Encode(encode) {\n return (IsTransform(this.schema) ? this.EncodeTransform(encode, this.schema) : this.EncodeSchema(encode, this.schema));\n }\n}\n/** `[Json]` Creates a Transform type */\nexport function Transform(schema) {\n return new TransformDecodeBuilder(schema);\n}\n","// ------------------------------------------------------------------\n// JsonTypeBuilder\n// ------------------------------------------------------------------\nexport { JsonTypeBuilder } from './json.mjs';\n// ------------------------------------------------------------------\n// JavaScriptTypeBuilder\n// ------------------------------------------------------------------\nimport * as TypeBuilder from './type.mjs';\nimport { JavaScriptTypeBuilder } from './javascript.mjs';\n/** JavaScript Type Builder with Static Resolution for TypeScript */\nconst Type = TypeBuilder;\nexport { JavaScriptTypeBuilder };\nexport { Type };\n","import { Intrinsic } from './intrinsic.mjs';\n/** `[Json]` Intrinsic function to Capitalize LiteralString types */\nexport function Capitalize(T, options = {}) {\n return Intrinsic(T, 'Capitalize', options);\n}\n","import { Tuple } from '../tuple/index.mjs';\nimport { Never } from '../never/index.mjs';\nimport * as KindGuard from '../guard/kind.mjs';\n/** `[JavaScript]` Extracts the ConstructorParameters from the given Constructor type */\nexport function ConstructorParameters(schema, options) {\n return (KindGuard.IsConstructor(schema) ? Tuple(schema.parameters, options) : Never(options));\n}\n","import { Literal } from '../literal/index.mjs';\nimport { Kind, Hint } from '../symbols/index.mjs';\nimport { Union } from '../union/index.mjs';\n// ------------------------------------------------------------------\n// ValueGuard\n// ------------------------------------------------------------------\nimport { IsUndefined } from '../guard/value.mjs';\n/** `[Json]` Creates a Enum type */\nexport function Enum(item, options) {\n if (IsUndefined(item))\n throw new Error('Enum undefined or empty');\n const values1 = globalThis.Object.getOwnPropertyNames(item)\n .filter((key) => isNaN(key))\n .map((key) => item[key]);\n const values2 = [...new Set(values1)];\n const anyOf = values2.map((value) => Literal(value));\n return Union(anyOf, { ...options, [Hint]: 'Enum' });\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Never } from '../never/index.mjs';\nimport * as KindGuard from '../guard/kind.mjs';\n/** `[JavaScript]` Extracts the InstanceType from the given Constructor type */\nexport function InstanceType(schema, options) {\n return (KindGuard.IsConstructor(schema) ? CreateType(schema.returns, options) : Never(options));\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates an Integer type */\nexport function Integer(options) {\n return CreateType({ [Kind]: 'Integer', type: 'integer' }, options);\n}\n","import { Intrinsic } from './intrinsic.mjs';\n/** `[Json]` Intrinsic function to Lowercase LiteralString types */\nexport function Lowercase(T, options = {}) {\n return Intrinsic(T, 'Lowercase', options);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates a Not type */\nexport function Not(type, options) {\n return CreateType({ [Kind]: 'Not', not: type }, options);\n}\n","import { Tuple } from '../tuple/index.mjs';\nimport { Never } from '../never/index.mjs';\nimport * as KindGuard from '../guard/kind.mjs';\n/** `[JavaScript]` Extracts the Parameters from the given Function type */\nexport function Parameters(schema, options) {\n return (KindGuard.IsFunction(schema) ? Tuple(schema.parameters, options) : Never());\n}\n","import { Readonly } from '../readonly/index.mjs';\nimport { Optional } from '../optional/index.mjs';\n/** `[Json]` Creates a Readonly and Optional property */\nexport function ReadonlyOptional(schema) {\n return Readonly(Optional(schema));\n}\n","import { Clone } from './value.mjs';\n/** Clones a Rest */\nexport function CloneRest(schemas) {\n return schemas.map((schema) => CloneType(schema));\n}\n/** Clones a Type */\nexport function CloneType(schema, options) {\n return options === undefined ? Clone(schema) : Clone({ ...options, ...schema });\n}\n","import { CreateType } from '../create/type.mjs';\nimport { IsString } from '../guard/value.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[JavaScript]` Creates a RegExp type */\nexport function RegExp(unresolved, options) {\n const expr = IsString(unresolved) ? new globalThis.RegExp(unresolved) : unresolved;\n return CreateType({ [Kind]: 'RegExp', type: 'RegExp', source: expr.source, flags: expr.flags }, options);\n}\n","// ------------------------------------------------------------------\n// TypeGuard\n// ------------------------------------------------------------------\nimport { IsIntersect, IsUnion, IsTuple } from '../guard/kind.mjs';\n// prettier-ignore\nfunction RestResolve(T) {\n return (IsIntersect(T) ? T.allOf :\n IsUnion(T) ? T.anyOf :\n IsTuple(T) ? T.items ?? [] :\n []);\n}\n/** `[Json]` Extracts interior Rest elements from Tuple, Intersect and Union types */\nexport function Rest(T) {\n return RestResolve(T);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Never } from '../never/index.mjs';\nimport * as KindGuard from '../guard/kind.mjs';\n/** `[JavaScript]` Extracts the ReturnType from the given Function type */\nexport function ReturnType(schema, options) {\n return (KindGuard.IsFunction(schema) ? CreateType(schema.returns, options) : Never(options));\n}\n","import { Intrinsic } from './intrinsic.mjs';\n/** `[Json]` Intrinsic function to Uncapitalize LiteralString types */\nexport function Uncapitalize(T, options = {}) {\n return Intrinsic(T, 'Uncapitalize', options);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[Json]` Creates a Unsafe type that will infers as the generic argument T */\nexport function Unsafe(options = {}) {\n return CreateType({ [Kind]: options[Kind] ?? 'Unsafe' }, options);\n}\n","import { Intrinsic } from './intrinsic.mjs';\n/** `[Json]` Intrinsic function to Uppercase LiteralString types */\nexport function Uppercase(T, options = {}) {\n return Intrinsic(T, 'Uppercase', options);\n}\n","import { CreateType } from '../create/type.mjs';\nimport { Kind } from '../symbols/index.mjs';\n/** `[JavaScript]` Creates a Void type */\nexport function Void(options) {\n return CreateType({ [Kind]: 'Void', type: 'void' }, options);\n}\n","/**\n * ATTENTION. This code was AUTO GENERATED by ts2typebox. While I don't know\n * your use case, there is a high chance that direct changes to this file get\n * lost. Consider making changes to the underlying Typescript code you use to\n * generate this file instead. The default file is called \"types.ts\", perhaps\n * have a look there! :]\n */\nimport { Type } from \"@sinclair/typebox\";\nexport const ProposalsBotStakeNeuronForSubmittingProposalsResponse = Type.Union([\n Type.Object({\n Success: Type.Tuple([\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n ]),\n }),\n Type.Object({\n NeuronAlreadyExists: Type.Tuple([\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n ]),\n }),\n Type.Literal(\"StakeTooLow\"),\n Type.Object({\n TransferError: Type.String(),\n }),\n Type.Literal(\"GovernanceCanisterNotSupported\"),\n Type.Literal(\"Unauthorized\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n]);\nexport const ProposalsBotTopUpNeuronResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Object({\n TransferError: Type.String(),\n }),\n Type.Literal(\"GovernanceCanisterNotSupported\"),\n Type.Literal(\"Unauthorized\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n]);\nexport const ProposalsBotSubmitProposalResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"GovernanceCanisterNotSupported\"),\n Type.Object({\n InsufficientPayment: Type.BigInt(),\n }),\n Type.Object({\n PaymentFailed: Type.String(),\n }),\n Type.Object({\n Retrying: Type.String(),\n }),\n Type.Object({\n InternalError: Type.String(),\n }),\n]);\nexport const ProposalsBotCanisterInstallMode = Type.Union([\n Type.Literal(\"Install\"),\n Type.Literal(\"Reinstall\"),\n Type.Literal(\"Upgrade\"),\n]);\nexport const ProposalsBotTreasury = Type.Union([Type.Literal(\"ICP\"), Type.Literal(\"SNS\")]);\nexport const OnlineUsersMinutesOnlineArgs = Type.Object({\n year: Type.Number(),\n month: Type.Number(),\n});\nexport const OnlineUsersMinutesOnlineResponse = Type.Object({\n Success: Type.Number(),\n});\nexport const OnlineUsersMarkAsOnlineSuccessResult = Type.Object({\n timestamp: Type.BigInt(),\n year: Type.Number(),\n month: Type.Number(),\n minutes_online: Type.Number(),\n});\nexport const GroupSummaryUpdatesArgs = Type.Object({\n updates_since: Type.BigInt(),\n});\nexport const GroupToggleMuteNotificationsArgs = Type.Object({\n mute: Type.Boolean(),\n});\nexport const GroupInviteCodeSuccessResult = Type.Object({\n code: Type.Optional(Type.BigInt()),\n});\nexport const GroupEnableInviteCodeArgs = Type.Object({\n correlation_id: Type.BigInt(),\n});\nexport const GroupEnableInviteCodeSuccessResult = Type.Object({\n code: Type.BigInt(),\n});\nexport const GroupDisableInviteCodeArgs = Type.Object({\n correlation_id: Type.BigInt(),\n});\nexport const GroupGenerateBotApiKeySuccessResult = Type.Object({\n api_key: Type.String(),\n});\nexport const GroupPublicSummaryArgs = Type.Object({\n invite_code: Type.Optional(Type.BigInt()),\n});\nexport const GroupRulesArgs = Type.Object({\n invite_code: Type.Optional(Type.BigInt()),\n});\nexport const GroupRulesSuccessResult = Type.Object({\n rules: Type.Optional(Type.String()),\n});\nexport const GroupSelectedUpdatesArgs = Type.Object({\n updates_since: Type.BigInt(),\n});\nexport const GroupSummaryArgs = Type.Object({});\nexport const UserUpdateBtcBalanceResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NoUpdates\"),\n Type.Object({\n Error: Type.String(),\n }),\n]);\nexport const UserMessageActivitySummary = Type.Object({\n read_up_to: Type.BigInt(),\n latest_event_timestamp: Type.BigInt(),\n unread_count: Type.Number(),\n});\nexport const UserMarkAchievementsSeenArgs = Type.Object({\n last_seen: Type.BigInt(),\n});\nexport const UserMarkAchievementsSeenResponse = Type.Literal(\"Success\");\nexport const UserBioResponse = Type.Object({\n Success: Type.String(),\n});\nexport const UserTokenSwapStatusArgs = Type.Object({\n swap_id: Type.BigInt(),\n});\nexport const UserTokenSwapStatusTokenSwapStatus = Type.Object({\n started: Type.BigInt(),\n icrc2: Type.Boolean(),\n auto_withdrawals: Type.Boolean(),\n deposit_account: Type.Optional(Type.Union([\n Type.Object({\n Ok: Type.Null(),\n }),\n Type.Object({\n Err: Type.String(),\n }),\n ])),\n transfer: Type.Optional(Type.Union([\n Type.Object({\n Ok: Type.BigInt(),\n }),\n Type.Object({\n Err: Type.String(),\n }),\n ])),\n transfer_or_approval: Type.Optional(Type.Union([\n Type.Object({\n Ok: Type.BigInt(),\n }),\n Type.Object({\n Err: Type.String(),\n }),\n ])),\n notify_dex: Type.Optional(Type.Union([\n Type.Object({\n Ok: Type.Null(),\n }),\n Type.Object({\n Err: Type.String(),\n }),\n ])),\n amount_swapped: Type.Optional(Type.Union([\n Type.Object({\n Ok: Type.Union([\n Type.Object({\n Ok: Type.BigInt(),\n }),\n Type.Object({\n Err: Type.String(),\n }),\n ]),\n }),\n Type.Object({\n Err: Type.String(),\n }),\n ])),\n withdraw_from_dex: Type.Optional(Type.Union([\n Type.Object({\n Ok: Type.BigInt(),\n }),\n Type.Object({\n Err: Type.String(),\n }),\n ])),\n success: Type.Optional(Type.Boolean()),\n});\nexport const UserSwapTokensSuccessResult = Type.Object({\n amount_out: Type.BigInt(),\n});\nexport const UserMessageActivityFeedArgs = Type.Object({\n since: Type.BigInt(),\n});\nexport const UserUnblockUserResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"UserSuspended\"),\n]);\nexport const UserAddHotGroupExclusionsResponse = Type.Literal(\"Success\");\nexport const UserUpdatesArgs = Type.Object({\n updates_since: Type.BigInt(),\n});\nexport const UserGenerateBotApiKeySuccessResult = Type.Object({\n api_key: Type.String(),\n});\nexport const UserSetBioArgs = Type.Object({\n text: Type.String(),\n});\nexport const UserClaimDailyChitSuccessResult = Type.Object({\n chit_earned: Type.Number(),\n chit_balance: Type.Number(),\n streak: Type.Number(),\n max_streak: Type.Number(),\n next_claim: Type.BigInt(),\n});\nexport const UserClaimDailyChitResponse = Type.Union([\n Type.Object({\n Success: UserClaimDailyChitSuccessResult,\n }),\n Type.Object({\n AlreadyClaimed: Type.BigInt(),\n }),\n]);\nexport const UserTokenSwapsArgs = Type.Object({\n start: Type.Number(),\n max_results: Type.Number(),\n});\nexport const UserMessageActivity = Type.Union([\n Type.Literal(\"Mention\"),\n Type.Literal(\"Reaction\"),\n Type.Literal(\"QuoteReply\"),\n Type.Literal(\"Tip\"),\n Type.Literal(\"Crypto\"),\n Type.Literal(\"PollVote\"),\n Type.Literal(\"P2PSwapAccepted\"),\n]);\nexport const UserSetCommunityIndexesResponse = Type.Literal(\"Success\");\nexport const UserReclaimSwapTokensResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Object({\n Failed: Type.String(),\n }),\n]);\nexport const UserPublicProfilePublicProfile = Type.Object({\n username: Type.String(),\n display_name: Type.Optional(Type.String()),\n avatar_id: Type.Optional(Type.BigInt()),\n bio: Type.String(),\n is_premium: Type.Boolean(),\n phone_is_verified: Type.Boolean(),\n created: Type.BigInt(),\n});\nexport const UserMarkReadResponse = Type.Literal(\"Success\");\nexport const UserCancelMessageReminderResponse = Type.Literal(\"Success\");\nexport const UserCancelMessageReminderArgs = Type.Object({\n reminder_id: Type.BigInt(),\n});\nexport const UserChitEventsArgs = Type.Object({\n from: Type.Optional(Type.BigInt()),\n to: Type.Optional(Type.BigInt()),\n skip: Type.Optional(Type.Number()),\n max: Type.Number(),\n ascending: Type.Boolean(),\n});\nexport const UserNamedAccount = Type.Object({\n name: Type.String(),\n account: Type.String(),\n});\nexport const UserAutoWallet = Type.Object({\n min_cents_visible: Type.Number(),\n});\nexport const UserMarkMessageActivityFeedReadResponse = Type.Literal(\"Success\");\nexport const UserMarkMessageActivityFeedReadArgs = Type.Object({\n read_up_to: Type.BigInt(),\n});\nexport const UserConfigureWalletResponse = Type.Literal(\"Success\");\nexport const MessageReminderContent = Type.Object({\n reminder_id: Type.BigInt(),\n notes: Type.Optional(Type.String()),\n});\nexport const Reaction = Type.String();\nexport const FieldTooShortResult = Type.Object({\n length_provided: Type.Number(),\n min_length: Type.Number(),\n});\nexport const MessageIndex = Type.Number();\nexport const DiamondMembershipPlanDuration = Type.Union([\n Type.Literal(\"OneMonth\"),\n Type.Literal(\"ThreeMonths\"),\n Type.Literal(\"OneYear\"),\n Type.Literal(\"Lifetime\"),\n]);\nexport const EventIndex = Type.Number();\nexport const ReferralStatus = Type.Union([\n Type.Literal(\"Registered\"),\n Type.Literal(\"Diamond\"),\n Type.Literal(\"UniquePerson\"),\n Type.Literal(\"LifetimeDiamond\"),\n]);\nexport const VoteOperation = Type.Union([Type.Literal(\"RegisterVote\"), Type.Literal(\"DeleteVote\")]);\nexport const SuspensionAction = Type.Union([\n Type.Object({\n Unsuspend: Type.BigInt(),\n }),\n Type.Object({\n Delete: Type.BigInt(),\n }),\n]);\nexport const OCError = Type.Tuple([Type.Number(), Type.Union([Type.String(), Type.Null()])]);\nexport const BotCommandOptionChoiceF64 = Type.Object({\n name: Type.String(),\n value: Type.Number(),\n});\nexport const SwapStatusErrorCancelled = Type.Object({\n token0_txn_out: Type.Optional(Type.BigInt()),\n});\nexport const SubscriptionKeys = Type.Object({\n p256dh: Type.String(),\n auth: Type.String(),\n});\nexport const CommunityRole = Type.Union([\n Type.Literal(\"Owner\"),\n Type.Literal(\"Admin\"),\n Type.Literal(\"Member\"),\n]);\nexport const ExchangeId = Type.Union([\n Type.Literal(\"ICPSwap\"),\n Type.Literal(\"Sonic\"),\n Type.Literal(\"KongSwap\"),\n]);\nexport const ProposalDecisionStatus = Type.Union([\n Type.Literal(\"Unspecified\"),\n Type.Literal(\"Open\"),\n Type.Literal(\"Rejected\"),\n Type.Literal(\"Adopted\"),\n Type.Literal(\"Executed\"),\n Type.Literal(\"Failed\"),\n]);\nexport const CanisterUpgradeStatus = Type.Union([\n Type.Literal(\"InProgress\"),\n Type.Literal(\"NotRequired\"),\n]);\nexport const OptionUpdateU128 = Type.Union([\n Type.Literal(\"NoChange\"),\n Type.Literal(\"SetToNone\"),\n Type.Object({\n SetToSome: Type.BigInt(),\n }),\n], { default: \"NoChange\" });\nexport const SwapStatusErrorExpired = Type.Object({\n token0_txn_out: Type.Optional(Type.BigInt()),\n});\nexport const PinNumberSettings = Type.Object({\n length: Type.Number(),\n attempts_blocked_until: Type.Optional(Type.BigInt()),\n});\nexport const ApproveError = Type.Union([\n Type.Object({\n BadFee: Type.Object({\n expected_fee: Type.BigInt(),\n }),\n }),\n Type.Object({\n InsufficientFunds: Type.Object({\n balance: Type.BigInt(),\n }),\n }),\n Type.Object({\n AllowanceChanged: Type.Object({\n current_allowance: Type.BigInt(),\n }),\n }),\n Type.Object({\n Expired: Type.Object({\n ledger_time: Type.BigInt(),\n }),\n }),\n Type.Literal(\"TooOld\"),\n Type.Object({\n CreatedInFuture: Type.Object({\n ledger_time: Type.BigInt(),\n }),\n }),\n Type.Object({\n Duplicate: Type.Object({\n duplicate_of: Type.BigInt(),\n }),\n }),\n Type.Literal(\"TemporarilyUnavailable\"),\n Type.Object({\n GenericError: Type.Object({\n error_code: Type.BigInt(),\n message: Type.String(),\n }),\n }),\n]);\nexport const VideoCallPresence = Type.Union([\n Type.Literal(\"Default\"),\n Type.Literal(\"Owner\"),\n Type.Literal(\"Hidden\"),\n]);\nexport const ChatMetrics = Type.Object({\n text_messages: Type.BigInt(),\n image_messages: Type.BigInt(),\n video_messages: Type.BigInt(),\n audio_messages: Type.BigInt(),\n file_messages: Type.BigInt(),\n polls: Type.BigInt(),\n poll_votes: Type.BigInt(),\n crypto_messages: Type.BigInt(),\n icp_messages: Type.BigInt(),\n sns1_messages: Type.BigInt(),\n ckbtc_messages: Type.BigInt(),\n chat_messages: Type.BigInt(),\n kinic_messages: Type.BigInt(),\n deleted_messages: Type.BigInt(),\n giphy_messages: Type.BigInt(),\n prize_messages: Type.BigInt(),\n prize_winner_messages: Type.BigInt(),\n replies: Type.BigInt(),\n edits: Type.BigInt(),\n reactions: Type.BigInt(),\n proposals: Type.BigInt(),\n reported_messages: Type.BigInt(),\n message_reminders: Type.BigInt(),\n custom_type_messages: Type.BigInt(),\n last_active: Type.BigInt(),\n});\nexport const VideoCallType = Type.Union([Type.Literal(\"Broadcast\"), Type.Literal(\"Default\")]);\nexport const VideoCall = Type.Object({\n message_index: MessageIndex,\n call_type: VideoCallType,\n});\nexport const GroupRole = Type.Union([\n Type.Literal(\"Owner\"),\n Type.Literal(\"Admin\"),\n Type.Literal(\"Moderator\"),\n Type.Literal(\"Participant\"),\n]);\nexport const AuthToken = Type.Union([\n Type.Object({\n Jwt: Type.String(),\n }),\n Type.Object({\n ApiKey: Type.String(),\n }),\n]);\nexport const ChannelId = Type.BigInt();\nexport const GroupPermissionRole = Type.Union([\n Type.Literal(\"None\"),\n Type.Literal(\"Owner\"),\n Type.Literal(\"Admins\"),\n Type.Literal(\"Moderators\"),\n Type.Literal(\"Members\"),\n]);\nexport const AcceptSwapSuccess = Type.Object({\n token1_txn_in: Type.BigInt(),\n});\nexport const OptionUpdateU64 = Type.Union([\n Type.Literal(\"NoChange\"),\n Type.Literal(\"SetToNone\"),\n Type.Object({\n SetToSome: Type.BigInt(),\n }),\n], { default: \"NoChange\" });\nexport const GroupCanisterThreadDetails = Type.Object({\n root_message_index: MessageIndex,\n latest_event: EventIndex,\n latest_message: MessageIndex,\n last_updated: Type.BigInt(),\n});\nexport const Tokens = Type.Object({\n e8s: Type.BigInt(),\n});\nexport const Rules = Type.Object({\n text: Type.String(),\n enabled: Type.Boolean(),\n});\nexport const SubscriptionInfo = Type.Object({\n endpoint: Type.String(),\n keys: SubscriptionKeys,\n});\nexport const OptionUpdateVideoCall = Type.Union([\n Type.Literal(\"NoChange\"),\n Type.Literal(\"SetToNone\"),\n Type.Object({\n SetToSome: VideoCall,\n }),\n], { default: \"NoChange\" });\nexport const UserSummaryVolatile = Type.Object({\n total_chit_earned: Type.Number(),\n chit_balance: Type.Number(),\n streak: Type.Number(),\n max_streak: Type.Number(),\n});\nexport const CommunityPermissionRole = Type.Union([\n Type.Literal(\"Owners\"),\n Type.Literal(\"Admins\"),\n Type.Literal(\"Members\"),\n]);\nexport const ProposalRewardStatus = Type.Union([\n Type.Literal(\"Unspecified\"),\n Type.Literal(\"AcceptVotes\"),\n Type.Literal(\"ReadyToSettle\"),\n Type.Literal(\"Settled\"),\n]);\nexport const OptionUpdatePinNumberSettings = Type.Union([\n Type.Literal(\"NoChange\"),\n Type.Literal(\"SetToNone\"),\n Type.Object({\n SetToSome: PinNumberSettings,\n }),\n], { default: \"NoChange\" });\nexport const CommunityPermissions = Type.Object({\n change_roles: CommunityPermissionRole,\n update_details: CommunityPermissionRole,\n invite_users: CommunityPermissionRole,\n remove_members: CommunityPermissionRole,\n create_public_channel: CommunityPermissionRole,\n create_private_channel: CommunityPermissionRole,\n manage_user_groups: CommunityPermissionRole,\n});\nexport const StreakInsurance = Type.Object({\n days_insured: Type.Number(),\n days_missed: Type.Number(),\n});\nexport const FieldTooLongResult = Type.Object({\n length_provided: Type.Number(),\n max_length: Type.Number(),\n});\nexport const Chit = Type.Object({\n balance: Type.Number(),\n streak: Type.Number(),\n});\nexport const PinNumberWrapper = Type.String();\nexport const GiphyImageVariant = Type.Object({\n width: Type.Number(),\n height: Type.Number(),\n url: Type.String(),\n mime_type: Type.String(),\n});\nexport const Achievement = Type.Union([\n Type.Literal(\"JoinedGroup\"),\n Type.Literal(\"JoinedCommunity\"),\n Type.Literal(\"SentDirectMessage\"),\n Type.Literal(\"ReceivedDirectMessage\"),\n Type.Literal(\"SetAvatar\"),\n Type.Literal(\"SetBio\"),\n Type.Literal(\"SetDisplayName\"),\n Type.Literal(\"UpgradedToDiamond\"),\n Type.Literal(\"UpgradedToGoldDiamond\"),\n Type.Literal(\"Streak3\"),\n Type.Literal(\"Streak7\"),\n Type.Literal(\"Streak14\"),\n Type.Literal(\"Streak30\"),\n Type.Literal(\"Streak100\"),\n Type.Literal(\"Streak365\"),\n Type.Literal(\"SentPoll\"),\n Type.Literal(\"SentText\"),\n Type.Literal(\"SentImage\"),\n Type.Literal(\"SentVideo\"),\n Type.Literal(\"SentAudio\"),\n Type.Literal(\"SentFile\"),\n Type.Literal(\"SentGiphy\"),\n Type.Literal(\"SentPrize\"),\n Type.Literal(\"SentMeme\"),\n Type.Literal(\"SentCrypto\"),\n Type.Literal(\"SentP2PSwapOffer\"),\n Type.Literal(\"StartedCall\"),\n Type.Literal(\"ReactedToMessage\"),\n Type.Literal(\"EditedMessage\"),\n Type.Literal(\"RepliedInThread\"),\n Type.Literal(\"QuoteReplied\"),\n Type.Literal(\"TippedMessage\"),\n Type.Literal(\"DeletedMessage\"),\n Type.Literal(\"ForwardedMessage\"),\n Type.Literal(\"ProvedUniquePersonhood\"),\n Type.Literal(\"ReceivedCrypto\"),\n Type.Literal(\"HadMessageReactedTo\"),\n Type.Literal(\"HadMessageTipped\"),\n Type.Literal(\"VotedOnPoll\"),\n Type.Literal(\"SentReminder\"),\n Type.Literal(\"JoinedCall\"),\n Type.Literal(\"AcceptedP2PSwapOffer\"),\n Type.Literal(\"SetCommunityDisplayName\"),\n Type.Literal(\"Referred1stUser\"),\n Type.Literal(\"Referred3rdUser\"),\n Type.Literal(\"Referred10thUser\"),\n Type.Literal(\"Referred20thUser\"),\n Type.Literal(\"Referred50thUser\"),\n Type.Literal(\"FollowedThread\"),\n Type.Literal(\"FavouritedChat\"),\n Type.Literal(\"SetPin\"),\n Type.Literal(\"SwappedFromWallet\"),\n Type.Literal(\"PinnedChat\"),\n Type.Literal(\"DepositedBtc\"),\n Type.Literal(\"ChangedTheme\"),\n]);\nexport const Empty = Type.Record(Type.String(), Type.Never());\nexport const ThumbnailData = Type.String();\nexport const GroupReplyContext = Type.Object({\n event_index: EventIndex,\n});\nexport const PushEventResult = Type.Object({\n index: EventIndex,\n timestamp: Type.BigInt(),\n expires_at: Type.Optional(Type.BigInt()),\n});\nexport const BuildVersion = Type.Object({\n major: Type.Number(),\n minor: Type.Number(),\n patch: Type.Number(),\n});\nexport const TSPrincipal = Type.Union([\n Type.Uint8Array(),\n Type.Array(Type.Number()),\n Type.String(),\n]);\nexport const OptionUpdateGroupPermissionRole = Type.Union([\n Type.Literal(\"NoChange\"),\n Type.Literal(\"SetToNone\"),\n Type.Object({\n SetToSome: GroupPermissionRole,\n }),\n], { default: \"NoChange\" });\nexport const BotCommandMeta = Type.Object({\n timezone: Type.String(),\n language: Type.String(),\n});\nexport const Cryptocurrency = Type.Union([\n Type.Literal(\"InternetComputer\"),\n Type.Literal(\"SNS1\"),\n Type.Literal(\"CKBTC\"),\n Type.Literal(\"CHAT\"),\n Type.Literal(\"KINIC\"),\n Type.Object({\n Other: Type.String(),\n }),\n]);\nexport const ChitEarnedReason = Type.Union([\n Type.Literal(\"DailyClaim\"),\n Type.Object({\n Achievement: Achievement,\n }),\n Type.Object({\n ExternalAchievement: Type.String(),\n }),\n Type.Object({\n Referral: ReferralStatus,\n }),\n Type.Literal(\"MemeContestWinner\"),\n]);\nexport const InvalidPollReason = Type.Union([\n Type.Object({\n TooFewOptions: Type.Number(),\n }),\n Type.Object({\n TooManyOptions: Type.Number(),\n }),\n Type.Object({\n OptionTooLong: Type.Number(),\n }),\n Type.Literal(\"DuplicateOptions\"),\n Type.Literal(\"EndDateInThePast\"),\n Type.Literal(\"PollsNotValidForDirectChats\"),\n]);\nexport const MembersAddedToDefaultChannel = Type.Object({\n count: Type.Number(),\n});\nexport const UserId = TSPrincipal;\nexport const CryptoAccountNNS = Type.Union([\n Type.Literal(\"Mint\"),\n Type.Object({\n Account: Type.Tuple([\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n ]),\n }),\n]);\nexport const BotCommandOptionChoiceI128 = Type.Object({\n name: Type.String(),\n value: Type.BigInt(),\n});\nexport const CommunityId = TSPrincipal;\nexport const MessageReminderCreatedContent = Type.Object({\n reminder_id: Type.BigInt(),\n remind_at: Type.BigInt(),\n notes: Type.Optional(Type.String()),\n hidden: Type.Boolean(),\n});\nexport const TransferFromError = Type.Union([\n Type.Object({\n BadFee: Type.Object({\n expected_fee: Type.BigInt(),\n }),\n }),\n Type.Object({\n BadBurn: Type.Object({\n min_burn_amount: Type.BigInt(),\n }),\n }),\n Type.Object({\n InsufficientFunds: Type.Object({\n balance: Type.BigInt(),\n }),\n }),\n Type.Object({\n InsufficientAllowance: Type.Object({\n allowance: Type.BigInt(),\n }),\n }),\n Type.Literal(\"TooOld\"),\n Type.Object({\n CreatedInFuture: Type.Object({\n ledger_time: Type.BigInt(),\n }),\n }),\n Type.Object({\n Duplicate: Type.Object({\n duplicate_of: Type.BigInt(),\n }),\n }),\n Type.Literal(\"TemporarilyUnavailable\"),\n Type.Object({\n GenericError: Type.Object({\n error_code: Type.BigInt(),\n message: Type.String(),\n }),\n }),\n]);\nexport const ChannelMessageTipped = Type.Object({\n ci: CommunityId,\n chi: ChannelId,\n tr: Type.Optional(MessageIndex),\n m: MessageIndex,\n e: EventIndex,\n cn: Type.String(),\n chn: Type.String(),\n ti: UserId,\n tn: Type.String(),\n td: Type.Optional(Type.String()),\n t: Type.String(),\n ca: Type.Optional(Type.BigInt()),\n cha: Type.Optional(Type.BigInt()),\n});\nexport const MessageMatch = Type.Object({\n message_index: MessageIndex,\n score: Type.Number(),\n});\nexport const OptionUpdateStreakInsurance = Type.Union([\n Type.Literal(\"NoChange\"),\n Type.Literal(\"SetToNone\"),\n Type.Object({\n SetToSome: StreakInsurance,\n }),\n], { default: \"NoChange\" });\nexport const DirectChatCreated = Type.Record(Type.String(), Type.Never());\nexport const UserOrAccount = Type.Union([\n Type.Object({\n User: UserId,\n }),\n Type.Object({\n Account: Type.Tuple([\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n ]),\n }),\n]);\nexport const VerifiedCredentialGateArgs = Type.Object({\n user_ii_principal: TSPrincipal,\n credential_jwt: Type.String(),\n credential_jwts: Type.Array(Type.String()),\n ii_origin: Type.String(),\n});\nexport const GovernanceProposalsSubtype = Type.Object({\n is_nns: Type.Boolean(),\n governance_canister_id: TSPrincipal,\n});\nexport const GroupInviteCodeChange = Type.Union([\n Type.Literal(\"Enabled\"),\n Type.Literal(\"Disabled\"),\n Type.Literal(\"Reset\"),\n]);\nexport const Version = Type.Number();\nexport const OptionalCommunityPermissions = Type.Object({\n change_roles: Type.Optional(CommunityPermissionRole),\n update_details: Type.Optional(CommunityPermissionRole),\n invite_users: Type.Optional(CommunityPermissionRole),\n remove_members: Type.Optional(CommunityPermissionRole),\n create_public_channel: Type.Optional(CommunityPermissionRole),\n create_private_channel: Type.Optional(CommunityPermissionRole),\n manage_user_groups: Type.Optional(CommunityPermissionRole),\n});\nexport const CommunityMembership = Type.Object({\n joined: Type.BigInt(),\n role: CommunityRole,\n rules_accepted: Type.Boolean(),\n display_name: Type.Optional(Type.String()),\n lapsed: Type.Boolean(),\n});\nexport const VerifiedCredentialArgumentValue = Type.Union([\n Type.Object({\n String: Type.String(),\n }),\n Type.Object({\n Int: Type.Number(),\n }),\n]);\nexport const BotPermissions = Type.Object({\n community: Type.Optional(Type.Number()),\n chat: Type.Optional(Type.Number()),\n message: Type.Optional(Type.Number()),\n});\nexport const DateTimeParam = Type.Object({\n future_only: Type.Boolean(),\n});\nexport const P2PSwapCancelled = Type.Object({\n token0_txn_out: Type.Optional(Type.BigInt()),\n});\nexport const FailedCryptoTransactionNNS = Type.Object({\n ledger: TSPrincipal,\n token: Cryptocurrency,\n amount: Tokens,\n fee: Tokens,\n from: CryptoAccountNNS,\n to: CryptoAccountNNS,\n memo: Type.BigInt(),\n created: Type.BigInt(),\n transaction_hash: Type.Tuple([\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n ]),\n error_message: Type.String(),\n});\nexport const TextContent = Type.Object({\n text: Type.String(),\n});\nexport const MessageId = Type.BigInt();\nexport const AutonomousConfig = Type.Object({\n permissions: BotPermissions,\n sync_api_key: Type.Boolean(),\n});\nexport const UsersBlocked = Type.Object({\n user_ids: Type.Array(UserId),\n blocked_by: UserId,\n});\nexport const BotCommandOptionChoiceString = Type.Object({\n name: Type.String(),\n value: Type.String(),\n});\nexport const CommunityMember = Type.Object({\n user_id: UserId,\n date_added: Type.BigInt(),\n role: CommunityRole,\n display_name: Type.Optional(Type.String()),\n referred_by: Type.Optional(UserId),\n lapsed: Type.Boolean(),\n});\nexport const User = Type.Object({\n user_id: UserId,\n username: Type.String(),\n});\nexport const MessageReport = Type.Object({\n reported_by: UserId,\n timestamp: Type.BigInt(),\n reason_code: Type.Number(),\n notes: Type.Optional(Type.String()),\n});\nexport const ThreadSummary = Type.Object({\n participant_ids: Type.Array(UserId),\n followed_by_me: Type.Boolean(),\n reply_count: Type.Number(),\n latest_event_index: EventIndex,\n latest_event_timestamp: Type.BigInt(),\n});\nexport const CustomPermission = Type.Object({\n subtype: Type.String(),\n role: GroupPermissionRole,\n});\nexport const SuspensionDetails = Type.Object({\n reason: Type.String(),\n action: SuspensionAction,\n suspended_by: UserId,\n});\nexport const TSBytes = Type.Union([Type.Uint8Array(), Type.Array(Type.Number())]);\nexport const UpdatedRules = Type.Object({\n text: Type.String(),\n enabled: Type.Boolean(),\n new_version: Type.Boolean(),\n});\nexport const OptionUpdateString = Type.Union([\n Type.Literal(\"NoChange\"),\n Type.Literal(\"SetToNone\"),\n Type.Object({\n SetToSome: Type.String(),\n }),\n], { default: \"NoChange\" });\nexport const DecimalParam = Type.Object({\n min_value: Type.Number(),\n max_value: Type.Number(),\n choices: Type.Array(BotCommandOptionChoiceF64),\n});\nexport const DiamondMembershipStatus = Type.Union([\n Type.Literal(\"Inactive\"),\n Type.Literal(\"Active\"),\n Type.Literal(\"Lifetime\"),\n]);\nexport const PollConfig = Type.Object({\n text: Type.Optional(Type.String()),\n options: Type.Array(Type.String()),\n end_date: Type.Optional(Type.BigInt()),\n anonymous: Type.Boolean(),\n show_votes_before_end_date: Type.Boolean(),\n allow_multiple_votes_per_user: Type.Boolean(),\n allow_user_to_change_vote: Type.Boolean(),\n});\nexport const Tally = Type.Object({\n yes: Type.BigInt(),\n no: Type.BigInt(),\n total: Type.BigInt(),\n timestamp: Type.BigInt(),\n});\nexport const CryptoTransferDetails = Type.Object({\n r: UserId,\n u: Type.Optional(Type.String()),\n l: TSPrincipal,\n s: Type.String(),\n a: Type.BigInt(),\n});\nexport const DiamondMembershipFeesByDuration = Type.Object({\n one_month: Type.BigInt(),\n three_months: Type.BigInt(),\n one_year: Type.BigInt(),\n lifetime: Type.BigInt(),\n});\nexport const UserGroupSummary = Type.Object({\n user_group_id: Type.Number(),\n name: Type.String(),\n members: Type.Number(),\n});\nexport const DiamondMembershipSubscription = Type.Union([\n Type.Literal(\"Disabled\"),\n Type.Literal(\"OneMonth\"),\n Type.Literal(\"ThreeMonths\"),\n Type.Literal(\"OneYear\"),\n]);\nexport const MemberLeft = Type.Object({\n user_id: UserId,\n});\nexport const BotAdded = Type.Object({\n user_id: UserId,\n added_by: UserId,\n});\nexport const UserGroupDetails = Type.Object({\n user_group_id: Type.Number(),\n name: Type.String(),\n members: Type.Array(UserId),\n});\nexport const GroupIndexFreezeGroupSuspensionDetails = Type.Object({\n duration: Type.Optional(Type.BigInt()),\n reason: Type.String(),\n});\nexport const GroupIndexAddHotGroupExclusionResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"ChatAlreadyExcluded\"),\n Type.Literal(\"ChatNotFound\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupIndexMarkLocalGroupIndexFullArgs = Type.Object({\n canister_id: TSPrincipal,\n full: Type.Boolean(),\n});\nexport const GroupIndexMarkLocalGroupIndexFullResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"LocalGroupIndexNotFound\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n]);\nexport const GroupIndexLookupChannelByGroupIdSuccessResult = Type.Object({\n community_id: CommunityId,\n channel_id: ChannelId,\n});\nexport const GroupIndexLookupChannelByGroupIdResponse = Type.Union([\n Type.Object({\n Success: GroupIndexLookupChannelByGroupIdSuccessResult,\n }),\n Type.Literal(\"NotFound\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupIndexExploreCommunitiesArgs = Type.Object({\n search_term: Type.Optional(Type.String()),\n languages: Type.Array(Type.String()),\n page_index: Type.Number(),\n page_size: Type.Number(),\n include_moderation_flags: Type.Number(),\n});\nexport const GroupIndexUnfreezeCommunityArgs = Type.Object({\n community_id: CommunityId,\n});\nexport const GroupIndexFreezeCommunitySuspensionDetails = Type.Object({\n duration: Type.Optional(Type.BigInt()),\n reason: Type.String(),\n});\nexport const GroupIndexSetGroupUpgradeConcurrencyResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n]);\nexport const GroupIndexSetGroupUpgradeConcurrencyArgs = Type.Object({\n value: Type.Number(),\n});\nexport const GroupIndexDeleteFrozenGroupResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"ChatNotFrozen\"),\n Type.Literal(\"ChatNotFound\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n]);\nexport const GroupIndexSetCommunityModerationFlagsResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"Unchanged\"),\n Type.Literal(\"CommunityNotFound\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"InvalidFlags\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n]);\nexport const GroupIndexSetCommunityModerationFlagsArgs = Type.Object({\n community_id: CommunityId,\n flags: Type.Number(),\n});\nexport const GroupIndexRemoveHotGroupExclusionResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"ChatNotExcluded\"),\n Type.Literal(\"ChatNotFound\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n]);\nexport const GroupIndexExploreGroupsArgs = Type.Object({\n search_term: Type.Optional(Type.String()),\n page_index: Type.Number(),\n page_size: Type.Number(),\n});\nexport const GroupIndexSetCommunityUpgradeConcurrencyResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n]);\nexport const GroupIndexSetCommunityUpgradeConcurrencyArgs = Type.Object({\n value: Type.Number(),\n});\nexport const StorageIndexCanForwardArgs = Type.Object({\n file_hash: Type.Tuple([\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n ]),\n file_size: Type.BigInt(),\n});\nexport const StorageIndexUserUserRecord = Type.Object({\n byte_limit: Type.BigInt(),\n bytes_used: Type.BigInt(),\n});\nexport const StorageIndexUserResponse = Type.Union([\n Type.Object({\n Success: StorageIndexUserUserRecord,\n }),\n Type.Literal(\"UserNotFound\"),\n]);\nexport const StorageIndexProjectedAllowance = Type.Object({\n byte_limit: Type.BigInt(),\n bytes_used: Type.BigInt(),\n bytes_used_after_upload: Type.BigInt(),\n bytes_used_after_operation: Type.BigInt(),\n});\nexport const StorageIndexAllocationBucketSuccessResult = Type.Object({\n canister_id: TSPrincipal,\n file_id: Type.BigInt(),\n chunk_size: Type.Number(),\n byte_limit: Type.BigInt(),\n bytes_used: Type.BigInt(),\n bytes_used_after_upload: Type.BigInt(),\n projected_allowance: StorageIndexProjectedAllowance,\n});\nexport const StorageIndexAllocationBucketResponse = Type.Union([\n Type.Object({\n Success: StorageIndexAllocationBucketSuccessResult,\n }),\n Type.Object({\n AllowanceExceeded: StorageIndexProjectedAllowance,\n }),\n Type.Literal(\"UserNotFound\"),\n Type.Literal(\"BucketUnavailable\"),\n]);\nexport const StorageIndexAllocationBucketArgs = Type.Object({\n file_hash: Type.Tuple([\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n ]),\n file_size: Type.BigInt(),\n file_id_seed: Type.Optional(Type.BigInt()),\n});\nexport const RegistryAddMessageFilterArgs = Type.Object({\n regex: Type.String(),\n});\nexport const RegistryAddMessageFilterResponse = Type.Union([\n Type.Object({\n Success: Type.BigInt(),\n }),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"AlreadyAdded\"),\n Type.Object({\n InvalidRequest: Type.String(),\n }),\n Type.Object({\n InternalError: Type.String(),\n }),\n]);\nexport const RegistrySetAirdropConfigResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"IncompleteConfig\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n]);\nexport const RegistrySetAirdropConfigArgs = Type.Object({\n enabled: Type.Optional(Type.Boolean()),\n community_id: Type.Optional(CommunityId),\n channel_id: Type.Optional(ChannelId),\n community_name: Type.Optional(Type.String()),\n channel_name: Type.Optional(Type.String()),\n});\nexport const RegistryMessageFilterSummary = Type.Object({\n id: Type.BigInt(),\n regex: Type.String(),\n});\nexport const RegistryRemoveMessageFilterResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"NotFound\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n]);\nexport const RegistryRemoveMessageFilterArgs = Type.Object({\n id: Type.BigInt(),\n});\nexport const RegistryNervousSystemSummary = Type.Object({\n root_canister_id: TSPrincipal,\n governance_canister_id: TSPrincipal,\n ledger_canister_id: TSPrincipal,\n index_canister_id: TSPrincipal,\n is_nns: Type.Boolean(),\n proposal_rejection_fee: Type.BigInt(),\n submitting_proposals_enabled: Type.Boolean(),\n});\nexport const RegistryAddRemoveSwapProviderResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n]);\nexport const RegistryAddRemoveSwapProviderArgs = Type.Object({\n swap_provider: ExchangeId,\n add: Type.Boolean(),\n});\nexport const RegistryPayment = Type.Object({\n amount: Type.BigInt(),\n block_index: Type.BigInt(),\n timestamp: Type.BigInt(),\n user_id: UserId,\n});\nexport const RegistryUpdatesArgs = Type.Object({\n since: Type.Optional(Type.BigInt()),\n});\nexport const RegistrySetTokenEnabledResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n]);\nexport const RegistrySetTokenEnabledArgs = Type.Object({\n ledger_canister_id: TSPrincipal,\n enabled: Type.Boolean(),\n});\nexport const RegistryTokenDetails = Type.Object({\n ledger_canister_id: TSPrincipal,\n name: Type.String(),\n symbol: Type.String(),\n decimals: Type.Number(),\n fee: Type.BigInt(),\n logo: Type.String(),\n logo_id: Type.Optional(Type.BigInt()),\n info_url: Type.String(),\n transaction_url_format: Type.String(),\n supported_standards: Type.Array(Type.String()),\n added: Type.BigInt(),\n enabled: Type.Boolean(),\n last_updated: Type.BigInt(),\n payments: Type.Array(RegistryPayment),\n});\nexport const UserIndexDiamondMembershipFeesDiamondMembershipFees = Type.Object({\n token_symbol: Type.String(),\n one_month: Type.BigInt(),\n three_months: Type.BigInt(),\n one_year: Type.BigInt(),\n lifetime: Type.BigInt(),\n});\nexport const UserIndexUsersChitSuccessResult = Type.Object({\n chit: Type.Array(Chit),\n});\nexport const UserIndexUsersChitArgs = Type.Object({\n users: Type.Array(UserId),\n year: Type.Number(),\n month: Type.Number(),\n});\nexport const UserIndexPublicKeyResponse = Type.Union([\n Type.Object({\n Success: Type.String(),\n }),\n Type.Literal(\"NotInitialised\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserIndexUpdateDiamondMembershipSubscriptionArgs = Type.Object({\n pay_in_chat: Type.Optional(Type.Boolean()),\n subscription: Type.Optional(DiamondMembershipSubscription),\n});\nexport const UserIndexUpdateDiamondMembershipSubscriptionResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NotDiamondMember\"),\n Type.Literal(\"AlreadyLifetimeDiamondMember\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserIndexSuspendUserResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"UserAlreadySuspended\"),\n Type.Literal(\"UserNotFound\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserIndexSuspendUserArgs = Type.Object({\n user_id: UserId,\n duration: Type.Optional(Type.BigInt()),\n reason: Type.String(),\n});\nexport const UserIndexCheckUsernameResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"UsernameTaken\"),\n Type.Literal(\"UsernameInvalid\"),\n Type.Object({\n UsernameTooShort: Type.Number(),\n }),\n Type.Object({\n UsernameTooLong: Type.Number(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserIndexCheckUsernameArgs = Type.Object({\n username: Type.String(),\n is_bot: Type.Boolean(),\n});\nexport const UserIndexSetModerationFlagsArgs = Type.Object({\n moderation_flags_enabled: Type.Number(),\n});\nexport const UserIndexSetModerationFlagsResponse = Type.Literal(\"Success\");\nexport const UserIndexPlatformOperatorsSuccessResult = Type.Object({\n users: Type.Array(UserId),\n});\nexport const UserIndexPlatformOperatorsResponse = Type.Object({\n Success: UserIndexPlatformOperatorsSuccessResult,\n});\nexport const UserIndexPlatformModeratorsSuccessResult = Type.Object({\n users: Type.Array(UserId),\n});\nexport const UserIndexSetUserUpgradeConcurrencyArgs = Type.Object({\n value: Type.Number(),\n});\nexport const UserIndexSetUserUpgradeConcurrencyResponse = Type.Literal(\"Success\");\nexport const UserIndexSuspectedBotsSuccessResult = Type.Object({\n users: Type.Array(UserId),\n});\nexport const UserIndexSuspectedBotsArgs = Type.Object({\n after: Type.Optional(UserId),\n count: Type.Number(),\n});\nexport const UserIndexExternalAchievementsExternalAchievement = Type.Object({\n id: Type.Number(),\n name: Type.String(),\n url: Type.String(),\n chit_reward: Type.Number(),\n expires: Type.BigInt(),\n budget_exhausted: Type.Boolean(),\n});\nexport const UserIndexExternalAchievementsArgs = Type.Object({\n updates_since: Type.BigInt(),\n});\nexport const UserIndexUserArgs = Type.Object({\n user_id: Type.Optional(UserId),\n username: Type.Optional(Type.String()),\n});\nexport const UserIndexBotUpdatesArgs = Type.Object({\n updated_since: Type.BigInt(),\n});\nexport const UserIndexReferralMetricsReferralMetrics = Type.Object({\n users_who_referred: Type.Number(),\n users_who_referred_paid_diamond: Type.Number(),\n users_who_referred_unpaid_diamond: Type.Number(),\n users_who_referred_90_percent_unpaid_diamond: Type.Number(),\n referrals_of_paid_diamond: Type.Number(),\n referrals_of_unpaid_diamond: Type.Number(),\n referrals_other: Type.Number(),\n icp_raised_by_referrals_to_paid_diamond: Type.Number(),\n});\nexport const UserIndexPayForDiamondMembershipSuccessResult = Type.Object({\n expires_at: Type.BigInt(),\n pay_in_chat: Type.Boolean(),\n subscription: DiamondMembershipSubscription,\n proof_jwt: Type.String(),\n});\nexport const UserIndexPayForDiamondMembershipResponse = Type.Union([\n Type.Object({\n Success: UserIndexPayForDiamondMembershipSuccessResult,\n }),\n Type.Literal(\"AlreadyLifetimeDiamondMember\"),\n Type.Literal(\"CurrencyNotSupported\"),\n Type.Literal(\"PriceMismatch\"),\n Type.Literal(\"PaymentAlreadyInProgress\"),\n Type.Literal(\"UserNotFound\"),\n Type.Object({\n InsufficientFunds: Type.BigInt(),\n }),\n Type.Object({\n TransferFailed: Type.String(),\n }),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserIndexPayForDiamondMembershipArgs = Type.Object({\n duration: DiamondMembershipPlanDuration,\n ledger: TSPrincipal,\n expected_price_e8s: Type.BigInt(),\n recurring: Type.Boolean(),\n});\nexport const UserIndexSearchArgs = Type.Object({\n search_term: Type.String(),\n max_results: Type.Number(),\n});\nexport const UserIndexDeleteUserResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n MalformedSignature: Type.String(),\n }),\n Type.Literal(\"DelegationTooOld\"),\n Type.Literal(\"UserNotFound\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserIndexRemoveBotArgs = Type.Object({\n bot_id: UserId,\n});\nexport const UserIndexRemoveBotResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"BotNotFound\"),\n Type.Literal(\"NotAuthorised\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserIndexUnsuspendUserArgs = Type.Object({\n user_id: UserId,\n});\nexport const UserIndexUnsuspendUserResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"UserNotSuspended\"),\n Type.Literal(\"UserNotFound\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserIndexUsersUserGroup = Type.Object({\n users: Type.Array(UserId),\n updated_since: Type.BigInt(),\n});\nexport const UserIndexUsersArgs = Type.Object({\n user_groups: Type.Array(UserIndexUsersUserGroup),\n users_suspended_since: Type.Optional(Type.BigInt()),\n});\nexport const UserIndexSubmitProofOfUniquePersonhoodResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Object({\n Invalid: Type.String(),\n }),\n Type.Literal(\"UserNotFound\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserIndexSubmitProofOfUniquePersonhoodArgs = Type.Object({\n user_ii_principal: TSPrincipal,\n credential_jwt: Type.String(),\n});\nexport const UserIndexChitLeaderboardChitUserBalance = Type.Object({\n user_id: UserId,\n username: Type.String(),\n balance: Type.Number(),\n});\nexport const UserIndexSetUsernameResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"UsernameTaken\"),\n Type.Literal(\"UserNotFound\"),\n Type.Literal(\"UsernameInvalid\"),\n Type.Object({\n UsernameTooShort: Type.Number(),\n }),\n Type.Object({\n UsernameTooLong: Type.Number(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserIndexSetUsernameArgs = Type.Object({\n username: Type.String(),\n});\nexport const UserIndexUpdateBotResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"PrincipalInvalid\"),\n Type.Literal(\"PrincipalAlreadyUsed\"),\n Type.Literal(\"AvatarInvalid\"),\n Type.Literal(\"EndpointInvalid\"),\n Type.Literal(\"BotNotFound\"),\n Type.Literal(\"BotSuspended\"),\n Type.Literal(\"NotAuthorised\"),\n Type.Literal(\"OwnerNotFound\"),\n Type.Literal(\"OwnerSuspended\"),\n Type.Literal(\"NewOwnerNotFound\"),\n Type.Literal(\"NewOwnerSuspended\"),\n Type.Literal(\"DescriptionTooLong\"),\n Type.Literal(\"TooManyCommands\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserIndexSetDisplayNameResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"UserNotFound\"),\n Type.Literal(\"DisplayNameInvalid\"),\n Type.Object({\n DisplayNameTooShort: Type.Number(),\n }),\n Type.Object({\n DisplayNameTooLong: Type.Number(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserIndexSetDisplayNameArgs = Type.Object({\n display_name: Type.Optional(Type.String()),\n});\nexport const UserIndexSetDiamondMembershipFeesResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"Invalid\"),\n]);\nexport const UserIndexRegisterBotSuccessResult = Type.Object({\n bot_id: UserId,\n});\nexport const UserIndexReportedMessagesArgs = Type.Object({\n user_id: Type.Optional(UserId),\n});\nexport const UserIndexReportedMessagesSuccessResult = Type.Object({\n json: Type.String(),\n});\nexport const UserIndexReportedMessagesResponse = Type.Object({\n Success: UserIndexReportedMessagesSuccessResult,\n});\nexport const UserIndexUserRegistrationCanisterResponse = Type.Union([\n Type.Object({\n Success: TSPrincipal,\n }),\n Type.Literal(\"NewRegistrationsClosed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const LocalUserIndexInviteUsersToCommunityArgs = Type.Object({\n community_id: CommunityId,\n user_ids: Type.Array(UserId),\n caller_username: Type.String(),\n});\nexport const LocalUserIndexInviteUsersToCommunityResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Object({\n TooManyInvites: Type.Number(),\n }),\n Type.Literal(\"UserSuspended\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const LocalUserIndexInstallBotResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"Frozen\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"AlreadyAdded\"),\n Type.Literal(\"NotFound\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const LocalUserIndexInviteUsersToGroupResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"GroupNotFound\"),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Object({\n TooManyInvites: Type.Number(),\n }),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const LocalUserIndexBotCreateChannelSuccessResult = Type.Object({\n channel_id: ChannelId,\n});\nexport const LocalUserIndexBotCreateChannelResponse = Type.Union([\n Type.Object({\n Success: LocalUserIndexBotCreateChannelSuccessResult,\n }),\n Type.Object({\n FailedAuthentication: Type.String(),\n }),\n Type.Object({\n InvalidRequest: Type.String(),\n }),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"Frozen\"),\n Type.Object({\n C2CError: Type.Tuple([Type.Number(), Type.String()]),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const LocalUserIndexBotDeleteChannelArgs = Type.Object({\n channel_id: ChannelId,\n auth_token: AuthToken,\n});\nexport const LocalUserIndexBotDeleteChannelResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Object({\n FailedAuthentication: Type.String(),\n }),\n Type.Object({\n InvalidRequest: Type.String(),\n }),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"Frozen\"),\n Type.Object({\n C2CError: Type.Tuple([Type.Number(), Type.String()]),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const LocalUserIndexUninstallBotResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const LocalUserIndexRegisterUserArgs = Type.Object({\n username: Type.String(),\n referral_code: Type.Optional(Type.String()),\n public_key: TSBytes,\n});\nexport const LocalUserIndexRegisterUserSuccessResult = Type.Object({\n user_id: UserId,\n icp_account: Type.Tuple([\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n ]),\n});\nexport const LocalUserIndexWithdrawFromIcpswapArgs = Type.Object({\n user_id: UserId,\n swap_id: Type.BigInt(),\n input_token: Type.Boolean(),\n amount: Type.Optional(Type.BigInt()),\n fee: Type.Optional(Type.BigInt()),\n});\nexport const LocalUserIndexWithdrawFromIcpswapResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"UserNotFound\"),\n Type.Literal(\"SwapNotFound\"),\n Type.Literal(\"AmountNotSpecified\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const LocalUserIndexChatEventsEventsByIndexArgs = Type.Object({\n events: Type.Array(EventIndex),\n});\nexport const LocalUserIndexChatEventsEventsWindowArgs = Type.Object({\n mid_point: MessageIndex,\n max_messages: Type.Number(),\n max_events: Type.Number(),\n});\nexport const LocalUserIndexChatEventsEventsPageArgs = Type.Object({\n start_index: EventIndex,\n ascending: Type.Boolean(),\n max_messages: Type.Number(),\n max_events: Type.Number(),\n});\nexport const LocalUserIndexJoinCommunityArgs = Type.Object({\n community_id: CommunityId,\n invite_code: Type.Optional(Type.BigInt()),\n referred_by: Type.Optional(UserId),\n verified_credential_args: Type.Optional(VerifiedCredentialGateArgs),\n});\nexport const LocalUserIndexJoinChannelArgs = Type.Object({\n community_id: CommunityId,\n channel_id: ChannelId,\n invite_code: Type.Optional(Type.BigInt()),\n referred_by: Type.Optional(UserId),\n verified_credential_args: Type.Optional(VerifiedCredentialGateArgs),\n});\nexport const LocalUserIndexBotChatDetailsArgs = Type.Object({\n channel_id: Type.Optional(ChannelId),\n auth_token: AuthToken,\n});\nexport const LocalUserIndexInviteUsersToChannelFailedResult = Type.Object({\n failed_users: Type.Array(UserId),\n});\nexport const LocalUserIndexInviteUsersToChannelPartialSuccessResult = Type.Object({\n failed_users: Type.Array(UserId),\n});\nexport const LocalUserIndexInviteUsersToChannelArgs = Type.Object({\n community_id: CommunityId,\n channel_id: ChannelId,\n user_ids: Type.Array(UserId),\n caller_username: Type.String(),\n});\nexport const LocalUserIndexAccessTokenV2Response = Type.Union([\n Type.Object({\n Success: Type.String(),\n }),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const LocalUserIndexReportMessageResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const LocalUserIndexBotSendMessageSuccessResult = Type.Object({\n message_id: MessageId,\n event_index: EventIndex,\n message_index: MessageIndex,\n timestamp: Type.BigInt(),\n expires_at: Type.Optional(Type.BigInt()),\n});\nexport const LocalUserIndexGroupAndCommunitySummaryUpdatesSummaryUpdatesArgs = Type.Object({\n canister_id: TSPrincipal,\n is_community: Type.Boolean(),\n invite_code: Type.Optional(Type.BigInt()),\n updates_since: Type.Optional(Type.BigInt()),\n});\nexport const CommunitySummaryUpdatesArgs = Type.Object({\n invite_code: Type.Optional(Type.BigInt()),\n updates_since: Type.BigInt(),\n});\nexport const CommunitySelectedChannelUpdatesArgs = Type.Object({\n channel_id: ChannelId,\n updates_since: Type.BigInt(),\n});\nexport const CommunityLeaveChannelResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"LastOwnerCannotLeave\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityLeaveChannelArgs = Type.Object({\n channel_id: ChannelId,\n});\nexport const CommunityRemoveMemberArgs = Type.Object({\n user_id: UserId,\n});\nexport const CommunityRemoveMemberResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"CannotRemoveSelf\"),\n Type.Literal(\"CannotRemoveUser\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"TargetUserNotInCommunity\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityToggleMuteNotificationsResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityToggleMuteNotificationsArgs = Type.Object({\n channel_id: Type.Optional(ChannelId),\n mute: Type.Boolean(),\n});\nexport const CommunityClaimPrizeArgs = Type.Object({\n channel_id: ChannelId,\n message_id: MessageId,\n});\nexport const CommunityCancelInvitesResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityCancelInvitesArgs = Type.Object({\n channel_id: Type.Optional(ChannelId),\n user_ids: Type.Array(UserId),\n});\nexport const CommunityCreateUserGroupArgs = Type.Object({\n name: Type.String(),\n user_ids: Type.Array(UserId),\n});\nexport const CommunityCreateUserGroupSuccessResult = Type.Object({\n user_group_id: Type.Number(),\n});\nexport const CommunityCreateUserGroupResponse = Type.Union([\n Type.Object({\n Success: CommunityCreateUserGroupSuccessResult,\n }),\n Type.Object({\n NameTooShort: FieldTooShortResult,\n }),\n Type.Object({\n NameTooLong: FieldTooLongResult,\n }),\n Type.Literal(\"NameInvalid\"),\n Type.Literal(\"NameTaken\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityJoinVideoCallArgs = Type.Object({\n channel_id: ChannelId,\n message_id: MessageId,\n new_achievement: Type.Boolean(),\n});\nexport const CommunitySetVideoCallPresenceArgs = Type.Object({\n channel_id: ChannelId,\n message_id: MessageId,\n presence: VideoCallPresence,\n new_achievement: Type.Boolean(),\n});\nexport const CommunitySetVideoCallPresenceResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"AlreadyEnded\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityDeletedMessageArgs = Type.Object({\n channel_id: ChannelId,\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n});\nexport const CommunityRegisterPollVoteArgs = Type.Object({\n channel_id: ChannelId,\n thread_root_message_index: Type.Optional(MessageIndex),\n message_index: MessageIndex,\n poll_option: Type.Number(),\n operation: VoteOperation,\n new_achievement: Type.Boolean(),\n});\nexport const CommunityCancelP2pSwapArgs = Type.Object({\n channel_id: ChannelId,\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n});\nexport const CommunitySearchChannelArgs = Type.Object({\n channel_id: ChannelId,\n search_term: Type.String(),\n max_results: Type.Number(),\n users: Type.Optional(Type.Array(UserId)),\n});\nexport const CommunitySearchChannelSuccessResult = Type.Object({\n matches: Type.Array(MessageMatch),\n});\nexport const CommunitySearchChannelResponse = Type.Union([\n Type.Object({\n Success: CommunitySearchChannelSuccessResult,\n }),\n Type.Literal(\"InvalidTerm\"),\n Type.Object({\n TermTooLong: Type.Number(),\n }),\n Type.Object({\n TermTooShort: Type.Number(),\n }),\n Type.Object({\n TooManyUsers: Type.Number(),\n }),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityUndeleteMessagesArgs = Type.Object({\n channel_id: ChannelId,\n thread_root_message_index: Type.Optional(MessageIndex),\n message_ids: Type.Array(MessageId),\n});\nexport const CommunityChangeRoleArgs = Type.Object({\n user_id: UserId,\n new_role: CommunityRole,\n});\nexport const CommunityChangeRoleResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"TargetUserNotInCommunity\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"Invalid\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunitySelectedChannelInitialArgs = Type.Object({\n channel_id: ChannelId,\n});\nexport const CommunityInviteCodeSuccessResult = Type.Object({\n code: Type.Optional(Type.BigInt()),\n});\nexport const CommunityInviteCodeResponse = Type.Union([\n Type.Object({\n Success: CommunityInviteCodeSuccessResult,\n }),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityUnblockUserArgs = Type.Object({\n user_id: UserId,\n});\nexport const CommunityUnblockUserResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"CannotUnblockSelf\"),\n Type.Literal(\"CommunityNotPublic\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityExploreChannelsArgs = Type.Object({\n invite_code: Type.Optional(Type.BigInt()),\n search_term: Type.Optional(Type.String()),\n page_index: Type.Number(),\n page_size: Type.Number(),\n});\nexport const CommunityChannelSummaryUpdatesArgs = Type.Object({\n channel_id: ChannelId,\n invite_code: Type.Optional(Type.BigInt()),\n updates_since: Type.BigInt(),\n});\nexport const CommunityUpdateUserGroupArgs = Type.Object({\n user_group_id: Type.Number(),\n name: Type.Optional(Type.String()),\n users_to_add: Type.Array(UserId),\n users_to_remove: Type.Array(UserId),\n});\nexport const CommunityUpdateUserGroupResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"UserGroupNotFound\"),\n Type.Object({\n NameTooShort: FieldTooShortResult,\n }),\n Type.Object({\n NameTooLong: FieldTooLongResult,\n }),\n Type.Literal(\"NameInvalid\"),\n Type.Literal(\"NameTaken\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityEventsWindowArgs = Type.Object({\n channel_id: ChannelId,\n thread_root_message_index: Type.Optional(MessageIndex),\n mid_point: MessageIndex,\n max_messages: Type.Number(),\n max_events: Type.Number(),\n latest_known_update: Type.Optional(Type.BigInt()),\n});\nexport const CommunityUnfollowThreadArgs = Type.Object({\n channel_id: ChannelId,\n thread_root_message_index: MessageIndex,\n});\nexport const CommunityUnfollowThreadResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NotFollowing\"),\n Type.Literal(\"ThreadNotFound\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityDeleteMessagesResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"NotPlatformModerator\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityDeleteMessagesArgs = Type.Object({\n channel_id: ChannelId,\n thread_root_message_index: Type.Optional(MessageIndex),\n message_ids: Type.Array(MessageId),\n as_platform_moderator: Type.Optional(Type.Boolean()),\n new_achievement: Type.Boolean(),\n});\nexport const CommunityRemoveMemberFromChannelResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"TargetUserNotInCommunity\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"TargetUserNotInChannel\"),\n Type.Literal(\"CannotRemoveSelf\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityRemoveMemberFromChannelArgs = Type.Object({\n channel_id: ChannelId,\n user_id: UserId,\n});\nexport const CommunityEnableInviteCodeSuccessResult = Type.Object({\n code: Type.BigInt(),\n});\nexport const CommunityEnableInviteCodeResponse = Type.Union([\n Type.Object({\n Success: CommunityEnableInviteCodeSuccessResult,\n }),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityCommunityMembersArgs = Type.Object({\n user_ids: Type.Array(UserId),\n});\nexport const CommunityCommunityMembersSuccessResult = Type.Object({\n members: Type.Array(CommunityMember),\n});\nexport const CommunityRegisterProposalVoteArgs = Type.Object({\n channel_id: ChannelId,\n message_index: MessageIndex,\n adopt: Type.Boolean(),\n});\nexport const CommunityRegisterProposalVoteResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Object({\n AlreadyVoted: Type.Boolean(),\n }),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"NoEligibleNeurons\"),\n Type.Literal(\"ProposalMessageNotFound\"),\n Type.Literal(\"ProposalNotFound\"),\n Type.Literal(\"ProposalNotAcceptingVotes\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityAddMembersToChannelUserFailedError = Type.Object({\n user_id: UserId,\n error: Type.String(),\n});\nexport const CommunityAddMembersToChannelArgs = Type.Object({\n channel_id: ChannelId,\n user_ids: Type.Array(UserId),\n added_by_name: Type.String(),\n added_by_display_name: Type.Optional(Type.String()),\n});\nexport const CommunityAddMembersToChannelPartialSuccessResult = Type.Object({\n users_added: Type.Array(UserId),\n users_already_in_channel: Type.Array(UserId),\n users_limit_reached: Type.Array(UserId),\n users_failed_with_error: Type.Array(CommunityAddMembersToChannelUserFailedError),\n});\nexport const CommunityAddMembersToChannelFailedResult = Type.Object({\n users_already_in_channel: Type.Array(UserId),\n users_limit_reached: Type.Array(UserId),\n users_failed_with_error: Type.Array(CommunityAddMembersToChannelUserFailedError),\n});\nexport const CommunityDisableInviteCodeResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityChannelSummaryArgs = Type.Object({\n channel_id: ChannelId,\n invite_code: Type.Optional(Type.BigInt()),\n});\nexport const CommunityGenerateBotApiKeySuccessResult = Type.Object({\n api_key: Type.String(),\n});\nexport const CommunityGenerateBotApiKeyArgs = Type.Object({\n bot_id: UserId,\n requested_permissions: BotPermissions,\n channel_id: Type.Optional(ChannelId),\n});\nexport const CommunityChangeChannelRoleArgs = Type.Object({\n channel_id: ChannelId,\n user_id: UserId,\n new_role: GroupRole,\n});\nexport const CommunityChangeChannelRoleResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"TargetUserNotInChannel\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"Invalid\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityApiKeyResponse = Type.Union([\n Type.Object({\n Success: Type.String(),\n }),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"NotFound\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityApiKeyArgs = Type.Object({\n bot_id: UserId,\n channel_id: Type.Optional(ChannelId),\n});\nexport const CommunityDeclineInvitationArgs = Type.Object({\n channel_id: Type.Optional(ChannelId),\n});\nexport const CommunityDeclineInvitationResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NotInvited\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityMessagesByMessageIndexArgs = Type.Object({\n channel_id: ChannelId,\n thread_root_message_index: Type.Optional(MessageIndex),\n messages: Type.Array(MessageIndex),\n latest_known_update: Type.Optional(Type.BigInt()),\n});\nexport const CommunityRegisterProposalVoteV2Args = Type.Object({\n channel_id: ChannelId,\n message_index: MessageIndex,\n adopt: Type.Boolean(),\n});\nexport const CommunityRegisterProposalVoteV2Response = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"ProposalMessageNotFound\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityDeleteUserGroupsResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityDeleteUserGroupsArgs = Type.Object({\n user_group_ids: Type.Array(Type.Number()),\n});\nexport const CommunityUpdateCommunitySuccessResult = Type.Object({\n rules_version: Type.Optional(Version),\n});\nexport const CommunityUpdateCommunityResponse = Type.Union([\n Type.Object({\n SuccessV2: CommunityUpdateCommunitySuccessResult,\n }),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Object({\n NameTooShort: FieldTooShortResult,\n }),\n Type.Object({\n NameTooLong: FieldTooLongResult,\n }),\n Type.Literal(\"NameReserved\"),\n Type.Object({\n DescriptionTooLong: FieldTooLongResult,\n }),\n Type.Object({\n AvatarTooBig: FieldTooLongResult,\n }),\n Type.Object({\n BannerTooBig: FieldTooLongResult,\n }),\n Type.Literal(\"AccessGateInvalid\"),\n Type.Literal(\"NameTaken\"),\n Type.Literal(\"InternalError\"),\n Type.Object({\n RulesTooLong: FieldTooLongResult,\n }),\n Type.Object({\n RulesTooShort: FieldTooShortResult,\n }),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"InvalidLanguage\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityRemoveReactionArgs = Type.Object({\n channel_id: ChannelId,\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n reaction: Reaction,\n});\nexport const CommunityRemoveReactionResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NoChange\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunitySelectedInitialArgs = Type.Object({\n invite_code: Type.Optional(Type.BigInt()),\n});\nexport const CommunityAddReactionArgs = Type.Object({\n channel_id: ChannelId,\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n reaction: Reaction,\n username: Type.String(),\n display_name: Type.Optional(Type.String()),\n new_achievement: Type.Boolean(),\n});\nexport const CommunityAddReactionResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NoChange\"),\n Type.Literal(\"InvalidReaction\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityThreadPreviewsArgs = Type.Object({\n channel_id: ChannelId,\n threads: Type.Array(MessageIndex),\n latest_client_thread_update: Type.Optional(Type.BigInt()),\n});\nexport const CommunityBlockUserResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"CannotBlockSelf\"),\n Type.Literal(\"CannotBlockUser\"),\n Type.Literal(\"CommunityNotPublic\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"TargetUserNotInCommunity\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityBlockUserArgs = Type.Object({\n user_id: UserId,\n});\nexport const CommunityPinMessageArgs = Type.Object({\n channel_id: ChannelId,\n message_index: MessageIndex,\n});\nexport const CommunityPinMessageResponse = Type.Union([\n Type.Object({\n Success: PushEventResult,\n }),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"NoChange\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityVideoCallParticipantsArgs = Type.Object({\n channel_id: ChannelId,\n message_id: MessageId,\n updated_since: Type.Optional(Type.BigInt()),\n});\nexport const CommunitySendMessageSuccessResult = Type.Object({\n event_index: EventIndex,\n message_index: MessageIndex,\n timestamp: Type.BigInt(),\n expires_at: Type.Optional(Type.BigInt()),\n});\nexport const CommunitySendMessageResponse = Type.Union([\n Type.Object({\n Success: CommunitySendMessageSuccessResult,\n }),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"ThreadMessageNotFound\"),\n Type.Literal(\"MessageEmpty\"),\n Type.Object({\n TextTooLong: Type.Number(),\n }),\n Type.Object({\n InvalidPoll: InvalidPollReason,\n }),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"UserSuspended\"),\n Type.Object({\n InvalidRequest: Type.String(),\n }),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"RulesNotAccepted\"),\n Type.Literal(\"MessageAlreadyExists\"),\n Type.Literal(\"CommunityRulesNotAccepted\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityEventsByIndexArgs = Type.Object({\n channel_id: ChannelId,\n thread_root_message_index: Type.Optional(MessageIndex),\n events: Type.Array(EventIndex),\n latest_known_update: Type.Optional(Type.BigInt()),\n});\nexport const CommunityLocalUserIndexResponse = Type.Object({\n Success: TSPrincipal,\n});\nexport const CommunityEventsArgs = Type.Object({\n channel_id: ChannelId,\n thread_root_message_index: Type.Optional(MessageIndex),\n start_index: EventIndex,\n ascending: Type.Boolean(),\n max_messages: Type.Number(),\n max_events: Type.Number(),\n latest_known_update: Type.Optional(Type.BigInt()),\n});\nexport const CommunityUpdateBotArgs = Type.Object({\n bot_id: UserId,\n granted_permissions: BotPermissions,\n});\nexport const CommunityUpdateBotResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"NotFound\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityAcceptP2pSwapArgs = Type.Object({\n channel_id: ChannelId,\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n pin: Type.Optional(PinNumberWrapper),\n new_achievement: Type.Boolean(),\n});\nexport const CommunityCreateChannelSuccessResult = Type.Object({\n channel_id: ChannelId,\n});\nexport const CommunitySelectedUpdatesArgs = Type.Object({\n invite_code: Type.Optional(Type.BigInt()),\n updates_since: Type.BigInt(),\n});\nexport const CommunityImportGroupSuccessResult = Type.Object({\n channel_id: ChannelId,\n total_bytes: Type.BigInt(),\n});\nexport const CommunityImportGroupResponse = Type.Union([\n Type.Object({\n Success: CommunityImportGroupSuccessResult,\n }),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserNotCommunityOwner\"),\n Type.Literal(\"UserNotInGroup\"),\n Type.Literal(\"UserNotGroupOwner\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"GroupNotFound\"),\n Type.Literal(\"GroupAlreadyBeingImported\"),\n Type.Literal(\"GroupImportingToAnotherCommunity\"),\n Type.Literal(\"GroupFrozen\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityReportMessageArgs = Type.Object({\n channel_id: ChannelId,\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n delete: Type.Boolean(),\n});\nexport const CommunityReportMessageResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"AlreadyReported\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityEditMessageResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityUpdateChannelSuccessResult = Type.Object({\n rules_version: Type.Optional(Version),\n});\nexport const CommunitySetMemberDisplayNameArgs = Type.Object({\n display_name: Type.Optional(Type.String()),\n new_achievement: Type.Boolean(),\n});\nexport const CommunitySetMemberDisplayNameResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"DisplayNameInvalid\"),\n Type.Object({\n DisplayNameTooShort: Type.Number(),\n }),\n Type.Object({\n DisplayNameTooLong: Type.Number(),\n }),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunitySummaryArgs = Type.Object({\n invite_code: Type.Optional(Type.BigInt()),\n});\nexport const CommunityFollowThreadResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"AlreadyFollowing\"),\n Type.Literal(\"ThreadNotFound\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityFollowThreadArgs = Type.Object({\n channel_id: ChannelId,\n thread_root_message_index: MessageIndex,\n new_achievement: Type.Boolean(),\n});\nexport const CommunityDeleteChannelResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityDeleteChannelArgs = Type.Object({\n channel_id: ChannelId,\n});\nexport const NotificationsIndexPushSubscriptionResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n]);\nexport const NotificationsIndexPushSubscriptionArgs = Type.Object({\n subscription: SubscriptionInfo,\n});\nexport const NotificationsIndexRemoveSubscriptionsForUserResponse = Type.Literal(\"Success\");\nexport const NotificationsIndexSubscriptionExistsArgs = Type.Object({\n p256dh_key: Type.String(),\n});\nexport const NotificationsIndexSubscriptionExistsResponse = Type.Union([\n Type.Literal(\"Yes\"),\n Type.Literal(\"No\"),\n]);\nexport const NotificationsIndexRemoveSubscriptionArgs = Type.Object({\n p256dh_key: Type.String(),\n});\nexport const NotificationsIndexRemoveSubscriptionResponse = Type.Literal(\"Success\");\nexport const StorageBucketDeleteFilesDeleteFileFailureReason = Type.Union([\n Type.Literal(\"NotFound\"),\n Type.Literal(\"NotAuthorized\"),\n]);\nexport const StorageBucketDeleteFilesArgs = Type.Object({\n file_ids: Type.Array(Type.BigInt()),\n});\nexport const StorageBucketDeleteFilesDeleteFileFailure = Type.Object({\n file_id: Type.BigInt(),\n reason: StorageBucketDeleteFilesDeleteFileFailureReason,\n});\nexport const StorageBucketFileInfoArgs = Type.Object({\n file_id: Type.BigInt(),\n});\nexport const StorageBucketFileInfoSuccessResult = Type.Object({\n is_owner: Type.Boolean(),\n file_size: Type.BigInt(),\n file_hash: Type.Tuple([\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n ]),\n});\nexport const StorageBucketFileInfoResponse = Type.Union([\n Type.Object({\n Success: StorageBucketFileInfoSuccessResult,\n }),\n Type.Literal(\"NotFound\"),\n]);\nexport const StorageBucketUploadChunkResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"AllowanceExceeded\"),\n Type.Literal(\"FileAlreadyExists\"),\n Type.Literal(\"FileTooBig\"),\n Type.Literal(\"FileExpired\"),\n Type.Literal(\"ChunkAlreadyExists\"),\n Type.Literal(\"ChunkIndexTooHigh\"),\n Type.Literal(\"ChunkSizeMismatch\"),\n Type.Literal(\"Full\"),\n Type.Literal(\"HashMismatch\"),\n Type.Literal(\"InvalidFileId\"),\n Type.Literal(\"UserNotFound\"),\n]);\nexport const StorageBucketUploadChunkArgs = Type.Object({\n file_id: Type.BigInt(),\n hash: Type.Tuple([\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n ]),\n mime_type: Type.String(),\n accessors: Type.Array(TSPrincipal),\n chunk_index: Type.Number(),\n chunk_size: Type.Number(),\n total_size: Type.BigInt(),\n bytes: TSBytes,\n expiry: Type.Optional(Type.BigInt()),\n});\nexport const StorageBucketDeleteFileResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"NotFound\"),\n]);\nexport const StorageBucketDeleteFileArgs = Type.Object({\n file_id: Type.BigInt(),\n});\nexport const StorageBucketForwardFileResponse = Type.Union([\n Type.Object({\n Success: Type.BigInt(),\n }),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"NotFound\"),\n]);\nexport const StorageBucketForwardFileArgs = Type.Object({\n file_id: Type.BigInt(),\n accessors: Type.Array(TSPrincipal),\n});\nexport const ProposalsBotStakeNeuronForSubmittingProposalsArgs = Type.Object({\n governance_canister_id: TSPrincipal,\n stake: Type.BigInt(),\n});\nexport const ProposalsBotTopUpNeuronArgs = Type.Object({\n governance_canister_id: TSPrincipal,\n amount: Type.BigInt(),\n});\nexport const ProposalsBotExecuteGenericNervousSystemFunction = Type.Object({\n function_id: Type.BigInt(),\n payload: TSBytes,\n});\nexport const ProposalsBotUpgradeSnsControlledCanister = Type.Object({\n canister_id: TSPrincipal,\n new_canister_wasm: TSBytes,\n mode: ProposalsBotCanisterInstallMode,\n});\nexport const OnlineUsersLastOnlineArgs = Type.Object({\n user_ids: Type.Array(UserId),\n});\nexport const OnlineUsersLastOnlineUserLastOnline = Type.Object({\n user_id: UserId,\n duration_since_last_online: Type.BigInt(),\n});\nexport const OnlineUsersMarkAsOnlineResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Object({\n SuccessV2: OnlineUsersMarkAsOnlineSuccessResult,\n }),\n Type.Literal(\"UserNotFound\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n]);\nexport const GroupSearchMessagesArgs = Type.Object({\n search_term: Type.String(),\n max_results: Type.Number(),\n users: Type.Optional(Type.Array(UserId)),\n});\nexport const GroupSearchMessagesSuccessResult = Type.Object({\n matches: Type.Array(MessageMatch),\n});\nexport const GroupSearchMessagesResponse = Type.Union([\n Type.Object({\n Success: GroupSearchMessagesSuccessResult,\n }),\n Type.Literal(\"InvalidTerm\"),\n Type.Object({\n TermTooLong: Type.Number(),\n }),\n Type.Object({\n TermTooShort: Type.Number(),\n }),\n Type.Object({\n TooManyUsers: Type.Number(),\n }),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupConvertIntoCommunitySuccessResult = Type.Object({\n community_id: CommunityId,\n channel_id: ChannelId,\n});\nexport const GroupConvertIntoCommunityResponse = Type.Union([\n Type.Object({\n Success: GroupConvertIntoCommunitySuccessResult,\n }),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Literal(\"AlreadyImportingToAnotherCommunity\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupConvertIntoCommunityArgs = Type.Object({\n rules: Rules,\n permissions: Type.Optional(CommunityPermissions),\n primary_language: Type.Optional(Type.String()),\n history_visible_to_new_joiners: Type.Boolean(),\n});\nexport const GroupToggleMuteNotificationsResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupClaimPrizeArgs = Type.Object({\n message_id: MessageId,\n correlation_id: Type.BigInt(),\n});\nexport const GroupCancelInvitesResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupCancelInvitesArgs = Type.Object({\n user_ids: Type.Array(UserId),\n});\nexport const GroupJoinVideoCallArgs = Type.Object({\n message_id: MessageId,\n new_achievement: Type.Boolean(),\n});\nexport const GroupSetVideoCallPresenceArgs = Type.Object({\n message_id: MessageId,\n presence: VideoCallPresence,\n new_achievement: Type.Boolean(),\n});\nexport const GroupSetVideoCallPresenceResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"AlreadyEnded\"),\n Type.Literal(\"GroupFrozen\"),\n Type.Literal(\"UserNotInGroup\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupDeletedMessageArgs = Type.Object({\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n});\nexport const GroupRegisterPollVoteArgs = Type.Object({\n thread_root_message_index: Type.Optional(MessageIndex),\n message_index: MessageIndex,\n poll_option: Type.Number(),\n operation: VoteOperation,\n new_achievement: Type.Boolean(),\n correlation_id: Type.BigInt(),\n});\nexport const GroupCancelP2pSwapArgs = Type.Object({\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n});\nexport const GroupUndeleteMessagesArgs = Type.Object({\n thread_root_message_index: Type.Optional(MessageIndex),\n message_ids: Type.Array(MessageId),\n correlation_id: Type.BigInt(),\n});\nexport const GroupChangeRoleResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"UserNotInGroup\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"Invalid\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupChangeRoleArgs = Type.Object({\n user_id: UserId,\n new_role: GroupRole,\n correlation_id: Type.BigInt(),\n});\nexport const GroupInviteCodeResponse = Type.Union([\n Type.Object({\n Success: GroupInviteCodeSuccessResult,\n }),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupUnblockUserResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Literal(\"CannotUnblockSelf\"),\n Type.Literal(\"GroupNotPublic\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupUnblockUserArgs = Type.Object({\n user_id: UserId,\n correlation_id: Type.BigInt(),\n});\nexport const GroupEventsWindowArgs = Type.Object({\n thread_root_message_index: Type.Optional(MessageIndex),\n mid_point: MessageIndex,\n max_messages: Type.Number(),\n max_events: Type.Number(),\n latest_known_update: Type.Optional(Type.BigInt()),\n});\nexport const GroupUnfollowThreadArgs = Type.Object({\n thread_root_message_index: MessageIndex,\n});\nexport const GroupUnfollowThreadResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NotFollowing\"),\n Type.Literal(\"ThreadNotFound\"),\n Type.Literal(\"UserNotInGroup\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"GroupFrozen\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupDeleteMessagesResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Literal(\"NotPlatformModerator\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupDeleteMessagesArgs = Type.Object({\n thread_root_message_index: Type.Optional(MessageIndex),\n message_ids: Type.Array(MessageId),\n as_platform_moderator: Type.Optional(Type.Boolean()),\n new_achievement: Type.Boolean(),\n correlation_id: Type.BigInt(),\n});\nexport const GroupEnableInviteCodeResponse = Type.Union([\n Type.Object({\n Success: GroupEnableInviteCodeSuccessResult,\n }),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupUpdateGroupSuccessResult = Type.Object({\n rules_version: Type.Optional(Version),\n});\nexport const GroupRegisterProposalVoteArgs = Type.Object({\n message_index: MessageIndex,\n adopt: Type.Boolean(),\n});\nexport const GroupRegisterProposalVoteResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Object({\n AlreadyVoted: Type.Boolean(),\n }),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Literal(\"NoEligibleNeurons\"),\n Type.Literal(\"ProposalMessageNotFound\"),\n Type.Literal(\"ProposalNotFound\"),\n Type.Literal(\"ProposalNotAcceptingVotes\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupDisableInviteCodeResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupGenerateBotApiKeyArgs = Type.Object({\n bot_id: UserId,\n requested_permissions: BotPermissions,\n});\nexport const GroupGenerateBotApiKeyResponse = Type.Union([\n Type.Object({\n Success: GroupGenerateBotApiKeySuccessResult,\n }),\n Type.Literal(\"BotNotFound\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupApiKeyResponse = Type.Union([\n Type.Object({\n Success: Type.String(),\n }),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"NotFound\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupApiKeyArgs = Type.Object({\n bot_id: UserId,\n});\nexport const GroupMessagesByMessageIndexArgs = Type.Object({\n thread_root_message_index: Type.Optional(MessageIndex),\n messages: Type.Array(MessageIndex),\n latest_known_update: Type.Optional(Type.BigInt()),\n});\nexport const GroupRegisterProposalVoteV2Response = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Literal(\"ProposalMessageNotFound\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupRegisterProposalVoteV2Args = Type.Object({\n message_index: MessageIndex,\n adopt: Type.Boolean(),\n});\nexport const GroupRemoveReactionResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NoChange\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupRemoveReactionArgs = Type.Object({\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n reaction: Reaction,\n correlation_id: Type.BigInt(),\n});\nexport const GroupAddReactionArgs = Type.Object({\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n reaction: Reaction,\n username: Type.String(),\n display_name: Type.Optional(Type.String()),\n new_achievement: Type.Boolean(),\n correlation_id: Type.BigInt(),\n});\nexport const GroupAddReactionResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NoChange\"),\n Type.Literal(\"InvalidReaction\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupThreadPreviewsArgs = Type.Object({\n threads: Type.Array(MessageIndex),\n latest_client_thread_update: Type.Optional(Type.BigInt()),\n});\nexport const GroupRulesResponse = Type.Union([\n Type.Object({\n Success: GroupRulesSuccessResult,\n }),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupBlockUserArgs = Type.Object({\n user_id: UserId,\n correlation_id: Type.BigInt(),\n});\nexport const GroupBlockUserResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Literal(\"CannotBlockSelf\"),\n Type.Literal(\"CannotBlockUser\"),\n Type.Literal(\"GroupNotPublic\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"UserNotInGroup\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupPinMessageResponse = Type.Union([\n Type.Object({\n Success: PushEventResult,\n }),\n Type.Literal(\"NoChange\"),\n Type.Literal(\"MessageIndexOutOfRange\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupPinMessageArgs = Type.Object({\n message_index: MessageIndex,\n correlation_id: Type.BigInt(),\n});\nexport const GroupRemoveParticipantArgs = Type.Object({\n user_id: UserId,\n correlation_id: Type.BigInt(),\n});\nexport const GroupRemoveParticipantResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Literal(\"CannotRemoveSelf\"),\n Type.Literal(\"CannotRemoveUser\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"UserNotInGroup\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupVideoCallParticipantsArgs = Type.Object({\n message_id: MessageId,\n updated_since: Type.Optional(Type.BigInt()),\n});\nexport const GroupDeclineInvitiationResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NotInvited\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupSendMessageSuccessResult = Type.Object({\n event_index: EventIndex,\n message_index: MessageIndex,\n timestamp: Type.BigInt(),\n expires_at: Type.Optional(Type.BigInt()),\n});\nexport const GroupSendMessageResponse = Type.Union([\n Type.Object({\n Success: GroupSendMessageSuccessResult,\n }),\n Type.Literal(\"ThreadMessageNotFound\"),\n Type.Literal(\"MessageEmpty\"),\n Type.Object({\n TextTooLong: Type.Number(),\n }),\n Type.Object({\n InvalidPoll: InvalidPollReason,\n }),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n InvalidRequest: Type.String(),\n }),\n Type.Literal(\"ChatFrozen\"),\n Type.Literal(\"RulesNotAccepted\"),\n Type.Literal(\"MessageAlreadyExists\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupEventsByIndexArgs = Type.Object({\n thread_root_message_index: Type.Optional(MessageIndex),\n events: Type.Array(EventIndex),\n latest_known_update: Type.Optional(Type.BigInt()),\n});\nexport const GroupUnpinMessageArgs = Type.Object({\n message_index: MessageIndex,\n correlation_id: Type.BigInt(),\n});\nexport const GroupUnpinMessageResponse = Type.Union([\n Type.Object({\n SuccessV2: PushEventResult,\n }),\n Type.Literal(\"NoChange\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupLocalUserIndexResponse = Type.Object({\n Success: TSPrincipal,\n});\nexport const GroupEventsArgs = Type.Object({\n thread_root_message_index: Type.Optional(MessageIndex),\n start_index: EventIndex,\n ascending: Type.Boolean(),\n max_messages: Type.Number(),\n max_events: Type.Number(),\n latest_known_update: Type.Optional(Type.BigInt()),\n});\nexport const GroupUpdateBotResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"NotFound\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupUpdateBotArgs = Type.Object({\n bot_id: UserId,\n granted_permissions: BotPermissions,\n});\nexport const GroupAcceptP2pSwapArgs = Type.Object({\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n pin: Type.Optional(PinNumberWrapper),\n new_achievement: Type.Boolean(),\n});\nexport const GroupReportMessageResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"AlreadyReported\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupReportMessageArgs = Type.Object({\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n delete: Type.Boolean(),\n});\nexport const GroupEditMessageResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupFollowThreadResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"AlreadyFollowing\"),\n Type.Literal(\"ThreadNotFound\"),\n Type.Literal(\"UserNotInGroup\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"GroupFrozen\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupFollowThreadArgs = Type.Object({\n thread_root_message_index: MessageIndex,\n new_achievement: Type.Boolean(),\n});\nexport const UserSearchMessagesSuccessResult = Type.Object({\n matches: Type.Array(MessageMatch),\n});\nexport const UserSearchMessagesResponse = Type.Union([\n Type.Object({\n Success: UserSearchMessagesSuccessResult,\n }),\n Type.Literal(\"InvalidTerm\"),\n Type.Object({\n TermTooLong: Type.Number(),\n }),\n Type.Object({\n TermTooShort: Type.Number(),\n }),\n Type.Literal(\"ChatNotFound\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserSearchMessagesArgs = Type.Object({\n user_id: UserId,\n search_term: Type.String(),\n max_results: Type.Number(),\n});\nexport const UserGenerateBtcAddressResponse = Type.Union([\n Type.Object({\n Success: Type.String(),\n }),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserManageFavouriteChatsResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"UserSuspended\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserSavedCryptoAccountsResponse = Type.Object({\n Success: Type.Array(UserNamedAccount),\n});\nexport const UserJoinVideoCallArgs = Type.Object({\n user_id: UserId,\n message_id: MessageId,\n});\nexport const UserJoinVideoCallResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"AlreadyEnded\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserBlocked\"),\n Type.Literal(\"ChatNotFound\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserTokenSwapStatusResponse = Type.Union([\n Type.Object({\n Success: UserTokenSwapStatusTokenSwapStatus,\n }),\n Type.Literal(\"NotFound\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserDeletedMessageArgs = Type.Object({\n user_id: UserId,\n message_id: MessageId,\n});\nexport const UserCancelP2pSwapArgs = Type.Object({\n user_id: UserId,\n message_id: MessageId,\n});\nexport const UserSetPinNumberResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Object({\n TooShort: FieldTooShortResult,\n }),\n Type.Object({\n TooLong: FieldTooLongResult,\n }),\n Type.Literal(\"PinRequired\"),\n Type.Object({\n PinIncorrect: Type.BigInt(),\n }),\n Type.Object({\n TooManyFailedPinAttempts: Type.BigInt(),\n }),\n Type.Object({\n MalformedSignature: Type.String(),\n }),\n Type.Literal(\"DelegationTooOld\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserSwapTokensICPSwapArgs = Type.Object({\n swap_canister_id: TSPrincipal,\n zero_for_one: Type.Boolean(),\n});\nexport const UserSwapTokensResponse = Type.Union([\n Type.Object({\n Success: UserSwapTokensSuccessResult,\n }),\n Type.Literal(\"SwapFailed\"),\n Type.Literal(\"PinRequired\"),\n Type.Object({\n PinIncorrect: Type.BigInt(),\n }),\n Type.Object({\n TooManyFailedPinAttempts: Type.BigInt(),\n }),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserSetAvatarResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Object({\n AvatarTooBig: FieldTooLongResult,\n }),\n Type.Literal(\"UserSuspended\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserUndeleteMessagesArgs = Type.Object({\n user_id: UserId,\n thread_root_message_index: Type.Optional(MessageIndex),\n message_ids: Type.Array(MessageId),\n correlation_id: Type.BigInt(),\n});\nexport const UserTipMessageResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"ChatNotFound\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"CannotTipSelf\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"TransferCannotBeZero\"),\n Type.Literal(\"TransferNotToMessageSender\"),\n Type.Object({\n TransferFailed: Type.String(),\n }),\n Type.Literal(\"ChatFrozen\"),\n Type.Literal(\"PinRequired\"),\n Type.Object({\n PinIncorrect: Type.BigInt(),\n }),\n Type.Object({\n TooManyFailedPinAttempts: Type.BigInt(),\n }),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Retrying: Type.String(),\n }),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserUnblockUserArgs = Type.Object({\n user_id: UserId,\n});\nexport const UserManualWallet = Type.Object({\n tokens: Type.Array(TSPrincipal),\n});\nexport const UserChannelSummaryUpdates = Type.Object({\n channel_id: ChannelId,\n read_by_me_up_to: Type.Optional(MessageIndex),\n threads_read: Type.Record(MessageIndex, MessageIndex),\n archived: Type.Optional(Type.Boolean()),\n date_read_pinned: Type.Optional(Type.BigInt()),\n});\nexport const UserWithdrawBtcResponse = Type.Union([\n Type.Object({\n Success: Type.BigInt(),\n }),\n Type.Object({\n ApproveError: Type.String(),\n }),\n Type.Object({\n RetrieveBtcError: Type.String(),\n }),\n Type.Literal(\"PinRequired\"),\n Type.Object({\n PinIncorrect: Type.BigInt(),\n }),\n Type.Object({\n TooManyFailedPinAttempts: Type.BigInt(),\n }),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserWithdrawBtcArgs = Type.Object({\n amount: Type.BigInt(),\n address: Type.String(),\n pin: Type.Optional(PinNumberWrapper),\n});\nexport const UserPinChatResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"ChatNotFound\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserContactsContact = Type.Object({\n user_id: UserId,\n nickname: Type.Optional(Type.String()),\n});\nexport const UserContactsSuccessResult = Type.Object({\n contacts: Type.Array(UserContactsContact),\n});\nexport const UserEventsWindowArgs = Type.Object({\n user_id: UserId,\n thread_root_message_index: Type.Optional(MessageIndex),\n mid_point: MessageIndex,\n max_messages: Type.Number(),\n max_events: Type.Number(),\n latest_known_update: Type.Optional(Type.BigInt()),\n});\nexport const UserDeleteDirectChatArgs = Type.Object({\n user_id: UserId,\n block_user: Type.Boolean(),\n});\nexport const UserDeleteDirectChatResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"ChatNotFound\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserDeleteMessagesArgs = Type.Object({\n user_id: UserId,\n thread_root_message_index: Type.Optional(MessageIndex),\n message_ids: Type.Array(MessageId),\n correlation_id: Type.BigInt(),\n});\nexport const UserDeleteMessagesResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"ChatNotFound\"),\n Type.Literal(\"UserSuspended\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserWalletConfig = Type.Union([\n Type.Object({\n Auto: UserAutoWallet,\n }),\n Type.Object({\n Manual: UserManualWallet,\n }),\n]);\nexport const UserSaveCryptoAccountResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"Invalid\"),\n Type.Literal(\"NameTaken\"),\n Type.Literal(\"UserSuspended\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserLeaveGroupResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"GroupNotFound\"),\n Type.Literal(\"GroupNotPublic\"),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Literal(\"OwnerCannotLeave\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserGenerateBotApiKeyResponse = Type.Union([\n Type.Object({\n Success: UserGenerateBotApiKeySuccessResult,\n }),\n Type.Literal(\"BotNotFound\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserGenerateBotApiKeyArgs = Type.Object({\n bot_id: UserId,\n requested_permissions: BotPermissions,\n});\nexport const UserMuteNotificationsResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"ChatNotFound\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserApiKeyResponse = Type.Union([\n Type.Object({\n Success: Type.String(),\n }),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"NotFound\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserApiKeyArgs = Type.Object({\n bot_id: UserId,\n});\nexport const UserSetBioResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Object({\n TooLong: FieldTooLongResult,\n }),\n Type.Literal(\"UserSuspended\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserChannelSummary = Type.Object({\n channel_id: ChannelId,\n read_by_me_up_to: Type.Optional(MessageIndex),\n threads_read: Type.Record(MessageIndex, MessageIndex),\n archived: Type.Boolean(),\n date_read_pinned: Type.Optional(Type.BigInt()),\n});\nexport const UserMessagesByMessageIndexArgs = Type.Object({\n user_id: UserId,\n thread_root_message_index: Type.Optional(MessageIndex),\n messages: Type.Array(MessageIndex),\n latest_known_update: Type.Optional(Type.BigInt()),\n});\nexport const UserApproveTransferResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Object({\n ApproveError: ApproveError,\n }),\n Type.Literal(\"PinRequired\"),\n Type.Object({\n PinIncorrect: Type.BigInt(),\n }),\n Type.Object({\n TooManyFailedPinAttempts: Type.BigInt(),\n }),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserDeleteGroupResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserSetMessageReminderResponse = Type.Union([\n Type.Object({\n Success: Type.BigInt(),\n }),\n Type.Literal(\"ReminderDateInThePast\"),\n Type.Object({\n NotesTooLong: FieldTooLongResult,\n }),\n Type.Literal(\"UserSuspended\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserRemoveReactionArgs = Type.Object({\n user_id: UserId,\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n reaction: Reaction,\n correlation_id: Type.BigInt(),\n});\nexport const UserRemoveReactionResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Object({\n SuccessV2: PushEventResult,\n }),\n Type.Literal(\"NoChange\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"ChatNotFound\"),\n Type.Literal(\"UserSuspended\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserSetContactOptionalContact = Type.Object({\n user_id: UserId,\n nickname: OptionUpdateString,\n});\nexport const UserSetContactArgs = Type.Object({\n contact: UserSetContactOptionalContact,\n});\nexport const UserSetContactResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NoChange\"),\n Type.Object({\n NicknameTooShort: FieldTooShortResult,\n }),\n Type.Object({\n NicknameTooLong: FieldTooLongResult,\n }),\n Type.Literal(\"UserSuspended\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserAddReactionArgs = Type.Object({\n user_id: UserId,\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n reaction: Reaction,\n correlation_id: Type.BigInt(),\n});\nexport const UserAddReactionResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Object({\n SuccessV2: PushEventResult,\n }),\n Type.Literal(\"NoChange\"),\n Type.Literal(\"InvalidReaction\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"ChatNotFound\"),\n Type.Literal(\"UserSuspended\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserReferral = Type.Object({\n user_id: UserId,\n status: ReferralStatus,\n});\nexport const UserBlockUserArgs = Type.Object({\n user_id: UserId,\n});\nexport const UserBlockUserResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"UserSuspended\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserSetCommunityIndexesArgs = Type.Object({\n indexes: Type.Array(Type.Tuple([CommunityId, Type.Number()])),\n});\nexport const UserReclaimSwapTokensArgs = Type.Object({\n exchange_id: ExchangeId,\n swap_canister_id: TSPrincipal,\n ledger_canister_id: TSPrincipal,\n amount: Type.BigInt(),\n fee: Type.BigInt(),\n});\nexport const UserPublicProfileResponse = Type.Object({\n Success: UserPublicProfilePublicProfile,\n});\nexport const UserEventsByIndexArgs = Type.Object({\n user_id: UserId,\n thread_root_message_index: Type.Optional(MessageIndex),\n events: Type.Array(EventIndex),\n latest_known_update: Type.Optional(Type.BigInt()),\n});\nexport const UserCreateCommunitySuccessResult = Type.Object({\n community_id: CommunityId,\n});\nexport const UserCreateCommunityResponse = Type.Union([\n Type.Object({\n Success: UserCreateCommunitySuccessResult,\n }),\n Type.Object({\n NameTooShort: FieldTooShortResult,\n }),\n Type.Object({\n NameTooLong: FieldTooLongResult,\n }),\n Type.Literal(\"NameReserved\"),\n Type.Object({\n DescriptionTooLong: FieldTooLongResult,\n }),\n Type.Object({\n RulesTooShort: FieldTooShortResult,\n }),\n Type.Object({\n RulesTooLong: FieldTooLongResult,\n }),\n Type.Object({\n AvatarTooBig: FieldTooLongResult,\n }),\n Type.Object({\n BannerTooBig: FieldTooLongResult,\n }),\n Type.Literal(\"AccessGateInvalid\"),\n Type.Object({\n MaxCommunitiesCreated: Type.Number(),\n }),\n Type.Literal(\"NameTaken\"),\n Type.Literal(\"Throttled\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"Unauthorized\"),\n Type.Literal(\"DefaultChannelsInvalid\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserMarkReadThreadRead = Type.Object({\n root_message_index: MessageIndex,\n read_up_to: MessageIndex,\n});\nexport const UserMarkReadChannelMessagesRead = Type.Object({\n channel_id: ChannelId,\n read_up_to: Type.Optional(MessageIndex),\n threads: Type.Array(UserMarkReadThreadRead),\n date_read_pinned: Type.Optional(Type.BigInt()),\n});\nexport const UserMarkReadCommunityMessagesRead = Type.Object({\n community_id: CommunityId,\n channels_read: Type.Array(UserMarkReadChannelMessagesRead),\n});\nexport const UserLocalUserIndexResponse = Type.Object({\n Success: TSPrincipal,\n});\nexport const UserEventsArgs = Type.Object({\n user_id: UserId,\n thread_root_message_index: Type.Optional(MessageIndex),\n start_index: EventIndex,\n ascending: Type.Boolean(),\n max_messages: Type.Number(),\n max_events: Type.Number(),\n latest_known_update: Type.Optional(Type.BigInt()),\n});\nexport const UserUpdateBotResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"NotFound\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserUpdateBotArgs = Type.Object({\n bot_id: UserId,\n granted_permissions: BotPermissions,\n});\nexport const UserLeaveCommunityArgs = Type.Object({\n community_id: CommunityId,\n});\nexport const UserLeaveCommunityResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"CommunityNotFound\"),\n Type.Literal(\"CommunityNotPublic\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"LastOwnerCannotLeave\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserAcceptP2pSwapArgs = Type.Object({\n user_id: UserId,\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n pin: Type.Optional(PinNumberWrapper),\n});\nexport const UserDeleteCommunityArgs = Type.Object({\n community_id: CommunityId,\n});\nexport const UserDeleteCommunityResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserReportMessageResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"ChatNotFound\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"AlreadyReported\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserReportMessageArgs = Type.Object({\n them: UserId,\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n delete: Type.Boolean(),\n});\nexport const UserEditMessageResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"ChatNotFound\"),\n Type.Literal(\"UserBlocked\"),\n Type.Literal(\"UserSuspended\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserUnpinChatResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"ChatNotFound\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserConfigureWalletArgs = Type.Object({\n config: UserWalletConfig,\n});\nexport const DirectReactionAddedNotification = Type.Object({\n t: UserId,\n tr: Type.Optional(MessageIndex),\n m: MessageIndex,\n e: EventIndex,\n u: Type.String(),\n d: Type.Optional(Type.String()),\n r: Reaction,\n a: Type.Optional(Type.BigInt()),\n});\nexport const PaymentGate = Type.Object({\n ledger_canister_id: TSPrincipal,\n amount: Type.BigInt(),\n fee: Type.BigInt(),\n});\nexport const VersionedRules = Type.Object({\n text: Type.String(),\n version: Version,\n enabled: Type.Boolean(),\n});\nexport const GroupSubtype = Type.Object({\n GovernanceProposals: GovernanceProposalsSubtype,\n});\nexport const AccountICRC1 = Type.Object({\n owner: TSPrincipal,\n subaccount: Type.Optional(Type.Tuple([\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n ])),\n});\nexport const CommunityMembershipUpdates = Type.Object({\n role: Type.Optional(CommunityRole),\n rules_accepted: Type.Optional(Type.Boolean()),\n display_name: OptionUpdateString,\n lapsed: Type.Optional(Type.Boolean()),\n});\nexport const GiphyContent = Type.Object({\n caption: Type.Optional(Type.String()),\n title: Type.String(),\n desktop: GiphyImageVariant,\n mobile: GiphyImageVariant,\n});\nexport const P2PSwapReserved = Type.Object({\n reserved_by: UserId,\n});\nexport const SnsNeuronGate = Type.Object({\n governance_canister_id: TSPrincipal,\n min_stake_e8s: Type.Optional(Type.BigInt()),\n min_dissolve_delay: Type.Optional(Type.BigInt()),\n});\nexport const OptionalMessagePermissions = Type.Object({\n default: Type.Optional(GroupPermissionRole),\n text: OptionUpdateGroupPermissionRole,\n image: OptionUpdateGroupPermissionRole,\n video: OptionUpdateGroupPermissionRole,\n audio: OptionUpdateGroupPermissionRole,\n file: OptionUpdateGroupPermissionRole,\n poll: OptionUpdateGroupPermissionRole,\n crypto: OptionUpdateGroupPermissionRole,\n giphy: OptionUpdateGroupPermissionRole,\n prize: OptionUpdateGroupPermissionRole,\n p2p_swap: OptionUpdateGroupPermissionRole,\n video_call: OptionUpdateGroupPermissionRole,\n custom_updated: Type.Array(CustomPermission),\n custom_deleted: Type.Array(Type.String()),\n});\nexport const Delegation = Type.Object({\n pubkey: TSBytes,\n expiration: Type.BigInt(),\n});\nexport const UserSummary = Type.Object({\n user_id: UserId,\n username: Type.String(),\n display_name: Type.Optional(Type.String()),\n avatar_id: Type.Optional(Type.BigInt()),\n is_bot: Type.Boolean(),\n suspended: Type.Boolean(),\n diamond_member: Type.Boolean(),\n diamond_membership_status: DiamondMembershipStatus,\n total_chit_earned: Type.Number(),\n chit_balance: Type.Number(),\n streak: Type.Number(),\n max_streak: Type.Number(),\n is_unique_person: Type.Boolean(),\n});\nexport const DirectMessageTipped = Type.Object({\n ti: UserId,\n tr: Type.Optional(MessageIndex),\n m: MessageIndex,\n e: EventIndex,\n u: Type.String(),\n d: Type.Optional(Type.String()),\n t: Type.String(),\n a: Type.Optional(Type.BigInt()),\n});\nexport const MessagePermissions = Type.Object({\n default: GroupPermissionRole,\n text: Type.Optional(GroupPermissionRole),\n image: Type.Optional(GroupPermissionRole),\n video: Type.Optional(GroupPermissionRole),\n audio: Type.Optional(GroupPermissionRole),\n file: Type.Optional(GroupPermissionRole),\n poll: Type.Optional(GroupPermissionRole),\n crypto: Type.Optional(GroupPermissionRole),\n giphy: Type.Optional(GroupPermissionRole),\n prize: Type.Optional(GroupPermissionRole),\n p2p_swap: Type.Optional(GroupPermissionRole),\n video_call: Type.Optional(GroupPermissionRole),\n custom: Type.Array(CustomPermission),\n});\nexport const ChatId = TSPrincipal;\nexport const AvatarChanged = Type.Object({\n new_avatar: Type.Optional(Type.BigInt()),\n previous_avatar: Type.Optional(Type.BigInt()),\n changed_by: UserId,\n});\nexport const CryptoAccountICRC1 = Type.Union([\n Type.Literal(\"Mint\"),\n Type.Object({\n Account: AccountICRC1,\n }),\n]);\nexport const IntegerParam = Type.Object({\n min_value: Type.BigInt(),\n max_value: Type.BigInt(),\n choices: Type.Array(BotCommandOptionChoiceI128),\n});\nexport const VerifiedCredentialGate = Type.Object({\n issuer_canister_id: TSPrincipal,\n issuer_origin: Type.String(),\n credential_type: Type.String(),\n credential_name: Type.String(),\n credential_arguments: Type.Record(Type.String(), VerifiedCredentialArgumentValue),\n});\nexport const NnsProposal = Type.Object({\n id: Type.BigInt(),\n topic: Type.Number(),\n proposer: Type.BigInt(),\n created: Type.BigInt(),\n title: Type.String(),\n summary: Type.String(),\n url: Type.String(),\n status: ProposalDecisionStatus,\n reward_status: ProposalRewardStatus,\n tally: Tally,\n deadline: Type.BigInt(),\n payload_text_rendering: Type.Optional(Type.String()),\n last_updated: Type.BigInt(),\n});\nexport const MembersRemoved = Type.Object({\n user_ids: Type.Array(UserId),\n removed_by: UserId,\n});\nexport const PublicApiKeyDetails = Type.Object({\n bot_id: UserId,\n granted_permissions: BotPermissions,\n generated_by: UserId,\n generated_at: Type.BigInt(),\n});\nexport const BotActionCommunityDetails = Type.Object({\n community_id: CommunityId,\n});\nexport const SwapStatusErrorReserved = Type.Object({\n reserved_by: UserId,\n});\nexport const BotRemoved = Type.Object({\n user_id: UserId,\n removed_by: UserId,\n});\nexport const BlobReference = Type.Object({\n canister_id: TSPrincipal,\n blob_id: Type.BigInt(),\n});\nexport const MessagePinned = Type.Object({\n message_index: MessageIndex,\n pinned_by: UserId,\n});\nexport const PendingCryptoTransactionICRC1 = Type.Object({\n ledger: TSPrincipal,\n token_symbol: Type.String(),\n amount: Type.BigInt(),\n to: AccountICRC1,\n fee: Type.BigInt(),\n memo: Type.Optional(TSBytes),\n created: Type.BigInt(),\n});\nexport const GroupDescriptionChanged = Type.Object({\n new_description: Type.String(),\n previous_description: Type.String(),\n changed_by: UserId,\n});\nexport const PrizeContent = Type.Object({\n prizes_remaining: Type.Number(),\n prizes_pending: Type.Number(),\n winners: Type.Array(UserId),\n winner_count: Type.Number(),\n user_is_winner: Type.Boolean(),\n token_symbol: Type.String(),\n ledger: TSPrincipal,\n end_date: Type.BigInt(),\n caption: Type.Optional(Type.String()),\n diamond_only: Type.Boolean(),\n lifetime_diamond_only: Type.Boolean(),\n unique_person_only: Type.Boolean(),\n streak_only: Type.Number(),\n});\nexport const GroupRulesChanged = Type.Object({\n enabled: Type.Boolean(),\n prev_enabled: Type.Boolean(),\n changed_by: UserId,\n});\nexport const GroupCreated = Type.Object({\n name: Type.String(),\n description: Type.String(),\n created_by: UserId,\n});\nexport const HydratedMention = Type.Object({\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n message_index: MessageIndex,\n event_index: EventIndex,\n});\nexport const ExternalUrlUpdated = Type.Object({\n updated_by: UserId,\n new_url: Type.Optional(Type.String()),\n});\nexport const DeletedGroupInfo = Type.Object({\n id: ChatId,\n timestamp: Type.BigInt(),\n deleted_by: UserId,\n group_name: Type.String(),\n name: Type.String(),\n public: Type.Boolean(),\n});\nexport const SwapStatusErrorAccepted = Type.Object({\n accepted_by: UserId,\n token1_txn_in: Type.BigInt(),\n});\nexport const DiamondMembershipFees = Type.Object({\n chat_fees: DiamondMembershipFeesByDuration,\n icp_fees: DiamondMembershipFeesByDuration,\n});\nexport const Document = Type.Object({\n id: Type.BigInt(),\n mime_type: Type.String(),\n data: TSBytes,\n});\nexport const FileContent = Type.Object({\n name: Type.String(),\n caption: Type.Optional(Type.String()),\n mime_type: Type.String(),\n file_size: Type.Number(),\n blob_reference: Type.Optional(BlobReference),\n});\nexport const P2PSwapCompleted = Type.Object({\n accepted_by: UserId,\n token1_txn_in: Type.BigInt(),\n token0_txn_out: Type.BigInt(),\n token1_txn_out: Type.BigInt(),\n});\nexport const InstalledBotDetails = Type.Object({\n user_id: UserId,\n added_by: UserId,\n permissions: BotPermissions,\n});\nexport const UserSummaryStable = Type.Object({\n username: Type.String(),\n display_name: Type.Optional(Type.String()),\n avatar_id: Type.Optional(Type.BigInt()),\n is_bot: Type.Boolean(),\n suspended: Type.Boolean(),\n diamond_membership_status: DiamondMembershipStatus,\n is_unique_person: Type.Boolean(),\n});\nexport const StringParam = Type.Object({\n min_length: Type.Number(),\n max_length: Type.Number(),\n choices: Type.Array(BotCommandOptionChoiceString),\n multi_line: Type.Boolean(),\n});\nexport const GroupInviteCodeChanged = Type.Object({\n change: GroupInviteCodeChange,\n changed_by: UserId,\n});\nexport const ChitEarned = Type.Object({\n amount: Type.Number(),\n timestamp: Type.BigInt(),\n reason: ChitEarnedReason,\n});\nexport const CustomContent = Type.Object({\n kind: Type.String(),\n data: TSBytes,\n});\nexport const FailedCryptoTransactionICRC1 = Type.Object({\n ledger: TSPrincipal,\n token: Cryptocurrency,\n amount: Type.BigInt(),\n fee: Type.BigInt(),\n from: CryptoAccountICRC1,\n to: CryptoAccountICRC1,\n memo: Type.Optional(TSBytes),\n created: Type.BigInt(),\n error_message: Type.String(),\n});\nexport const GroupNameChanged = Type.Object({\n new_name: Type.String(),\n previous_name: Type.String(),\n changed_by: UserId,\n});\nexport const Chat = Type.Union([\n Type.Object({\n Direct: ChatId,\n }),\n Type.Object({\n Group: ChatId,\n }),\n Type.Object({\n Channel: Type.Tuple([CommunityId, ChannelId]),\n }),\n]);\nexport const DeletedBy = Type.Object({\n deleted_by: UserId,\n timestamp: Type.BigInt(),\n});\nexport const TokenBalanceGate = Type.Object({\n ledger_canister_id: TSPrincipal,\n min_balance: Type.BigInt(),\n});\nexport const P2PSwapAccepted = Type.Object({\n accepted_by: UserId,\n token1_txn_in: Type.BigInt(),\n});\nexport const GroupMember = Type.Object({\n user_id: UserId,\n date_added: Type.BigInt(),\n role: GroupRole,\n lapsed: Type.Boolean(),\n});\nexport const GateCheckFailedReason = Type.Union([\n Type.Literal(\"NotDiamondMember\"),\n Type.Literal(\"NotLifetimeDiamondMember\"),\n Type.Literal(\"NoUniquePersonProof\"),\n Type.Literal(\"NoSnsNeuronsFound\"),\n Type.Literal(\"NoSnsNeuronsWithRequiredStakeFound\"),\n Type.Literal(\"NoSnsNeuronsWithRequiredDissolveDelayFound\"),\n Type.Object({\n PaymentFailed: TransferFromError,\n }),\n Type.Object({\n InsufficientBalance: Type.BigInt(),\n }),\n Type.Object({\n FailedVerifiedCredentialCheck: Type.String(),\n }),\n Type.Literal(\"Locked\"),\n Type.Literal(\"NotReferredByMember\"),\n]);\nexport const StartVideoCallArgs = Type.Object({\n call_type: VideoCallType,\n chat: Chat,\n});\nexport const TokenInfo = Type.Object({\n symbol: Type.String(),\n ledger: TSPrincipal,\n decimals: Type.Number(),\n fee: Type.BigInt(),\n});\nexport const MessageUnpinned = Type.Object({\n message_index: MessageIndex,\n unpinned_by: UserId,\n due_to_message_deleted: Type.Boolean(),\n});\nexport const DirectMessageNotification = Type.Object({\n s: UserId,\n tr: Type.Optional(MessageIndex),\n m: MessageIndex,\n e: EventIndex,\n sn: Type.String(),\n sd: Type.Optional(Type.String()),\n ty: Type.String(),\n tx: Type.Optional(Type.String()),\n i: Type.Optional(Type.String()),\n a: Type.Optional(Type.BigInt()),\n ct: Type.Optional(CryptoTransferDetails),\n});\nexport const CompletedCryptoTransactionNNS = Type.Object({\n ledger: TSPrincipal,\n token: Cryptocurrency,\n amount: Tokens,\n fee: Tokens,\n from: CryptoAccountNNS,\n to: CryptoAccountNNS,\n memo: Type.BigInt(),\n created: Type.BigInt(),\n transaction_hash: Type.Tuple([\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n ]),\n block_index: Type.BigInt(),\n});\nexport const TotalVotes = Type.Union([\n Type.Object({\n Visible: Type.Record(Type.Number(), Type.Array(UserId)),\n }),\n Type.Object({\n Anonymous: Type.Record(Type.Number(), Type.Number()),\n }),\n Type.Object({\n Hidden: Type.Number(),\n }),\n]);\nexport const MultiUserChat = Type.Union([\n Type.Object({\n Group: ChatId,\n }),\n Type.Object({\n Channel: Type.Tuple([CommunityId, ChannelId]),\n }),\n]);\nexport const UsersUnblocked = Type.Object({\n user_ids: Type.Array(UserId),\n unblocked_by: UserId,\n});\nexport const Tips = Type.Array(Type.Tuple([TSPrincipal, Type.Array(Type.Tuple([UserId, Type.BigInt()]))]));\nexport const CallParticipant = Type.Object({\n user_id: UserId,\n joined: Type.BigInt(),\n});\nexport const GroupFrozen = Type.Object({\n frozen_by: UserId,\n reason: Type.Optional(Type.String()),\n});\nexport const BotUpdated = Type.Object({\n user_id: UserId,\n updated_by: UserId,\n});\nexport const OptionUpdateOptionalMessagePermissions = Type.Union([\n Type.Literal(\"NoChange\"),\n Type.Literal(\"SetToNone\"),\n Type.Object({\n SetToSome: OptionalMessagePermissions,\n }),\n], { default: \"NoChange\" });\nexport const FailedCryptoTransactionICRC2 = Type.Object({\n ledger: TSPrincipal,\n token: Cryptocurrency,\n amount: Type.BigInt(),\n fee: Type.BigInt(),\n spender: UserId,\n from: CryptoAccountICRC1,\n to: CryptoAccountICRC1,\n memo: Type.Optional(TSBytes),\n created: Type.BigInt(),\n error_message: Type.String(),\n});\nexport const GroupReactionAddedNotification = Type.Object({\n c: ChatId,\n tr: Type.Optional(MessageIndex),\n m: MessageIndex,\n e: EventIndex,\n g: Type.String(),\n a: UserId,\n n: Type.String(),\n d: Type.Optional(Type.String()),\n r: Reaction,\n av: Type.Optional(Type.BigInt()),\n});\nexport const ChannelReactionAddedNotification = Type.Object({\n ci: CommunityId,\n chi: ChannelId,\n tr: Type.Optional(MessageIndex),\n m: MessageIndex,\n e: EventIndex,\n cn: Type.String(),\n chn: Type.String(),\n a: UserId,\n an: Type.String(),\n ad: Type.Optional(Type.String()),\n r: Reaction,\n ca: Type.Optional(Type.BigInt()),\n cha: Type.Optional(Type.BigInt()),\n});\nexport const UsersInvited = Type.Object({\n user_ids: Type.Array(UserId),\n invited_by: UserId,\n});\nexport const PendingCryptoTransactionNNS = Type.Object({\n ledger: TSPrincipal,\n token_symbol: Type.String(),\n amount: Tokens,\n to: UserOrAccount,\n fee: Type.Optional(Tokens),\n memo: Type.Optional(Type.BigInt()),\n created: Type.BigInt(),\n});\nexport const DeletedCommunityInfo = Type.Object({\n id: CommunityId,\n timestamp: Type.BigInt(),\n deleted_by: UserId,\n name: Type.String(),\n public: Type.Boolean(),\n});\nexport const VideoCallParticipants = Type.Object({\n participants: Type.Array(CallParticipant),\n hidden: Type.Array(CallParticipant),\n last_updated: Type.BigInt(),\n});\nexport const SwapStatusErrorCompleted = Type.Object({\n accepted_by: UserId,\n token1_txn_in: Type.BigInt(),\n token0_txn_out: Type.BigInt(),\n token1_txn_out: Type.BigInt(),\n});\nexport const AirdropConfig = Type.Object({\n community_id: CommunityId,\n channel_id: ChannelId,\n community_name: Type.String(),\n channel_name: Type.String(),\n});\nexport const MembersAdded = Type.Object({\n user_ids: Type.Array(UserId),\n added_by: UserId,\n unblocked: Type.Array(UserId),\n});\nexport const FrozenGroupInfo = Type.Object({\n timestamp: Type.BigInt(),\n frozen_by: UserId,\n reason: Type.Optional(Type.String()),\n});\nexport const GroupUnfrozen = Type.Object({\n unfrozen_by: UserId,\n});\nexport const EventsTimeToLiveUpdated = Type.Object({\n updated_by: UserId,\n new_ttl: Type.Optional(Type.BigInt()),\n});\nexport const BotCommandArgValue = Type.Union([\n Type.Object({\n String: Type.String(),\n }),\n Type.Object({\n Integer: Type.BigInt(),\n }),\n Type.Object({\n Decimal: Type.Number(),\n }),\n Type.Object({\n Boolean: Type.Boolean(),\n }),\n Type.Object({\n User: UserId,\n }),\n Type.Object({\n DateTime: Type.BigInt(),\n }),\n]);\nexport const PendingCryptoTransactionICRC2 = Type.Object({\n ledger: TSPrincipal,\n token_symbol: Type.String(),\n amount: Type.BigInt(),\n from: AccountICRC1,\n to: AccountICRC1,\n fee: Type.BigInt(),\n memo: Type.Optional(TSBytes),\n created: Type.BigInt(),\n});\nexport const MemberJoined = Type.Object({\n user_id: UserId,\n invited_by: Type.Optional(UserId),\n});\nexport const AddedToChannelNotification = Type.Object({\n ci: CommunityId,\n cn: Type.String(),\n chi: ChannelId,\n chn: Type.String(),\n a: UserId,\n an: Type.String(),\n ad: Type.Optional(Type.String()),\n ca: Type.Optional(Type.BigInt()),\n cha: Type.Optional(Type.BigInt()),\n});\nexport const AudioContent = Type.Object({\n caption: Type.Optional(Type.String()),\n mime_type: Type.String(),\n blob_reference: Type.Optional(BlobReference),\n});\nexport const ImageContent = Type.Object({\n width: Type.Number(),\n height: Type.Number(),\n thumbnail_data: ThumbnailData,\n caption: Type.Optional(Type.String()),\n mime_type: Type.String(),\n blob_reference: Type.Optional(BlobReference),\n});\nexport const JoinVideoCallArgs = Type.Object({\n chat: Chat,\n});\nexport const RoleChanged = Type.Object({\n user_ids: Type.Array(UserId),\n changed_by: UserId,\n old_role: GroupRole,\n new_role: GroupRole,\n});\nexport const GroupVisibilityChanged = Type.Object({\n public: Type.Optional(Type.Boolean()),\n messages_visible_to_non_members: Type.Optional(Type.Boolean()),\n changed_by: UserId,\n});\nexport const MarkVideoCallAsEndedArgs = Type.Object({\n chat: Chat,\n});\nexport const SelectedGroupUpdates = Type.Object({\n timestamp: Type.BigInt(),\n last_updated: Type.BigInt(),\n latest_event_index: EventIndex,\n members_added_or_updated: Type.Array(GroupMember),\n members_removed: Type.Array(UserId),\n bots_added_or_updated: Type.Array(InstalledBotDetails),\n bots_removed: Type.Array(UserId),\n api_keys_generated: Type.Array(PublicApiKeyDetails),\n blocked_users_added: Type.Array(UserId),\n blocked_users_removed: Type.Array(UserId),\n invited_users: Type.Optional(Type.Array(UserId)),\n pinned_messages_added: Type.Array(MessageIndex),\n pinned_messages_removed: Type.Array(MessageIndex),\n chat_rules: Type.Optional(VersionedRules),\n});\nexport const BotInstallationLocation = Type.Union([\n Type.Object({\n Community: CommunityId,\n }),\n Type.Object({\n Group: ChatId,\n }),\n Type.Object({\n User: ChatId,\n }),\n]);\nexport const CompletedCryptoTransactionICRC1 = Type.Object({\n ledger: TSPrincipal,\n token: Cryptocurrency,\n amount: Type.BigInt(),\n from: CryptoAccountICRC1,\n to: CryptoAccountICRC1,\n fee: Type.BigInt(),\n memo: Type.Optional(TSBytes),\n created: Type.BigInt(),\n block_index: Type.BigInt(),\n});\nexport const GroupMembership = Type.Object({\n joined: Type.BigInt(),\n role: GroupRole,\n mentions: Type.Array(HydratedMention),\n notifications_muted: Type.Boolean(),\n my_metrics: ChatMetrics,\n latest_threads: Type.Array(GroupCanisterThreadDetails),\n rules_accepted: Type.Boolean(),\n lapsed: Type.Boolean(),\n});\nexport const OptionUpdateFrozenGroupInfo = Type.Union([\n Type.Literal(\"NoChange\"),\n Type.Literal(\"SetToNone\"),\n Type.Object({\n SetToSome: FrozenGroupInfo,\n }),\n], { default: \"NoChange\" });\nexport const OptionalGroupPermissions = Type.Object({\n change_roles: Type.Optional(GroupPermissionRole),\n update_group: Type.Optional(GroupPermissionRole),\n invite_users: Type.Optional(GroupPermissionRole),\n add_members: Type.Optional(GroupPermissionRole),\n remove_members: Type.Optional(GroupPermissionRole),\n delete_messages: Type.Optional(GroupPermissionRole),\n pin_messages: Type.Optional(GroupPermissionRole),\n react_to_messages: Type.Optional(GroupPermissionRole),\n mention_all_members: Type.Optional(GroupPermissionRole),\n start_video_call: Type.Optional(GroupPermissionRole),\n message_permissions: Type.Optional(OptionalMessagePermissions),\n thread_permissions: OptionUpdateOptionalMessagePermissions,\n});\nexport const ReplyContext = Type.Object({\n chat_if_other: Type.Optional(Type.Tuple([Chat, Type.Union([MessageIndex, Type.Null()])])),\n event_index: EventIndex,\n});\nexport const BotActionChatDetails = Type.Object({\n chat: Chat,\n thread: Type.Optional(MessageIndex),\n message_id: MessageId,\n user_message_id: Type.Optional(MessageId),\n});\nexport const ReportedMessage = Type.Object({\n reports: Type.Array(MessageReport),\n count: Type.Number(),\n});\nexport const ChannelMessageNotification = Type.Object({\n ci: CommunityId,\n chi: ChannelId,\n tr: Type.Optional(MessageIndex),\n m: MessageIndex,\n e: EventIndex,\n cn: Type.String(),\n chn: Type.String(),\n s: UserId,\n sn: Type.String(),\n sd: Type.Optional(Type.String()),\n ty: Type.String(),\n tx: Type.Optional(Type.String()),\n i: Type.Optional(Type.String()),\n ca: Type.Optional(Type.BigInt()),\n cha: Type.Optional(Type.BigInt()),\n ct: Type.Optional(CryptoTransferDetails),\n});\nexport const GroupMembershipUpdates = Type.Object({\n role: Type.Optional(GroupRole),\n mentions: Type.Array(HydratedMention),\n notifications_muted: Type.Optional(Type.Boolean()),\n my_metrics: Type.Optional(ChatMetrics),\n latest_threads: Type.Array(GroupCanisterThreadDetails),\n unfollowed_threads: Type.Array(MessageIndex),\n rules_accepted: Type.Optional(Type.Boolean()),\n lapsed: Type.Optional(Type.Boolean()),\n});\nexport const BotCommandParamType = Type.Union([\n Type.Literal(\"UserParam\"),\n Type.Literal(\"BooleanParam\"),\n Type.Object({\n StringParam: StringParam,\n }),\n Type.Object({\n IntegerParam: IntegerParam,\n }),\n Type.Object({\n DecimalParam: DecimalParam,\n }),\n Type.Object({\n DateTimeParam: DateTimeParam,\n }),\n]);\nexport const SnsProposal = Type.Object({\n id: Type.BigInt(),\n action: Type.BigInt(),\n proposer: Type.Tuple([\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n ]),\n created: Type.BigInt(),\n title: Type.String(),\n summary: Type.String(),\n url: Type.String(),\n status: ProposalDecisionStatus,\n reward_status: ProposalRewardStatus,\n tally: Tally,\n deadline: Type.BigInt(),\n payload_text_rendering: Type.Optional(Type.String()),\n minimum_yes_proportion_of_total: Type.Number(),\n minimum_yes_proportion_of_exercised: Type.Number(),\n last_updated: Type.BigInt(),\n});\nexport const OptionUpdateAirdropConfig = Type.Union([\n Type.Literal(\"NoChange\"),\n Type.Literal(\"SetToNone\"),\n Type.Object({\n SetToSome: AirdropConfig,\n }),\n], { default: \"NoChange\" });\nexport const GroupMessageTipped = Type.Object({\n c: ChatId,\n tr: Type.Optional(MessageIndex),\n m: MessageIndex,\n e: EventIndex,\n g: Type.String(),\n ti: UserId,\n tn: Type.String(),\n td: Type.Optional(Type.String()),\n t: Type.String(),\n a: Type.Optional(Type.BigInt()),\n});\nexport const GroupMessageNotification = Type.Object({\n c: ChatId,\n tr: Type.Optional(MessageIndex),\n m: MessageIndex,\n e: EventIndex,\n g: Type.String(),\n s: UserId,\n sn: Type.String(),\n sd: Type.Optional(Type.String()),\n ty: Type.String(),\n tx: Type.Optional(Type.String()),\n i: Type.Optional(Type.String()),\n a: Type.Optional(Type.BigInt()),\n ct: Type.Optional(CryptoTransferDetails),\n});\nexport const OptionUpdateDocument = Type.Union([\n Type.Literal(\"NoChange\"),\n Type.Literal(\"SetToNone\"),\n Type.Object({\n SetToSome: Document,\n }),\n], { default: \"NoChange\" });\nexport const OptionUpdateGroupSubtype = Type.Union([\n Type.Literal(\"NoChange\"),\n Type.Literal(\"SetToNone\"),\n Type.Object({\n SetToSome: GroupSubtype,\n }),\n], { default: \"NoChange\" });\nexport const DiamondMembershipDetails = Type.Object({\n expires_at: Type.BigInt(),\n pay_in_chat: Type.Boolean(),\n subscription: DiamondMembershipSubscription,\n});\nexport const GroupIndexRecommendedGroupsArgs = Type.Object({\n count: Type.Number(),\n exclusions: Type.Array(ChatId),\n});\nexport const GroupIndexFreezeGroupArgs = Type.Object({\n chat_id: ChatId,\n reason: Type.Optional(Type.String()),\n suspend_members: Type.Optional(GroupIndexFreezeGroupSuspensionDetails),\n});\nexport const GroupIndexAddHotGroupExclusionArgs = Type.Object({\n chat_id: ChatId,\n});\nexport const GroupIndexLookupChannelByGroupIdArgs = Type.Object({\n group_id: ChatId,\n});\nexport const GroupIndexFreezeCommunityArgs = Type.Object({\n community_id: CommunityId,\n reason: Type.Optional(Type.String()),\n suspend_members: Type.Optional(GroupIndexFreezeCommunitySuspensionDetails),\n});\nexport const GroupIndexDeleteFrozenGroupArgs = Type.Object({\n chat_id: ChatId,\n});\nexport const GroupIndexRemoveHotGroupExclusionArgs = Type.Object({\n chat_id: ChatId,\n});\nexport const GroupIndexActiveGroupsArgs = Type.Object({\n group_ids: Type.Array(ChatId),\n community_ids: Type.Array(CommunityId),\n active_since: Type.Optional(Type.BigInt()),\n});\nexport const GroupIndexActiveGroupsSuccessResult = Type.Object({\n timestamp: Type.BigInt(),\n active_groups: Type.Array(ChatId),\n active_communities: Type.Array(CommunityId),\n deleted_groups: Type.Array(DeletedGroupInfo),\n deleted_communities: Type.Array(DeletedCommunityInfo),\n});\nexport const GroupIndexUnfreezeGroupArgs = Type.Object({\n chat_id: ChatId,\n});\nexport const StorageIndexCanForwardResponse = Type.Union([\n Type.Object({\n Success: StorageIndexProjectedAllowance,\n }),\n Type.Object({\n AllowanceExceeded: StorageIndexProjectedAllowance,\n }),\n Type.Literal(\"UserNotFound\"),\n]);\nexport const RegistryUpdatesSuccessResult = Type.Object({\n last_updated: Type.BigInt(),\n token_details: Type.Optional(Type.Array(RegistryTokenDetails)),\n nervous_system_details: Type.Array(RegistryNervousSystemSummary),\n message_filters_added: Type.Array(RegistryMessageFilterSummary),\n message_filters_removed: Type.Array(Type.BigInt()),\n swap_providers: Type.Optional(Type.Array(ExchangeId)),\n airdrop_config: OptionUpdateAirdropConfig,\n});\nexport const RegistryUpdatesResponse = Type.Union([\n Type.Object({\n Success: RegistryUpdatesSuccessResult,\n }),\n Type.Literal(\"SuccessNoUpdates\"),\n]);\nexport const UserIndexDiamondMembershipFeesResponse = Type.Object({\n Success: Type.Array(UserIndexDiamondMembershipFeesDiamondMembershipFees),\n});\nexport const UserIndexUsersChitResponse = Type.Object({\n Success: UserIndexUsersChitSuccessResult,\n});\nexport const UserIndexPlatformModeratorsResponse = Type.Object({\n Success: UserIndexPlatformModeratorsSuccessResult,\n});\nexport const UserIndexSuspectedBotsResponse = Type.Object({\n Success: UserIndexSuspectedBotsSuccessResult,\n});\nexport const UserIndexExternalAchievementsSuccessResult = Type.Object({\n last_updated: Type.BigInt(),\n added_or_updated: Type.Array(UserIndexExternalAchievementsExternalAchievement),\n});\nexport const UserIndexExternalAchievementsResponse = Type.Union([\n Type.Object({\n Success: UserIndexExternalAchievementsSuccessResult,\n }),\n Type.Literal(\"SuccessNoUpdates\"),\n]);\nexport const UserIndexUserResponse = Type.Union([\n Type.Object({\n Success: UserSummary,\n }),\n Type.Literal(\"UserNotFound\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserIndexReferralMetricsResponse = Type.Object({\n Success: UserIndexReferralMetricsReferralMetrics,\n});\nexport const UserIndexSearchResult = Type.Object({\n users: Type.Array(UserSummary),\n timestamp: Type.BigInt(),\n});\nexport const UserIndexSearchResponse = Type.Object({\n Success: UserIndexSearchResult,\n});\nexport const UserIndexExploreBotsArgs = Type.Object({\n search_term: Type.Optional(Type.String()),\n page_index: Type.Number(),\n page_size: Type.Number(),\n installation_location: Type.Optional(BotInstallationLocation),\n});\nexport const UserIndexChitLeaderboardSuccessResult = Type.Object({\n all_time: Type.Array(UserIndexChitLeaderboardChitUserBalance),\n this_month: Type.Array(UserIndexChitLeaderboardChitUserBalance),\n last_month: Type.Array(UserIndexChitLeaderboardChitUserBalance),\n});\nexport const UserIndexChitLeaderboardResponse = Type.Object({\n SuccessV2: UserIndexChitLeaderboardSuccessResult,\n});\nexport const UserIndexSetDiamondMembershipFeesArgs = Type.Object({\n fees: DiamondMembershipFees,\n});\nexport const UserIndexRegisterBotResponse = Type.Union([\n Type.Object({\n Success: UserIndexRegisterBotSuccessResult,\n }),\n Type.Literal(\"AlreadyRegistered\"),\n Type.Object({\n InvalidRequest: Type.String(),\n }),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Literal(\"UserSuspended\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserIndexPlatformModeratorsGroupResponse = Type.Object({\n Success: ChatId,\n});\nexport const LocalUserIndexInstallBotArgs = Type.Object({\n location: BotInstallationLocation,\n bot_id: UserId,\n granted_permissions: BotPermissions,\n});\nexport const LocalUserIndexInviteUsersToGroupArgs = Type.Object({\n group_id: ChatId,\n user_ids: Type.Array(UserId),\n caller_username: Type.String(),\n correlation_id: Type.BigInt(),\n});\nexport const LocalUserIndexJoinGroupArgs = Type.Object({\n chat_id: ChatId,\n invite_code: Type.Optional(Type.BigInt()),\n verified_credential_args: Type.Optional(VerifiedCredentialGateArgs),\n correlation_id: Type.BigInt(),\n});\nexport const LocalUserIndexUninstallBotArgs = Type.Object({\n location: BotInstallationLocation,\n bot_id: UserId,\n});\nexport const LocalUserIndexRegisterUserResponse = Type.Union([\n Type.Object({\n Success: LocalUserIndexRegisterUserSuccessResult,\n }),\n Type.Literal(\"RegistrationInProgress\"),\n Type.Literal(\"AlreadyRegistered\"),\n Type.Literal(\"UserLimitReached\"),\n Type.Literal(\"UsernameInvalid\"),\n Type.Object({\n UsernameTooShort: Type.Number(),\n }),\n Type.Object({\n UsernameTooLong: Type.Number(),\n }),\n Type.Literal(\"CyclesBalanceTooLow\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n PublicKeyInvalid: Type.String(),\n }),\n Type.Literal(\"ReferralCodeInvalid\"),\n Type.Literal(\"ReferralCodeAlreadyClaimed\"),\n Type.Literal(\"ReferralCodeExpired\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const LocalUserIndexChatEventsEventsContext = Type.Union([\n Type.Object({\n Direct: UserId,\n }),\n Type.Object({\n Group: Type.Tuple([ChatId, Type.Union([MessageIndex, Type.Null()])]),\n }),\n Type.Object({\n Channel: Type.Tuple([CommunityId, ChannelId, Type.Union([MessageIndex, Type.Null()])]),\n }),\n]);\nexport const LocalUserIndexChatEventsEventsSelectionCriteria = Type.Union([\n Type.Object({\n Page: LocalUserIndexChatEventsEventsPageArgs,\n }),\n Type.Object({\n ByIndex: LocalUserIndexChatEventsEventsByIndexArgs,\n }),\n Type.Object({\n Window: LocalUserIndexChatEventsEventsWindowArgs,\n }),\n]);\nexport const LocalUserIndexInviteUsersToChannelResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Object({\n PartialSuccess: LocalUserIndexInviteUsersToChannelPartialSuccessResult,\n }),\n Type.Object({\n Failed: LocalUserIndexInviteUsersToChannelFailedResult,\n }),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n TooManyInvites: Type.Number(),\n }),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const LocalUserIndexBotChatEventsArgs = Type.Object({\n channel_id: Type.Optional(ChannelId),\n events: LocalUserIndexChatEventsEventsSelectionCriteria,\n auth_token: AuthToken,\n});\nexport const LocalUserIndexReportMessageArgs = Type.Object({\n chat_id: MultiUserChat,\n thread_root_message_index: Type.Optional(MessageIndex),\n event_index: EventIndex,\n reason_code: Type.Number(),\n notes: Type.Optional(Type.String()),\n});\nexport const LocalUserIndexBotSendMessageResponse = Type.Union([\n Type.Object({\n Success: LocalUserIndexBotSendMessageSuccessResult,\n }),\n Type.Object({\n FailedAuthentication: Type.String(),\n }),\n Type.Object({\n InvalidRequest: Type.String(),\n }),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"Frozen\"),\n Type.Literal(\"ThreadNotFound\"),\n Type.Literal(\"MessageAlreadyFinalised\"),\n Type.Object({\n C2CError: Type.Tuple([Type.Number(), Type.String()]),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const LocalUserIndexGroupAndCommunitySummaryUpdatesArgs = Type.Object({\n requests: Type.Array(LocalUserIndexGroupAndCommunitySummaryUpdatesSummaryUpdatesArgs),\n});\nexport const CommunitySelectedChannelUpdatesResponse = Type.Union([\n Type.Object({\n Success: SelectedGroupUpdates,\n }),\n Type.Object({\n SuccessNoUpdates: Type.BigInt(),\n }),\n Type.Literal(\"PrivateCommunity\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"PrivateChannel\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunitySelectedChannelInitialSuccessResult = Type.Object({\n timestamp: Type.BigInt(),\n last_updated: Type.BigInt(),\n latest_event_index: EventIndex,\n members: Type.Array(GroupMember),\n basic_members: Type.Array(UserId),\n blocked_users: Type.Array(UserId),\n invited_users: Type.Array(UserId),\n pinned_messages: Type.Array(MessageIndex),\n chat_rules: VersionedRules,\n api_keys: Type.Array(PublicApiKeyDetails),\n});\nexport const CommunityCommunityMembersResponse = Type.Union([\n Type.Object({\n Success: CommunityCommunityMembersSuccessResult,\n }),\n Type.Literal(\"PrivateCommunity\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityAddMembersToChannelResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Object({\n PartialSuccess: CommunityAddMembersToChannelPartialSuccessResult,\n }),\n Type.Object({\n Failed: CommunityAddMembersToChannelFailedResult,\n }),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"CommunityPublic\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Object({\n UserLimitReached: Type.Number(),\n }),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityGenerateBotApiKeyResponse = Type.Union([\n Type.Object({\n Success: CommunityGenerateBotApiKeySuccessResult,\n }),\n Type.Literal(\"BotNotFound\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunitySelectedInitialSuccessResult = Type.Object({\n timestamp: Type.BigInt(),\n last_updated: Type.BigInt(),\n latest_event_index: EventIndex,\n members: Type.Array(CommunityMember),\n bots: Type.Array(InstalledBotDetails),\n api_keys: Type.Array(PublicApiKeyDetails),\n basic_members: Type.Array(UserId),\n blocked_users: Type.Array(UserId),\n invited_users: Type.Array(UserId),\n chat_rules: VersionedRules,\n user_groups: Type.Array(UserGroupDetails),\n referrals: Type.Array(UserId),\n});\nexport const CommunityVideoCallParticipantsResponse = Type.Union([\n Type.Object({\n Success: VideoCallParticipants,\n }),\n Type.Literal(\"VideoCallNotFound\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityCreateChannelResponse = Type.Union([\n Type.Object({\n Success: CommunityCreateChannelSuccessResult,\n }),\n Type.Object({\n NameTooShort: FieldTooShortResult,\n }),\n Type.Object({\n NameTooLong: FieldTooLongResult,\n }),\n Type.Literal(\"NameReserved\"),\n Type.Object({\n DescriptionTooLong: FieldTooLongResult,\n }),\n Type.Object({\n RulesTooShort: FieldTooShortResult,\n }),\n Type.Object({\n RulesTooLong: FieldTooLongResult,\n }),\n Type.Object({\n AvatarTooBig: FieldTooLongResult,\n }),\n Type.Literal(\"AccessGateInvalid\"),\n Type.Object({\n MaxChannelsCreated: Type.Number(),\n }),\n Type.Literal(\"NameTaken\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"ExternalUrlInvalid\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunitySelectedUpdatesSuccessResult = Type.Object({\n timestamp: Type.BigInt(),\n last_updated: Type.BigInt(),\n members_added_or_updated: Type.Array(CommunityMember),\n members_removed: Type.Array(UserId),\n bots_added_or_updated: Type.Array(InstalledBotDetails),\n bots_removed: Type.Array(UserId),\n api_keys_generated: Type.Array(PublicApiKeyDetails),\n blocked_users_added: Type.Array(UserId),\n blocked_users_removed: Type.Array(UserId),\n invited_users: Type.Optional(Type.Array(UserId)),\n chat_rules: Type.Optional(VersionedRules),\n user_groups: Type.Array(UserGroupDetails),\n user_groups_deleted: Type.Array(Type.Number()),\n referrals_added: Type.Array(UserId),\n referrals_removed: Type.Array(UserId),\n});\nexport const CommunitySelectedUpdatesResponse = Type.Union([\n Type.Object({\n Success: CommunitySelectedUpdatesSuccessResult,\n }),\n Type.Object({\n SuccessNoUpdates: Type.BigInt(),\n }),\n Type.Literal(\"PrivateCommunity\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityImportGroupArgs = Type.Object({\n group_id: ChatId,\n});\nexport const CommunityUpdateChannelResponse = Type.Union([\n Type.Object({\n SuccessV2: CommunityUpdateChannelSuccessResult,\n }),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Object({\n NameTooShort: FieldTooShortResult,\n }),\n Type.Object({\n NameTooLong: FieldTooLongResult,\n }),\n Type.Literal(\"NameReserved\"),\n Type.Object({\n DescriptionTooLong: FieldTooLongResult,\n }),\n Type.Object({\n AvatarTooBig: FieldTooLongResult,\n }),\n Type.Literal(\"AccessGateInvalid\"),\n Type.Literal(\"NameTaken\"),\n Type.Object({\n RulesTooLong: FieldTooLongResult,\n }),\n Type.Object({\n RulesTooShort: FieldTooShortResult,\n }),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"ExternalUrlInvalid\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const StorageBucketDeleteFilesResponse = Type.Object({\n success: Type.Array(Type.BigInt()),\n failures: Type.Array(StorageBucketDeleteFilesDeleteFileFailure),\n});\nexport const ProposalsBotTransferSnsTreasuryFunds = Type.Object({\n treasury: ProposalsBotTreasury,\n amount: Type.BigInt(),\n to: AccountICRC1,\n memo: Type.Optional(Type.BigInt()),\n});\nexport const ProposalsBotMintSnsTokens = Type.Object({\n amount: Type.BigInt(),\n to: AccountICRC1,\n memo: Type.Optional(Type.BigInt()),\n});\nexport const OnlineUsersLastOnlineResponse = Type.Object({\n Success: Type.Array(OnlineUsersLastOnlineUserLastOnline),\n});\nexport const GroupUpdateGroupResponse = Type.Union([\n Type.Object({\n SuccessV2: GroupUpdateGroupSuccessResult,\n }),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Object({\n NameTooShort: FieldTooShortResult,\n }),\n Type.Object({\n NameTooLong: FieldTooLongResult,\n }),\n Type.Literal(\"NameReserved\"),\n Type.Object({\n DescriptionTooLong: FieldTooLongResult,\n }),\n Type.Object({\n RulesTooShort: FieldTooShortResult,\n }),\n Type.Object({\n RulesTooLong: FieldTooLongResult,\n }),\n Type.Object({\n AvatarTooBig: FieldTooLongResult,\n }),\n Type.Literal(\"AccessGateInvalid\"),\n Type.Literal(\"NameTaken\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Literal(\"InternalError\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupSelectedInitialSuccessResult = Type.Object({\n timestamp: Type.BigInt(),\n last_updated: Type.BigInt(),\n latest_event_index: EventIndex,\n participants: Type.Array(GroupMember),\n bots: Type.Array(InstalledBotDetails),\n api_keys: Type.Array(PublicApiKeyDetails),\n basic_members: Type.Array(UserId),\n blocked_users: Type.Array(UserId),\n invited_users: Type.Array(UserId),\n pinned_messages: Type.Array(MessageIndex),\n chat_rules: VersionedRules,\n});\nexport const GroupSelectedInitialResponse = Type.Union([\n Type.Object({\n Success: GroupSelectedInitialSuccessResult,\n }),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupVideoCallParticipantsResponse = Type.Union([\n Type.Object({\n Success: VideoCallParticipants,\n }),\n Type.Literal(\"VideoCallNotFound\"),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupSelectedUpdatesResponse = Type.Union([\n Type.Object({\n Success: SelectedGroupUpdates,\n }),\n Type.Object({\n SuccessNoUpdates: Type.BigInt(),\n }),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserCommunitySummaryUpdates = Type.Object({\n community_id: CommunityId,\n channels: Type.Array(UserChannelSummaryUpdates),\n index: Type.Optional(Type.Number()),\n archived: Type.Optional(Type.Boolean()),\n pinned: Type.Optional(Type.Array(ChannelId)),\n});\nexport const UserManageFavouriteChatsArgs = Type.Object({\n to_add: Type.Array(Chat),\n to_remove: Type.Array(Chat),\n});\nexport const UserGroupChatSummary = Type.Object({\n chat_id: ChatId,\n local_user_index_canister_id: TSPrincipal,\n read_by_me_up_to: Type.Optional(MessageIndex),\n threads_read: Type.Record(MessageIndex, MessageIndex),\n archived: Type.Boolean(),\n date_read_pinned: Type.Optional(Type.BigInt()),\n});\nexport const UserMessageActivityEvent = Type.Object({\n chat: Chat,\n thread_root_message_index: Type.Optional(MessageIndex),\n message_index: MessageIndex,\n message_id: MessageId,\n event_index: EventIndex,\n activity: UserMessageActivity,\n timestamp: Type.BigInt(),\n user_id: Type.Optional(UserId),\n});\nexport const UserCreateGroupSuccessResult = Type.Object({\n chat_id: ChatId,\n});\nexport const UserCommunitySummary = Type.Object({\n community_id: CommunityId,\n local_user_index_canister_id: TSPrincipal,\n channels: Type.Array(UserChannelSummary),\n index: Type.Number(),\n archived: Type.Boolean(),\n pinned: Type.Array(ChannelId),\n});\nexport const UserSwapTokensExchangeArgs = Type.Union([\n Type.Object({\n ICPSwap: UserSwapTokensICPSwapArgs,\n }),\n Type.Object({\n Sonic: UserSwapTokensICPSwapArgs,\n }),\n Type.Object({\n KongSwap: UserSwapTokensICPSwapArgs,\n }),\n]);\nexport const UserSwapTokensArgs = Type.Object({\n swap_id: Type.BigInt(),\n input_token: TokenInfo,\n output_token: TokenInfo,\n input_amount: Type.BigInt(),\n exchange_args: UserSwapTokensExchangeArgs,\n min_output_amount: Type.BigInt(),\n pin: Type.Optional(PinNumberWrapper),\n});\nexport const UserSetAvatarArgs = Type.Object({\n avatar: Type.Optional(Document),\n});\nexport const UserMessageActivityFeedSuccessResult = Type.Object({\n events: Type.Array(UserMessageActivityEvent),\n total: Type.Number(),\n});\nexport const UserMessageActivityFeedResponse = Type.Object({\n Success: UserMessageActivityFeedSuccessResult,\n});\nexport const UserGroupChatSummaryUpdates = Type.Object({\n chat_id: ChatId,\n read_by_me_up_to: Type.Optional(MessageIndex),\n threads_read: Type.Record(MessageIndex, MessageIndex),\n archived: Type.Optional(Type.Boolean()),\n date_read_pinned: Type.Optional(Type.BigInt()),\n});\nexport const UserTipMessageArgs = Type.Object({\n chat: Chat,\n recipient: UserId,\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n ledger: TSPrincipal,\n token_symbol: Type.String(),\n amount: Type.BigInt(),\n fee: Type.BigInt(),\n decimals: Type.Number(),\n pin: Type.Optional(PinNumberWrapper),\n});\nexport const UserAddHotGroupExclusionsArgs = Type.Object({\n groups: Type.Array(ChatId),\n duration: Type.Optional(Type.BigInt()),\n});\nexport const UserChatInList = Type.Union([\n Type.Object({\n Direct: ChatId,\n }),\n Type.Object({\n Group: ChatId,\n }),\n Type.Object({\n Favourite: Chat,\n }),\n Type.Object({\n Community: Type.Tuple([CommunityId, ChannelId]),\n }),\n]);\nexport const UserPinChatArgs = Type.Object({\n chat: UserChatInList,\n});\nexport const UserContactsResponse = Type.Object({\n Success: UserContactsSuccessResult,\n});\nexport const UserInitialStateCommunitiesInitial = Type.Object({\n summaries: Type.Array(UserCommunitySummary),\n});\nexport const UserInitialStateGroupChatsInitial = Type.Object({\n summaries: Type.Array(UserGroupChatSummary),\n pinned: Type.Array(ChatId),\n});\nexport const UserInitialStateFavouriteChatsInitial = Type.Object({\n chats: Type.Array(Chat),\n pinned: Type.Array(Chat),\n});\nexport const UserHotGroupExclusionsResponse = Type.Object({\n Success: Type.Array(ChatId),\n});\nexport const UserUpdatesGroupChatsUpdates = Type.Object({\n added: Type.Array(UserGroupChatSummary),\n updated: Type.Array(UserGroupChatSummaryUpdates),\n removed: Type.Array(ChatId),\n pinned: Type.Optional(Type.Array(ChatId)),\n});\nexport const UserUpdatesCommunitiesUpdates = Type.Object({\n added: Type.Array(UserCommunitySummary),\n updated: Type.Array(UserCommunitySummaryUpdates),\n removed: Type.Array(CommunityId),\n});\nexport const UserUpdatesFavouriteChatsUpdates = Type.Object({\n chats: Type.Optional(Type.Array(Chat)),\n pinned: Type.Optional(Type.Array(Chat)),\n});\nexport const UserLeaveGroupArgs = Type.Object({\n chat_id: ChatId,\n});\nexport const UserMuteNotificationsArgs = Type.Object({\n chat_id: ChatId,\n});\nexport const UserApproveTransferArgs = Type.Object({\n spender: AccountICRC1,\n ledger_canister_id: TSPrincipal,\n amount: Type.BigInt(),\n expires_in: Type.Optional(Type.BigInt()),\n pin: Type.Optional(PinNumberWrapper),\n});\nexport const UserDeleteGroupArgs = Type.Object({\n chat_id: ChatId,\n});\nexport const UserSetMessageReminderArgs = Type.Object({\n chat: Chat,\n thread_root_message_index: Type.Optional(MessageIndex),\n event_index: EventIndex,\n notes: Type.Optional(Type.String()),\n remind_at: Type.BigInt(),\n});\nexport const UserTokenSwapsTokenSwap = Type.Object({\n args: UserSwapTokensArgs,\n started: Type.BigInt(),\n icrc2: Type.Boolean(),\n transfer_or_approval: Type.Optional(Type.Union([\n Type.Object({\n Ok: Type.BigInt(),\n }),\n Type.Object({\n Err: Type.String(),\n }),\n ])),\n notified_dex: Type.Optional(Type.Union([\n Type.Object({\n Ok: Type.Null(),\n }),\n Type.Object({\n Err: Type.String(),\n }),\n ])),\n amount_swapped: Type.Optional(Type.Union([\n Type.Object({\n Ok: Type.Union([\n Type.Object({\n Ok: Type.BigInt(),\n }),\n Type.Object({\n Err: Type.String(),\n }),\n ]),\n }),\n Type.Object({\n Err: Type.String(),\n }),\n ])),\n withdrawn_from_dex: Type.Optional(Type.Union([\n Type.Object({\n Ok: Type.BigInt(),\n }),\n Type.Object({\n Err: Type.String(),\n }),\n ])),\n success: Type.Optional(Type.Boolean()),\n});\nexport const UserTokenSwapsSuccessResult = Type.Object({\n total: Type.Number(),\n swaps: Type.Array(UserTokenSwapsTokenSwap),\n});\nexport const UserArchiveUnarchiveChatsArgs = Type.Object({\n to_archive: Type.Array(Chat),\n to_unarchive: Type.Array(Chat),\n});\nexport const UserArchiveUnarchiveChatsPartialSuccessResult = Type.Object({\n chats_not_found: Type.Array(Chat),\n});\nexport const UserSendMessageSuccessResult = Type.Object({\n chat_id: ChatId,\n event_index: EventIndex,\n message_index: MessageIndex,\n timestamp: Type.BigInt(),\n expires_at: Type.Optional(Type.BigInt()),\n});\nexport const UserMarkReadChatMessagesRead = Type.Object({\n chat_id: ChatId,\n read_up_to: Type.Optional(MessageIndex),\n threads: Type.Array(UserMarkReadThreadRead),\n date_read_pinned: Type.Optional(Type.BigInt()),\n});\nexport const UserChitEventsSuccessResult = Type.Object({\n events: Type.Array(ChitEarned),\n total: Type.Number(),\n});\nexport const UserUnpinChatArgs = Type.Object({\n chat: UserChatInList,\n});\nexport const VideoContent = Type.Object({\n width: Type.Number(),\n height: Type.Number(),\n thumbnail_data: ThumbnailData,\n caption: Type.Optional(Type.String()),\n mime_type: Type.String(),\n image_blob_reference: Type.Optional(BlobReference),\n video_blob_reference: Type.Optional(BlobReference),\n});\nexport const GroupPermissions = Type.Object({\n change_roles: GroupPermissionRole,\n update_group: GroupPermissionRole,\n add_members: GroupPermissionRole,\n invite_users: GroupPermissionRole,\n remove_members: GroupPermissionRole,\n delete_messages: GroupPermissionRole,\n pin_messages: GroupPermissionRole,\n react_to_messages: GroupPermissionRole,\n mention_all_members: GroupPermissionRole,\n start_video_call: GroupPermissionRole,\n message_permissions: MessagePermissions,\n thread_permissions: Type.Optional(MessagePermissions),\n});\nexport const VideoCallContent = Type.Object({\n call_type: VideoCallType,\n ended: Type.Optional(Type.BigInt()),\n participants: Type.Array(CallParticipant),\n hidden_participants: Type.Number(),\n});\nexport const EventWrapperGroupFrozen = Type.Object({\n index: EventIndex,\n timestamp: Type.BigInt(),\n correlation_id: Type.BigInt(),\n expires_at: Type.Optional(Type.BigInt()),\n event: GroupFrozen,\n});\nexport const SignedDelegation = Type.Object({\n delegation: Delegation,\n signature: TSBytes,\n});\nexport const FailedCryptoTransaction = Type.Union([\n Type.Object({\n NNS: FailedCryptoTransactionNNS,\n }),\n Type.Object({\n ICRC1: FailedCryptoTransactionICRC1,\n }),\n Type.Object({\n ICRC2: FailedCryptoTransactionICRC2,\n }),\n]);\nexport const CompletedCryptoTransactionICRC2 = Type.Object({\n ledger: TSPrincipal,\n token: Cryptocurrency,\n amount: Type.BigInt(),\n spender: UserId,\n from: CryptoAccountICRC1,\n to: CryptoAccountICRC1,\n fee: Type.BigInt(),\n memo: Type.Optional(TSBytes),\n created: Type.BigInt(),\n block_index: Type.BigInt(),\n});\nexport const BotRegistrationStatus = Type.Union([\n Type.Literal(\"Public\"),\n Type.Object({\n Private: Type.Union([BotInstallationLocation, Type.Null()]),\n }),\n]);\nexport const EventWrapperGroupUnfrozen = Type.Object({\n index: EventIndex,\n timestamp: Type.BigInt(),\n correlation_id: Type.BigInt(),\n expires_at: Type.Optional(Type.BigInt()),\n event: GroupUnfrozen,\n});\nexport const P2PSwapContentInitial = Type.Object({\n token0: TokenInfo,\n token0_amount: Type.BigInt(),\n token1: TokenInfo,\n token1_amount: Type.BigInt(),\n expires_in: Type.BigInt(),\n caption: Type.Optional(Type.String()),\n});\nexport const PendingCryptoTransaction = Type.Union([\n Type.Object({\n NNS: PendingCryptoTransactionNNS,\n }),\n Type.Object({\n ICRC1: PendingCryptoTransactionICRC1,\n }),\n Type.Object({\n ICRC2: PendingCryptoTransactionICRC2,\n }),\n]);\nexport const BotActionScope = Type.Union([\n Type.Object({\n Chat: BotActionChatDetails,\n }),\n Type.Object({\n Community: BotActionCommunityDetails,\n }),\n]);\nexport const UserSummaryV2 = Type.Object({\n user_id: UserId,\n stable: Type.Optional(UserSummaryStable),\n volatile: Type.Optional(UserSummaryVolatile),\n});\nexport const P2PSwapStatus = Type.Union([\n Type.Literal(\"Open\"),\n Type.Object({\n Cancelled: P2PSwapCancelled,\n }),\n Type.Object({\n Expired: P2PSwapCancelled,\n }),\n Type.Object({\n Reserved: P2PSwapReserved,\n }),\n Type.Object({\n Accepted: P2PSwapAccepted,\n }),\n Type.Object({\n Completed: P2PSwapCompleted,\n }),\n]);\nexport const PollVotes = Type.Object({\n total: TotalVotes,\n user: Type.Array(Type.Number()),\n});\nexport const AccessGateNonComposite = Type.Union([\n Type.Literal(\"DiamondMember\"),\n Type.Literal(\"LifetimeDiamondMember\"),\n Type.Literal(\"UniquePerson\"),\n Type.Object({\n VerifiedCredential: VerifiedCredentialGate,\n }),\n Type.Object({\n SnsNeuron: SnsNeuronGate,\n }),\n Type.Object({\n Payment: PaymentGate,\n }),\n Type.Object({\n TokenBalance: TokenBalanceGate,\n }),\n Type.Literal(\"Locked\"),\n Type.Literal(\"ReferredByMember\"),\n]);\nexport const CompletedCryptoTransaction = Type.Union([\n Type.Object({\n NNS: CompletedCryptoTransactionNNS,\n }),\n Type.Object({\n ICRC1: CompletedCryptoTransactionICRC1,\n }),\n Type.Object({\n ICRC2: CompletedCryptoTransactionICRC2,\n }),\n]);\nexport const PermissionsChanged = Type.Object({\n old_permissions_v2: GroupPermissions,\n new_permissions_v2: GroupPermissions,\n changed_by: UserId,\n});\nexport const BotCommandArg = Type.Object({\n name: Type.String(),\n value: BotCommandArgValue,\n});\nexport const BotCommand = Type.Object({\n name: Type.String(),\n args: Type.Array(BotCommandArg),\n initiator: UserId,\n meta: Type.Optional(BotCommandMeta),\n});\nexport const Proposal = Type.Union([\n Type.Object({\n NNS: NnsProposal,\n }),\n Type.Object({\n SNS: SnsProposal,\n }),\n]);\nexport const SwapStatusError = Type.Union([\n Type.Object({\n Reserved: SwapStatusErrorReserved,\n }),\n Type.Object({\n Accepted: SwapStatusErrorAccepted,\n }),\n Type.Object({\n Completed: SwapStatusErrorCompleted,\n }),\n Type.Object({\n Expired: SwapStatusErrorExpired,\n }),\n Type.Object({\n Cancelled: SwapStatusErrorCancelled,\n }),\n]);\nexport const Notification = Type.Union([\n Type.Object({\n ac: AddedToChannelNotification,\n }),\n Type.Object({\n dm: DirectMessageNotification,\n }),\n Type.Object({\n gm: GroupMessageNotification,\n }),\n Type.Object({\n cm: ChannelMessageNotification,\n }),\n Type.Object({\n dr: DirectReactionAddedNotification,\n }),\n Type.Object({\n gr: GroupReactionAddedNotification,\n }),\n Type.Object({\n cr: ChannelReactionAddedNotification,\n }),\n Type.Object({\n dt: DirectMessageTipped,\n }),\n Type.Object({\n gt: GroupMessageTipped,\n }),\n Type.Object({\n ct: ChannelMessageTipped,\n }),\n]);\nexport const ProposalContent = Type.Object({\n governance_canister_id: TSPrincipal,\n proposal: Proposal,\n my_vote: Type.Optional(Type.Boolean()),\n});\nexport const BotCommandParam = Type.Object({\n name: Type.String(),\n description: Type.Optional(Type.String()),\n placeholder: Type.Optional(Type.String()),\n required: Type.Boolean(),\n param_type: BotCommandParamType,\n});\nexport const DiamondMembershipStatusFull = Type.Union([\n Type.Literal(\"Inactive\"),\n Type.Object({\n Active: DiamondMembershipDetails,\n }),\n Type.Literal(\"Lifetime\"),\n]);\nexport const P2PSwapContent = Type.Object({\n swap_id: Type.Number(),\n token0: TokenInfo,\n token0_amount: Type.BigInt(),\n token1: TokenInfo,\n token1_amount: Type.BigInt(),\n expires_at: Type.BigInt(),\n caption: Type.Optional(Type.String()),\n token0_txn_in: Type.BigInt(),\n status: P2PSwapStatus,\n});\nexport const GroupIndexFreezeGroupResponse = Type.Union([\n Type.Object({\n Success: EventWrapperGroupFrozen,\n }),\n Type.Literal(\"ChatAlreadyFrozen\"),\n Type.Literal(\"ChatNotFound\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n]);\nexport const GroupIndexUnfreezeCommunityResponse = Type.Union([\n Type.Object({\n Success: EventWrapperGroupUnfrozen,\n }),\n Type.Literal(\"CommunityNotFrozen\"),\n Type.Literal(\"CommunityNotFound\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupIndexFreezeCommunityResponse = Type.Union([\n Type.Object({\n Success: EventWrapperGroupFrozen,\n }),\n Type.Literal(\"CommunityAlreadyFrozen\"),\n Type.Literal(\"CommunityNotFound\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n]);\nexport const GroupIndexActiveGroupsResponse = Type.Object({\n Success: GroupIndexActiveGroupsSuccessResult,\n});\nexport const GroupIndexUnfreezeGroupResponse = Type.Union([\n Type.Object({\n Success: EventWrapperGroupUnfrozen,\n }),\n Type.Literal(\"ChatNotFrozen\"),\n Type.Literal(\"ChatNotFound\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserIndexDeleteUserArgs = Type.Object({\n user_id: UserId,\n delegation: SignedDelegation,\n});\nexport const UserIndexCurrentUserSuccessResult = Type.Object({\n user_id: UserId,\n username: Type.String(),\n date_created: Type.BigInt(),\n display_name: Type.Optional(Type.String()),\n avatar_id: Type.Optional(Type.BigInt()),\n canister_upgrade_status: CanisterUpgradeStatus,\n wasm_version: BuildVersion,\n icp_account: Type.Tuple([\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n Type.Number(),\n ]),\n referrals: Type.Array(UserId),\n is_platform_moderator: Type.Boolean(),\n is_platform_operator: Type.Boolean(),\n suspension_details: Type.Optional(SuspensionDetails),\n is_suspected_bot: Type.Boolean(),\n diamond_membership_details: Type.Optional(DiamondMembershipDetails),\n diamond_membership_status: DiamondMembershipStatusFull,\n moderation_flags_enabled: Type.Number(),\n is_unique_person: Type.Boolean(),\n});\nexport const UserIndexCurrentUserResponse = Type.Union([\n Type.Object({\n Success: UserIndexCurrentUserSuccessResult,\n }),\n Type.Literal(\"UserNotFound\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const LocalUserIndexChatEventsEventsArgs = Type.Object({\n context: LocalUserIndexChatEventsEventsContext,\n args: LocalUserIndexChatEventsEventsSelectionCriteria,\n latest_known_update: Type.Optional(Type.BigInt()),\n});\nexport const CommunityClaimPrizeResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"AlreadyClaimed\"),\n Type.Literal(\"PrizeFullyClaimed\"),\n Type.Literal(\"PrizeEnded\"),\n Type.Literal(\"LedgerError\"),\n Type.Object({\n TransferFailed: Type.Tuple([Type.String(), FailedCryptoTransaction]),\n }),\n Type.Object({\n FailedAfterTransfer: Type.Tuple([Type.String(), CompletedCryptoTransaction]),\n }),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityRegisterPollVoteResponse = Type.Union([\n Type.Object({\n Success: PollVotes,\n }),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"UserCannotChangeVote\"),\n Type.Literal(\"PollNotFound\"),\n Type.Literal(\"PollEnded\"),\n Type.Literal(\"OptionIndexOutOfRange\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityCancelP2pSwapResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Object({\n StatusError: SwapStatusError,\n }),\n Type.Literal(\"SwapNotFound\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunitySelectedChannelInitialResponse = Type.Union([\n Type.Object({\n Success: CommunitySelectedChannelInitialSuccessResult,\n }),\n Type.Literal(\"PrivateCommunity\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"PrivateChannel\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunitySelectedInitialResponse = Type.Union([\n Type.Object({\n Success: CommunitySelectedInitialSuccessResult,\n }),\n Type.Literal(\"PrivateCommunity\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityAcceptP2pSwapResponse = Type.Union([\n Type.Object({\n Success: AcceptSwapSuccess,\n }),\n Type.Literal(\"InsufficientFunds\"),\n Type.Object({\n StatusError: SwapStatusError,\n }),\n Type.Literal(\"SwapNotFound\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Literal(\"PinRequired\"),\n Type.Object({\n PinIncorrect: Type.BigInt(),\n }),\n Type.Object({\n TooManyFailedPinAttempts: Type.BigInt(),\n }),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const ProposalsBotProposalToSubmitAction = Type.Union([\n Type.Literal(\"Motion\"),\n Type.Object({\n TransferSnsTreasuryFunds: ProposalsBotTransferSnsTreasuryFunds,\n }),\n Type.Object({\n MintSnsTokens: ProposalsBotMintSnsTokens,\n }),\n Type.Literal(\"UpgradeSnsToNextVersion\"),\n Type.Literal(\"AdvanceSnsTargetVersion\"),\n Type.Object({\n UpgradeSnsControlledCanister: ProposalsBotUpgradeSnsControlledCanister,\n }),\n Type.Object({\n ExecuteGenericNervousSystemFunction: ProposalsBotExecuteGenericNervousSystemFunction,\n }),\n]);\nexport const ProposalsBotProposalToSubmit = Type.Object({\n title: Type.String(),\n summary: Type.String(),\n url: Type.String(),\n action: ProposalsBotProposalToSubmitAction,\n});\nexport const GroupClaimPrizeResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"AlreadyClaimed\"),\n Type.Literal(\"PrizeFullyClaimed\"),\n Type.Literal(\"PrizeEnded\"),\n Type.Literal(\"LedgerError\"),\n Type.Object({\n TransferFailed: Type.Tuple([Type.String(), FailedCryptoTransaction]),\n }),\n Type.Object({\n FailedAfterTransfer: Type.Tuple([Type.String(), CompletedCryptoTransaction]),\n }),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupRegisterPollVoteResponse = Type.Union([\n Type.Object({\n Success: PollVotes,\n }),\n Type.Literal(\"PollNotFound\"),\n Type.Literal(\"PollEnded\"),\n Type.Literal(\"OptionIndexOutOfRange\"),\n Type.Literal(\"UserCannotChangeVote\"),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupCancelP2pSwapResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Object({\n StatusError: SwapStatusError,\n }),\n Type.Literal(\"SwapNotFound\"),\n Type.Literal(\"UserNotInGroup\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupAcceptP2pSwapResponse = Type.Union([\n Type.Object({\n Success: AcceptSwapSuccess,\n }),\n Type.Literal(\"InsufficientFunds\"),\n Type.Object({\n StatusError: SwapStatusError,\n }),\n Type.Literal(\"SwapNotFound\"),\n Type.Literal(\"UserNotInGroup\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Literal(\"PinRequired\"),\n Type.Object({\n PinIncorrect: Type.BigInt(),\n }),\n Type.Object({\n TooManyFailedPinAttempts: Type.BigInt(),\n }),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserCreateGroupResponse = Type.Union([\n Type.Object({\n Success: UserCreateGroupSuccessResult,\n }),\n Type.Object({\n NameTooShort: FieldTooShortResult,\n }),\n Type.Object({\n NameTooLong: FieldTooLongResult,\n }),\n Type.Literal(\"NameReserved\"),\n Type.Object({\n DescriptionTooLong: FieldTooLongResult,\n }),\n Type.Object({\n RulesTooShort: FieldTooShortResult,\n }),\n Type.Object({\n RulesTooLong: FieldTooLongResult,\n }),\n Type.Object({\n AvatarTooBig: FieldTooLongResult,\n }),\n Type.Literal(\"AccessGateInvalid\"),\n Type.Object({\n MaxGroupsCreated: Type.Number(),\n }),\n Type.Literal(\"NameTaken\"),\n Type.Literal(\"Throttled\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UnauthorizedToCreatePublicGroup\"),\n Type.Literal(\"InternalError\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserCancelP2pSwapResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Literal(\"ChatNotFound\"),\n Type.Object({\n StatusError: SwapStatusError,\n }),\n Type.Literal(\"SwapNotFound\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserSetPinNumberPinNumberVerification = Type.Union([\n Type.Literal(\"None\"),\n Type.Object({\n PIN: PinNumberWrapper,\n }),\n Type.Object({\n Delegation: SignedDelegation,\n }),\n]);\nexport const UserSetPinNumberArgs = Type.Object({\n new: Type.Optional(PinNumberWrapper),\n verification: UserSetPinNumberPinNumberVerification,\n});\nexport const UserSendMessageWithTransferToGroupSuccessResult = Type.Object({\n event_index: EventIndex,\n message_index: MessageIndex,\n timestamp: Type.BigInt(),\n expires_at: Type.Optional(Type.BigInt()),\n transfer: CompletedCryptoTransaction,\n});\nexport const UserWithdrawCryptoArgs = Type.Object({\n withdrawal: PendingCryptoTransaction,\n pin: Type.Optional(PinNumberWrapper),\n});\nexport const UserWithdrawCryptoResponse = Type.Union([\n Type.Object({\n Success: CompletedCryptoTransaction,\n }),\n Type.Object({\n TransactionFailed: FailedCryptoTransaction,\n }),\n Type.Literal(\"CurrencyNotSupported\"),\n Type.Literal(\"PinRequired\"),\n Type.Object({\n PinIncorrect: Type.BigInt(),\n }),\n Type.Object({\n TooManyFailedPinAttempts: Type.BigInt(),\n }),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserTokenSwapsResponse = Type.Object({\n Success: UserTokenSwapsSuccessResult,\n});\nexport const UserArchiveUnarchiveChatsResponse = Type.Union([\n Type.Literal(\"Success\"),\n Type.Object({\n PartialSuccess: UserArchiveUnarchiveChatsPartialSuccessResult,\n }),\n Type.Literal(\"Failure\"),\n Type.Literal(\"UserSuspended\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserSendMessageTransferSuccessV2Result = Type.Object({\n chat_id: ChatId,\n event_index: EventIndex,\n message_index: MessageIndex,\n timestamp: Type.BigInt(),\n expires_at: Type.Optional(Type.BigInt()),\n transfer: CompletedCryptoTransaction,\n});\nexport const UserSendMessageResponse = Type.Union([\n Type.Object({\n Success: UserSendMessageSuccessResult,\n }),\n Type.Object({\n TransferSuccessV2: UserSendMessageTransferSuccessV2Result,\n }),\n Type.Literal(\"MessageEmpty\"),\n Type.Object({\n TextTooLong: Type.Number(),\n }),\n Type.Literal(\"RecipientBlocked\"),\n Type.Literal(\"RecipientNotFound\"),\n Type.Object({\n InvalidPoll: InvalidPollReason,\n }),\n Type.Object({\n InvalidRequest: Type.String(),\n }),\n Type.Object({\n TransferFailed: Type.String(),\n }),\n Type.Literal(\"TransferCannotBeZero\"),\n Type.Literal(\"TransferCannotBeToSelf\"),\n Type.Object({\n P2PSwapSetUpFailed: Type.String(),\n }),\n Type.Literal(\"DuplicateMessageId\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"PinRequired\"),\n Type.Object({\n PinIncorrect: Type.BigInt(),\n }),\n Type.Object({\n TooManyFailedPinAttempts: Type.BigInt(),\n }),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserSendMessageWithTransferToChannelSuccessResult = Type.Object({\n event_index: EventIndex,\n message_index: MessageIndex,\n timestamp: Type.BigInt(),\n expires_at: Type.Optional(Type.BigInt()),\n transfer: CompletedCryptoTransaction,\n});\nexport const UserMarkReadArgs = Type.Object({\n messages_read: Type.Array(UserMarkReadChatMessagesRead),\n community_messages_read: Type.Array(UserMarkReadCommunityMessagesRead),\n});\nexport const UserAcceptP2pSwapResponse = Type.Union([\n Type.Object({\n Success: AcceptSwapSuccess,\n }),\n Type.Literal(\"ChatNotFound\"),\n Type.Literal(\"InsufficientFunds\"),\n Type.Object({\n StatusError: SwapStatusError,\n }),\n Type.Literal(\"SwapNotFound\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"PinRequired\"),\n Type.Object({\n PinIncorrect: Type.BigInt(),\n }),\n Type.Object({\n TooManyFailedPinAttempts: Type.BigInt(),\n }),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserChitEventsResponse = Type.Object({\n Success: UserChitEventsSuccessResult,\n});\nexport const PollContent = Type.Object({\n config: PollConfig,\n votes: PollVotes,\n ended: Type.Boolean(),\n});\nexport const PrizeWinnerContent = Type.Object({\n winner: UserId,\n transaction: CompletedCryptoTransaction,\n prize_message: MessageIndex,\n});\nexport const BotCommandInitial = Type.Object({\n name: Type.String(),\n args: Type.Array(BotCommandArg),\n meta: Type.Optional(BotCommandMeta),\n});\nexport const BotCommandDefinition = Type.Object({\n name: Type.String(),\n description: Type.Optional(Type.String()),\n placeholder: Type.Optional(Type.String()),\n params: Type.Array(BotCommandParam),\n permissions: BotPermissions,\n default_role: Type.Optional(GroupRole),\n direct_messages: Type.Optional(Type.Boolean()),\n});\nexport const CompositeGate = Type.Object({\n inner: Type.Array(AccessGateNonComposite),\n and: Type.Boolean(),\n});\nexport const CryptoTransaction = Type.Union([\n Type.Object({\n Pending: PendingCryptoTransaction,\n }),\n Type.Object({\n Completed: CompletedCryptoTransaction,\n }),\n Type.Object({\n Failed: FailedCryptoTransaction,\n }),\n]);\nexport const BotMessageContext = Type.Object({\n command: Type.Optional(BotCommand),\n finalised: Type.Boolean(),\n});\nexport const BotMessageContent = Type.Union([\n Type.Object({\n Text: TextContent,\n }),\n Type.Object({\n Image: ImageContent,\n }),\n Type.Object({\n Video: VideoContent,\n }),\n Type.Object({\n Audio: AudioContent,\n }),\n Type.Object({\n File: FileContent,\n }),\n Type.Object({\n Poll: PollContent,\n }),\n Type.Object({\n Giphy: GiphyContent,\n }),\n]);\nexport const CurrentUserSummary = Type.Object({\n user_id: UserId,\n username: Type.String(),\n display_name: Type.Optional(Type.String()),\n avatar_id: Type.Optional(Type.BigInt()),\n is_bot: Type.Boolean(),\n is_platform_moderator: Type.Boolean(),\n is_platform_operator: Type.Boolean(),\n suspension_details: Type.Optional(SuspensionDetails),\n is_suspected_bot: Type.Boolean(),\n diamond_membership_details: Type.Optional(DiamondMembershipDetails),\n diamond_membership_status: DiamondMembershipStatusFull,\n moderation_flags_enabled: Type.Number(),\n is_unique_person: Type.Boolean(),\n});\nexport const BotMatch = Type.Object({\n id: UserId,\n score: Type.Number(),\n name: Type.String(),\n description: Type.String(),\n endpoint: Type.String(),\n owner: UserId,\n avatar_id: Type.Optional(Type.BigInt()),\n commands: Type.Array(BotCommandDefinition),\n autonomous_config: Type.Optional(AutonomousConfig),\n});\nexport const BotActionByCommandArgs = Type.Object({\n bot_id: UserId,\n command: BotCommandInitial,\n scope: BotActionScope,\n});\nexport const AccessGate = Type.Union([\n Type.Literal(\"DiamondMember\"),\n Type.Literal(\"LifetimeDiamondMember\"),\n Type.Literal(\"UniquePerson\"),\n Type.Object({\n VerifiedCredential: VerifiedCredentialGate,\n }),\n Type.Object({\n SnsNeuron: SnsNeuronGate,\n }),\n Type.Object({\n Payment: PaymentGate,\n }),\n Type.Object({\n TokenBalance: TokenBalanceGate,\n }),\n Type.Object({\n Composite: CompositeGate,\n }),\n Type.Literal(\"Locked\"),\n Type.Literal(\"ReferredByMember\"),\n]);\nexport const BotDefinition = Type.Object({\n description: Type.String(),\n commands: Type.Array(BotCommandDefinition),\n autonomous_config: Type.Optional(AutonomousConfig),\n});\nexport const UserIndexBotUpdatesBotDetails = Type.Object({\n id: UserId,\n owner: UserId,\n name: Type.String(),\n avatar_id: Type.Optional(Type.BigInt()),\n endpoint: Type.String(),\n description: Type.String(),\n commands: Type.Array(BotCommandDefinition),\n autonomous_config: Type.Optional(AutonomousConfig),\n last_updated: Type.BigInt(),\n registration_status: BotRegistrationStatus,\n});\nexport const UserIndexUsersResult = Type.Object({\n users: Type.Array(UserSummaryV2),\n current_user: Type.Optional(CurrentUserSummary),\n deleted: Type.Array(UserId),\n timestamp: Type.BigInt(),\n});\nexport const UserIndexUsersResponse = Type.Object({\n Success: UserIndexUsersResult,\n});\nexport const UserIndexExploreBotsSuccessResult = Type.Object({\n matches: Type.Array(BotMatch),\n total: Type.Number(),\n});\nexport const UserIndexExploreBotsResponse = Type.Union([\n Type.Object({\n Success: UserIndexExploreBotsSuccessResult,\n }),\n Type.Object({\n TermTooShort: Type.Number(),\n }),\n Type.Object({\n TermTooLong: Type.Number(),\n }),\n Type.Literal(\"InvalidTerm\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserIndexUpdateBotArgs = Type.Object({\n bot_id: UserId,\n owner: Type.Optional(UserId),\n principal: Type.Optional(TSPrincipal),\n avatar: OptionUpdateString,\n endpoint: Type.Optional(Type.String()),\n definition: Type.Optional(BotDefinition),\n});\nexport const UserIndexRegisterBotArgs = Type.Object({\n principal: TSPrincipal,\n name: Type.String(),\n avatar: Type.Optional(Type.String()),\n endpoint: Type.String(),\n definition: BotDefinition,\n permitted_install_location: Type.Optional(BotInstallationLocation),\n});\nexport const LocalUserIndexChatEventsArgs = Type.Object({\n requests: Type.Array(LocalUserIndexChatEventsEventsArgs),\n});\nexport const LocalUserIndexAccessTokenV2Args = Type.Union([\n Type.Object({\n StartVideoCall: StartVideoCallArgs,\n }),\n Type.Object({\n JoinVideoCall: JoinVideoCallArgs,\n }),\n Type.Object({\n MarkVideoCallAsEnded: MarkVideoCallAsEndedArgs,\n }),\n Type.Object({\n BotActionByCommand: BotActionByCommandArgs,\n }),\n Type.Object({\n BotActionByApiKey: Type.String(),\n }),\n]);\nexport const LocalUserIndexBotSendMessageArgs = Type.Object({\n channel_id: Type.Optional(ChannelId),\n message_id: Type.Optional(MessageId),\n content: BotMessageContent,\n block_level_markdown: Type.Boolean(),\n finalised: Type.Boolean(),\n auth_token: AuthToken,\n});\nexport const ProposalsBotSubmitProposalArgs = Type.Object({\n governance_canister_id: TSPrincipal,\n proposal: ProposalsBotProposalToSubmit,\n transaction: PendingCryptoTransactionICRC2,\n});\nexport const UserSendMessageWithTransferToGroupResponse = Type.Union([\n Type.Object({\n Success: UserSendMessageWithTransferToGroupSuccessResult,\n }),\n Type.Object({\n TextTooLong: Type.Number(),\n }),\n Type.Literal(\"RecipientBlocked\"),\n Type.Object({\n CallerNotInGroup: Type.Union([CompletedCryptoTransaction, Type.Null()]),\n }),\n Type.Object({\n CryptocurrencyNotSupported: Cryptocurrency,\n }),\n Type.Object({\n InvalidRequest: Type.String(),\n }),\n Type.Object({\n TransferFailed: Type.String(),\n }),\n Type.Literal(\"TransferCannotBeZero\"),\n Type.Literal(\"TransferCannotBeToSelf\"),\n Type.Object({\n P2PSwapSetUpFailed: Type.String(),\n }),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Literal(\"RulesNotAccepted\"),\n Type.Literal(\"MessageAlreadyExists\"),\n Type.Object({\n Retrying: Type.Tuple([Type.String(), CompletedCryptoTransaction]),\n }),\n Type.Literal(\"PinRequired\"),\n Type.Object({\n PinIncorrect: Type.BigInt(),\n }),\n Type.Object({\n TooManyFailedPinAttempts: Type.BigInt(),\n }),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserSendMessageWithTransferToChannelResponse = Type.Union([\n Type.Object({\n Success: UserSendMessageWithTransferToChannelSuccessResult,\n }),\n Type.Object({\n TextTooLong: Type.Number(),\n }),\n Type.Literal(\"RecipientBlocked\"),\n Type.Object({\n UserNotInCommunity: Type.Union([CompletedCryptoTransaction, Type.Null()]),\n }),\n Type.Object({\n UserNotInChannel: CompletedCryptoTransaction,\n }),\n Type.Object({\n ChannelNotFound: CompletedCryptoTransaction,\n }),\n Type.Object({\n CryptocurrencyNotSupported: Cryptocurrency,\n }),\n Type.Object({\n InvalidRequest: Type.String(),\n }),\n Type.Object({\n TransferFailed: Type.String(),\n }),\n Type.Literal(\"TransferCannotBeZero\"),\n Type.Literal(\"TransferCannotBeToSelf\"),\n Type.Object({\n P2PSwapSetUpFailed: Type.String(),\n }),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"RulesNotAccepted\"),\n Type.Literal(\"MessageAlreadyExists\"),\n Type.Literal(\"CommunityRulesNotAccepted\"),\n Type.Object({\n Retrying: Type.Tuple([Type.String(), CompletedCryptoTransaction]),\n }),\n Type.Literal(\"PinRequired\"),\n Type.Object({\n PinIncorrect: Type.BigInt(),\n }),\n Type.Object({\n TooManyFailedPinAttempts: Type.BigInt(),\n }),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CryptoContent = Type.Object({\n recipient: UserId,\n transfer: CryptoTransaction,\n caption: Type.Optional(Type.String()),\n});\nexport const PrizeContentInitial = Type.Object({\n prizes_v2: Type.Array(Type.BigInt()),\n transfer: CryptoTransaction,\n end_date: Type.BigInt(),\n caption: Type.Optional(Type.String()),\n diamond_only: Type.Boolean(),\n lifetime_diamond_only: Type.Boolean(),\n unique_person_only: Type.Boolean(),\n streak_only: Type.Number(),\n});\nexport const OptionUpdateAccessGate = Type.Union([\n Type.Literal(\"NoChange\"),\n Type.Literal(\"SetToNone\"),\n Type.Object({\n SetToSome: AccessGate,\n }),\n], { default: \"NoChange\" });\nexport const MessageContent = Type.Union([\n Type.Object({\n Text: TextContent,\n }),\n Type.Object({\n Image: ImageContent,\n }),\n Type.Object({\n Video: VideoContent,\n }),\n Type.Object({\n Audio: AudioContent,\n }),\n Type.Object({\n File: FileContent,\n }),\n Type.Object({\n Poll: PollContent,\n }),\n Type.Object({\n Crypto: CryptoContent,\n }),\n Type.Object({\n Deleted: DeletedBy,\n }),\n Type.Object({\n Giphy: GiphyContent,\n }),\n Type.Object({\n GovernanceProposal: ProposalContent,\n }),\n Type.Object({\n Prize: PrizeContent,\n }),\n Type.Object({\n PrizeWinner: PrizeWinnerContent,\n }),\n Type.Object({\n MessageReminderCreated: MessageReminderCreatedContent,\n }),\n Type.Object({\n MessageReminder: MessageReminderContent,\n }),\n Type.Object({\n ReportedMessage: ReportedMessage,\n }),\n Type.Object({\n P2PSwap: P2PSwapContent,\n }),\n Type.Object({\n VideoCall: VideoCallContent,\n }),\n Type.Object({\n Custom: CustomContent,\n }),\n]);\nexport const GroupMatch = Type.Object({\n id: ChatId,\n name: Type.String(),\n description: Type.String(),\n avatar_id: Type.Optional(Type.BigInt()),\n member_count: Type.Number(),\n gate: Type.Optional(AccessGate),\n subtype: Type.Optional(GroupSubtype),\n verified: Type.Boolean(),\n});\nexport const AccessGateConfig = Type.Object({\n gate: AccessGate,\n expiry: Type.Optional(Type.BigInt()),\n});\nexport const MessageContentInitial = Type.Union([\n Type.Object({\n Text: TextContent,\n }),\n Type.Object({\n Image: ImageContent,\n }),\n Type.Object({\n Video: VideoContent,\n }),\n Type.Object({\n Audio: AudioContent,\n }),\n Type.Object({\n File: FileContent,\n }),\n Type.Object({\n Poll: PollContent,\n }),\n Type.Object({\n Crypto: CryptoContent,\n }),\n Type.Object({\n Deleted: DeletedBy,\n }),\n Type.Object({\n Giphy: GiphyContent,\n }),\n Type.Object({\n GovernanceProposal: ProposalContent,\n }),\n Type.Object({\n Prize: PrizeContentInitial,\n }),\n Type.Object({\n MessageReminderCreated: MessageReminderCreatedContent,\n }),\n Type.Object({\n MessageReminder: MessageReminderContent,\n }),\n Type.Object({\n P2PSwap: P2PSwapContentInitial,\n }),\n Type.Object({\n Custom: CustomContent,\n }),\n]);\nexport const OptionUpdateAccessGateConfig = Type.Union([\n Type.Literal(\"NoChange\"),\n Type.Literal(\"SetToNone\"),\n Type.Object({\n SetToSome: AccessGateConfig,\n }),\n], { default: \"NoChange\" });\nexport const GroupGateUpdated = Type.Object({\n updated_by: UserId,\n new_gate: Type.Optional(AccessGate),\n new_gate_config: Type.Optional(AccessGateConfig),\n});\nexport const GroupIndexExploreGroupsSuccessResult = Type.Object({\n matches: Type.Array(GroupMatch),\n total: Type.Number(),\n});\nexport const GroupIndexExploreGroupsResponse = Type.Union([\n Type.Object({\n Success: GroupIndexExploreGroupsSuccessResult,\n }),\n Type.Object({\n TermTooShort: Type.Number(),\n }),\n Type.Object({\n TermTooLong: Type.Number(),\n }),\n Type.Literal(\"InvalidTerm\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserIndexBotUpdatesSuccessResult = Type.Object({\n added_or_updated: Type.Array(UserIndexBotUpdatesBotDetails),\n removed: Type.Array(UserId),\n timestamp: Type.BigInt(),\n});\nexport const UserIndexBotUpdatesResponse = Type.Union([\n Type.Object({\n Success: UserIndexBotUpdatesSuccessResult,\n }),\n Type.Literal(\"SuccessNoUpdates\"),\n]);\nexport const LocalUserIndexBotCreateChannelArgs = Type.Object({\n is_public: Type.Boolean(),\n name: Type.String(),\n description: Type.String(),\n rules: Rules,\n avatar: Type.Optional(Document),\n history_visible_to_new_joiners: Type.Boolean(),\n messages_visible_to_non_members: Type.Boolean(),\n permissions: Type.Optional(GroupPermissions),\n events_ttl: Type.Optional(Type.BigInt()),\n gate_config: Type.Optional(AccessGateConfig),\n external_url: Type.Optional(Type.String()),\n auth_token: AuthToken,\n});\nexport const CommunityDeletedMessageSuccessResult = Type.Object({\n content: MessageContent,\n});\nexport const CommunityDeletedMessageResponse = Type.Union([\n Type.Object({\n Success: CommunityDeletedMessageSuccessResult,\n }),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"MessageHardDeleted\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityUpdateCommunityArgs = Type.Object({\n name: Type.Optional(Type.String()),\n description: Type.Optional(Type.String()),\n rules: Type.Optional(UpdatedRules),\n avatar: OptionUpdateDocument,\n banner: OptionUpdateDocument,\n permissions: Type.Optional(OptionalCommunityPermissions),\n gate_config: OptionUpdateAccessGateConfig,\n public: Type.Optional(Type.Boolean()),\n primary_language: Type.Optional(Type.String()),\n});\nexport const CommunitySendMessageArgs = Type.Object({\n channel_id: ChannelId,\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n content: MessageContentInitial,\n sender_name: Type.String(),\n sender_display_name: Type.Optional(Type.String()),\n replies_to: Type.Optional(GroupReplyContext),\n mentioned: Type.Array(User),\n forwarding: Type.Boolean(),\n block_level_markdown: Type.Boolean(),\n community_rules_accepted: Type.Optional(Version),\n channel_rules_accepted: Type.Optional(Version),\n message_filter_failed: Type.Optional(Type.BigInt()),\n new_achievement: Type.Boolean(),\n});\nexport const CommunityCreateChannelArgs = Type.Object({\n is_public: Type.Boolean(),\n name: Type.String(),\n description: Type.String(),\n rules: Rules,\n subtype: Type.Optional(GroupSubtype),\n avatar: Type.Optional(Document),\n history_visible_to_new_joiners: Type.Boolean(),\n messages_visible_to_non_members: Type.Optional(Type.Boolean()),\n permissions_v2: Type.Optional(GroupPermissions),\n events_ttl: Type.Optional(Type.BigInt()),\n gate_config: Type.Optional(AccessGateConfig),\n external_url: Type.Optional(Type.String()),\n});\nexport const CommunityEditMessageArgs = Type.Object({\n channel_id: ChannelId,\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n content: MessageContentInitial,\n block_level_markdown: Type.Optional(Type.Boolean()),\n new_achievement: Type.Boolean(),\n});\nexport const CommunityUpdateChannelArgs = Type.Object({\n channel_id: ChannelId,\n name: Type.Optional(Type.String()),\n description: Type.Optional(Type.String()),\n rules: Type.Optional(UpdatedRules),\n avatar: OptionUpdateDocument,\n permissions_v2: Type.Optional(OptionalGroupPermissions),\n events_ttl: OptionUpdateU64,\n gate_config: OptionUpdateAccessGateConfig,\n public: Type.Optional(Type.Boolean()),\n messages_visible_to_non_members: Type.Optional(Type.Boolean()),\n external_url: OptionUpdateString,\n});\nexport const GroupDeletedMessageSuccessResult = Type.Object({\n content: MessageContent,\n});\nexport const GroupUpdateGroupArgs = Type.Object({\n name: Type.Optional(Type.String()),\n description: Type.Optional(Type.String()),\n rules: Type.Optional(UpdatedRules),\n avatar: OptionUpdateDocument,\n permissions_v2: Type.Optional(OptionalGroupPermissions),\n events_ttl: OptionUpdateU64,\n gate_config: OptionUpdateAccessGateConfig,\n public: Type.Optional(Type.Boolean()),\n messages_visible_to_non_members: Type.Optional(Type.Boolean()),\n correlation_id: Type.BigInt(),\n});\nexport const GroupSendMessageArgs = Type.Object({\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n content: MessageContentInitial,\n sender_name: Type.String(),\n sender_display_name: Type.Optional(Type.String()),\n replies_to: Type.Optional(GroupReplyContext),\n mentioned: Type.Array(User),\n forwarding: Type.Boolean(),\n block_level_markdown: Type.Boolean(),\n rules_accepted: Type.Optional(Version),\n message_filter_failed: Type.Optional(Type.BigInt()),\n new_achievement: Type.Boolean(),\n correlation_id: Type.BigInt(),\n});\nexport const GroupEditMessageArgs = Type.Object({\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n content: MessageContentInitial,\n block_level_markdown: Type.Optional(Type.Boolean()),\n new_achievement: Type.Boolean(),\n correlation_id: Type.BigInt(),\n});\nexport const UserCreateGroupArgs = Type.Object({\n is_public: Type.Boolean(),\n name: Type.String(),\n description: Type.String(),\n rules: Rules,\n avatar: Type.Optional(Document),\n history_visible_to_new_joiners: Type.Boolean(),\n messages_visible_to_non_members: Type.Optional(Type.Boolean()),\n permissions_v2: Type.Optional(GroupPermissions),\n events_ttl: Type.Optional(Type.BigInt()),\n gate_config: Type.Optional(AccessGateConfig),\n});\nexport const UserDeletedMessageSuccessResult = Type.Object({\n content: MessageContent,\n});\nexport const UserDeletedMessageResponse = Type.Union([\n Type.Object({\n Success: UserDeletedMessageSuccessResult,\n }),\n Type.Literal(\"ChatNotFound\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"MessageHardDeleted\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserSendMessageWithTransferToGroupArgs = Type.Object({\n group_id: ChatId,\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n content: MessageContentInitial,\n sender_name: Type.String(),\n sender_display_name: Type.Optional(Type.String()),\n replies_to: Type.Optional(GroupReplyContext),\n mentioned: Type.Array(User),\n block_level_markdown: Type.Boolean(),\n correlation_id: Type.BigInt(),\n rules_accepted: Type.Optional(Version),\n message_filter_failed: Type.Optional(Type.BigInt()),\n pin: Type.Optional(PinNumberWrapper),\n});\nexport const UserSendMessageArgs = Type.Object({\n recipient: UserId,\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n content: MessageContentInitial,\n replies_to: Type.Optional(ReplyContext),\n forwarding: Type.Boolean(),\n block_level_markdown: Type.Boolean(),\n message_filter_failed: Type.Optional(Type.BigInt()),\n pin: Type.Optional(PinNumberWrapper),\n correlation_id: Type.BigInt(),\n});\nexport const UserCreateCommunityArgs = Type.Object({\n is_public: Type.Boolean(),\n name: Type.String(),\n description: Type.String(),\n rules: Rules,\n avatar: Type.Optional(Document),\n banner: Type.Optional(Document),\n history_visible_to_new_joiners: Type.Boolean(),\n permissions: Type.Optional(CommunityPermissions),\n gate_config: Type.Optional(AccessGateConfig),\n default_channels: Type.Array(Type.String()),\n default_channel_rules: Type.Optional(Rules),\n primary_language: Type.String(),\n});\nexport const UserSendMessageWithTransferToChannelArgs = Type.Object({\n community_id: CommunityId,\n channel_id: ChannelId,\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n content: MessageContentInitial,\n sender_name: Type.String(),\n sender_display_name: Type.Optional(Type.String()),\n replies_to: Type.Optional(GroupReplyContext),\n mentioned: Type.Array(User),\n block_level_markdown: Type.Boolean(),\n community_rules_accepted: Type.Optional(Version),\n channel_rules_accepted: Type.Optional(Version),\n message_filter_failed: Type.Optional(Type.BigInt()),\n pin: Type.Optional(PinNumberWrapper),\n});\nexport const UserEditMessageArgs = Type.Object({\n user_id: UserId,\n thread_root_message_index: Type.Optional(MessageIndex),\n message_id: MessageId,\n content: MessageContentInitial,\n block_level_markdown: Type.Optional(Type.Boolean()),\n correlation_id: Type.BigInt(),\n});\nexport const ChannelMatch = Type.Object({\n id: ChannelId,\n name: Type.String(),\n description: Type.String(),\n avatar_id: Type.Optional(Type.BigInt()),\n member_count: Type.Number(),\n gate: Type.Optional(AccessGate),\n gate_config: Type.Optional(AccessGateConfig),\n subtype: Type.Optional(GroupSubtype),\n is_public: Type.Boolean(),\n});\nexport const Message = Type.Object({\n message_index: MessageIndex,\n message_id: MessageId,\n sender: UserId,\n content: MessageContent,\n bot_context: Type.Optional(BotMessageContext),\n replies_to: Type.Optional(ReplyContext),\n reactions: Type.Array(Type.Tuple([Reaction, Type.Array(UserId)])),\n tips: Tips,\n thread_summary: Type.Optional(ThreadSummary),\n edited: Type.Boolean(),\n forwarded: Type.Boolean(),\n block_level_markdown: Type.Boolean(),\n});\nexport const ChatDetails = Type.Object({\n name: Type.String(),\n description: Type.String(),\n avatar_id: Type.Optional(Type.BigInt()),\n is_public: Type.Boolean(),\n history_visible_to_new_joiners: Type.Boolean(),\n messages_visible_to_non_members: Type.Boolean(),\n permissions: GroupPermissions,\n rules: VersionedRules,\n events_ttl: Type.Optional(Type.BigInt()),\n events_ttl_last_updated: Type.Optional(Type.BigInt()),\n gate_config: Type.Optional(AccessGateConfig),\n video_call_in_progress: Type.Optional(VideoCall),\n verified: Type.Optional(Type.Boolean()),\n frozen: Type.Optional(FrozenGroupInfo),\n date_last_pinned: Type.Optional(Type.BigInt()),\n last_updated: Type.BigInt(),\n external_url: Type.Optional(Type.String()),\n latest_event_index: EventIndex,\n latest_message_index: Type.Optional(MessageIndex),\n member_count: Type.Number(),\n});\nexport const CommunityMatch = Type.Object({\n id: CommunityId,\n score: Type.Number(),\n name: Type.String(),\n description: Type.String(),\n avatar_id: Type.Optional(Type.BigInt()),\n banner_id: Type.Optional(Type.BigInt()),\n member_count: Type.Number(),\n channel_count: Type.Number(),\n gate: Type.Optional(AccessGate),\n gate_config: Type.Optional(AccessGateConfig),\n moderation_flags: Type.Number(),\n primary_language: Type.String(),\n verified: Type.Boolean(),\n});\nexport const EventWrapperMessage = Type.Object({\n index: EventIndex,\n timestamp: Type.BigInt(),\n correlation_id: Type.BigInt(),\n expires_at: Type.Optional(Type.BigInt()),\n event: Message,\n});\nexport const ChatEvent = Type.Union([\n Type.Literal(\"Empty\"),\n Type.Object({\n Message: Message,\n }),\n Type.Object({\n GroupChatCreated: GroupCreated,\n }),\n Type.Object({\n DirectChatCreated: DirectChatCreated,\n }),\n Type.Object({\n GroupNameChanged: GroupNameChanged,\n }),\n Type.Object({\n GroupDescriptionChanged: GroupDescriptionChanged,\n }),\n Type.Object({\n GroupRulesChanged: GroupRulesChanged,\n }),\n Type.Object({\n AvatarChanged: AvatarChanged,\n }),\n Type.Object({\n ParticipantsAdded: MembersAdded,\n }),\n Type.Object({\n ParticipantsRemoved: MembersRemoved,\n }),\n Type.Object({\n ParticipantJoined: MemberJoined,\n }),\n Type.Object({\n ParticipantLeft: MemberLeft,\n }),\n Type.Object({\n RoleChanged: RoleChanged,\n }),\n Type.Object({\n UsersBlocked: UsersBlocked,\n }),\n Type.Object({\n UsersUnblocked: UsersUnblocked,\n }),\n Type.Object({\n MessagePinned: MessagePinned,\n }),\n Type.Object({\n MessageUnpinned: MessageUnpinned,\n }),\n Type.Object({\n PermissionsChanged: PermissionsChanged,\n }),\n Type.Object({\n GroupVisibilityChanged: GroupVisibilityChanged,\n }),\n Type.Object({\n GroupInviteCodeChanged: GroupInviteCodeChanged,\n }),\n Type.Object({\n ChatFrozen: GroupFrozen,\n }),\n Type.Object({\n ChatUnfrozen: GroupUnfrozen,\n }),\n Type.Object({\n EventsTimeToLiveUpdated: EventsTimeToLiveUpdated,\n }),\n Type.Object({\n GroupGateUpdated: GroupGateUpdated,\n }),\n Type.Object({\n UsersInvited: UsersInvited,\n }),\n Type.Object({\n MembersAddedToDefaultChannel: MembersAddedToDefaultChannel,\n }),\n Type.Object({\n ExternalUrlUpdated: ExternalUrlUpdated,\n }),\n Type.Object({\n BotAdded: BotAdded,\n }),\n Type.Object({\n BotRemoved: BotRemoved,\n }),\n Type.Object({\n BotUpdated: BotUpdated,\n }),\n Type.Literal(\"FailedToDeserialize\"),\n]);\nexport const CommunityCanisterChannelSummaryUpdates = Type.Object({\n channel_id: ChannelId,\n last_updated: Type.BigInt(),\n name: Type.Optional(Type.String()),\n description: Type.Optional(Type.String()),\n subtype: OptionUpdateGroupSubtype,\n avatar_id: OptionUpdateU128,\n is_public: Type.Optional(Type.Boolean()),\n messages_visible_to_non_members: Type.Optional(Type.Boolean()),\n latest_message: Type.Optional(EventWrapperMessage),\n latest_message_sender_display_name: Type.Optional(Type.String()),\n latest_event_index: Type.Optional(EventIndex),\n latest_message_index: Type.Optional(MessageIndex),\n member_count: Type.Optional(Type.Number()),\n permissions_v2: Type.Optional(GroupPermissions),\n updated_events: Type.Array(Type.Tuple([Type.Union([MessageIndex, Type.Null()]), EventIndex, Type.BigInt()])),\n metrics: Type.Optional(ChatMetrics),\n date_last_pinned: Type.Optional(Type.BigInt()),\n events_ttl: OptionUpdateU64,\n events_ttl_last_updated: Type.Optional(Type.BigInt()),\n gate: OptionUpdateAccessGate,\n gate_config: OptionUpdateAccessGateConfig,\n membership: Type.Optional(GroupMembershipUpdates),\n video_call_in_progress: OptionUpdateVideoCall,\n external_url: OptionUpdateString,\n any_updates_missed: Type.Boolean(),\n});\nexport const GroupIndexExploreCommunitiesSuccessResult = Type.Object({\n matches: Type.Array(CommunityMatch),\n total: Type.Number(),\n});\nexport const GroupIndexExploreCommunitiesResponse = Type.Union([\n Type.Object({\n Success: GroupIndexExploreCommunitiesSuccessResult,\n }),\n Type.Object({\n TermTooShort: Type.Number(),\n }),\n Type.Object({\n TermTooLong: Type.Number(),\n }),\n Type.Literal(\"InvalidTerm\"),\n Type.Literal(\"InvalidFlags\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const LocalUserIndexBotChatDetailsResponse = Type.Union([\n Type.Object({\n Success: ChatDetails,\n }),\n Type.Object({\n FailedAuthentication: Type.String(),\n }),\n Type.Literal(\"DirectChatUnsupported\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"NotFound\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityUndeleteMessagesSuccessResult = Type.Object({\n messages: Type.Array(Message),\n});\nexport const CommunityUndeleteMessagesResponse = Type.Union([\n Type.Object({\n Success: CommunityUndeleteMessagesSuccessResult,\n }),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"GroupNotFound\"),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityExploreChannelsSuccessResult = Type.Object({\n matches: Type.Array(ChannelMatch),\n total: Type.Number(),\n});\nexport const CommunityExploreChannelsResponse = Type.Union([\n Type.Object({\n Success: CommunityExploreChannelsSuccessResult,\n }),\n Type.Object({\n TermTooShort: Type.Number(),\n }),\n Type.Object({\n TermTooLong: Type.Number(),\n }),\n Type.Literal(\"InvalidTerm\"),\n Type.Literal(\"PrivateCommunity\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupDeletedMessageResponse = Type.Union([\n Type.Object({\n Success: GroupDeletedMessageSuccessResult,\n }),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"MessageHardDeleted\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupUndeleteMessagesSuccessResult = Type.Object({\n messages: Type.Array(Message),\n});\nexport const GroupUndeleteMessagesResponse = Type.Union([\n Type.Object({\n Success: GroupUndeleteMessagesSuccessResult,\n }),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Literal(\"MessageNotFound\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserUndeleteMessagesSuccessResult = Type.Object({\n messages: Type.Array(Message),\n});\nexport const UserUndeleteMessagesResponse = Type.Union([\n Type.Object({\n Success: UserUndeleteMessagesSuccessResult,\n }),\n Type.Literal(\"ChatNotFound\"),\n Type.Literal(\"UserSuspended\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const DirectChatSummary = Type.Object({\n them: UserId,\n last_updated: Type.BigInt(),\n latest_message: Type.Optional(EventWrapperMessage),\n latest_event_index: EventIndex,\n latest_message_index: Type.Optional(MessageIndex),\n date_created: Type.BigInt(),\n read_by_me_up_to: Type.Optional(MessageIndex),\n read_by_them_up_to: Type.Optional(MessageIndex),\n notifications_muted: Type.Boolean(),\n metrics: ChatMetrics,\n my_metrics: ChatMetrics,\n archived: Type.Boolean(),\n events_ttl: Type.Optional(Type.BigInt()),\n events_ttl_last_updated: Type.BigInt(),\n video_call_in_progress: Type.Optional(VideoCall),\n});\nexport const MessagesResponse = Type.Object({\n messages: Type.Array(EventWrapperMessage),\n latest_event_index: EventIndex,\n chat_last_updated: Type.BigInt(),\n});\nexport const GroupCanisterGroupChatSummary = Type.Object({\n chat_id: ChatId,\n local_user_index_canister_id: TSPrincipal,\n last_updated: Type.BigInt(),\n name: Type.String(),\n description: Type.String(),\n subtype: Type.Optional(GroupSubtype),\n avatar_id: Type.Optional(Type.BigInt()),\n is_public: Type.Boolean(),\n history_visible_to_new_joiners: Type.Boolean(),\n messages_visible_to_non_members: Type.Boolean(),\n min_visible_event_index: EventIndex,\n min_visible_message_index: MessageIndex,\n latest_message: Type.Optional(EventWrapperMessage),\n latest_event_index: EventIndex,\n latest_message_index: Type.Optional(MessageIndex),\n joined: Type.BigInt(),\n participant_count: Type.Number(),\n role: GroupRole,\n mentions: Type.Array(HydratedMention),\n wasm_version: BuildVersion,\n permissions_v2: GroupPermissions,\n notifications_muted: Type.Boolean(),\n metrics: ChatMetrics,\n my_metrics: ChatMetrics,\n latest_threads: Type.Array(GroupCanisterThreadDetails),\n frozen: Type.Optional(FrozenGroupInfo),\n date_last_pinned: Type.Optional(Type.BigInt()),\n events_ttl: Type.Optional(Type.BigInt()),\n events_ttl_last_updated: Type.BigInt(),\n gate: Type.Optional(AccessGate),\n gate_config: Type.Optional(AccessGateConfig),\n rules_accepted: Type.Boolean(),\n membership: Type.Optional(GroupMembership),\n video_call_in_progress: Type.Optional(VideoCall),\n verified: Type.Boolean(),\n});\nexport const EventWrapperChatEvent = Type.Object({\n index: EventIndex,\n timestamp: Type.BigInt(),\n correlation_id: Type.BigInt(),\n expires_at: Type.Optional(Type.BigInt()),\n event: ChatEvent,\n});\nexport const ThreadPreview = Type.Object({\n root_message: EventWrapperMessage,\n latest_replies: Type.Array(EventWrapperMessage),\n total_replies: Type.Number(),\n});\nexport const GroupCanisterGroupChatSummaryUpdates = Type.Object({\n chat_id: ChatId,\n last_updated: Type.BigInt(),\n name: Type.Optional(Type.String()),\n description: Type.Optional(Type.String()),\n subtype: OptionUpdateGroupSubtype,\n avatar_id: OptionUpdateU128,\n latest_message: Type.Optional(EventWrapperMessage),\n latest_event_index: Type.Optional(EventIndex),\n latest_message_index: Type.Optional(MessageIndex),\n participant_count: Type.Optional(Type.Number()),\n role: Type.Optional(GroupRole),\n mentions: Type.Array(HydratedMention),\n wasm_version: Type.Optional(BuildVersion),\n permissions_v2: Type.Optional(GroupPermissions),\n updated_events: Type.Array(Type.Tuple([Type.Union([MessageIndex, Type.Null()]), EventIndex, Type.BigInt()])),\n metrics: Type.Optional(ChatMetrics),\n my_metrics: Type.Optional(ChatMetrics),\n is_public: Type.Optional(Type.Boolean()),\n messages_visible_to_non_members: Type.Optional(Type.Boolean()),\n latest_threads: Type.Array(GroupCanisterThreadDetails),\n unfollowed_threads: Type.Array(MessageIndex),\n notifications_muted: Type.Optional(Type.Boolean()),\n frozen: OptionUpdateFrozenGroupInfo,\n date_last_pinned: Type.Optional(Type.BigInt()),\n events_ttl: OptionUpdateU64,\n events_ttl_last_updated: Type.Optional(Type.BigInt()),\n gate: OptionUpdateAccessGate,\n gate_config: OptionUpdateAccessGateConfig,\n rules_accepted: Type.Optional(Type.Boolean()),\n membership: Type.Optional(GroupMembershipUpdates),\n video_call_in_progress: OptionUpdateVideoCall,\n any_updates_missed: Type.Boolean(),\n verified: Type.Optional(Type.Boolean()),\n});\nexport const DirectChatSummaryUpdates = Type.Object({\n chat_id: ChatId,\n last_updated: Type.BigInt(),\n latest_message: Type.Optional(EventWrapperMessage),\n latest_event_index: Type.Optional(EventIndex),\n latest_message_index: Type.Optional(MessageIndex),\n read_by_me_up_to: Type.Optional(MessageIndex),\n read_by_them_up_to: Type.Optional(MessageIndex),\n notifications_muted: Type.Optional(Type.Boolean()),\n updated_events: Type.Array(Type.Tuple([EventIndex, Type.BigInt()])),\n metrics: Type.Optional(ChatMetrics),\n my_metrics: Type.Optional(ChatMetrics),\n archived: Type.Optional(Type.Boolean()),\n events_ttl: OptionUpdateU64,\n events_ttl_last_updated: Type.Optional(Type.BigInt()),\n video_call_in_progress: OptionUpdateVideoCall,\n});\nexport const PublicGroupSummary = Type.Object({\n chat_id: ChatId,\n local_user_index_canister_id: TSPrincipal,\n last_updated: Type.BigInt(),\n name: Type.String(),\n description: Type.String(),\n subtype: Type.Optional(GroupSubtype),\n history_visible_to_new_joiners: Type.Boolean(),\n messages_visible_to_non_members: Type.Boolean(),\n avatar_id: Type.Optional(Type.BigInt()),\n latest_message: Type.Optional(EventWrapperMessage),\n latest_event_index: EventIndex,\n latest_message_index: Type.Optional(MessageIndex),\n participant_count: Type.Number(),\n wasm_version: BuildVersion,\n is_public: Type.Boolean(),\n frozen: Type.Optional(FrozenGroupInfo),\n events_ttl: Type.Optional(Type.BigInt()),\n events_ttl_last_updated: Type.BigInt(),\n gate: Type.Optional(AccessGate),\n gate_config: Type.Optional(AccessGateConfig),\n});\nexport const CommunityCanisterChannelSummary = Type.Object({\n channel_id: ChannelId,\n last_updated: Type.BigInt(),\n name: Type.String(),\n description: Type.String(),\n subtype: Type.Optional(GroupSubtype),\n avatar_id: Type.Optional(Type.BigInt()),\n is_public: Type.Boolean(),\n history_visible_to_new_joiners: Type.Boolean(),\n messages_visible_to_non_members: Type.Boolean(),\n min_visible_event_index: EventIndex,\n min_visible_message_index: MessageIndex,\n latest_message: Type.Optional(EventWrapperMessage),\n latest_message_sender_display_name: Type.Optional(Type.String()),\n latest_event_index: EventIndex,\n latest_message_index: Type.Optional(MessageIndex),\n member_count: Type.Number(),\n permissions_v2: GroupPermissions,\n metrics: ChatMetrics,\n date_last_pinned: Type.Optional(Type.BigInt()),\n events_ttl: Type.Optional(Type.BigInt()),\n events_ttl_last_updated: Type.BigInt(),\n gate: Type.Optional(AccessGate),\n gate_config: Type.Optional(AccessGateConfig),\n membership: Type.Optional(GroupMembership),\n video_call_in_progress: Type.Optional(VideoCall),\n is_invited: Type.Optional(Type.Boolean()),\n external_url: Type.Optional(Type.String()),\n});\nexport const GroupIndexRecommendedGroupsSuccessResult = Type.Object({\n groups: Type.Array(PublicGroupSummary),\n});\nexport const GroupIndexRecommendedGroupsResponse = Type.Object({\n Success: GroupIndexRecommendedGroupsSuccessResult,\n});\nexport const LocalUserIndexJoinGroupResponse = Type.Union([\n Type.Object({\n Success: GroupCanisterGroupChatSummary,\n }),\n Type.Literal(\"AlreadyInGroup\"),\n Type.Object({\n AlreadyInGroupV2: GroupCanisterGroupChatSummary,\n }),\n Type.Object({\n GateCheckFailed: GateCheckFailedReason,\n }),\n Type.Literal(\"GroupNotFound\"),\n Type.Literal(\"GroupNotPublic\"),\n Type.Literal(\"NotInvited\"),\n Type.Object({\n ParticipantLimitReached: Type.Number(),\n }),\n Type.Literal(\"Blocked\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"ChatFrozen\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityChannelSummaryUpdatesResponse = Type.Union([\n Type.Object({\n SuccessAdded: CommunityCanisterChannelSummary,\n }),\n Type.Object({\n SuccessUpdated: CommunityCanisterChannelSummaryUpdates,\n }),\n Type.Literal(\"SuccessNoUpdates\"),\n Type.Literal(\"PrivateCommunity\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"PrivateChannel\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityChannelSummaryResponse = Type.Union([\n Type.Object({\n Success: CommunityCanisterChannelSummary,\n }),\n Type.Literal(\"PrivateCommunity\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"PrivateChannel\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityMessagesByMessageIndexResponse = Type.Union([\n Type.Object({\n Success: MessagesResponse,\n }),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"ThreadNotFound\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n ReplicaNotUpToDateV2: Type.BigInt(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityThreadPreviewsSuccessResult = Type.Object({\n threads: Type.Array(ThreadPreview),\n timestamp: Type.BigInt(),\n});\nexport const CommunityThreadPreviewsResponse = Type.Union([\n Type.Object({\n Success: CommunityThreadPreviewsSuccessResult,\n }),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Object({\n ReplicaNotUpToDate: Type.BigInt(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupSummaryUpdatesSuccessResult = Type.Object({\n updates: GroupCanisterGroupChatSummaryUpdates,\n});\nexport const GroupSummaryUpdatesResponse = Type.Union([\n Type.Object({\n Success: GroupSummaryUpdatesSuccessResult,\n }),\n Type.Literal(\"SuccessNoUpdates\"),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupMessagesByMessageIndexResponse = Type.Union([\n Type.Object({\n Success: MessagesResponse,\n }),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Literal(\"ThreadMessageNotFound\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n ReplicaNotUpToDateV2: Type.BigInt(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupPublicSummarySuccessResult = Type.Object({\n summary: PublicGroupSummary,\n is_invited: Type.Boolean(),\n});\nexport const GroupPublicSummaryResponse = Type.Union([\n Type.Object({\n Success: GroupPublicSummarySuccessResult,\n }),\n Type.Literal(\"NotAuthorized\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupThreadPreviewsSuccessResult = Type.Object({\n threads: Type.Array(ThreadPreview),\n timestamp: Type.BigInt(),\n});\nexport const GroupSummarySuccessResult = Type.Object({\n summary: GroupCanisterGroupChatSummary,\n});\nexport const GroupSummaryResponse = Type.Union([\n Type.Object({\n Success: GroupSummarySuccessResult,\n }),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserInitialStateDirectChatsInitial = Type.Object({\n summaries: Type.Array(DirectChatSummary),\n pinned: Type.Array(ChatId),\n});\nexport const UserUpdatesDirectChatsUpdates = Type.Object({\n added: Type.Array(DirectChatSummary),\n updated: Type.Array(DirectChatSummaryUpdates),\n removed: Type.Array(ChatId),\n pinned: Type.Optional(Type.Array(ChatId)),\n});\nexport const UserMessagesByMessageIndexResponse = Type.Union([\n Type.Object({\n Success: MessagesResponse,\n }),\n Type.Literal(\"ChatNotFound\"),\n Type.Literal(\"ThreadMessageNotFound\"),\n Type.Object({\n ReplicaNotUpToDateV2: Type.BigInt(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const EventsResponse = Type.Object({\n events: Type.Array(EventWrapperChatEvent),\n unauthorized: Type.Array(EventIndex),\n expired_event_ranges: Type.Array(Type.Tuple([EventIndex, EventIndex])),\n expired_message_ranges: Type.Array(Type.Tuple([MessageIndex, MessageIndex])),\n latest_event_index: EventIndex,\n chat_last_updated: Type.BigInt(),\n});\nexport const CommunityCanisterCommunitySummary = Type.Object({\n community_id: CommunityId,\n local_user_index_canister_id: TSPrincipal,\n last_updated: Type.BigInt(),\n name: Type.String(),\n description: Type.String(),\n avatar_id: Type.Optional(Type.BigInt()),\n banner_id: Type.Optional(Type.BigInt()),\n is_public: Type.Boolean(),\n member_count: Type.Number(),\n permissions: CommunityPermissions,\n frozen: Type.Optional(FrozenGroupInfo),\n gate: Type.Optional(AccessGate),\n gate_config: Type.Optional(AccessGateConfig),\n primary_language: Type.String(),\n latest_event_index: EventIndex,\n channels: Type.Array(CommunityCanisterChannelSummary),\n membership: Type.Optional(CommunityMembership),\n user_groups: Type.Array(UserGroupSummary),\n is_invited: Type.Optional(Type.Boolean()),\n metrics: ChatMetrics,\n verified: Type.Boolean(),\n});\nexport const CommunityCanisterCommunitySummaryUpdates = Type.Object({\n community_id: CommunityId,\n last_updated: Type.BigInt(),\n name: Type.Optional(Type.String()),\n description: Type.Optional(Type.String()),\n avatar_id: OptionUpdateU128,\n banner_id: OptionUpdateU128,\n is_public: Type.Optional(Type.Boolean()),\n member_count: Type.Optional(Type.Number()),\n permissions: Type.Optional(CommunityPermissions),\n frozen: OptionUpdateFrozenGroupInfo,\n gate: OptionUpdateAccessGate,\n gate_config: OptionUpdateAccessGateConfig,\n primary_language: Type.Optional(Type.String()),\n latest_event_index: Type.Optional(EventIndex),\n channels_added: Type.Array(CommunityCanisterChannelSummary),\n channels_updated: Type.Array(CommunityCanisterChannelSummaryUpdates),\n channels_removed: Type.Array(ChannelId),\n membership: Type.Optional(CommunityMembershipUpdates),\n user_groups: Type.Array(UserGroupSummary),\n user_groups_deleted: Type.Array(Type.Number()),\n metrics: Type.Optional(ChatMetrics),\n verified: Type.Optional(Type.Boolean()),\n});\nexport const LocalUserIndexChatEventsEventsResponse = Type.Union([\n Type.Object({\n Success: EventsResponse,\n }),\n Type.Literal(\"NotFound\"),\n Type.Object({\n ReplicaNotUpToDate: Type.BigInt(),\n }),\n Type.Object({\n InternalError: Type.String(),\n }),\n]);\nexport const LocalUserIndexChatEventsSuccessResult = Type.Object({\n responses: Type.Array(LocalUserIndexChatEventsEventsResponse),\n timestamp: Type.BigInt(),\n});\nexport const LocalUserIndexChatEventsResponse = Type.Object({\n Success: LocalUserIndexChatEventsSuccessResult,\n});\nexport const LocalUserIndexJoinCommunityResponse = Type.Union([\n Type.Object({\n Success: CommunityCanisterCommunitySummary,\n }),\n Type.Object({\n AlreadyInCommunity: CommunityCanisterCommunitySummary,\n }),\n Type.Object({\n GateCheckFailed: GateCheckFailedReason,\n }),\n Type.Literal(\"CommunityNotFound\"),\n Type.Literal(\"CommunityNotPublic\"),\n Type.Literal(\"NotInvited\"),\n Type.Object({\n MemberLimitReached: Type.Number(),\n }),\n Type.Literal(\"UserBlocked\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const LocalUserIndexJoinChannelResponse = Type.Union([\n Type.Object({\n Success: CommunityCanisterChannelSummary,\n }),\n Type.Object({\n SuccessJoinedCommunity: CommunityCanisterCommunitySummary,\n }),\n Type.Object({\n AlreadyInChannel: CommunityCanisterChannelSummary,\n }),\n Type.Object({\n GateCheckFailed: GateCheckFailedReason,\n }),\n Type.Literal(\"CommunityNotFound\"),\n Type.Literal(\"CommunityNotPublic\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Object({\n MemberLimitReached: Type.Number(),\n }),\n Type.Literal(\"UserBlocked\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"CommunityFrozen\"),\n Type.Literal(\"NotInvited\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const LocalUserIndexBotChatEventsResponse = Type.Union([\n Type.Object({\n Success: EventsResponse,\n }),\n Type.Object({\n FailedAuthentication: Type.String(),\n }),\n Type.Literal(\"NotAuthorized\"),\n Type.Literal(\"NotFound\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const LocalUserIndexGroupAndCommunitySummaryUpdatesSummaryUpdatesResponse = Type.Union([\n Type.Object({\n SuccessGroup: GroupCanisterGroupChatSummary,\n }),\n Type.Object({\n SuccessCommunity: CommunityCanisterCommunitySummary,\n }),\n Type.Object({\n SuccessGroupUpdates: GroupCanisterGroupChatSummaryUpdates,\n }),\n Type.Object({\n SuccessCommunityUpdates: CommunityCanisterCommunitySummaryUpdates,\n }),\n Type.Literal(\"SuccessNoUpdates\"),\n Type.Literal(\"NotFound\"),\n Type.Object({\n InternalError: Type.String(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const LocalUserIndexGroupAndCommunitySummaryUpdatesResponse = Type.Object({\n Success: Type.Array(LocalUserIndexGroupAndCommunitySummaryUpdatesSummaryUpdatesResponse),\n});\nexport const CommunitySummaryUpdatesResponse = Type.Union([\n Type.Object({\n Success: CommunityCanisterCommunitySummaryUpdates,\n }),\n Type.Literal(\"SuccessNoUpdates\"),\n Type.Literal(\"PrivateCommunity\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunityEventsResponse = Type.Union([\n Type.Object({\n Success: EventsResponse,\n }),\n Type.Literal(\"UserNotInCommunity\"),\n Type.Literal(\"UserNotInChannel\"),\n Type.Literal(\"ChannelNotFound\"),\n Type.Literal(\"ThreadNotFound\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n ReplicaNotUpToDateV2: Type.BigInt(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const CommunitySummaryResponse = Type.Union([\n Type.Object({\n Success: CommunityCanisterCommunitySummary,\n }),\n Type.Literal(\"PrivateCommunity\"),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupThreadPreviewsResponse = Type.Union([\n Type.Object({\n Success: GroupThreadPreviewsSuccessResult,\n }),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Object({\n ReplicaNotUpToDate: Type.BigInt(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const GroupEventsResponse = Type.Union([\n Type.Object({\n Success: EventsResponse,\n }),\n Type.Literal(\"CallerNotInGroup\"),\n Type.Literal(\"ThreadMessageNotFound\"),\n Type.Literal(\"UserSuspended\"),\n Type.Literal(\"UserLapsed\"),\n Type.Object({\n ReplicaNotUpToDateV2: Type.BigInt(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserEventsResponse = Type.Union([\n Type.Object({\n Success: EventsResponse,\n }),\n Type.Literal(\"ChatNotFound\"),\n Type.Literal(\"ThreadMessageNotFound\"),\n Type.Object({\n ReplicaNotUpToDateV2: Type.BigInt(),\n }),\n Type.Object({\n Error: OCError,\n }),\n]);\nexport const UserInitialStateSuccessResult = Type.Object({\n timestamp: Type.BigInt(),\n direct_chats: UserInitialStateDirectChatsInitial,\n group_chats: UserInitialStateGroupChatsInitial,\n favourite_chats: UserInitialStateFavouriteChatsInitial,\n communities: UserInitialStateCommunitiesInitial,\n avatar_id: Type.Optional(Type.BigInt()),\n blocked_users: Type.Array(UserId),\n suspended: Type.Boolean(),\n pin_number_settings: Type.Optional(PinNumberSettings),\n local_user_index_canister_id: TSPrincipal,\n achievements: Type.Array(ChitEarned),\n achievements_last_seen: Type.BigInt(),\n total_chit_earned: Type.Number(),\n chit_balance: Type.Number(),\n streak: Type.Number(),\n streak_ends: Type.BigInt(),\n max_streak: Type.Number(),\n streak_insurance: Type.Optional(StreakInsurance),\n next_daily_claim: Type.BigInt(),\n is_unique_person: Type.Boolean(),\n wallet_config: UserWalletConfig,\n referrals: Type.Array(UserReferral),\n message_activity_summary: UserMessageActivitySummary,\n bots: Type.Array(InstalledBotDetails),\n api_keys: Type.Array(PublicApiKeyDetails),\n btc_address: Type.Optional(Type.String()),\n});\nexport const UserInitialStateResponse = Type.Object({\n Success: UserInitialStateSuccessResult,\n});\nexport const UserUpdatesSuccessResult = Type.Object({\n timestamp: Type.BigInt(),\n username: Type.Optional(Type.String()),\n display_name: OptionUpdateString,\n direct_chats: UserUpdatesDirectChatsUpdates,\n group_chats: UserUpdatesGroupChatsUpdates,\n favourite_chats: UserUpdatesFavouriteChatsUpdates,\n communities: UserUpdatesCommunitiesUpdates,\n avatar_id: OptionUpdateU128,\n blocked_users: Type.Optional(Type.Array(UserId)),\n suspended: Type.Optional(Type.Boolean()),\n pin_number_settings: OptionUpdatePinNumberSettings,\n achievements: Type.Array(ChitEarned),\n achievements_last_seen: Type.Optional(Type.BigInt()),\n total_chit_earned: Type.Number(),\n chit_balance: Type.Number(),\n streak: Type.Number(),\n streak_ends: Type.BigInt(),\n max_streak: Type.Number(),\n streak_insurance: OptionUpdateStreakInsurance,\n next_daily_claim: Type.BigInt(),\n is_unique_person: Type.Optional(Type.Boolean()),\n wallet_config: Type.Optional(UserWalletConfig),\n referrals: Type.Array(UserReferral),\n message_activity_summary: Type.Optional(UserMessageActivitySummary),\n bots_added_or_updated: Type.Array(InstalledBotDetails),\n bots_removed: Type.Array(UserId),\n api_keys_generated: Type.Array(PublicApiKeyDetails),\n btc_address: Type.Optional(Type.String()),\n});\nexport const UserUpdatesResponse = Type.Union([\n Type.Object({\n Success: UserUpdatesSuccessResult,\n }),\n Type.Literal(\"SuccessNoUpdates\"),\n]);\n","import { SignedDelegation as TSignedDelegation } from \"../typebox\";\nexport function signedDelegation(chain) {\n const delegation = chain.delegations[0];\n return {\n signature: new Uint8Array(delegation.signature),\n delegation: {\n pubkey: new Uint8Array(delegation.delegation.pubkey),\n expiration: delegation.delegation.expiration,\n },\n };\n}\n","import { groupBy } from \"../../utils/list\";\nimport { mergeUserSummaryWithUpdates, offline, Stream, userSummaryFromCurrentUserSummary, } from \"openchat-shared\";\nimport { MsgpackCanisterAgent } from \"../canisterAgent/msgpack\";\nimport { checkUsernameResponse, setUsernameResponse, usersApiResponse, suspendUserResponse, unsuspendUserResponse, payForDiamondMembershipResponse, setDisplayNameResponse, diamondMembershipFeesResponse, chitLeaderboardResponse, submitProofOfUniquePersonhoodResponse, currentUserResponse, userRegistrationCanisterResponse, userSearchResponse, apiJsonDiamondDuration, externalAchievementsResponse, exploreBotsResponse, botUpdatesResponse, apiBotDefinition, apiBotInstallLocation, } from \"./mappers\";\nimport { getCachedUsers, getCachedDeletedUserIds, getSuspendedUsersSyncedUpTo, setCachedDeletedUserIds, setCachedUsers, setDisplayNameInCache, setSuspendedUsersSyncedUpTo, setUserDiamondStatusInCache, setUsernameInCache, } from \"../../utils/userCache\";\nimport { getCachedCurrentUser, mergeCachedCurrentUser, setCachedCurrentUser, setCurrentUserDiamondStatusInCache, } from \"../../utils/caching\";\nimport { identity, mapOptional, principalBytesToString, principalStringToBytes, } from \"../../utils/mapping\";\nimport { Empty, UserIndexBotUpdatesArgs, UserIndexBotUpdatesResponse, UserIndexCheckUsernameArgs, UserIndexCheckUsernameResponse, UserIndexChitLeaderboardResponse, UserIndexCurrentUserResponse, UserIndexDeleteUserArgs, UserIndexDeleteUserResponse, UserIndexDiamondMembershipFeesResponse, UserIndexExploreBotsArgs, UserIndexExploreBotsResponse, UserIndexExternalAchievementsArgs, UserIndexExternalAchievementsResponse, UserIndexPayForDiamondMembershipArgs, UserIndexPayForDiamondMembershipResponse, UserIndexPlatformModeratorsGroupResponse, UserIndexRegisterBotArgs, UserIndexRegisterBotResponse, UserIndexRemoveBotArgs, UserIndexRemoveBotResponse, UserIndexReportedMessagesArgs, UserIndexReportedMessagesResponse, UserIndexSearchArgs, UserIndexSearchResponse, UserIndexSetDiamondMembershipFeesArgs, UserIndexSetDiamondMembershipFeesResponse, UserIndexSetDisplayNameArgs, UserIndexSetDisplayNameResponse, UserIndexSetModerationFlagsArgs, UserIndexSetModerationFlagsResponse, UserIndexSetUsernameArgs, UserIndexSetUsernameResponse, UserIndexSetUserUpgradeConcurrencyArgs, UserIndexSetUserUpgradeConcurrencyResponse, UserIndexSubmitProofOfUniquePersonhoodArgs, UserIndexSubmitProofOfUniquePersonhoodResponse, UserIndexSuspendUserArgs, UserIndexSuspendUserResponse, UserIndexUnsuspendUserArgs, UserIndexUnsuspendUserResponse, UserIndexUpdateBotArgs, UserIndexUpdateBotResponse, UserIndexUserRegistrationCanisterResponse, UserIndexUsersArgs, UserIndexUsersResponse, } from \"../../typebox\";\nimport { signedDelegation } from \"../../utils/id\";\nexport class UserIndexClient extends MsgpackCanisterAgent {\n constructor(identity, agent, canisterId, blobUrlPattern) {\n super(identity, agent, canisterId, \"UserIndex\");\n this.blobUrlPattern = blobUrlPattern;\n }\n getCurrentUser() {\n return new Stream(async (resolve, reject) => {\n try {\n const principal = this.identity.getPrincipal().toString();\n const cachedUser = await getCachedCurrentUser(principal);\n const isOffline = offline();\n if (cachedUser !== undefined) {\n resolve(cachedUser, isOffline);\n }\n if (!isOffline) {\n const liveUser = await this.executeMsgpackQuery(\"current_user\", {}, currentUserResponse, Empty, UserIndexCurrentUserResponse);\n if (liveUser.kind === \"created_user\") {\n setCachedCurrentUser(principal, liveUser);\n }\n resolve(liveUser, true);\n }\n }\n catch (err) {\n reject(err);\n }\n });\n }\n setModerationFlags(flags) {\n return this.executeMsgpackUpdate(\"set_moderation_flags\", {\n moderation_flags_enabled: flags,\n }, (_) => true, UserIndexSetModerationFlagsArgs, UserIndexSetModerationFlagsResponse);\n }\n userRegistrationCanister() {\n return this.executeMsgpackQuery(\"user_registration_canister\", {}, userRegistrationCanisterResponse, Empty, UserIndexUserRegistrationCanisterResponse);\n }\n searchUsers(searchTerm, maxResults = 20) {\n const args = {\n search_term: searchTerm,\n max_results: maxResults,\n };\n return this.executeMsgpackQuery(\"search\", args, userSearchResponse, UserIndexSearchArgs, UserIndexSearchResponse);\n }\n async getUsers(chitState, users, allowStale) {\n const allUsers = users.userGroups.flatMap((g) => g.users);\n const fromCache = await getCachedUsers(allUsers);\n const cachedDeletedUserIds = await getCachedDeletedUserIds();\n const suspendedUsersSyncedTo = await getSuspendedUsersSyncedUpTo();\n // We throw away all of the updatedSince values passed in and instead use the values from the cache, this\n // ensures the cache is always correct and doesn't miss any updates\n const args = this.buildGetUsersArgs(allUsers, fromCache, allowStale, cachedDeletedUserIds);\n const requestedFromServer = new Set([...args.userGroups.flatMap((g) => g.users)]);\n const apiResponse = await this.getUsersFromBackend(args, suspendedUsersSyncedTo);\n // We return the fully hydrated users so that it is not possible for the Svelte store to miss any updates\n const mergedResponse = this.mergeGetUsersResponse(chitState, allUsers, requestedFromServer, apiResponse, fromCache);\n setCachedDeletedUserIds(apiResponse.deletedUserIds);\n setCachedUsers(mergedResponse.users).catch((err) => console.error(\"Failed to save users to the cache\", err));\n if (mergedResponse.currentUser) {\n mergeCachedCurrentUser(this.principal.toString(), mergedResponse.currentUser);\n }\n if (mergedResponse.serverTimestamp !== undefined) {\n setSuspendedUsersSyncedUpTo(mergedResponse.serverTimestamp).catch((err) => console.error(\"Failed to set 'suspended users synced up to' in the cache\", err));\n }\n return mergedResponse;\n }\n getUsersFromBackend(users, suspendedUsersSyncedUpTo) {\n if (offline())\n return Promise.resolve({\n serverTimestamp: 0n,\n users: [],\n deletedUserIds: new Set(),\n });\n const userGroups = users.userGroups.filter((g) => g.users.length > 0);\n const args = {\n user_groups: userGroups.map(({ users, updatedSince }) => ({\n users: users.map(principalStringToBytes),\n updated_since: updatedSince,\n })),\n users_suspended_since: suspendedUsersSyncedUpTo,\n };\n return this.executeMsgpackQuery(\"users\", args, usersApiResponse, UserIndexUsersArgs, UserIndexUsersResponse);\n }\n buildGetUsersArgs(users, fromCache, allowStale, _cachedDeletedUserIds) {\n const fromCacheGrouped = groupBy(fromCache, (u) => u.updated);\n const fromCacheSet = new Set(fromCache.map((u) => u.userId));\n const args = {\n userGroups: [],\n };\n // Add the users not found in the cache and ask for all updates\n const notFoundInCache = users.filter(\n // (u) => !fromCacheSet.has(u) && !cachedDeletedUserIds.has(u),\n (u) => !fromCacheSet.has(u));\n if (notFoundInCache.length > 0) {\n args.userGroups.push({\n users: notFoundInCache,\n updatedSince: BigInt(0),\n });\n }\n if (!allowStale) {\n // Add the users found in the cache but only ask for updates since the date they were last updated in the cache\n for (const [updatedSince, users] of fromCacheGrouped) {\n args.userGroups.push({\n users: users\n // .filter((u) => !cachedDeletedUserIds.has(u.userId))\n .map((u) => u.userId),\n updatedSince,\n });\n }\n }\n return args;\n }\n // Merges the cached values into the response\n mergeGetUsersResponse(chitState, allUsersRequested, requestedFromServer, apiResponse, fromCache) {\n const fromCacheMap = new Map(fromCache.map((u) => [u.userId, u]));\n const apiResponseMap = new Map(apiResponse.users.map((u) => [u.userId, u]));\n const users = [];\n for (const userId of allUsersRequested) {\n const cached = fromCacheMap.get(userId);\n const fromServer = apiResponseMap.get(userId);\n if (fromServer !== undefined) {\n apiResponseMap.delete(userId);\n const merged = mergeUserSummaryWithUpdates(cached, fromServer, apiResponse.serverTimestamp);\n if (merged !== undefined) {\n users.push(merged);\n }\n }\n else if (cached !== undefined) {\n if (cached.userId !== apiResponse.currentUser?.userId) {\n if (requestedFromServer.has(userId)) {\n // If this user was requested from the server but wasn't included in the response, then that means\n // our cached copy is up to date.\n users.push({\n ...cached,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n updated: apiResponse.serverTimestamp,\n });\n }\n else {\n users.push(cached);\n }\n }\n }\n else {\n // if we get here it means that for this user, nothing came back from the server\n // & nothing was in the cache - this would be odd but worth knowing if this is happening\n console.debug(\"USERS: userId requested not in cache and not returned from server\", userId);\n }\n }\n // This is needed because newly suspended users won't have been included in the `allUsers` array\n for (const user of apiResponseMap.values()) {\n const cached = fromCacheMap.get(user.userId);\n const merged = mergeUserSummaryWithUpdates(cached, user, apiResponse.serverTimestamp);\n if (merged !== undefined) {\n users.push(merged);\n }\n }\n // let's see if we got the current user back from the server\n if (apiResponse.currentUser !== undefined) {\n users.push(userSummaryFromCurrentUserSummary(chitState, apiResponse.currentUser));\n }\n return {\n serverTimestamp: apiResponse.serverTimestamp,\n users,\n currentUser: apiResponse.currentUser,\n deletedUserIds: apiResponse.deletedUserIds,\n };\n }\n checkUsername(username, isBot) {\n const args = {\n username: username,\n is_bot: isBot,\n };\n return this.executeMsgpackQuery(\"check_username\", args, checkUsernameResponse, UserIndexCheckUsernameArgs, UserIndexCheckUsernameResponse);\n }\n setUsername(userId, username) {\n return this.executeMsgpackUpdate(\"set_username\", { username }, setUsernameResponse, UserIndexSetUsernameArgs, UserIndexSetUsernameResponse).then((res) => {\n if (res === \"success\") {\n setUsernameInCache(userId, username);\n }\n return res;\n });\n }\n setDisplayName(userId, displayName) {\n return this.executeMsgpackUpdate(\"set_display_name\", {\n display_name: displayName,\n }, setDisplayNameResponse, UserIndexSetDisplayNameArgs, UserIndexSetDisplayNameResponse).then((res) => {\n if (res === \"success\") {\n setDisplayNameInCache(userId, displayName);\n }\n return res;\n });\n }\n suspendUser(userId, reason) {\n return this.executeMsgpackUpdate(\"suspend_user\", {\n user_id: principalStringToBytes(userId),\n reason,\n }, suspendUserResponse, UserIndexSuspendUserArgs, UserIndexSuspendUserResponse);\n }\n unsuspendUser(userId) {\n return this.executeMsgpackUpdate(\"unsuspend_user\", {\n user_id: principalStringToBytes(userId),\n }, unsuspendUserResponse, UserIndexUnsuspendUserArgs, UserIndexUnsuspendUserResponse);\n }\n payForDiamondMembership(userId, ledger, duration, recurring, expectedPriceE8s) {\n return this.executeMsgpackUpdate(\"pay_for_diamond_membership\", {\n ledger,\n duration: apiJsonDiamondDuration(duration),\n recurring,\n expected_price_e8s: expectedPriceE8s,\n }, (res) => payForDiamondMembershipResponse(duration, res), UserIndexPayForDiamondMembershipArgs, UserIndexPayForDiamondMembershipResponse).then((res) => {\n if (res.kind === \"success\") {\n const principal = this.identity.getPrincipal().toString();\n setUserDiamondStatusInCache(userId, res.status);\n setCurrentUserDiamondStatusInCache(principal, res.status);\n }\n return res;\n });\n }\n setUserUpgradeConcurrency(value) {\n return this.executeMsgpackUpdate(\"set_user_upgrade_concurrency\", { value }, () => \"success\", UserIndexSetUserUpgradeConcurrencyArgs, UserIndexSetUserUpgradeConcurrencyResponse);\n }\n getPlatformModeratorGroup() {\n return this.executeMsgpackQuery(\"platform_moderators_group\", {}, (res) => principalBytesToString(res.Success), Empty, UserIndexPlatformModeratorsGroupResponse);\n }\n diamondMembershipFees() {\n return this.executeMsgpackQuery(\"diamond_membership_fees\", {}, diamondMembershipFeesResponse, Empty, UserIndexDiamondMembershipFeesResponse);\n }\n setDiamondMembershipFees(fees) {\n const chatFees = fees.find((f) => f.token === \"CHAT\");\n const icpFees = fees.find((f) => f.token === \"ICP\");\n if (chatFees === undefined || icpFees === undefined) {\n return Promise.resolve(false);\n }\n const args = {\n fees: {\n chat_fees: {\n one_month: chatFees.oneMonth,\n three_months: chatFees.threeMonths,\n one_year: chatFees.oneYear,\n lifetime: chatFees.lifetime,\n },\n icp_fees: {\n one_month: icpFees.oneMonth,\n three_months: icpFees.threeMonths,\n one_year: icpFees.oneYear,\n lifetime: icpFees.lifetime,\n },\n },\n };\n return this.executeMsgpackUpdate(\"set_diamond_membership_fees\", args, (res) => res === \"Success\", UserIndexSetDiamondMembershipFeesArgs, UserIndexSetDiamondMembershipFeesResponse);\n }\n reportedMessages(userId) {\n return this.executeMsgpackQuery(\"reported_messages\", {\n user_id: mapOptional(userId, principalStringToBytes),\n }, (res) => res.Success.json, UserIndexReportedMessagesArgs, UserIndexReportedMessagesResponse);\n }\n chitLeaderboard() {\n return this.executeMsgpackQuery(\"chit_leaderboard\", {}, chitLeaderboardResponse, Empty, UserIndexChitLeaderboardResponse);\n }\n submitProofOfUniquePersonhood(iiPrincipal, credential) {\n const args = {\n user_ii_principal: principalStringToBytes(iiPrincipal),\n credential_jwt: credential,\n };\n return this.executeMsgpackUpdate(\"submit_proof_of_unique_personhood\", args, submitProofOfUniquePersonhoodResponse, UserIndexSubmitProofOfUniquePersonhoodArgs, UserIndexSubmitProofOfUniquePersonhoodResponse);\n }\n getExternalAchievements(updatesSince) {\n return this.executeMsgpackQuery(\"external_achievements\", { updates_since: updatesSince }, externalAchievementsResponse, UserIndexExternalAchievementsArgs, UserIndexExternalAchievementsResponse);\n }\n deleteUser(userId, delegation) {\n return this.executeMsgpackUpdate(\"delete_user\", { user_id: principalStringToBytes(userId), delegation: signedDelegation(delegation) }, (resp) => resp === \"Success\", UserIndexDeleteUserArgs, UserIndexDeleteUserResponse);\n }\n exploreBots(searchTerm, pageIndex, pageSize, location) {\n return this.executeMsgpackQuery(\"explore_bots\", {\n search_term: searchTerm,\n page_index: pageIndex,\n page_size: pageSize,\n installation_location: mapOptional(location, apiBotInstallLocation),\n }, (resp) => exploreBotsResponse(resp, this.blobUrlPattern, this.canisterId), UserIndexExploreBotsArgs, UserIndexExploreBotsResponse);\n }\n registerBot(principal, bot) {\n const location = bot.registrationStatus.kind === \"private\" ? bot.registrationStatus.location : undefined;\n return this.executeMsgpackUpdate(\"register_bot\", {\n principal: principalStringToBytes(principal),\n name: bot.name,\n avatar: mapOptional(bot.avatarUrl, identity),\n endpoint: bot.endpoint,\n definition: apiBotDefinition(bot.definition),\n permitted_install_location: mapOptional(location, apiBotInstallLocation),\n }, (resp) => {\n console.log(\"UserIndex register bot response: \", resp);\n return typeof resp === \"object\" && \"Success\" in resp;\n }, UserIndexRegisterBotArgs, UserIndexRegisterBotResponse);\n }\n removeBot(botId) {\n return this.executeMsgpackUpdate(\"remove_bot\", {\n bot_id: principalStringToBytes(botId),\n }, (resp) => {\n console.log(\"UserIndex remove bot response: \", resp);\n return resp === \"Success\";\n }, UserIndexRemoveBotArgs, UserIndexRemoveBotResponse);\n }\n updateRegisteredBot(id, principal, ownerId, avatarUrl, endpoint, definition) {\n return this.executeMsgpackUpdate(\"update_bot\", {\n bot_id: principalStringToBytes(id),\n owner: mapOptional(ownerId, principalStringToBytes),\n principal: mapOptional(principal, principalStringToBytes),\n avatar: mapOptional(avatarUrl, (url) => ({\n SetToSome: url,\n })) ?? \"NoChange\",\n endpoint: mapOptional(endpoint, identity),\n definition: mapOptional(definition, apiBotDefinition),\n }, (resp) => {\n console.log(\"UserIndex update bot response: \", resp);\n return true;\n }, UserIndexUpdateBotArgs, UserIndexUpdateBotResponse);\n }\n getBots(current) {\n return this.executeMsgpackQuery(\"bot_updates\", {\n updated_since: current?.timestamp ?? 0n,\n }, (resp) => botUpdatesResponse(resp, current, this.blobUrlPattern, this.canisterId), UserIndexBotUpdatesArgs, UserIndexBotUpdatesResponse);\n }\n}\n","import { openDbAndGetCachedChats } from \"../../utils/caching\";\nimport { ReplicaNotUpToDateError } from \"../error\";\nimport { chatIdentifiersEqual, } from \"openchat-shared\";\nconst DATE_FIXED = BigInt(1699800000000);\nexport async function ensureReplicaIsUpToDate(principal, chatId, replicaChatLastUpdated, suppressError = false) {\n const clientChat = await getChat(principal, chatId);\n if (clientChat !== undefined &&\n replicaChatLastUpdated < clientChat.lastUpdated &&\n clientChat.lastUpdated > DATE_FIXED) {\n if (suppressError) {\n return {\n kind: \"replica_not_up_to_date\",\n replicaTimestamp: replicaChatLastUpdated,\n clientTimestamp: clientChat.lastUpdated,\n };\n }\n throw ReplicaNotUpToDateError.byTimestamp(replicaChatLastUpdated, clientChat.lastUpdated, true);\n }\n}\nexport function excludeLatestKnownUpdateIfBeforeFix(latestKnownUpdate) {\n if (latestKnownUpdate !== undefined && latestKnownUpdate < DATE_FIXED) {\n return undefined;\n }\n return latestKnownUpdate;\n}\nasync function getChat(principal, chatId) {\n const chats = await openDbAndGetCachedChats(principal);\n if (chats === undefined)\n return undefined;\n switch (chatId.kind) {\n case \"direct_chat\":\n return chats.directChats.find((c) => chatIdentifiersEqual(c.id, chatId));\n case \"group_chat\":\n return chats.groupChats.find((c) => chatIdentifiersEqual(c.id, chatId));\n case \"channel\":\n return chats.communities\n .find((c) => c.id.communityId === chatId.communityId)\n ?.channels.find((c) => c.id === chatId);\n }\n}\n","import { nullMembership, toBigInt32, toBigInt64, CommonResponses, UnsupportedValueError, } from \"openchat-shared\";\nimport { bytesToBigint, bytesToHexString, identity, mapOptional, optionUpdateV2, principalBytesToString, principalStringToBytes, } from \"../../utils/mapping\";\nimport { chatMetrics, completedCryptoTransfer, message, messageContent, messageMatch, messageEvent, eventsSuccessResponse, installedBotDetails, publicApiKeyDetails, ocError, } from \"../common/chatMappersV2\";\nimport { ensureReplicaIsUpToDate } from \"../common/replicaUpToDateChecker\";\nimport { ReplicaNotUpToDateError } from \"../error\";\nimport { Principal } from \"@dfinity/principal\";\nimport { pinNumberFailureResponseV2 } from \"../common/pinNumberErrorMapper\";\nimport { signedDelegation } from \"../../utils/id\";\nimport { mapCommonResponses } from \"../common/commonResponseMapper\";\nexport function messageActivityFeedResponse(value) {\n if (\"Success\" in value) {\n return {\n total: value.Success.total,\n events: value.Success.events.map(messageActivityEvent),\n };\n }\n return {\n total: 0,\n events: [],\n };\n}\nexport function messageActivityEvent(value) {\n return {\n messageContext: messageContext(value.chat, mapOptional(value.thread_root_message_index, identity)),\n eventIndex: value.event_index,\n messageIndex: value.message_index,\n messageId: toBigInt64(value.message_id),\n activity: messageActivity(value.activity),\n timestamp: value.timestamp,\n userId: mapOptional(value.user_id, principalBytesToString),\n message: undefined,\n };\n}\nexport function messageContext(chat, threadRootMessageIndex) {\n return {\n chatId: chatIdentifier(chat),\n threadRootMessageIndex,\n };\n}\nexport function messageActivity(value) {\n if (\"Tip\" === value) {\n return \"tip\";\n }\n if (\"P2PSwapAccepted\" === value) {\n return \"p2p_swap_accepted\";\n }\n if (\"PollVote\" === value) {\n return \"poll_vote\";\n }\n if (\"Mention\" === value) {\n return \"mention\";\n }\n if (\"Crypto\" === value) {\n return \"crypto\";\n }\n if (\"QuoteReply\" === value) {\n return \"quote_reply\";\n }\n if (\"Reaction\" === value) {\n return \"reaction\";\n }\n throw new UnsupportedValueError(\"Unexpect type of ApiMessageActivity received\", value);\n}\nexport function chitEventsResponse(value) {\n if (\"Success\" in value) {\n return {\n events: value.Success.events.map(chitEarned),\n total: value.Success.total,\n };\n }\n else {\n console.warn(\"chitEventsResponse failed with: \", value);\n return {\n events: [],\n total: 0,\n };\n }\n}\nexport function chitEarned(value) {\n return {\n amount: value.amount,\n timestamp: value.timestamp,\n reason: chitEarnedReason(value.reason),\n };\n}\nexport function chitEarnedReason(value) {\n if (value === \"DailyClaim\") {\n return { kind: \"daily_claim\" };\n }\n if (value === \"MemeContestWinner\") {\n return { kind: \"meme_contest_winner\" };\n }\n if (typeof value === \"object\") {\n if (\"Achievement\" in value) {\n return { kind: \"achievement_unlocked\", type: achievementType(value.Achievement) };\n }\n if (\"Referral\" in value) {\n return { kind: \"referral\", type: referralStatus(value.Referral) };\n }\n if (\"ExternalAchievement\" in value) {\n return { kind: \"external_achievement_unlocked\", name: value.ExternalAchievement };\n }\n }\n throw new UnsupportedValueError(\"Unexpected ApiChitEarnedReason encountered\", value);\n}\nexport function referralStatus(value) {\n if (value === \"Registered\") {\n return \"registered\";\n }\n if (value === \"Diamond\") {\n return \"diamond\";\n }\n if (value === \"UniquePerson\") {\n return \"unique_person\";\n }\n if (value === \"LifetimeDiamond\") {\n return \"lifetime_diamond\";\n }\n throw new UnsupportedValueError(\"Unexpected ApiReferralStatus encountered\", value);\n}\nexport function achievementType(value) {\n switch (value) {\n case \"ChangedTheme\":\n return \"changed_theme\";\n case \"FavouritedChat\":\n return \"favourited_chat\";\n case \"HadMessageReactedTo\":\n return \"received_reaction\";\n case \"VotedOnPoll\":\n return \"voted_on_poll\";\n case \"SetCommunityDisplayName\":\n return \"set_community_display_name\";\n case \"PinnedChat\":\n return \"pinned_chat\";\n case \"StartedCall\":\n return \"started_call\";\n case \"TippedMessage\":\n return \"tipped_message\";\n case \"SentGiphy\":\n return \"sent_giphy\";\n case \"HadMessageTipped\":\n return \"had_message_tipped\";\n case \"SwappedFromWallet\":\n return \"swapped_from_wallet\";\n case \"EditedMessage\":\n return \"edited_message\";\n case \"ReactedToMessage\":\n return \"reacted_to_message\";\n case \"AcceptedP2PSwapOffer\":\n return \"accepted_swap_offer\";\n case \"JoinedCall\":\n return \"joined_call\";\n case \"SentImage\":\n return \"sent_image\";\n case \"ForwardedMessage\":\n return \"forwarded_message\";\n case \"SentPrize\":\n return \"sent_prize\";\n case \"FollowedThread\":\n return \"followed_thread\";\n case \"SentReminder\":\n return \"sent_reminder\";\n case \"ProvedUniquePersonhood\":\n return \"proved_unique_personhood\";\n case \"DeletedMessage\":\n return \"deleted_message\";\n case \"SentText\":\n return \"sent_text\";\n case \"SentP2PSwapOffer\":\n return \"sent_swap_offer\";\n case \"QuoteReplied\":\n return \"quote_replied\";\n case \"SentCrypto\":\n return \"sent_crypto\";\n case \"ReceivedCrypto\":\n return \"received_crypto\";\n case \"RepliedInThread\":\n return \"replied_in_thread\";\n case \"SentFile\":\n return \"sent_file\";\n case \"SentMeme\":\n return \"sent_meme\";\n case \"SentPoll\":\n return \"sent_poll\";\n case \"SentAudio\":\n return \"sent_audio\";\n case \"SentVideo\":\n return \"sent_video\";\n case \"JoinedCommunity\":\n return \"joined_community\";\n case \"JoinedGroup\":\n return \"joined_group\";\n case \"Streak14\":\n return \"streak_14\";\n case \"Streak30\":\n return \"streak_30\";\n case \"UpgradedToDiamond\":\n return \"upgraded_to_diamond\";\n case \"ReceivedDirectMessage\":\n return \"received_direct_message\";\n case \"SetDisplayName\":\n return \"set_display_name\";\n case \"SetBio\":\n return \"set_bio\";\n case \"Streak3\":\n return \"streak_3\";\n case \"Streak7\":\n return \"streak_7\";\n case \"Streak100\":\n return \"streak_100\";\n case \"Streak365\":\n return \"streak_365\";\n case \"UpgradedToGoldDiamond\":\n return \"upgrade_to_gold_diamond\";\n case \"SentDirectMessage\":\n return \"sent_direct_message\";\n case \"SetAvatar\":\n return \"set_avatar\";\n case \"Referred1stUser\":\n return \"referred_1st_user\";\n case \"Referred3rdUser\":\n return \"referred_3rd_user\";\n case \"Referred10thUser\":\n return \"referred_10th_user\";\n case \"Referred20thUser\":\n return \"referred_20th_user\";\n case \"Referred50thUser\":\n return \"referred_50th_user\";\n case \"SetPin\":\n return \"set_pin\";\n case \"DepositedBtc\":\n return \"deposited_btc\";\n default:\n throw new UnsupportedValueError(\"Unexpected ApiAchievement received\", value);\n }\n}\nexport function saveCryptoAccountResponse(value) {\n if (value === \"Success\") {\n return CommonResponses.success();\n }\n else if (value === \"NameTaken\") {\n return { kind: \"name_taken\" };\n }\n else {\n console.warn(\"saveCryptoAccountResponse failed with: \", value);\n return CommonResponses.failure();\n }\n}\nexport function savedCryptoAccountsResponse(value) {\n if (\"Success\" in value) {\n return value.Success;\n }\n return [];\n}\nexport function tipMessageResponse(value) {\n if (value === \"Success\") {\n return CommonResponses.success();\n }\n if (value === \"PinRequired\") {\n return pinNumberFailureResponseV2(value);\n }\n if (typeof value === \"object\") {\n if (\"PinIncorrect\" in value || \"TooManyFailedPinAttempts\" in value) {\n return pinNumberFailureResponseV2(value);\n }\n }\n console.warn(\"tipMessage failed with: \", value);\n return CommonResponses.failure();\n}\nexport function publicProfileResponse(value) {\n const profile = value.Success;\n return {\n username: profile.username,\n displayName: profile.display_name,\n avatarId: profile.avatar_id,\n bio: profile.bio,\n isPremium: profile.is_premium,\n phoneIsVerified: profile.phone_is_verified,\n created: profile.created,\n };\n}\nexport function setBioResponse(value) {\n if (typeof value === \"object\" && \"TooLong\" in value) {\n return \"bio_too_long\";\n }\n if (typeof value === \"object\" && \"Error\" in value) {\n return ocError(value.Error);\n }\n return mapCommonResponses(value, \"SetBio\");\n}\nexport function searchDirectChatResponse(value, chatId) {\n if (typeof value === \"object\") {\n if (\"Success\" in value) {\n return {\n kind: \"success\",\n matches: value.Success.matches.map((m) => messageMatch(m, chatId)),\n };\n }\n if (\"TermTooShort\" in value || \"TermTooLong\" in value) {\n return {\n kind: \"term_invalid\",\n };\n }\n }\n if (value === \"ChatNotFound\") {\n return {\n kind: \"chat_not_found\",\n };\n }\n if (value === \"InvalidTerm\") {\n return {\n kind: \"term_invalid\",\n };\n }\n if (\"Error\" in value) {\n return ocError(value.Error);\n }\n throw new UnsupportedValueError(\"Unknown UserIndex.ApiSearchMessagesResponse type received\", value);\n}\nexport function deleteMessageResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n else {\n console.warn(\"Unexpected ApiDeleteMessageResponse type received\", value);\n return \"failure\";\n }\n}\nexport function undeleteMessageResponse(value) {\n if (typeof value === \"object\" && \"Success\" in value) {\n if (value.Success.messages.length == 0) {\n return CommonResponses.failure();\n }\n else {\n return {\n kind: \"success\",\n message: message(value.Success.messages[0]),\n };\n }\n }\n else {\n console.warn(\"Unexpected ApiUndeleteMessageResponse type received\", value);\n return CommonResponses.failure();\n }\n}\nexport function setAvatarResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n if (value === \"UserSuspended\") {\n return \"user_suspended\";\n }\n if (typeof value === \"object\" && \"AvatarTooBig\" in value) {\n return \"avatar_too_big\";\n }\n if (typeof value === \"object\" && \"Error\" in value) {\n return ocError(value.Error);\n }\n throw new UnsupportedValueError(\"Unexpected ApiSetAvatarResponse type received\", value);\n}\nexport function pinChatResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n else {\n console.warn(\"Unexpected ApiPinChatResponse type received\", value);\n return \"failure\";\n }\n}\nexport function archiveChatResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n else {\n console.warn(\"Archive/Unarchive chat failed with \", value);\n return \"failure\";\n }\n}\nexport function sendMessageWithTransferToChannelResponse(value, sender, recipient) {\n if (typeof value === \"object\") {\n if (\"Success\" in value) {\n return {\n kind: \"transfer_success\",\n timestamp: value.Success.timestamp,\n messageIndex: value.Success.message_index,\n eventIndex: value.Success.event_index,\n expiresAt: mapOptional(value.Success.expires_at, Number),\n transfer: completedCryptoTransfer(value.Success.transfer, sender, recipient ?? \"\"),\n };\n }\n if (\"PinIncorrect\" in value || \"TooManyFailedPinAttempts\" in value) {\n return pinNumberFailureResponseV2(value);\n }\n }\n if (value === \"PinRequired\") {\n return pinNumberFailureResponseV2(value);\n }\n console.warn(\"SendMessageWithTransferToChannel failed with\", value);\n return CommonResponses.failure();\n}\nexport function sendMessageWithTransferToGroupResponse(value, sender, recipient) {\n if (typeof value === \"object\") {\n if (\"Success\" in value) {\n return {\n kind: \"transfer_success\",\n timestamp: value.Success.timestamp,\n messageIndex: value.Success.message_index,\n eventIndex: value.Success.event_index,\n expiresAt: mapOptional(value.Success.expires_at, Number),\n transfer: completedCryptoTransfer(value.Success.transfer, sender, recipient ?? \"\"),\n };\n }\n if (\"PinIncorrect\" in value || \"TooManyFailedPinAttempts\" in value) {\n return pinNumberFailureResponseV2(value);\n }\n }\n if (value === \"PinRequired\") {\n return pinNumberFailureResponseV2(value);\n }\n console.warn(\"SendMessageWithTransferToGroup failed with\", value);\n return CommonResponses.failure();\n}\nexport function sendMessageResponse(value, sender, recipient) {\n if (typeof value === \"object\") {\n if (\"Success\" in value) {\n return {\n kind: \"success\",\n timestamp: value.Success.timestamp,\n messageIndex: value.Success.message_index,\n eventIndex: value.Success.event_index,\n expiresAt: mapOptional(value.Success.expires_at, Number),\n };\n }\n if (\"TransferSuccessV2\" in value) {\n return {\n kind: \"transfer_success\",\n timestamp: value.TransferSuccessV2.timestamp,\n messageIndex: value.TransferSuccessV2.message_index,\n eventIndex: value.TransferSuccessV2.event_index,\n transfer: completedCryptoTransfer(value.TransferSuccessV2.transfer, sender, recipient),\n expiresAt: mapOptional(value.TransferSuccessV2.expires_at, Number),\n };\n }\n if (\"InvalidRequest\" in value) {\n return { kind: \"invalid_request\", reason: value.InvalidRequest };\n }\n if (\"TextTooLong\" in value) {\n return { kind: \"text_too_long\" };\n }\n if (\"InternalError\" in value || \"Error\" in value) {\n return { kind: \"internal_error\" };\n }\n if (\"TransferFailed\" in value) {\n return { kind: \"transfer_failed\" };\n }\n if (\"InvalidPoll\" in value) {\n return { kind: \"invalid_poll\" };\n }\n if (\"P2PSwapSetUpFailed\" in value) {\n return { kind: \"p2p_swap_setup_failed\", text: value.P2PSwapSetUpFailed };\n }\n }\n if (value === \"TransferCannotBeZero\") {\n return { kind: \"transfer_cannot_be_zero\" };\n }\n if (value === \"TransferCannotBeToSelf\") {\n return { kind: \"transfer_cannot_be_to_self\" };\n }\n if (value === \"RecipientBlocked\") {\n return { kind: \"recipient_blocked\" };\n }\n if (value === \"MessageEmpty\") {\n return { kind: \"message_empty\" };\n }\n if (value === \"RecipientNotFound\") {\n return { kind: \"recipient_not_found\" };\n }\n if (value === \"UserSuspended\") {\n return { kind: \"user_suspended\" };\n }\n if (value === \"DuplicateMessageId\") {\n return { kind: \"duplicate_message_id\" };\n }\n if (value === \"PinRequired\" || \"PinIncorrect\" in value || \"TooManyFailedPinAttempts\" in value) {\n return pinNumberFailureResponseV2(value);\n }\n throw new UnsupportedValueError(\"Unexpected ApiSendMessageResponse type received\", value);\n}\nexport function createCommunityResponse(value) {\n if (typeof value === \"object\" && \"Success\" in value) {\n return { kind: \"success\", id: principalBytesToString(value.Success.community_id) };\n }\n else if (value === \"NameTaken\") {\n return { kind: \"name_taken\" };\n }\n else {\n console.warn(\"CreateCommunity failed with\", value);\n return CommonResponses.failure();\n }\n}\nexport async function getEventsResponse(principal, value, chatId, latestKnownUpdatePreRequest) {\n if (typeof value === \"object\") {\n if (\"Success\" in value) {\n await ensureReplicaIsUpToDate(principal, chatId, value.Success.chat_last_updated);\n return eventsSuccessResponse(value.Success);\n }\n if (\"ReplicaNotUpToDateV2\" in value) {\n throw ReplicaNotUpToDateError.byTimestamp(value.ReplicaNotUpToDateV2, latestKnownUpdatePreRequest ?? BigInt(-1), false);\n }\n if (\"Error\" in value) {\n return \"events_failed\";\n }\n }\n if (value === \"ChatNotFound\" || value === \"ThreadMessageNotFound\") {\n return \"events_failed\";\n }\n throw new UnsupportedValueError(\"Unexpected ApiEventsResponse type received\", value);\n}\nfunction groupChatsInitial(value) {\n return {\n summaries: value.summaries.map(userCanisterGroupSummary),\n pinned: value.pinned.map((c) => ({\n kind: \"group_chat\",\n groupId: principalBytesToString(c),\n })),\n };\n}\nfunction directChatsInitial(value) {\n return {\n summaries: value.summaries.map(directChatSummary),\n pinned: value.pinned.map((c) => ({\n kind: \"direct_chat\",\n userId: principalBytesToString(c),\n })),\n };\n}\nfunction userCanisterChannelSummary(value, communityId) {\n return {\n id: {\n kind: \"channel\",\n communityId: communityId,\n channelId: Number(toBigInt32(value.channel_id)),\n },\n readByMeUpTo: value.read_by_me_up_to,\n dateReadPinned: value.date_read_pinned,\n threadsRead: Object.entries(value.threads_read).reduce((curr, next) => {\n curr[Number(next[0])] = next[1];\n return curr;\n }, {}),\n archived: value.archived,\n };\n}\nfunction userCanisterCommunitySummary(value) {\n const communityId = principalBytesToString(value.community_id);\n return {\n id: { kind: \"community\", communityId },\n index: value.index,\n channels: value.channels.map((c) => userCanisterChannelSummary(c, communityId)),\n pinned: value.pinned.map((p) => ({\n kind: \"channel\",\n communityId,\n channelId: Number(toBigInt32(p)),\n })),\n archived: value.archived,\n localUserIndex: principalBytesToString(value.local_user_index_canister_id),\n };\n}\nfunction communitiesInitial(value) {\n return {\n summaries: value.summaries.map(userCanisterCommunitySummary),\n };\n}\nfunction chatIdentifier(value) {\n if (\"Group\" in value) {\n return { kind: \"group_chat\", groupId: principalBytesToString(value.Group) };\n }\n if (\"Direct\" in value) {\n return { kind: \"direct_chat\", userId: principalBytesToString(value.Direct) };\n }\n if (\"Channel\" in value) {\n return {\n kind: \"channel\",\n communityId: principalBytesToString(value.Channel[0]),\n channelId: Number(toBigInt32(value.Channel[1])),\n };\n }\n throw new UnsupportedValueError(\"Unexpected ApiChat type received\", value);\n}\nfunction favouriteChatsInitial(value) {\n return {\n chats: value.chats.map(chatIdentifier),\n pinned: value.pinned.map(chatIdentifier),\n };\n}\nexport function initialStateResponse(value) {\n if (\"Success\" in value) {\n const result = value.Success;\n return {\n blockedUsers: result.blocked_users.map(principalBytesToString),\n communities: communitiesInitial(value.Success.communities),\n groupChats: groupChatsInitial(value.Success.group_chats),\n favouriteChats: favouriteChatsInitial(value.Success.favourite_chats),\n avatarId: result.avatar_id,\n directChats: directChatsInitial(value.Success.direct_chats),\n timestamp: result.timestamp,\n suspended: result.suspended,\n pinNumberSettings: mapOptional(result.pin_number_settings, pinNumberSettings),\n localUserIndex: principalBytesToString(result.local_user_index_canister_id),\n achievementsLastSeen: result.achievements_last_seen,\n achievements: result.achievements.map(chitEarned),\n streakEnds: result.streak_ends,\n streak: result.streak,\n nextDailyClaim: result.next_daily_claim,\n chitBalance: result.chit_balance,\n totalChitEarned: result.total_chit_earned,\n referrals: result.referrals.map(referral),\n walletConfig: walletConfig(result.wallet_config),\n messageActivitySummary: messageActivitySummary(result.message_activity_summary),\n bots: result.bots.map(installedBotDetails).reduce((m, b) => {\n m.set(b.id, b.permissions);\n return m;\n }, new Map()),\n apiKeys: result.api_keys.map(publicApiKeyDetails).reduce((m, k) => {\n m.set(k.botId, k);\n return m;\n }, new Map()),\n bitcoinAddress: result.btc_address,\n };\n }\n throw new Error(`Unexpected ApiUpdatesResponse type received: ${value}`);\n}\nfunction messageActivitySummary(value) {\n return {\n readUpToTimestamp: value.read_up_to,\n latestTimestamp: value.latest_event_timestamp,\n unreadCount: value.unread_count,\n };\n}\nfunction referral(value) {\n return {\n userId: principalBytesToString(value.user_id),\n status: referralStatus(value.status),\n };\n}\nexport function apiWalletConfig(domain) {\n switch (domain.kind) {\n case \"auto_wallet\": {\n return { Auto: { min_cents_visible: Math.round(domain.minDollarValue * 100) } };\n }\n case \"manual_wallet\": {\n return { Manual: { tokens: [...domain.tokens].map(principalStringToBytes) } };\n }\n }\n throw new UnsupportedValueError(\"Unexpected WalletConfig value received\", domain);\n}\nfunction walletConfig(value) {\n if (\"Auto\" in value) {\n return {\n kind: \"auto_wallet\",\n minDollarValue: value.Auto.min_cents_visible / 100,\n };\n }\n if (\"Manual\" in value) {\n return {\n kind: \"manual_wallet\",\n tokens: new Set(value.Manual.tokens.map(principalBytesToString)),\n };\n }\n throw new UnsupportedValueError(\"Unexpected ApiWalletConfig value received\", value);\n}\nfunction pinNumberSettings(value) {\n return {\n length: value.length,\n attemptsBlockedUntil: value.attempts_blocked_until,\n };\n}\nexport function userCanisterChannelSummaryUpdates(value, communityId) {\n return {\n id: { kind: \"channel\", communityId, channelId: Number(toBigInt32(value.channel_id)) },\n readByMeUpTo: value.read_by_me_up_to,\n dateReadPinned: value.date_read_pinned,\n threadsRead: Object.entries(value.threads_read).reduce((curr, next) => {\n curr[Number(next[0])] = next[1];\n return curr;\n }, {}),\n archived: value.archived,\n };\n}\nexport function userCanisterCommunitySummaryUpdates(value) {\n const communityId = principalBytesToString(value.community_id);\n return {\n id: { kind: \"community\", communityId },\n index: value.index,\n channels: value.channels.map((c) => userCanisterChannelSummaryUpdates(c, communityId)),\n pinned: mapOptional(value.pinned, (p) => p.map((c) => ({ kind: \"channel\", communityId, channelId: Number(toBigInt32(c)) }))),\n archived: value.archived,\n };\n}\nexport function communitiesUpdates(value) {\n return {\n added: value.added.map(userCanisterCommunitySummary),\n updated: value.updated.map(userCanisterCommunitySummaryUpdates),\n removed: value.removed.map(principalBytesToString),\n };\n}\nexport function favouriteChatsUpdates(value) {\n return {\n chats: mapOptional(value.chats, (c) => c.map(chatIdentifier)),\n pinned: mapOptional(value.pinned, (c) => c.map(chatIdentifier)),\n };\n}\nexport function groupChatsUpdates(value) {\n return {\n added: value.added.map(userCanisterGroupSummary),\n pinned: mapOptional(value.pinned, (p) => p.map((p) => ({ kind: \"group_chat\", groupId: principalBytesToString(p) }))),\n updated: value.updated.map(userCanisterGroupSummaryUpdates),\n removed: value.removed.map(principalBytesToString),\n };\n}\nexport function directChatsUpdates(value) {\n return {\n added: value.added.map(directChatSummary),\n pinned: mapOptional(value.pinned, (p) => p.map((p) => ({ kind: \"direct_chat\", userId: principalBytesToString(p) }))),\n removed: value.removed.map((id) => ({\n kind: \"direct_chat\",\n userId: principalBytesToString(id),\n })),\n updated: value.updated.map(directChatSummaryUpdates),\n };\n}\nexport function manageFavouritesResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n else {\n console.warn(\"ApiManageFavouriteChatsResponse failure response\", value);\n return \"failure\";\n }\n}\nexport function getUpdatesResponse(value) {\n if (value === \"SuccessNoUpdates\") {\n return {\n kind: \"success_no_updates\",\n };\n }\n if (\"Success\" in value) {\n const result = value.Success;\n return {\n kind: \"success\",\n timestamp: result.timestamp,\n blockedUsers: mapOptional(result.blocked_users, (b) => b.map(principalBytesToString)),\n communities: communitiesUpdates(result.communities),\n favouriteChats: favouriteChatsUpdates(result.favourite_chats),\n groupChats: groupChatsUpdates(result.group_chats),\n avatarId: optionUpdateV2(result.avatar_id, identity),\n directChats: directChatsUpdates(result.direct_chats),\n suspended: result.suspended,\n pinNumberSettings: optionUpdateV2(result.pin_number_settings, pinNumberSettings),\n achievementsLastSeen: result.achievements_last_seen,\n achievements: result.achievements.map(chitEarned),\n streakEnds: result.streak_ends,\n streak: result.streak,\n nextDailyClaim: result.next_daily_claim,\n chitBalance: result.chit_balance,\n totalChitEarned: result.total_chit_earned,\n referrals: result.referrals.map(referral),\n walletConfig: mapOptional(result.wallet_config, walletConfig),\n messageActivitySummary: mapOptional(result.message_activity_summary, messageActivitySummary),\n botsAddedOrUpdated: value.Success.bots_added_or_updated.map(installedBotDetails),\n botsRemoved: new Set(value.Success.bots_removed.map(principalBytesToString)),\n apiKeysGenerated: value.Success.api_keys_generated.map(publicApiKeyDetails),\n bitcoinAddress: value.Success.btc_address,\n };\n }\n throw new Error(`Unexpected ApiUpdatesResponse type received: ${value}`);\n}\nfunction userCanisterGroupSummary(summary) {\n return {\n id: { kind: \"group_chat\", groupId: principalBytesToString(summary.chat_id) },\n readByMeUpTo: summary.read_by_me_up_to,\n threadsRead: Object.entries(summary.threads_read).reduce((curr, next) => {\n curr[Number(next[0])] = next[1];\n return curr;\n }, {}),\n archived: summary.archived,\n dateReadPinned: summary.date_read_pinned,\n localUserIndex: principalBytesToString(summary.local_user_index_canister_id),\n };\n}\nfunction userCanisterGroupSummaryUpdates(summary) {\n return {\n id: { kind: \"group_chat\", groupId: principalBytesToString(summary.chat_id) },\n readByMeUpTo: summary.read_by_me_up_to,\n threadsRead: Object.entries(summary.threads_read).reduce((curr, next) => {\n curr[Number(next[0])] = next[1];\n return curr;\n }, {}),\n archived: summary.archived,\n dateReadPinned: summary.date_read_pinned,\n };\n}\nfunction directChatSummaryUpdates(value) {\n return {\n kind: \"direct_chat\",\n id: { kind: \"direct_chat\", userId: principalBytesToString(value.chat_id) },\n readByMeUpTo: value.read_by_me_up_to,\n readByThemUpTo: value.read_by_them_up_to,\n lastUpdated: value.last_updated,\n latestMessage: mapOptional(value.latest_message, messageEvent),\n latestEventIndex: value.latest_event_index,\n latestMessageIndex: value.latest_message_index,\n notificationsMuted: value.notifications_muted,\n updatedEvents: value.updated_events.map(updatedEvent),\n eventsTTL: optionUpdateV2(value.events_ttl, identity),\n eventsTtlLastUpdated: value.events_ttl_last_updated,\n metrics: mapOptional(value.metrics, chatMetrics),\n myMetrics: mapOptional(value.my_metrics, chatMetrics),\n archived: value.archived,\n videoCallInProgress: optionUpdateV2(value.video_call_in_progress, (v) => v.message_index),\n };\n}\nfunction updatedEvent([eventIndex, timestamp]) {\n return {\n eventIndex,\n timestamp,\n };\n}\nfunction directChatSummary(value) {\n return {\n id: { kind: \"direct_chat\", userId: principalBytesToString(value.them) },\n kind: \"direct_chat\",\n latestMessageIndex: value.latest_message_index,\n latestMessage: mapOptional(value.latest_message, messageEvent),\n them: { kind: \"direct_chat\", userId: principalBytesToString(value.them) },\n latestEventIndex: value.latest_event_index,\n lastUpdated: value.last_updated,\n readByThemUpTo: value.read_by_them_up_to,\n dateCreated: value.date_created,\n eventsTTL: undefined,\n eventsTtlLastUpdated: BigInt(0),\n metrics: chatMetrics(value.metrics),\n videoCallInProgress: mapOptional(value.video_call_in_progress, (v) => v.message_index),\n membership: {\n ...nullMembership(),\n role: \"owner\",\n myMetrics: chatMetrics(value.my_metrics),\n notificationsMuted: value.notifications_muted,\n readByMeUpTo: value.read_by_me_up_to,\n archived: value.archived,\n rulesAccepted: false,\n },\n };\n}\nfunction failedNnsCryptoWithdrawal(value) {\n return {\n kind: \"failed\",\n ledger: principalBytesToString(value.ledger),\n to: value.to !== \"Mint\" ? bytesToHexString(value.to.Account) : \"\",\n amountE8s: value.amount.e8s,\n feeE8s: value.fee.e8s,\n memo: value.memo,\n errorMessage: value.error_message,\n };\n}\nfunction failedIcrc1CryptoWithdrawal(value) {\n return {\n kind: \"failed\",\n ledger: principalBytesToString(value.ledger),\n to: value.to !== \"Mint\" ? formatIcrc1Account(value.to.Account) : \"\",\n amountE8s: value.amount,\n feeE8s: value.fee,\n memo: mapOptional(value.memo, bytesToBigint) ?? BigInt(0),\n errorMessage: value.error_message,\n };\n}\nfunction completedNnsCryptoWithdrawal(value) {\n return {\n kind: \"completed\",\n ledger: principalBytesToString(value.ledger),\n to: value.to !== \"Mint\" ? bytesToHexString(value.to.Account) : \"\",\n amountE8s: value.amount.e8s,\n feeE8s: value.fee.e8s,\n memo: value.memo,\n blockIndex: value.block_index,\n };\n}\nfunction completedIcrc1CryptoWithdrawal(value) {\n return {\n kind: \"completed\",\n ledger: principalBytesToString(value.ledger),\n to: value.to !== \"Mint\" ? formatIcrc1Account(value.to.Account) : \"\",\n amountE8s: value.amount,\n feeE8s: value.fee,\n memo: mapOptional(value.memo, bytesToBigint) ?? BigInt(0),\n blockIndex: value.block_index,\n };\n}\nexport function withdrawCryptoResponse(value) {\n if (typeof value === \"object\") {\n if (\"PinIncorrect\" in value || \"TooManyFailedPinAttempts\" in value) {\n return pinNumberFailureResponseV2(value);\n }\n if (\"TransactionFailed\" in value) {\n if (\"NNS\" in value.TransactionFailed) {\n return failedNnsCryptoWithdrawal(value.TransactionFailed.NNS);\n }\n else if (\"ICRC1\" in value.TransactionFailed) {\n return failedIcrc1CryptoWithdrawal(value.TransactionFailed.ICRC1);\n }\n }\n if (\"Success\" in value) {\n if (\"NNS\" in value.Success) {\n return completedNnsCryptoWithdrawal(value.Success.NNS);\n }\n else if (\"ICRC1\" in value.Success) {\n return completedIcrc1CryptoWithdrawal(value.Success.ICRC1);\n }\n }\n }\n if (value === \"PinRequired\") {\n return pinNumberFailureResponseV2(value);\n }\n if (value === \"CurrencyNotSupported\") {\n return { kind: \"currency_not_supported\" };\n }\n throw new Error(\"Unexpected ApiWithdrawCryptocurrencyResponse type received\");\n}\nfunction formatIcrc1Account(value) {\n const owner = principalBytesToString(value.owner);\n const subaccount = mapOptional(value.subaccount, bytesToHexString);\n return subaccount !== undefined ? `${owner}:${subaccount}` : owner;\n}\nexport function deletedMessageResponse(value) {\n if (typeof value === \"object\") {\n if (\"Success\" in value) {\n return {\n kind: \"success\",\n content: messageContent(value.Success.content, \"unknown\"),\n };\n }\n if (\"Error\" in value) {\n return ocError(value.Error);\n }\n }\n if (value === \"MessageHardDeleted\") {\n return { kind: \"message_hard_deleted\" };\n }\n return {\n kind: mapCommonResponses(value, \"DeletedMessage\"),\n };\n}\nexport function setMessageReminderResponse(value) {\n if (typeof value === \"object\" && \"Success\" in value) {\n return \"success\";\n }\n else {\n console.warn(\"SetMessageReminder failed with\", value);\n return \"failure\";\n }\n}\nexport function leaveCommunityResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n else {\n console.warn(\"LeaveCommunity failed with\", value);\n return \"failure\";\n }\n}\nexport function deleteCommunityResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n else {\n console.warn(\"DeleteCommunity failed with\", value);\n return \"failure\";\n }\n}\nexport function reportMessageResponse(value) {\n return value === \"Success\" || value === \"AlreadyReported\";\n}\nexport function swapTokensResponse(value) {\n if (typeof value === \"object\") {\n if (\"Success\" in value) {\n return {\n kind: \"success\",\n amountOut: value.Success.amount_out,\n };\n }\n if (\"InternalError\" in value) {\n return {\n kind: \"internal_error\",\n error: value.InternalError,\n };\n }\n if (\"Error\" in value) {\n return ocError(value.Error);\n }\n if (\"PinIncorrect\" in value || \"TooManyFailedPinAttempts\" in value) {\n return pinNumberFailureResponseV2(value);\n }\n }\n if (value === \"SwapFailed\") {\n return {\n kind: \"swap_failed\",\n };\n }\n if (value === \"PinRequired\") {\n return pinNumberFailureResponseV2(value);\n }\n throw new UnsupportedValueError(\"Unexpected ApiSwapTokensResponse type received\", value);\n}\nexport function tokenSwapStatusResponse(value) {\n if (typeof value === \"object\") {\n if (\"Success\" in value) {\n return {\n kind: \"success\",\n started: value.Success.started,\n depositAccount: mapOptional(value.Success.deposit_account, result),\n transfer: mapOptional(value.Success.transfer, result),\n notifyDex: mapOptional(value.Success.notify_dex, result),\n amountSwapped: mapOptional(value.Success.amount_swapped, resultOfResult),\n withdrawnFromDex: mapOptional(value.Success.withdraw_from_dex, result),\n };\n }\n if (\"Error\" in value) {\n return ocError(value.Error);\n }\n }\n if (value === \"NotFound\") {\n return {\n kind: \"not_found\",\n };\n }\n throw new UnsupportedValueError(\"Unexpected ApiTokenSwapStatusResponse type received\", value);\n}\nfunction result(value) {\n if (\"Ok\" in value) {\n return {\n kind: \"ok\",\n value: value.Ok,\n };\n }\n return {\n kind: \"error\",\n error: value.Err,\n };\n}\nfunction resultOfResult(value) {\n if (\"Ok\" in value) {\n return {\n kind: \"ok\",\n value: result(value.Ok),\n };\n }\n return {\n kind: \"error\",\n error: value.Err,\n };\n}\nexport function approveTransferResponse(value) {\n if (value === \"Success\") {\n return { kind: \"success\" };\n }\n if (typeof value === \"object\") {\n if (\"InternalError\" in value) {\n return { kind: \"internal_error\", error: value.InternalError };\n }\n if (\"Error\" in value) {\n return { kind: \"internal_error\", error: JSON.stringify(value.Error) };\n }\n if (\"ApproveError\" in value) {\n return { kind: \"approve_error\", error: JSON.stringify(value.ApproveError) };\n }\n if (\"PinIncorrect\" in value || \"TooManyFailedPinAttempts\" in value) {\n return pinNumberFailureResponseV2(value);\n }\n }\n if (value === \"PinRequired\") {\n return pinNumberFailureResponseV2(value);\n }\n throw new UnsupportedValueError(\"Unexpected ApiApproveTransferResponse type received\", value);\n}\nexport function apiExchangeArgs(args) {\n const value = {\n swap_canister_id: principalStringToBytes(args.swapCanisterId),\n zero_for_one: args.zeroForOne,\n };\n if (args.dex === \"icpswap\") {\n return {\n ICPSwap: value,\n };\n }\n else if (args.dex === \"kongswap\") {\n return {\n KongSwap: value,\n };\n }\n else if (args.dex === \"sonic\") {\n throw new Error(\"Unsupported DEX sonic\");\n // return {\n // Sonic: value\n // }\n }\n throw new UnsupportedValueError(\"Unexpected dex\", args.dex);\n}\nexport function claimDailyChitResponse(value) {\n if (\"Success\" in value) {\n return {\n kind: \"success\",\n streak: value.Success.streak,\n chitBalance: value.Success.chit_balance,\n chitEarned: value.Success.chit_earned,\n nextDailyChitClaim: value.Success.next_claim,\n };\n }\n if (\"AlreadyClaimed\" in value) {\n return {\n kind: \"already_claimed\",\n nextDailyChitClaim: value.AlreadyClaimed,\n };\n }\n throw new UnsupportedValueError(\"Unexpected ApiClaimDailyChitResponse type received\", value);\n}\nexport function apiVerification(domain) {\n switch (domain.kind) {\n case \"delegation_verification\":\n return { Delegation: signedDelegation(domain.delegation) };\n case \"no_verification\":\n return \"None\";\n case \"pin_verification\":\n return { PIN: domain.pin };\n }\n}\nexport function withdrawBtcResponse(value) {\n if (typeof value === \"object\") {\n if (\"Success\" in value) {\n return {\n kind: \"success\",\n };\n }\n if (\"PinIncorrect\" in value || \"TooManyFailedPinAttempts\" in value) {\n return pinNumberFailureResponseV2(value);\n }\n }\n if (value === \"PinRequired\") {\n return pinNumberFailureResponseV2(value);\n }\n console.log(\"Failed to withdraw BTC\", value);\n return { kind: \"failure\", message: JSON.stringify(value) };\n}\n","/**\n * [js-sha3]{@link https://github.com/emn178/js-sha3}\n *\n * @version 0.8.0\n * @author Chen, Yi-Cyuan [emn178@gmail.com]\n * @copyright Chen, Yi-Cyuan 2015-2018\n * @license MIT\n */\n/*jslint bitwise: true */\n(function () {\n 'use strict';\n\n var INPUT_ERROR = 'input is invalid type';\n var FINALIZE_ERROR = 'finalize already called';\n var WINDOW = typeof window === 'object';\n var root = WINDOW ? window : {};\n if (root.JS_SHA3_NO_WINDOW) {\n WINDOW = false;\n }\n var WEB_WORKER = !WINDOW && typeof self === 'object';\n var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node;\n if (NODE_JS) {\n root = global;\n } else if (WEB_WORKER) {\n root = self;\n }\n var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && typeof module === 'object' && module.exports;\n var AMD = typeof define === 'function' && define.amd;\n var ARRAY_BUFFER = !root.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined';\n var HEX_CHARS = '0123456789abcdef'.split('');\n var SHAKE_PADDING = [31, 7936, 2031616, 520093696];\n var CSHAKE_PADDING = [4, 1024, 262144, 67108864];\n var KECCAK_PADDING = [1, 256, 65536, 16777216];\n var PADDING = [6, 1536, 393216, 100663296];\n var SHIFT = [0, 8, 16, 24];\n var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649,\n 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0,\n 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771,\n 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648,\n 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648];\n var BITS = [224, 256, 384, 512];\n var SHAKE_BITS = [128, 256];\n var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array', 'digest'];\n var CSHAKE_BYTEPAD = {\n '128': 168,\n '256': 136\n };\n\n if (root.JS_SHA3_NO_NODE_JS || !Array.isArray) {\n Array.isArray = function (obj) {\n return Object.prototype.toString.call(obj) === '[object Array]';\n };\n }\n\n if (ARRAY_BUFFER && (root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) {\n ArrayBuffer.isView = function (obj) {\n return typeof obj === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer;\n };\n }\n\n var createOutputMethod = function (bits, padding, outputType) {\n return function (message) {\n return new Keccak(bits, padding, bits).update(message)[outputType]();\n };\n };\n\n var createShakeOutputMethod = function (bits, padding, outputType) {\n return function (message, outputBits) {\n return new Keccak(bits, padding, outputBits).update(message)[outputType]();\n };\n };\n\n var createCshakeOutputMethod = function (bits, padding, outputType) {\n return function (message, outputBits, n, s) {\n return methods['cshake' + bits].update(message, outputBits, n, s)[outputType]();\n };\n };\n\n var createKmacOutputMethod = function (bits, padding, outputType) {\n return function (key, message, outputBits, s) {\n return methods['kmac' + bits].update(key, message, outputBits, s)[outputType]();\n };\n };\n\n var createOutputMethods = function (method, createMethod, bits, padding) {\n for (var i = 0; i < OUTPUT_TYPES.length; ++i) {\n var type = OUTPUT_TYPES[i];\n method[type] = createMethod(bits, padding, type);\n }\n return method;\n };\n\n var createMethod = function (bits, padding) {\n var method = createOutputMethod(bits, padding, 'hex');\n method.create = function () {\n return new Keccak(bits, padding, bits);\n };\n method.update = function (message) {\n return method.create().update(message);\n };\n return createOutputMethods(method, createOutputMethod, bits, padding);\n };\n\n var createShakeMethod = function (bits, padding) {\n var method = createShakeOutputMethod(bits, padding, 'hex');\n method.create = function (outputBits) {\n return new Keccak(bits, padding, outputBits);\n };\n method.update = function (message, outputBits) {\n return method.create(outputBits).update(message);\n };\n return createOutputMethods(method, createShakeOutputMethod, bits, padding);\n };\n\n var createCshakeMethod = function (bits, padding) {\n var w = CSHAKE_BYTEPAD[bits];\n var method = createCshakeOutputMethod(bits, padding, 'hex');\n method.create = function (outputBits, n, s) {\n if (!n && !s) {\n return methods['shake' + bits].create(outputBits);\n } else {\n return new Keccak(bits, padding, outputBits).bytepad([n, s], w);\n }\n };\n method.update = function (message, outputBits, n, s) {\n return method.create(outputBits, n, s).update(message);\n };\n return createOutputMethods(method, createCshakeOutputMethod, bits, padding);\n };\n\n var createKmacMethod = function (bits, padding) {\n var w = CSHAKE_BYTEPAD[bits];\n var method = createKmacOutputMethod(bits, padding, 'hex');\n method.create = function (key, outputBits, s) {\n return new Kmac(bits, padding, outputBits).bytepad(['KMAC', s], w).bytepad([key], w);\n };\n method.update = function (key, message, outputBits, s) {\n return method.create(key, outputBits, s).update(message);\n };\n return createOutputMethods(method, createKmacOutputMethod, bits, padding);\n };\n\n var algorithms = [\n { name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod },\n { name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod },\n { name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod },\n { name: 'cshake', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createCshakeMethod },\n { name: 'kmac', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createKmacMethod }\n ];\n\n var methods = {}, methodNames = [];\n\n for (var i = 0; i < algorithms.length; ++i) {\n var algorithm = algorithms[i];\n var bits = algorithm.bits;\n for (var j = 0; j < bits.length; ++j) {\n var methodName = algorithm.name + '_' + bits[j];\n methodNames.push(methodName);\n methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding);\n if (algorithm.name !== 'sha3') {\n var newMethodName = algorithm.name + bits[j];\n methodNames.push(newMethodName);\n methods[newMethodName] = methods[methodName];\n }\n }\n }\n\n function Keccak(bits, padding, outputBits) {\n this.blocks = [];\n this.s = [];\n this.padding = padding;\n this.outputBits = outputBits;\n this.reset = true;\n this.finalized = false;\n this.block = 0;\n this.start = 0;\n this.blockCount = (1600 - (bits << 1)) >> 5;\n this.byteCount = this.blockCount << 2;\n this.outputBlocks = outputBits >> 5;\n this.extraBytes = (outputBits & 31) >> 3;\n\n for (var i = 0; i < 50; ++i) {\n this.s[i] = 0;\n }\n }\n\n Keccak.prototype.update = function (message) {\n if (this.finalized) {\n throw new Error(FINALIZE_ERROR);\n }\n var notString, type = typeof message;\n if (type !== 'string') {\n if (type === 'object') {\n if (message === null) {\n throw new Error(INPUT_ERROR);\n } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) {\n message = new Uint8Array(message);\n } else if (!Array.isArray(message)) {\n if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) {\n throw new Error(INPUT_ERROR);\n }\n }\n } else {\n throw new Error(INPUT_ERROR);\n }\n notString = true;\n }\n var blocks = this.blocks, byteCount = this.byteCount, length = message.length,\n blockCount = this.blockCount, index = 0, s = this.s, i, code;\n\n while (index < length) {\n if (this.reset) {\n this.reset = false;\n blocks[0] = this.block;\n for (i = 1; i < blockCount + 1; ++i) {\n blocks[i] = 0;\n }\n }\n if (notString) {\n for (i = this.start; index < length && i < byteCount; ++index) {\n blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];\n }\n } else {\n for (i = this.start; index < length && i < byteCount; ++index) {\n code = message.charCodeAt(index);\n if (code < 0x80) {\n blocks[i >> 2] |= code << SHIFT[i++ & 3];\n } else if (code < 0x800) {\n blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n } else if (code < 0xd800 || code >= 0xe000) {\n blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n } else {\n code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff));\n blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n }\n }\n }\n this.lastByteIndex = i;\n if (i >= byteCount) {\n this.start = i - byteCount;\n this.block = blocks[blockCount];\n for (i = 0; i < blockCount; ++i) {\n s[i] ^= blocks[i];\n }\n f(s);\n this.reset = true;\n } else {\n this.start = i;\n }\n }\n return this;\n };\n\n Keccak.prototype.encode = function (x, right) {\n var o = x & 255, n = 1;\n var bytes = [o];\n x = x >> 8;\n o = x & 255;\n while (o > 0) {\n bytes.unshift(o);\n x = x >> 8;\n o = x & 255;\n ++n;\n }\n if (right) {\n bytes.push(n);\n } else {\n bytes.unshift(n);\n }\n this.update(bytes);\n return bytes.length;\n };\n\n Keccak.prototype.encodeString = function (str) {\n var notString, type = typeof str;\n if (type !== 'string') {\n if (type === 'object') {\n if (str === null) {\n throw new Error(INPUT_ERROR);\n } else if (ARRAY_BUFFER && str.constructor === ArrayBuffer) {\n str = new Uint8Array(str);\n } else if (!Array.isArray(str)) {\n if (!ARRAY_BUFFER || !ArrayBuffer.isView(str)) {\n throw new Error(INPUT_ERROR);\n }\n }\n } else {\n throw new Error(INPUT_ERROR);\n }\n notString = true;\n }\n var bytes = 0, length = str.length;\n if (notString) {\n bytes = length;\n } else {\n for (var i = 0; i < str.length; ++i) {\n var code = str.charCodeAt(i);\n if (code < 0x80) {\n bytes += 1;\n } else if (code < 0x800) {\n bytes += 2;\n } else if (code < 0xd800 || code >= 0xe000) {\n bytes += 3;\n } else {\n code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++i) & 0x3ff));\n bytes += 4;\n }\n }\n }\n bytes += this.encode(bytes * 8);\n this.update(str);\n return bytes;\n };\n\n Keccak.prototype.bytepad = function (strs, w) {\n var bytes = this.encode(w);\n for (var i = 0; i < strs.length; ++i) {\n bytes += this.encodeString(strs[i]);\n }\n var paddingBytes = w - bytes % w;\n var zeros = [];\n zeros.length = paddingBytes;\n this.update(zeros);\n return this;\n };\n\n Keccak.prototype.finalize = function () {\n if (this.finalized) {\n return;\n }\n this.finalized = true;\n var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s;\n blocks[i >> 2] |= this.padding[i & 3];\n if (this.lastByteIndex === this.byteCount) {\n blocks[0] = blocks[blockCount];\n for (i = 1; i < blockCount + 1; ++i) {\n blocks[i] = 0;\n }\n }\n blocks[blockCount - 1] |= 0x80000000;\n for (i = 0; i < blockCount; ++i) {\n s[i] ^= blocks[i];\n }\n f(s);\n };\n\n Keccak.prototype.toString = Keccak.prototype.hex = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var hex = '', block;\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n block = s[i];\n hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] +\n HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] +\n HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] +\n HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F];\n }\n if (j % blockCount === 0) {\n f(s);\n i = 0;\n }\n }\n if (extraBytes) {\n block = s[i];\n hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F];\n if (extraBytes > 1) {\n hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F];\n }\n if (extraBytes > 2) {\n hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F];\n }\n }\n return hex;\n };\n\n Keccak.prototype.arrayBuffer = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var bytes = this.outputBits >> 3;\n var buffer;\n if (extraBytes) {\n buffer = new ArrayBuffer((outputBlocks + 1) << 2);\n } else {\n buffer = new ArrayBuffer(bytes);\n }\n var array = new Uint32Array(buffer);\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n array[j] = s[i];\n }\n if (j % blockCount === 0) {\n f(s);\n }\n }\n if (extraBytes) {\n array[i] = s[i];\n buffer = buffer.slice(0, bytes);\n }\n return buffer;\n };\n\n Keccak.prototype.buffer = Keccak.prototype.arrayBuffer;\n\n Keccak.prototype.digest = Keccak.prototype.array = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var array = [], offset, block;\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n offset = j << 2;\n block = s[i];\n array[offset] = block & 0xFF;\n array[offset + 1] = (block >> 8) & 0xFF;\n array[offset + 2] = (block >> 16) & 0xFF;\n array[offset + 3] = (block >> 24) & 0xFF;\n }\n if (j % blockCount === 0) {\n f(s);\n }\n }\n if (extraBytes) {\n offset = j << 2;\n block = s[i];\n array[offset] = block & 0xFF;\n if (extraBytes > 1) {\n array[offset + 1] = (block >> 8) & 0xFF;\n }\n if (extraBytes > 2) {\n array[offset + 2] = (block >> 16) & 0xFF;\n }\n }\n return array;\n };\n\n function Kmac(bits, padding, outputBits) {\n Keccak.call(this, bits, padding, outputBits);\n }\n\n Kmac.prototype = new Keccak();\n\n Kmac.prototype.finalize = function () {\n this.encode(this.outputBits, true);\n return Keccak.prototype.finalize.call(this);\n };\n\n var f = function (s) {\n var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9,\n b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17,\n b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33,\n b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49;\n for (n = 0; n < 48; n += 2) {\n c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40];\n c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41];\n c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42];\n c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43];\n c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44];\n c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45];\n c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46];\n c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47];\n c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48];\n c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49];\n\n h = c8 ^ ((c2 << 1) | (c3 >>> 31));\n l = c9 ^ ((c3 << 1) | (c2 >>> 31));\n s[0] ^= h;\n s[1] ^= l;\n s[10] ^= h;\n s[11] ^= l;\n s[20] ^= h;\n s[21] ^= l;\n s[30] ^= h;\n s[31] ^= l;\n s[40] ^= h;\n s[41] ^= l;\n h = c0 ^ ((c4 << 1) | (c5 >>> 31));\n l = c1 ^ ((c5 << 1) | (c4 >>> 31));\n s[2] ^= h;\n s[3] ^= l;\n s[12] ^= h;\n s[13] ^= l;\n s[22] ^= h;\n s[23] ^= l;\n s[32] ^= h;\n s[33] ^= l;\n s[42] ^= h;\n s[43] ^= l;\n h = c2 ^ ((c6 << 1) | (c7 >>> 31));\n l = c3 ^ ((c7 << 1) | (c6 >>> 31));\n s[4] ^= h;\n s[5] ^= l;\n s[14] ^= h;\n s[15] ^= l;\n s[24] ^= h;\n s[25] ^= l;\n s[34] ^= h;\n s[35] ^= l;\n s[44] ^= h;\n s[45] ^= l;\n h = c4 ^ ((c8 << 1) | (c9 >>> 31));\n l = c5 ^ ((c9 << 1) | (c8 >>> 31));\n s[6] ^= h;\n s[7] ^= l;\n s[16] ^= h;\n s[17] ^= l;\n s[26] ^= h;\n s[27] ^= l;\n s[36] ^= h;\n s[37] ^= l;\n s[46] ^= h;\n s[47] ^= l;\n h = c6 ^ ((c0 << 1) | (c1 >>> 31));\n l = c7 ^ ((c1 << 1) | (c0 >>> 31));\n s[8] ^= h;\n s[9] ^= l;\n s[18] ^= h;\n s[19] ^= l;\n s[28] ^= h;\n s[29] ^= l;\n s[38] ^= h;\n s[39] ^= l;\n s[48] ^= h;\n s[49] ^= l;\n\n b0 = s[0];\n b1 = s[1];\n b32 = (s[11] << 4) | (s[10] >>> 28);\n b33 = (s[10] << 4) | (s[11] >>> 28);\n b14 = (s[20] << 3) | (s[21] >>> 29);\n b15 = (s[21] << 3) | (s[20] >>> 29);\n b46 = (s[31] << 9) | (s[30] >>> 23);\n b47 = (s[30] << 9) | (s[31] >>> 23);\n b28 = (s[40] << 18) | (s[41] >>> 14);\n b29 = (s[41] << 18) | (s[40] >>> 14);\n b20 = (s[2] << 1) | (s[3] >>> 31);\n b21 = (s[3] << 1) | (s[2] >>> 31);\n b2 = (s[13] << 12) | (s[12] >>> 20);\n b3 = (s[12] << 12) | (s[13] >>> 20);\n b34 = (s[22] << 10) | (s[23] >>> 22);\n b35 = (s[23] << 10) | (s[22] >>> 22);\n b16 = (s[33] << 13) | (s[32] >>> 19);\n b17 = (s[32] << 13) | (s[33] >>> 19);\n b48 = (s[42] << 2) | (s[43] >>> 30);\n b49 = (s[43] << 2) | (s[42] >>> 30);\n b40 = (s[5] << 30) | (s[4] >>> 2);\n b41 = (s[4] << 30) | (s[5] >>> 2);\n b22 = (s[14] << 6) | (s[15] >>> 26);\n b23 = (s[15] << 6) | (s[14] >>> 26);\n b4 = (s[25] << 11) | (s[24] >>> 21);\n b5 = (s[24] << 11) | (s[25] >>> 21);\n b36 = (s[34] << 15) | (s[35] >>> 17);\n b37 = (s[35] << 15) | (s[34] >>> 17);\n b18 = (s[45] << 29) | (s[44] >>> 3);\n b19 = (s[44] << 29) | (s[45] >>> 3);\n b10 = (s[6] << 28) | (s[7] >>> 4);\n b11 = (s[7] << 28) | (s[6] >>> 4);\n b42 = (s[17] << 23) | (s[16] >>> 9);\n b43 = (s[16] << 23) | (s[17] >>> 9);\n b24 = (s[26] << 25) | (s[27] >>> 7);\n b25 = (s[27] << 25) | (s[26] >>> 7);\n b6 = (s[36] << 21) | (s[37] >>> 11);\n b7 = (s[37] << 21) | (s[36] >>> 11);\n b38 = (s[47] << 24) | (s[46] >>> 8);\n b39 = (s[46] << 24) | (s[47] >>> 8);\n b30 = (s[8] << 27) | (s[9] >>> 5);\n b31 = (s[9] << 27) | (s[8] >>> 5);\n b12 = (s[18] << 20) | (s[19] >>> 12);\n b13 = (s[19] << 20) | (s[18] >>> 12);\n b44 = (s[29] << 7) | (s[28] >>> 25);\n b45 = (s[28] << 7) | (s[29] >>> 25);\n b26 = (s[38] << 8) | (s[39] >>> 24);\n b27 = (s[39] << 8) | (s[38] >>> 24);\n b8 = (s[48] << 14) | (s[49] >>> 18);\n b9 = (s[49] << 14) | (s[48] >>> 18);\n\n s[0] = b0 ^ (~b2 & b4);\n s[1] = b1 ^ (~b3 & b5);\n s[10] = b10 ^ (~b12 & b14);\n s[11] = b11 ^ (~b13 & b15);\n s[20] = b20 ^ (~b22 & b24);\n s[21] = b21 ^ (~b23 & b25);\n s[30] = b30 ^ (~b32 & b34);\n s[31] = b31 ^ (~b33 & b35);\n s[40] = b40 ^ (~b42 & b44);\n s[41] = b41 ^ (~b43 & b45);\n s[2] = b2 ^ (~b4 & b6);\n s[3] = b3 ^ (~b5 & b7);\n s[12] = b12 ^ (~b14 & b16);\n s[13] = b13 ^ (~b15 & b17);\n s[22] = b22 ^ (~b24 & b26);\n s[23] = b23 ^ (~b25 & b27);\n s[32] = b32 ^ (~b34 & b36);\n s[33] = b33 ^ (~b35 & b37);\n s[42] = b42 ^ (~b44 & b46);\n s[43] = b43 ^ (~b45 & b47);\n s[4] = b4 ^ (~b6 & b8);\n s[5] = b5 ^ (~b7 & b9);\n s[14] = b14 ^ (~b16 & b18);\n s[15] = b15 ^ (~b17 & b19);\n s[24] = b24 ^ (~b26 & b28);\n s[25] = b25 ^ (~b27 & b29);\n s[34] = b34 ^ (~b36 & b38);\n s[35] = b35 ^ (~b37 & b39);\n s[44] = b44 ^ (~b46 & b48);\n s[45] = b45 ^ (~b47 & b49);\n s[6] = b6 ^ (~b8 & b0);\n s[7] = b7 ^ (~b9 & b1);\n s[16] = b16 ^ (~b18 & b10);\n s[17] = b17 ^ (~b19 & b11);\n s[26] = b26 ^ (~b28 & b20);\n s[27] = b27 ^ (~b29 & b21);\n s[36] = b36 ^ (~b38 & b30);\n s[37] = b37 ^ (~b39 & b31);\n s[46] = b46 ^ (~b48 & b40);\n s[47] = b47 ^ (~b49 & b41);\n s[8] = b8 ^ (~b0 & b2);\n s[9] = b9 ^ (~b1 & b3);\n s[18] = b18 ^ (~b10 & b12);\n s[19] = b19 ^ (~b11 & b13);\n s[28] = b28 ^ (~b20 & b22);\n s[29] = b29 ^ (~b21 & b23);\n s[38] = b38 ^ (~b30 & b32);\n s[39] = b39 ^ (~b31 & b33);\n s[48] = b48 ^ (~b40 & b42);\n s[49] = b49 ^ (~b41 & b43);\n\n s[0] ^= RC[n];\n s[1] ^= RC[n + 1];\n }\n };\n\n if (COMMON_JS) {\n module.exports = methods;\n } else {\n for (i = 0; i < methodNames.length; ++i) {\n root[methodNames[i]] = methods[methodNames[i]];\n }\n if (AMD) {\n define(function () {\n return methods;\n });\n }\n }\n})();\n","/**\n* A handy class to calculate color values.\n*\n* @version 1.0\n* @author Robert Eisele \n* @copyright Copyright (c) 2010, Robert Eisele\n* @link http://www.xarg.org/2010/03/generate-client-side-png-files-using-javascript/\n* @license http://www.opensource.org/licenses/bsd-license.php BSD License\n*\n*/\n\n(function() {\n\n\t// helper functions for that ctx\n\tfunction write(buffer, offs) {\n\t\tfor (var i = 2; i < arguments.length; i++) {\n\t\t\tfor (var j = 0; j < arguments[i].length; j++) {\n\t\t\t\tbuffer[offs++] = arguments[i].charAt(j);\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction byte2(w) {\n\t\treturn String.fromCharCode((w >> 8) & 255, w & 255);\n\t}\n\n\tfunction byte4(w) {\n\t\treturn String.fromCharCode((w >> 24) & 255, (w >> 16) & 255, (w >> 8) & 255, w & 255);\n\t}\n\n\tfunction byte2lsb(w) {\n\t\treturn String.fromCharCode(w & 255, (w >> 8) & 255);\n\t}\n\n\t// modified from original source to support NPM\n\tvar PNGlib = function(width,height,depth) {\n\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t\tthis.depth = depth;\n\n\t\t// pixel data and row filter identifier size\n\t\tthis.pix_size = height * (width + 1);\n\n\t\t// deflate header, pix_size, block headers, adler32 checksum\n\t\tthis.data_size = 2 + this.pix_size + 5 * Math.floor((0xfffe + this.pix_size) / 0xffff) + 4;\n\n\t\t// offsets and sizes of Png chunks\n\t\tthis.ihdr_offs = 0;\t\t\t\t\t\t\t\t\t// IHDR offset and size\n\t\tthis.ihdr_size = 4 + 4 + 13 + 4;\n\t\tthis.plte_offs = this.ihdr_offs + this.ihdr_size;\t// PLTE offset and size\n\t\tthis.plte_size = 4 + 4 + 3 * depth + 4;\n\t\tthis.trns_offs = this.plte_offs + this.plte_size;\t// tRNS offset and size\n\t\tthis.trns_size = 4 + 4 + depth + 4;\n\t\tthis.idat_offs = this.trns_offs + this.trns_size;\t// IDAT offset and size\n\t\tthis.idat_size = 4 + 4 + this.data_size + 4;\n\t\tthis.iend_offs = this.idat_offs + this.idat_size;\t// IEND offset and size\n\t\tthis.iend_size = 4 + 4 + 4;\n\t\tthis.buffer_size = this.iend_offs + this.iend_size;\t// total PNG size\n\n\t\tthis.buffer = new Array();\n\t\tthis.palette = new Object();\n\t\tthis.pindex = 0;\n\n\t\tvar _crc32 = new Array();\n\n\t\t// initialize buffer with zero bytes\n\t\tfor (var i = 0; i < this.buffer_size; i++) {\n\t\t\tthis.buffer[i] = \"\\x00\";\n\t\t}\n\n\t\t// initialize non-zero elements\n\t\twrite(this.buffer, this.ihdr_offs, byte4(this.ihdr_size - 12), 'IHDR', byte4(width), byte4(height), \"\\x08\\x03\");\n\t\twrite(this.buffer, this.plte_offs, byte4(this.plte_size - 12), 'PLTE');\n\t\twrite(this.buffer, this.trns_offs, byte4(this.trns_size - 12), 'tRNS');\n\t\twrite(this.buffer, this.idat_offs, byte4(this.idat_size - 12), 'IDAT');\n\t\twrite(this.buffer, this.iend_offs, byte4(this.iend_size - 12), 'IEND');\n\n\t\t// initialize deflate header\n\t\tvar header = ((8 + (7 << 4)) << 8) | (3 << 6);\n\t\theader+= 31 - (header % 31);\n\n\t\twrite(this.buffer, this.idat_offs + 8, byte2(header));\n\n\t\t// initialize deflate block headers\n\t\tfor (var i = 0; (i << 16) - 1 < this.pix_size; i++) {\n\t\t\tvar size, bits;\n\t\t\tif (i + 0xffff < this.pix_size) {\n\t\t\t\tsize = 0xffff;\n\t\t\t\tbits = \"\\x00\";\n\t\t\t} else {\n\t\t\t\tsize = this.pix_size - (i << 16) - i;\n\t\t\t\tbits = \"\\x01\";\n\t\t\t}\n\t\t\twrite(this.buffer, this.idat_offs + 8 + 2 + (i << 16) + (i << 2), bits, byte2lsb(size), byte2lsb(~size));\n\t\t}\n\n\t\t/* Create crc32 lookup table */\n\t\tfor (var i = 0; i < 256; i++) {\n\t\t\tvar c = i;\n\t\t\tfor (var j = 0; j < 8; j++) {\n\t\t\t\tif (c & 1) {\n\t\t\t\t\tc = -306674912 ^ ((c >> 1) & 0x7fffffff);\n\t\t\t\t} else {\n\t\t\t\t\tc = (c >> 1) & 0x7fffffff;\n\t\t\t\t}\n\t\t\t}\n\t\t\t_crc32[i] = c;\n\t\t}\n\n\t\t// compute the index into a png for a given pixel\n\t\tthis.index = function(x,y) {\n\t\t\tvar i = y * (this.width + 1) + x + 1;\n\t\t\tvar j = this.idat_offs + 8 + 2 + 5 * Math.floor((i / 0xffff) + 1) + i;\n\t\t\treturn j;\n\t\t}\n\n\t\t// convert a color and build up the palette\n\t\tthis.color = function(red, green, blue, alpha) {\n\n\t\t\talpha = alpha >= 0 ? alpha : 255;\n\t\t\tvar color = (((((alpha << 8) | red) << 8) | green) << 8) | blue;\n\n\t\t\tif (typeof this.palette[color] == \"undefined\") {\n\t\t\t\tif (this.pindex == this.depth) return \"\\x00\";\n\n\t\t\t\tvar ndx = this.plte_offs + 8 + 3 * this.pindex;\n\n\t\t\t\tthis.buffer[ndx + 0] = String.fromCharCode(red);\n\t\t\t\tthis.buffer[ndx + 1] = String.fromCharCode(green);\n\t\t\t\tthis.buffer[ndx + 2] = String.fromCharCode(blue);\n\t\t\t\tthis.buffer[this.trns_offs+8+this.pindex] = String.fromCharCode(alpha);\n\n\t\t\t\tthis.palette[color] = String.fromCharCode(this.pindex++);\n\t\t\t}\n\t\t\treturn this.palette[color];\n\t\t}\n\n\t\t// output a PNG string, Base64 encoded\n\t\tthis.getBase64 = function() {\n\n\t\t\tvar s = this.getDump();\n\n\t\t\tvar ch = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\n\t\t\tvar c1, c2, c3, e1, e2, e3, e4;\n\t\t\tvar l = s.length;\n\t\t\tvar i = 0;\n\t\t\tvar r = \"\";\n\n\t\t\tdo {\n\t\t\t\tc1 = s.charCodeAt(i);\n\t\t\t\te1 = c1 >> 2;\n\t\t\t\tc2 = s.charCodeAt(i+1);\n\t\t\t\te2 = ((c1 & 3) << 4) | (c2 >> 4);\n\t\t\t\tc3 = s.charCodeAt(i+2);\n\t\t\t\tif (l < i+2) { e3 = 64; } else { e3 = ((c2 & 0xf) << 2) | (c3 >> 6); }\n\t\t\t\tif (l < i+3) { e4 = 64; } else { e4 = c3 & 0x3f; }\n\t\t\t\tr+= ch.charAt(e1) + ch.charAt(e2) + ch.charAt(e3) + ch.charAt(e4);\n\t\t\t} while ((i+= 3) < l);\n\t\t\treturn r;\n\t\t}\n\n\t\t// output a PNG string\n\t\tthis.getDump = function() {\n\n\t\t\t// compute adler32 of output pixels + row filter bytes\n\t\t\tvar BASE = 65521; /* largest prime smaller than 65536 */\n\t\t\tvar NMAX = 5552; /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */\n\t\t\tvar s1 = 1;\n\t\t\tvar s2 = 0;\n\t\t\tvar n = NMAX;\n\n\t\t\tfor (var y = 0; y < this.height; y++) {\n\t\t\t\tfor (var x = -1; x < this.width; x++) {\n\t\t\t\t\ts1+= this.buffer[this.index(x, y)].charCodeAt(0);\n\t\t\t\t\ts2+= s1;\n\t\t\t\t\tif ((n-= 1) == 0) {\n\t\t\t\t\t\ts1%= BASE;\n\t\t\t\t\t\ts2%= BASE;\n\t\t\t\t\t\tn = NMAX;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\ts1%= BASE;\n\t\t\ts2%= BASE;\n\t\t\twrite(this.buffer, this.idat_offs + this.idat_size - 8, byte4((s2 << 16) | s1));\n\n\t\t\t// compute crc32 of the PNG chunks\n\t\t\tfunction crc32(png, offs, size) {\n\t\t\t\tvar crc = -1;\n\t\t\t\tfor (var i = 4; i < size-4; i += 1) {\n\t\t\t\t\tcrc = _crc32[(crc ^ png[offs+i].charCodeAt(0)) & 0xff] ^ ((crc >> 8) & 0x00ffffff);\n\t\t\t\t}\n\t\t\t\twrite(png, offs+size-4, byte4(crc ^ -1));\n\t\t\t}\n\n\t\t\tcrc32(this.buffer, this.ihdr_offs, this.ihdr_size);\n\t\t\tcrc32(this.buffer, this.plte_offs, this.plte_size);\n\t\t\tcrc32(this.buffer, this.trns_offs, this.trns_size);\n\t\t\tcrc32(this.buffer, this.idat_offs, this.idat_size);\n\t\t\tcrc32(this.buffer, this.iend_offs, this.iend_size);\n\n\t\t\t// convert PNG to string\n\t\t\treturn \"\\x89PNG\\r\\n\\x1a\\n\"+this.buffer.join('');\n\t\t}\n\t}\n\n\t// modified from original source to support NPM\n\tif (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {\n\t\tmodule.exports = PNGlib;\n\t} else {\n\t\twindow.PNGlib = PNGlib;\n\t}\n})();\n","/**\n * Identicon.js 2.3.3\n * http://github.com/stewartlord/identicon.js\n *\n * PNGLib required for PNG output\n * http://www.xarg.org/download/pnglib.js\n *\n * Copyright 2018, Stewart Lord\n * Released under the BSD license\n * http://www.opensource.org/licenses/bsd-license.php\n */\n\n(function() {\n var PNGlib;\n if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {\n PNGlib = require('./pnglib');\n } else {\n PNGlib = window.PNGlib;\n }\n\n var Identicon = function(hash, options){\n if (typeof(hash) !== 'string' || hash.length < 15) {\n throw 'A hash of at least 15 characters is required.';\n }\n\n this.defaults = {\n background: [240, 240, 240, 255],\n margin: 0.08,\n size: 64,\n saturation: 0.7,\n brightness: 0.5,\n format: 'png'\n };\n\n this.options = typeof(options) === 'object' ? options : this.defaults;\n\n // backward compatibility with old constructor (hash, size, margin)\n if (typeof(arguments[1]) === 'number') { this.options.size = arguments[1]; }\n if (arguments[2]) { this.options.margin = arguments[2]; }\n\n this.hash = hash\n this.background = this.options.background || this.defaults.background;\n this.size = this.options.size || this.defaults.size;\n this.format = this.options.format || this.defaults.format;\n this.margin = this.options.margin !== undefined ? this.options.margin : this.defaults.margin;\n\n // foreground defaults to last 7 chars as hue at 70% saturation, 50% brightness\n var hue = parseInt(this.hash.substr(-7), 16) / 0xfffffff;\n var saturation = this.options.saturation || this.defaults.saturation;\n var brightness = this.options.brightness || this.defaults.brightness;\n this.foreground = this.options.foreground || this.hsl2rgb(hue, saturation, brightness);\n };\n\n Identicon.prototype = {\n background: null,\n foreground: null,\n hash: null,\n margin: null,\n size: null,\n format: null,\n\n image: function(){\n return this.isSvg()\n ? new Svg(this.size, this.foreground, this.background)\n : new PNGlib(this.size, this.size, 256);\n },\n\n render: function(){\n var image = this.image(),\n size = this.size,\n baseMargin = Math.floor(size * this.margin),\n cell = Math.floor((size - (baseMargin * 2)) / 5),\n margin = Math.floor((size - cell * 5) / 2),\n bg = image.color.apply(image, this.background),\n fg = image.color.apply(image, this.foreground);\n\n // the first 15 characters of the hash control the pixels (even/odd)\n // they are drawn down the middle first, then mirrored outwards\n var i, color;\n for (i = 0; i < 15; i++) {\n color = parseInt(this.hash.charAt(i), 16) % 2 ? bg : fg;\n if (i < 5) {\n this.rectangle(2 * cell + margin, i * cell + margin, cell, cell, color, image);\n } else if (i < 10) {\n this.rectangle(1 * cell + margin, (i - 5) * cell + margin, cell, cell, color, image);\n this.rectangle(3 * cell + margin, (i - 5) * cell + margin, cell, cell, color, image);\n } else if (i < 15) {\n this.rectangle(0 * cell + margin, (i - 10) * cell + margin, cell, cell, color, image);\n this.rectangle(4 * cell + margin, (i - 10) * cell + margin, cell, cell, color, image);\n }\n }\n\n return image;\n },\n\n rectangle: function(x, y, w, h, color, image){\n if (this.isSvg()) {\n image.rectangles.push({x: x, y: y, w: w, h: h, color: color});\n } else {\n var i, j;\n for (i = x; i < x + w; i++) {\n for (j = y; j < y + h; j++) {\n image.buffer[image.index(i, j)] = color;\n }\n }\n }\n },\n\n // adapted from: https://gist.github.com/aemkei/1325937\n hsl2rgb: function(h, s, b){\n h *= 6;\n s = [\n b += s *= b < .5 ? b : 1 - b,\n b - h % 1 * s * 2,\n b -= s *= 2,\n b,\n b + h % 1 * s,\n b + s\n ];\n\n return[\n s[ ~~h % 6 ] * 255, // red\n s[ (h|16) % 6 ] * 255, // green\n s[ (h|8) % 6 ] * 255 // blue\n ];\n },\n\n toString: function(raw){\n // backward compatibility with old toString, default to base64\n if (raw) {\n return this.render().getDump();\n } else {\n return this.render().getBase64();\n }\n },\n\n isSvg: function(){\n return this.format.match(/svg/i)\n }\n };\n\n var Svg = function(size, foreground, background){\n this.size = size;\n this.foreground = this.color.apply(this, foreground);\n this.background = this.color.apply(this, background);\n this.rectangles = [];\n };\n\n Svg.prototype = {\n size: null,\n foreground: null,\n background: null,\n rectangles: null,\n\n color: function(r, g, b, a){\n var values = [r, g, b].map(Math.round);\n values.push((a >= 0) && (a <= 255) ? a/255 : 1);\n return 'rgba(' + values.join(',') + ')';\n },\n\n getDump: function(){\n var i,\n xml,\n rect,\n fg = this.foreground,\n bg = this.background,\n stroke = this.size * 0.005;\n\n xml = \"\"\n + \"\";\n\n for (i = 0; i < this.rectangles.length; i++) {\n rect = this.rectangles[i];\n if (rect.color == bg) continue;\n xml += \"\";\n }\n xml += \"\"\n\n return xml;\n },\n\n getBase64: function(){\n if ('function' === typeof btoa) {\n return btoa(this.getDump());\n } else if (Buffer) {\n return new Buffer(this.getDump(), 'binary').toString('base64');\n } else {\n throw 'Cannot generate base64 output';\n }\n }\n };\n\n if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {\n module.exports = Identicon;\n } else {\n window.Identicon = Identicon;\n }\n})();\n","(function() {\n var base64map\n = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n\n crypt = {\n // Bit-wise rotation left\n rotl: function(n, b) {\n return (n << b) | (n >>> (32 - b));\n },\n\n // Bit-wise rotation right\n rotr: function(n, b) {\n return (n << (32 - b)) | (n >>> b);\n },\n\n // Swap big-endian to little-endian and vice versa\n endian: function(n) {\n // If number given, swap endian\n if (n.constructor == Number) {\n return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00;\n }\n\n // Else, assume array and swap all items\n for (var i = 0; i < n.length; i++)\n n[i] = crypt.endian(n[i]);\n return n;\n },\n\n // Generate an array of any length of random bytes\n randomBytes: function(n) {\n for (var bytes = []; n > 0; n--)\n bytes.push(Math.floor(Math.random() * 256));\n return bytes;\n },\n\n // Convert a byte array to big-endian 32-bit words\n bytesToWords: function(bytes) {\n for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8)\n words[b >>> 5] |= bytes[i] << (24 - b % 32);\n return words;\n },\n\n // Convert big-endian 32-bit words to a byte array\n wordsToBytes: function(words) {\n for (var bytes = [], b = 0; b < words.length * 32; b += 8)\n bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);\n return bytes;\n },\n\n // Convert a byte array to a hex string\n bytesToHex: function(bytes) {\n for (var hex = [], i = 0; i < bytes.length; i++) {\n hex.push((bytes[i] >>> 4).toString(16));\n hex.push((bytes[i] & 0xF).toString(16));\n }\n return hex.join('');\n },\n\n // Convert a hex string to a byte array\n hexToBytes: function(hex) {\n for (var bytes = [], c = 0; c < hex.length; c += 2)\n bytes.push(parseInt(hex.substr(c, 2), 16));\n return bytes;\n },\n\n // Convert a byte array to a base-64 string\n bytesToBase64: function(bytes) {\n for (var base64 = [], i = 0; i < bytes.length; i += 3) {\n var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n for (var j = 0; j < 4; j++)\n if (i * 8 + j * 6 <= bytes.length * 8)\n base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F));\n else\n base64.push('=');\n }\n return base64.join('');\n },\n\n // Convert a base-64 string to a byte array\n base64ToBytes: function(base64) {\n // Remove non-base-64 characters\n base64 = base64.replace(/[^A-Z0-9+\\/]/ig, '');\n\n for (var bytes = [], i = 0, imod4 = 0; i < base64.length;\n imod4 = ++i % 4) {\n if (imod4 == 0) continue;\n bytes.push(((base64map.indexOf(base64.charAt(i - 1))\n & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2))\n | (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2)));\n }\n return bytes;\n }\n };\n\n module.exports = crypt;\n})();\n","var charenc = {\n // UTF-8 encoding\n utf8: {\n // Convert a string to a byte array\n stringToBytes: function(str) {\n return charenc.bin.stringToBytes(unescape(encodeURIComponent(str)));\n },\n\n // Convert a byte array to a string\n bytesToString: function(bytes) {\n return decodeURIComponent(escape(charenc.bin.bytesToString(bytes)));\n }\n },\n\n // Binary encoding\n bin: {\n // Convert a string to a byte array\n stringToBytes: function(str) {\n for (var bytes = [], i = 0; i < str.length; i++)\n bytes.push(str.charCodeAt(i) & 0xFF);\n return bytes;\n },\n\n // Convert a byte array to a string\n bytesToString: function(bytes) {\n for (var str = [], i = 0; i < bytes.length; i++)\n str.push(String.fromCharCode(bytes[i]));\n return str.join('');\n }\n }\n};\n\nmodule.exports = charenc;\n","/*!\n * Determine if an object is a Buffer\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n\n// The _isBuffer check is for Safari 5-7 support, because it's missing\n// Object.prototype.constructor. Remove this eventually\nmodule.exports = function (obj) {\n return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)\n}\n\nfunction isBuffer (obj) {\n return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)\n}\n\n// For Node v0.10 support. Remove this eventually.\nfunction isSlowBuffer (obj) {\n return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))\n}\n","(function(){\r\n var crypt = require('crypt'),\r\n utf8 = require('charenc').utf8,\r\n isBuffer = require('is-buffer'),\r\n bin = require('charenc').bin,\r\n\r\n // The core\r\n md5 = function (message, options) {\r\n // Convert to byte array\r\n if (message.constructor == String)\r\n if (options && options.encoding === 'binary')\r\n message = bin.stringToBytes(message);\r\n else\r\n message = utf8.stringToBytes(message);\r\n else if (isBuffer(message))\r\n message = Array.prototype.slice.call(message, 0);\r\n else if (!Array.isArray(message) && message.constructor !== Uint8Array)\r\n message = message.toString();\r\n // else, assume byte array already\r\n\r\n var m = crypt.bytesToWords(message),\r\n l = message.length * 8,\r\n a = 1732584193,\r\n b = -271733879,\r\n c = -1732584194,\r\n d = 271733878;\r\n\r\n // Swap endian\r\n for (var i = 0; i < m.length; i++) {\r\n m[i] = ((m[i] << 8) | (m[i] >>> 24)) & 0x00FF00FF |\r\n ((m[i] << 24) | (m[i] >>> 8)) & 0xFF00FF00;\r\n }\r\n\r\n // Padding\r\n m[l >>> 5] |= 0x80 << (l % 32);\r\n m[(((l + 64) >>> 9) << 4) + 14] = l;\r\n\r\n // Method shortcuts\r\n var FF = md5._ff,\r\n GG = md5._gg,\r\n HH = md5._hh,\r\n II = md5._ii;\r\n\r\n for (var i = 0; i < m.length; i += 16) {\r\n\r\n var aa = a,\r\n bb = b,\r\n cc = c,\r\n dd = d;\r\n\r\n a = FF(a, b, c, d, m[i+ 0], 7, -680876936);\r\n d = FF(d, a, b, c, m[i+ 1], 12, -389564586);\r\n c = FF(c, d, a, b, m[i+ 2], 17, 606105819);\r\n b = FF(b, c, d, a, m[i+ 3], 22, -1044525330);\r\n a = FF(a, b, c, d, m[i+ 4], 7, -176418897);\r\n d = FF(d, a, b, c, m[i+ 5], 12, 1200080426);\r\n c = FF(c, d, a, b, m[i+ 6], 17, -1473231341);\r\n b = FF(b, c, d, a, m[i+ 7], 22, -45705983);\r\n a = FF(a, b, c, d, m[i+ 8], 7, 1770035416);\r\n d = FF(d, a, b, c, m[i+ 9], 12, -1958414417);\r\n c = FF(c, d, a, b, m[i+10], 17, -42063);\r\n b = FF(b, c, d, a, m[i+11], 22, -1990404162);\r\n a = FF(a, b, c, d, m[i+12], 7, 1804603682);\r\n d = FF(d, a, b, c, m[i+13], 12, -40341101);\r\n c = FF(c, d, a, b, m[i+14], 17, -1502002290);\r\n b = FF(b, c, d, a, m[i+15], 22, 1236535329);\r\n\r\n a = GG(a, b, c, d, m[i+ 1], 5, -165796510);\r\n d = GG(d, a, b, c, m[i+ 6], 9, -1069501632);\r\n c = GG(c, d, a, b, m[i+11], 14, 643717713);\r\n b = GG(b, c, d, a, m[i+ 0], 20, -373897302);\r\n a = GG(a, b, c, d, m[i+ 5], 5, -701558691);\r\n d = GG(d, a, b, c, m[i+10], 9, 38016083);\r\n c = GG(c, d, a, b, m[i+15], 14, -660478335);\r\n b = GG(b, c, d, a, m[i+ 4], 20, -405537848);\r\n a = GG(a, b, c, d, m[i+ 9], 5, 568446438);\r\n d = GG(d, a, b, c, m[i+14], 9, -1019803690);\r\n c = GG(c, d, a, b, m[i+ 3], 14, -187363961);\r\n b = GG(b, c, d, a, m[i+ 8], 20, 1163531501);\r\n a = GG(a, b, c, d, m[i+13], 5, -1444681467);\r\n d = GG(d, a, b, c, m[i+ 2], 9, -51403784);\r\n c = GG(c, d, a, b, m[i+ 7], 14, 1735328473);\r\n b = GG(b, c, d, a, m[i+12], 20, -1926607734);\r\n\r\n a = HH(a, b, c, d, m[i+ 5], 4, -378558);\r\n d = HH(d, a, b, c, m[i+ 8], 11, -2022574463);\r\n c = HH(c, d, a, b, m[i+11], 16, 1839030562);\r\n b = HH(b, c, d, a, m[i+14], 23, -35309556);\r\n a = HH(a, b, c, d, m[i+ 1], 4, -1530992060);\r\n d = HH(d, a, b, c, m[i+ 4], 11, 1272893353);\r\n c = HH(c, d, a, b, m[i+ 7], 16, -155497632);\r\n b = HH(b, c, d, a, m[i+10], 23, -1094730640);\r\n a = HH(a, b, c, d, m[i+13], 4, 681279174);\r\n d = HH(d, a, b, c, m[i+ 0], 11, -358537222);\r\n c = HH(c, d, a, b, m[i+ 3], 16, -722521979);\r\n b = HH(b, c, d, a, m[i+ 6], 23, 76029189);\r\n a = HH(a, b, c, d, m[i+ 9], 4, -640364487);\r\n d = HH(d, a, b, c, m[i+12], 11, -421815835);\r\n c = HH(c, d, a, b, m[i+15], 16, 530742520);\r\n b = HH(b, c, d, a, m[i+ 2], 23, -995338651);\r\n\r\n a = II(a, b, c, d, m[i+ 0], 6, -198630844);\r\n d = II(d, a, b, c, m[i+ 7], 10, 1126891415);\r\n c = II(c, d, a, b, m[i+14], 15, -1416354905);\r\n b = II(b, c, d, a, m[i+ 5], 21, -57434055);\r\n a = II(a, b, c, d, m[i+12], 6, 1700485571);\r\n d = II(d, a, b, c, m[i+ 3], 10, -1894986606);\r\n c = II(c, d, a, b, m[i+10], 15, -1051523);\r\n b = II(b, c, d, a, m[i+ 1], 21, -2054922799);\r\n a = II(a, b, c, d, m[i+ 8], 6, 1873313359);\r\n d = II(d, a, b, c, m[i+15], 10, -30611744);\r\n c = II(c, d, a, b, m[i+ 6], 15, -1560198380);\r\n b = II(b, c, d, a, m[i+13], 21, 1309151649);\r\n a = II(a, b, c, d, m[i+ 4], 6, -145523070);\r\n d = II(d, a, b, c, m[i+11], 10, -1120210379);\r\n c = II(c, d, a, b, m[i+ 2], 15, 718787259);\r\n b = II(b, c, d, a, m[i+ 9], 21, -343485551);\r\n\r\n a = (a + aa) >>> 0;\r\n b = (b + bb) >>> 0;\r\n c = (c + cc) >>> 0;\r\n d = (d + dd) >>> 0;\r\n }\r\n\r\n return crypt.endian([a, b, c, d]);\r\n };\r\n\r\n // Auxiliary functions\r\n md5._ff = function (a, b, c, d, x, s, t) {\r\n var n = a + (b & c | ~b & d) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n md5._gg = function (a, b, c, d, x, s, t) {\r\n var n = a + (b & d | c & ~d) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n md5._hh = function (a, b, c, d, x, s, t) {\r\n var n = a + (b ^ c ^ d) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n md5._ii = function (a, b, c, d, x, s, t) {\r\n var n = a + (c ^ (b | ~d)) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n\r\n // Package private blocksize\r\n md5._blocksize = 16;\r\n md5._digestsize = 16;\r\n\r\n module.exports = function (message, options) {\r\n if (message === undefined || message === null)\r\n throw new Error('Illegal argument ' + message);\r\n\r\n var digestbytes = crypt.wordsToBytes(md5(message, options));\r\n return options && options.asBytes ? digestbytes :\r\n options && options.asString ? bin.bytesToString(digestbytes) :\r\n crypt.bytesToHex(digestbytes);\r\n };\r\n\r\n})();\r\n","import { ChatMap, applyOptionUpdate, bigIntMax, mapOptionUpdate, OPENCHAT_BOT_AVATAR_URL, OPENCHAT_BOT_USER_ID, OPENCHAT_VIDEO_CALL_AVATAR_URL, OPENCHAT_VIDEO_CALL_USER_ID, } from \"openchat-shared\";\nimport { toRecord } from \"./list\";\nimport { identity } from \"./mapping\";\nimport Identicon from \"identicon.js\";\nimport md5 from \"md5\";\n// this is used to merge both the overall list of chats with updates and also the list of participants\n// within a group chat\nfunction mergeThings(keyFn, mergeFn, things, updates) {\n // if there's nothing to do - do nothing\n if (updates.added.length === 0 && updates.updated.length === 0 && updates.removed.size === 0)\n return things;\n // create a lookup of all existing and added things\n const dict = toRecord(things.concat(updates.added), keyFn);\n // delete all removed things\n updates.removed.forEach((key) => {\n delete dict[key];\n });\n // merge in all updates\n const updated = updates.updated.reduce((dict, updated) => {\n const key = keyFn(updated);\n const merged = mergeFn(dict[key], updated);\n if (merged) {\n dict[key] = merged;\n }\n return dict;\n }, dict);\n // return the result\n return Object.values(updated);\n}\nexport function mergeCommunityDetails(previous, updates) {\n updates.botsRemoved.forEach((id) => {\n previous.apiKeys.delete(id);\n });\n return {\n lastUpdated: updates.lastUpdated,\n members: mergeThings((p) => p.userId, mergeParticipants, previous.members, {\n added: [],\n updated: updates.membersAddedOrUpdated,\n removed: updates.membersRemoved,\n }),\n blockedUsers: new Set(mergeThings(identity, identity, [...previous.blockedUsers], {\n added: [...updates.blockedUsersAdded],\n updated: [],\n removed: updates.blockedUsersRemoved,\n })),\n referrals: new Set(mergeThings(identity, identity, [...previous.referrals], {\n added: [...updates.referralsAdded],\n updated: [],\n removed: updates.referralsRemoved,\n })),\n invitedUsers: updates.invitedUsers ?? previous.invitedUsers,\n rules: updates.rules ?? previous.rules,\n userGroups: mergeUserGroups(previous.userGroups, updates.userGroups, updates.userGroupsDeleted),\n bots: mergeThings((b) => b.id, (_, updated) => updated, previous.bots, {\n added: [],\n updated: updates.botsAddedOrUpdated,\n removed: updates.botsRemoved,\n }),\n apiKeys: updates.apiKeysGenerated.reduce((m, k) => {\n m.set(k.botId, k);\n return m;\n }, previous.apiKeys),\n };\n}\nfunction mergeUserGroups(previous, updated, deleted) {\n deleted.forEach((id) => previous.delete(id));\n updated.forEach((g) => previous.set(g.id, g));\n return new Map(previous);\n}\nexport function mergeGroupChatDetails(previous, updates) {\n updates.botsRemoved.forEach((id) => {\n previous.apiKeys.delete(id);\n });\n return {\n timestamp: updates.timestamp,\n members: mergeThings((p) => p.userId, mergeParticipants, previous.members, {\n added: [],\n updated: updates.membersAddedOrUpdated,\n removed: updates.membersRemoved,\n }),\n blockedUsers: new Set(mergeThings(identity, identity, [...previous.blockedUsers], {\n added: [...updates.blockedUsersAdded],\n updated: [],\n removed: updates.blockedUsersRemoved,\n })),\n invitedUsers: updates.invitedUsers ?? previous.invitedUsers,\n pinnedMessages: mergePinnedMessages(previous.pinnedMessages, updates.pinnedMessagesAdded, updates.pinnedMessagesRemoved),\n rules: updates.rules ?? previous.rules,\n bots: mergeThings((b) => b.id, (_, updated) => updated, previous.bots, {\n added: [],\n updated: updates.botsAddedOrUpdated,\n removed: updates.botsRemoved,\n }),\n apiKeys: updates.apiKeysGenerated.reduce((m, k) => {\n m.set(k.botId, k);\n return m;\n }, previous.apiKeys),\n };\n}\nfunction mergePinnedMessages(current, added, removed) {\n removed.forEach((m) => current.delete(m));\n added.forEach((m) => current.add(m));\n return current;\n}\nfunction mergeParticipants(_, updated) {\n return updated;\n}\nexport function mergeDirectChatUpdates(directChats, updates, removed) {\n const lookup = ChatMap.fromList(updates);\n const toRemove = new Set(removed);\n return directChats\n .filter((c) => !toRemove.has(c.them.userId))\n .map((c) => {\n const u = lookup.get(c.id);\n if (u === undefined)\n return c;\n return {\n kind: \"direct_chat\",\n id: c.id,\n them: c.them,\n readByThemUpTo: u.readByThemUpTo ?? c.readByThemUpTo,\n dateCreated: c.dateCreated,\n lastUpdated: u.lastUpdated,\n latestEventIndex: u.latestEventIndex ?? c.latestEventIndex,\n latestMessage: u.latestMessage ?? c.latestMessage,\n latestMessageIndex: u.latestMessageIndex ?? c.latestMessageIndex,\n metrics: u.metrics ?? c.metrics,\n eventsTTL: applyOptionUpdate(c.eventsTTL, u.eventsTTL),\n eventsTtlLastUpdated: bigIntMax(c.eventsTtlLastUpdated ?? BigInt(0), u.eventsTtlLastUpdated ?? BigInt(0)),\n videoCallInProgress: applyOptionUpdate(c.videoCallInProgress, u.videoCallInProgress),\n membership: {\n ...c.membership,\n readByMeUpTo: u.readByMeUpTo ?? c.membership.readByMeUpTo,\n notificationsMuted: u.notificationsMuted ?? c.membership.notificationsMuted,\n myMetrics: u.myMetrics ?? c.membership.myMetrics,\n archived: u.archived ?? c.membership.archived,\n rulesAccepted: false,\n lapsed: false,\n },\n };\n });\n}\nexport function mergeGroupChatUpdates(groupChats, userCanisterUpdates, groupCanisterUpdates) {\n const userLookup = ChatMap.fromList(userCanisterUpdates);\n const groupLookup = ChatMap.fromList(groupCanisterUpdates);\n return groupChats.map((c) => {\n const u = userLookup.get(c.id);\n const g = groupLookup.get(c.id);\n if (u === undefined && g === undefined)\n return c;\n const latestMessageIndex = g?.latestMessageIndex ?? c.latestMessageIndex;\n let latestMessage = g?.latestMessage ?? c.latestMessage;\n if (latestMessage !== undefined &&\n latestMessage.event.messageIndex !== latestMessageIndex) {\n latestMessage = undefined;\n }\n const readByMeUpTo = u?.readByMeUpTo ?? c.membership.readByMeUpTo;\n const blobReferenceUpdate = mapOptionUpdate(g?.avatarId, (avatarId) => ({\n blobId: avatarId,\n canisterId: c.id.groupId,\n }));\n return {\n kind: \"group_chat\",\n id: c.id,\n name: g?.name ?? c.name,\n description: g?.description ?? c.description,\n minVisibleEventIndex: c.minVisibleEventIndex,\n minVisibleMessageIndex: c.minVisibleMessageIndex,\n lastUpdated: g?.lastUpdated ?? c.lastUpdated,\n memberCount: g?.memberCount ?? c.memberCount,\n public: g?.public ?? c.public,\n permissions: g?.permissions ?? c.permissions,\n historyVisible: c.historyVisible,\n subtype: applyOptionUpdate(c.subtype, g?.subtype),\n previewed: false,\n frozen: applyOptionUpdate(c.frozen, g?.frozen) ?? false,\n latestEventIndex: g?.latestEventIndex ?? c.latestEventIndex,\n latestMessage,\n latestMessageIndex,\n metrics: g?.metrics ?? c.metrics,\n blobReference: applyOptionUpdate(c.blobReference, blobReferenceUpdate),\n dateLastPinned: g?.dateLastPinned ?? c.dateLastPinned,\n dateReadPinned: u?.dateReadPinned ?? c.dateReadPinned,\n gateConfig: applyOptionUpdate(c.gateConfig, g?.gateConfig) ?? {\n gate: { kind: \"no_gate\" },\n expiry: undefined,\n },\n level: \"group\",\n eventsTTL: applyOptionUpdate(c.eventsTTL, g?.eventsTTL),\n eventsTtlLastUpdated: bigIntMax(c.eventsTtlLastUpdated ?? BigInt(0), g?.eventsTtlLastUpdated ?? BigInt(0)),\n membership: {\n ...c.membership,\n mentions: g === undefined\n ? c.membership.mentions\n : [...(g?.membership?.mentions ?? []), ...c.membership.mentions],\n role: g?.membership?.myRole ?? c.membership.role,\n latestThreads: mergeThreads(c.membership.latestThreads, g?.membership?.latestThreads ?? [], g?.membership?.unfollowedThreads ?? [], u?.threadsRead ?? {}),\n readByMeUpTo: readByMeUpTo !== undefined && latestMessage !== undefined\n ? Math.min(readByMeUpTo, latestMessage.event.messageIndex)\n : readByMeUpTo,\n notificationsMuted: g?.membership?.notificationsMuted ?? c.membership.notificationsMuted,\n myMetrics: g?.membership?.myMetrics ?? c.membership.myMetrics,\n archived: u?.archived ?? c.membership.archived,\n rulesAccepted: g?.membership?.rulesAccepted ?? c.membership.rulesAccepted,\n lapsed: g?.membership?.lapsed ?? c.membership.lapsed,\n },\n localUserIndex: c.localUserIndex,\n videoCallInProgress: applyOptionUpdate(c.videoCallInProgress, g?.videoCallInProgress),\n isInvited: false,\n messagesVisibleToNonMembers: g?.messagesVisibleToNonMembers ?? c.messagesVisibleToNonMembers,\n verified: g?.verified ?? c.verified,\n };\n });\n}\nexport function mergeGroupChats(userCanisterGroups, groupCanisterGroups) {\n const userCanisterGroupLookup = ChatMap.fromList(userCanisterGroups);\n return groupCanisterGroups.map((g) => {\n const u = userCanisterGroupLookup.get(g.id);\n return {\n kind: \"group_chat\",\n id: g.id,\n name: g.name,\n description: g.description,\n minVisibleEventIndex: g.minVisibleEventIndex,\n minVisibleMessageIndex: g.minVisibleMessageIndex,\n lastUpdated: g.lastUpdated,\n memberCount: g.memberCount,\n public: g.public,\n permissions: g.permissions,\n historyVisible: g.historyVisible,\n subtype: g.subtype,\n previewed: false,\n frozen: g.frozen,\n latestEventIndex: g.latestEventIndex,\n latestMessage: g.latestMessage,\n latestMessageIndex: g.latestMessageIndex,\n metrics: g.metrics,\n blobReference: g.avatarId !== undefined\n ? { blobId: g.avatarId, canisterId: g.id.groupId }\n : undefined,\n dateLastPinned: g.dateLastPinned,\n dateReadPinned: u?.dateReadPinned,\n gateConfig: g.gateConfig,\n level: \"group\",\n eventsTTL: g.eventsTTL,\n eventsTtlLastUpdated: g.eventsTtlLastUpdated,\n membership: {\n ...g.membership,\n latestThreads: mergeThreads([], g.membership.latestThreads, [], u?.threadsRead ?? {}),\n readByMeUpTo: u?.readByMeUpTo,\n archived: u?.archived ?? false,\n },\n localUserIndex: g.localUserIndex,\n videoCallInProgress: g.videoCallInProgress,\n isInvited: false,\n messagesVisibleToNonMembers: g.messagesVisibleToNonMembers,\n verified: g.verified,\n };\n });\n}\nfunction mergeThreads(current, groupCanisterUpdates, groupCanisterUnfollowedThreads, readUpToUpdates) {\n const initial = current.filter((t) => !groupCanisterUnfollowedThreads.includes(t.threadRootMessageIndex));\n const threadsRecord = toRecord(initial, (t) => t.threadRootMessageIndex);\n for (const groupUpdate of groupCanisterUpdates) {\n threadsRecord[groupUpdate.threadRootMessageIndex] = {\n ...threadsRecord[groupUpdate.threadRootMessageIndex],\n ...groupUpdate,\n };\n }\n return Object.values(threadsRecord).map((t) => {\n const readUpToUpdate = readUpToUpdates[t.threadRootMessageIndex];\n return readUpToUpdate !== undefined && readUpToUpdate > (t.readUpTo ?? -1)\n ? { ...t, readUpTo: readUpToUpdate }\n : t;\n });\n}\nexport function getUpdatedEvents(directChats, groupChats, communities) {\n const result = new ChatMap();\n directChats\n .filter((c) => c.updatedEvents.length > 0)\n .forEach((c) => result.set(c.id, c.updatedEvents));\n groupChats\n .filter((c) => c.updatedEvents.length > 0)\n .forEach((c) => result.set(c.id, c.updatedEvents));\n communities\n .flatMap((c) => c.channelsUpdated)\n .filter((c) => c.updatedEvents.length > 0)\n .forEach((c) => result.set(c.id, c.updatedEvents));\n return result;\n}\nexport function buildBlobUrl(pattern, canisterId, blobId, blobType, channelId) {\n const blobTypeFragment = channelId === undefined ? blobType : `channel/${channelId.channelId}/${blobType}`;\n return `${pattern\n .replace(\"{canisterId}\", canisterId)\n .replace(\"{blobType}\", blobTypeFragment)}/${blobId}`;\n}\nexport function buildTokenLogoUrl(pattern, canisterId, ledger, logoId) {\n return `${pattern\n .replace(\"{canisterId}\", canisterId)\n .replace(\"{blobType}\", \"logo\")}?ledger=${ledger}&id=${logoId}`;\n}\nexport function buildUserAvatarUrl(pattern, userId, avatarId) {\n return avatarId !== undefined\n ? buildBlobUrl(pattern, userId, avatarId, \"avatar\")\n : userId === OPENCHAT_BOT_USER_ID\n ? OPENCHAT_BOT_AVATAR_URL\n : userId === OPENCHAT_VIDEO_CALL_USER_ID\n ? OPENCHAT_VIDEO_CALL_AVATAR_URL\n : buildIdenticonUrl(userId);\n}\nexport function buildIdenticonUrl(userId) {\n const identicon = new Identicon(md5(userId), {\n margin: 0,\n format: \"svg\",\n });\n return `data:image/svg+xml;base64,${identicon}`;\n}\nexport function emptyChatMetrics() {\n return {\n audioMessages: 0,\n edits: 0,\n icpMessages: 0,\n sns1Messages: 0,\n ckbtcMessages: 0,\n giphyMessages: 0,\n deletedMessages: 0,\n reportedMessages: 0,\n fileMessages: 0,\n pollVotes: 0,\n textMessages: 0,\n imageMessages: 0,\n replies: 0,\n videoMessages: 0,\n polls: 0,\n reactions: 0,\n };\n}\nexport function nextIndex(ascending, events) {\n if (events.length === 0)\n return undefined;\n return ascending ? events[events.length - 1].index + 1 : events[0].index - 1;\n}\n","export const idlFactory = ({ IDL }) => {\n const Hash = IDL.Vec(IDL.Nat8);\n const AllocatedBucketArgs = IDL.Record({\n 'file_hash': Hash,\n 'file_size': IDL.Nat64,\n 'file_id_seed': IDL.Opt(IDL.Nat),\n });\n const CanisterId = IDL.Principal;\n const ProjectedAllowance = IDL.Record({\n 'bytes_used_after_operation': IDL.Nat64,\n 'byte_limit': IDL.Nat64,\n 'bytes_used_after_upload': IDL.Nat64,\n 'bytes_used': IDL.Nat64,\n });\n const FileId = IDL.Nat;\n const AllocatedBucketSuccessResult = IDL.Record({\n 'byte_limit': IDL.Nat64,\n 'canister_id': CanisterId,\n 'bytes_used_after_upload': IDL.Nat64,\n 'bytes_used': IDL.Nat64,\n 'projected_allowance': ProjectedAllowance,\n 'chunk_size': IDL.Nat32,\n 'file_id': FileId,\n });\n const AllocatedBucketResponse = IDL.Variant({\n 'Success': AllocatedBucketSuccessResult,\n 'AllowanceExceeded': ProjectedAllowance,\n 'UserNotFound': IDL.Null,\n 'BucketUnavailable': IDL.Null,\n });\n const CanForwardArgs = IDL.Record({\n 'file_hash': Hash,\n 'file_size': IDL.Nat64,\n });\n const CanForwardResponse = IDL.Variant({\n 'Success': ProjectedAllowance,\n 'AllowanceExceeded': ProjectedAllowance,\n 'UserNotFound': IDL.Null,\n });\n const UserArgs = IDL.Record({});\n const UserRecord = IDL.Record({\n 'byte_limit': IDL.Nat64,\n 'bytes_used': IDL.Nat64,\n });\n const UserResponse = IDL.Variant({\n 'Success': UserRecord,\n 'UserNotFound': IDL.Null,\n });\n return IDL.Service({\n 'allocated_bucket_v2': IDL.Func([AllocatedBucketArgs], [AllocatedBucketResponse], ['query']),\n 'can_forward': IDL.Func([CanForwardArgs], [CanForwardResponse], ['query']),\n 'user': IDL.Func([UserArgs], [UserResponse], ['query']),\n });\n};\nexport const init = ({ IDL }) => { return []; };\n","import { Actor, HttpAgent, } from \"@dfinity/agent\";\nimport { toCanisterResponseError } from \"../error\";\nimport { CanisterAgent } from \"./base\";\nexport class CandidCanisterAgent extends CanisterAgent {\n constructor(identity, agent, canisterId, factory, canisterName) {\n super(identity, agent, canisterId, canisterName);\n this.service = Actor.createActor(factory, {\n agent,\n canisterId,\n });\n }\n handleQueryResponse(serviceCall, mapper, args) {\n return this.executeQuery(() => serviceCall(), mapper, args, 0);\n }\n handleResponse(service, mapper, args) {\n return service.then(mapper).catch((err) => {\n console.log(err, args);\n throw toCanisterResponseError(err, this.identity);\n });\n }\n}\n","import { UnsupportedValueError } from \"openchat-shared\";\nexport function allocatedBucketResponse(candid) {\n if (\"Success\" in candid) {\n return {\n kind: \"success\",\n canisterId: candid.Success.canister_id,\n fileId: candid.Success.file_id,\n chunkSize: candid.Success.chunk_size,\n projectedAllowance: projectedAllowance(candid.Success.projected_allowance),\n };\n }\n if (\"AllowanceExceeded\" in candid) {\n return allowanceExceeded(candid.AllowanceExceeded);\n }\n if (\"UserNotFound\" in candid) {\n return userNotFound();\n }\n if (\"BucketUnavailable\" in candid) {\n return {\n kind: \"bucket_unavailable\",\n };\n }\n throw new UnsupportedValueError(\"Unknown Index.CandidAllocatedBucketResponse type received\", candid);\n}\nexport function canForwardResponse(candid) {\n if (\"Success\" in candid) {\n return {\n kind: \"success\",\n projectedAllowance: projectedAllowance(candid.Success),\n };\n }\n if (\"AllowanceExceeded\" in candid) {\n return allowanceExceeded(candid.AllowanceExceeded);\n }\n if (\"UserNotFound\" in candid) {\n return userNotFound();\n }\n throw new UnsupportedValueError(\"Unknown Index.CandidCanForwardResponse type received\", candid);\n}\nexport function userResponse(candid) {\n if (\"Success\" in candid) {\n return {\n kind: \"user\",\n byteLimit: candid.Success.byte_limit,\n bytesUsed: candid.Success.bytes_used,\n };\n }\n if (\"UserNotFound\" in candid) {\n return userNotFound();\n }\n throw new UnsupportedValueError(\"Unknown Index.CandidUserResponse type received\", candid);\n}\nfunction allowanceExceeded(candid) {\n return {\n kind: \"allowance_exceeded\",\n projectedAllowance: projectedAllowance(candid)\n };\n}\nfunction userNotFound() {\n return { kind: \"user_not_found\" };\n}\nfunction projectedAllowance(candid) {\n return {\n byteLimit: candid.byte_limit,\n bytesUsed: candid.bytes_used,\n bytesUsedAfterOperation: candid.bytes_used_after_operation,\n };\n}\n","import { idlFactory } from \"./candid/idl\";\nimport { CandidCanisterAgent } from \"../canisterAgent/candid\";\nimport { allocatedBucketResponse, canForwardResponse, userResponse } from \"./mappers\";\nexport class StorageIndexClient extends CandidCanisterAgent {\n constructor(identity, agent, canisterId) {\n super(identity, agent, canisterId, idlFactory, \"StorageIndex\");\n }\n user() {\n return this.handleQueryResponse(() => this.service.user({}), userResponse);\n }\n allocatedBucket(fileHash, fileSize, fileIdSeed) {\n return this.handleQueryResponse(() => this.service.allocated_bucket_v2({\n file_hash: fileHash,\n file_size: fileSize,\n file_id_seed: fileIdSeed === undefined ? [] : [fileIdSeed],\n }), allocatedBucketResponse);\n }\n canForward(fileHash, fileSize) {\n return this.handleResponse(this.service.can_forward({ file_hash: fileHash, file_size: fileSize }), canForwardResponse);\n }\n}\n","export const idlFactory = ({ IDL }) => {\n const FileId = IDL.Nat;\n const DeleteFileArgs = IDL.Record({ 'file_id': FileId });\n const DeleteFileResponse = IDL.Variant({\n 'NotFound': IDL.Null,\n 'NotAuthorized': IDL.Null,\n 'Success': IDL.Null,\n });\n const DeleteFilesArgs = IDL.Record({ 'file_ids': IDL.Vec(FileId) });\n const DeleteFileFailureReason = IDL.Variant({\n 'NotFound': IDL.Null,\n 'NotAuthorized': IDL.Null,\n });\n const DeleteFileFailure = IDL.Record({\n 'reason': DeleteFileFailureReason,\n 'file_id': FileId,\n });\n const DeleteFilesResponse = IDL.Record({\n 'failures': IDL.Vec(DeleteFileFailure),\n 'success': IDL.Vec(FileId),\n });\n const FileInfoArgs = IDL.Record({ 'file_id': FileId });\n const Hash = IDL.Vec(IDL.Nat8);\n const FileInfoSuccessResult = IDL.Record({\n 'is_owner': IDL.Bool,\n 'file_hash': Hash,\n 'file_size': IDL.Nat64,\n });\n const FileInfoResponse = IDL.Variant({\n 'NotFound': IDL.Null,\n 'Success': FileInfoSuccessResult,\n });\n const AccessorId = IDL.Principal;\n const ForwardFileArgs = IDL.Record({\n 'accessors': IDL.Vec(AccessorId),\n 'file_id': FileId,\n });\n const ForwardFileResponse = IDL.Variant({\n 'NotFound': IDL.Null,\n 'NotAuthorized': IDL.Null,\n 'Success': FileId,\n });\n const TimestampMillis = IDL.Nat64;\n const UploadChunkArgs = IDL.Record({\n 'accessors': IDL.Vec(AccessorId),\n 'chunk_index': IDL.Nat32,\n 'hash': Hash,\n 'mime_type': IDL.Text,\n 'total_size': IDL.Nat64,\n 'bytes': IDL.Vec(IDL.Nat8),\n 'expiry': IDL.Opt(TimestampMillis),\n 'chunk_size': IDL.Nat32,\n 'file_id': FileId,\n });\n const UploadChunkResponse = IDL.Variant({\n 'ChunkAlreadyExists': IDL.Null,\n 'Full': IDL.Null,\n 'ChunkSizeMismatch': IDL.Null,\n 'FileTooBig': IDL.Null,\n 'ChunkIndexTooHigh': IDL.Null,\n 'Success': IDL.Null,\n 'FileExpired': IDL.Null,\n 'HashMismatch': IDL.Null,\n 'FileAlreadyExists': IDL.Null,\n 'AllowanceExceeded': IDL.Null,\n 'InvalidFileId': IDL.Null,\n 'UserNotFound': IDL.Null,\n });\n return IDL.Service({\n 'delete_file': IDL.Func([DeleteFileArgs], [DeleteFileResponse], []),\n 'delete_files': IDL.Func([DeleteFilesArgs], [DeleteFilesResponse], []),\n 'file_info': IDL.Func([FileInfoArgs], [FileInfoResponse], ['query']),\n 'forward_file': IDL.Func([ForwardFileArgs], [ForwardFileResponse], []),\n 'upload_chunk_v2': IDL.Func([UploadChunkArgs], [UploadChunkResponse], []),\n });\n};\nexport const init = ({ IDL }) => { return []; };\n","import { UnsupportedValueError } from \"openchat-shared\";\nexport function uploadChunkResponse(candid) {\n if (\"Success\" in candid) {\n return \"success\";\n }\n if (\"FileAlreadyExists\" in candid) {\n return \"file_already_exists\";\n }\n if (\"FileTooBig\" in candid) {\n return \"file_too_big\";\n }\n if (\"FileExpired\" in candid) {\n return \"file_expired\";\n }\n if (\"ChunkAlreadyExists\" in candid) {\n return \"chunk_already_exists\";\n }\n if (\"ChunkSizeMismatch\" in candid) {\n return \"chunk_size_mismatch\";\n }\n if (\"ChunkIndexTooHigh\" in candid) {\n return \"chunk_index_too_high\";\n }\n if (\"AllowanceExceeded\" in candid) {\n return \"allowance_exceeded\";\n }\n if (\"UserNotFound\" in candid) {\n return \"user_not_found\";\n }\n if (\"HashMismatch\" in candid) {\n return \"hash_mismatch\";\n }\n if (\"InvalidFileId\" in candid) {\n return \"invalid_file_id\";\n }\n if (\"Full\" in candid) {\n return \"full\";\n }\n throw new UnsupportedValueError(\"Unknown Bucket.CandidUploadChunkResponse type received\", candid);\n}\nexport function forwardFileResponse(candid) {\n if (\"Success\" in candid) {\n return {\n kind: \"success\",\n newFileId: candid.Success,\n };\n }\n if (\"NotAuthorized\" in candid) {\n return { kind: \"not_authorized\" };\n }\n if (\"NotFound\" in candid) {\n return { kind: \"file_not_found\" };\n }\n throw new UnsupportedValueError(\"Unknown Bucket.CandidForwardFileResponse type received\", candid);\n}\nexport function deleteFileResponse(candid) {\n if (\"Success\" in candid) {\n return \"success\";\n }\n if (\"NotAuthorized\" in candid) {\n return \"not_authorized\";\n }\n if (\"NotFound\" in candid) {\n return \"file_not_found\";\n }\n throw new UnsupportedValueError(\"Unknown Bucket.CandidDeleteFileResponse type received\", candid);\n}\nexport function fileInfoResponse(candid) {\n if (\"Success\" in candid) {\n return {\n kind: \"success\",\n isOwner: candid.Success.is_owner,\n fileSize: candid.Success.file_size,\n fileHash: Array.isArray(candid.Success.file_hash)\n ? new Uint8Array(candid.Success.file_hash)\n : candid.Success.file_hash,\n };\n }\n if (\"NotFound\" in candid) {\n return { kind: \"file_not_found\" };\n }\n throw new UnsupportedValueError(\"Unknown Bucket.CandidFileInfoResponse type received\", candid);\n}\n","import { idlFactory } from \"./candid/idl\";\nimport { CandidCanisterAgent } from \"../canisterAgent/candid\";\nimport { deleteFileResponse, fileInfoResponse, forwardFileResponse, uploadChunkResponse, } from \"./mappers\";\nexport class StorageBucketClient extends CandidCanisterAgent {\n constructor(identity, agent, canisterId) {\n super(identity, agent, canisterId, idlFactory, \"StorageBucket\");\n }\n uploadChunk(fileId, hash, mimeType, accessors, totalSize, chunkSize, chunkIndex, bytes, expiryTimestampMillis) {\n return this.handleResponse(this.service.upload_chunk_v2({\n accessors,\n chunk_index: chunkIndex,\n file_id: fileId,\n hash,\n mime_type: mimeType,\n total_size: totalSize,\n bytes,\n chunk_size: chunkSize,\n expiry: expiryTimestampMillis !== undefined ? [expiryTimestampMillis] : [],\n }), uploadChunkResponse);\n }\n forwardFile(fileId, accessors) {\n return this.handleResponse(this.service.forward_file({ file_id: fileId, accessors }), forwardFileResponse);\n }\n deleteFile(fileId) {\n return this.handleResponse(this.service.delete_file({ file_id: fileId }), deleteFileResponse);\n }\n fileInfo(fileId) {\n return this.handleResponse(this.service.file_info({ file_id: fileId }), fileInfoResponse);\n }\n}\n","import { Principal } from \"@dfinity/principal\";\nimport { sha3_256 } from \"js-sha3\";\nimport { buildBlobUrl } from \"../../utils/chat\";\nimport { random128, StorageUpdated } from \"openchat-shared\";\nimport { StorageIndexClient } from \"../storageIndex/storageIndex.client\";\nimport { StorageBucketClient } from \"../storageBucket/storageBucket.client\";\nexport class DataClient extends EventTarget {\n constructor(identity, agent, config) {\n super();\n this.identity = identity;\n this.agent = agent;\n this.config = config;\n this.storageIndexClient = new StorageIndexClient(identity, agent, config.openStorageIndexCanister);\n }\n static newBlobId() {\n return random128();\n }\n storageStatus() {\n return this.storageIndexClient.user().then((resp) => {\n if (resp.kind === \"user\") {\n return {\n byteLimit: Number(resp.byteLimit),\n bytesUsed: Number(resp.bytesUsed),\n };\n }\n else {\n return {\n byteLimit: 0,\n bytesUsed: 0,\n };\n }\n });\n }\n async uploadData(content, accessorCanisterIds) {\n let byteLimit = undefined;\n let bytesUsed = undefined;\n let updatedContent = undefined;\n if (content.kind === \"file_content\" ||\n content.kind === \"image_content\" ||\n content.kind === \"audio_content\") {\n if (content.blobData && content.blobReference === undefined) {\n const accessorIds = accessorCanisterIds.map((c) => Principal.fromText(c));\n const response = await this.uploadFile(content.mimeType, accessorIds, content.blobData);\n const ref = this.extractBlobReference(response);\n updatedContent = {\n ...content,\n blobReference: ref,\n blobUrl: buildBlobUrl(this.config.blobUrlPattern, ref.canisterId, ref.blobId, \"blobs\"),\n };\n byteLimit = Number(response.projectedAllowance.byteLimit);\n bytesUsed = Number(response.projectedAllowance.bytesUsedAfterOperation);\n }\n }\n else if (content.kind === \"video_content\") {\n if (content.videoData.blobData &&\n content.imageData.blobData &&\n content.videoData.blobReference === undefined &&\n content.imageData.blobReference === undefined) {\n const accessorIds = accessorCanisterIds.map((c) => Principal.fromText(c));\n await Promise.all([\n this.uploadFile(content.mimeType, accessorIds, content.videoData.blobData),\n this.uploadFile(\"image/jpg\", accessorIds, content.imageData.blobData),\n ]).then(([video, image]) => {\n const videoRef = this.extractBlobReference(video);\n const imageRef = this.extractBlobReference(image);\n updatedContent = {\n ...content,\n videoData: {\n ...content.videoData,\n blobReference: videoRef,\n blobUrl: buildBlobUrl(this.config.blobUrlPattern, videoRef.canisterId, videoRef.blobId, \"blobs\"),\n },\n imageData: {\n ...content.imageData,\n blobReference: imageRef,\n blobUrl: buildBlobUrl(this.config.blobUrlPattern, imageRef.canisterId, imageRef.blobId, \"blobs\"),\n },\n };\n byteLimit = Number(video.projectedAllowance.byteLimit);\n bytesUsed = Number(video.projectedAllowance.bytesUsedAfterOperation +\n image.projectedAllowance.bytesUsedAfterOperation -\n image.projectedAllowance.bytesUsed);\n });\n }\n }\n if (bytesUsed !== undefined && byteLimit !== undefined) {\n this.dispatchEvent(new StorageUpdated({\n byteLimit,\n bytesUsed,\n }));\n }\n return updatedContent;\n }\n async forwardData(content, accessorCanisterIds) {\n let byteLimit = undefined;\n let bytesUsed = undefined;\n let updatedContent = undefined;\n let error = undefined;\n if (content.kind === \"file_content\" ||\n content.kind === \"image_content\" ||\n content.kind === \"audio_content\") {\n if (content.blobReference !== undefined) {\n const accessorIds = accessorCanisterIds.map((c) => Principal.fromText(c));\n const response = await this.forwardFile(content.blobReference.canisterId, content.blobReference.blobId, accessorIds);\n if (response.kind === \"success\") {\n byteLimit = Number(response.projectedAllowance.byteLimit);\n bytesUsed = Number(response.projectedAllowance.bytesUsedAfterOperation);\n updatedContent = {\n ...content,\n blobReference: {\n canisterId: content.blobReference.canisterId,\n blobId: response.newFileId,\n },\n blobUrl: buildBlobUrl(this.config.blobUrlPattern, content.blobReference.canisterId, content.blobReference.blobId, \"blobs\"),\n };\n }\n else {\n if (response.kind === \"allowance_exceeded\") {\n byteLimit = Number(response.projectedAllowance.byteLimit);\n bytesUsed = Number(response.projectedAllowance.bytesUsed);\n }\n error = response.kind;\n }\n }\n }\n else if (content.kind === \"video_content\") {\n if (content.videoData.blobReference !== undefined &&\n content.imageData.blobReference !== undefined) {\n const accessorIds = accessorCanisterIds.map((c) => Principal.fromText(c));\n const videoCanisterId = content.videoData.blobReference.canisterId;\n const imageCanisterId = content.imageData.blobReference.canisterId;\n await Promise.all([\n this.forwardFile(videoCanisterId, content.videoData.blobReference.blobId, accessorIds),\n this.forwardFile(imageCanisterId, content.imageData.blobReference.blobId, accessorIds),\n ]).then(([video, image]) => {\n if (video.kind === \"success\" && image.kind === \"success\") {\n byteLimit = Number(video.projectedAllowance.byteLimit);\n bytesUsed = Number(video.projectedAllowance.bytesUsedAfterOperation +\n image.projectedAllowance.bytesUsedAfterOperation -\n image.projectedAllowance.bytesUsed);\n updatedContent = {\n ...content,\n videoData: {\n ...content.videoData,\n blobReference: {\n canisterId: videoCanisterId,\n blobId: video.newFileId,\n },\n blobUrl: buildBlobUrl(this.config.blobUrlPattern, videoCanisterId, video.newFileId, \"blobs\"),\n },\n imageData: {\n ...content.imageData,\n blobReference: {\n canisterId: imageCanisterId,\n blobId: image.newFileId,\n },\n blobUrl: buildBlobUrl(this.config.blobUrlPattern, imageCanisterId, image.newFileId, \"blobs\"),\n },\n };\n }\n else if (video.kind === \"success\") {\n byteLimit = Number(video.projectedAllowance.byteLimit);\n bytesUsed = Number(video.projectedAllowance.bytesUsedAfterOperation);\n error = image.kind;\n }\n else {\n if (video.kind === \"allowance_exceeded\") {\n byteLimit = Number(video.projectedAllowance.byteLimit);\n bytesUsed = Number(video.projectedAllowance.bytesUsed);\n }\n error = video.kind;\n }\n });\n }\n }\n if (bytesUsed !== undefined && byteLimit !== undefined) {\n this.dispatchEvent(new StorageUpdated({\n byteLimit,\n bytesUsed,\n }));\n }\n if (error !== undefined) {\n throw new Error(\"Unable to forward file: \" + error);\n }\n return updatedContent;\n }\n extractBlobReference(response) {\n return {\n canisterId: response.canisterId.toString(),\n blobId: response.fileId,\n };\n }\n async uploadFile(mimeType, accessors, bytes, expiryTimestampMillis, onProgress) {\n const hash = new Uint8Array(hashBytes(bytes));\n const fileSize = bytes.byteLength;\n const allocatedBucketResponse = await this.storageIndexClient.allocatedBucket(hash, BigInt(fileSize), random128());\n if (allocatedBucketResponse.kind !== \"success\") {\n // TODO make this better!\n throw new Error(allocatedBucketResponse.kind);\n }\n const bucketCanisterId = allocatedBucketResponse.canisterId.toString();\n const fileId = allocatedBucketResponse.fileId;\n const chunkSize = allocatedBucketResponse.chunkSize;\n const chunkCount = Math.ceil(fileSize / chunkSize);\n const chunkIndexes = [...Array(chunkCount).keys()];\n const bucketClient = new StorageBucketClient(this.identity, this.agent, bucketCanisterId);\n let chunksCompleted = 0;\n const promises = chunkIndexes.map(async (chunkIndex) => {\n const start = chunkIndex * chunkSize;\n const end = Math.min(start + chunkSize, fileSize);\n const chunkBytes = new Uint8Array(bytes.slice(start, end));\n let attempt = 0;\n while (attempt++ < 5) {\n try {\n const chunkResponse = await bucketClient.uploadChunk(fileId, hash, mimeType, accessors, BigInt(fileSize), chunkSize, chunkIndex, chunkBytes, expiryTimestampMillis);\n if (chunkResponse === \"success\") {\n chunksCompleted++;\n onProgress?.((100 * chunksCompleted) / chunkCount);\n return;\n }\n }\n catch (e) {\n console.log(\"Error uploading chunk \" + chunkIndex, e);\n }\n }\n throw new Error(\"Failed to upload chunk\");\n });\n await Promise.all(promises);\n return {\n canisterId: bucketCanisterId,\n fileId,\n pathPrefix: \"/files/\",\n projectedAllowance: allocatedBucketResponse.projectedAllowance,\n };\n }\n async forwardFile(bucketCanisterId, fileId, accessors) {\n const bucketClient = new StorageBucketClient(this.identity, this.agent, bucketCanisterId);\n const fileInfoResponse = await bucketClient.fileInfo(fileId);\n if (fileInfoResponse.kind === \"file_not_found\") {\n return fileInfoResponse;\n }\n const canForwardResponse = await this.storageIndexClient.canForward(fileInfoResponse.fileHash, fileInfoResponse.fileSize);\n switch (canForwardResponse.kind) {\n case \"user_not_found\":\n case \"allowance_exceeded\":\n return canForwardResponse;\n }\n const forwardFileResponse = await bucketClient.forwardFile(fileId, accessors);\n switch (forwardFileResponse.kind) {\n case \"success\":\n return {\n kind: \"success\",\n newFileId: forwardFileResponse.newFileId,\n projectedAllowance: canForwardResponse.projectedAllowance,\n };\n case \"not_authorized\":\n case \"file_not_found\":\n return forwardFileResponse;\n }\n }\n}\nfunction hashBytes(bytes) {\n const hash = sha3_256.create();\n hash.update(bytes);\n return hash.arrayBuffer();\n}\n","const max32 = Math.pow(2, 32) - 1;\nexport function generateUint64() {\n const rand1 = Math.floor(Math.random() * max32);\n const rand2 = Math.floor(Math.random() * max32);\n return (BigInt(rand1) << BigInt(32)) + BigInt(rand2);\n}\n","import { MAX_EVENTS, ResponseTooLargeError, } from \"openchat-shared\";\nfunction mergeEventsResponse(a, b) {\n return {\n events: [...a.events, ...b.events],\n expiredEventRanges: [...a.expiredEventRanges, ...b.expiredEventRanges],\n expiredMessageRanges: [...a.expiredMessageRanges, ...b.expiredMessageRanges],\n latestEventIndex: Math.max(a.latestEventIndex ?? 0, b.latestEventIndex ?? 0),\n };\n}\nexport async function chunkedChatEventsFromBackend(eventsFn, [minIndex, maxIndex], startIndex, ascending) {\n const chunkSize = MAX_EVENTS / 5;\n let index = startIndex;\n let aggregatedResponse = {\n events: [],\n expiredEventRanges: [],\n expiredMessageRanges: [],\n latestEventIndex: undefined,\n };\n while (aggregatedResponse.events.length < MAX_EVENTS &&\n index >= minIndex &&\n index <= maxIndex) {\n try {\n const resp = await eventsFn(index, chunkSize);\n // if we get any failures we will need to bail otherwise things are going to get very messed up\n if (resp === \"events_failed\")\n return resp;\n aggregatedResponse = ascending\n ? mergeEventsResponse(aggregatedResponse, resp)\n : mergeEventsResponse(resp, aggregatedResponse);\n if (resp.events.length > 0) {\n index = ascending\n ? resp.events[resp.events.length - 1].index + 1\n : resp.events[0].index - 1;\n }\n }\n catch (err) {\n if (err instanceof ResponseTooLargeError) {\n // Possible that we still have a size problem. If so, just log the error and bail out\n // if we see this condition we will have to think again but I'd rather avoid the complexity if we don't need it\n console.error(\"Response size still too large with chunk size: \", chunkSize);\n }\n throw err;\n }\n }\n return aggregatedResponse;\n}\nexport async function chunkedChatEventsWindowFromBackend(eventsFn, eventsWindowFn, [minIndex, maxIndex], messageIndex) {\n const chunkSize = MAX_EVENTS / 5;\n let highIndex = messageIndex;\n let lowIndex = messageIndex;\n let aggregatedResponse = {\n events: [],\n expiredEventRanges: [],\n expiredMessageRanges: [],\n latestEventIndex: undefined,\n };\n while (aggregatedResponse.events.length < MAX_EVENTS &&\n (lowIndex >= minIndex || highIndex <= maxIndex)) {\n try {\n if (lowIndex === highIndex) {\n // these will be equal on the first iteration\n const resp = await eventsWindowFn(lowIndex, chunkSize);\n // if we get any failures we will need to bail otherwise things are going to get very messed up\n if (resp === \"events_failed\")\n return resp;\n aggregatedResponse = mergeEventsResponse(aggregatedResponse, resp);\n }\n else {\n // in this branch we want to concurrently expand the window in both directions and then merge in the results\n if (lowIndex >= minIndex) {\n const above = await eventsFn(lowIndex, false, chunkSize);\n if (above === \"events_failed\")\n return \"events_failed\";\n aggregatedResponse = mergeEventsResponse(above, aggregatedResponse);\n }\n if (highIndex <= maxIndex) {\n const below = await eventsFn(highIndex, true, chunkSize);\n if (below === \"events_failed\")\n return \"events_failed\";\n aggregatedResponse = mergeEventsResponse(aggregatedResponse, below);\n }\n }\n if (aggregatedResponse.events.length > 0) {\n lowIndex = aggregatedResponse.events[0].index - 1;\n highIndex =\n aggregatedResponse.events[aggregatedResponse.events.length - 1].index + 1;\n }\n }\n catch (err) {\n if (err instanceof ResponseTooLargeError) {\n // Possible that we still have a size problem. If so, just log the error and bail out\n // if we see this condition we will have to think again but I'd rather avoid the complexity if we don't need it\n console.error(\"Response size still too large with chunk size: \", chunkSize);\n }\n throw err;\n }\n }\n return aggregatedResponse;\n}\n","export function toggleNotificationsResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n else {\n console.warn(\"MuteNotification failed with: \", value);\n return \"failure\";\n }\n}\nexport function subscriptionExistsResponse(value) {\n return value === \"Yes\";\n}\n","import { MsgpackCanisterAgent } from \"../canisterAgent/msgpack\";\nimport { deleteMessageResponse, undeleteMessageResponse, getEventsResponse, getUpdatesResponse, initialStateResponse, searchDirectChatResponse, setAvatarResponse, setBioResponse, withdrawBtcResponse, withdrawCryptoResponse, sendMessageResponse, sendMessageWithTransferToChannelResponse, sendMessageWithTransferToGroupResponse, publicProfileResponse, pinChatResponse, archiveChatResponse, deletedMessageResponse, setMessageReminderResponse, createCommunityResponse, manageFavouritesResponse, leaveCommunityResponse, deleteCommunityResponse, tipMessageResponse, savedCryptoAccountsResponse, saveCryptoAccountResponse, reportMessageResponse, swapTokensResponse, tokenSwapStatusResponse, approveTransferResponse, apiExchangeArgs, chitEventsResponse, claimDailyChitResponse, apiWalletConfig, apiVerification, messageActivityFeedResponse, } from \"./mappersV2\";\nimport { getCachedEvents, getCachedEventsByIndex, getCachedEventsWindowByMessageIndex, mergeSuccessResponses, recordFailedMessage, removeFailedMessage, setCachedEvents, setCachedMessageFromSendResponse, } from \"../../utils/caching\";\nimport { apiCommunityPermissions, apiExternalBotPermissions, apiGroupPermissions, apiMessageContent, editMessageResponse, apiPendingCryptocurrencyWithdrawal, apiReplyContextArgs, addRemoveReactionResponse, createGroupResponse, leaveGroupResponse, deleteGroupResponse, apiChatIdentifier, acceptP2PSwapResponse, cancelP2PSwapResponse, joinVideoCallResponse, setPinNumberResponse, apiMaybeAccessGateConfig, updateBotResponse, generateApiKeyResponse, } from \"../common/chatMappersV2\";\nimport { DataClient } from \"../data/data.client\";\nimport { mapOptional, principalBytesToString, principalStringToBytes, toVoid, } from \"../../utils/mapping\";\nimport { generateUint64 } from \"../../utils/rng\";\nimport { toBigInt32, MAX_EVENTS, MAX_MESSAGES, MAX_MISSING, ResponseTooLargeError, } from \"openchat-shared\";\nimport { chunkedChatEventsFromBackend, chunkedChatEventsWindowFromBackend, } from \"../common/chunked\";\nimport { setChitInfoInCache } from \"../../utils/userCache\";\nimport { Empty as TEmpty, UserAcceptP2pSwapArgs, UserAcceptP2pSwapResponse, UserAddHotGroupExclusionsArgs, UserAddHotGroupExclusionsResponse, UserAddReactionArgs, UserAddReactionResponse, UserApproveTransferArgs, UserApproveTransferResponse, UserArchiveUnarchiveChatsArgs, UserArchiveUnarchiveChatsResponse, UserBioResponse, UserBlockUserArgs, UserBlockUserResponse, UserCancelMessageReminderArgs, UserCancelMessageReminderResponse, UserCancelP2pSwapArgs, UserCancelP2pSwapResponse, UserChatInList, UserChitEventsArgs, UserChitEventsResponse, UserClaimDailyChitResponse, UserConfigureWalletArgs, UserConfigureWalletResponse, UserCreateCommunityArgs, UserCreateCommunityResponse, UserCreateGroupArgs, UserCreateGroupResponse, UserDeleteCommunityArgs, UserDeleteCommunityResponse, UserDeleteDirectChatArgs, UserDeleteDirectChatResponse, UserDeletedMessageArgs, UserDeletedMessageResponse, UserDeleteGroupArgs, UserDeleteGroupResponse, UserDeleteMessagesArgs, UserDeleteMessagesResponse, UserEditMessageArgs, UserEditMessageResponse, UserEventsArgs, UserEventsByIndexArgs, UserEventsResponse, UserEventsWindowArgs, UserInitialStateResponse, UserJoinVideoCallArgs, UserJoinVideoCallResponse, UserLeaveCommunityArgs, UserLeaveCommunityResponse, UserLeaveGroupArgs, UserLeaveGroupResponse, UserLocalUserIndexResponse, UserManageFavouriteChatsArgs, UserManageFavouriteChatsResponse, UserMarkAchievementsSeenArgs, UserMarkAchievementsSeenResponse, UserMarkReadArgs, UserMarkReadChannelMessagesRead, UserMarkReadChatMessagesRead, UserMarkReadResponse, UserMuteNotificationsArgs, UserMuteNotificationsResponse, UserNamedAccount, UserPinChatArgs, UserPinChatResponse, UserPublicProfileResponse, UserRemoveReactionArgs, UserRemoveReactionResponse, UserReportMessageArgs, UserReportMessageResponse, UserSaveCryptoAccountResponse, UserSavedCryptoAccountsResponse, UserSearchMessagesArgs, UserSearchMessagesResponse, UserSendMessageArgs, UserSendMessageResponse, UserSendMessageWithTransferToChannelArgs, UserSendMessageWithTransferToChannelResponse, UserSendMessageWithTransferToGroupArgs, UserSendMessageWithTransferToGroupResponse, UserSetAvatarArgs, UserSetAvatarResponse, UserSetBioArgs, UserSetBioResponse, UserSetCommunityIndexesArgs, UserSetCommunityIndexesResponse, UserSetMessageReminderArgs, UserSetMessageReminderResponse, UserSetPinNumberArgs, UserSetPinNumberResponse, UserSwapTokensArgs, UserSwapTokensResponse, UserTipMessageArgs, UserTipMessageResponse, UserTokenSwapStatusArgs, UserTokenSwapStatusResponse, UserUnblockUserArgs, UserUnblockUserResponse, UserUndeleteMessagesArgs, UserUndeleteMessagesResponse, UserUnpinChatArgs, UserUnpinChatResponse, UserUpdateBtcBalanceResponse, UserUpdatesArgs, UserUpdatesResponse, UserWithdrawCryptoArgs, UserWithdrawCryptoResponse, UserMarkMessageActivityFeedReadArgs, UserMarkMessageActivityFeedReadResponse, UserMessageActivityFeedArgs, UserMessageActivityFeedResponse, UserUpdateBotArgs, UserUpdateBotResponse, UserGenerateBotApiKeyArgs, UserGenerateBotApiKeyResponse, UserGenerateBtcAddressResponse, UserApiKeyArgs, UserApiKeyResponse, UserWithdrawBtcArgs, UserWithdrawBtcResponse, } from \"../../typebox\";\nimport { toggleNotificationsResponse } from \"../notifications/mappers\";\nexport class UserClient extends MsgpackCanisterAgent {\n constructor(userId, identity, agent, config, db) {\n super(identity, agent, userId, \"User\");\n this.config = config;\n this.db = db;\n this.userId = userId;\n this.chatId = { kind: \"direct_chat\", userId: userId };\n }\n setCachedEvents(chatId, resp, threadRootMessageIndex) {\n setCachedEvents(this.db, chatId, resp, threadRootMessageIndex).catch((err) => this.config.logger.error(\"Error writing cached group events\", err));\n return resp;\n }\n handleMissingEvents(chatId, [cachedEvents, missing], threadRootMessageIndex, latestKnownUpdate) {\n if (missing.size === 0) {\n return Promise.resolve(cachedEvents);\n }\n else {\n return this.chatEventsByIndexFromBackend([...missing], chatId, threadRootMessageIndex, latestKnownUpdate)\n .then((resp) => this.setCachedEvents(chatId, resp, threadRootMessageIndex))\n .then((resp) => {\n if (resp !== \"events_failed\") {\n return mergeSuccessResponses(cachedEvents, resp);\n }\n return resp;\n });\n }\n }\n manageFavouriteChats(toAdd, toRemove) {\n return this.executeMsgpackUpdate(\"manage_favourite_chats\", {\n to_add: toAdd.map(apiChatIdentifier),\n to_remove: toRemove.map(apiChatIdentifier),\n }, manageFavouritesResponse, UserManageFavouriteChatsArgs, UserManageFavouriteChatsResponse);\n }\n getInitialState() {\n return this.executeMsgpackQuery(\"initial_state\", {}, initialStateResponse, TEmpty, UserInitialStateResponse);\n }\n getUpdates(updatesSince) {\n const args = {\n updates_since: updatesSince,\n };\n return this.executeMsgpackQuery(\"updates\", args, getUpdatesResponse, UserUpdatesArgs, UserUpdatesResponse);\n }\n createCommunity(community, rules, defaultChannels, defaultChannelRules) {\n return this.executeMsgpackUpdate(\"create_community\", {\n is_public: community.public,\n name: community.name,\n description: community.description,\n history_visible_to_new_joiners: community.historyVisible,\n avatar: mapOptional(community.avatar?.blobData, (data) => {\n return {\n id: DataClient.newBlobId(),\n data,\n mime_type: \"image/jpg\",\n };\n }),\n banner: mapOptional(community.banner?.blobData, (data) => {\n return {\n id: DataClient.newBlobId(),\n data,\n mime_type: \"image/jpg\",\n };\n }),\n permissions: apiCommunityPermissions(community.permissions),\n rules,\n gate_config: apiMaybeAccessGateConfig(community.gateConfig),\n default_channels: defaultChannels,\n default_channel_rules: defaultChannelRules,\n primary_language: community.primaryLanguage,\n }, createCommunityResponse, UserCreateCommunityArgs, UserCreateCommunityResponse);\n }\n createGroup(group) {\n return this.executeMsgpackUpdate(\"create_group\", {\n is_public: group.public,\n name: group.name,\n description: group.description,\n history_visible_to_new_joiners: group.historyVisible,\n avatar: mapOptional(group.avatar?.blobData, (data) => {\n return {\n id: DataClient.newBlobId(),\n data,\n mime_type: \"image/jpg\",\n };\n }),\n permissions_v2: apiGroupPermissions(group.permissions),\n rules: group.rules,\n gate_config: apiMaybeAccessGateConfig(group.gateConfig),\n events_ttl: group.eventsTTL,\n messages_visible_to_non_members: group.messagesVisibleToNonMembers,\n }, (resp) => createGroupResponse(resp, group.id), UserCreateGroupArgs, UserCreateGroupResponse);\n }\n deleteGroup(chatId) {\n return this.executeMsgpackUpdate(\"delete_group\", {\n chat_id: principalStringToBytes(chatId),\n }, deleteGroupResponse, UserDeleteGroupArgs, UserDeleteGroupResponse);\n }\n deleteCommunity(id) {\n return this.executeMsgpackUpdate(\"delete_community\", {\n community_id: principalStringToBytes(id.communityId),\n }, deleteCommunityResponse, UserDeleteCommunityArgs, UserDeleteCommunityResponse);\n }\n getCachedEventsByIndex(eventIndexes, chatId, threadRootMessageIndex) {\n return getCachedEventsByIndex(this.db, eventIndexes, {\n chatId,\n threadRootMessageIndex,\n });\n }\n chatEventsByIndex(eventIndexes, chatId, threadRootMessageIndex, latestKnownUpdate) {\n return this.getCachedEventsByIndex(eventIndexes, chatId, threadRootMessageIndex).then((res) => this.handleMissingEvents(chatId, res, threadRootMessageIndex, latestKnownUpdate));\n }\n chatEventsByIndexFromBackend(eventIndexes, chatId, threadRootMessageIndex, latestKnownUpdate) {\n const args = {\n thread_root_message_index: threadRootMessageIndex,\n user_id: principalStringToBytes(chatId.userId),\n events: eventIndexes,\n latest_known_update: latestKnownUpdate,\n latest_client_event_index: undefined,\n };\n return this.executeMsgpackQuery(\"events_by_index\", args, (resp) => getEventsResponse(this.principal, resp, chatId, latestKnownUpdate), UserEventsByIndexArgs, UserEventsResponse);\n }\n async chatEventsWindow(eventIndexRange, chatId, messageIndex, latestKnownUpdate) {\n const [cachedEvents, missing, totalMiss] = await getCachedEventsWindowByMessageIndex(this.db, eventIndexRange, { chatId }, messageIndex);\n if (totalMiss || missing.size >= MAX_MISSING) {\n // if we have exceeded the maximum number of missing events, let's just consider it a complete miss and go to the api\n console.log(\"We didn't get enough back from the cache, going to the api\", missing.size, totalMiss);\n return this.chatEventsWindowFromBackend(chatId, messageIndex, latestKnownUpdate)\n .then((resp) => this.setCachedEvents(chatId, resp))\n .catch((err) => {\n if (err instanceof ResponseTooLargeError) {\n console.log(\"Response size too large, we will try to split the window request into a a few chunks\");\n return chunkedChatEventsWindowFromBackend((index, ascending, chunkSize) => this.chatEventsFromBackend(chatId, index, ascending, undefined, latestKnownUpdate, chunkSize), (index, chunkSize) => this.chatEventsWindowFromBackend(chatId, index, latestKnownUpdate, chunkSize), eventIndexRange, messageIndex).then((resp) => this.setCachedEvents(chatId, resp));\n }\n else {\n throw err;\n }\n });\n }\n else {\n return this.handleMissingEvents(chatId, [cachedEvents, missing], undefined, latestKnownUpdate);\n }\n }\n async chatEventsWindowFromBackend(chatId, messageIndex, latestKnownUpdate, maxEvents = MAX_EVENTS) {\n const args = {\n thread_root_message_index: undefined,\n user_id: principalStringToBytes(chatId.userId),\n max_messages: MAX_MESSAGES,\n max_events: maxEvents,\n mid_point: messageIndex,\n latest_known_update: latestKnownUpdate,\n };\n return this.executeMsgpackQuery(\"events_window\", args, (resp) => getEventsResponse(this.principal, resp, chatId, latestKnownUpdate), UserEventsWindowArgs, UserEventsResponse);\n }\n async chatEvents(eventIndexRange, chatId, startIndex, ascending, threadRootMessageIndex, latestKnownUpdate) {\n const [cachedEvents, missing] = await getCachedEvents(this.db, eventIndexRange, { chatId, threadRootMessageIndex }, startIndex, ascending);\n // we may or may not have all of the requested events\n if (missing.size >= MAX_MISSING) {\n // if we have exceeded the maximum number of missing events, let's just consider it a complete miss and go to the api\n console.log(\"We didn't get enough back from the cache, going to the api\");\n return this.chatEventsFromBackend(chatId, startIndex, ascending, threadRootMessageIndex, latestKnownUpdate)\n .then((resp) => this.setCachedEvents(chatId, resp, threadRootMessageIndex))\n .catch((err) => {\n if (err instanceof ResponseTooLargeError) {\n console.log(\"Response size too large, we will try to split the payload into a a few chunks\");\n return chunkedChatEventsFromBackend((index, chunkSize) => this.chatEventsFromBackend(chatId, index, ascending, threadRootMessageIndex, latestKnownUpdate, chunkSize), eventIndexRange, startIndex, ascending).then((resp) => this.setCachedEvents(chatId, resp, threadRootMessageIndex));\n }\n else {\n throw err;\n }\n });\n }\n else {\n return this.handleMissingEvents(chatId, [cachedEvents, missing], threadRootMessageIndex, latestKnownUpdate);\n }\n }\n chatEventsFromBackend(chatId, startIndex, ascending, threadRootMessageIndex, latestKnownUpdate, maxEvents = MAX_EVENTS) {\n const args = {\n thread_root_message_index: threadRootMessageIndex,\n user_id: principalStringToBytes(chatId.userId),\n max_messages: MAX_MESSAGES,\n max_events: maxEvents,\n start_index: startIndex,\n ascending: ascending,\n latest_known_update: latestKnownUpdate,\n latest_client_event_index: undefined,\n };\n return this.executeMsgpackQuery(\"events\", args, (resp) => getEventsResponse(this.principal, resp, chatId, latestKnownUpdate), UserEventsArgs, UserEventsResponse);\n }\n setAvatar(bytes) {\n const blobId = DataClient.newBlobId();\n return this.executeMsgpackUpdate(\"set_avatar\", {\n avatar: {\n id: blobId,\n data: bytes,\n mime_type: \"image/jpg\",\n },\n }, setAvatarResponse, UserSetAvatarArgs, UserSetAvatarResponse).then((resp) => {\n if (resp === \"success\") {\n return {\n blobId,\n canisterId: this.userId,\n };\n }\n throw new Error(\"Unable to set avatar\");\n });\n }\n editMessage(recipientId, message, threadRootMessageIndex, blockLevelMarkdown) {\n return new DataClient(this.identity, this.agent, this.config)\n .uploadData(message.content, [this.userId, recipientId])\n .then((content) => {\n const req = {\n content: apiMessageContent(content ?? message.content),\n user_id: principalStringToBytes(recipientId),\n thread_root_message_index: threadRootMessageIndex,\n message_id: message.messageId,\n correlation_id: generateUint64(),\n block_level_markdown: blockLevelMarkdown,\n };\n return this.executeMsgpackUpdate(\"edit_message_v2\", req, editMessageResponse, UserEditMessageArgs, UserEditMessageResponse);\n });\n }\n sendMessage(chatId, event, messageFilterFailed, threadRootMessageIndex, pin, onRequestAccepted) {\n removeFailedMessage(this.db, this.chatId, event.event.messageId, threadRootMessageIndex);\n const dataClient = new DataClient(this.identity, this.agent, this.config);\n const uploadContentPromise = event.event.forwarded\n ? dataClient.forwardData(event.event.content, [this.userId, chatId.userId])\n : dataClient.uploadData(event.event.content, [this.userId, chatId.userId]);\n return uploadContentPromise.then((content) => {\n const newEvent = content !== undefined ? { ...event, event: { ...event.event, content } } : event;\n const req = {\n content: apiMessageContent(newEvent.event.content),\n recipient: principalStringToBytes(chatId.userId),\n message_id: newEvent.event.messageId,\n replies_to: mapOptional(newEvent.event.repliesTo, (replyContext) => apiReplyContextArgs(chatId, replyContext)),\n forwarding: newEvent.event.forwarded,\n thread_root_message_index: threadRootMessageIndex,\n message_filter_failed: messageFilterFailed,\n pin,\n correlation_id: generateUint64(),\n block_level_markdown: newEvent.event.blockLevelMarkdown,\n };\n return this.executeMsgpackUpdate(\"send_message_v2\", req, (resp) => sendMessageResponse(resp, newEvent.event.sender, chatId.userId), UserSendMessageArgs, UserSendMessageResponse, onRequestAccepted)\n .then((resp) => {\n const retVal = [resp, newEvent.event];\n setCachedMessageFromSendResponse(this.db, chatId, newEvent, threadRootMessageIndex)(retVal);\n return retVal;\n })\n .catch((err) => {\n recordFailedMessage(this.db, chatId, newEvent, threadRootMessageIndex);\n throw err;\n });\n });\n }\n sendMessageWithTransferToGroup(groupId, recipientId, sender, event, threadRootMessageIndex, rulesAccepted, messageFilterFailed, pin) {\n removeFailedMessage(this.db, this.chatId, event.event.messageId, threadRootMessageIndex);\n return this.sendMessageWithTransferToGroupToBackend(groupId, recipientId, sender, event, threadRootMessageIndex, rulesAccepted, messageFilterFailed, pin)\n .then(setCachedMessageFromSendResponse(this.db, groupId, event, threadRootMessageIndex))\n .catch((err) => {\n recordFailedMessage(this.db, groupId, event);\n throw err;\n });\n }\n sendMessageWithTransferToGroupToBackend(groupId, recipientId, sender, event, threadRootMessageIndex, rulesAccepted, messageFilterFailed, pin) {\n const content = apiMessageContent(event.event.content);\n const req = {\n thread_root_message_index: threadRootMessageIndex,\n content,\n sender_name: sender.username,\n sender_display_name: sender.displayName,\n rules_accepted: rulesAccepted,\n mentioned: [],\n message_id: event.event.messageId,\n group_id: principalStringToBytes(groupId.groupId),\n replies_to: mapOptional(event.event.repliesTo, (replyContext) => apiReplyContextArgs(groupId, replyContext)),\n block_level_markdown: true,\n message_filter_failed: messageFilterFailed,\n pin,\n correlation_id: generateUint64(),\n };\n return this.executeMsgpackUpdate(\"send_message_with_transfer_to_group\", req, (resp) => sendMessageWithTransferToGroupResponse(resp, event.event.sender, recipientId), UserSendMessageWithTransferToGroupArgs, UserSendMessageWithTransferToGroupResponse).then((resp) => [resp, event.event]);\n }\n loadSavedCryptoAccounts() {\n return this.executeMsgpackQuery(\"saved_crypto_accounts\", {}, savedCryptoAccountsResponse, TEmpty, UserSavedCryptoAccountsResponse);\n }\n saveCryptoAccount({ name, account }) {\n return this.executeMsgpackUpdate(\"save_crypto_account\", {\n name,\n account,\n }, saveCryptoAccountResponse, UserNamedAccount, UserSaveCryptoAccountResponse);\n }\n sendMessageWithTransferToChannel(id, recipientId, sender, event, threadRootMessageIndex, communityRulesAccepted, channelRulesAccepted, messageFilterFailed, pin) {\n removeFailedMessage(this.db, this.chatId, event.event.messageId, threadRootMessageIndex);\n return this.sendMessageWithTransferToChannelToBackend(id, recipientId, sender, event, threadRootMessageIndex, communityRulesAccepted, channelRulesAccepted, messageFilterFailed, pin)\n .then(setCachedMessageFromSendResponse(this.db, id, event, threadRootMessageIndex))\n .catch((err) => {\n recordFailedMessage(this.db, id, event);\n throw err;\n });\n }\n sendMessageWithTransferToChannelToBackend(id, recipientId, sender, event, threadRootMessageIndex, communityRulesAccepted, channelRulesAccepted, messageFilterFailed, pin) {\n const content = apiMessageContent(event.event.content);\n const req = {\n thread_root_message_index: threadRootMessageIndex,\n content,\n sender_name: sender.username,\n sender_display_name: sender.displayName,\n mentioned: [],\n message_id: event.event.messageId,\n community_id: principalStringToBytes(id.communityId),\n channel_id: toBigInt32(id.channelId),\n replies_to: mapOptional(event.event.repliesTo, (replyContext) => apiReplyContextArgs(id, replyContext)),\n block_level_markdown: true,\n community_rules_accepted: communityRulesAccepted,\n channel_rules_accepted: channelRulesAccepted,\n message_filter_failed: messageFilterFailed,\n pin,\n };\n return this.executeMsgpackUpdate(\"send_message_with_transfer_to_channel\", req, (resp) => sendMessageWithTransferToChannelResponse(resp, event.event.sender, recipientId), UserSendMessageWithTransferToChannelArgs, UserSendMessageWithTransferToChannelResponse).then((resp) => [resp, event.event]);\n }\n blockUser(userId) {\n return this.executeMsgpackUpdate(\"block_user\", {\n user_id: principalStringToBytes(userId),\n }, (_) => \"success\", UserBlockUserArgs, UserBlockUserResponse);\n }\n unblockUser(userId) {\n return this.executeMsgpackUpdate(\"unblock_user\", {\n user_id: principalStringToBytes(userId),\n }, (_) => \"success\", UserUnblockUserArgs, UserUnblockUserResponse);\n }\n leaveGroup(chatId) {\n return this.executeMsgpackUpdate(\"leave_group\", {\n chat_id: principalStringToBytes(chatId),\n }, leaveGroupResponse, UserLeaveGroupArgs, UserLeaveGroupResponse);\n }\n leaveCommunity(id) {\n return this.executeMsgpackUpdate(\"leave_community\", {\n community_id: principalStringToBytes(id.communityId),\n }, leaveCommunityResponse, UserLeaveCommunityArgs, UserLeaveCommunityResponse);\n }\n markMessageArg(chatId, readUpTo, threads, dateReadPinned) {\n return {\n chat_id: principalStringToBytes(chatId),\n read_up_to: readUpTo,\n threads: threads.map((t) => ({\n root_message_index: t.threadRootMessageIndex,\n read_up_to: t.readUpTo,\n })),\n date_read_pinned: dateReadPinned,\n };\n }\n markChannelMessageArg(channelId, readUpTo, threads, dateReadPinned) {\n return {\n channel_id: toBigInt32(channelId),\n read_up_to: readUpTo,\n threads: threads.map((t) => ({\n root_message_index: t.threadRootMessageIndex,\n read_up_to: t.readUpTo,\n })),\n date_read_pinned: dateReadPinned,\n };\n }\n markMessageArgs(req) {\n const community = {};\n const chat = [];\n req.forEach(({ chatId, readUpTo, threads, dateReadPinned }) => {\n if (chatId.kind === \"direct_chat\") {\n chat.push(this.markMessageArg(chatId.userId, readUpTo, threads, dateReadPinned));\n }\n if (chatId.kind === \"group_chat\") {\n chat.push(this.markMessageArg(chatId.groupId, readUpTo, threads, dateReadPinned));\n }\n if (chatId.kind === \"channel\") {\n if (community[chatId.communityId] === undefined) {\n community[chatId.communityId] = [];\n }\n community[chatId.communityId].push(this.markChannelMessageArg(chatId.channelId, readUpTo, threads, dateReadPinned));\n }\n });\n return {\n messages_read: chat,\n community_messages_read: Object.entries(community).map(([communityId, read]) => ({\n community_id: principalStringToBytes(communityId),\n channels_read: read,\n })),\n };\n }\n markMessagesRead(request) {\n return this.executeMsgpackUpdate(\"mark_read\", this.markMessageArgs(request), (_) => \"success\", UserMarkReadArgs, UserMarkReadResponse);\n }\n tipMessage(messageContext, messageId, transfer, decimals, pin) {\n return this.executeMsgpackUpdate(\"tip_message\", {\n chat: apiChatIdentifier(messageContext.chatId),\n message_id: messageId,\n fee: transfer.feeE8s ?? 0n,\n decimals,\n token_symbol: transfer.token,\n recipient: principalStringToBytes(transfer.recipient),\n ledger: principalStringToBytes(transfer.ledger),\n amount: transfer.amountE8s,\n thread_root_message_index: messageContext.threadRootMessageIndex,\n pin,\n }, tipMessageResponse, UserTipMessageArgs, UserTipMessageResponse);\n }\n addReaction(otherUserId, messageId, reaction, threadRootMessageIndex) {\n return this.executeMsgpackUpdate(\"add_reaction\", {\n user_id: principalStringToBytes(otherUserId),\n thread_root_message_index: threadRootMessageIndex,\n message_id: messageId,\n reaction,\n correlation_id: generateUint64(),\n }, addRemoveReactionResponse, UserAddReactionArgs, UserAddReactionResponse);\n }\n removeReaction(otherUserId, messageId, reaction, threadRootMessageIndex) {\n return this.executeMsgpackUpdate(\"remove_reaction\", {\n user_id: principalStringToBytes(otherUserId),\n thread_root_message_index: threadRootMessageIndex,\n message_id: messageId,\n reaction,\n correlation_id: generateUint64(),\n }, addRemoveReactionResponse, UserRemoveReactionArgs, UserRemoveReactionResponse);\n }\n deleteMessage(otherUserId, messageId, threadRootMessageIndex) {\n return this.executeMsgpackUpdate(\"delete_messages\", {\n user_id: principalStringToBytes(otherUserId),\n thread_root_message_index: threadRootMessageIndex,\n message_ids: [messageId],\n correlation_id: generateUint64(),\n }, deleteMessageResponse, UserDeleteMessagesArgs, UserDeleteMessagesResponse);\n }\n undeleteMessage(otherUserId, messageId, threadRootMessageIndex) {\n return this.executeMsgpackUpdate(\"undelete_messages\", {\n user_id: principalStringToBytes(otherUserId),\n thread_root_message_index: threadRootMessageIndex,\n message_ids: [messageId],\n correlation_id: generateUint64(),\n }, undeleteMessageResponse, UserUndeleteMessagesArgs, UserUndeleteMessagesResponse);\n }\n searchDirectChat(chatId, searchTerm, maxResults) {\n const args = {\n user_id: principalStringToBytes(chatId.userId),\n search_term: searchTerm,\n max_results: maxResults,\n };\n return this.executeMsgpackQuery(\"search_messages\", args, (res) => searchDirectChatResponse(res, chatId), UserSearchMessagesArgs, UserSearchMessagesResponse);\n }\n toggleMuteNotifications(chatId, muted) {\n const args = {\n chat_id: principalStringToBytes(chatId),\n };\n return this.executeMsgpackUpdate(muted ? \"mute_notifications\" : \"unmute_notifications\", args, toggleNotificationsResponse, UserMuteNotificationsArgs, UserMuteNotificationsResponse);\n }\n dismissRecommendation(chatId) {\n return this.executeMsgpackUpdate(\"add_hot_group_exclusions\", {\n duration: undefined,\n groups: [principalStringToBytes(chatId)],\n }, toVoid, UserAddHotGroupExclusionsArgs, UserAddHotGroupExclusionsResponse);\n }\n getBio() {\n return this.executeMsgpackQuery(\"bio\", {}, (value) => value.Success, TEmpty, UserBioResponse);\n }\n getPublicProfile() {\n return this.executeMsgpackQuery(\"public_profile\", {}, publicProfileResponse, TEmpty, UserPublicProfileResponse);\n }\n setBio(bio) {\n return this.executeMsgpackUpdate(\"set_bio\", { text: bio }, setBioResponse, UserSetBioArgs, UserSetBioResponse);\n }\n withdrawCryptocurrency(domain, pin) {\n const req = apiPendingCryptocurrencyWithdrawal(domain, pin);\n return this.executeMsgpackUpdate(\"withdraw_crypto_v2\", req, withdrawCryptoResponse, UserWithdrawCryptoArgs, UserWithdrawCryptoResponse);\n }\n toChatInList(chatId, favourite) {\n if (favourite) {\n return {\n Favourite: apiChatIdentifier(chatId),\n };\n }\n else {\n switch (chatId.kind) {\n case \"group_chat\":\n return { Group: principalStringToBytes(chatId.groupId) };\n case \"direct_chat\":\n return { Direct: principalStringToBytes(chatId.userId) };\n case \"channel\":\n return {\n Community: [\n principalStringToBytes(chatId.communityId),\n toBigInt32(chatId.channelId),\n ],\n };\n }\n }\n }\n pinChat(chatId, favourite) {\n return this.executeMsgpackUpdate(\"pin_chat_v2\", {\n chat: this.toChatInList(chatId, favourite),\n }, pinChatResponse, UserPinChatArgs, UserPinChatResponse);\n }\n unpinChat(chatId, favourite) {\n return this.executeMsgpackUpdate(\"unpin_chat_v2\", {\n chat: this.toChatInList(chatId, favourite),\n }, pinChatResponse, UserUnpinChatArgs, UserUnpinChatResponse);\n }\n archiveChat(chatId) {\n return this.executeMsgpackUpdate(\"archive_unarchive_chats\", {\n to_archive: [apiChatIdentifier(chatId)],\n to_unarchive: [],\n }, archiveChatResponse, UserArchiveUnarchiveChatsArgs, UserArchiveUnarchiveChatsResponse);\n }\n unarchiveChat(chatId) {\n return this.executeMsgpackUpdate(\"archive_unarchive_chats\", {\n to_archive: [],\n to_unarchive: [apiChatIdentifier(chatId)],\n }, archiveChatResponse, UserArchiveUnarchiveChatsArgs, UserArchiveUnarchiveChatsResponse);\n }\n getDeletedMessage(userId, messageId) {\n return this.executeMsgpackQuery(\"deleted_message\", {\n user_id: principalStringToBytes(userId),\n message_id: messageId,\n }, deletedMessageResponse, UserDeletedMessageArgs, UserDeletedMessageResponse);\n }\n setMessageReminder(chatId, eventIndex, remindAt, notes, threadRootMessageIndex) {\n return this.executeMsgpackUpdate(\"set_message_reminder_v2\", {\n chat: apiChatIdentifier(chatId),\n notes,\n remind_at: BigInt(remindAt),\n thread_root_message_index: threadRootMessageIndex,\n event_index: eventIndex,\n }, setMessageReminderResponse, UserSetMessageReminderArgs, UserSetMessageReminderResponse);\n }\n cancelMessageReminder(reminderId) {\n return this.executeMsgpackUpdate(\"cancel_message_reminder\", {\n reminder_id: reminderId,\n }, (_) => true, UserCancelMessageReminderArgs, UserCancelMessageReminderResponse);\n }\n setCommunityIndexes(communityIndexes) {\n const indexes = Object.entries(communityIndexes).map(([id, idx]) => [principalStringToBytes(id), idx]);\n return this.executeMsgpackUpdate(\"set_community_indexes\", { indexes }, (_) => true, UserSetCommunityIndexesArgs, UserSetCommunityIndexesResponse);\n }\n reportMessage(chatId, threadRootMessageIndex, messageId, deleteMessage) {\n return this.executeMsgpackUpdate(\"report_message\", {\n them: principalStringToBytes(chatId.userId),\n message_id: messageId,\n delete: deleteMessage,\n thread_root_message_index: threadRootMessageIndex,\n }, reportMessageResponse, UserReportMessageArgs, UserReportMessageResponse);\n }\n swapTokens(swapId, inputToken, outputToken, amountIn, minAmountOut, exchangeArgs, pin) {\n return this.executeMsgpackUpdate(\"swap_tokens\", {\n swap_id: swapId,\n input_token: {\n symbol: inputToken.symbol,\n ledger: principalStringToBytes(inputToken.ledger),\n decimals: inputToken.decimals,\n fee: inputToken.transferFee,\n },\n output_token: {\n symbol: outputToken.symbol,\n ledger: principalStringToBytes(outputToken.ledger),\n decimals: outputToken.decimals,\n fee: outputToken.transferFee,\n },\n input_amount: amountIn,\n exchange_args: apiExchangeArgs(exchangeArgs),\n min_output_amount: minAmountOut,\n pin,\n }, swapTokensResponse, UserSwapTokensArgs, UserSwapTokensResponse);\n }\n tokenSwapStatus(swapId) {\n const args = {\n swap_id: swapId,\n };\n return this.executeMsgpackQuery(\"token_swap_status\", args, tokenSwapStatusResponse, UserTokenSwapStatusArgs, UserTokenSwapStatusResponse);\n }\n approveTransfer(spender, ledger, amount, expiresIn, pin) {\n return this.executeMsgpackUpdate(\"approve_transfer\", {\n spender: {\n owner: principalStringToBytes(spender),\n subaccount: undefined,\n },\n ledger_canister_id: principalStringToBytes(ledger),\n amount,\n expires_in: expiresIn,\n pin,\n }, approveTransferResponse, UserApproveTransferArgs, UserApproveTransferResponse);\n }\n deleteDirectChat(userId, blockUser) {\n return this.executeMsgpackUpdate(\"delete_direct_chat\", {\n user_id: principalStringToBytes(userId),\n block_user: blockUser,\n }, (resp) => resp === \"Success\", UserDeleteDirectChatArgs, UserDeleteDirectChatResponse);\n }\n acceptP2PSwap(userId, threadRootMessageIndex, messageId, pin) {\n return this.executeMsgpackUpdate(\"accept_p2p_swap\", {\n user_id: principalStringToBytes(userId),\n message_id: messageId,\n thread_root_message_index: threadRootMessageIndex,\n pin,\n }, acceptP2PSwapResponse, UserAcceptP2pSwapArgs, UserAcceptP2pSwapResponse);\n }\n cancelP2PSwap(userId, messageId) {\n return this.executeMsgpackUpdate(\"cancel_p2p_swap\", {\n user_id: principalStringToBytes(userId),\n message_id: messageId,\n }, cancelP2PSwapResponse, UserCancelP2pSwapArgs, UserCancelP2pSwapResponse);\n }\n joinVideoCall(userId, messageId) {\n return this.executeMsgpackUpdate(\"join_video_call\", {\n user_id: principalStringToBytes(userId),\n message_id: messageId,\n }, joinVideoCallResponse, UserJoinVideoCallArgs, UserJoinVideoCallResponse);\n }\n localUserIndex() {\n return this.executeMsgpackQuery(\"local_user_index\", {}, (resp) => principalBytesToString(resp.Success), TEmpty, UserLocalUserIndexResponse);\n }\n setPinNumber(verification, newPin) {\n return this.executeMsgpackUpdate(\"set_pin_number\", {\n verification: apiVerification(verification),\n new: newPin,\n }, setPinNumberResponse, UserSetPinNumberArgs, UserSetPinNumberResponse);\n }\n chitEvents({ from, to, max, ascending }) {\n return this.executeMsgpackQuery(\"chit_events\", {\n from,\n to,\n max,\n ascending,\n skip: undefined,\n }, chitEventsResponse, UserChitEventsArgs, UserChitEventsResponse);\n }\n markAchievementsSeen(lastSeen) {\n return this.executeMsgpackUpdate(\"mark_achievements_seen\", {\n last_seen: lastSeen,\n }, (res) => {\n console.log(\"Set Achievements Last seen\", lastSeen, res);\n }, UserMarkAchievementsSeenArgs, UserMarkAchievementsSeenResponse);\n }\n claimDailyChit() {\n return this.executeMsgpackUpdate(\"claim_daily_chit\", {}, claimDailyChitResponse, TEmpty, UserClaimDailyChitResponse).then((res) => {\n if (res.kind === \"success\") {\n // Note this only updates the users db, the chats db will be updated by the updates loop\n setChitInfoInCache(this.userId, res.chitBalance, res.streak);\n }\n return res;\n });\n }\n configureWallet(walletConfig) {\n return this.executeMsgpackUpdate(\"configure_wallet\", {\n config: apiWalletConfig(walletConfig),\n }, toVoid, UserConfigureWalletArgs, UserConfigureWalletResponse);\n }\n markActivityFeedRead(readUpTo) {\n return this.executeMsgpackUpdate(\"mark_message_activity_feed_read\", { read_up_to: readUpTo }, toVoid, UserMarkMessageActivityFeedReadArgs, UserMarkMessageActivityFeedReadResponse);\n }\n messageActivityFeed(since) {\n return this.executeMsgpackQuery(\"message_activity_feed\", { since }, messageActivityFeedResponse, UserMessageActivityFeedArgs, UserMessageActivityFeedResponse);\n }\n updateInstalledBot(botId, grantedPermissions) {\n return this.executeMsgpackUpdate(\"update_bot\", {\n bot_id: principalStringToBytes(botId),\n granted_permissions: apiExternalBotPermissions(grantedPermissions),\n }, updateBotResponse, UserUpdateBotArgs, UserUpdateBotResponse);\n }\n generateBotApiKey(botId, permissions) {\n return this.executeMsgpackUpdate(\"generate_bot_api_key\", {\n bot_id: principalStringToBytes(botId),\n requested_permissions: apiExternalBotPermissions(permissions),\n }, generateApiKeyResponse, UserGenerateBotApiKeyArgs, UserGenerateBotApiKeyResponse);\n }\n getApiKey(botId) {\n return this.executeMsgpackQuery(\"api_key\", {\n bot_id: principalStringToBytes(botId),\n }, (resp) => {\n if (typeof resp === \"object\" && \"Success\" in resp) {\n return resp.Success;\n }\n console.log(\"Failed to get direct api key: \", botId, resp);\n return undefined;\n }, UserApiKeyArgs, UserApiKeyResponse);\n }\n generateBtcAddress() {\n return this.executeMsgpackUpdate(\"generate_btc_address\", {}, (resp) => {\n if (\"Success\" in resp) {\n return resp.Success;\n }\n else {\n throw new Error(`Failed to generate btc address: ${resp}`);\n }\n }, TEmpty, UserGenerateBtcAddressResponse);\n }\n updateBtcBalance() {\n return this.executeMsgpackUpdate(\"update_btc_balance\", {}, (resp) => resp === \"Success\", TEmpty, UserUpdateBtcBalanceResponse);\n }\n withdrawBtc(address, amount, pin) {\n return this.executeMsgpackUpdate(\"withdraw_btc\", {\n address,\n amount,\n pin,\n }, withdrawBtcResponse, UserWithdrawBtcArgs, UserWithdrawBtcResponse);\n }\n}\n","export const E8S_PER_TOKEN = 100_000_000;\nexport const CHAT_SYMBOL = \"CHAT\";\nexport const ICP_SYMBOL = \"ICP\";\nexport const BTC_SYMBOL = \"BTC\";\nexport const CKBTC_SYMBOL = \"ckBTC\";\nexport const SNS1_SYMBOL = \"SNS1\";\nexport const KINIC_SYMBOL = \"KINIC\";\nexport const HOTORNOT_SYMBOL = \"HOT\";\nexport const GHOST_SYMBOL = \"GHOST\";\nexport const LEDGER_CANISTER_ICP = \"ryjl3-tyaaa-aaaaa-aaaba-cai\";\nexport const LEDGER_CANISTER_CHAT = \"2ouva-viaaa-aaaaq-aaamq-cai\";\nexport const DEFAULT_TOKENS = [\"CHAT\", \"ICP\", \"ckUSDC\", \"ckBTC\", \"ckETH\"];\n","import { toBigInt32, CommonResponses, emptyChatMetrics } from \"openchat-shared\";\nimport { accessGateConfig, apiPermissionRole, chatMetrics, eventsSuccessResponse, groupPermissions, groupSubtype, memberRole, mentions, messageEvent, messagesSuccessResponse, ocError, threadSyncDetails, updatedEvent, } from \"../common/chatMappersV2\";\nimport { ensureReplicaIsUpToDate } from \"../common/replicaUpToDateChecker\";\nimport { apiOptionUpdateV2, identity, mapOptional, optionUpdateV2, principalBytesToString, } from \"../../utils/mapping\";\nimport { ReplicaNotUpToDateError } from \"../error\";\nimport { mapCommonResponses } from \"../common/commonResponseMapper\";\nexport function apiRole(role) {\n switch (role) {\n case \"admin\":\n return \"Admin\";\n case \"moderator\":\n return \"Moderator\";\n case \"member\":\n return \"Participant\";\n case \"owner\":\n return \"Owner\";\n default:\n return undefined;\n }\n}\nexport function summaryResponse(value) {\n if (typeof value === \"object\" && \"Success\" in value) {\n return groupChatSummary(value.Success.summary);\n }\n if (typeof value === \"object\" && \"Error\" in value) {\n return ocError(value.Error);\n }\n return {\n kind: mapCommonResponses(value, \"GroupSummaryResponse\"),\n };\n}\nexport function groupChatSummary(value) {\n return {\n id: { kind: \"group_chat\", groupId: principalBytesToString(value.chat_id) },\n lastUpdated: value.last_updated,\n name: value.name,\n description: value.description,\n subtype: mapOptional(value.subtype, groupSubtype),\n avatarId: value.avatar_id,\n public: value.is_public,\n historyVisible: value.history_visible_to_new_joiners,\n minVisibleEventIndex: value.min_visible_event_index,\n minVisibleMessageIndex: value.min_visible_message_index,\n latestMessage: mapOptional(value.latest_message, messageEvent),\n latestEventIndex: value.latest_event_index,\n latestMessageIndex: value.latest_message_index,\n memberCount: value.participant_count,\n permissions: groupPermissions(value.permissions_v2),\n metrics: chatMetrics(value.metrics),\n frozen: value.frozen !== undefined,\n dateLastPinned: value.date_last_pinned,\n gateConfig: mapOptional(value.gate_config, accessGateConfig) ?? {\n gate: { kind: \"no_gate\" },\n expiry: undefined,\n },\n eventsTTL: value.events_ttl,\n eventsTtlLastUpdated: value.events_ttl_last_updated,\n localUserIndex: principalBytesToString(value.local_user_index_canister_id),\n videoCallInProgress: mapOptional(value.video_call_in_progress, (v) => v.message_index),\n messagesVisibleToNonMembers: value.messages_visible_to_non_members,\n membership: mapOptional(value.membership, (m) => ({\n joined: m.joined,\n role: memberRole(m.role),\n notificationsMuted: m.notifications_muted,\n lapsed: m.lapsed,\n rulesAccepted: m.rules_accepted,\n latestThreads: m.latest_threads.map(threadSyncDetails),\n mentions: mentions(m.mentions),\n myMetrics: chatMetrics(m.my_metrics),\n })) ?? {\n joined: 0n,\n role: \"none\",\n mentions: [],\n latestThreads: [],\n myMetrics: emptyChatMetrics(),\n notificationsMuted: false,\n rulesAccepted: false,\n lapsed: false,\n },\n verified: value.verified,\n };\n}\nexport function summaryUpdatesResponse(value) {\n if (typeof value === \"object\" && \"Success\" in value) {\n return groupChatSummaryUpdates(value.Success.updates);\n }\n if (typeof value === \"object\" && \"Error\" in value) {\n return ocError(value.Error);\n }\n return {\n kind: mapCommonResponses(value, \"GroupSummaryUpdates\"),\n };\n}\nexport function groupMembershipUpdates(value) {\n return {\n myRole: mapOptional(value.role, memberRole),\n mentions: mentions(value.mentions),\n notificationsMuted: value.notifications_muted,\n myMetrics: mapOptional(value.my_metrics, chatMetrics),\n latestThreads: value.latest_threads.map(threadSyncDetails),\n unfollowedThreads: Array.from(value.unfollowed_threads),\n rulesAccepted: value.rules_accepted,\n lapsed: value.lapsed,\n };\n}\nexport function groupChatSummaryUpdates(value) {\n return {\n id: { kind: \"group_chat\", groupId: principalBytesToString(value.chat_id) },\n lastUpdated: value.last_updated,\n name: value.name,\n description: value.description,\n subtype: optionUpdateV2(value.subtype, groupSubtype),\n avatarId: optionUpdateV2(value.avatar_id, identity),\n public: value.is_public,\n latestMessage: mapOptional(value.latest_message, messageEvent),\n latestEventIndex: value.latest_event_index,\n latestMessageIndex: value.latest_message_index,\n memberCount: value.participant_count,\n permissions: mapOptional(value.permissions_v2, groupPermissions),\n metrics: mapOptional(value.metrics, chatMetrics),\n frozen: optionUpdateV2(value.frozen, (_) => true),\n updatedEvents: value.updated_events.map(updatedEvent),\n dateLastPinned: value.date_last_pinned,\n gateConfig: optionUpdateV2(value.gate_config, accessGateConfig),\n eventsTTL: optionUpdateV2(value.events_ttl, identity),\n eventsTtlLastUpdated: value.events_ttl_last_updated,\n videoCallInProgress: optionUpdateV2(value.video_call_in_progress, (v) => v.message_index),\n messagesVisibleToNonMembers: value.messages_visible_to_non_members,\n membership: mapOptional(value.membership, groupMembershipUpdates),\n verified: mapOptional(value.verified, identity),\n };\n}\nexport function apiOptionalGroupPermissions(permissions) {\n return {\n delete_messages: mapOptional(permissions.deleteMessages, apiPermissionRole),\n remove_members: mapOptional(permissions.removeMembers, apiPermissionRole),\n update_group: mapOptional(permissions.updateGroup, apiPermissionRole),\n invite_users: mapOptional(permissions.inviteUsers, apiPermissionRole),\n add_members: mapOptional(permissions.addMembers, apiPermissionRole),\n change_roles: mapOptional(permissions.changeRoles, apiPermissionRole),\n pin_messages: mapOptional(permissions.pinMessages, apiPermissionRole),\n react_to_messages: mapOptional(permissions.reactToMessages, apiPermissionRole),\n mention_all_members: mapOptional(permissions.mentionAllMembers, apiPermissionRole),\n start_video_call: mapOptional(permissions.startVideoCall, apiPermissionRole),\n message_permissions: mapOptional(permissions.messagePermissions, apiOptionalMessagePermissions),\n thread_permissions: apiOptionUpdateV2(apiOptionalMessagePermissions, permissions.threadPermissions),\n };\n}\nfunction apiOptionalMessagePermissions(permissions) {\n const custom_updated = permissions.memeFighter !== undefined && permissions.memeFighter !== \"set_to_none\"\n ? [{ subtype: \"meme_fighter\", role: apiPermissionRole(permissions.memeFighter.value) }]\n : [];\n const custom_deleted = permissions.memeFighter === \"set_to_none\" ? [\"meme_fighter\"] : [];\n return {\n default: mapOptional(permissions.default, apiPermissionRole),\n text: apiOptionUpdateV2(apiPermissionRole, permissions.text),\n image: apiOptionUpdateV2(apiPermissionRole, permissions.image),\n video: apiOptionUpdateV2(apiPermissionRole, permissions.video),\n audio: apiOptionUpdateV2(apiPermissionRole, permissions.audio),\n file: apiOptionUpdateV2(apiPermissionRole, permissions.file),\n poll: apiOptionUpdateV2(apiPermissionRole, permissions.poll),\n crypto: apiOptionUpdateV2(apiPermissionRole, permissions.crypto),\n giphy: apiOptionUpdateV2(apiPermissionRole, permissions.giphy),\n prize: apiOptionUpdateV2(apiPermissionRole, permissions.prize),\n p2p_swap: apiOptionUpdateV2(apiPermissionRole, permissions.p2pSwap),\n video_call: apiOptionUpdateV2(apiPermissionRole, undefined),\n custom_updated,\n custom_deleted,\n };\n}\nexport function unblockUserResponse(value) {\n if (value === \"CannotUnblockSelf\") {\n return \"cannot_unblock_self\";\n }\n if (typeof value === \"object\" && \"Error\" in value) {\n return ocError(value.Error);\n }\n return mapCommonResponses(value, \"GroupUnblockUser\");\n}\nexport function blockUserResponse(value) {\n if (value === \"CannotBlockSelf\") {\n return \"cannot_block_self\";\n }\n if (value === \"CannotBlockUser\") {\n return \"cannot_block_user\";\n }\n if (typeof value === \"object\" && \"Error\" in value) {\n return ocError(value.Error);\n }\n return mapCommonResponses(value, \"GroupBlockUser\");\n}\nexport function sendMessageResponse(value) {\n if (typeof value === \"object\") {\n if (\"Success\" in value) {\n return {\n kind: \"success\",\n timestamp: value.Success.timestamp,\n messageIndex: value.Success.message_index,\n eventIndex: value.Success.event_index,\n expiresAt: mapOptional(value.Success.expires_at, Number),\n };\n }\n if (\"TextTooLong\" in value) {\n return { kind: \"text_too_long\" };\n }\n if (\"InvalidRequest\" in value) {\n return { kind: \"invalid_request\", reason: value.InvalidRequest };\n }\n if (\"InvalidPoll\" in value) {\n return { kind: \"invalid_poll\" };\n }\n if (\"Error\" in value) {\n return ocError(value.Error);\n }\n }\n if (value === \"MessageEmpty\") {\n return { kind: \"message_empty\" };\n }\n if (value === \"RulesNotAccepted\") {\n return { kind: \"rules_not_accepted\" };\n }\n return {\n kind: mapCommonResponses(value, \"GroupSendMessage\"),\n };\n}\nexport function removeMemberResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n else {\n console.warn(\"RemoveMember failed with \", value);\n return \"failure\";\n }\n}\nexport async function getMessagesByMessageIndexResponse(principal, value, chatId, latestKnownUpdatePreRequest) {\n if (typeof value === \"object\") {\n if (\"Success\" in value) {\n await ensureReplicaIsUpToDate(principal, chatId, value.Success.chat_last_updated);\n return messagesSuccessResponse(value.Success);\n }\n if (\"ReplicaNotUpToDateV2\" in value) {\n throw ReplicaNotUpToDateError.byTimestamp(value.ReplicaNotUpToDateV2, latestKnownUpdatePreRequest ?? BigInt(-1), false);\n }\n }\n console.warn(\"MessagesByMessageIndex failed with \", value);\n return \"events_failed\";\n}\nexport async function getEventsResponse(principal, value, chatId, latestKnownUpdatePreRequest) {\n if (typeof value === \"object\") {\n if (\"Success\" in value) {\n await ensureReplicaIsUpToDate(principal, chatId, value.Success.chat_last_updated);\n return eventsSuccessResponse(value.Success);\n }\n if (\"ReplicaNotUpToDateV2\" in value) {\n throw ReplicaNotUpToDateError.byTimestamp(value.ReplicaNotUpToDateV2, latestKnownUpdatePreRequest ?? BigInt(-1), false);\n }\n }\n console.warn(\"GetGroupChatEvents failed with \", value);\n return \"events_failed\";\n}\nexport function convertToCommunityResponse(value) {\n if (typeof value === \"object\" && \"Success\" in value) {\n return {\n kind: \"success\",\n id: {\n kind: \"channel\",\n communityId: principalBytesToString(value.Success.community_id),\n channelId: Number(toBigInt32(value.Success.channel_id)),\n },\n };\n }\n else {\n console.warn(\"ConvertToCommunity failed with \", value);\n return CommonResponses.failure();\n }\n}\nexport function apiUpdatedRules(rules) {\n return {\n text: rules.text,\n enabled: rules.enabled,\n new_version: rules.newVersion,\n };\n}\nexport function followThreadResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n if (value === \"AlreadyFollowing\" || value === \"NotFollowing\") {\n return \"unchanged\";\n }\n else {\n console.warn(\"followThread failed with\", value);\n return \"failed\";\n }\n}\nexport function reportMessageResponse(value) {\n return value === \"Success\" || value === \"AlreadyReported\";\n}\n","import { emptyChatMetrics } from \"../../utils/chat\";\nimport { mapOptional, principalBytesToString } from \"../../utils/mapping\";\nimport { accessGateConfig, groupSubtype, messageEvent } from \"./chatMappersV2\";\nimport { nullMembership, CommonResponses, } from \"openchat-shared\";\nexport function publicGroupSummary(value, isInvited) {\n const groupId = principalBytesToString(value.chat_id);\n return {\n kind: \"group_chat\",\n id: { kind: \"group_chat\", groupId },\n latestEventIndex: value.latest_event_index,\n latestMessageIndex: value.latest_message_index,\n latestMessage: mapOptional(value.latest_message, messageEvent),\n name: value.name,\n description: value.description,\n public: value.is_public,\n historyVisible: false,\n minVisibleEventIndex: 0,\n minVisibleMessageIndex: 0,\n lastUpdated: value.last_updated,\n memberCount: value.participant_count,\n blobReference: mapOptional(value.avatar_id, (blobId) => ({\n blobId,\n canisterId: groupId,\n })),\n permissions: {\n changeRoles: \"none\",\n removeMembers: \"none\",\n deleteMessages: \"none\",\n updateGroup: \"none\",\n pinMessages: \"none\",\n inviteUsers: \"none\",\n addMembers: \"none\",\n reactToMessages: \"none\",\n mentionAllMembers: \"none\",\n startVideoCall: \"none\",\n messagePermissions: {\n default: \"none\",\n },\n threadPermissions: undefined,\n },\n eventsTTL: value.events_ttl,\n eventsTtlLastUpdated: value.events_ttl_last_updated,\n metrics: emptyChatMetrics(),\n subtype: mapOptional(value.subtype, groupSubtype),\n previewed: true,\n frozen: value.frozen !== undefined,\n dateLastPinned: undefined,\n dateReadPinned: undefined,\n gateConfig: mapOptional(value.gate_config, accessGateConfig) ?? {\n gate: { kind: \"no_gate\" },\n expiry: undefined,\n },\n level: \"group\",\n membership: nullMembership(),\n localUserIndex: principalBytesToString(value.local_user_index_canister_id),\n isInvited,\n messagesVisibleToNonMembers: value.messages_visible_to_non_members,\n verified: false, // TODO - this needs to come from the backend\n };\n}\nexport function publicSummaryResponse(value) {\n if (typeof value === \"object\" && \"Success\" in value) {\n return {\n kind: \"success\",\n group: publicGroupSummary(value.Success.summary, value.Success.is_invited),\n };\n }\n else {\n console.warn(\"ApiPublicSummaryResponse failed with \", value);\n return CommonResponses.failure();\n }\n}\n","import { DestinationInvalidError, offline, textToCode, MAX_EVENTS, MAX_MESSAGES, MAX_MISSING, } from \"openchat-shared\";\nimport { MsgpackCanisterAgent } from \"../canisterAgent/msgpack\";\nimport { apiRole, getEventsResponse, removeMemberResponse, blockUserResponse, unblockUserResponse, getMessagesByMessageIndexResponse, apiOptionalGroupPermissions, summaryResponse, summaryUpdatesResponse, convertToCommunityResponse, apiUpdatedRules, followThreadResponse, reportMessageResponse, } from \"./mappersV2\";\nimport { sendMessageResponse } from \"./mappersV2\";\nimport { getCachedEvents, getCachedEventsByIndex, getCachedEventsWindowByMessageIndex, getCachedGroupDetails, loadMessagesByMessageIndex, mergeSuccessResponses, recordFailedMessage, removeFailedMessage, setCachedEvents, setCachedGroupDetails, } from \"../../utils/caching\";\nimport { acceptP2PSwapResponse, addRemoveReactionResponse, apiAccessGateConfig, apiExternalBotPermissions, apiMessageContent, apiUser as apiUserV2, apiVideoCallPresence, cancelP2PSwapResponse, changeRoleResponse, claimPrizeResponse, declineInvitationResponse, deleteMessageResponse, deletedMessageResponse, disableInviteCodeResponse, editMessageResponse, enableOrResetInviteCodeResponse, generateApiKeyResponse, groupDetailsResponse, groupDetailsUpdatesResponse, inviteCodeResponse, joinVideoCallResponse, pinMessageResponse, registerPollVoteResponse, registerProposalVoteResponse, searchGroupChatResponse, setVideoCallPresence, threadPreviewsResponse, undeleteMessageResponse, unpinMessageResponse, updateBotResponse, updateGroupResponse, videoCallParticipantsResponse, } from \"../common/chatMappersV2\";\nimport { DataClient } from \"../data/data.client\";\nimport { mergeGroupChatDetails } from \"../../utils/chat\";\nimport { publicSummaryResponse } from \"../common/publicSummaryMapperV2\";\nimport { apiOptionUpdateV2, identity, mapOptional, principalBytesToString, principalStringToBytes, } from \"../../utils/mapping\";\nimport { generateUint64 } from \"../../utils/rng\";\nimport { setCachedMessageFromSendResponse } from \"../../utils/caching\";\nimport { toggleNotificationsResponse } from \"../notifications/mappers\";\nimport { ResponseTooLargeError } from \"openchat-shared\";\nimport { chunkedChatEventsFromBackend, chunkedChatEventsWindowFromBackend, } from \"../common/chunked\";\nimport { Empty as TEmpty, GroupAcceptP2pSwapArgs, GroupAcceptP2pSwapResponse, GroupAddReactionArgs, GroupAddReactionResponse, GroupBlockUserArgs, GroupBlockUserResponse, GroupCancelInvitesArgs, GroupCancelInvitesResponse, GroupCancelP2pSwapArgs, GroupCancelP2pSwapResponse, GroupChangeRoleArgs, GroupChangeRoleResponse, GroupClaimPrizeArgs, GroupClaimPrizeResponse, GroupConvertIntoCommunityArgs, GroupConvertIntoCommunityResponse, GroupDeclineInvitiationResponse, GroupDeletedMessageArgs, GroupDeletedMessageResponse, GroupDeleteMessagesArgs, GroupDeleteMessagesResponse, GroupDisableInviteCodeArgs, GroupDisableInviteCodeResponse, GroupEditMessageArgs, GroupEditMessageResponse, GroupEnableInviteCodeArgs, GroupEnableInviteCodeResponse, GroupEventsArgs, GroupEventsByIndexArgs, GroupEventsResponse, GroupEventsWindowArgs, GroupFollowThreadArgs, GroupFollowThreadResponse, GroupInviteCodeResponse, GroupJoinVideoCallArgs, GroupLocalUserIndexResponse, GroupMessagesByMessageIndexArgs, GroupMessagesByMessageIndexResponse, GroupPinMessageArgs, GroupPinMessageResponse, GroupPublicSummaryArgs, GroupPublicSummaryResponse, GroupRegisterPollVoteArgs, GroupRegisterPollVoteResponse, GroupRegisterProposalVoteArgs, GroupRegisterProposalVoteResponse, GroupRegisterProposalVoteV2Args, GroupRegisterProposalVoteV2Response, GroupRemoveParticipantArgs, GroupRemoveParticipantResponse, GroupRemoveReactionArgs, GroupRemoveReactionResponse, GroupReportMessageArgs, GroupReportMessageResponse, GroupSearchMessagesArgs, GroupSearchMessagesResponse, GroupSelectedInitialResponse, GroupSelectedUpdatesArgs, GroupSelectedUpdatesResponse, GroupSendMessageArgs, GroupSendMessageResponse, GroupSetVideoCallPresenceArgs, GroupSetVideoCallPresenceResponse, GroupSummaryResponse, GroupSummaryUpdatesArgs, GroupSummaryUpdatesResponse, GroupThreadPreviewsArgs, GroupThreadPreviewsResponse, GroupToggleMuteNotificationsArgs, GroupToggleMuteNotificationsResponse, GroupUnblockUserArgs, GroupUnblockUserResponse, GroupUndeleteMessagesArgs, GroupUndeleteMessagesResponse, GroupUnpinMessageArgs, GroupUnpinMessageResponse, GroupUpdateGroupArgs, GroupUpdateGroupResponse, GroupVideoCallParticipantsArgs, GroupVideoCallParticipantsResponse, GroupUpdateBotArgs, GroupUpdateBotResponse, GroupGenerateBotApiKeyArgs, GroupGenerateBotApiKeyResponse, GroupApiKeyArgs, GroupApiKeyResponse, } from \"../../typebox\";\nexport class GroupClient extends MsgpackCanisterAgent {\n constructor(identity, agent, config, chatId, db, inviteCode) {\n super(identity, agent, chatId.groupId, \"Group\");\n this.config = config;\n this.chatId = chatId;\n this.db = db;\n this.inviteCode = inviteCode;\n }\n summary() {\n return this.executeMsgpackQuery(\"summary\", {}, summaryResponse, TEmpty, GroupSummaryResponse).catch((err) => {\n if (err instanceof DestinationInvalidError) {\n return { kind: \"canister_not_found\" };\n }\n else {\n throw err;\n }\n });\n }\n summaryUpdates(updatesSince) {\n const args = { updates_since: updatesSince };\n return this.executeMsgpackQuery(\"summary_updates\", args, summaryUpdatesResponse, GroupSummaryUpdatesArgs, GroupSummaryUpdatesResponse);\n }\n getCachedEventsByIndex(eventIndexes, threadRootMessageIndex) {\n return getCachedEventsByIndex(this.db, eventIndexes, {\n chatId: this.chatId,\n threadRootMessageIndex,\n });\n }\n chatEventsByIndex(eventIndexes, threadRootMessageIndex, latestKnownUpdate) {\n return this.getCachedEventsByIndex(eventIndexes, threadRootMessageIndex).then((res) => this.handleMissingEvents(res, threadRootMessageIndex, latestKnownUpdate));\n }\n setCachedEvents(resp, threadRootMessageIndex) {\n setCachedEvents(this.db, this.chatId, resp, threadRootMessageIndex).catch((err) => this.config.logger.error(\"Error writing cached group events\", err));\n return resp;\n }\n handleMissingEvents([cachedEvents, missing], threadRootMessageIndex, latestKnownUpdate) {\n if (missing.size === 0) {\n return Promise.resolve(cachedEvents);\n }\n else {\n return this.chatEventsByIndexFromBackend([...missing], threadRootMessageIndex, latestKnownUpdate)\n .then((resp) => this.setCachedEvents(resp, threadRootMessageIndex))\n .then((resp) => {\n if (resp !== \"events_failed\") {\n return mergeSuccessResponses(cachedEvents, resp);\n }\n return resp;\n });\n }\n }\n chatEventsByIndexFromBackend(eventIndexes, threadRootMessageIndex, latestKnownUpdate) {\n const args = {\n thread_root_message_index: threadRootMessageIndex,\n events: eventIndexes,\n latest_known_update: latestKnownUpdate,\n latest_client_event_index: undefined,\n };\n return this.executeMsgpackQuery(\"events_by_index\", args, (resp) => getEventsResponse(this.principal, resp, this.chatId, latestKnownUpdate), GroupEventsByIndexArgs, GroupEventsResponse);\n }\n async chatEventsWindow(eventIndexRange, messageIndex, threadRootMessageIndex, latestKnownUpdate, maxEvents = MAX_EVENTS) {\n const [cachedEvents, missing, totalMiss] = await getCachedEventsWindowByMessageIndex(this.db, eventIndexRange, { chatId: this.chatId, threadRootMessageIndex }, messageIndex, maxEvents);\n if (totalMiss || missing.size >= MAX_MISSING) {\n // if we have exceeded the maximum number of missing events, let's just consider it a complete miss and go to the api\n console.log(\"We didn't get enough back from the cache, going to the api\", missing.size, totalMiss);\n return this.chatEventsWindowFromBackend(messageIndex, threadRootMessageIndex, latestKnownUpdate, maxEvents)\n .then((resp) => this.setCachedEvents(resp, threadRootMessageIndex))\n .catch((err) => {\n if (err instanceof ResponseTooLargeError) {\n console.log(\"Response size too large, we will try to split the window request into a a few chunks\");\n return chunkedChatEventsWindowFromBackend((index, ascending, chunkSize) => this.chatEventsFromBackend(index, ascending, threadRootMessageIndex, latestKnownUpdate, chunkSize), (index, chunkSize) => this.chatEventsWindowFromBackend(index, threadRootMessageIndex, latestKnownUpdate, chunkSize), eventIndexRange, messageIndex).then((resp) => this.setCachedEvents(resp, threadRootMessageIndex));\n }\n else {\n throw err;\n }\n });\n }\n else {\n return this.handleMissingEvents([cachedEvents, missing], threadRootMessageIndex, latestKnownUpdate);\n }\n }\n async chatEventsWindowFromBackend(messageIndex, threadRootMessageIndex, latestKnownUpdate, maxEvents = MAX_EVENTS) {\n const args = {\n thread_root_message_index: threadRootMessageIndex,\n max_messages: MAX_MESSAGES,\n max_events: maxEvents,\n mid_point: messageIndex,\n latest_known_update: latestKnownUpdate,\n latest_client_event_index: undefined,\n };\n return this.executeMsgpackQuery(\"events_window\", args, (resp) => getEventsResponse(this.principal, resp, this.chatId, latestKnownUpdate), GroupEventsWindowArgs, GroupEventsResponse);\n }\n async chatEvents(eventIndexRange, startIndex, ascending, threadRootMessageIndex, latestKnownUpdate) {\n const [cachedEvents, missing] = await getCachedEvents(this.db, eventIndexRange, { chatId: this.chatId, threadRootMessageIndex }, startIndex, ascending);\n // we may or may not have all of the requested events\n if (missing.size >= MAX_MISSING) {\n // if we have exceeded the maximum number of missing events, let's just consider it a complete miss and go to the api\n console.log(\"We didn't get enough back from the cache, going to the api\", missing.size);\n return this.chatEventsFromBackend(startIndex, ascending, threadRootMessageIndex, latestKnownUpdate)\n .then((resp) => this.setCachedEvents(resp, threadRootMessageIndex))\n .catch((err) => {\n if (err instanceof ResponseTooLargeError) {\n console.log(\"Response size too large, we will try to split the payload into a a few chunks\");\n return chunkedChatEventsFromBackend((index, chunkSize) => this.chatEventsFromBackend(index, ascending, threadRootMessageIndex, latestKnownUpdate, chunkSize), eventIndexRange, startIndex, ascending).then((resp) => this.setCachedEvents(resp, threadRootMessageIndex));\n }\n else {\n throw err;\n }\n });\n }\n else {\n return this.handleMissingEvents([cachedEvents, missing], threadRootMessageIndex, latestKnownUpdate);\n }\n }\n chatEventsFromBackend(startIndex, ascending, threadRootMessageIndex, latestKnownUpdate, maxEvents = MAX_EVENTS) {\n const args = {\n thread_root_message_index: threadRootMessageIndex,\n max_messages: MAX_MESSAGES,\n max_events: maxEvents,\n ascending,\n start_index: startIndex,\n latest_known_update: latestKnownUpdate,\n latest_client_event_index: undefined,\n };\n return this.executeMsgpackQuery(\"events\", args, (resp) => getEventsResponse(this.principal, resp, this.chatId, latestKnownUpdate), GroupEventsArgs, GroupEventsResponse);\n }\n changeRole(userId, newRole) {\n const new_role = apiRole(newRole);\n if (new_role === undefined) {\n throw new Error(`Cannot change user's role to: ${newRole}`);\n }\n return this.executeMsgpackUpdate(\"change_role\", {\n user_id: principalStringToBytes(userId),\n new_role,\n correlation_id: generateUint64(),\n }, changeRoleResponse, GroupChangeRoleArgs, GroupChangeRoleResponse);\n }\n removeMember(userId) {\n return this.executeMsgpackUpdate(\"remove_participant\", {\n user_id: principalStringToBytes(userId),\n correlation_id: generateUint64(),\n }, removeMemberResponse, GroupRemoveParticipantArgs, GroupRemoveParticipantResponse);\n }\n editMessage(message, threadRootMessageIndex, blockLevelMarkdown, newAchievement) {\n return new DataClient(this.identity, this.agent, this.config)\n .uploadData(message.content, [this.chatId.groupId])\n .then((content) => {\n const args = {\n thread_root_message_index: threadRootMessageIndex,\n content: apiMessageContent(content ?? message.content),\n message_id: message.messageId,\n block_level_markdown: blockLevelMarkdown,\n correlation_id: generateUint64(),\n new_achievement: newAchievement,\n };\n return this.executeMsgpackUpdate(\"edit_message_v2\", args, editMessageResponse, GroupEditMessageArgs, GroupEditMessageResponse);\n });\n }\n claimPrize(messageId) {\n return this.executeMsgpackUpdate(\"claim_prize\", {\n correlation_id: generateUint64(),\n message_id: messageId,\n }, claimPrizeResponse, GroupClaimPrizeArgs, GroupClaimPrizeResponse);\n }\n sendMessage(senderName, senderDisplayName, mentioned, event, threadRootMessageIndex, rulesAccepted, messageFilterFailed, newAchievement, onRequestAccepted) {\n // pre-emtively remove the failed message from indexeddb - it will get re-added if anything goes wrong\n removeFailedMessage(this.db, this.chatId, event.event.messageId, threadRootMessageIndex);\n const dataClient = new DataClient(this.identity, this.agent, this.config);\n const uploadContentPromise = event.event.forwarded\n ? dataClient.forwardData(event.event.content, [this.chatId.groupId])\n : dataClient.uploadData(event.event.content, [this.chatId.groupId]);\n return uploadContentPromise.then((content) => {\n const newEvent = content !== undefined ? { ...event, event: { ...event.event, content } } : event;\n const args = {\n content: apiMessageContent(newEvent.event.content),\n message_id: newEvent.event.messageId,\n sender_name: senderName,\n sender_display_name: senderDisplayName,\n rules_accepted: rulesAccepted,\n replies_to: mapOptional(newEvent.event.repliesTo, (replyContext) => ({\n event_index: replyContext.eventIndex,\n })),\n mentioned: mentioned.map(apiUserV2),\n forwarding: newEvent.event.forwarded,\n thread_root_message_index: threadRootMessageIndex,\n message_filter_failed: messageFilterFailed,\n correlation_id: generateUint64(),\n block_level_markdown: newEvent.event.blockLevelMarkdown,\n new_achievement: newAchievement,\n };\n return this.executeMsgpackUpdate(\"send_message_v2\", args, sendMessageResponse, GroupSendMessageArgs, GroupSendMessageResponse, onRequestAccepted)\n .then((resp) => {\n const retVal = [resp, newEvent.event];\n setCachedMessageFromSendResponse(this.db, this.chatId, newEvent, threadRootMessageIndex)(retVal);\n return retVal;\n })\n .catch((err) => {\n recordFailedMessage(this.db, this.chatId, newEvent, threadRootMessageIndex);\n throw err;\n });\n });\n }\n updateGroup(name, description, rules, permissions, avatar, eventsTimeToLiveMs, gateConfig, isPublic, messagesVisibleToNonMembers) {\n return this.executeMsgpackUpdate(\"update_group_v2\", {\n name,\n description,\n public: isPublic,\n avatar: avatar === undefined\n ? \"NoChange\"\n : {\n SetToSome: {\n id: DataClient.newBlobId(),\n mime_type: \"image/jpg\",\n data: avatar,\n },\n },\n permissions_v2: mapOptional(permissions, apiOptionalGroupPermissions),\n rules: mapOptional(rules, apiUpdatedRules),\n events_ttl: apiOptionUpdateV2(identity, eventsTimeToLiveMs),\n correlation_id: generateUint64(),\n gate_config: gateConfig === undefined\n ? \"NoChange\"\n : gateConfig.gate.kind === \"no_gate\"\n ? \"SetToNone\"\n : { SetToSome: apiAccessGateConfig(gateConfig) },\n messages_visible_to_non_members: messagesVisibleToNonMembers,\n }, updateGroupResponse, GroupUpdateGroupArgs, GroupUpdateGroupResponse);\n }\n addReaction(messageId, reaction, username, displayName, threadRootMessageIndex, newAchievement) {\n return this.executeMsgpackUpdate(\"add_reaction\", {\n thread_root_message_index: threadRootMessageIndex,\n message_id: messageId,\n reaction,\n username,\n display_name: displayName,\n correlation_id: generateUint64(),\n new_achievement: newAchievement,\n }, addRemoveReactionResponse, GroupAddReactionArgs, GroupAddReactionResponse);\n }\n removeReaction(messageId, reaction, threadRootMessageIndex) {\n return this.executeMsgpackUpdate(\"remove_reaction\", {\n thread_root_message_index: threadRootMessageIndex,\n message_id: messageId,\n reaction,\n correlation_id: generateUint64(),\n }, addRemoveReactionResponse, GroupRemoveReactionArgs, GroupRemoveReactionResponse);\n }\n deleteMessage(messageId, threadRootMessageIndex, asPlatformModerator, newAchievement) {\n return this.executeMsgpackUpdate(\"delete_messages\", {\n thread_root_message_index: threadRootMessageIndex,\n message_ids: [messageId],\n correlation_id: generateUint64(),\n as_platform_moderator: asPlatformModerator,\n new_achievement: newAchievement,\n }, deleteMessageResponse, GroupDeleteMessagesArgs, GroupDeleteMessagesResponse);\n }\n undeleteMessage(messageId, threadRootMessageIndex) {\n return this.executeMsgpackUpdate(\"undelete_messages\", {\n thread_root_message_index: threadRootMessageIndex,\n message_ids: [messageId],\n correlation_id: generateUint64(),\n }, undeleteMessageResponse, GroupUndeleteMessagesArgs, GroupUndeleteMessagesResponse);\n }\n blockUser(userId) {\n return this.executeMsgpackUpdate(\"block_user\", {\n user_id: principalStringToBytes(userId),\n correlation_id: generateUint64(),\n }, blockUserResponse, GroupBlockUserArgs, GroupBlockUserResponse);\n }\n unblockUser(userId) {\n return this.executeMsgpackUpdate(\"unblock_user\", {\n user_id: principalStringToBytes(userId),\n correlation_id: generateUint64(),\n }, unblockUserResponse, GroupUnblockUserArgs, GroupUnblockUserResponse);\n }\n async getGroupDetails(chatLastUpdated) {\n const fromCache = await getCachedGroupDetails(this.db, this.chatId.groupId);\n if (fromCache !== undefined) {\n if (fromCache.timestamp >= chatLastUpdated || offline()) {\n return fromCache;\n }\n else {\n return this.getGroupDetailsUpdates(fromCache);\n }\n }\n const response = await this.getGroupDetailsFromBackend();\n if (response !== \"failure\") {\n await setCachedGroupDetails(this.db, this.chatId.groupId, response);\n }\n return response;\n }\n getGroupDetailsFromBackend() {\n return this.executeMsgpackQuery(\"selected_initial\", {}, groupDetailsResponse, TEmpty, GroupSelectedInitialResponse);\n }\n async getGroupDetailsUpdates(previous) {\n const response = await this.getGroupDetailsUpdatesFromBackend(previous);\n if (response.timestamp > previous.timestamp) {\n await setCachedGroupDetails(this.db, this.chatId.groupId, response);\n }\n return response;\n }\n async getGroupDetailsUpdatesFromBackend(previous) {\n const args = {\n updates_since: previous.timestamp,\n };\n const updatesResponse = await this.executeMsgpackQuery(\"selected_updates_v2\", args, groupDetailsUpdatesResponse, GroupSelectedUpdatesArgs, GroupSelectedUpdatesResponse);\n if (updatesResponse.kind === \"failure\") {\n return previous;\n }\n if (updatesResponse.kind === \"success_no_updates\") {\n return {\n ...previous,\n timestamp: updatesResponse.timestamp,\n };\n }\n return mergeGroupChatDetails(previous, updatesResponse);\n }\n getPublicSummary() {\n const args = { invite_code: mapOptional(this.inviteCode, textToCode) };\n return this.executeMsgpackQuery(\"public_summary\", args, publicSummaryResponse, GroupPublicSummaryArgs, GroupPublicSummaryResponse);\n }\n async getMessagesByMessageIndex(messageIndexes, latestKnownUpdate) {\n const fromCache = await loadMessagesByMessageIndex(this.db, this.chatId, messageIndexes);\n if (fromCache.missing.size > 0) {\n console.log(\"Missing idxs from the cached: \", fromCache.missing);\n const resp = await this.getMessagesByMessageIndexFromBackend([...fromCache.missing], latestKnownUpdate).then((resp) => this.setCachedEvents(resp));\n return resp === \"events_failed\"\n ? resp\n : {\n events: [...fromCache.messageEvents, ...resp.events],\n expiredEventRanges: [],\n expiredMessageRanges: [],\n latestEventIndex: resp.latestEventIndex,\n };\n }\n return {\n events: fromCache.messageEvents,\n expiredEventRanges: [],\n expiredMessageRanges: [],\n latestEventIndex: undefined,\n };\n }\n getMessagesByMessageIndexFromBackend(messageIndexes, latestKnownUpdate) {\n const args = {\n thread_root_message_index: undefined,\n messages: messageIndexes,\n invite_code: undefined,\n latest_known_update: latestKnownUpdate,\n latest_client_event_index: undefined,\n };\n return this.executeMsgpackQuery(\"messages_by_message_index\", args, (resp) => getMessagesByMessageIndexResponse(this.principal, resp, this.chatId, latestKnownUpdate), GroupMessagesByMessageIndexArgs, GroupMessagesByMessageIndexResponse);\n }\n getDeletedMessage(messageId, threadRootMessageIndex) {\n return this.executeMsgpackUpdate(\"deleted_message\", {\n message_id: messageId,\n thread_root_message_index: threadRootMessageIndex,\n }, deletedMessageResponse, GroupDeletedMessageArgs, GroupDeletedMessageResponse);\n }\n pinMessage(messageIndex) {\n return this.executeMsgpackUpdate(\"pin_message_v2\", {\n message_index: messageIndex,\n correlation_id: generateUint64(),\n }, pinMessageResponse, GroupPinMessageArgs, GroupPinMessageResponse);\n }\n unpinMessage(messageIndex) {\n return this.executeMsgpackUpdate(\"unpin_message\", {\n message_index: messageIndex,\n correlation_id: generateUint64(),\n }, unpinMessageResponse, GroupUnpinMessageArgs, GroupUnpinMessageResponse);\n }\n registerPollVote(messageIdx, answerIdx, voteType, threadRootMessageIndex, newAchievement) {\n return this.executeMsgpackUpdate(\"register_poll_vote\", {\n thread_root_message_index: threadRootMessageIndex,\n poll_option: answerIdx,\n operation: voteType === \"register\" ? \"RegisterVote\" : \"DeleteVote\",\n message_index: messageIdx,\n new_achievement: newAchievement,\n correlation_id: generateUint64(),\n }, registerPollVoteResponse, GroupRegisterPollVoteArgs, GroupRegisterPollVoteResponse);\n }\n searchGroupChat(searchTerm, userIds, maxResults) {\n const args = {\n search_term: searchTerm,\n max_results: maxResults,\n users: userIds.map(principalStringToBytes),\n };\n return this.executeMsgpackQuery(\"search_messages\", args, (res) => searchGroupChatResponse(res, this.chatId), GroupSearchMessagesArgs, GroupSearchMessagesResponse);\n }\n getInviteCode() {\n return this.executeMsgpackQuery(\"invite_code\", {}, inviteCodeResponse, TEmpty, GroupInviteCodeResponse);\n }\n enableInviteCode() {\n return this.executeMsgpackUpdate(\"enable_invite_code\", {\n correlation_id: generateUint64(),\n }, enableOrResetInviteCodeResponse, GroupEnableInviteCodeArgs, GroupEnableInviteCodeResponse);\n }\n disableInviteCode() {\n return this.executeMsgpackUpdate(\"disable_invite_code\", {\n correlation_id: generateUint64(),\n }, disableInviteCodeResponse, GroupDisableInviteCodeArgs, GroupDisableInviteCodeResponse);\n }\n resetInviteCode() {\n return this.executeMsgpackUpdate(\"reset_invite_code\", {\n correlation_id: generateUint64(),\n }, enableOrResetInviteCodeResponse, GroupEnableInviteCodeArgs, GroupEnableInviteCodeResponse);\n }\n threadPreviews(threadRootMessageIndexes, latestClientThreadUpdate) {\n return this.executeMsgpackQuery(\"thread_previews\", {\n threads: threadRootMessageIndexes,\n latest_client_thread_update: latestClientThreadUpdate,\n }, (resp) => threadPreviewsResponse(resp, this.chatId, latestClientThreadUpdate), GroupThreadPreviewsArgs, GroupThreadPreviewsResponse);\n }\n registerProposalVote(messageIdx, adopt) {\n return this.executeMsgpackUpdate(\"register_proposal_vote\", {\n adopt,\n message_index: messageIdx,\n }, registerProposalVoteResponse, GroupRegisterProposalVoteArgs, GroupRegisterProposalVoteResponse);\n }\n registerProposalVoteV2(messageIdx, adopt) {\n return this.executeMsgpackUpdate(\"register_proposal_vote_v2\", {\n adopt,\n message_index: messageIdx,\n }, registerProposalVoteResponse, GroupRegisterProposalVoteV2Args, GroupRegisterProposalVoteV2Response);\n }\n localUserIndex() {\n return this.executeMsgpackQuery(\"local_user_index\", {}, (resp) => principalBytesToString(resp.Success), TEmpty, GroupLocalUserIndexResponse);\n }\n declineInvitation() {\n return this.executeMsgpackUpdate(\"decline_invitation\", {}, declineInvitationResponse, TEmpty, GroupDeclineInvitiationResponse);\n }\n toggleMuteNotifications(mute) {\n return this.executeMsgpackUpdate(\"toggle_mute_notifications\", { mute }, toggleNotificationsResponse, GroupToggleMuteNotificationsArgs, GroupToggleMuteNotificationsResponse);\n }\n convertToCommunity(historyVisible, rules) {\n return this.executeMsgpackUpdate(\"convert_into_community\", {\n history_visible_to_new_joiners: historyVisible,\n primary_language: undefined,\n permissions: undefined,\n rules,\n }, convertToCommunityResponse, GroupConvertIntoCommunityArgs, GroupConvertIntoCommunityResponse);\n }\n followThread(threadRootMessageIndex, follow, newAchievement) {\n const args = {\n thread_root_message_index: threadRootMessageIndex,\n new_achievement: newAchievement,\n };\n return this.executeMsgpackUpdate(follow ? \"follow_thread\" : \"unfollow_thread\", args, followThreadResponse, GroupFollowThreadArgs, GroupFollowThreadResponse);\n }\n reportMessage(threadRootMessageIndex, messageId, deleteMessage) {\n return this.executeMsgpackUpdate(\"report_message\", {\n thread_root_message_index: threadRootMessageIndex,\n message_id: messageId,\n delete: deleteMessage,\n }, reportMessageResponse, GroupReportMessageArgs, GroupReportMessageResponse);\n }\n acceptP2PSwap(threadRootMessageIndex, messageId, pin, newAchievement) {\n return this.executeMsgpackUpdate(\"accept_p2p_swap\", {\n thread_root_message_index: threadRootMessageIndex,\n message_id: messageId,\n pin,\n new_achievement: newAchievement,\n }, acceptP2PSwapResponse, GroupAcceptP2pSwapArgs, GroupAcceptP2pSwapResponse);\n }\n cancelP2PSwap(threadRootMessageIndex, messageId) {\n return this.executeMsgpackUpdate(\"cancel_p2p_swap\", {\n thread_root_message_index: threadRootMessageIndex,\n message_id: messageId,\n }, cancelP2PSwapResponse, GroupCancelP2pSwapArgs, GroupCancelP2pSwapResponse);\n }\n joinVideoCall(messageId, newAchievement) {\n return this.executeMsgpackUpdate(\"join_video_call\", {\n message_id: messageId,\n new_achievement: newAchievement,\n }, joinVideoCallResponse, GroupJoinVideoCallArgs, GroupSetVideoCallPresenceResponse);\n }\n setVideoCallPresence(messageId, presence, newAchievement) {\n return this.executeMsgpackUpdate(\"set_video_call_presence\", {\n message_id: messageId,\n presence: apiVideoCallPresence(presence),\n new_achievement: newAchievement,\n }, setVideoCallPresence, GroupSetVideoCallPresenceArgs, GroupSetVideoCallPresenceResponse);\n }\n videoCallParticipants(messageId, updatesSince) {\n return this.executeMsgpackQuery(\"video_call_participants\", {\n message_id: messageId,\n updated_since: updatesSince,\n }, videoCallParticipantsResponse, GroupVideoCallParticipantsArgs, GroupVideoCallParticipantsResponse);\n }\n cancelInvites(userIds) {\n return this.executeMsgpackUpdate(\"cancel_invites\", {\n user_ids: userIds.map(principalStringToBytes),\n }, (value) => value === \"Success\", GroupCancelInvitesArgs, GroupCancelInvitesResponse);\n }\n updateInstalledBot(botId, grantedPermissions) {\n return this.executeMsgpackUpdate(\"update_bot\", {\n bot_id: principalStringToBytes(botId),\n granted_permissions: apiExternalBotPermissions(grantedPermissions),\n }, updateBotResponse, GroupUpdateBotArgs, GroupUpdateBotResponse);\n }\n generateBotApiKey(botId, permissions) {\n return this.executeMsgpackUpdate(\"generate_bot_api_key\", {\n bot_id: principalStringToBytes(botId),\n requested_permissions: apiExternalBotPermissions(permissions),\n }, generateApiKeyResponse, GroupGenerateBotApiKeyArgs, GroupGenerateBotApiKeyResponse);\n }\n getApiKey(botId) {\n return this.executeMsgpackQuery(\"api_key\", {\n bot_id: principalStringToBytes(botId),\n }, (resp) => {\n if (typeof resp === \"object\" && \"Success\" in resp) {\n return resp.Success;\n }\n console.log(\"Failed to get community api key: \", botId, resp);\n return undefined;\n }, GroupApiKeyArgs, GroupApiKeyResponse);\n }\n}\n","import { Principal } from \"@dfinity/principal\";\nimport { toBigInt32, CommonResponses, MAX_EVENTS, MAX_MESSAGES, UnsupportedValueError, } from \"openchat-shared\";\nimport { bytesToHexString, principalBytesToString, principalStringToBytes, } from \"../../utils/mapping\";\nimport { apiChatIdentifier, communityChannelSummary, communitySummary, eventsSuccessResponse, gateCheckFailedReason, ocError, } from \"../common/chatMappersV2\";\nimport { groupChatSummary, groupChatSummaryUpdates } from \"../group/mappersV2\";\nimport { communitySummaryUpdates } from \"../community/mappersV2\";\nimport { ensureReplicaIsUpToDate } from \"../common/replicaUpToDateChecker\";\nexport function apiAccessTokenType(domain) {\n switch (domain.kind) {\n case \"join_video_call\":\n return { JoinVideoCall: { chat: apiChatIdentifier(domain.chatId) } };\n case \"start_video_call\":\n return {\n StartVideoCall: {\n call_type: apiCallType(domain.callType),\n chat: apiChatIdentifier(domain.chatId),\n },\n };\n case \"bot_action_by_command\":\n return {\n BotActionByCommand: {\n bot_id: principalStringToBytes(domain.botId),\n scope: apiBotActionScope(domain.scope),\n command: {\n name: domain.command.commandName,\n args: domain.command.arguments\n .filter(commandArgumentHasValue)\n .map(apiBotCommandArg),\n meta: domain.command.meta,\n },\n },\n };\n }\n}\nfunction commandArgumentHasValue(arg) {\n switch (arg.kind) {\n case \"user\":\n return arg.userId != null;\n default:\n return arg.value != null;\n }\n}\nexport function apiBotActionScope(domain) {\n switch (domain.kind) {\n case \"chat_scope\":\n return {\n Chat: {\n chat: apiChatIdentifier(domain.chatId),\n thread: domain.threadRootMessageIndex,\n message_id: domain.messageId,\n user_message_id: domain.userMessageId,\n },\n };\n case \"community_scope\":\n return {\n Community: {\n community_id: principalStringToBytes(domain.communityId.communityId),\n },\n };\n }\n}\nexport function apiBotCommandArg(domain) {\n return {\n name: domain.name,\n value: apiBotCommandArgValue(domain),\n };\n}\nexport function apiBotCommandArgValue(domain) {\n switch (domain.kind) {\n case \"boolean\":\n return {\n Boolean: domain.value,\n };\n case \"integer\":\n return {\n Integer: domain.value,\n };\n case \"decimal\":\n return {\n Decimal: domain.value,\n };\n case \"string\":\n return {\n String: domain.value,\n };\n case \"user\":\n return {\n User: principalStringToBytes(domain.userId),\n };\n case \"dateTime\":\n return {\n DateTime: domain.value,\n };\n }\n}\nexport function apiCallType(domain) {\n if (domain === \"broadcast\")\n return \"Broadcast\";\n if (domain === \"default\")\n return \"Default\";\n throw new UnsupportedValueError(\"Unexpected VideoCallType received\", domain);\n}\nexport function accessTokenResponse(value) {\n if (typeof value === \"object\" && \"Success\" in value) {\n return value.Success;\n }\n console.warn(\"Unable to get access token: \", value);\n return undefined;\n}\nexport function groupAndCommunitySummaryUpdates(value) {\n const results = [];\n for (const result of value.Success) {\n if (result === \"SuccessNoUpdates\") {\n results.push({\n kind: \"no_updates\",\n });\n }\n else if (result === \"NotFound\") {\n results.push({\n kind: \"not_found\",\n });\n }\n else if (\"SuccessGroup\" in result) {\n results.push({\n kind: \"group\",\n value: groupChatSummary(result.SuccessGroup),\n });\n }\n else if (\"SuccessGroupUpdates\" in result) {\n results.push({\n kind: \"group_updates\",\n value: groupChatSummaryUpdates(result.SuccessGroupUpdates),\n });\n }\n else if (\"SuccessCommunity\" in result) {\n results.push({\n kind: \"community\",\n value: communitySummary(result.SuccessCommunity),\n });\n }\n else if (\"SuccessCommunityUpdates\" in result) {\n results.push({\n kind: \"community_updates\",\n value: communitySummaryUpdates(result.SuccessCommunityUpdates),\n });\n }\n else if (\"InternalError\" in result) {\n results.push({\n kind: \"error\",\n error: result.InternalError,\n });\n }\n else if (\"Error\" in result) {\n results.push({\n kind: \"error\",\n error: JSON.stringify(result.Error),\n });\n }\n else {\n throw new UnsupportedValueError(\"Unexpected ApiSummaryUpdatesResponse type received\", result);\n }\n }\n return results;\n}\nexport function chatEventsArgs(eventArgs) {\n return {\n context: eventsContext(eventArgs.context),\n args: eventsArgsInner(eventArgs.args),\n latest_known_update: eventArgs.latestKnownUpdate,\n };\n}\nfunction eventsContext(context) {\n switch (context.chatId.kind) {\n case \"direct_chat\":\n return {\n Direct: principalStringToBytes(context.chatId.userId),\n };\n case \"group_chat\":\n return {\n Group: [\n principalStringToBytes(context.chatId.groupId),\n context.threadRootMessageIndex ?? null,\n ],\n };\n case \"channel\":\n return {\n Channel: [\n principalStringToBytes(context.chatId.communityId),\n toBigInt32(context.chatId.channelId),\n context.threadRootMessageIndex ?? null,\n ],\n };\n }\n}\nfunction eventsArgsInner(args) {\n switch (args.kind) {\n case \"page\":\n return {\n Page: {\n max_messages: MAX_MESSAGES,\n max_events: MAX_EVENTS,\n ascending: args.ascending,\n start_index: args.startIndex,\n },\n };\n case \"by_index\":\n return {\n ByIndex: {\n events: args.events,\n },\n };\n case \"window\": {\n return {\n Window: {\n mid_point: args.midPoint,\n max_messages: MAX_MESSAGES,\n max_events: MAX_EVENTS,\n },\n };\n }\n }\n}\nexport async function chatEventsBatchResponse(principal, requests, value) {\n const responses = [];\n for (let i = 0; i < requests.length; i++) {\n const response = value.Success.responses[i];\n const args = requests[i];\n if (response === \"NotFound\") {\n responses.push({\n kind: \"not_found\",\n });\n }\n else if (\"Success\" in response) {\n const error = await ensureReplicaIsUpToDate(principal, args.context.chatId, response.Success.chat_last_updated, true);\n responses.push(error ?? {\n kind: \"success\",\n result: eventsSuccessResponse(response.Success),\n });\n }\n else if (\"ReplicaNotUpToDate\" in response) {\n responses.push({\n kind: \"replica_not_up_to_date\",\n replicaTimestamp: response.ReplicaNotUpToDate,\n clientTimestamp: args.latestKnownUpdate ?? BigInt(-1),\n });\n }\n else {\n responses.push({\n kind: \"internal_error\",\n error: response.InternalError,\n });\n }\n }\n return {\n responses,\n timestamp: value.Success.timestamp,\n };\n}\nexport function joinChannelResponse(value, communityId) {\n if (typeof value === \"object\") {\n if (\"Success\" in value) {\n return { kind: \"success\", group: communityChannelSummary(value.Success, communityId) };\n }\n else if (\"AlreadyInChannel\" in value) {\n return {\n kind: \"success\",\n group: communityChannelSummary(value.AlreadyInChannel, communityId),\n };\n }\n else if (\"SuccessJoinedCommunity\" in value) {\n return {\n kind: \"success_joined_community\",\n community: communitySummary(value.SuccessJoinedCommunity),\n };\n }\n else if (\"GateCheckFailed\" in value) {\n return {\n kind: \"gate_check_failed\",\n reason: gateCheckFailedReason(value.GateCheckFailed),\n };\n }\n }\n if (value === \"UserBlocked\") {\n return CommonResponses.userBlocked();\n }\n else {\n console.warn(\"Join group failed with: \", value);\n return CommonResponses.failure();\n }\n}\nexport function registerUserResponse(value) {\n if (value === \"UsernameInvalid\") {\n return { kind: \"username_invalid\" };\n }\n if (value === \"AlreadyRegistered\") {\n return { kind: \"already_registered\" };\n }\n if (value === \"UserLimitReached\") {\n return { kind: \"user_limit_reached\" };\n }\n if (value === \"RegistrationInProgress\") {\n return { kind: \"registration_in_progress\" };\n }\n if (value === \"CyclesBalanceTooLow\") {\n return { kind: \"cycles_balance_too_low\" };\n }\n if (value === \"ReferralCodeInvalid\") {\n return { kind: \"referral_code_invalid\" };\n }\n if (value === \"ReferralCodeAlreadyClaimed\") {\n return { kind: \"referral_code_already_claimed\" };\n }\n if (value === \"ReferralCodeExpired\") {\n return { kind: \"referral_code_expired\" };\n }\n if (\"Success\" in value) {\n return {\n kind: \"success\",\n userId: principalBytesToString(value.Success.user_id),\n icpAccount: bytesToHexString(value.Success.icp_account),\n };\n }\n if (\"UsernameTooShort\" in value) {\n return { kind: \"username_too_short\" };\n }\n if (\"UsernameTooLong\" in value) {\n return { kind: \"username_too_long\" };\n }\n if (\"NotSupported\" in value) {\n return { kind: \"not_supported\" };\n }\n if (\"InternalError\" in value) {\n return { kind: \"internal_error\" };\n }\n if (\"PublicKeyInvalid\" in value) {\n return { kind: \"public_key_invalid\" };\n }\n if (\"Error\" in value) {\n return ocError(value.Error);\n }\n throw new UnsupportedValueError(\"Unexpected ApiRegisterUserResponse type received\", value);\n}\nexport function inviteUsersResponse(value) {\n if (value === \"Success\") {\n return true;\n }\n else {\n console.warn(\"InviteUsersResponse was unsuccessful\", value);\n return false;\n }\n}\nexport function joinCommunityResponse(value) {\n if (typeof value === \"object\") {\n if (\"Success\" in value) {\n return { kind: \"success\", community: communitySummary(value.Success) };\n }\n else if (\"AlreadyInCommunity\" in value) {\n return { kind: \"success\", community: communitySummary(value.AlreadyInCommunity) };\n }\n else if (\"GateCheckFailed\" in value) {\n return {\n kind: \"gate_check_failed\",\n reason: gateCheckFailedReason(value.GateCheckFailed),\n };\n }\n }\n console.warn(\"Join community failed with: \", value);\n return CommonResponses.failure();\n}\nexport function apiVerifiedCredentialArgs(domain) {\n return {\n user_ii_principal: principalStringToBytes(domain.userIIPrincipal),\n ii_origin: domain.iiOrigin,\n credential_jwts: domain.credentialJwts,\n credential_jwt: domain.credentialJwts[0],\n };\n}\nexport function withdrawFromIcpSwapResponse(value) {\n console.log(\"Withdraw from ICPSwap response\", value);\n return value === \"Success\";\n}\n","import { MsgpackCanisterAgent } from \"../canisterAgent/msgpack\";\nimport { accessTokenResponse, apiAccessTokenType, apiVerifiedCredentialArgs, chatEventsArgs, chatEventsBatchResponse, groupAndCommunitySummaryUpdates, inviteUsersResponse, joinChannelResponse, joinCommunityResponse, registerUserResponse, withdrawFromIcpSwapResponse, } from \"./mappers\";\nimport { joinGroupResponse, apiExternalBotPermissions } from \"../common/chatMappersV2\";\nimport { toBigInt32, MAX_MISSING, textToCode, UnsupportedValueError } from \"openchat-shared\";\nimport { mapOptional, maybePrincipalStringToBytes, principalStringToBytes, } from \"../../utils/mapping\";\nimport { getCachedEvents, getCachedEventsByIndex, getCachedEventsWindowByMessageIndex, setCachedEvents, setCachePrimerTimestamp, } from \"../../utils/caching\";\nimport { BotInstallationLocation as ApiBotInstallationLocation, LocalUserIndexAccessTokenV2Args, LocalUserIndexAccessTokenV2Response, LocalUserIndexChatEventsArgs, LocalUserIndexChatEventsResponse, LocalUserIndexGroupAndCommunitySummaryUpdatesArgs, LocalUserIndexGroupAndCommunitySummaryUpdatesResponse, LocalUserIndexInstallBotArgs, LocalUserIndexInstallBotResponse, LocalUserIndexInviteUsersToChannelArgs, LocalUserIndexInviteUsersToChannelResponse, LocalUserIndexInviteUsersToCommunityArgs, LocalUserIndexInviteUsersToCommunityResponse, LocalUserIndexInviteUsersToGroupArgs, LocalUserIndexInviteUsersToGroupResponse, LocalUserIndexJoinChannelArgs, LocalUserIndexJoinChannelResponse, LocalUserIndexJoinCommunityArgs, LocalUserIndexJoinCommunityResponse, LocalUserIndexJoinGroupArgs, LocalUserIndexJoinGroupResponse, LocalUserIndexRegisterUserArgs, LocalUserIndexRegisterUserResponse, LocalUserIndexUninstallBotArgs, LocalUserIndexUninstallBotResponse, LocalUserIndexWithdrawFromIcpswapArgs, LocalUserIndexWithdrawFromIcpswapResponse, } from \"../../typebox\";\nexport class LocalUserIndexClient extends MsgpackCanisterAgent {\n constructor(identity, agent, canisterId, db) {\n super(identity, agent, canisterId, \"LocalUserIndex\");\n this.db = db;\n }\n groupAndCommunitySummaryUpdates(requests) {\n const args = {\n requests: requests.map((r) => ({\n canister_id: principalStringToBytes(r.canisterId),\n is_community: r.isCommunity,\n invite_code: r.inviteCode,\n updates_since: r.updatesSince,\n })),\n };\n return this.executeMsgpackQuery(\"group_and_community_summary_updates\", args, groupAndCommunitySummaryUpdates, LocalUserIndexGroupAndCommunitySummaryUpdatesArgs, LocalUserIndexGroupAndCommunitySummaryUpdatesResponse);\n }\n async chatEvents(requests, cachePrimer = false) {\n // The responses must be ordered such that the response at index i matches the request at index i\n const responses = [];\n const partialCachedResults = [];\n const requestsToBackend = [];\n for (let i = 0; i < requests.length; i++) {\n const request = requests[i];\n const [cached, missing] = await this.getEventsFromCache(request.context, request.args);\n if (missing.size === 0) {\n // Insert the response into the index matching the request\n responses[i] = {\n kind: \"success\",\n result: cached,\n };\n if (cachePrimer && request.latestKnownUpdate !== undefined) {\n setCachePrimerTimestamp(this.db, request.context.chatId, request.latestKnownUpdate);\n }\n }\n else if (missing.size > MAX_MISSING) {\n requestsToBackend.push(request);\n }\n else {\n partialCachedResults[i] = cached.events;\n requestsToBackend.push({\n context: request.context,\n args: {\n kind: \"by_index\",\n events: [...missing],\n },\n latestKnownUpdate: request.latestKnownUpdate,\n });\n }\n }\n if (requestsToBackend.length > 0) {\n const batchResponse = await this.getChatEventsFromBackend(requestsToBackend);\n for (let i = 0; i < batchResponse.responses.length; i++) {\n const request = requestsToBackend[i];\n const response = batchResponse.responses[i];\n if (response.kind === \"success\") {\n setCachedEvents(this.db, request.context.chatId, response.result, request.context.threadRootMessageIndex);\n if (cachePrimer) {\n setCachePrimerTimestamp(this.db, request.context.chatId, batchResponse.timestamp);\n }\n }\n // Insert the response into the first empty index, this will match the index of the request\n for (let j = i; j <= responses.length; j++) {\n if (responses[j] === undefined) {\n if (response.kind === \"success\") {\n const fromCache = partialCachedResults[j];\n if (fromCache !== undefined) {\n response.result.events = [\n ...response.result.events,\n ...fromCache,\n ].sort((a, b) => a.index - b.index);\n }\n }\n responses[j] = response;\n break;\n }\n }\n }\n }\n return responses;\n }\n async getEventsFromCache(context, args) {\n if (args.kind === \"page\") {\n return await getCachedEvents(this.db, args.eventIndexRange, context, args.startIndex, args.ascending, undefined, undefined, 1);\n }\n if (args.kind === \"window\") {\n const [cached, missing, _] = await getCachedEventsWindowByMessageIndex(this.db, args.eventIndexRange, context, args.midPoint, undefined, undefined, 1);\n return [cached, missing];\n }\n if (args.kind === \"by_index\") {\n return await getCachedEventsByIndex(this.db, args.events, context);\n }\n throw new UnsupportedValueError(\"Unexpected ChatEventsArgs type\", args);\n }\n getChatEventsFromBackend(requests) {\n const args = {\n requests: requests.map(chatEventsArgs),\n };\n return this.executeMsgpackQuery(\"chat_events\", args, (resp) => chatEventsBatchResponse(this.principal, requests, resp), LocalUserIndexChatEventsArgs, LocalUserIndexChatEventsResponse);\n }\n registerUser(username, referralCode) {\n return this.executeMsgpackUpdate(\"register_user\", {\n username,\n referral_code: referralCode,\n public_key: new Uint8Array(this.identity.getPublicKey().toDer()),\n }, registerUserResponse, LocalUserIndexRegisterUserArgs, LocalUserIndexRegisterUserResponse);\n }\n joinCommunity(communityId, inviteCode, credentialArgs, referredBy) {\n return this.executeMsgpackUpdate(\"join_community\", {\n community_id: principalStringToBytes(communityId),\n invite_code: mapOptional(inviteCode, textToCode),\n verified_credential_args: mapOptional(credentialArgs, apiVerifiedCredentialArgs),\n referred_by: maybePrincipalStringToBytes(referredBy),\n }, joinCommunityResponse, LocalUserIndexJoinCommunityArgs, LocalUserIndexJoinCommunityResponse);\n }\n joinGroup(chatId, inviteCode, credentialArgs) {\n return this.executeMsgpackUpdate(\"join_group\", {\n chat_id: principalStringToBytes(chatId),\n invite_code: mapOptional(inviteCode, textToCode),\n verified_credential_args: mapOptional(credentialArgs, apiVerifiedCredentialArgs),\n correlation_id: BigInt(0),\n }, joinGroupResponse, LocalUserIndexJoinGroupArgs, LocalUserIndexJoinGroupResponse);\n }\n joinChannel(id, inviteCode, credentialArgs, referredBy) {\n return this.executeMsgpackUpdate(\"join_channel\", {\n community_id: principalStringToBytes(id.communityId),\n channel_id: toBigInt32(id.channelId),\n invite_code: mapOptional(inviteCode, textToCode),\n verified_credential_args: mapOptional(credentialArgs, apiVerifiedCredentialArgs),\n referred_by: maybePrincipalStringToBytes(referredBy),\n }, (resp) => {\n return joinChannelResponse(resp, id.communityId);\n }, LocalUserIndexJoinChannelArgs, LocalUserIndexJoinChannelResponse);\n }\n inviteUsersToCommunity(communityId, userIds, callerUsername) {\n return this.executeMsgpackUpdate(\"invite_users_to_community\", {\n community_id: principalStringToBytes(communityId),\n user_ids: userIds.map(principalStringToBytes),\n caller_username: callerUsername,\n }, inviteUsersResponse, LocalUserIndexInviteUsersToCommunityArgs, LocalUserIndexInviteUsersToCommunityResponse);\n }\n inviteUsersToGroup(chatId, userIds, callerUsername) {\n return this.executeMsgpackUpdate(\"invite_users_to_group\", {\n group_id: principalStringToBytes(chatId),\n user_ids: userIds.map(principalStringToBytes),\n caller_username: callerUsername,\n correlation_id: BigInt(0),\n }, inviteUsersResponse, LocalUserIndexInviteUsersToGroupArgs, LocalUserIndexInviteUsersToGroupResponse);\n }\n inviteUsersToChannel(communityId, channelId, userIds, callerUsername) {\n return this.executeMsgpackUpdate(\"invite_users_to_channel\", {\n community_id: principalStringToBytes(communityId),\n channel_id: toBigInt32(channelId),\n user_ids: userIds.map(principalStringToBytes),\n caller_username: callerUsername,\n }, inviteUsersResponse, LocalUserIndexInviteUsersToChannelArgs, LocalUserIndexInviteUsersToChannelResponse);\n }\n #apiBotInstallationLocation(domain) {\n switch (domain.kind) {\n case \"community\":\n return { Community: principalStringToBytes(domain.communityId) };\n case \"group_chat\":\n return { Group: principalStringToBytes(domain.groupId) };\n case \"direct_chat\":\n return { User: principalStringToBytes(domain.userId) };\n }\n }\n installBot(location, botId, grantedPermissions) {\n return this.executeMsgpackUpdate(\"install_bot\", {\n location: this.#apiBotInstallationLocation(location),\n bot_id: principalStringToBytes(botId),\n granted_permissions: apiExternalBotPermissions(grantedPermissions),\n }, (resp) => {\n console.log(\"Install bot response: \", resp);\n return resp === \"Success\";\n }, LocalUserIndexInstallBotArgs, LocalUserIndexInstallBotResponse);\n }\n uninstallBot(location, botId) {\n return this.executeMsgpackUpdate(\"uninstall_bot\", {\n location: this.#apiBotInstallationLocation(location),\n bot_id: principalStringToBytes(botId),\n }, (resp) => {\n if (resp !== \"Success\") {\n console.log(\"Error uninstalling bot: \", resp);\n }\n return resp === \"Success\";\n }, LocalUserIndexUninstallBotArgs, LocalUserIndexUninstallBotResponse);\n }\n getAccessToken(accessType) {\n return this.executeMsgpackQuery(\"access_token_v2\", apiAccessTokenType(accessType), accessTokenResponse, LocalUserIndexAccessTokenV2Args, LocalUserIndexAccessTokenV2Response);\n }\n withdrawFromIcpSwap(userId, swapId, inputToken, amount, fee) {\n return this.executeMsgpackUpdate(\"withdraw_from_icpswap\", {\n user_id: principalStringToBytes(userId),\n swap_id: swapId,\n input_token: inputToken,\n amount,\n fee,\n }, withdrawFromIcpSwapResponse, LocalUserIndexWithdrawFromIcpswapArgs, LocalUserIndexWithdrawFromIcpswapResponse);\n }\n}\n","import { MsgpackCanisterAgent } from \"../canisterAgent/msgpack\";\nimport { subscriptionExistsResponse } from \"./mappers\";\nimport { toVoid } from \"../../utils/mapping\";\nimport { NotificationsIndexPushSubscriptionArgs, NotificationsIndexPushSubscriptionResponse, NotificationsIndexRemoveSubscriptionArgs, NotificationsIndexRemoveSubscriptionResponse, NotificationsIndexSubscriptionExistsArgs, NotificationsIndexSubscriptionExistsResponse, } from \"../../typebox\";\nexport class NotificationsClient extends MsgpackCanisterAgent {\n constructor(identity, agent, canisterId) {\n super(identity, agent, canisterId, \"Notifications\");\n }\n subscriptionExists(p256dh_key) {\n return this.executeMsgpackQuery(\"subscription_exists\", {\n p256dh_key,\n }, subscriptionExistsResponse, NotificationsIndexSubscriptionExistsArgs, NotificationsIndexSubscriptionExistsResponse);\n }\n pushSubscription(subscription) {\n const request = {\n subscription: {\n endpoint: subscription.endpoint,\n keys: {\n auth: subscription.keys[\"auth\"],\n p256dh: subscription.keys[\"p256dh\"],\n },\n },\n };\n return this.executeMsgpackUpdate(\"push_subscription\", request, toVoid, NotificationsIndexPushSubscriptionArgs, NotificationsIndexPushSubscriptionResponse);\n }\n removeSubscription(subscription) {\n return this.executeMsgpackUpdate(\"remove_subscription\", {\n p256dh_key: subscription.keys[\"p256dh\"],\n }, toVoid, NotificationsIndexRemoveSubscriptionArgs, NotificationsIndexRemoveSubscriptionResponse);\n }\n}\n","import { UnsupportedValueError, } from \"openchat-shared\";\nimport { CommonResponses } from \"openchat-shared\";\nimport { hexStringToBytes, mapOptional, principalStringToBytes } from \"../../utils/mapping\";\nexport function submitProposalResponse(value) {\n if (value === \"Success\") {\n return { kind: \"success\" };\n }\n if (value === \"GovernanceCanisterNotSupported\") {\n return { kind: \"governance_canister_not_supported\" };\n }\n if (typeof value === \"object\") {\n if (\"Retrying\" in value) {\n return { kind: \"retrying\", error: value.Retrying };\n }\n if (\"InsufficientPayment\" in value) {\n return { kind: \"insufficient_payment\" };\n }\n if (\"PaymentFailed\" in value) {\n return { kind: \"transfer_failed\", error: value.PaymentFailed };\n }\n if (\"InternalError\" in value) {\n return { kind: \"internal_error\", error: value.InternalError };\n }\n }\n throw new UnsupportedValueError(\"Unexpected ApiSubmitProposalResponse type received\", value);\n}\nexport function stakeNeuronForSubmittingProposalsResponse(value) {\n if (typeof value === \"object\" && \"Success\" in value) {\n return CommonResponses.success();\n }\n console.warn(\"stakeNeuronForSubmittingProposals failed with: \", value);\n return CommonResponses.failure();\n}\nexport function topUpNeuronResponse(value) {\n if (typeof value === \"object\" && \"Success\" in value) {\n return CommonResponses.success();\n }\n console.warn(\"topUpNeuron failed with: \", value);\n return CommonResponses.failure();\n}\nexport function proposalToSubmit(proposal) {\n return {\n title: proposal.title,\n url: proposal.url ?? \"\",\n summary: proposal.summary,\n action: proposalAction(proposal.action),\n };\n}\nfunction proposalAction(action) {\n switch (action.kind) {\n case \"motion\":\n return \"Motion\";\n case \"transfer_sns_funds\":\n return {\n TransferSnsTreasuryFunds: {\n to: {\n owner: principalStringToBytes(action.recipient.owner),\n subaccount: mapOptional(action.recipient.subaccount, (s) => [...hexStringToBytes(s)]),\n },\n amount: action.amount,\n memo: undefined,\n treasury: action.treasury,\n },\n };\n case \"advance_sns_target_version\":\n return \"AdvanceSnsTargetVersion\";\n case \"execute_generic_nervous_system_function\":\n return {\n ExecuteGenericNervousSystemFunction: {\n function_id: action.functionId,\n payload: action.payload,\n },\n };\n }\n}\n","import { MsgpackCanisterAgent } from \"../canisterAgent/msgpack\";\nimport { nowNanos, } from \"openchat-shared\";\nimport { proposalToSubmit, stakeNeuronForSubmittingProposalsResponse, submitProposalResponse, topUpNeuronResponse, } from \"./mappers\";\nimport { principalStringToBytes } from \"../../utils/mapping\";\nimport { ProposalsBotStakeNeuronForSubmittingProposalsArgs, ProposalsBotStakeNeuronForSubmittingProposalsResponse, ProposalsBotSubmitProposalArgs, ProposalsBotSubmitProposalResponse, ProposalsBotTopUpNeuronArgs, ProposalsBotTopUpNeuronResponse, } from \"../../typebox\";\nimport { principalToIcrcAccount } from \"../common/chatMappersV2\";\nexport class ProposalsBotClient extends MsgpackCanisterAgent {\n constructor(identity, agent, canisterId) {\n super(identity, agent, canisterId, \"ProposalsBot\");\n }\n submitProposal(userId, governanceCanisterId, proposal, ledger, token, proposalRejectionFee, transactionFee) {\n const args = {\n governance_canister_id: principalStringToBytes(governanceCanisterId),\n proposal: proposalToSubmit(proposal),\n transaction: {\n ledger: principalStringToBytes(ledger),\n token_symbol: token,\n amount: proposalRejectionFee,\n from: principalToIcrcAccount(userId),\n to: principalToIcrcAccount(this.canisterId),\n fee: transactionFee,\n memo: undefined,\n created: nowNanos(),\n },\n };\n return this.executeMsgpackUpdate(\"submit_proposal\", args, submitProposalResponse, ProposalsBotSubmitProposalArgs, ProposalsBotSubmitProposalResponse);\n }\n stakeNeuronForSubmittingProposals(governanceCanisterId, stake) {\n const args = {\n governance_canister_id: principalStringToBytes(governanceCanisterId),\n stake,\n };\n return this.executeMsgpackUpdate(\"stake_neuron_for_submitting_proposals\", args, stakeNeuronForSubmittingProposalsResponse, ProposalsBotStakeNeuronForSubmittingProposalsArgs, ProposalsBotStakeNeuronForSubmittingProposalsResponse);\n }\n topUpNeuron(governanceCanisterId, amount) {\n const args = {\n governance_canister_id: principalStringToBytes(governanceCanisterId),\n amount,\n };\n return this.executeMsgpackUpdate(\"top_up_neuron\", args, topUpNeuronResponse, ProposalsBotTopUpNeuronArgs, ProposalsBotTopUpNeuronResponse);\n }\n}\n","export function nowNanos() {\n return BigInt(Date.now()) * BigInt(1_000_000);\n}\n","import { principalBytesToString } from \"../../utils/mapping\";\nexport function lastOnlineResponse(value) {\n const now = Date.now();\n return value.Success.reduce((res, next) => {\n res[principalBytesToString(next.user_id)] =\n now - Number(next.duration_since_last_online);\n return res;\n }, {});\n}\nexport function markAsOnlineResponse(value) {\n if (typeof value === \"object\" && \"SuccessV2\" in value) {\n return value.SuccessV2.minutes_online;\n }\n return 0;\n}\n","import { MsgpackCanisterAgent } from \"../canisterAgent/msgpack\";\nimport { principalStringToBytes } from \"../../utils/mapping\";\nimport { lastOnlineResponse, markAsOnlineResponse } from \"./mappers\";\nimport { Empty, OnlineUsersLastOnlineArgs, OnlineUsersLastOnlineResponse, OnlineUsersMarkAsOnlineResponse, OnlineUsersMinutesOnlineArgs, OnlineUsersMinutesOnlineResponse, } from \"../../typebox\";\nexport class OnlineClient extends MsgpackCanisterAgent {\n constructor(identity, agent, canisterId) {\n super(identity, agent, canisterId, \"OnlineUsers\");\n }\n lastOnline(userIds) {\n const args = {\n user_ids: userIds.map(principalStringToBytes),\n };\n return this.executeMsgpackQuery(\"last_online\", args, lastOnlineResponse, OnlineUsersLastOnlineArgs, OnlineUsersLastOnlineResponse);\n }\n markAsOnline() {\n return this.executeMsgpackUpdate(\"mark_as_online\", {}, markAsOnlineResponse, Empty, OnlineUsersMarkAsOnlineResponse);\n }\n minutesOnline(year, month) {\n return this.executeMsgpackQuery(\"minutes_online\", { year, month }, (resp) => resp.Success, OnlineUsersMinutesOnlineArgs, OnlineUsersMinutesOnlineResponse);\n }\n}\n","export const idlFactory = ({ IDL }) => {\n const Account = IDL.Record({\n 'owner': IDL.Principal,\n 'subaccount': IDL.Opt(IDL.Vec(IDL.Nat8)),\n });\n return IDL.Service({\n 'icrc1_balance_of': IDL.Func([Account], [IDL.Nat], ['query']),\n });\n};\nexport const init = ({ IDL }) => { return []; };\n","import { idlFactory } from \"./candid/idl\";\nimport { CandidCanisterAgent } from \"../canisterAgent/candid\";\nimport { Principal } from \"@dfinity/principal\";\nexport class LedgerClient extends CandidCanisterAgent {\n constructor(identity, agent, canisterId) {\n super(identity, agent, canisterId, idlFactory, \"Ledger\");\n }\n accountBalance(principal) {\n return this.handleQueryResponse(() => this.service.icrc1_balance_of({ owner: Principal.fromText(principal), subaccount: [] }), (balance) => {\n return balance;\n });\n }\n}\n","export const idlFactory = ({ IDL }) => {\n const Value = IDL.Rec();\n const UpgradeArg = IDL.Record({\n 'ledger_id': IDL.Opt(IDL.Principal),\n 'retrieve_blocks_from_ledger_interval_seconds': IDL.Opt(IDL.Nat64),\n });\n const InitArg = IDL.Record({\n 'ledger_id': IDL.Principal,\n 'retrieve_blocks_from_ledger_interval_seconds': IDL.Opt(IDL.Nat64),\n });\n const IndexArg = IDL.Variant({ 'Upgrade': UpgradeArg, 'Init': InitArg });\n const BlockIndex = IDL.Nat;\n const SubAccount = IDL.Vec(IDL.Nat8);\n const Account = IDL.Record({\n 'owner': IDL.Principal,\n 'subaccount': IDL.Opt(SubAccount),\n });\n const GetAccountTransactionsArgs = IDL.Record({\n 'max_results': IDL.Nat,\n 'start': IDL.Opt(BlockIndex),\n 'account': Account,\n });\n const Tokens = IDL.Nat;\n const Burn = IDL.Record({\n 'from': Account,\n 'memo': IDL.Opt(IDL.Vec(IDL.Nat8)),\n 'created_at_time': IDL.Opt(IDL.Nat64),\n 'amount': IDL.Nat,\n 'spender': IDL.Opt(Account),\n });\n const Mint = IDL.Record({\n 'to': Account,\n 'memo': IDL.Opt(IDL.Vec(IDL.Nat8)),\n 'created_at_time': IDL.Opt(IDL.Nat64),\n 'amount': IDL.Nat,\n });\n const Approve = IDL.Record({\n 'fee': IDL.Opt(IDL.Nat),\n 'from': Account,\n 'memo': IDL.Opt(IDL.Vec(IDL.Nat8)),\n 'created_at_time': IDL.Opt(IDL.Nat64),\n 'amount': IDL.Nat,\n 'expected_allowance': IDL.Opt(IDL.Nat),\n 'expires_at': IDL.Opt(IDL.Nat64),\n 'spender': Account,\n });\n const Transfer = IDL.Record({\n 'to': Account,\n 'fee': IDL.Opt(IDL.Nat),\n 'from': Account,\n 'memo': IDL.Opt(IDL.Vec(IDL.Nat8)),\n 'created_at_time': IDL.Opt(IDL.Nat64),\n 'amount': IDL.Nat,\n 'spender': IDL.Opt(Account),\n });\n const Transaction = IDL.Record({\n 'burn': IDL.Opt(Burn),\n 'kind': IDL.Text,\n 'mint': IDL.Opt(Mint),\n 'approve': IDL.Opt(Approve),\n 'timestamp': IDL.Nat64,\n 'transfer': IDL.Opt(Transfer),\n });\n const TransactionWithId = IDL.Record({\n 'id': BlockIndex,\n 'transaction': Transaction,\n });\n const GetTransactions = IDL.Record({\n 'balance': Tokens,\n 'transactions': IDL.Vec(TransactionWithId),\n 'oldest_tx_id': IDL.Opt(BlockIndex),\n });\n const GetTransactionsErr = IDL.Record({ 'message': IDL.Text });\n const GetTransactionsResult = IDL.Variant({\n 'Ok': GetTransactions,\n 'Err': GetTransactionsErr,\n });\n const GetBlocksRequest = IDL.Record({\n 'start': IDL.Nat,\n 'length': IDL.Nat,\n });\n const Map = IDL.Vec(IDL.Tuple(IDL.Text, Value));\n Value.fill(IDL.Variant({\n 'Int': IDL.Int,\n 'Map': Map,\n 'Nat': IDL.Nat,\n 'Nat64': IDL.Nat64,\n 'Blob': IDL.Vec(IDL.Nat8),\n 'Text': IDL.Text,\n 'Array': IDL.Vec(Value),\n }));\n const Block = Value;\n const GetBlocksResponse = IDL.Record({\n 'blocks': IDL.Vec(Block),\n 'chain_length': IDL.Nat64,\n });\n const FeeCollectorRanges = IDL.Record({\n 'ranges': IDL.Vec(IDL.Tuple(Account, IDL.Vec(IDL.Tuple(BlockIndex, BlockIndex)))),\n });\n const ListSubaccountsArgs = IDL.Record({\n 'owner': IDL.Principal,\n 'start': IDL.Opt(SubAccount),\n });\n const Status = IDL.Record({ 'num_blocks_synced': BlockIndex });\n return IDL.Service({\n 'get_account_transactions': IDL.Func([GetAccountTransactionsArgs], [GetTransactionsResult], ['query']),\n 'get_blocks': IDL.Func([GetBlocksRequest], [GetBlocksResponse], ['query']),\n 'get_fee_collectors_ranges': IDL.Func([], [FeeCollectorRanges], ['query']),\n 'icrc1_balance_of': IDL.Func([Account], [Tokens], ['query']),\n 'ledger_id': IDL.Func([], [IDL.Principal], ['query']),\n 'list_subaccounts': IDL.Func([ListSubaccountsArgs], [IDL.Vec(SubAccount)], ['query']),\n 'status': IDL.Func([], [Status], ['query']),\n });\n};\nexport const init = ({ IDL }) => {\n const UpgradeArg = IDL.Record({\n 'ledger_id': IDL.Opt(IDL.Principal),\n 'retrieve_blocks_from_ledger_interval_seconds': IDL.Opt(IDL.Nat64),\n });\n const InitArg = IDL.Record({\n 'ledger_id': IDL.Principal,\n 'retrieve_blocks_from_ledger_interval_seconds': IDL.Opt(IDL.Nat64),\n });\n const IndexArg = IDL.Variant({ 'Upgrade': UpgradeArg, 'Init': InitArg });\n return [IDL.Opt(IndexArg)];\n};\n","import { identity, optional } from \"../../utils/mapping\";\nimport { CommonResponses, UnsupportedValueError, } from \"openchat-shared\";\nexport function accountTransactions(candid) {\n if (\"Err\" in candid) {\n return CommonResponses.failure();\n }\n if (\"Ok\" in candid) {\n return getTransactions(candid.Ok);\n }\n throw new UnsupportedValueError(\"Unknown ApiGetTransactionsResult type\", candid);\n}\nfunction getTransactions(candid) {\n return {\n kind: \"success\",\n transactions: candid.transactions.map(transaction),\n oldestTransactionId: optional(candid.oldest_tx_id, identity),\n };\n}\nfunction nanosToDate(n) {\n return new Date(Number(n / 1000000n));\n}\nfunction transaction(candid) {\n // the candid types are quite fuzzy here - the old \"product type when it should be sum type\" thing\n if (candid.transaction.burn[0] !== undefined) {\n const burn = candid.transaction.burn[0];\n return {\n id: candid.id,\n kind: \"burn\",\n timestamp: nanosToDate(candid.transaction.timestamp),\n memo: optional(burn.memo, memo),\n createdAt: optional(burn.created_at_time, nanosToDate),\n amount: burn.amount,\n from: account(burn.from),\n spender: optional(burn.spender, account),\n };\n }\n if (candid.transaction.mint[0] !== undefined) {\n const mint = candid.transaction.mint[0];\n return {\n id: candid.id,\n kind: \"mint\",\n timestamp: nanosToDate(candid.transaction.timestamp),\n memo: optional(mint.memo, memo),\n createdAt: optional(mint.created_at_time, nanosToDate),\n amount: mint.amount,\n to: account(mint.to),\n };\n }\n if (candid.transaction.approve[0] !== undefined) {\n const approve = candid.transaction.approve[0];\n return {\n id: candid.id,\n kind: \"approve\",\n timestamp: nanosToDate(candid.transaction.timestamp),\n memo: optional(approve.memo, memo),\n createdAt: optional(approve.created_at_time, nanosToDate),\n amount: approve.amount,\n fee: optional(approve.fee, identity),\n from: account(approve.from),\n expectedAllowance: optional(approve.expected_allowance, identity),\n expiredAt: optional(approve.expires_at, identity),\n spender: account(approve.spender),\n };\n }\n if (candid.transaction.transfer[0] !== undefined) {\n const transfer = candid.transaction.transfer[0];\n return {\n id: candid.id,\n kind: \"transfer\",\n timestamp: nanosToDate(candid.transaction.timestamp),\n memo: optional(transfer.memo, memo),\n createdAt: optional(transfer.created_at_time, nanosToDate),\n amount: transfer.amount,\n fee: optional(transfer.fee, identity),\n to: account(transfer.to),\n from: account(transfer.from),\n spender: optional(transfer.spender, account),\n };\n }\n throw new Error(`Unexpected transaction type received: ${candid.transaction}`);\n}\nfunction memo(candid) {\n return [...candid].map((n) => String.fromCharCode(n)).join(\"\");\n}\nfunction account(candid) {\n return candid.owner.toString();\n}\n","export function apiOptional(mapper, domain) {\n return domain !== undefined ? [mapper(domain)] : [];\n}\nexport function proposalVote(vote) {\n if (vote === 1)\n return true;\n if (vote === 2)\n return false;\n return undefined;\n}\nexport function apiProposalVote(vote) {\n return vote ? 1 : 2;\n}\n","import { idlFactory } from \"./candid/idl\";\nimport { CandidCanisterAgent } from \"../canisterAgent/candid\";\nimport { Principal } from \"@dfinity/principal\";\nimport { accountTransactions } from \"./mappers\";\nimport { apiOptional } from \"../common/chatMappers\";\nimport { identity } from \"../../utils/mapping\";\nexport class LedgerIndexClient extends CandidCanisterAgent {\n constructor(identity, agent, canisterId) {\n super(identity, agent, canisterId, idlFactory, \"LedgerIndex\");\n }\n getAccountTransactions(principal, fromId) {\n return this.handleQueryResponse(() => this.service.get_account_transactions({\n max_results: 100n,\n start: apiOptional(identity, fromId),\n account: { owner: Principal.fromText(principal), subaccount: [] },\n }), accountTransactions);\n }\n}\n// Here are some fake transactions that can be used for testing ...\n// function nanosToDate(n: bigint): Date {\n// return new Date(Number(n / 1_000_000n));\n// }\n// const fake: AccountTransactionResult = {\n// kind: \"success\",\n// transactions: [\n// {\n// id: 138564n,\n// kind: \"transfer\",\n// timestamp: nanosToDate(1697552025392673986n),\n// memo: \"OC_MSG\",\n// createdAt: nanosToDate(1697552019815000000n),\n// amount: 100000n,\n// fee: 100000n,\n// to: \"cgpjn-omaaa-aaaaa-qaakq-cai\",\n// from: \"cpmcr-yeaaa-aaaaa-qaala-cai\",\n// },\n// {\n// id: 128503n,\n// kind: \"transfer\",\n// timestamp: nanosToDate(1696327482080010244n),\n// createdAt: nanosToDate(1696327473845000000n),\n// amount: 50000000n,\n// fee: 100000n,\n// to: \"cgpjn-omaaa-aaaaa-qaakq-cai\",\n// from: \"cpmcr-yeaaa-aaaaa-qaala-cai\",\n// },\n// {\n// id: 127837n,\n// kind: \"transfer\",\n// timestamp: nanosToDate(1696265754013069897n),\n// createdAt: nanosToDate(1696265749487000000n),\n// amount: 100000000n,\n// fee: 100000n,\n// to: \"cgpjn-omaaa-aaaaa-qaakq-cai\",\n// from: \"cpmcr-yeaaa-aaaaa-qaala-cai\",\n// },\n// {\n// id: 125464n,\n// kind: \"transfer\",\n// timestamp: nanosToDate(1695739529582317081n),\n// createdAt: nanosToDate(1695739525038085446n),\n// amount: 176899063n,\n// fee: 100000n,\n// to: \"cpmcr-yeaaa-aaaaa-qaala-cai\",\n// from: \"cgpjn-omaaa-aaaaa-qaakq-cai\",\n// },\n// {\n// id: 125449n,\n// kind: \"transfer\",\n// timestamp: nanosToDate(1695737069245451916n),\n// createdAt: nanosToDate(1695737065548632757n),\n// amount: 7075963n,\n// fee: 100000n,\n// to: \"cpmcr-yeaaa-aaaaa-qaala-cai\",\n// from: \"cgpjn-omaaa-aaaaa-qaakq-cai\",\n// },\n// {\n// id: 125411n,\n// kind: \"transfer\",\n// timestamp: nanosToDate(1695725448930037799n),\n// createdAt: nanosToDate(1695725444893331578n),\n// amount: 70759625n,\n// fee: 100000n,\n// to: \"cpmcr-yeaaa-aaaaa-qaala-cai\",\n// from: \"cgpjn-omaaa-aaaaa-qaakq-cai\",\n// },\n// {\n// id: 138564n,\n// kind: \"transfer\",\n// timestamp: nanosToDate(1697552025392673986n),\n// memo: \"OC_MSG\",\n// createdAt: nanosToDate(1697552019815000000n),\n// amount: 100000n,\n// fee: 100000n,\n// to: \"cgpjn-omaaa-aaaaa-qaakq-cai\",\n// from: \"cpmcr-yeaaa-aaaaa-qaala-cai\",\n// },\n// {\n// id: 128503n,\n// kind: \"transfer\",\n// timestamp: nanosToDate(1696327482080010244n),\n// createdAt: nanosToDate(1696327473845000000n),\n// amount: 50000000n,\n// fee: 100000n,\n// to: \"cgpjn-omaaa-aaaaa-qaakq-cai\",\n// from: \"cpmcr-yeaaa-aaaaa-qaala-cai\",\n// },\n// {\n// id: 127837n,\n// kind: \"transfer\",\n// timestamp: nanosToDate(1696265754013069897n),\n// createdAt: nanosToDate(1696265749487000000n),\n// amount: 100000000n,\n// fee: 100000n,\n// to: \"cgpjn-omaaa-aaaaa-qaakq-cai\",\n// from: \"cpmcr-yeaaa-aaaaa-qaala-cai\",\n// },\n// {\n// id: 125464n,\n// kind: \"transfer\",\n// timestamp: nanosToDate(1695739529582317081n),\n// createdAt: nanosToDate(1695739525038085446n),\n// amount: 176899063n,\n// fee: 100000n,\n// to: \"cpmcr-yeaaa-aaaaa-qaala-cai\",\n// from: \"cgpjn-omaaa-aaaaa-qaakq-cai\",\n// },\n// {\n// id: 125449n,\n// kind: \"transfer\",\n// timestamp: nanosToDate(1695737069245451916n),\n// createdAt: nanosToDate(1695737065548632757n),\n// amount: 7075963n,\n// fee: 100000n,\n// to: \"cpmcr-yeaaa-aaaaa-qaala-cai\",\n// from: \"cgpjn-omaaa-aaaaa-qaakq-cai\",\n// },\n// {\n// id: 125411n,\n// kind: \"transfer\",\n// timestamp: nanosToDate(1695725448930037799n),\n// createdAt: nanosToDate(1695725444893331578n),\n// amount: 70759625n,\n// fee: 100000n,\n// to: \"cpmcr-yeaaa-aaaaa-qaala-cai\",\n// from: \"cgpjn-omaaa-aaaaa-qaakq-cai\",\n// },\n// ],\n// oldestTransactionId: 125411n,\n// };\n","import { mapOptional, principalBytesToString } from \"../../utils/mapping\";\nimport { toBigInt32, UnsupportedValueError } from \"openchat-shared\";\nimport { publicGroupSummary } from \"../common/publicSummaryMapperV2\";\nimport { accessGateConfig, groupSubtype, ocError } from \"../common/chatMappersV2\";\nexport function activeGroupsResponse(value) {\n return {\n timestamp: value.Success.timestamp,\n activeGroups: value.Success.active_groups.map(principalBytesToString),\n activeCommunities: value.Success.active_communities.map(principalBytesToString),\n deletedCommunities: value.Success.deleted_communities.map((d) => ({\n id: principalBytesToString(d.id),\n timestamp: d.timestamp,\n deletedBy: principalBytesToString(d.deleted_by),\n name: d.name,\n public: d.public,\n })),\n deletedGroups: value.Success.deleted_groups.map((d) => ({\n id: principalBytesToString(d.id),\n timestamp: d.timestamp,\n deletedBy: principalBytesToString(d.deleted_by),\n name: d.name,\n public: d.public,\n })),\n };\n}\nexport function recommendedGroupsResponse(value) {\n if (\"Success\" in value) {\n // TODO - we are hard-coding is_invited to false here which is something we have to live with for the moment\n return value.Success.groups.map((g) => publicGroupSummary(g, false));\n }\n throw new Error(`Unknown GroupIndex.RecommendedGroupsResponse of ${value}`);\n}\nexport function lookupChannelResponse(value) {\n if (value !== \"NotFound\" && \"Success\" in value) {\n return {\n kind: \"channel\",\n communityId: principalBytesToString(value.Success.community_id),\n channelId: Number(toBigInt32(value.Success.channel_id)),\n };\n }\n console.warn(\"ApiLookupChannelByGroupIdResponse failed with \", value);\n return undefined;\n}\nexport function exploreCommunitiesResponse(value) {\n if (value === \"InvalidTerm\" ||\n value === \"InvalidFlags\" ||\n \"TermTooShort\" in value ||\n \"TermTooLong\" in value) {\n return { kind: \"term_invalid\" };\n }\n if (\"Success\" in value) {\n return {\n kind: \"success\",\n matches: value.Success.matches.map(communityMatch),\n total: value.Success.total,\n };\n }\n if (\"Error\" in value) {\n return ocError(value.Error);\n }\n throw new UnsupportedValueError(\"Unexpected GroupIndex.ExploreCommunitiesResponse type received\", value);\n}\nexport function exploreGroupsResponse(value) {\n if (value === \"InvalidTerm\" || \"TermTooShort\" in value || \"TermTooLong\" in value) {\n return { kind: \"term_invalid\" };\n }\n if (\"Success\" in value) {\n return {\n kind: \"success\",\n matches: value.Success.matches.map(groupMatch),\n total: value.Success.total,\n };\n }\n if (\"Error\" in value) {\n return ocError(value.Error);\n }\n throw new UnsupportedValueError(\"Unexpected GroupIndex.ExploreGroupsResponse type received\", value);\n}\nexport function freezeGroupResponse(value) {\n if (value === \"ChatAlreadyFrozen\") {\n return \"chat_already_frozen\";\n }\n if (value === \"ChatNotFound\") {\n return \"chat_not_found\";\n }\n if (value === \"NotAuthorized\") {\n return \"not_authorized\";\n }\n if (\"Success\" in value) {\n return {\n event: {\n kind: \"chat_frozen\",\n frozenBy: principalBytesToString(value.Success.event.frozen_by),\n reason: value.Success.event.reason,\n },\n timestamp: value.Success.timestamp,\n index: value.Success.index,\n expiresAt: mapOptional(value.Success.expires_at, Number),\n };\n }\n if (\"InternalError\" in value) {\n return \"internal_error\";\n }\n throw new UnsupportedValueError(\"Unexpected ApiFreezeGroupResponse type received\", value);\n}\nexport function freezeCommunityResponse(value) {\n if (value === \"CommunityAlreadyFrozen\") {\n return \"community_already_frozen\";\n }\n if (value === \"CommunityNotFound\") {\n return \"community_not_found\";\n }\n if (value === \"NotAuthorized\") {\n return \"not_authorized\";\n }\n if (\"Success\" in value) {\n return \"success\";\n }\n if (\"InternalError\" in value) {\n return \"internal_error\";\n }\n throw new UnsupportedValueError(\"Unexpected ApiFreezeCommunityResponse type received\", value);\n}\nexport function unfreezeCommunityResponse(value) {\n if (value === \"CommunityNotFrozen\") {\n return \"community_not_frozen\";\n }\n if (value === \"CommunityNotFound\") {\n return \"community_not_found\";\n }\n if (value === \"NotAuthorized\") {\n return \"not_authorized\";\n }\n if (\"Success\" in value) {\n return \"success\";\n }\n if (\"InternalError\" in value || \"Error\" in value) {\n return \"internal_error\";\n }\n throw new UnsupportedValueError(\"Unexpected ApiUnfreezeCommunityResponse type received\", value);\n}\nexport function unfreezeGroupResponse(value) {\n if (value === \"ChatNotFrozen\") {\n return \"chat_not_frozen\";\n }\n if (value === \"ChatNotFound\") {\n return \"chat_not_found\";\n }\n if (value === \"NotAuthorized\") {\n return \"not_authorized\";\n }\n if (\"Success\" in value) {\n return {\n event: {\n kind: \"chat_unfrozen\",\n unfrozenBy: principalBytesToString(value.Success.event.unfrozen_by),\n },\n timestamp: value.Success.timestamp,\n index: value.Success.index,\n expiresAt: mapOptional(value.Success.expires_at, Number),\n };\n }\n if (\"InternalError\" in value || \"Error\" in value) {\n return \"internal_error\";\n }\n throw new UnsupportedValueError(\"Unexpected ApiUnfreezeGroupResponse type received\", value);\n}\nexport function deleteFrozenGroupResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n if (value === \"ChatNotFrozen\") {\n return \"chat_not_frozen\";\n }\n if (value === \"ChatNotFound\") {\n return \"chat_not_found\";\n }\n if (value === \"NotAuthorized\") {\n return \"not_authorized\";\n }\n if (\"InternalError\" in value) {\n return \"internal_error\";\n }\n throw new UnsupportedValueError(\"Unexpected ApiDeleteFrozenGroupResponse type received\", value);\n}\nexport function addHotGroupExclusionResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n if (value === \"ChatAlreadyExcluded\") {\n return \"chat_already_excluded\";\n }\n if (value === \"ChatNotFound\") {\n return \"chat_not_found\";\n }\n if (value === \"NotAuthorized\") {\n return \"not_authorized\";\n }\n if (\"InternalError\" in value || \"Error\" in value) {\n return \"internal_error\";\n }\n throw new UnsupportedValueError(\"Unexpected ApiAddHotGroupExclusionResponse type received\", value);\n}\nexport function removeHotGroupExclusionResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n if (value === \"ChatNotExcluded\") {\n return \"chat_not_excluded\";\n }\n if (value === \"ChatNotFound\") {\n return \"chat_not_found\";\n }\n if (value === \"NotAuthorized\") {\n return \"not_authorized\";\n }\n if (\"InternalError\" in value) {\n return \"internal_error\";\n }\n throw new UnsupportedValueError(\"Unexpected ApiRemoveHotGroupExclusionResponse type received\", value);\n}\nexport function setUpgradeConcurrencyResponse(value) {\n if (value === \"Success\") {\n return \"success\";\n }\n if (value === \"NotAuthorized\") {\n return \"not_authorized\";\n }\n if (\"InternalError\" in value) {\n return \"internal_error\";\n }\n throw new UnsupportedValueError(\"Unexpected ApiSetUpgradeConcurrencyResponse type received\", value);\n}\nexport function setCommunityModerationFlagsResponse(value) {\n if (value === \"Success\" || value === \"Unchanged\") {\n return \"success\";\n }\n if (value === \"CommunityNotFound\") {\n return \"community_not_found\";\n }\n if (value === \"InvalidFlags\") {\n return \"invalid_flags\";\n }\n if (value === \"NotAuthorized\") {\n return \"not_authorized\";\n }\n if (\"InternalError\" in value) {\n return \"internal_error\";\n }\n throw new UnsupportedValueError(\"Unexpected ApiSetCommunityModerationFlagsResponse type received\", value);\n}\nfunction groupMatch(value) {\n return {\n kind: \"group_match\",\n chatId: { kind: \"group_chat\", groupId: principalBytesToString(value.id) },\n name: value.name,\n description: value.description,\n subtype: mapOptional(value.subtype, groupSubtype),\n blobReference: mapOptional(value.avatar_id, (blobId) => ({\n blobId,\n canisterId: principalBytesToString(value.id),\n })),\n verified: value.verified,\n };\n}\nfunction communityMatch(value) {\n return {\n kind: \"community_match\",\n id: { kind: \"community\", communityId: principalBytesToString(value.id) },\n name: value.name,\n description: value.description,\n avatar: {\n blobReference: mapOptional(value.avatar_id, (blobId) => ({\n blobId,\n canisterId: principalBytesToString(value.id),\n })),\n },\n banner: {\n blobReference: mapOptional(value.banner_id, (blobId) => ({\n blobId,\n canisterId: principalBytesToString(value.id),\n })),\n },\n memberCount: value.member_count,\n channelCount: value.channel_count,\n gateConfig: mapOptional(value.gate_config, accessGateConfig) ?? {\n expiry: undefined,\n gate: { kind: \"no_gate\" },\n },\n flags: value.moderation_flags,\n primaryLanguage: value.primary_language === \"\" ? \"en\" : value.primary_language,\n verified: value.verified,\n };\n}\n","import { MsgpackCanisterAgent } from \"../canisterAgent/msgpack\";\nimport { addHotGroupExclusionResponse, deleteFrozenGroupResponse, freezeGroupResponse, recommendedGroupsResponse, removeHotGroupExclusionResponse, setCommunityModerationFlagsResponse, setUpgradeConcurrencyResponse, unfreezeGroupResponse, activeGroupsResponse, exploreCommunitiesResponse, lookupChannelResponse, exploreGroupsResponse, freezeCommunityResponse, unfreezeCommunityResponse, } from \"./mappers\";\nimport { GroupIndexActiveGroupsArgs, GroupIndexActiveGroupsResponse, GroupIndexAddHotGroupExclusionArgs, GroupIndexAddHotGroupExclusionResponse, GroupIndexDeleteFrozenGroupArgs, GroupIndexDeleteFrozenGroupResponse, GroupIndexExploreCommunitiesArgs, GroupIndexExploreCommunitiesResponse, GroupIndexExploreGroupsArgs, GroupIndexExploreGroupsResponse, GroupIndexFreezeCommunityArgs, GroupIndexFreezeCommunityResponse, GroupIndexFreezeGroupArgs, GroupIndexFreezeGroupResponse, GroupIndexLookupChannelByGroupIdArgs, GroupIndexLookupChannelByGroupIdResponse, GroupIndexMarkLocalGroupIndexFullArgs, GroupIndexMarkLocalGroupIndexFullResponse, GroupIndexRecommendedGroupsArgs, GroupIndexRecommendedGroupsResponse, GroupIndexRemoveHotGroupExclusionArgs, GroupIndexRemoveHotGroupExclusionResponse, GroupIndexSetCommunityModerationFlagsArgs, GroupIndexSetCommunityModerationFlagsResponse, GroupIndexSetCommunityUpgradeConcurrencyArgs, GroupIndexSetCommunityUpgradeConcurrencyResponse, GroupIndexSetGroupUpgradeConcurrencyArgs, GroupIndexSetGroupUpgradeConcurrencyResponse, GroupIndexUnfreezeCommunityArgs, GroupIndexUnfreezeCommunityResponse, GroupIndexUnfreezeGroupArgs, GroupIndexUnfreezeGroupResponse, } from \"../../typebox\";\nimport { principalStringToBytes } from \"../../utils/mapping\";\nexport class GroupIndexClient extends MsgpackCanisterAgent {\n constructor(identity, agent, canisterId) {\n super(identity, agent, canisterId, \"GroupIndex\");\n }\n activeGroups(communityIds, groupIds, activeSince) {\n const args = {\n group_ids: groupIds.map((c) => principalStringToBytes(c.groupId)),\n community_ids: communityIds.map((c) => principalStringToBytes(c.communityId)),\n active_since: activeSince,\n };\n return this.executeMsgpackQuery(\"active_groups\", args, activeGroupsResponse, GroupIndexActiveGroupsArgs, GroupIndexActiveGroupsResponse);\n }\n recommendedGroups(exclusions) {\n const args = {\n count: 30,\n exclusions: exclusions.map(principalStringToBytes),\n };\n return this.executeMsgpackQuery(\"recommended_groups\", args, recommendedGroupsResponse, GroupIndexRecommendedGroupsArgs, GroupIndexRecommendedGroupsResponse);\n }\n searchGroups(searchTerm, maxResults = 10) {\n const args = {\n search_term: searchTerm,\n page_index: 0,\n page_size: maxResults,\n };\n return this.executeMsgpackQuery(\"explore_groups\", args, exploreGroupsResponse, GroupIndexExploreGroupsArgs, GroupIndexExploreGroupsResponse);\n }\n lookupChannelByGroupId(id) {\n return this.executeMsgpackQuery(\"lookup_channel_by_group_id\", {\n group_id: principalStringToBytes(id.groupId),\n }, lookupChannelResponse, GroupIndexLookupChannelByGroupIdArgs, GroupIndexLookupChannelByGroupIdResponse);\n }\n exploreCommunities(searchTerm, pageIndex, pageSize, flags, languages) {\n const args = {\n languages,\n include_moderation_flags: flags,\n page_size: pageSize,\n page_index: pageIndex,\n search_term: searchTerm,\n };\n return this.executeMsgpackQuery(\"explore_communities\", args, exploreCommunitiesResponse, GroupIndexExploreCommunitiesArgs, GroupIndexExploreCommunitiesResponse);\n }\n freezeGroup(chatId, reason) {\n return this.executeMsgpackUpdate(\"freeze_group\", {\n chat_id: principalStringToBytes(chatId),\n reason: reason,\n }, freezeGroupResponse, GroupIndexFreezeGroupArgs, GroupIndexFreezeGroupResponse);\n }\n freezeCommunity(id, reason) {\n return this.executeMsgpackUpdate(\"freeze_community\", {\n community_id: principalStringToBytes(id.communityId),\n reason: reason,\n }, freezeCommunityResponse, GroupIndexFreezeCommunityArgs, GroupIndexFreezeCommunityResponse);\n }\n unfreezeCommunity(id) {\n return this.executeMsgpackUpdate(\"unfreeze_community\", {\n community_id: principalStringToBytes(id.communityId),\n }, unfreezeCommunityResponse, GroupIndexUnfreezeCommunityArgs, GroupIndexUnfreezeCommunityResponse);\n }\n unfreezeGroup(chatId) {\n return this.executeMsgpackUpdate(\"unfreeze_group\", { chat_id: principalStringToBytes(chatId) }, unfreezeGroupResponse, GroupIndexUnfreezeGroupArgs, GroupIndexUnfreezeGroupResponse);\n }\n deleteFrozenGroup(chatId) {\n return this.executeMsgpackUpdate(\"delete_frozen_group\", { chat_id: principalStringToBytes(chatId) }, deleteFrozenGroupResponse, GroupIndexDeleteFrozenGroupArgs, GroupIndexDeleteFrozenGroupResponse);\n }\n addHotGroupExclusion(chatId) {\n return this.executeMsgpackUpdate(\"add_hot_group_exclusion\", { chat_id: principalStringToBytes(chatId) }, addHotGroupExclusionResponse, GroupIndexAddHotGroupExclusionArgs, GroupIndexAddHotGroupExclusionResponse);\n }\n removeHotGroupExclusion(chatId) {\n return this.executeMsgpackUpdate(\"remove_hot_group_exclusion\", { chat_id: principalStringToBytes(chatId) }, removeHotGroupExclusionResponse, GroupIndexRemoveHotGroupExclusionArgs, GroupIndexRemoveHotGroupExclusionResponse);\n }\n setCommunityModerationFlags(communityId, flags) {\n return this.executeMsgpackUpdate(\"set_community_moderation_flags\", {\n community_id: principalStringToBytes(communityId),\n flags,\n }, setCommunityModerationFlagsResponse, GroupIndexSetCommunityModerationFlagsArgs, GroupIndexSetCommunityModerationFlagsResponse);\n }\n setGroupUpgradeConcurrency(value) {\n return this.executeMsgpackUpdate(\"set_group_upgrade_concurrency\", { value }, setUpgradeConcurrencyResponse, GroupIndexSetGroupUpgradeConcurrencyArgs, GroupIndexSetGroupUpgradeConcurrencyResponse);\n }\n setCommunityUpgradeConcurrency(value) {\n return this.executeMsgpackUpdate(\"set_community_upgrade_concurrency\", { value }, setUpgradeConcurrencyResponse, GroupIndexSetCommunityUpgradeConcurrencyArgs, GroupIndexSetCommunityUpgradeConcurrencyResponse);\n }\n markLocalGroupIndexFull(canisterId, full) {\n return this.executeMsgpackUpdate(\"mark_local_group_index_full\", {\n canister_id: principalStringToBytes(canisterId),\n full,\n }, (resp) => resp === \"Success\", GroupIndexMarkLocalGroupIndexFullArgs, GroupIndexMarkLocalGroupIndexFullResponse);\n }\n}\n","export const idlFactory = ({ IDL }) => {\n const ExchangeId = IDL.Nat32;\n const UpdateConfigArgs = IDL.Record({\n 'exchange_id': ExchangeId,\n 'max_orders_to_cancel_per_iteration': IDL.Opt(IDL.Nat32),\n 'min_order_size': IDL.Opt(IDL.Nat64),\n 'price_increment': IDL.Opt(IDL.Nat64),\n 'min_orders_per_direction': IDL.Opt(IDL.Nat32),\n 'enabled': IDL.Opt(IDL.Bool),\n 'min_sell_price': IDL.Opt(IDL.Nat64),\n 'order_size': IDL.Opt(IDL.Nat64),\n 'max_buy_price': IDL.Opt(IDL.Nat64),\n 'spread': IDL.Opt(IDL.Nat64),\n 'max_orders_to_make_per_iteration': IDL.Opt(IDL.Nat32),\n 'max_orders_per_direction': IDL.Opt(IDL.Nat32),\n });\n const UpdateConfigResponse = IDL.Variant({\n 'ExchangeNotFound': IDL.Null,\n 'NotAuthorized': IDL.Null,\n 'Success': IDL.Null,\n 'InternalError': IDL.Text,\n });\n return IDL.Service({\n 'update_config': IDL.Func([UpdateConfigArgs], [UpdateConfigResponse], []),\n });\n};\nexport const init = ({ IDL }) => { return []; };\n","import { UnsupportedValueError } from \"openchat-shared\";\nexport function updateConfigResponse(candid) {\n if (\"Success\" in candid) {\n return \"success\";\n }\n if (\"ExchangeNotFound\" in candid) {\n return \"exchange_not_found\";\n }\n if (\"NotAuthorized\" in candid) {\n return \"not_authorized\";\n }\n if (\"InternalError\" in candid) {\n return \"internal_error\";\n }\n throw new UnsupportedValueError(\"Unexpected ApiRole type received\", candid);\n}\n","import { idlFactory } from \"./candid/idl\";\nimport { CandidCanisterAgent } from \"../canisterAgent/candid\";\nimport { updateConfigResponse } from \"./mappers\";\nimport { apiOptional } from \"../common/chatMappers\";\nimport { identity } from \"../../utils/mapping\";\nexport class MarketMakerClient extends CandidCanisterAgent {\n constructor(identity, agent, canisterId) {\n super(identity, agent, canisterId, idlFactory, \"MarketMaker\");\n }\n updateConfig(config) {\n const args = {\n exchange_id: config.exchangeId,\n enabled: apiOptional(identity, config.enabled),\n price_increment: apiOptional(identity, config.priceIncrement),\n order_size: apiOptional(identity, config.orderSize),\n min_order_size: apiOptional(identity, config.minOrderSize),\n max_buy_price: apiOptional(identity, config.maxBuyPrice),\n min_sell_price: apiOptional(identity, config.minSellPrice),\n spread: apiOptional(identity, config.spread),\n min_orders_per_direction: apiOptional(identity, config.minOrdersPerDirection),\n max_orders_per_direction: apiOptional(identity, config.maxOrdersPerDirection),\n max_orders_to_make_per_iteration: apiOptional(identity, config.maxOrdersToMakePerIteration),\n max_orders_to_cancel_per_iteration: apiOptional(identity, config.maxOrdersToCancelPerIteration),\n };\n return this.handleResponse(this.service.update_config(args), updateConfigResponse);\n }\n}\n","import { mapOptional, principalBytesToString } from \"../../utils/mapping\";\nimport { BTC_SYMBOL, CKBTC_SYMBOL, UnsupportedValueError } from \"openchat-shared\";\nimport { buildTokenLogoUrl } from \"../../utils/chat\";\nconst CKBTC_TO_BTC_OVERRIDE_ENABLED = false;\nexport function updatesResponse(value, blobUrlPattern, registryCanisterId) {\n if (value === \"SuccessNoUpdates\") {\n return {\n kind: \"success_no_updates\",\n };\n }\n if (\"Success\" in value) {\n const communityId = \"txydz-jyaaa-aaaaf-bifea-cai\";\n const channelId = 2481490751;\n const channelName = \"March Airdrop 🪂\";\n const communityName = \"CHIT for CHAT\";\n return {\n kind: \"success\",\n lastUpdated: value.Success.last_updated,\n tokenDetails: mapOptional(value.Success.token_details, (tokens) => tokens.map((t) => tokenDetails(t, blobUrlPattern, registryCanisterId))) ?? [],\n nervousSystemSummary: value.Success.nervous_system_details.map(nervousSystemSummary),\n swapProviders: mapOptional(value.Success.swap_providers, (r) => r.map(swapProvider)),\n messageFiltersAdded: value.Success.message_filters_added,\n messageFiltersRemoved: value.Success.message_filters_removed,\n currentAirdropChannel: {\n //TODO - fill this in\n id: {\n kind: \"channel\",\n communityId,\n channelId,\n },\n channelName,\n communityName,\n url: `/community/${communityId}/channel/${channelId}`,\n },\n };\n }\n throw new UnsupportedValueError(\"Unexpected ApiUpdatesResponse type received\", value);\n}\nfunction tokenDetails(value, blobUrlPattern, registryCanisterId) {\n const ledger = principalBytesToString(value.ledger_canister_id);\n const tokenDetails = {\n ledger,\n name: value.name,\n symbol: value.symbol,\n decimals: value.decimals,\n transferFee: value.fee,\n logo: value.logo_id !== undefined\n ? buildTokenLogoUrl(blobUrlPattern, registryCanisterId, ledger, BigInt(value.logo_id))\n : value.logo,\n infoUrl: value.info_url,\n transactionUrlFormat: value.transaction_url_format,\n supportedStandards: value.supported_standards,\n added: value.added,\n enabled: value.enabled,\n lastUpdated: value.last_updated,\n };\n if (CKBTC_TO_BTC_OVERRIDE_ENABLED && tokenDetails.symbol === CKBTC_SYMBOL) {\n // Override ckBTC to BTC\n tokenDetails.name = \"Bitcoin\";\n tokenDetails.symbol = BTC_SYMBOL;\n tokenDetails.logo = \"/assets/btc_logo.svg\";\n }\n return tokenDetails;\n}\nfunction nervousSystemSummary(value) {\n return {\n rootCanisterId: principalBytesToString(value.root_canister_id),\n governanceCanisterId: principalBytesToString(value.governance_canister_id),\n ledgerCanisterId: principalBytesToString(value.ledger_canister_id),\n indexCanisterId: principalBytesToString(value.index_canister_id),\n isNns: value.is_nns,\n proposalRejectionFee: value.proposal_rejection_fee,\n submittingProposalsEnabled: value.submitting_proposals_enabled,\n };\n}\nfunction swapProvider(value) {\n if (value === \"ICPSwap\")\n return \"icpswap\";\n if (value === \"Sonic\")\n return \"sonic\";\n if (value === \"KongSwap\")\n return \"kongswap\";\n throw new UnsupportedValueError(\"Unexpected ApiSwapProvider type received\", value);\n}\n","import { MsgpackCanisterAgent } from \"../canisterAgent/msgpack\";\nimport { updatesResponse } from \"./mappers\";\nimport { principalStringToBytes } from \"../../utils/mapping\";\nimport { RegistryAddMessageFilterArgs, RegistryAddMessageFilterResponse, RegistryAddRemoveSwapProviderArgs, RegistryAddRemoveSwapProviderResponse, RegistryRemoveMessageFilterArgs, RegistrySetTokenEnabledArgs, RegistrySetTokenEnabledResponse, RegistryUpdatesArgs, RegistryUpdatesResponse as TRegistryUpdatesResponse, } from \"../../typebox\";\nimport { apiDexId } from \"../common/chatMappersV2\";\nexport class RegistryClient extends MsgpackCanisterAgent {\n constructor(identity, agent, canisterId, blobUrlPattern) {\n super(identity, agent, canisterId, \"Registry\");\n this.blobUrlPattern = blobUrlPattern;\n }\n updates(since) {\n const args = {\n since,\n };\n return this.executeMsgpackQuery(\"updates\", args, (resp) => updatesResponse(resp, this.blobUrlPattern, this.canisterId), RegistryUpdatesArgs, TRegistryUpdatesResponse);\n }\n addRemoveSwapProvider(swapProvider, add) {\n return this.executeMsgpackUpdate(\"add_remove_swap_provider\", {\n swap_provider: apiDexId(swapProvider),\n add,\n }, (resp) => resp === \"Success\", RegistryAddRemoveSwapProviderArgs, RegistryAddRemoveSwapProviderResponse);\n }\n addMessageFilter(regex) {\n return this.executeMsgpackUpdate(\"add_message_filter\", { regex }, (resp) => {\n if (typeof resp !== \"string\" && \"Success\" in resp) {\n console.log(`New message filter id: ${resp.Success}`);\n return true;\n }\n else {\n console.debug(\"Error calling add_message_filter\", resp);\n return false;\n }\n }, RegistryAddMessageFilterArgs, RegistryAddMessageFilterResponse);\n }\n removeMessageFilter(id) {\n return this.executeMsgpackUpdate(\"remove_message_filter\", { id }, (resp) => typeof resp === \"object\" && \"Success\" in resp, RegistryRemoveMessageFilterArgs, RegistryAddMessageFilterResponse);\n }\n setTokenEnabled(ledger, enabled) {\n return this.executeMsgpackUpdate(\"set_token_enabled\", {\n ledger_canister_id: principalStringToBytes(ledger),\n enabled,\n }, (resp) => resp === \"Success\", RegistrySetTokenEnabledArgs, RegistrySetTokenEnabledResponse);\n }\n}\n","export const idlFactory = ({ IDL }) => {\n const Token = IDL.Record({ 'address': IDL.Text, 'standard': IDL.Text });\n const PoolData = IDL.Record({\n 'token0': Token,\n 'token1': Token,\n 'canisterId': IDL.Principal,\n });\n const Error = IDL.Variant({\n 'CommonError': IDL.Null,\n 'InternalError': IDL.Text,\n 'UnsupportedToken': IDL.Text,\n 'InsufficientFunds': IDL.Null,\n });\n const GetPoolsResponse = IDL.Variant({\n 'ok': IDL.Vec(PoolData),\n 'err': Error,\n });\n return IDL.Service({\n 'getPools': IDL.Func([], [GetPoolsResponse], ['query']),\n });\n};\nexport const init = ({ IDL }) => { return []; };\n","export function getPoolsResponse(candid) {\n if (\"ok\" in candid) {\n return candid.ok\n .filter((p) => isStandardSupported(p.token0.standard) &&\n isStandardSupported(p.token1.standard))\n .map((p) => ({\n dex: \"icpswap\",\n dexName: \"ICPSwap\",\n canisterId: p.canisterId.toString(),\n token0: p.token0.address,\n token1: p.token1.address,\n }));\n }\n throw new Error(\"Unable to get pools from ICPSwap: \" + JSON.stringify(candid));\n}\nfunction isStandardSupported(standard) {\n return standard === \"ICP\" || standard.includes(\"ICRC\");\n}\n","export const idlFactory = ({ IDL }) => {\n const QuoteArgs = IDL.Record({\n 'amountIn': IDL.Text,\n 'zeroForOne': IDL.Bool,\n 'amountOutMinimum': IDL.Text,\n });\n const Error = IDL.Variant({\n 'CommonError': IDL.Null,\n 'InternalError': IDL.Text,\n 'UnsupportedToken': IDL.Text,\n 'InsufficientFunds': IDL.Null,\n });\n const QuoteResponse = IDL.Variant({ 'ok': IDL.Nat, 'err': Error });\n return IDL.Service({\n 'quoteForAll': IDL.Func([QuoteArgs], [QuoteResponse], ['query']),\n });\n};\nexport const init = ({ IDL }) => { return []; };\n","export function quoteResponse(candid) {\n if (\"ok\" in candid) {\n return candid.ok;\n }\n throw new Error(\"Unable to get quote from ICPSwap: \" + JSON.stringify(candid));\n}\n","import { idlFactory } from \"./candid/idl\";\nimport { CandidCanisterAgent } from \"../../../canisterAgent/candid\";\nimport { quoteResponse } from \"./mappers\";\nexport class IcpSwapPoolClient extends CandidCanisterAgent {\n constructor(identity, agent, canisterId, token0, token1) {\n super(identity, agent, canisterId, idlFactory, \"IcpSwapPool\");\n this.token0 = token0;\n this.token1 = token1;\n }\n quote(inputToken, outputToken, amountIn) {\n const zeroForOne = this.zeroForOne(inputToken, outputToken);\n const args = {\n amountIn: amountIn.toString(),\n amountOutMinimum: \"0\",\n zeroForOne,\n };\n return this.handleQueryResponse(() => this.service.quoteForAll(args), quoteResponse, args);\n }\n zeroForOne(inputToken, outputToken) {\n if (inputToken === this.token0 && outputToken === this.token1)\n return true;\n if (inputToken === this.token1 && outputToken === this.token0)\n return false;\n throw new Error(\"ICPSwap pool does not match requested tokens\");\n }\n}\n","import { idlFactory } from \"./candid/idl\";\nimport { CandidCanisterAgent } from \"../../../canisterAgent/candid\";\nimport { getPoolsResponse } from \"./mappers\";\nimport { IcpSwapPoolClient } from \"../pool/icpSwap.pool.client\";\nconst ICPSWAP_INDEX_CANISTER_ID = \"4mmnk-kiaaa-aaaag-qbllq-cai\";\nexport class IcpSwapIndexClient extends CandidCanisterAgent {\n constructor(identity, agent) {\n super(identity, agent, ICPSWAP_INDEX_CANISTER_ID, idlFactory, \"IcpSwapIndex\");\n }\n getPoolClient(canisterId, token0, token1) {\n return new IcpSwapPoolClient(this.identity, this.agent, canisterId, token0, token1);\n }\n getPools() {\n return this.handleQueryResponse(this.service.getPools, getPoolsResponse);\n }\n}\n","export const idlFactory = ({ IDL }) => {\n const SwapAmountsReply = IDL.Record({ 'receive_amount': IDL.Nat });\n const SwapAmountsResult = IDL.Variant({\n 'Ok': SwapAmountsReply,\n 'Err': IDL.Text,\n });\n const ICTokenReply = IDL.Record({\n 'canister_id': IDL.Text,\n 'is_removed': IDL.Bool,\n });\n const LPTokenReply = IDL.Record({});\n const TokenReply = IDL.Variant({ 'IC': ICTokenReply, 'LP': LPTokenReply });\n const TokensResult = IDL.Variant({\n 'Ok': IDL.Vec(TokenReply),\n 'Err': IDL.Text,\n });\n return IDL.Service({\n 'swap_amounts': IDL.Func([IDL.Text, IDL.Nat, IDL.Text], [SwapAmountsResult], ['query']),\n 'tokens': IDL.Func([IDL.Opt(IDL.Text)], [TokensResult], ['query']),\n });\n};\nexport const init = ({ IDL }) => { return []; };\n","export function tokensResponse(candid) {\n const tokens = [];\n if (\"Ok\" in candid) {\n for (const token of candid.Ok) {\n if (\"IC\" in token && !token.IC.is_removed) {\n tokens.push(token.IC.canister_id);\n }\n }\n }\n return tokens;\n}\nexport function swapAmountsResponse(candid) {\n return \"Ok\" in candid ? candid.Ok.receive_amount : BigInt(0);\n}\n","import { idlFactory } from \"./candid/idl\";\nimport { CandidCanisterAgent } from \"../../canisterAgent/candid\";\nimport { swapAmountsResponse, tokensResponse } from \"./mappers\";\nconst KONG_SWAP_CANISTER_ID = \"2ipq2-uqaaa-aaaar-qailq-cai\";\nexport class KongSwapClient extends CandidCanisterAgent {\n constructor(identity, agent) {\n super(identity, agent, KONG_SWAP_CANISTER_ID, idlFactory, \"KongSwap\");\n this.icrc2Tokens = new Set();\n }\n updateTokenDetails(tokenDetails) {\n for (const token of tokenDetails) {\n if (token.supportedStandards.includes(\"ICRC-2\")) {\n this.icrc2Tokens.add(token.ledger);\n }\n }\n }\n getPoolClient(_canisterId, _token0, _token1) {\n return this;\n }\n async getPools() {\n const tokens = await this.handleQueryResponse(() => this.service.tokens([]), tokensResponse);\n const pools = [];\n for (let i = 0; i < tokens.length - 1; i++) {\n for (let j = i + 1; j < tokens.length; j++) {\n const token0 = tokens[i];\n const token1 = tokens[j];\n if (this.icrc2Tokens.has(token0) && this.icrc2Tokens.has(token1)) {\n pools.push({\n dex: \"kongswap\",\n canisterId: KONG_SWAP_CANISTER_ID,\n token0,\n token1,\n });\n }\n }\n }\n return pools;\n }\n quote(inputToken, outputToken, amountIn) {\n return this.handleQueryResponse(() => this.service.swap_amounts(`IC.${inputToken}`, amountIn, `IC.${outputToken}`), swapAmountsResponse);\n }\n}\n","export const idlFactory = ({ IDL }) => {\n const PairInfoExt = IDL.Record({\n 'id': IDL.Text,\n 'price0CumulativeLast': IDL.Nat,\n 'creator': IDL.Principal,\n 'reserve0': IDL.Nat,\n 'reserve1': IDL.Nat,\n 'lptoken': IDL.Text,\n 'totalSupply': IDL.Nat,\n 'token0': IDL.Text,\n 'token1': IDL.Text,\n 'price1CumulativeLast': IDL.Nat,\n 'kLast': IDL.Nat,\n 'blockTimestampLast': IDL.Int,\n });\n return IDL.Service({\n 'getAllPairs': IDL.Func([], [IDL.Vec(PairInfoExt)], ['query']),\n 'getPair': IDL.Func([IDL.Principal, IDL.Principal], [IDL.Opt(PairInfoExt)], ['query']),\n });\n};\nexport const init = ({ IDL }) => { return []; };\n","import { optional } from \"../../../../utils/mapping\";\nexport function getAllPairsResponse(candid, canisterId) {\n return candid.map((p) => ({\n dex: \"sonic\",\n canisterId,\n token0: p.token0,\n token1: p.token1,\n }));\n}\nexport function getPairResponse(candid) {\n return optional(candid, pair);\n}\nfunction pair(candid) {\n return {\n token0: candid.token0,\n reserve0: candid.reserve0,\n token1: candid.token1,\n reserve1: candid.reserve1,\n };\n}\n","import { idlFactory } from \"./candid/idl\";\nimport { CandidCanisterAgent } from \"../../../canisterAgent/candid\";\nimport { getAllPairsResponse, getPairResponse } from \"./mappers\";\nimport { Principal } from \"@dfinity/principal\";\nconst SONIC_INDEX_CANISTER_ID = \"3xwpq-ziaaa-aaaah-qcn4a-cai\";\nexport class SonicSwapsClient extends CandidCanisterAgent {\n constructor(identity, agent) {\n super(identity, agent, SONIC_INDEX_CANISTER_ID, idlFactory, \"Sonic\");\n }\n getPoolClient(_canisterId, _token0, _token1) {\n return this;\n }\n getPools() {\n return this.handleQueryResponse(this.service.getAllPairs, (resp) => getAllPairsResponse(resp, SONIC_INDEX_CANISTER_ID));\n }\n async quote(inputToken, outputToken, amountIn) {\n const pair = await this.handleQueryResponse(() => this.service.getPair(Principal.fromText(inputToken), Principal.fromText(outputToken)), getPairResponse);\n if (pair === undefined)\n return BigInt(0);\n const zeroForOne = pair.token0 === inputToken;\n const reserveIn = zeroForOne ? pair.reserve0 : pair.reserve1;\n const reserveOut = zeroForOne ? pair.reserve1 : pair.reserve0;\n const amountInWithFee = amountIn * BigInt(997);\n const numerator = amountInWithFee * reserveOut;\n const denominator = reserveIn * BigInt(1000) + amountInWithFee;\n return numerator / denominator;\n }\n}\n","import { AnonymousIdentity } from \"@dfinity/agent\";\nimport { IcpSwapIndexClient } from \"./icpSwap/index/icpSwap.index.client\";\nimport { KongSwapClient } from \"./kongswap/kongswap.client\";\nimport { SonicSwapsClient } from \"./sonic/swaps/sonic.swaps.client\";\nconst TEN_MINUTES = 10 * 60 * 1000;\nexport class DexesAgent {\n constructor(agent) {\n this.agent = agent;\n this._poolsCache = {};\n this._identity = new AnonymousIdentity();\n this._swapIndexClients = {\n icpswap: new IcpSwapIndexClient(this._identity, this.agent),\n kongswap: new KongSwapClient(this._identity, this.agent),\n sonic: new SonicSwapsClient(this._identity, this.agent),\n };\n }\n updateTokenDetails(tokenDetails) {\n this._swapIndexClients[\"kongswap\"].updateTokenDetails(tokenDetails);\n }\n async getSwapPools(inputToken, outputTokens, swapProviders) {\n const allPools = await this.getAllSwapPools(swapProviders);\n return allPools.filter((p) => (p.token0 === inputToken && outputTokens.has(p.token1)) ||\n (p.token1 === inputToken && outputTokens.has(p.token0)));\n }\n async canSwap(tokens, swapProviders) {\n const allPools = await this.getAllSwapPools(swapProviders);\n const available = new Set();\n for (const p of allPools) {\n if (tokens.has(p.token0) && tokens.has(p.token1)) {\n available.add(p.token0);\n available.add(p.token1);\n }\n }\n return available;\n }\n async quoteSwap(inputToken, outputToken, amountIn, swapProviders) {\n const pools = await this.getSwapPools(inputToken, new Set([outputToken]), swapProviders);\n return await Promise.all(pools.map((p) => this.quoteSingle(p, inputToken, outputToken, amountIn).then((quote) => [p.dex, quote])));\n }\n getAllSwapPools(swapProviders) {\n const promises = [];\n for (const swapProvider of swapProviders) {\n const cached = this.tryGetAllSwapPoolsFromCache(swapProvider);\n if (cached !== undefined) {\n promises.push(Promise.resolve(cached));\n continue;\n }\n const client = this._swapIndexClients[swapProvider];\n if (client === undefined) {\n continue;\n }\n promises.push(client.getPools().then((pools) => {\n this._poolsCache[swapProvider] = [pools, Date.now()];\n return pools;\n }));\n }\n return Promise.allSettled(promises).then((result) => result.flatMap((r) => (r.status === \"fulfilled\" ? r.value : [])));\n }\n quoteSingle(pool, inputToken, outputToken, amountIn) {\n const indexClient = this._swapIndexClients[pool.dex];\n if (indexClient === undefined) {\n return Promise.resolve(BigInt(0));\n }\n const poolClient = indexClient.getPoolClient(pool.canisterId, pool.token0, pool.token1);\n return poolClient.quote(inputToken, outputToken, amountIn);\n }\n tryGetAllSwapPoolsFromCache(dex) {\n const cached = this._poolsCache[dex];\n if (cached === undefined) {\n return undefined;\n }\n const [pools, timestamp] = cached;\n const now = Date.now();\n return now - timestamp < TEN_MINUTES ? pools : undefined;\n }\n}\n","export const idlFactory = ({ IDL }) => {\n const NeuronId = IDL.Record({ 'id': IDL.Nat64 });\n const ListProposalInfo = IDL.Record({\n 'include_reward_status': IDL.Vec(IDL.Int32),\n 'before_proposal': IDL.Opt(NeuronId),\n 'limit': IDL.Nat32,\n 'exclude_topic': IDL.Vec(IDL.Int32),\n 'include_status': IDL.Vec(IDL.Int32),\n });\n const Ballot = IDL.Record({ 'vote': IDL.Int32, 'voting_power': IDL.Nat64 });\n const Tally = IDL.Record({\n 'no': IDL.Nat64,\n 'yes': IDL.Nat64,\n 'total': IDL.Nat64,\n 'timestamp_seconds': IDL.Nat64,\n });\n const ProposalInfo = IDL.Record({\n 'id': IDL.Opt(NeuronId),\n 'ballots': IDL.Vec(IDL.Tuple(IDL.Nat64, Ballot)),\n 'latest_tally': IDL.Opt(Tally),\n });\n const ListProposalInfoResponse = IDL.Record({\n 'proposal_info': IDL.Vec(ProposalInfo),\n });\n const RegisterVote = IDL.Record({\n 'vote': IDL.Int32,\n 'proposal': IDL.Opt(NeuronId),\n });\n const Command = IDL.Variant({ 'RegisterVote': RegisterVote });\n const ManageNeuron = IDL.Record({\n 'id': IDL.Opt(NeuronId),\n 'command': IDL.Opt(Command),\n });\n const GovernanceError = IDL.Record({\n 'error_message': IDL.Text,\n 'error_type': IDL.Int32,\n });\n const Command_1 = IDL.Variant({\n 'Error': GovernanceError,\n 'RegisterVote': IDL.Record({}),\n });\n const ManageNeuronResponse = IDL.Record({ 'command': IDL.Opt(Command_1) });\n return IDL.Service({\n 'list_proposals': IDL.Func([ListProposalInfo], [ListProposalInfoResponse], ['query']),\n 'manage_neuron': IDL.Func([ManageNeuron], [ManageNeuronResponse], []),\n });\n};\nexport const init = ({ IDL }) => { return []; };\n","import { proposalVote } from \"../common/chatMappers\";\nconst E8S_AS_BIGINT = BigInt(100_000_000);\nexport function manageNeuronResponse(candid) {\n const result = candid.command[0];\n if (\"RegisterVote\" in result) {\n return {\n kind: \"success\",\n };\n }\n if (\"Error\" in result) {\n return {\n kind: \"error\",\n type: result.Error.error_type,\n message: result.Error.error_message,\n };\n }\n throw new Error(`Unexpected ApiManageNeuronResponse type received: ${candid}`);\n}\nexport function getProposalVoteDetails(candid) {\n const proposal = candid.proposal_info[0];\n if (proposal === undefined) {\n throw new Error(\"GetProposal returned an empty response\");\n }\n const ballots = proposal.ballots;\n const tally = proposal.latest_tally[0];\n return {\n id: proposal.id[0].id,\n ballots: ballots.map(([n, b]) => ({\n neuronId: n.toString(),\n vote: proposalVote(b.vote),\n votingPower: b.voting_power,\n })),\n latestTally: {\n yes: Number(tally.yes / E8S_AS_BIGINT),\n no: Number(tally.no / E8S_AS_BIGINT),\n total: Number(tally.total / E8S_AS_BIGINT),\n timestamp: tally.timestamp_seconds * BigInt(1000)\n }\n };\n}\n","import { idlFactory } from \"./candid/idl\";\nimport { CandidCanisterAgent } from \"../canisterAgent/candid\";\nimport { getProposalVoteDetails, manageNeuronResponse } from \"./mappers\";\nimport { apiOptional, apiProposalVote } from \"../common/chatMappers\";\nimport { identity } from \"../../utils/mapping\";\nexport class NnsGovernanceClient extends CandidCanisterAgent {\n constructor(identity, agent, canisterId) {\n super(identity, agent, canisterId, idlFactory, \"NnsGovernance\");\n }\n registerVote(neuronId, proposalId, vote) {\n const args = {\n id: apiOptional(identity, { id: BigInt(neuronId) }),\n command: apiOptional(identity, {\n RegisterVote: {\n vote: apiProposalVote(vote),\n proposal: apiOptional(identity, { id: proposalId }),\n },\n }),\n };\n return this.handleResponse(this.service.manage_neuron(args), manageNeuronResponse);\n }\n getProposalVoteDetails(proposalId) {\n const args = {\n include_reward_status: [],\n before_proposal: apiOptional(identity, { id: proposalId + BigInt(1) }),\n limit: 1,\n exclude_topic: [],\n include_status: [],\n };\n return this.handleQueryResponse(() => this.service.list_proposals(args), getProposalVoteDetails);\n }\n}\n","export const idlFactory = ({ IDL }) => {\n const GenericNervousSystemFunction = IDL.Record({\n 'validator_canister_id': IDL.Opt(IDL.Principal),\n 'target_canister_id': IDL.Opt(IDL.Principal),\n 'validator_method_name': IDL.Opt(IDL.Text),\n 'target_method_name': IDL.Opt(IDL.Text),\n });\n const FunctionType = IDL.Variant({\n 'NativeNervousSystemFunction': IDL.Record({}),\n 'GenericNervousSystemFunction': GenericNervousSystemFunction,\n });\n const NervousSystemFunction = IDL.Record({\n 'id': IDL.Nat64,\n 'name': IDL.Text,\n 'description': IDL.Opt(IDL.Text),\n 'function_type': IDL.Opt(FunctionType),\n });\n const ListNervousSystemFunctionsResponse = IDL.Record({\n 'reserved_ids': IDL.Vec(IDL.Nat64),\n 'functions': IDL.Vec(NervousSystemFunction),\n });\n const ProposalId = IDL.Record({ 'id': IDL.Nat64 });\n const ListProposals = IDL.Record({\n 'include_reward_status': IDL.Vec(IDL.Int32),\n 'before_proposal': IDL.Opt(ProposalId),\n 'limit': IDL.Nat32,\n 'exclude_type': IDL.Vec(IDL.Nat64),\n 'include_status': IDL.Vec(IDL.Int32),\n });\n const Ballot = IDL.Record({ 'vote': IDL.Int32, 'voting_power': IDL.Nat64 });\n const Tally = IDL.Record({\n 'no': IDL.Nat64,\n 'yes': IDL.Nat64,\n 'total': IDL.Nat64,\n 'timestamp_seconds': IDL.Nat64,\n });\n const ProposalData = IDL.Record({\n 'id': IDL.Opt(ProposalId),\n 'ballots': IDL.Vec(IDL.Tuple(IDL.Text, Ballot)),\n 'latest_tally': IDL.Opt(Tally),\n });\n const ListProposalsResponse = IDL.Record({\n 'proposals': IDL.Vec(ProposalData),\n });\n const RegisterVote = IDL.Record({\n 'vote': IDL.Int32,\n 'proposal': IDL.Opt(ProposalId),\n });\n const Command = IDL.Variant({ 'RegisterVote': RegisterVote });\n const ManageNeuron = IDL.Record({\n 'subaccount': IDL.Vec(IDL.Nat8),\n 'command': IDL.Opt(Command),\n });\n const GovernanceError = IDL.Record({\n 'error_message': IDL.Text,\n 'error_type': IDL.Int32,\n });\n const Command_1 = IDL.Variant({\n 'Error': GovernanceError,\n 'RegisterVote': IDL.Record({}),\n });\n const ManageNeuronResponse = IDL.Record({ 'command': IDL.Opt(Command_1) });\n return IDL.Service({\n 'list_nervous_system_functions': IDL.Func([], [ListNervousSystemFunctionsResponse], ['query']),\n 'list_proposals': IDL.Func([ListProposals], [ListProposalsResponse], ['query']),\n 'manage_neuron': IDL.Func([ManageNeuron], [ManageNeuronResponse], []),\n });\n};\nexport const init = ({ IDL }) => { return []; };\n","import { identity, optional } from \"../../utils/mapping\";\nimport { proposalVote } from \"../common/chatMappers\";\nconst E8S_AS_BIGINT = BigInt(100_000_000);\nexport function manageNeuronResponse(candid) {\n const result = candid.command[0];\n if (\"RegisterVote\" in result) {\n return {\n kind: \"success\",\n };\n }\n if (\"Error\" in result) {\n return {\n kind: \"error\",\n type: result.Error.error_type,\n message: result.Error.error_message,\n };\n }\n throw new Error(`Unexpected ApiManageNeuronResponse type received: ${candid}`);\n}\nexport function getProposalVoteDetails(candid) {\n const proposal = candid.proposals[0];\n if (proposal === undefined) {\n throw new Error(\"GetProposal returned an empty response\");\n }\n const ballots = proposal.ballots;\n const tally = proposal.latest_tally[0];\n return {\n id: proposal.id[0].id,\n ballots: ballots.map(([n, b]) => ({\n neuronId: n,\n vote: proposalVote(b.vote),\n votingPower: b.voting_power,\n })),\n latestTally: {\n yes: Number(tally.yes / E8S_AS_BIGINT),\n no: Number(tally.no / E8S_AS_BIGINT),\n total: Number(tally.total / E8S_AS_BIGINT),\n timestamp: tally.timestamp_seconds * BigInt(1000)\n }\n };\n}\nexport function nervousSystemFunctions(candid) {\n return {\n reservedIds: [...candid.reserved_ids],\n functions: candid.functions.map(nervousSystemFunction),\n };\n}\nfunction nervousSystemFunction(candid) {\n return {\n id: Number(candid.id),\n name: candid.name,\n description: optional(candid.description, identity) ?? \"\",\n functionType: optional(candid.function_type, snsFunctionType),\n };\n}\nfunction snsFunctionType(candid) {\n if (\"NativeNervousSystemFunction\" in candid) {\n return { kind: \"native_nervous_system_function\" };\n }\n else {\n return { kind: \"generic_nervous_system_function\" };\n }\n}\n","import { idlFactory } from \"./candid/idl\";\nimport { CandidCanisterAgent } from \"../canisterAgent/candid\";\nimport { getProposalVoteDetails, manageNeuronResponse, nervousSystemFunctions } from \"./mappers\";\nimport { apiOptional, apiProposalVote } from \"../common/chatMappers\";\nimport { identity } from \"../../utils/mapping\";\nimport { toUint8Array } from \"../../utils/base64\";\nexport class SnsGovernanceClient extends CandidCanisterAgent {\n constructor(identity, agent, canisterId) {\n super(identity, agent, canisterId, idlFactory, \"SnsGovernance\");\n }\n registerVote(neuronId, proposalId, vote) {\n const args = {\n subaccount: toUint8Array(neuronId),\n command: apiOptional(identity, {\n RegisterVote: {\n vote: apiProposalVote(vote),\n proposal: apiOptional(identity, { id: proposalId }),\n },\n }),\n };\n return this.handleResponse(this.service.manage_neuron(args), manageNeuronResponse);\n }\n getProposalVoteDetails(proposalId) {\n const args = {\n include_reward_status: [],\n before_proposal: [{ id: proposalId + BigInt(1) }],\n limit: 1,\n exclude_type: [],\n include_status: [],\n };\n return this.handleQueryResponse(() => this.service.list_proposals(args), getProposalVoteDetails);\n }\n listNervousSystemFunctions() {\n return this.handleQueryResponse(() => this.service.list_nervous_system_functions(), nervousSystemFunctions);\n }\n}\n","export function toUint8Array(base64String) {\n return Uint8Array.from(atob(base64String), (c) => c.charCodeAt(0));\n}\nexport function bigintToBase64(bn) {\n let hex = bn.toString(16);\n if (hex.length % 2) {\n hex = \"0\" + hex;\n }\n const bin = [];\n let i = 0;\n let d;\n let b;\n while (i < hex.length) {\n d = parseInt(hex.slice(i, i + 2), 16);\n b = String.fromCharCode(d);\n bin.push(b);\n i += 2;\n }\n return btoa(bin.join(\"\"));\n}\nexport function base64ToBigint(b64) {\n const bin = atob(b64);\n const hex = [];\n bin.split(\"\").forEach(function (ch) {\n let h = ch.charCodeAt(0).toString(16);\n if (h.length % 2) {\n h = \"0\" + h;\n }\n hex.push(h);\n });\n return BigInt(\"0x\" + hex.join(\"\"));\n}\n","import { MessageContextMap, waitAll } from \"openchat-shared\";\nexport class AsyncMessageContextMap extends MessageContextMap {\n insert(context, val) {\n if (!this.has(context)) {\n this.set(context, []);\n }\n this.get(context)?.push(val);\n }\n get length() {\n return this.size;\n }\n lookup(key) {\n return this.get(key) ?? [];\n }\n async asyncMap(fn) {\n const intermediate = this.entries().map(([key, val]) => fn(key, val));\n const result = await waitAll(intermediate);\n if (result.errors.length > 0) {\n console.error(\"Some missing indexes could not be resolved: \", result.errors);\n }\n return result.success.reduce((res, [messageContext, messages]) => {\n res.set(messageContext, (res.get(messageContext) ?? []).concat(messages));\n return res;\n }, new AsyncMessageContextMap());\n }\n}\n","import { MsgpackCanisterAgent } from \"../canisterAgent/msgpack\";\nimport { apiOptionUpdateV2, identity, mapOptional, principalBytesToString, principalStringToBytes, } from \"../../utils/mapping\";\nimport { addMembersToChannelResponse, apiCommunityRole, apiMemberRole, apiOptionalCommunityPermissions, blockUserResponse, changeRoleResponse, communityChannelSummaryResponse, communityDetailsResponse, communityDetailsUpdatesResponse, createUserGroupResponse, deleteUserGroupsResponse, exploreChannelsResponse, followThreadResponse, importGroupResponse, removeMemberFromChannelResponse, removeMemberResponse, reportMessageResponse, sendMessageResponse as sendMessageResponseV2, setMemberDisplayNameResponse, summaryResponse, summaryUpdatesResponse, unblockUserResponse, updateCommunityResponse, updateUserGroupResponse, } from \"./mappersV2\";\nimport { acceptP2PSwapResponse, apiAccessGateConfig, addRemoveReactionResponse, apiExternalBotPermissions, apiGroupPermissions, apiMessageContent, apiUser as apiUserV2, apiVideoCallPresence, cancelP2PSwapResponse, changeRoleResponse as changeChannelRoleResponse, claimPrizeResponse, createGroupResponse, declineInvitationResponse, deletedMessageResponse, deleteGroupResponse, deleteMessageResponse, disableInviteCodeResponse, editMessageResponse, enableOrResetInviteCodeResponse, groupDetailsResponse, groupDetailsUpdatesResponse, inviteCodeResponse, joinVideoCallResponse, leaveGroupResponse, pinMessageResponse, registerPollVoteResponse, registerProposalVoteResponse, searchGroupChatResponse, setVideoCallPresence, threadPreviewsResponse, undeleteMessageResponse, unpinMessageResponse, updateGroupResponse, videoCallParticipantsResponse, apiMaybeAccessGateConfig, updateBotResponse, generateApiKeyResponse, } from \"../common/chatMappersV2\";\nimport { textToCode, toBigInt32, DestinationInvalidError, offline, MAX_EVENTS, MAX_MESSAGES, MAX_MISSING, ResponseTooLargeError, } from \"openchat-shared\";\nimport { apiOptionalGroupPermissions, apiUpdatedRules, getEventsResponse, getMessagesByMessageIndexResponse, } from \"../group/mappersV2\";\nimport { DataClient } from \"../data/data.client\";\nimport { getCachedCommunityDetails, getCachedEvents, getCachedEventsByIndex, getCachedEventsWindowByMessageIndex, getCachedGroupDetails, loadMessagesByMessageIndex, mergeSuccessResponses, recordFailedMessage, removeCachedChannelApiKeys, removeFailedMessage, setCachedCommunityDetails, setCachedEvents, setCachedGroupDetails, setCachedMessageFromSendResponse, } from \"../../utils/caching\";\nimport { mergeCommunityDetails, mergeGroupChatDetails } from \"../../utils/chat\";\nimport { toggleNotificationsResponse } from \"../notifications/mappers\";\nimport { chunkedChatEventsFromBackend, chunkedChatEventsWindowFromBackend, } from \"../common/chunked\";\nimport { CommunityAcceptP2pSwapArgs, CommunityAcceptP2pSwapResponse, CommunityAddMembersToChannelArgs, CommunityAddMembersToChannelResponse, CommunityAddReactionArgs, CommunityAddReactionResponse, CommunityBlockUserArgs, CommunityBlockUserResponse, CommunityCancelInvitesArgs, CommunityCancelInvitesResponse, CommunityCancelP2pSwapArgs, CommunityCancelP2pSwapResponse, CommunityChangeChannelRoleArgs, CommunityChangeChannelRoleResponse, CommunityChangeRoleArgs, CommunityChangeRoleResponse, CommunityChannelSummaryArgs, CommunityChannelSummaryResponse, CommunityClaimPrizeArgs, CommunityClaimPrizeResponse, CommunityCreateChannelArgs, CommunityCreateChannelResponse, CommunityCreateUserGroupArgs, CommunityCreateUserGroupResponse, CommunityDeclineInvitationArgs, CommunityDeclineInvitationResponse, CommunityDeleteChannelArgs, CommunityDeleteChannelResponse, CommunityDeletedMessageArgs, CommunityDeletedMessageResponse, CommunityDeleteMessagesArgs, CommunityDeleteMessagesResponse, CommunityDeleteUserGroupsArgs, CommunityDeleteUserGroupsResponse, CommunityDisableInviteCodeResponse, CommunityEditMessageArgs, CommunityEditMessageResponse, CommunityEnableInviteCodeResponse, CommunityEventsArgs, CommunityEventsByIndexArgs, CommunityEventsResponse, CommunityEventsWindowArgs, CommunityExploreChannelsArgs, CommunityExploreChannelsResponse, CommunityFollowThreadArgs, CommunityFollowThreadResponse, CommunityImportGroupArgs, CommunityImportGroupResponse, CommunityInviteCodeResponse, CommunityJoinVideoCallArgs, CommunityLeaveChannelArgs, CommunityLeaveChannelResponse, CommunityLocalUserIndexResponse, CommunityMessagesByMessageIndexArgs, CommunityMessagesByMessageIndexResponse, CommunityPinMessageArgs, CommunityPinMessageResponse, CommunityRegisterPollVoteArgs, CommunityRegisterPollVoteResponse, CommunityRegisterProposalVoteArgs, CommunityRegisterProposalVoteResponse, CommunityRemoveMemberArgs, CommunityRemoveMemberFromChannelArgs, CommunityRemoveMemberFromChannelResponse, CommunityRemoveMemberResponse, CommunityRemoveReactionArgs, CommunityRemoveReactionResponse, CommunityReportMessageArgs, CommunityReportMessageResponse, CommunitySearchChannelArgs, CommunitySearchChannelResponse, CommunitySelectedChannelInitialArgs, CommunitySelectedChannelInitialResponse, CommunitySelectedChannelUpdatesArgs, CommunitySelectedChannelUpdatesResponse, CommunitySelectedInitialArgs, CommunitySelectedInitialResponse, CommunitySelectedUpdatesArgs, CommunitySelectedUpdatesResponse, CommunitySendMessageArgs, CommunitySendMessageResponse, CommunitySetMemberDisplayNameArgs, CommunitySetMemberDisplayNameResponse, CommunitySetVideoCallPresenceArgs, CommunitySetVideoCallPresenceResponse, CommunitySummaryArgs, CommunitySummaryResponse as TCommunitySummaryResponse, CommunitySummaryUpdatesArgs, CommunitySummaryUpdatesResponse as TCommunitySummaryUpdatesResponse, CommunityThreadPreviewsArgs, CommunityThreadPreviewsResponse, CommunityToggleMuteNotificationsArgs, CommunityToggleMuteNotificationsResponse, CommunityUnblockUserArgs, CommunityUnblockUserResponse, CommunityUndeleteMessagesArgs, CommunityUndeleteMessagesResponse, CommunityUpdateChannelArgs, CommunityUpdateChannelResponse, CommunityUpdateCommunityArgs, CommunityUpdateCommunityResponse, CommunityUpdateUserGroupArgs, CommunityUpdateUserGroupResponse, CommunityVideoCallParticipantsArgs, CommunityVideoCallParticipantsResponse, Empty as TEmpty, CommunityUpdateBotArgs, CommunityUpdateBotResponse, CommunityGenerateBotApiKeyArgs, CommunityGenerateBotApiKeyResponse, CommunityApiKeyResponse, CommunityApiKeyArgs, } from \"../../typebox\";\nexport class CommunityClient extends MsgpackCanisterAgent {\n constructor(identity, agent, config, communityId, db, inviteCode) {\n super(identity, agent, communityId, \"Community\");\n this.config = config;\n this.communityId = communityId;\n this.db = db;\n this.inviteCode = inviteCode;\n }\n claimPrize(channelId, messageId) {\n return this.executeMsgpackUpdate(\"claim_prize\", {\n channel_id: toBigInt32(channelId),\n message_id: messageId,\n }, claimPrizeResponse, CommunityClaimPrizeArgs, CommunityClaimPrizeResponse);\n }\n addMembersToChannel(chatId, userIds, username, displayName) {\n return this.executeMsgpackUpdate(\"add_members_to_channel\", {\n channel_id: toBigInt32(chatId.channelId),\n user_ids: userIds.map(principalStringToBytes),\n added_by_name: username,\n added_by_display_name: displayName,\n }, addMembersToChannelResponse, CommunityAddMembersToChannelArgs, CommunityAddMembersToChannelResponse);\n }\n addReaction(chatId, username, displayName, messageId, reaction, threadRootMessageIndex, newAchievement) {\n return this.executeMsgpackUpdate(\"add_reaction\", {\n channel_id: toBigInt32(chatId.channelId),\n username,\n display_name: displayName,\n message_id: messageId,\n thread_root_message_index: threadRootMessageIndex,\n reaction,\n new_achievement: newAchievement,\n }, addRemoveReactionResponse, CommunityAddReactionArgs, CommunityAddReactionResponse);\n }\n blockUser(userId) {\n return this.executeMsgpackUpdate(\"block_user\", {\n user_id: principalStringToBytes(userId),\n }, blockUserResponse, CommunityBlockUserArgs, CommunityBlockUserResponse);\n }\n changeChannelRole(chatId, userId, newRole) {\n return this.executeMsgpackUpdate(\"change_channel_role\", {\n channel_id: toBigInt32(chatId.channelId),\n user_id: principalStringToBytes(userId),\n new_role: apiMemberRole(newRole),\n }, changeChannelRoleResponse, CommunityChangeChannelRoleArgs, CommunityChangeChannelRoleResponse);\n }\n changeRole(userId, newRole) {\n return this.executeMsgpackUpdate(\"change_role\", {\n user_id: principalStringToBytes(userId),\n new_role: apiCommunityRole(newRole),\n }, changeRoleResponse, CommunityChangeRoleArgs, CommunityChangeRoleResponse);\n }\n createChannel(channel) {\n return this.executeMsgpackUpdate(\"create_channel\", {\n is_public: channel.public,\n name: channel.name,\n events_ttl: channel.eventsTTL,\n description: channel.description,\n external_url: channel.externalUrl,\n history_visible_to_new_joiners: channel.historyVisible,\n avatar: mapOptional(channel.avatar?.blobData, (data) => {\n return {\n id: DataClient.newBlobId(),\n data,\n mime_type: \"image/jpg\",\n };\n }),\n permissions_v2: apiGroupPermissions(channel.permissions),\n rules: channel.rules,\n gate_config: apiMaybeAccessGateConfig(channel.gateConfig),\n messages_visible_to_non_members: channel.messagesVisibleToNonMembers,\n }, (resp) => createGroupResponse(resp, channel.id), CommunityCreateChannelArgs, CommunityCreateChannelResponse);\n }\n declineInvitation(chatId) {\n return this.executeMsgpackUpdate(\"decline_invitation\", {\n channel_id: toBigInt32(chatId.channelId),\n }, declineInvitationResponse, CommunityDeclineInvitationArgs, CommunityDeclineInvitationResponse);\n }\n deleteChannel(chatId) {\n return this.executeMsgpackUpdate(\"delete_channel\", {\n channel_id: toBigInt32(chatId.channelId),\n }, deleteGroupResponse, CommunityDeleteChannelArgs, CommunityDeleteChannelResponse);\n }\n getDeletedMessage(chatId, messageId, threadRootMessageIndex) {\n return this.executeMsgpackQuery(\"deleted_message\", {\n channel_id: toBigInt32(chatId.channelId),\n message_id: messageId,\n thread_root_message_index: threadRootMessageIndex,\n }, deletedMessageResponse, CommunityDeletedMessageArgs, CommunityDeletedMessageResponse);\n }\n deleteMessages(chatId, messageIds, threadRootMessageIndex, asPlatformModerator, newAchievement) {\n return this.executeMsgpackUpdate(\"delete_messages\", {\n channel_id: toBigInt32(chatId.channelId),\n message_ids: messageIds,\n as_platform_moderator: asPlatformModerator,\n thread_root_message_index: threadRootMessageIndex,\n new_achievement: newAchievement,\n }, deleteMessageResponse, CommunityDeleteMessagesArgs, CommunityDeleteMessagesResponse);\n }\n disableInviteCode() {\n return this.executeMsgpackUpdate(\"disable_invite_code\", {}, disableInviteCodeResponse, TEmpty, CommunityDisableInviteCodeResponse);\n }\n editMessage(chatId, message, threadRootMessageIndex, blockLevelMarkdown, newAchievement) {\n return new DataClient(this.identity, this.agent, this.config)\n .uploadData(message.content, [chatId.communityId])\n .then((content) => {\n return this.executeMsgpackUpdate(\"edit_message\", {\n channel_id: toBigInt32(chatId.channelId),\n thread_root_message_index: threadRootMessageIndex,\n content: apiMessageContent(content ?? message.content),\n message_id: message.messageId,\n block_level_markdown: blockLevelMarkdown,\n new_achievement: newAchievement,\n }, editMessageResponse, CommunityEditMessageArgs, CommunityEditMessageResponse);\n });\n }\n enableInviteCode() {\n return this.executeMsgpackUpdate(\"enable_invite_code\", {}, enableOrResetInviteCodeResponse, TEmpty, CommunityEnableInviteCodeResponse);\n }\n async events(chatId, eventIndexRange, startIndex, ascending, threadRootMessageIndex, latestKnownUpdate) {\n const [cachedEvents, missing] = await getCachedEvents(this.db, eventIndexRange, { chatId, threadRootMessageIndex }, startIndex, ascending);\n // we may or may not have all of the requested events\n if (missing.size >= MAX_MISSING) {\n // if we have exceeded the maximum number of missing events, let's just consider it a complete miss and go to the api\n console.log(\"We didn't get enough back from the cache, going to the api\");\n return this.eventsFromBackend(chatId, startIndex, ascending, threadRootMessageIndex, latestKnownUpdate)\n .then((resp) => this.setCachedEvents(chatId, resp, threadRootMessageIndex))\n .catch((err) => {\n if (err instanceof ResponseTooLargeError) {\n console.log(\"Response size too large, we will try to split the payload into a a few chunks\");\n return chunkedChatEventsFromBackend((index, chunkSize) => this.eventsFromBackend(chatId, index, ascending, threadRootMessageIndex, latestKnownUpdate, chunkSize), eventIndexRange, startIndex, ascending).then((resp) => this.setCachedEvents(chatId, resp, threadRootMessageIndex));\n }\n else {\n throw err;\n }\n });\n }\n else {\n return this.handleMissingEvents(chatId, [cachedEvents, missing], threadRootMessageIndex, latestKnownUpdate);\n }\n }\n eventsFromBackend(chatId, startIndex, ascending, threadRootMessageIndex, latestKnownUpdate, maxEvents = MAX_EVENTS) {\n const args = {\n channel_id: toBigInt32(chatId.channelId),\n thread_root_message_index: threadRootMessageIndex,\n max_messages: MAX_MESSAGES,\n max_events: maxEvents,\n start_index: startIndex,\n ascending: ascending,\n latest_known_update: latestKnownUpdate,\n latest_client_event_index: undefined,\n };\n return this.executeMsgpackQuery(\"events\", args, (res) => {\n return getEventsResponse(this.principal, res, chatId, latestKnownUpdate);\n }, CommunityEventsArgs, CommunityEventsResponse);\n }\n getCachedEventsByIndex(chatId, eventIndexes, threadRootMessageIndex) {\n return getCachedEventsByIndex(this.db, eventIndexes, {\n chatId,\n threadRootMessageIndex,\n });\n }\n eventsByIndex(chatId, eventIndexes, threadRootMessageIndex, latestKnownUpdate) {\n return this.getCachedEventsByIndex(chatId, eventIndexes, threadRootMessageIndex).then((res) => this.handleMissingEvents(chatId, res, threadRootMessageIndex, latestKnownUpdate));\n }\n eventsByIndexFromBackend(chatId, eventIndexes, threadRootMessageIndex, latestKnownUpdate) {\n const args = {\n channel_id: toBigInt32(chatId.channelId),\n thread_root_message_index: threadRootMessageIndex,\n events: eventIndexes,\n latest_known_update: latestKnownUpdate,\n latest_client_event_index: [],\n };\n return this.executeMsgpackQuery(\"events_by_index\", args, (res) => {\n return getEventsResponse(this.principal, res, chatId, latestKnownUpdate);\n }, CommunityEventsByIndexArgs, CommunityEventsResponse);\n }\n async eventsWindow(chatId, eventIndexRange, messageIndex, threadRootMessageIndex, latestKnownUpdate) {\n const [cachedEvents, missing, totalMiss] = await getCachedEventsWindowByMessageIndex(this.db, eventIndexRange, { chatId, threadRootMessageIndex }, messageIndex);\n if (totalMiss || missing.size >= MAX_MISSING) {\n // if we have exceeded the maximum number of missing events, let's just consider it a complete miss and go to the api\n console.log(\"We didn't get enough back from the cache, going to the api\", missing.size, totalMiss);\n return this.eventsWindowFromBackend(chatId, messageIndex, threadRootMessageIndex, latestKnownUpdate)\n .then((resp) => this.setCachedEvents(chatId, resp, threadRootMessageIndex))\n .catch((err) => {\n if (err instanceof ResponseTooLargeError) {\n console.log(\"Response size too large, we will try to split the window request into a a few chunks\");\n return chunkedChatEventsWindowFromBackend((index, ascending, chunkSize) => this.eventsFromBackend(chatId, index, ascending, threadRootMessageIndex, latestKnownUpdate, chunkSize), (index, chunkSize) => this.eventsWindowFromBackend(chatId, index, threadRootMessageIndex, latestKnownUpdate, chunkSize), eventIndexRange, messageIndex).then((resp) => this.setCachedEvents(chatId, resp, threadRootMessageIndex));\n }\n else {\n throw err;\n }\n });\n }\n else {\n return this.handleMissingEvents(chatId, [cachedEvents, missing], threadRootMessageIndex, latestKnownUpdate);\n }\n }\n async eventsWindowFromBackend(chatId, messageIndex, threadRootMessageIndex, latestKnownUpdate, maxEvents = MAX_EVENTS) {\n const args = {\n channel_id: toBigInt32(chatId.channelId),\n thread_root_message_index: threadRootMessageIndex,\n max_messages: MAX_MESSAGES,\n max_events: maxEvents,\n mid_point: messageIndex,\n latest_known_update: latestKnownUpdate,\n latest_client_event_index: undefined,\n };\n return this.executeMsgpackQuery(\"events_window\", args, (res) => getEventsResponse(this.principal, res, chatId, latestKnownUpdate), CommunityEventsWindowArgs, CommunityEventsResponse);\n }\n async getMessagesByMessageIndex(chatId, messageIndexes, latestKnownUpdate) {\n const fromCache = await loadMessagesByMessageIndex(this.db, chatId, messageIndexes);\n if (fromCache.missing.size > 0) {\n console.log(\"Missing idxs from the cached: \", fromCache.missing);\n const resp = await this.getMessagesByMessageIndexFromBackend(chatId, [...fromCache.missing], latestKnownUpdate).then((resp) => this.setCachedEvents(chatId, resp));\n return resp === \"events_failed\"\n ? resp\n : {\n events: [...fromCache.messageEvents, ...resp.events],\n expiredEventRanges: [],\n expiredMessageRanges: [],\n latestEventIndex: resp.latestEventIndex,\n };\n }\n return {\n events: fromCache.messageEvents,\n expiredEventRanges: [],\n expiredMessageRanges: [],\n latestEventIndex: undefined,\n };\n }\n getMessagesByMessageIndexFromBackend(chatId, messageIndexes, latestKnownUpdate) {\n const args = {\n channel_id: toBigInt32(chatId.channelId),\n thread_root_message_index: undefined,\n messages: messageIndexes,\n invite_code: mapOptional(this.inviteCode, textToCode),\n latest_known_update: latestKnownUpdate,\n latest_client_event_index: undefined,\n };\n return this.executeMsgpackQuery(\"messages_by_message_index\", args, (resp) => getMessagesByMessageIndexResponse(this.principal, resp, chatId, latestKnownUpdate), CommunityMessagesByMessageIndexArgs, CommunityMessagesByMessageIndexResponse);\n }\n handleMissingEvents(chatId, [cachedEvents, missing], threadRootMessageIndex, latestKnownUpdate) {\n if (missing.size === 0) {\n return Promise.resolve(cachedEvents);\n }\n else {\n return this.eventsByIndexFromBackend(chatId, [...missing], threadRootMessageIndex, latestKnownUpdate)\n .then((resp) => this.setCachedEvents(chatId, resp, threadRootMessageIndex))\n .then((resp) => {\n if (resp !== \"events_failed\") {\n return mergeSuccessResponses(cachedEvents, resp);\n }\n return resp;\n });\n }\n }\n setCachedEvents(chatId, resp, threadRootMessageIndex) {\n setCachedEvents(this.db, chatId, resp, threadRootMessageIndex).catch((err) => this.config.logger.error(\"Error writing cached channel events\", err));\n return resp;\n }\n getInviteCode() {\n return this.executeMsgpackQuery(\"invite_code\", {}, inviteCodeResponse, TEmpty, CommunityInviteCodeResponse);\n }\n leaveChannel(chatId) {\n return this.executeMsgpackUpdate(\"leave_channel\", {\n channel_id: toBigInt32(chatId.channelId),\n }, leaveGroupResponse, CommunityLeaveChannelArgs, CommunityLeaveChannelResponse);\n }\n localUserIndex() {\n return this.executeMsgpackQuery(\"local_user_index\", {}, (resp) => principalBytesToString(resp.Success), TEmpty, CommunityLocalUserIndexResponse);\n }\n unpinMessage(chatId, messageIndex) {\n return this.executeMsgpackUpdate(\"unpin_message\", {\n channel_id: toBigInt32(chatId.channelId),\n message_index: messageIndex,\n }, unpinMessageResponse, CommunityPinMessageArgs, CommunityPinMessageResponse);\n }\n pinMessage(chatId, messageIndex) {\n return this.executeMsgpackUpdate(\"pin_message\", {\n channel_id: toBigInt32(chatId.channelId),\n message_index: messageIndex,\n }, pinMessageResponse, CommunityPinMessageArgs, CommunityPinMessageResponse);\n }\n removeMember(userId) {\n return this.executeMsgpackUpdate(\"remove_member\", {\n user_id: principalStringToBytes(userId),\n }, removeMemberResponse, CommunityRemoveMemberArgs, CommunityRemoveMemberResponse);\n }\n removeMemberFromChannel(chatId, userId) {\n return this.executeMsgpackUpdate(\"remove_member_from_channel\", {\n channel_id: toBigInt32(chatId.channelId),\n user_id: principalStringToBytes(userId),\n }, removeMemberFromChannelResponse, CommunityRemoveMemberFromChannelArgs, CommunityRemoveMemberFromChannelResponse);\n }\n removeReaction(chatId, messageId, reaction, threadRootMessageIndex) {\n return this.executeMsgpackUpdate(\"remove_reaction\", {\n channel_id: toBigInt32(chatId.channelId),\n message_id: messageId,\n reaction,\n thread_root_message_index: threadRootMessageIndex,\n }, addRemoveReactionResponse, CommunityRemoveReactionArgs, CommunityRemoveReactionResponse);\n }\n resetInviteCode() {\n return this.executeMsgpackUpdate(\"reset_invite_code\", {}, enableOrResetInviteCodeResponse, TEmpty, CommunityEnableInviteCodeResponse);\n }\n searchChannel(chatId, maxResults, users, searchTerm) {\n return this.executeMsgpackQuery(\"search_channel\", {\n channel_id: toBigInt32(chatId.channelId),\n max_results: maxResults,\n users: users.map(principalStringToBytes),\n search_term: searchTerm,\n }, (resp) => searchGroupChatResponse(resp, chatId), CommunitySearchChannelArgs, CommunitySearchChannelResponse);\n }\n async getCommunityDetails(id, communityLastUpdated) {\n const fromCache = await getCachedCommunityDetails(this.db, id.communityId);\n if (fromCache !== undefined) {\n if (fromCache.lastUpdated >= communityLastUpdated || offline()) {\n return fromCache;\n }\n else {\n return this.getCommunityDetailsUpdates(id, fromCache);\n }\n }\n const response = await this.getCommunityDetailsFromBackend();\n if (response !== \"failure\") {\n await setCachedCommunityDetails(this.db, id.communityId, response);\n }\n return response;\n }\n getCommunityDetailsFromBackend() {\n return this.executeMsgpackQuery(\"selected_initial\", {\n invite_code: mapOptional(this.inviteCode, textToCode),\n }, communityDetailsResponse, CommunitySelectedInitialArgs, CommunitySelectedInitialResponse);\n }\n async getCommunityDetailsUpdates(id, previous) {\n const response = await this.getCommunityDetailsUpdatesFromBackend(previous);\n if (response.lastUpdated > previous.lastUpdated) {\n await setCachedCommunityDetails(this.db, id.communityId, response);\n }\n return response;\n }\n async getCommunityDetailsUpdatesFromBackend(previous) {\n const updatesResponse = await this.executeMsgpackQuery(\"selected_updates_v2\", {\n updates_since: previous.lastUpdated,\n invite_code: mapOptional(this.inviteCode, textToCode),\n }, communityDetailsUpdatesResponse, CommunitySelectedUpdatesArgs, CommunitySelectedUpdatesResponse);\n if (updatesResponse.kind === \"failure\") {\n return previous;\n }\n if (updatesResponse.kind === \"success_no_updates\") {\n return {\n ...previous,\n lastUpdated: updatesResponse.lastUpdated,\n };\n }\n updatesResponse.botsRemoved.forEach((botId) => removeCachedChannelApiKeys(this.principal, this.communityId, botId));\n return mergeCommunityDetails(previous, updatesResponse);\n }\n async getChannelDetails(chatId, chatLastUpdated) {\n const cacheKey = `${chatId.communityId}_${chatId.channelId}`;\n const fromCache = await getCachedGroupDetails(this.db, cacheKey);\n if (fromCache !== undefined) {\n if (fromCache.timestamp >= chatLastUpdated || offline()) {\n return fromCache;\n }\n else {\n return this.getChannelDetailsUpdates(chatId, cacheKey, fromCache);\n }\n }\n const response = await this.getChannelDetailsFromBackend(chatId);\n if (response !== \"failure\") {\n await setCachedGroupDetails(this.db, cacheKey, response);\n }\n return response;\n }\n getChannelDetailsFromBackend(chatId) {\n return this.executeMsgpackQuery(\"selected_channel_initial\", {\n channel_id: toBigInt32(chatId.channelId),\n }, groupDetailsResponse, CommunitySelectedChannelInitialArgs, CommunitySelectedChannelInitialResponse);\n }\n async getChannelDetailsUpdates(chatId, cacheKey, previous) {\n const response = await this.getChannelDetailsUpdatesFromBackend(chatId, previous);\n if (response.timestamp > previous.timestamp) {\n await setCachedGroupDetails(this.db, cacheKey, response);\n }\n return response;\n }\n async getChannelDetailsUpdatesFromBackend(chatId, previous) {\n const updatesResponse = await this.executeMsgpackQuery(\"selected_channel_updates_v2\", {\n channel_id: toBigInt32(chatId.channelId),\n updates_since: previous.timestamp,\n }, groupDetailsUpdatesResponse, CommunitySelectedChannelUpdatesArgs, CommunitySelectedChannelUpdatesResponse);\n if (updatesResponse.kind === \"failure\") {\n return previous;\n }\n if (updatesResponse.kind === \"success_no_updates\") {\n return {\n ...previous,\n timestamp: updatesResponse.timestamp,\n };\n }\n return mergeGroupChatDetails(previous, updatesResponse);\n }\n sendMessage(chatId, senderName, senderDisplayName, mentioned, event, threadRootMessageIndex, communityRulesAccepted, channelRulesAccepted, messageFilterFailed, newAchievement, onRequestAccepted) {\n // pre-emtively remove the failed message from indexeddb - it will get re-added if anything goes wrong\n removeFailedMessage(this.db, chatId, event.event.messageId, threadRootMessageIndex);\n const dataClient = new DataClient(this.identity, this.agent, this.config);\n const uploadContentPromise = event.event.forwarded\n ? dataClient.forwardData(event.event.content, [chatId.communityId])\n : dataClient.uploadData(event.event.content, [chatId.communityId]);\n return uploadContentPromise.then((content) => {\n const newEvent = content !== undefined ? { ...event, event: { ...event.event, content } } : event;\n const args = {\n channel_id: toBigInt32(chatId.channelId),\n content: apiMessageContent(newEvent.event.content),\n message_id: newEvent.event.messageId,\n sender_name: senderName,\n sender_display_name: senderDisplayName,\n community_rules_accepted: communityRulesAccepted,\n channel_rules_accepted: channelRulesAccepted,\n replies_to: mapOptional(newEvent.event.repliesTo, (replyContext) => ({\n event_index: replyContext.eventIndex,\n })),\n mentioned: mentioned.map(apiUserV2),\n forwarding: newEvent.event.forwarded,\n thread_root_message_index: threadRootMessageIndex,\n message_filter_failed: messageFilterFailed,\n block_level_markdown: newEvent.event.blockLevelMarkdown,\n new_achievement: newAchievement,\n };\n return this.executeMsgpackUpdate(\"send_message\", args, sendMessageResponseV2, CommunitySendMessageArgs, CommunitySendMessageResponse, onRequestAccepted)\n .then((resp) => {\n const retVal = [resp, newEvent.event];\n setCachedMessageFromSendResponse(this.db, chatId, newEvent, threadRootMessageIndex)(retVal);\n return retVal;\n })\n .catch((err) => {\n recordFailedMessage(this.db, chatId, newEvent, threadRootMessageIndex);\n throw err;\n });\n });\n }\n registerPollVote(chatId, messageIdx, answerIdx, voteType, threadRootMessageIndex, newAchievement) {\n return this.executeMsgpackUpdate(\"register_poll_vote\", {\n channel_id: toBigInt32(chatId.channelId),\n thread_root_message_index: threadRootMessageIndex,\n poll_option: answerIdx,\n operation: voteType === \"register\" ? \"RegisterVote\" : \"DeleteVote\",\n message_index: messageIdx,\n new_achievement: newAchievement,\n }, registerPollVoteResponse, CommunityRegisterPollVoteArgs, CommunityRegisterPollVoteResponse);\n }\n channelSummary(chatId) {\n return this.executeMsgpackQuery(\"channel_summary\", {\n channel_id: toBigInt32(chatId.channelId),\n invite_code: mapOptional(this.inviteCode, textToCode),\n }, (resp) => communityChannelSummaryResponse(resp, this.communityId), CommunityChannelSummaryArgs, CommunityChannelSummaryResponse).catch((err) => {\n if (err instanceof DestinationInvalidError) {\n return { kind: \"canister_not_found\" };\n }\n else {\n throw err;\n }\n });\n }\n importGroup(id) {\n return this.executeMsgpackUpdate(\"import_group\", {\n group_id: principalStringToBytes(id.groupId),\n }, (resp) => importGroupResponse(this.communityId, resp), CommunityImportGroupArgs, CommunityImportGroupResponse);\n }\n summary() {\n return this.executeMsgpackQuery(\"summary\", {\n invite_code: mapOptional(this.inviteCode, textToCode),\n }, summaryResponse, CommunitySummaryArgs, TCommunitySummaryResponse);\n }\n exploreChannels(searchTerm, pageSize, pageIndex) {\n return this.executeMsgpackQuery(\"explore_channels\", {\n page_size: pageSize,\n page_index: pageIndex,\n search_term: searchTerm,\n invite_code: mapOptional(this.inviteCode, textToCode),\n }, (resp) => exploreChannelsResponse(resp, this.communityId), CommunityExploreChannelsArgs, CommunityExploreChannelsResponse);\n }\n summaryUpdates(updatesSince) {\n return this.executeMsgpackQuery(\"summary_updates\", {\n updates_since: updatesSince,\n invite_code: mapOptional(this.inviteCode, textToCode),\n }, summaryUpdatesResponse, CommunitySummaryUpdatesArgs, TCommunitySummaryUpdatesResponse);\n }\n toggleMuteChannelNotifications(chatId, mute) {\n return this.executeMsgpackUpdate(\"toggle_mute_notifications\", {\n channel_id: chatId ? toBigInt32(chatId.channelId) : undefined,\n mute,\n }, toggleNotificationsResponse, CommunityToggleMuteNotificationsArgs, CommunityToggleMuteNotificationsResponse);\n }\n unblockUser(userId) {\n return this.executeMsgpackUpdate(\"unblock_user\", {\n user_id: principalStringToBytes(userId),\n }, unblockUserResponse, CommunityUnblockUserArgs, CommunityUnblockUserResponse);\n }\n undeleteMessage(chatId, messageId, threadRootMessageIndex) {\n return this.executeMsgpackUpdate(\"undelete_messages\", {\n channel_id: toBigInt32(chatId.channelId),\n thread_root_message_index: threadRootMessageIndex,\n message_ids: [messageId],\n }, undeleteMessageResponse, CommunityUndeleteMessagesArgs, CommunityUndeleteMessagesResponse);\n }\n threadPreviews(chatId, threadRootMessageIndexes, latestClientThreadUpdate) {\n return this.executeMsgpackQuery(\"thread_previews\", {\n channel_id: toBigInt32(chatId.channelId),\n threads: threadRootMessageIndexes,\n latest_client_thread_update: latestClientThreadUpdate,\n }, (resp) => threadPreviewsResponse(resp, chatId, latestClientThreadUpdate), CommunityThreadPreviewsArgs, CommunityThreadPreviewsResponse);\n }\n registerProposalVote(channelId, messageIdx, adopt) {\n return this.executeMsgpackUpdate(\"register_proposal_vote\", {\n channel_id: toBigInt32(channelId),\n adopt,\n message_index: messageIdx,\n }, registerProposalVoteResponse, CommunityRegisterProposalVoteArgs, CommunityRegisterProposalVoteResponse);\n }\n updateChannel(chatId, name, description, rules, permissions, avatar, eventsTimeToLiveMs, gateConfig, isPublic, messagesVisibleToNonMembers, externalUrl) {\n return this.executeMsgpackUpdate(\"update_channel\", {\n channel_id: toBigInt32(chatId.channelId),\n name: name,\n description,\n external_url: externalUrl === undefined ? \"NoChange\" : { SetToSome: externalUrl },\n permissions_v2: mapOptional(permissions, apiOptionalGroupPermissions),\n rules: mapOptional(rules, apiUpdatedRules),\n public: isPublic,\n events_ttl: apiOptionUpdateV2(identity, eventsTimeToLiveMs),\n gate_config: gateConfig === undefined\n ? \"NoChange\"\n : gateConfig.gate.kind === \"no_gate\"\n ? \"SetToNone\"\n : {\n SetToSome: apiAccessGateConfig(gateConfig),\n },\n avatar: avatar === undefined\n ? \"NoChange\"\n : {\n SetToSome: {\n id: DataClient.newBlobId(),\n mime_type: \"image/jpg\",\n data: avatar,\n },\n },\n messages_visible_to_non_members: messagesVisibleToNonMembers,\n }, updateGroupResponse, CommunityUpdateChannelArgs, CommunityUpdateChannelResponse);\n }\n updateCommunity(name, description, rules, permissions, avatar, banner, gateConfig, isPublic, primaryLanguage) {\n return this.executeMsgpackUpdate(\"update_community\", {\n name,\n description,\n permissions: mapOptional(permissions, apiOptionalCommunityPermissions),\n rules: mapOptional(rules, apiUpdatedRules),\n public: isPublic,\n primary_language: primaryLanguage,\n gate_config: gateConfig === undefined\n ? \"NoChange\"\n : gateConfig.gate.kind === \"no_gate\"\n ? \"SetToNone\"\n : {\n SetToSome: apiAccessGateConfig(gateConfig),\n },\n avatar: avatar === undefined\n ? \"NoChange\"\n : {\n SetToSome: {\n id: DataClient.newBlobId(),\n mime_type: \"image/jpg\",\n data: avatar,\n },\n },\n banner: banner === undefined\n ? \"NoChange\"\n : {\n SetToSome: {\n id: DataClient.newBlobId(),\n mime_type: \"image/jpg\",\n data: banner,\n },\n },\n }, updateCommunityResponse, CommunityUpdateCommunityArgs, CommunityUpdateCommunityResponse);\n }\n createUserGroup(name, users) {\n return this.executeMsgpackUpdate(\"create_user_group\", {\n name,\n user_ids: users.map(principalStringToBytes),\n }, createUserGroupResponse, CommunityCreateUserGroupArgs, CommunityCreateUserGroupResponse);\n }\n updateUserGroup(userGroupId, name, usersToAdd, usersToRemove) {\n return this.executeMsgpackUpdate(\"update_user_group\", {\n user_group_id: userGroupId,\n name,\n users_to_add: usersToAdd.map(principalStringToBytes),\n users_to_remove: usersToRemove.map(principalStringToBytes),\n }, updateUserGroupResponse, CommunityUpdateUserGroupArgs, CommunityUpdateUserGroupResponse);\n }\n setMemberDisplayName(displayName, newAchievement) {\n return this.executeMsgpackUpdate(\"set_member_display_name\", {\n display_name: displayName,\n new_achievement: newAchievement,\n }, setMemberDisplayNameResponse, CommunitySetMemberDisplayNameArgs, CommunitySetMemberDisplayNameResponse);\n }\n deleteUserGroups(userGroupIds) {\n return this.executeMsgpackUpdate(\"delete_user_groups\", {\n user_group_ids: userGroupIds,\n }, deleteUserGroupsResponse, CommunityDeleteUserGroupsArgs, CommunityDeleteUserGroupsResponse);\n }\n followThread(channelId, threadRootMessageIndex, follow, newAchievement) {\n const args = {\n channel_id: toBigInt32(channelId),\n thread_root_message_index: threadRootMessageIndex,\n new_achievement: newAchievement,\n };\n return this.executeMsgpackUpdate(follow ? \"follow_thread\" : \"unfollow_thread\", args, followThreadResponse, CommunityFollowThreadArgs, CommunityFollowThreadResponse);\n }\n reportMessage(channelId, threadRootMessageIndex, messageId, deleteMessage) {\n return this.executeMsgpackUpdate(\"report_message\", {\n channel_id: toBigInt32(channelId),\n thread_root_message_index: threadRootMessageIndex,\n message_id: messageId,\n delete: deleteMessage,\n }, reportMessageResponse, CommunityReportMessageArgs, CommunityReportMessageResponse);\n }\n acceptP2PSwap(channelId, threadRootMessageIndex, messageId, pin, newAchievement) {\n return this.executeMsgpackUpdate(\"accept_p2p_swap\", {\n channel_id: toBigInt32(channelId),\n thread_root_message_index: threadRootMessageIndex,\n message_id: messageId,\n pin,\n new_achievement: newAchievement,\n }, acceptP2PSwapResponse, CommunityAcceptP2pSwapArgs, CommunityAcceptP2pSwapResponse);\n }\n cancelP2PSwap(channelId, threadRootMessageIndex, messageId) {\n return this.executeMsgpackUpdate(\"cancel_p2p_swap\", {\n channel_id: toBigInt32(channelId),\n thread_root_message_index: threadRootMessageIndex,\n message_id: messageId,\n }, cancelP2PSwapResponse, CommunityCancelP2pSwapArgs, CommunityCancelP2pSwapResponse);\n }\n joinVideoCall(channelId, messageId, newAchievement) {\n return this.executeMsgpackUpdate(\"join_video_call\", {\n message_id: messageId,\n channel_id: toBigInt32(channelId),\n new_achievement: newAchievement,\n }, joinVideoCallResponse, CommunityJoinVideoCallArgs, CommunitySetVideoCallPresenceResponse);\n }\n setVideoCallPresence(channelId, messageId, presence, newAchievement) {\n return this.executeMsgpackUpdate(\"set_video_call_presence\", {\n channel_id: toBigInt32(channelId),\n message_id: messageId,\n presence: apiVideoCallPresence(presence),\n new_achievement: newAchievement,\n }, setVideoCallPresence, CommunitySetVideoCallPresenceArgs, CommunitySetVideoCallPresenceResponse);\n }\n videoCallParticipants(channelId, messageId, updatesSince) {\n return this.executeMsgpackQuery(\"video_call_participants\", {\n channel_id: toBigInt32(channelId),\n message_id: messageId,\n updated_since: updatesSince,\n }, videoCallParticipantsResponse, CommunityVideoCallParticipantsArgs, CommunityVideoCallParticipantsResponse);\n }\n cancelInvites(channelId, userIds) {\n return this.executeMsgpackUpdate(\"cancel_invites\", {\n channel_id: mapOptional(channelId, (cid) => toBigInt32(cid)),\n user_ids: userIds.map(principalStringToBytes),\n }, (value) => value === \"Success\", CommunityCancelInvitesArgs, CommunityCancelInvitesResponse);\n }\n updateInstalledBot(botId, grantedPermissions) {\n return this.executeMsgpackUpdate(\"update_bot\", {\n bot_id: principalStringToBytes(botId),\n granted_permissions: apiExternalBotPermissions(grantedPermissions),\n }, updateBotResponse, CommunityUpdateBotArgs, CommunityUpdateBotResponse);\n }\n generateBotApiKey(botId, permissions, channelId) {\n return this.executeMsgpackUpdate(\"generate_bot_api_key\", {\n bot_id: principalStringToBytes(botId),\n requested_permissions: apiExternalBotPermissions(permissions),\n channel_id: mapOptional(channelId, toBigInt32),\n }, generateApiKeyResponse, CommunityGenerateBotApiKeyArgs, CommunityGenerateBotApiKeyResponse);\n }\n getApiKey(botId, channelId) {\n return this.executeMsgpackQuery(\"api_key\", {\n channel_id: channelId ? toBigInt32(channelId) : undefined,\n bot_id: principalStringToBytes(botId),\n }, (resp) => {\n if (typeof resp === \"object\" && \"Success\" in resp) {\n return resp.Success;\n }\n console.log(\"Failed to get community api key: \", botId, channelId, resp);\n return undefined;\n }, CommunityApiKeyArgs, CommunityApiKeyResponse);\n }\n}\n","import { CommunityMap, ChatMap, mapOptionUpdate, applyOptionUpdate, bigIntMax, } from \"openchat-shared\";\nimport { toRecord } from \"./list\";\nexport function mergeCommunities(userCanisterCommunities, communityCanisterCommunities) {\n const userCanisterCommunityLookup = CommunityMap.fromList(userCanisterCommunities);\n return communityCanisterCommunities.map((community) => {\n const u = userCanisterCommunityLookup.get(community.id);\n return {\n ...community,\n membership: {\n ...community.membership,\n archived: u?.archived ?? community.membership.archived,\n pinned: u?.pinned ?? community.membership.pinned,\n index: u?.index ?? community.membership.index,\n },\n channels: mergeChannels(u?.channels ?? [], community.channels),\n };\n });\n}\nexport function mergeChannels(userCanisterChannels, communityCanisterChannels) {\n const userCanisterGroupLookup = ChatMap.fromList(userCanisterChannels);\n return communityCanisterChannels.map((c) => {\n const u = userCanisterGroupLookup.get(c.id);\n return {\n ...c,\n dateReadPinned: u?.dateReadPinned,\n membership: {\n ...c.membership,\n latestThreads: mergeThreads([], c.membership.latestThreads, [], u?.threadsRead ?? {}),\n readByMeUpTo: u?.readByMeUpTo,\n archived: u?.archived ?? false,\n },\n };\n });\n}\nexport function mergeCommunityUpdates(communities, userCanisterUpdates, communityCanisterUpdates) {\n const userLookup = CommunityMap.fromList(userCanisterUpdates);\n const communityLookup = CommunityMap.fromList(communityCanisterUpdates);\n return communities.map((community) => {\n const u = userLookup.get(community.id);\n const c = communityLookup.get(community.id);\n const avatarUpdate = mapOptionUpdate(c?.avatarId, (avatarId) => ({\n blobId: avatarId,\n canisterId: community.id.communityId,\n }));\n const bannerUpdate = mapOptionUpdate(c?.bannerId, (bannerId) => ({\n blobId: bannerId,\n canisterId: community.id.communityId,\n }));\n const channelsRemoved = new Set((c?.channelsRemoved ?? []).map((c) => c.channelId));\n const channelsAdded = c?.channelsAdded ?? [];\n const currentChannels = community.channels\n .filter((c) => !channelsRemoved.has(c.id.channelId))\n .concat(channelsAdded);\n return {\n kind: community.kind,\n id: community.id,\n name: c?.name ?? community?.name,\n latestEventIndex: c?.latestEventIndex ?? community.latestEventIndex,\n lastUpdated: c?.lastUpdated ?? community.lastUpdated,\n description: c?.description ?? community.description,\n memberCount: c?.memberCount ?? community.memberCount,\n metrics: c?.metrics ?? community.metrics,\n avatar: {\n ...community.avatar,\n blobReference: applyOptionUpdate(community.avatar.blobReference, avatarUpdate),\n },\n banner: {\n ...community.banner,\n blobReference: applyOptionUpdate(community.banner.blobReference, bannerUpdate),\n },\n membership: {\n ...community.membership,\n role: c?.membership?.role ?? community.membership.role,\n archived: u?.archived ?? community.membership.archived,\n pinned: u?.pinned ?? community.membership.pinned,\n index: u?.index ?? community.membership.index,\n displayName: applyOptionUpdate(community.membership.displayName, c?.membership?.displayName),\n rulesAccepted: c?.membership?.rulesAccepted ?? community.membership.rulesAccepted,\n lapsed: c?.membership?.lapsed ?? community.membership.lapsed,\n },\n channels: mergeChannelUpdates(currentChannels, u?.channels ?? [], c?.channelsUpdated ?? []),\n gateConfig: applyOptionUpdate(community.gateConfig, c?.gateConfig) ?? {\n gate: { kind: \"no_gate\" },\n expiry: undefined,\n },\n level: \"community\",\n public: c?.public ?? community.public,\n frozen: applyOptionUpdate(community.frozen, c?.frozen) ?? false,\n historyVisible: community.historyVisible,\n permissions: c?.permissions ?? community.permissions,\n primaryLanguage: c?.primaryLanguage ?? community.primaryLanguage,\n userGroups: mergeUserGroups(community.userGroups, c?.userGroups ?? [], c?.userGroupsDeleted ?? new Set()),\n localUserIndex: community.localUserIndex,\n isInvited: false,\n verified: c?.verified ?? community.verified,\n };\n });\n}\nfunction mergeUserGroups(existing, updated, deleted) {\n deleted.forEach((id) => existing.delete(id));\n updated.forEach((g) => existing.set(g.id, g));\n return new Map(existing);\n}\nfunction mergeChannelUpdates(channels, userCanisterUpdates, communityCanisterUpdates) {\n const userLookup = ChatMap.fromList(userCanisterUpdates);\n const channelLookup = ChatMap.fromList(communityCanisterUpdates);\n return channels.map((channel) => {\n const u = userLookup.get(channel.id);\n const c = channelLookup.get(channel.id);\n if (u === undefined && c === undefined)\n return channel;\n const latestMessage = c?.latestMessage ?? channel.latestMessage;\n const readByMeUpTo = u?.readByMeUpTo ?? channel.membership.readByMeUpTo;\n const blobReferenceUpdate = mapOptionUpdate(c?.avatarId, (avatarId) => ({\n blobId: avatarId,\n canisterId: channel.id.communityId,\n }));\n const description = c?.description ?? channel.description;\n return {\n kind: \"channel\",\n id: channel.id,\n name: c?.name ?? channel.name,\n description,\n minVisibleEventIndex: channel.minVisibleEventIndex,\n minVisibleMessageIndex: channel.minVisibleMessageIndex,\n lastUpdated: c?.lastUpdated ?? channel.lastUpdated,\n memberCount: c?.memberCount ?? channel.memberCount,\n public: c?.public ?? channel.public,\n permissions: c?.permissions ?? channel.permissions,\n historyVisible: channel.historyVisible,\n subtype: applyOptionUpdate(channel.subtype, c?.subtype),\n previewed: false,\n frozen: channel.frozen, // frozen doesn't exist on CommunityCanisterChannelSummaryUpdates\n latestEventIndex: c?.latestEventIndex ?? channel.latestEventIndex,\n latestMessageIndex: c?.latestMessageIndex ?? channel.latestMessageIndex,\n latestMessage,\n metrics: c?.metrics ?? channel.metrics,\n blobReference: applyOptionUpdate(channel.blobReference, blobReferenceUpdate),\n dateLastPinned: c?.dateLastPinned ?? channel.dateLastPinned,\n dateReadPinned: u?.dateReadPinned ?? channel.dateReadPinned,\n gateConfig: applyOptionUpdate(channel.gateConfig, c?.gateConfig) ?? {\n gate: { kind: \"no_gate\" },\n expiry: undefined,\n },\n level: \"channel\",\n eventsTTL: applyOptionUpdate(channel.eventsTTL, c?.eventsTTL),\n eventsTtlLastUpdated: bigIntMax(channel.eventsTtlLastUpdated, c?.eventsTtlLastUpdated ?? BigInt(0)),\n videoCallInProgress: applyOptionUpdate(channel.videoCallInProgress, c?.videoCallInProgress),\n membership: {\n ...channel.membership,\n mentions: c === undefined\n ? channel.membership.mentions\n : [...(c.membership?.mentions ?? []), ...channel.membership.mentions],\n role: c?.membership?.myRole ?? channel.membership.role,\n latestThreads: mergeThreads(channel.membership.latestThreads, c?.membership?.latestThreads ?? [], c?.membership?.unfollowedThreads ?? [], u?.threadsRead ?? {}),\n readByMeUpTo: readByMeUpTo !== undefined && latestMessage !== undefined\n ? Math.min(readByMeUpTo, latestMessage.event.messageIndex)\n : readByMeUpTo,\n notificationsMuted: c?.membership?.notificationsMuted ?? channel.membership.notificationsMuted,\n myMetrics: c?.membership?.myMetrics ?? channel.membership.myMetrics,\n archived: u?.archived ?? channel.membership.archived,\n rulesAccepted: c?.membership?.rulesAccepted ?? channel.membership.rulesAccepted,\n lapsed: c?.membership?.lapsed ?? channel.membership.lapsed,\n },\n isInvited: false,\n messagesVisibleToNonMembers: c?.messageVisibleToNonMembers ?? channel.messagesVisibleToNonMembers,\n externalUrl: applyOptionUpdate(channel.externalUrl, c?.externalUrl),\n };\n });\n}\nfunction mergeThreads(current, communityCanisterUpdates, unfollowedThreads, readUpToUpdates) {\n const initial = current.filter((t) => !unfollowedThreads.includes(t.threadRootMessageIndex));\n const threadsRecord = toRecord(initial, (t) => t.threadRootMessageIndex);\n for (const groupUpdate of communityCanisterUpdates) {\n threadsRecord[groupUpdate.threadRootMessageIndex] = {\n ...threadsRecord[groupUpdate.threadRootMessageIndex],\n ...groupUpdate,\n };\n }\n return Object.values(threadsRecord).map((t) => {\n const readUpToUpdate = readUpToUpdates[t.threadRootMessageIndex];\n return readUpToUpdate !== undefined && readUpToUpdate > (t.readUpTo ?? -1)\n ? { ...t, readUpTo: readUpToUpdate }\n : t;\n });\n}\nexport function isSuccessfulCommunitySummaryResponse(response) {\n return \"id\" in response;\n}\n","import { ANON_USER_ID } from \"openchat-shared\";\nimport { AnonymousOperationError } from \"openchat-shared\";\nexport class AnonUserClient {\n get userId() {\n return ANON_USER_ID;\n }\n static create() {\n console.debug(\"ANON: creating anonymous user client\");\n return new AnonUserClient();\n }\n manageFavouriteChats(_toAdd, _toRemove) {\n return Promise.resolve(\"success\");\n }\n getInitialState() {\n return Promise.resolve({\n blockedUsers: [],\n communities: {\n summaries: [],\n },\n groupChats: {\n summaries: [],\n pinned: [],\n cached: undefined,\n },\n avatarId: undefined,\n directChats: {\n summaries: [],\n pinned: [],\n },\n favouriteChats: {\n chats: [],\n pinned: [],\n },\n timestamp: BigInt(Date.now()),\n suspended: false,\n pinNumberSettings: undefined,\n localUserIndex: \"\",\n achievements: [],\n achievementsLastSeen: 0n,\n streakEnds: 0n,\n streak: 0,\n nextDailyClaim: 0n,\n chitBalance: 0,\n totalChitEarned: 0,\n referrals: [],\n walletConfig: { kind: \"auto_wallet\", minDollarValue: 1 },\n messageActivitySummary: {\n readUpToTimestamp: 0n,\n latestTimestamp: 0n,\n unreadCount: 0,\n },\n bots: new Map(),\n apiKeys: new Map(),\n bitcoinAddress: undefined,\n });\n }\n getUpdates(_updatesSince) {\n return Promise.resolve({\n kind: \"success_no_updates\",\n });\n }\n createCommunity(_community, _rules, _defaultChannels, _defaultChannelRules) {\n throw new AnonymousOperationError();\n }\n createGroup(_group) {\n throw new AnonymousOperationError();\n }\n deleteGroup(_chatId) {\n throw new AnonymousOperationError();\n }\n deleteCommunity(_id) {\n throw new AnonymousOperationError();\n }\n getCachedEventsByIndex(_eventIndexes, _chatId, _threadRootMessageIndex) {\n throw new AnonymousOperationError();\n }\n chatEventsByIndex(_eventIndexes, _chatId, _threadRootMessageIndex, _latestKnownUpdate) {\n throw new AnonymousOperationError();\n }\n async chatEventsWindow(_eventIndexRange, _chatId, _messageIndex, _latestKnownUpdate) {\n throw new AnonymousOperationError();\n }\n async chatEvents(_eventIndexRange, _chatId, _startIndex, _ascending, _threadRootMessageIndex, _latestKnownUpdate) {\n throw new AnonymousOperationError();\n }\n setAvatar(_bytes) {\n throw new AnonymousOperationError();\n }\n editMessage(_recipientId, _message, _threadRootMessageIndex) {\n throw new AnonymousOperationError();\n }\n sendMessage(_chatId, _event, _messageFilterFailed, _threadRootMessageIndex, _pin, _onRequestAccepted) {\n throw new AnonymousOperationError();\n }\n sendMessageToBackend(_chatId, _event, _threadRootMessageIndex) {\n throw new AnonymousOperationError();\n }\n sendMessageWithTransferToGroup(_groupId, _recipientId, _sender, _event, _threadRootMessageIndex, _rulesAccepted) {\n throw new AnonymousOperationError();\n }\n loadSavedCryptoAccounts() {\n return Promise.resolve([]);\n }\n saveCryptoAccount(_) {\n throw new AnonymousOperationError();\n }\n sendMessageWithTransferToChannel(_id, _recipientId, _sender, _event, _threadRootMessageIndex, _communityRulesAccepted, _channelRulesAccepted) {\n throw new AnonymousOperationError();\n }\n blockUser(_userId) {\n throw new AnonymousOperationError();\n }\n unblockUser(_userId) {\n throw new AnonymousOperationError();\n }\n leaveGroup(_chatId) {\n throw new AnonymousOperationError();\n }\n leaveCommunity(_id) {\n throw new AnonymousOperationError();\n }\n markMessagesRead(_request) {\n throw new AnonymousOperationError();\n }\n tipMessage(_messageContext, _messageId, _transfer, _decimals, _pin) {\n throw new AnonymousOperationError();\n }\n addReaction(_otherUserId, _messageId, _reaction, _threadRootMessageIndex) {\n throw new AnonymousOperationError();\n }\n removeReaction(_otherUserId, _messageId, _reaction, _threadRootMessageIndex) {\n throw new AnonymousOperationError();\n }\n deleteMessage(_otherUserId, _messageId, _threadRootMessageIndex) {\n throw new AnonymousOperationError();\n }\n undeleteMessage(_otherUserId, _messageId, _threadRootMessageIndex) {\n throw new AnonymousOperationError();\n }\n searchDirectChat(_chatId, _searchTerm, _maxResults) {\n throw new AnonymousOperationError();\n }\n toggleMuteNotifications(_chatId, _muted) {\n throw new AnonymousOperationError();\n }\n dismissRecommendation(_chatId) {\n throw new AnonymousOperationError();\n }\n getBio() {\n throw new AnonymousOperationError();\n }\n getPublicProfile() {\n throw new AnonymousOperationError();\n }\n setBio(_bio) {\n throw new AnonymousOperationError();\n }\n withdrawCryptocurrency(_domain) {\n throw new AnonymousOperationError();\n }\n pinChat(_chatId, _favourite) {\n throw new AnonymousOperationError();\n }\n unpinChat(_chatId, _favourite) {\n throw new AnonymousOperationError();\n }\n archiveChat(_chatId) {\n throw new AnonymousOperationError();\n }\n unarchiveChat(_chatId) {\n throw new AnonymousOperationError();\n }\n getDeletedMessage(_userId, _messageId) {\n throw new AnonymousOperationError();\n }\n setMessageReminder(_chatId, _eventIndex, _remindAt, _notes, _threadRootMessageIndex) {\n throw new AnonymousOperationError();\n }\n cancelMessageReminder(_reminderId) {\n throw new AnonymousOperationError();\n }\n setCommunityIndexes(_communityIndexes) {\n throw new AnonymousOperationError();\n }\n reportMessage(_chatId, _threadRootMessageIndex, _messageId, _deleteMessage) {\n throw new AnonymousOperationError();\n }\n swapTokens(_swapId, _inputToken, _outputToken, _amountIn, _minAmountOut, _exchangeArgs) {\n throw new AnonymousOperationError();\n }\n tokenSwapStatus(_swapId) {\n throw new AnonymousOperationError();\n }\n approveTransfer(_spender, _ledger, _amount, _expiresIn) {\n throw new AnonymousOperationError();\n }\n deleteDirectChat(_userId, _blockUser) {\n throw new AnonymousOperationError();\n }\n acceptP2PSwap(_userId, _threadRootMessageIndex, _messageId, _pin) {\n throw new AnonymousOperationError();\n }\n cancelP2PSwap(_userId, _messageId) {\n throw new AnonymousOperationError();\n }\n joinVideoCall(_userId, _messageId) {\n throw new AnonymousOperationError();\n }\n setVideoCallPresence(_messageId, _presence) {\n throw new AnonymousOperationError();\n }\n localUserIndex() {\n throw new AnonymousOperationError();\n }\n setPinNumber(_verification, _newPin) {\n throw new AnonymousOperationError();\n }\n chitEvents(_req) {\n throw new AnonymousOperationError();\n }\n markAchievementsSeen(_lastSeen) {\n throw new AnonymousOperationError();\n }\n claimDailyChit() {\n throw new AnonymousOperationError();\n }\n configureWallet(_walletConfig) {\n throw new AnonymousOperationError();\n }\n markActivityFeedRead(_timestamp) {\n throw new AnonymousOperationError();\n }\n messageActivityFeed(_since) {\n throw new AnonymousOperationError();\n }\n updateInstalledBot(_botId, _grantedPermissions) {\n throw new AnonymousOperationError();\n }\n generateBotApiKey(_botId, _permissions) {\n throw new AnonymousOperationError();\n }\n getApiKey(_botId) {\n throw new AnonymousOperationError();\n }\n generateBtcAddress() {\n throw new AnonymousOperationError();\n }\n updateBtcBalance() {\n throw new AnonymousOperationError();\n }\n withdrawBtc(_address, _amount, _pin) {\n throw new AnonymousOperationError();\n }\n}\n","export const idlFactory = ({ IDL }) => {\n const TokenId = IDL.Nat;\n const LatestTokenRow = IDL.Tuple(IDL.Tuple(TokenId, TokenId), IDL.Text, IDL.Float64);\n return IDL.Service({\n 'get_latest': IDL.Func([], [IDL.Vec(LatestTokenRow)], ['query']),\n });\n};\nexport const init = ({ IDL }) => { return []; };\n","export function getLatestResponse(candid, supportedTokens) {\n const supportedSymbols = new Set(supportedTokens.map((t) => t.symbol.toLowerCase()));\n supportedSymbols.add(\"btc\");\n supportedSymbols.add(\"eth\");\n const exchangeRates = {};\n for (const row of candid) {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const [_pair, pairText, rate] = row;\n const [from, to] = parseSymbolPair(pairText);\n if (to === \"usd\" && supportedSymbols.has(from)) {\n exchangeRates[from] = { toUSD: rate };\n }\n }\n return exchangeRates;\n}\nfunction parseSymbolPair(pair) {\n const parts = pair.split(\"/\");\n return [parts[0].toLowerCase(), parts[1].toLowerCase()];\n}\n","import { idlFactory } from \"./candid/idl\";\nimport { CandidCanisterAgent } from \"../canisterAgent/candid\";\nimport { getLatestResponse } from \"./mappers\";\nconst ICPCOINS_CANISTER_ID = \"u45jl-liaaa-aaaam-abppa-cai\";\nexport class IcpCoinsClient extends CandidCanisterAgent {\n constructor(identity, agent) {\n super(identity, agent, ICPCOINS_CANISTER_ID, idlFactory, \"IcpCoins\");\n }\n exchangeRates(supportedTokens) {\n return this.handleQueryResponse(() => this.service.get_latest(), (resp) => getLatestResponse(resp, supportedTokens));\n }\n}\n","export const idlFactory = ({ IDL }) => {\n const PublicTokenOverview = IDL.Record({\n 'volumeUSD7d': IDL.Float64,\n 'address': IDL.Text,\n 'priceUSD': IDL.Float64,\n 'symbol': IDL.Text,\n });\n return IDL.Service({\n 'getAllTokens': IDL.Func([], [IDL.Vec(PublicTokenOverview)], ['query']),\n });\n};\nexport const init = ({ IDL }) => { return []; };\n","import { idlFactory } from \"./candid/idl\";\nimport { CandidCanisterAgent } from \"../canisterAgent/candid\";\nimport { getAllTokensResponse } from \"./mappers\";\nconst ICPSWAP_CANISTER_ID = \"ggzvv-5qaaa-aaaag-qck7a-cai\";\nexport class IcpSwapClient extends CandidCanisterAgent {\n constructor(identity, agent) {\n super(identity, agent, ICPSWAP_CANISTER_ID, idlFactory, \"IcpSwapExchangeRates\");\n }\n exchangeRates(supportedTokens) {\n return this.handleQueryResponse(() => this.service.getAllTokens(), (resp) => getAllTokensResponse(resp, supportedTokens));\n }\n}\n","import {} from \"openchat-shared\";\nexport function getAllTokensResponse(candid, supportedTokens) {\n const exchangeRates = {};\n const supportedLedgers = new Set(supportedTokens.map((t) => t.ledger));\n for (const token of candid) {\n if (supportedLedgers.has(token.address)) {\n exchangeRates[token.symbol.trim().toLowerCase()] = {\n toUSD: token.priceUSD,\n };\n }\n }\n return exchangeRates;\n}\n","export const idlFactory = ({ IDL }) => {\n const Account = IDL.Record({\n 'owner': IDL.Principal,\n 'subaccount': IDL.Opt(IDL.Vec(IDL.Nat8)),\n });\n const GetAccountTransactionsArgs = IDL.Record({\n 'max_results': IDL.Nat,\n 'start': IDL.Opt(IDL.Nat),\n 'account': Account,\n });\n const Tokens = IDL.Record({ 'e8s': IDL.Nat64 });\n const TimeStamp = IDL.Record({ 'timestamp_nanos': IDL.Nat64 });\n const Operation = IDL.Variant({\n 'Approve': IDL.Record({\n 'fee': Tokens,\n 'from': IDL.Text,\n 'allowance': Tokens,\n 'expected_allowance': IDL.Opt(Tokens),\n 'expires_at': IDL.Opt(TimeStamp),\n 'spender': IDL.Text,\n }),\n 'Burn': IDL.Record({\n 'from': IDL.Text,\n 'amount': Tokens,\n 'spender': IDL.Opt(IDL.Text),\n }),\n 'Mint': IDL.Record({ 'to': IDL.Text, 'amount': Tokens }),\n 'Transfer': IDL.Record({\n 'to': IDL.Text,\n 'fee': Tokens,\n 'from': IDL.Text,\n 'amount': Tokens,\n 'spender': IDL.Opt(IDL.Text),\n }),\n });\n const Transaction = IDL.Record({\n 'memo': IDL.Nat64,\n 'icrc1_memo': IDL.Opt(IDL.Vec(IDL.Nat8)),\n 'operation': Operation,\n 'timestamp': IDL.Opt(TimeStamp),\n 'created_at_time': IDL.Opt(TimeStamp),\n });\n const TransactionWithId = IDL.Record({\n 'id': IDL.Nat64,\n 'transaction': Transaction,\n });\n const GetAccountIdentifierTransactionsResponse = IDL.Record({\n 'balance': IDL.Nat64,\n 'transactions': IDL.Vec(TransactionWithId),\n 'oldest_tx_id': IDL.Opt(IDL.Nat64),\n });\n const GetAccountIdentifierTransactionsError = IDL.Record({\n 'message': IDL.Text,\n });\n const GetAccountIdentifierTransactionsResult = IDL.Variant({\n 'Ok': GetAccountIdentifierTransactionsResponse,\n 'Err': GetAccountIdentifierTransactionsError,\n });\n return IDL.Service({\n 'get_account_transactions': IDL.Func([GetAccountTransactionsArgs], [GetAccountIdentifierTransactionsResult], ['query']),\n });\n};\nexport const init = ({ IDL }) => { return []; };\n","import { identity, optional } from \"../../utils/mapping\";\nimport { CommonResponses, UnsupportedValueError, } from \"openchat-shared\";\nexport function accountTransactions(candid) {\n if (\"Err\" in candid) {\n return CommonResponses.failure();\n }\n if (\"Ok\" in candid) {\n return getTransactions(candid.Ok);\n }\n throw new UnsupportedValueError(\"Unknown ApiGetTransactionsResult type\", candid);\n}\nfunction getTransactions(candid) {\n return {\n kind: \"success\",\n transactions: candid.transactions.map(transaction),\n oldestTransactionId: optional(candid.oldest_tx_id, identity),\n };\n}\nfunction timestampToDate(ts) {\n return new Date(Number(ts.timestamp_nanos / 1000000n));\n}\nfunction transaction(candid) {\n // the candid types are quite fuzzy here - the old \"product type when it should be sum type\" thing\n const timestamp = optional(candid.transaction.timestamp, timestampToDate) ?? new Date();\n const memo = optional(candid.transaction.icrc1_memo, convertMemo) ?? candid.transaction.memo.toString();\n const createdAt = optional(candid.transaction.created_at_time, timestampToDate);\n if (\"Transfer\" in candid.transaction.operation) {\n const transfer = candid.transaction.operation.Transfer;\n return {\n id: candid.id,\n kind: \"transfer\",\n timestamp,\n memo,\n createdAt,\n amount: transfer.amount.e8s,\n fee: transfer.fee.e8s,\n to: transfer.to,\n from: transfer.from,\n spender: optional(transfer.spender, identity),\n };\n }\n if (\"Burn\" in candid.transaction.operation) {\n const burn = candid.transaction.operation.Burn;\n return {\n id: candid.id,\n kind: \"burn\",\n timestamp,\n memo,\n createdAt,\n amount: burn.amount.e8s,\n from: burn.from,\n spender: optional(burn.spender, identity),\n };\n }\n if (\"Mint\" in candid.transaction.operation) {\n const mint = candid.transaction.operation.Mint;\n return {\n id: candid.id,\n kind: \"mint\",\n timestamp,\n memo,\n createdAt,\n amount: mint.amount.e8s,\n to: mint.to,\n };\n }\n if (\"Approve\" in candid.transaction.operation) {\n const approve = candid.transaction.operation.Approve;\n return {\n id: candid.id,\n kind: \"approve\",\n timestamp,\n memo,\n createdAt,\n amount: approve.allowance.e8s,\n fee: approve.fee.e8s,\n from: approve.from,\n expectedAllowance: optional(approve.expected_allowance, (a) => a.e8s),\n expiredAt: optional(approve.expires_at, (ts) => ts.timestamp_nanos),\n spender: approve.spender,\n };\n }\n throw new Error(`Unexpected transaction type received: ${candid.transaction}`);\n}\nfunction convertMemo(candid) {\n return [...candid].map((n) => String.fromCharCode(n)).join(\"\");\n}\n","import { idlFactory } from \"./candid/idl\";\nimport { CandidCanisterAgent } from \"../canisterAgent/candid\";\nimport { Principal } from \"@dfinity/principal\";\nimport { accountTransactions } from \"./mappers\";\nimport { apiOptional } from \"../common/chatMappers\";\nimport { identity } from \"../../utils/mapping\";\nexport class IcpLedgerIndexClient extends CandidCanisterAgent {\n constructor(identity, agent, canisterId) {\n super(identity, agent, canisterId, idlFactory, \"IcpLedgerIndex\");\n }\n getAccountTransactions(principal, fromId) {\n return this.handleQueryResponse(() => this.service.get_account_transactions({\n max_results: 100n,\n start: apiOptional(identity, fromId),\n account: { owner: Principal.fromText(principal), subaccount: [] },\n }), accountTransactions);\n }\n}\n","export const idlFactory = ({ IDL }) => {\n const ApproveArgs = IDL.Record({ 'id': IDL.Nat64 });\n const ApproveResponse = IDL.Variant({\n 'NotFound': IDL.Null,\n 'NotAuthorized': IDL.Null,\n 'Success': IDL.Null,\n 'NotProposed': IDL.Null,\n 'InternalError': IDL.Text,\n });\n const TimestampMillis = IDL.Nat64;\n const MarkDeployedArgs = IDL.Record({ 'latest_approval': TimestampMillis });\n const MarkDeployedResponse = IDL.Variant({ 'Success': IDL.Null });\n const EmptyArgs = IDL.Record({});\n const Translation = IDL.Record({\n 'key': IDL.Text,\n 'value': IDL.Text,\n 'locale': IDL.Text,\n });\n const PendingDeploymentSuccessResult = IDL.Record({\n 'latest_approval': TimestampMillis,\n 'translations': IDL.Vec(Translation),\n });\n const PendingDeploymentResponse = IDL.Variant({\n 'Success': PendingDeploymentSuccessResult,\n });\n const ProposeArgs = IDL.Record({\n 'key': IDL.Text,\n 'value': IDL.Text,\n 'locale': IDL.Text,\n });\n const ProposeResponse = IDL.Variant({\n 'AlreadyProposed': IDL.Null,\n 'Success': IDL.Nat64,\n 'InvalidArgs': IDL.Text,\n 'InternalError': IDL.Text,\n 'UserNotFound': IDL.Null,\n });\n const CanisterId = IDL.Principal;\n const UserId = CanisterId;\n const CandidateTranslation = IDL.Record({\n 'id': IDL.Nat64,\n 'value': IDL.Text,\n 'proposed_at': TimestampMillis,\n 'proposed_by': UserId,\n });\n const Record = IDL.Record({\n 'key': IDL.Text,\n 'locale': IDL.Text,\n 'deployment_count': IDL.Nat32,\n 'candidates': IDL.Vec(CandidateTranslation),\n });\n const ProposedSuccessResult = IDL.Record({ 'records': IDL.Vec(Record) });\n const ProposedResponse = IDL.Variant({\n 'NotAuthorized': IDL.Null,\n 'Success': ProposedSuccessResult,\n 'InternalError': IDL.Text,\n });\n const RejectReason = IDL.Variant({\n 'TooLong': IDL.Null,\n 'IncorrectMeaning': IDL.Null,\n });\n const RejectArgs = IDL.Record({ 'id': IDL.Nat64, 'reason': RejectReason });\n const RejectResponse = IDL.Variant({\n 'NotFound': IDL.Null,\n 'NotAuthorized': IDL.Null,\n 'Success': IDL.Null,\n 'NotProposed': IDL.Null,\n 'InternalError': IDL.Text,\n });\n return IDL.Service({\n 'approve': IDL.Func([ApproveArgs], [ApproveResponse], []),\n 'mark_deployed': IDL.Func([MarkDeployedArgs], [MarkDeployedResponse], []),\n 'pending_deployment': IDL.Func([EmptyArgs], [PendingDeploymentResponse], ['query']),\n 'propose': IDL.Func([ProposeArgs], [ProposeResponse], []),\n 'proposed': IDL.Func([EmptyArgs], [ProposedResponse], ['query']),\n 'reject': IDL.Func([RejectArgs], [RejectResponse], []),\n });\n};\nexport const init = ({ IDL }) => { return []; };\n","import { UnsupportedValueError, } from \"openchat-shared\";\nfunction candidateTranslation(candid) {\n return {\n id: candid.id,\n value: candid.value,\n proposedAt: candid.proposed_at,\n proposedBy: candid.proposed_by.toString(),\n };\n}\nexport function proposedResponse(candid) {\n if (\"Success\" in candid) {\n return {\n kind: \"success\",\n proposed: candid.Success.records.map((c) => ({\n key: c.key,\n locale: c.locale,\n deploymentCount: c.deployment_count,\n candidates: c.candidates.map(candidateTranslation),\n })),\n };\n }\n console.warn(\"proposed translations failed with: \", candid);\n return { kind: \"failure\" };\n}\nexport function pendingDeploymentResponse(candid) {\n if (\"Success\" in candid) {\n return {\n kind: \"success\",\n latestApproval: candid.Success.latest_approval,\n translations: candid.Success.translations.map(({ locale, key, value }) => ({\n locale,\n key,\n value,\n })),\n };\n }\n console.warn(\"pending deployments failed with\", candid);\n return { kind: \"failure\" };\n}\nexport function proposeResponse(candid) {\n if (\"Success\" in candid) {\n return \"success\";\n }\n if (\"AlreadyProposed\" in candid) {\n return \"already_proposed\";\n }\n console.warn(\"propose translation failed with: \", candid);\n return \"failure\";\n}\nexport function approveResponse(candid) {\n if (\"Success\" in candid) {\n return \"success\";\n }\n console.warn(\"approve translation failed with: \", candid);\n return \"failure\";\n}\nexport function rejectResponse(candid) {\n if (\"Success\" in candid) {\n return \"success\";\n }\n console.warn(\"reject translation failed with: \", candid);\n return \"failure\";\n}\nexport function apiRejectReason(domain) {\n if (domain === \"incorrect_meaning\") {\n return {\n IncorrectMeaning: null,\n };\n }\n if (domain === \"too_long\") {\n return {\n TooLong: null,\n };\n }\n throw new UnsupportedValueError(\"Unknown reject reason: \", domain);\n}\nexport function markDeployedResponse(candid) {\n if (\"Success\" in candid) {\n return \"success\";\n }\n console.warn(\"mark translations deployed failed with: \", candid);\n return \"failure\";\n}\n","import { idlFactory } from \"./candid/idl\";\nimport { CandidCanisterAgent } from \"../canisterAgent/candid\";\nimport { apiRejectReason, approveResponse, markDeployedResponse, pendingDeploymentResponse, proposedResponse, proposeResponse, rejectResponse, } from \"./mappers\";\nexport class TranslationsClient extends CandidCanisterAgent {\n constructor(identity, agent, canisterId) {\n super(identity, agent, canisterId, idlFactory, \"Translations\");\n }\n propose(locale, key, value) {\n return this.handleResponse(this.service.propose({\n key,\n locale,\n value,\n }), proposeResponse);\n }\n approve(id) {\n return this.handleResponse(this.service.approve({\n id,\n }), approveResponse);\n }\n reject(id, reason) {\n return this.handleResponse(this.service.reject({\n id,\n reason: apiRejectReason(reason),\n }), rejectResponse);\n }\n markDeployed() {\n return this.handleResponse(this.service.mark_deployed({\n latest_approval: BigInt(Date.now()),\n }), markDeployedResponse);\n }\n proposed() {\n return this.handleQueryResponse(() => this.service.proposed({}), proposedResponse);\n }\n pendingDeployment() {\n return this.handleQueryResponse(() => this.service.pending_deployment({}), pendingDeploymentResponse);\n }\n}\n","export const idlFactory = ({ IDL }) => {\n const Utxo = IDL.Record({\n 'height': IDL.Nat32,\n 'value': IDL.Nat64,\n 'outpoint': IDL.Record({ 'txid': IDL.Vec(IDL.Nat8), 'vout': IDL.Nat32 }),\n });\n const MinterInfo = IDL.Record({\n 'retrieve_btc_min_amount': IDL.Nat64,\n 'min_confirmations': IDL.Nat32,\n 'kyt_fee': IDL.Nat64,\n });\n return IDL.Service({\n 'estimate_withdrawal_fee': IDL.Func([IDL.Record({ 'amount': IDL.Opt(IDL.Nat64) })], [IDL.Record({ 'minter_fee': IDL.Nat64, 'bitcoin_fee': IDL.Nat64 })], ['query']),\n 'get_deposit_fee': IDL.Func([], [IDL.Nat64], ['query']),\n 'get_known_utxos': IDL.Func([\n IDL.Record({\n 'owner': IDL.Opt(IDL.Principal),\n 'subaccount': IDL.Opt(IDL.Vec(IDL.Nat8)),\n }),\n ], [IDL.Vec(Utxo)], ['query']),\n 'get_minter_info': IDL.Func([], [MinterInfo], ['query']),\n });\n};\nexport const init = ({ IDL }) => { return []; };\n","import {} from \"openchat-shared\";\nimport { consolidateBytes } from \"../../utils/mapping\";\nexport function getUtxosResponse(candid) {\n return candid.utxos.map(utxo);\n}\nexport function utxo(candid) {\n return {\n height: candid.height,\n value: candid.value,\n outpoint: outpoint(candid.outpoint),\n };\n}\nfunction outpoint(candid) {\n return {\n txid: consolidateBytes(candid.txid),\n vout: candid.vout,\n };\n}\n","import { Principal } from \"@dfinity/principal\";\nimport { CandidCanisterAgent } from \"../canisterAgent/candid\";\nimport { idlFactory } from \"./candid/idl\";\nimport { utxo } from \"../bitcoin/mappers\";\nimport { identity } from \"../../utils/mapping\";\nconst MAINNET_CKBTC_MINTER_CANISTER_ID = \"mqygn-kiaaa-aaaar-qaadq-cai\";\nconst TESTNET_CKBTC_MINTER_CANISTER_ID = \"ml52i-qqaaa-aaaar-qaaba-cai\";\nexport class CkbtcMinterClient extends CandidCanisterAgent {\n #cachedMinterInfo;\n constructor(identity, agent, mainnetEnabled) {\n super(identity, agent, mainnetEnabled ? MAINNET_CKBTC_MINTER_CANISTER_ID : TESTNET_CKBTC_MINTER_CANISTER_ID, idlFactory, \"CkbtcMinter\");\n }\n getKnownUtxos(userId) {\n return this.handleQueryResponse(() => this.service.get_known_utxos({\n owner: [Principal.fromText(userId)],\n subaccount: [],\n }), (resp) => resp.map(utxo));\n }\n async getDepositInfo() {\n const minConfirmationsPromise = this.getMinterInfoCached().then((i) => i.minConfirmations);\n const depositFeePromise = this.handleQueryResponse(() => this.service.get_deposit_fee(), identity);\n const [minConfirmations, depositFee] = await Promise.all([minConfirmationsPromise, depositFeePromise]);\n return {\n minConfirmations,\n depositFee,\n };\n }\n async getWithdrawalInfo(amount) {\n const minWithdrawalAmountPromise = this.getMinterInfoCached().then((i) => i.minWithdrawalAmount);\n const feeEstimatePromise = this.handleQueryResponse(() => this.service.estimate_withdrawal_fee({ amount: [amount] }), (resp) => resp.minter_fee + resp.bitcoin_fee);\n const [minWithdrawalAmount, feeEstimate] = await Promise.all([minWithdrawalAmountPromise, feeEstimatePromise]);\n return {\n minWithdrawalAmount,\n feeEstimate,\n };\n }\n async getMinterInfoCached() {\n return this.#cachedMinterInfo ??= await this.getMinterInfo();\n }\n getMinterInfo() {\n return this.handleQueryResponse(() => this.service.get_minter_info(), (resp) => ({\n minConfirmations: resp.min_confirmations,\n minWithdrawalAmount: resp.retrieve_btc_min_amount,\n }));\n }\n}\n","export const idlFactory = ({ IDL }) => {\n const GenerateMagicLinkArgs = IDL.Record({\n 'session_key': IDL.Vec(IDL.Nat8),\n 'email': IDL.Text,\n 'max_time_to_live': IDL.Opt(IDL.Nat64),\n });\n const GenerateMagicLinkSuccess = IDL.Record({\n 'created': IDL.Nat64,\n 'user_key': IDL.Vec(IDL.Nat8),\n 'code': IDL.Text,\n 'expiration': IDL.Nat64,\n });\n const GenerateMagicLinkResponse = IDL.Variant({\n 'Blocked': IDL.Nat64,\n 'EmailInvalid': IDL.Null,\n 'FailedToSendEmail': IDL.Text,\n 'Success': GenerateMagicLinkSuccess,\n });\n const GetDelegationArgs = IDL.Record({\n 'session_key': IDL.Vec(IDL.Nat8),\n 'email': IDL.Text,\n 'expiration': IDL.Nat64,\n });\n const Delegation = IDL.Record({\n 'pubkey': IDL.Vec(IDL.Nat8),\n 'expiration': IDL.Nat64,\n });\n const SignedDelegation = IDL.Record({\n 'signature': IDL.Vec(IDL.Nat8),\n 'delegation': Delegation,\n });\n const GetDelegationResponse = IDL.Variant({\n 'NotFound': IDL.Null,\n 'Success': SignedDelegation,\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 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 return IDL.Service({\n 'generate_magic_link': IDL.Func([GenerateMagicLinkArgs], [GenerateMagicLinkResponse], []),\n 'get_delegation': IDL.Func([GetDelegationArgs], [GetDelegationResponse], ['query']),\n 'http_request': IDL.Func([HttpRequest], [HttpResponse], ['query']),\n 'http_request_update': IDL.Func([HttpRequest], [HttpResponse], []),\n 'rsa_public_key': IDL.Func([], [IDL.Opt(IDL.Text)], ['query']),\n });\n};\nexport const init = ({ IDL }) => { return []; };\n","import { UnsupportedValueError } from \"openchat-shared\";\nimport { consolidateBytes } from \"../../utils/mapping\";\nexport function generateMagicLinkResponse(candid) {\n if (\"Success\" in candid) {\n return {\n kind: \"success\",\n userKey: consolidateBytes(candid.Success.user_key),\n code: candid.Success.code,\n expiration: candid.Success.expiration,\n };\n }\n if (\"EmailInvalid\" in candid) {\n return {\n kind: \"email_invalid\",\n };\n }\n if (\"Blocked\" in candid) {\n return {\n kind: \"blocked\",\n duration: Number(candid.Blocked),\n };\n }\n if (\"FailedToSendEmail\" in candid) {\n return {\n kind: \"failed_to_send_email\",\n error: candid.FailedToSendEmail,\n };\n }\n throw new UnsupportedValueError(\"Unexpected ApiGenerateMagicLinkResponse type received\", candid);\n}\n// function durationToTimestamp(duration: bigint): bigint {\n// return BigInt(Date.now() + Number(duration));\n// }\n","var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nvar _PartialDelegationIdentity_delegation;\nimport { fromHex, requestIdOf, SignIdentity, toHex, } from '@dfinity/agent';\nimport { Principal } from '@dfinity/principal';\nimport * as cbor from 'simple-cbor';\nimport { PartialIdentity } from './partial';\nconst domainSeparator = new TextEncoder().encode('\\x1Aic-request-auth-delegation');\nconst requestDomainSeparator = new TextEncoder().encode('\\x0Aic-request');\nfunction _parseBlob(value) {\n if (typeof value !== 'string' || value.length < 64) {\n throw new Error('Invalid public key.');\n }\n return fromHex(value);\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(pubkey, expiration, targets) {\n this.pubkey = pubkey;\n this.expiration = expiration;\n this.targets = targets;\n }\n toCBOR() {\n // Expiration field needs to be encoded as a u64 specifically.\n return cbor.value.map(Object.assign({ pubkey: cbor.value.bytes(this.pubkey), expiration: cbor.value.u64(this.expiration.toString(16), 16) }, (this.targets && {\n targets: cbor.value.array(this.targets.map(t => cbor.value.bytes(t.toUint8Array()))),\n })));\n }\n toJSON() {\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 Object.assign({ expiration: this.expiration.toString(16), pubkey: toHex(this.pubkey) }, (this.targets && { targets: this.targets.map(p => p.toHex()) }));\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(from, to, expiration, targets) {\n const delegation = new Delegation(to.toDer(), BigInt(+expiration) * BigInt(1000000), // In nanoseconds.\n targets);\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(Object.assign({}, delegation))),\n ]);\n const signature = await from.sign(challenge);\n return {\n delegation,\n signature,\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 constructor(delegations, publicKey) {\n this.delegations = delegations;\n this.publicKey = publicKey;\n }\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 static async create(from, to, expiration = new Date(Date.now() + 15 * 60 * 1000), options = {}) {\n var _a, _b;\n const delegation = await _createSingleDelegation(from, to, expiration, options.targets);\n return new DelegationChain([...(((_a = options.previous) === null || _a === void 0 ? void 0 : _a.delegations) || []), delegation], ((_b = options.previous) === null || _b === void 0 ? void 0 : _b.publicKey) || from.getPublicKey().toDer());\n }\n /**\n * Creates a DelegationChain object from a JSON string.\n * @param json The JSON string to parse.\n */\n static fromJSON(json) {\n const { publicKey, delegations } = typeof json === 'string' ? JSON.parse(json) : json;\n if (!Array.isArray(delegations)) {\n throw new Error('Invalid delegations.');\n }\n const parsedDelegations = 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 return {\n delegation: new Delegation(_parseBlob(pubkey), BigInt('0x' + expiration), // expiration in JSON is an hexa string (See toJSON() below).\n targets &&\n targets.map((t) => {\n if (typeof t !== 'string') {\n throw new Error('Invalid target.');\n }\n return Principal.fromHex(t);\n })),\n signature: _parseBlob(signature),\n };\n });\n return new this(parsedDelegations, _parseBlob(publicKey));\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 static fromDelegations(delegations, publicKey) {\n return new this(delegations, publicKey);\n }\n toJSON() {\n return {\n delegations: this.delegations.map(signedDelegation => {\n const { delegation, signature } = signedDelegation;\n const { targets } = delegation;\n return {\n delegation: Object.assign({ expiration: delegation.expiration.toString(16), pubkey: toHex(delegation.pubkey) }, (targets && {\n targets: targets.map(t => t.toHex()),\n })),\n signature: toHex(signature),\n };\n }),\n publicKey: toHex(this.publicKey),\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 constructor(_inner, _delegation) {\n super();\n this._inner = _inner;\n this._delegation = _delegation;\n }\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 static fromDelegation(key, delegation) {\n return new this(key, delegation);\n }\n getDelegation() {\n return this._delegation;\n }\n getPublicKey() {\n return {\n derKey: this._delegation.publicKey,\n toDer: () => this._delegation.publicKey,\n };\n }\n sign(blob) {\n return this._inner.sign(blob);\n }\n async transformRequest(request) {\n const { body } = request, fields = __rest(request, [\"body\"]);\n const requestId = await requestIdOf(body);\n return Object.assign(Object.assign({}, fields), { body: {\n content: body,\n sender_sig: await this.sign(new Uint8Array([...requestDomainSeparator, ...new Uint8Array(requestId)])),\n sender_delegation: this._delegation.delegations,\n sender_pubkey: this._delegation.publicKey,\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 constructor(inner, delegation) {\n super(inner);\n _PartialDelegationIdentity_delegation.set(this, void 0);\n __classPrivateFieldSet(this, _PartialDelegationIdentity_delegation, delegation, \"f\");\n }\n /**\n * The Delegation Chain of this identity.\n */\n get delegation() {\n return __classPrivateFieldGet(this, _PartialDelegationIdentity_delegation, \"f\");\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 static fromDelegation(key, delegation) {\n return new PartialDelegationIdentity(key, delegation);\n }\n}\n_PartialDelegationIdentity_delegation = new WeakMap();\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, checks) {\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 // Check the scopes.\n const scopes = [];\n const maybeScope = checks === null || checks === void 0 ? void 0 : checks.scope;\n if (maybeScope) {\n if (Array.isArray(maybeScope)) {\n scopes.push(...maybeScope.map(s => (typeof s === 'string' ? Principal.fromText(s) : s)));\n }\n else {\n scopes.push(typeof maybeScope === 'string' ? Principal.fromText(maybeScope) : maybeScope);\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 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 return true;\n}\n//# sourceMappingURL=delegation.js.map","import { SignIdentity, wrapDER, DER_COSE_OID, fromHex, toHex, } from '@dfinity/agent';\nimport borc from 'borc';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { bufFromBufLike } from '@dfinity/candid';\nfunction _coseToDerEncodedBlob(cose) {\n return wrapDER(cose, DER_COSE_OID).buffer;\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) {\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 // Get the public key object.\n return authData.slice(55 + credentialIdLength);\n}\nexport class CosePublicKey {\n constructor(_cose) {\n this._cose = _cose;\n this._encodedKey = _coseToDerEncodedBlob(_cose);\n }\n toDer() {\n return this._encodedKey;\n }\n getCose() {\n return this._cose;\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 = '') {\n if (typeof challenge === 'string') {\n return Uint8Array.from(challenge, c => c.charCodeAt(0));\n }\n else {\n return challenge;\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(credentialCreationOptions) {\n const creds = (await navigator.credentials.create(credentialCreationOptions !== null && credentialCreationOptions !== void 0 ? 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 if (creds === null) {\n return null;\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// 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.\nvar PubKeyCoseAlgo;\n(function (PubKeyCoseAlgo) {\n PubKeyCoseAlgo[PubKeyCoseAlgo[\"ECDSA_WITH_SHA256\"] = -7] = \"ECDSA_WITH_SHA256\";\n})(PubKeyCoseAlgo || (PubKeyCoseAlgo = {}));\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 constructor(rawId, cose, authenticatorAttachment) {\n super();\n this.rawId = rawId;\n this.authenticatorAttachment = authenticatorAttachment;\n this._publicKey = new CosePublicKey(cose);\n }\n /**\n * Create an identity from a JSON serialization.\n * @param json - json to parse\n */\n static fromJSON(json) {\n const { publicKey, rawId } = JSON.parse(json);\n if (typeof publicKey !== 'string' || typeof rawId !== 'string') {\n throw new Error('Invalid JSON string.');\n }\n return new this(fromHex(rawId), fromHex(publicKey), undefined);\n }\n /**\n * Create an identity.\n * @param credentialCreationOptions an optional CredentialCreationOptions Challenge\n */\n static async create(credentialCreationOptions) {\n var _a;\n const creds = await _createCredential(credentialCreationOptions);\n if (!creds || creds.type !== 'public-key') {\n throw new Error('Could not create credentials.');\n }\n const response = creds.response;\n if (response.attestationObject === undefined) {\n throw new Error('Was expecting an attestation response.');\n }\n // Parse the attestationObject as CBOR.\n const attObject = borc.decodeFirst(new Uint8Array(response.attestationObject));\n return new this(creds.rawId, _authDataToCose(attObject.authData), (_a = creds.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined);\n }\n getPublicKey() {\n return this._publicKey;\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 getAuthenticatorAttachment() {\n return this.authenticatorAttachment;\n }\n async sign(blob) {\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 }));\n if (result.authenticatorAttachment !== null) {\n this.authenticatorAttachment = result.authenticatorAttachment;\n }\n const response = result.response;\n const cbor = borc.encode(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 if (!cbor) {\n throw new Error('failed to encode cbor');\n }\n return cbor.buffer;\n }\n /**\n * Allow for JSON serialization of all information needed to reuse this identity.\n */\n toJSON() {\n return {\n publicKey: toHex(this._publicKey.getCose()),\n rawId: toHex(this.rawId),\n };\n }\n}\n//# sourceMappingURL=webauthn.js.map","import { UnsupportedValueError, } from \"openchat-shared\";\nimport { consolidateBytes, optional } from \"../../utils/mapping\";\nimport { Delegation } from \"@dfinity/identity\";\nexport function createIdentityResponse(candid) {\n if (\"Success\" in candid) {\n return prepareDelegationSuccess(candid.Success);\n }\n if (\"AlreadyRegistered\" in candid) {\n return { kind: \"already_registered\" };\n }\n if (\"PublicKeyInvalid\" in candid) {\n return { kind: \"public_key_invalid\" };\n }\n if (\"OriginatingCanisterInvalid\" in candid) {\n return { kind: \"originating_canister_invalid\" };\n }\n if (\"ChallengeFailed\" in candid) {\n return { kind: \"challenge_failed\" };\n }\n if (\"ChallengeRequired\" in candid) {\n return { kind: \"challenge_required\" };\n }\n throw new UnsupportedValueError(\"Unexpected ApiCreateIdentityResponse type received\", candid);\n}\nexport function checkAuthPrincipalResponse(candid) {\n if (\"Success\" in candid) {\n return {\n kind: \"success\",\n userId: optional(candid.Success.user_id, (p) => p.toString()),\n webAuthnKey: optional(candid.Success.webauthn_key, webAuthnKey),\n originatingCanister: candid.Success.originating_canister.toString(),\n isIIPrincipal: candid.Success.is_ii_principal,\n };\n }\n if (\"NotFound\" in candid) {\n return { kind: \"not_found\" };\n }\n throw new UnsupportedValueError(\"Unexpected ApiCheckAuthPrincipalResponse type received\", candid);\n}\nexport function prepareDelegationResponse(candid) {\n if (\"Success\" in candid) {\n return prepareDelegationSuccess(candid.Success);\n }\n if (\"NotFound\" in candid) {\n return { kind: \"not_found\" };\n }\n throw new UnsupportedValueError(\"Unexpected ApiPrepareDelegationResponse type received\", candid);\n}\nexport function getDelegationResponse(candid) {\n if (\"Success\" in candid) {\n return signedDelegation(candid.Success);\n }\n if (\"NotFound\" in candid) {\n return { kind: \"not_found\" };\n }\n throw new UnsupportedValueError(\"Unexpected ApiGetDelegationResponse type received\", candid);\n}\nexport function signedDelegation(signedDelegation) {\n return {\n kind: \"success\",\n delegation: new Delegation(consolidateBytes(signedDelegation.delegation.pubkey), signedDelegation.delegation.expiration),\n signature: consolidateBytes(signedDelegation.signature),\n };\n}\nfunction prepareDelegationSuccess(candid) {\n return {\n kind: \"success\",\n userKey: consolidateBytes(candid.user_key),\n expiration: candid.expiration,\n };\n}\nexport function generateChallengeResponse(candid) {\n if (\"Success\" in candid) {\n return {\n kind: \"success\",\n key: candid.Success.key,\n pngBase64: candid.Success.png_base64,\n };\n }\n if (\"AlreadyRegistered\" in candid) {\n return { kind: \"already_registered\" };\n }\n if (\"Throttled\" in candid) {\n return { kind: \"throttled\" };\n }\n throw new UnsupportedValueError(\"Unexpected ApiGenerateChallengeResponse type received\", candid);\n}\nexport function initiateIdentityLinkResponse(candid) {\n if (\"Success\" in candid) {\n return \"success\";\n }\n if (\"AlreadyRegistered\" in candid) {\n return \"already_registered\";\n }\n if (\"AlreadyLinkedToPrincipal\" in candid) {\n return \"already_linked_to_principal\";\n }\n if (\"TargetUserNotFound\" in candid) {\n return \"target_user_not_found\";\n }\n if (\"PublicKeyInvalid\" in candid) {\n return \"public_key_invalid\";\n }\n if (\"OriginatingCanisterInvalid\" in candid) {\n return \"originating_canister_invalid\";\n }\n if (\"LinkedIdentitiesLimitReached\" in candid) {\n return \"linked_identities_limit_reached\";\n }\n throw new UnsupportedValueError(\"Unexpected ApiInitiateIdentityLinkResponse type received\", candid);\n}\nexport function authPrincipalsResponse(candid) {\n if (\"NotFound\" in candid) {\n return [];\n }\n if (\"Success\" in candid) {\n return candid.Success.map((p) => ({\n principal: p.principal.toString(),\n originatingCanister: p.originating_canister.toString(),\n isIIPrincipal: p.is_ii_principal,\n isCurrentIdentity: p.is_current_identity,\n webAuthnKey: optional(p.webauthn_key, webAuthnKey),\n }));\n }\n throw new UnsupportedValueError(\"Unexpected ApiAuthPrincipalResponse type received\", candid);\n}\nexport function approveIdentityLinkResponse(candid) {\n if (\"Success\" in candid) {\n return \"success\";\n }\n if (\"CallerNotRecognised\" in candid) {\n return \"caller_not_recognised\";\n }\n if (\"LinkRequestNotFound\" in candid) {\n return \"link_request_not_found\";\n }\n if (\"PrincipalAlreadyLinkedToAnotherOcUser\" in candid) {\n return \"principal_linked_to_another_oc_user\";\n }\n if (\"MalformedSignature\" in candid || \"InvalidSignature\" in candid) {\n return \"invalid_signature\";\n }\n if (\"DelegationTooOld\" in candid) {\n return \"delegation_too_old\";\n }\n if (\"PrincipalAlreadyLinkedToAnotherOcUser\" in candid) {\n return \"principal_linked_to_another_oc_user\";\n }\n throw new UnsupportedValueError(\"Unexpected ApiApproveIdentityLinkResponse type received\", candid);\n}\nexport function removeIdentityLinkResponse(candid) {\n if (\"Success\" in candid) {\n return \"success\";\n }\n if (\"CannotUnlinkActivePrincipal\" in candid) {\n return \"cannot_unlink_active_principal\";\n }\n if (\"IdentityLinkNotFound\" in candid) {\n return \"identity_link_not_found\";\n }\n if (\"UserNotFound\" in candid) {\n return \"user_not_found\";\n }\n throw new UnsupportedValueError(\"Unexpected ApiRemoveIdentityLinkResponse type received\", candid);\n}\nfunction webAuthnKey(key) {\n return {\n publicKey: consolidateBytes(key.public_key),\n credentialId: consolidateBytes(key.credential_id),\n origin: key.origin,\n crossPlatform: key.cross_platform,\n aaguid: consolidateBytes(key.aaguid),\n };\n}\nexport function apiWebAuthnKey(key) {\n return {\n public_key: key.publicKey,\n credential_id: key.credentialId,\n origin: key.origin,\n cross_platform: key.crossPlatform,\n aaguid: key.aaguid,\n };\n}\n","import { idlFactory } from \"./candid/idl\";\nimport { CandidCanisterAgent } from \"../canisterAgent/candid\";\nimport { generateMagicLinkResponse } from \"./mappers\";\nimport { getDelegationResponse } from \"../identity/mappers\";\nexport class SignInWithEmailClient extends CandidCanisterAgent {\n constructor(identity, agent, canisterId) {\n super(identity, agent, canisterId, idlFactory, \"SignInWithEmail\");\n }\n generateMagicLink(email, sessionKey) {\n const args = { email, session_key: sessionKey, max_time_to_live: [] };\n return this.handleResponse(this.service.generate_magic_link(args), generateMagicLinkResponse, args);\n }\n getDelegation(email, sessionKey, expiration) {\n const args = {\n email,\n session_key: sessionKey,\n expiration,\n };\n return this.handleQueryResponse(() => this.service.get_delegation(args), getDelegationResponse, args);\n }\n}\n","export const idlFactory = ({ IDL }) => {\n const RuntimeFeature = IDL.Variant({\n 'IncludeUriInSeed': IDL.Null,\n 'DisableEthToPrincipalMapping': IDL.Null,\n 'DisablePrincipalToEthMapping': IDL.Null,\n });\n const SettingsInput = IDL.Record({\n 'uri': IDL.Text,\n 'runtime_features': IDL.Opt(IDL.Vec(RuntimeFeature)),\n 'domain': IDL.Text,\n 'statement': IDL.Opt(IDL.Text),\n 'scheme': IDL.Opt(IDL.Text),\n 'salt': IDL.Text,\n 'session_expires_in': IDL.Opt(IDL.Nat64),\n 'targets': IDL.Opt(IDL.Vec(IDL.Text)),\n 'chain_id': IDL.Opt(IDL.Nat),\n 'sign_in_expires_in': IDL.Opt(IDL.Nat64),\n });\n const Principal = IDL.Vec(IDL.Nat8);\n const Address = IDL.Text;\n const GetAddressResponse = IDL.Variant({ 'Ok': Address, 'Err': IDL.Text });\n const GetPrincipalResponse = IDL.Variant({\n 'Ok': Principal,\n 'Err': IDL.Text,\n });\n const PublicKey = IDL.Vec(IDL.Nat8);\n const SessionKey = PublicKey;\n const Timestamp = IDL.Nat64;\n const Delegation = IDL.Record({\n 'pubkey': PublicKey,\n 'targets': IDL.Opt(IDL.Vec(IDL.Principal)),\n 'expiration': Timestamp,\n });\n const SignedDelegation = IDL.Record({\n 'signature': IDL.Vec(IDL.Nat8),\n 'delegation': Delegation,\n });\n const GetDelegationResponse = IDL.Variant({\n 'Ok': SignedDelegation,\n 'Err': IDL.Text,\n });\n const SiweSignature = IDL.Text;\n const CanisterPublicKey = PublicKey;\n const LoginDetails = IDL.Record({\n 'user_canister_pubkey': CanisterPublicKey,\n 'expiration': Timestamp,\n });\n const LoginResponse = IDL.Variant({ 'Ok': LoginDetails, 'Err': IDL.Text });\n const SiweMessage = IDL.Text;\n const PrepareLoginResponse = IDL.Variant({\n 'Ok': SiweMessage,\n 'Err': IDL.Text,\n });\n return IDL.Service({\n 'get_address': IDL.Func([Principal], [GetAddressResponse], ['query']),\n 'get_caller_address': IDL.Func([], [GetAddressResponse], ['query']),\n 'get_principal': IDL.Func([Address], [GetPrincipalResponse], ['query']),\n 'siwe_get_delegation': IDL.Func([Address, SessionKey, Timestamp], [GetDelegationResponse], ['query']),\n 'siwe_login': IDL.Func([SiweSignature, Address, SessionKey], [LoginResponse], []),\n 'siwe_prepare_login': IDL.Func([Address], [PrepareLoginResponse], []),\n });\n};\nexport const init = ({ IDL }) => {\n const RuntimeFeature = IDL.Variant({\n 'IncludeUriInSeed': IDL.Null,\n 'DisableEthToPrincipalMapping': IDL.Null,\n 'DisablePrincipalToEthMapping': IDL.Null,\n });\n const SettingsInput = IDL.Record({\n 'uri': IDL.Text,\n 'runtime_features': IDL.Opt(IDL.Vec(RuntimeFeature)),\n 'domain': IDL.Text,\n 'statement': IDL.Opt(IDL.Text),\n 'scheme': IDL.Opt(IDL.Text),\n 'salt': IDL.Text,\n 'session_expires_in': IDL.Opt(IDL.Nat64),\n 'targets': IDL.Opt(IDL.Vec(IDL.Text)),\n 'chain_id': IDL.Opt(IDL.Nat),\n 'sign_in_expires_in': IDL.Opt(IDL.Nat64),\n });\n return [SettingsInput];\n};\n","import { UnsupportedValueError, } from \"openchat-shared\";\nimport { signedDelegation } from \"../identity/mappers\";\nimport { consolidateBytes } from \"../../utils/mapping\";\nexport function prepareLoginResponse(candid) {\n if (\"Ok\" in candid) {\n return {\n kind: \"success\",\n siweMessage: candid.Ok,\n };\n }\n if (\"Err\" in candid) {\n return {\n kind: \"error\",\n error: candid.Err,\n };\n }\n throw new UnsupportedValueError(\"Unexpected ApiPrepareLoginResponse type received\", candid);\n}\nexport function loginResponse(candid) {\n if (\"Ok\" in candid) {\n return {\n kind: \"success\",\n userKey: consolidateBytes(candid.Ok.user_canister_pubkey),\n expiration: candid.Ok.expiration,\n };\n }\n if (\"Err\" in candid) {\n return { kind: \"error\", error: candid.Err };\n }\n throw new UnsupportedValueError(\"Unexpected ApiLoginResponse type received\", candid);\n}\nexport function getDelegationResponse(candid) {\n if (\"Ok\" in candid) {\n return signedDelegation(candid.Ok);\n }\n if (\"Err\" in candid) {\n return {\n kind: \"error\",\n error: candid.Err,\n };\n }\n throw new UnsupportedValueError(\"Unexpected ApiGetDelegationResponse type received\", candid);\n}\n","import { idlFactory } from \"./candid/idl\";\nimport { CandidCanisterAgent } from \"../canisterAgent/candid\";\nimport { getDelegationResponse, loginResponse, prepareLoginResponse } from \"./mappers\";\nexport class SignInWithEthereumClient extends CandidCanisterAgent {\n constructor(identity, agent, canisterId) {\n super(identity, agent, canisterId, idlFactory, \"SignInWithEthereum\");\n }\n prepareLogin(address) {\n return this.handleResponse(this.service.siwe_prepare_login(address), prepareLoginResponse, address);\n }\n login(signature, address, sessionKey) {\n return this.handleResponse(this.service.siwe_login(signature, address, sessionKey), loginResponse, [signature, address, sessionKey]);\n }\n getDelegation(address, sessionKey, expiration) {\n return this.handleQueryResponse(() => this.service.siwe_get_delegation(address, sessionKey, expiration), getDelegationResponse, [address, sessionKey, expiration]);\n }\n}\n","export const idlFactory = ({ IDL }) => {\n const RuntimeFeature = IDL.Variant({\n 'IncludeUriInSeed': IDL.Null,\n 'DisablePrincipalToSolMapping': IDL.Null,\n 'DisableSolToPrincipalMapping': IDL.Null,\n });\n const SettingsInput = IDL.Record({\n 'uri': IDL.Text,\n 'runtime_features': IDL.Opt(IDL.Vec(RuntimeFeature)),\n 'domain': IDL.Text,\n 'statement': IDL.Opt(IDL.Text),\n 'scheme': IDL.Opt(IDL.Text),\n 'salt': IDL.Text,\n 'session_expires_in': IDL.Opt(IDL.Nat64),\n 'targets': IDL.Opt(IDL.Vec(IDL.Text)),\n 'chain_id': IDL.Opt(IDL.Text),\n 'sign_in_expires_in': IDL.Opt(IDL.Nat64),\n });\n const Principal = IDL.Vec(IDL.Nat8);\n const Address = IDL.Text;\n const GetAddressResponse = IDL.Variant({ 'Ok': Address, 'Err': IDL.Text });\n const GetPrincipalResponse = IDL.Variant({\n 'Ok': Principal,\n 'Err': IDL.Text,\n });\n const PublicKey = IDL.Vec(IDL.Nat8);\n const SessionKey = PublicKey;\n const Timestamp = IDL.Nat64;\n const Delegation = IDL.Record({\n 'pubkey': PublicKey,\n 'targets': IDL.Opt(IDL.Vec(IDL.Principal)),\n 'expiration': Timestamp,\n });\n const SignedDelegation = IDL.Record({\n 'signature': IDL.Vec(IDL.Nat8),\n 'delegation': Delegation,\n });\n const GetDelegationResponse = IDL.Variant({\n 'Ok': SignedDelegation,\n 'Err': IDL.Text,\n });\n const SiwsSignature = IDL.Text;\n const CanisterPublicKey = PublicKey;\n const LoginDetails = IDL.Record({\n 'user_canister_pubkey': CanisterPublicKey,\n 'expiration': Timestamp,\n });\n const LoginResponse = IDL.Variant({ 'Ok': LoginDetails, 'Err': IDL.Text });\n const SiwsMessage = IDL.Record({\n 'uri': IDL.Text,\n 'issued_at': IDL.Nat64,\n 'domain': IDL.Text,\n 'statement': IDL.Text,\n 'version': IDL.Nat32,\n 'chain_id': IDL.Text,\n 'address': Address,\n 'nonce': IDL.Text,\n 'expiration_time': IDL.Nat64,\n });\n const PrepareLoginResponse = IDL.Variant({\n 'Ok': SiwsMessage,\n 'Err': IDL.Text,\n });\n return IDL.Service({\n 'get_address': IDL.Func([Principal], [GetAddressResponse], ['query']),\n 'get_caller_address': IDL.Func([], [GetAddressResponse], ['query']),\n 'get_principal': IDL.Func([Address], [GetPrincipalResponse], ['query']),\n 'siws_get_delegation': IDL.Func([Address, SessionKey, Timestamp], [GetDelegationResponse], ['query']),\n 'siws_login': IDL.Func([SiwsSignature, Address, SessionKey], [LoginResponse], []),\n 'siws_prepare_login': IDL.Func([Address], [PrepareLoginResponse], []),\n });\n};\nexport const init = ({ IDL }) => {\n const RuntimeFeature = IDL.Variant({\n 'IncludeUriInSeed': IDL.Null,\n 'DisablePrincipalToSolMapping': IDL.Null,\n 'DisableSolToPrincipalMapping': IDL.Null,\n });\n const SettingsInput = IDL.Record({\n 'uri': IDL.Text,\n 'runtime_features': IDL.Opt(IDL.Vec(RuntimeFeature)),\n 'domain': IDL.Text,\n 'statement': IDL.Opt(IDL.Text),\n 'scheme': IDL.Opt(IDL.Text),\n 'salt': IDL.Text,\n 'session_expires_in': IDL.Opt(IDL.Nat64),\n 'targets': IDL.Opt(IDL.Vec(IDL.Text)),\n 'chain_id': IDL.Opt(IDL.Text),\n 'sign_in_expires_in': IDL.Opt(IDL.Nat64),\n });\n return [SettingsInput];\n};\n","import { UnsupportedValueError } from \"openchat-shared\";\nexport function prepareLoginResponse(candid) {\n if (\"Ok\" in candid) {\n return {\n kind: \"success\",\n siwsMessage: {\n uri: candid.Ok.uri,\n issuedAt: candid.Ok.issued_at,\n domain: candid.Ok.domain,\n statement: candid.Ok.statement,\n version: candid.Ok.version,\n chainId: candid.Ok.chain_id,\n address: candid.Ok.address,\n nonce: candid.Ok.nonce,\n expirationTime: candid.Ok.expiration_time,\n },\n };\n }\n if (\"Err\" in candid) {\n return {\n kind: \"error\",\n error: candid.Err,\n };\n }\n throw new UnsupportedValueError(\"Unexpected ApiPrepareLoginResponse type received\", candid);\n}\n","import { idlFactory } from \"./candid/idl\";\nimport { CandidCanisterAgent } from \"../canisterAgent/candid\";\nimport { prepareLoginResponse } from \"./mappers\";\nimport { getDelegationResponse, loginResponse } from \"../signInWithEthereum/mappers\";\nexport class SignInWithSolanaClient extends CandidCanisterAgent {\n constructor(identity, agent, canisterId) {\n super(identity, agent, canisterId, idlFactory, \"SignInWithSolana\");\n }\n prepareLogin(address) {\n return this.handleResponse(this.service.siws_prepare_login(address), prepareLoginResponse, address);\n }\n login(signature, address, sessionKey) {\n return this.handleResponse(this.service.siws_login(signature, address, sessionKey), loginResponse, [signature, address, sessionKey]);\n }\n getDelegation(address, sessionKey, expiration) {\n return this.handleQueryResponse(() => this.service.siws_get_delegation(address, sessionKey, expiration), getDelegationResponse, [address, sessionKey, expiration]);\n }\n}\n","import { HttpAgent } from \"@dfinity/agent\";\nimport { isMainnet } from \"./network\";\nimport { offline } from \"openchat-shared\";\nexport function createHttpAgentSync(identity, icUrl) {\n const [agent] = createHttpAgentInternal(identity, icUrl);\n return agent;\n}\nexport async function createHttpAgent(identity, icUrl) {\n const [agent, fetchRootKeyPromise] = createHttpAgentInternal(identity, icUrl);\n await fetchRootKeyPromise;\n return agent;\n}\nfunction createHttpAgentInternal(identity, icUrl) {\n const agent = HttpAgent.createSync({\n identity,\n host: icUrl,\n verifyQuerySignatures: false,\n });\n const fetchRootKey = !isMainnet(icUrl) && !offline();\n const fetchRootKeyPromise = fetchRootKey\n ? agent.fetchRootKey().then((_) => { })\n : Promise.resolve();\n return [agent, fetchRootKeyPromise];\n}\n","import { deleteDB, openDB } from \"idb\";\nconst CACHE_VERSION = 2;\nlet db;\nexport function lazyOpenReferralCache() {\n if (db)\n return db;\n console.log(\"referral db undefined, opening db\");\n db = openReferralCache();\n return db;\n}\nfunction openReferralCache() {\n return openDB(`openchat_referrals`, CACHE_VERSION, {\n upgrade(db, _oldVersion, _newVersion, _transaction) {\n if (db.objectStoreNames.contains(\"community_referrals\")) {\n db.deleteObjectStore(\"community_referrals\");\n }\n db.createObjectStore(\"community_referrals\");\n },\n });\n}\nexport async function setCommunityReferral(communityId, userId, timestamp) {\n const resolvedDb = await lazyOpenReferralCache();\n await resolvedDb.put(\"community_referrals\", { userId, timestamp }, communityId);\n}\nexport async function deleteCommunityReferral(communityId) {\n const resolvedDb = await lazyOpenReferralCache();\n resolvedDb.delete(\"community_referrals\", communityId);\n}\nexport async function getCommunityReferral(communityId, timestamp) {\n const resolvedDb = await lazyOpenReferralCache();\n const referral = await resolvedDb.get(\"community_referrals\", communityId);\n if (referral) {\n const oneWeekInMs = 7 * 24 * 60 * 60 * 1000;\n if (timestamp - referral.timestamp > oneWeekInMs) {\n return undefined;\n }\n return referral.userId;\n }\n return undefined;\n}\nexport async function clearCache() {\n const name = `openchat_referrals`;\n try {\n if (db !== undefined) {\n (await db).close();\n }\n await deleteDB(name);\n console.log(\"deleted db: \", name);\n }\n catch (err) {\n console.error(\"Unable to delete db: \", name, err);\n }\n}\n","export function mean(arr) {\n let total = 0;\n let count = 0;\n for (const value of arr) {\n if (value !== undefined) {\n total += value;\n count++;\n }\n }\n return count > 0 ? total / count : 0;\n}\n","import { toBigInt64 } from \"openchat-shared\";\nimport { AssertError } from \"@sinclair/typebox/value\";\nimport { Type } from \"@sinclair/typebox\";\nimport { BotDefinition, BotMessageContent as MessageContent } from \"../../typebox\";\nimport { externalBotDefinition, messageContent } from \"../common/chatMappersV2\";\nimport { mapOptional } from \"../../utils/mapping\";\nimport { typeboxValidate } from \"../../utils/typebox\";\nconst ApiBotSuccess = Type.Object({\n message: Type.Optional(Type.Object({\n id: Type.String(),\n content: MessageContent,\n finalised: Type.Optional(Type.Boolean()),\n block_level_markdown: Type.Optional(Type.Boolean()),\n ephemeral: Type.Optional(Type.Boolean()),\n })),\n});\nconst ApiBotBadRequest = Type.Any();\nconst ApiBotInternalError = Type.Any();\nconst ApiBotResponse = Type.Union([\n Type.Object({\n Success: ApiBotSuccess,\n }),\n Type.Object({\n BadRequest: ApiBotBadRequest,\n }),\n Type.Object({\n InternalError: ApiBotInternalError,\n }),\n Type.Literal(\"TooManyRequests\"),\n]);\nexport function getBotDefinition(endpoint) {\n return fetch(`${endpoint}/bot_definition`)\n .then((res) => {\n if (res.ok) {\n return res.json();\n }\n else {\n const msg = `Failed to load external bot schema: ${res.status}, ${res.statusText}, ${JSON.stringify(endpoint)}`;\n return {\n kind: \"bot_definition_failure\",\n error: msg,\n };\n }\n })\n .then(validateBotDefinition);\n}\nfunction validateBotDefinition(json) {\n try {\n const value = typeboxValidate(json, BotDefinition);\n return externalBotDefinition(value);\n }\n catch (err) {\n return {\n kind: \"bot_definition_failure\",\n error: formatError(err),\n };\n }\n}\nfunction formatError(err) {\n if (err instanceof AssertError) {\n return `${err.message}: ${err.error?.path}`;\n }\n return err;\n}\nfunction validateBotResponse(json) {\n try {\n const value = typeboxValidate(json, ApiBotResponse);\n return externalBotResponse(value);\n }\n catch (err) {\n console.error(\"Parse error: \", JSON.stringify(err));\n return {\n kind: \"internal_error\",\n error: formatError(err),\n };\n }\n}\nfunction externalBotResponse(value) {\n if (value === \"TooManyRequests\") {\n return {\n kind: \"too_many_requests\",\n };\n }\n else if (\"Success\" in value) {\n return {\n kind: \"success\",\n message: mapOptional(value.Success.message, ({ id, content, finalised, block_level_markdown, ephemeral }) => {\n return {\n messageId: toBigInt64(id),\n messageContent: messageContent(content, \"\"),\n finalised: finalised ?? false,\n blockLevelMarkdown: block_level_markdown ?? false,\n ephemeral: ephemeral ?? false,\n };\n }),\n };\n }\n else if (\"BadRequest\" in value) {\n return {\n kind: \"bad_request\",\n // TODO handle the various types\n reason: JSON.stringify(value.BadRequest),\n };\n }\n else if (\"InternalError\" in value) {\n return {\n kind: \"internal_error\",\n error: value.InternalError,\n };\n }\n return {\n kind: \"internal_error\",\n error: \"unknown\",\n };\n}\nexport function callBotCommandEndpoint(endpoint, token) {\n const headers = new Headers();\n headers.append(\"Content-type\", \"text/plain\");\n headers.append(\"x-oc-jwt\", token);\n return fetch(`${endpoint}/execute_command`, {\n method: \"POST\",\n headers: headers,\n })\n .then(async (res) => {\n if (res.ok) {\n return { Success: await res.json() };\n }\n else if (res.status === 400) {\n return { BadRequest: await res.text() };\n }\n else if (res.status === 429) {\n return \"TooManyRequests\";\n }\n else {\n return { InternalError: await res.text() };\n }\n })\n .then(validateBotResponse)\n .catch((err) => {\n console.log(\"Bot command failed: \", err);\n return { kind: \"internal_error\", error: err };\n });\n}\n","export const idlFactory = ({ IDL }) => {\n const network = IDL.Variant({\n 'mainnet': IDL.Null,\n 'regtest': IDL.Null,\n 'testnet': IDL.Null,\n });\n const address = IDL.Text;\n const get_utxos_request = IDL.Record({\n 'network': network,\n 'filter': IDL.Opt(IDL.Variant({\n 'page': IDL.Vec(IDL.Nat8),\n 'min_confirmations': IDL.Nat32,\n })),\n 'address': address,\n });\n const block_height = IDL.Nat32;\n const block_hash = IDL.Vec(IDL.Nat8);\n const satoshi = IDL.Nat64;\n const outpoint = IDL.Record({\n 'txid': IDL.Vec(IDL.Nat8),\n 'vout': IDL.Nat32,\n });\n const utxo = IDL.Record({\n 'height': block_height,\n 'value': satoshi,\n 'outpoint': outpoint,\n });\n const get_utxos_response = IDL.Record({\n 'next_page': IDL.Opt(IDL.Vec(IDL.Nat8)),\n 'tip_height': block_height,\n 'tip_block_hash': block_hash,\n 'utxos': IDL.Vec(utxo),\n });\n return IDL.Service({\n 'bitcoin_get_utxos_query': IDL.Func([get_utxos_request], [get_utxos_response], ['query']),\n });\n};\nexport const init = ({ IDL }) => { return []; };\n","import { CandidCanisterAgent } from \"../canisterAgent/candid\";\nimport { idlFactory } from \"./candid/idl\";\nimport { getUtxosResponse } from \"./mappers\";\nconst BITCOIN_CANISTER_ID = \"ghsi2-tqaaa-aaaan-aaaca-cai\";\nexport class BitcoinClient extends CandidCanisterAgent {\n constructor(identity, agent, mainnetEnabled) {\n super(identity, agent, BITCOIN_CANISTER_ID, idlFactory, \"BitcoinCanister\");\n this.network = mainnetEnabled\n ? { mainnet: null }\n : { testnet: null };\n }\n getUtxos(address) {\n return this.handleQueryResponse(() => this.service.bitcoin_get_utxos_query({\n network: this.network,\n address,\n filter: []\n }), getUtxosResponse);\n }\n}\n","/* eslint-disable no-case-declarations */\nimport { HttpAgent } from \"@dfinity/agent\";\nimport { getCachedChats, getCachePrimerTimestamps, initDb, loadFailedMessages, removeFailedMessage, setCachedChats, setCachedMessageIfNotExists, recordFailedMessage, cacheLocalUserIndexForUser, getLocalUserIndexForUser, clearCache, getCachedExternalAchievements, setCachedExternalAchievements, getActivityFeedEvents, setActivityFeedEvents, getCachedBots, setCachedBots, deleteEventsForChat, } from \"../utils/caching\";\nimport { isMainnet } from \"../utils/network\";\nimport { getAllUsers, clearCache as clearUserCache, isUserIdDeleted } from \"../utils/userCache\";\nimport { getCachedRegistry, setCachedRegistry } from \"../utils/registryCache\";\nimport { UserIndexClient } from \"./userIndex/userIndex.client\";\nimport { UserClient } from \"./user/user.client\";\nimport { GroupClient } from \"./group/group.client\";\nimport { LocalUserIndexClient } from \"./localUserIndex/localUserIndex.client\";\nimport { NotificationsClient } from \"./notifications/notifications.client\";\nimport { ProposalsBotClient } from \"./proposalsBot/proposalsBot.client\";\nimport { OnlineClient } from \"./online/online.client\";\nimport { DataClient } from \"./data/data.client\";\nimport { LedgerClient } from \"./ledger/ledger.client\";\nimport { LedgerIndexClient } from \"./ledgerIndex/ledgerIndex.client\";\nimport { GroupIndexClient } from \"./groupIndex/groupIndex.client\";\nimport { MarketMakerClient } from \"./marketMaker/marketMaker.client\";\nimport { RegistryClient } from \"./registry/registry.client\";\nimport { DexesAgent } from \"./dexes\";\nimport { chunk, distinctBy, toRecord, toRecord2 } from \"../utils/list\";\nimport { measure } from \"./common/profiling\";\nimport { buildBlobUrl, buildUserAvatarUrl, getUpdatedEvents, mergeDirectChatUpdates, mergeGroupChats, mergeGroupChatUpdates, } from \"../utils/chat\";\nimport { NnsGovernanceClient } from \"./nnsGovernance/nns.governance.client\";\nimport { SnsGovernanceClient } from \"./snsGovernance/sns.governance.client\";\nimport { UnsupportedValueError, ChatMap, chatIdentifiersEqual, DestinationInvalidError, CommonResponses, applyOptionUpdate, ANON_USER_ID, offline, Stream, getOrAdd, waitAll, Lazy, MessageMap, MAX_ACTIVITY_EVENTS, messageContextToString, MessageContextMap, } from \"openchat-shared\";\nimport { AsyncMessageContextMap } from \"../utils/messageContext\";\nimport { CommunityClient } from \"./community/community.client\";\nimport { isSuccessfulCommunitySummaryResponse, mergeCommunities, mergeCommunityUpdates, } from \"../utils/community\";\nimport { AnonUserClient } from \"./user/anonUser.client\";\nimport { excludeLatestKnownUpdateIfBeforeFix } from \"./common/replicaUpToDateChecker\";\nimport { IcpCoinsClient } from \"./icpcoins/icpCoinsClient\";\nimport { IcpSwapClient } from \"./icpSwap/icpSwapClient\";\nimport { IcpLedgerIndexClient } from \"./icpLedgerIndex/icpLedgerIndex.client\";\nimport { TranslationsClient } from \"./translations/translations.client\";\nimport { CkbtcMinterClient } from \"./ckbtcMinter/ckbtcMinter.client\";\nimport { SignInWithEmailClient } from \"./signInWithEmail/signInWithEmail.client\";\nimport { SignInWithEthereumClient } from \"./signInWithEthereum/signInWithEthereum.client\";\nimport { SignInWithSolanaClient } from \"./signInWithSolana/signInWithSolana.client\";\nimport { createHttpAgentSync } from \"../utils/httpAgent\";\nimport { deleteCommunityReferral, clearCache as clearReferralCache, getCommunityReferral, } from \"../utils/referralCache\";\nimport { mean } from \"../utils/maths\";\nimport { callBotCommandEndpoint } from \"./externalBot/externalBot\";\nimport { BitcoinClient } from \"./bitcoin/bitcoin.client\";\nimport { bytesToHexString } from \"../utils/mapping\";\nexport class OpenChatAgent extends EventTarget {\n constructor(identity, config) {\n super();\n this.identity = identity;\n this.config = config;\n this._logger = config.logger;\n this._agent = createHttpAgentSync(identity, config.icUrl);\n this.db = initDb(this.principal);\n this._onlineClient = new OnlineClient(identity, this._agent, config.onlineCanister);\n this._userIndexClient = new UserIndexClient(identity, this._agent, config.userIndexCanister, config.blobUrlPattern);\n this._groupIndexClient = new GroupIndexClient(identity, this._agent, config.groupIndexCanister);\n this._notificationClient = new NotificationsClient(identity, this._agent, config.notificationsCanister);\n this._registryClient = new RegistryClient(identity, this._agent, config.registryCanister, config.blobUrlPattern);\n this._dataClient = new DataClient(identity, this._agent, config);\n this._exchangeRateClients = [\n new IcpCoinsClient(identity, this._agent),\n new IcpSwapClient(identity, this._agent),\n ];\n this._localUserIndexClients = {};\n this._ledgerClients = {};\n this._ledgerIndexClients = {};\n this._groupClients = {};\n this._communityClients = {};\n this._groupInvite = config.groupInvite;\n this._bitcoinClient = new Lazy(() => new BitcoinClient(this.identity, this._agent, this.config.bitcoinMainnetEnabled));\n this._ckbtcMinterClient = new Lazy(() => new CkbtcMinterClient(this.identity, this._agent, this.config.bitcoinMainnetEnabled));\n this._dexesAgent = new Lazy(() => new DexesAgent(this._agent));\n this._marketMakerClient = new Lazy(() => new MarketMakerClient(identity, this._agent, config.marketMakerCanister));\n this._proposalsBotClient = new Lazy(() => new ProposalsBotClient(identity, this._agent, config.proposalBotCanister));\n this._signInWithEmailClient = new Lazy(() => new SignInWithEmailClient(identity, this._agent, config.signInWithEmailCanister));\n this._signInWithEthereumClient = new Lazy(() => new SignInWithEthereumClient(identity, this._agent, config.signInWithEthereumCanister));\n this._signInWithSolanaClient = new Lazy(() => new SignInWithSolanaClient(identity, this._agent, config.signInWithSolanaCanister));\n this._translationsClient = new Lazy(() => new TranslationsClient(identity, this._agent, config.translationsCanister));\n }\n get principal() {\n return this.identity.getPrincipal();\n }\n getAllCachedUsers() {\n return measure(\"getAllUsers\", () => getAllUsers()).then((users) => {\n return new Map(users.map((user) => [user.userId, this.rehydrateUserSummary(user)]));\n });\n }\n logError(message, ...optionalParams) {\n this._logger.error(message, optionalParams);\n }\n set groupInvite(value) {\n this._groupInvite = value;\n }\n set communityInvite(value) {\n this._communityInvite = value;\n }\n createUserClient(userId) {\n if (userId === ANON_USER_ID) {\n this._userClient = AnonUserClient.create();\n }\n else {\n this._userClient = new UserClient(userId, this.identity, this._agent, this.config, this.db);\n }\n return this;\n }\n communityClient(communityId) {\n if (!this._communityClients[communityId]) {\n const inviteCode = this.getProvidedCommunityInviteCode(communityId);\n this._communityClients[communityId] = new CommunityClient(this.identity, this._agent, this.config, communityId, this.db, inviteCode);\n }\n return this._communityClients[communityId];\n }\n getGroupClient(chatId) {\n if (!this._groupClients[chatId]) {\n const inviteCode = this.getProvidedGroupInviteCode({\n kind: \"group_chat\",\n groupId: chatId,\n });\n this._groupClients[chatId] = new GroupClient(this.identity, this._agent, this.config, { kind: \"group_chat\", groupId: chatId }, this.db, inviteCode);\n }\n return this._groupClients[chatId];\n }\n get userClient() {\n if (this._userClient) {\n return this._userClient;\n }\n throw new Error(\"Attempted to use the user client before it has been initialised\");\n }\n getLedgerClient(ledger) {\n if (!this._ledgerClients[ledger]) {\n this._ledgerClients[ledger] = new LedgerClient(this.identity, this._agent, ledger);\n }\n return this._ledgerClients[ledger];\n }\n getLedgerIndexClient(ledgerIndex) {\n if (!this._ledgerIndexClients[ledgerIndex]) {\n this._ledgerIndexClients[ledgerIndex] = new LedgerIndexClient(this.identity, this._agent, ledgerIndex);\n }\n return this._ledgerIndexClients[ledgerIndex];\n }\n getLocalUserIndexClient(canisterId) {\n if (!this._localUserIndexClients[canisterId]) {\n this._localUserIndexClients[canisterId] = new LocalUserIndexClient(this.identity, this._agent, canisterId, this.db);\n }\n return this._localUserIndexClients[canisterId];\n }\n getProvidedGroupInviteCode(chatId) {\n if (this._groupInvite === undefined)\n return undefined;\n return chatIdentifiersEqual(this._groupInvite.chatId, chatId)\n ? this._groupInvite.code\n : undefined;\n }\n getProvidedCommunityInviteCode(communityId) {\n if (this._communityInvite === undefined)\n return undefined;\n return this._communityInvite.id.communityId === communityId\n ? this._communityInvite.code\n : undefined;\n }\n getCommunityReferral(communityId) {\n return getCommunityReferral(communityId, Date.now());\n }\n translationsClient() {\n return this._translationsClient.get();\n }\n editMessage(chatId, msg, threadRootMessageIndex, blockLevelMarkdown, newAchievement) {\n if (offline())\n return Promise.resolve(\"failure\");\n switch (chatId.kind) {\n case \"direct_chat\":\n return this.editDirectMessage(chatId, msg, threadRootMessageIndex, blockLevelMarkdown);\n case \"group_chat\":\n return this.editGroupMessage(chatId, msg, threadRootMessageIndex, blockLevelMarkdown, newAchievement);\n case \"channel\":\n return this.editChannelMessage(chatId, msg, threadRootMessageIndex, blockLevelMarkdown, newAchievement);\n }\n }\n sendMessage(messageContext, user, mentioned, event, acceptedRules, messageFilterFailed, pin, newAchievement) {\n return new Stream(async (resolve, reject) => {\n const onRequestAccepted = () => resolve(\"accepted\", false);\n const { chatId, threadRootMessageIndex } = messageContext;\n if (offline()) {\n recordFailedMessage(this.db, chatId, event, threadRootMessageIndex);\n return resolve([CommonResponses.offline(), event.event], true);\n }\n if (chatId.kind === \"channel\") {\n if (event.event.content.kind === \"crypto_content\" ||\n event.event.content.kind === \"prize_content_initial\" ||\n event.event.content.kind === \"p2p_swap_content_initial\") {\n return resolve(await this.userClient.sendMessageWithTransferToChannel(chatId, event.event.content.kind !== \"p2p_swap_content_initial\"\n ? event.event.content.transfer.recipient\n : undefined, user, event, threadRootMessageIndex, acceptedRules?.community, acceptedRules?.chat, messageFilterFailed, pin), true);\n }\n return resolve(await this.sendChannelMessage(chatId, user.username, user.displayName, mentioned, event, threadRootMessageIndex, acceptedRules?.community, acceptedRules?.chat, messageFilterFailed, newAchievement, onRequestAccepted), true);\n }\n if (chatId.kind === \"group_chat\") {\n if (event.event.content.kind === \"crypto_content\" ||\n event.event.content.kind === \"prize_content_initial\" ||\n event.event.content.kind === \"p2p_swap_content_initial\") {\n return resolve(await this.userClient.sendMessageWithTransferToGroup(chatId, event.event.content.kind !== \"p2p_swap_content_initial\"\n ? event.event.content.transfer.recipient\n : undefined, user, event, threadRootMessageIndex, acceptedRules?.chat, messageFilterFailed, pin), true);\n }\n return resolve(await this.sendGroupMessage(chatId, user.username, user.displayName, mentioned, event, threadRootMessageIndex, acceptedRules?.chat, messageFilterFailed, newAchievement, onRequestAccepted), true);\n }\n if (chatId.kind === \"direct_chat\") {\n return resolve(await this.sendDirectMessage(chatId, event, messageFilterFailed, threadRootMessageIndex, pin, onRequestAccepted), true);\n }\n reject(new UnsupportedValueError(\"Unexpect chat type\", chatId));\n });\n }\n sendChannelMessage(chatId, senderName, senderDisplayName, mentioned, event, threadRootMessageIndex, communityRulesAccepted, channelRulesAccepted, messageFilterFailed, newAchievement, onRequestAccepted) {\n return this.communityClient(chatId.communityId).sendMessage(chatId, senderName, senderDisplayName, mentioned, event, threadRootMessageIndex, communityRulesAccepted, channelRulesAccepted, messageFilterFailed, newAchievement, onRequestAccepted);\n }\n sendGroupMessage(chatId, senderName, senderDisplayName, mentioned, event, threadRootMessageIndex, rulesAccepted, messageFilterFailed, newAchievement, onRequestAccepted) {\n return this.getGroupClient(chatId.groupId).sendMessage(senderName, senderDisplayName, mentioned, event, threadRootMessageIndex, rulesAccepted, messageFilterFailed, newAchievement, onRequestAccepted);\n }\n editGroupMessage(chatId, message, threadRootMessageIndex, blockLevelMarkdown, newAchievement) {\n return this.getGroupClient(chatId.groupId).editMessage(message, threadRootMessageIndex, blockLevelMarkdown, newAchievement);\n }\n editChannelMessage(chatId, message, threadRootMessageIndex, blockLevelMarkdown, newAchievement) {\n return this.communityClient(chatId.communityId).editMessage(chatId, message, threadRootMessageIndex, blockLevelMarkdown, newAchievement);\n }\n sendDirectMessage(chatId, event, messageFilterFailed, threadRootMessageIndex, pin, onRequestAccepted) {\n return this.userClient.sendMessage(chatId, event, messageFilterFailed, threadRootMessageIndex, pin, onRequestAccepted);\n }\n editDirectMessage(recipientId, message, threadRootMessageIndex, blockLevelMarkdown) {\n return this.userClient.editMessage(recipientId.userId, message, threadRootMessageIndex, blockLevelMarkdown);\n }\n createGroupChat(candidate) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n if (candidate.id.kind === \"channel\") {\n return this.communityClient(candidate.id.communityId).createChannel(candidate);\n }\n else {\n return this.userClient.createGroup(candidate);\n }\n }\n updateGroup(chatId, name, desc, rules, permissions, avatar, eventsTimeToLive, gateConfig, isPublic, messagesVisibleToNonMembers, externalUrl) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n switch (chatId.kind) {\n case \"group_chat\":\n return this.getGroupClient(chatId.groupId).updateGroup(name, desc, rules, permissions, avatar, eventsTimeToLive, gateConfig, isPublic, messagesVisibleToNonMembers);\n case \"channel\":\n return this.communityClient(chatId.communityId).updateChannel(chatId, name, desc, rules, permissions, avatar, eventsTimeToLive, gateConfig, isPublic, messagesVisibleToNonMembers, externalUrl);\n }\n }\n async inviteUsers(id, userIds, callerUsername) {\n if (!userIds.length) {\n return Promise.resolve(true);\n }\n if (offline())\n return Promise.resolve(false);\n switch (id.kind) {\n case \"community\": {\n const localUserIndex = await this.communityClient(id.communityId).localUserIndex();\n const localUserIndexClient = this.getLocalUserIndexClient(localUserIndex);\n return localUserIndexClient.inviteUsersToCommunity(id.communityId, userIds, callerUsername);\n }\n case \"group_chat\": {\n const localUserIndex = await this.getGroupClient(id.groupId).localUserIndex();\n const localUserIndexClient = this.getLocalUserIndexClient(localUserIndex);\n return localUserIndexClient.inviteUsersToGroup(id.groupId, userIds, callerUsername);\n }\n case \"channel\": {\n const localUserIndex = await this.communityClient(id.communityId).localUserIndex();\n const localUserIndexClient = this.getLocalUserIndexClient(localUserIndex);\n return localUserIndexClient.inviteUsersToChannel(id.communityId, id.channelId, userIds, callerUsername);\n }\n }\n }\n chatEventsBatch(localUserIndex, requests, cachePrimer) {\n console.debug(\"CHAT EVENTS: Getting events batch\", {\n localUserIndex,\n requests,\n });\n return this.getLocalUserIndexClient(localUserIndex).chatEvents(requests, cachePrimer);\n }\n chatEventsWindow(eventIndexRange, chatId, messageIndex, threadRootMessageIndex, latestKnownUpdate) {\n latestKnownUpdate = excludeLatestKnownUpdateIfBeforeFix(latestKnownUpdate);\n console.debug(\"CHAT EVENTS: Getting events window\", {\n chatId,\n threadRootMessageIndex,\n messageIndex,\n });\n switch (chatId.kind) {\n case \"direct_chat\":\n return this.directChatEventsWindow(eventIndexRange, chatId, messageIndex, latestKnownUpdate);\n case \"group_chat\":\n return this.groupChatEventsWindow(eventIndexRange, chatId, messageIndex, threadRootMessageIndex, latestKnownUpdate);\n case \"channel\":\n return this.channelEventsWindow(eventIndexRange, chatId, messageIndex, threadRootMessageIndex, latestKnownUpdate);\n }\n }\n directChatEventsWindow(eventIndexRange, chatId, messageIndex, latestKnownUpdate) {\n return this.rehydrateEventResponse(chatId, this.userClient.chatEventsWindow(eventIndexRange, chatId, messageIndex, latestKnownUpdate), undefined, latestKnownUpdate);\n }\n chatEvents(chatId, eventIndexRange, startIndex, ascending, threadRootMessageIndex, latestKnownUpdate) {\n latestKnownUpdate = excludeLatestKnownUpdateIfBeforeFix(latestKnownUpdate);\n console.debug(\"CHAT EVENTS: Getting chat events\", {\n chatId,\n threadRootMessageIndex,\n startIndex,\n ascending,\n });\n if (chatId.kind === \"group_chat\") {\n return this.groupChatEvents(eventIndexRange, chatId, startIndex, ascending, threadRootMessageIndex, latestKnownUpdate);\n }\n else if (chatId.kind === \"direct_chat\") {\n return this.directChatEvents(eventIndexRange, chatId, startIndex, ascending, threadRootMessageIndex, latestKnownUpdate);\n }\n else if (chatId.kind === \"channel\") {\n return this.channelEvents(eventIndexRange, chatId, startIndex, ascending, threadRootMessageIndex, latestKnownUpdate);\n }\n throw new UnsupportedValueError(\"Unexpect chat type\", chatId);\n }\n directChatEvents(eventIndexRange, chatId, startIndex, ascending, threadRootMessageIndex, latestKnownUpdate) {\n return this.rehydrateEventResponse(chatId, this.userClient.chatEvents(eventIndexRange, chatId, startIndex, ascending, threadRootMessageIndex, latestKnownUpdate), threadRootMessageIndex, latestKnownUpdate);\n }\n directChatEventsByEventIndex(chatId, eventIndexes, threadRootMessageIndex, \n // If threadRootMessageIndex is defined, then this should be the latest event index for that thread\n latestKnownUpdate) {\n return this.rehydrateEventResponse(chatId, this.userClient.chatEventsByIndex(eventIndexes, chatId, threadRootMessageIndex, latestKnownUpdate), threadRootMessageIndex, latestKnownUpdate);\n }\n channelEventsWindow(eventIndexRange, chatId, messageIndex, threadRootMessageIndex, latestKnownUpdate) {\n return this.rehydrateEventResponse(chatId, this.communityClient(chatId.communityId).eventsWindow(chatId, eventIndexRange, messageIndex, threadRootMessageIndex, latestKnownUpdate), threadRootMessageIndex, latestKnownUpdate);\n }\n groupChatEventsWindow(eventIndexRange, chatId, messageIndex, threadRootMessageIndex, latestKnownUpdate) {\n const rawEvents = this.getGroupClient(chatId.groupId).chatEventsWindow(eventIndexRange, messageIndex, threadRootMessageIndex, latestKnownUpdate);\n return this.rehydrateEventResponse(chatId, rawEvents, threadRootMessageIndex, latestKnownUpdate);\n }\n channelEvents(eventIndexRange, chatId, startIndex, ascending, threadRootMessageIndex, latestKnownUpdate) {\n return this.rehydrateEventResponse(chatId, this.communityClient(chatId.communityId).events(chatId, eventIndexRange, startIndex, ascending, threadRootMessageIndex, latestKnownUpdate), threadRootMessageIndex, latestKnownUpdate);\n }\n groupChatEvents(eventIndexRange, chatId, startIndex, ascending, threadRootMessageIndex, latestKnownUpdate) {\n return this.rehydrateEventResponse(chatId, this.getGroupClient(chatId.groupId).chatEvents(eventIndexRange, startIndex, ascending, threadRootMessageIndex, latestKnownUpdate), threadRootMessageIndex, latestKnownUpdate);\n }\n chatEventsByEventIndex(chatId, eventIndexes, threadRootMessageIndex, latestKnownUpdate) {\n latestKnownUpdate = excludeLatestKnownUpdateIfBeforeFix(latestKnownUpdate);\n console.debug(\"CHAT EVENTS: Getting chat events by index\", {\n chatId,\n threadRootMessageIndex,\n eventIndexes,\n });\n switch (chatId.kind) {\n case \"group_chat\":\n return this.groupChatEventsByEventIndex(chatId, eventIndexes, threadRootMessageIndex, latestKnownUpdate);\n case \"direct_chat\":\n return this.directChatEventsByEventIndex(chatId, eventIndexes, threadRootMessageIndex, latestKnownUpdate);\n case \"channel\":\n return this.channelEventsByEventIndex(chatId, eventIndexes, threadRootMessageIndex, latestKnownUpdate);\n }\n }\n channelEventsByEventIndex(chatId, eventIndexes, threadRootMessageIndex, latestKnownUpdate) {\n return this.rehydrateEventResponse(chatId, this.communityClient(chatId.communityId).eventsByIndex(chatId, eventIndexes, threadRootMessageIndex, latestKnownUpdate), threadRootMessageIndex, latestKnownUpdate);\n }\n groupChatEventsByEventIndex(chatId, eventIndexes, threadRootMessageIndex, \n // If threadRootMessageIndex is defined, then this should be the latest event index for that thread\n latestKnownUpdate) {\n return this.rehydrateEventResponse(chatId, this.getGroupClient(chatId.groupId).chatEventsByIndex(eventIndexes, threadRootMessageIndex, latestKnownUpdate), threadRootMessageIndex, latestKnownUpdate);\n }\n async getDeletedGroupMessage(chatId, messageId, threadRootMessageIndex) {\n switch (chatId.kind) {\n case \"group_chat\":\n const groupResp = await this.getGroupClient(chatId.groupId).getDeletedMessage(messageId, threadRootMessageIndex);\n if (groupResp.kind === \"success\") {\n groupResp.content = this.rehydrateMessageContent(groupResp.content);\n }\n return groupResp;\n case \"channel\":\n const channelResp = await this.communityClient(chatId.communityId).getDeletedMessage(chatId, messageId, threadRootMessageIndex);\n if (channelResp.kind === \"success\") {\n channelResp.content = this.rehydrateMessageContent(channelResp.content);\n }\n return channelResp;\n }\n }\n async getDeletedDirectMessage(userId, messageId) {\n const response = await this.userClient.getDeletedMessage(userId, messageId);\n if (response.kind === \"success\") {\n response.content = this.rehydrateMessageContent(response.content);\n }\n return response;\n }\n rehydrateMessageContent(content) {\n if ((content.kind === \"file_content\" ||\n content.kind === \"image_content\" ||\n content.kind === \"audio_content\") &&\n content.blobReference !== undefined) {\n content = this.rehydrateDataContent(content);\n }\n if (content.kind === \"video_content\") {\n return {\n ...content,\n videoData: this.rehydrateDataContent(content.videoData),\n imageData: this.rehydrateDataContent(content.imageData),\n };\n }\n return content;\n }\n /**\n * Given a list of events, identify all eventIndexes which we may need to look up\n * In practice this means the event indexes of embedded reply contexts\n */\n findMissingEventIndexesByChat(defaultChatId, events, threadRootMessageIndex) {\n return events.reduce((result, ev) => {\n if (ev.event.kind === \"message\" &&\n ev.event.repliesTo &&\n ev.event.repliesTo.kind === \"raw_reply_context\") {\n result.insert(ev.event.repliesTo.sourceContext ?? {\n chatId: { ...defaultChatId },\n threadRootMessageIndex,\n }, ev.event.repliesTo.eventIndex);\n }\n return result;\n }, new AsyncMessageContextMap());\n }\n messagesFromEventsResponse(context, resp) {\n if (resp !== \"events_failed\") {\n return [\n context,\n resp.events.reduce((msgs, ev) => {\n if (ev.event.kind === \"message\") {\n msgs.push(ev);\n }\n return msgs;\n }, []),\n ];\n }\n else {\n return [context, []];\n }\n }\n async resolveMissingIndexes(currentChatId, events, threadRootMessageIndex, latestKnownUpdate) {\n const contextMap = this.findMissingEventIndexesByChat(currentChatId, events, threadRootMessageIndex);\n if (contextMap.length === 0)\n return Promise.resolve(new AsyncMessageContextMap());\n const mapped = await contextMap.asyncMap((ctx, idxs) => {\n const chatId = ctx.chatId;\n const chatKind = chatId.kind;\n // Note that the latestKnownUpdate relates to the *currentChat*, not necessarily the chat for this messageContext\n // So only include it if the context matches the current chat\n // And yes - this is probably trying to tell us something\n const latestUpdate = chatIdentifiersEqual(chatId, currentChatId)\n ? latestKnownUpdate\n : undefined;\n if (chatKind === \"direct_chat\") {\n return this.userClient\n .chatEventsByIndex(idxs, chatId, ctx.threadRootMessageIndex, latestUpdate)\n .then((resp) => this.messagesFromEventsResponse(ctx, resp));\n }\n else if (chatKind === \"group_chat\") {\n const client = this.getGroupClient(chatId.groupId);\n return client\n .chatEventsByIndex(idxs, ctx.threadRootMessageIndex, latestUpdate)\n .then((resp) => this.messagesFromEventsResponse(ctx, resp));\n }\n else if (chatKind === \"channel\") {\n const client = this.communityClient(chatId.communityId);\n return client\n .eventsByIndex(chatId, idxs, ctx.threadRootMessageIndex, latestUpdate)\n .then((resp) => this.messagesFromEventsResponse(ctx, resp));\n }\n else {\n throw new UnsupportedValueError(\"unknown chatid kind supplied\", chatId);\n }\n });\n return mapped;\n }\n rehydrateEvent(ev, defaultChatId, missingReplies, threadRootMessageIndex) {\n if (ev.event.kind === \"message\") {\n const originalContent = ev.event.content;\n const rehydratedContent = this.rehydrateMessageContent(originalContent);\n const originalReplyContext = ev.event.repliesTo;\n let rehydratedReplyContext = undefined;\n if (ev.event.repliesTo && ev.event.repliesTo.kind === \"raw_reply_context\") {\n const messageContext = ev.event.repliesTo.sourceContext ?? {\n chatId: { ...defaultChatId },\n threadRootMessageIndex,\n };\n const messageEvents = missingReplies.lookup(messageContext);\n const idx = ev.event.repliesTo.eventIndex;\n const msg = messageEvents.find((me) => me.index === idx)?.event;\n if (msg) {\n rehydratedReplyContext = {\n kind: \"rehydrated_reply_context\",\n content: structuredClone(this.rehydrateMessageContent(msg.content)),\n senderId: msg.sender,\n messageId: msg.messageId,\n messageIndex: msg.messageIndex,\n eventIndex: idx,\n edited: msg.edited,\n isThreadRoot: msg.thread !== undefined,\n sourceContext: messageContext,\n };\n }\n else {\n this._logger.log(\"Reply context not found, this should only happen if we failed to load the reply context message\", {\n chatId: { ...defaultChatId },\n messageContext,\n messageEvents,\n repliesTo: ev.event.repliesTo,\n });\n }\n }\n if (originalContent !== rehydratedContent || rehydratedReplyContext !== undefined) {\n return {\n ...ev,\n event: {\n ...ev.event,\n content: rehydratedContent,\n repliesTo: rehydratedReplyContext ?? originalReplyContext,\n },\n };\n }\n }\n return ev;\n }\n async rehydrateEventResponse(currentChatId, eventsPromise, threadRootMessageIndex, latestKnownUpdate) {\n const resp = await eventsPromise;\n if (resp === \"events_failed\") {\n return resp;\n }\n const missing = await this.resolveMissingIndexes(currentChatId, resp.events, threadRootMessageIndex, latestKnownUpdate);\n resp.events = resp.events.map((e) => this.rehydrateEvent(e, currentChatId, missing, threadRootMessageIndex));\n return resp;\n }\n rehydrateUserSummary(userSummary) {\n const ref = userSummary.blobReference;\n if (userSummary.kind === \"bot\") {\n return {\n ...userSummary,\n blobData: undefined,\n blobUrl: ref?.blobId === undefined\n ? \"/assets/bot_avatar.svg\"\n : `${this.config.blobUrlPattern\n .replace(\"{canisterId}\", this.config.userIndexCanister)\n .replace(\"{blobType}\", \"avatar\")}/${userSummary.userId}/${ref?.blobId}`,\n };\n }\n return userSummary.blobUrl\n ? userSummary\n : {\n ...userSummary,\n blobData: undefined,\n blobUrl: buildUserAvatarUrl(this.config.blobUrlPattern, userSummary.userId, ref?.blobId ?? undefined),\n };\n }\n callBotCommandEndpoint(endpoint, token) {\n return callBotCommandEndpoint(endpoint, token).then((resp) => {\n if (resp.kind === \"success\" && resp.message !== undefined) {\n return {\n ...resp,\n message: {\n ...resp.message,\n messageContent: this.rehydrateMessageContent(resp.message.messageContent),\n },\n };\n }\n return resp;\n });\n }\n rehydrateDataContent(dataContent, blobType = \"blobs\", channelId) {\n const ref = dataContent.blobReference;\n return ref !== undefined\n ? {\n ...dataContent,\n blobData: undefined,\n blobUrl: buildBlobUrl(this.config.blobUrlPattern, ref.canisterId, ref.blobId, blobType, channelId),\n }\n : dataContent;\n }\n async rehydrateMessage(chatId, message, threadRootMessageIndex, latestKnownUpdate) {\n latestKnownUpdate = excludeLatestKnownUpdateIfBeforeFix(latestKnownUpdate);\n const missing = await this.resolveMissingIndexes(chatId, [message], threadRootMessageIndex, latestKnownUpdate);\n return this.rehydrateEvent(message, chatId, missing, threadRootMessageIndex);\n }\n searchUsers(searchTerm, maxResults = 20) {\n if (offline())\n return Promise.resolve([]);\n return this._userIndexClient\n .searchUsers(searchTerm, maxResults)\n .then((users) => users.map((u) => this.rehydrateUserSummary(u)));\n }\n exploreChannels(id, searchTerm, pageIndex, pageSize = 10) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n return this.communityClient(id.communityId)\n .exploreChannels(searchTerm, pageIndex, pageSize)\n .then((res) => {\n if (res.kind === \"success\") {\n return {\n ...res,\n matches: res.matches.map((match) => ({\n ...match,\n avatar: this.rehydrateDataContent(match.avatar, \"avatar\", match.id),\n })),\n };\n }\n return res;\n });\n }\n exploreCommunities(searchTerm, pageIndex, pageSize = 10, flags, languages) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n return this._groupIndexClient\n .exploreCommunities(searchTerm, pageIndex, pageSize, flags, languages)\n .then((res) => {\n if (res.kind === \"success\") {\n return {\n ...res,\n matches: res.matches.map((match) => ({\n ...match,\n avatar: this.rehydrateDataContent(match.avatar, \"avatar\"),\n banner: this.rehydrateDataContent(match.banner, \"banner\"),\n })),\n };\n }\n return res;\n });\n }\n searchGroups(searchTerm, maxResults = 10) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n return this._groupIndexClient.searchGroups(searchTerm, maxResults).then((res) => {\n if (res.kind === \"success\") {\n return {\n ...res,\n matches: res.matches.map((match) => this.rehydrateDataContent(match, \"avatar\")),\n };\n }\n return res;\n });\n }\n searchGroupChat(chatId, searchTerm, userIds, maxResults = 10) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n switch (chatId.kind) {\n case \"group_chat\":\n return this.getGroupClient(chatId.groupId).searchGroupChat(searchTerm, userIds, maxResults);\n case \"channel\":\n return this.communityClient(chatId.communityId).searchChannel(chatId, maxResults, userIds, searchTerm);\n }\n }\n searchDirectChat(chatId, searchTerm, maxResults = 10) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n return this.userClient.searchDirectChat(chatId, searchTerm, maxResults);\n }\n async getUser(chitState, userId, allowStale = false) {\n const response = await this.getUsers(chitState, {\n userGroups: [\n {\n users: [userId],\n updatedSince: BigInt(0),\n },\n ],\n }, allowStale);\n if (response.users.length == 0) {\n return undefined;\n }\n return response.users[0];\n }\n getUsers(chitState, users, allowStale = false) {\n return this._userIndexClient.getUsers(chitState, users, allowStale).then((resp) => ({\n ...resp,\n users: resp.users.map((u) => this.rehydrateUserSummary(u)),\n }));\n }\n getUpdatedPinnedChannels(currentPinnedChannels, userResponse) {\n const byCommunity = currentPinnedChannels.reduce((map, channel) => {\n const channels = map.get(channel.communityId) ?? [];\n channels.push(channel);\n map.set(channel.communityId, channels);\n return map;\n }, new Map());\n userResponse.communities.added\n .flatMap((c) => c.pinned)\n .forEach((channel) => {\n byCommunity.get(channel.communityId)?.push(channel);\n });\n userResponse.communities.updated.forEach((c) => {\n if (c.pinned !== undefined) {\n if (c.pinned.length === 0) {\n byCommunity.delete(c.id.communityId);\n }\n else {\n byCommunity.set(c.id.communityId, c.pinned);\n }\n }\n });\n return [...byCommunity.values()].flat();\n }\n async _getUpdates(current) {\n const start = Date.now();\n let numberOfAsyncCalls = 0;\n let directChats;\n let directChatUpdates = [];\n let currentGroups = [];\n let groupsAdded = [];\n let userCanisterGroupUpdates = [];\n const groupsToCheckForUpdates = new Set();\n const groupsRemoved = new Set();\n let currentCommunities = [];\n let communitiesAdded = [];\n let userCanisterCommunityUpdates = [];\n const communitiesToCheckForUpdates = new Set();\n const communitiesRemoved = new Set();\n let avatarId;\n let blockedUsers;\n let pinnedGroupChats;\n let pinnedDirectChats;\n let pinnedFavouriteChats;\n let pinnedChannels;\n let favouriteChats;\n let suspensionChanged = undefined;\n let pinNumberSettings;\n let userCanisterLocalUserIndex;\n let achievements;\n let newAchievements;\n let achievementsLastSeen;\n let chitState;\n let referrals;\n let walletConfig;\n let messageActivitySummary;\n let installedBots;\n let apiKeys;\n let bitcoinAddress = undefined;\n let latestActiveGroupsCheck = BigInt(0);\n let latestUserCanisterUpdates;\n let anyUpdates = false;\n if (current === undefined) {\n const userResponse = await this.userClient.getInitialState();\n numberOfAsyncCalls++;\n directChats = userResponse.directChats.summaries;\n groupsAdded = userResponse.groupChats.summaries;\n communitiesAdded = userResponse.communities.summaries;\n avatarId = userResponse.avatarId;\n blockedUsers = userResponse.blockedUsers;\n pinnedGroupChats = userResponse.groupChats.pinned;\n pinnedDirectChats = userResponse.directChats.pinned;\n pinnedFavouriteChats = userResponse.favouriteChats.pinned;\n pinnedChannels = userResponse.communities.summaries.flatMap((c) => c.pinned);\n favouriteChats = userResponse.favouriteChats.chats;\n latestUserCanisterUpdates = userResponse.timestamp;\n pinNumberSettings = userResponse.pinNumberSettings;\n userCanisterLocalUserIndex = userResponse.localUserIndex;\n newAchievements = userResponse.achievements ?? [];\n achievements = new Set(newAchievements.reduce((all, a) => {\n if (a.reason.kind === \"achievement_unlocked\") {\n all.push(a.reason.type);\n }\n if (a.reason.kind === \"external_achievement_unlocked\") {\n all.push(a.reason.name);\n }\n return all;\n }, []));\n achievementsLastSeen = userResponse.achievementsLastSeen;\n chitState = {\n streakEnds: userResponse.streakEnds,\n streak: userResponse.streak,\n chitBalance: userResponse.chitBalance,\n nextDailyChitClaim: userResponse.nextDailyClaim,\n totalChitEarned: userResponse.totalChitEarned,\n };\n referrals = userResponse.referrals;\n walletConfig = userResponse.walletConfig;\n messageActivitySummary = userResponse.messageActivitySummary;\n anyUpdates = true;\n installedBots = userResponse.bots;\n apiKeys = userResponse.apiKeys;\n bitcoinAddress = userResponse.bitcoinAddress;\n }\n else {\n directChats = current.directChats;\n currentGroups = current.groupChats;\n currentCommunities = current.communities;\n latestActiveGroupsCheck = current.latestActiveGroupsCheck;\n installedBots = current.installedBots;\n apiKeys = current.apiKeys;\n bitcoinAddress = current.bitcoinAddress;\n const userResponse = await this.userClient.getUpdates(current.latestUserCanisterUpdates);\n numberOfAsyncCalls++;\n avatarId = current.avatarId;\n blockedUsers = current.blockedUsers;\n pinnedGroupChats = current.pinnedGroupChats;\n pinnedDirectChats = current.pinnedDirectChats;\n pinnedFavouriteChats = current.pinnedFavouriteChats;\n pinnedChannels = current.pinnedChannels;\n favouriteChats = current.favouriteChats;\n latestUserCanisterUpdates = current.latestUserCanisterUpdates;\n pinNumberSettings = current.pinNumberSettings;\n userCanisterLocalUserIndex = current.userCanisterLocalUserIndex;\n achievementsLastSeen = current.achievementsLastSeen;\n achievements = current.achievements;\n newAchievements = [];\n chitState = current.chitState;\n referrals = current.referrals;\n walletConfig = current.walletConfig;\n messageActivitySummary = current.messageActivitySummary;\n if (userResponse.kind === \"success\") {\n userResponse.botsAddedOrUpdated.forEach((b) => installedBots.set(b.id, b.permissions));\n userResponse.apiKeysGenerated.forEach((api) => apiKeys.set(api.botId, api));\n userResponse.botsRemoved.forEach((b) => {\n installedBots.delete(b);\n apiKeys.delete(b);\n });\n const removeDirectChatIds = userResponse.directChats.removed.map((id) => id.userId);\n directChats = userResponse.directChats.added.concat(mergeDirectChatUpdates(directChats, userResponse.directChats.updated, removeDirectChatIds));\n removeDirectChatIds.forEach((id) => {\n deleteEventsForChat(this.db, id);\n });\n directChatUpdates = userResponse.directChats.updated;\n groupsAdded = userResponse.groupChats.added;\n userCanisterGroupUpdates = userResponse.groupChats.updated;\n userCanisterGroupUpdates.forEach((g) => groupsToCheckForUpdates.add(g.id.groupId));\n userResponse.groupChats.removed.forEach((g) => groupsRemoved.add(g));\n communitiesAdded = userResponse.communities.added;\n userCanisterCommunityUpdates = userResponse.communities.updated;\n userCanisterCommunityUpdates.forEach((c) => communitiesToCheckForUpdates.add(c.id.communityId));\n userResponse.communities.removed.forEach((c) => communitiesRemoved.add(c));\n avatarId = applyOptionUpdate(avatarId, userResponse.avatarId);\n blockedUsers = userResponse.blockedUsers ?? blockedUsers;\n pinnedGroupChats = userResponse.groupChats.pinned ?? pinnedGroupChats;\n pinnedDirectChats = userResponse.directChats.pinned ?? pinnedDirectChats;\n pinnedFavouriteChats = userResponse.favouriteChats.pinned ?? pinnedFavouriteChats;\n pinnedChannels = this.getUpdatedPinnedChannels(pinnedChannels, userResponse);\n favouriteChats = userResponse.favouriteChats.chats ?? favouriteChats;\n suspensionChanged = userResponse.suspended;\n latestUserCanisterUpdates = userResponse.timestamp;\n pinNumberSettings = applyOptionUpdate(pinNumberSettings, userResponse.pinNumberSettings);\n achievementsLastSeen = userResponse.achievementsLastSeen ?? achievementsLastSeen;\n newAchievements = userResponse.achievements ?? [];\n newAchievements.forEach((a) => {\n if (a.reason.kind === \"achievement_unlocked\") {\n achievements.add(a.reason.type);\n }\n if (a.reason.kind === \"external_achievement_unlocked\") {\n achievements.add(a.reason.name);\n }\n });\n chitState = {\n streakEnds: userResponse.streakEnds,\n streak: userResponse.streak,\n chitBalance: userResponse.chitBalance,\n nextDailyChitClaim: userResponse.nextDailyClaim,\n totalChitEarned: userResponse.totalChitEarned,\n };\n referrals = referrals\n .filter((prev) => !userResponse.referrals.find((latest) => latest.userId === prev.userId))\n .concat(userResponse.referrals);\n walletConfig = userResponse.walletConfig ?? current.walletConfig;\n messageActivitySummary =\n userResponse.messageActivitySummary ?? current.messageActivitySummary;\n bitcoinAddress ??= userResponse.bitcoinAddress;\n anyUpdates = true;\n }\n }\n const currentGroupChatIds = currentGroups.map((g) => g.id);\n const currentCommunityIds = currentCommunities.map((c) => c.id);\n if (currentGroupChatIds.length > 0 || currentCommunityIds.length > 0) {\n const groupIndexResponse = await this._groupIndexClient.activeGroups(currentCommunityIds, currentGroupChatIds, latestActiveGroupsCheck);\n numberOfAsyncCalls++;\n groupIndexResponse.activeGroups.forEach((g) => groupsToCheckForUpdates.add(g));\n groupIndexResponse.deletedGroups.forEach((g) => groupsRemoved.add(g.id));\n groupIndexResponse.activeCommunities.forEach((c) => communitiesToCheckForUpdates.add(c));\n groupIndexResponse.deletedCommunities.forEach((c) => groupsRemoved.add(c.id));\n latestActiveGroupsCheck = groupIndexResponse.timestamp;\n // Also check for updates for recently joined groups and communities since it may take a few iterations\n // before the GroupIndex knows that they are active\n const recentlyJoinedCutOff = BigInt(start - 10 * 60 * 1000);\n for (const group of currentGroups) {\n if (group.membership.joined > recentlyJoinedCutOff) {\n groupsToCheckForUpdates.add(group.id.groupId);\n }\n }\n for (const community of currentCommunities) {\n if (community.membership.joined > recentlyJoinedCutOff) {\n groupsToCheckForUpdates.add(community.id.communityId);\n }\n }\n }\n const byLocalUserIndex = new Map();\n for (const group of groupsAdded) {\n getOrAdd(byLocalUserIndex, group.localUserIndex, []).push({\n canisterId: group.id.groupId,\n isCommunity: false,\n inviteCode: undefined,\n updatesSince: undefined,\n });\n }\n for (const community of communitiesAdded) {\n getOrAdd(byLocalUserIndex, community.localUserIndex, []).push({\n canisterId: community.id.communityId,\n isCommunity: true,\n inviteCode: undefined,\n updatesSince: undefined,\n });\n }\n for (const group of currentGroups) {\n if (groupsToCheckForUpdates.has(group.id.groupId)) {\n getOrAdd(byLocalUserIndex, group.localUserIndex, []).push({\n canisterId: group.id.groupId,\n isCommunity: false,\n inviteCode: undefined,\n updatesSince: group.lastUpdated,\n });\n }\n }\n for (const community of currentCommunities) {\n if (communitiesToCheckForUpdates.has(community.id.communityId)) {\n getOrAdd(byLocalUserIndex, community.localUserIndex, []).push({\n canisterId: community.id.communityId,\n isCommunity: true,\n inviteCode: undefined,\n updatesSince: community.lastUpdated,\n });\n }\n }\n const summaryUpdatesPromises = [];\n for (const [localUserIndex, args] of byLocalUserIndex) {\n for (const batch of chunk(args, 50)) {\n summaryUpdatesPromises.push(this.getLocalUserIndexClient(localUserIndex).groupAndCommunitySummaryUpdates(batch));\n numberOfAsyncCalls++;\n }\n }\n const summaryUpdatesResults = await waitAll(summaryUpdatesPromises);\n for (const error of summaryUpdatesResults.errors) {\n this._logger.error(\"Summary updates error\", error);\n }\n const groupCanisterGroupSummaries = [];\n const communityCanisterCommunitySummaries = [];\n const groupUpdates = [];\n const communityUpdates = [];\n let anyErrors = summaryUpdatesResults.errors.length > 0;\n for (const response of summaryUpdatesResults.success) {\n for (const result of response) {\n switch (result.kind) {\n case \"group\": {\n groupCanisterGroupSummaries.push(result.value);\n break;\n }\n case \"group_updates\": {\n groupUpdates.push(result.value);\n break;\n }\n case \"community\": {\n communityCanisterCommunitySummaries.push(result.value);\n break;\n }\n case \"community_updates\": {\n communityUpdates.push(result.value);\n break;\n }\n case \"error\": {\n if (!result.error.includes(\"DestinationInvalid\")) {\n anyErrors = true;\n }\n break;\n }\n }\n }\n }\n if (groupUpdates.length > 0 || communityUpdates.length > 0) {\n anyUpdates = true;\n }\n const groupChats = mergeGroupChats(groupsAdded, groupCanisterGroupSummaries)\n .concat(mergeGroupChatUpdates(currentGroups, userCanisterGroupUpdates, groupUpdates))\n .filter((g) => !groupsRemoved.has(g.id.groupId));\n const communities = mergeCommunities(communitiesAdded, communityCanisterCommunitySummaries)\n .concat(mergeCommunityUpdates(currentCommunities, userCanisterCommunityUpdates, communityUpdates))\n .filter((c) => !communitiesRemoved.has(c.id.communityId));\n this.removeExpiredLatestMessages(directChats, start);\n this.removeExpiredLatestMessages(groupChats, start);\n communities.forEach((c) => this.removeExpiredLatestMessages(c.channels, start));\n const state = {\n latestUserCanisterUpdates,\n latestActiveGroupsCheck,\n directChats,\n groupChats,\n communities,\n avatarId,\n blockedUsers,\n pinnedGroupChats,\n pinnedDirectChats,\n pinnedFavouriteChats,\n pinnedChannels,\n favouriteChats,\n pinNumberSettings,\n userCanisterLocalUserIndex,\n achievementsLastSeen,\n achievements,\n chitState,\n referrals,\n walletConfig,\n messageActivitySummary,\n installedBots,\n apiKeys,\n bitcoinAddress,\n };\n const updatedEvents = getUpdatedEvents(directChatUpdates, groupUpdates, communityUpdates);\n if (!anyErrors && this.userClient.userId !== ANON_USER_ID) {\n setCachedChats(this.db, this.principal, state, updatedEvents);\n }\n const end = Date.now();\n const duration = end - start;\n console.debug(`GetUpdates completed in ${duration}ms. Number of async calls: ${numberOfAsyncCalls}`);\n return {\n state: this.hydrateChatState(state),\n updatedEvents: updatedEvents.toMap(),\n anyUpdates,\n suspensionChanged,\n newAchievements,\n };\n }\n getUpdates(initialLoad) {\n return new Stream(async (resolve, reject) => {\n const cachedState = await getCachedChats(this.db, this.principal);\n const isOffline = offline();\n if (cachedState && initialLoad) {\n resolve({\n state: this.hydrateChatState(cachedState),\n updatedEvents: new Map(),\n anyUpdates: false,\n suspensionChanged: undefined,\n newAchievements: [],\n }, isOffline);\n }\n if (!isOffline) {\n try {\n const updates = await this._getUpdates(cachedState);\n resolve(updates, true);\n }\n catch (err) {\n reject(err);\n }\n }\n });\n }\n removeExpiredLatestMessages(chats, now) {\n for (const chat of chats) {\n if (chat.latestMessage?.event.messageIndex !== chat.latestMessageIndex ||\n (chat.latestMessage?.expiresAt !== undefined && chat.latestMessage.expiresAt < now)) {\n chat.latestMessage = undefined;\n }\n }\n }\n async getCommunitySummary(communityId) {\n const resp = await this.communityClient(communityId).summary();\n if (isSuccessfulCommunitySummaryResponse(resp)) {\n return this.hydrateCommunity(resp);\n }\n return resp;\n }\n hydrateChatState(state) {\n const groupChats = state.groupChats.map((c) => this.hydrateChatSummary(c));\n const communities = state.communities.map((c) => this.hydrateCommunity(c));\n return {\n ...state,\n groupChats,\n communities,\n };\n }\n hydrateCommunity(community) {\n const channels = community.channels.map((c) => this.hydrateChatSummary(c));\n return {\n ...community,\n channels,\n avatar: {\n ...this.rehydrateDataContent(community.avatar, \"avatar\"),\n },\n banner: {\n ...this.rehydrateDataContent(community.banner, \"banner\"),\n },\n };\n }\n hydrateChatSummary(chat) {\n switch (chat.kind) {\n case \"direct_chat\":\n return chat;\n case \"group_chat\":\n return this.rehydrateDataContent(chat, \"avatar\");\n case \"channel\":\n return this.rehydrateDataContent(chat, \"avatar\", chat.id);\n }\n }\n getCurrentUser() {\n return this._userIndexClient.getCurrentUser();\n }\n setModerationFlags(flags) {\n if (offline())\n return Promise.resolve(false);\n return this._userIndexClient.setModerationFlags(flags);\n }\n checkUsername(username, isBot) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this._userIndexClient.checkUsername(username, isBot);\n }\n setUsername(userId, username) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this._userIndexClient.setUsername(userId, username);\n }\n setDisplayName(userId, displayName) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this._userIndexClient.setDisplayName(userId, displayName);\n }\n changeRole(chatId, userId, newRole) {\n if (offline())\n return Promise.resolve(\"offline\");\n switch (chatId.kind) {\n case \"group_chat\":\n return this.getGroupClient(chatId.groupId).changeRole(userId, newRole);\n case \"channel\":\n return this.communityClient(chatId.communityId).changeChannelRole(chatId, userId, newRole);\n }\n }\n deleteGroup(chatId) {\n if (offline())\n return Promise.resolve(\"offline\");\n switch (chatId.kind) {\n case \"group_chat\":\n return this.userClient.deleteGroup(chatId.groupId);\n case \"channel\":\n return this.communityClient(chatId.communityId).deleteChannel(chatId);\n }\n }\n removeMember(chatId, userId) {\n if (offline())\n return Promise.resolve(\"offline\");\n switch (chatId.kind) {\n case \"group_chat\":\n return this.getGroupClient(chatId.groupId).removeMember(userId);\n case \"channel\":\n return this.communityClient(chatId.communityId).removeMemberFromChannel(chatId, userId);\n }\n }\n blockUserFromDirectChat(userId) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this.userClient.blockUser(userId);\n }\n blockUserFromGroupChat(chatId, userId) {\n if (offline())\n return Promise.resolve(\"offline\");\n if (chatId.kind === \"channel\")\n throw new Error(\"TODO - blockUserFromChannel not implemented\");\n return this.getGroupClient(chatId.groupId).blockUser(userId);\n }\n unblockUserFromGroupChat(chatId, userId) {\n if (offline())\n return Promise.resolve(\"offline\");\n if (chatId.kind === \"channel\")\n throw new Error(\"TODO - unblockUserFromChannel not implemented\");\n return this.getGroupClient(chatId.groupId).unblockUser(userId);\n }\n unblockUserFromDirectChat(userId) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this.userClient.unblockUser(userId);\n }\n leaveGroup(chatId) {\n if (offline())\n return Promise.resolve(\"offline\");\n if (chatIdentifiersEqual(this._groupInvite?.chatId, chatId)) {\n this._groupInvite = undefined;\n }\n switch (chatId.kind) {\n case \"group_chat\":\n return this.userClient.leaveGroup(chatId.groupId);\n case \"channel\":\n return this.communityClient(chatId.communityId).leaveChannel(chatId);\n }\n }\n async joinGroup(chatId, credentialArgs) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n switch (chatId.kind) {\n case \"group_chat\": {\n const localUserIndex = await this.getGroupClient(chatId.groupId).localUserIndex();\n const localUserIndexClient = this.getLocalUserIndexClient(localUserIndex);\n const groupInviteCode = this.getProvidedGroupInviteCode(chatId);\n return localUserIndexClient\n .joinGroup(chatId.groupId, groupInviteCode, credentialArgs)\n .then((resp) => {\n if (resp.kind === \"success\") {\n return {\n kind: \"success\",\n group: this.hydrateChatSummary(resp.group),\n };\n }\n return resp;\n });\n }\n case \"channel\": {\n const localUserIndex = await this.communityClient(chatId.communityId).localUserIndex();\n const localUserIndexClient = this.getLocalUserIndexClient(localUserIndex);\n const communityInviteCode = this.getProvidedCommunityInviteCode(chatId.communityId);\n const referredBy = await this.getCommunityReferral(chatId.communityId);\n return localUserIndexClient\n .joinChannel(chatId, communityInviteCode, credentialArgs, referredBy)\n .then((resp) => {\n if (resp.kind === \"success\" || resp.kind === \"success_joined_community\") {\n deleteCommunityReferral(chatId.communityId);\n }\n if (resp.kind === \"success\") {\n return {\n kind: \"success\",\n group: this.hydrateChatSummary(resp.group),\n };\n }\n if (resp.kind === \"success_joined_community\") {\n return {\n kind: \"success_joined_community\",\n community: this.hydrateCommunity(resp.community),\n };\n }\n return resp;\n });\n }\n }\n }\n async joinCommunity(id, credentialArgs) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n const inviteCode = this.getProvidedCommunityInviteCode(id.communityId);\n const localUserIndex = await this.communityClient(id.communityId).localUserIndex();\n const referredBy = await this.getCommunityReferral(id.communityId);\n return this.getLocalUserIndexClient(localUserIndex)\n .joinCommunity(id.communityId, inviteCode, credentialArgs, referredBy)\n .then((resp) => {\n if (resp.kind === \"success\") {\n deleteCommunityReferral(id.communityId);\n }\n return resp;\n });\n }\n markMessagesRead(request) {\n return this.userClient.markMessagesRead(request);\n }\n setUserAvatar(data) {\n return this.userClient.setAvatar(data);\n }\n addReaction(chatId, messageId, reaction, username, displayName, threadRootMessageIndex, newAchievement) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n switch (chatId.kind) {\n case \"group_chat\":\n return this.getGroupClient(chatId.groupId).addReaction(messageId, reaction, username, displayName, threadRootMessageIndex, newAchievement);\n case \"direct_chat\":\n return this.userClient.addReaction(chatId.userId, messageId, reaction, threadRootMessageIndex);\n case \"channel\":\n return this.communityClient(chatId.communityId).addReaction(chatId, username, displayName, messageId, reaction, threadRootMessageIndex, newAchievement);\n }\n }\n removeReaction(chatId, messageId, reaction, threadRootMessageIndex) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n switch (chatId.kind) {\n case \"group_chat\":\n return this.getGroupClient(chatId.groupId).removeReaction(messageId, reaction, threadRootMessageIndex);\n case \"direct_chat\":\n return this.userClient.removeReaction(chatId.userId, messageId, reaction, threadRootMessageIndex);\n case \"channel\":\n return this.communityClient(chatId.communityId).removeReaction(chatId, messageId, reaction, threadRootMessageIndex);\n }\n }\n deleteMessage(chatId, messageId, threadRootMessageIndex, asPlatformModerator, newAchievement) {\n if (offline())\n return Promise.resolve(\"offline\");\n switch (chatId.kind) {\n case \"group_chat\":\n return this.deleteGroupMessage(chatId.groupId, messageId, threadRootMessageIndex, asPlatformModerator, newAchievement);\n case \"direct_chat\":\n return this.deleteDirectMessage(chatId.userId, messageId, threadRootMessageIndex);\n case \"channel\":\n return this.deleteChannelMessage(chatId, messageId, threadRootMessageIndex, asPlatformModerator, newAchievement);\n }\n }\n deleteChannelMessage(chatId, messageId, threadRootMessageIndex, asPlatformModerator, newAchievement) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this.communityClient(chatId.communityId).deleteMessages(chatId, [messageId], threadRootMessageIndex, asPlatformModerator, newAchievement);\n }\n deleteGroupMessage(chatId, messageId, threadRootMessageIndex, asPlatformModerator, newAchievement) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this.getGroupClient(chatId).deleteMessage(messageId, threadRootMessageIndex, asPlatformModerator, newAchievement);\n }\n deleteDirectMessage(otherUserId, messageId, threadRootMessageIndex) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this.userClient.deleteMessage(otherUserId, messageId, threadRootMessageIndex);\n }\n undeleteMessage(chatId, messageId, threadRootMessageIndex) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n switch (chatId.kind) {\n case \"group_chat\":\n return this.getGroupClient(chatId.groupId).undeleteMessage(messageId, threadRootMessageIndex);\n case \"direct_chat\":\n return this.userClient.undeleteMessage(chatId.userId, messageId, threadRootMessageIndex);\n case \"channel\":\n return this.communityClient(chatId.communityId).undeleteMessage(chatId, messageId, threadRootMessageIndex);\n }\n }\n lastOnline(userIds) {\n return this._onlineClient.lastOnline(userIds);\n }\n markAsOnline() {\n return this._onlineClient.markAsOnline();\n }\n minutesOnline(year, month) {\n return this._onlineClient.minutesOnline(year, month);\n }\n subscriptionExists(p256dh_key) {\n return this._notificationClient.subscriptionExists(p256dh_key);\n }\n pushSubscription(subscription) {\n return this._notificationClient.pushSubscription(subscription);\n }\n removeSubscription(subscription) {\n return this._notificationClient.removeSubscription(subscription);\n }\n toggleMuteNotifications(id, muted) {\n if (offline())\n return Promise.resolve(\"offline\");\n switch (id.kind) {\n case \"group_chat\":\n return this.getGroupClient(id.groupId).toggleMuteNotifications(muted);\n case \"direct_chat\":\n return this.userClient.toggleMuteNotifications(id.userId, muted);\n case \"channel\":\n return this.communityClient(id.communityId).toggleMuteChannelNotifications(id, muted);\n case \"community\":\n return this.communityClient(id.communityId).toggleMuteChannelNotifications(undefined, muted);\n }\n }\n getGroupDetails(chatId, chatLastUpdated) {\n switch (chatId.kind) {\n case \"group_chat\":\n return this.getGroupClient(chatId.groupId).getGroupDetails(chatLastUpdated);\n case \"channel\":\n return this.communityClient(chatId.communityId).getChannelDetails(chatId, chatLastUpdated);\n }\n }\n getPublicGroupSummary(chatId) {\n return this.getGroupClient(chatId.groupId)\n .getPublicSummary()\n .then((resp) => {\n if (resp.kind === \"success\") {\n return {\n kind: \"success\",\n group: this.rehydrateDataContent(resp.group, \"avatar\"),\n };\n }\n return resp;\n })\n .catch((err) => {\n if (err instanceof DestinationInvalidError) {\n return this._groupIndexClient.lookupChannelByGroupId(chatId).then((resp) => {\n if (resp === undefined)\n return CommonResponses.failure();\n return {\n kind: \"group_moved\",\n location: resp,\n };\n });\n }\n return CommonResponses.failure();\n });\n }\n getRecommendedGroups(exclusions) {\n return this._groupIndexClient\n .recommendedGroups(exclusions)\n .then((groups) => groups.map((g) => this.rehydrateDataContent(g, \"avatar\")));\n }\n dismissRecommendation(chatId) {\n return this.userClient.dismissRecommendation(chatId.groupId);\n }\n getBio(userId) {\n if (offline())\n return Promise.resolve(\"\");\n const userClient = userId\n ? new UserClient(userId, this.identity, this._agent, this.config, this.db)\n : this.userClient;\n return userClient.getBio();\n }\n getPublicProfile(userId) {\n if (userId) {\n return isUserIdDeleted(userId).then((deleted) => {\n if (deleted)\n return undefined;\n const userClient = new UserClient(userId, this.identity, this._agent, this.config, this.db);\n return userClient.getPublicProfile();\n });\n }\n else {\n return this.userClient.getPublicProfile();\n }\n }\n setBio(bio) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this.userClient.setBio(bio);\n }\n async registerUser(username, referralCode) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n const localUserIndex = await this._userIndexClient.userRegistrationCanister();\n return this.getLocalUserIndexClient(localUserIndex).registerUser(username, referralCode);\n }\n getUserStorageLimits() {\n return this._dataClient.storageStatus();\n }\n refreshAccountBalance(ledger, principal) {\n if (offline())\n return Promise.resolve(0n);\n return this.getLedgerClient(ledger).accountBalance(principal);\n }\n getAccountTransactions(ledgerIndex, principal, fromId) {\n const icpLedgerIndex = this._registryValue?.nervousSystemSummary.find((ns) => ns.isNns)\n ?.indexCanisterId;\n if (ledgerIndex === icpLedgerIndex) {\n return new IcpLedgerIndexClient(this.identity, this._agent, ledgerIndex).getAccountTransactions(principal, fromId);\n }\n return this.getLedgerIndexClient(ledgerIndex).getAccountTransactions(principal, fromId);\n }\n getGroupMessagesByMessageIndex(chatId, messageIndexes, latestKnownUpdate) {\n latestKnownUpdate = excludeLatestKnownUpdateIfBeforeFix(latestKnownUpdate);\n switch (chatId.kind) {\n case \"group_chat\":\n return this.rehydrateEventResponse(chatId, this.getGroupClient(chatId.groupId).getMessagesByMessageIndex(messageIndexes, latestKnownUpdate), undefined, latestKnownUpdate);\n case \"channel\":\n return this.rehydrateEventResponse(chatId, this.communityClient(chatId.communityId).getMessagesByMessageIndex(chatId, messageIndexes, latestKnownUpdate), undefined, latestKnownUpdate);\n }\n }\n pinMessage(chatId, messageIndex) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n switch (chatId.kind) {\n case \"group_chat\":\n return this.getGroupClient(chatId.groupId).pinMessage(messageIndex);\n case \"channel\":\n return this.communityClient(chatId.communityId).pinMessage(chatId, messageIndex);\n }\n }\n unpinMessage(chatId, messageIndex) {\n if (offline())\n return Promise.resolve(\"offline\");\n switch (chatId.kind) {\n case \"group_chat\":\n return this.getGroupClient(chatId.groupId).unpinMessage(messageIndex);\n case \"channel\":\n return this.communityClient(chatId.communityId).unpinMessage(chatId, messageIndex);\n }\n }\n registerPollVote(chatId, messageIdx, answerIdx, voteType, threadRootMessageIndex, newAchievement) {\n if (offline())\n return Promise.resolve(\"offline\");\n switch (chatId.kind) {\n case \"group_chat\":\n return this.getGroupClient(chatId.groupId).registerPollVote(messageIdx, answerIdx, voteType, threadRootMessageIndex, newAchievement);\n case \"channel\":\n return this.communityClient(chatId.communityId).registerPollVote(chatId, messageIdx, answerIdx, voteType, threadRootMessageIndex, newAchievement);\n }\n }\n withdrawCryptocurrency(domain, pin) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n return this.userClient.withdrawCryptocurrency(domain, pin);\n }\n getInviteCode(id) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n switch (id.kind) {\n case \"community\":\n return this.communityClient(id.communityId).getInviteCode();\n case \"group_chat\":\n return this.getGroupClient(id.groupId).getInviteCode();\n }\n }\n enableInviteCode(id) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n switch (id.kind) {\n case \"community\":\n return this.communityClient(id.communityId).enableInviteCode();\n case \"group_chat\":\n return this.getGroupClient(id.groupId).enableInviteCode();\n }\n }\n disableInviteCode(id) {\n if (offline())\n return Promise.resolve(\"offline\");\n switch (id.kind) {\n case \"community\":\n return this.communityClient(id.communityId).disableInviteCode();\n case \"group_chat\":\n return this.getGroupClient(id.groupId).disableInviteCode();\n }\n }\n resetInviteCode(id) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n switch (id.kind) {\n case \"community\":\n return this.communityClient(id.communityId).resetInviteCode();\n case \"group_chat\":\n return this.getGroupClient(id.groupId).resetInviteCode();\n }\n }\n pinChat(chatId, favourite) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this.userClient.pinChat(chatId, favourite);\n }\n unpinChat(chatId, favourite) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this.userClient.unpinChat(chatId, favourite);\n }\n archiveChat(chatId) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this.userClient.archiveChat(chatId);\n }\n unarchiveChat(chatId) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this.userClient.unarchiveChat(chatId);\n }\n registerProposalVote(chatId, messageIndex, adopt) {\n if (offline())\n return Promise.resolve(\"offline\");\n switch (chatId.kind) {\n case \"group_chat\":\n return this.getGroupClient(chatId.groupId).registerProposalVote(messageIndex, adopt);\n case \"channel\":\n return this.communityClient(chatId.communityId).registerProposalVote(chatId.channelId, messageIndex, adopt);\n }\n }\n getProposalVoteDetails(governanceCanisterId, proposalId, isNns) {\n if (isNns) {\n return new NnsGovernanceClient(this.identity, this._agent, governanceCanisterId).getProposalVoteDetails(proposalId);\n }\n else {\n return new SnsGovernanceClient(this.identity, this._agent, governanceCanisterId).getProposalVoteDetails(proposalId);\n }\n }\n listNervousSystemFunctions(snsGovernanceCanisterId) {\n return new SnsGovernanceClient(this.identity, this._agent, snsGovernanceCanisterId).listNervousSystemFunctions();\n }\n async threadPreviews(threadsByChat) {\n function latestMessageTimestamp(messages) {\n return messages[messages.length - 1]?.timestamp ?? BigInt(0);\n }\n return Promise.all(ChatMap.fromMap(threadsByChat)\n .entries()\n .map(([chatId, [threadSyncs, latestKnownUpdate]]) => {\n latestKnownUpdate = excludeLatestKnownUpdateIfBeforeFix(latestKnownUpdate);\n const latestClientThreadUpdate = threadSyncs.reduce((curr, next) => (next.lastUpdated > curr ? next.lastUpdated : curr), BigInt(0));\n switch (chatId.kind) {\n case \"group_chat\":\n return this.getGroupClient(chatId.groupId)\n .threadPreviews(threadSyncs.map((t) => t.threadRootMessageIndex), latestClientThreadUpdate)\n .then((response) => [response, latestKnownUpdate]);\n case \"channel\":\n return this.communityClient(chatId.communityId)\n .threadPreviews(chatId, threadSyncs.map((t) => t.threadRootMessageIndex), latestClientThreadUpdate)\n .then((response) => [response, latestKnownUpdate]);\n case \"direct_chat\":\n throw new Error(\"direct chat thread previews not supported\");\n }\n })).then((responses) => Promise.all(responses.map(([r, latestKnownUpdate]) => {\n return r.kind === \"thread_previews_success\"\n ? Promise.all(r.threads.map((t) => this.rehydrateThreadPreview(t, latestKnownUpdate)))\n : [];\n })).then((threads) => threads\n .flat()\n .sort((a, b) => Number(latestMessageTimestamp(b.latestReplies) -\n latestMessageTimestamp(a.latestReplies)))));\n }\n async rehydrateThreadPreview(thread, latestKnownUpdate) {\n const threadMissing = await this.resolveMissingIndexes(thread.chatId, thread.latestReplies, thread.rootMessage.event.messageIndex, latestKnownUpdate);\n const rootMissing = await this.resolveMissingIndexes(thread.chatId, [thread.rootMessage], undefined, latestKnownUpdate);\n const latestReplies = thread.latestReplies.map((r) => this.rehydrateEvent(r, thread.chatId, threadMissing, thread.rootMessage.event.messageIndex));\n const rootMessage = this.rehydrateEvent(thread.rootMessage, thread.chatId, rootMissing, undefined);\n return {\n ...thread,\n rootMessage,\n latestReplies,\n };\n }\n setCachedMessageFromNotification(chatId, threadRootMessageIndex, message) {\n return setCachedMessageIfNotExists(this.db, chatId, message, threadRootMessageIndex);\n }\n freezeGroup(chatId, reason) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this._groupIndexClient.freezeGroup(chatId.groupId, reason);\n }\n unfreezeGroup(chatId) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this._groupIndexClient.unfreezeGroup(chatId.groupId);\n }\n freezeCommunity(id, reason) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this._groupIndexClient.freezeCommunity(id, reason);\n }\n unfreezeCommunity(id) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this._groupIndexClient.unfreezeCommunity(id);\n }\n deleteFrozenGroup(chatId) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this._groupIndexClient.deleteFrozenGroup(chatId.groupId);\n }\n addHotGroupExclusion(chatId) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this._groupIndexClient.addHotGroupExclusion(chatId.groupId);\n }\n removeHotGroupExclusion(chatId) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this._groupIndexClient.removeHotGroupExclusion(chatId.groupId);\n }\n suspendUser(userId, reason) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this._userIndexClient.suspendUser(userId, reason);\n }\n unsuspendUser(userId) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this._userIndexClient.unsuspendUser(userId);\n }\n loadFailedMessages() {\n return loadFailedMessages(this.db).then((messages) => messages.toMap());\n }\n deleteFailedMessage(chatId, messageId, threadRootMessageIndex) {\n return removeFailedMessage(this.db, chatId, messageId, threadRootMessageIndex);\n }\n claimPrize(chatId, messageId) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n switch (chatId.kind) {\n case \"group_chat\":\n return this.getGroupClient(chatId.groupId).claimPrize(messageId);\n case \"channel\":\n return this.communityClient(chatId.communityId).claimPrize(chatId.channelId, messageId);\n }\n }\n payForDiamondMembership(userId, ledger, duration, recurring, expectedPriceE8s) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n return this._userIndexClient.payForDiamondMembership(userId, ledger, duration, recurring, expectedPriceE8s);\n }\n setCommunityModerationFlags(communityId, flags) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this._groupIndexClient.setCommunityModerationFlags(communityId, flags);\n }\n setGroupUpgradeConcurrency(value) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this._groupIndexClient.setGroupUpgradeConcurrency(value);\n }\n setCommunityUpgradeConcurrency(value) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this._groupIndexClient.setCommunityUpgradeConcurrency(value);\n }\n setUserUpgradeConcurrency(value) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this._userIndexClient.setUserUpgradeConcurrency(value);\n }\n markLocalGroupIndexFull(canisterId, full) {\n return this._groupIndexClient.markLocalGroupIndexFull(canisterId, full);\n }\n stakeNeuronForSubmittingProposals(governanceCanisterId, stake) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n return this._proposalsBotClient.get().stakeNeuronForSubmittingProposals(governanceCanisterId, stake);\n }\n topUpNeuronForSubmittingProposals(governanceCanisterId, amount) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n return this._proposalsBotClient.get().topUpNeuron(governanceCanisterId, amount);\n }\n updateMarketMakerConfig(config) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this._marketMakerClient.get().updateConfig(config);\n }\n setMessageReminder(chatId, eventIndex, remindAt, notes, threadRootMessageIndex) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this.userClient.setMessageReminder(chatId, eventIndex, remindAt, notes, threadRootMessageIndex);\n }\n cancelMessageReminder(reminderId) {\n if (offline())\n return Promise.resolve(false);\n return this.userClient.cancelMessageReminder(reminderId);\n }\n declineInvitation(chatId) {\n if (offline())\n return Promise.resolve(\"offline\");\n switch (chatId.kind) {\n case \"group_chat\":\n return this.getGroupClient(chatId.groupId).declineInvitation();\n case \"channel\":\n return this.communityClient(chatId.communityId).declineInvitation(chatId);\n }\n }\n convertGroupToCommunity(chatId, historyVisible, rules) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n return this.getGroupClient(chatId.groupId).convertToCommunity(historyVisible, rules);\n }\n getRegistry() {\n return new Stream(async (resolve, reject) => {\n const current = await getCachedRegistry();\n const isOffline = offline();\n if (current !== undefined) {\n this._registryValue = current;\n resolve([current, false], isOffline);\n }\n if (!isOffline) {\n try {\n const updates = await this._registryClient.updates(current?.lastUpdated);\n if (updates.kind === \"success\") {\n const updated = {\n lastUpdated: updates.lastUpdated,\n tokenDetails: distinctBy([...updates.tokenDetails, ...(current?.tokenDetails ?? [])], (t) => t.ledger),\n nervousSystemSummary: distinctBy([\n ...updates.nervousSystemSummary,\n ...(current?.nervousSystemSummary ?? []),\n ], (ns) => ns.governanceCanisterId),\n swapProviders: updates.swapProviders ?? current?.swapProviders ?? [],\n messageFilters: [\n ...(current?.messageFilters ?? []),\n ...updates.messageFiltersAdded,\n ].filter((f) => !updates.messageFiltersRemoved.includes(f.id)),\n currentAirdropChannel: updates.currentAirdropChannel,\n };\n setCachedRegistry(updated);\n this._registryValue = updated;\n this._dexesAgent.get().updateTokenDetails(updated.tokenDetails);\n resolve([updated, true], true);\n }\n else if (updates.kind === \"success_no_updates\" && current !== undefined) {\n resolve([current, false], true);\n }\n else {\n // this is a fallback for is we had nothing in the cache and nothing from the api\n reject(\"Registry is empty... this should never happen!\");\n }\n }\n catch (err) {\n console.warn(\"Getting registry updates failed: \", err);\n reject(err);\n }\n }\n });\n }\n setCommunityIndexes(communityIndexes) {\n if (offline())\n return Promise.resolve(false);\n return this.userClient.setCommunityIndexes(communityIndexes);\n }\n createUserGroup(communityId, name, userIds) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n return this.communityClient(communityId).createUserGroup(name, userIds);\n }\n updateUserGroup(communityId, userGroupId, name, usersToAdd, usersToRemove) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n return this.communityClient(communityId).updateUserGroup(userGroupId, name, usersToAdd, usersToRemove);\n }\n setMemberDisplayName(communityId, display_name, newAchievement) {\n if (offline())\n return Promise.resolve(\"offline\");\n return this.communityClient(communityId).setMemberDisplayName(display_name, newAchievement);\n }\n deleteUserGroups(communityId, userGroupIds) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n return this.communityClient(communityId).deleteUserGroups(userGroupIds);\n }\n getCachePrimerTimestamps() {\n return getCachePrimerTimestamps(this.db);\n }\n followThread(chatId, threadRootMessageIndex, follow, newAchievement) {\n if (offline())\n return Promise.resolve(\"offline\");\n if (chatId.kind === \"channel\") {\n return this.communityClient(chatId.communityId).followThread(chatId.channelId, threadRootMessageIndex, follow, newAchievement);\n }\n else if (chatId.kind === \"group_chat\") {\n return this.getGroupClient(chatId.groupId).followThread(threadRootMessageIndex, follow, newAchievement);\n }\n else {\n throw new Error(\"followThread not implemented for direct chats\");\n }\n }\n submitProposal(currentUserId, governanceCanisterId, proposal, ledger, token, proposalRejectionFee, transactionFee) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n return this._proposalsBotClient.get().submitProposal(currentUserId, governanceCanisterId, proposal, ledger, token, proposalRejectionFee, transactionFee);\n }\n reportMessage(chatId, threadRootMessageIndex, messageId, deleteMessage) {\n if (offline())\n return Promise.resolve(false);\n if (chatId.kind === \"channel\") {\n return this.communityClient(chatId.communityId).reportMessage(chatId.channelId, threadRootMessageIndex, messageId, deleteMessage);\n }\n else if (chatId.kind === \"group_chat\") {\n return this.getGroupClient(chatId.groupId).reportMessage(threadRootMessageIndex, messageId, deleteMessage);\n }\n else {\n return this.userClient.reportMessage(chatId, threadRootMessageIndex, messageId, deleteMessage);\n }\n }\n canSwap(tokenLedgers) {\n return this._dexesAgent.get().canSwap(tokenLedgers, this.swapProviders());\n }\n getTokenSwaps(inputTokenLedger, outputTokenLedgers) {\n return this._dexesAgent.get()\n .getSwapPools(inputTokenLedger, new Set(outputTokenLedgers), this.swapProviders())\n .then((pools) => {\n return pools.reduce(swapReducer, {});\n });\n function swapReducer(result, pool) {\n const outputTokenLedger = inputTokenLedger === pool.token0 ? pool.token1 : pool.token0;\n return {\n ...result,\n [outputTokenLedger]: [...(result[outputTokenLedger] || []), pool.dex],\n };\n }\n }\n getTokenSwapQuotes(inputTokenLedger, outputTokenLedger, amountIn) {\n return this._dexesAgent.get()\n .quoteSwap(inputTokenLedger, outputTokenLedger, amountIn, this.swapProviders())\n .then((quotes) => {\n // Sort the quotes by amount descending so the first quote is the best\n quotes.sort(compare);\n return quotes;\n });\n function compare([_dexA, amountA], [_dexB, amountB]) {\n if (amountA > amountB) {\n return -1;\n }\n if (amountA < amountB) {\n return 1;\n }\n return 0;\n }\n }\n swapTokens(swapId, inputTokenDetails, outputTokenDetails, amountIn, minAmountOut, dex, pin) {\n return this._dexesAgent.get()\n .getSwapPools(inputTokenDetails.ledger, new Set([outputTokenDetails.ledger]), this.swapProviders())\n .then((pools) => {\n const pool = pools.find((p) => p.dex === dex);\n if (pool === undefined) {\n return Promise.reject(\"Cannot find a matching pool\");\n }\n const exchangeArgs = {\n dex,\n swapCanisterId: pool.canisterId,\n zeroForOne: pool.token0 === inputTokenDetails.ledger,\n };\n return this.userClient.swapTokens(swapId, inputTokenDetails, outputTokenDetails, amountIn, minAmountOut, exchangeArgs, pin);\n });\n }\n tokenSwapStatus(swapId) {\n return this.userClient.tokenSwapStatus(swapId);\n }\n swapProviders() {\n return this._registryValue?.swapProviders ?? [];\n }\n approveTransfer(spender, ledger, amount, expiresIn, pin) {\n return this.userClient.approveTransfer(spender, ledger, amount, expiresIn, pin);\n }\n deleteDirectChat(userId, blockUser) {\n return this.userClient.deleteDirectChat(userId, blockUser);\n }\n diamondMembershipFees() {\n return this._userIndexClient.diamondMembershipFees();\n }\n setDiamondMembershipFees(fees) {\n return this._userIndexClient.setDiamondMembershipFees(fees);\n }\n addRemoveSwapProvider(swapProvider, add) {\n return this._registryClient.addRemoveSwapProvider(swapProvider, add);\n }\n addMessageFilter(regex) {\n return this._registryClient.addMessageFilter(regex);\n }\n removeMessageFilter(id) {\n return this._registryClient.removeMessageFilter(id);\n }\n setTokenEnabled(ledger, enabled) {\n return this._registryClient.setTokenEnabled(ledger, enabled);\n }\n async exchangeRates() {\n const supportedTokens = this._registryValue?.tokenDetails;\n if (supportedTokens === undefined || !isMainnet(this.config.icUrl)) {\n return Promise.resolve({});\n }\n const exchangeRatesFromAllProviders = await Promise.allSettled(this._exchangeRateClients.map((c) => c.exchangeRates(supportedTokens)));\n const grouped = {};\n for (const response of exchangeRatesFromAllProviders) {\n if (response.status === \"fulfilled\") {\n for (const [token, exchangeRates] of Object.entries(response.value)) {\n if (grouped[token] === undefined) {\n grouped[token] = [];\n }\n grouped[token].push(exchangeRates);\n }\n }\n }\n return toRecord2(Object.entries(grouped), ([token, _]) => token, ([_, group]) => ({\n toUSD: mean(group.map((e) => e.toUSD)),\n }));\n }\n reportedMessages(userId) {\n return this._userIndexClient.reportedMessages(userId);\n }\n acceptP2PSwap(chatId, threadRootMessageIndex, messageId, pin, newAchievement) {\n if (chatId.kind === \"channel\") {\n return this.communityClient(chatId.communityId).acceptP2PSwap(chatId.channelId, threadRootMessageIndex, messageId, pin, newAchievement);\n }\n else if (chatId.kind === \"group_chat\") {\n return this.getGroupClient(chatId.groupId).acceptP2PSwap(threadRootMessageIndex, messageId, pin, newAchievement);\n }\n else {\n return this.userClient.acceptP2PSwap(chatId.userId, threadRootMessageIndex, messageId, pin);\n }\n }\n cancelP2PSwap(chatId, threadRootMessageIndex, messageId) {\n if (chatId.kind === \"channel\") {\n return this.communityClient(chatId.communityId).cancelP2PSwap(chatId.channelId, threadRootMessageIndex, messageId);\n }\n else if (chatId.kind === \"group_chat\") {\n return this.getGroupClient(chatId.groupId).cancelP2PSwap(threadRootMessageIndex, messageId);\n }\n else {\n return this.userClient.cancelP2PSwap(chatId.userId, messageId);\n }\n }\n videoCallParticipants(chatId, messageId, updatesSince) {\n switch (chatId.kind) {\n case \"channel\":\n return this.communityClient(chatId.communityId).videoCallParticipants(chatId.channelId, messageId, updatesSince);\n case \"group_chat\":\n return this.getGroupClient(chatId.groupId).videoCallParticipants(messageId, updatesSince);\n }\n }\n joinVideoCall(chatId, messageId, newAchievement) {\n if (chatId.kind === \"channel\") {\n return this.communityClient(chatId.communityId).joinVideoCall(chatId.channelId, messageId, newAchievement);\n }\n else if (chatId.kind === \"group_chat\") {\n return this.getGroupClient(chatId.groupId).joinVideoCall(messageId, newAchievement);\n }\n else {\n return this.userClient.joinVideoCall(chatId.userId, messageId);\n }\n }\n setVideoCallPresence(chatId, messageId, presence, newAchievement) {\n switch (chatId.kind) {\n case \"channel\":\n return this.communityClient(chatId.communityId).setVideoCallPresence(chatId.channelId, messageId, presence, newAchievement);\n case \"group_chat\":\n return this.getGroupClient(chatId.groupId).setVideoCallPresence(messageId, presence, newAchievement);\n }\n }\n async getAccessToken(accessTokenType, localUserIndex) {\n return this.getLocalUserIndexClient(localUserIndex).getAccessToken(accessTokenType);\n }\n async getLocalUserIndexForUser(userId) {\n const localUserIndex = await getLocalUserIndexForUser(userId);\n if (localUserIndex !== undefined) {\n return localUserIndex;\n }\n return new UserClient(userId, this.identity, this._agent, this.config, this.db)\n .localUserIndex()\n .then((localUserIndex) => {\n return cacheLocalUserIndexForUser(userId, localUserIndex);\n });\n }\n generateBtcAddress() {\n return this.userClient.generateBtcAddress();\n }\n // Query the Bitcoin canister to check for any new UTXOs for this user, if there are any, then also query the ckBTC\n // minter to check that it has processed them, if it has not, call `update_btc_balance` on the user canister which\n // will then call into `update_balance` on the ckBTC minter to pull in the new UTXOs.\n async updateBtcBalance(userId, bitcoinAddress) {\n const allUtxos = await this._bitcoinClient.get().getUtxos(bitcoinAddress);\n if (allUtxos.length > 0) {\n const knownUtxos = await this._ckbtcMinterClient.get().getKnownUtxos(userId);\n const knownUtxosSet = new Set(knownUtxos.map((utxo) => bytesToHexString(utxo.outpoint.txid)));\n if (allUtxos.some((utxo) => !knownUtxosSet.has(bytesToHexString(utxo.outpoint.txid)))) {\n return await this.userClient.updateBtcBalance();\n }\n }\n return false;\n }\n withdrawBtc(address, amount, pin) {\n return this.userClient.withdrawBtc(address, amount, pin);\n }\n getCkbtcMinterDepositInfo() {\n return this._ckbtcMinterClient.get().getDepositInfo();\n }\n getCkbtcMinterWithdrawalInfo(amount) {\n return this._ckbtcMinterClient.get().getWithdrawalInfo(amount);\n }\n generateMagicLink(email, sessionKey) {\n return this._signInWithEmailClient.get().generateMagicLink(email, sessionKey);\n }\n getSignInWithEmailDelegation(email, sessionKey, expiration) {\n return this._signInWithEmailClient.get().getDelegation(email, sessionKey, expiration);\n }\n siwePrepareLogin(address) {\n return this._signInWithEthereumClient.get().prepareLogin(address);\n }\n siwsPrepareLogin(address) {\n return this._signInWithSolanaClient.get().prepareLogin(address);\n }\n loginWithWallet(token, address, signature, sessionKey) {\n switch (token) {\n case \"eth\":\n return this._signInWithEthereumClient.get().login(signature, address, sessionKey);\n case \"sol\":\n return this._signInWithSolanaClient.get().login(signature, address, sessionKey);\n }\n }\n getDelegationWithWallet(token, address, sessionKey, expiration) {\n switch (token) {\n case \"eth\":\n return this._signInWithEthereumClient.get().getDelegation(address, sessionKey, expiration);\n case \"sol\":\n return this._signInWithSolanaClient.get().getDelegation(address, sessionKey, expiration);\n }\n }\n setPinNumber(verification, newPin) {\n return this.userClient.setPinNumber(verification, newPin);\n }\n claimDailyChit() {\n return this.userClient.claimDailyChit();\n }\n chitLeaderboard() {\n return this._userIndexClient.chitLeaderboard();\n }\n chitEvents(req) {\n return this.userClient.chitEvents(req);\n }\n async markAchievementsSeen() {\n const cachedState = await getCachedChats(this.db, this.principal);\n if (cachedState !== undefined) {\n return this.userClient.markAchievementsSeen(cachedState.latestUserCanisterUpdates);\n }\n }\n submitProofOfUniquePersonhood(iiPrincipal, credential) {\n return this._userIndexClient.submitProofOfUniquePersonhood(iiPrincipal, credential);\n }\n configureWallet(config) {\n return this.userClient.configureWallet(config);\n }\n cancelInvites(id, userIds) {\n if (offline())\n return Promise.resolve(false);\n switch (id.kind) {\n case \"group_chat\":\n return this.getGroupClient(id.groupId).cancelInvites(userIds);\n case \"channel\":\n return this.communityClient(id.communityId).cancelInvites(id.channelId, userIds);\n case \"community\":\n return this.communityClient(id.communityId).cancelInvites(undefined, userIds);\n }\n }\n async clearCachedData() {\n await Promise.all([\n clearCache(this.principal.toString()),\n clearUserCache(),\n clearReferralCache(),\n ]);\n }\n async getExternalAchievements() {\n const cached = await getCachedExternalAchievements();\n const updates = await this._userIndexClient.getExternalAchievements(cached?.lastUpdated ?? 0n);\n if (updates.kind === \"success\") {\n const merged = this.mergeExternalAchievements(cached, updates);\n setCachedExternalAchievements(merged.lastUpdated, merged.achievements);\n return merged.achievements;\n }\n return cached?.achievements ?? [];\n }\n mergeExternalAchievements(cached, updates) {\n if (cached === undefined) {\n return {\n lastUpdated: updates.lastUpdated,\n achievements: updates.addedOrUpdated,\n };\n }\n const { achievements } = cached;\n const map = toRecord(achievements, (a) => a.id);\n updates.addedOrUpdated.forEach((a) => {\n map[a.id] = a;\n });\n return {\n lastUpdated: updates.lastUpdated,\n achievements: Object.values(map),\n };\n }\n markActivityFeedRead(readUpTo) {\n return this.userClient.markActivityFeedRead(readUpTo);\n }\n messageActivityFeed() {\n return new Stream(async (resolve) => {\n const cachedEvents = await getActivityFeedEvents();\n const since = cachedEvents[0]?.timestamp ?? 0n;\n const server = await this.userClient.messageActivityFeed(since);\n const combined = [...cachedEvents, ...server.events];\n // first sort ascending\n combined.sort((a, b) => Number(a.timestamp) - Number(b.timestamp));\n // dedupe by overwriting earlier events with the same context, activity type and event index\n const deduped = combined.reduce((map, ev) => {\n map.set(`${messageContextToString(ev.messageContext)}_${ev.activity}_${ev.eventIndex}`, ev);\n return map;\n }, new Map());\n // then sort descending\n const sorted = [...deduped.values()].sort((a, b) => Number(b.timestamp) - Number(a.timestamp));\n setActivityFeedEvents(sorted.slice(0, MAX_ACTIVITY_EVENTS));\n this.hydrateActivityFeedEvents(sorted, (hydrated, final) => resolve({ total: server.total, events: hydrated }, final));\n });\n }\n /**\n * Hydration is a two phase process. First we load all the messages that we have in the cache\n * and resolve. Secondly we then optionally load any missing messages from the backend and\n * resolve again.\n */\n async hydrateActivityFeedEvents(activityEvents, callback) {\n const eventIndexesByMessageContext = activityEvents.reduce((map, event) => {\n const eventIndexes = map.get(event.messageContext) ?? [];\n eventIndexes.push(event.eventIndex);\n map.set(event.messageContext, eventIndexes);\n return map;\n }, new AsyncMessageContextMap());\n const [withCachedMessages, missing] = await this.getMessagesByMessageContext(eventIndexesByMessageContext, activityEvents, \"cached\");\n const anyMissing = [...missing.values()].some((s) => s.size > 0);\n callback(withCachedMessages, !anyMissing);\n if (anyMissing) {\n this.getMessagesByMessageContext(new AsyncMessageContextMap(missing.map((_, v) => [...v]).toMap()), withCachedMessages, \"missing\").then(([withServerMessages]) => callback(withServerMessages, true));\n }\n }\n async getMessagesByMessageContext(eventIndexesByMessageContext, activityEvents, mode) {\n const allMissing = new MessageContextMap();\n const messagesByMessageContext = await eventIndexesByMessageContext.asyncMap((ctx, idxs) => {\n const chatId = ctx.chatId;\n const chatKind = chatId.kind;\n function addMissing(context, missing) {\n if (missing.size > 0) {\n const current = allMissing.get(context) ?? new Set();\n missing.forEach((n) => current.add(n));\n allMissing.set(context, current);\n }\n }\n if (chatKind === \"direct_chat\") {\n switch (mode) {\n case \"cached\":\n return this.userClient\n .getCachedEventsByIndex(idxs, chatId, ctx.threadRootMessageIndex)\n .then(([resp, missing]) => {\n addMissing(ctx, missing);\n return this.messagesFromEventsResponse(ctx, resp);\n });\n case \"missing\":\n return this.userClient\n .chatEventsByIndex(\n // getMissing(ctx),\n idxs, chatId, ctx.threadRootMessageIndex, undefined)\n .then((resp) => this.messagesFromEventsResponse(ctx, resp));\n }\n }\n else if (chatKind === \"group_chat\") {\n const client = this.getGroupClient(chatId.groupId);\n switch (mode) {\n case \"cached\":\n return client\n .getCachedEventsByIndex(idxs, ctx.threadRootMessageIndex)\n .then(([resp, missing]) => {\n addMissing(ctx, missing);\n return this.messagesFromEventsResponse(ctx, resp);\n });\n case \"missing\":\n return client\n .chatEventsByIndex(\n // getMissing(ctx),\n idxs, ctx.threadRootMessageIndex, undefined)\n .then((resp) => this.messagesFromEventsResponse(ctx, resp));\n }\n }\n else if (chatKind === \"channel\") {\n const client = this.communityClient(chatId.communityId);\n switch (mode) {\n case \"cached\":\n return client\n .getCachedEventsByIndex(chatId, idxs, ctx.threadRootMessageIndex)\n .then(([resp, missing]) => {\n addMissing(ctx, missing);\n return this.messagesFromEventsResponse(ctx, resp);\n });\n case \"missing\":\n return client\n .eventsByIndex(chatId, idxs, ctx.threadRootMessageIndex, undefined)\n .then((resp) => this.messagesFromEventsResponse(ctx, resp));\n }\n }\n else {\n throw new UnsupportedValueError(\"unknown chatid kind supplied\", chatId);\n }\n });\n const lookup = [...messagesByMessageContext.values()].reduce((lookup, events) => {\n events.forEach((ev) => lookup.set(ev.event.messageId, ev.event));\n return lookup;\n }, new MessageMap());\n return [\n activityEvents.map((ev) => ({\n ...ev,\n message: ev.message ?? lookup.get(ev.messageId),\n })),\n allMissing,\n ];\n }\n deleteUser(userId, delegation) {\n return this._userIndexClient.deleteUser(userId, delegation);\n }\n getChannelSummary(channelId) {\n return this.communityClient(channelId.communityId)\n .channelSummary(channelId)\n .then((resp) => {\n if (resp.kind === \"channel\") {\n return this.hydrateChatSummary(resp);\n }\n return resp;\n });\n }\n exploreBots(searchTerm, pageIndex, pageSize, location) {\n if (offline())\n return Promise.resolve(CommonResponses.offline());\n return this._userIndexClient.exploreBots(searchTerm, pageIndex, pageSize, location);\n }\n registerBot(principal, bot) {\n if (offline())\n return Promise.resolve(false);\n return this._userIndexClient.registerBot(principal, bot);\n }\n removeBot(botId) {\n if (offline())\n return Promise.resolve(false);\n return this._userIndexClient.removeBot(botId);\n }\n updateRegisteredBot(id, principal, ownerId, avatarUrl, endpoint, definition) {\n if (offline())\n return Promise.resolve(false);\n return this._userIndexClient.updateRegisteredBot(id, principal, ownerId, avatarUrl, endpoint, definition);\n }\n #localUserIndexForBotContext(id) {\n switch (id.kind) {\n case \"community\":\n return this.communityClient(id.communityId).localUserIndex();\n case \"group_chat\":\n return this.getGroupClient(id.groupId).localUserIndex();\n case \"direct_chat\":\n return this.getLocalUserIndexForUser(this.userClient.userId);\n }\n }\n async installBot(id, botId, grantedPermissions) {\n const localUserIndex = await this.#localUserIndexForBotContext(id);\n return this.getLocalUserIndexClient(localUserIndex).installBot(id, botId, grantedPermissions);\n }\n updateInstalledBot(id, botId, grantedPermissions) {\n switch (id.kind) {\n case \"community\":\n return this.communityClient(id.communityId).updateInstalledBot(botId, grantedPermissions);\n case \"group_chat\":\n return this.getGroupClient(id.groupId).updateInstalledBot(botId, grantedPermissions);\n case \"direct_chat\":\n return this.userClient.updateInstalledBot(botId, grantedPermissions);\n }\n }\n async uninstallBot(id, botId) {\n const localUserIndex = await this.#localUserIndexForBotContext(id);\n return this.getLocalUserIndexClient(localUserIndex).uninstallBot(id, botId);\n }\n getBots(initialLoad) {\n return new Stream(async (resolve, reject) => {\n const cachedBots = await getCachedBots(this.db, this.principal);\n const isOffline = offline();\n if (cachedBots && initialLoad) {\n resolve(cachedBots, isOffline);\n }\n if (!isOffline) {\n try {\n const updates = await this._userIndexClient.getBots(cachedBots);\n setCachedBots(this.db, this.principal, updates);\n resolve(updates, true);\n }\n catch (err) {\n reject(err);\n }\n }\n });\n }\n async withdrawFromIcpSwap(userId, swapId, inputToken, amount, fee) {\n const localUserIndex = await this.getLocalUserIndexForUser(userId);\n return this.getLocalUserIndexClient(localUserIndex).withdrawFromIcpSwap(userId, swapId, inputToken, amount, fee);\n }\n generateBotApiKey(id, botId, permissions) {\n switch (id.kind) {\n case \"channel\":\n return this.communityClient(id.communityId).generateBotApiKey(botId, permissions, id.channelId);\n case \"community\":\n return this.communityClient(id.communityId).generateBotApiKey(botId, permissions);\n case \"group_chat\":\n return this.getGroupClient(id.groupId).generateBotApiKey(botId, permissions);\n case \"direct_chat\":\n return this.userClient.generateBotApiKey(botId, permissions);\n }\n }\n getApiKey(id, botId) {\n switch (id.kind) {\n case \"channel\":\n return this.communityClient(id.communityId).getApiKey(botId, id.channelId);\n case \"community\":\n return this.communityClient(id.communityId).getApiKey(botId);\n case \"group_chat\":\n return this.getGroupClient(id.groupId).getApiKey(botId);\n case \"direct_chat\":\n return this.userClient.getApiKey(botId);\n }\n }\n}\n","/* eslint-disable @typescript-eslint/ban-types */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nfunction end(start, key) {\n return (result) => {\n const end = performance.now();\n const duration = end - start;\n console.log(`${key}: ${duration}ms`);\n return result;\n };\n}\nexport function measure(key, fn) {\n const start = performance.now();\n return fn().then((res) => {\n const end = performance.now();\n console.log(key, end - start);\n return res;\n });\n}\n// function inWorker() {\n// return self.WorkerGlobalScope;\n// }\nexport const profile = (service) => (_target, _propertyKey, descriptor) => {\n return descriptor;\n // FIXME - we can't access local storage in a worker\n // if (inWorker()) return descriptor;\n // if (!localStorage.getItem(\"openchat_profile\")) return descriptor;\n const originalMethod = descriptor.value;\n descriptor.value = function (...args) {\n const start = performance.now();\n const key = `${service}.${originalMethod.name}`;\n const result = originalMethod.apply(this, args);\n if (result instanceof Promise) {\n return result.then(end(start, key));\n }\n else {\n return end(start, key)(result);\n }\n };\n return descriptor;\n};\n","export const idlFactory = ({ IDL }) => {\n const PublicKey = IDL.Vec(IDL.Nat8);\n const TimestampNanoseconds = IDL.Nat64;\n const SignedDelegation = IDL.Record({\n 'signature': IDL.Vec(IDL.Nat8),\n 'delegation': IDL.Record({\n 'pubkey': PublicKey,\n 'expiration': TimestampNanoseconds,\n }),\n });\n const ApproveIdentityLinkArgs = IDL.Record({\n 'link_initiated_by': IDL.Principal,\n 'public_key': IDL.Vec(IDL.Nat8),\n 'delegation': SignedDelegation,\n });\n const ApproveIdentityLinkResponse = IDL.Variant({\n 'LinkRequestNotFound': IDL.Null,\n 'InvalidSignature': IDL.Null,\n 'PrincipalAlreadyLinkedToAnotherOcUser': IDL.Null,\n 'Success': IDL.Null,\n 'MalformedSignature': IDL.Text,\n 'DelegationTooOld': IDL.Null,\n 'CallerNotRecognised': IDL.Null,\n });\n const WebAuthnKey = IDL.Record({\n 'public_key': IDL.Vec(IDL.Nat8),\n 'origin': IDL.Text,\n 'cross_platform': IDL.Bool,\n 'aaguid': IDL.Vec(IDL.Nat8),\n 'credential_id': IDL.Vec(IDL.Nat8),\n });\n const TimestampMillis = IDL.Nat64;\n const AuthPrincipalsResponse = IDL.Variant({\n 'NotFound': IDL.Null,\n 'Success': IDL.Vec(IDL.Record({\n 'principal': IDL.Principal,\n 'webauthn_key': IDL.Opt(WebAuthnKey),\n 'is_current_identity': IDL.Bool,\n 'originating_canister': IDL.Principal,\n 'is_ii_principal': IDL.Bool,\n 'last_used': TimestampMillis,\n })),\n });\n const CheckAuthPrincipalResponse = IDL.Variant({\n 'NotFound': IDL.Null,\n 'Success': IDL.Null,\n });\n const UserId = IDL.Principal;\n const CheckAuthPrincipalV2Response = IDL.Variant({\n 'NotFound': IDL.Null,\n 'Success': IDL.Record({\n 'webauthn_key': IDL.Opt(WebAuthnKey),\n 'user_id': IDL.Opt(UserId),\n 'originating_canister': IDL.Principal,\n 'is_ii_principal': IDL.Bool,\n }),\n });\n const Nanoseconds = IDL.Nat64;\n const CreateIdentityArgs = IDL.Record({\n 'webauthn_key': IDL.Opt(WebAuthnKey),\n 'public_key': PublicKey,\n 'session_key': PublicKey,\n 'max_time_to_live': IDL.Opt(Nanoseconds),\n 'is_ii_principal': IDL.Opt(IDL.Bool),\n 'challenge_attempt': IDL.Opt(IDL.Record({ 'key': IDL.Nat32, 'chars': IDL.Text })),\n });\n const PrepareDelegationSuccess = IDL.Record({\n 'user_key': PublicKey,\n 'expiration': TimestampNanoseconds,\n });\n const CreateIdentityResponse = IDL.Variant({\n 'AlreadyRegistered': IDL.Null,\n 'OriginatingCanisterInvalid': IDL.Principal,\n 'Success': PrepareDelegationSuccess,\n 'ChallengeFailed': IDL.Null,\n 'ChallengeRequired': IDL.Null,\n 'PublicKeyInvalid': IDL.Text,\n });\n const GenerateChallengeResponse = IDL.Variant({\n 'AlreadyRegistered': IDL.Null,\n 'Throttled': IDL.Null,\n 'Success': IDL.Record({ 'key': IDL.Nat32, 'png_base64': IDL.Text }),\n });\n const GetDelegationArgs = IDL.Record({\n 'session_key': PublicKey,\n 'expiration': TimestampNanoseconds,\n });\n const GetDelegationResponse = IDL.Variant({\n 'NotFound': IDL.Null,\n 'Success': SignedDelegation,\n });\n const InitiateIdentityLinkArgs = IDL.Record({\n 'webauthn_key': IDL.Opt(WebAuthnKey),\n 'public_key': IDL.Vec(IDL.Nat8),\n 'link_to_principal': IDL.Principal,\n 'is_ii_principal': IDL.Opt(IDL.Bool),\n });\n const InitiateIdentityLinkResponse = IDL.Variant({\n 'AlreadyRegistered': IDL.Null,\n 'OriginatingCanisterInvalid': IDL.Principal,\n 'Success': IDL.Null,\n 'TargetUserNotFound': IDL.Null,\n 'PublicKeyInvalid': IDL.Text,\n 'AlreadyLinkedToPrincipal': IDL.Null,\n 'LinkedIdentitiesLimitReached': IDL.Nat32,\n });\n const LookupWebAuthnPubKeyArgs = IDL.Record({\n 'credential_id': IDL.Vec(IDL.Nat8),\n });\n const LookupWebAuthnPubKeyResponse = IDL.Variant({\n 'NotFound': IDL.Null,\n 'Success': IDL.Record({ 'pubkey': IDL.Vec(IDL.Nat8) }),\n });\n const PrepareDelegationArgs = IDL.Record({\n 'session_key': PublicKey,\n 'max_time_to_live': IDL.Opt(Nanoseconds),\n 'is_ii_principal': IDL.Opt(IDL.Bool),\n });\n const PrepareDelegationResponse = IDL.Variant({\n 'NotFound': IDL.Null,\n 'Success': PrepareDelegationSuccess,\n });\n const RemoveIdentityLinkArgs = IDL.Record({\n 'linked_principal': IDL.Principal,\n });\n const RemoveIdentityLinkResponse = IDL.Variant({\n 'CannotUnlinkActivePrincipal': IDL.Null,\n 'Success': IDL.Null,\n 'IdentityLinkNotFound': IDL.Null,\n 'UserNotFound': IDL.Null,\n });\n return IDL.Service({\n 'approve_identity_link': IDL.Func([ApproveIdentityLinkArgs], [ApproveIdentityLinkResponse], []),\n 'auth_principals': IDL.Func([IDL.Record({})], [AuthPrincipalsResponse], ['query']),\n 'check_auth_principal': IDL.Func([IDL.Record({})], [CheckAuthPrincipalResponse], ['query']),\n 'check_auth_principal_v2': IDL.Func([IDL.Record({})], [CheckAuthPrincipalV2Response], ['query']),\n 'create_identity': IDL.Func([CreateIdentityArgs], [CreateIdentityResponse], []),\n 'generate_challenge': IDL.Func([IDL.Record({})], [GenerateChallengeResponse], []),\n 'get_delegation': IDL.Func([GetDelegationArgs], [GetDelegationResponse], ['query']),\n 'initiate_identity_link': IDL.Func([InitiateIdentityLinkArgs], [InitiateIdentityLinkResponse], []),\n 'lookup_webauthn_pubkey': IDL.Func([LookupWebAuthnPubKeyArgs], [LookupWebAuthnPubKeyResponse], ['query']),\n 'prepare_delegation': IDL.Func([PrepareDelegationArgs], [PrepareDelegationResponse], []),\n 'remove_identity_link': IDL.Func([RemoveIdentityLinkArgs], [RemoveIdentityLinkResponse], []),\n });\n};\nexport const init = ({ IDL }) => { return []; };\n","import { idlFactory } from \"./candid/idl\";\nimport { CandidCanisterAgent } from \"../canisterAgent/candid\";\nimport { apiWebAuthnKey, approveIdentityLinkResponse, authPrincipalsResponse, checkAuthPrincipalResponse, createIdentityResponse, generateChallengeResponse, getDelegationResponse, initiateIdentityLinkResponse, prepareDelegationResponse, removeIdentityLinkResponse, } from \"./mappers\";\nimport { apiOptional } from \"../common/chatMappers\";\nimport { consolidateBytes, identity } from \"../../utils/mapping\";\nimport { Principal } from \"@dfinity/principal\";\nimport { signedDelegation } from \"../../utils/id\";\nexport class IdentityClient extends CandidCanisterAgent {\n constructor(identity, agent, identityCanister) {\n super(identity, agent, identityCanister, idlFactory, \"Identity\");\n }\n createIdentity(sessionKey, webAuthnKey, isIIPrincipal, challengeAttempt) {\n const args = {\n public_key: this.publicKey(),\n webauthn_key: apiOptional(apiWebAuthnKey, webAuthnKey),\n session_key: sessionKey,\n is_ii_principal: apiOptional(identity, isIIPrincipal),\n max_time_to_live: [],\n challenge_attempt: apiOptional(identity, challengeAttempt),\n };\n return this.handleResponse(this.service.create_identity(args), createIdentityResponse, args);\n }\n checkAuthPrincipal() {\n return this.handleQueryResponse(() => this.service.check_auth_principal_v2({}), checkAuthPrincipalResponse, {});\n }\n prepareDelegation(sessionKey, isIIPrincipal) {\n const args = {\n session_key: sessionKey,\n is_ii_principal: apiOptional(identity, isIIPrincipal),\n max_time_to_live: [],\n };\n return this.handleResponse(this.service.prepare_delegation(args), prepareDelegationResponse, args);\n }\n getDelegation(sessionKey, expiration) {\n const args = {\n session_key: sessionKey,\n expiration,\n };\n return this.handleQueryResponse(() => this.service.get_delegation(args), getDelegationResponse, args);\n }\n generateChallenge() {\n return this.handleResponse(this.service.generate_challenge({}), generateChallengeResponse);\n }\n initiateIdentityLink(linkToPrincipal, webAuthnKey, isIIPrincipal) {\n return this.handleResponse(this.service.initiate_identity_link({\n link_to_principal: Principal.fromText(linkToPrincipal),\n webauthn_key: apiOptional(apiWebAuthnKey, webAuthnKey),\n public_key: this.publicKey(),\n is_ii_principal: apiOptional(identity, isIIPrincipal),\n }), initiateIdentityLinkResponse);\n }\n approveIdentityLink(linkInitiatedBy) {\n return this.handleResponse(this.service.approve_identity_link({\n link_initiated_by: Principal.fromText(linkInitiatedBy),\n public_key: this.publicKey(),\n delegation: signedDelegation(this.identity.getDelegation()),\n }), approveIdentityLinkResponse);\n }\n removeIdentityLink(linked_principal) {\n return this.handleResponse(this.service.remove_identity_link({\n linked_principal: Principal.fromText(linked_principal),\n }), removeIdentityLinkResponse);\n }\n getAuthenticationPrincipals() {\n return this.handleQueryResponse(() => this.service.auth_principals({}), authPrincipalsResponse);\n }\n lookupWebAuthnPubKey(credentialId) {\n const args = {\n credential_id: credentialId,\n };\n return this.handleQueryResponse(() => this.service.lookup_webauthn_pubkey(args), (resp) => {\n if (\"Success\" in resp) {\n return consolidateBytes(resp.Success.pubkey);\n }\n else {\n return undefined;\n }\n }, args);\n }\n publicKey() {\n return new Uint8Array(this.identity.getPublicKey().toDer());\n }\n}\n","import { openDB } from \"idb\";\nimport { bytesToHexString } from \"./mapping\";\nconst CACHE_VERSION = 1;\nconst STORE_NAME = \"webauthn_keys\";\nlet db;\nexport function lazyOpenWebAuthnKeyCache() {\n if (db)\n return db;\n console.log(\"WebAuthnKey db undefined, opening db\");\n db = openWebAuthnKeyCache();\n return db;\n}\nfunction openWebAuthnKeyCache() {\n return openDB(`openchat_webauthn_keys`, CACHE_VERSION, {\n upgrade(db, _oldVersion, _newVersion, _transaction) {\n if (db.objectStoreNames.contains(STORE_NAME)) {\n db.deleteObjectStore(STORE_NAME);\n }\n db.createObjectStore(STORE_NAME);\n },\n });\n}\nexport async function getCachedWebAuthnKey(credentialId) {\n const resolvedDb = await lazyOpenWebAuthnKeyCache();\n const key = bytesToHexString(credentialId);\n return await resolvedDb.get(STORE_NAME, key);\n}\nexport async function setCachedWebAuthnKey(value) {\n const resolvedDb = await lazyOpenWebAuthnKeyCache();\n const key = bytesToHexString(value.credentialId);\n await resolvedDb.put(STORE_NAME, value, key);\n}\n","import { IdentityClient } from \"./identity/identity.client\";\nimport { HttpAgent } from \"@dfinity/agent\";\nimport { DelegationIdentity } from \"@dfinity/identity\";\nimport { buildDelegationIdentity, toDer } from \"openchat-shared\";\nimport { createHttpAgent } from \"../utils/httpAgent\";\nimport { getCachedWebAuthnKey } from \"../utils/webAuthnKeyCache\";\nexport class IdentityAgent {\n constructor(identity, agent, identityCanister, isIIPrincipal) {\n this._identityClient = new IdentityClient(identity, agent, identityCanister);\n this._isIIPrincipal = isIIPrincipal;\n }\n static async create(identity, identityCanister, icUrl, isIIPrincipal) {\n const agent = await createHttpAgent(identity, icUrl);\n return new IdentityAgent(identity, agent, identityCanister, isIIPrincipal);\n }\n checkOpenChatIdentityExists() {\n return this._identityClient.checkAuthPrincipal().then((resp) => resp.kind === \"success\");\n }\n checkAuthPrincipal() {\n return this._identityClient.checkAuthPrincipal();\n }\n async createOpenChatIdentity(sessionKey, webAuthnCredentialId, challengeAttempt) {\n const webAuthnKey = webAuthnCredentialId !== undefined\n ? await this.hydrateWebAuthnKey(webAuthnCredentialId)\n : undefined;\n const sessionKeyDer = toDer(sessionKey);\n const createIdentityResponse = await this._identityClient.createIdentity(sessionKeyDer, webAuthnKey, this._isIIPrincipal, challengeAttempt);\n if (createIdentityResponse.kind === \"success\") {\n const delegation = await this.getDelegation(createIdentityResponse.userKey, sessionKey, sessionKeyDer, createIdentityResponse.expiration);\n if (delegation === undefined) {\n throw new Error(\"Delegation not found, this should never happen\");\n }\n return delegation;\n }\n return createIdentityResponse.kind;\n }\n async getOpenChatIdentity(sessionKey) {\n const sessionKeyDer = toDer(sessionKey);\n const prepareDelegationResponse = await this._identityClient.prepareDelegation(sessionKeyDer, this._isIIPrincipal);\n return prepareDelegationResponse.kind === \"success\"\n ? this.getDelegation(prepareDelegationResponse.userKey, sessionKey, sessionKeyDer, prepareDelegationResponse.expiration)\n : undefined;\n }\n generateChallenge() {\n return this._identityClient.generateChallenge();\n }\n async initiateIdentityLink(linkToPrincipal, webAuthnCredentialId) {\n const webAuthnKey = webAuthnCredentialId !== undefined\n ? await this.hydrateWebAuthnKey(webAuthnCredentialId)\n : undefined;\n return this._identityClient.initiateIdentityLink(linkToPrincipal, webAuthnKey, this._isIIPrincipal);\n }\n approveIdentityLink(linkInitiatedBy) {\n return this._identityClient.approveIdentityLink(linkInitiatedBy);\n }\n removeIdentityLink(linked_principal) {\n return this._identityClient.removeIdentityLink(linked_principal);\n }\n getAuthenticationPrincipals() {\n return this._identityClient.getAuthenticationPrincipals();\n }\n async lookupWebAuthnPubKey(credentialId) {\n const cached = await getCachedWebAuthnKey(credentialId);\n return cached !== undefined\n ? cached.publicKey\n : this._identityClient.lookupWebAuthnPubKey(credentialId);\n }\n async getDelegation(userKey, sessionKey, sessionKeyDer, expiration) {\n const getDelegationResponse = await this._identityClient.getDelegation(sessionKeyDer, expiration);\n if (getDelegationResponse.kind !== \"success\") {\n return undefined;\n }\n return buildDelegationIdentity(userKey, sessionKey, getDelegationResponse.delegation, getDelegationResponse.signature);\n }\n async hydrateWebAuthnKey(credentialId) {\n const key = await getCachedWebAuthnKey(credentialId);\n if (key === undefined)\n throw new Error(\"Failed to find WebAuthnKey details\");\n return key;\n }\n}\n","import { AnonymousIdentity, SignIdentity } from \"@dfinity/agent\";\nimport { DelegationChain, DelegationIdentity, ECDSAKeyIdentity, } from \"@dfinity/identity\";\nimport { Principal } from \"@dfinity/principal\";\nimport { IdentityAgent, OpenChatAgent, setCommunityReferral, getBotDefinition, setCachedWebAuthnKey, } from \"openchat-agent\";\nimport { MessagesReadFromServer, StorageUpdated, UsersLoaded, inititaliseLogger, Stream, IdentityStorage, AuthProvider, } from \"openchat-shared\";\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n//@ts-ignore\nBigInt.prototype.toJSON = function () {\n return this.toString();\n};\nconst authIdentityStorage = IdentityStorage.createForAuthIdentity();\nconst ocIdentityStorage = IdentityStorage.createForOcIdentity();\nlet initPayload = undefined;\nlet identityAgent = undefined;\nlet authPrincipalString = undefined;\nlet logger = undefined;\nlet agent = undefined;\nlet identityCanister = \"\";\nlet icUrl = \"\";\nasync function initialize(expectedAuthPrincipal, authProvider, _identityCanister, _icUrl) {\n identityCanister = _identityCanister;\n icUrl = _icUrl;\n const authProviderIdentity = (await authIdentityStorage.get()) ?? new AnonymousIdentity();\n const authPrincipal = authProviderIdentity.getPrincipal();\n authPrincipalString = authPrincipal.toString();\n identityAgent = await IdentityAgent.create(authProviderIdentity, identityCanister, icUrl, authProvider === undefined ? undefined : authProvider === AuthProvider.II);\n if (authPrincipal.isAnonymous() || authPrincipalString !== expectedAuthPrincipal) {\n return { kind: \"auth_identity_not_found\" };\n }\n const ocIdentity = await ocIdentityStorage.get(authPrincipalString);\n if (ocIdentity !== undefined) {\n return { kind: \"success\", identity: ocIdentity };\n }\n const ocIdentityExists = await identityAgent.checkOpenChatIdentityExists();\n if (ocIdentityExists) {\n const sessionKey = await ECDSAKeyIdentity.generate();\n const identity = await identityAgent.getOpenChatIdentity(sessionKey);\n if (identity !== undefined && typeof identity !== \"string\") {\n await ocIdentityStorage.set(sessionKey, identity.getDelegation(), authPrincipalString);\n return { kind: \"success\", identity };\n }\n }\n return { kind: \"oc_identity_not_found\" };\n}\nasync function createOpenChatIdentity(webAuthnCredentialId, challengeAttempt) {\n if (identityAgent === undefined || authPrincipalString === undefined) {\n throw new Error(\"IdentityAgent not initialized\");\n }\n const sessionKey = await ECDSAKeyIdentity.generate();\n const response = await identityAgent.createOpenChatIdentity(sessionKey, webAuthnCredentialId, challengeAttempt);\n if (typeof response !== \"string\") {\n await ocIdentityStorage.set(sessionKey, response.getDelegation(), authPrincipalString);\n }\n return response;\n}\nfunction handleAgentEvent(ev) {\n if (ev instanceof MessagesReadFromServer) {\n sendEvent({\n event: {\n subkind: \"messages_read_from_server\",\n chatId: ev.detail.chatId,\n readByMeUpTo: ev.detail.readByMeUpTo,\n threadsRead: ev.detail.threadsRead,\n dateReadPinned: ev.detail.dateReadPinned,\n },\n });\n }\n if (ev instanceof StorageUpdated) {\n sendEvent({\n event: {\n subkind: \"storage_updated\",\n status: ev.detail,\n },\n });\n }\n if (ev instanceof UsersLoaded) {\n sendEvent({\n event: {\n subkind: \"users_loaded\",\n users: ev.detail,\n },\n });\n }\n}\nconst sendError = (correlationId, payload) => {\n return (error) => {\n logger?.error(\"WORKER: error caused by payload: \", error, payload);\n postMessage({\n kind: \"worker_error\",\n correlationId,\n error: JSON.stringify(error, Object.getOwnPropertyNames(error)),\n });\n };\n};\nfunction streamReplies(payload, correlationId, chain) {\n const start = Date.now();\n chain.subscribe({\n onResult: (value, final) => {\n console.debug(`WORKER: sending streamed reply ${Date.now() - start}ms after subscribing`, correlationId, value, Date.now(), final);\n sendResponse(correlationId, value, final);\n },\n onError: sendError(correlationId, payload),\n });\n}\nfunction executeThenReply(payload, correlationId, promise) {\n promise\n .then((response) => sendResponse(correlationId, response))\n .catch(sendError(correlationId, payload));\n}\nfunction sendResponse(correlationId, response, final = true) {\n logger?.debug(\"WORKER: sending response: \", correlationId);\n postMessage({\n kind: \"worker_response\",\n correlationId,\n response,\n final,\n });\n}\nfunction sendEvent(msg) {\n postMessage({\n kind: \"worker_event\",\n ...msg,\n });\n}\nself.addEventListener(\"error\", (err) => {\n logger?.error(\"WORKER: unhandled error: \", err);\n});\nself.addEventListener(\"unhandledrejection\", (err) => {\n logger?.error(\"WORKER: unhandled promise rejection: \", err);\n});\nself.addEventListener(\"message\", (msg) => {\n (logger ?? console).debug(\"WORKER: received \", msg.data.kind, msg.data.correlationId);\n const payload = msg.data;\n const kind = payload.kind;\n const correlationId = payload.correlationId;\n try {\n if (kind === \"init\") {\n initPayload = payload;\n const init = payload;\n executeThenReply(payload, correlationId, initialize(init.authPrincipal, init.authProvider, init.identityCanister, init.icUrl).then((resp) => {\n const id = resp.kind === \"success\" ? resp.identity : new AnonymousIdentity();\n console.debug(\"anon: init worker\", id.getPrincipal().toString(), id?.getPrincipal().isAnonymous());\n logger = inititaliseLogger(init.rollbarApiKey, init.websiteVersion, init.env);\n logger?.debug(\"WORKER: constructing agent instance\");\n agent = new OpenChatAgent(id, {\n ...init,\n logger,\n });\n agent.addEventListener(\"openchat_event\", handleAgentEvent);\n return resp.kind;\n }));\n return;\n }\n if (initPayload === undefined) {\n throw new Error(\"Worker not initialised\");\n }\n if (payload.kind === \"generateIdentityChallenge\") {\n if (identityAgent === undefined) {\n throw new Error(\"IdentityAgent not initialized\");\n }\n executeThenReply(payload, correlationId, identityAgent.generateChallenge());\n return;\n }\n if (kind === \"createOpenChatIdentity\") {\n executeThenReply(payload, correlationId, createOpenChatIdentity(payload.webAuthnCredentialId, payload.challengeAttempt).then((resp) => {\n const id = typeof resp !== \"string\" ? resp : new AnonymousIdentity();\n agent = new OpenChatAgent(id, {\n ...initPayload,\n logger: logger,\n });\n agent.addEventListener(\"openchat_event\", handleAgentEvent);\n return typeof resp !== \"string\" ? \"success\" : resp;\n }));\n return;\n }\n if (!agent) {\n logger?.debug(\"WORKER: agent does not exist: \", msg.data);\n return;\n }\n switch (kind) {\n case \"getCurrentUser\":\n streamReplies(payload, correlationId, agent.getCurrentUser());\n break;\n case \"getDeletedGroupMessage\":\n executeThenReply(payload, correlationId, agent.getDeletedGroupMessage(payload.chatId, payload.messageId, payload.threadRootMessageIndex));\n break;\n case \"getDeletedDirectMessage\":\n executeThenReply(payload, correlationId, agent.getDeletedDirectMessage(payload.userId, payload.messageId));\n break;\n case \"getUpdates\":\n streamReplies(payload, correlationId, agent.getUpdates(payload.initialLoad));\n break;\n case \"getBots\":\n streamReplies(payload, correlationId, agent.getBots(payload.initialLoad));\n break;\n case \"createUserClient\":\n agent.createUserClient(payload.userId);\n sendResponse(correlationId, undefined);\n break;\n case \"chatEvents\":\n executeThenReply(payload, correlationId, agent.chatEvents(payload.chatId, payload.eventIndexRange, payload.startIndex, payload.ascending, payload.threadRootMessageIndex, payload.latestKnownUpdate));\n break;\n case \"getUsers\":\n executeThenReply(payload, correlationId, agent.getUsers(payload.chitState, payload.users, payload.allowStale));\n break;\n case \"getAllCachedUsers\":\n executeThenReply(payload, correlationId, agent.getAllCachedUsers());\n break;\n case \"markMessagesRead\":\n executeThenReply(payload, correlationId, agent.markMessagesRead(payload.payload));\n break;\n case \"getGroupDetails\":\n executeThenReply(payload, correlationId, agent.getGroupDetails(payload.chatId, payload.chatLastUpdated));\n break;\n case \"lastOnline\":\n executeThenReply(payload, correlationId, agent.lastOnline(payload.userIds));\n break;\n case \"markAsOnline\":\n executeThenReply(payload, correlationId, agent.markAsOnline());\n break;\n case \"minutesOnline\":\n executeThenReply(payload, correlationId, agent.minutesOnline(payload.year, payload.month));\n break;\n case \"chatEventsBatch\":\n executeThenReply(payload, correlationId, agent.chatEventsBatch(payload.localUserIndex, payload.requests, payload.cachePrimer));\n break;\n case \"chatEventsWindow\":\n executeThenReply(payload, correlationId, agent.chatEventsWindow(payload.eventIndexRange, payload.chatId, payload.messageIndex, payload.threadRootMessageIndex, payload.latestKnownUpdate));\n break;\n case \"chatEventsByEventIndex\":\n executeThenReply(payload, correlationId, agent.chatEventsByEventIndex(payload.chatId, payload.eventIndexes, payload.threadRootMessageIndex, payload.latestKnownUpdate));\n break;\n case \"rehydrateMessage\":\n executeThenReply(payload, correlationId, agent.rehydrateMessage(payload.chatId, payload.message, payload.threadRootMessageIndex, payload.latestKnownUpdate));\n break;\n case \"checkUsername\":\n executeThenReply(payload, correlationId, agent.checkUsername(payload.username, payload.isBot));\n break;\n case \"searchUsers\":\n executeThenReply(payload, correlationId, agent.searchUsers(payload.searchTerm, payload.maxResults));\n break;\n case \"getUserStorageLimits\":\n executeThenReply(payload, correlationId, agent.getUserStorageLimits());\n break;\n case \"getPublicGroupSummary\":\n executeThenReply(payload, correlationId, agent.getPublicGroupSummary(payload.chatId));\n break;\n case \"toggleMuteNotifications\":\n executeThenReply(payload, correlationId, agent.toggleMuteNotifications(payload.id, payload.muted));\n break;\n case \"archiveChat\":\n executeThenReply(payload, correlationId, agent.archiveChat(payload.chatId));\n break;\n case \"unarchiveChat\":\n executeThenReply(payload, correlationId, agent.unarchiveChat(payload.chatId));\n break;\n case \"pinChat\":\n executeThenReply(payload, correlationId, agent.pinChat(payload.chatId, payload.favourite));\n break;\n case \"unpinChat\":\n executeThenReply(payload, correlationId, agent.unpinChat(payload.chatId, payload.favourite));\n break;\n case \"blockUserFromDirectChat\":\n executeThenReply(payload, correlationId, agent.blockUserFromDirectChat(payload.userId));\n break;\n case \"unblockUserFromDirectChat\":\n executeThenReply(payload, correlationId, agent.unblockUserFromDirectChat(payload.userId));\n break;\n case \"setUserAvatar\":\n executeThenReply(payload, correlationId, agent.setUserAvatar(payload.data));\n break;\n case \"deleteGroup\":\n executeThenReply(payload, correlationId, agent.deleteGroup(payload.chatId));\n break;\n case \"leaveGroup\":\n executeThenReply(payload, correlationId, agent.leaveGroup(payload.chatId));\n break;\n case \"joinGroup\":\n executeThenReply(payload, correlationId, agent.joinGroup(payload.chatId, payload.credentialArgs));\n break;\n case \"joinCommunity\":\n executeThenReply(payload, correlationId, agent.joinCommunity(payload.id, payload.credentialArgs));\n break;\n case \"updateGroup\":\n executeThenReply(payload, correlationId, agent.updateGroup(payload.chatId, payload.name, payload.desc, payload.rules, payload.permissions, payload.avatar, payload.eventsTimeToLive, payload.gateConfig, payload.isPublic, payload.messagesVisibleToNonMembers, payload.externalUrl));\n break;\n case \"registerPollVote\":\n executeThenReply(payload, correlationId, agent.registerPollVote(payload.chatId, payload.messageIdx, payload.answerIdx, payload.voteType, payload.threadRootMessageIndex, payload.newAchievement));\n break;\n case \"deleteMessage\":\n executeThenReply(payload, correlationId, agent.deleteMessage(payload.chatId, payload.messageId, payload.threadRootMessageIndex, payload.asPlatformModerator, payload.newAchievement));\n break;\n case \"undeleteMessage\":\n executeThenReply(payload, correlationId, agent.undeleteMessage(payload.chatId, payload.messageId, payload.threadRootMessageIndex));\n break;\n case \"addReaction\":\n executeThenReply(payload, correlationId, agent.addReaction(payload.chatId, payload.messageId, payload.reaction, payload.username, payload.displayName, payload.threadRootMessageIndex, payload.newAchievement));\n break;\n case \"removeReaction\":\n executeThenReply(payload, correlationId, agent.removeReaction(payload.chatId, payload.messageId, payload.reaction, payload.threadRootMessageIndex));\n break;\n case \"blockUserFromGroupChat\":\n executeThenReply(payload, correlationId, agent.blockUserFromGroupChat(payload.chatId, payload.userId));\n break;\n case \"unblockUserFromGroupChat\":\n executeThenReply(payload, correlationId, agent.unblockUserFromGroupChat(payload.chatId, payload.userId));\n break;\n case \"getProposalVoteDetails\":\n executeThenReply(payload, correlationId, agent.getProposalVoteDetails(payload.governanceCanisterId, payload.proposalId, payload.isNns));\n break;\n case \"listNervousSystemFunctions\":\n executeThenReply(payload, correlationId, agent.listNervousSystemFunctions(payload.snsGovernanceCanisterId));\n break;\n case \"unpinMessage\":\n executeThenReply(payload, correlationId, agent.unpinMessage(payload.chatId, payload.messageIndex));\n break;\n case \"pinMessage\":\n executeThenReply(payload, correlationId, agent.pinMessage(payload.chatId, payload.messageIndex));\n break;\n case \"sendMessage\":\n streamReplies(payload, correlationId, agent.sendMessage(payload.messageContext, payload.user, payload.mentioned, payload.event, payload.acceptedRules, payload.messageFilterFailed, payload.pin, payload.newAchievement));\n break;\n case \"editMessage\":\n executeThenReply(payload, correlationId, agent.editMessage(payload.chatId, payload.msg, payload.threadRootMessageIndex, payload.blockLevelMarkdown, payload.newAchievement));\n break;\n case \"registerUser\":\n executeThenReply(payload, correlationId, agent.registerUser(payload.username, payload.referralCode));\n break;\n case \"subscriptionExists\":\n executeThenReply(payload, correlationId, agent.subscriptionExists(payload.p256dh_key));\n break;\n case \"pushSubscription\":\n executeThenReply(payload, correlationId, agent.pushSubscription(payload.subscription).then(() => undefined));\n break;\n case \"removeSubscription\":\n executeThenReply(payload, correlationId, agent.removeSubscription(payload.subscription).then(() => undefined));\n break;\n case \"inviteUsers\":\n executeThenReply(payload, correlationId, agent.inviteUsers(payload.id, payload.userIds, payload.callerUsername));\n break;\n case \"removeMember\":\n executeThenReply(payload, correlationId, agent.removeMember(payload.chatId, payload.userId));\n break;\n case \"changeRole\":\n executeThenReply(payload, correlationId, agent.changeRole(payload.chatId, payload.userId, payload.newRole));\n break;\n case \"registerProposalVote\":\n executeThenReply(payload, correlationId, agent.registerProposalVote(payload.chatId, payload.messageIndex, payload.adopt));\n break;\n case \"getRecommendedGroups\":\n executeThenReply(payload, correlationId, agent.getRecommendedGroups(payload.exclusions));\n break;\n case \"exploreCommunities\":\n executeThenReply(payload, correlationId, agent.exploreCommunities(payload.searchTerm, payload.pageIndex, payload.pageSize, payload.flags, payload.languages));\n break;\n case \"exploreBots\":\n executeThenReply(payload, correlationId, agent.exploreBots(payload.searchTerm, payload.pageIndex, payload.pageSize, payload.location));\n break;\n case \"registerBot\":\n executeThenReply(payload, correlationId, agent.registerBot(payload.principal, payload.bot));\n break;\n case \"removeBot\":\n executeThenReply(payload, correlationId, agent.removeBot(payload.botId));\n break;\n case \"updateRegisteredBot\":\n executeThenReply(payload, correlationId, agent.updateRegisteredBot(payload.id, payload.principal, payload.ownerId, payload.avatarUrl, payload.endpoint, payload.definition));\n break;\n case \"searchGroups\":\n executeThenReply(payload, correlationId, agent.searchGroups(payload.searchTerm, payload.maxResults));\n break;\n case \"dismissRecommendation\":\n executeThenReply(payload, correlationId, agent.dismissRecommendation(payload.chatId).then(() => undefined));\n break;\n case \"communityInvite\":\n agent.communityInvite = payload.value;\n sendResponse(correlationId, undefined);\n break;\n case \"groupInvite\":\n agent.groupInvite = payload.value;\n sendResponse(correlationId, undefined);\n break;\n case \"searchGroupChat\":\n executeThenReply(payload, correlationId, agent.searchGroupChat(payload.chatId, payload.searchTerm, payload.userIds, payload.maxResults));\n break;\n case \"searchDirectChat\":\n executeThenReply(payload, correlationId, agent.searchDirectChat(payload.chatId, payload.searchTerm, payload.maxResults));\n break;\n case \"refreshAccountBalance\":\n executeThenReply(payload, correlationId, agent.refreshAccountBalance(payload.ledger, payload.principal));\n break;\n case \"getAccountTransactions\":\n executeThenReply(payload, correlationId, agent.getAccountTransactions(payload.ledgerIndex, payload.principal, payload.fromId));\n break;\n case \"threadPreviews\":\n executeThenReply(payload, correlationId, agent.threadPreviews(payload.threadsByChat));\n break;\n case \"getUser\":\n executeThenReply(payload, correlationId, agent.getUser(payload.chitState, payload.userId, payload.allowStale));\n break;\n case \"getPublicProfile\":\n executeThenReply(payload, correlationId, agent.getPublicProfile(payload.userId));\n break;\n case \"setUsername\":\n executeThenReply(payload, correlationId, agent.setUsername(payload.userId, payload.username));\n break;\n case \"setDisplayName\":\n executeThenReply(payload, correlationId, agent.setDisplayName(payload.userId, payload.displayName));\n break;\n case \"setBio\":\n executeThenReply(payload, correlationId, agent.setBio(payload.bio));\n break;\n case \"getBio\":\n executeThenReply(payload, correlationId, agent.getBio(payload.userId));\n break;\n case \"withdrawCryptocurrency\":\n executeThenReply(payload, correlationId, agent.withdrawCryptocurrency(payload.domain, payload.pin));\n break;\n case \"getGroupMessagesByMessageIndex\":\n executeThenReply(payload, correlationId, agent.getGroupMessagesByMessageIndex(payload.chatId, payload.messageIndexes, payload.latestKnownUpdate));\n break;\n case \"getInviteCode\":\n executeThenReply(payload, correlationId, agent.getInviteCode(payload.id));\n break;\n case \"enableInviteCode\":\n executeThenReply(payload, correlationId, agent.enableInviteCode(payload.id));\n break;\n case \"disableInviteCode\":\n executeThenReply(payload, correlationId, agent.disableInviteCode(payload.id));\n break;\n case \"resetInviteCode\":\n executeThenReply(payload, correlationId, agent.resetInviteCode(payload.id));\n break;\n case \"createGroupChat\":\n executeThenReply(payload, correlationId, agent.createGroupChat(payload.candidate));\n break;\n case \"setCachedMessageFromNotification\":\n executeThenReply(payload, correlationId, agent\n .setCachedMessageFromNotification(payload.chatId, payload.threadRootMessageIndex, payload.message)\n .then(() => undefined));\n break;\n case \"freezeGroup\":\n executeThenReply(payload, correlationId, agent.freezeGroup(payload.chatId, payload.reason));\n break;\n case \"unfreezeGroup\":\n executeThenReply(payload, correlationId, agent.unfreezeGroup(payload.chatId));\n break;\n case \"freezeCommunity\":\n executeThenReply(payload, correlationId, agent.freezeCommunity(payload.id, payload.reason));\n break;\n case \"unfreezeCommunity\":\n executeThenReply(payload, correlationId, agent.unfreezeCommunity(payload.id));\n break;\n case \"deleteFrozenGroup\":\n executeThenReply(payload, correlationId, agent.deleteFrozenGroup(payload.chatId));\n break;\n case \"addHotGroupExclusion\":\n executeThenReply(payload, correlationId, agent.addHotGroupExclusion(payload.chatId));\n break;\n case \"removeHotGroupExclusion\":\n executeThenReply(payload, correlationId, agent.removeHotGroupExclusion(payload.chatId));\n break;\n case \"addRemoveSwapProvider\":\n executeThenReply(payload, correlationId, agent.addRemoveSwapProvider(payload.swapProvider, payload.add));\n break;\n case \"addMessageFilter\":\n executeThenReply(payload, correlationId, agent.addMessageFilter(payload.regex));\n break;\n case \"removeMessageFilter\":\n executeThenReply(payload, correlationId, agent.removeMessageFilter(payload.id));\n break;\n case \"setTokenEnabled\":\n executeThenReply(payload, correlationId, agent.setTokenEnabled(payload.ledger, payload.enabled));\n break;\n case \"suspendUser\":\n executeThenReply(payload, correlationId, agent.suspendUser(payload.userId, payload.reason));\n break;\n case \"unsuspendUser\":\n executeThenReply(payload, correlationId, agent.unsuspendUser(payload.userId));\n break;\n case \"setCommunityModerationFlags\":\n executeThenReply(payload, correlationId, agent.setCommunityModerationFlags(payload.communityId, payload.flags));\n break;\n case \"setGroupUpgradeConcurrency\":\n executeThenReply(payload, correlationId, agent.setGroupUpgradeConcurrency(payload.value));\n break;\n case \"setCommunityUpgradeConcurrency\":\n executeThenReply(payload, correlationId, agent.setCommunityUpgradeConcurrency(payload.value));\n break;\n case \"setUserUpgradeConcurrency\":\n executeThenReply(payload, correlationId, agent.setUserUpgradeConcurrency(payload.value));\n break;\n case \"markLocalGroupIndexFull\":\n executeThenReply(payload, correlationId, agent.markLocalGroupIndexFull(payload.canisterId, payload.full));\n break;\n case \"setDiamondMembershipFees\":\n executeThenReply(payload, correlationId, agent.setDiamondMembershipFees(payload.fees));\n break;\n case \"stakeNeuronForSubmittingProposals\":\n executeThenReply(payload, correlationId, agent.stakeNeuronForSubmittingProposals(payload.governanceCanisterId, payload.stake));\n break;\n case \"topUpNeuronForSubmittingProposals\":\n executeThenReply(payload, correlationId, agent.topUpNeuronForSubmittingProposals(payload.governanceCanisterId, payload.amount));\n break;\n case \"loadFailedMessages\":\n executeThenReply(payload, correlationId, agent.loadFailedMessages());\n break;\n case \"deleteFailedMessage\":\n executeThenReply(payload, correlationId, agent\n .deleteFailedMessage(payload.chatId, payload.messageId, payload.threadRootMessageIndex)\n .then(() => undefined));\n break;\n case \"claimPrize\":\n executeThenReply(payload, correlationId, agent.claimPrize(payload.chatId, payload.messageId));\n break;\n case \"payForDiamondMembership\":\n executeThenReply(payload, correlationId, agent.payForDiamondMembership(payload.userId, payload.ledger, payload.duration, payload.recurring, payload.expectedPriceE8s));\n break;\n case \"updateMarketMakerConfig\":\n executeThenReply(payload, correlationId, agent.updateMarketMakerConfig(payload));\n break;\n case \"setMessageReminder\":\n executeThenReply(payload, correlationId, agent.setMessageReminder(payload.chatId, payload.eventIndex, payload.remindAt, payload.notes, payload.threadRootMessageIndex));\n break;\n case \"cancelMessageReminder\":\n executeThenReply(payload, correlationId, agent.cancelMessageReminder(payload.reminderId));\n break;\n case \"reportMessage\":\n executeThenReply(payload, correlationId, agent.reportMessage(payload.chatId, payload.threadRootMessageIndex, payload.messageId, payload.deleteMessage));\n break;\n case \"approveTransfer\":\n executeThenReply(payload, correlationId, agent.approveTransfer(payload.spender, payload.ledger, payload.amount, payload.expiresIn, payload.pin));\n break;\n case \"declineInvitation\":\n executeThenReply(payload, correlationId, agent.declineInvitation(payload.chatId));\n break;\n // Community level functions\n case \"addMembersToChannel\":\n executeThenReply(payload, correlationId, agent\n .communityClient(payload.chatId.communityId)\n .addMembersToChannel(payload.chatId, payload.userIds, payload.username, payload.displayName));\n break;\n case \"blockCommunityUser\":\n executeThenReply(payload, correlationId, agent.communityClient(payload.id.communityId).blockUser(payload.userId));\n break;\n case \"changeChannelRole\":\n executeThenReply(payload, correlationId, agent\n .communityClient(payload.chatId.communityId)\n .changeChannelRole(payload.chatId, payload.userId, payload.newRole));\n break;\n case \"changeCommunityRole\":\n executeThenReply(payload, correlationId, agent\n .communityClient(payload.id.communityId)\n .changeRole(payload.userId, payload.newRole));\n break;\n case \"declineChannelInvitation\":\n executeThenReply(payload, correlationId, agent\n .communityClient(payload.chatId.communityId)\n .declineInvitation(payload.chatId));\n break;\n case \"removeCommunityMember\":\n executeThenReply(payload, correlationId, agent.communityClient(payload.id.communityId).removeMember(payload.userId));\n break;\n case \"unblockCommunityUser\":\n executeThenReply(payload, correlationId, agent.communityClient(payload.id.communityId).unblockUser(payload.userId));\n break;\n case \"updateCommunity\":\n executeThenReply(payload, correlationId, agent\n .communityClient(payload.communityId)\n .updateCommunity(payload.name, payload.description, payload.rules, payload.permissions, payload.avatar, payload.banner, payload.gateConfig, payload.isPublic, payload.primaryLanguage));\n break;\n case \"createCommunity\":\n executeThenReply(payload, correlationId, agent.userClient.createCommunity(payload.community, payload.rules, payload.defaultChannels, payload.defaultChannelRules));\n break;\n case \"getCommunitySummary\":\n executeThenReply(payload, correlationId, agent.getCommunitySummary(payload.communityId));\n break;\n case \"getChannelSummary\":\n executeThenReply(payload, correlationId, agent.getChannelSummary(payload.chatId));\n break;\n case \"exploreChannels\":\n executeThenReply(payload, correlationId, agent.exploreChannels(payload.id, payload.searchTerm, payload.pageSize, payload.pageIndex));\n break;\n case \"getCommunityDetails\":\n executeThenReply(payload, correlationId, agent\n .communityClient(payload.id.communityId)\n .getCommunityDetails(payload.id, payload.communityLastUpdated));\n break;\n case \"addToFavourites\":\n executeThenReply(payload, correlationId, agent.userClient.manageFavouriteChats([payload.chatId], []));\n break;\n case \"removeFromFavourites\":\n executeThenReply(payload, correlationId, agent.userClient.manageFavouriteChats([], [payload.chatId]));\n break;\n case \"leaveCommunity\":\n executeThenReply(payload, correlationId, agent.userClient.leaveCommunity(payload.id));\n break;\n case \"deleteCommunity\":\n executeThenReply(payload, correlationId, agent.userClient.deleteCommunity(payload.id));\n break;\n case \"convertGroupToCommunity\":\n executeThenReply(payload, correlationId, agent.convertGroupToCommunity(payload.chatId, payload.historyVisible, payload.rules));\n break;\n case \"importGroupToCommunity\":\n executeThenReply(payload, correlationId, agent\n .communityClient(payload.communityId.communityId)\n .importGroup(payload.groupId));\n break;\n case \"setModerationFlags\":\n executeThenReply(payload, correlationId, agent.setModerationFlags(payload.flags));\n break;\n case \"updateRegistry\":\n streamReplies(payload, correlationId, agent.getRegistry());\n break;\n case \"setCommunityIndexes\":\n executeThenReply(payload, correlationId, agent.setCommunityIndexes(payload.indexes));\n break;\n case \"createUserGroup\":\n executeThenReply(payload, correlationId, agent.createUserGroup(payload.communityId, payload.name, payload.userIds));\n break;\n case \"updateUserGroup\":\n executeThenReply(payload, correlationId, agent.updateUserGroup(payload.communityId, payload.userGroupId, payload.name, payload.usersToAdd, payload.usersToRemove));\n break;\n case \"deleteUserGroups\":\n executeThenReply(payload, correlationId, agent.deleteUserGroups(payload.communityId, payload.userGroupIds));\n break;\n case \"setMemberDisplayName\":\n executeThenReply(payload, correlationId, agent.setMemberDisplayName(payload.communityId, payload.displayName, payload.newAchievement));\n break;\n case \"followThread\":\n executeThenReply(payload, correlationId, agent.followThread(payload.chatId, payload.threadRootMessageIndex, payload.follow, payload.newAchievement));\n break;\n case \"submitProposal\":\n executeThenReply(payload, correlationId, agent.submitProposal(payload.currentUserId, payload.governanceCanisterId, payload.proposal, payload.ledger, payload.token, payload.proposalRejectionFee, payload.transactionFee));\n break;\n case \"getCachePrimerTimestamps\":\n executeThenReply(payload, correlationId, agent.getCachePrimerTimestamps());\n break;\n case \"tipMessage\":\n executeThenReply(payload, correlationId, agent.userClient.tipMessage(payload.messageContext, payload.messageId, payload.transfer, payload.decimals, payload.pin));\n break;\n case \"loadSavedCryptoAccounts\":\n executeThenReply(payload, correlationId, agent.userClient.loadSavedCryptoAccounts());\n break;\n case \"saveCryptoAccount\":\n executeThenReply(payload, correlationId, agent.userClient.saveCryptoAccount(payload.namedAccount));\n break;\n case \"canSwap\":\n executeThenReply(payload, correlationId, agent.canSwap(payload.tokenLedgers));\n break;\n case \"getTokenSwaps\":\n executeThenReply(payload, correlationId, agent.getTokenSwaps(payload.inputTokenLedger, payload.outputTokenLedgers));\n break;\n case \"getTokenSwapQuotes\":\n executeThenReply(payload, correlationId, agent.getTokenSwapQuotes(payload.inputTokenLedger, payload.outputTokenLedger, payload.amountIn));\n break;\n case \"swapTokens\":\n executeThenReply(payload, correlationId, agent.swapTokens(payload.swapId, payload.inputTokenDetails, payload.outputTokenDetails, payload.amountIn, payload.minAmountOut, payload.dex, payload.pin));\n break;\n case \"tokenSwapStatus\":\n executeThenReply(payload, correlationId, agent.tokenSwapStatus(payload.swapId));\n break;\n case \"deleteDirectChat\":\n executeThenReply(payload, correlationId, agent.deleteDirectChat(payload.userId, payload.blockUser));\n break;\n case \"diamondMembershipFees\":\n executeThenReply(payload, correlationId, agent.diamondMembershipFees());\n break;\n case \"reportedMessages\":\n executeThenReply(payload, correlationId, agent.reportedMessages(payload.userId));\n break;\n case \"exchangeRates\":\n executeThenReply(payload, correlationId, agent.exchangeRates());\n break;\n case \"proposeTranslation\":\n executeThenReply(payload, correlationId, agent.translationsClient().propose(payload.locale, payload.key, payload.value));\n break;\n case \"approveTranslation\":\n executeThenReply(payload, correlationId, agent.translationsClient().approve(payload.id));\n break;\n case \"rejectTranslation\":\n executeThenReply(payload, correlationId, agent.translationsClient().reject(payload.id, payload.reason));\n break;\n case \"getProposedTranslations\":\n executeThenReply(payload, correlationId, agent.translationsClient().proposed());\n break;\n case \"markTranslationsDeployed\":\n executeThenReply(payload, correlationId, agent.translationsClient().markDeployed());\n break;\n case \"getTranslationsPendingDeployment\":\n executeThenReply(payload, correlationId, agent.translationsClient().pendingDeployment());\n break;\n case \"acceptP2PSwap\":\n executeThenReply(payload, correlationId, agent.acceptP2PSwap(payload.chatId, payload.threadRootMessageIndex, payload.messageId, payload.pin, payload.newAchievement));\n break;\n case \"cancelP2PSwap\":\n executeThenReply(payload, correlationId, agent.cancelP2PSwap(payload.chatId, payload.threadRootMessageIndex, payload.messageId));\n break;\n case \"joinVideoCall\":\n executeThenReply(payload, correlationId, agent.joinVideoCall(payload.chatId, payload.messageId, payload.newAchievement));\n break;\n case \"videoCallParticipants\":\n executeThenReply(payload, correlationId, agent.videoCallParticipants(payload.chatId, payload.messageId, payload.updatesSince));\n break;\n case \"setVideoCallPresence\":\n executeThenReply(payload, correlationId, agent.setVideoCallPresence(payload.chatId, payload.messageId, payload.presence, payload.newAchievement));\n break;\n case \"getAccessToken\":\n executeThenReply(payload, correlationId, agent.getAccessToken(payload.accessTokenType, payload.localUserIndex));\n break;\n case \"generateBotApiKey\":\n executeThenReply(payload, correlationId, agent.generateBotApiKey(payload.id, payload.botId, payload.permissions));\n break;\n case \"getApiKey\":\n executeThenReply(payload, correlationId, agent.getApiKey(payload.id, payload.botId));\n break;\n case \"getLocalUserIndexForUser\":\n executeThenReply(payload, correlationId, agent.getLocalUserIndexForUser(payload.userId));\n break;\n case \"generateBtcAddress\":\n executeThenReply(payload, correlationId, agent.generateBtcAddress());\n break;\n case \"updateBtcBalance\":\n executeThenReply(payload, correlationId, agent.updateBtcBalance(payload.userId, payload.bitcoinAddress));\n break;\n case \"withdrawBtc\":\n executeThenReply(payload, correlationId, agent.withdrawBtc(payload.address, payload.amount, payload.pin));\n break;\n case \"ckbtcMinterDepositInfo\":\n executeThenReply(payload, correlationId, agent.getCkbtcMinterDepositInfo());\n break;\n case \"ckbtcMinterWithdrawalInfo\":\n executeThenReply(payload, correlationId, agent.getCkbtcMinterWithdrawalInfo(payload.amount));\n break;\n case \"currentUserWebAuthnKey\":\n executeThenReply(payload, correlationId, identityAgent?.checkAuthPrincipal().then((res) => {\n return res.kind === \"success\" ? res.webAuthnKey : undefined;\n }) ?? Promise.resolve(undefined));\n break;\n case \"lookupWebAuthnPubKey\":\n executeThenReply(payload, correlationId, identityAgent?.lookupWebAuthnPubKey(payload.credentialId) ??\n Promise.resolve(undefined));\n break;\n case \"setCachedWebAuthnKey\":\n executeThenReply(payload, correlationId, setCachedWebAuthnKey(payload.key));\n break;\n case \"generateMagicLink\":\n executeThenReply(payload, correlationId, agent.generateMagicLink(payload.email, payload.sessionKey));\n break;\n case \"getSignInWithEmailDelegation\":\n executeThenReply(payload, correlationId, agent.getSignInWithEmailDelegation(payload.email, payload.sessionKey, payload.expiration));\n break;\n case \"siwePrepareLogin\":\n executeThenReply(payload, correlationId, agent.siwePrepareLogin(payload.address));\n break;\n case \"siwsPrepareLogin\":\n executeThenReply(payload, correlationId, agent.siwsPrepareLogin(payload.address));\n break;\n case \"loginWithWallet\":\n executeThenReply(payload, correlationId, agent.loginWithWallet(payload.token, payload.address, payload.signature, payload.sessionKey));\n break;\n case \"getDelegationWithWallet\":\n executeThenReply(payload, correlationId, agent.getDelegationWithWallet(payload.token, payload.address, payload.sessionKey, payload.expiration));\n break;\n case \"setPinNumber\":\n executeThenReply(payload, correlationId, agent.setPinNumber(payload.verification, payload.newPin));\n break;\n case \"claimDailyChit\":\n executeThenReply(payload, correlationId, agent.claimDailyChit());\n break;\n case \"chitLeaderboard\":\n executeThenReply(payload, correlationId, agent.chitLeaderboard());\n break;\n case \"getChitEvents\":\n executeThenReply(payload, correlationId, agent.chitEvents(payload));\n break;\n case \"markAchievementsSeen\":\n executeThenReply(payload, correlationId, agent.markAchievementsSeen());\n break;\n case \"submitProofOfUniquePersonhood\":\n executeThenReply(payload, correlationId, agent.submitProofOfUniquePersonhood(payload.iiPrincipal, payload.credential));\n break;\n case \"linkIdentities\":\n executeThenReply(payload, correlationId, linkIdentities(payload.initiatorKey, payload.initiatorDelegation, payload.initiatorIsIIPrincipal, payload.initiatorWebAuthnKey, payload.approverKey, payload.approverDelegation));\n break;\n case \"removeIdentityLink\":\n executeThenReply(payload, correlationId, removeIdentityLink(payload.linked_principal));\n break;\n case \"getAuthenticationPrincipals\":\n if (identityAgent === undefined) {\n throw new Error(\"IdentityAgent not initialized\");\n }\n executeThenReply(payload, correlationId, identityAgent.getAuthenticationPrincipals());\n break;\n case \"configureWallet\":\n executeThenReply(payload, correlationId, agent.configureWallet(payload.config));\n break;\n case \"clearCachedData\":\n executeThenReply(payload, correlationId, agent.clearCachedData());\n break;\n case \"setCommunityReferral\":\n executeThenReply(payload, correlationId, setCommunityReferral(payload.communityId.communityId, payload.referredBy, Date.now()));\n break;\n case \"getExternalAchievements\":\n executeThenReply(payload, correlationId, agent.getExternalAchievements());\n break;\n case \"cancelInvites\":\n executeThenReply(payload, correlationId, agent.cancelInvites(payload.id, payload.userIds));\n break;\n case \"messageActivityFeed\":\n streamReplies(payload, correlationId, agent.messageActivityFeed());\n break;\n case \"markActivityFeedRead\":\n executeThenReply(payload, correlationId, agent.markActivityFeedRead(payload.readUpTo));\n break;\n case \"deleteUser\":\n executeThenReply(payload, correlationId, agent.deleteUser(payload.userId, payload.delegation));\n break;\n case \"installBot\":\n executeThenReply(payload, correlationId, agent.installBot(payload.id, payload.botId, payload.grantedPermissions));\n break;\n case \"updateInstalledBot\":\n executeThenReply(payload, correlationId, agent.updateInstalledBot(payload.id, payload.botId, payload.grantedPermissions));\n break;\n case \"uninstallBot\":\n executeThenReply(payload, correlationId, agent.uninstallBot(payload.id, payload.botId));\n break;\n case \"getBotDefinition\":\n executeThenReply(payload, correlationId, getBotDefinition(payload.endpoint));\n break;\n case \"callBotCommandEndpoint\":\n executeThenReply(payload, correlationId, agent.callBotCommandEndpoint(payload.endpoint, payload.token));\n break;\n case \"withdrawFromIcpSwap\":\n executeThenReply(payload, correlationId, agent.withdrawFromIcpSwap(payload.userId, payload.swapId, payload.inputToken, payload.amount, payload.fee));\n break;\n default:\n logger?.debug(\"WORKER: unknown message kind received: \", kind);\n }\n }\n catch (err) {\n logger?.debug(\"WORKER: unhandled error: \", err);\n sendError(correlationId)(err);\n }\n});\nasync function linkIdentities(initiatorKey, initiatorDelegation, initiatorIsIIPrincipal, initiatorWebAuthnKey, approverKey, approverDelegation) {\n const initiatorIdentity = DelegationIdentity.fromDelegation(await ECDSAKeyIdentity.fromKeyPair(initiatorKey), DelegationChain.fromJSON(initiatorDelegation));\n const initiatorAgent = await IdentityAgent.create(initiatorIdentity, identityCanister, icUrl, initiatorIsIIPrincipal);\n const approverIdentity = DelegationIdentity.fromDelegation(await ECDSAKeyIdentity.fromKeyPair(approverKey), DelegationChain.fromJSON(approverDelegation));\n const approverAgent = await IdentityAgent.create(approverIdentity, identityCanister, icUrl, undefined);\n const approver = approverIdentity.getPrincipal().toString();\n const initiateResponse = await initiatorAgent.initiateIdentityLink(approver, initiatorWebAuthnKey?.credentialId);\n if (initiateResponse !== \"success\") {\n return initiateResponse;\n }\n const initiatorPrincipal = initiatorWebAuthnKey !== undefined\n ? Principal.selfAuthenticating(initiatorWebAuthnKey.publicKey)\n : initiatorIdentity.getPrincipal();\n return await approverAgent.approveIdentityLink(initiatorPrincipal.toString());\n}\nasync function removeIdentityLink(linked_principal) {\n if (identityAgent) {\n return identityAgent.removeIdentityLink(linked_principal);\n }\n throw new Error(\"IdentityAgent not initialized\");\n}\n"],"names":["base64Js","b64","lens","getLens","validLen","placeHoldersLen","tmp","i","arr","Arr","_byteLength","curByte","len","revLookup","charCodeAt","uint8","length","extraBytes","parts","maxChunkLength","len2","push","encodeChunk","lookup","join","Uint8Array","Array","code","Error","indexOf","start","end","num","output","ReplicaRejectCode","ieee754","read","buffer","offset","isLE","mLen","nBytes","e","m","eLen","eMax","eBias","nBits","d","s","NaN","Infinity","Math","pow","write","value","c","rt","abs","isNaN","floor","log","LN2","base64","require$$0","require$$1","customInspectSymbol","Symbol","exports","Buffer","SlowBuffer","alloc","INSPECT_MAX_BYTES","K_MAX_LENGTH","createBuffer","RangeError","buf","Object","setPrototypeOf","prototype","arg","encodingOrOffset","TypeError","allocUnsafe","from","string","encoding","isEncoding","byteLength","actual","slice","fromString","ArrayBuffer","isView","arrayView","isInstance","copy","fromArrayBuffer","byteOffset","fromArrayLike","fromArrayView","SharedArrayBuffer","valueOf","b","obj","isBuffer","checked","undefined","numberIsNaN","type","isArray","data","fromObject","toPrimitive","assertSize","size","array","toString","mustMatch","arguments","loweredCase","utf8ToBytes","base64ToBytes","toLowerCase","slowToString","this","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","swap","n","bidirectionalIndexOf","val","dir","arrayIndexOf","call","lastIndexOf","indexSize","arrLength","valLength","String","readUInt16BE","foundIndex","found","j","hexWrite","Number","remaining","strLen","parsed","parseInt","substr","utf8Write","blitBuffer","asciiWrite","str","byteArray","asciiToBytes","base64Write","ucs2Write","units","hi","lo","utf16leToBytes","fromByteArray","min","res","firstByte","codePoint","bytesPerSequence","secondByte","thirdByte","fourthByte","tempCodePoint","codePoints","MAX_ARGUMENTS_LENGTH","fromCharCode","apply","decodeCodePointsArray","kMaxLength","TYPED_ARRAY_SUPPORT","proto","foo","typedArraySupport","console","error","defineProperty","enumerable","get","poolSize","fill","allocUnsafeSlow","_isBuffer","compare","a","x","y","concat","list","pos","set","swap16","swap32","swap64","toLocaleString","equals","inspect","max","replace","trim","target","thisStart","thisEnd","thisCopy","targetCopy","includes","isFinite","toJSON","_arr","ret","out","hexSliceLookupTable","bytes","checkOffset","ext","checkInt","wrtBigUInt64LE","checkIntBI","BigInt","wrtBigUInt64BE","checkIEEE754","writeFloat","littleEndian","noAssert","writeDouble","newBuf","subarray","readUintLE","readUIntLE","mul","readUintBE","readUIntBE","readUint8","readUInt8","readUint16LE","readUInt16LE","readUint16BE","readUint32LE","readUInt32LE","readUint32BE","readUInt32BE","readBigUInt64LE","defineBigIntMethod","validateNumber","first","last","boundsError","readBigUInt64BE","readIntLE","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readInt32BE","readBigInt64LE","readBigInt64BE","readFloatLE","readFloatBE","readDoubleLE","readDoubleBE","writeUintLE","writeUIntLE","writeUintBE","writeUIntBE","writeUint8","writeUInt8","writeUint16LE","writeUInt16LE","writeUint16BE","writeUInt16BE","writeUint32LE","writeUInt32LE","writeUint32BE","writeUInt32BE","writeBigUInt64LE","writeBigUInt64BE","writeIntLE","limit","sub","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32LE","writeInt32BE","writeBigInt64LE","writeBigInt64BE","writeFloatLE","writeFloatBE","writeDoubleLE","writeDoubleBE","targetStart","copyWithin","errors","E","sym","getMessage","Base","constructor","super","writable","configurable","name","stack","message","addNumericalSeparator","range","ERR_OUT_OF_RANGE","checkBounds","ERR_INVALID_ARG_TYPE","ERR_BUFFER_OUT_OF_BOUNDS","input","msg","received","isInteger","INVALID_BASE64_RE","leadSurrogate","toByteArray","split","base64clean","src","dst","alphabet","table","i16","fn","BufferBigIntNotDefined","lookupTable","create","o","lookUpTable","Uint32Array","lengths","exists","instance","checkFinished","destroyed","finished","crypto","globalThis","createView","DataView","rotr","word","shift","TextEncoder","encode","toBytes","abytes","Hash$1","clone","_cloneInto","wrapConstructor","hashCons","hashC","update","digest","outputLen","blockLen","randomBytes","bytesLength","getRandomValues","Chi","Maj","HashMD","Hash","padOffset","view","take","process","dataView","roundClean","digestInto","setBigUint64","_32n","_u32_max","wh","wl","h","l","setUint32","oview","outLen","state","destroy","to","SHA256_K","SHA256_IV","SHA256_W","SHA256","A","B","C","D","F","G","H","getUint32","W15","W2","s0","s1","T1","T2","SHA224","sha256","sha224","JSON_KEY_PRINCIPAL","Principal$3","Principal","_isPrincipal","anonymous","managementCanister","fromHex","selfAuthenticating","publicKey","sha","jsSha224","other","fromText","getPrototypeOf","JSON","stringify","hex","hexString","_a","match","map","byte","fromHexString","text","maybePrincipal","parse","skip","decodeChar","char","decode","principal","toText","fromUint8Array","isAnonymous","toUint8Array","toHex","reduce","padStart","toHexString","toUpperCase","checksumArrayBuf","crc","getCrc32","checksum","result","bits","matches","JSON_KEY_PRINCIPAL$2","compareTo","ltEq","cmp","gtEq","buffers","acc","curr","index","hexRe","RegExp","test","PipeArrayBuffer$2","_buffer","bufFromBufLike","_view","amount","v","uint8ToBuf","bufLike","eob","safeReadUint8","pipe","lebEncode","ceil","log2","Pipe","slebEncode","isNeg","getLowerBytes","iexp2","nBig","Type$3","display","valueToString","toReadableString","buildTypeTable","typeTable","has","_buildTypeTableImpl","Type","checkType","t","RecClass","ty","getType","encodeType","PrimitiveType","_bits","accept","visitFloat","covariant","encodeValue","setFloat32","setFloat64","decodeValue","getFloat32","getFloat64","visitFixedInt","ok","visitFixedNat","ConstructType","_id","_counter","_type","visitRec","add","merge","_key","substring","toReadableString_max","FloatClass","FixedIntClass","FixedNatClass","globalObject","BigNumber","isNumeric","mathceil","mathfloor","bignumberError","tooManyDigits","BASE","LOG_BASE","MAX_SAFE_INTEGER","POWS_TEN","SQRT_BASE","MAX","bitFloor","coeffToString","z","r","xc","yc","k","intCheck","isOdd","toExponential","charAt","toFixedPoint","zs","configObject","div","convertBase","parseNumeric","pow2_53","random53bitInt","basePrefix","dotAfter","dotBefore","isInfinityOrNaN","whitespaceOrPlus","P","ONE","DECIMAL_PLACES","ROUNDING_MODE","TO_EXP_NEG","TO_EXP_POS","MIN_EXP","MAX_EXP","CRYPTO","MODULO_MODE","POW_PRECISION","FORMAT","prefix","groupSize","secondaryGroupSize","groupSeparator","decimalSeparator","fractionGroupSize","fractionGroupSeparator","suffix","ALPHABET","alphabetHasNormalDecimalDigits","caseChanged","isNum","_isBigNumber","search","round","DEBUG","format","rm","id","c0","ne","maxOrMin","args","normalise","pop","sd","ni","rd","pows10","ROUND_UP","ROUND_DOWN","ROUND_CEIL","ROUND_FLOOR","ROUND_HALF_UP","ROUND_HALF_DOWN","ROUND_HALF_EVEN","ROUND_HALF_CEIL","ROUND_HALF_FLOOR","EUCLID","config","p","hasOwnProperty","EXPONENTIAL_AT","RANGE","isBigNumber","maximum","minimum","random","dp","rand","splice","sum","plus","decimal","toBaseOut","baseIn","baseOut","arrL","reverse","sign","callerIsToString","multiply","base","temp","xlo","xhi","carry","klo","khi","aL","bL","subtract","more","prod","prodL","q","qc","rem","remL","rem0","xi","xL","yc0","yL","yz","p1","p2","absoluteValue","comparedTo","decimalPlaces","dividedBy","dividedToIntegerBy","idiv","exponentiatedBy","half","isModExp","nIsBig","nIsNeg","nIsOdd","mod","times","integerValue","isEqualTo","eq","isGreaterThan","gt","isGreaterThanOrEqualTo","gte","isLessThan","lt","isLessThanOrEqualTo","lte","isNegative","isPositive","isZero","minus","xLTy","xe","ye","modulo","multipliedBy","xcL","ycL","ylo","yhi","zc","sqrtBase","negated","precision","shiftedBy","squareRoot","sqrt","rep","toFixed","toFormat","g1","g2","intPart","fractionPart","intDigits","toFraction","md","d0","d1","d2","exp","n0","n1","toNumber","toPrecision","module","self","window","utils$3","constants$2","Bignumber","constants","MT","POS_INT","NEG_INT","BYTE_STRING","UTF8_STRING","ARRAY","MAP","TAG","SIMPLE_FLOAT","DATE_STRING","DATE_EPOCH","POS_BIGINT","NEG_BIGINT","DECIMAL_FRAC","BIGFLOAT","BASE64URL_EXPECTED","BASE64_EXPECTED","BASE16_EXPECTED","CBOR","URI","BASE64URL","BASE64","REGEXP","MIME","NUMBYTES","ZERO","TWO","FOUR","EIGHT","INDEFINITE","SIMPLE","FALSE","TRUE","NULL","UNDEFINED","SYMS","PARENT","BREAK","STREAM","SHIFT32","SHIFT16","MAX_SAFE_HIGH","NEG_ONE","TEN","OBJECT","require$$2","parseHalf","mant","arrayBufferToBignumber","buildMap","Map","keys","buildInt32","f","g","buildInt64","f1","f2","writeHalf","u32","u","s16","keySorter","lenA","lenB","isNegativeZero","nextPowerOf2","count","simple","Simple","encodeCBOR","gen","_pushInt","isSimple","hasParent","tagged","Tagged","tag","err","_pushTag","pushAny","convert","converters","er","defaultBase","location","protocol","host","URL","urlBrowser","URLWithLegacySupport","url","path","pathname","auth","username","password","query","startsWith","hash","hostname","href","origin","port","searchParams","createObjectURL","revokeObjectURL","URLSearchParams","userPass","isoUrl","relative","protocolMap","defaultProtocol","urlParsed","assign","parser","stdlib","foreign","heap","pushInt","pushInt32","pushInt32Neg","pushInt64","pushInt64Neg","pushFloat","pushFloatSingle","pushFloatDouble","pushTrue","pushFalse","pushUndefined","pushNull","pushInfinity","pushInfinityNeg","pushNaN","pushNaNNeg","pushArrayStart","pushArrayStartFixed","pushArrayStartFixed32","pushArrayStartFixed64","pushObjectStart","pushObjectStartFixed","pushObjectStartFixed32","pushObjectStartFixed64","pushByteString","pushByteStringStart","pushUtf8String","pushUtf8StringStart","pushSimpleUnassigned","pushTagStart","pushTagStart4","pushTagStart8","pushTagUnassigned","pushBreak","inputLength","jumpTable","readUInt16","readUInt32","INT_P","octet","UINT_P_8","UINT_P_16","UINT_P_32","UINT_P_64","INT_N","UINT_N_8","UINT_N_16","UINT_N_32","UINT_N_64","step","BYTE_STRING_8","BYTE_STRING_16","BYTE_STRING_32","BYTE_STRING_64","BYTE_STRING_BREAK","UTF8_STRING_8","UTF8_STRING_16","UTF8_STRING_32","UTF8_STRING_64","UTF8_STRING_BREAK","ARRAY_8","ARRAY_16","ARRAY_32","ARRAY_64","ARRAY_BREAK","MAP_8","MAP_16","MAP_32","MAP_64","MAP_BREAK","TAG_KNOWN","TAG_BIGNUM_POS","TAG_BIGNUM_NEG","TAG_FRAC","TAG_BIGNUM_FLOAT","TAG_UNASSIGNED","TAG_BASE64_URL","TAG_BASE64","TAG_BASE16","TAG_MORE_1","TAG_MORE_2","TAG_MORE_4","TAG_MORE_8","SIMPLE_UNASSIGNED","SIMPLE_FALSE","SIMPLE_TRUE","SIMPLE_NULL","SIMPLE_UNDEFINED","SIMPLE_BYTE","SIMPLE_FLOAT_HALF","SIMPLE_FLOAT_SINGLE","SIMPLE_FLOAT_DOUBLE","ERROR","utils","require$$4","require$$5","require$$6","require$$7","require$$8","Decoder$1","Decoder","opts","_heap","_heap8","_reset","_knownTags","Date","tags","global","bind","_depth","_parents","_currentParent","_ref","ref","_closeParent","_push","createTag","createByteString","createUtf8String","values","createMap","createObject","createArray","_dec","hasChildren","tmpKey","_createParent","_res","tagNumber","typ","raw","createByteStringFromHeap","createInt","createInt32","createInt64","createFloat","createFloatSingle","createFloatDouble","createInt32Neg","createInt64Neg","createTrue","createFalse","createNull","createUndefined","createInfinity","createInfinityNeg","createNaN","createNaNNeg","createUtf8StringFromHeap","createSimpleUnassigned","_createArrayStartFixed","len1","len3","len4","_createObjectStartFixed","_decode","decodeFirst","decodeAll","enc","decoder","Diagnose","fl","collectObject","diagnose","key","require$$3","HALF","FLOAT","DOUBLE","MAXINT_BN","BUF_NAN","BUF_INF_NEG","BUF_INF_POS","Encoder","options","streaming","stream","onData","semanticTypes","_pushUrl","_pushBigNumber","addTypes","genTypes","addSemanticType","fun","old","resultMethod","resultLength","finalize","pushWrite","method","_pushUInt8","_pushUInt16BE","_pushUInt32BE","_pushDoubleBE","_pushNaN","_pushInfinity","_pushFloat","b2","b4","mt","orig","_pushIntNum","_pushNumber","_pushString","_pushBoolean","_pushUndefined","_pushArray","_pushDate","_pushBuffer","_pushNoFilter","_pushRegexp","source","_pushSet","_pushBigint","dec","slide","_pushMap","_pushRawMap","_pushObject","keyLength","sort","toType","encoder","leveldb","hashValue","borc","hashString","toHash","hashOfMap","requestIdOf","request","hashed","entries","filter","sorted","k1","k2","b1","u1","u2","__rest","getOwnPropertySymbols","propertyIsEnumerable","domainSeparator","SignIdentity$1","getPrincipal","_principal","getPublicKey","toDer","transformRequest","body","fields","requestId","content","sender_pubkey","sender_sig","AnonymousIdentity$1","src$1","serializer$3","MAX_U64_NUMBER","_concat","newBuffer","_serializeValue","major","minor","_serializeNumber","_serializeString","utf8","charcode","uSmall","u8","radix","u16","u64","iSmall","i8","i32","i64","done","newI64","reduceRight","true_","false_","number","items","stable","keyA","keyB","localeCompare","singleFloat","single","Float32Array","doubleFloat","Float64Array","bool","null_","undefined_","__importStar","__esModule","serializer","cbor","BufferClasses","Uint16Array","Int8Array","Int16Array","Int32Array","JsonDefaultCborEncoder","_serializer","_stable","priority","serializeValue","find","getOwnPropertyNames","item","ToCborEncoder","toCBOR","CborSerializer","_encoders","Set","withDefaultEncoders","addEncoder","removeEncoder","delete","getEncoderFor","chosenEncoder","serialize","SelfDescribeCborSerializer","__export","CborTag","cbor.value","SubmitRequestType","_0n","_1n","_2n","isBytes","hexes","_","bytesToHex","hexToNumber","asciis","_0","_9","_A","_F","_f","asciiToBase16","hexToBytes","hl","al","ai","n2","bytesToNumberBE","bytesToNumberLE","numberToBytesBE","numberToBytesLE","ensureBytes","title","expectedLength","concatBytes","arrays","pad","bitLen","bitGet","bitMask","validatorFns","bigint","function","boolean","stringOrUint8Array","isSafeInteger","field","object","Fp","isValid","validateObject","validators","optValidators","checkField","fieldName","isOptional","checkVal","_3n","_4n","_5n","_8n","power","pow2","invert","FpSqrt","p1div4","root","eql","sqr","c1","nv","legendreC","Q","S","Z","Q1div2","neg","t2","ge","tonelliShanks","FIELD_FIELDS","validateField","ORDER","MASK","BYTES","BITS","FpPow","FpInvertBatch","nums","lastMultiplied","is0","inverted","inv","nLength","nBitLength","_nBitLength","nByteLength","Field","redef","sqrtP","freeze","lhs","rhs","sqrN","addN","subN","mulN","invertBatch","lst","cmov","fromBytes","getFieldBytesLength","fieldOrder","bitLength","getMinHashLength","os2ip","i2osp","strxor","anum","hash_to_field","DST","expand","_DST","log2p","L","len_in_bytes","prb","lenInBytes","b_in_bytes","r_in_bytes","ell","DST_prime","Z_pad","l_i_b_str","b_0","expand_message_xmd","dkLen","expand_message_xof","elm_offset","tv","isogenyMap","COEFF","xNum","xDen","yNum","yDen","createHasher","Point","mapToCurve","def","hashToCurve","u0","fromAffine","clearCofactor","assertValidity","encodeToCurve","encodeDST","wNAF","constTimeNegate","condition","negate","W","windows","windowSize","unsafeLadder","elm","double","precomputeWindow","points","precomputes","mask","maxNumber","shiftBy","wbits","offset1","offset2","cond1","cond2","wNAFCached","precomputesMap","transform","_WINDOW_SIZE","comp","validateBasic","curve","Gx","Gy","weierstrassPoints","CURVE","ut.validateObject","allowedPrivateKeyLengths","wrapPrivateKey","isTorsionFree","allowInfinityPoint","endo","beta","splitScalar","validatePointOpts","_c","point","_isCompressed","toAffine","ut.concatBytes","tail","weierstrassEquation","x2","x3","isWithinCurveOrder","assertGE","normPrivateKeyToScalar","ut.isBytes","ut.bytesToHex","ut.bytesToNumberBE","mod.mod","pointPrecomputes","assertPrjPoint","px","py","pz","normalizeZ","toInv","fromPrivateKey","privateKey","_setWindowSize","left","right","hasEvenY","X1","Y1","Z1","X2","Y2","Z2","U1","U2","b3","X3","Y3","Z3","t0","t1","t3","t4","t5","wnaf","multiplyUnsafe","I","k1neg","k2neg","k1p","k2p","scalar","fake","f1p","f2p","multiplyAndAddUnsafe","iz","ax","ay","zz","cofactor","toRawBytes","isCompressed","ProjectivePoint","mapToCurveSimpleSWU","mod.validateField","sqrtRatio","_2n_pow_c1_1","_2n_pow_c1","c2","c3","c4","c5","c6","c7","tv1","tv2","tv3","tv5","tv4","isQR","tvv5","e1","y1","y2","SWUFpSqrtRatio","tv6","_16n","Fp_raw","mod.Field","Fr","Fp2Add","r0","r1","Fp2Subtract","Fp2Multiply","Fp2Square","FP2_ORDER","Fp2","mod.FpPow","mod.FpInvertBatch","factor","candidateSqrt","check","R","FP2_ROOTS_OF_UNITY","divisor","x1","re","re1","im","im1","reim","re2","im2","x0","concatB","mulByNonresidue","multiplyByB","fromBigTuple","tuple","fps","frobeniusMap","FP2_FROBENIUS_COEFFICIENTS","rv1","pair","Fp6Add","r2","Fp6Subtract","Fp6Multiply","Fp6Square","Fp6","fromBigSix","FP6_FROBENIUS_COEFFICIENTS_1","FP6_FROBENIUS_COEFFICIENTS_2","multiplyBy1","multiplyBy01","b0","multiplyByFp2","BLS_X","BLS_X_LEN","Fp12Add","Fp12Subtract","Fp12Multiply","Fp12Square","ab","Fp4Square","a2","second","Fp12","fromBigTwelve","coeff","FP12_FROBENIUS_COEFFICIENTS","multiplyBy014","o0","o1","o4","conjugate","_cyclotomicSquare","c0c0","c0c1","c0c2","c1c0","c1c1","c1c2","t6","t7","t8","t9","_cyclotomicExp","finalExponentiate","t2_t5_pow_q2","t4_t1_pow_q3","t6_t1c_pow_q1","t7_t3c_t1","isogenyMapG2","isogenyMapG1","G2_SWU","G1_SWU","ut_root","wsq","wcu","wsq_inv","wcu_inv","G2psi","affine","PSI2_C1","G2psi2","htfDefaults","COMPRESSED_ZERO","setMask","infinity","compressed","parseMask","signatureG1ToRawBytes","bls12_381","G1","Boolean","signatureG2ToRawBytes","G2","y0","z2","params","calcPairingPrecomputes","Qx","Qy","Rx","Ry","Rz","ell_coeff","millerLoop","Px","Py","f12","randomPrivateKey","fieldLen","minLen","reduced","mapHashToField","G1_","G2_","ShortSignature","Signature","pairing","withFinalExponent","Qa","looped","_PPRECOMPUTES","pairingPrecomputes","normP1","normP1Hash","htfOpts","normP2","normP2Hash","getPublicKeyForShortSignatures","msgPoint","sigPoint","signShortSignature","verify","signature","Hm","ePHm","eGS","verifyBatch","messages","publicKeys","sig","nMessages","nPublicKeys","paired","groupPublicKey","subMessage","product","verifyShortSignature","eHmP","eSG","aggregatePublicKeys","aggAffine","aggregateSignatures","signatures","aggregateShortSignatures","G1b","G2b","bls","cubicRootOfUnityModP","phi","scalars","compressedValue","aflag","hEff","slc","x_1","x_0","Y_bit","flag","z1","aflag1","NodeType","LookupStatus","LabelLookupStatus","U32_MASK64","fromBig","le","Ah","Al","toBig","shrSH","_l","shrSL","rotrSH","rotrSL","rotrBH","rotrBL","rotr32H","_h","rotr32L","rotlSH","rotlSL","rotlBH","rotlBL","Bh","Bl","add3L","Cl","add3H","low","Ch","add4L","Dl","add4H","Dh","add5H","Eh","add5L","El","SHA512_Kh","SHA512_Kl","SHA512_W_H","SHA512_W_L","SHA512","Fh","Fl","Gh","Gl","Hh","Hl","W15h","W15l","s0h","s0l","W2h","W2l","s1h","s1l","SUMl","SUMh","sigma1h","sigma1l","CHIh","CHIl","T1ll","T1h","T1l","sigma0h","sigma0l","MAJh","MAJl","All","sha512","VERIFY_DEFAULT","zip215","twistedEdwards","curveDef","adjustScalarBytes","domain","uvRatio","validateOpts","CURVE_ORDER","prehash","cHash","modP","ctx","phflag","inBig","inRange","in0MaskRange","assertInRange","assertGE0","isPoint","ex","ey","ez","et","X","Y","T","Z4","aX2","X1Z2","X2Z1","Y1Z2","Y2Z1","x1y1","T3","isSmallOrder","normed","lastByte","ut.bytesToNumberLE","isXOdd","isLastByteOdd","privKey","getExtendedPublicKey","ut.numberToBytesLE","modN","modN_LE","head","pointBytes","hashDomainToScalar","context","msgs","verifyOpts","SB","ExtendedPoint","precompute","ED25519_P","ED25519_SQRT_M1","_10n","_20n","_40n","_80n","ed25519Defaults","v3","b5","b10","b20","b40","b80","b160","b240","b250","pow_p_5_8","ed25519_pow_2_252_3","vx2","root1","root2","useRoot1","useRoot2","noRoot","ed25519","ELL2_C1","RequestStatusResponseStatus","ProxyMessageKind","FpSqrtEven","CryptoError$1","CryptoError","_getEffectiveCrypto","subtleCrypto","subtle","ECDSAKeyIdentity","SignIdentity","keyPair","derKey","_keyPair","_derKey","_subtleCrypto","generate","extractable","keyUsages","effectiveCrypto","generateKey","namedCurve","exportKey","fromKeyPair","getKeyPair","challenge","requestDomainSeparator","_parseBlob","Delegation$3","pubkey","expiration","targets","DelegationChain$1","DelegationChain","delegations","now","_b","delegation","async","Delegation","_createSingleDelegation","previous","fromJSON","json","parsedDelegations","signedDelegation","fromDelegations","_inner","_delegation","fromDelegation","getDelegation","blob","sender_delegation","PubKeyCoseAlgo","Principal$2","JSON_KEY_PRINCIPAL$1","bufEquals","AgentError","__proto__","PipeArrayBuffer$1","idlLabelToId","label","idlHash","safeRead","lebDecode","weight","slebDecode","pipeView","magicNumber","zipWith","xs","ys","TypeTable","_typs","_idx","idx","knot","knotIdx","typeName","Type$2","EmptyClass","visitEmpty","UnknownClass","visitType","typeFunc","decodedValue","BoolClass","visitBool","NullClass","visitNull","ReservedClass","visitReserved","TextClass","visitText","TextDecoder","fatal","IntClass","visitInt","NatClass","visitNat","VecClass","_blobOptimization","visitVec","BYTES_PER_ELEMENT","every","encoded","opCode","vec","BigUint64Array","BigInt64Array","rets","OptClass","visitOpt","opt","RecordClass","_fields","visitRecord","tryAsTuple","bufs","forEach","record","expectedRecordIdx","actualRecordIdx","expectKey","expectType","expectedId","actualId","TupleClass","_components","visitTuple","wireType","VariantClass","visitVariant","variant","wireHash","decodePrincipalId","PrincipalId","PrincipalClass","visitPrincipal","FuncClass","argTypes","retTypes","annotations","argsToString","types","visitFunc","methodName","canister","methodLen","argLen","retLen","annLen","anns","encodeAnnotation","ann","ServiceClass","visitService","func","meths","labelBuf","magic","typs","vals","magicBuffer","rawTable","rawTypes","prevHash","objectLength","argLength","returnValues","returnValuesLength","annotationLength","servLength","methods","nameLength","funcName","funcType","rawList","readTypeTable","Rec","Null","Bool","Nat","Int","Nat8","Nat16","Nat32","Nat64","Int8","Int16","Int32","Int64","Float32","Float64","Text","Reserved","Empty","buildType","entry","Vec","Opt","Record","Tuple","Variant","Func","rec","typeRef","Service","ind","Unknown","IDL","ConstructType$1","Empty$1","FixedIntClass$1","FixedNatClass$1","FloatClass$1","Null$1","PrimitiveType$1","Principal$1","RecClass$1","Record$1","Tuple$1","Unknown$1","Visitor","visitPrimitive","visitNumber","visitConstruct","components","decode$2","encode$2","AnonymousIdentity","decodePositiveBigInt","Uint8ArrayDecoder$1","Uint8ArrayDecoder","Semantic","randomNumber","randomInt","makeNonce","rand1","rand2","rand3","rand4","NANOSECONDS_PER_MILLISECONDS","Expiry","deltaInMSec","ingress_as_seconds","_value","rounded_down_nanos","makeNonceTransform","nonceFn","headers","endpoint","nonce","httpHeadersTransform","headerFields","AgentHTTPResponseError","response","blsVerify","pk","primaryKey","decodeLeb128","PipeArrayBuffer","decodeTime","decoded","CertificateVerificationError","reason","Certificate","certificate","_rootKey","_canisterId","_blsVerify","_maxAgeInMinutes","cert","cbor.decode","createUnverified","bls.blsVerify","rootKey","canisterId","maxAgeInMinutes","lookup_path","tree","lookup_label","rootHash","reconstruct","_checkDelegationAndGetKey","DER_PREFIX","KEY_LENGTH","extractDER","domain_sep","sigVer","lookupTime","lookupResultToBuffer","MAX_AGE_IN_MSEC","earliestCertificateTime","fiveMinutesFromNow","certTime","getTime","toISOString","MANAGEMENT_CANISTER_ID","check_canister_ranges","subnetId","subnet_id","publicKeyLookup","status","Found","Pruned","Leaf","Labeled","Fork","lookupResult","find_label","Greater","Less","Absent","flatten_forks","a8","b8","isBufferGreaterThan","leftLookupResult","rightLookupResult","rangeLookup","some","agent","paths","uniquePaths","encodedPaths","encodePath","promises","readState","fetchNodeKeys","decodeControllers","decodeHex","decodeStrategy","decodeCbor","decodeUtf8","warn","group","groupEnd","Promise","all","root_key","Cbor.decode","subnetLookupResult","nodeForks","nodeKeys","fork","node_id","publicKeyLookupResult","derEncodedPublicKey","canisterBuffer","metaPath","_ExpirableMap_inner","_ExpirableMap_expirationTime","CustomPath","__classPrivateFieldSet","receiver","kind","__classPrivateFieldGet","ExpirableMap","expirationTime","currentTime","timestamp","prune","clear","iterator","generator","callbackfn","thisArg","WeakMap","toStringTag","encodeLenBytes","encodeLen","decodeLenBytes","ED25519_OID","unwrapDER","derEncoded","oid","expect","payloadLen","lenBytes","decodeLen","_Ed25519PublicKey_rawKey","_Ed25519PublicKey_derKey","Ed25519PublicKey","RAW_KEY_LENGTH","derEncode","fromDer","fromRaw","rawKey","derDecode","payload","bitStringHeaderLength","wrapDER","unwrapped","toRaw","Observable","observers","subscribe","unsubscribe","observer","notify","rest","ObservableLog","print","level","_ExponentialBackoff_currentInterval","_ExponentialBackoff_randomizationFactor","_ExponentialBackoff_multiplier","_ExponentialBackoff_maxInterval","_ExponentialBackoff_startTime","_ExponentialBackoff_maxElapsedTime","_ExponentialBackoff_maxIterations","_ExponentialBackoff_date","_ExponentialBackoff_count","RANDOMIZATION_FACTOR","MULTIPLIER","INITIAL_INTERVAL_MSEC","MAX_INTERVAL_MSEC","MAX_ELAPSED_TIME_MSEC","MAX_ITERATIONS","ExponentialBackoff","default","initialInterval","randomizationFactor","multiplier","maxInterval","maxElapsedTime","maxIterations","date","ellapsedTimeInMsec","currentInterval","randomValueFromInterval","delta","incrementCurrentInterval","next","DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS","_HttpAgent_instances","_HttpAgent_identity","_HttpAgent_fetch","_HttpAgent_fetchOptions","_HttpAgent_callOptions","_HttpAgent_timeDiffMsecs","_HttpAgent_credentials","_HttpAgent_rootKeyFetched","_HttpAgent_retryTimes","_HttpAgent_backoffStrategy","_HttpAgent_maxIngressExpiryInMinutes","_HttpAgent_waterMark","_HttpAgent_queryPipeline","_HttpAgent_updatePipeline","_HttpAgent_subnetKeys","_HttpAgent_verifyQuerySignatures","_HttpAgent_requestAndRetryQuery","_HttpAgent_requestAndRetry","_HttpAgent_verifyQueryResponse","MINUTE_TO_MSECS","HttpDefaultFetchError","IdentityInvalidError","HttpAgent","_isAgent","queryResponse","subnetStatus","identity","nodeId","reply","request_id","reject_code","reject_message","error_code","separatorWithHash","pubKey","fetch","defaultFetch","getDefaultFetch","fetchOptions","callOptions","configuredHost","knownHosts","remoteHosts","knownHost","endsWith","determineHost","verifyQuerySignatures","retryTimes","backoffStrategy","credentials","resolve","ingressExpiryInMinutes","addTransform","useQueryNonces","logToConsole","waterMark","createSync","shouldFetchRootKey","initPromises","syncTime","fetchRootKey","_fetch","_fetchOptions","_callOptions","_host","_identity","isLocal","findIndex","callSync","ecid","effectiveCanisterId","sender","ingress_expiry","submit","request_type","Call","canister_id","method_name","transformedRequest","_transform","Authorization","btoa","cbor.encode","backoff","requestSync","requestAsync","tries","responseBuffer","arrayBuffer","responseBody","time","parseTimeFromResponse","statusText","requestDetails","queryResult","makeQuery","fetchSubnetKeys","getSubnetStatus","queryWithDetails","updatedSubnetStatus","createReadStateRequest","decodedResponse","parsedTime","timeLookup","CanisterStatus","callTime","replicaTime","invalidateIdentity","replaceIdentity","subnetResponse","then","getDefaultAgent","ic","WeakSet","delay","setTimeout","fetchResponse","httpDetails","timeStampInMs","responseText","errorMessage","FIVE_MINUTES_IN_MSEC","defaultStrategy","strategies","chain","once","timeInMsec","startingThrottleInMsec","backoffFactor","currentThrottling","timeout","hasProperty","property","pollForResponse","strategy","currentRequest","isSignedReadStateRequestWithExpiry","maybeBuf","Replied","Received","Processing","Rejected","rejectCode","rejectMessage","Done","managementCanisterIdl","bitcoin_network","mainnet","testnet","bitcoin_address","bitcoin_get_balance_args","network","address","min_confirmations","satoshi","bitcoin_get_balance_result","bitcoin_block_height","bitcoin_get_block_headers_args","start_height","end_height","bitcoin_block_header","bitcoin_get_block_headers_result","tip_height","block_headers","bitcoin_get_current_fee_percentiles_args","millisatoshi_per_byte","bitcoin_get_current_fee_percentiles_result","bitcoin_get_utxos_args","page","bitcoin_block_hash","outpoint","txid","vout","utxo","height","bitcoin_get_utxos_result","next_page","tip_block_hash","utxos","bitcoin_send_transaction_args","transaction","canister_info_args","num_requested_changes","change_origin","from_user","user_id","from_canister","canister_version","snapshot_id","change_details","creation","controllers","code_deployment","mode","reinstall","upgrade","install","module_hash","load_snapshot","taken_at_timestamp","controllers_change","code_uninstall","change","timestamp_nanos","details","canister_info_result","recent_changes","total_num_changes","canister_status_args","log_visibility","public","definite_canister_settings","freezing_threshold","reserved_cycles_limit","wasm_memory_limit","memory_allocation","compute_allocation","canister_status_result","stopped","stopping","running","memory_size","cycles","settings","query_stats","response_payload_bytes_total","num_instructions_total","num_calls_total","request_payload_bytes_total","idle_cycles_burned_per_day","reserved_cycles","clear_chunk_store_args","canister_settings","create_canister_args","sender_canister_version","create_canister_result","delete_canister_args","delete_canister_snapshot_args","deposit_cycles_args","ecdsa_curve","secp256k1","ecdsa_public_key_args","key_id","derivation_path","ecdsa_public_key_result","public_key","chain_code","fetch_canister_logs_args","canister_log_record","fetch_canister_logs_result","canister_log_records","http_header","http_request_result","http_request_args","post","max_response_bytes","canister_install_mode","wasm_memory_persistence","keep","skip_pre_upgrade","chunk_hash","install_chunked_code_args","wasm_module_hash","chunk_hashes_list","target_canister","store_canister","wasm_module","install_code_args","list_canister_snapshots_args","snapshot","total_size","list_canister_snapshots_result","load_canister_snapshot_args","node_metrics_history_args","start_at_timestamp_nanos","node_metrics","num_block_failures_total","num_blocks_proposed_total","node_metrics_history_result","provisional_create_canister_with_cycles_args","specified_id","provisional_create_canister_with_cycles_result","provisional_top_up_canister_args","raw_rand_result","schnorr_algorithm","bip340secp256k1","schnorr_public_key_args","algorithm","schnorr_public_key_result","sign_with_ecdsa_args","message_hash","sign_with_ecdsa_result","sign_with_schnorr_args","sign_with_schnorr_result","start_canister_args","stop_canister_args","stored_chunks_args","stored_chunks_result","take_canister_snapshot_args","replace_snapshot","take_canister_snapshot_result","uninstall_code_args","update_settings_args","upload_chunk_args","chunk","upload_chunk_result","bitcoin_get_balance","bitcoin_get_block_headers","bitcoin_get_current_fee_percentiles","bitcoin_get_utxos","bitcoin_send_transaction","canister_info","canister_status","clear_chunk_store","create_canister","delete_canister","delete_canister_snapshot","deposit_cycles","ecdsa_public_key","fetch_canister_logs","http_request","install_chunked_code","install_code","list_canister_snapshots","load_canister_snapshot","node_metrics_history","provisional_create_canister_with_cycles","provisional_top_up_canister","raw_rand","schnorr_public_key","sign_with_ecdsa","sign_with_schnorr","start_canister","stop_canister","stored_chunks","take_canister_snapshot","uninstall_code","update_settings","upload_chunk","ActorCallError","props","QueryCallRejectedError","Status","Code","Message","UpdateCallRejectedError","metadataSymbol","for","Actor","metadata","agentOf","actor","interfaceOf","service","canisterIdOf","wasmModule","getManagementCanister","createCanister","settingsToCanisterSettings","createAndInstallCanister","interfaceFactory","createActor","createActorClass","DEFAULT_ACTOR_CONFIG","ACTOR_METHOD_WITH_HTTP_DETAILS","ACTOR_METHOD_WITH_CERTIFICATE","_createActorMethod","configuration","createActorWithHttpDetails","createActorWithExtendedDetails","actorClassOptions","decodeReturnValue","IDL.decode","pollingStrategyFactory","strategy.defaultStrategy","caller","queryTransform","cid","IDL.encode","callTransform","error_code_buf","pollStrategy","shouldIncludeHttpDetails","shouldIncludeCertificate","handler","withOptions","instanceOfAny","constructors","idbProxyableTypes","cursorAdvanceMethods","cursorRequestMap","transactionDoneMap","transactionStoreNamesMap","transformCache","reverseTransformCache","idbProxyTraps","prop","IDBTransaction","objectStoreNames","objectStore","wrap","wrapFunction","IDBDatabase","IDBCursor","advance","continue","continuePrimaryKey","unwrap","storeNames","tx","transformCachableValue","reject","unlisten","removeEventListener","complete","DOMException","addEventListener","cacheDonePromiseForTransaction","IDBObjectStore","IDBIndex","Proxy","IDBRequest","promise","success","catch","promisifyRequest","newValue","openDB","version","blocked","blocking","terminated","indexedDB","open","openPromise","event","oldVersion","newVersion","db","deleteDB","deleteDatabase","readMethods","writeMethods","cachedMethods","getMethod","targetFuncName","useIndex","isWrite","storeName","store","callback","AuthProvider","bigIntMax","toBigInt32","toBigInt64","chatIdentifierToString","chatId","userId","groupId","communityId","channelId","UnsupportedValueError","oldTraps","Type$1","Delegation$2","DelegationIdentity","AUTH_DB_NAME","OBJECT_STORE_NAME","IdbKeyVal","_db","_storeName","dbName","DB_VERSION","isBrowser","localStorage","getItem","KEY_STORAGE_DELEGATION","removeItem","KEY_STORAGE_KEY","database","contains","createObjectStore","_openDbStore","put","_setValue","_getValue","remove","_removeValue","_IdbStorage_options","IdbStorage","initializedDb","KEY_STORAGE_AUTH_PRINCIPAL","IdentityStorage","storage","createForAuthIdentity","createForOcIdentity","authPrincipal","storedAuthPrincipal","chainJson","scopes","scope","none","isDelegationValid","Lazy","initFn","rollbar_umd_min","Function","strictMode","strict","loose","addParamsAndAccessTokenToPath","access_token","createItem","w","extraArgs","custom","notifier","diagnostic","uuid","skipFrames","lambdaContext","_originalArgs","original_arg_types","addErrorContext","rollbarContext","error_context","createTelemetryEvent","filterIp","user_ip","formatArgsAsString","formatUrl","handleOptions","hostWhiteList","hostSafeList","hostBlackList","hostBlockList","overwriteScrubFields","scrubFields","isError","isFiniteNumber","isFunction","isIterable","isNativeFunction","isObject","isString","isType","isPromise","jsonParse","LEVELS","debug","info","warning","critical","makeUnhandledStackInfo","line","column","guessFunctionName","gatherContext","document","navigator","userAgent","useragent","redact","RollbarJSON","sanitizeUrl","exec","anchor","setupJSON","maxByteSize","uuid4","unshift","ieVersion","_stackFrame","fileName","lineNumber","functionName","columnNumber","rawStack","rawException","guessErrorClass","nested","cause","traceChain","Stack","Frame","mapped","_rollbarConfig","globalAlias","shimId","_rollbarStartTime","rollbar","_rollbarDidLoad","setComponents","telemeter","instrumenter","polyfillJSON","wrapGlobals","scrub","truncation","_configuredOptions","client","isChrome","chrome","runtime","anonymousErrorsPending","handleDomException","handleItemWithError","ensureItemHasSomethingToSay","addBaseInfo","addRequestInfo","addClientInfo","addPluginInfo","addBody","addMessageWithError","addTelemetryData","addConfigToPayload","addScrubber","addPayloadOptions","userTransform","addConfiguredOptions","addDiagnosticKeys","itemToPayload","queue","addPredicate","checkLevel","checkIgnore","userCheckIgnore","urlIsNotBlockListed","urlIsSafeListed","messageIsIgnored","setupUnhandledCapture","instrument","init","configure","lastError","_createItem","buildJsonPayload","sendJsonPayload","unhandledExceptionsInitialized","captureUncaught","handleUncaughtExceptions","captureUncaughtExceptions","wrapGlobalEventHandlers","unhandledRejectionsInitialized","captureUnhandledRejections","handleUnhandledRejections","handleUncaughtException","inspectAnonymousErrors","_unhandledStackInfo","stackInfo","uncaughtErrorLevel","_isUncaught","handleAnonymousErrors","prepareStackTrace","_isAnonymous","handleUnhandledRejection","_rollbarContext","_isWrap","_rollbar_wrapped","_rollbarWrappedError","_wrappedSource","captureEvent","captureDomContentLoaded","captureLoad","loadFull","logLevel","reportLevel","verbose","enabled","transmit","sendConfig","includeItemsInTelemetry","captureIp","ignoreDuplicateErrors","logger","rateLimiter","configureGlobal","setPlatformOptions","api","tracer","lastErrorHash","stackTraceLimit","active","maxItems","itemsPerMinute","_defaultLogLevel","_log","wait","postJsonPayload","_sameAsLastError","_addTracingInfo","_captureRollbarItem","telemetryEvents","copyEvents","toSpanId","toTraceId","setTag","opentracing_span_id","opentracing_trace_id","startTime","counter","perMinCounter","platform","platformOptions","ignoreRateLimit","extra","language","environment","framework","shouldSend","globalSettings","predicates","pendingItems","pendingRequests","retryQueue","retryHandle","waitCallback","waitIntervalID","addPendingItem","removePendingItem","addItem","_applyPredicates","stop","_maybeLog","_makeApiRequest","_dequeuePendingRequest","_maybeCallWait","clearInterval","setInterval","postItem","_maybeRetry","retryInterval","maxRetries","retries","_retryApiRequest","transforms","_applyTransforms","transport","jsonBackup","accessToken","transportOptions","getTransportFromOptions","buildPayload","truncate","oldOptions","defaultTransport","XMLHttpRequest","proxy","appendPathToPath","createElement","getElementsByTagName","innerHTML","_rollbarOldOnError","onerror","_rollbarURH","belongsToShim","detail","_makeZoneRequest","Zone","current","_name","_parent","run","_makeRequest","RollbarProxy","AbortController","abort","signal","clearTimeout","ActiveXObject","readyState","setRequestHeader","onreadystatechange","send","XDomainRequest","onprogress","ontimeout","onload","description","exception","class","frames","filename","lineno","colno","sendFrameUrl","pre","_savedStackTrace","server","query_string","screen","runtime_ms","javascript","browser","cookie_enabled","cookieEnabled","width","plugins","trace_chain","trace","scrubPaths","stacktrace","parseOpera","parseV8OrIE","parseFFOrSafari","extractLocation","parseOpera9","parseOpera11","parseOpera10","getArgs","setArgs","getEvalOrigin","evalOrigin","setEvalOrigin","getFileName","getLineNumber","getColumnNumber","getFunctionName","getIsEval","parseFloat","configured_options","is_anonymous","is_uncaught","raw_error","constructor_name","failed","onSendCallback","ignoredMessages","itemsPerMin","maxTelemetryEvents","maxQueueSize","manual","filterTelemetry","capture","timestamp_ms","captureError","captureLog","captureNetwork","subtype","levelFromStatus","status_code","captureDom","element","captureNavigation","captureConnectivityChange","networkResponseHeaders","networkResponseBody","networkRequestHeaders","networkRequestBody","networkErrorOnHttp5xx","networkErrorOnHttp4xx","networkErrorOnHttp0","dom","navigation","connectivity","contentSecurityPolicy","errorOnContentSecurityPolicy","autoInstrument","scrubTelemetryInputs","telemetryScrubber","defaultValueScrubber","attributes","_window","_document","replacements","eventRemovers","contentsecuritypolicy","_location","_lastHref","deinstrumentNetwork","instrumentNetwork","deinstrumentConsole","instrumentConsole","deinstrumentDom","instrumentDom","deinstrumentNavigation","instrumentNavigation","deinstrumentConnectivity","instrumentConnectivity","deinstrumentContentSecurityPolicy","instrumentContentSecurityPolicy","__rollbar_xhr","start_time_ms","end_time_ms","request_headers","request_content_type","__rollbar_event","response_content_type","getResponseHeader","getAllResponseHeaders","isJsonContentType","scrubJson","errorOnHttpStatus","trackHttpErrors","fetchHeaders","removeListeners","handleClick","handleBlur","addListener","getElementFromEvent","tagName","isDescribedElement","captureDomEvent","handleSelectInputChanged","multiple","selected","selectedIndex","getElementType","describeElement","elementArrayToString","treeToArray","app","history","pushState","handleUrlChange","handleCspEvent","blockedURI","violatedDirective","effectiveDirective","sourceFile","originalPolicy","handleCspError","attachEvent","detachEvent","append","Headers","getAttribute","classes","className","descriptionToString","parentNode","elementFromPoint","clientX","clientY","lastIndex","getUTCFullYear","getUTCMonth","getUTCDate","getUTCHours","getUTCMinutes","getUTCSeconds","go","firstokey","okey","ovalue","firstavalue","avalue","container","ocomma","acomma","colon","SyntaxError","true","false","null","_rollbarOldAdd","_rollbarOldRemove","truncateFrames","truncateStrings","maybeTruncateValue","MAX_MESSAGES","MAX_EVENTS","MAX_MISSING","MIN_DOWNLINK","ONE_DAY","offline","onLine","connection","downlink","SafeMap","_map","agg","empty","toMap","ChatMap","fromList","things","fromMap","MessageContextMap","CommunityMap","MessageMap","getOrAdd","existing","waitAll","results","allSettled","random128","getTimeUntilSessionExpiryMs","HEX_REGEX","isAccountIdentifierValid","isHexString","ProposalDecisionStatus","ProposalRewardStatus","NnsProposalTopic","chatIdentifiersEqual","nullMembership","joined","role","mentions","latestThreads","myMetrics","audioMessages","edits","icpMessages","sns1Messages","ckbtcMessages","giphyMessages","deletedMessages","reportedMessages","fileMessages","pollVotes","textMessages","imageMessages","replies","videoMessages","polls","reactions","notificationsMuted","readByMeUpTo","archived","rulesAccepted","lapsed","HttpError","AuthError","SessionExpiryError","DestinationInvalidError","ResponseTooLargeError","maxSize","InvalidDelegationError","TypeboxValidationError","AnonymousOperationError","StorageUpdated","CustomEvent","UsersLoaded","MessagesReadFromServer","threadsRead","dateReadPinned","codeToText","textToCode","codeStr","bin","atob","ch","base64ToBigint","applyOptionUpdate","original","mapOptionUpdate","mapper","messagePermissionsList","communityPermissionsList","botChatPermissionList","CommonResponses","Stream","initialiser","subscribed","final","onResult","onEnd","onError","subscription","deletedUser","blobUrl","displayName","updated","MAX_VALUE","suspended","diamondStatus","chitBalance","streak","isUniquePerson","totalChitEarned","mergeUserSummaryWithUpdates","cached","updates","volatile","isBot","UserStatus","AvatarSize","ANON_USER_ID","CACHE_VERSION","EARLIEST_SUPPORTED_MIGRATION","MAX_INDEX","clearChatsStore","migrations","createFailedCacheKey","messageId","createCacheKey","threadRootMessageIndex","messageContextToString","padMessageIndex","openCache","previousVersion","deleteObjectStore","chatEvents","createIndex","nuke","migrate","getCachedChats","resolvedDb","chats","latestUserCanisterUpdates","getCachedEvents","eventIndexRange","startIndex","ascending","maxEvents","maxMessages","maxMissing","events","expiredEventRanges","missing","iterateCachedEvents","expiredMessageRanges","latestEventIndex","getCachedEventsWindowByMessageIndex","messageIndex","eventIndex","getNearestCachedEventIndexForMessageIndex","combinedMissing","getCachedEventsWindow","getCachedEventsByIndex","eventIndexes","evt","upperBound","processEventExpiry","IDBKeyRange","bound","getCachedEventByIndex","iterations","cacheKey","cacheKeyUpperBound","getFromIndex","getCachedEventIndexByMessageIndex","mergeSuccessResponses","getIndex","makeSerialisable","ev","removeBlobs","messageKey","removeBlobData","repliesTo","removeReplyContent","dataToBlobUrl","Blob","blobData","sourceContext","removeFailedMessage","recordFailedMessage","loadFailedMessages","getAll","parsedKey","imageData","videoData","setCachedEvents","resp","durability","eventStore","boundaryKeys","setCachedMessageFromSendResponse","sentEvent","transfer","prizesRemaining","prizes","prizesPending","winners","token","endDate","caption","diamondOnly","lifetimeDiamondOnly","uniquePersonOnly","streakOnly","token0","token0Amount","token1","token1Amount","expiresAt","expiresIn","token0TxnIn","blockIndex","swapId","messageToEvent","setCachedMessageIfNotExists","messageEvent","getCachePrimerTimestamps","cursor","openCursor","readAll","setCachePrimerTimestamp","getCachedGroupDetails","setCachedCommunityDetails","communityDetails","setCachedGroupDetails","groupDetails","expiredEventSweeperJob","loadMessagesByMessageIndex","messagesIndexes","msgIdx","messageEvents","makeCommunitySerializable","community","channels","makeChatSummarySerializable","avatar","banner","chat","latestMessage","EventsIterator","messageCount","expectedNextIndex","getNext","remainingMissingCount","endIndex","onComplete","messageContext","startKey","lower","upper","mergeRanges","tryStartExpiredEventSweeper","runExpiredEventSweeper","eventsStore","threadEventsStore","expiredKeys","getAllKeys","thread","threadKey","getCachedCurrentUser","clearCache","close","isMainnet","icUrl","lazyOpenUserCache","_oldVersion","_newVersion","_transaction","getDeletedUserIdsList","setCachedUsers","users","writeCachedUsersToDatabase","KEY","lazyOpenRegistryCache","distinctBy","keyFn","thing","chunkCount","chunks","chunkIndex","toRecord","toRecord2","valFn","ReplicaNotUpToDateError","byTimestamp","replicaTimestamp","clientTimestamp","failedPostCheck","toCanisterResponseError","tooLarge","responseTooLarge","statusLine","valueText","valueParts","cachedSetTimeout","cachedClearTimeout","browserModule","defaultSetTimout","defaultClearTimeout","runTimeout","currentQueue","draining","queueIndex","cleanUpNextTick","drainQueue","marker","runClearTimeout","Item","noop","nextTick","env","argv","versions","on","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","umask","MAX_RETRIES","NODE_ENV","CanisterAgent","canisterName","executeQuery","serviceCall","responseErr","debugInfo","writeTrace","duration","trunc","IsAsyncIterator","IsObject","asyncIterator","IsIterator","IsPromise","IsDate","IsUint8Array","HasPropertyKey","IsArray","IsUndefined","IsNull","IsBoolean","IsNumber","IsInteger","IsBigInt","IsString","IsFunction","IsSymbol","IsValueType","TypeSystemPolicy","IsObjectLike","AllowArrayObject","InstanceMode","ExactOptionalPropertyTypes","AllowNaN","AllowNullVoid","IsExactOptionalProperty","IsRecordLike","IsNumberLike","IsVoidLike","isUndefined","Has","Get","IsRegExp","Immutable","ValueGuard.IsArray","ImmutableArray","ValueGuard.IsDate","ValueGuard.IsUint8Array","ValueGuard.IsRegExp","ValueGuard.IsObject","ImmutableObject","Visit","ArrayType","DateType","Uint8ArrayType","flags","RegExpType","ObjectType","Clone","CreateType","schema","TransformKind","ReadonlyKind","OptionalKind","Hint","Kind","TypeBoxError","MappedResult","properties","Discard","DiscardKey","AsyncIterator","Constructor","parameters","returns","Computed","Never","not","IsReadonly","IsOptional","IsAny","IsKindOf","IsComputed","IsConstructor","IsIntersect","IsLiteralValue","ValueGuard.IsBoolean","ValueGuard.IsNumber","ValueGuard.IsString","IsLiteral","IsMappedKey","IsMappedResult","IsNever","IsRecord","IsRef","IsTemplateLiteral","IsTransform","IsTuple","IsUnion","IsKind","IsSchema","IsNot","IsThis","IsUnknown","IsUnsafe","IsVoid","OptionalWithFlag","RemoveOptional","AddOptional","Optional","enable","Acc","K2","FromProperties","FromMappedResult","OptionalFromMappedResult","IntersectCreate","allObjects","clonedUnevaluatedProperties","unevaluatedProperties","allOf","RemoveOptionalFromRest","ResolveIntersect","IsIntersectOptional","IntersectEvaluated","Intersect","UnionCreate","anyOf","ResolveUnion","IsUnionOptional","UnionEvaluated","Union","TemplateLiteralParserError","Unescape","pattern","IsNonEscaped","IsOpenParen","IsCloseParen","IsSeparator","TemplateLiteralParse","IsGroup","InGroup","IsPrecedenceOr","expressions","const","expr","Or","IsPrecedenceAnd","Group","scan","Range","And","TemplateLiteralParseExact","TemplateLiteralFiniteError","IsTemplateLiteralExpressionFinite","expression","IsNumberExpression","IsStringExpression","IsBooleanExpression","TemplateLiteralGenerateError","GenerateReduce","GenerateAnd","TemplateLiteralExpressionGenerate","GenerateOr","GenerateConst","TemplateLiteralGenerate","Literal","FromUnion","syntax","literals","literal","FromTerminal","FromSyntax","PatternBoolean","PatternNumber","PatternString","PatternNumberExact","PatternStringExact","PatternNeverExact","TemplateLiteralPatternError","Escape","TemplateLiteralPattern","kinds","TemplateLiteralToUnion","TemplateLiteral","unresolved","IndexPropertyKeys","templateLiteral","literalValue","mappedResult","Index","FromRest","IndexFromPropertyKey","FromIntersect","FromIntersectRest","FromUnionRest","propertyKey","FromArray","FromProperty","IndexFromPropertyKeys","propertyKeys","FromSchema","IndexFromMappedResult","mappedKey","MappedIndexPropertyKey","MappedIndexPropertyKeys","MappedIndexProperties","IndexFromMappedKey","Iterator","required","RequiredKeys","ReadonlyWithFlag","RemoveReadonly","AddReadonly","Readonly","K","ReadonlyFromMappedResult","additionalItems","minItems","FromSchemaType","MappedKeyToMappedResultProperties","MappedKeyToKnownMappedResultProperties","MappedKeyToUnknownMappedResultProperties","FromMappedKey","FunctionType","Ref","$ref","$id","KeyOfPropertyKeys","SetUnionMany","propertyKeysArray","Init","SetIntersect","SetIntersectManyResolve","indexer","FromTuple","patternProperties","includePatternProperties","KeyOfPattern","KeyOfFromType","propertyKeyTypes","KeyOfPropertyKeysToRest","KeyOf","FromComputed","KeyOfFromMappedResult","KeyOfPropertyEntries","schemas","ExtendsUndefinedCheck","Not","errorFunction","errorType","ValueErrorType","ArrayContains","ArrayMaxContains","maxContains","ArrayMinContains","minContains","ArrayMaxItems","ArrayMinItems","ArrayUniqueItems","BigIntExclusiveMaximum","exclusiveMaximum","BigIntExclusiveMinimum","exclusiveMinimum","BigIntMaximum","BigIntMinimum","BigIntMultipleOf","multipleOf","DateExclusiveMinimumTimestamp","exclusiveMinimumTimestamp","DateExclusiveMaximumTimestamp","exclusiveMaximumTimestamp","DateMinimumTimestamp","minimumTimestamp","DateMaximumTimestamp","maximumTimestamp","DateMultipleOfTimestamp","multipleOfTimestamp","IntegerExclusiveMaximum","IntegerExclusiveMinimum","IntegerMaximum","IntegerMinimum","IntegerMultipleOf","Integer","IntersectUnevaluatedProperties","NumberExclusiveMaximum","NumberExclusiveMinimum","NumberMaximum","NumberMinimum","NumberMultipleOf","ObjectAdditionalProperties","ObjectMaxProperties","maxProperties","ObjectMinProperties","minProperties","ObjectRequiredProperty","StringFormatUnknown","StringFormat","StringMaxLength","maxLength","StringMinLength","minLength","StringPattern","TupleLength","Uint8ArrayMaxByteLength","maxByteLength","Uint8ArrayMinByteLength","minByteLength","Undefined","Void","TypeDereferenceError","Pushref","references","Deref","Resolve","ValueHashError","ByteMarker","Accumulator","Prime","Size","Bytes","F64","F64In","F64Out","NumberToBytes","byteCount","FNV1A64","BooleanType","setBigInt64","BigIntType","NumberType","StringType","SymbolType","Any","KnownTypes","IsPattern","IsControlCharacterFree","IsAdditionalProperties","IsOptionalBoolean","IsOptionalBigInt","ValueGuard.IsUndefined","ValueGuard.IsBigInt","IsOptionalNumber","IsOptionalString","IsOptionalSchema","uniqueItems","IsProperties","IsLiteralString","IsLiteralNumber","IsLiteralBoolean","additionalProperties","IsOptionalPattern","IsOptionalFormat","ExtendsResolverError","ExtendsResult","IntoBooleanResult","False","True","Throw","IsStructuralRight","TypeGuard.IsNever","TypeGuard.IsIntersect","TypeGuard.IsUnion","TypeGuard.IsUnknown","TypeGuard.IsAny","StructuralRight","FromNeverRight","FromIntersectRight","FromUnionRight","FromUnknownRight","FromAnyRight","FromBooleanRight","TypeGuard.IsLiteralBoolean","TypeGuard.IsBoolean","FromIntegerRight","TypeGuard.IsLiteral","TypeGuard.IsNumber","TypeGuard.IsInteger","UnwrapTNot","depth","TypeGuard.IsNot","FromNumberRight","TypeGuard.IsLiteralNumber","IsObjectPropertyCount","IsObjectStringLike","IsObjectArrayLike","IsObjectSymbolLike","TypeGuard.IsString","TypeGuard.IsUndefined","IsObjectNumberLike","IsObjectBooleanLike","Property","TypeGuard.IsOptional","FromObjectRight","TypeGuard.IsLiteralString","TypeGuard.IsSymbol","TypeGuard.IsBigInt","TypeGuard.IsUint8Array","IsObjectUint8ArrayLike","TypeGuard.IsDate","IsObjectDateLike","TypeGuard.IsConstructor","IsObjectConstructorLike","TypeGuard.IsFunction","IsObjectFunctionLike","TypeGuard.IsRecord","RecordKey","FromPromise","TypeGuard.IsObject","IsObjectPromiseLike","TypeGuard.IsPromise","RecordValue","FromRecordRight","Key","Value","TypeGuard.IsArray","FromStringRight","IsArrayOfTuple","TypeGuard.IsTuple","FromUndefined","TypeGuard.IsVoid","FromVoidRight","FromUnknown","FromArrayRight","FromTupleRight","TypeGuard.IsTemplateLiteral","FromTemplateLiteral","TypeGuard.IsRegExp","FromRegExp","FromNot","FromAny","FromBigInt","FromBoolean","TypeGuard.IsAsyncIterator","FromAsyncIterator","FromConstructor","FromDate","FromFunction","FromInteger","TypeGuard.IsIterator","FromIterator","FromLiteral","TypeGuard.IsNull","FromNull","FromNumber","FromObject","FromRecord","FromString","FromSymbol","FromUint8Array","FromVoid","ExtendsCheck","Left","Right","Extends","ExtendsFromMappedResult","U","LK","FromPropertyKey","FromPropertyKeys","ExtendsFromMappedKey","trueType","falseType","ExtendsResolve","ValueCheckUnknownTypeError","IsAnyOrUnknown","IsDefined","references_","schema_","containsSchema","containsCount","definitions","$defs","FromImport","check1","keyPattern","check2","keyCheck","knownKeys","knownKey","valueKeys","valueKey","patternKey","patternSchema","regex","check3","FromThis","FormatRegistry.Has","FormatRegistry.Get","inner","TypeRegistry.Has","TypeRegistry.Get","FromKind","Check","ValueErrorsUnknownTypeError","EscapeKey","ValueErrorIterator","First","Create","hasError","FromNever","requiredKeys","unknownKeys","requiredKey","propertyValue","_AssertError_instances","_AssertError_iterator","_AssertError_Iterator","AssertError","Errors","AssertValue","IsTypedArray","FromTypedArray","IsMap","FromMap","IsSet","FromSet","IsCheckable","composite","knownkeys","propertySchema","propertyKeyTest","IsStringNumeric","IsValueTrue","IsValueFalse","is","TryConvertLiteral","conversion","TryConvertString","TryConvertLiteralString","TryConvertNumber","TryConvertLiteralNumber","TryConvertBoolean","TryConvertLiteralBoolean","IsValueToString","TryConvertDate","IsTimeStringWithoutTimeZone","IsTimeStringWithTimeZone","IsDateTimeStringWithoutTimeZone","IsDateTimeStringWithTimeZone","IsDateString","truncateInteger","TryConvertBigInt","TryConvertInteger","TryConvertNull","TryConvertUndefined","propKey","propValue","subschema","converted","TransformDecodeError","Default","Decode","knownEntries","knownProperties","knownSchema","unknownProperties","IsUndefinedValue","TransformEncodeError","Encode","defaulted","value1","visited","HasTransform","ValueOrDefault","defaultValue","HasDefaultProperty","knownPropertyKeys","additionalPropertiesSchema","propertyKeyPattern","knownPropertyKey","FromRef","ParseError","ParseRegistry","registry","_references","Clean","Convert","Assert","TransformDecode","TransformEncode","Delete","ParseDefault","Parse","operations","operationKey","operation","ParseValue","deepRemoveNullishFields","typeboxValidate","validator","Value.Parse","srcEnd","currentStructures","srcString","bundledStrings","referenceMap","position","currentUnpackr","srcStringStart","srcStringEnd","currentExtensions","defaultOptions","useRecords","mapsAsObjects","C1Type","C1","sequentialMode","inlineObjectReadThreshold","Unpackr","sequential","trusted","structures","maxSharedStructures","sharedLength","getStructures","uninitialized","int64AsNumber","int64AsType","unpack","saveState","clearSource","checkedRead","unpackMultiple","lastPosition","defaultUnpackr","_mergeStructures","loadedStructures","existingStructures","isFrozen","structure","isShared","highByte","restoreStructures","randomAccessStructure","postBundlePosition","jsonView","incomplete","loadStructures","createStructureReader","readKey","freezeData","shortStringInJS","longStringInJS","readFixedString","position1","position0","readBin","getUint16","readExt","useFloat32","mult10","getBigUint64","getInt8","getInt16","getInt32","getBigInt64","recordDefinition","extension","noBuffer","readString8","readString16","readString32","readArray","readMap","validName","firstId","readObject","createSecondByteReader","read0","readStringJS","byte1","byte2","byte3","unit","readOnlyJSString","copyBuffers","readPosition","keyCache","asSafeString","checkPosition","existingStructure","ReferenceError","structuredClone","refEntry","targetProperties","used","typedArrays","glbl","typeCode","typedArrayName","TEMP_BUNDLE","savedSrcEnd","savedPosition","savedSrcStringStart","savedSrcStringEnd","savedSrcString","savedReferenceMap","savedBundledStrings","savedSrc","savedStructures","savedStructuresContents","savedPackr","savedSequentialMode","dataSize","dataPosition","textEncoder","extensions","extensionClasses","f32Array","hasNodeBuffer","ByteArrayAllocate","ByteArray","MAX_BUFFER_SIZE","keysTarget","targetView","safeEnd","hasNonLatin","RECORD_SYMBOL","Packr","hasSharedUpdate","encodeUtf8","encodeInto","written","packr","isSequential","hasSharedStructures","saveStructures","moreTypes","maxOwnStructures","useTwoByteRecords","sharedLimitId","maxStructureId","recordIdsToRemove","transitionsCount","serializationsSinceTransitionRebuild","pack","encodeOptions","RESERVE_START_SPACE","bundleStrings","transitions","nextTransition","transition","lastNamedStructuresLength","nextId","encodingError","writeStruct","lastBundle","writeBundles","idsToInsert","incrementPosition","insertionPoint","stringsPosition","makeRoom","serialized","distanceToMove","lastEnd","insertIds","REUSE_BUFFER_MODE","resetStructures","returnBuffer","newSharedData","isCompatible","compatible","prepareStructures","RESET_BUFFER_MODE","packArray","headerSize","strLength","extStart","maxBytes","setUint16","twoByte","strPosition","setInt16","setInt32","xShifted","referee","writeObject","mapAsEmptyObject","entryValue","writeResult","currentTarget","currentTargetView","currentPosition","writeExtensionData","writeFunction","largeBigIntToFloat","largeBigIntToString","useBigIntExtension","alignedSign","encodeUndefinedAsNil","writePlainObject","variableMapSize","coercibleKeyAsNumber","skipValues","objectOffset","writeRecord","progressiveRecords","wroteKeys","lastTransition","newTransitions","newRecord","insertNewRecord","recordId","__keys__","checkUseRecords","newSize","shouldShareStructure","nextOwnId","insertionOffset","mainTarget","mainPosition","mainSafeEnd","mainStart","keysPosition","newEnd","insertionPosition","newPosition","writeStructSlots","notifySharedUpdate","startTarget","useBuffer","clearSharedData","typedStructs","writeExtBuffer","typedArray","allocateForWrite","writeBuffer","writeStrings","seconds","useTimestamp32","getMilliseconds","onInvalidDate","setAsEmptyObject","defaultPackr","Packer","MsgpackCanisterAgent","executeMsgpackQuery","requestValidator","responseValidator","performance","prepareMsgpackArgs","processMsgpackResponse","executeMsgpackUpdate","onRequestAccepted","polling.pollForResponse","polling.defaultStrategy","CanisterReject","serializeToMsgPack","responseBytes","deserializeFromMsgPack","optional","candid","mapOptional","optionUpdateV2","SetToSome","apiOptionUpdateV2","toVoid","_x","hexStringToBytes","consolidateBytes","bytesToHexString","principalBytesToString","principalStringToBytes","maybePrincipalStringToBytes","bigintToBytes","bytesToBigint","durationToTimestamp","pinNumberFailureResponseV2","nextRetryAt","PinIncorrect","TooManyFailedPinAttempts","E8S_AS_BIGINT","generateApiKeyResponse","apiKey","Success","api_key","eventsSuccessResponse","eventWrapper","expired_event_ranges","expiredEventsRange","expired_message_ranges","expiredMessagesRange","latest_event_index","expires_at","GroupChatCreated","created_by","userIds","ParticipantsAdded","user_ids","addedBy","added_by","UsersInvited","invitedBy","invited_by","ParticipantJoined","ParticipantsRemoved","removedBy","removed_by","ParticipantLeft","changedBy","GroupNameChanged","changed_by","GroupDescriptionChanged","GroupRulesChanged","enabledPrev","prev_enabled","AvatarChanged","UsersBlocked","blockedBy","blocked_by","UsersUnblocked","unblockedBy","unblocked_by","RoleChanged","oldRole","memberRole","old_role","newRole","new_role","pinnedBy","MessagePinned","pinned_by","message_index","unpinnedBy","MessageUnpinned","unpinned_by","oldPermissions","groupPermissions","PermissionsChanged","old_permissions_v2","newPermissions","new_permissions_v2","GroupVisibilityChanged","messagesVisibleToNonMembers","messages_visible_to_non_members","GroupInviteCodeChanged","frozenBy","ChatFrozen","frozen_by","unfrozenBy","ChatUnfrozen","unfrozen_by","updatedBy","EventsTimeToLiveUpdated","updated_by","newTimeToLive","new_ttl","GroupGateUpdated","MembersAddedToDefaultChannel","newUrl","ExternalUrlUpdated","new_url","BotAdded","BotRemoved","BotUpdated","messageContent","replies_to","replyContext","message_id","tips","edited","forwarded","deleted","thread_summary","threadSummary","blockLevelMarkdown","block_level_markdown","botContext","bot_context","botMessageContext","finalised","command","botCommandArg","initiator","Decimal","User","DateTime","ledger","userTips","participantIds","participant_ids","followedByMe","followed_by_me","numberOfReplies","reply_count","latestEventTimestamp","latest_event_timestamp","mimeType","mime_type","blobReference","blob_reference","fileSize","file_size","fileContent","File","textContent","thumbnailData","thumbnail_data","imageContent","Image","video_blob_reference","image_blob_reference","videoContent","Video","audioContent","Audio","deletedBy","deleted_by","deletedContent","Deleted","cryptoTransfer","recipient","cryptoContent","Crypto","votes","pollConfig","ended","pollContent","Poll","desktop","giphyImageVariant","mobile","giphyContent","Giphy","governanceCanisterId","governance_canister_id","proposal","myVote","my_vote","proposalContent","GovernanceProposal","prizes_remaining","prizes_pending","diamond_only","lifetime_diamond_only","unique_person_only","streak_only","token_symbol","end_date","prizeContent","Prize","senderId","completedCryptoTransfer","winner","prizeMessageIndex","prize_message","prizeWinnerContent","PrizeWinner","notes","remindAt","remind_at","reminderId","reminder_id","hidden","messageReminderCreated","MessageReminderCreated","messageReminder","MessageReminder","customContent","Custom","total","reports","reasonCode","reason_code","reportedBy","reported_by","reportedMessage","ReportedMessage","tokenInfo","token0_amount","token1_amount","p2pTradeStatus","swap_id","token0_txn_in","p2pSwapContent","P2PSwap","participants","videoCallParticipant","callType","videoCallType","call_type","videoCallContent","VideoCall","fee","decimals","symbol","reservedBy","reserved_by","acceptedBy","Accepted","accepted_by","token1TxnIn","token1_txn_in","token0TxnOut","Cancelled","token0_txn_out","Expired","token1_txn_out","Completed","token1TxnOut","apiUser","NNS","topic","proposer","summary","proposalDecisionStatus","rewardStatus","proposalRewardStatus","reward_status","tally","yes","no","lastUpdated","last_updated","created","deadline","payloadTextRendering","payload_text_rendering","minYesPercentageOfTotal","minYesPercentageOfExercised","SNS","action","minimum_yes_proportion_of_total","minimum_yes_proportion_of_exercised","Failed","Open","Executed","Adopted","Unspecified","AcceptVotes","ReadyToSettle","Settled","allowMultipleVotesPerUser","allow_multiple_votes_per_user","allowUserToChangeVote","allow_user_to_change_vote","showVotesBeforeEndDate","show_votes_before_end_date","totalPollVotes","user","Anonymous","Visible","Hidden","trans","amountE8s","e8s","feeE8s","memo","createdAtNanos","ICRC1","pendingCryptoTransfer","Pending","error_message","ICRC2","failedCryptoTransfer","block_index","blobId","blob_id","event_index","chat_if_other","replySourceContext","maybeThreadRoot","Direct","Channel","reaction","changeRoles","permissionRole","change_roles","updateGroup","update_group","inviteUsers","invite_users","addMembers","add_members","removeMembers","remove_members","deleteMessages","delete_messages","pinMessages","pin_messages","reactToMessages","react_to_messages","mentionAllMembers","mention_all_members","startVideoCall","start_video_call","messagePermissions","message_permissions","threadPermissions","thread_permissions","mf","cp","image","video","audio","file","poll","giphy","prize","p2pSwap","p2p_swap","memeFighter","communityPermissions","communityPermissionRole","updateDetails","update_details","createPublicChannel","create_public_channel","createPrivateChannel","create_private_channel","manageUserGroups","manage_user_groups","apiCommunityPermissionRole","apiGroupPermissions","permissions","apiPermissionRole","apiMessagePermissions","video_call","chatMetrics","audio_messages","icp_messages","sns1_messages","ckbtc_messages","giphy_messages","deleted_messages","file_messages","poll_votes","text_messages","image_messages","video_messages","reported_messages","apiMultiUserChat","apiReplyContextArgs","apiMessageContent","apiTextContent","apiImageContent","apiVideoContent","apiAudioContent","apiFileContent","apiPendingCryptoContent","apiPollContent","apiGiphyContent","apiPrizeContentInitial","apiP2PSwapContentInitial","apiGiphyImageVariant","apiPollVotes","apiPollConfig","apiTotalPollVotes","apiBlobReference","apiMaybeAccessGateConfig","gate","Composite","gates","apiLeafAccessGate","and","operator","VerifiedCredential","credential_name","credential","credentialName","issuer_canister_id","issuerCanisterId","issuer_origin","issuerOrigin","credential_type","credentialType","credential_arguments","apiCredentialArguments","credentialArguments","SnsNeuron","governanceCanister","min_dissolve_delay","minDissolveDelay","min_stake_e8s","minStakeE8s","Payment","ledger_canister_id","ledgerCanister","TokenBalance","min_balance","minBalance","apiMaybeAccessGate","expiry","apiAccessGateConfig","apiAccessGate","accessGateConfig","accessGate","credentialArgs","apiPendingCryptoTransaction","prizes_v2","apiTokenInfo","expires_in","apiICP","principalToIcrcAccount","groupChatSummary","chat_id","latest_message","is_public","historyVisible","history_visible_to_new_joiners","minVisibleEventIndex","min_visible_event_index","minVisibleMessageIndex","min_visible_message_index","latestMessageIndex","latest_message_index","avatar_id","memberCount","participant_count","permissions_v2","metrics","groupSubtype","previewed","frozen","dateLastPinned","date_last_pinned","gateConfig","gate_config","eventsTTL","events_ttl","eventsTtlLastUpdated","events_ttl_last_updated","membership","my_metrics","notifications_muted","rules_accepted","localUserIndex","local_user_index_canister_id","isInvited","verified","communitySummary","community_id","banner_id","member_count","pinned","display_name","communityChannelSummary","primaryLanguage","primary_language","userGroups","user_groups","userGroup","is_invited","user_group_id","members","channel_id","videoCallInProgress","video_call_in_progress","latest_threads","threadSyncDetails","externalUrl","external_url","root_message_index","latest_event","updatedEvent","gateCheckFailedReason","addRemoveReactionResponse","isNns","GovernanceProposals","is_nns","mention","thread_root_message_index","updateGroupResponse","rulesVersion","SuccessV2","rules_version","ocError","createGroupResponse","deleteGroupResponse","pinMessageResponse","unpinMessageResponse","groupDetailsResponse","member","basicMembers","basic_members","membersSet","bots","blockedUsers","blocked_users","invitedUsers","invited_users","pinnedMessages","pinned_messages","rules","chat_rules","installedBotDetails","apiKeys","api_keys","publicApiKeyDetails","botId","bot_id","grantedPermissions","externalBotPermissions","granted_permissions","generatedBy","generated_by","generatedAt","generated_at","groupDetailsUpdatesResponse","membersAddedOrUpdated","members_added_or_updated","membersRemoved","members_removed","blockedUsersAdded","blocked_users_added","blockedUsersRemoved","blocked_users_removed","pinnedMessagesAdded","pinned_messages_added","pinnedMessagesRemoved","pinned_messages_removed","botsAddedOrUpdated","bots_added_or_updated","botsRemoved","bots_removed","apiKeysGenerated","api_keys_generated","SuccessNoUpdates","editMessageResponse","declineInvitationResponse","leaveGroupResponse","deleteMessageResponse","deletedMessageResponse","undeleteMessageResponse","threadPreviewsResponse","latestClientThreadUpdate","threads","latestReplies","latest_replies","e2","totalReplies","total_replies","rootMessage","root_message","threadPreview","ReplicaNotUpToDate","changeRoleResponse","registerPollVoteResponse","apiChatIdentifier","joinGroupResponse","AlreadyInGroupV2","GateCheckFailed","searchGroupChatResponse","messageMatch","score","inviteCodeResponse","enableOrResetInviteCodeResponse","disableInviteCodeResponse","registerProposalVoteResponse","claimPrizeResponse","statusError","acceptP2PSwapResponse","StatusError","InternalError","cancelP2PSwapResponse","joinVideoCallResponse","apiVideoCallPresence","setVideoCallPresence","videoCallParticipantsResponse","setPinNumberResponse","TooShort","min_length","TooLong","max_length","apiDexId","dex","permissionsFromBits","chatPermissions","apiExternalBotPermissions","permissionsToBits","allPermissions","updateBotResponse","externalBotDefinition","commands","externalBotCommand","autonomousConfig","autonomous_config","syncApiKey","sync_api_key","placeholder","externalBotParam","defaultRole","default_role","directMessages","direct_messages","param","customParamFields","param_type","paramType","StringParam","choices","multi_line","minValue","IntegerParam","min_value","maxValue","max_value","DecimalParam","future_only","DateTimeParam","owner","subaccount","mapCommonResponses","mapCommonResponsesInner","addMembersToChannelResponse","usersLimitReached","users_limit_reached","usersAlreadyInChannel","users_already_in_channel","usersFailedWithError","users_failed_with_error","userFailedWithError","usersAdded","users_added","addToChannelPartialSuccess","PartialSuccess","addToChannelFailed","blockUserResponse","removeMemberResponse","removeMemberFromChannelResponse","sendMessageResponse","exploreChannelsResponse","channelMatch","summaryResponse","summaryUpdatesResponse","communitySummaryUpdates","channelsUpdated","channels_updated","avatarId","groupMembershipUpdates","updatedEvents","updated_events","messageVisibleToNonMembers","communityChannelUpdates","channelsRemoved","channels_removed","channelsAdded","channels_added","communityMembershipUpdates","bannerId","userGroupsDeleted","user_groups_deleted","myRole","unfollowedThreads","unfollowed_threads","unblockUserResponse","updateCommunityResponse","apiMemberRole","apiCommunityRole","apiOptionalCommunityPermissions","communityDetailsResponse","userGroupDetails","referrals","communityDetailsUpdatesResponse","referralsRemoved","referrals_removed","referralsAdded","referrals_added","createUserGroupResponse","userGroupId","updateUserGroupResponse","deleteUserGroupsResponse","setMemberDisplayNameResponse","followThreadResponse","reportMessageResponse","apiBotInstallLocation","Community","botUpdatesResponse","blobUrlPattern","removed","added_or_updated","bot","avatarUrl","ownerId","definition","registrationStatus","botRegistrationStatus","registration_status","botSchema","Private","botInstallationLocation","userSearchResponse","is_bot","diamond_membership_status","chit_balance","total_chit_earned","is_unique_person","userSummary","usersApiResponse","serverTimestamp","userSummaryUpdate","deletedUserIds","currentUser","current_user","isPlatformOperator","is_platform_operator","diamondMembershipStatus","moderationFlagsEnabled","moderation_flags_enabled","isSuspectedBot","is_suspected_bot","suspensionDetails","suspension_details","isPlatformModerator","is_platform_moderator","diamondDetails","diamond_membership_details","diamondMembership","currentUserSummary","userRegistrationCanisterResponse","currentUserResponse","dateCreated","date_created","cryptoAccount","icp_account","Active","diamondMembershipSubscription","payInChat","pay_in_chat","suspensionAction","suspendedBy","suspended_by","Unsuspend","checkUsernameResponse","setUsernameResponse","setDisplayNameResponse","suspendUserResponse","unsuspendUserResponse","apiJsonDiamondDuration","diamondMembershipFeesResponse","oneMonth","one_month","threeMonths","three_months","oneYear","one_year","lifetime","chitLeaderboardResponse","allTime","all_time","chitUserBalance","lastMonth","last_month","thisMonth","this_month","balance","submitProofOfUniquePersonhoodResponse","externalAchievementsResponse","addedOrUpdated","externalAchievement","chitReward","chit_reward","expires","budgetExhausted","budget_exhausted","apiCustomParamFields","apiExternalBotParam","apiBotDefinition","apiExternalBotCommand","apiAutonomousConfig","exploreBotsResponse","externalBotMatch","Awaited","CompositeKeys","SetDistinct","CompositeProperty","FilterNever","ConditionalReadonly","FromValue","Exclude","ExcludeFromTemplateLiteral","ExcludeFromMappedResult","excluded","ExcludeRest","Extract","ExtractFromTemplateLiteral","ExtractFromMappedResult","extracted","ExtractRest","MappedIntrinsicPropertyKey","M","Intrinsic","MappedIntrinsicProperties","MappedIntrinsicPropertyKeys","FromLiteralValue","ApplyUncapitalize","ApplyCapitalize","ApplyUppercase","ApplyLowercase","IntrinsicFromMappedKey","Omit","OmitResolve","omittedProperties","typeKey","IsArrayValue","UnionFromPropertyKeys","isTypeRef","isKeyRef","OmitFromMappedResult","OmitFromMappedKey","Pick","PickResolve","PickFromMappedResult","leftKey","PickFromMappedKey","partialProperties","PartialResolve","Partial","PartialFromMappedResult","RecordCreateFromPattern","RecordCreateFromKeys","FromTemplateLiteralKey","FromUnionKey","FromLiteralKey","FromIntegerKey","FromNumberKey","FromRegExpKey","FromStringKey","FromAnyKey","FromNeverKey","requiredProperties","RequiredResolve","Required","RequiredFromMappedResult","DerefParameters","moduleProperties","KindGuard.IsRef","FromType","dereferenced","FromAwaited","FromIndex","FromKeyOf","FromPartial","FromOmit","FromPick","FromRequired","KindGuard.IsOptional","KindGuard.IsReadonly","KindGuard.IsArray","KindGuard.IsAsyncIterator","KindGuard.IsComputed","KindGuard.IsConstructor","instanceType","KindGuard.IsFunction","returnType","KindGuard.IsIntersect","KindGuard.IsIterator","KindGuard.IsObject","KindGuard.IsTuple","KindGuard.IsUnion","ComputeType","TModule","computed","identified","WithIdentifiers","Import","Ordinal","TransformDecodeBuilder","TransformEncodeBuilder","EncodeTransform","Codec","EncodeSchema","TypeBuilder","Array$1","BigInt$1","Boolean$1","Capitalize","CompositeProperties","Const","ConstructorParameters","Date$1","Enum","values1","Function$1","InstanceType","Intersect$1","Lowercase","Mapped","MappedFunctionReturnType","Module","Number$1","Object$1","Parameters","Promise$1","ReadonlyOptional","Recursive","thisType","Rest","RestResolve","ReturnType","String$1","Symbol$1","Transform","Uint8Array$1","Uncapitalize","Union$1","Unsafe","Uppercase","ProposalsBotStakeNeuronForSubmittingProposalsResponse","NeuronAlreadyExists","TransferError","ProposalsBotTopUpNeuronResponse","ProposalsBotSubmitProposalResponse","InsufficientPayment","PaymentFailed","Retrying","ProposalsBotCanisterInstallMode","ProposalsBotTreasury","OnlineUsersMinutesOnlineArgs","year","month","OnlineUsersMinutesOnlineResponse","OnlineUsersMarkAsOnlineSuccessResult","minutes_online","GroupSummaryUpdatesArgs","updates_since","GroupToggleMuteNotificationsArgs","mute","GroupInviteCodeSuccessResult","GroupEnableInviteCodeArgs","correlation_id","GroupEnableInviteCodeSuccessResult","GroupDisableInviteCodeArgs","GroupGenerateBotApiKeySuccessResult","GroupPublicSummaryArgs","invite_code","GroupRulesSuccessResult","GroupSelectedUpdatesArgs","UserUpdateBtcBalanceResponse","UserMessageActivitySummary","read_up_to","unread_count","UserMarkAchievementsSeenArgs","last_seen","UserMarkAchievementsSeenResponse","UserBioResponse","UserTokenSwapStatusArgs","UserTokenSwapStatusTokenSwapStatus","started","icrc2","auto_withdrawals","deposit_account","Ok","Err","transfer_or_approval","notify_dex","amount_swapped","withdraw_from_dex","UserSwapTokensSuccessResult","amount_out","UserMessageActivityFeedArgs","since","UserUnblockUserResponse","UserAddHotGroupExclusionsResponse","UserUpdatesArgs","UserGenerateBotApiKeySuccessResult","UserSetBioArgs","UserClaimDailyChitSuccessResult","chit_earned","max_streak","next_claim","UserClaimDailyChitResponse","AlreadyClaimed","max_results","UserMessageActivity","UserSetCommunityIndexesResponse","UserPublicProfilePublicProfile","bio","is_premium","phone_is_verified","UserMarkReadResponse","UserCancelMessageReminderResponse","UserCancelMessageReminderArgs","UserChitEventsArgs","UserNamedAccount","account","UserAutoWallet","min_cents_visible","UserMarkMessageActivityFeedReadResponse","UserMarkMessageActivityFeedReadArgs","UserConfigureWalletResponse","MessageReminderContent","Reaction","FieldTooShortResult","length_provided","MessageIndex","DiamondMembershipPlanDuration","EventIndex","ReferralStatus","VoteOperation","SuspensionAction","OCError","BotCommandOptionChoiceF64","SwapStatusErrorCancelled","SubscriptionKeys","p256dh","CommunityRole","ExchangeId","CanisterUpgradeStatus","OptionUpdateU128","SwapStatusErrorExpired","PinNumberSettings","attempts_blocked_until","ApproveError","BadFee","expected_fee","InsufficientFunds","AllowanceChanged","current_allowance","ledger_time","CreatedInFuture","Duplicate","duplicate_of","GenericError","VideoCallPresence","ChatMetrics","crypto_messages","chat_messages","kinic_messages","prize_messages","prize_winner_messages","proposals","message_reminders","custom_type_messages","last_active","VideoCallType","GroupRole","AuthToken","Jwt","ApiKey","ChannelId","GroupPermissionRole","AcceptSwapSuccess","OptionUpdateU64","GroupCanisterThreadDetails","Tokens","Rules","SubscriptionInfo","OptionUpdateVideoCall","UserSummaryVolatile","CommunityPermissionRole","OptionUpdatePinNumberSettings","CommunityPermissions","StreakInsurance","days_insured","days_missed","FieldTooLongResult","Chit","PinNumberWrapper","GiphyImageVariant","Achievement","ThumbnailData","GroupReplyContext","PushEventResult","BuildVersion","patch","TSPrincipal","OptionUpdateGroupPermissionRole","BotCommandMeta","timezone","Cryptocurrency","Other","ChitEarnedReason","ExternalAchievement","Referral","InvalidPollReason","TooFewOptions","TooManyOptions","OptionTooLong","UserId","CryptoAccountNNS","Account","BotCommandOptionChoiceI128","CommunityId","MessageReminderCreatedContent","TransferFromError","BadBurn","min_burn_amount","InsufficientAllowance","allowance","ChannelMessageTipped","ci","chi","tr","cn","chn","ti","tn","td","ca","cha","MessageMatch","OptionUpdateStreakInsurance","DirectChatCreated","UserOrAccount","VerifiedCredentialGateArgs","user_ii_principal","credential_jwt","credential_jwts","ii_origin","GovernanceProposalsSubtype","GroupInviteCodeChange","Version","OptionalCommunityPermissions","CommunityMembership","VerifiedCredentialArgumentValue","BotPermissions","P2PSwapCancelled","FailedCryptoTransactionNNS","transaction_hash","TextContent","MessageId","AutonomousConfig","BotCommandOptionChoiceString","CommunityMember","date_added","referred_by","MessageReport","ThreadSummary","CustomPermission","SuspensionDetails","TSBytes","UpdatedRules","new_version","OptionUpdateString","DiamondMembershipStatus","PollConfig","Tally","CryptoTransferDetails","DiamondMembershipFeesByDuration","UserGroupSummary","DiamondMembershipSubscription","MemberLeft","UserGroupDetails","GroupIndexFreezeGroupSuspensionDetails","GroupIndexAddHotGroupExclusionResponse","GroupIndexMarkLocalGroupIndexFullArgs","full","GroupIndexMarkLocalGroupIndexFullResponse","GroupIndexLookupChannelByGroupIdSuccessResult","GroupIndexLookupChannelByGroupIdResponse","GroupIndexExploreCommunitiesArgs","search_term","languages","page_index","page_size","include_moderation_flags","GroupIndexUnfreezeCommunityArgs","GroupIndexFreezeCommunitySuspensionDetails","GroupIndexSetGroupUpgradeConcurrencyResponse","GroupIndexSetGroupUpgradeConcurrencyArgs","GroupIndexDeleteFrozenGroupResponse","GroupIndexSetCommunityModerationFlagsResponse","GroupIndexSetCommunityModerationFlagsArgs","GroupIndexRemoveHotGroupExclusionResponse","GroupIndexExploreGroupsArgs","GroupIndexSetCommunityUpgradeConcurrencyResponse","GroupIndexSetCommunityUpgradeConcurrencyArgs","file_hash","StorageIndexUserUserRecord","byte_limit","bytes_used","StorageIndexProjectedAllowance","bytes_used_after_upload","bytes_used_after_operation","StorageIndexAllocationBucketSuccessResult","file_id","chunk_size","projected_allowance","AllowanceExceeded","file_id_seed","RegistryAddMessageFilterArgs","RegistryAddMessageFilterResponse","InvalidRequest","community_name","channel_name","RegistryMessageFilterSummary","RegistryRemoveMessageFilterArgs","RegistryNervousSystemSummary","root_canister_id","index_canister_id","proposal_rejection_fee","submitting_proposals_enabled","RegistryAddRemoveSwapProviderResponse","RegistryAddRemoveSwapProviderArgs","swap_provider","RegistryPayment","RegistryUpdatesArgs","RegistrySetTokenEnabledResponse","RegistrySetTokenEnabledArgs","RegistryTokenDetails","logo","logo_id","info_url","transaction_url_format","supported_standards","added","payments","UserIndexDiamondMembershipFeesDiamondMembershipFees","UserIndexUsersChitSuccessResult","chit","UserIndexSuspendUserResponse","UserIndexSuspendUserArgs","UserIndexCheckUsernameResponse","UsernameTooShort","UsernameTooLong","UserIndexCheckUsernameArgs","UserIndexSetModerationFlagsArgs","UserIndexSetModerationFlagsResponse","UserIndexPlatformOperatorsSuccessResult","UserIndexPlatformModeratorsSuccessResult","UserIndexSetUserUpgradeConcurrencyArgs","UserIndexSetUserUpgradeConcurrencyResponse","UserIndexSuspectedBotsSuccessResult","after","UserIndexExternalAchievementsExternalAchievement","UserIndexExternalAchievementsArgs","UserIndexBotUpdatesArgs","updated_since","UserIndexReferralMetricsReferralMetrics","users_who_referred","users_who_referred_paid_diamond","users_who_referred_unpaid_diamond","users_who_referred_90_percent_unpaid_diamond","referrals_of_paid_diamond","referrals_of_unpaid_diamond","referrals_other","icp_raised_by_referrals_to_paid_diamond","UserIndexPayForDiamondMembershipSuccessResult","proof_jwt","UserIndexPayForDiamondMembershipResponse","TransferFailed","UserIndexPayForDiamondMembershipArgs","expected_price_e8s","recurring","UserIndexSearchArgs","UserIndexDeleteUserResponse","MalformedSignature","UserIndexRemoveBotArgs","UserIndexRemoveBotResponse","UserIndexUnsuspendUserArgs","UserIndexUnsuspendUserResponse","UserIndexUsersUserGroup","UserIndexUsersArgs","users_suspended_since","UserIndexSubmitProofOfUniquePersonhoodResponse","Invalid","UserIndexSubmitProofOfUniquePersonhoodArgs","UserIndexChitLeaderboardChitUserBalance","UserIndexSetUsernameResponse","UserIndexSetUsernameArgs","UserIndexUpdateBotResponse","UserIndexSetDisplayNameResponse","DisplayNameTooShort","DisplayNameTooLong","UserIndexSetDisplayNameArgs","UserIndexSetDiamondMembershipFeesResponse","UserIndexRegisterBotSuccessResult","UserIndexReportedMessagesArgs","UserIndexReportedMessagesSuccessResult","UserIndexReportedMessagesResponse","UserIndexUserRegistrationCanisterResponse","LocalUserIndexInviteUsersToCommunityArgs","caller_username","LocalUserIndexInviteUsersToCommunityResponse","TooManyInvites","LocalUserIndexInstallBotResponse","LocalUserIndexInviteUsersToGroupResponse","LocalUserIndexBotCreateChannelSuccessResult","FailedAuthentication","C2CError","auth_token","LocalUserIndexUninstallBotResponse","LocalUserIndexRegisterUserArgs","referral_code","LocalUserIndexRegisterUserSuccessResult","LocalUserIndexWithdrawFromIcpswapArgs","input_token","LocalUserIndexWithdrawFromIcpswapResponse","LocalUserIndexChatEventsEventsByIndexArgs","LocalUserIndexChatEventsEventsWindowArgs","mid_point","max_messages","max_events","LocalUserIndexChatEventsEventsPageArgs","start_index","LocalUserIndexJoinCommunityArgs","verified_credential_args","LocalUserIndexJoinChannelArgs","LocalUserIndexInviteUsersToChannelFailedResult","failed_users","LocalUserIndexInviteUsersToChannelPartialSuccessResult","LocalUserIndexInviteUsersToChannelArgs","LocalUserIndexAccessTokenV2Response","LocalUserIndexBotSendMessageSuccessResult","LocalUserIndexGroupAndCommunitySummaryUpdatesSummaryUpdatesArgs","is_community","CommunitySummaryUpdatesArgs","CommunitySelectedChannelUpdatesArgs","CommunityLeaveChannelResponse","CommunityLeaveChannelArgs","CommunityRemoveMemberArgs","CommunityRemoveMemberResponse","CommunityToggleMuteNotificationsResponse","CommunityToggleMuteNotificationsArgs","CommunityClaimPrizeArgs","CommunityCancelInvitesResponse","CommunityCancelInvitesArgs","CommunityCreateUserGroupArgs","CommunityCreateUserGroupSuccessResult","CommunityCreateUserGroupResponse","NameTooShort","NameTooLong","CommunityJoinVideoCallArgs","new_achievement","CommunitySetVideoCallPresenceArgs","presence","CommunitySetVideoCallPresenceResponse","CommunityDeletedMessageArgs","CommunityRegisterPollVoteArgs","poll_option","CommunityCancelP2pSwapArgs","CommunitySearchChannelArgs","CommunitySearchChannelSuccessResult","CommunitySearchChannelResponse","TermTooLong","TermTooShort","TooManyUsers","CommunityUndeleteMessagesArgs","message_ids","CommunityChangeRoleArgs","CommunityChangeRoleResponse","CommunitySelectedChannelInitialArgs","CommunityInviteCodeSuccessResult","CommunityInviteCodeResponse","CommunityUnblockUserArgs","CommunityUnblockUserResponse","CommunityExploreChannelsArgs","CommunityUpdateUserGroupArgs","users_to_add","users_to_remove","CommunityUpdateUserGroupResponse","CommunityEventsWindowArgs","latest_known_update","CommunityDeleteMessagesResponse","CommunityDeleteMessagesArgs","as_platform_moderator","CommunityRemoveMemberFromChannelResponse","CommunityRemoveMemberFromChannelArgs","CommunityEnableInviteCodeSuccessResult","CommunityEnableInviteCodeResponse","CommunityCommunityMembersSuccessResult","CommunityRegisterProposalVoteArgs","adopt","CommunityRegisterProposalVoteResponse","AlreadyVoted","CommunityAddMembersToChannelUserFailedError","CommunityAddMembersToChannelArgs","added_by_name","added_by_display_name","CommunityAddMembersToChannelPartialSuccessResult","CommunityAddMembersToChannelFailedResult","CommunityDisableInviteCodeResponse","CommunityChannelSummaryArgs","CommunityGenerateBotApiKeySuccessResult","CommunityGenerateBotApiKeyArgs","requested_permissions","CommunityChangeChannelRoleArgs","CommunityChangeChannelRoleResponse","CommunityApiKeyResponse","CommunityApiKeyArgs","CommunityDeclineInvitationArgs","CommunityDeclineInvitationResponse","CommunityMessagesByMessageIndexArgs","CommunityDeleteUserGroupsResponse","CommunityDeleteUserGroupsArgs","user_group_ids","CommunityUpdateCommunitySuccessResult","CommunityUpdateCommunityResponse","DescriptionTooLong","AvatarTooBig","BannerTooBig","RulesTooLong","RulesTooShort","CommunityRemoveReactionArgs","CommunityRemoveReactionResponse","CommunitySelectedInitialArgs","CommunityAddReactionArgs","CommunityAddReactionResponse","CommunityThreadPreviewsArgs","latest_client_thread_update","CommunityBlockUserResponse","CommunityBlockUserArgs","CommunityPinMessageArgs","CommunityPinMessageResponse","CommunityVideoCallParticipantsArgs","CommunitySendMessageSuccessResult","CommunitySendMessageResponse","TextTooLong","InvalidPoll","CommunityEventsByIndexArgs","CommunityLocalUserIndexResponse","CommunityEventsArgs","CommunityUpdateBotArgs","CommunityUpdateBotResponse","CommunityAcceptP2pSwapArgs","pin","CommunityCreateChannelSuccessResult","CommunitySelectedUpdatesArgs","CommunityImportGroupSuccessResult","total_bytes","CommunityImportGroupResponse","CommunityReportMessageArgs","CommunityReportMessageResponse","CommunityEditMessageResponse","CommunityUpdateChannelSuccessResult","CommunitySetMemberDisplayNameArgs","CommunitySetMemberDisplayNameResponse","CommunitySummaryArgs","CommunityFollowThreadResponse","CommunityFollowThreadArgs","CommunityDeleteChannelResponse","CommunityDeleteChannelArgs","NotificationsIndexPushSubscriptionResponse","NotificationsIndexPushSubscriptionArgs","NotificationsIndexSubscriptionExistsArgs","p256dh_key","NotificationsIndexSubscriptionExistsResponse","NotificationsIndexRemoveSubscriptionArgs","NotificationsIndexRemoveSubscriptionResponse","StorageBucketDeleteFilesDeleteFileFailureReason","file_ids","StorageBucketDeleteFilesDeleteFileFailure","StorageBucketFileInfoSuccessResult","is_owner","accessors","chunk_index","ProposalsBotStakeNeuronForSubmittingProposalsArgs","stake","ProposalsBotTopUpNeuronArgs","ProposalsBotExecuteGenericNervousSystemFunction","function_id","ProposalsBotUpgradeSnsControlledCanister","new_canister_wasm","OnlineUsersLastOnlineArgs","OnlineUsersLastOnlineUserLastOnline","duration_since_last_online","OnlineUsersMarkAsOnlineResponse","GroupSearchMessagesArgs","GroupSearchMessagesSuccessResult","GroupSearchMessagesResponse","GroupConvertIntoCommunitySuccessResult","GroupConvertIntoCommunityResponse","GroupConvertIntoCommunityArgs","GroupToggleMuteNotificationsResponse","GroupClaimPrizeArgs","GroupCancelInvitesResponse","GroupCancelInvitesArgs","GroupJoinVideoCallArgs","GroupSetVideoCallPresenceArgs","GroupSetVideoCallPresenceResponse","GroupDeletedMessageArgs","GroupRegisterPollVoteArgs","GroupCancelP2pSwapArgs","GroupUndeleteMessagesArgs","GroupChangeRoleResponse","GroupChangeRoleArgs","GroupInviteCodeResponse","GroupUnblockUserResponse","GroupUnblockUserArgs","GroupEventsWindowArgs","GroupDeleteMessagesResponse","GroupDeleteMessagesArgs","GroupEnableInviteCodeResponse","GroupUpdateGroupSuccessResult","GroupRegisterProposalVoteArgs","GroupRegisterProposalVoteResponse","GroupDisableInviteCodeResponse","GroupGenerateBotApiKeyArgs","GroupGenerateBotApiKeyResponse","GroupApiKeyResponse","GroupApiKeyArgs","GroupMessagesByMessageIndexArgs","GroupRegisterProposalVoteV2Response","GroupRegisterProposalVoteV2Args","GroupRemoveReactionResponse","GroupRemoveReactionArgs","GroupAddReactionArgs","GroupAddReactionResponse","GroupThreadPreviewsArgs","GroupBlockUserArgs","GroupBlockUserResponse","GroupPinMessageResponse","GroupPinMessageArgs","GroupRemoveParticipantArgs","GroupRemoveParticipantResponse","GroupVideoCallParticipantsArgs","GroupDeclineInvitiationResponse","GroupSendMessageSuccessResult","GroupSendMessageResponse","GroupEventsByIndexArgs","GroupUnpinMessageArgs","GroupUnpinMessageResponse","GroupLocalUserIndexResponse","GroupEventsArgs","GroupUpdateBotResponse","GroupUpdateBotArgs","GroupAcceptP2pSwapArgs","GroupReportMessageResponse","GroupReportMessageArgs","GroupEditMessageResponse","GroupFollowThreadResponse","GroupFollowThreadArgs","UserSearchMessagesSuccessResult","UserSearchMessagesResponse","UserSearchMessagesArgs","UserGenerateBtcAddressResponse","UserManageFavouriteChatsResponse","UserSavedCryptoAccountsResponse","UserJoinVideoCallArgs","UserJoinVideoCallResponse","UserTokenSwapStatusResponse","UserDeletedMessageArgs","UserCancelP2pSwapArgs","UserSetPinNumberResponse","UserSwapTokensICPSwapArgs","swap_canister_id","zero_for_one","UserSwapTokensResponse","UserSetAvatarResponse","UserUndeleteMessagesArgs","UserTipMessageResponse","UserUnblockUserArgs","UserManualWallet","tokens","UserChannelSummaryUpdates","read_by_me_up_to","threads_read","date_read_pinned","UserWithdrawBtcResponse","RetrieveBtcError","UserWithdrawBtcArgs","UserPinChatResponse","UserContactsContact","nickname","UserContactsSuccessResult","contacts","UserEventsWindowArgs","UserDeleteDirectChatArgs","block_user","UserDeleteDirectChatResponse","UserDeleteMessagesArgs","UserDeleteMessagesResponse","UserWalletConfig","Auto","Manual","UserSaveCryptoAccountResponse","UserLeaveGroupResponse","UserGenerateBotApiKeyResponse","UserGenerateBotApiKeyArgs","UserMuteNotificationsResponse","UserApiKeyResponse","UserApiKeyArgs","UserSetBioResponse","UserChannelSummary","UserApproveTransferResponse","UserDeleteGroupResponse","UserSetMessageReminderResponse","NotesTooLong","UserRemoveReactionArgs","UserRemoveReactionResponse","UserSetContactOptionalContact","contact","NicknameTooShort","NicknameTooLong","UserAddReactionArgs","UserAddReactionResponse","UserReferral","UserBlockUserArgs","UserBlockUserResponse","UserSetCommunityIndexesArgs","indexes","exchange_id","UserPublicProfileResponse","UserEventsByIndexArgs","UserCreateCommunitySuccessResult","UserCreateCommunityResponse","MaxCommunitiesCreated","UserMarkReadThreadRead","UserMarkReadChannelMessagesRead","UserMarkReadCommunityMessagesRead","channels_read","UserLocalUserIndexResponse","UserEventsArgs","UserUpdateBotResponse","UserUpdateBotArgs","UserLeaveCommunityArgs","UserLeaveCommunityResponse","UserAcceptP2pSwapArgs","UserDeleteCommunityArgs","UserDeleteCommunityResponse","UserReportMessageResponse","UserReportMessageArgs","them","UserEditMessageResponse","UserUnpinChatResponse","UserConfigureWalletArgs","DirectReactionAddedNotification","PaymentGate","VersionedRules","GroupSubtype","AccountICRC1","CommunityMembershipUpdates","GiphyContent","P2PSwapReserved","SnsNeuronGate","OptionalMessagePermissions","custom_updated","custom_deleted","UserSummary","diamond_member","DirectMessageTipped","MessagePermissions","ChatId","new_avatar","previous_avatar","CryptoAccountICRC1","VerifiedCredentialGate","NnsProposal","MembersRemoved","PublicApiKeyDetails","BotActionCommunityDetails","SwapStatusErrorReserved","BlobReference","PendingCryptoTransactionICRC1","new_description","previous_description","PrizeContent","winner_count","user_is_winner","GroupCreated","HydratedMention","DeletedGroupInfo","group_name","SwapStatusErrorAccepted","DiamondMembershipFees","chat_fees","icp_fees","Document","FileContent","P2PSwapCompleted","InstalledBotDetails","UserSummaryStable","ChitEarned","CustomContent","FailedCryptoTransactionICRC1","new_name","previous_name","Chat","DeletedBy","TokenBalanceGate","P2PSwapAccepted","GroupMember","GateCheckFailedReason","InsufficientBalance","FailedVerifiedCredentialCheck","StartVideoCallArgs","TokenInfo","due_to_message_deleted","DirectMessageNotification","sn","ct","CompletedCryptoTransactionNNS","TotalVotes","MultiUserChat","Tips","CallParticipant","GroupFrozen","OptionUpdateOptionalMessagePermissions","FailedCryptoTransactionICRC2","spender","GroupReactionAddedNotification","av","ChannelReactionAddedNotification","an","ad","PendingCryptoTransactionNNS","DeletedCommunityInfo","VideoCallParticipants","SwapStatusErrorCompleted","AirdropConfig","MembersAdded","unblocked","FrozenGroupInfo","GroupUnfrozen","BotCommandArgValue","PendingCryptoTransactionICRC2","MemberJoined","AddedToChannelNotification","AudioContent","ImageContent","JoinVideoCallArgs","MarkVideoCallAsEndedArgs","SelectedGroupUpdates","BotInstallationLocation","CompletedCryptoTransactionICRC1","GroupMembership","OptionUpdateFrozenGroupInfo","OptionalGroupPermissions","ReplyContext","BotActionChatDetails","user_message_id","ChannelMessageNotification","GroupMembershipUpdates","BotCommandParamType","SnsProposal","OptionUpdateAirdropConfig","GroupMessageTipped","GroupMessageNotification","OptionUpdateDocument","OptionUpdateGroupSubtype","DiamondMembershipDetails","GroupIndexRecommendedGroupsArgs","exclusions","GroupIndexFreezeGroupArgs","suspend_members","GroupIndexAddHotGroupExclusionArgs","GroupIndexLookupChannelByGroupIdArgs","group_id","GroupIndexFreezeCommunityArgs","GroupIndexDeleteFrozenGroupArgs","GroupIndexRemoveHotGroupExclusionArgs","GroupIndexActiveGroupsArgs","group_ids","community_ids","active_since","GroupIndexActiveGroupsSuccessResult","active_groups","active_communities","deleted_groups","deleted_communities","GroupIndexUnfreezeGroupArgs","RegistryUpdatesSuccessResult","token_details","nervous_system_details","message_filters_added","message_filters_removed","swap_providers","airdrop_config","RegistryUpdatesResponse","UserIndexDiamondMembershipFeesResponse","UserIndexExternalAchievementsSuccessResult","UserIndexExternalAchievementsResponse","UserIndexSearchResult","UserIndexSearchResponse","UserIndexExploreBotsArgs","installation_location","UserIndexChitLeaderboardSuccessResult","UserIndexChitLeaderboardResponse","UserIndexSetDiamondMembershipFeesArgs","fees","UserIndexRegisterBotResponse","UserIndexPlatformModeratorsGroupResponse","LocalUserIndexInstallBotArgs","LocalUserIndexInviteUsersToGroupArgs","LocalUserIndexJoinGroupArgs","LocalUserIndexUninstallBotArgs","LocalUserIndexRegisterUserResponse","PublicKeyInvalid","LocalUserIndexChatEventsEventsContext","LocalUserIndexChatEventsEventsSelectionCriteria","Page","ByIndex","Window","LocalUserIndexInviteUsersToChannelResponse","LocalUserIndexGroupAndCommunitySummaryUpdatesArgs","requests","CommunitySelectedChannelUpdatesResponse","CommunitySelectedChannelInitialSuccessResult","CommunityAddMembersToChannelResponse","UserLimitReached","CommunityGenerateBotApiKeyResponse","CommunitySelectedInitialSuccessResult","CommunityVideoCallParticipantsResponse","CommunityCreateChannelResponse","MaxChannelsCreated","CommunitySelectedUpdatesSuccessResult","CommunitySelectedUpdatesResponse","CommunityImportGroupArgs","CommunityUpdateChannelResponse","failures","ProposalsBotTransferSnsTreasuryFunds","treasury","ProposalsBotMintSnsTokens","OnlineUsersLastOnlineResponse","GroupUpdateGroupResponse","GroupSelectedInitialSuccessResult","GroupSelectedInitialResponse","GroupVideoCallParticipantsResponse","GroupSelectedUpdatesResponse","UserCommunitySummaryUpdates","UserManageFavouriteChatsArgs","to_add","to_remove","UserGroupChatSummary","UserMessageActivityEvent","activity","UserCreateGroupSuccessResult","UserCommunitySummary","UserSwapTokensExchangeArgs","ICPSwap","Sonic","KongSwap","UserSwapTokensArgs","output_token","input_amount","exchange_args","min_output_amount","UserSetAvatarArgs","UserMessageActivityFeedSuccessResult","UserMessageActivityFeedResponse","UserGroupChatSummaryUpdates","UserTipMessageArgs","UserAddHotGroupExclusionsArgs","groups","UserChatInList","Favourite","UserPinChatArgs","UserInitialStateCommunitiesInitial","summaries","UserInitialStateGroupChatsInitial","UserInitialStateFavouriteChatsInitial","UserUpdatesGroupChatsUpdates","UserUpdatesCommunitiesUpdates","UserUpdatesFavouriteChatsUpdates","UserLeaveGroupArgs","UserMuteNotificationsArgs","UserApproveTransferArgs","UserDeleteGroupArgs","UserSetMessageReminderArgs","UserTokenSwapsTokenSwap","notified_dex","withdrawn_from_dex","UserTokenSwapsSuccessResult","swaps","UserArchiveUnarchiveChatsArgs","to_archive","to_unarchive","UserArchiveUnarchiveChatsPartialSuccessResult","chats_not_found","UserSendMessageSuccessResult","UserMarkReadChatMessagesRead","UserChitEventsSuccessResult","UserUnpinChatArgs","VideoContent","GroupPermissions","VideoCallContent","hidden_participants","EventWrapperGroupFrozen","SignedDelegation","FailedCryptoTransaction","CompletedCryptoTransactionICRC2","BotRegistrationStatus","EventWrapperGroupUnfrozen","P2PSwapContentInitial","PendingCryptoTransaction","BotActionScope","UserSummaryV2","P2PSwapStatus","PollVotes","AccessGateNonComposite","CompletedCryptoTransaction","BotCommandArg","BotCommand","meta","Proposal","SwapStatusError","ac","dm","gm","cm","dr","gr","cr","dt","ProposalContent","BotCommandParam","DiamondMembershipStatusFull","P2PSwapContent","GroupIndexFreezeGroupResponse","GroupIndexUnfreezeCommunityResponse","GroupIndexFreezeCommunityResponse","GroupIndexActiveGroupsResponse","GroupIndexUnfreezeGroupResponse","UserIndexDeleteUserArgs","UserIndexCurrentUserSuccessResult","canister_upgrade_status","wasm_version","UserIndexCurrentUserResponse","LocalUserIndexChatEventsEventsArgs","CommunityClaimPrizeResponse","FailedAfterTransfer","CommunityRegisterPollVoteResponse","CommunityCancelP2pSwapResponse","CommunitySelectedChannelInitialResponse","CommunitySelectedInitialResponse","CommunityAcceptP2pSwapResponse","ProposalsBotProposalToSubmitAction","TransferSnsTreasuryFunds","MintSnsTokens","UpgradeSnsControlledCanister","ExecuteGenericNervousSystemFunction","ProposalsBotProposalToSubmit","GroupClaimPrizeResponse","GroupRegisterPollVoteResponse","GroupCancelP2pSwapResponse","GroupAcceptP2pSwapResponse","UserCreateGroupResponse","MaxGroupsCreated","UserCancelP2pSwapResponse","UserSetPinNumberPinNumberVerification","PIN","UserSetPinNumberArgs","new","verification","UserSendMessageWithTransferToGroupSuccessResult","UserWithdrawCryptoArgs","withdrawal","UserWithdrawCryptoResponse","TransactionFailed","UserArchiveUnarchiveChatsResponse","UserSendMessageTransferSuccessV2Result","UserSendMessageResponse","TransferSuccessV2","P2PSwapSetUpFailed","UserSendMessageWithTransferToChannelSuccessResult","UserMarkReadArgs","messages_read","community_messages_read","UserAcceptP2pSwapResponse","UserChitEventsResponse","PollContent","PrizeWinnerContent","BotCommandInitial","BotCommandDefinition","CompositeGate","CryptoTransaction","BotMessageContext","BotMessageContent","CurrentUserSummary","BotMatch","BotActionByCommandArgs","AccessGate","BotDefinition","UserIndexBotUpdatesBotDetails","UserIndexUsersResult","UserIndexUsersResponse","UserIndexExploreBotsSuccessResult","UserIndexExploreBotsResponse","UserIndexUpdateBotArgs","UserIndexRegisterBotArgs","permitted_install_location","LocalUserIndexChatEventsArgs","LocalUserIndexAccessTokenV2Args","StartVideoCall","JoinVideoCall","MarkVideoCallAsEnded","BotActionByCommand","BotActionByApiKey","ProposalsBotSubmitProposalArgs","UserSendMessageWithTransferToGroupResponse","CallerNotInGroup","CryptocurrencyNotSupported","UserSendMessageWithTransferToChannelResponse","UserNotInCommunity","UserNotInChannel","ChannelNotFound","CryptoContent","PrizeContentInitial","OptionUpdateAccessGate","MessageContent","GroupMatch","AccessGateConfig","MessageContentInitial","OptionUpdateAccessGateConfig","new_gate","new_gate_config","GroupIndexExploreGroupsSuccessResult","GroupIndexExploreGroupsResponse","UserIndexBotUpdatesSuccessResult","UserIndexBotUpdatesResponse","CommunityDeletedMessageSuccessResult","CommunityDeletedMessageResponse","CommunityUpdateCommunityArgs","CommunitySendMessageArgs","sender_name","sender_display_name","mentioned","forwarding","community_rules_accepted","channel_rules_accepted","message_filter_failed","CommunityCreateChannelArgs","CommunityEditMessageArgs","CommunityUpdateChannelArgs","GroupDeletedMessageSuccessResult","GroupUpdateGroupArgs","GroupSendMessageArgs","GroupEditMessageArgs","UserCreateGroupArgs","UserDeletedMessageSuccessResult","UserDeletedMessageResponse","UserSendMessageWithTransferToGroupArgs","UserSendMessageArgs","UserCreateCommunityArgs","default_channels","default_channel_rules","UserSendMessageWithTransferToChannelArgs","UserEditMessageArgs","ChannelMatch","ChatDetails","CommunityMatch","channel_count","moderation_flags","EventWrapperMessage","ChatEvent","CommunityCanisterChannelSummaryUpdates","latest_message_sender_display_name","any_updates_missed","GroupIndexExploreCommunitiesSuccessResult","GroupIndexExploreCommunitiesResponse","CommunityUndeleteMessagesSuccessResult","CommunityUndeleteMessagesResponse","CommunityExploreChannelsSuccessResult","CommunityExploreChannelsResponse","GroupDeletedMessageResponse","GroupUndeleteMessagesSuccessResult","GroupUndeleteMessagesResponse","UserUndeleteMessagesSuccessResult","UserUndeleteMessagesResponse","DirectChatSummary","read_by_them_up_to","MessagesResponse","chat_last_updated","GroupCanisterGroupChatSummary","EventWrapperChatEvent","ThreadPreview","GroupCanisterGroupChatSummaryUpdates","DirectChatSummaryUpdates","PublicGroupSummary","CommunityCanisterChannelSummary","GroupIndexRecommendedGroupsSuccessResult","GroupIndexRecommendedGroupsResponse","LocalUserIndexJoinGroupResponse","ParticipantLimitReached","SuccessAdded","SuccessUpdated","CommunityChannelSummaryResponse","CommunityMessagesByMessageIndexResponse","ReplicaNotUpToDateV2","CommunityThreadPreviewsSuccessResult","CommunityThreadPreviewsResponse","GroupSummaryUpdatesSuccessResult","GroupSummaryUpdatesResponse","GroupMessagesByMessageIndexResponse","GroupPublicSummarySuccessResult","GroupPublicSummaryResponse","GroupThreadPreviewsSuccessResult","GroupSummarySuccessResult","GroupSummaryResponse","UserInitialStateDirectChatsInitial","UserUpdatesDirectChatsUpdates","EventsResponse","unauthorized","CommunityCanisterCommunitySummary","CommunityCanisterCommunitySummaryUpdates","LocalUserIndexChatEventsEventsResponse","LocalUserIndexChatEventsSuccessResult","responses","LocalUserIndexChatEventsResponse","LocalUserIndexJoinCommunityResponse","AlreadyInCommunity","MemberLimitReached","LocalUserIndexJoinChannelResponse","SuccessJoinedCommunity","AlreadyInChannel","LocalUserIndexGroupAndCommunitySummaryUpdatesSummaryUpdatesResponse","SuccessGroup","SuccessCommunity","SuccessGroupUpdates","SuccessCommunityUpdates","LocalUserIndexGroupAndCommunitySummaryUpdatesResponse","CommunitySummaryUpdatesResponse","CommunityEventsResponse","CommunitySummaryResponse","GroupThreadPreviewsResponse","GroupEventsResponse","UserEventsResponse","UserInitialStateSuccessResult","direct_chats","group_chats","favourite_chats","communities","pin_number_settings","achievements","achievements_last_seen","streak_ends","streak_insurance","next_daily_claim","wallet_config","message_activity_summary","btc_address","UserInitialStateResponse","UserUpdatesSuccessResult","UserUpdatesResponse","UserIndexClient","getCurrentUser","cachedUser","isOffline","liveUser","setCachedCurrentUser","setModerationFlags","userRegistrationCanister","searchUsers","searchTerm","maxResults","getUsers","chitState","allowStale","allUsers","flatMap","fromCache","getCachedUsers","cachedDeletedUserIds","getCachedDeletedUserIds","suspendedUsersSyncedTo","getSuspendedUsersSyncedUpTo","buildGetUsersArgs","requestedFromServer","apiResponse","getUsersFromBackend","mergedResponse","mergeGetUsersResponse","deletedStore","userStore","inserts","deletes","setCachedDeletedUserIds","merged","mergeCachedCurrentUser","setSuspendedUsersSyncedUpTo","suspendedUsersSyncedUpTo","updatedSince","_cachedDeletedUserIds","fromCacheGrouped","keySelector","grouped","groupBy","fromCacheSet","notFoundInCache","allUsersRequested","fromCacheMap","apiResponseMap","fromServer","currentSummary","userSummaryFromCurrentUserSummary","checkUsername","setUsername","setUsernameInCache","setDisplayName","setDisplayNameInCache","suspendUser","unsuspendUser","payForDiamondMembership","expectedPriceE8s","proof","payForDiamondMembershipResponse","setUserDiamondStatusInCache","setCurrentUserDiamondStatusInCache","setUserUpgradeConcurrency","getPlatformModeratorGroup","diamondMembershipFees","setDiamondMembershipFees","chatFees","icpFees","chitLeaderboard","submitProofOfUniquePersonhood","iiPrincipal","getExternalAchievements","updatesSince","deleteUser","exploreBots","pageIndex","pageSize","registerBot","removeBot","updateRegisteredBot","getBots","DATE_FIXED","ensureReplicaIsUpToDate","replicaChatLastUpdated","suppressError","clientChat","openDbAndGetCachedChats","directChats","groupChats","getChat","excludeLatestKnownUpdateIfBeforeFix","latestKnownUpdate","messageActivityFeedResponse","messageActivityEvent","chatIdentifier","messageActivity","chitEventsResponse","chitEarned","chitEarnedReason","achievementType","referralStatus","saveCryptoAccountResponse","savedCryptoAccountsResponse","tipMessageResponse","publicProfileResponse","profile","isPremium","phoneIsVerified","setBioResponse","setAvatarResponse","pinChatResponse","archiveChatResponse","createCommunityResponse","getEventsResponse","latestKnownUpdatePreRequest","groupChatsInitial","userCanisterGroupSummary","directChatsInitial","directChatSummary","userCanisterCommunitySummary","userCanisterChannelSummary","communitiesInitial","favouriteChatsInitial","initialStateResponse","favouriteChats","pinNumberSettings","achievementsLastSeen","streakEnds","nextDailyClaim","referral","walletConfig","messageActivitySummary","bitcoinAddress","readUpToTimestamp","latestTimestamp","unreadCount","apiWalletConfig","minDollarValue","attemptsBlockedUntil","userCanisterCommunitySummaryUpdates","userCanisterChannelSummaryUpdates","communitiesUpdates","favouriteChatsUpdates","groupChatsUpdates","userCanisterGroupSummaryUpdates","directChatsUpdates","directChatSummaryUpdates","manageFavouritesResponse","getUpdatesResponse","readByThemUpTo","withdrawCryptoResponse","failedNnsCryptoWithdrawal","formatIcrc1Account","failedIcrc1CryptoWithdrawal","completedNnsCryptoWithdrawal","completedIcrc1CryptoWithdrawal","setMessageReminderResponse","leaveCommunityResponse","deleteCommunityResponse","swapTokensResponse","amountOut","tokenSwapStatusResponse","depositAccount","notifyDex","amountSwapped","resultOfResult","withdrawnFromDex","approveTransferResponse","apiExchangeArgs","swapCanisterId","zeroForOne","claimDailyChitResponse","nextDailyChitClaim","apiVerification","withdrawBtcResponse","INPUT_ERROR","WINDOW","JS_SHA3_NO_WINDOW","WEB_WORKER","JS_SHA3_NO_NODE_JS","node","COMMON_JS","JS_SHA3_NO_COMMON_JS","ARRAY_BUFFER","JS_SHA3_NO_ARRAY_BUFFER","HEX_CHARS","CSHAKE_PADDING","SHIFT","RC","SHAKE_BITS","OUTPUT_TYPES","CSHAKE_BYTEPAD","JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW","createOutputMethod","padding","outputType","Keccak","createShakeOutputMethod","outputBits","createCshakeOutputMethod","createKmacOutputMethod","createOutputMethods","createMethod","algorithms","bytepad","Kmac","methodNames","newMethodName","blocks","reset","finalized","block","blockCount","outputBlocks","notString","lastByteIndex","encodeString","strs","paddingBytes","zeros","c8","c9","b6","b7","b9","b11","b12","b13","b14","b15","b16","b17","b18","b19","b21","b22","b23","b24","b25","b26","b27","b28","b29","b30","b31","b32","b33","b34","b35","b36","b37","b38","b39","b41","b42","b43","b44","b45","b46","b47","b48","b49","offs","byte4","byte2lsb","pix_size","data_size","ihdr_offs","ihdr_size","plte_offs","plte_size","trns_offs","trns_size","idat_offs","idat_size","iend_offs","iend_size","buffer_size","palette","pindex","_crc32","header","color","red","green","blue","alpha","ndx","getBase64","e3","e4","getDump","s2","crc32","png","PNGlib","Identicon","defaults","background","margin","saturation","brightness","hue","foreground","hsl2rgb","isSvg","Svg","render","baseMargin","cell","bg","fg","rectangle","rectangles","xml","rect","stroke","base64map","crypt","rotl","endian","bytesToWords","words","wordsToBytes","bytesToBase64","triplet","imod4","cryptModule","charenc","stringToBytes","unescape","encodeURIComponent","bytesToString","decodeURIComponent","escape","charenc_1","isBuffer_1","isSlowBuffer","md5","FF","_ff","GG","_gg","HH","_hh","II","_ii","aa","bb","cc","dd","_blocksize","_digestsize","md5Module","digestbytes","asBytes","asString","mergeThings","mergeFn","dict","mergeUserGroups","mergeGroupChatDetails","mergeParticipants","mergePinnedMessages","mergeThreads","groupCanisterUpdates","groupCanisterUnfollowedThreads","readUpToUpdates","threadsRecord","groupUpdate","readUpToUpdate","readUpTo","buildBlobUrl","blobType","blobTypeFragment","buildTokenLogoUrl","logoId","buildUserAvatarUrl","identicon","buildIdenticonUrl","idlFactory","AllocatedBucketArgs","CanisterId","ProjectedAllowance","FileId","AllocatedBucketSuccessResult","AllocatedBucketResponse","UserNotFound","BucketUnavailable","CanForwardArgs","CanForwardResponse","UserArgs","UserRecord","UserResponse","allocated_bucket_v2","can_forward","CandidCanisterAgent","factory","handleQueryResponse","handleResponse","allocatedBucketResponse","fileId","chunkSize","projectedAllowance","allowanceExceeded","canForwardResponse","userResponse","byteLimit","bytesUsed","bytesUsedAfterOperation","StorageIndexClient","allocatedBucket","fileHash","fileIdSeed","canForward","DeleteFileArgs","DeleteFileResponse","NotFound","NotAuthorized","DeleteFilesArgs","DeleteFileFailureReason","DeleteFileFailure","DeleteFilesResponse","FileInfoArgs","FileInfoSuccessResult","FileInfoResponse","AccessorId","ForwardFileArgs","ForwardFileResponse","TimestampMillis","UploadChunkArgs","UploadChunkResponse","ChunkAlreadyExists","Full","ChunkSizeMismatch","FileTooBig","ChunkIndexTooHigh","FileExpired","HashMismatch","FileAlreadyExists","InvalidFileId","delete_file","delete_files","file_info","forward_file","upload_chunk_v2","uploadChunkResponse","forwardFileResponse","newFileId","deleteFileResponse","fileInfoResponse","isOwner","StorageBucketClient","uploadChunk","totalSize","expiryTimestampMillis","forwardFile","deleteFile","fileInfo","DataClient","EventTarget","storageIndexClient","openStorageIndexCanister","newBlobId","storageStatus","uploadData","accessorCanisterIds","updatedContent","accessorIds","uploadFile","extractBlobReference","videoRef","imageRef","dispatchEvent","forwardData","videoCanisterId","imageCanisterId","onProgress","sha3_256","hashBytes","bucketCanisterId","chunkIndexes","bucketClient","chunksCompleted","chunkBytes","attempt","pathPrefix","max32","generateUint64","mergeEventsResponse","chunkedChatEventsFromBackend","eventsFn","minIndex","maxIndex","aggregatedResponse","chunkedChatEventsWindowFromBackend","eventsWindowFn","highIndex","lowIndex","above","below","toggleNotificationsResponse","subscriptionExistsResponse","UserClient","handleMissingEvents","cachedEvents","chatEventsByIndexFromBackend","manageFavouriteChats","toAdd","toRemove","getInitialState","TEmpty","getUpdates","createCommunity","defaultChannels","defaultChannelRules","createGroup","deleteGroup","deleteCommunity","chatEventsByIndex","latest_client_event_index","chatEventsWindow","totalMiss","chatEventsWindowFromBackend","chatEventsFromBackend","setAvatar","editMessage","recipientId","req","sendMessage","messageFilterFailed","dataClient","newEvent","retVal","sendMessageWithTransferToGroup","sendMessageWithTransferToGroupToBackend","sendMessageWithTransferToGroupResponse","loadSavedCryptoAccounts","saveCryptoAccount","sendMessageWithTransferToChannel","communityRulesAccepted","channelRulesAccepted","sendMessageWithTransferToChannelToBackend","sendMessageWithTransferToChannelResponse","blockUser","unblockUser","leaveGroup","leaveCommunity","markMessageArg","markChannelMessageArg","markMessageArgs","markMessagesRead","tipMessage","addReaction","otherUserId","removeReaction","deleteMessage","undeleteMessage","searchDirectChat","searchDirectChatResponse","toggleMuteNotifications","muted","dismissRecommendation","getBio","getPublicProfile","setBio","withdrawCryptocurrency","apiPendingCryptocurrencyWithdrawal","toChatInList","favourite","pinChat","unpinChat","archiveChat","unarchiveChat","getDeletedMessage","setMessageReminder","cancelMessageReminder","setCommunityIndexes","communityIndexes","reportMessage","swapTokens","inputToken","outputToken","amountIn","minAmountOut","exchangeArgs","transferFee","tokenSwapStatus","approveTransfer","deleteDirectChat","acceptP2PSwap","cancelP2PSwap","joinVideoCall","setPinNumber","newPin","chitEvents","markAchievementsSeen","lastSeen","claimDailyChit","setChitInfoInCache","configureWallet","markActivityFeedRead","messageActivityFeed","updateInstalledBot","generateBotApiKey","getApiKey","generateBtcAddress","updateBtcBalance","withdrawBtc","groupChatSummaryUpdates","apiOptionalGroupPermissions","apiOptionalMessagePermissions","getMessagesByMessageIndexResponse","messagesSuccessResponse","convertToCommunityResponse","apiUpdatedRules","publicGroupSummary","publicSummaryResponse","GroupClient","inviteCode","summaryUpdates","changeRole","apiRole","removeMember","newAchievement","claimPrize","senderName","senderDisplayName","apiUserV2","eventsTimeToLiveMs","isPublic","asPlatformModerator","getGroupDetails","chatLastUpdated","getGroupDetailsUpdates","getGroupDetailsFromBackend","getGroupDetailsUpdatesFromBackend","updatesResponse","getPublicSummary","getMessagesByMessageIndex","messageIndexes","getMessagesByMessageIndexFromBackend","pinMessage","unpinMessage","registerPollVote","messageIdx","answerIdx","voteType","searchGroupChat","getInviteCode","enableInviteCode","disableInviteCode","resetInviteCode","threadPreviews","threadRootMessageIndexes","registerProposalVote","registerProposalVoteV2","declineInvitation","convertToCommunity","followThread","follow","videoCallParticipants","cancelInvites","commandArgumentHasValue","apiBotActionScope","userMessageId","apiBotCommandArg","apiBotCommandArgValue","apiCallType","accessTokenResponse","groupAndCommunitySummaryUpdates","chatEventsArgs","eventArgs","eventsContext","eventsArgsInner","midPoint","registerUserResponse","icpAccount","inviteUsersResponse","joinCommunityResponse","apiVerifiedCredentialArgs","userIIPrincipal","iiOrigin","credentialJwts","withdrawFromIcpSwapResponse","LocalUserIndexClient","isCommunity","cachePrimer","partialCachedResults","requestsToBackend","getEventsFromCache","batchResponse","getChatEventsFromBackend","chatEventsBatchResponse","registerUser","referralCode","joinCommunity","referredBy","joinGroup","joinChannel","joinChannelResponse","inviteUsersToCommunity","callerUsername","inviteUsersToGroup","inviteUsersToChannel","apiBotInstallationLocation","installBot","uninstallBot","getAccessToken","accessType","commandName","apiAccessTokenType","withdrawFromIcpSwap","NotificationsClient","subscriptionExists","pushSubscription","removeSubscription","submitProposalResponse","stakeNeuronForSubmittingProposalsResponse","topUpNeuronResponse","proposalToSubmit","proposalAction","functionId","ProposalsBotClient","submitProposal","proposalRejectionFee","transactionFee","stakeNeuronForSubmittingProposals","topUpNeuron","lastOnlineResponse","markAsOnlineResponse","OnlineClient","lastOnline","markAsOnline","minutesOnline","icrc1_balance_of","LedgerClient","accountBalance","UpgradeArg","ledger_id","retrieve_blocks_from_ledger_interval_seconds","InitArg","Upgrade","BlockIndex","SubAccount","GetAccountTransactionsArgs","Burn","created_at_time","Mint","Approve","expected_allowance","Transfer","Transaction","burn","mint","approve","TransactionWithId","GetTransactions","transactions","oldest_tx_id","GetTransactionsErr","GetTransactionsResult","GetBlocksRequest","Block","GetBlocksResponse","chain_length","FeeCollectorRanges","ranges","ListSubaccountsArgs","num_blocks_synced","get_account_transactions","get_blocks","get_fee_collectors_ranges","list_subaccounts","accountTransactions","oldestTransactionId","getTransactions","nanosToDate","createdAt","expectedAllowance","expiredAt","apiOptional","proposalVote","vote","apiProposalVote","LedgerIndexClient","getAccountTransactions","fromId","activeGroupsResponse","activeGroups","activeCommunities","deletedCommunities","deletedGroups","recommendedGroupsResponse","lookupChannelResponse","exploreCommunitiesResponse","communityMatch","exploreGroupsResponse","groupMatch","freezeGroupResponse","freezeCommunityResponse","unfreezeCommunityResponse","unfreezeGroupResponse","deleteFrozenGroupResponse","addHotGroupExclusionResponse","removeHotGroupExclusionResponse","setUpgradeConcurrencyResponse","setCommunityModerationFlagsResponse","channelCount","GroupIndexClient","communityIds","groupIds","activeSince","recommendedGroups","searchGroups","lookupChannelByGroupId","exploreCommunities","freezeGroup","freezeCommunity","unfreezeCommunity","unfreezeGroup","deleteFrozenGroup","addHotGroupExclusion","removeHotGroupExclusion","setCommunityModerationFlags","setGroupUpgradeConcurrency","setCommunityUpgradeConcurrency","markLocalGroupIndexFull","UpdateConfigArgs","max_orders_to_cancel_per_iteration","min_order_size","price_increment","min_orders_per_direction","min_sell_price","order_size","max_buy_price","spread","max_orders_to_make_per_iteration","max_orders_per_direction","UpdateConfigResponse","ExchangeNotFound","update_config","updateConfigResponse","MarketMakerClient","updateConfig","exchangeId","priceIncrement","orderSize","minOrderSize","maxBuyPrice","minSellPrice","minOrdersPerDirection","maxOrdersPerDirection","maxOrdersToMakePerIteration","maxOrdersToCancelPerIteration","registryCanisterId","channelName","communityName","tokenDetails","infoUrl","transactionUrlFormat","supportedStandards","nervousSystemSummary","swapProviders","swapProvider","messageFiltersAdded","messageFiltersRemoved","currentAirdropChannel","rootCanisterId","ledgerCanisterId","indexCanisterId","submittingProposalsEnabled","RegistryClient","TRegistryUpdatesResponse","addRemoveSwapProvider","addMessageFilter","removeMessageFilter","setTokenEnabled","Token","standard","PoolData","CommonError","UnsupportedToken","GetPoolsResponse","getPools","getPoolsResponse","isStandardSupported","dexName","QuoteArgs","amountOutMinimum","QuoteResponse","quoteForAll","quoteResponse","IcpSwapPoolClient","quote","IcpSwapIndexClient","getPoolClient","SwapAmountsReply","receive_amount","SwapAmountsResult","ICTokenReply","is_removed","LPTokenReply","TokenReply","IC","LP","TokensResult","swap_amounts","tokensResponse","swapAmountsResponse","KONG_SWAP_CANISTER_ID","KongSwapClient","icrc2Tokens","updateTokenDetails","_token0","_token1","pools","PairInfoExt","price0CumulativeLast","creator","reserve0","reserve1","lptoken","totalSupply","price1CumulativeLast","kLast","blockTimestampLast","getAllPairs","getPair","getPairResponse","SONIC_INDEX_CANISTER_ID","SonicSwapsClient","getAllPairsResponse","reserveIn","reserveOut","amountInWithFee","DexesAgent","_poolsCache","_swapIndexClients","icpswap","kongswap","sonic","getSwapPools","outputTokens","getAllSwapPools","canSwap","allPools","available","quoteSwap","quoteSingle","tryGetAllSwapPoolsFromCache","pool","indexClient","NeuronId","ListProposalInfo","include_reward_status","before_proposal","exclude_topic","include_status","Ballot","voting_power","timestamp_seconds","ProposalInfo","ballots","latest_tally","ListProposalInfoResponse","proposal_info","RegisterVote","Command","ManageNeuron","GovernanceError","error_type","Command_1","ManageNeuronResponse","list_proposals","manage_neuron","manageNeuronResponse","getProposalVoteDetails","neuronId","votingPower","latestTally","NnsGovernanceClient","registerVote","proposalId","GenericNervousSystemFunction","validator_canister_id","target_canister_id","validator_method_name","target_method_name","NativeNervousSystemFunction","NervousSystemFunction","function_type","ListNervousSystemFunctionsResponse","reserved_ids","functions","ProposalId","ListProposals","exclude_type","ProposalData","ListProposalsResponse","list_nervous_system_functions","nervousSystemFunctions","reservedIds","nervousSystemFunction","functionType","snsFunctionType","SnsGovernanceClient","base64String","listNervousSystemFunctions","AsyncMessageContextMap","insert","asyncMap","intermediate","CommunityClient","addMembersToChannel","changeChannelRole","changeChannelRoleResponse","createChannel","channel","deleteChannel","messageIds","eventsFromBackend","eventsByIndex","eventsByIndexFromBackend","eventsWindow","eventsWindowFromBackend","leaveChannel","removeMemberFromChannel","searchChannel","getCommunityDetails","communityLastUpdated","getCachedCommunityDetails","getCommunityDetailsUpdates","getCommunityDetailsFromBackend","getCommunityDetailsUpdatesFromBackend","commit","removeCachedChannelApiKeys","mergeCommunityDetails","getChannelDetails","getChannelDetailsUpdates","getChannelDetailsFromBackend","getChannelDetailsUpdatesFromBackend","sendMessageResponseV2","channelSummary","communityChannelSummaryResponse","importGroup","importGroupResponse","TCommunitySummaryResponse","exploreChannels","TCommunitySummaryUpdatesResponse","toggleMuteChannelNotifications","updateChannel","updateCommunity","createUserGroup","updateUserGroup","usersToAdd","usersToRemove","setMemberDisplayName","deleteUserGroups","userGroupIds","mergeChannels","userCanisterChannels","communityCanisterChannels","userCanisterGroupLookup","mergeChannelUpdates","userCanisterUpdates","communityCanisterUpdates","userLookup","channelLookup","blobReferenceUpdate","AnonUserClient","_toAdd","_toRemove","_updatesSince","_community","_rules","_defaultChannels","_defaultChannelRules","_group","_chatId","_eventIndexes","_threadRootMessageIndex","_latestKnownUpdate","_eventIndexRange","_messageIndex","_startIndex","_ascending","_bytes","_recipientId","_message","_event","_messageFilterFailed","_pin","_onRequestAccepted","sendMessageToBackend","_groupId","_sender","_rulesAccepted","_communityRulesAccepted","_channelRulesAccepted","_userId","_request","_messageContext","_messageId","_transfer","_decimals","_otherUserId","_reaction","_searchTerm","_maxResults","_muted","_bio","_domain","_favourite","_eventIndex","_remindAt","_notes","_reminderId","_communityIndexes","_deleteMessage","_swapId","_inputToken","_outputToken","_amountIn","_minAmountOut","_exchangeArgs","_spender","_ledger","_amount","_expiresIn","_blockUser","_presence","_verification","_newPin","_req","_lastSeen","_walletConfig","_timestamp","_since","_botId","_grantedPermissions","_permissions","_address","TokenId","LatestTokenRow","get_latest","parseSymbolPair","IcpCoinsClient","exchangeRates","supportedTokens","supportedSymbols","row","_pair","pairText","rate","toUSD","getLatestResponse","PublicTokenOverview","volumeUSD7d","priceUSD","getAllTokens","IcpSwapClient","supportedLedgers","getAllTokensResponse","TimeStamp","Operation","icrc1_memo","GetAccountIdentifierTransactionsResponse","GetAccountIdentifierTransactionsError","GetAccountIdentifierTransactionsResult","timestampToDate","ts","convertMemo","IcpLedgerIndexClient","ApproveArgs","ApproveResponse","NotProposed","MarkDeployedArgs","latest_approval","MarkDeployedResponse","EmptyArgs","Translation","locale","PendingDeploymentSuccessResult","translations","PendingDeploymentResponse","ProposeArgs","ProposeResponse","AlreadyProposed","InvalidArgs","CandidateTranslation","proposed_at","proposed_by","deployment_count","candidates","ProposedSuccessResult","records","ProposedResponse","RejectReason","IncorrectMeaning","RejectArgs","RejectResponse","mark_deployed","pending_deployment","propose","proposed","candidateTranslation","proposedAt","proposedBy","proposedResponse","deploymentCount","pendingDeploymentResponse","latestApproval","proposeResponse","approveResponse","rejectResponse","apiRejectReason","markDeployedResponse","TranslationsClient","markDeployed","pendingDeployment","Utxo","MinterInfo","retrieve_btc_min_amount","kyt_fee","estimate_withdrawal_fee","minter_fee","bitcoin_fee","get_deposit_fee","get_known_utxos","get_minter_info","getUtxosResponse","CkbtcMinterClient","cachedMinterInfo","mainnetEnabled","getKnownUtxos","getDepositInfo","minConfirmationsPromise","getMinterInfoCached","minConfirmations","depositFeePromise","depositFee","getWithdrawalInfo","minWithdrawalAmountPromise","minWithdrawalAmount","feeEstimatePromise","feeEstimate","getMinterInfo","GenerateMagicLinkArgs","session_key","email","max_time_to_live","GenerateMagicLinkSuccess","user_key","GenerateMagicLinkResponse","Blocked","EmailInvalid","FailedToSendEmail","GetDelegationArgs","GetDelegationResponse","HttpRequest","HttpResponse","generate_magic_link","get_delegation","http_request_update","rsa_public_key","generateMagicLinkResponse","userKey","createIdentityResponse","prepareDelegationSuccess","checkAuthPrincipalResponse","webAuthnKey","webauthn_key","originatingCanister","originating_canister","isIIPrincipal","is_ii_principal","prepareDelegationResponse","getDelegationResponse","generateChallengeResponse","pngBase64","png_base64","initiateIdentityLinkResponse","authPrincipalsResponse","isCurrentIdentity","is_current_identity","approveIdentityLinkResponse","removeIdentityLinkResponse","credentialId","credential_id","crossPlatform","cross_platform","aaguid","apiWebAuthnKey","SignInWithEmailClient","generateMagicLink","sessionKey","RuntimeFeature","IncludeUriInSeed","DisableEthToPrincipalMapping","DisablePrincipalToEthMapping","uri","runtime_features","statement","scheme","salt","session_expires_in","chain_id","sign_in_expires_in","Address","GetAddressResponse","GetPrincipalResponse","PublicKey","SessionKey","Timestamp","SiweSignature","CanisterPublicKey","LoginDetails","user_canister_pubkey","LoginResponse","SiweMessage","PrepareLoginResponse","get_address","get_caller_address","get_principal","siwe_get_delegation","siwe_login","siwe_prepare_login","prepareLoginResponse","siweMessage","loginResponse","SignInWithEthereumClient","prepareLogin","login","DisablePrincipalToSolMapping","DisableSolToPrincipalMapping","SiwsSignature","SiwsMessage","issued_at","expiration_time","siws_get_delegation","siws_login","siws_prepare_login","siwsMessage","issuedAt","chainId","SignInWithSolanaClient","createHttpAgentInternal","fetchRootKeyPromise","lazyOpenReferralCache","deleteCommunityReferral","mean","ApiBotSuccess","ephemeral","ApiBotBadRequest","ApiBotInternalError","ApiBotResponse","BadRequest","validateBotDefinition","formatError","validateBotResponse","externalBotResponse","regtest","get_utxos_request","block_height","block_hash","get_utxos_response","bitcoin_get_utxos_query","BitcoinClient","getUtxos","OpenChatAgent","_logger","_agent","createHttpAgentSync","_onlineClient","onlineCanister","_userIndexClient","userIndexCanister","_groupIndexClient","groupIndexCanister","_notificationClient","notificationsCanister","_registryClient","registryCanister","_dataClient","_exchangeRateClients","_localUserIndexClients","_ledgerClients","_ledgerIndexClients","_groupClients","_communityClients","_groupInvite","groupInvite","_bitcoinClient","bitcoinMainnetEnabled","_ckbtcMinterClient","_dexesAgent","_marketMakerClient","marketMakerCanister","_proposalsBotClient","proposalBotCanister","_signInWithEmailClient","signInWithEmailCanister","_signInWithEthereumClient","signInWithEthereumCanister","_signInWithSolanaClient","signInWithSolanaCanister","_translationsClient","translationsCanister","getAllCachedUsers","measure","reallyDeleted","getAllUsers","rehydrateUserSummary","logError","optionalParams","communityInvite","_communityInvite","createUserClient","_userClient","communityClient","getProvidedCommunityInviteCode","getGroupClient","getProvidedGroupInviteCode","userClient","getLedgerClient","getLedgerIndexClient","ledgerIndex","getLocalUserIndexClient","getCommunityReferral","oneWeekInMs","translationsClient","editDirectMessage","editGroupMessage","editChannelMessage","acceptedRules","sendChannelMessage","sendGroupMessage","sendDirectMessage","createGroupChat","candidate","desc","eventsTimeToLive","chatEventsBatch","directChatEventsWindow","groupChatEventsWindow","channelEventsWindow","rehydrateEventResponse","groupChatEvents","directChatEvents","channelEvents","directChatEventsByEventIndex","rawEvents","chatEventsByEventIndex","groupChatEventsByEventIndex","channelEventsByEventIndex","getDeletedGroupMessage","groupResp","rehydrateMessageContent","channelResp","getDeletedDirectMessage","rehydrateDataContent","findMissingEventIndexesByChat","defaultChatId","messagesFromEventsResponse","resolveMissingIndexes","currentChatId","contextMap","idxs","chatKind","latestUpdate","rehydrateEvent","missingReplies","originalContent","rehydratedContent","originalReplyContext","rehydratedReplyContext","me","isThreadRoot","eventsPromise","callBotCommandEndpoint","dataContent","rehydrateMessage","getUser","getUpdatedPinnedChannels","currentPinnedChannels","byCommunity","flat","_getUpdates","numberOfAsyncCalls","directChatUpdates","currentGroups","groupsAdded","userCanisterGroupUpdates","groupsToCheckForUpdates","groupsRemoved","currentCommunities","communitiesAdded","userCanisterCommunityUpdates","communitiesToCheckForUpdates","communitiesRemoved","pinnedGroupChats","pinnedDirectChats","pinnedFavouriteChats","pinnedChannels","suspensionChanged","userCanisterLocalUserIndex","newAchievements","installedBots","latestActiveGroupsCheck","anyUpdates","removeDirectChatIds","mergeDirectChatUpdates","lowerBound","deleteEventsForChat","prev","latest","currentGroupChatIds","currentCommunityIds","groupIndexResponse","recentlyJoinedCutOff","byLocalUserIndex","summaryUpdatesPromises","batch","summaryUpdatesResults","groupCanisterGroupSummaries","communityCanisterCommunitySummaries","groupUpdates","communityUpdates","anyErrors","userCanisterGroups","groupCanisterGroups","mergeGroupChats","groupLookup","mergeGroupChatUpdates","userCanisterCommunities","communityCanisterCommunities","userCanisterCommunityLookup","mergeCommunities","communityLookup","avatarUpdate","bannerUpdate","currentChannels","mergeCommunityUpdates","removeExpiredLatestMessages","getUpdatedEvents","chatState","stateToCache","chatsStore","threadsStore","deleteRequests","setCachedChats","hydrateChatState","initialLoad","cachedState","getCommunitySummary","hydrateCommunity","hydrateChatSummary","blockUserFromDirectChat","blockUserFromGroupChat","unblockUserFromGroupChat","unblockUserFromDirectChat","localUserIndexClient","groupInviteCode","communityInviteCode","setUserAvatar","deleteGroupMessage","deleteDirectMessage","deleteChannelMessage","getPublicGroupSummary","getRecommendedGroups","isUserIdDeleted","getUserStorageLimits","refreshAccountBalance","icpLedgerIndex","_registryValue","ns","getGroupMessagesByMessageIndex","snsGovernanceCanisterId","threadsByChat","latestMessageTimestamp","threadSyncs","rehydrateThreadPreview","threadMissing","rootMissing","setCachedMessageFromNotification","deleteFailedMessage","topUpNeuronForSubmittingProposals","updateMarketMakerConfig","convertGroupToCommunity","getRegistry","getCachedRegistry","messageFilters","setCachedRegistry","currentUserId","tokenLedgers","getTokenSwaps","inputTokenLedger","outputTokenLedgers","swapReducer","outputTokenLedger","getTokenSwapQuotes","quotes","_dexA","amountA","_dexB","amountB","inputTokenDetails","outputTokenDetails","exchangeRatesFromAllProviders","accessTokenType","getLocalUserIndexForUser","cacheLocalUserIndexForUser","allUtxos","knownUtxos","knownUtxosSet","getCkbtcMinterDepositInfo","getCkbtcMinterWithdrawalInfo","getSignInWithEmailDelegation","siwePrepareLogin","siwsPrepareLogin","loginWithWallet","getDelegationWithWallet","clearCachedData","clearUserCache","clearReferralCache","getCachedExternalAchievements","mergeExternalAchievements","setCachedExternalAchievements","getActivityFeedEvents","combined","deduped","setActivityFeedEvents","hydrateActivityFeedEvents","hydrated","activityEvents","eventIndexesByMessageContext","withCachedMessages","getMessagesByMessageContext","anyMissing","withServerMessages","allMissing","addMissing","getChannelSummary","localUserIndexForBotContext","cachedBots","getCachedBots","setCachedBots","TimestampNanoseconds","ApproveIdentityLinkArgs","link_initiated_by","ApproveIdentityLinkResponse","LinkRequestNotFound","InvalidSignature","PrincipalAlreadyLinkedToAnotherOcUser","DelegationTooOld","CallerNotRecognised","WebAuthnKey","AuthPrincipalsResponse","last_used","CheckAuthPrincipalResponse","CheckAuthPrincipalV2Response","Nanoseconds","CreateIdentityArgs","challenge_attempt","chars","PrepareDelegationSuccess","CreateIdentityResponse","AlreadyRegistered","OriginatingCanisterInvalid","ChallengeFailed","ChallengeRequired","GenerateChallengeResponse","Throttled","InitiateIdentityLinkArgs","link_to_principal","InitiateIdentityLinkResponse","TargetUserNotFound","AlreadyLinkedToPrincipal","LinkedIdentitiesLimitReached","LookupWebAuthnPubKeyArgs","LookupWebAuthnPubKeyResponse","PrepareDelegationArgs","PrepareDelegationResponse","RemoveIdentityLinkArgs","linked_principal","RemoveIdentityLinkResponse","CannotUnlinkActivePrincipal","IdentityLinkNotFound","approve_identity_link","auth_principals","check_auth_principal","check_auth_principal_v2","create_identity","generate_challenge","initiate_identity_link","lookup_webauthn_pubkey","prepare_delegation","remove_identity_link","IdentityClient","identityCanister","createIdentity","challengeAttempt","checkAuthPrincipal","prepareDelegation","generateChallenge","initiateIdentityLink","linkToPrincipal","approveIdentityLink","linkInitiatedBy","removeIdentityLink","getAuthenticationPrincipals","lookupWebAuthnPubKey","STORE_NAME","lazyOpenWebAuthnKeyCache","getCachedWebAuthnKey","IdentityAgent","_identityClient","_isIIPrincipal","createHttpAgent","checkOpenChatIdentityExists","createOpenChatIdentity","webAuthnCredentialId","hydrateWebAuthnKey","sessionKeyDer","getOpenChatIdentity","delegationChain","buildDelegationIdentity","authIdentityStorage","ocIdentityStorage","initPayload","identityAgent","authPrincipalString","handleAgentEvent","sendEvent","subkind","sendError","correlationId","postMessage","streamReplies","sendResponse","executeThenReply","expectedAuthPrincipal","authProvider","_identityCanister","_icUrl","authProviderIdentity","ocIdentity","initialize","apikey","rollbarApiKey","websiteVersion","Rollbar","source_map_enabled","code_version","guess_uncaught_frames","namedAccount","setCachedWebAuthnKey","initiatorKey","initiatorDelegation","initiatorIsIIPrincipal","initiatorWebAuthnKey","approverKey","approverDelegation","initiatorIdentity","initiatorAgent","approverIdentity","approverAgent","approver","initiateResponse","initiatorPrincipal","linkIdentities","setCommunityReferral"],"mappings":"yPAWA,gBATAA,WAuCA,SAAqBC,GACnB,IAAIC,EAAOC,EAAQF,GACfG,EAAWF,EAAK,GAChBG,EAAkBH,EAAK,GAC3B,OAAuC,GAA9BE,EAAWC,GAAuB,EAAKA,CAClD,EA3CAL,YAiDA,SAAsBC,GACpB,IAAIK,EAcAC,EAbAL,EAAOC,EAAQF,GACfG,EAAWF,EAAK,GAChBG,EAAkBH,EAAK,GAEvBM,EAAM,IAAIC,EAVhB,SAAsBR,EAAKG,EAAUC,GACnC,OAAuC,GAA9BD,EAAWC,GAAuB,EAAKA,CAClD,CAQoBK,CAAYT,EAAKG,EAAUC,IAEzCM,EAAU,EAGVC,EAAMP,EAAkB,EACxBD,EAAW,EACXA,EA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AAS,EAAK,EAExB,OAAO,CACX,CAIE,IAAIg2B,GAAY,CAEdG,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EAEAE,EAEAC,EAEAC,EAEAC,EACAiD,GACAA,GACAA,GACAA,GAEAhD,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EACAA,EAEAC,EAEAC,EAEAC,GAEAC,GACA4C,GACAA,GACAA,GACAA,GAEAhN,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GAEAsK,GAEAC,GAEAC,GAEAC,GACAuC,GACAA,GACAA,GAEAtC,GAEAzK,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GAEA0K,GAEAC,GAEAC,GAEAC,GAEAkC,GACAA,GACAA,GACAjC,GAEA7K,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GAEA8K,GAEAC,GAEAC,GAEAC,GAEA6B,GACAA,GACAA,GACA5B,GAEAjL,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GACAA,GAEAkL,GAEAC,GAEAC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BACD,MAAO,6BACX,IAAK,aACD,MAAO,cACX,IAAK,cACD,MAAO,eACX,IAAK,gBACD,MAAO,iBACX,IAAK,YACD,MAAO,aACX,IAAK,mBACD,MAAO,qBACX,IAAK,oBACD,MAAO,sBACX,IAAK,gBACD,MAAO,iBACX,IAAK,mBACD,MAAO,qBACX,IAAK,uBACD,MAAO,sBACX,IAAK,aACD,MAAO,cACX,IAAK,YACD,MAAO,aACX,IAAK,mBACD,MAAO,oBACX,IAAK,YACD,MAAO,aACX,IAAK,iBACD,MAAO,kBACX,IAAK,eACD,MAAO,gBACX,IAAK,yBACD,MAAO,2BACX,IAAK,iBACD,MAAO,kBACX,IAAK,WACD,MAAO,YACX,IAAK,mBACD,MAAO,kBACX,IAAK,eACD,MAAO,gBACX,IAAK,aACD,MAAO,cACX,IAAK,iBACD,MAAO,kBACX,IAAK,kBACD,MAAO,oBACX,IAAK,WACD,MAAO,YACX,IAAK,WACD,MAAO,YACX,IAAK,WACD,MAAO,YACX,IAAK,YACD,MAAO,aACX,IAAK,YACD,MAAO,aACX,IAAK,kBACD,MAAO,mBACX,IAAK,cACD,MAAO,eACX,IAAK,WACD,MAAO,YACX,IAAK,WACD,MAAO,YACX,IAAK,oBACD,MAAO,sBACX,IAAK,wBACD,MAAO,0BACX,IAAK,iBACD,MAAO,mBACX,IAAK,SACD,MAAO,UACX,IAAK,UACD,MAAO,WACX,IAAK,UACD,MAAO,WACX,IAAK,YACD,MAAO,aACX,IAAK,YACD,MAAO,aACX,IAAK,wBACD,MAAO,0BACX,IAAK,oBACD,MAAO,sBACX,IAAK,YACD,MAAO,aACX,IAAK,kBACD,MAAO,oBACX,IAAK,kBACD,MAAO,oBACX,IAAK,mBACD,MAAO,qBACX,IAAK,mBACD,MAAO,qBACX,IAAK,mBACD,MAAO,qBACX,IAAK,SACD,MAAO,UACX,IAAK,eACD,MAAO,gBACX,QACI,MAAM,IAAIwmF,GAAsB,qCAAsCxmF,GAElF,CACO,SAAS09M,GAA0B19M,GAC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t8D,MAHQ,uCAAuCnB,EAAIo6D,WAAWp6D,EAAIqoE,eAAe33D,KAAKC,UAAUqmD,QAOvGuS,KAAK07K,MSgxBE,MACJ,IAAK,yBACD+X,GAAiBr9L,EAASi9L,EAAerhM,GAAMoxL,uBAAuBhtL,EAAQ3I,SAAU2I,EAAQ2rC,QAChG,MACJ,IAAK,sBACD0xJ,GAAiBr9L,EAASi9L,EAAerhM,GAAMohK,oBAAoBh9J,EAAQuf,OAAQvf,EAAQ0sC,OAAQ1sC,EAAQ60J,WAAY70J,EAAQhsD,OAAQgsD,EAAQ03E,MAC/I,MACJ,QACI1qD,IAAQ7H,MAAM,0CAA2CrnB,GAEpE,CACD,MAAOx0C,GACH0jE,IAAQ7H,MAAM,4BAA6B77D,GAC3C0zO,GAAUC,EAAVD,CAAyB1zO,EAC5B,CT5yBE,IAA0B+tC,CS4yB5B","x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,98,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,123,124,127,151,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,234,235,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,298,299,300,301,302,303,304,384,385]}