@metamask/snaps-utils 7.4.1 → 7.5.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 (57) hide show
  1. package/CHANGELOG.md +11 -1
  2. package/dist/{chunk-CQRPSEH3.js → chunk-37VHIRUJ.js} +27 -4
  3. package/dist/chunk-37VHIRUJ.js.map +1 -0
  4. package/dist/{chunk-QNPXK3B3.mjs → chunk-4I22UHIU.mjs} +3 -3
  5. package/dist/{chunk-MJGSG5N2.mjs → chunk-BZ7BMGXN.mjs} +20 -5
  6. package/dist/chunk-BZ7BMGXN.mjs.map +1 -0
  7. package/dist/{chunk-4YAWNZXM.js → chunk-IHHQU6IS.js} +20 -5
  8. package/dist/chunk-IHHQU6IS.js.map +1 -0
  9. package/dist/{chunk-DKDGMZFU.mjs → chunk-K2OTEZZZ.mjs} +27 -4
  10. package/dist/chunk-K2OTEZZZ.mjs.map +1 -0
  11. package/dist/{chunk-HVTYDKBO.js → chunk-K4B37F3L.js} +1 -1
  12. package/dist/chunk-K4B37F3L.js.map +1 -0
  13. package/dist/{chunk-IAHW6IFC.js → chunk-LNZLPDBB.js} +6 -6
  14. package/dist/{chunk-UCRFECSX.mjs → chunk-R6VG7F6Y.mjs} +3 -3
  15. package/dist/{chunk-N4KSSDO5.js → chunk-SWU464Y6.js} +11 -11
  16. package/dist/{chunk-RLA43SHY.mjs → chunk-VXLHHSAP.mjs} +3 -3
  17. package/dist/{chunk-3ZSYZX3I.js → chunk-YC2LIIR4.js} +5 -5
  18. package/dist/{chunk-2M6G46W6.mjs → chunk-YCIPY3UP.mjs} +1 -1
  19. package/dist/chunk-YCIPY3UP.mjs.map +1 -0
  20. package/dist/index.js +6 -6
  21. package/dist/index.mjs +5 -5
  22. package/dist/json-rpc.js +2 -2
  23. package/dist/json-rpc.mjs +1 -1
  24. package/dist/manifest/index.js +4 -4
  25. package/dist/manifest/index.mjs +3 -3
  26. package/dist/manifest/manifest.js +5 -5
  27. package/dist/manifest/manifest.mjs +4 -4
  28. package/dist/manifest/node.js +5 -5
  29. package/dist/manifest/node.mjs +4 -4
  30. package/dist/manifest/validation.js +4 -4
  31. package/dist/manifest/validation.mjs +3 -3
  32. package/dist/node.js +7 -7
  33. package/dist/node.mjs +6 -6
  34. package/dist/npm.js +5 -5
  35. package/dist/npm.mjs +4 -4
  36. package/dist/snaps.js +2 -2
  37. package/dist/snaps.mjs +1 -1
  38. package/dist/tsconfig.build.tsbuildinfo +1 -1
  39. package/dist/types/snaps.d.ts +4 -0
  40. package/dist/types/ui.d.ts +2 -1
  41. package/dist/ui.js +2 -2
  42. package/dist/ui.mjs +1 -1
  43. package/dist/validation.js +5 -5
  44. package/dist/validation.mjs +4 -4
  45. package/package.json +2 -2
  46. package/dist/chunk-2M6G46W6.mjs.map +0 -1
  47. package/dist/chunk-4YAWNZXM.js.map +0 -1
  48. package/dist/chunk-CQRPSEH3.js.map +0 -1
  49. package/dist/chunk-DKDGMZFU.mjs.map +0 -1
  50. package/dist/chunk-HVTYDKBO.js.map +0 -1
  51. package/dist/chunk-MJGSG5N2.mjs.map +0 -1
  52. /package/dist/{chunk-QNPXK3B3.mjs.map → chunk-4I22UHIU.mjs.map} +0 -0
  53. /package/dist/{chunk-IAHW6IFC.js.map → chunk-LNZLPDBB.js.map} +0 -0
  54. /package/dist/{chunk-UCRFECSX.mjs.map → chunk-R6VG7F6Y.mjs.map} +0 -0
  55. /package/dist/{chunk-N4KSSDO5.js.map → chunk-SWU464Y6.js.map} +0 -0
  56. /package/dist/{chunk-RLA43SHY.mjs.map → chunk-VXLHHSAP.mjs.map} +0 -0
  57. /package/dist/{chunk-3ZSYZX3I.js.map → chunk-YC2LIIR4.js.map} +0 -0
package/CHANGELOG.md CHANGED
@@ -6,6 +6,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [7.5.0]
10
+ ### Added
11
+ - Allow wildcards in `allowedOrigins` ([#2458](https://github.com/MetaMask/snaps/pull/2458))
12
+ - Add `hidden` flag for preinstalled Snaps ([#2463](https://github.com/MetaMask/snaps/pull/2463))
13
+
14
+ ### Fixed
15
+ - Require at least 1 child in JSX components ([#2466](https://github.com/MetaMask/snaps/pull/2466))
16
+
9
17
  ## [7.4.1]
10
18
  ### Fixed
11
19
  - Fix invalid `@metamask/snaps-sdk` imports ([#2452](https://github.com/MetaMask/snaps/pull/2452))
@@ -15,6 +23,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
15
23
  - Add support for BIP-32-Ed25519 / CIP-3 key derivation ([#2408](https://github.com/MetaMask/snaps/pull/2408))
16
24
 
17
25
  ## Fixed
26
+
18
27
  - Fix build producing invalid JSX types ([#2410](https://github.com/MetaMask/snaps/pull/2410))
19
28
 
20
29
  ## [7.3.0]
@@ -236,7 +245,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
236
245
  - The version of the package no longer needs to match the version of all other
237
246
  MetaMask Snaps packages.
238
247
 
239
- [Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@7.4.1...HEAD
248
+ [Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@7.5.0...HEAD
249
+ [7.5.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@7.4.1...@metamask/snaps-utils@7.5.0
240
250
  [7.4.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@7.4.0...@metamask/snaps-utils@7.4.1
241
251
  [7.4.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@7.3.0...@metamask/snaps-utils@7.4.0
242
252
  [7.3.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@7.2.0...@metamask/snaps-utils@7.3.0
@@ -6,11 +6,20 @@ var _permissioncontroller = require('@metamask/permission-controller');
6
6
 
7
7
  var _utils = require('@metamask/utils');
8
8
  var _superstruct = require('superstruct');
9
+ var AllowedOriginsStruct = _superstruct.array.call(void 0,
10
+ _superstruct.refine.call(void 0, _superstruct.string.call(void 0, ), "Allowed origin", (value) => {
11
+ const wildcards = value.split("*").length - 1;
12
+ if (wildcards > 2) {
13
+ return 'No more than two wildcards ("*") are allowed in an origin specifier.';
14
+ }
15
+ return true;
16
+ })
17
+ );
9
18
  var RpcOriginsStruct = _superstruct.refine.call(void 0,
10
19
  _superstruct.object.call(void 0, {
11
20
  dapps: _superstruct.optional.call(void 0, _superstruct.boolean.call(void 0, )),
12
21
  snaps: _superstruct.optional.call(void 0, _superstruct.boolean.call(void 0, )),
13
- allowedOrigins: _superstruct.optional.call(void 0, _superstruct.array.call(void 0, _superstruct.string.call(void 0, )))
22
+ allowedOrigins: _superstruct.optional.call(void 0, AllowedOriginsStruct)
14
23
  }),
15
24
  "RPC origins",
16
25
  (value) => {
@@ -32,7 +41,7 @@ function assertIsRpcOrigins(value, ErrorWrapper) {
32
41
  );
33
42
  }
34
43
  var KeyringOriginsStruct = _superstruct.object.call(void 0, {
35
- allowedOrigins: _superstruct.optional.call(void 0, _superstruct.array.call(void 0, _superstruct.string.call(void 0, )))
44
+ allowedOrigins: _superstruct.optional.call(void 0, AllowedOriginsStruct)
36
45
  });
37
46
  function assertIsKeyringOrigins(value, ErrorWrapper) {
38
47
  _utils.assertStruct.call(void 0,
@@ -42,11 +51,25 @@ function assertIsKeyringOrigins(value, ErrorWrapper) {
42
51
  ErrorWrapper
43
52
  );
44
53
  }
54
+ function createOriginRegExp(matcher) {
55
+ const escaped = matcher.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
56
+ const regex = escaped.replace(/\*/gu, ".*");
57
+ return RegExp(regex, "u");
58
+ }
59
+ function checkAllowedOrigin(matcher, origin) {
60
+ if (matcher === "*" || matcher === origin) {
61
+ return true;
62
+ }
63
+ const regex = createOriginRegExp(matcher);
64
+ return regex.test(origin);
65
+ }
45
66
  function isOriginAllowed(origins, subjectType, origin) {
46
67
  if (origin === "metamask") {
47
68
  return true;
48
69
  }
49
- if (origins.allowedOrigins?.includes(origin)) {
70
+ if (origins.allowedOrigins?.some(
71
+ (matcher) => checkAllowedOrigin(matcher, origin)
72
+ )) {
50
73
  return true;
51
74
  }
52
75
  if (subjectType === _permissioncontroller.SubjectType.Website && origins.dapps) {
@@ -71,4 +94,4 @@ function assertIsJsonRpcSuccess(value) {
71
94
 
72
95
 
73
96
  exports.RpcOriginsStruct = RpcOriginsStruct; exports.assertIsRpcOrigins = assertIsRpcOrigins; exports.KeyringOriginsStruct = KeyringOriginsStruct; exports.assertIsKeyringOrigins = assertIsKeyringOrigins; exports.isOriginAllowed = isOriginAllowed; exports.assertIsJsonRpcSuccess = assertIsJsonRpcSuccess;
74
- //# sourceMappingURL=chunk-CQRPSEH3.js.map
97
+ //# sourceMappingURL=chunk-37VHIRUJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/json-rpc.ts"],"names":[],"mappings":";AAAA,SAAS,mBAAmB;AAM5B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,OAAO,SAAS,QAAQ,UAAU,QAAQ,cAAc;AAEjE,IAAM,uBAAuB;AAAA,EAC3B,OAAO,OAAO,GAAG,kBAAkB,CAAC,UAAU;AAC5C,UAAM,YAAY,MAAM,MAAM,GAAG,EAAE,SAAS;AAC5C,QAAI,YAAY,GAAG;AACjB,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,EACT,CAAC;AACH;AAEO,IAAM,mBAAmB;AAAA,EAC9B,OAAO;AAAA,IACL,OAAO,SAAS,QAAQ,CAAC;AAAA,IACzB,OAAO,SAAS,QAAQ,CAAC;AAAA,IACzB,gBAAgB,SAAS,oBAAoB;AAAA,EAC/C,CAAC;AAAA,EACD;AAAA,EACA,CAAC,UAAU;AACT,UAAM,aAAa;AAAA,MACjB,MAAM,UAAU,QACd,MAAM,UAAU,QACf,MAAM,kBAAkB,MAAM,eAAe,SAAS;AAAA,IAC3D;AAEA,QAAI,YAAY;AACd,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,EACT;AACF;AAYO,SAAS,mBACd,OAEA,cAC6B;AAC7B;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,uBAAuB,OAAO;AAAA,EACzC,gBAAgB,SAAS,oBAAoB;AAC/C,CAAC;AAYM,SAAS,uBACd,OAEA,cACiC;AACjC;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAUA,SAAS,mBAAmB,SAAiB;AAE3C,QAAM,UAAU,QAAQ,QAAQ,wBAAwB,MAAM;AAE9D,QAAM,QAAQ,QAAQ,QAAQ,QAAQ,IAAI;AAC1C,SAAO,OAAO,OAAO,GAAG;AAC1B;AAcA,SAAS,mBAAmB,SAAiB,QAAgB;AAE3D,MAAI,YAAY,OAAO,YAAY,QAAQ;AACzC,WAAO;AAAA,EACT;AAEA,QAAM,QAAQ,mBAAmB,OAAO;AACxC,SAAO,MAAM,KAAK,MAAM;AAC1B;AAUO,SAAS,gBACd,SACA,aACA,QACA;AAEA,MAAI,WAAW,YAAY;AACzB,WAAO;AAAA,EACT;AAGA,MACE,QAAQ,gBAAgB;AAAA,IAAK,CAAC,YAC5B,mBAAmB,SAAS,MAAM;AAAA,EACpC,GACA;AACA,WAAO;AAAA,EACT;AAGA,MAAI,gBAAgB,YAAY,WAAW,QAAQ,OAAO;AACxD,WAAO;AAAA,EACT;AAGA,SAAO,QAAQ,gBAAgB,YAAY,QAAQ,QAAQ,KAAK;AAClE;AAUO,SAAS,uBACd,OACuC;AACvC,MAAI,CAAC,iBAAiB,KAAK,GAAG;AAC5B,QAAI,iBAAiB,KAAK,GAAG;AAC3B,YAAM,IAAI,MAAM,4BAA4B,MAAM,MAAM,OAAO,EAAE;AAAA,IACnE;AAEA,UAAM,IAAI,MAAM,4BAA4B;AAAA,EAC9C;AACF","sourcesContent":["import { SubjectType } from '@metamask/permission-controller';\nimport type {\n AssertionErrorConstructor,\n Json,\n JsonRpcSuccess,\n} from '@metamask/utils';\nimport {\n assertStruct,\n isJsonRpcFailure,\n isJsonRpcSuccess,\n} from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport { array, boolean, object, optional, refine, string } from 'superstruct';\n\nconst AllowedOriginsStruct = array(\n refine(string(), 'Allowed origin', (value) => {\n const wildcards = value.split('*').length - 1;\n if (wildcards > 2) {\n return 'No more than two wildcards (\"*\") are allowed in an origin specifier.';\n }\n\n return true;\n }),\n);\n\nexport const RpcOriginsStruct = refine(\n object({\n dapps: optional(boolean()),\n snaps: optional(boolean()),\n allowedOrigins: optional(AllowedOriginsStruct),\n }),\n 'RPC origins',\n (value) => {\n const hasOrigins = Boolean(\n value.snaps === true ||\n value.dapps === true ||\n (value.allowedOrigins && value.allowedOrigins.length > 0),\n );\n\n if (hasOrigins) {\n return true;\n }\n\n return 'Must specify at least one JSON-RPC origin.';\n },\n);\n\nexport type RpcOrigins = Infer<typeof RpcOriginsStruct>;\n\n/**\n * Asserts that the given value is a valid {@link RpcOrigins} object.\n *\n * @param value - The value to assert.\n * @param ErrorWrapper - An optional error wrapper to use. Defaults to\n * {@link AssertionError}.\n * @throws If the value is not a valid {@link RpcOrigins} object.\n */\nexport function assertIsRpcOrigins(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is RpcOrigins {\n assertStruct(\n value,\n RpcOriginsStruct,\n 'Invalid JSON-RPC origins',\n ErrorWrapper,\n );\n}\n\nexport const KeyringOriginsStruct = object({\n allowedOrigins: optional(AllowedOriginsStruct),\n});\n\nexport type KeyringOrigins = Infer<typeof KeyringOriginsStruct>;\n\n/**\n * Assert that the given value is a valid {@link KeyringOrigins} object.\n *\n * @param value - The value to assert.\n * @param ErrorWrapper - An optional error wrapper to use. Defaults to\n * {@link AssertionError}.\n * @throws If the value is not a valid {@link KeyringOrigins} object.\n */\nexport function assertIsKeyringOrigins(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is KeyringOrigins {\n assertStruct(\n value,\n KeyringOriginsStruct,\n 'Invalid keyring origins',\n ErrorWrapper,\n );\n}\n\n/**\n * Create regular expression for matching against an origin while allowing wildcards.\n *\n * The \"*\" symbol is treated as a wildcard and will match 0 or more characters.\n *\n * @param matcher - The string to create the regular expression with.\n * @returns The regular expression.\n */\nfunction createOriginRegExp(matcher: string) {\n // Escape potential Regex characters\n const escaped = matcher.replace(/[.*+?^${}()|[\\]\\\\]/gu, '\\\\$&');\n // Support wildcards\n const regex = escaped.replace(/\\*/gu, '.*');\n return RegExp(regex, 'u');\n}\n\n/**\n * Check whether an origin is allowed or not using a matcher string.\n *\n * The matcher string may be a specific origin to match or include wildcards.\n * The \"*\" symbol is treated as a wildcard and will match 0 or more characters.\n * Note: this means that https://*metamask.io matches both https://metamask.io\n * and https://snaps.metamask.io.\n *\n * @param matcher - The matcher string.\n * @param origin - The origin.\n * @returns Whether the origin is allowed.\n */\nfunction checkAllowedOrigin(matcher: string, origin: string) {\n // If the matcher is a single wildcard or identical to the origin we can return true immediately.\n if (matcher === '*' || matcher === origin) {\n return true;\n }\n\n const regex = createOriginRegExp(matcher);\n return regex.test(origin);\n}\n\n/**\n * Check if the given origin is allowed by the given JSON-RPC origins object.\n *\n * @param origins - The JSON-RPC origins object.\n * @param subjectType - The type of the origin.\n * @param origin - The origin to check.\n * @returns Whether the origin is allowed.\n */\nexport function isOriginAllowed(\n origins: RpcOrigins,\n subjectType: SubjectType,\n origin: string,\n) {\n // The MetaMask client is always allowed.\n if (origin === 'metamask') {\n return true;\n }\n\n // If the origin is in the `allowedOrigins` list, it is allowed.\n if (\n origins.allowedOrigins?.some((matcher) =>\n checkAllowedOrigin(matcher, origin),\n )\n ) {\n return true;\n }\n\n // If the origin is a website and `dapps` is true, it is allowed.\n if (subjectType === SubjectType.Website && origins.dapps) {\n return true;\n }\n\n // If the origin is a snap and `snaps` is true, it is allowed.\n return Boolean(subjectType === SubjectType.Snap && origins.snaps);\n}\n\n/**\n * Assert that the given value is a successful JSON-RPC response. If the value\n * is not a success response, an error is thrown. If the value is an JSON-RPC\n * error, the error message is included in the thrown error.\n *\n * @param value - The value to check.\n * @throws If the value is not a JSON-RPC success response.\n */\nexport function assertIsJsonRpcSuccess(\n value: unknown,\n): asserts value is JsonRpcSuccess<Json> {\n if (!isJsonRpcSuccess(value)) {\n if (isJsonRpcFailure(value)) {\n throw new Error(`JSON-RPC request failed: ${value.error.message}`);\n }\n\n throw new Error('Invalid JSON-RPC response.');\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  SnapIdStruct
3
- } from "./chunk-2M6G46W6.mjs";
3
+ } from "./chunk-YCIPY3UP.mjs";
4
4
  import {
5
5
  ChainIdStruct
6
6
  } from "./chunk-EXUEHPZ4.mjs";
@@ -11,7 +11,7 @@ import {
11
11
  import {
12
12
  KeyringOriginsStruct,
13
13
  RpcOriginsStruct
14
- } from "./chunk-DKDGMZFU.mjs";
14
+ } from "./chunk-K2OTEZZZ.mjs";
15
15
  import {
16
16
  SIP_6_MAGIC_VALUE,
17
17
  STATE_ENCRYPTION_MAGIC_VALUE
@@ -286,4 +286,4 @@ export {
286
286
  assertIsSnapManifest,
287
287
  createSnapManifest
288
288
  };
289
- //# sourceMappingURL=chunk-QNPXK3B3.mjs.map
289
+ //# sourceMappingURL=chunk-4I22UHIU.mjs.map
@@ -47,12 +47,18 @@ function getChildren(elements) {
47
47
  }
48
48
  function getLinkText(token) {
49
49
  if (token.tokens && token.tokens.length > 0) {
50
- return getChildren(token.tokens.flatMap(getTextChildFromToken));
50
+ return getChildren(
51
+ token.tokens.flatMap(
52
+ getTextChildFromToken
53
+ )
54
+ );
51
55
  }
52
56
  return token.href;
53
57
  }
54
58
  function getTextChildFromTokens(tokens) {
55
- return getChildren(tokens.flatMap(getTextChildFromToken));
59
+ return getChildren(
60
+ tokens.flatMap(getTextChildFromToken)
61
+ );
56
62
  }
57
63
  function getTextChildFromToken(token) {
58
64
  switch (token.type) {
@@ -121,7 +127,9 @@ function getJsxElementFromComponent(legacyComponent) {
121
127
  case NodeType.Divider:
122
128
  return /* @__PURE__ */ jsx(Divider, {});
123
129
  case NodeType.Form:
124
- return /* @__PURE__ */ jsx(Form, { name: component.name, children: getChildren(component.children.map(getElement)) });
130
+ return /* @__PURE__ */ jsx(Form, { name: component.name, children: getChildren(
131
+ component.children.map(getElement)
132
+ ) });
125
133
  case NodeType.Heading:
126
134
  return /* @__PURE__ */ jsx(Heading, { children: component.value });
127
135
  case NodeType.Image:
@@ -137,7 +145,14 @@ function getJsxElementFromComponent(legacyComponent) {
137
145
  }
138
146
  ) });
139
147
  case NodeType.Panel:
140
- return /* @__PURE__ */ jsx(Box, { children: getChildren(component.children.map(getElement)) });
148
+ return /* @__PURE__ */ jsx(
149
+ Box,
150
+ {
151
+ children: getChildren(
152
+ component.children.map(getElement)
153
+ )
154
+ }
155
+ );
141
156
  case NodeType.Row:
142
157
  return /* @__PURE__ */ jsx(Row, { label: component.label, children: getElement(component.value) });
143
158
  case NodeType.Spinner:
@@ -259,4 +274,4 @@ export {
259
274
  getJsxChildren,
260
275
  walkJsx
261
276
  };
262
- //# sourceMappingURL=chunk-MJGSG5N2.mjs.map
277
+ //# sourceMappingURL=chunk-BZ7BMGXN.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/ui.tsx"],"sourcesContent":["import type { Component } from '@metamask/snaps-sdk';\nimport { NodeType } from '@metamask/snaps-sdk';\nimport type {\n BoldChildren,\n FieldElement,\n ItalicChildren,\n JSXElement,\n LinkElement,\n MaybeArray,\n RowChildren,\n StandardFormattingElement,\n TextChildren,\n} from '@metamask/snaps-sdk/jsx';\nimport {\n Italic,\n Link,\n Bold,\n Row,\n Text,\n Field,\n Image,\n Input,\n Heading,\n Form,\n Divider,\n Spinner,\n Copyable,\n Box,\n Button,\n Address,\n} from '@metamask/snaps-sdk/jsx';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport {\n assert,\n assertExhaustive,\n AssertionError,\n hasProperty,\n isPlainObject,\n} from '@metamask/utils';\nimport { lexer, walkTokens } from 'marked';\nimport type { Token, Tokens } from 'marked';\n\nconst MAX_TEXT_LENGTH = 50_000; // 50 kb\nconst ALLOWED_PROTOCOLS = ['https:', 'mailto:'];\n\n/**\n * Get the button variant from a legacy button component variant.\n *\n * @param variant - The legacy button component variant.\n * @returns The button variant.\n */\nfunction getButtonVariant(variant?: 'primary' | 'secondary' | undefined) {\n switch (variant) {\n case 'primary':\n return 'primary';\n case 'secondary':\n return 'destructive';\n default:\n return undefined;\n }\n}\n\n/**\n * Get the children of a JSX element. If there is only one child, the child is\n * returned directly. Otherwise, the children are returned as an array.\n *\n * @param elements - The JSX elements.\n * @returns The child or children.\n */\nfunction getChildren<Type>(elements: NonEmptyArray<Type>) {\n if (elements.length === 1) {\n return elements[0];\n }\n\n return elements;\n}\n\n/**\n * Get the text of a link token.\n *\n * @param token - The link token.\n * @returns The text of the link token.\n */\nfunction getLinkText(token: Tokens.Link | Tokens.Generic) {\n if (token.tokens && token.tokens.length > 0) {\n return getChildren(\n token.tokens.flatMap(\n getTextChildFromToken,\n ) as NonEmptyArray<TextChildren>,\n );\n }\n\n return token.href;\n}\n\n/**\n * Get the text child from a list of markdown tokens.\n *\n * @param tokens - The markdown tokens.\n * @returns The text child.\n */\nfunction getTextChildFromTokens(tokens: Token[]) {\n return getChildren(\n tokens.flatMap(getTextChildFromToken) as NonEmptyArray<TextChildren>,\n );\n}\n\n/**\n * Get the text child from a markdown token.\n *\n * @param token - The markdown token.\n * @returns The text child.\n */\nfunction getTextChildFromToken(token: Token): TextChildren {\n switch (token.type) {\n case 'link': {\n return <Link href={token.href} children={getLinkText(token)} />;\n }\n\n case 'text':\n return token.text;\n\n case 'strong':\n return (\n <Bold>\n {\n getTextChildFromTokens(\n // Due to the way `marked` is typed, `token.tokens` can be\n // `undefined`, but it's a required field of `Tokens.Bold`, so we\n // can safely cast it to `Token[]`.\n token.tokens as Token[],\n ) as BoldChildren\n }\n </Bold>\n );\n\n case 'em':\n return (\n <Italic>\n {\n getTextChildFromTokens(\n // Due to the way `marked` is typed, `token.tokens` can be\n // `undefined`, but it's a required field of `Tokens.Bold`, so we\n // can safely cast it to `Token[]`.\n token.tokens as Token[],\n ) as ItalicChildren\n }\n </Italic>\n );\n\n default:\n return null;\n }\n}\n\n/**\n * Get all text children from a markdown string.\n *\n * @param value - The markdown string.\n * @returns The text children.\n */\nexport function getTextChildren(\n value: string,\n): NonEmptyArray<string | StandardFormattingElement | LinkElement> {\n const rootTokens = lexer(value, { gfm: false });\n const children: (string | StandardFormattingElement | LinkElement | null)[] =\n [];\n\n walkTokens(rootTokens, (token) => {\n if (token.type === 'paragraph') {\n if (children.length > 0) {\n children.push('\\n\\n');\n }\n\n const { tokens } = token as Tokens.Paragraph;\n children.push(...tokens.flatMap(getTextChildFromToken));\n }\n });\n\n return children.filter((child) => child !== null) as NonEmptyArray<\n string | StandardFormattingElement | LinkElement\n >;\n}\n\n/**\n * Validate the text size of a component. The text size is the total length of\n * all text in the component.\n *\n * @param component - The component to validate.\n * @throws An error if the text size exceeds the maximum allowed size.\n */\nfunction validateComponentTextSize(component: Component) {\n const textSize = getTotalTextLength(component);\n assert(\n textSize <= MAX_TEXT_LENGTH,\n `The text in a Snap UI may not be larger than ${\n MAX_TEXT_LENGTH / 1000\n } kB.`,\n );\n}\n\n/**\n * Get a JSX element from a legacy UI component. This supports all legacy UI\n * components, and maps them to their JSX equivalents where possible.\n *\n * This function validates the text size of the component, but does not validate\n * the total size. The total size of the component should be validated before\n * calling this function.\n *\n * @param legacyComponent - The legacy UI component.\n * @returns The JSX element.\n */\nexport function getJsxElementFromComponent(\n legacyComponent: Component,\n): JSXElement {\n validateComponentTextSize(legacyComponent);\n\n /**\n * Get the JSX element for a component. This function is recursive and will\n * call itself for child components.\n *\n * @param component - The component to convert to a JSX element.\n * @returns The JSX element.\n */\n function getElement(component: Component) {\n switch (component.type) {\n case NodeType.Address:\n return <Address address={component.value} />;\n\n case NodeType.Button:\n return (\n <Button\n name={component.name}\n variant={getButtonVariant(component.variant)}\n type={component.buttonType}\n >\n {component.value}\n </Button>\n );\n\n case NodeType.Copyable:\n return (\n <Copyable value={component.value} sensitive={component.sensitive} />\n );\n\n case NodeType.Divider:\n return <Divider />;\n\n case NodeType.Form:\n return (\n <Form name={component.name}>\n {getChildren(\n component.children.map(getElement) as NonEmptyArray<FieldElement>,\n )}\n </Form>\n );\n\n case NodeType.Heading:\n return <Heading children={component.value} />;\n\n case NodeType.Image:\n // `Image` supports `alt`, but the legacy `Image` component does not.\n return <Image src={component.value} />;\n\n case NodeType.Input:\n return (\n <Field label={component.label} error={component.error}>\n <Input\n name={component.name}\n type={component.inputType}\n value={component.value}\n placeholder={component.placeholder}\n />\n </Field>\n );\n\n case NodeType.Panel:\n // `Panel` is renamed to `Box` in JSX.\n return (\n <Box\n children={getChildren(\n component.children.map(getElement) as NonEmptyArray<JSXElement>,\n )}\n />\n );\n\n case NodeType.Row:\n return (\n <Row label={component.label}>\n {getElement(component.value) as RowChildren}\n </Row>\n );\n\n case NodeType.Spinner:\n return <Spinner />;\n\n case NodeType.Text:\n return <Text>{getChildren(getTextChildren(component.value))}</Text>;\n\n /* istanbul ignore next 2 */\n default:\n return assertExhaustive(component);\n }\n }\n\n return getElement(legacyComponent);\n}\n\n/**\n * Extract all links from a Markdown text string using the `marked` lexer.\n *\n * @param text - The markdown text string.\n * @returns A list of URLs linked to in the string.\n */\nfunction getMarkdownLinks(text: string) {\n const tokens = lexer(text, { gfm: false });\n const links: Tokens.Link[] = [];\n\n // Walk the lexed tokens and collect all link tokens\n walkTokens(tokens, (token) => {\n if (token.type === 'link') {\n links.push(token as Tokens.Link);\n }\n });\n\n return links;\n}\n\n/**\n * Validate a link against the phishing list.\n *\n * @param link - The link to validate.\n * @param isOnPhishingList - The function that checks the link against the\n * phishing list.\n */\nfunction validateLink(\n link: string,\n isOnPhishingList: (url: string) => boolean,\n) {\n try {\n const url = new URL(link);\n assert(\n ALLOWED_PROTOCOLS.includes(url.protocol),\n `Protocol must be one of: ${ALLOWED_PROTOCOLS.join(', ')}.`,\n );\n\n const hostname =\n url.protocol === 'mailto:' ? url.pathname.split('@')[1] : url.hostname;\n\n assert(!isOnPhishingList(hostname), 'The specified URL is not allowed.');\n } catch (error) {\n throw new Error(\n `Invalid URL: ${\n error instanceof AssertionError ? error.message : 'Unable to parse URL.'\n }`,\n );\n }\n}\n\n/**\n * Search for Markdown links in a string and checks them against the phishing\n * list.\n *\n * @param text - The text to verify.\n * @param isOnPhishingList - The function that checks the link against the\n * phishing list.\n * @throws If the text contains a link that is not allowed.\n */\nexport function validateTextLinks(\n text: string,\n isOnPhishingList: (url: string) => boolean,\n) {\n const links = getMarkdownLinks(text);\n\n for (const link of links) {\n validateLink(link.href, isOnPhishingList);\n }\n}\n\n/**\n * Walk a JSX tree and validate each {@link LinkElement} node against the\n * phishing list.\n *\n * @param node - The JSX node to walk.\n * @param isOnPhishingList - The function that checks the link against the\n * phishing list.\n */\nexport function validateJsxLinks(\n node: JSXElement,\n isOnPhishingList: (url: string) => boolean,\n) {\n walkJsx(node, (childNode) => {\n if (childNode.type !== 'Link') {\n return;\n }\n\n validateLink(childNode.props.href, isOnPhishingList);\n });\n}\n\n/**\n * Calculate the total length of all text in the component.\n *\n * @param component - A custom UI component.\n * @returns The total length of all text components in the component.\n */\nexport function getTotalTextLength(component: Component): number {\n const { type } = component;\n\n switch (type) {\n case NodeType.Panel:\n return component.children.reduce<number>(\n // This is a bug in TypeScript: https://github.com/microsoft/TypeScript/issues/48313\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n (sum, node) => sum + getTotalTextLength(node),\n 0,\n );\n\n case NodeType.Row:\n return getTotalTextLength(component.value);\n\n case NodeType.Text:\n return component.value.length;\n\n default:\n return 0;\n }\n}\n\n/**\n * Check if a JSX element has children.\n *\n * @param element - A JSX element.\n * @returns `true` if the element has children, `false` otherwise.\n */\nexport function hasChildren<Element extends JSXElement>(\n element: Element,\n): element is Element & {\n props: { children: MaybeArray<JSXElement | string> };\n} {\n return hasProperty(element.props, 'children');\n}\n\n/**\n * Get the children of a JSX element as an array. If the element has only one\n * child, the child is returned as an array.\n *\n * @param element - A JSX element.\n * @returns The children of the element.\n */\nexport function getJsxChildren(element: JSXElement): (JSXElement | string)[] {\n if (hasChildren(element)) {\n if (Array.isArray(element.props.children)) {\n // @ts-expect-error - Each member of the union type has signatures, but\n // none of those signatures are compatible with each other.\n return element.props.children.filter(Boolean);\n }\n\n if (element.props.children) {\n return [element.props.children];\n }\n }\n\n return [];\n}\n\n/**\n * Walk a JSX tree and call a callback on each node.\n *\n * @param node - The JSX node to walk.\n * @param callback - The callback to call on each node.\n * @returns The result of the callback, if any.\n */\nexport function walkJsx<Value>(\n node: JSXElement | JSXElement[],\n callback: (node: JSXElement) => Value | undefined,\n): Value | undefined {\n if (Array.isArray(node)) {\n for (const child of node) {\n const childResult = walkJsx(child as JSXElement, callback);\n if (childResult !== undefined) {\n return childResult;\n }\n }\n\n return undefined;\n }\n\n const result = callback(node);\n if (result !== undefined) {\n return result;\n }\n\n if (\n hasProperty(node, 'props') &&\n isPlainObject(node.props) &&\n hasProperty(node.props, 'children')\n ) {\n const children = getJsxChildren(node);\n for (const child of children) {\n if (isPlainObject(child)) {\n const childResult = walkJsx(child, callback);\n if (childResult !== undefined) {\n return childResult;\n }\n }\n }\n }\n\n return undefined;\n}\n"],"mappings":";AACA,SAAS,gBAAgB;AAYzB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,S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,QAAW;AACxB,WAAO;AAAA,EACT;AAEA,MACE,YAAY,MAAM,OAAO,KACzB,cAAc,KAAK,KAAK,KACxB,YAAY,KAAK,OAAO,UAAU,GAClC;AACA,UAAM,WAAW,eAAe,IAAI;AACpC,eAAW,SAAS,UAAU;AAC5B,UAAI,cAAc,KAAK,GAAG;AACxB,cAAM,cAAc,QAAQ,OAAO,QAAQ;AAC3C,YAAI,gBAAgB,QAAW;AAC7B,iBAAO;AAAA,QACT;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
@@ -47,12 +47,18 @@ function getChildren(elements) {
47
47
  }
48
48
  function getLinkText(token) {
49
49
  if (token.tokens && token.tokens.length > 0) {
50
- return getChildren(token.tokens.flatMap(getTextChildFromToken));
50
+ return getChildren(
51
+ token.tokens.flatMap(
52
+ getTextChildFromToken
53
+ )
54
+ );
51
55
  }
52
56
  return token.href;
53
57
  }
54
58
  function getTextChildFromTokens(tokens) {
55
- return getChildren(tokens.flatMap(getTextChildFromToken));
59
+ return getChildren(
60
+ tokens.flatMap(getTextChildFromToken)
61
+ );
56
62
  }
57
63
  function getTextChildFromToken(token) {
58
64
  switch (token.type) {
@@ -121,7 +127,9 @@ function getJsxElementFromComponent(legacyComponent) {
121
127
  case _snapssdk.NodeType.Divider:
122
128
  return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _jsx.Divider, {});
123
129
  case _snapssdk.NodeType.Form:
124
- return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _jsx.Form, { name: component.name, children: getChildren(component.children.map(getElement)) });
130
+ return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _jsx.Form, { name: component.name, children: getChildren(
131
+ component.children.map(getElement)
132
+ ) });
125
133
  case _snapssdk.NodeType.Heading:
126
134
  return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _jsx.Heading, { children: component.value });
127
135
  case _snapssdk.NodeType.Image:
@@ -137,7 +145,14 @@ function getJsxElementFromComponent(legacyComponent) {
137
145
  }
138
146
  ) });
139
147
  case _snapssdk.NodeType.Panel:
140
- return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _jsx.Box, { children: getChildren(component.children.map(getElement)) });
148
+ return /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
149
+ _jsx.Box,
150
+ {
151
+ children: getChildren(
152
+ component.children.map(getElement)
153
+ )
154
+ }
155
+ );
141
156
  case _snapssdk.NodeType.Row:
142
157
  return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _jsx.Row, { label: component.label, children: getElement(component.value) });
143
158
  case _snapssdk.NodeType.Spinner:
@@ -259,4 +274,4 @@ function walkJsx(node, callback) {
259
274
 
260
275
 
261
276
  exports.getTextChildren = getTextChildren; exports.getJsxElementFromComponent = getJsxElementFromComponent; exports.validateTextLinks = validateTextLinks; exports.validateJsxLinks = validateJsxLinks; exports.getTotalTextLength = getTotalTextLength; exports.hasChildren = hasChildren; exports.getJsxChildren = getJsxChildren; exports.walkJsx = walkJsx;
262
- //# sourceMappingURL=chunk-4YAWNZXM.js.map
277
+ //# sourceMappingURL=chunk-IHHQU6IS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/ui.tsx"],"names":[],"mappings":";AACA,SAAS,gBAAgB;AAYzB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,OAAO,kBAAkB;AA6ErB;AA1Eb,IAAM,kBAAkB;AACxB,IAAM,oBAAoB,CAAC,UAAU,SAAS;AAQ9C,SAAS,iBAAiB,SAA+C;AACvE,UAAQ,SAAS;AAAA,IACf,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO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AAK,GAAG;AACxB,cAAM,cAAc,QAAQ,OAAO,QAAQ;AAC3C,YAAI,gBAAgB,QAAW;AAC7B,iBAAO;AAAA,QACT;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT","sourcesContent":["import type { Component } from '@metamask/snaps-sdk';\nimport { NodeType } from '@metamask/snaps-sdk';\nimport type {\n BoldChildren,\n FieldElement,\n ItalicChildren,\n JSXElement,\n LinkElement,\n MaybeArray,\n RowChildren,\n StandardFormattingElement,\n TextChildren,\n} from '@metamask/snaps-sdk/jsx';\nimport {\n Italic,\n Link,\n Bold,\n Row,\n Text,\n Field,\n Image,\n Input,\n Heading,\n Form,\n Divider,\n Spinner,\n Copyable,\n Box,\n Button,\n Address,\n} from '@metamask/snaps-sdk/jsx';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport {\n assert,\n assertExhaustive,\n AssertionError,\n hasProperty,\n isPlainObject,\n} from '@metamask/utils';\nimport { lexer, walkTokens } from 'marked';\nimport type { Token, Tokens } from 'marked';\n\nconst MAX_TEXT_LENGTH = 50_000; // 50 kb\nconst ALLOWED_PROTOCOLS = ['https:', 'mailto:'];\n\n/**\n * Get the button variant from a legacy button component variant.\n *\n * @param variant - The legacy button component variant.\n * @returns The button variant.\n */\nfunction getButtonVariant(variant?: 'primary' | 'secondary' | undefined) {\n switch (variant) {\n case 'primary':\n return 'primary';\n case 'secondary':\n return 'destructive';\n default:\n return undefined;\n }\n}\n\n/**\n * Get the children of a JSX element. If there is only one child, the child is\n * returned directly. Otherwise, the children are returned as an array.\n *\n * @param elements - The JSX elements.\n * @returns The child or children.\n */\nfunction getChildren<Type>(elements: NonEmptyArray<Type>) {\n if (elements.length === 1) {\n return elements[0];\n }\n\n return elements;\n}\n\n/**\n * Get the text of a link token.\n *\n * @param token - The link token.\n * @returns The text of the link token.\n */\nfunction getLinkText(token: Tokens.Link | Tokens.Generic) {\n if (token.tokens && token.tokens.length > 0) {\n return getChildren(\n token.tokens.flatMap(\n getTextChildFromToken,\n ) as NonEmptyArray<TextChildren>,\n );\n }\n\n return token.href;\n}\n\n/**\n * Get the text child from a list of markdown tokens.\n *\n * @param tokens - The markdown tokens.\n * @returns The text child.\n */\nfunction getTextChildFromTokens(tokens: Token[]) {\n return getChildren(\n tokens.flatMap(getTextChildFromToken) as NonEmptyArray<TextChildren>,\n );\n}\n\n/**\n * Get the text child from a markdown token.\n *\n * @param token - The markdown token.\n * @returns The text child.\n */\nfunction getTextChildFromToken(token: Token): TextChildren {\n switch (token.type) {\n case 'link': {\n return <Link href={token.href} children={getLinkText(token)} />;\n }\n\n case 'text':\n return token.text;\n\n case 'strong':\n return (\n <Bold>\n {\n getTextChildFromTokens(\n // Due to the way `marked` is typed, `token.tokens` can be\n // `undefined`, but it's a required field of `Tokens.Bold`, so we\n // can safely cast it to `Token[]`.\n token.tokens as Token[],\n ) as BoldChildren\n }\n </Bold>\n );\n\n case 'em':\n return (\n <Italic>\n {\n getTextChildFromTokens(\n // Due to the way `marked` is typed, `token.tokens` can be\n // `undefined`, but it's a required field of `Tokens.Bold`, so we\n // can safely cast it to `Token[]`.\n token.tokens as Token[],\n ) as ItalicChildren\n }\n </Italic>\n );\n\n default:\n return null;\n }\n}\n\n/**\n * Get all text children from a markdown string.\n *\n * @param value - The markdown string.\n * @returns The text children.\n */\nexport function getTextChildren(\n value: string,\n): NonEmptyArray<string | StandardFormattingElement | LinkElement> {\n const rootTokens = lexer(value, { gfm: false });\n const children: (string | StandardFormattingElement | LinkElement | null)[] =\n [];\n\n walkTokens(rootTokens, (token) => {\n if (token.type === 'paragraph') {\n if (children.length > 0) {\n children.push('\\n\\n');\n }\n\n const { tokens } = token as Tokens.Paragraph;\n children.push(...tokens.flatMap(getTextChildFromToken));\n }\n });\n\n return children.filter((child) => child !== null) as NonEmptyArray<\n string | StandardFormattingElement | LinkElement\n >;\n}\n\n/**\n * Validate the text size of a component. The text size is the total length of\n * all text in the component.\n *\n * @param component - The component to validate.\n * @throws An error if the text size exceeds the maximum allowed size.\n */\nfunction validateComponentTextSize(component: Component) {\n const textSize = getTotalTextLength(component);\n assert(\n textSize <= MAX_TEXT_LENGTH,\n `The text in a Snap UI may not be larger than ${\n MAX_TEXT_LENGTH / 1000\n } kB.`,\n );\n}\n\n/**\n * Get a JSX element from a legacy UI component. This supports all legacy UI\n * components, and maps them to their JSX equivalents where possible.\n *\n * This function validates the text size of the component, but does not validate\n * the total size. The total size of the component should be validated before\n * calling this function.\n *\n * @param legacyComponent - The legacy UI component.\n * @returns The JSX element.\n */\nexport function getJsxElementFromComponent(\n legacyComponent: Component,\n): JSXElement {\n validateComponentTextSize(legacyComponent);\n\n /**\n * Get the JSX element for a component. This function is recursive and will\n * call itself for child components.\n *\n * @param component - The component to convert to a JSX element.\n * @returns The JSX element.\n */\n function getElement(component: Component) {\n switch (component.type) {\n case NodeType.Address:\n return <Address address={component.value} />;\n\n case NodeType.Button:\n return (\n <Button\n name={component.name}\n variant={getButtonVariant(component.variant)}\n type={component.buttonType}\n >\n {component.value}\n </Button>\n );\n\n case NodeType.Copyable:\n return (\n <Copyable value={component.value} sensitive={component.sensitive} />\n );\n\n case NodeType.Divider:\n return <Divider />;\n\n case NodeType.Form:\n return (\n <Form name={component.name}>\n {getChildren(\n component.children.map(getElement) as NonEmptyArray<FieldElement>,\n )}\n </Form>\n );\n\n case NodeType.Heading:\n return <Heading children={component.value} />;\n\n case NodeType.Image:\n // `Image` supports `alt`, but the legacy `Image` component does not.\n return <Image src={component.value} />;\n\n case NodeType.Input:\n return (\n <Field label={component.label} error={component.error}>\n <Input\n name={component.name}\n type={component.inputType}\n value={component.value}\n placeholder={component.placeholder}\n />\n </Field>\n );\n\n case NodeType.Panel:\n // `Panel` is renamed to `Box` in JSX.\n return (\n <Box\n children={getChildren(\n component.children.map(getElement) as NonEmptyArray<JSXElement>,\n )}\n />\n );\n\n case NodeType.Row:\n return (\n <Row label={component.label}>\n {getElement(component.value) as RowChildren}\n </Row>\n );\n\n case NodeType.Spinner:\n return <Spinner />;\n\n case NodeType.Text:\n return <Text>{getChildren(getTextChildren(component.value))}</Text>;\n\n /* istanbul ignore next 2 */\n default:\n return assertExhaustive(component);\n }\n }\n\n return getElement(legacyComponent);\n}\n\n/**\n * Extract all links from a Markdown text string using the `marked` lexer.\n *\n * @param text - The markdown text string.\n * @returns A list of URLs linked to in the string.\n */\nfunction getMarkdownLinks(text: string) {\n const tokens = lexer(text, { gfm: false });\n const links: Tokens.Link[] = [];\n\n // Walk the lexed tokens and collect all link tokens\n walkTokens(tokens, (token) => {\n if (token.type === 'link') {\n links.push(token as Tokens.Link);\n }\n });\n\n return links;\n}\n\n/**\n * Validate a link against the phishing list.\n *\n * @param link - The link to validate.\n * @param isOnPhishingList - The function that checks the link against the\n * phishing list.\n */\nfunction validateLink(\n link: string,\n isOnPhishingList: (url: string) => boolean,\n) {\n try {\n const url = new URL(link);\n assert(\n ALLOWED_PROTOCOLS.includes(url.protocol),\n `Protocol must be one of: ${ALLOWED_PROTOCOLS.join(', ')}.`,\n );\n\n const hostname =\n url.protocol === 'mailto:' ? url.pathname.split('@')[1] : url.hostname;\n\n assert(!isOnPhishingList(hostname), 'The specified URL is not allowed.');\n } catch (error) {\n throw new Error(\n `Invalid URL: ${\n error instanceof AssertionError ? error.message : 'Unable to parse URL.'\n }`,\n );\n }\n}\n\n/**\n * Search for Markdown links in a string and checks them against the phishing\n * list.\n *\n * @param text - The text to verify.\n * @param isOnPhishingList - The function that checks the link against the\n * phishing list.\n * @throws If the text contains a link that is not allowed.\n */\nexport function validateTextLinks(\n text: string,\n isOnPhishingList: (url: string) => boolean,\n) {\n const links = getMarkdownLinks(text);\n\n for (const link of links) {\n validateLink(link.href, isOnPhishingList);\n }\n}\n\n/**\n * Walk a JSX tree and validate each {@link LinkElement} node against the\n * phishing list.\n *\n * @param node - The JSX node to walk.\n * @param isOnPhishingList - The function that checks the link against the\n * phishing list.\n */\nexport function validateJsxLinks(\n node: JSXElement,\n isOnPhishingList: (url: string) => boolean,\n) {\n walkJsx(node, (childNode) => {\n if (childNode.type !== 'Link') {\n return;\n }\n\n validateLink(childNode.props.href, isOnPhishingList);\n });\n}\n\n/**\n * Calculate the total length of all text in the component.\n *\n * @param component - A custom UI component.\n * @returns The total length of all text components in the component.\n */\nexport function getTotalTextLength(component: Component): number {\n const { type } = component;\n\n switch (type) {\n case NodeType.Panel:\n return component.children.reduce<number>(\n // This is a bug in TypeScript: https://github.com/microsoft/TypeScript/issues/48313\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n (sum, node) => sum + getTotalTextLength(node),\n 0,\n );\n\n case NodeType.Row:\n return getTotalTextLength(component.value);\n\n case NodeType.Text:\n return component.value.length;\n\n default:\n return 0;\n }\n}\n\n/**\n * Check if a JSX element has children.\n *\n * @param element - A JSX element.\n * @returns `true` if the element has children, `false` otherwise.\n */\nexport function hasChildren<Element extends JSXElement>(\n element: Element,\n): element is Element & {\n props: { children: MaybeArray<JSXElement | string> };\n} {\n return hasProperty(element.props, 'children');\n}\n\n/**\n * Get the children of a JSX element as an array. If the element has only one\n * child, the child is returned as an array.\n *\n * @param element - A JSX element.\n * @returns The children of the element.\n */\nexport function getJsxChildren(element: JSXElement): (JSXElement | string)[] {\n if (hasChildren(element)) {\n if (Array.isArray(element.props.children)) {\n // @ts-expect-error - Each member of the union type has signatures, but\n // none of those signatures are compatible with each other.\n return element.props.children.filter(Boolean);\n }\n\n if (element.props.children) {\n return [element.props.children];\n }\n }\n\n return [];\n}\n\n/**\n * Walk a JSX tree and call a callback on each node.\n *\n * @param node - The JSX node to walk.\n * @param callback - The callback to call on each node.\n * @returns The result of the callback, if any.\n */\nexport function walkJsx<Value>(\n node: JSXElement | JSXElement[],\n callback: (node: JSXElement) => Value | undefined,\n): Value | undefined {\n if (Array.isArray(node)) {\n for (const child of node) {\n const childResult = walkJsx(child as JSXElement, callback);\n if (childResult !== undefined) {\n return childResult;\n }\n }\n\n return undefined;\n }\n\n const result = callback(node);\n if (result !== undefined) {\n return result;\n }\n\n if (\n hasProperty(node, 'props') &&\n isPlainObject(node.props) &&\n hasProperty(node.props, 'children')\n ) {\n const children = getJsxChildren(node);\n for (const child of children) {\n if (isPlainObject(child)) {\n const childResult = walkJsx(child, callback);\n if (childResult !== undefined) {\n return childResult;\n }\n }\n }\n }\n\n return undefined;\n}\n"]}
@@ -6,11 +6,20 @@ import {
6
6
  isJsonRpcSuccess
7
7
  } from "@metamask/utils";
8
8
  import { array, boolean, object, optional, refine, string } from "superstruct";
9
+ var AllowedOriginsStruct = array(
10
+ refine(string(), "Allowed origin", (value) => {
11
+ const wildcards = value.split("*").length - 1;
12
+ if (wildcards > 2) {
13
+ return 'No more than two wildcards ("*") are allowed in an origin specifier.';
14
+ }
15
+ return true;
16
+ })
17
+ );
9
18
  var RpcOriginsStruct = refine(
10
19
  object({
11
20
  dapps: optional(boolean()),
12
21
  snaps: optional(boolean()),
13
- allowedOrigins: optional(array(string()))
22
+ allowedOrigins: optional(AllowedOriginsStruct)
14
23
  }),
15
24
  "RPC origins",
16
25
  (value) => {
@@ -32,7 +41,7 @@ function assertIsRpcOrigins(value, ErrorWrapper) {
32
41
  );
33
42
  }
34
43
  var KeyringOriginsStruct = object({
35
- allowedOrigins: optional(array(string()))
44
+ allowedOrigins: optional(AllowedOriginsStruct)
36
45
  });
37
46
  function assertIsKeyringOrigins(value, ErrorWrapper) {
38
47
  assertStruct(
@@ -42,11 +51,25 @@ function assertIsKeyringOrigins(value, ErrorWrapper) {
42
51
  ErrorWrapper
43
52
  );
44
53
  }
54
+ function createOriginRegExp(matcher) {
55
+ const escaped = matcher.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
56
+ const regex = escaped.replace(/\*/gu, ".*");
57
+ return RegExp(regex, "u");
58
+ }
59
+ function checkAllowedOrigin(matcher, origin) {
60
+ if (matcher === "*" || matcher === origin) {
61
+ return true;
62
+ }
63
+ const regex = createOriginRegExp(matcher);
64
+ return regex.test(origin);
65
+ }
45
66
  function isOriginAllowed(origins, subjectType, origin) {
46
67
  if (origin === "metamask") {
47
68
  return true;
48
69
  }
49
- if (origins.allowedOrigins?.includes(origin)) {
70
+ if (origins.allowedOrigins?.some(
71
+ (matcher) => checkAllowedOrigin(matcher, origin)
72
+ )) {
50
73
  return true;
51
74
  }
52
75
  if (subjectType === SubjectType.Website && origins.dapps) {
@@ -71,4 +94,4 @@ export {
71
94
  isOriginAllowed,
72
95
  assertIsJsonRpcSuccess
73
96
  };
74
- //# sourceMappingURL=chunk-DKDGMZFU.mjs.map
97
+ //# sourceMappingURL=chunk-K2OTEZZZ.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/json-rpc.ts"],"sourcesContent":["import { SubjectType } from '@metamask/permission-controller';\nimport type {\n AssertionErrorConstructor,\n Json,\n JsonRpcSuccess,\n} from '@metamask/utils';\nimport {\n assertStruct,\n isJsonRpcFailure,\n isJsonRpcSuccess,\n} from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport { array, boolean, object, optional, refine, string } from 'superstruct';\n\nconst AllowedOriginsStruct = array(\n refine(string(), 'Allowed origin', (value) => {\n const wildcards = value.split('*').length - 1;\n if (wildcards > 2) {\n return 'No more than two wildcards (\"*\") are allowed in an origin specifier.';\n }\n\n return true;\n }),\n);\n\nexport const RpcOriginsStruct = refine(\n object({\n dapps: optional(boolean()),\n snaps: optional(boolean()),\n allowedOrigins: optional(AllowedOriginsStruct),\n }),\n 'RPC origins',\n (value) => {\n const hasOrigins = Boolean(\n value.snaps === true ||\n value.dapps === true ||\n (value.allowedOrigins && value.allowedOrigins.length > 0),\n );\n\n if (hasOrigins) {\n return true;\n }\n\n return 'Must specify at least one JSON-RPC origin.';\n },\n);\n\nexport type RpcOrigins = Infer<typeof RpcOriginsStruct>;\n\n/**\n * Asserts that the given value is a valid {@link RpcOrigins} object.\n *\n * @param value - The value to assert.\n * @param ErrorWrapper - An optional error wrapper to use. Defaults to\n * {@link AssertionError}.\n * @throws If the value is not a valid {@link RpcOrigins} object.\n */\nexport function assertIsRpcOrigins(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is RpcOrigins {\n assertStruct(\n value,\n RpcOriginsStruct,\n 'Invalid JSON-RPC origins',\n ErrorWrapper,\n );\n}\n\nexport const KeyringOriginsStruct = object({\n allowedOrigins: optional(AllowedOriginsStruct),\n});\n\nexport type KeyringOrigins = Infer<typeof KeyringOriginsStruct>;\n\n/**\n * Assert that the given value is a valid {@link KeyringOrigins} object.\n *\n * @param value - The value to assert.\n * @param ErrorWrapper - An optional error wrapper to use. Defaults to\n * {@link AssertionError}.\n * @throws If the value is not a valid {@link KeyringOrigins} object.\n */\nexport function assertIsKeyringOrigins(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is KeyringOrigins {\n assertStruct(\n value,\n KeyringOriginsStruct,\n 'Invalid keyring origins',\n ErrorWrapper,\n );\n}\n\n/**\n * Create regular expression for matching against an origin while allowing wildcards.\n *\n * The \"*\" symbol is treated as a wildcard and will match 0 or more characters.\n *\n * @param matcher - The string to create the regular expression with.\n * @returns The regular expression.\n */\nfunction createOriginRegExp(matcher: string) {\n // Escape potential Regex characters\n const escaped = matcher.replace(/[.*+?^${}()|[\\]\\\\]/gu, '\\\\$&');\n // Support wildcards\n const regex = escaped.replace(/\\*/gu, '.*');\n return RegExp(regex, 'u');\n}\n\n/**\n * Check whether an origin is allowed or not using a matcher string.\n *\n * The matcher string may be a specific origin to match or include wildcards.\n * The \"*\" symbol is treated as a wildcard and will match 0 or more characters.\n * Note: this means that https://*metamask.io matches both https://metamask.io\n * and https://snaps.metamask.io.\n *\n * @param matcher - The matcher string.\n * @param origin - The origin.\n * @returns Whether the origin is allowed.\n */\nfunction checkAllowedOrigin(matcher: string, origin: string) {\n // If the matcher is a single wildcard or identical to the origin we can return true immediately.\n if (matcher === '*' || matcher === origin) {\n return true;\n }\n\n const regex = createOriginRegExp(matcher);\n return regex.test(origin);\n}\n\n/**\n * Check if the given origin is allowed by the given JSON-RPC origins object.\n *\n * @param origins - The JSON-RPC origins object.\n * @param subjectType - The type of the origin.\n * @param origin - The origin to check.\n * @returns Whether the origin is allowed.\n */\nexport function isOriginAllowed(\n origins: RpcOrigins,\n subjectType: SubjectType,\n origin: string,\n) {\n // The MetaMask client is always allowed.\n if (origin === 'metamask') {\n return true;\n }\n\n // If the origin is in the `allowedOrigins` list, it is allowed.\n if (\n origins.allowedOrigins?.some((matcher) =>\n checkAllowedOrigin(matcher, origin),\n )\n ) {\n return true;\n }\n\n // If the origin is a website and `dapps` is true, it is allowed.\n if (subjectType === SubjectType.Website && origins.dapps) {\n return true;\n }\n\n // If the origin is a snap and `snaps` is true, it is allowed.\n return Boolean(subjectType === SubjectType.Snap && origins.snaps);\n}\n\n/**\n * Assert that the given value is a successful JSON-RPC response. If the value\n * is not a success response, an error is thrown. If the value is an JSON-RPC\n * error, the error message is included in the thrown error.\n *\n * @param value - The value to check.\n * @throws If the value is not a JSON-RPC success response.\n */\nexport function assertIsJsonRpcSuccess(\n value: unknown,\n): asserts value is JsonRpcSuccess<Json> {\n if (!isJsonRpcSuccess(value)) {\n if (isJsonRpcFailure(value)) {\n throw new Error(`JSON-RPC request failed: ${value.error.message}`);\n }\n\n throw new Error('Invalid JSON-RPC response.');\n }\n}\n"],"mappings":";AAAA,SAAS,mBAAmB;AAM5B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,OAAO,SAAS,QAAQ,UAAU,QAAQ,cAAc;AAEjE,IAAM,uBAAuB;AAAA,EAC3B,OAAO,OAAO,GAAG,kBAAkB,CAAC,UAAU;AAC5C,UAAM,YAAY,MAAM,MAAM,GAAG,EAAE,SAAS;AAC5C,QAAI,YAAY,GAAG;AACjB,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,EACT,CAAC;AACH;AAEO,IAAM,mBAAmB;AAAA,EAC9B,OAAO;AAAA,IACL,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AK;AAClE;AAUO,SAAS,uBACd,OACuC;AACvC,MAAI,CAAC,iBAAiB,KAAK,GAAG;AAC5B,QAAI,iBAAiB,KAAK,GAAG;AAC3B,YAAM,IAAI,MAAM,4BAA4B,MAAM,MAAM,OAAO,EAAE;AAAA,IACnE;AAEA,UAAM,IAAI,MAAM,4BAA4B;AAAA,EAC9C;AACF;","names":[]}
@@ -190,4 +190,4 @@ function verifyRequestedSnapPermissions(requestedPermissions) {
190
190
 
191
191
 
192
192
  exports.PROPOSED_NAME_REGEX = PROPOSED_NAME_REGEX; exports.SnapStatus = SnapStatus; exports.SnapStatusEvents = SnapStatusEvents; exports.ProgrammaticallyFixableSnapError = ProgrammaticallyFixableSnapError; exports.getSnapChecksum = getSnapChecksum; exports.validateSnapShasum = validateSnapShasum; exports.LOCALHOST_HOSTNAMES = LOCALHOST_HOSTNAMES; exports.BaseSnapIdStruct = BaseSnapIdStruct; exports.LocalSnapIdStruct = LocalSnapIdStruct; exports.NpmSnapIdStruct = NpmSnapIdStruct; exports.HttpSnapIdStruct = HttpSnapIdStruct; exports.SnapIdStruct = SnapIdStruct; exports.getSnapPrefix = getSnapPrefix; exports.stripSnapPrefix = stripSnapPrefix; exports.assertIsValidSnapId = assertIsValidSnapId; exports.isCaipChainId = isCaipChainId; exports.isSnapPermitted = isSnapPermitted; exports.verifyRequestedSnapPermissions = verifyRequestedSnapPermissions;
193
- //# sourceMappingURL=chunk-HVTYDKBO.js.map
193
+ //# sourceMappingURL=chunk-K4B37F3L.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/snaps.ts"],"names":["SnapStatus","SnapStatusEvents"],"mappings":";;;;;;;;;AAQA,SAAS,QAAQ,UAAU,oBAAoB;AAC/C,SAAS,cAAc;AACvB,OAAO,qBAAqB;AAE5B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,OAAO,wBA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5D,QAAM,SAAS,OAAO,OAAO,cAAc,EAAE;AAAA,IAAK,CAAC,mBACjD,OAAO,WAAW,cAAc;AAAA,EAClC;AACA,MAAI,WAAW,QAAW;AACxB,WAAO;AAAA,EACT;AACA,QAAM,IAAI,MAAM,mCAAmC,MAAM,GAAG;AAC9D;AAQO,SAAS,gBAAgB,QAAwB;AACtD,SAAO,OAAO,QAAQ,cAAc,MAAM,GAAG,EAAE;AACjD;AAQO,SAAS,oBAAoB,OAAyC;AAC3E,eAAa,OAAO,cAAc,iBAAiB;AACrD;AAQO,SAAS,cAAc,SAAqC;AACjE,SACE,OAAO,YAAY,YACnB,mEAAmE;AAAA,IACjE;AAAA,EACF;AAEJ;AASO,SAAS,gBACd,aACA,QACA;AACA,SAAO;AAAA,KAGA,aAAa,aAAa,SAAS;AAAA,MAClC,CAAC,WAAW,OAAO;AAAA,IACrB,KAAK,CAAC,GACN,QACA,MAAM;AAAA,EACZ;AACF;AASO,SAAS,+BACd,sBACwD;AACxD;AAAA,IACE,SAAS,oBAAoB;AAAA,IAC7B;AAAA,EACF;AAEA,QAAM,EAAE,aAAa,qBAAqB,IAAI;AAE9C;AAAA,IACE,SAAS,oBAAoB;AAAA,IAC7B;AAAA,EACF;AAEA,QAAM,EAAE,QAAQ,IAAI;AAEpB;AAAA,IACE,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW;AAAA,IAC7C;AAAA,EACF;AAEA,QAAM,CAAC,MAAM,IAAI;AAEjB;AAAA,IACE,SAAS,MAAM,KACb,OAAO,oCACP,SAAS,OAAO,KAAK;AAAA,IACvB,wEAAuE;AAAA,EACzE;AACF","sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport type { SnapId, Snap as TruncatedSnap } from '@metamask/snaps-sdk';\nimport type { Json } from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport stableStringify from 'fast-json-stable-stringify';\nimport type { Struct } from 'superstruct';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from 'superstruct';\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, SnapValidationFailureReason, 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 SnapAuxilaryFile = {\n path: string;\n // Value here should be stored as base64\n value: string;\n};\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?: SnapAuxilaryFile[];\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\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\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 ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\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 = pattern(string(), /^[\\x21-\\x7E]*$/u);\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 SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\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 * 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 * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\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,6 +1,6 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
- var _chunkHVTYDKBOjs = require('./chunk-HVTYDKBO.js');
3
+ var _chunkK4B37F3Ljs = require('./chunk-K4B37F3L.js');
4
4
 
5
5
 
6
6
  var _chunk6LOYTBS3js = require('./chunk-6LOYTBS3.js');
@@ -11,7 +11,7 @@ var _chunkCMOSYNZRjs = require('./chunk-CMOSYNZR.js');
11
11
 
12
12
 
13
13
 
14
- var _chunkCQRPSEH3js = require('./chunk-CQRPSEH3.js');
14
+ var _chunk37VHIRUJjs = require('./chunk-37VHIRUJ.js');
15
15
 
16
16
 
17
17
 
@@ -120,7 +120,7 @@ var SemVerRangeStruct = _superstruct.refine.call(void 0, _superstruct.string.cal
120
120
  return "Expected a valid SemVer range.";
121
121
  });
122
122
  var SnapIdsStruct = _superstruct.refine.call(void 0,
123
- _superstruct.record.call(void 0, _chunkHVTYDKBOjs.SnapIdStruct, _superstruct.object.call(void 0, { version: _superstruct.optional.call(void 0, SemVerRangeStruct) })),
123
+ _superstruct.record.call(void 0, _chunkK4B37F3Ljs.SnapIdStruct, _superstruct.object.call(void 0, { version: _superstruct.optional.call(void 0, SemVerRangeStruct) })),
124
124
  "SnapIds",
125
125
  (value) => {
126
126
  if (Object.keys(value).length === 0) {
@@ -162,7 +162,7 @@ var PermissionsStruct = _superstruct.type.call(void 0, {
162
162
  ),
163
163
  "endowment:ethereum-provider": _superstruct.optional.call(void 0, EmptyObjectStruct),
164
164
  "endowment:keyring": _superstruct.optional.call(void 0,
165
- _superstruct.assign.call(void 0, HandlerCaveatsStruct, _chunkCQRPSEH3js.KeyringOriginsStruct)
165
+ _superstruct.assign.call(void 0, HandlerCaveatsStruct, _chunk37VHIRUJjs.KeyringOriginsStruct)
166
166
  ),
167
167
  "endowment:lifecycle-hooks": _superstruct.optional.call(void 0, HandlerCaveatsStruct),
168
168
  "endowment:name-lookup": _superstruct.optional.call(void 0,
@@ -176,7 +176,7 @@ var PermissionsStruct = _superstruct.type.call(void 0, {
176
176
  ),
177
177
  "endowment:network-access": _superstruct.optional.call(void 0, EmptyObjectStruct),
178
178
  "endowment:page-home": _superstruct.optional.call(void 0, HandlerCaveatsStruct),
179
- "endowment:rpc": _superstruct.optional.call(void 0, _superstruct.assign.call(void 0, HandlerCaveatsStruct, _chunkCQRPSEH3js.RpcOriginsStruct)),
179
+ "endowment:rpc": _superstruct.optional.call(void 0, _superstruct.assign.call(void 0, HandlerCaveatsStruct, _chunk37VHIRUJjs.RpcOriginsStruct)),
180
180
  "endowment:signature-insight": _superstruct.optional.call(void 0,
181
181
  _superstruct.assign.call(void 0,
182
182
  HandlerCaveatsStruct,
@@ -286,4 +286,4 @@ function createSnapManifest(value) {
286
286
 
287
287
 
288
288
  exports.FORBIDDEN_COIN_TYPES = FORBIDDEN_COIN_TYPES; exports.Bip32PathStruct = Bip32PathStruct; exports.bip32entropy = bip32entropy; exports.CurveStruct = CurveStruct; exports.Bip32EntropyStruct = Bip32EntropyStruct; exports.SnapGetBip32EntropyPermissionsStruct = SnapGetBip32EntropyPermissionsStruct; exports.SemVerRangeStruct = SemVerRangeStruct; exports.SnapIdsStruct = SnapIdsStruct; exports.ChainIdsStruct = ChainIdsStruct; exports.LookupMatchersStruct = LookupMatchersStruct; exports.MINIMUM_REQUEST_TIMEOUT = MINIMUM_REQUEST_TIMEOUT; exports.MAXIMUM_REQUEST_TIMEOUT = MAXIMUM_REQUEST_TIMEOUT; exports.MaxRequestTimeStruct = MaxRequestTimeStruct; exports.HandlerCaveatsStruct = HandlerCaveatsStruct; exports.EmptyObjectStruct = EmptyObjectStruct; exports.PermissionsStruct = PermissionsStruct; exports.SnapAuxilaryFilesStruct = SnapAuxilaryFilesStruct; exports.InitialConnectionsStruct = InitialConnectionsStruct; exports.SnapManifestStruct = SnapManifestStruct; exports.isSnapManifest = isSnapManifest; exports.assertIsSnapManifest = assertIsSnapManifest; exports.createSnapManifest = createSnapManifest;
289
- //# sourceMappingURL=chunk-IAHW6IFC.js.map
289
+ //# sourceMappingURL=chunk-LNZLPDBB.js.map
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  assertIsSnapManifest
3
- } from "./chunk-QNPXK3B3.mjs";
3
+ } from "./chunk-4I22UHIU.mjs";
4
4
  import {
5
5
  ProgrammaticallyFixableSnapError,
6
6
  getSnapChecksum,
7
7
  validateSnapShasum
8
- } from "./chunk-2M6G46W6.mjs";
8
+ } from "./chunk-YCIPY3UP.mjs";
9
9
  import {
10
10
  assertIsSnapIcon,
11
11
  getSvgDimensions
@@ -406,4 +406,4 @@ export {
406
406
  getWritableManifest,
407
407
  validateNpmSnapManifest
408
408
  };
409
- //# sourceMappingURL=chunk-UCRFECSX.mjs.map
409
+ //# sourceMappingURL=chunk-R6VG7F6Y.mjs.map
@@ -1,11 +1,11 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2
2
 
3
- var _chunkIAHW6IFCjs = require('./chunk-IAHW6IFC.js');
3
+ var _chunkLNZLPDBBjs = require('./chunk-LNZLPDBB.js');
4
4
 
5
5
 
6
6
 
7
7
 
8
- var _chunkHVTYDKBOjs = require('./chunk-HVTYDKBO.js');
8
+ var _chunkK4B37F3Ljs = require('./chunk-K4B37F3L.js');
9
9
 
10
10
 
11
11
 
@@ -83,7 +83,7 @@ async function checkManifest(basePath, writeManifest = true, sourceCode, writeFi
83
83
  try {
84
84
  ({ manifest } = await validateNpmSnap(snapFiles));
85
85
  } catch (error) {
86
- if (error instanceof _chunkHVTYDKBOjs.ProgrammaticallyFixableSnapError) {
86
+ if (error instanceof _chunkK4B37F3Ljs.ProgrammaticallyFixableSnapError) {
87
87
  errors.push(error.message);
88
88
  const partiallyValidatedFiles = snapFiles;
89
89
  let isInvalid = true;
@@ -102,7 +102,7 @@ async function checkManifest(basePath, writeManifest = true, sourceCode, writeFi
102
102
  isInvalid = false;
103
103
  } catch (nextValidationError) {
104
104
  currentError = nextValidationError;
105
- if (!(nextValidationError instanceof _chunkHVTYDKBOjs.ProgrammaticallyFixableSnapError) || attempts === maxAttempts && !isInvalid) {
105
+ if (!(nextValidationError instanceof _chunkK4B37F3Ljs.ProgrammaticallyFixableSnapError) || attempts === maxAttempts && !isInvalid) {
106
106
  throw new Error(
107
107
  `Internal error: Failed to fix manifest. This is a bug, please report it. Reason:
108
108
  ${error.message}`
@@ -180,7 +180,7 @@ async function fixManifest(snapFiles, error) {
180
180
  manifestCopy.repository = packageJson.result.repository ? _chunkNUCLSR2Gjs.deepClone.call(void 0, packageJson.result.repository) : void 0;
181
181
  break;
182
182
  case '"shasum" field mismatch' /* ShasumMismatch */:
183
- manifestCopy.source.shasum = await _chunkHVTYDKBOjs.getSnapChecksum.call(void 0, snapFiles);
183
+ manifestCopy.source.shasum = await _chunkK4B37F3Ljs.getSnapChecksum.call(void 0, snapFiles);
184
184
  break;
185
185
  default:
186
186
  _utils.assertExhaustive.call(void 0, error.reason);
@@ -287,13 +287,13 @@ async function validateNpmSnapManifest({
287
287
  const manifestPackageVersion = manifest.result.version;
288
288
  const manifestRepository = manifest.result.repository;
289
289
  if (packageJsonName !== manifestPackageName) {
290
- throw new (0, _chunkHVTYDKBOjs.ProgrammaticallyFixableSnapError)(
290
+ throw new (0, _chunkK4B37F3Ljs.ProgrammaticallyFixableSnapError)(
291
291
  `"${"snap.manifest.json" /* Manifest */}" npm package name ("${manifestPackageName}") does not match the "${"package.json" /* PackageJson */}" "name" field ("${packageJsonName}").`,
292
292
  '"name" field mismatch' /* NameMismatch */
293
293
  );
294
294
  }
295
295
  if (packageJsonVersion !== manifestPackageVersion) {
296
- throw new (0, _chunkHVTYDKBOjs.ProgrammaticallyFixableSnapError)(
296
+ throw new (0, _chunkK4B37F3Ljs.ProgrammaticallyFixableSnapError)(
297
297
  `"${"snap.manifest.json" /* Manifest */}" npm package version ("${manifestPackageVersion}") does not match the "${"package.json" /* PackageJson */}" "version" field ("${packageJsonVersion}").`,
298
298
  '"version" field mismatch' /* VersionMismatch */
299
299
  );
@@ -303,12 +303,12 @@ async function validateNpmSnapManifest({
303
303
  // or `null` in the Snap manifest due to TS@<4.4 issues.
304
304
  (packageJsonRepository || manifestRepository) && !_fastdeepequal2.default.call(void 0, packageJsonRepository, manifestRepository)
305
305
  ) {
306
- throw new (0, _chunkHVTYDKBOjs.ProgrammaticallyFixableSnapError)(
306
+ throw new (0, _chunkK4B37F3Ljs.ProgrammaticallyFixableSnapError)(
307
307
  `"${"snap.manifest.json" /* Manifest */}" "repository" field does not match the "${"package.json" /* PackageJson */}" "repository" field.`,
308
308
  '"repository" field mismatch' /* RepositoryMismatch */
309
309
  );
310
310
  }
311
- await _chunkHVTYDKBOjs.validateSnapShasum.call(void 0,
311
+ await _chunkK4B37F3Ljs.validateSnapShasum.call(void 0,
312
312
  { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles },
313
313
  `"${"snap.manifest.json" /* Manifest */}" "shasum" field does not match computed shasum.`
314
314
  );
@@ -342,7 +342,7 @@ async function validateNpmSnap(snapFiles, errorPrefix) {
342
342
  localizationFiles
343
343
  } = snapFiles;
344
344
  try {
345
- _chunkIAHW6IFCjs.assertIsSnapManifest.call(void 0, manifest.result);
345
+ _chunkLNZLPDBBjs.assertIsSnapManifest.call(void 0, manifest.result);
346
346
  } catch (error) {
347
347
  throw new Error(`${errorPrefix ?? ""}${error.message}`);
348
348
  }
@@ -406,4 +406,4 @@ async function validateNpmSnap(snapFiles, errorPrefix) {
406
406
 
407
407
 
408
408
  exports.EXPECTED_SNAP_FILES = EXPECTED_SNAP_FILES; exports.SnapFileNameFromKey = SnapFileNameFromKey; exports.validateNpmSnap = validateNpmSnap; exports.checkManifest = checkManifest; exports.fixManifest = fixManifest; exports.getSnapSourceCode = getSnapSourceCode; exports.getSnapIcon = getSnapIcon; exports.getSnapFilePaths = getSnapFilePaths; exports.getSnapFiles = getSnapFiles; exports.getWritableManifest = getWritableManifest; exports.validateNpmSnapManifest = validateNpmSnapManifest;
409
- //# sourceMappingURL=chunk-N4KSSDO5.js.map
409
+ //# sourceMappingURL=chunk-SWU464Y6.js.map