@metamask/snaps-utils 3.3.0 → 4.0.0

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.
Files changed (82) hide show
  1. package/CHANGELOG.md +29 -1
  2. package/dist/cjs/auxiliary-files.js +6 -19
  3. package/dist/cjs/auxiliary-files.js.map +1 -1
  4. package/dist/cjs/checksum.js +22 -5
  5. package/dist/cjs/checksum.js.map +1 -1
  6. package/dist/cjs/cronjob.js.map +1 -1
  7. package/dist/cjs/enum.js.map +1 -1
  8. package/dist/cjs/errors.js +6 -154
  9. package/dist/cjs/errors.js.map +1 -1
  10. package/dist/cjs/handlers.js +6 -13
  11. package/dist/cjs/handlers.js.map +1 -1
  12. package/dist/cjs/index.browser.js +1 -0
  13. package/dist/cjs/index.browser.js.map +1 -1
  14. package/dist/cjs/index.js +1 -0
  15. package/dist/cjs/index.js.map +1 -1
  16. package/dist/cjs/localization.js +2 -2
  17. package/dist/cjs/localization.js.map +1 -1
  18. package/dist/cjs/manifest/manifest.js +11 -11
  19. package/dist/cjs/manifest/manifest.js.map +1 -1
  20. package/dist/cjs/manifest/validation.js.map +1 -1
  21. package/dist/cjs/namespace.js +5 -1
  22. package/dist/cjs/namespace.js.map +1 -1
  23. package/dist/cjs/npm.js +2 -2
  24. package/dist/cjs/npm.js.map +1 -1
  25. package/dist/cjs/snaps.js +7 -6
  26. package/dist/cjs/snaps.js.map +1 -1
  27. package/dist/cjs/structs.js.map +1 -1
  28. package/dist/cjs/types.js.map +1 -1
  29. package/dist/cjs/ui.js +51 -0
  30. package/dist/cjs/ui.js.map +1 -0
  31. package/dist/cjs/validation.js +2 -2
  32. package/dist/cjs/validation.js.map +1 -1
  33. package/dist/esm/auxiliary-files.js +1 -6
  34. package/dist/esm/auxiliary-files.js.map +1 -1
  35. package/dist/esm/checksum.js +25 -6
  36. package/dist/esm/checksum.js.map +1 -1
  37. package/dist/esm/cronjob.js +1 -1
  38. package/dist/esm/cronjob.js.map +1 -1
  39. package/dist/esm/enum.js.map +1 -1
  40. package/dist/esm/errors.js +2 -157
  41. package/dist/esm/errors.js.map +1 -1
  42. package/dist/esm/handlers.js +4 -8
  43. package/dist/esm/handlers.js.map +1 -1
  44. package/dist/esm/index.browser.js +1 -0
  45. package/dist/esm/index.browser.js.map +1 -1
  46. package/dist/esm/index.js +1 -0
  47. package/dist/esm/index.js.map +1 -1
  48. package/dist/esm/localization.js +1 -1
  49. package/dist/esm/localization.js.map +1 -1
  50. package/dist/esm/manifest/manifest.js +8 -8
  51. package/dist/esm/manifest/manifest.js.map +1 -1
  52. package/dist/esm/manifest/validation.js.map +1 -1
  53. package/dist/esm/namespace.js +3 -2
  54. package/dist/esm/namespace.js.map +1 -1
  55. package/dist/esm/npm.js +2 -2
  56. package/dist/esm/npm.js.map +1 -1
  57. package/dist/esm/snaps.js +7 -6
  58. package/dist/esm/snaps.js.map +1 -1
  59. package/dist/esm/structs.js.map +1 -1
  60. package/dist/esm/types.js.map +1 -1
  61. package/dist/esm/ui.js +48 -0
  62. package/dist/esm/ui.js.map +1 -0
  63. package/dist/esm/validation.js +2 -2
  64. package/dist/esm/validation.js.map +1 -1
  65. package/dist/types/auxiliary-files.d.ts +1 -5
  66. package/dist/types/checksum.d.ts +9 -2
  67. package/dist/types/enum.d.ts +1 -21
  68. package/dist/types/errors.d.ts +1 -109
  69. package/dist/types/handlers.d.ts +48 -173
  70. package/dist/types/index.browser.d.ts +1 -0
  71. package/dist/types/index.d.ts +1 -0
  72. package/dist/types/localization.d.ts +22 -22
  73. package/dist/types/manifest/manifest.d.ts +2 -2
  74. package/dist/types/manifest/validation.d.ts +80 -78
  75. package/dist/types/namespace.d.ts +11 -10
  76. package/dist/types/npm.d.ts +1 -1
  77. package/dist/types/snaps.d.ts +8 -43
  78. package/dist/types/structs.d.ts +23 -0
  79. package/dist/types/types.d.ts +0 -1
  80. package/dist/types/ui.d.ts +20 -0
  81. package/dist/types/validation.d.ts +1 -1
  82. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -6,6 +6,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [4.0.0]
10
+ ### Changed
11
+ - Use `SubtleCrypto` for checksum calculation if available ([#1953](https://github.com/MetaMask/snaps/pull/1953))
12
+ - This reduces the time of the checksum calculation by up to 95% in some
13
+ environments.
14
+ - Use `@metamask/snaps-sdk` package ([#1930](https://github.com/MetaMask/snaps/pull/1930),
15
+ [#1946](https://github.com/MetaMask/snaps/pull/1946), [#1950](https://github.com/MetaMask/snaps/pull/1950),
16
+ [#1949](https://github.com/MetaMask/snaps/pull/1949), [#1954](https://github.com/MetaMask/snaps/pull/1954))
17
+ - This package replaces the `@metamask/snaps-types` and
18
+ - `@metamask/snaps-ui` packages, and is much more lightweight.
19
+
20
+ ### Removed
21
+ - **BREAKING**: Remove `ValidatedSnapId` and `SnapId` types ([#1930](https://github.com/MetaMask/snaps/pull/1930))
22
+ - `ValidatedSnapId` was moved to the `@metamask/snaps-sdk` package as
23
+ `SnapId`.
24
+ - `SnapId` was an alias of `string`, and is no longer needed.
25
+ - **BREAKING**: Remove `SnapError` ([#1949](https://github.com/MetaMask/snaps/pull/1949))
26
+ - This class was moved to the `@metamask/snaps-sdk` package.
27
+ - **BREAKING**: Remove `EnumToUnion` type ([#1930](https://github.com/MetaMask/snaps/pull/1930))
28
+ - This type was moved to the `@metamask/snaps-sdk` package.
29
+ - **BREAKING**: Remove `RequestedSnapPermissions` type ([#1930](https://github.com/MetaMask/snaps/pull/1930))
30
+ - This type was deprecated, and is now replaced by the `InitialPermissions`
31
+ type from the `@metamask/snaps-sdk` package.
32
+
33
+ ### Fixed
34
+ - Include localization files in checksum calculations ([#1956](https://github.com/MetaMask/snaps/pull/1956))
35
+
9
36
  ## [3.3.0]
10
37
  ### Added
11
38
  - Add manifest localization functionality ([#1889](https://github.com/MetaMask/snaps/pull/1889))
@@ -76,7 +103,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
76
103
  - The version of the package no longer needs to match the version of all other
77
104
  MetaMask Snaps packages.
78
105
 
79
- [Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@3.3.0...HEAD
106
+ [Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@4.0.0...HEAD
107
+ [4.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@3.3.0...@metamask/snaps-utils@4.0.0
80
108
  [3.3.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@3.2.0...@metamask/snaps-utils@3.3.0
81
109
  [3.2.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@3.1.0...@metamask/snaps-utils@3.2.0
82
110
  [3.1.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@3.0.0...@metamask/snaps-utils@3.1.0
@@ -2,36 +2,23 @@
2
2
  Object.defineProperty(exports, "__esModule", {
3
3
  value: true
4
4
  });
5
- function _export(target, all) {
6
- for(var name in all)Object.defineProperty(target, name, {
7
- enumerable: true,
8
- get: all[name]
9
- });
10
- }
11
- _export(exports, {
12
- AuxiliaryFileEncoding: function() {
13
- return AuxiliaryFileEncoding;
14
- },
15
- encodeAuxiliaryFile: function() {
5
+ Object.defineProperty(exports, "encodeAuxiliaryFile", {
6
+ enumerable: true,
7
+ get: function() {
16
8
  return encodeAuxiliaryFile;
17
9
  }
18
10
  });
11
+ const _snapssdk = require("@metamask/snaps-sdk");
19
12
  const _utils = require("@metamask/utils");
20
13
  const _base = require("@scure/base");
21
- var AuxiliaryFileEncoding;
22
- (function(AuxiliaryFileEncoding) {
23
- AuxiliaryFileEncoding["Base64"] = 'base64';
24
- AuxiliaryFileEncoding["Hex"] = 'hex';
25
- AuxiliaryFileEncoding["Utf8"] = 'utf8';
26
- })(AuxiliaryFileEncoding || (AuxiliaryFileEncoding = {}));
27
14
  function encodeAuxiliaryFile(value, encoding) {
28
15
  // Input is assumed to be the stored file in base64.
29
- if (encoding === AuxiliaryFileEncoding.Base64) {
16
+ if (encoding === _snapssdk.AuxiliaryFileEncoding.Base64) {
30
17
  return value;
31
18
  }
32
19
  // TODO: Use @metamask/utils for this
33
20
  const decoded = _base.base64.decode(value);
34
- if (encoding === AuxiliaryFileEncoding.Utf8) {
21
+ if (encoding === _snapssdk.AuxiliaryFileEncoding.Utf8) {
35
22
  return (0, _utils.bytesToString)(decoded);
36
23
  }
37
24
  return (0, _utils.bytesToHex)(decoded);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auxiliary-files.ts"],"sourcesContent":["import { bytesToHex, bytesToString } from '@metamask/utils';\nimport { base64 } from '@scure/base';\n\nexport enum AuxiliaryFileEncoding {\n Base64 = 'base64',\n Hex = 'hex',\n Utf8 = 'utf8',\n}\n\n/**\n * Re-encodes an auxiliary file if needed depending on the requested file encoding.\n *\n * @param value - The base64 value stored for the auxiliary file.\n * @param encoding - The chosen encoding.\n * @returns The file encoded in the requested encoding.\n */\nexport function encodeAuxiliaryFile(\n value: string,\n encoding: AuxiliaryFileEncoding,\n) {\n // Input is assumed to be the stored file in base64.\n if (encoding === AuxiliaryFileEncoding.Base64) {\n return value;\n }\n\n // TODO: Use @metamask/utils for this\n const decoded = base64.decode(value);\n if (encoding === AuxiliaryFileEncoding.Utf8) {\n return bytesToString(decoded);\n }\n\n return bytesToHex(decoded);\n}\n"],"names":["encodeAuxiliaryFile","AuxiliaryFileEncoding","Base64","Hex","Utf8","value","encoding","decoded","base64","decode","bytesToString","bytesToHex"],"mappings":";;;;;;;;;;;;;;IAgBgBA,mBAAmB;eAAnBA;;;uBAhB0B;sBACnB;IAEhB;UAAKC,qBAAqB;IAArBA,sBACVC,YAAS;IADCD,sBAEVE,SAAM;IAFIF,sBAGVG,UAAO;GAHGH,0BAAAA;AAaL,SAASD,oBACdK,KAAa,EACbC,QAA+B;IAE/B,oDAAoD;IACpD,IAAIA,aAAaL,sBAAsBC,MAAM,EAAE;QAC7C,OAAOG;IACT;IAEA,qCAAqC;IACrC,MAAME,UAAUC,YAAM,CAACC,MAAM,CAACJ;IAC9B,IAAIC,aAAaL,sBAAsBG,IAAI,EAAE;QAC3C,OAAOM,IAAAA,oBAAa,EAACH;IACvB;IAEA,OAAOI,IAAAA,iBAAU,EAACJ;AACpB"}
1
+ {"version":3,"sources":["../../src/auxiliary-files.ts"],"sourcesContent":["import { AuxiliaryFileEncoding } from '@metamask/snaps-sdk';\nimport { bytesToHex, bytesToString } from '@metamask/utils';\nimport { base64 } from '@scure/base';\n\n/**\n * Re-encodes an auxiliary file if needed depending on the requested file encoding.\n *\n * @param value - The base64 value stored for the auxiliary file.\n * @param encoding - The chosen encoding.\n * @returns The file encoded in the requested encoding.\n */\nexport function encodeAuxiliaryFile(\n value: string,\n encoding: AuxiliaryFileEncoding,\n) {\n // Input is assumed to be the stored file in base64.\n if (encoding === AuxiliaryFileEncoding.Base64) {\n return value;\n }\n\n // TODO: Use @metamask/utils for this\n const decoded = base64.decode(value);\n if (encoding === AuxiliaryFileEncoding.Utf8) {\n return bytesToString(decoded);\n }\n\n return bytesToHex(decoded);\n}\n"],"names":["encodeAuxiliaryFile","value","encoding","AuxiliaryFileEncoding","Base64","decoded","base64","decode","Utf8","bytesToString","bytesToHex"],"mappings":";;;;+BAWgBA;;;eAAAA;;;0BAXsB;uBACI;sBACnB;AAShB,SAASA,oBACdC,KAAa,EACbC,QAA+B;IAE/B,oDAAoD;IACpD,IAAIA,aAAaC,+BAAqB,CAACC,MAAM,EAAE;QAC7C,OAAOH;IACT;IAEA,qCAAqC;IACrC,MAAMI,UAAUC,YAAM,CAACC,MAAM,CAACN;IAC9B,IAAIC,aAAaC,+BAAqB,CAACK,IAAI,EAAE;QAC3C,OAAOC,IAAAA,oBAAa,EAACJ;IACvB;IAEA,OAAOK,IAAAA,iBAAU,EAACL;AACpB"}
@@ -9,6 +9,9 @@ function _export(target, all) {
9
9
  });
10
10
  }
11
11
  _export(exports, {
12
+ getChecksumBytes: function() {
13
+ return getChecksumBytes;
14
+ },
12
15
  checksum: function() {
13
16
  return checksum;
14
17
  },
@@ -19,12 +22,25 @@ _export(exports, {
19
22
  const _utils = require("@metamask/utils");
20
23
  const _sha256 = require("@noble/hashes/sha256");
21
24
  const _VirtualFile = require("./virtual-file/VirtualFile");
22
- function checksum(bytes) {
23
- const value = bytes instanceof _VirtualFile.VirtualFile ? bytes.value : bytes;
25
+ function getChecksumBytes(bytes) {
26
+ // Unwrap VirtualFiles to extract the content
27
+ // The content is then either a string or Uint8Array
28
+ const unwrapped = bytes instanceof _VirtualFile.VirtualFile ? bytes.value : bytes;
29
+ if (typeof unwrapped === 'string') {
30
+ return (0, _utils.stringToBytes)(unwrapped);
31
+ }
32
+ return unwrapped;
33
+ }
34
+ async function checksum(bytes) {
35
+ const value = getChecksumBytes(bytes);
36
+ // Use crypto.subtle.digest whenever possible as it is faster.
37
+ if ('crypto' in globalThis && typeof globalThis.crypto === 'object' && crypto.subtle?.digest) {
38
+ return new Uint8Array(await crypto.subtle.digest('SHA-256', value));
39
+ }
24
40
  return (0, _sha256.sha256)(value);
25
41
  }
26
- function checksumFiles(files) {
27
- return checksum((0, _utils.concatBytes)([
42
+ async function checksumFiles(files) {
43
+ const checksums = await Promise.all([
28
44
  ...files
29
45
  ].sort((a, b)=>{
30
46
  (0, _utils.assert)(a.path !== b.path, 'Tried to sort files with non-unique paths.');
@@ -32,7 +48,8 @@ function checksumFiles(files) {
32
48
  return -1;
33
49
  }
34
50
  return 1;
35
- }).map((file)=>checksum(file))));
51
+ }).map(async (file)=>checksum(file)));
52
+ return checksum((0, _utils.concatBytes)(checksums));
36
53
  }
37
54
 
38
55
  //# sourceMappingURL=checksum.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/checksum.ts"],"sourcesContent":["import { assert, concatBytes } from '@metamask/utils';\nimport { sha256 } from '@noble/hashes/sha256';\n\nimport { VirtualFile } from './virtual-file/VirtualFile';\n\n/**\n * Calculates checksum for a single byte array.\n *\n * @param bytes - The byte array to calculate the checksum for.\n * @returns A single sha-256 checksum.\n */\nexport function checksum(bytes: VirtualFile | Uint8Array | string): Uint8Array {\n const value = bytes instanceof VirtualFile ? bytes.value : bytes;\n return sha256(value);\n}\n\n/**\n * Calculates checksum over multiple files in a reproducible way.\n *\n * 1. Sort all the files by their paths.\n * 2. Calculate sha-256 checksum of each file separately.\n * 3. Concatenate all the checksums into one buffer and sha-256 that buffer.\n *\n * The sorting of paths is done using {@link https://tc39.es/ecma262/#sec-islessthan UTF-16 Code Units}.\n *\n * @param files - The files over which to calculate the checksum.\n * @returns A single sha-256 checksum.\n */\nexport function checksumFiles(files: VirtualFile[]) {\n return checksum(\n concatBytes(\n [...files]\n .sort((a, b) => {\n assert(\n a.path !== b.path,\n 'Tried to sort files with non-unique paths.',\n );\n if (a.path < b.path) {\n return -1;\n }\n return 1;\n })\n .map((file) => checksum(file)),\n ),\n );\n}\n"],"names":["checksum","checksumFiles","bytes","value","VirtualFile","sha256","files","concatBytes","sort","a","b","assert","path","map","file"],"mappings":";;;;;;;;;;;IAWgBA,QAAQ;eAARA;;IAiBAC,aAAa;eAAbA;;;uBA5BoB;wBACb;6BAEK;AAQrB,SAASD,SAASE,KAAwC;IAC/D,MAAMC,QAAQD,iBAAiBE,wBAAW,GAAGF,MAAMC,KAAK,GAAGD;IAC3D,OAAOG,IAAAA,cAAM,EAACF;AAChB;AAcO,SAASF,cAAcK,KAAoB;IAChD,OAAON,SACLO,IAAAA,kBAAW,EACT;WAAID;KAAM,CACPE,IAAI,CAAC,CAACC,GAAGC;QACRC,IAAAA,aAAM,EACJF,EAAEG,IAAI,KAAKF,EAAEE,IAAI,EACjB;QAEF,IAAIH,EAAEG,IAAI,GAAGF,EAAEE,IAAI,EAAE;YACnB,OAAO,CAAC;QACV;QACA,OAAO;IACT,GACCC,GAAG,CAAC,CAACC,OAASd,SAASc;AAGhC"}
1
+ {"version":3,"sources":["../../src/checksum.ts"],"sourcesContent":["import { assert, concatBytes, stringToBytes } from '@metamask/utils';\nimport { sha256 } from '@noble/hashes/sha256';\n\nimport { VirtualFile } from './virtual-file/VirtualFile';\n\n/**\n * Convert an input value to a Uint8Array for use in a checksum.\n *\n * @param bytes - A value to use for a checksum calculation.\n * @returns The input value converted to a Uint8Array if necessary.\n */\nexport function getChecksumBytes(\n bytes: VirtualFile | Uint8Array | string,\n): Uint8Array {\n // Unwrap VirtualFiles to extract the content\n // The content is then either a string or Uint8Array\n const unwrapped = bytes instanceof VirtualFile ? bytes.value : bytes;\n\n if (typeof unwrapped === 'string') {\n return stringToBytes(unwrapped);\n }\n\n return unwrapped;\n}\n\n/**\n * Calculates checksum for a single byte array.\n *\n * @param bytes - The byte array to calculate the checksum for.\n * @returns A single sha-256 checksum.\n */\nexport async function checksum(\n bytes: VirtualFile | Uint8Array | string,\n): Promise<Uint8Array> {\n const value = getChecksumBytes(bytes);\n // Use crypto.subtle.digest whenever possible as it is faster.\n if (\n 'crypto' in globalThis &&\n typeof globalThis.crypto === 'object' &&\n crypto.subtle?.digest\n ) {\n return new Uint8Array(await crypto.subtle.digest('SHA-256', value));\n }\n return sha256(value);\n}\n\n/**\n * Calculates checksum over multiple files in a reproducible way.\n *\n * 1. Sort all the files by their paths.\n * 2. Calculate sha-256 checksum of each file separately.\n * 3. Concatenate all the checksums into one buffer and sha-256 that buffer.\n *\n * The sorting of paths is done using {@link https://tc39.es/ecma262/#sec-islessthan UTF-16 Code Units}.\n *\n * @param files - The files over which to calculate the checksum.\n * @returns A single sha-256 checksum.\n */\nexport async function checksumFiles(files: VirtualFile[]) {\n const checksums = await Promise.all(\n [...files]\n .sort((a, b) => {\n assert(a.path !== b.path, 'Tried to sort files with non-unique paths.');\n if (a.path < b.path) {\n return -1;\n }\n return 1;\n })\n .map(async (file) => checksum(file)),\n );\n\n return checksum(concatBytes(checksums));\n}\n"],"names":["getChecksumBytes","checksum","checksumFiles","bytes","unwrapped","VirtualFile","value","stringToBytes","globalThis","crypto","subtle","digest","Uint8Array","sha256","files","checksums","Promise","all","sort","a","b","assert","path","map","file","concatBytes"],"mappings":";;;;;;;;;;;IAWgBA,gBAAgB;eAAhBA;;IAoBMC,QAAQ;eAARA;;IA2BAC,aAAa;eAAbA;;;uBA1D6B;wBAC5B;6BAEK;AAQrB,SAASF,iBACdG,KAAwC;IAExC,6CAA6C;IAC7C,oDAAoD;IACpD,MAAMC,YAAYD,iBAAiBE,wBAAW,GAAGF,MAAMG,KAAK,GAAGH;IAE/D,IAAI,OAAOC,cAAc,UAAU;QACjC,OAAOG,IAAAA,oBAAa,EAACH;IACvB;IAEA,OAAOA;AACT;AAQO,eAAeH,SACpBE,KAAwC;IAExC,MAAMG,QAAQN,iBAAiBG;IAC/B,8DAA8D;IAC9D,IACE,YAAYK,cACZ,OAAOA,WAAWC,MAAM,KAAK,YAC7BA,OAAOC,MAAM,EAAEC,QACf;QACA,OAAO,IAAIC,WAAW,MAAMH,OAAOC,MAAM,CAACC,MAAM,CAAC,WAAWL;IAC9D;IACA,OAAOO,IAAAA,cAAM,EAACP;AAChB;AAcO,eAAeJ,cAAcY,KAAoB;IACtD,MAAMC,YAAY,MAAMC,QAAQC,GAAG,CACjC;WAAIH;KAAM,CACPI,IAAI,CAAC,CAACC,GAAGC;QACRC,IAAAA,aAAM,EAACF,EAAEG,IAAI,KAAKF,EAAEE,IAAI,EAAE;QAC1B,IAAIH,EAAEG,IAAI,GAAGF,EAAEE,IAAI,EAAE;YACnB,OAAO,CAAC;QACV;QACA,OAAO;IACT,GACCC,GAAG,CAAC,OAAOC,OAASvB,SAASuB;IAGlC,OAAOvB,SAASwB,IAAAA,kBAAW,EAACV;AAC9B"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cronjob.ts"],"sourcesContent":["import { JsonRpcRequestStruct } from '@metamask/utils';\nimport { parseExpression } from 'cron-parser';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n assign,\n coerce,\n create,\n object,\n omit,\n optional,\n partial,\n pick,\n refine,\n string,\n} from 'superstruct';\n\nexport const CronjobRpcRequestStruct = assign(\n partial(pick(JsonRpcRequestStruct, ['id', 'jsonrpc'])),\n omit(JsonRpcRequestStruct, ['id', 'jsonrpc']),\n);\nexport type CronjobRpcRequest = Infer<typeof CronjobRpcRequestStruct>;\n\nexport const CronExpressionStruct = refine(\n coerce(\n string(),\n object({\n minute: optional(string()),\n hour: optional(string()),\n dayOfMonth: optional(string()),\n month: optional(string()),\n dayOfWeek: optional(string()),\n }),\n (value) =>\n `${value.minute ?? '*'} ${value.hour ?? '*'} ${value.dayOfMonth ?? '*'} ${\n value.month ?? '*'\n } ${value.dayOfWeek ?? '*'}`,\n ),\n 'CronExpression',\n (value) => {\n try {\n parseExpression(value);\n return true;\n } catch {\n return false;\n }\n },\n);\n\nexport type CronExpression = Infer<typeof CronExpressionStruct>;\n\n/**\n * Parses a cron expression.\n *\n * @param expression - Expression to parse.\n * @returns A CronExpression class instance.\n */\nexport function parseCronExpression(expression: string | object) {\n const ensureStringExpression = create(expression, CronExpressionStruct);\n return parseExpression(ensureStringExpression);\n}\n\nexport const CronjobSpecificationStruct = object({\n expression: CronExpressionStruct,\n request: CronjobRpcRequestStruct,\n});\nexport type CronjobSpecification = Infer<typeof CronjobSpecificationStruct>;\n\n/**\n * Check if the given value is a {@link CronjobSpecification} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link CronjobSpecification} object.\n */\nexport function isCronjobSpecification(value: unknown): boolean {\n try {\n create(value, CronjobSpecificationStruct);\n return true;\n } catch {\n return false;\n }\n}\n\nexport const CronjobSpecificationArrayStruct = array(\n CronjobSpecificationStruct,\n);\n\n/**\n * Check if the given value is an array of {@link CronjobSpecification} objects.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid array of {@link CronjobSpecification} objects.\n */\nexport function isCronjobSpecificationArray(value: unknown): boolean {\n try {\n create(value, CronjobSpecificationArrayStruct);\n return true;\n } catch {\n return false;\n }\n}\n"],"names":["CronjobRpcRequestStruct","CronExpressionStruct","parseCronExpression","CronjobSpecificationStruct","isCronjobSpecification","CronjobSpecificationArrayStruct","isCronjobSpecificationArray","assign","partial","pick","JsonRpcRequestStruct","omit","refine","coerce","string","object","minute","optional","hour","dayOfMonth","month","dayOfWeek","value","parseExpression","expression","ensureStringExpression","create","request","array"],"mappings":";;;;;;;;;;;IAiBaA,uBAAuB;eAAvBA;;IAMAC,oBAAoB;eAApBA;;IAkCGC,mBAAmB;eAAnBA;;IAKHC,0BAA0B;eAA1BA;;IAYGC,sBAAsB;eAAtBA;;IASHC,+BAA+B;eAA/BA;;IAUGC,2BAA2B;eAA3BA;;;uBA7FqB;4BACL;6BAczB;AAEA,MAAMN,0BAA0BO,IAAAA,mBAAM,EAC3CC,IAAAA,oBAAO,EAACC,IAAAA,iBAAI,EAACC,2BAAoB,EAAE;IAAC;IAAM;CAAU,IACpDC,IAAAA,iBAAI,EAACD,2BAAoB,EAAE;IAAC;IAAM;CAAU;AAIvC,MAAMT,uBAAuBW,IAAAA,mBAAM,EACxCC,IAAAA,mBAAM,EACJC,IAAAA,mBAAM,KACNC,IAAAA,mBAAM,EAAC;IACLC,QAAQC,IAAAA,qBAAQ,EAACH,IAAAA,mBAAM;IACvBI,MAAMD,IAAAA,qBAAQ,EAACH,IAAAA,mBAAM;IACrBK,YAAYF,IAAAA,qBAAQ,EAACH,IAAAA,mBAAM;IAC3BM,OAAOH,IAAAA,qBAAQ,EAACH,IAAAA,mBAAM;IACtBO,WAAWJ,IAAAA,qBAAQ,EAACH,IAAAA,mBAAM;AAC5B,IACA,CAACQ,QACC,CAAC,EAAEA,MAAMN,MAAM,IAAI,IAAI,CAAC,EAAEM,MAAMJ,IAAI,IAAI,IAAI,CAAC,EAAEI,MAAMH,UAAU,IAAI,IAAI,CAAC,EACtEG,MAAMF,KAAK,IAAI,IAChB,CAAC,EAAEE,MAAMD,SAAS,IAAI,IAAI,CAAC,GAEhC,kBACA,CAACC;IACC,IAAI;QACFC,IAAAA,2BAAe,EAACD;QAChB,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAWK,SAASpB,oBAAoBsB,UAA2B;IAC7D,MAAMC,yBAAyBC,IAAAA,mBAAM,EAACF,YAAYvB;IAClD,OAAOsB,IAAAA,2BAAe,EAACE;AACzB;AAEO,MAAMtB,6BAA6BY,IAAAA,mBAAM,EAAC;IAC/CS,YAAYvB;IACZ0B,SAAS3B;AACX;AASO,SAASI,uBAAuBkB,KAAc;IACnD,IAAI;QACFI,IAAAA,mBAAM,EAACJ,OAAOnB;QACd,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAEO,MAAME,kCAAkCuB,IAAAA,kBAAK,EAClDzB;AASK,SAASG,4BAA4BgB,KAAc;IACxD,IAAI;QACFI,IAAAA,mBAAM,EAACJ,OAAOjB;QACd,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF"}
1
+ {"version":3,"sources":["../../src/cronjob.ts"],"sourcesContent":["import { JsonRpcRequestStruct } from '@metamask/utils';\nimport { parseExpression } from 'cron-parser';\nimport type { Infer } from 'superstruct';\nimport {\n assign,\n omit,\n partial,\n pick,\n array,\n coerce,\n create,\n object,\n optional,\n refine,\n string,\n} from 'superstruct';\n\nexport const CronjobRpcRequestStruct = assign(\n partial(pick(JsonRpcRequestStruct, ['id', 'jsonrpc'])),\n omit(JsonRpcRequestStruct, ['id', 'jsonrpc']),\n);\nexport type CronjobRpcRequest = Infer<typeof CronjobRpcRequestStruct>;\n\nexport const CronExpressionStruct = refine(\n coerce(\n string(),\n object({\n minute: optional(string()),\n hour: optional(string()),\n dayOfMonth: optional(string()),\n month: optional(string()),\n dayOfWeek: optional(string()),\n }),\n (value) =>\n `${value.minute ?? '*'} ${value.hour ?? '*'} ${value.dayOfMonth ?? '*'} ${\n value.month ?? '*'\n } ${value.dayOfWeek ?? '*'}`,\n ),\n 'CronExpression',\n (value) => {\n try {\n parseExpression(value);\n return true;\n } catch {\n return false;\n }\n },\n);\n\nexport type CronExpression = Infer<typeof CronExpressionStruct>;\n\n/**\n * Parses a cron expression.\n *\n * @param expression - Expression to parse.\n * @returns A CronExpression class instance.\n */\nexport function parseCronExpression(expression: string | object) {\n const ensureStringExpression = create(expression, CronExpressionStruct);\n return parseExpression(ensureStringExpression);\n}\n\nexport const CronjobSpecificationStruct = object({\n expression: CronExpressionStruct,\n request: CronjobRpcRequestStruct,\n});\nexport type CronjobSpecification = Infer<typeof CronjobSpecificationStruct>;\n\n/**\n * Check if the given value is a {@link CronjobSpecification} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link CronjobSpecification} object.\n */\nexport function isCronjobSpecification(value: unknown): boolean {\n try {\n create(value, CronjobSpecificationStruct);\n return true;\n } catch {\n return false;\n }\n}\n\nexport const CronjobSpecificationArrayStruct = array(\n CronjobSpecificationStruct,\n);\n\n/**\n * Check if the given value is an array of {@link CronjobSpecification} objects.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid array of {@link CronjobSpecification} objects.\n */\nexport function isCronjobSpecificationArray(value: unknown): boolean {\n try {\n create(value, CronjobSpecificationArrayStruct);\n return true;\n } catch {\n return false;\n }\n}\n"],"names":["CronjobRpcRequestStruct","CronExpressionStruct","parseCronExpression","CronjobSpecificationStruct","isCronjobSpecification","CronjobSpecificationArrayStruct","isCronjobSpecificationArray","assign","partial","pick","JsonRpcRequestStruct","omit","refine","coerce","string","object","minute","optional","hour","dayOfMonth","month","dayOfWeek","value","parseExpression","expression","ensureStringExpression","create","request","array"],"mappings":";;;;;;;;;;;IAiBaA,uBAAuB;eAAvBA;;IAMAC,oBAAoB;eAApBA;;IAkCGC,mBAAmB;eAAnBA;;IAKHC,0BAA0B;eAA1BA;;IAYGC,sBAAsB;eAAtBA;;IASHC,+BAA+B;eAA/BA;;IAUGC,2BAA2B;eAA3BA;;;uBA7FqB;4BACL;6BAczB;AAEA,MAAMN,0BAA0BO,IAAAA,mBAAM,EAC3CC,IAAAA,oBAAO,EAACC,IAAAA,iBAAI,EAACC,2BAAoB,EAAE;IAAC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,EAAE,OAAM;QACN,OAAO;IACT;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/enum.ts"],"sourcesContent":["import type { Struct } from 'superstruct';\n\nimport { literal } from './structs';\n\n/**\n * Get the enum values as union type. This allows using both the enum string\n * values and the enum itself as values.\n *\n * Note: This only works for string enums.\n *\n * @example\n * ```typescript\n * enum Foo {\n * Bar = 'bar',\n * Baz = 'baz',\n * }\n *\n * type FooValue = EnumToUnion<Foo>;\n * // FooValue is 'bar' | 'baz'\n *\n * const foo: FooValue = Foo.Bar; // Works\n * const foo: FooValue = 'bar'; // Also works\n * ```\n */\nexport type EnumToUnion<Type extends string> = `${Type}`;\n\n/**\n * Superstruct struct for validating an enum value. This allows using both the\n * enum string values and the enum itself as values.\n *\n * @param constant - The enum to validate against.\n * @returns The superstruct struct.\n */\nexport function enumValue<Type extends string>(\n constant: Type,\n): Struct<EnumToUnion<Type>, null> {\n return literal(constant as EnumToUnion<Type>);\n}\n"],"names":["enumValue","constant","literal"],"mappings":";;;;+BAiCgBA;;;eAAAA;;;yBA/BQ;AA+BjB,SAASA,UACdC,QAAc;IAEd,OAAOC,IAAAA,gBAAO,EAACD;AACjB"}
1
+ {"version":3,"sources":["../../src/enum.ts"],"sourcesContent":["import type { EnumToUnion } from '@metamask/snaps-sdk';\nimport type { Struct } from 'superstruct';\n\nimport { literal } from './structs';\n\n/**\n * Superstruct struct for validating an enum value. This allows using both the\n * enum string values and the enum itself as values.\n *\n * @param constant - The enum to validate against.\n * @returns The superstruct struct.\n */\nexport function enumValue<Type extends string>(\n constant: Type,\n): Struct<EnumToUnion<Type>, null> {\n return literal(constant as EnumToUnion<Type>);\n}\n"],"names":["enumValue","constant","literal"],"mappings":";;;;+BAYgBA;;;eAAAA;;;yBATQ;AASjB,SAASA,UACdC,QAAc;IAEd,OAAOC,IAAAA,gBAAO,EAACD;AACjB"}
@@ -9,36 +9,15 @@ function _export(target, all) {
9
9
  });
10
10
  }
11
11
  _export(exports, {
12
- getErrorMessage: function() {
13
- return getErrorMessage;
14
- },
15
- getErrorStack: function() {
16
- return getErrorStack;
17
- },
18
- getErrorCode: function() {
19
- return getErrorCode;
20
- },
21
- getErrorData: function() {
22
- return getErrorData;
23
- },
24
12
  SNAP_ERROR_WRAPPER_CODE: function() {
25
13
  return SNAP_ERROR_WRAPPER_CODE;
26
14
  },
27
15
  SNAP_ERROR_WRAPPER_MESSAGE: function() {
28
16
  return SNAP_ERROR_WRAPPER_MESSAGE;
29
17
  },
30
- SNAP_ERROR_CODE: function() {
31
- return SNAP_ERROR_CODE;
32
- },
33
- SNAP_ERROR_MESSAGE: function() {
34
- return SNAP_ERROR_MESSAGE;
35
- },
36
18
  WrappedSnapError: function() {
37
19
  return WrappedSnapError;
38
20
  },
39
- SnapError: function() {
40
- return SnapError;
41
- },
42
21
  isSnapError: function() {
43
22
  return isSnapError;
44
23
  },
@@ -53,6 +32,7 @@ _export(exports, {
53
32
  }
54
33
  });
55
34
  const _rpcerrors = require("@metamask/rpc-errors");
35
+ const _snapssdk = require("@metamask/snaps-sdk");
56
36
  const _utils = require("@metamask/utils");
57
37
  function _check_private_redeclaration(obj, privateCollection) {
58
38
  if (privateCollection.has(obj)) {
@@ -94,34 +74,8 @@ function _class_private_field_set(receiver, privateMap, value) {
94
74
  _class_apply_descriptor_set(receiver, descriptor, value);
95
75
  return value;
96
76
  }
97
- function getErrorMessage(error) {
98
- if ((0, _utils.isObject)(error) && (0, _utils.hasProperty)(error, 'message') && typeof error.message === 'string') {
99
- return error.message;
100
- }
101
- return String(error);
102
- }
103
- function getErrorStack(error) {
104
- if ((0, _utils.isObject)(error) && (0, _utils.hasProperty)(error, 'stack') && typeof error.stack === 'string') {
105
- return error.stack;
106
- }
107
- return undefined;
108
- }
109
- function getErrorCode(error) {
110
- if ((0, _utils.isObject)(error) && (0, _utils.hasProperty)(error, 'code') && typeof error.code === 'number' && Number.isInteger(error.code)) {
111
- return error.code;
112
- }
113
- return _rpcerrors.errorCodes.rpc.internal;
114
- }
115
- function getErrorData(error) {
116
- if ((0, _utils.isObject)(error) && (0, _utils.hasProperty)(error, 'data') && typeof error.data === 'object' && error.data !== null && (0, _utils.isValidJson)(error.data) && !Array.isArray(error.data)) {
117
- return error.data;
118
- }
119
- return {};
120
- }
121
77
  const SNAP_ERROR_WRAPPER_CODE = -31001;
122
78
  const SNAP_ERROR_WRAPPER_MESSAGE = 'Wrapped Snap Error';
123
- const SNAP_ERROR_CODE = -31002;
124
- const SNAP_ERROR_MESSAGE = 'Snap Error';
125
79
  var _error = /*#__PURE__*/ new WeakMap(), _message = /*#__PURE__*/ new WeakMap(), _stack = /*#__PURE__*/ new WeakMap();
126
80
  class WrappedSnapError extends Error {
127
81
  /**
@@ -172,7 +126,7 @@ class WrappedSnapError extends Error {
172
126
  *
173
127
  * @param error - The error to create the `WrappedSnapError` from.
174
128
  */ constructor(error){
175
- const message = getErrorMessage(error);
129
+ const message = (0, _snapssdk.getErrorMessage)(error);
176
130
  super(message);
177
131
  _class_private_field_init(this, _error, {
178
132
  writable: true,
@@ -188,109 +142,7 @@ class WrappedSnapError extends Error {
188
142
  });
189
143
  _class_private_field_set(this, _error, error);
190
144
  _class_private_field_set(this, _message, message);
191
- _class_private_field_set(this, _stack, getErrorStack(error));
192
- }
193
- }
194
- var _code = /*#__PURE__*/ new WeakMap(), _message1 = /*#__PURE__*/ new WeakMap(), _data = /*#__PURE__*/ new WeakMap(), _stack1 = /*#__PURE__*/ new WeakMap();
195
- class SnapError extends Error {
196
- /**
197
- * The error name.
198
- *
199
- * @returns The error name.
200
- */ get name() {
201
- return 'SnapError';
202
- }
203
- /**
204
- * The error code.
205
- *
206
- * @returns The error code.
207
- */ get code() {
208
- return _class_private_field_get(this, _code);
209
- }
210
- /**
211
- * The error message.
212
- *
213
- * @returns The error message.
214
- */ get message() {
215
- return _class_private_field_get(this, _message1);
216
- }
217
- /**
218
- * Additional data for the error.
219
- *
220
- * @returns Additional data for the error.
221
- */ get data() {
222
- return _class_private_field_get(this, _data);
223
- }
224
- /**
225
- * The error stack.
226
- *
227
- * @returns The error stack.
228
- */ get stack() {
229
- return _class_private_field_get(this, _stack1);
230
- }
231
- /**
232
- * Convert the error to a JSON object.
233
- *
234
- * @returns The JSON object.
235
- */ toJSON() {
236
- return {
237
- code: SNAP_ERROR_CODE,
238
- message: SNAP_ERROR_MESSAGE,
239
- data: {
240
- cause: {
241
- code: this.code,
242
- message: this.message,
243
- stack: this.stack,
244
- data: this.data
245
- }
246
- }
247
- };
248
- }
249
- /**
250
- * Serialize the error to a JSON object. This is called by
251
- * `@metamask/rpc-errors` when serializing the error.
252
- *
253
- * @returns The JSON object.
254
- */ serialize() {
255
- return this.toJSON();
256
- }
257
- /**
258
- * Create a new `SnapError`.
259
- *
260
- * @param error - The error to create the `SnapError` from. If this is a
261
- * `string`, it will be used as the error message. If this is an `Error`, its
262
- * `message` property will be used as the error message. If this is a
263
- * `JsonRpcError`, its `message` property will be used as the error message
264
- * and its `code` property will be used as the error code. Otherwise, the
265
- * error will be converted to a string and used as the error message.
266
- * @param data - Additional data to include in the error. This will be merged
267
- * with the error data, if any.
268
- */ constructor(error, data = {}){
269
- const message = getErrorMessage(error);
270
- super(message);
271
- _class_private_field_init(this, _code, {
272
- writable: true,
273
- value: void 0
274
- });
275
- _class_private_field_init(this, _message1, {
276
- writable: true,
277
- value: void 0
278
- });
279
- _class_private_field_init(this, _data, {
280
- writable: true,
281
- value: void 0
282
- });
283
- _class_private_field_init(this, _stack1, {
284
- writable: true,
285
- value: void 0
286
- });
287
- _class_private_field_set(this, _message1, message);
288
- _class_private_field_set(this, _code, getErrorCode(error));
289
- _class_private_field_set(this, _data, {
290
- ...getErrorData(error),
291
- ...data
292
- });
293
- _class_private_field_set(this, _stack1, super.stack);
145
+ _class_private_field_set(this, _stack, (0, _snapssdk.getErrorStack)(error));
294
146
  }
295
147
  }
296
148
  function isSnapError(error) {
@@ -301,7 +153,7 @@ function isSnapError(error) {
301
153
  return false;
302
154
  }
303
155
  function isSerializedSnapError(error) {
304
- return error.code === SNAP_ERROR_CODE && error.message === SNAP_ERROR_MESSAGE;
156
+ return error.code === _snapssdk.SNAP_ERROR_CODE && error.message === _snapssdk.SNAP_ERROR_MESSAGE;
305
157
  }
306
158
  function isWrappedSnapError(error) {
307
159
  return (0, _utils.isJsonRpcError)(error) && error.code === SNAP_ERROR_WRAPPER_CODE && error.message === SNAP_ERROR_WRAPPER_MESSAGE;
@@ -345,7 +197,7 @@ function unwrapError(error) {
345
197
  // Otherwise, we throw an internal error with the wrapped error as the
346
198
  // message.
347
199
  return [
348
- getJsonRpcError(_rpcerrors.errorCodes.rpc.internal, getErrorMessage(error.data.cause), getErrorStack(error.data.cause)),
200
+ getJsonRpcError(_rpcerrors.errorCodes.rpc.internal, (0, _snapssdk.getErrorMessage)(error.data.cause), (0, _snapssdk.getErrorStack)(error.data.cause)),
349
201
  false
350
202
  ];
351
203
  }
@@ -361,7 +213,7 @@ function unwrapError(error) {
361
213
  // If the error is not a wrapped error, we don't know how to handle it, so we
362
214
  // throw an internal error with the error as the message.
363
215
  return [
364
- getJsonRpcError(_rpcerrors.errorCodes.rpc.internal, getErrorMessage(error), getErrorStack(error)),
216
+ getJsonRpcError(_rpcerrors.errorCodes.rpc.internal, (0, _snapssdk.getErrorMessage)(error), (0, _snapssdk.getErrorStack)(error)),
365
217
  false
366
218
  ];
367
219
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/errors.ts"],"sourcesContent":["import {\n errorCodes,\n JsonRpcError as RpcError,\n serializeCause,\n} from '@metamask/rpc-errors';\nimport type { DataWithOptionalCause } from '@metamask/rpc-errors';\nimport type { Json, JsonRpcError } from '@metamask/utils';\nimport {\n hasProperty,\n isJsonRpcError,\n isObject,\n isValidJson,\n} from '@metamask/utils';\n\n/**\n * Get the error message from an unknown error type.\n *\n * - If the error is an object with a `message` property, return the message.\n * - Otherwise, return the error converted to a string.\n *\n * @param error - The error to get the message from.\n * @returns The error message.\n */\nexport function getErrorMessage(error: unknown) {\n if (\n isObject(error) &&\n hasProperty(error, 'message') &&\n typeof error.message === 'string'\n ) {\n return error.message;\n }\n\n return String(error);\n}\n\n/**\n * Get the error stack from an unknown error type.\n *\n * @param error - The error to get the stack from.\n * @returns The error stack, or undefined if the error does not have a valid\n * stack.\n */\nexport function getErrorStack(error: unknown) {\n if (\n isObject(error) &&\n hasProperty(error, 'stack') &&\n typeof error.stack === 'string'\n ) {\n return error.stack;\n }\n\n return undefined;\n}\n\n/**\n * Get the error code from an unknown error type.\n *\n * @param error - The error to get the code from.\n * @returns The error code, or `-32603` if the error does not have a valid code.\n */\nexport function getErrorCode(error: unknown) {\n if (\n isObject(error) &&\n hasProperty(error, 'code') &&\n typeof error.code === 'number' &&\n Number.isInteger(error.code)\n ) {\n return error.code;\n }\n\n return errorCodes.rpc.internal;\n}\n\n/**\n * Get the error data from an unknown error type.\n *\n * @param error - The error to get the data from.\n * @returns The error data, or an empty object if the error does not have valid\n * data.\n */\nexport function getErrorData(error: unknown) {\n if (\n isObject(error) &&\n hasProperty(error, 'data') &&\n typeof error.data === 'object' &&\n error.data !== null &&\n isValidJson(error.data) &&\n !Array.isArray(error.data)\n ) {\n return error.data;\n }\n\n return {};\n}\n\nexport const SNAP_ERROR_WRAPPER_CODE = -31001;\nexport const SNAP_ERROR_WRAPPER_MESSAGE = 'Wrapped Snap Error';\n\nexport const SNAP_ERROR_CODE = -31002;\nexport const SNAP_ERROR_MESSAGE = '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 type SerializedSnapError = {\n code: typeof SNAP_ERROR_CODE;\n message: typeof SNAP_ERROR_MESSAGE;\n data: {\n cause: JsonRpcError & {\n data: Record<string, Json>;\n };\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);\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 * A generic error which can be thrown by a Snap, without it causing the Snap to\n * crash.\n */\nexport class SnapError extends Error {\n readonly #code: number;\n\n readonly #message: string;\n\n readonly #data: Record<string, Json>;\n\n readonly #stack?: string;\n\n /**\n * Create a new `SnapError`.\n *\n * @param error - The error to create the `SnapError` from. If this is a\n * `string`, it will be used as the error message. If this is an `Error`, its\n * `message` property will be used as the error message. If this is a\n * `JsonRpcError`, its `message` property will be used as the error message\n * and its `code` property will be used as the error code. Otherwise, the\n * error will be converted to a string and used as the error message.\n * @param data - Additional data to include in the error. This will be merged\n * with the error data, if any.\n */\n constructor(\n error: string | Error | JsonRpcError,\n data: Record<string, Json> = {},\n ) {\n const message = getErrorMessage(error);\n super(message);\n\n this.#message = message;\n this.#code = getErrorCode(error);\n this.#data = { ...getErrorData(error), ...data };\n this.#stack = super.stack;\n }\n\n /**\n * The error name.\n *\n * @returns The error name.\n */\n get name() {\n return 'SnapError';\n }\n\n /**\n * The error code.\n *\n * @returns The error code.\n */\n get code() {\n return this.#code;\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 * Additional data for the error.\n *\n * @returns Additional data for the error.\n */\n get data() {\n return this.#data;\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(): SerializedSnapError {\n return {\n code: SNAP_ERROR_CODE,\n message: SNAP_ERROR_MESSAGE,\n data: {\n cause: {\n code: this.code,\n message: this.message,\n stack: this.stack,\n data: this.data,\n },\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,\n data?: Json,\n) {\n const error = new RpcError(code, message, data);\n error.stack = stack;\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 // 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"],"names":["getErrorMessage","getErrorStack","getErrorCode","getErrorData","SNAP_ERROR_WRAPPER_CODE","SNAP_ERROR_WRAPPER_MESSAGE","SNAP_ERROR_CODE","SNAP_ERROR_MESSAGE","WrappedSnapError","SnapError","isSnapError","isSerializedSnapError","isWrappedSnapError","unwrapError","error","isObject","hasProperty","message","String","stack","undefined","code","Number","isInteger","errorCodes","rpc","internal","data","isValidJson","Array","isArray","Error","name","toJSON","cause","serialize","serializeCause","constructor","serialized","isJsonRpcError","getJsonRpcError","RpcError"],"mappings":";;;;;;;;;;;IAuBgBA,eAAe;eAAfA;;IAmBAC,aAAa;eAAbA;;IAkBAC,YAAY;eAAZA;;IAoBAC,YAAY;eAAZA;;IAeHC,uBAAuB;eAAvBA;;IACAC,0BAA0B;eAA1BA;;IAEAC,eAAe;eAAfA;;IACAC,kBAAkB;eAAlBA;;IAoBAC,gBAAgB;eAAhBA;;IAkFAC,SAAS;eAATA;;IAoHGC,WAAW;eAAXA;;IAmBAC,qBAAqB;eAArBA;;IAYAC,kBAAkB;eAAlBA;;IAwCAC,WAAW;eAAXA;;;2BAhYT;uBAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,SAASb,gBAAgBc,KAAc;IAC5C,IACEC,IAAAA,eAAQ,EAACD,UACTE,IAAAA,kBAAW,EAACF,OAAO,cACnB,OAAOA,MAAMG,OAAO,KAAK,UACzB;QACA,OAAOH,MAAMG,OAAO;IACtB;IAEA,OAAOC,OAAOJ;AAChB;AASO,SAASb,cAAca,KAAc;IAC1C,IACEC,IAAAA,eAAQ,EAACD,UACTE,IAAAA,kBAAW,EAACF,OAAO,YACnB,OAAOA,MAAMK,KAAK,KAAK,UACvB;QACA,OAAOL,MAAMK,KAAK;IACpB;IAEA,OAAOC;AACT;AAQO,SAASlB,aAAaY,KAAc;IACzC,IACEC,IAAAA,eAAQ,EAACD,UACTE,IAAAA,kBAAW,EAACF,OAAO,WACnB,OAAOA,MAAMO,IAAI,KAAK,YACtBC,OAA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;YACLa,gBACEhB,qBAAU,CAACC,GAAG,CAACC,QAAQ,EACvB1B,gBAAgBc,MAAMa,IAAI,CAACO,KAAK,GAChCjC,cAAca,MAAMa,IAAI,CAACO,KAAK;YAEhC;SACD;IACH;IAEA,2EAA2E;IAC3E,qDAAqD;IACrD,IAAIK,IAAAA,qBAAc,EAACzB,QAAQ;QACzB,MAAM,EAAEO,IAAI,EAAEJ,OAAO,EAAEE,KAAK,EAAEQ,IAAI,EAAE,GAAGb;QACvC,OAAO;YAAC0B,gBAAgBnB,MAAMJ,SAASE,OAAOQ;YAAO;SAAM;IAC7D;IAEA,6EAA6E;IAC7E,yDAAyD;IACzD,OAAO;QACLa,gBACEhB,qBAAU,CAACC,GAAG,CAACC,QAAQ,EACvB1B,gBAAgBc,QAChBb,cAAca;QAEhB;KACD;AACH"}
1
+ {"version":3,"sources":["../../src/errors.ts"],"sourcesContent":["import {\n errorCodes,\n JsonRpcError as RpcError,\n serializeCause,\n} from '@metamask/rpc-errors';\nimport type { DataWithOptionalCause } from '@metamask/rpc-errors';\nimport type { SerializedSnapError, SnapError } from '@metamask/snaps-sdk';\nimport {\n getErrorMessage,\n getErrorStack,\n SNAP_ERROR_CODE,\n SNAP_ERROR_MESSAGE,\n} from '@metamask/snaps-sdk';\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);\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,\n data?: Json,\n) {\n const error = new RpcError(code, message, data);\n error.stack = stack;\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 // 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"],"names":["SNAP_ERROR_WRAPPER_CODE","SNAP_ERROR_WRAPPER_MESSAGE","WrappedSnapError","isSnapError","isSerializedSnapError","isWrappedSnapError","unwrapError","Error","name","message","stack","toJSON","cause","error","serialize","serializeCause","code","data","constructor","getErrorMessage","getErrorStack","isObject","serialized","isJsonRpcError","SNAP_ERROR_CODE","SNAP_ERROR_MESSAGE","getJsonRpcError","RpcError","errorCodes","rpc","internal"],"mappings":";;;;;;;;;;;IAgBaA,uBAAuB;eAAvBA;;IACAC,0BAA0B;eAA1BA;;IAUAC,gBAAgB;eAAhBA;;IAoFGC,WAAW;eAAXA;;IAmBAC,qBAAqB;eAArBA;;IAYAC,kBAAkB;eAAlBA;;IAwCAC,WAAW;eAAXA;;;2BAlLT;0BAQA;uBAEkC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAElC,MAAMN,0BAA0B,CAAC;AACjC,MAAMC,6BAA6B;IAW/B,sCAEA,wCAEA;AALJ,MAAMC,yBAAyBK;IAqBpC;;;;GAIC,GACD,IAAIC,OAAO;QACT,OAAO;IACT;IAEA;;;;GAIC,GACD,IAAIC,UAAU;QACZ,gCAAO,IAAI,EAAEA;IACf;IAEA;;;;GAIC,GACD,IAAIC,QAAQ;QACV,gCAAO,IAAI,EAAEA;IACf;IAEA;;;;GAIC,GACDC,SAAqC;QACnC,MAAMC,QAAQT,qCAAY,IAAI,EAAEU,WAC5B,yBAAA,IAAI,EAAEA,QAAMC,SAAS,KACrBC,IAAAA,yBAAc,2BAAC,IAAI,EAAEF;QAEzB,OAAO;YACLG,MAAMhB;YACNS,SAASR;YACTgB,MAAM;gBACJL;YACF;QACF;IACF;IAEA;;;;;GAKC,GACDE,YAAY;QACV,OAAO,IAAI,CAACH,MAAM;IACpB;IApEA;;;;GAIC,GACDO,YAAYL,KAAc,CAAE;QAC1B,MAAMJ,UAAUU,IAAAA,yBAAe,EAACN;QAChC,KAAK,CAACJ;QAbR,gCAAS;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MP,SAASC,OAAOO;oBAAO;iBAAK;YAC5D;YAEA,iDAAiD;YACjD,MAAM,EAAED,IAAI,EAAEP,OAAO,EAAEC,KAAK,EAAEO,IAAI,EAAE,GAAGJ,MAAMI,IAAI,CAACL,KAAK;YACvD,OAAO;gBAACc,gBAAgBV,MAAMP,SAASC,OAAOO;gBAAO;aAAM;QAC7D;QAEA,sEAAsE;QACtE,WAAW;QACX,OAAO;YACLS,gBACEE,qBAAU,CAACC,GAAG,CAACC,QAAQ,EACvBX,IAAAA,yBAAe,EAACN,MAAMI,IAAI,CAACL,KAAK,GAChCQ,IAAAA,uBAAa,EAACP,MAAMI,IAAI,CAACL,KAAK;YAEhC;SACD;IACH;IAEA,2EAA2E;IAC3E,qDAAqD;IACrD,IAAIW,IAAAA,qBAAc,EAACV,QAAQ;QACzB,MAAM,EAAEG,IAAI,EAAEP,OAAO,EAAEC,KAAK,EAAEO,IAAI,EAAE,GAAGJ;QACvC,OAAO;YAACa,gBAAgBV,MAAMP,SAASC,OAAOO;YAAO;SAAM;IAC7D;IAEA,6EAA6E;IAC7E,yDAAyD;IACzD,OAAO;QACLS,gBACEE,qBAAU,CAACC,GAAG,CAACC,QAAQ,EACvBX,IAAAA,yBAAe,EAACN,QAChBO,IAAAA,uBAAa,EAACP;QAEhB;KACD;AACH"}
@@ -9,9 +9,6 @@ function _export(target, all) {
9
9
  });
10
10
  }
11
11
  _export(exports, {
12
- SeverityLevel: function() {
13
- return SeverityLevel;
14
- },
15
12
  SNAP_EXPORTS: function() {
16
13
  return SNAP_EXPORTS;
17
14
  },
@@ -22,7 +19,7 @@ _export(exports, {
22
19
  return OnHomePageResponseStruct;
23
20
  }
24
21
  });
25
- const _snapsui = require("@metamask/snaps-ui");
22
+ const _snapssdk = require("@metamask/snaps-sdk");
26
23
  const _superstruct = require("superstruct");
27
24
  const _handlertypes = require("./handler-types");
28
25
  const SNAP_EXPORTS = {
@@ -83,16 +80,12 @@ const SNAP_EXPORTS = {
83
80
  }
84
81
  }
85
82
  };
86
- var SeverityLevel;
87
- (function(SeverityLevel) {
88
- SeverityLevel["Critical"] = 'critical';
89
- })(SeverityLevel || (SeverityLevel = {}));
90
- const OnTransactionResponseStruct = (0, _superstruct.object)({
91
- content: _snapsui.ComponentStruct,
92
- severity: (0, _superstruct.optional)((0, _superstruct.literal)(SeverityLevel.Critical))
93
- });
83
+ const OnTransactionResponseStruct = (0, _superstruct.nullable)((0, _superstruct.object)({
84
+ content: _snapssdk.ComponentStruct,
85
+ severity: (0, _superstruct.optional)((0, _superstruct.literal)(_snapssdk.SeverityLevel.Critical))
86
+ }));
94
87
  const OnHomePageResponseStruct = (0, _superstruct.object)({
95
- content: _snapsui.ComponentStruct
88
+ content: _snapssdk.ComponentStruct
96
89
  });
97
90
 
98
91
  //# sourceMappingURL=handlers.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/handlers.ts"],"sourcesContent":["import { ComponentStruct } from '@metamask/snaps-ui';\nimport type { Json, JsonRpcParams, JsonRpcRequest } from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport { literal, object, optional } from 'superstruct';\n\nimport type { SnapHandler } from './handler-types';\nimport { HandlerType } from './handler-types';\nimport type { AccountAddress, Caip2ChainId } from './namespace';\n\nexport type SnapRpcHookArgs = {\n origin: string;\n handler: HandlerType;\n request: Record<string, unknown>;\n};\n\nexport const SNAP_EXPORTS = {\n [HandlerType.OnRpcRequest]: {\n type: HandlerType.OnRpcRequest,\n required: true,\n validator: (snapExport: unknown): snapExport is OnRpcRequestHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnTransaction]: {\n type: HandlerType.OnTransaction,\n required: true,\n validator: (snapExport: unknown): snapExport is OnTransactionHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnCronjob]: {\n type: HandlerType.OnCronjob,\n required: true,\n validator: (snapExport: unknown): snapExport is OnCronjobHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnNameLookup]: {\n type: HandlerType.OnNameLookup,\n required: true,\n validator: (snapExport: unknown): snapExport is OnNameLookupHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnInstall]: {\n type: HandlerType.OnInstall,\n required: false,\n validator: (snapExport: unknown): snapExport is OnInstallHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnUpdate]: {\n type: HandlerType.OnUpdate,\n required: false,\n validator: (snapExport: unknown): snapExport is OnUpdateHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnKeyringRequest]: {\n type: HandlerType.OnKeyringRequest,\n required: true,\n validator: (snapExport: unknown): snapExport is OnKeyringRequestHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnHomePage]: {\n type: HandlerType.OnHomePage,\n required: true,\n validator: (snapExport: unknown): snapExport is OnHomePageHandler => {\n return typeof snapExport === 'function';\n },\n },\n} as const;\n\n/**\n * The `onRpcRequest` handler. This is called whenever a JSON-RPC request is\n * made to the snap.\n *\n * @param args - The request arguments.\n * @param args.origin - The origin of the request. This can be the ID of another\n * snap, or the URL of a dapp.\n * @param args.request - The JSON-RPC request sent to the snap.\n * @returns The JSON-RPC response. This must be a JSON-serializable value.\n */\nexport type OnRpcRequestHandler<Params extends JsonRpcParams = JsonRpcParams> =\n (args: {\n origin: string;\n request: JsonRpcRequest<Params>;\n }) => Promise<unknown>;\n\n/**\n * Enum used to specify the severity level of content being returned from a transaction insight.\n */\nexport enum SeverityLevel {\n Critical = 'critical',\n}\n\nexport const OnTransactionResponseStruct = object({\n content: ComponentStruct,\n severity: optional(literal(SeverityLevel.Critical)),\n});\n\n/**\n * The response from a snap's `onTransaction` handler.\n *\n * @property content - A custom UI component, that will be shown in MetaMask. Can be created using `@metamask/snaps-ui`.\n *\n * If the snap has no insights about the transaction, this should be `null`.\n */\nexport type OnTransactionResponse = Infer<typeof OnTransactionResponseStruct>;\n\n/**\n * The `onTransaction` handler. This is called whenever a transaction is\n * submitted to the snap. It can return insights about the transaction, which\n * will be displayed to the user.\n *\n * @param args - The request arguments.\n * @param args.transaction - The transaction object.\n * @param args.chainId - The CAIP-2 chain ID of the network the transaction is\n * being submitted to.\n * @param args.transactionOrigin - The origin of the transaction. This is the\n * URL of the dapp that submitted the transaction.\n * @returns Insights about the transaction. See {@link OnTransactionResponse}.\n */\n// TODO: Improve type.\nexport type OnTransactionHandler = (args: {\n transaction: { [key: string]: Json };\n chainId: string;\n transactionOrigin?: string;\n}) => Promise<OnTransactionResponse>;\n\n/**\n * The `onCronjob` handler. This is called on a regular interval, as defined by\n * the snap's manifest.\n *\n * @param args - The request arguments.\n * @param args.request - The JSON-RPC request sent to the snap.\n */\nexport type OnCronjobHandler<Params extends JsonRpcParams = JsonRpcParams> =\n (args: { request: JsonRpcRequest<Params> }) => Promise<unknown>;\n\n/**\n * A handler that can be used for the lifecycle hooks.\n */\nexport type LifecycleEventHandler = (args: {\n request: JsonRpcRequest;\n}) => Promise<unknown>;\n\n/**\n * The `onInstall` handler. This is called after the snap is installed.\n *\n * This type is an alias for {@link LifecycleEventHandler}.\n */\nexport type OnInstallHandler = LifecycleEventHandler;\n\n/**\n * The `onUpdate` handler. This is called after the snap is updated.\n *\n * This type is an alias for {@link LifecycleEventHandler}.\n */\nexport type OnUpdateHandler = LifecycleEventHandler;\n\n/**\n * The `onKeyringRequest` handler. This is called by the MetaMask client for\n * privileged keyring actions.\n *\n * @param args - The request arguments.\n * @param args.origin - The origin of the request. This can be the ID of\n * another snap, or the URL of a dapp.\n * @param args.request - The JSON-RPC request sent to the snap.\n */\nexport type OnKeyringRequestHandler<\n Params extends JsonRpcParams = JsonRpcParams,\n> = (args: {\n origin: string;\n request: JsonRpcRequest<Params>;\n}) => Promise<unknown>;\n\nexport type OnHomePageHandler = () => Promise<OnHomePageResponse>;\n\nexport const OnHomePageResponseStruct = object({\n content: ComponentStruct,\n});\n\nexport type OnHomePageResponse = Infer<typeof OnHomePageResponseStruct>;\n\n/**\n * Utility type for getting the handler function type from a handler type.\n */\nexport type HandlerFunction<Type extends SnapHandler> =\n Type['validator'] extends (snapExport: unknown) => snapExport is infer Handler\n ? Handler\n : never;\n\n/**\n * The response from a snap's `onNameLookup` handler.\n *\n * @property resolvedAddress - The resolved address for a given domain.\n * @property resolvedDomain - The resolved domain for a given address.\n *\n *\n * If the snap has no resolved address/domain from its lookup, this should be `null`.\n */\nexport type OnNameLookupResponse =\n | {\n resolvedAddress: AccountAddress;\n resolvedDomain?: never;\n }\n | { resolvedDomain: string; resolvedAddress?: never }\n | null;\n\nexport type OnNameLookupArgs = {\n chainId: Caip2ChainId;\n} & ({ domain: string; address?: never } | { address: string; domain?: never });\n\n/**\n * The `onNameLookup` handler. This is called whenever content is entered\n * into the send to field for sending assets to an EOA address.\n *\n * @param args - The request arguments.\n * @param args.domain - The human-readable address that is to be resolved.\n * @param args.chainId - The CAIP-2 chain ID of the network the transaction is\n * being submitted to.\n * @param args.address - The address that is to be resolved.\n * @returns Resolved address/domain from the lookup. See {@link OnNameLookupResponse}.\n */\nexport type OnNameLookupHandler = (\n args: OnNameLookupArgs,\n) => Promise<OnNameLookupResponse>;\n\n/**\n * All the function-based handlers that a snap can implement.\n */\nexport type SnapFunctionExports = {\n [Key in keyof typeof SNAP_EXPORTS]?: HandlerFunction<\n (typeof SNAP_EXPORTS)[Key]\n >;\n};\n\n/**\n * All handlers that a snap can implement.\n */\nexport type SnapExports = SnapFunctionExports;\n"],"names":["SNAP_EXPORTS","OnTransactionResponseStruct","OnHomePageResponseStruct","HandlerType","OnRpcRequest","type","required","validator","snapExport","OnTransaction","OnCronjob","OnNameLookup","OnInstall","OnUpdate","OnKeyringRequest","OnHomePage","SeverityLevel","Critical","object","content","ComponentStruct","severity","optional","literal"],"mappings":";;;;;;;;;;;;;;IAeaA,YAAY;eAAZA;;IAkFAC,2BAA2B;eAA3BA;;IAmFAC,wBAAwB;eAAxBA;;;yBApLmB;6BAGU;8BAGd;AASrB,MAAMF,eAAe;IAC1B,CAACG,yBAAW,CAACC,YAAY,CAA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AM,EAAC;IAChDC,SAASC,wBAAe;IACxBC,UAAUC,IAAAA,qBAAQ,EAACC,IAAAA,oBAAO,EAACP,cAAcC,QAAQ;AACnD;AAgFO,MAAMf,2BAA2BgB,IAAAA,mBAAM,EAAC;IAC7CC,SAASC,wBAAe;AAC1B"}
1
+ {"version":3,"sources":["../../src/handlers.ts"],"sourcesContent":["import type {\n OnCronjobHandler,\n OnHomePageHandler,\n OnInstallHandler,\n OnKeyringRequestHandler,\n OnNameLookupHandler,\n OnRpcRequestHandler,\n OnTransactionHandler,\n OnUpdateHandler,\n} from '@metamask/snaps-sdk';\nimport { SeverityLevel, ComponentStruct } from '@metamask/snaps-sdk';\nimport { literal, nullable, object, optional } from 'superstruct';\n\nimport type { SnapHandler } from './handler-types';\nimport { HandlerType } from './handler-types';\n\nexport type SnapRpcHookArgs = {\n origin: string;\n handler: HandlerType;\n request: Record<string, unknown>;\n};\n\nexport const SNAP_EXPORTS = {\n [HandlerType.OnRpcRequest]: {\n type: HandlerType.OnRpcRequest,\n required: true,\n validator: (snapExport: unknown): snapExport is OnRpcRequestHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnTransaction]: {\n type: HandlerType.OnTransaction,\n required: true,\n validator: (snapExport: unknown): snapExport is OnTransactionHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnCronjob]: {\n type: HandlerType.OnCronjob,\n required: true,\n validator: (snapExport: unknown): snapExport is OnCronjobHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnNameLookup]: {\n type: HandlerType.OnNameLookup,\n required: true,\n validator: (snapExport: unknown): snapExport is OnNameLookupHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnInstall]: {\n type: HandlerType.OnInstall,\n required: false,\n validator: (snapExport: unknown): snapExport is OnInstallHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnUpdate]: {\n type: HandlerType.OnUpdate,\n required: false,\n validator: (snapExport: unknown): snapExport is OnUpdateHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnKeyringRequest]: {\n type: HandlerType.OnKeyringRequest,\n required: true,\n validator: (snapExport: unknown): snapExport is OnKeyringRequestHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnHomePage]: {\n type: HandlerType.OnHomePage,\n required: true,\n validator: (snapExport: unknown): snapExport is OnHomePageHandler => {\n return typeof snapExport === 'function';\n },\n },\n} as const;\n\nexport const OnTransactionResponseStruct = nullable(\n object({\n content: ComponentStruct,\n severity: optional(literal(SeverityLevel.Critical)),\n }),\n);\n\nexport const OnHomePageResponseStruct = object({\n content: ComponentStruct,\n});\n\n/**\n * Utility type for getting the handler function type from a handler type.\n */\nexport type HandlerFunction<Type extends SnapHandler> =\n Type['validator'] extends (snapExport: unknown) => snapExport is infer Handler\n ? Handler\n : never;\n\n/**\n * All the function-based handlers that a snap can implement.\n */\nexport type SnapFunctionExports = {\n [Key in keyof typeof SNAP_EXPORTS]?: HandlerFunction<\n (typeof SNAP_EXPORTS)[Key]\n >;\n};\n\n/**\n * All handlers that a snap can implement.\n */\nexport type SnapExports = SnapFunctionExports;\n"],"names":["SNAP_EXPORTS","OnTransactionResponseStruct","OnHomePageResponseStruct","HandlerType","OnRpcRequest","type","required","validator","snapExport","OnTransaction","OnCronjob","OnNameLookup","OnInstall","OnUpdate","OnKeyringRequest","OnHomePage","nullable","object","content","ComponentStruct","severity","optional","literal","SeverityLevel","Critical"],"mappings":";;;;;;;;;;;IAsBaA,YAAY;eAAZA;;IA2DAC,2BAA2B;eAA3BA;;IAOAC,wBAAwB;eAAxBA;;;0BA9EkC;6BACK;8BAGxB;AAQrB,MAAMF,eAAe;IAC1B,CAACG,yBAAW,CAACC,YAAY,CAAC,EAAE;QAC1BC,MAAMF,yBAAW,CAACC,YAAY;QAC9BE,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACM,aAAa,CAAC,EAAE;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@@ -26,6 +26,7 @@ _export_star(require("./snaps"), exports);
26
26
  _export_star(require("./strings"), exports);
27
27
  _export_star(require("./structs"), exports);
28
28
  _export_star(require("./types"), exports);
29
+ _export_star(require("./ui"), exports);
29
30
  _export_star(require("./validation"), exports);
30
31
  _export_star(require("./versions"), exports);
31
32
  _export_star(require("./virtual-file/index.browser"), exports);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.browser.ts"],"sourcesContent":["export * from './array';\nexport * from './auxiliary-files';\nexport * from './caveats';\nexport * from './checksum';\nexport * from './cronjob';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './errors';\nexport * from './handlers';\nexport * from './handler-types';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './localization';\nexport * from './logging';\nexport * from './manifest/index.browser';\nexport * from './namespace';\nexport * from './path';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file/index.browser';\n"],"names":[],"mappings":";;;;qBAAc;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA"}
1
+ {"version":3,"sources":["../../src/index.browser.ts"],"sourcesContent":["export * from './array';\nexport * from './auxiliary-files';\nexport * from './caveats';\nexport * from './checksum';\nexport * from './cronjob';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './errors';\nexport * from './handlers';\nexport * from './handler-types';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './localization';\nexport * from './logging';\nexport * from './manifest/index.browser';\nexport * from './namespace';\nexport * from './path';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './ui';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file/index.browser';\n"],"names":[],"mappings":";;;;qBAAc;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA"}
package/dist/cjs/index.js CHANGED
@@ -31,6 +31,7 @@ _export_star(require("./snaps"), exports);
31
31
  _export_star(require("./strings"), exports);
32
32
  _export_star(require("./structs"), exports);
33
33
  _export_star(require("./types"), exports);
34
+ _export_star(require("./ui"), exports);
34
35
  _export_star(require("./validation"), exports);
35
36
  _export_star(require("./versions"), exports);
36
37
  _export_star(require("./virtual-file"), exports);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export * from './array';\nexport * from './auxiliary-files';\nexport * from './caveats';\nexport * from './cronjob';\nexport * from './checksum';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './eval';\nexport * from './errors';\nexport * from './fs';\nexport * from './handlers';\nexport * from './handler-types';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './localization';\nexport * from './logging';\nexport * from './manifest';\nexport * from './mock';\nexport * from './namespace';\nexport * from './npm';\nexport * from './path';\nexport * from './post-process';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file';\n"],"names":[],"mappings":";;;;qBAAc;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA"}
1
+ {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export * from './array';\nexport * from './auxiliary-files';\nexport * from './caveats';\nexport * from './cronjob';\nexport * from './checksum';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './eval';\nexport * from './errors';\nexport * from './fs';\nexport * from './handlers';\nexport * from './handler-types';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './localization';\nexport * from './logging';\nexport * from './manifest';\nexport * from './mock';\nexport * from './namespace';\nexport * from './npm';\nexport * from './path';\nexport * from './post-process';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './ui';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file';\n"],"names":[],"mappings":";;;;qBAAc;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA"}
@@ -34,8 +34,8 @@ _export(exports, {
34
34
  return validateSnapManifestLocalizations;
35
35
  }
36
36
  });
37
+ const _snapssdk = require("@metamask/snaps-sdk");
37
38
  const _superstruct = require("superstruct");
38
- const _errors = require("./errors");
39
39
  const _json = require("./json");
40
40
  const LOCALIZABLE_FIELDS = [
41
41
  'description',
@@ -106,7 +106,7 @@ function validateSnapManifestLocalizations(snapManifest, localizationFiles) {
106
106
  // The manifest must be localizable in English.
107
107
  getLocalizedSnapManifest(snapManifest, 'en', localizationFiles);
108
108
  } catch (error) {
109
- throw new Error(`Failed to localize Snap manifest: ${(0, _errors.getErrorMessage)(error)}`);
109
+ throw new Error(`Failed to localize Snap manifest: ${(0, _snapssdk.getErrorMessage)(error)}`);
110
110
  }
111
111
  }
112
112