@metamask/snaps-utils 12.0.1 → 12.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [12.1.1]
11
+
12
+ ### Changed
13
+
14
+ - Move `isSnapError` and `isSerializedSnapError` to `@metamask/snaps-sdk` ([#3891](https://github.com/MetaMask/snaps/pull/3891))
15
+ - They are re-exported from this package for backwards compatibility, but will
16
+ be removed in a future release.
17
+
18
+ ## [12.1.0]
19
+
20
+ ### Added
21
+
22
+ - Add types for Snap's `StorageService` data ([#3777](https://github.com/MetaMask/snaps/pull/3777))
23
+ - Add Canton Network derivation path ([#3833](https://github.com/MetaMask/snaps/pull/3833))
24
+
25
+ ### Changed
26
+
27
+ - Bump `@metamask/slip44` from `4.3.0` to `4.4.0` ([#3834](https://github.com/MetaMask/snaps/pull/3834))
28
+ - Bump `fast-xml-parser` from `4.5.3` to `5.3.4` ([#3831](https://github.com/MetaMask/snaps/pull/3831))
29
+
10
30
  ## [12.0.1]
11
31
 
12
32
  ### Fixed
@@ -773,7 +793,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
773
793
  - The version of the package no longer needs to match the version of all other
774
794
  MetaMask Snaps packages.
775
795
 
776
- [Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@12.0.1...HEAD
796
+ [Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@12.1.1...HEAD
797
+ [12.1.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@12.1.0...@metamask/snaps-utils@12.1.1
798
+ [12.1.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@12.0.1...@metamask/snaps-utils@12.1.0
777
799
  [12.0.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@12.0.0...@metamask/snaps-utils@12.0.1
778
800
  [12.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@11.7.1...@metamask/snaps-utils@12.0.0
779
801
  [11.7.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@11.7.0...@metamask/snaps-utils@11.7.1
@@ -187,6 +187,11 @@ exports.SNAPS_DERIVATION_PATHS = [
187
187
  curve: 'ed25519',
188
188
  name: 'IOTA',
189
189
  },
190
+ {
191
+ path: ['m', `44'`, `6767'`],
192
+ curve: 'ed25519',
193
+ name: 'Canton',
194
+ },
190
195
  ];
191
196
  /**
192
197
  * Gets the name of a derivation path supported by snaps.
@@ -1 +1 @@
1
- {"version":3,"file":"derivation-paths.cjs","sourceRoot":"","sources":["../src/derivation-paths.ts"],"names":[],"mappings":";;;;;;AACA,8DAAsC;AAEtC,uCAAkC;AAQrB,QAAA,sBAAsB,GAA0B;IAC3D;QACE,IAAI,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC;QACxB,KAAK,EAAE,SAAS;QAChB,IAAI,EAAE,4BAA4B;KACnC;IACD;QACE,IAAI,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC;QACxB,KAAK,EAAE,WAAW;QAClB,IAAI,EAAE,SAAS;KAChB;IACD;QACE,IAAI,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC;QACxB,KAAK,EAAE,WAAW;QAClB,IAAI,EAAE,gBAAgB;KACvB;IACD;QACE,IAAI,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC;QACxB,KAAK,EAAE,WAAW;QAClB,IAAI,EAAE,uBAAuB;KAC9B;IACD;QACE,IAAI,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC;QACxB,KAAK,EAAE,WAAW;QAClB,IAAI,EAAE,+BAA+B;KACtC;IACD;QACE,IAAI,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC;QACxB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QAChB,IAAI,EAAE,MAAM;KACb;CACF,CAAC;AAEF;;;;;;GAMG;AACH,SAAgB,yBAAyB,CACvC,IAAiC,EACjC,KAAqB;IAErB,MAAM,YAAY,GAAG,8BAAsB,CAAC,IAAI,CAC9C,CAAC,cAAc,EAAE,EAAE,CACjB,cAAc,CAAC,KAAK,KAAK,KAAK,IAAI,IAAA,eAAO,EAAC,cAAc,CAAC,IAAI,EAAE,IAAI,CAAC,CACvE,CAAC;IAEF,IAAI,YAAY,EAAE,CAAC;QACjB,OAAO,YAAY,CAAC,IAAI,CAAC;IAC3B,CAAC;IAED,+DAA+D;IAC/D,yDAAyD;IACzD,IACE,KAAK,KAAK,WAAW;QACrB,IAAI,CAAC,CAAC,CAAC,KAAK,GAAG;QACf,IAAI,CAAC,CAAC,CAAC,KAAK,KAAK;QACjB,IAAI,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,EACrB,CAAC;QACD,MAAM,QAAQ,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;QACtC,OAAO,qBAAqB,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC;IACjD,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC;AA1BD,8DA0BC;AAED;;;;;;;GAOG;AACH,SAAgB,qBAAqB,CAAC,QAAyB;IAC7D,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,GAAG,EAAE,CAAC;QAC7B,OAAO,eAAe,CAAC;IACzB,CAAC;IAED,OAAO,gBAAM,CAAC,QAA+B,CAAC,EAAE,IAAI,IAAI,IAAI,CAAC;AAC/D,CAAC;AAND,sDAMC","sourcesContent":["import type { SupportedCurve } from '@metamask/key-tree';\nimport slip44 from '@metamask/slip44';\n\nimport { isEqual } from './array';\n\nexport type SnapsDerivationPath = {\n path: ['m', ...string[]];\n curve: SupportedCurve;\n name: string;\n};\n\nexport const SNAPS_DERIVATION_PATHS: SnapsDerivationPath[] = [\n {\n path: ['m', `44'`, `0'`],\n curve: 'ed25519',\n name: 'Test BIP-32 Path (ed25519)',\n },\n {\n path: ['m', `44'`, `1'`],\n curve: 'secp256k1',\n name: 'Testnet',\n },\n {\n path: ['m', `44'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Legacy',\n },\n {\n path: ['m', `49'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Nested SegWit',\n },\n {\n path: ['m', `49'`, `1'`],\n curve: 'secp256k1',\n name: 'Bitcoin Testnet Nested SegWit',\n },\n {\n path: ['m', `84'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Native SegWit',\n },\n {\n path: ['m', `84'`, `1'`],\n curve: 'secp256k1',\n name: 'Bitcoin Testnet Native SegWit',\n },\n {\n path: ['m', `86'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Taproot',\n },\n {\n path: ['m', `86'`, `1'`],\n curve: 'secp256k1',\n name: 'Bitcoin Testnet Taproot',\n },\n {\n path: ['m', `44'`, `501'`],\n curve: 'ed25519',\n name: 'Solana',\n },\n {\n path: ['m', `44'`, `501'`, \"0'\", \"0'\"],\n curve: 'ed25519',\n name: 'Solana',\n },\n {\n path: ['m', `44'`, `2'`],\n curve: 'secp256k1',\n name: 'Litecoin',\n },\n {\n path: ['m', `44'`, `3'`],\n curve: 'secp256k1',\n name: 'Dogecoin',\n },\n {\n path: ['m', `44'`, `60'`],\n curve: 'secp256k1',\n name: 'Ethereum',\n },\n {\n path: ['m', `44'`, `118'`],\n curve: 'secp256k1',\n name: 'Atom',\n },\n {\n path: ['m', `44'`, `145'`],\n curve: 'secp256k1',\n name: 'Bitcoin Cash',\n },\n {\n path: ['m', `44'`, `637'`],\n curve: 'ed25519',\n name: 'Aptos',\n },\n {\n path: ['m', `44'`, `714'`],\n curve: 'secp256k1',\n name: 'Binance (BNB)',\n },\n {\n path: ['m', `44'`, `784'`],\n curve: 'ed25519',\n name: 'Sui',\n },\n {\n path: ['m', `44'`, `931'`],\n curve: 'secp256k1',\n name: 'THORChain (RUNE)',\n },\n {\n path: ['m', `44'`, `330'`],\n curve: 'secp256k1',\n name: 'Terra (LUNA)',\n },\n {\n path: ['m', `44'`, `459'`],\n curve: 'secp256k1',\n name: 'Kava',\n },\n {\n path: ['m', `44'`, `529'`],\n curve: 'secp256k1',\n name: 'Secret Network',\n },\n {\n path: ['m', `44'`, `397'`, `0'`],\n curve: 'ed25519',\n name: 'NEAR Protocol',\n },\n {\n path: ['m', `44'`, `1'`, `0'`],\n curve: 'ed25519',\n name: 'Testnet',\n },\n {\n path: ['m', `44'`, `472'`],\n curve: 'ed25519',\n name: 'Arweave',\n },\n {\n path: ['m', `44'`, `12586'`],\n curve: 'secp256k1',\n name: 'Mina',\n },\n {\n path: ['m', `44'`, `242'`],\n curve: 'ed25519',\n name: 'Nimiq',\n },\n {\n path: ['m', `44'`, `1729'`, `0'`, `0'`],\n curve: 'ed25519',\n name: 'Tezos',\n },\n {\n path: ['m', `1789'`, `0'`],\n curve: 'ed25519',\n name: 'Vega',\n },\n {\n path: ['m', `1852'`, `1815'`],\n curve: 'ed25519Bip32',\n name: 'Cardano',\n },\n {\n path: ['m', `44'`, `508'`, `0'`, `0'`, `0'`],\n curve: 'ed25519',\n name: 'MultiversX',\n },\n {\n path: ['m', `44'`, `709'`],\n curve: 'secp256k1',\n name: 'Avail',\n },\n {\n path: ['m', `44'`, `626'`],\n curve: 'ed25519',\n name: 'Kadena',\n },\n {\n path: ['m', `44'`, `632'`],\n curve: 'ed25519',\n name: 'Massa',\n },\n {\n path: ['m', `44'`, `4218'`],\n curve: 'ed25519',\n name: 'IOTA',\n },\n];\n\n/**\n * Gets the name of a derivation path supported by snaps.\n *\n * @param path - The derivation path.\n * @param curve - The curve used to derive the keys.\n * @returns The name of the derivation path, otherwise null.\n */\nexport function getSnapDerivationPathName(\n path: SnapsDerivationPath['path'],\n curve: SupportedCurve,\n): string | null {\n const pathMetadata = SNAPS_DERIVATION_PATHS.find(\n (derivationPath) =>\n derivationPath.curve === curve && isEqual(derivationPath.path, path),\n );\n\n if (pathMetadata) {\n return pathMetadata.name;\n }\n\n // If the curve is secp256k1 and the path is a valid BIP44 path\n // we try looking for the network/protocol name in SLIP44\n if (\n curve === 'secp256k1' &&\n path[0] === 'm' &&\n path[1] === `44'` &&\n path[2].endsWith(`'`)\n ) {\n const coinType = path[2].slice(0, -1);\n return getSlip44ProtocolName(coinType) ?? null;\n }\n\n return null;\n}\n\n/**\n * Gets the name of the SLIP-44 protocol corresponding to the specified\n * `coin_type`.\n *\n * @param coinType - The SLIP-44 `coin_type` value whose name\n * to retrieve.\n * @returns The name of the protocol, otherwise null.\n */\nexport function getSlip44ProtocolName(coinType: number | string) {\n if (String(coinType) === '1') {\n return 'Test Networks';\n }\n\n return slip44[coinType as keyof typeof slip44]?.name ?? null;\n}\n"]}
1
+ {"version":3,"file":"derivation-paths.cjs","sourceRoot":"","sources":["../src/derivation-paths.ts"],"names":[],"mappings":";;;;;;AACA,8DAAsC;AAEtC,uCAAkC;AAQrB,QAAA,sBAAsB,GAA0B;IAC3D;QACE,IAAI,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC;QACxB,KAAK,EAAE,SAAS;QAChB,IAAI,EAAE,4BAA4B;KACnC;IACD;QACE,IAAI,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC;QACxB,KAAK,EAAE,WAAW;QAClB,IAAI,EAAE,SAAS;KAChB;IACD;QACE,IAAI,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC;QACxB,KAAK,EAAE,WAAW;QAClB,IAAI,EAAE,gBAAgB;KACvB;IACD;QACE,IAAI,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC;QACxB,KAAK,EAAE,WAAW;QAClB,IAAI,EAAE,uBAAuB;KAC9B;IACD;QACE,IAAI,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC;QACxB,KAAK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IAAI,IAAI,IAAI,CAAC;AAC/D,CAAC;AAND,sDAMC","sourcesContent":["import type { SupportedCurve } from '@metamask/key-tree';\nimport slip44 from '@metamask/slip44';\n\nimport { isEqual } from './array';\n\nexport type SnapsDerivationPath = {\n path: ['m', ...string[]];\n curve: SupportedCurve;\n name: string;\n};\n\nexport const SNAPS_DERIVATION_PATHS: SnapsDerivationPath[] = [\n {\n path: ['m', `44'`, `0'`],\n curve: 'ed25519',\n name: 'Test BIP-32 Path (ed25519)',\n },\n {\n path: ['m', `44'`, `1'`],\n curve: 'secp256k1',\n name: 'Testnet',\n },\n {\n path: ['m', `44'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Legacy',\n },\n {\n path: ['m', `49'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Nested SegWit',\n },\n {\n path: ['m', `49'`, `1'`],\n curve: 'secp256k1',\n name: 'Bitcoin Testnet Nested SegWit',\n },\n {\n path: ['m', `84'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Native SegWit',\n },\n {\n path: ['m', `84'`, `1'`],\n curve: 'secp256k1',\n name: 'Bitcoin Testnet Native SegWit',\n },\n {\n path: ['m', `86'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Taproot',\n },\n {\n path: ['m', `86'`, `1'`],\n curve: 'secp256k1',\n name: 'Bitcoin Testnet Taproot',\n },\n {\n path: ['m', `44'`, `501'`],\n curve: 'ed25519',\n name: 'Solana',\n },\n {\n path: ['m', `44'`, `501'`, \"0'\", \"0'\"],\n curve: 'ed25519',\n name: 'Solana',\n },\n {\n path: ['m', `44'`, `2'`],\n curve: 'secp256k1',\n name: 'Litecoin',\n },\n {\n path: ['m', `44'`, `3'`],\n curve: 'secp256k1',\n name: 'Dogecoin',\n },\n {\n path: ['m', `44'`, `60'`],\n curve: 'secp256k1',\n name: 'Ethereum',\n },\n {\n path: ['m', `44'`, `118'`],\n curve: 'secp256k1',\n name: 'Atom',\n },\n {\n path: ['m', `44'`, `145'`],\n curve: 'secp256k1',\n name: 'Bitcoin Cash',\n },\n {\n path: ['m', `44'`, `637'`],\n curve: 'ed25519',\n name: 'Aptos',\n },\n {\n path: ['m', `44'`, `714'`],\n curve: 'secp256k1',\n name: 'Binance (BNB)',\n },\n {\n path: ['m', `44'`, `784'`],\n curve: 'ed25519',\n name: 'Sui',\n },\n {\n path: ['m', `44'`, `931'`],\n curve: 'secp256k1',\n name: 'THORChain (RUNE)',\n },\n {\n path: ['m', `44'`, `330'`],\n curve: 'secp256k1',\n name: 'Terra (LUNA)',\n },\n {\n path: ['m', `44'`, `459'`],\n curve: 'secp256k1',\n name: 'Kava',\n },\n {\n path: ['m', `44'`, `529'`],\n curve: 'secp256k1',\n name: 'Secret Network',\n },\n {\n path: ['m', `44'`, `397'`, `0'`],\n curve: 'ed25519',\n name: 'NEAR Protocol',\n },\n {\n path: ['m', `44'`, `1'`, `0'`],\n curve: 'ed25519',\n name: 'Testnet',\n },\n {\n path: ['m', `44'`, `472'`],\n curve: 'ed25519',\n name: 'Arweave',\n },\n {\n path: ['m', `44'`, `12586'`],\n curve: 'secp256k1',\n name: 'Mina',\n },\n {\n path: ['m', `44'`, `242'`],\n curve: 'ed25519',\n name: 'Nimiq',\n },\n {\n path: ['m', `44'`, `1729'`, `0'`, `0'`],\n curve: 'ed25519',\n name: 'Tezos',\n },\n {\n path: ['m', `1789'`, `0'`],\n curve: 'ed25519',\n name: 'Vega',\n },\n {\n path: ['m', `1852'`, `1815'`],\n curve: 'ed25519Bip32',\n name: 'Cardano',\n },\n {\n path: ['m', `44'`, `508'`, `0'`, `0'`, `0'`],\n curve: 'ed25519',\n name: 'MultiversX',\n },\n {\n path: ['m', `44'`, `709'`],\n curve: 'secp256k1',\n name: 'Avail',\n },\n {\n path: ['m', `44'`, `626'`],\n curve: 'ed25519',\n name: 'Kadena',\n },\n {\n path: ['m', `44'`, `632'`],\n curve: 'ed25519',\n name: 'Massa',\n },\n {\n path: ['m', `44'`, `4218'`],\n curve: 'ed25519',\n name: 'IOTA',\n },\n {\n path: ['m', `44'`, `6767'`],\n curve: 'ed25519',\n name: 'Canton',\n },\n];\n\n/**\n * Gets the name of a derivation path supported by snaps.\n *\n * @param path - The derivation path.\n * @param curve - The curve used to derive the keys.\n * @returns The name of the derivation path, otherwise null.\n */\nexport function getSnapDerivationPathName(\n path: SnapsDerivationPath['path'],\n curve: SupportedCurve,\n): string | null {\n const pathMetadata = SNAPS_DERIVATION_PATHS.find(\n (derivationPath) =>\n derivationPath.curve === curve && isEqual(derivationPath.path, path),\n );\n\n if (pathMetadata) {\n return pathMetadata.name;\n }\n\n // If the curve is secp256k1 and the path is a valid BIP44 path\n // we try looking for the network/protocol name in SLIP44\n if (\n curve === 'secp256k1' &&\n path[0] === 'm' &&\n path[1] === `44'` &&\n path[2].endsWith(`'`)\n ) {\n const coinType = path[2].slice(0, -1);\n return getSlip44ProtocolName(coinType) ?? null;\n }\n\n return null;\n}\n\n/**\n * Gets the name of the SLIP-44 protocol corresponding to the specified\n * `coin_type`.\n *\n * @param coinType - The SLIP-44 `coin_type` value whose name\n * to retrieve.\n * @returns The name of the protocol, otherwise null.\n */\nexport function getSlip44ProtocolName(coinType: number | string) {\n if (String(coinType) === '1') {\n return 'Test Networks';\n }\n\n return slip44[coinType as keyof typeof slip44]?.name ?? null;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"derivation-paths.d.cts","sourceRoot":"","sources":["../src/derivation-paths.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,2BAA2B;AAKzD,MAAM,MAAM,mBAAmB,GAAG;IAChC,IAAI,EAAE,CAAC,GAAG,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC;IACzB,KAAK,EAAE,cAAc,CAAC;IACtB,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,eAAO,MAAM,sBAAsB,EAAE,mBAAmB,EAqLvD,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CACvC,IAAI,EAAE,mBAAmB,CAAC,MAAM,CAAC,EACjC,KAAK,EAAE,cAAc,GACpB,MAAM,GAAG,IAAI,CAuBf;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,UAM9D"}
1
+ {"version":3,"file":"derivation-paths.d.cts","sourceRoot":"","sources":["../src/derivation-paths.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,2BAA2B;AAKzD,MAAM,MAAM,mBAAmB,GAAG;IAChC,IAAI,EAAE,CAAC,GAAG,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC;IACzB,KAAK,EAAE,cAAc,CAAC;IACtB,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,eAAO,MAAM,sBAAsB,EAAE,mBAAmB,EA0LvD,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CACvC,IAAI,EAAE,mBAAmB,CAAC,MAAM,CAAC,EACjC,KAAK,EAAE,cAAc,GACpB,MAAM,GAAG,IAAI,CAuBf;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,UAM9D"}
@@ -1 +1 @@
1
- {"version":3,"file":"derivation-paths.d.mts","sourceRoot":"","sources":["../src/derivation-paths.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,2BAA2B;AAKzD,MAAM,MAAM,mBAAmB,GAAG;IAChC,IAAI,EAAE,CAAC,GAAG,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC;IACzB,KAAK,EAAE,cAAc,CAAC;IACtB,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,eAAO,MAAM,sBAAsB,EAAE,mBAAmB,EAqLvD,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CACvC,IAAI,EAAE,mBAAmB,CAAC,MAAM,CAAC,EACjC,KAAK,EAAE,cAAc,GACpB,MAAM,GAAG,IAAI,CAuBf;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,UAM9D"}
1
+ {"version":3,"file":"derivation-paths.d.mts","sourceRoot":"","sources":["../src/derivation-paths.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,2BAA2B;AAKzD,MAAM,MAAM,mBAAmB,GAAG;IAChC,IAAI,EAAE,CAAC,GAAG,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC;IACzB,KAAK,EAAE,cAAc,CAAC;IACtB,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,eAAO,MAAM,sBAAsB,EAAE,mBAAmB,EA0LvD,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CACvC,IAAI,EAAE,mBAAmB,CAAC,MAAM,CAAC,EACjC,KAAK,EAAE,cAAc,GACpB,MAAM,GAAG,IAAI,CAuBf;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,UAM9D"}
@@ -181,6 +181,11 @@ export const SNAPS_DERIVATION_PATHS = [
181
181
  curve: 'ed25519',
182
182
  name: 'IOTA',
183
183
  },
184
+ {
185
+ path: ['m', `44'`, `6767'`],
186
+ curve: 'ed25519',
187
+ name: 'Canton',
188
+ },
184
189
  ];
185
190
  /**
186
191
  * Gets the name of a derivation path supported by snaps.
@@ -1 +1 @@
1
- {"version":3,"file":"derivation-paths.mjs","sourceRoot":"","sources":["../src/derivation-paths.ts"],"names":[],"mappings":"AACA,OAAO,MAAM,+CAAyB;AAEtC,OAAO,EAAE,OAAO,EAAE,oBAAgB;AAQlC,MAAM,CAAC,MAAM,sBAAsB,GAA0B;IAC3D;QACE,IAAI,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC;QACxB,KAAK,EAAE,SAAS;QAChB,IAAI,EAAE,4BAA4B;KACnC;IACD;QACE,IAAI,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AqB,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC;IACjD,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,qBAAqB,CAAC,QAAyB;IAC7D,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,GAAG,EAAE,CAAC;QAC7B,OAAO,eAAe,CAAC;IACzB,CAAC;IAED,OAAO,MAAM,CAAC,QAA+B,CAAC,EAAE,IAAI,IAAI,IAAI,CAAC;AAC/D,CAAC","sourcesContent":["import type { SupportedCurve } from '@metamask/key-tree';\nimport slip44 from '@metamask/slip44';\n\nimport { isEqual } from './array';\n\nexport type SnapsDerivationPath = {\n path: ['m', ...string[]];\n curve: SupportedCurve;\n name: string;\n};\n\nexport const SNAPS_DERIVATION_PATHS: SnapsDerivationPath[] = [\n {\n path: ['m', `44'`, `0'`],\n curve: 'ed25519',\n name: 'Test BIP-32 Path (ed25519)',\n },\n {\n path: ['m', `44'`, `1'`],\n curve: 'secp256k1',\n name: 'Testnet',\n },\n {\n path: ['m', `44'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Legacy',\n },\n {\n path: ['m', `49'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Nested SegWit',\n },\n {\n path: ['m', `49'`, `1'`],\n curve: 'secp256k1',\n name: 'Bitcoin Testnet Nested SegWit',\n },\n {\n path: ['m', `84'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Native SegWit',\n },\n {\n path: ['m', `84'`, `1'`],\n curve: 'secp256k1',\n name: 'Bitcoin Testnet Native SegWit',\n },\n {\n path: ['m', `86'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Taproot',\n },\n {\n path: ['m', `86'`, `1'`],\n curve: 'secp256k1',\n name: 'Bitcoin Testnet Taproot',\n },\n {\n path: ['m', `44'`, `501'`],\n curve: 'ed25519',\n name: 'Solana',\n },\n {\n path: ['m', `44'`, `501'`, \"0'\", \"0'\"],\n curve: 'ed25519',\n name: 'Solana',\n },\n {\n path: ['m', `44'`, `2'`],\n curve: 'secp256k1',\n name: 'Litecoin',\n },\n {\n path: ['m', `44'`, `3'`],\n curve: 'secp256k1',\n name: 'Dogecoin',\n },\n {\n path: ['m', `44'`, `60'`],\n curve: 'secp256k1',\n name: 'Ethereum',\n },\n {\n path: ['m', `44'`, `118'`],\n curve: 'secp256k1',\n name: 'Atom',\n },\n {\n path: ['m', `44'`, `145'`],\n curve: 'secp256k1',\n name: 'Bitcoin Cash',\n },\n {\n path: ['m', `44'`, `637'`],\n curve: 'ed25519',\n name: 'Aptos',\n },\n {\n path: ['m', `44'`, `714'`],\n curve: 'secp256k1',\n name: 'Binance (BNB)',\n },\n {\n path: ['m', `44'`, `784'`],\n curve: 'ed25519',\n name: 'Sui',\n },\n {\n path: ['m', `44'`, `931'`],\n curve: 'secp256k1',\n name: 'THORChain (RUNE)',\n },\n {\n path: ['m', `44'`, `330'`],\n curve: 'secp256k1',\n name: 'Terra (LUNA)',\n },\n {\n path: ['m', `44'`, `459'`],\n curve: 'secp256k1',\n name: 'Kava',\n },\n {\n path: ['m', `44'`, `529'`],\n curve: 'secp256k1',\n name: 'Secret Network',\n },\n {\n path: ['m', `44'`, `397'`, `0'`],\n curve: 'ed25519',\n name: 'NEAR Protocol',\n },\n {\n path: ['m', `44'`, `1'`, `0'`],\n curve: 'ed25519',\n name: 'Testnet',\n },\n {\n path: ['m', `44'`, `472'`],\n curve: 'ed25519',\n name: 'Arweave',\n },\n {\n path: ['m', `44'`, `12586'`],\n curve: 'secp256k1',\n name: 'Mina',\n },\n {\n path: ['m', `44'`, `242'`],\n curve: 'ed25519',\n name: 'Nimiq',\n },\n {\n path: ['m', `44'`, `1729'`, `0'`, `0'`],\n curve: 'ed25519',\n name: 'Tezos',\n },\n {\n path: ['m', `1789'`, `0'`],\n curve: 'ed25519',\n name: 'Vega',\n },\n {\n path: ['m', `1852'`, `1815'`],\n curve: 'ed25519Bip32',\n name: 'Cardano',\n },\n {\n path: ['m', `44'`, `508'`, `0'`, `0'`, `0'`],\n curve: 'ed25519',\n name: 'MultiversX',\n },\n {\n path: ['m', `44'`, `709'`],\n curve: 'secp256k1',\n name: 'Avail',\n },\n {\n path: ['m', `44'`, `626'`],\n curve: 'ed25519',\n name: 'Kadena',\n },\n {\n path: ['m', `44'`, `632'`],\n curve: 'ed25519',\n name: 'Massa',\n },\n {\n path: ['m', `44'`, `4218'`],\n curve: 'ed25519',\n name: 'IOTA',\n },\n];\n\n/**\n * Gets the name of a derivation path supported by snaps.\n *\n * @param path - The derivation path.\n * @param curve - The curve used to derive the keys.\n * @returns The name of the derivation path, otherwise null.\n */\nexport function getSnapDerivationPathName(\n path: SnapsDerivationPath['path'],\n curve: SupportedCurve,\n): string | null {\n const pathMetadata = SNAPS_DERIVATION_PATHS.find(\n (derivationPath) =>\n derivationPath.curve === curve && isEqual(derivationPath.path, path),\n );\n\n if (pathMetadata) {\n return pathMetadata.name;\n }\n\n // If the curve is secp256k1 and the path is a valid BIP44 path\n // we try looking for the network/protocol name in SLIP44\n if (\n curve === 'secp256k1' &&\n path[0] === 'm' &&\n path[1] === `44'` &&\n path[2].endsWith(`'`)\n ) {\n const coinType = path[2].slice(0, -1);\n return getSlip44ProtocolName(coinType) ?? null;\n }\n\n return null;\n}\n\n/**\n * Gets the name of the SLIP-44 protocol corresponding to the specified\n * `coin_type`.\n *\n * @param coinType - The SLIP-44 `coin_type` value whose name\n * to retrieve.\n * @returns The name of the protocol, otherwise null.\n */\nexport function getSlip44ProtocolName(coinType: number | string) {\n if (String(coinType) === '1') {\n return 'Test Networks';\n }\n\n return slip44[coinType as keyof typeof slip44]?.name ?? null;\n}\n"]}
1
+ {"version":3,"file":"derivation-paths.mjs","sourceRoot":"","sources":["../src/derivation-paths.ts"],"names":[],"mappings":"AACA,OAAO,MAAM,+CAAyB;AAEtC,OAAO,EAAE,OAAO,EAAE,oBAAgB;AAQlC,MAAM,CAAC,MAAM,sBAAsB,GAA0B;IAC3D;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CAAC,KAAK,GAAG;QACf,IAAI,CAAC,CAAC,CAAC,KAAK,KAAK;QACjB,IAAI,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,EACrB,CAAC;QACD,MAAM,QAAQ,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;QACtC,OAAO,qBAAqB,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC;IACjD,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,qBAAqB,CAAC,QAAyB;IAC7D,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,GAAG,EAAE,CAAC;QAC7B,OAAO,eAAe,CAAC;IACzB,CAAC;IAED,OAAO,MAAM,CAAC,QAA+B,CAAC,EAAE,IAAI,IAAI,IAAI,CAAC;AAC/D,CAAC","sourcesContent":["import type { SupportedCurve } from '@metamask/key-tree';\nimport slip44 from '@metamask/slip44';\n\nimport { isEqual } from './array';\n\nexport type SnapsDerivationPath = {\n path: ['m', ...string[]];\n curve: SupportedCurve;\n name: string;\n};\n\nexport const SNAPS_DERIVATION_PATHS: SnapsDerivationPath[] = [\n {\n path: ['m', `44'`, `0'`],\n curve: 'ed25519',\n name: 'Test BIP-32 Path (ed25519)',\n },\n {\n path: ['m', `44'`, `1'`],\n curve: 'secp256k1',\n name: 'Testnet',\n },\n {\n path: ['m', `44'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Legacy',\n },\n {\n path: ['m', `49'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Nested SegWit',\n },\n {\n path: ['m', `49'`, `1'`],\n curve: 'secp256k1',\n name: 'Bitcoin Testnet Nested SegWit',\n },\n {\n path: ['m', `84'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Native SegWit',\n },\n {\n path: ['m', `84'`, `1'`],\n curve: 'secp256k1',\n name: 'Bitcoin Testnet Native SegWit',\n },\n {\n path: ['m', `86'`, `0'`],\n curve: 'secp256k1',\n name: 'Bitcoin Taproot',\n },\n {\n path: ['m', `86'`, `1'`],\n curve: 'secp256k1',\n name: 'Bitcoin Testnet Taproot',\n },\n {\n path: ['m', `44'`, `501'`],\n curve: 'ed25519',\n name: 'Solana',\n },\n {\n path: ['m', `44'`, `501'`, \"0'\", \"0'\"],\n curve: 'ed25519',\n name: 'Solana',\n },\n {\n path: ['m', `44'`, `2'`],\n curve: 'secp256k1',\n name: 'Litecoin',\n },\n {\n path: ['m', `44'`, `3'`],\n curve: 'secp256k1',\n name: 'Dogecoin',\n },\n {\n path: ['m', `44'`, `60'`],\n curve: 'secp256k1',\n name: 'Ethereum',\n },\n {\n path: ['m', `44'`, `118'`],\n curve: 'secp256k1',\n name: 'Atom',\n },\n {\n path: ['m', `44'`, `145'`],\n curve: 'secp256k1',\n name: 'Bitcoin Cash',\n },\n {\n path: ['m', `44'`, `637'`],\n curve: 'ed25519',\n name: 'Aptos',\n },\n {\n path: ['m', `44'`, `714'`],\n curve: 'secp256k1',\n name: 'Binance (BNB)',\n },\n {\n path: ['m', `44'`, `784'`],\n curve: 'ed25519',\n name: 'Sui',\n },\n {\n path: ['m', `44'`, `931'`],\n curve: 'secp256k1',\n name: 'THORChain (RUNE)',\n },\n {\n path: ['m', `44'`, `330'`],\n curve: 'secp256k1',\n name: 'Terra (LUNA)',\n },\n {\n path: ['m', `44'`, `459'`],\n curve: 'secp256k1',\n name: 'Kava',\n },\n {\n path: ['m', `44'`, `529'`],\n curve: 'secp256k1',\n name: 'Secret Network',\n },\n {\n path: ['m', `44'`, `397'`, `0'`],\n curve: 'ed25519',\n name: 'NEAR Protocol',\n },\n {\n path: ['m', `44'`, `1'`, `0'`],\n curve: 'ed25519',\n name: 'Testnet',\n },\n {\n path: ['m', `44'`, `472'`],\n curve: 'ed25519',\n name: 'Arweave',\n },\n {\n path: ['m', `44'`, `12586'`],\n curve: 'secp256k1',\n name: 'Mina',\n },\n {\n path: ['m', `44'`, `242'`],\n curve: 'ed25519',\n name: 'Nimiq',\n },\n {\n path: ['m', `44'`, `1729'`, `0'`, `0'`],\n curve: 'ed25519',\n name: 'Tezos',\n },\n {\n path: ['m', `1789'`, `0'`],\n curve: 'ed25519',\n name: 'Vega',\n },\n {\n path: ['m', `1852'`, `1815'`],\n curve: 'ed25519Bip32',\n name: 'Cardano',\n },\n {\n path: ['m', `44'`, `508'`, `0'`, `0'`, `0'`],\n curve: 'ed25519',\n name: 'MultiversX',\n },\n {\n path: ['m', `44'`, `709'`],\n curve: 'secp256k1',\n name: 'Avail',\n },\n {\n path: ['m', `44'`, `626'`],\n curve: 'ed25519',\n name: 'Kadena',\n },\n {\n path: ['m', `44'`, `632'`],\n curve: 'ed25519',\n name: 'Massa',\n },\n {\n path: ['m', `44'`, `4218'`],\n curve: 'ed25519',\n name: 'IOTA',\n },\n {\n path: ['m', `44'`, `6767'`],\n curve: 'ed25519',\n name: 'Canton',\n },\n];\n\n/**\n * Gets the name of a derivation path supported by snaps.\n *\n * @param path - The derivation path.\n * @param curve - The curve used to derive the keys.\n * @returns The name of the derivation path, otherwise null.\n */\nexport function getSnapDerivationPathName(\n path: SnapsDerivationPath['path'],\n curve: SupportedCurve,\n): string | null {\n const pathMetadata = SNAPS_DERIVATION_PATHS.find(\n (derivationPath) =>\n derivationPath.curve === curve && isEqual(derivationPath.path, path),\n );\n\n if (pathMetadata) {\n return pathMetadata.name;\n }\n\n // If the curve is secp256k1 and the path is a valid BIP44 path\n // we try looking for the network/protocol name in SLIP44\n if (\n curve === 'secp256k1' &&\n path[0] === 'm' &&\n path[1] === `44'` &&\n path[2].endsWith(`'`)\n ) {\n const coinType = path[2].slice(0, -1);\n return getSlip44ProtocolName(coinType) ?? null;\n }\n\n return null;\n}\n\n/**\n * Gets the name of the SLIP-44 protocol corresponding to the specified\n * `coin_type`.\n *\n * @param coinType - The SLIP-44 `coin_type` value whose name\n * to retrieve.\n * @returns The name of the protocol, otherwise null.\n */\nexport function getSlip44ProtocolName(coinType: number | string) {\n if (String(coinType) === '1') {\n return 'Test Networks';\n }\n\n return slip44[coinType as keyof typeof slip44]?.name ?? null;\n}\n"]}
package/dist/errors.cjs CHANGED
@@ -1,8 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TrackableErrorStruct = exports.unwrapError = exports.isWrappedSnapError = exports.isSerializedSnapError = exports.isSnapError = exports.WrappedSnapError = exports.SNAP_ERROR_WRAPPER_MESSAGE = exports.SNAP_ERROR_WRAPPER_CODE = void 0;
3
+ exports.isSerializedSnapError = exports.isSnapError = exports.TrackableErrorStruct = exports.unwrapError = exports.isWrappedSnapError = exports.WrappedSnapError = exports.SNAP_ERROR_WRAPPER_MESSAGE = exports.SNAP_ERROR_WRAPPER_CODE = void 0;
4
4
  const rpc_errors_1 = require("@metamask/rpc-errors");
5
5
  const snaps_sdk_1 = require("@metamask/snaps-sdk");
6
+ Object.defineProperty(exports, "isSerializedSnapError", { enumerable: true, get: function () { return snaps_sdk_1.isSerializedSnapError; } });
7
+ Object.defineProperty(exports, "isSnapError", { enumerable: true, get: function () { return snaps_sdk_1.isSnapError; } });
6
8
  const superstruct_1 = require("@metamask/superstruct");
7
9
  const utils_1 = require("@metamask/utils");
8
10
  exports.SNAP_ERROR_WRAPPER_CODE = -31001;
@@ -53,7 +55,7 @@ class WrappedSnapError extends Error {
53
55
  * @returns The JSON object.
54
56
  */
55
57
  toJSON() {
56
- const cause = isSnapError(this.#error)
58
+ const cause = (0, snaps_sdk_1.isSnapError)(this.#error)
57
59
  ? this.#error.serialize()
58
60
  : (0, rpc_errors_1.serializeCause)(this.#error);
59
61
  return {
@@ -75,32 +77,6 @@ class WrappedSnapError extends Error {
75
77
  }
76
78
  }
77
79
  exports.WrappedSnapError = WrappedSnapError;
78
- /**
79
- * Check if an object is a `SnapError`.
80
- *
81
- * @param error - The object to check.
82
- * @returns Whether the object is a `SnapError`.
83
- */
84
- function isSnapError(error) {
85
- if ((0, utils_1.isObject)(error) &&
86
- 'serialize' in error &&
87
- typeof error.serialize === 'function') {
88
- const serialized = error.serialize();
89
- return (0, utils_1.isJsonRpcError)(serialized) && isSerializedSnapError(serialized);
90
- }
91
- return false;
92
- }
93
- exports.isSnapError = isSnapError;
94
- /**
95
- * Check if a JSON-RPC error is a `SnapError`.
96
- *
97
- * @param error - The object to check.
98
- * @returns Whether the object is a `SnapError`.
99
- */
100
- function isSerializedSnapError(error) {
101
- return error.code === snaps_sdk_1.SNAP_ERROR_CODE && error.message === snaps_sdk_1.SNAP_ERROR_MESSAGE;
102
- }
103
- exports.isSerializedSnapError = isSerializedSnapError;
104
80
  /**
105
81
  * Check if a JSON-RPC error is a `WrappedSnapError`.
106
82
  *
@@ -145,7 +121,7 @@ function unwrapError(error) {
145
121
  // a JSON-RPC error, we can unwrap it further.
146
122
  if ((0, utils_1.isJsonRpcError)(error.data.cause)) {
147
123
  // If the JSON-RPC error is a wrapped Snap error, unwrap it further.
148
- if (isSerializedSnapError(error.data.cause)) {
124
+ if ((0, snaps_sdk_1.isSerializedSnapError)(error.data.cause)) {
149
125
  const { code, message, stack, data } = error.data.cause.data.cause;
150
126
  return [getJsonRpcError(code, message, stack, data), true];
151
127
  }
@@ -1 +1 @@
1
- {"version":3,"file":"errors.cjs","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":";;;AAAA,qDAI8B;AAO9B,mDAK6B;AAE7B,uDAAuE;AAEvE,2CAA2D;AAE9C,QAAA,uBAAuB,GAAG,CAAC,KAAK,CAAC;AACjC,QAAA,0BAA0B,GAAG,oBAAoB,CAAC;AAU/D,MAAa,gBAAiB,SAAQ,KAAK;IAChC,MAAM,CAAU;IAEhB,QAAQ,CAAS;IAEjB,MAAM,CAAU;IAEzB;;;;OAIG;IACH,YAAY,KAAc;QACxB,MAAM,OAAO,GAAG,IAAA,2BAAe,EAAC,KAAK,CAAC,CAAC;QACvC,KAAK,CAAC,OAAO,CAAC,CAAC;Q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;QAC7C,OAAO,CAAC,eAAe,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,KAAK,CAAC,CAAC;IAC9D,CAAC;IAED,6EAA6E;IAC7E,yDAAyD;IACzD,OAAO;QACL,eAAe,CACb,uBAAU,CAAC,GAAG,CAAC,QAAQ,EACvB,IAAA,2BAAe,EAAC,KAAK,CAAC,EACtB,IAAA,yBAAa,EAAC,KAAK,CAAC,CACrB;QACD,KAAK;KACN,CAAC;AACJ,CAAC;AAjED,kCAiEC;AAEY,QAAA,oBAAoB,GAA2B,IAAA,oBAAM,EAAC;IACjE,IAAI,EAAE,IAAA,oBAAM,GAAE;IACd,OAAO,EAAE,IAAA,oBAAM,GAAE;IACjB,KAAK,EAAE,IAAA,sBAAQ,EAAC,IAAA,oBAAM,GAAE,CAAC;IACzB,KAAK,EAAE,IAAA,sBAAQ,EAAC,IAAA,kBAAI,EAAiB,GAAG,EAAE,CAAC,4BAAoB,CAAC,CAAC;CAClE,CAAC,CAAC","sourcesContent":["import {\n errorCodes,\n JsonRpcError as RpcError,\n serializeCause,\n} from '@metamask/rpc-errors';\nimport type { DataWithOptionalCause } from '@metamask/rpc-errors';\nimport type {\n SerializedSnapError,\n SnapError,\n TrackableError,\n} from '@metamask/snaps-sdk';\nimport {\n getErrorMessage,\n getErrorStack,\n SNAP_ERROR_CODE,\n SNAP_ERROR_MESSAGE,\n} from '@metamask/snaps-sdk';\nimport type { Struct } from '@metamask/superstruct';\nimport { lazy, nullable, object, string } from '@metamask/superstruct';\nimport type { Json, JsonRpcError } from '@metamask/utils';\nimport { isObject, isJsonRpcError } from '@metamask/utils';\n\nexport const SNAP_ERROR_WRAPPER_CODE = -31001;\nexport const SNAP_ERROR_WRAPPER_MESSAGE = 'Wrapped Snap Error';\n\nexport type SerializedSnapErrorWrapper = {\n code: typeof SNAP_ERROR_WRAPPER_CODE;\n message: typeof SNAP_ERROR_WRAPPER_MESSAGE;\n data: {\n cause: Json;\n };\n};\n\nexport class WrappedSnapError extends Error {\n readonly #error: unknown;\n\n readonly #message: string;\n\n readonly #stack?: string;\n\n /**\n * Create a new `WrappedSnapError`.\n *\n * @param error - The error to create the `WrappedSnapError` from.\n */\n constructor(error: unknown) {\n const message = getErrorMessage(error);\n super(message);\n\n this.#error = error;\n this.#message = message;\n this.#stack = getErrorStack(error) ?? undefined;\n }\n\n /**\n * The error name.\n *\n * @returns The error name.\n */\n get name() {\n return 'WrappedSnapError';\n }\n\n /**\n * The error message.\n *\n * @returns The error message.\n */\n get message() {\n return this.#message;\n }\n\n /**\n * The error stack.\n *\n * @returns The error stack.\n */\n get stack() {\n return this.#stack;\n }\n\n /**\n * Convert the error to a JSON object.\n *\n * @returns The JSON object.\n */\n toJSON(): SerializedSnapErrorWrapper {\n const cause = isSnapError(this.#error)\n ? this.#error.serialize()\n : serializeCause(this.#error);\n\n return {\n code: SNAP_ERROR_WRAPPER_CODE,\n message: SNAP_ERROR_WRAPPER_MESSAGE,\n data: {\n cause,\n },\n };\n }\n\n /**\n * Serialize the error to a JSON object. This is called by\n * `@metamask/rpc-errors` when serializing the error.\n *\n * @returns The JSON object.\n */\n serialize() {\n return this.toJSON();\n }\n}\n\n/**\n * Check if an object is a `SnapError`.\n *\n * @param error - The object to check.\n * @returns Whether the object is a `SnapError`.\n */\nexport function isSnapError(error: unknown): error is SnapError {\n if (\n isObject(error) &&\n 'serialize' in error &&\n typeof error.serialize === 'function'\n ) {\n const serialized = error.serialize();\n return isJsonRpcError(serialized) && isSerializedSnapError(serialized);\n }\n\n return false;\n}\n\n/**\n * Check if a JSON-RPC error is a `SnapError`.\n *\n * @param error - The object to check.\n * @returns Whether the object is a `SnapError`.\n */\nexport function isSerializedSnapError(\n error: JsonRpcError,\n): error is SerializedSnapError {\n return error.code === SNAP_ERROR_CODE && error.message === SNAP_ERROR_MESSAGE;\n}\n\n/**\n * Check if a JSON-RPC error is a `WrappedSnapError`.\n *\n * @param error - The object to check.\n * @returns Whether the object is a `WrappedSnapError`.\n */\nexport function isWrappedSnapError(\n error: unknown,\n): error is SerializedSnapErrorWrapper {\n return (\n isJsonRpcError(error) &&\n error.code === SNAP_ERROR_WRAPPER_CODE &&\n error.message === SNAP_ERROR_WRAPPER_MESSAGE\n );\n}\n\n/**\n * Get a JSON-RPC error with the given code, message, stack, and data.\n *\n * @param code - The error code.\n * @param message - The error message.\n * @param stack - The error stack.\n * @param data - Additional data for the error.\n * @returns The JSON-RPC error.\n */\nfunction getJsonRpcError(\n code: number,\n message: string,\n stack?: string | null,\n data?: Json,\n) {\n const error = new RpcError(code, message, data);\n error.stack = stack ?? undefined;\n\n return error;\n}\n\n/**\n * Attempt to unwrap an unknown error to a `JsonRpcError`. This function will\n * try to get the error code, message, and data from the error, and return a\n * `JsonRpcError` with those properties.\n *\n * @param error - The error to unwrap.\n * @returns A tuple containing the unwrapped error and a boolean indicating\n * whether the error was handled.\n */\nexport function unwrapError(\n error: unknown,\n): [error: RpcError<DataWithOptionalCause>, isHandled: boolean] {\n // This logic is a bit complicated, but it's necessary to handle all the\n // different types of errors that can be thrown by a Snap.\n\n // If the error is a wrapped Snap error, unwrap it.\n if (isWrappedSnapError(error)) {\n // The wrapped error can be a JSON-RPC error, or an unknown error. If it's\n // a JSON-RPC error, we can unwrap it further.\n if (isJsonRpcError(error.data.cause)) {\n // If the JSON-RPC error is a wrapped Snap error, unwrap it further.\n if (isSerializedSnapError(error.data.cause)) {\n const { code, message, stack, data } = error.data.cause.data.cause;\n return [getJsonRpcError(code, message, stack, data), true];\n }\n\n // If the JSON-RPC error is double wrapped, unwrap it further to provide the stack.\n if (\n isObject(error.data.cause.data) &&\n isObject(error.data.cause.data.cause) &&\n error.data.cause.message === error.data.cause.data.cause.message\n ) {\n const nestedCause = error.data.cause.data.cause;\n const { code, message } = error.data.cause;\n return [\n getJsonRpcError(code, message, getErrorStack(nestedCause)),\n false,\n ];\n }\n\n // Otherwise, we use the original JSON-RPC error.\n const { code, message, stack, data } = error.data.cause;\n return [getJsonRpcError(code, message, stack, data), false];\n }\n\n // Otherwise, we throw an internal error with the wrapped error as the\n // message.\n return [\n getJsonRpcError(\n errorCodes.rpc.internal,\n getErrorMessage(error.data.cause),\n getErrorStack(error.data.cause),\n ),\n false,\n ];\n }\n\n // The error can be a non-wrapped JSON-RPC error, in which case we can just\n // re-throw it with the same code, message, and data.\n if (isJsonRpcError(error)) {\n const { code, message, stack, data } = error;\n return [getJsonRpcError(code, message, stack, data), false];\n }\n\n // If the error is not a wrapped error, we don't know how to handle it, so we\n // throw an internal error with the error as the message.\n return [\n getJsonRpcError(\n errorCodes.rpc.internal,\n getErrorMessage(error),\n getErrorStack(error),\n ),\n false,\n ];\n}\n\nexport const TrackableErrorStruct: Struct<TrackableError> = object({\n name: string(),\n message: string(),\n stack: nullable(string()),\n cause: nullable(lazy<TrackableError>(() => TrackableErrorStruct)),\n});\n"]}
1
+ {"version":3,"file":"errors.cjs","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":";;;AAAA,qDAI8B;AAG9B,mDAK6B;AAuNP,sGAzNpB,iCAAqB,OAyNoB;AAAlC,4FAxNP,uBAAW,OAwNO;AArNpB,uDAAuE;AAEvE,2CAA2D;AAE9C,QAAA,uBAAuB,GAAG,CAAC,KAAK,CAAC;AACjC,QAAA,0BAA0B,GAAG,oBAAoB,CAAC;AAU/D,MAAa,gBAAiB,SAAQ,KAAK;IAChC,MAAM,CAAU;IAEhB,QAAQ,CAAS;IAEjB,MAAM,CAAU;IAEzB;;;;OAIG;IACH,YAAY,KAAc;QACxB,MAAM,OAAO,GAAG,IAAA,2BAAe,EAAC,KAAK,CAAC,CAAC;QACvC,KAAK,CAAC,OAAO,CAAC,CAAC;QAEf,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;QACpB,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QACxB,IAAI,CAAC,MAAM,GAAG,IAAA,yBAAa,EAAC,KAAK,CAAC,IAAI,SAAS,CAAC;IAClD,CAAC;IAED;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@metamask/rpc-errors';\nimport type { DataWithOptionalCause } from '@metamask/rpc-errors';\nimport type { TrackableError } from '@metamask/snaps-sdk';\nimport {\n getErrorMessage,\n getErrorStack,\n isSerializedSnapError,\n isSnapError,\n} from '@metamask/snaps-sdk';\nimport type { Struct } from '@metamask/superstruct';\nimport { lazy, nullable, object, string } from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { isObject, isJsonRpcError } from '@metamask/utils';\n\nexport const SNAP_ERROR_WRAPPER_CODE = -31001;\nexport const SNAP_ERROR_WRAPPER_MESSAGE = 'Wrapped Snap Error';\n\nexport type SerializedSnapErrorWrapper = {\n code: typeof SNAP_ERROR_WRAPPER_CODE;\n message: typeof SNAP_ERROR_WRAPPER_MESSAGE;\n data: {\n cause: Json;\n };\n};\n\nexport class WrappedSnapError extends Error {\n readonly #error: unknown;\n\n readonly #message: string;\n\n readonly #stack?: string;\n\n /**\n * Create a new `WrappedSnapError`.\n *\n * @param error - The error to create the `WrappedSnapError` from.\n */\n constructor(error: unknown) {\n const message = getErrorMessage(error);\n super(message);\n\n this.#error = error;\n this.#message = message;\n this.#stack = getErrorStack(error) ?? undefined;\n }\n\n /**\n * The error name.\n *\n * @returns The error name.\n */\n get name() {\n return 'WrappedSnapError';\n }\n\n /**\n * The error message.\n *\n * @returns The error message.\n */\n get message() {\n return this.#message;\n }\n\n /**\n * The error stack.\n *\n * @returns The error stack.\n */\n get stack() {\n return this.#stack;\n }\n\n /**\n * Convert the error to a JSON object.\n *\n * @returns The JSON object.\n */\n toJSON(): SerializedSnapErrorWrapper {\n const cause = isSnapError(this.#error)\n ? this.#error.serialize()\n : serializeCause(this.#error);\n\n return {\n code: SNAP_ERROR_WRAPPER_CODE,\n message: SNAP_ERROR_WRAPPER_MESSAGE,\n data: {\n cause,\n },\n };\n }\n\n /**\n * Serialize the error to a JSON object. This is called by\n * `@metamask/rpc-errors` when serializing the error.\n *\n * @returns The JSON object.\n */\n serialize() {\n return this.toJSON();\n }\n}\n\n/**\n * Check if a JSON-RPC error is a `WrappedSnapError`.\n *\n * @param error - The object to check.\n * @returns Whether the object is a `WrappedSnapError`.\n */\nexport function isWrappedSnapError(\n error: unknown,\n): error is SerializedSnapErrorWrapper {\n return (\n isJsonRpcError(error) &&\n error.code === SNAP_ERROR_WRAPPER_CODE &&\n error.message === SNAP_ERROR_WRAPPER_MESSAGE\n );\n}\n\n/**\n * Get a JSON-RPC error with the given code, message, stack, and data.\n *\n * @param code - The error code.\n * @param message - The error message.\n * @param stack - The error stack.\n * @param data - Additional data for the error.\n * @returns The JSON-RPC error.\n */\nfunction getJsonRpcError(\n code: number,\n message: string,\n stack?: string | null,\n data?: Json,\n) {\n const error = new RpcError(code, message, data);\n error.stack = stack ?? undefined;\n\n return error;\n}\n\n/**\n * Attempt to unwrap an unknown error to a `JsonRpcError`. This function will\n * try to get the error code, message, and data from the error, and return a\n * `JsonRpcError` with those properties.\n *\n * @param error - The error to unwrap.\n * @returns A tuple containing the unwrapped error and a boolean indicating\n * whether the error was handled.\n */\nexport function unwrapError(\n error: unknown,\n): [error: RpcError<DataWithOptionalCause>, isHandled: boolean] {\n // This logic is a bit complicated, but it's necessary to handle all the\n // different types of errors that can be thrown by a Snap.\n\n // If the error is a wrapped Snap error, unwrap it.\n if (isWrappedSnapError(error)) {\n // The wrapped error can be a JSON-RPC error, or an unknown error. If it's\n // a JSON-RPC error, we can unwrap it further.\n if (isJsonRpcError(error.data.cause)) {\n // If the JSON-RPC error is a wrapped Snap error, unwrap it further.\n if (isSerializedSnapError(error.data.cause)) {\n const { code, message, stack, data } = error.data.cause.data.cause;\n return [getJsonRpcError(code, message, stack, data), true];\n }\n\n // If the JSON-RPC error is double wrapped, unwrap it further to provide the stack.\n if (\n isObject(error.data.cause.data) &&\n isObject(error.data.cause.data.cause) &&\n error.data.cause.message === error.data.cause.data.cause.message\n ) {\n const nestedCause = error.data.cause.data.cause;\n const { code, message } = error.data.cause;\n return [\n getJsonRpcError(code, message, getErrorStack(nestedCause)),\n false,\n ];\n }\n\n // Otherwise, we use the original JSON-RPC error.\n const { code, message, stack, data } = error.data.cause;\n return [getJsonRpcError(code, message, stack, data), false];\n }\n\n // Otherwise, we throw an internal error with the wrapped error as the\n // message.\n return [\n getJsonRpcError(\n errorCodes.rpc.internal,\n getErrorMessage(error.data.cause),\n getErrorStack(error.data.cause),\n ),\n false,\n ];\n }\n\n // The error can be a non-wrapped JSON-RPC error, in which case we can just\n // re-throw it with the same code, message, and data.\n if (isJsonRpcError(error)) {\n const { code, message, stack, data } = error;\n return [getJsonRpcError(code, message, stack, data), false];\n }\n\n // If the error is not a wrapped error, we don't know how to handle it, so we\n // throw an internal error with the error as the message.\n return [\n getJsonRpcError(\n errorCodes.rpc.internal,\n getErrorMessage(error),\n getErrorStack(error),\n ),\n false,\n ];\n}\n\nexport const TrackableErrorStruct: Struct<TrackableError> = object({\n name: string(),\n message: string(),\n stack: nullable(string()),\n cause: nullable(lazy<TrackableError>(() => TrackableErrorStruct)),\n});\n\nexport { isSnapError, isSerializedSnapError };\n"]}
package/dist/errors.d.cts CHANGED
@@ -1,8 +1,9 @@
1
1
  import { JsonRpcError as RpcError } from "@metamask/rpc-errors";
2
2
  import type { DataWithOptionalCause } from "@metamask/rpc-errors";
3
- import type { SerializedSnapError, SnapError, TrackableError } from "@metamask/snaps-sdk";
3
+ import type { TrackableError } from "@metamask/snaps-sdk";
4
+ import { isSerializedSnapError, isSnapError } from "@metamask/snaps-sdk";
4
5
  import type { Struct } from "@metamask/superstruct";
5
- import type { Json, JsonRpcError } from "@metamask/utils";
6
+ import type { Json } from "@metamask/utils";
6
7
  export declare const SNAP_ERROR_WRAPPER_CODE = -31001;
7
8
  export declare const SNAP_ERROR_WRAPPER_MESSAGE = "Wrapped Snap Error";
8
9
  export type SerializedSnapErrorWrapper = {
@@ -52,20 +53,6 @@ export declare class WrappedSnapError extends Error {
52
53
  */
53
54
  serialize(): SerializedSnapErrorWrapper;
54
55
  }
55
- /**
56
- * Check if an object is a `SnapError`.
57
- *
58
- * @param error - The object to check.
59
- * @returns Whether the object is a `SnapError`.
60
- */
61
- export declare function isSnapError(error: unknown): error is SnapError;
62
- /**
63
- * Check if a JSON-RPC error is a `SnapError`.
64
- *
65
- * @param error - The object to check.
66
- * @returns Whether the object is a `SnapError`.
67
- */
68
- export declare function isSerializedSnapError(error: JsonRpcError): error is SerializedSnapError;
69
56
  /**
70
57
  * Check if a JSON-RPC error is a `WrappedSnapError`.
71
58
  *
@@ -84,4 +71,5 @@ export declare function isWrappedSnapError(error: unknown): error is SerializedS
84
71
  */
85
72
  export declare function unwrapError(error: unknown): [error: RpcError<DataWithOptionalCause>, isHandled: boolean];
86
73
  export declare const TrackableErrorStruct: Struct<TrackableError>;
74
+ export { isSnapError, isSerializedSnapError };
87
75
  //# sourceMappingURL=errors.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.cts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,YAAY,IAAI,QAAQ,EAEzB,6BAA6B;AAC9B,OAAO,KAAK,EAAE,qBAAqB,EAAE,6BAA6B;AAClE,OAAO,KAAK,EACV,mBAAmB,EACnB,SAAS,EACT,cAAc,EACf,4BAA4B;AAO7B,OAAO,KAAK,EAAE,MAAM,EAAE,8BAA8B;AAEpD,OAAO,KAAK,EAAE,IAAI,EAAE,YAAY,EAAE,wBAAwB;AAG1D,eAAO,MAAM,uBAAuB,SAAS,CAAC;AAC9C,eAAO,MAAM,0BAA0B,uBAAuB,CAAC;AAE/D,MAAM,MAAM,0BAA0B,GAAG;IACvC,IAAI,EAAE,OAAO,uBAAuB,CAAC;IACrC,OAAO,EAAE,OAAO,0BAA0B,CAAC;IAC3C,IAAI,EAAE;QACJ,KAAK,EAAE,IAAI,CAAC;KACb,CAAC;CACH,CAAC;AAEF,qBAAa,gBAAiB,SAAQ,KAAK;;IAOzC;;;;OAIG;gBACS,KAAK,EAAE,OAAO;IAS1B;;;;OAIG;IACH,IAAI,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J,KAAK,EAAE,IAAI,CAAC;KACb,CAAC;CACH,CAAC;AAEF,qBAAa,gBAAiB,SAAQ,KAAK;;IAOzC;;;;OAIG;gBACS,KAAK,EAAE,OAAO;IAS1B;;;;OAIG;IACH,IAAI,IAAI,WAEP;IAED;;;;OAIG;IACH,IAAI,OAAO,WAEV;IAED;;;;OAIG;IACH,IAAI,KAAK,uBAER;IAED;;;;OAIG;IACH,MAAM,IAAI,0BAA0B;IAcpC;;;;;OAKG;IACH,SAAS;CAGV;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,OAAO,GACb,KAAK,IAAI,0BAA0B,CAMrC;AAuBD;;;;;;;;GAQG;AACH,wBAAgB,WAAW,CACzB,KAAK,EAAE,OAAO,GACb,CAAC,KAAK,EAAE,QAAQ,CAAC,qBAAqB,CAAC,EAAE,SAAS,EAAE,OAAO,CAAC,CA+D9D;AAED,eAAO,MAAM,oBAAoB,EAAE,MAAM,CAAC,cAAc,CAKtD,CAAC;AAEH,OAAO,EAAE,WAAW,EAAE,qBAAqB,EAAE,CAAC"}
package/dist/errors.d.mts CHANGED
@@ -1,8 +1,9 @@
1
1
  import { JsonRpcError as RpcError } from "@metamask/rpc-errors";
2
2
  import type { DataWithOptionalCause } from "@metamask/rpc-errors";
3
- import type { SerializedSnapError, SnapError, TrackableError } from "@metamask/snaps-sdk";
3
+ import type { TrackableError } from "@metamask/snaps-sdk";
4
+ import { isSerializedSnapError, isSnapError } from "@metamask/snaps-sdk";
4
5
  import type { Struct } from "@metamask/superstruct";
5
- import type { Json, JsonRpcError } from "@metamask/utils";
6
+ import type { Json } from "@metamask/utils";
6
7
  export declare const SNAP_ERROR_WRAPPER_CODE = -31001;
7
8
  export declare const SNAP_ERROR_WRAPPER_MESSAGE = "Wrapped Snap Error";
8
9
  export type SerializedSnapErrorWrapper = {
@@ -52,20 +53,6 @@ export declare class WrappedSnapError extends Error {
52
53
  */
53
54
  serialize(): SerializedSnapErrorWrapper;
54
55
  }
55
- /**
56
- * Check if an object is a `SnapError`.
57
- *
58
- * @param error - The object to check.
59
- * @returns Whether the object is a `SnapError`.
60
- */
61
- export declare function isSnapError(error: unknown): error is SnapError;
62
- /**
63
- * Check if a JSON-RPC error is a `SnapError`.
64
- *
65
- * @param error - The object to check.
66
- * @returns Whether the object is a `SnapError`.
67
- */
68
- export declare function isSerializedSnapError(error: JsonRpcError): error is SerializedSnapError;
69
56
  /**
70
57
  * Check if a JSON-RPC error is a `WrappedSnapError`.
71
58
  *
@@ -84,4 +71,5 @@ export declare function isWrappedSnapError(error: unknown): error is SerializedS
84
71
  */
85
72
  export declare function unwrapError(error: unknown): [error: RpcError<DataWithOptionalCause>, isHandled: boolean];
86
73
  export declare const TrackableErrorStruct: Struct<TrackableError>;
74
+ export { isSnapError, isSerializedSnapError };
87
75
  //# sourceMappingURL=errors.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.mts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,YAAY,IAAI,QAAQ,EAEzB,6BAA6B;AAC9B,OAAO,KAAK,EAAE,qBAAqB,EAAE,6BAA6B;AAClE,OAAO,KAAK,EACV,mBAAmB,EACnB,SAAS,EACT,cAAc,EACf,4BAA4B;AAO7B,OAAO,KAAK,EAAE,MAAM,EAAE,8BAA8B;AAEpD,OAAO,KAAK,EAAE,IAAI,EAAE,YAAY,EAAE,wBAAwB;AAG1D,eAAO,MAAM,uBAAuB,SAAS,CAAC;AAC9C,eAAO,MAAM,0BAA0B,uBAAuB,CAAC;AAE/D,MAAM,MAAM,0BAA0B,GAAG;IACvC,IAAI,EAAE,OAAO,uBAAuB,CAAC;IACrC,OAAO,EAAE,OAAO,0BAA0B,CAAC;IAC3C,IAAI,EAAE;QACJ,KAAK,EAAE,IAAI,CAAC;KACb,CAAC;CACH,CAAC;AAEF,qBAAa,gBAAiB,SAAQ,KAAK;;IAOzC;;;;OAIG;gBACS,KAAK,EAAE,OAA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B,CAAC;IAC3C,IAAI,EAAE;QACJ,KAAK,EAAE,IAAI,CAAC;KACb,CAAC;CACH,CAAC;AAEF,qBAAa,gBAAiB,SAAQ,KAAK;;IAOzC;;;;OAIG;gBACS,KAAK,EAAE,OAAO;IAS1B;;;;OAIG;IACH,IAAI,IAAI,WAEP;IAED;;;;OAIG;IACH,IAAI,OAAO,WAEV;IAED;;;;OAIG;IACH,IAAI,KAAK,uBAER;IAED;;;;OAIG;IACH,MAAM,IAAI,0BAA0B;IAcpC;;;;;OAKG;IACH,SAAS;CAGV;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,OAAO,GACb,KAAK,IAAI,0BAA0B,CAMrC;AAuBD;;;;;;;;GAQG;AACH,wBAAgB,WAAW,CACzB,KAAK,EAAE,OAAO,GACb,CAAC,KAAK,EAAE,QAAQ,CAAC,qBAAqB,CAAC,EAAE,SAAS,EAAE,OAAO,CAAC,CA+D9D;AAED,eAAO,MAAM,oBAAoB,EAAE,MAAM,CAAC,cAAc,CAKtD,CAAC;AAEH,OAAO,EAAE,WAAW,EAAE,qBAAqB,EAAE,CAAC"}
package/dist/errors.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { errorCodes, JsonRpcError as RpcError, serializeCause } from "@metamask/rpc-errors";
2
- import { getErrorMessage, getErrorStack, SNAP_ERROR_CODE, SNAP_ERROR_MESSAGE } from "@metamask/snaps-sdk";
2
+ import { getErrorMessage, getErrorStack, isSerializedSnapError, isSnapError } from "@metamask/snaps-sdk";
3
3
  import { lazy, nullable, object, string } from "@metamask/superstruct";
4
4
  import { isObject, isJsonRpcError } from "@metamask/utils";
5
5
  export const SNAP_ERROR_WRAPPER_CODE = -31001;
@@ -71,30 +71,6 @@ export class WrappedSnapError extends Error {
71
71
  return this.toJSON();
72
72
  }
73
73
  }
74
- /**
75
- * Check if an object is a `SnapError`.
76
- *
77
- * @param error - The object to check.
78
- * @returns Whether the object is a `SnapError`.
79
- */
80
- export function isSnapError(error) {
81
- if (isObject(error) &&
82
- 'serialize' in error &&
83
- typeof error.serialize === 'function') {
84
- const serialized = error.serialize();
85
- return isJsonRpcError(serialized) && isSerializedSnapError(serialized);
86
- }
87
- return false;
88
- }
89
- /**
90
- * Check if a JSON-RPC error is a `SnapError`.
91
- *
92
- * @param error - The object to check.
93
- * @returns Whether the object is a `SnapError`.
94
- */
95
- export function isSerializedSnapError(error) {
96
- return error.code === SNAP_ERROR_CODE && error.message === SNAP_ERROR_MESSAGE;
97
- }
98
74
  /**
99
75
  * Check if a JSON-RPC error is a `WrappedSnapError`.
100
76
  *
@@ -183,4 +159,5 @@ export const TrackableErrorStruct = object({
183
159
  stack: nullable(string()),
184
160
  cause: nullable(lazy(() => TrackableErrorStruct)),
185
161
  });
162
+ export { isSnapError, isSerializedSnapError };
186
163
  //# sourceMappingURL=errors.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.mjs","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,YAAY,IAAI,QAAQ,EACxB,cAAc,EACf,6BAA6B;AAO9B,OAAO,EACL,eAAe,EACf,aAAa,EACb,eAAe,EACf,kBAAkB,EACnB,4BAA4B;AAE7B,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,8BAA8B;AAEvE,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,wBAAwB;AAE3D,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,KAAK,CAAC;AAC9C,MAAM,CAAC,MAAM,0BAA0B,GAAG,oBAAoB,CAAC;AAU/D,MAAM,OAAO,gBAAiB,SAAQ,KAAK;IAChC,MAAM,CAAU;IAEhB,QAAQ,CAAS;IAEjB,MAAM,CAAU;IAEzB;;;;OAIG;IACH,YAAY,KAAc;QACxB,MAAM,OAAO,GAAG,eAAe,CAAC,KAAK,CAAC,CAAC;QACvC,KAAK,CAAC,OAAO,CAAC,CAAC;QAEf,I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IAC7E,yDAAyD;IACzD,OAAO;QACL,eAAe,CACb,UAAU,CAAC,GAAG,CAAC,QAAQ,EACvB,eAAe,CAAC,KAAK,CAAC,EACtB,aAAa,CAAC,KAAK,CAAC,CACrB;QACD,KAAK;KACN,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,MAAM,oBAAoB,GAA2B,MAAM,CAAC;IACjE,IAAI,EAAE,MAAM,EAAE;IACd,OAAO,EAAE,MAAM,EAAE;IACjB,KAAK,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC;IACzB,KAAK,EAAE,QAAQ,CAAC,IAAI,CAAiB,GAAG,EAAE,CAAC,oBAAoB,CAAC,CAAC;CAClE,CAAC,CAAC","sourcesContent":["import {\n errorCodes,\n JsonRpcError as RpcError,\n serializeCause,\n} from '@metamask/rpc-errors';\nimport type { DataWithOptionalCause } from '@metamask/rpc-errors';\nimport type {\n SerializedSnapError,\n SnapError,\n TrackableError,\n} from '@metamask/snaps-sdk';\nimport {\n getErrorMessage,\n getErrorStack,\n SNAP_ERROR_CODE,\n SNAP_ERROR_MESSAGE,\n} from '@metamask/snaps-sdk';\nimport type { Struct } from '@metamask/superstruct';\nimport { lazy, nullable, object, string } from '@metamask/superstruct';\nimport type { Json, JsonRpcError } from '@metamask/utils';\nimport { isObject, isJsonRpcError } from '@metamask/utils';\n\nexport const SNAP_ERROR_WRAPPER_CODE = -31001;\nexport const SNAP_ERROR_WRAPPER_MESSAGE = 'Wrapped Snap Error';\n\nexport type SerializedSnapErrorWrapper = {\n code: typeof SNAP_ERROR_WRAPPER_CODE;\n message: typeof SNAP_ERROR_WRAPPER_MESSAGE;\n data: {\n cause: Json;\n };\n};\n\nexport class WrappedSnapError extends Error {\n readonly #error: unknown;\n\n readonly #message: string;\n\n readonly #stack?: string;\n\n /**\n * Create a new `WrappedSnapError`.\n *\n * @param error - The error to create the `WrappedSnapError` from.\n */\n constructor(error: unknown) {\n const message = getErrorMessage(error);\n super(message);\n\n this.#error = error;\n this.#message = message;\n this.#stack = getErrorStack(error) ?? undefined;\n }\n\n /**\n * The error name.\n *\n * @returns The error name.\n */\n get name() {\n return 'WrappedSnapError';\n }\n\n /**\n * The error message.\n *\n * @returns The error message.\n */\n get message() {\n return this.#message;\n }\n\n /**\n * The error stack.\n *\n * @returns The error stack.\n */\n get stack() {\n return this.#stack;\n }\n\n /**\n * Convert the error to a JSON object.\n *\n * @returns The JSON object.\n */\n toJSON(): SerializedSnapErrorWrapper {\n const cause = isSnapError(this.#error)\n ? this.#error.serialize()\n : serializeCause(this.#error);\n\n return {\n code: SNAP_ERROR_WRAPPER_CODE,\n message: SNAP_ERROR_WRAPPER_MESSAGE,\n data: {\n cause,\n },\n };\n }\n\n /**\n * Serialize the error to a JSON object. This is called by\n * `@metamask/rpc-errors` when serializing the error.\n *\n * @returns The JSON object.\n */\n serialize() {\n return this.toJSON();\n }\n}\n\n/**\n * Check if an object is a `SnapError`.\n *\n * @param error - The object to check.\n * @returns Whether the object is a `SnapError`.\n */\nexport function isSnapError(error: unknown): error is SnapError {\n if (\n isObject(error) &&\n 'serialize' in error &&\n typeof error.serialize === 'function'\n ) {\n const serialized = error.serialize();\n return isJsonRpcError(serialized) && isSerializedSnapError(serialized);\n }\n\n return false;\n}\n\n/**\n * Check if a JSON-RPC error is a `SnapError`.\n *\n * @param error - The object to check.\n * @returns Whether the object is a `SnapError`.\n */\nexport function isSerializedSnapError(\n error: JsonRpcError,\n): error is SerializedSnapError {\n return error.code === SNAP_ERROR_CODE && error.message === SNAP_ERROR_MESSAGE;\n}\n\n/**\n * Check if a JSON-RPC error is a `WrappedSnapError`.\n *\n * @param error - The object to check.\n * @returns Whether the object is a `WrappedSnapError`.\n */\nexport function isWrappedSnapError(\n error: unknown,\n): error is SerializedSnapErrorWrapper {\n return (\n isJsonRpcError(error) &&\n error.code === SNAP_ERROR_WRAPPER_CODE &&\n error.message === SNAP_ERROR_WRAPPER_MESSAGE\n );\n}\n\n/**\n * Get a JSON-RPC error with the given code, message, stack, and data.\n *\n * @param code - The error code.\n * @param message - The error message.\n * @param stack - The error stack.\n * @param data - Additional data for the error.\n * @returns The JSON-RPC error.\n */\nfunction getJsonRpcError(\n code: number,\n message: string,\n stack?: string | null,\n data?: Json,\n) {\n const error = new RpcError(code, message, data);\n error.stack = stack ?? undefined;\n\n return error;\n}\n\n/**\n * Attempt to unwrap an unknown error to a `JsonRpcError`. This function will\n * try to get the error code, message, and data from the error, and return a\n * `JsonRpcError` with those properties.\n *\n * @param error - The error to unwrap.\n * @returns A tuple containing the unwrapped error and a boolean indicating\n * whether the error was handled.\n */\nexport function unwrapError(\n error: unknown,\n): [error: RpcError<DataWithOptionalCause>, isHandled: boolean] {\n // This logic is a bit complicated, but it's necessary to handle all the\n // different types of errors that can be thrown by a Snap.\n\n // If the error is a wrapped Snap error, unwrap it.\n if (isWrappedSnapError(error)) {\n // The wrapped error can be a JSON-RPC error, or an unknown error. If it's\n // a JSON-RPC error, we can unwrap it further.\n if (isJsonRpcError(error.data.cause)) {\n // If the JSON-RPC error is a wrapped Snap error, unwrap it further.\n if (isSerializedSnapError(error.data.cause)) {\n const { code, message, stack, data } = error.data.cause.data.cause;\n return [getJsonRpcError(code, message, stack, data), true];\n }\n\n // If the JSON-RPC error is double wrapped, unwrap it further to provide the stack.\n if (\n isObject(error.data.cause.data) &&\n isObject(error.data.cause.data.cause) &&\n error.data.cause.message === error.data.cause.data.cause.message\n ) {\n const nestedCause = error.data.cause.data.cause;\n const { code, message } = error.data.cause;\n return [\n getJsonRpcError(code, message, getErrorStack(nestedCause)),\n false,\n ];\n }\n\n // Otherwise, we use the original JSON-RPC error.\n const { code, message, stack, data } = error.data.cause;\n return [getJsonRpcError(code, message, stack, data), false];\n }\n\n // Otherwise, we throw an internal error with the wrapped error as the\n // message.\n return [\n getJsonRpcError(\n errorCodes.rpc.internal,\n getErrorMessage(error.data.cause),\n getErrorStack(error.data.cause),\n ),\n false,\n ];\n }\n\n // The error can be a non-wrapped JSON-RPC error, in which case we can just\n // re-throw it with the same code, message, and data.\n if (isJsonRpcError(error)) {\n const { code, message, stack, data } = error;\n return [getJsonRpcError(code, message, stack, data), false];\n }\n\n // If the error is not a wrapped error, we don't know how to handle it, so we\n // throw an internal error with the error as the message.\n return [\n getJsonRpcError(\n errorCodes.rpc.internal,\n getErrorMessage(error),\n getErrorStack(error),\n ),\n false,\n ];\n}\n\nexport const TrackableErrorStruct: Struct<TrackableError> = object({\n name: string(),\n message: string(),\n stack: nullable(string()),\n cause: nullable(lazy<TrackableError>(() => TrackableErrorStruct)),\n});\n"]}
1
+ {"version":3,"file":"errors.mjs","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,YAAY,IAAI,QAAQ,EACxB,cAAc,EACf,6BAA6B;AAG9B,OAAO,EACL,eAAe,EACf,aAAa,EACb,qBAAqB,EACrB,WAAW,EACZ,4BAA4B;AAE7B,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,8BAA8B;AAEvE,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,wBAAwB;AAE3D,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,KAAK,CAAC;AAC9C,MAAM,CAAC,MAAM,0BAA0B,GAAG,oBAAoB,CAAC;AAU/D,MAAM,OAAO,gBAAiB,SAAQ,KAAK;IAChC,MAAM,CAAU;IAEhB,QAAQ,CAAS;IAEjB,MAAM,CAAU;IAEzB;;;;OAIG;IACH,YAAY,KAAc;QACxB,MAAM,OAAO,GAAG,eAAe,CAAC,KAAK,CAAC,CAAC;QACvC,KAAK,CAAC,OAAO,CAAC,CAAC;QAEf,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;QACpB,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QACxB,IAAI,CAAC,MAAM,GAAG,aAAa,CAAC,KAAK,CAAC,IAAI,SAAS,CAAC;IAClD,CAAC;IAED;;;;OAIG;IACH,IAAI,IAAI;QACN,OAA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C;QAC9D,CAAC;QAED,sEAAsE;QACtE,WAAW;QACX,OAAO;YACL,eAAe,CACb,UAAU,CAAC,GAAG,CAAC,QAAQ,EACvB,eAAe,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,EACjC,aAAa,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAChC;YACD,KAAK;SACN,CAAC;IACJ,CAAC;IAED,2EAA2E;IAC3E,qDAAqD;IACrD,IAAI,cAAc,CAAC,KAAK,CAAC,EAAE,CAAC;QAC1B,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC;QAC7C,OAAO,CAAC,eAAe,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,EAAE,KAAK,CAAC,CAAC;IAC9D,CAAC;IAED,6EAA6E;IAC7E,yDAAyD;IACzD,OAAO;QACL,eAAe,CACb,UAAU,CAAC,GAAG,CAAC,QAAQ,EACvB,eAAe,CAAC,KAAK,CAAC,EACtB,aAAa,CAAC,KAAK,CAAC,CACrB;QACD,KAAK;KACN,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,MAAM,oBAAoB,GAA2B,MAAM,CAAC;IACjE,IAAI,EAAE,MAAM,EAAE;IACd,OAAO,EAAE,MAAM,EAAE;IACjB,KAAK,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC;IACzB,KAAK,EAAE,QAAQ,CAAC,IAAI,CAAiB,GAAG,EAAE,CAAC,oBAAoB,CAAC,CAAC;CAClE,CAAC,CAAC;AAEH,OAAO,EAAE,WAAW,EAAE,qBAAqB,EAAE,CAAC","sourcesContent":["import {\n errorCodes,\n JsonRpcError as RpcError,\n serializeCause,\n} from '@metamask/rpc-errors';\nimport type { DataWithOptionalCause } from '@metamask/rpc-errors';\nimport type { TrackableError } from '@metamask/snaps-sdk';\nimport {\n getErrorMessage,\n getErrorStack,\n isSerializedSnapError,\n isSnapError,\n} from '@metamask/snaps-sdk';\nimport type { Struct } from '@metamask/superstruct';\nimport { lazy, nullable, object, string } from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { isObject, isJsonRpcError } from '@metamask/utils';\n\nexport const SNAP_ERROR_WRAPPER_CODE = -31001;\nexport const SNAP_ERROR_WRAPPER_MESSAGE = 'Wrapped Snap Error';\n\nexport type SerializedSnapErrorWrapper = {\n code: typeof SNAP_ERROR_WRAPPER_CODE;\n message: typeof SNAP_ERROR_WRAPPER_MESSAGE;\n data: {\n cause: Json;\n };\n};\n\nexport class WrappedSnapError extends Error {\n readonly #error: unknown;\n\n readonly #message: string;\n\n readonly #stack?: string;\n\n /**\n * Create a new `WrappedSnapError`.\n *\n * @param error - The error to create the `WrappedSnapError` from.\n */\n constructor(error: unknown) {\n const message = getErrorMessage(error);\n super(message);\n\n this.#error = error;\n this.#message = message;\n this.#stack = getErrorStack(error) ?? undefined;\n }\n\n /**\n * The error name.\n *\n * @returns The error name.\n */\n get name() {\n return 'WrappedSnapError';\n }\n\n /**\n * The error message.\n *\n * @returns The error message.\n */\n get message() {\n return this.#message;\n }\n\n /**\n * The error stack.\n *\n * @returns The error stack.\n */\n get stack() {\n return this.#stack;\n }\n\n /**\n * Convert the error to a JSON object.\n *\n * @returns The JSON object.\n */\n toJSON(): SerializedSnapErrorWrapper {\n const cause = isSnapError(this.#error)\n ? this.#error.serialize()\n : serializeCause(this.#error);\n\n return {\n code: SNAP_ERROR_WRAPPER_CODE,\n message: SNAP_ERROR_WRAPPER_MESSAGE,\n data: {\n cause,\n },\n };\n }\n\n /**\n * Serialize the error to a JSON object. This is called by\n * `@metamask/rpc-errors` when serializing the error.\n *\n * @returns The JSON object.\n */\n serialize() {\n return this.toJSON();\n }\n}\n\n/**\n * Check if a JSON-RPC error is a `WrappedSnapError`.\n *\n * @param error - The object to check.\n * @returns Whether the object is a `WrappedSnapError`.\n */\nexport function isWrappedSnapError(\n error: unknown,\n): error is SerializedSnapErrorWrapper {\n return (\n isJsonRpcError(error) &&\n error.code === SNAP_ERROR_WRAPPER_CODE &&\n error.message === SNAP_ERROR_WRAPPER_MESSAGE\n );\n}\n\n/**\n * Get a JSON-RPC error with the given code, message, stack, and data.\n *\n * @param code - The error code.\n * @param message - The error message.\n * @param stack - The error stack.\n * @param data - Additional data for the error.\n * @returns The JSON-RPC error.\n */\nfunction getJsonRpcError(\n code: number,\n message: string,\n stack?: string | null,\n data?: Json,\n) {\n const error = new RpcError(code, message, data);\n error.stack = stack ?? undefined;\n\n return error;\n}\n\n/**\n * Attempt to unwrap an unknown error to a `JsonRpcError`. This function will\n * try to get the error code, message, and data from the error, and return a\n * `JsonRpcError` with those properties.\n *\n * @param error - The error to unwrap.\n * @returns A tuple containing the unwrapped error and a boolean indicating\n * whether the error was handled.\n */\nexport function unwrapError(\n error: unknown,\n): [error: RpcError<DataWithOptionalCause>, isHandled: boolean] {\n // This logic is a bit complicated, but it's necessary to handle all the\n // different types of errors that can be thrown by a Snap.\n\n // If the error is a wrapped Snap error, unwrap it.\n if (isWrappedSnapError(error)) {\n // The wrapped error can be a JSON-RPC error, or an unknown error. If it's\n // a JSON-RPC error, we can unwrap it further.\n if (isJsonRpcError(error.data.cause)) {\n // If the JSON-RPC error is a wrapped Snap error, unwrap it further.\n if (isSerializedSnapError(error.data.cause)) {\n const { code, message, stack, data } = error.data.cause.data.cause;\n return [getJsonRpcError(code, message, stack, data), true];\n }\n\n // If the JSON-RPC error is double wrapped, unwrap it further to provide the stack.\n if (\n isObject(error.data.cause.data) &&\n isObject(error.data.cause.data.cause) &&\n error.data.cause.message === error.data.cause.data.cause.message\n ) {\n const nestedCause = error.data.cause.data.cause;\n const { code, message } = error.data.cause;\n return [\n getJsonRpcError(code, message, getErrorStack(nestedCause)),\n false,\n ];\n }\n\n // Otherwise, we use the original JSON-RPC error.\n const { code, message, stack, data } = error.data.cause;\n return [getJsonRpcError(code, message, stack, data), false];\n }\n\n // Otherwise, we throw an internal error with the wrapped error as the\n // message.\n return [\n getJsonRpcError(\n errorCodes.rpc.internal,\n getErrorMessage(error.data.cause),\n getErrorStack(error.data.cause),\n ),\n false,\n ];\n }\n\n // The error can be a non-wrapped JSON-RPC error, in which case we can just\n // re-throw it with the same code, message, and data.\n if (isJsonRpcError(error)) {\n const { code, message, stack, data } = error;\n return [getJsonRpcError(code, message, stack, data), false];\n }\n\n // If the error is not a wrapped error, we don't know how to handle it, so we\n // throw an internal error with the error as the message.\n return [\n getJsonRpcError(\n errorCodes.rpc.internal,\n getErrorMessage(error),\n getErrorStack(error),\n ),\n false,\n ];\n}\n\nexport const TrackableErrorStruct: Struct<TrackableError> = object({\n name: string(),\n message: string(),\n stack: nullable(string()),\n cause: nullable(lazy<TrackableError>(() => TrackableErrorStruct)),\n});\n\nexport { isSnapError, isSerializedSnapError };\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"snaps.cjs","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":";;;;;;AAMA,mDAI6B;AAE7B,uDAS+B;AAE/B,2CAAgF;AAChF,sCAAqC;AACrC,4FAAyD;AACzD,0FAA2D;AAE3D,2CAA2C;AAC3C,6CAA2C;AAQ3C,uCAA8C;AAG9C,+EAA+E;AAC/E,0EAA0E;AAC1E,0EAA0E;AAC1E,4DAA4D;AAC5D,uCAAuC;AACvC,2EAA2E;AAC3E,8EAA8E;AAC9E,qDAAqD;AACrD,mIAAmI;AACtH,QAAA,mBAAmB,GAC9B,kHAAkH,CAAC;AAErH,IAAY,UAMX;AAND,WAAY,UAAU;IACpB,uCAAyB,CAAA;IACzB,mCAAqB,CAAA;IACrB,iCAAmB,CAAA;IACnB,iCAAmB,CAAA;IACnB,iCAAmB,CAAA;AACrB,CAAC,EANW,UAAU,0BAAV,UAAU,QAMrB;AAED,IAAY,gBAKX;AALD,WAAY,gBAAgB;IAC1B,mCAAe,CAAA;IACf,iCAAa,CAAA;IACb,mCAAe,CAAA;IACf,qCAAiB,CAAA;AACnB,CAAC,EALW,gBAAgB,gCAAhB,gBA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ockReason } from '@metamask/snaps-registry';\nimport {\n selectiveUnion,\n type SnapId,\n type Snap as TruncatedSnap,\n} from '@metamask/snaps-sdk';\nimport type { Struct } from '@metamask/superstruct';\nimport {\n is,\n empty,\n enums,\n intersection,\n literal,\n refine,\n string,\n validate,\n} from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { assert, isObject, assertStruct, definePattern } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport stableStringify from 'fast-json-stable-stringify';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { LocalizationFile } from './localization';\nimport type {\n InitialConnections,\n SnapManifest,\n SnapPermissions,\n} from './manifest/validation';\nimport type { FetchedSnapFiles, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: SnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type SnapAuxiliaryFile = {\n path: string;\n // Value here should be stored as base64\n value: string;\n};\n\n/**\n * @deprecated Use SnapAuxiliaryFile instead. This was a typo that has been fixed.\n */\nexport type SnapAuxilaryFile = SnapAuxiliaryFile;\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = TruncatedSnap & {\n /**\n * The initial connections of the Snap, optional, requested on installation.\n */\n initialConnections?: InitialConnections;\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n\n /**\n * Static auxiliary files that can be loaded at runtime.\n */\n auxiliaryFiles?: SnapAuxiliaryFile[];\n\n /**\n * Localization files which are used to translate the manifest.\n */\n localizationFiles?: LocalizationFile[];\n\n /**\n * Flag to signal whether this snap was preinstalled or not.\n *\n * A lack of specifying this option will be deemed as not preinstalled.\n */\n preinstalled?: boolean;\n\n /**\n * Flag to signal whether this snap is removable or not.\n *\n * A lack of specifying this option will be deemed as removable.\n */\n removable?: boolean;\n\n /**\n * Flag to signal whether this snap should be hidden from the user or not.\n */\n hidden?: boolean;\n\n /**\n * Flag to signal whether this snap should hide the Snap branding like header or avatar in the UI or not.\n */\n hideSnapBranding?: boolean;\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport async function getSnapChecksum(\n files: FetchedSnapFiles,\n): Promise<string> {\n const { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles } =\n files;\n\n const all = [\n getChecksummableManifest(manifest),\n sourceCode,\n svgIcon,\n ...auxiliaryFiles,\n ...localizationFiles,\n ].filter((file) => file !== undefined);\n\n return base64.encode(await checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport async function validateSnapShasum(\n files: FetchedSnapFiles,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): Promise<void> {\n if (files.manifest.result.source.shasum !== (await getSnapChecksum(files))) {\n throw new Error(errorMessage);\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = definePattern(\n 'Base Snap Id',\n /^[\\x21-\\x7E]*$/u,\n);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\n\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdPrefixStruct = refine(\n string(),\n 'Snap ID prefix',\n (value) => {\n if (\n Object.values(SnapIdPrefixes).some((prefix) => value.startsWith(prefix))\n ) {\n return true;\n }\n\n const allowedPrefixes = Object.values(SnapIdPrefixes)\n .map((prefix) => `\"${prefix}\"`)\n .join(', ');\n\n return `Invalid or no prefix found. Expected Snap ID to start with one of: ${allowedPrefixes}, but received: \"${value}\"`;\n },\n);\n\nexport const SnapIdStruct = selectiveUnion((value) => {\n if (typeof value === 'string' && value.startsWith(SnapIdPrefixes.npm)) {\n return NpmSnapIdStruct;\n }\n\n if (typeof value === 'string' && value.startsWith(SnapIdPrefixes.local)) {\n return LocalSnapIdStruct;\n }\n\n return SnapIdPrefixStruct;\n});\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Check if the given value is a valid snap ID. This function is a type guard,\n * and will narrow the type of the value to `SnapId` if it returns `true`.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a valid snap ID, and `false` otherwise.\n */\nexport function isSnapId(value: unknown): value is SnapId {\n return is(value, SnapIdStruct);\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(value: unknown): asserts value is SnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n\nexport type { Snap as TruncatedSnap } from '@metamask/snaps-sdk';\n"]}
1
+ {"version":3,"file":"snaps.cjs","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":";;;;;;AAMA,mDAI6B;AAE7B,uDAS+B;AAE/B,2CAAgF;AAChF,sCAAqC;AACrC,4FAAyD;AACzD,0FAA2D;AAE3D,2CAA2C;AAC3C,6CAA2C;AAQ3C,uCAA8C;AAG9C,+EAA+E;AAC/E,0EAA0E;AAC1E,0EAA0E;AAC1E,4DAA4D;AAC5D,uCAAuC;AACvC,2EAA2E;AAC3E,8EAA8E;AAC9E,qDAAqD;AACrD,mIAAmI;AACtH,QAAA,mBAAmB,GAC9B,kHAAkH,CAAC;AAErH,IAAY,UAMX;AAND,WAAY,UAAU;IACpB,uCAAyB,CAAA;IACzB,mCAAqB,CAAA;IACrB,iCAAmB,CAAA;IACnB,iCAAmB,CAAA;IACnB,iCAAmB,CAAA;AACrB,CAAC,EANW,UAAU,0BAAV,UAAU,QAMrB;AAED,IAAY,gBAKX;AALD,WAAY,gBAAgB;IAC1B,mCAAe,CAAA;IACf,iCAAa,CAAA;IACb,mCAAe,CAAA;IACf,qCAAiB,CAAA;AACnB,CAAC,EALW,gBAAgB,gCAAhB,gBAAgB,QAK3B;AAqHD;;;;;GAKG;AACH,SAAS,wBAAwB,CAC/B,QAAmC;IAEnC,MAAM,YAAY,GAAG,QAAQ,CAAC,KAAK,EAAsB,CAAC;IAC1D,OAAO,YAAY,CAAC,MAAM,CAAC,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OAAO,OAAO,CAGR,CAAC,WAAW,EAAE,WAAW,EAAE,OAAO,EAAE,IAAI,CACtC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,wBAAc,CAAC,OAAO,CACnD,IAAI,EAAE,CACR,CAAC,KACH,EAAE,CAAC,MAAM,CAAC,CACZ,CAAC;AACJ,CAAC;AAbD,0CAaC;AAED;;;;;;GAMG;AACH,SAAgB,8BAA8B,CAC5C,oBAA6B;IAE7B,IAAA,cAAM,EACJ,IAAA,gBAAQ,EAAC,oBAAoB,CAAC,EAC9B,0CAA0C,CAC3C,CAAC;IAEF,MAAM,EAAE,WAAW,EAAE,oBAAoB,EAAE,GAAG,oBAAoB,CAAC;IAEnE,IAAA,cAAM,EACJ,IAAA,gBAAQ,EAAC,oBAAoB,CAAC,EAC9B,wDAAwD,CACzD,CAAC;IAEF,MAAM,EAAE,OAAO,EAAE,GAAG,oBAAoB,CAAC;IAEzC,IAAA,cAAM,EACJ,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAC9C,yEAAyE,CAC1E,CAAC;IAEF,MAAM,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC;IAEzB,IAAA,cAAM,EACJ,IAAA,gBAAQ,EAAC,MAAM,CAAC;QACd,MAAM,CAAC,IAAI,KAAK,wBAAc,CAAC,OAAO;QACtC,IAAA,gBAAQ,EAAC,MAAM,CAAC,KAAK,CAAC,EACxB,iDAAiD,wBAAc,CAAC,OAAO,UAAU,CAClF,CAAC;AACJ,CAAC;AA9BD,wEA8BC","sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport {\n selectiveUnion,\n type SnapId,\n type Snap as TruncatedSnap,\n} from '@metamask/snaps-sdk';\nimport type { Struct } from '@metamask/superstruct';\nimport {\n is,\n empty,\n enums,\n intersection,\n literal,\n refine,\n string,\n validate,\n} from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { assert, isObject, assertStruct, definePattern } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport stableStringify from 'fast-json-stable-stringify';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { LocalizationFile } from './localization';\nimport type {\n InitialConnections,\n SnapManifest,\n SnapPermissions,\n} from './manifest/validation';\nimport type { FetchedSnapFiles, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: SnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type SnapAuxiliaryFile = {\n path: string;\n // Value here should be stored as base64\n value: string;\n};\n\n/**\n * @deprecated Use SnapAuxiliaryFile instead. This was a typo that has been fixed.\n */\nexport type SnapAuxilaryFile = SnapAuxiliaryFile;\n\n/**\n * A Snap's data as stored in the StorageService.\n */\nexport type StorageServiceSnapData = {\n sourceCode: string;\n};\n\n/**\n * A Snap's data as stored in the StorageService and the SnapController state.\n */\nexport type PersistedSnap = Snap & StorageServiceSnapData;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = TruncatedSnap & {\n /**\n * The initial connections of the Snap, optional, requested on installation.\n */\n initialConnections?: InitialConnections;\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n\n /**\n * Static auxiliary files that can be loaded at runtime.\n */\n auxiliaryFiles?: SnapAuxiliaryFile[];\n\n /**\n * Localization files which are used to translate the manifest.\n */\n localizationFiles?: LocalizationFile[];\n\n /**\n * Flag to signal whether this snap was preinstalled or not.\n *\n * A lack of specifying this option will be deemed as not preinstalled.\n */\n preinstalled?: boolean;\n\n /**\n * Flag to signal whether this snap is removable or not.\n *\n * A lack of specifying this option will be deemed as removable.\n */\n removable?: boolean;\n\n /**\n * Flag to signal whether this snap should be hidden from the user or not.\n */\n hidden?: boolean;\n\n /**\n * Flag to signal whether this snap should hide the Snap branding like header or avatar in the UI or not.\n */\n hideSnapBranding?: boolean;\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport async function getSnapChecksum(\n files: FetchedSnapFiles,\n): Promise<string> {\n const { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles } =\n files;\n\n const all = [\n getChecksummableManifest(manifest),\n sourceCode,\n svgIcon,\n ...auxiliaryFiles,\n ...localizationFiles,\n ].filter((file) => file !== undefined);\n\n return base64.encode(await checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport async function validateSnapShasum(\n files: FetchedSnapFiles,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): Promise<void> {\n if (files.manifest.result.source.shasum !== (await getSnapChecksum(files))) {\n throw new Error(errorMessage);\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = definePattern(\n 'Base Snap Id',\n /^[\\x21-\\x7E]*$/u,\n);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\n\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdPrefixStruct = refine(\n string(),\n 'Snap ID prefix',\n (value) => {\n if (\n Object.values(SnapIdPrefixes).some((prefix) => value.startsWith(prefix))\n ) {\n return true;\n }\n\n const allowedPrefixes = Object.values(SnapIdPrefixes)\n .map((prefix) => `\"${prefix}\"`)\n .join(', ');\n\n return `Invalid or no prefix found. Expected Snap ID to start with one of: ${allowedPrefixes}, but received: \"${value}\"`;\n },\n);\n\nexport const SnapIdStruct = selectiveUnion((value) => {\n if (typeof value === 'string' && value.startsWith(SnapIdPrefixes.npm)) {\n return NpmSnapIdStruct;\n }\n\n if (typeof value === 'string' && value.startsWith(SnapIdPrefixes.local)) {\n return LocalSnapIdStruct;\n }\n\n return SnapIdPrefixStruct;\n});\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Check if the given value is a valid snap ID. This function is a type guard,\n * and will narrow the type of the value to `SnapId` if it returns `true`.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a valid snap ID, and `false` otherwise.\n */\nexport function isSnapId(value: unknown): value is SnapId {\n return is(value, SnapIdStruct);\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(value: unknown): asserts value is SnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n\nexport type { Snap as TruncatedSnap } from '@metamask/snaps-sdk';\n"]}
package/dist/snaps.d.cts CHANGED
@@ -44,7 +44,16 @@ export type SnapAuxiliaryFile = {
44
44
  * @deprecated Use SnapAuxiliaryFile instead. This was a typo that has been fixed.
45
45
  */
46
46
  export type SnapAuxilaryFile = SnapAuxiliaryFile;
47
- export type PersistedSnap = Snap;
47
+ /**
48
+ * A Snap's data as stored in the StorageService.
49
+ */
50
+ export type StorageServiceSnapData = {
51
+ sourceCode: string;
52
+ };
53
+ /**
54
+ * A Snap's data as stored in the StorageService and the SnapController state.
55
+ */
56
+ export type PersistedSnap = Snap & StorageServiceSnapData;
48
57
  /**
49
58
  * A Snap as it exists in {@link SnapController} state.
50
59
  */
@@ -58,10 +67,6 @@ export type Snap = TruncatedSnap & {
58
67
  * installed.
59
68
  */
60
69
  initialPermissions: SnapPermissions;
61
- /**
62
- * The source code of the Snap.
63
- */
64
- sourceCode: string;
65
70
  /**
66
71
  * The Snap's manifest file.
67
72
  */
@@ -1 +1 @@
1
- {"version":3,"file":"snaps.d.cts","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,kBAAkB,EAClB,oBAAoB,EACrB,wCAAwC;AACzC,OAAO,KAAK,EAAE,WAAW,EAAE,iCAAiC;AAC5D,OAAO,EAEL,KAAK,MAAM,EACX,KAAK,IAAI,IAAI,aAAa,EAC3B,4BAA4B;AAC7B,OAAO,KAAK,EAAE,MAAM,EAAE,8BAA8B;AAmBpD,OAAO,KAAK,EAAE,gBAAgB,EAAE,2BAAuB;AACvD,OAAO,KAAK,EACV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AE3E;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,WAAW,EAAE,kBAAkB,CAAC,oBAAoB,CAAC,EACrD,MAAM,EAAE,MAAM,WAWf;AAED;;;;;;GAMG;AACH,wBAAgB,8BAA8B,CAC5C,oBAAoB,EAAE,OAAO,GAC5B,OAAO,CAAC,oBAAoB,IAAI,sBAAsB,CA4BxD;AAED,YAAY,EAAE,IAAI,IAAI,aAAa,EAAE,4BAA4B"}
package/dist/snaps.d.mts CHANGED
@@ -44,7 +44,16 @@ export type SnapAuxiliaryFile = {
44
44
  * @deprecated Use SnapAuxiliaryFile instead. This was a typo that has been fixed.
45
45
  */
46
46
  export type SnapAuxilaryFile = SnapAuxiliaryFile;
47
- export type PersistedSnap = Snap;
47
+ /**
48
+ * A Snap's data as stored in the StorageService.
49
+ */
50
+ export type StorageServiceSnapData = {
51
+ sourceCode: string;
52
+ };
53
+ /**
54
+ * A Snap's data as stored in the StorageService and the SnapController state.
55
+ */
56
+ export type PersistedSnap = Snap & StorageServiceSnapData;
48
57
  /**
49
58
  * A Snap as it exists in {@link SnapController} state.
50
59
  */
@@ -58,10 +67,6 @@ export type Snap = TruncatedSnap & {
58
67
  * installed.
59
68
  */
60
69
  initialPermissions: SnapPermissions;
61
- /**
62
- * The source code of the Snap.
63
- */
64
- sourceCode: string;
65
70
  /**
66
71
  * The Snap's manifest file.
67
72
  */
@@ -1 +1 @@
1
- {"version":3,"file":"snaps.d.mts","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,kBAAkB,EAClB,oBAAoB,EACrB,wCAAwC;AACzC,OAAO,KAAK,EAAE,WAAW,EAAE,iCAAiC;AAC5D,OAAO,EAEL,KAAK,MAAM,EACX,KAAK,IAAI,IAAI,aAAa,EAC3B,4BAA4B;AAC7B,OAAO,KAAK,EAAE,MAAM,EAAE,8BAA8B;AAmBpD,OAAO,KAAK,EAAE,gBAAgB,EAAE,2BAAuB;AACvD,OAA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Y,EAAE,iBAAiB,CAAC,CAAC;AACvD,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAC7B,WAAqD,EACrD,MAAc;IAEd,OAAO,OAAO,CAGR,CAAC,WAAW,EAAE,WAAW,EAAE,OAAO,EAAE,IAAI,CACtC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,cAAc,CAAC,OAAO,CACnD,IAAI,EAAE,CACR,CAAC,KACH,EAAE,CAAC,MAAM,CAAC,CACZ,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,8BAA8B,CAC5C,oBAA6B;IAE7B,MAAM,CACJ,QAAQ,CAAC,oBAAoB,CAAC,EAC9B,0CAA0C,CAC3C,CAAC;IAEF,MAAM,EAAE,WAAW,EAAE,oBAAoB,EAAE,GAAG,oBAAoB,CAAC;IAEnE,MAAM,CACJ,QAAQ,CAAC,oBAAoB,CAAC,EAC9B,wDAAwD,CACzD,CAAC;IAEF,MAAM,EAAE,OAAO,EAAE,GAAG,oBAAoB,CAAC;IAEzC,MAAM,CACJ,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAC9C,yEAAyE,CAC1E,CAAC;IAEF,MAAM,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC;IAEzB,MAAM,CACJ,QAAQ,CAAC,MAAM,CAAC;QACd,MAAM,CAAC,IAAI,KAAK,cAAc,CAAC,OAAO;QACtC,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,EACxB,iDAAiD,cAAc,CAAC,OAAO,UAAU,CAClF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport {\n selectiveUnion,\n type SnapId,\n type Snap as TruncatedSnap,\n} from '@metamask/snaps-sdk';\nimport type { Struct } from '@metamask/superstruct';\nimport {\n is,\n empty,\n enums,\n intersection,\n literal,\n refine,\n string,\n validate,\n} from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { assert, isObject, assertStruct, definePattern } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport stableStringify from 'fast-json-stable-stringify';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { LocalizationFile } from './localization';\nimport type {\n InitialConnections,\n SnapManifest,\n SnapPermissions,\n} from './manifest/validation';\nimport type { FetchedSnapFiles, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: SnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type SnapAuxiliaryFile = {\n path: string;\n // Value here should be stored as base64\n value: string;\n};\n\n/**\n * @deprecated Use SnapAuxiliaryFile instead. This was a typo that has been fixed.\n */\nexport type SnapAuxilaryFile = SnapAuxiliaryFile;\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = TruncatedSnap & {\n /**\n * The initial connections of the Snap, optional, requested on installation.\n */\n initialConnections?: InitialConnections;\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n\n /**\n * Static auxiliary files that can be loaded at runtime.\n */\n auxiliaryFiles?: SnapAuxiliaryFile[];\n\n /**\n * Localization files which are used to translate the manifest.\n */\n localizationFiles?: LocalizationFile[];\n\n /**\n * Flag to signal whether this snap was preinstalled or not.\n *\n * A lack of specifying this option will be deemed as not preinstalled.\n */\n preinstalled?: boolean;\n\n /**\n * Flag to signal whether this snap is removable or not.\n *\n * A lack of specifying this option will be deemed as removable.\n */\n removable?: boolean;\n\n /**\n * Flag to signal whether this snap should be hidden from the user or not.\n */\n hidden?: boolean;\n\n /**\n * Flag to signal whether this snap should hide the Snap branding like header or avatar in the UI or not.\n */\n hideSnapBranding?: boolean;\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport async function getSnapChecksum(\n files: FetchedSnapFiles,\n): Promise<string> {\n const { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles } =\n files;\n\n const all = [\n getChecksummableManifest(manifest),\n sourceCode,\n svgIcon,\n ...auxiliaryFiles,\n ...localizationFiles,\n ].filter((file) => file !== undefined);\n\n return base64.encode(await checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport async function validateSnapShasum(\n files: FetchedSnapFiles,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): Promise<void> {\n if (files.manifest.result.source.shasum !== (await getSnapChecksum(files))) {\n throw new Error(errorMessage);\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = definePattern(\n 'Base Snap Id',\n /^[\\x21-\\x7E]*$/u,\n);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\n\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdPrefixStruct = refine(\n string(),\n 'Snap ID prefix',\n (value) => {\n if (\n Object.values(SnapIdPrefixes).some((prefix) => value.startsWith(prefix))\n ) {\n return true;\n }\n\n const allowedPrefixes = Object.values(SnapIdPrefixes)\n .map((prefix) => `\"${prefix}\"`)\n .join(', ');\n\n return `Invalid or no prefix found. Expected Snap ID to start with one of: ${allowedPrefixes}, but received: \"${value}\"`;\n },\n);\n\nexport const SnapIdStruct = selectiveUnion((value) => {\n if (typeof value === 'string' && value.startsWith(SnapIdPrefixes.npm)) {\n return NpmSnapIdStruct;\n }\n\n if (typeof value === 'string' && value.startsWith(SnapIdPrefixes.local)) {\n return LocalSnapIdStruct;\n }\n\n return SnapIdPrefixStruct;\n});\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Check if the given value is a valid snap ID. This function is a type guard,\n * and will narrow the type of the value to `SnapId` if it returns `true`.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a valid snap ID, and `false` otherwise.\n */\nexport function isSnapId(value: unknown): value is SnapId {\n return is(value, SnapIdStruct);\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(value: unknown): asserts value is SnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n\nexport type { Snap as TruncatedSnap } from '@metamask/snaps-sdk';\n"]}
1
+ {"version":3,"file":"snaps.mjs","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":";;;;;;AAMA,OAAO,EACL,cAAc,EAGf,4BAA4B;AAE7B,OAAO,EACL,EAAE,EACF,KAAK,EACL,KAAK,EACL,YAAY,EACZ,OAAO,EACP,MAAM,EACN,MAAM,EACN,QAAQ,EACT,8BAA8B;AAE/B,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,YAAY,EAAE,aAAa,EAAE,wBAAwB;AAChF,OAAO,EAAE,MAAM,EAAE,oBAAoB;AACrC,OAAO,gBAAe,mCAAmC;;AACzD,OAAO,mBAAkB,kCAAkC;;AAE3D,OAAO,EAAE,cAAc,EAAE,sBAAkB;AAC3C,OAAO,EAAE,aAAa,EAAE,uBAAmB;AAQ3C,OAAO,EAAE,cAAc,EAAE,GAAG,EAAE,oBAAgB;AAG9C,+EAA+E;AAC/E,0EAA0E;AAC1E,0EAA0E;AAC1E,4DAA4D;AAC5D,uCAAuC;AACvC,2EAA2E;AAC3E,8EAA8E;AAC9E,qDAAqD;AACrD,mIAAmI;AACnI,MAAM,CAAC,MAAM,mBAAmB,GAC9B,kHAAkH,CAAC;AAErH,MAAM,CAAN,IAAY,UAMX;AAND,WAAY,UAAU;IACpB,uCAAyB,CAAA;IACzB,mCAAqB,CAAA;IACrB,iCAAmB,CAAA;IACnB,iCAAmB,CAAA;IACnB,iCAAmB,CAAA;AACrB,CAAC,EANW,UAAU,KAAV,UAAU,QAMrB;AAED,MAAM,CAAN,IAAY,gBAKX;AALD,WAAY,gBAAgB;IAC1B,mCAAe,CAAA;IACf,iCAAa,CAAA;IAC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AqD,EACrD,MAAc;IAEd,OAAO,OAAO,CAGR,CAAC,WAAW,EAAE,WAAW,EAAE,OAAO,EAAE,IAAI,CACtC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,cAAc,CAAC,OAAO,CACnD,IAAI,EAAE,CACR,CAAC,KACH,EAAE,CAAC,MAAM,CAAC,CACZ,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,8BAA8B,CAC5C,oBAA6B;IAE7B,MAAM,CACJ,QAAQ,CAAC,oBAAoB,CAAC,EAC9B,0CAA0C,CAC3C,CAAC;IAEF,MAAM,EAAE,WAAW,EAAE,oBAAoB,EAAE,GAAG,oBAAoB,CAAC;IAEnE,MAAM,CACJ,QAAQ,CAAC,oBAAoB,CAAC,EAC9B,wDAAwD,CACzD,CAAC;IAEF,MAAM,EAAE,OAAO,EAAE,GAAG,oBAAoB,CAAC;IAEzC,MAAM,CACJ,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAC9C,yEAAyE,CAC1E,CAAC;IAEF,MAAM,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC;IAEzB,MAAM,CACJ,QAAQ,CAAC,MAAM,CAAC;QACd,MAAM,CAAC,IAAI,KAAK,cAAc,CAAC,OAAO;QACtC,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,EACxB,iDAAiD,cAAc,CAAC,OAAO,UAAU,CAClF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport {\n selectiveUnion,\n type SnapId,\n type Snap as TruncatedSnap,\n} from '@metamask/snaps-sdk';\nimport type { Struct } from '@metamask/superstruct';\nimport {\n is,\n empty,\n enums,\n intersection,\n literal,\n refine,\n string,\n validate,\n} from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { assert, isObject, assertStruct, definePattern } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport stableStringify from 'fast-json-stable-stringify';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { LocalizationFile } from './localization';\nimport type {\n InitialConnections,\n SnapManifest,\n SnapPermissions,\n} from './manifest/validation';\nimport type { FetchedSnapFiles, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: SnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type SnapAuxiliaryFile = {\n path: string;\n // Value here should be stored as base64\n value: string;\n};\n\n/**\n * @deprecated Use SnapAuxiliaryFile instead. This was a typo that has been fixed.\n */\nexport type SnapAuxilaryFile = SnapAuxiliaryFile;\n\n/**\n * A Snap's data as stored in the StorageService.\n */\nexport type StorageServiceSnapData = {\n sourceCode: string;\n};\n\n/**\n * A Snap's data as stored in the StorageService and the SnapController state.\n */\nexport type PersistedSnap = Snap & StorageServiceSnapData;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = TruncatedSnap & {\n /**\n * The initial connections of the Snap, optional, requested on installation.\n */\n initialConnections?: InitialConnections;\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n\n /**\n * Static auxiliary files that can be loaded at runtime.\n */\n auxiliaryFiles?: SnapAuxiliaryFile[];\n\n /**\n * Localization files which are used to translate the manifest.\n */\n localizationFiles?: LocalizationFile[];\n\n /**\n * Flag to signal whether this snap was preinstalled or not.\n *\n * A lack of specifying this option will be deemed as not preinstalled.\n */\n preinstalled?: boolean;\n\n /**\n * Flag to signal whether this snap is removable or not.\n *\n * A lack of specifying this option will be deemed as removable.\n */\n removable?: boolean;\n\n /**\n * Flag to signal whether this snap should be hidden from the user or not.\n */\n hidden?: boolean;\n\n /**\n * Flag to signal whether this snap should hide the Snap branding like header or avatar in the UI or not.\n */\n hideSnapBranding?: boolean;\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport async function getSnapChecksum(\n files: FetchedSnapFiles,\n): Promise<string> {\n const { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles } =\n files;\n\n const all = [\n getChecksummableManifest(manifest),\n sourceCode,\n svgIcon,\n ...auxiliaryFiles,\n ...localizationFiles,\n ].filter((file) => file !== undefined);\n\n return base64.encode(await checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport async function validateSnapShasum(\n files: FetchedSnapFiles,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): Promise<void> {\n if (files.manifest.result.source.shasum !== (await getSnapChecksum(files))) {\n throw new Error(errorMessage);\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = definePattern(\n 'Base Snap Id',\n /^[\\x21-\\x7E]*$/u,\n);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\n\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdPrefixStruct = refine(\n string(),\n 'Snap ID prefix',\n (value) => {\n if (\n Object.values(SnapIdPrefixes).some((prefix) => value.startsWith(prefix))\n ) {\n return true;\n }\n\n const allowedPrefixes = Object.values(SnapIdPrefixes)\n .map((prefix) => `\"${prefix}\"`)\n .join(', ');\n\n return `Invalid or no prefix found. Expected Snap ID to start with one of: ${allowedPrefixes}, but received: \"${value}\"`;\n },\n);\n\nexport const SnapIdStruct = selectiveUnion((value) => {\n if (typeof value === 'string' && value.startsWith(SnapIdPrefixes.npm)) {\n return NpmSnapIdStruct;\n }\n\n if (typeof value === 'string' && value.startsWith(SnapIdPrefixes.local)) {\n return LocalSnapIdStruct;\n }\n\n return SnapIdPrefixStruct;\n});\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Check if the given value is a valid snap ID. This function is a type guard,\n * and will narrow the type of the value to `SnapId` if it returns `true`.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a valid snap ID, and `false` otherwise.\n */\nexport function isSnapId(value: unknown): value is SnapId {\n return is(value, SnapIdStruct);\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(value: unknown): asserts value is SnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n\nexport type { Snap as TruncatedSnap } from '@metamask/snaps-sdk';\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask/snaps-utils",
3
- "version": "12.0.1",
3
+ "version": "12.1.1",
4
4
  "description": "A collection of utilities for MetaMask Snaps",
5
5
  "keywords": [
6
6
  "MetaMask",
@@ -84,27 +84,27 @@
84
84
  "@metamask/messenger": "^0.3.0",
85
85
  "@metamask/permission-controller": "^12.2.0",
86
86
  "@metamask/rpc-errors": "^7.0.3",
87
- "@metamask/slip44": "^4.3.0",
87
+ "@metamask/slip44": "^4.4.0",
88
88
  "@metamask/snaps-registry": "^4.0.0",
89
- "@metamask/snaps-sdk": "^10.4.0",
89
+ "@metamask/snaps-sdk": "^11.0.0",
90
90
  "@metamask/superstruct": "^3.2.1",
91
- "@metamask/utils": "^11.9.0",
91
+ "@metamask/utils": "^11.10.0",
92
92
  "@scure/base": "^1.1.1",
93
93
  "chalk": "^4.1.2",
94
94
  "cron-parser": "^4.5.0",
95
95
  "fast-deep-equal": "^3.1.3",
96
96
  "fast-json-stable-stringify": "^2.1.0",
97
- "fast-xml-parser": "^4.4.1",
97
+ "fast-xml-parser": "^5.3.8",
98
98
  "luxon": "^3.5.0",
99
99
  "marked": "^12.0.1",
100
100
  "rfdc": "^1.3.0",
101
101
  "semver": "^7.5.4",
102
- "ses": "^1.14.0",
102
+ "ses": "^1.15.0",
103
103
  "validate-npm-package-name": "^5.0.0"
104
104
  },
105
105
  "devDependencies": {
106
- "@lavamoat/allow-scripts": "^3.4.2",
107
- "@metamask/auto-changelog": "^5.0.2",
106
+ "@lavamoat/allow-scripts": "^3.4.3",
107
+ "@metamask/auto-changelog": "^5.3.2",
108
108
  "@metamask/post-message-stream": "^10.0.0",
109
109
  "@swc/core": "1.11.31",
110
110
  "@swc/jest": "^0.2.38",