@metamask/snaps-utils 1.0.2 → 2.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 (268) hide show
  1. package/CHANGELOG.md +33 -223
  2. package/dist/cjs/array.js +23 -0
  3. package/dist/cjs/array.js.map +1 -0
  4. package/dist/cjs/caveats.js +36 -0
  5. package/dist/cjs/caveats.js.map +1 -0
  6. package/dist/cjs/checksum.js +38 -0
  7. package/dist/cjs/checksum.js.map +1 -0
  8. package/dist/cjs/cronjob.js +84 -0
  9. package/dist/cjs/cronjob.js.map +1 -0
  10. package/dist/cjs/deep-clone.js +22 -0
  11. package/dist/cjs/deep-clone.js.map +1 -0
  12. package/dist/cjs/default-endowments.js +49 -0
  13. package/dist/cjs/default-endowments.js.map +1 -0
  14. package/dist/cjs/entropy.js +23 -0
  15. package/dist/cjs/entropy.js.map +1 -0
  16. package/dist/cjs/enum.js +16 -0
  17. package/dist/cjs/enum.js.map +1 -0
  18. package/dist/cjs/errors.js +19 -0
  19. package/dist/cjs/errors.js.map +1 -0
  20. package/dist/{eval-worker.js → cjs/eval-worker.js} +22 -21
  21. package/dist/cjs/eval-worker.js.map +1 -0
  22. package/dist/cjs/eval.js +77 -0
  23. package/dist/cjs/eval.js.map +1 -0
  24. package/dist/cjs/fs.js +126 -0
  25. package/dist/cjs/fs.js.map +1 -0
  26. package/dist/cjs/handlers.js +80 -0
  27. package/dist/cjs/handlers.js.map +1 -0
  28. package/dist/cjs/icon.js +37 -0
  29. package/dist/cjs/icon.js.map +1 -0
  30. package/dist/cjs/iframe.js +59 -0
  31. package/dist/cjs/iframe.js.map +1 -0
  32. package/dist/cjs/index.browser.js +43 -0
  33. package/dist/cjs/index.browser.js.map +1 -0
  34. package/dist/cjs/index.executionenv.js +24 -0
  35. package/dist/cjs/index.executionenv.js.map +1 -0
  36. package/dist/cjs/index.js +48 -0
  37. package/dist/cjs/index.js.map +1 -0
  38. package/dist/cjs/json-rpc.js +46 -0
  39. package/dist/cjs/json-rpc.js.map +1 -0
  40. package/dist/cjs/json.js +16 -0
  41. package/dist/cjs/json.js.map +1 -0
  42. package/dist/cjs/logging.js +40 -0
  43. package/dist/cjs/logging.js.map +1 -0
  44. package/dist/cjs/manifest/index.browser.js +20 -0
  45. package/dist/cjs/manifest/index.browser.js.map +1 -0
  46. package/dist/cjs/manifest/index.js +21 -0
  47. package/dist/cjs/manifest/index.js.map +1 -0
  48. package/dist/cjs/manifest/manifest.js +239 -0
  49. package/dist/cjs/manifest/manifest.js.map +1 -0
  50. package/dist/cjs/manifest/validation.js +189 -0
  51. package/dist/cjs/manifest/validation.js.map +1 -0
  52. package/dist/cjs/mock.js +128 -0
  53. package/dist/cjs/mock.js.map +1 -0
  54. package/dist/cjs/namespace.js +132 -0
  55. package/dist/cjs/namespace.js.map +1 -0
  56. package/dist/cjs/npm.js +81 -0
  57. package/dist/cjs/npm.js.map +1 -0
  58. package/dist/cjs/path.js +21 -0
  59. package/dist/cjs/path.js.map +1 -0
  60. package/dist/cjs/post-process.js +328 -0
  61. package/dist/cjs/post-process.js.map +1 -0
  62. package/dist/cjs/snaps.js +230 -0
  63. package/dist/cjs/snaps.js.map +1 -0
  64. package/dist/cjs/strings.js +21 -0
  65. package/dist/cjs/strings.js.map +1 -0
  66. package/dist/cjs/structs.js +163 -0
  67. package/dist/cjs/structs.js.map +1 -0
  68. package/dist/cjs/types.js +109 -0
  69. package/dist/cjs/types.js.map +1 -0
  70. package/dist/cjs/validation.js +22 -0
  71. package/dist/cjs/validation.js.map +1 -0
  72. package/dist/cjs/versions.js +47 -0
  73. package/dist/cjs/versions.js.map +1 -0
  74. package/dist/cjs/virtual-file/VirtualFile.js +85 -0
  75. package/dist/cjs/virtual-file/VirtualFile.js.map +1 -0
  76. package/dist/cjs/virtual-file/index.browser.js +20 -0
  77. package/dist/cjs/virtual-file/index.browser.js.map +1 -0
  78. package/dist/cjs/virtual-file/index.js +21 -0
  79. package/dist/cjs/virtual-file/index.js.map +1 -0
  80. package/dist/cjs/virtual-file/toVirtualFile.js +33 -0
  81. package/dist/cjs/virtual-file/toVirtualFile.js.map +1 -0
  82. package/dist/{array.js → esm/array.js} +3 -7
  83. package/dist/esm/array.js.map +1 -0
  84. package/dist/esm/caveats.js +26 -0
  85. package/dist/esm/caveats.js.map +1 -0
  86. package/dist/esm/checksum.js +36 -0
  87. package/dist/esm/checksum.js.map +1 -0
  88. package/dist/esm/cronjob.js +66 -0
  89. package/dist/esm/cronjob.js.map +1 -0
  90. package/dist/esm/deep-clone.js +7 -0
  91. package/dist/esm/deep-clone.js.map +1 -0
  92. package/dist/{default-endowments.js → esm/default-endowments.js} +3 -6
  93. package/dist/esm/default-endowments.js.map +1 -0
  94. package/dist/esm/entropy.js +6 -0
  95. package/dist/esm/entropy.js.map +1 -0
  96. package/dist/esm/enum.js +12 -0
  97. package/dist/esm/enum.js.map +1 -0
  98. package/dist/esm/errors.js +17 -0
  99. package/dist/esm/errors.js.map +1 -0
  100. package/dist/esm/eval-worker.js +47 -0
  101. package/dist/esm/eval-worker.js.map +1 -0
  102. package/dist/esm/eval.js +65 -0
  103. package/dist/esm/eval.js.map +1 -0
  104. package/dist/{fs.js → esm/fs.js} +33 -56
  105. package/dist/esm/fs.js.map +1 -0
  106. package/dist/esm/handlers.js +59 -0
  107. package/dist/esm/handlers.js.map +1 -0
  108. package/dist/esm/icon.js +11 -0
  109. package/dist/esm/icon.js.map +1 -0
  110. package/dist/{iframe.js → esm/iframe.js} +16 -18
  111. package/dist/esm/iframe.js.map +1 -0
  112. package/dist/esm/index.browser.js +26 -0
  113. package/dist/esm/index.browser.js.map +1 -0
  114. package/dist/esm/index.executionenv.js +7 -0
  115. package/dist/esm/index.executionenv.js.map +1 -0
  116. package/dist/esm/index.js +31 -0
  117. package/dist/esm/index.js.map +1 -0
  118. package/dist/esm/json-rpc.js +39 -0
  119. package/dist/esm/json-rpc.js.map +1 -0
  120. package/dist/esm/json.js +17 -0
  121. package/dist/esm/json.js.map +1 -0
  122. package/dist/{logging.js → esm/logging.js} +6 -14
  123. package/dist/esm/logging.js.map +1 -0
  124. package/dist/esm/manifest/index.browser.js +3 -0
  125. package/dist/esm/manifest/index.browser.js.map +1 -0
  126. package/dist/esm/manifest/index.js +4 -0
  127. package/dist/esm/manifest/index.js.map +1 -0
  128. package/dist/{manifest → esm/manifest}/manifest.js +101 -115
  129. package/dist/esm/manifest/manifest.js.map +1 -0
  130. package/dist/esm/manifest/validation.js +155 -0
  131. package/dist/esm/manifest/validation.js.map +1 -0
  132. package/dist/{mock.js → esm/mock.js} +42 -40
  133. package/dist/esm/mock.js.map +1 -0
  134. package/dist/esm/namespace.js +112 -0
  135. package/dist/esm/namespace.js.map +1 -0
  136. package/dist/esm/npm.js +70 -0
  137. package/dist/esm/npm.js.map +1 -0
  138. package/dist/esm/path.js +17 -0
  139. package/dist/esm/path.js.map +1 -0
  140. package/dist/{post-process.js → esm/post-process.js} +110 -99
  141. package/dist/esm/post-process.js.map +1 -0
  142. package/dist/esm/snaps.js +215 -0
  143. package/dist/esm/snaps.js.map +1 -0
  144. package/dist/esm/strings.js +11 -0
  145. package/dist/esm/strings.js.map +1 -0
  146. package/dist/esm/structs.js +230 -0
  147. package/dist/esm/structs.js.map +1 -0
  148. package/dist/esm/types.js +80 -0
  149. package/dist/esm/types.js.map +1 -0
  150. package/dist/esm/validation.js +17 -0
  151. package/dist/esm/validation.js.map +1 -0
  152. package/dist/{versions.js → esm/versions.js} +15 -18
  153. package/dist/esm/versions.js.map +1 -0
  154. package/dist/{virtual-file → esm/virtual-file}/VirtualFile.js +47 -33
  155. package/dist/esm/virtual-file/VirtualFile.js.map +1 -0
  156. package/dist/esm/virtual-file/index.browser.js +3 -0
  157. package/dist/esm/virtual-file/index.browser.js.map +1 -0
  158. package/dist/esm/virtual-file/index.js +4 -0
  159. package/dist/esm/virtual-file/index.js.map +1 -0
  160. package/dist/esm/virtual-file/toVirtualFile.js +26 -0
  161. package/dist/esm/virtual-file/toVirtualFile.js.map +1 -0
  162. package/dist/{caveats.d.ts → types/caveats.d.ts} +5 -5
  163. package/dist/{cronjob.d.ts → types/cronjob.d.ts} +1 -1
  164. package/dist/types/enum.d.ts +30 -0
  165. package/dist/types/errors.d.ts +10 -0
  166. package/dist/{eval.d.ts → types/eval.d.ts} +9 -1
  167. package/dist/{fs.d.ts → types/fs.d.ts} +2 -2
  168. package/dist/types/handlers.d.ts +196 -0
  169. package/dist/types/icon.d.ts +4 -0
  170. package/dist/{iframe.d.ts → types/iframe.d.ts} +3 -2
  171. package/dist/{index.browser.d.ts → types/index.browser.d.ts} +5 -1
  172. package/dist/{index.d.ts → types/index.d.ts} +5 -1
  173. package/dist/{json-rpc.d.ts → types/json-rpc.d.ts} +2 -2
  174. package/dist/types/json.d.ts +13 -0
  175. package/dist/{manifest → types/manifest}/manifest.d.ts +6 -4
  176. package/dist/{manifest → types/manifest}/validation.d.ts +40 -76
  177. package/dist/types/namespace.d.ts +128 -0
  178. package/dist/{npm.d.ts → types/npm.d.ts} +2 -3
  179. package/dist/{snaps.d.ts → types/snaps.d.ts} +17 -9
  180. package/dist/types/strings.d.ts +8 -0
  181. package/dist/types/structs.d.ts +158 -0
  182. package/dist/{types.d.ts → types/types.d.ts} +15 -22
  183. package/dist/types/validation.d.ts +8 -0
  184. package/dist/{versions.d.ts → types/versions.d.ts} +1 -1
  185. package/package.json +66 -46
  186. package/dist/array.js.map +0 -1
  187. package/dist/caveats.js +0 -35
  188. package/dist/caveats.js.map +0 -1
  189. package/dist/checksum.js +0 -42
  190. package/dist/checksum.js.map +0 -1
  191. package/dist/cronjob.js +0 -71
  192. package/dist/cronjob.js.map +0 -1
  193. package/dist/deep-clone.js +0 -9
  194. package/dist/deep-clone.js.map +0 -1
  195. package/dist/default-endowments.js.map +0 -1
  196. package/dist/entropy.js +0 -8
  197. package/dist/entropy.js.map +0 -1
  198. package/dist/eval-worker.js.map +0 -1
  199. package/dist/eval.js +0 -27
  200. package/dist/eval.js.map +0 -1
  201. package/dist/fs.js.map +0 -1
  202. package/dist/handlers.d.ts +0 -105
  203. package/dist/handlers.js +0 -3
  204. package/dist/handlers.js.map +0 -1
  205. package/dist/iframe.js.map +0 -1
  206. package/dist/iframe.test.browser.js +0 -15
  207. package/dist/iframe.test.browser.js.map +0 -1
  208. package/dist/index.browser.js +0 -37
  209. package/dist/index.browser.js.map +0 -1
  210. package/dist/index.executionenv.js +0 -22
  211. package/dist/index.executionenv.js.map +0 -1
  212. package/dist/index.js +0 -42
  213. package/dist/index.js.map +0 -1
  214. package/dist/json-rpc.js +0 -46
  215. package/dist/json-rpc.js.map +0 -1
  216. package/dist/json.d.ts +0 -9
  217. package/dist/json.js +0 -18
  218. package/dist/json.js.map +0 -1
  219. package/dist/logging.js.map +0 -1
  220. package/dist/manifest/index.browser.js +0 -18
  221. package/dist/manifest/index.browser.js.map +0 -1
  222. package/dist/manifest/index.js +0 -19
  223. package/dist/manifest/index.js.map +0 -1
  224. package/dist/manifest/manifest.js.map +0 -1
  225. package/dist/manifest/validation.js +0 -141
  226. package/dist/manifest/validation.js.map +0 -1
  227. package/dist/mock.js.map +0 -1
  228. package/dist/namespace.d.ts +0 -275
  229. package/dist/namespace.js +0 -225
  230. package/dist/namespace.js.map +0 -1
  231. package/dist/notification.d.ts +0 -66
  232. package/dist/notification.js +0 -58
  233. package/dist/notification.js.map +0 -1
  234. package/dist/npm.js +0 -74
  235. package/dist/npm.js.map +0 -1
  236. package/dist/path.js +0 -21
  237. package/dist/path.js.map +0 -1
  238. package/dist/post-process.js.map +0 -1
  239. package/dist/snaps.js +0 -202
  240. package/dist/snaps.js.map +0 -1
  241. package/dist/types.js +0 -103
  242. package/dist/types.js.map +0 -1
  243. package/dist/versions.js.map +0 -1
  244. package/dist/virtual-file/VirtualFile.js.map +0 -1
  245. package/dist/virtual-file/index.browser.js +0 -18
  246. package/dist/virtual-file/index.browser.js.map +0 -1
  247. package/dist/virtual-file/index.js +0 -19
  248. package/dist/virtual-file/index.js.map +0 -1
  249. package/dist/virtual-file/toVirtualFile.js +0 -30
  250. package/dist/virtual-file/toVirtualFile.js.map +0 -1
  251. /package/dist/{array.d.ts → types/array.d.ts} +0 -0
  252. /package/dist/{checksum.d.ts → types/checksum.d.ts} +0 -0
  253. /package/dist/{deep-clone.d.ts → types/deep-clone.d.ts} +0 -0
  254. /package/dist/{default-endowments.d.ts → types/default-endowments.d.ts} +0 -0
  255. /package/dist/{entropy.d.ts → types/entropy.d.ts} +0 -0
  256. /package/dist/{eval-worker.d.ts → types/eval-worker.d.ts} +0 -0
  257. /package/dist/{iframe.test.browser.d.ts → types/iframe.test.browser.d.ts} +0 -0
  258. /package/dist/{index.executionenv.d.ts → types/index.executionenv.d.ts} +0 -0
  259. /package/dist/{logging.d.ts → types/logging.d.ts} +0 -0
  260. /package/dist/{manifest → types/manifest}/index.browser.d.ts +0 -0
  261. /package/dist/{manifest → types/manifest}/index.d.ts +0 -0
  262. /package/dist/{mock.d.ts → types/mock.d.ts} +0 -0
  263. /package/dist/{path.d.ts → types/path.d.ts} +0 -0
  264. /package/dist/{post-process.d.ts → types/post-process.d.ts} +0 -0
  265. /package/dist/{virtual-file → types/virtual-file}/VirtualFile.d.ts +0 -0
  266. /package/dist/{virtual-file → types/virtual-file}/index.browser.d.ts +0 -0
  267. /package/dist/{virtual-file → types/virtual-file}/index.d.ts +0 -0
  268. /package/dist/{virtual-file → types/virtual-file}/toVirtualFile.d.ts +0 -0
@@ -1,32 +1,35 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.generateMockEndowments = exports.isConstructor = exports.ALL_APIS = void 0;
7
- const crypto_1 = __importDefault(require("crypto"));
8
- const events_1 = __importDefault(require("events"));
9
- const default_endowments_1 = require("./default-endowments");
10
- const NETWORK_APIS = ['fetch'];
11
- exports.ALL_APIS = [...default_endowments_1.DEFAULT_ENDOWMENTS, ...NETWORK_APIS];
1
+ import crypto from 'crypto';
2
+ import EventEmitter from 'events';
3
+ import { DEFAULT_ENDOWMENTS } from './default-endowments';
4
+ const NETWORK_APIS = [
5
+ 'fetch',
6
+ 'Request',
7
+ 'Headers',
8
+ 'Response'
9
+ ];
10
+ export const ALL_APIS = [
11
+ ...DEFAULT_ENDOWMENTS,
12
+ ...NETWORK_APIS,
13
+ 'WebAssembly'
14
+ ];
12
15
  /**
13
16
  * Get a mock snap API, that always returns `true` for requests.
14
17
  *
15
18
  * @returns A mocked snap provider.
16
- */
17
- function getMockSnapGlobal() {
19
+ */ function getMockSnapGlobal() {
18
20
  // eslint-disable-next-line @typescript-eslint/require-await
19
- return { request: async () => true };
21
+ return {
22
+ request: async ()=>true
23
+ };
20
24
  }
21
25
  /**
22
26
  * Get a mock Ethereum provider, that always returns `true` for requests.
23
27
  *
24
28
  * @returns A mocked ethereum provider.
25
- */
26
- function getMockEthereumProvider() {
27
- const mockProvider = new events_1.default();
29
+ */ function getMockEthereumProvider() {
30
+ const mockProvider = new EventEmitter();
28
31
  // eslint-disable-next-line @typescript-eslint/require-await
29
- mockProvider.request = async () => true;
32
+ mockProvider.request = async ()=>true;
30
33
  return mockProvider;
31
34
  }
32
35
  /**
@@ -34,25 +37,22 @@ function getMockEthereumProvider() {
34
37
  *
35
38
  * @param value - The value to check.
36
39
  * @returns `true` if the value is a constructor, or `false` otherwise.
37
- */
38
- const isConstructor = (value) => Boolean(typeof value?.prototype?.constructor?.name === 'string');
39
- exports.isConstructor = isConstructor;
40
+ */ export const isConstructor = (value)=>Boolean(typeof value?.prototype?.constructor?.name === 'string');
40
41
  /**
41
42
  * A function that always returns `true`.
42
43
  *
43
44
  * @returns `true`.
44
- */
45
- const mockFunction = () => true;
45
+ */ const mockFunction = ()=>true;
46
46
  class MockClass {
47
47
  }
48
48
  const handler = {
49
49
  // eslint-disable-next-line @typescript-eslint/naming-convention
50
- construct(Target, args) {
50
+ construct (Target, args) {
51
51
  return new Proxy(new Target(...args), handler);
52
52
  },
53
- get(_target, _prop) {
53
+ get (_target, _prop) {
54
54
  return mockFunction;
55
- },
55
+ }
56
56
  };
57
57
  /**
58
58
  * Generate a mock class for a given value. The value is wrapped in a Proxy, and
@@ -60,15 +60,14 @@ const handler = {
60
60
  *
61
61
  * @param value - The value to mock.
62
62
  * @returns A mock class.
63
- */
64
- const generateMockClass = (value) => {
63
+ */ const generateMockClass = (value)=>{
65
64
  return new Proxy(value, handler);
66
65
  };
67
66
  // Things not currently auto-mocked because of NodeJS, by adding them here we
68
67
  // have types for them and can use that to generate mocks if needed.
69
68
  const mockWindow = {
70
- crypto: crypto_1.default,
71
- SubtleCrypto: MockClass,
69
+ crypto,
70
+ SubtleCrypto: MockClass
72
71
  };
73
72
  /**
74
73
  * Generate a mock endowment for a certain class or function on the `globalThis`
@@ -77,21 +76,19 @@ const mockWindow = {
77
76
  * @param key - The key to generate the mock endowment for.
78
77
  * @returns A mocked class or function. If the key is part of the default
79
78
  * endowments, the original value is returned.
80
- */
81
- const generateMockEndowment = (key) => {
79
+ */ const generateMockEndowment = (key)=>{
82
80
  const globalValue = globalThis[key];
83
81
  // Default exposed APIs don't need to be mocked
84
- if (globalValue && default_endowments_1.DEFAULT_ENDOWMENTS.includes(key)) {
82
+ if (globalValue && DEFAULT_ENDOWMENTS.includes(key)) {
85
83
  return globalValue;
86
84
  }
87
85
  // Fall back to mockWindow for certain APIs not exposed in global in Node.JS
88
86
  const globalOrMocked = globalValue ?? mockWindow[key];
89
87
  const type = typeof globalOrMocked;
90
88
  const isFunction = type === 'function';
91
- if (isFunction && (0, exports.isConstructor)(globalOrMocked)) {
89
+ if (isFunction && isConstructor(globalOrMocked)) {
92
90
  return generateMockClass(globalOrMocked);
93
- }
94
- else if (isFunction || !globalOrMocked) {
91
+ } else if (isFunction || !globalOrMocked) {
95
92
  // Fall back to function mock for now
96
93
  return mockFunction;
97
94
  }
@@ -101,9 +98,14 @@ const generateMockEndowment = (key) => {
101
98
  * Generate mock endowments for all the APIs as defined in {@link ALL_APIS}.
102
99
  *
103
100
  * @returns A map of endowments.
104
- */
105
- const generateMockEndowments = () => {
106
- return exports.ALL_APIS.reduce((acc, cur) => ({ ...acc, [cur]: generateMockEndowment(cur) }), { snap: getMockSnapGlobal(), ethereum: getMockEthereumProvider() });
101
+ */ export const generateMockEndowments = ()=>{
102
+ return ALL_APIS.reduce((acc, cur)=>({
103
+ ...acc,
104
+ [cur]: generateMockEndowment(cur)
105
+ }), {
106
+ snap: getMockSnapGlobal(),
107
+ ethereum: getMockEthereumProvider()
108
+ });
107
109
  };
108
- exports.generateMockEndowments = generateMockEndowments;
110
+
109
111
  //# sourceMappingURL=mock.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/mock.ts"],"sourcesContent":["import crypto from 'crypto';\nimport EventEmitter from 'events';\n\nimport { DEFAULT_ENDOWMENTS } from './default-endowments';\n\nconst NETWORK_APIS = ['fetch', 'Request', 'Headers', 'Response'];\n\nexport const ALL_APIS: string[] = [\n ...DEFAULT_ENDOWMENTS,\n ...NETWORK_APIS,\n 'WebAssembly',\n];\n\ntype MockSnapGlobal = {\n request: () => Promise<any>;\n};\n\ntype MockEthereumProvider = EventEmitter & {\n request: () => Promise<any>;\n};\n\n/**\n * Get a mock snap API, that always returns `true` for requests.\n *\n * @returns A mocked snap provider.\n */\nfunction getMockSnapGlobal(): MockSnapGlobal {\n // eslint-disable-next-line @typescript-eslint/require-await\n return { request: async () => true };\n}\n\n/**\n * Get a mock Ethereum provider, that always returns `true` for requests.\n *\n * @returns A mocked ethereum provider.\n */\nfunction getMockEthereumProvider(): MockEthereumProvider {\n const mockProvider = new EventEmitter() as Partial<MockEthereumProvider>;\n // eslint-disable-next-line @typescript-eslint/require-await\n mockProvider.request = async () => true;\n return mockProvider as MockEthereumProvider;\n}\n\n/**\n * Check if a value is a constructor.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a constructor, or `false` otherwise.\n */\nexport const isConstructor = (value: any) =>\n Boolean(typeof value?.prototype?.constructor?.name === 'string');\n\n/**\n * A function that always returns `true`.\n *\n * @returns `true`.\n */\nconst mockFunction = () => true;\nclass MockClass {}\n\nconst handler = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n construct(Target: any, args: any[]): any {\n return new Proxy(new Target(...args), handler);\n },\n get(_target: any, _prop: any) {\n return mockFunction;\n },\n};\n\n/**\n * Generate a mock class for a given value. The value is wrapped in a Proxy, and\n * all methods are replaced with a mock function.\n *\n * @param value - The value to mock.\n * @returns A mock class.\n */\nconst generateMockClass = (value: any) => {\n return new Proxy(value, handler);\n};\n\n// Things not currently auto-mocked because of NodeJS, by adding them here we\n// have types for them and can use that to generate mocks if needed.\nconst mockWindow: Record<string, unknown> = {\n crypto,\n SubtleCrypto: MockClass,\n};\n\n/**\n * Generate a mock endowment for a certain class or function on the `globalThis`\n * object.\n *\n * @param key - The key to generate the mock endowment for.\n * @returns A mocked class or function. If the key is part of the default\n * endowments, the original value is returned.\n */\nconst generateMockEndowment = (key: string) => {\n const globalValue = (globalThis as any)[key];\n\n // Default exposed APIs don't need to be mocked\n if (globalValue && DEFAULT_ENDOWMENTS.includes(key)) {\n return globalValue;\n }\n\n // Fall back to mockWindow for certain APIs not exposed in global in Node.JS\n const globalOrMocked = globalValue ?? mockWindow[key];\n\n const type = typeof globalOrMocked;\n const isFunction = type === 'function';\n if (isFunction && isConstructor(globalOrMocked)) {\n return generateMockClass(globalOrMocked);\n } else if (isFunction || !globalOrMocked) {\n // Fall back to function mock for now\n return mockFunction;\n }\n return globalOrMocked;\n};\n\n/**\n * Generate mock endowments for all the APIs as defined in {@link ALL_APIS}.\n *\n * @returns A map of endowments.\n */\nexport const generateMockEndowments = () => {\n return ALL_APIS.reduce<Record<string, any>>(\n (acc, cur) => ({ ...acc, [cur]: generateMockEndowment(cur) }),\n { snap: getMockSnapGlobal(), ethereum: getMockEthereumProvider() },\n );\n};\n"],"names":["crypto","EventEmitter","DEFAULT_ENDOWMENTS","NETWORK_APIS","ALL_APIS","getMockSnapGlobal","request","getMockEthereumProvider","mockProvider","isConstructor","value","Boolean","prototype","constructor","name","mockFunction","MockClass","handler","construct","Target","args","Proxy","get","_target","_prop","generateMockClass","mockWindow","SubtleCrypto","generateMockEndowment","key","globalValue","globalThis","includes","globalOrMocked","type","isFunction","generateMockEndowments","reduce","acc","cur","snap","ethereum"],"mappings":"AAAA,OAAOA,YAAY,SAAS;AAC5B,OAAOC,kBAAkB,SAAS;AAElC,SAASC,kBAAkB,QAAQ,uBAAuB;AAE1D,MAAMC,eAAe;IAAC;IAAS;IAAW;IAAW;CAAW;AAEhE,OAAO,MAAMC,WAAqB;OAC7BF;OACAC;IACH;CACD,CAAC;AAUF;;;;CAIC,GACD,SAASE;IACP,4DAA4D;IAC5D,OAAO;QAAEC,SAAS,UAAY;IAAK;AACrC;AAEA;;;;CAIC,GACD,SAASC;IACP,MAAMC,eAAe,IAAIP;IACzB,4DAA4D;IAC5DO,aAAaF,OAAO,GAAG,UAAY;IACnC,OAAOE;AACT;AAEA;;;;;CAKC,GACD,OAAO,MAAMC,gBAAgB,CAACC,QAC5BC,QAAQ,OAAOD,OAAOE,WAAWC,aAAaC,SAAS,UAAU;AAEnE;;;;CAIC,GACD,MAAMC,eAAe,IAAM;AAC3B,MAAMC;AAAW;AAEjB,MAAMC,UAAU;IACd,gEAAgE;IAChEC,WAAUC,MAAW,EAAEC,IAAW;QAChC,OAAO,IAAIC,MAAM,IAAIF,UAAUC,OAAOH;IACxC;IACAK,KAAIC,OAAY,EAAEC,KAAU;QAC1B,OAAOT;IACT;AACF;AAEA;;;;;;CAMC,GACD,MAAMU,oBAAoB,CAACf;IACzB,OAAO,IAAIW,MAAMX,OAAOO;AAC1B;AAEA,6EAA6E;AAC7E,oEAAoE;AACpE,MAAMS,aAAsC;IAC1C1B;IACA2B,cAAcX;AAChB;AAEA;;;;;;;CAOC,GACD,MAAMY,wBAAwB,CAACC;IAC7B,MAAMC,cAAc,AAACC,UAAkB,CAACF,IAAI;IAE5C,+CAA+C;IAC/C,IAAIC,eAAe5B,mBAAmB8B,QAAQ,CAACH,MAAM;QACnD,OAAOC;IACT;IAEA,4EAA4E;IAC5E,MAAMG,iBAAiBH,eAAeJ,UAAU,CAACG,IAAI;IAErD,MAAMK,OAAO,OAAOD;IACpB,MAAME,aAAaD,SAAS;IAC5B,IAAIC,cAAc1B,cAAcwB,iBAAiB;QAC/C,OAAOR,kBAAkBQ;IAC3B,OAAO,IAAIE,cAAc,CAACF,gBAAgB;QACxC,qCAAqC;QACrC,OAAOlB;IACT;IACA,OAAOkB;AACT;AAEA;;;;CAIC,GACD,OAAO,MAAMG,yBAAyB;IACpC,OAAOhC,SAASiC,MAAM,CACpB,CAACC,KAAKC,MAAS,CAAA;YAAE,GAAGD,GAAG;YAAE,CAACC,IAAI,EAAEX,sBAAsBW;QAAK,CAAA,GAC3D;QAAEC,MAAMnC;QAAqBoC,UAAUlC;IAA0B;AAErE,EAAE"}
@@ -0,0 +1,112 @@
1
+ import { array, is, object, optional, pattern, size, string } from 'superstruct';
2
+ export const CHAIN_ID_REGEX = RegExp("^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$", "u");
3
+ export const ACCOUNT_ID_REGEX = RegExp("^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$", "u");
4
+ export const ACCOUNT_ADDRESS_REGEX = RegExp("^(?<accountAddress>[a-zA-Z0-9]{1,64})$", "u");
5
+ /**
6
+ * Parse a chain ID string to an object containing the namespace and reference.
7
+ * This validates the chain ID before parsing it.
8
+ *
9
+ * @param chainId - The chain ID to validate and parse.
10
+ * @returns The parsed chain ID.
11
+ */ export function parseChainId(chainId) {
12
+ const match = CHAIN_ID_REGEX.exec(chainId);
13
+ if (!match?.groups) {
14
+ throw new Error('Invalid chain ID.');
15
+ }
16
+ return {
17
+ namespace: match.groups.namespace,
18
+ reference: match.groups.reference
19
+ };
20
+ }
21
+ /**
22
+ * Parse an account ID to an object containing the chain, chain ID and address.
23
+ * This validates the account ID before parsing it.
24
+ *
25
+ * @param accountId - The account ID to validate and parse.
26
+ * @returns The parsed account ID.
27
+ */ export function parseAccountId(accountId) {
28
+ const match = ACCOUNT_ID_REGEX.exec(accountId);
29
+ if (!match?.groups) {
30
+ throw new Error('Invalid account ID.');
31
+ }
32
+ return {
33
+ address: match.groups.accountAddress,
34
+ chainId: match.groups.chainId,
35
+ chain: {
36
+ namespace: match.groups.namespace,
37
+ reference: match.groups.reference
38
+ }
39
+ };
40
+ }
41
+ /**
42
+ * A helper struct for a string with a minimum length of 1 and a maximum length
43
+ * of 40.
44
+ */ export const LimitedString = size(string(), 1, 40);
45
+ /**
46
+ * A CAIP-2 chain ID, i.e., a human-readable namespace and reference.
47
+ */ export const ChainIdStruct = pattern(string(), CHAIN_ID_REGEX);
48
+ export const AccountIdStruct = pattern(string(), ACCOUNT_ID_REGEX);
49
+ export const AccountIdArrayStruct = array(AccountIdStruct);
50
+ export const AccountAddressStruct = pattern(string(), ACCOUNT_ADDRESS_REGEX);
51
+ /**
52
+ * A chain descriptor.
53
+ */ export const ChainStruct = object({
54
+ id: ChainIdStruct,
55
+ name: LimitedString
56
+ });
57
+ export const NamespaceStruct = object({
58
+ /**
59
+ * A list of supported chains in the namespace.
60
+ */ chains: array(ChainStruct),
61
+ /**
62
+ * A list of supported RPC methods on the namespace, that a DApp can call.
63
+ */ methods: optional(array(LimitedString)),
64
+ /**
65
+ * A list of supported RPC events on the namespace, that a DApp can listen to.
66
+ */ events: optional(array(LimitedString))
67
+ });
68
+ /**
69
+ * A CAIP-2 namespace, i.e., the first part of a chain ID.
70
+ */ export const NamespaceIdStruct = pattern(string(), /^[-a-z0-9]{3,8}$/u);
71
+ /**
72
+ * Check if the given value is a CAIP-2 namespace ID.
73
+ *
74
+ * @param value - The value to check.
75
+ * @returns Whether the value is a CAIP-2 namespace ID.
76
+ */ export function isNamespaceId(value) {
77
+ return is(value, NamespaceIdStruct);
78
+ }
79
+ /**
80
+ * Check if the given value is a CAIP-2 chain ID.
81
+ *
82
+ * @param value - The value to check.
83
+ * @returns Whether the value is a CAIP-2 chain ID.
84
+ */ export function isChainId(value) {
85
+ return is(value, ChainIdStruct);
86
+ }
87
+ /**
88
+ * Check if the given value is a CAIP-10 account ID.
89
+ *
90
+ * @param value - The value to check.
91
+ * @returns Whether the value is a CAIP-10 account ID.
92
+ */ export function isAccountId(value) {
93
+ return is(value, AccountIdStruct);
94
+ }
95
+ /**
96
+ * Check if the given value is an array of CAIP-10 account IDs.
97
+ *
98
+ * @param value - The value to check.
99
+ * @returns Whether the value is an array of CAIP-10 account IDs.
100
+ */ export function isAccountIdArray(value) {
101
+ return is(value, AccountIdArrayStruct);
102
+ }
103
+ /**
104
+ * Check if a value is a {@link Namespace}.
105
+ *
106
+ * @param value - The value to validate.
107
+ * @returns True if the value is a valid {@link Namespace}.
108
+ */ export function isNamespace(value) {
109
+ return is(value, NamespaceStruct);
110
+ }
111
+
112
+ //# sourceMappingURL=namespace.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/namespace.ts"],"sourcesContent":["import type { Infer } from 'superstruct';\nimport {\n array,\n is,\n object,\n optional,\n pattern,\n size,\n string,\n} from 'superstruct';\n\nexport const CHAIN_ID_REGEX =\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u;\n\nexport const ACCOUNT_ID_REGEX =\n /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;\n\nexport const ACCOUNT_ADDRESS_REGEX = /^(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;\n\n/**\n * Parse a chain ID string to an object containing the namespace and reference.\n * This validates the chain ID before parsing it.\n *\n * @param chainId - The chain ID to validate and parse.\n * @returns The parsed chain ID.\n */\nexport function parseChainId(chainId: ChainId): {\n namespace: NamespaceId;\n reference: string;\n} {\n const match = CHAIN_ID_REGEX.exec(chainId);\n if (!match?.groups) {\n throw new Error('Invalid chain ID.');\n }\n\n return {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n };\n}\n\n/**\n * Parse an account ID to an object containing the chain, chain ID and address.\n * This validates the account ID before parsing it.\n *\n * @param accountId - The account ID to validate and parse.\n * @returns The parsed account ID.\n */\nexport function parseAccountId(accountId: AccountId): {\n chain: { namespace: NamespaceId; reference: string };\n chainId: ChainId;\n address: string;\n} {\n const match = ACCOUNT_ID_REGEX.exec(accountId);\n if (!match?.groups) {\n throw new Error('Invalid account ID.');\n }\n\n return {\n address: match.groups.accountAddress,\n chainId: match.groups.chainId as ChainId,\n chain: {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n },\n };\n}\n\n/**\n * A helper struct for a string with a minimum length of 1 and a maximum length\n * of 40.\n */\nexport const LimitedString = size(string(), 1, 40);\n\n/**\n * A CAIP-2 chain ID, i.e., a human-readable namespace and reference.\n */\nexport const ChainIdStruct = pattern(string(), CHAIN_ID_REGEX);\nexport type ChainId = `${string}:${string}`;\nexport type Caip2ChainId = Infer<typeof ChainIdStruct>;\n\nexport const AccountIdStruct = pattern(string(), ACCOUNT_ID_REGEX);\nexport type AccountId = `${ChainId}:${string}`;\n\nexport const AccountIdArrayStruct = array(AccountIdStruct);\nexport const AccountAddressStruct = pattern(string(), ACCOUNT_ADDRESS_REGEX);\nexport type AccountAddress = Infer<typeof AccountAddressStruct>;\n\n/**\n * A chain descriptor.\n */\nexport const ChainStruct = object({\n id: ChainIdStruct,\n name: LimitedString,\n});\nexport type Chain = Infer<typeof ChainStruct>;\n\nexport const NamespaceStruct = object({\n /**\n * A list of supported chains in the namespace.\n */\n chains: array(ChainStruct),\n\n /**\n * A list of supported RPC methods on the namespace, that a DApp can call.\n */\n methods: optional(array(LimitedString)),\n\n /**\n * A list of supported RPC events on the namespace, that a DApp can listen to.\n */\n events: optional(array(LimitedString)),\n});\nexport type Namespace = Infer<typeof NamespaceStruct>;\n\n/**\n * A CAIP-2 namespace, i.e., the first part of a chain ID.\n */\nexport const NamespaceIdStruct = pattern(string(), /^[-a-z0-9]{3,8}$/u);\nexport type NamespaceId = Infer<typeof NamespaceIdStruct>;\n\n/**\n * Check if the given value is a CAIP-2 namespace ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 namespace ID.\n */\nexport function isNamespaceId(value: unknown): value is NamespaceId {\n return is(value, NamespaceIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-2 chain ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 chain ID.\n */\nexport function isChainId(value: unknown): value is ChainId {\n return is(value, ChainIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-10 account ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-10 account ID.\n */\nexport function isAccountId(value: unknown): value is AccountId {\n return is(value, AccountIdStruct);\n}\n\n/**\n * Check if the given value is an array of CAIP-10 account IDs.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of CAIP-10 account IDs.\n */\nexport function isAccountIdArray(value: unknown): value is AccountId[] {\n return is(value, AccountIdArrayStruct);\n}\n\n/**\n * Check if a value is a {@link Namespace}.\n *\n * @param value - The value to validate.\n * @returns True if the value is a valid {@link Namespace}.\n */\nexport function isNamespace(value: unknown): value is Namespace {\n return is(value, NamespaceStruct);\n}\n"],"names":["array","is","object","optional","pattern","size","string","CHAIN_ID_REGEX","ACCOUNT_ID_REGEX","ACCOUNT_ADDRESS_REGEX","parseChainId","chainId","match","exec","groups","Error","namespace","reference","parseAccountId","accountId","address","accountAddress","chain","LimitedString","ChainIdStruct","AccountIdStruct","AccountIdArrayStruct","AccountAddressStruct","ChainStruct","id","name","NamespaceStruct","chains","methods","events","NamespaceIdStruct","isNamespaceId","value","isChainId","isAccountId","isAccountIdArray","isNamespace"],"mappings":"AACA,SACEA,KAAK,EACLC,EAAE,EACFC,MAAM,EACNC,QAAQ,EACRC,OAAO,EACPC,IAAI,EACJC,MAAM,QACD,cAAc;AAErB,OAAO,MAAMC,iBACX,+EAAmE;AAErE,OAAO,MAAMC,mBACX,gIAAoH;AAEtH,OAAO,MAAMC,wBAAwB,sDAA0C;AAE/E;;;;;;CAMC,GACD,OAAO,SAASC,aAAaC,OAAgB;IAI3C,MAAMC,QAAQL,eAAeM,IAAI,CAACF;IAClC,IAAI,CAACC,OAAOE,QAAQ;QAClB,MAAM,IAAIC,MAAM;IAClB;IAEA,OAAO;QACLC,WAAWJ,MAAME,MAAM,CAACE,SAAS;QACjCC,WAAWL,MAAME,MAAM,CAACG,SAAS;IACnC;AACF;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,eAAeC,SAAoB;IAKjD,MAAMP,QAAQJ,iBAAiBK,IAAI,CAACM;IACpC,IAAI,CAACP,OAAOE,QAAQ;QAClB,MAAM,IAAIC,MAAM;IAClB;IAEA,OAAO;QACLK,SAASR,MAAME,MAAM,CAACO,cAAc;QACpCV,SAASC,MAAME,MAAM,CAACH,OAAO;QAC7BW,OAAO;YACLN,WAAWJ,MAAME,MAAM,CAACE,SAAS;YACjCC,WAAWL,MAAME,MAAM,CAACG,SAAS;QACnC;IACF;AACF;AAEA;;;CAGC,GACD,OAAO,MAAMM,gBAAgBlB,KAAKC,UAAU,GAAG,IAAI;AAEnD;;CAEC,GACD,OAAO,MAAMkB,gBAAgBpB,QAAQE,UAAUC,gBAAgB;AAI/D,OAAO,MAAMkB,kBAAkBrB,QAAQE,UAAUE,kBAAkB;AAGnE,OAAO,MAAMkB,uBAAuB1B,MAAMyB,iBAAiB;AAC3D,OAAO,MAAME,uBAAuBvB,QAAQE,UAAUG,uBAAuB;AAG7E;;CAEC,GACD,OAAO,MAAMmB,cAAc1B,OAAO;IAChC2B,IAAIL;IACJM,MAAMP;AACR,GAAG;AAGH,OAAO,MAAMQ,kBAAkB7B,OAAO;IACpC;;GAEC,GACD8B,QAAQhC,MAAM4B;IAEd;;GAEC,GACDK,SAAS9B,SAASH,MAAMuB;IAExB;;GAEC,GACDW,QAAQ/B,SAASH,MAAMuB;AACzB,GAAG;AAGH;;CAEC,GACD,OAAO,MAAMY,oBAAoB/B,QAAQE,UAAU,qBAAqB;AAGxE;;;;;CAKC,GACD,OAAO,SAAS8B,cAAcC,KAAc;IAC1C,OAAOpC,GAAGoC,OAAOF;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASG,UAAUD,KAAc;IACtC,OAAOpC,GAAGoC,OAAOb;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASe,YAAYF,KAAc;IACxC,OAAOpC,GAAGoC,OAAOZ;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASe,iBAAiBH,KAAc;IAC7C,OAAOpC,GAAGoC,OAAOX;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASe,YAAYJ,KAAc;IACxC,OAAOpC,GAAGoC,OAAON;AACnB"}
@@ -0,0 +1,70 @@
1
+ import { assertIsSnapIcon } from './icon';
2
+ import { validateNpmSnapManifest } from './manifest/manifest';
3
+ import { assertIsSnapManifest } from './manifest/validation';
4
+ import { assertIsNpmSnapPackageJson, NpmSnapFileNames } from './types';
5
+ export const EXPECTED_SNAP_FILES = [
6
+ 'manifest',
7
+ 'packageJson',
8
+ 'sourceCode'
9
+ ];
10
+ export const SnapFileNameFromKey = {
11
+ manifest: NpmSnapFileNames.Manifest,
12
+ packageJson: NpmSnapFileNames.PackageJson,
13
+ sourceCode: 'source code bundle'
14
+ };
15
+ // TODO: Refactor this to be more shared with other validation.
16
+ /**
17
+ * Validates the files extracted from an npm Snap package tarball by ensuring
18
+ * that they're non-empty and that the Json files match their respective schemas
19
+ * and the Snaps publishing specification.
20
+ *
21
+ * @param snapFiles - The object containing the expected Snap file contents,
22
+ * if any.
23
+ * @param errorPrefix - The prefix of the error message.
24
+ * @returns A tuple of the Snap manifest object and the Snap source code.
25
+ */ export function validateNpmSnap(snapFiles, errorPrefix) {
26
+ EXPECTED_SNAP_FILES.forEach((key)=>{
27
+ if (!snapFiles[key]) {
28
+ throw new Error(`${errorPrefix ?? ''}Missing file "${SnapFileNameFromKey[key]}".`);
29
+ }
30
+ });
31
+ // Typecast: We are assured that the required files exist if we get here.
32
+ const { manifest, packageJson, sourceCode, svgIcon } = snapFiles;
33
+ try {
34
+ assertIsSnapManifest(manifest.result);
35
+ } catch (error) {
36
+ throw new Error(`${errorPrefix ?? ''}${error.message}`);
37
+ }
38
+ const validatedManifest = manifest;
39
+ const { iconPath } = validatedManifest.result.source.location.npm;
40
+ if (iconPath && !svgIcon) {
41
+ throw new Error(`Missing file "${iconPath}".`);
42
+ }
43
+ try {
44
+ assertIsNpmSnapPackageJson(packageJson.result);
45
+ } catch (error) {
46
+ throw new Error(`${errorPrefix ?? ''}${error.message}`);
47
+ }
48
+ const validatedPackageJson = packageJson;
49
+ validateNpmSnapManifest({
50
+ manifest: validatedManifest,
51
+ packageJson: validatedPackageJson,
52
+ sourceCode,
53
+ svgIcon
54
+ });
55
+ if (svgIcon) {
56
+ try {
57
+ assertIsSnapIcon(svgIcon);
58
+ } catch (error) {
59
+ throw new Error(`${errorPrefix ?? ''}${error.message}`);
60
+ }
61
+ }
62
+ return {
63
+ manifest: validatedManifest,
64
+ packageJson: validatedPackageJson,
65
+ sourceCode,
66
+ svgIcon
67
+ };
68
+ }
69
+
70
+ //# sourceMappingURL=npm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/npm.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { validateNpmSnapManifest } from './manifest/manifest';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport type { SnapFiles, UnvalidatedSnapFiles } from './types';\nimport { assertIsNpmSnapPackageJson, NpmSnapFileNames } from './types';\n\nexport const EXPECTED_SNAP_FILES = [\n 'manifest',\n 'packageJson',\n 'sourceCode',\n] as const;\n\nexport const SnapFileNameFromKey = {\n manifest: NpmSnapFileNames.Manifest,\n packageJson: NpmSnapFileNames.PackageJson,\n sourceCode: 'source code bundle',\n} as const;\n\n// TODO: Refactor this to be more shared with other validation.\n\n/**\n * Validates the files extracted from an npm Snap package tarball by ensuring\n * that they're non-empty and that the Json files match their respective schemas\n * and the Snaps publishing specification.\n *\n * @param snapFiles - The object containing the expected Snap file contents,\n * if any.\n * @param errorPrefix - The prefix of the error message.\n * @returns A tuple of the Snap manifest object and the Snap source code.\n */\nexport function validateNpmSnap(\n snapFiles: UnvalidatedSnapFiles,\n errorPrefix?: `${string}: `,\n): SnapFiles {\n EXPECTED_SNAP_FILES.forEach((key) => {\n if (!snapFiles[key]) {\n throw new Error(\n `${errorPrefix ?? ''}Missing file \"${SnapFileNameFromKey[key]}\".`,\n );\n }\n });\n\n // Typecast: We are assured that the required files exist if we get here.\n const { manifest, packageJson, sourceCode, svgIcon } = snapFiles as SnapFiles;\n try {\n assertIsSnapManifest(manifest.result);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n const validatedManifest = manifest;\n\n const { iconPath } = validatedManifest.result.source.location.npm;\n if (iconPath && !svgIcon) {\n throw new Error(`Missing file \"${iconPath}\".`);\n }\n\n try {\n assertIsNpmSnapPackageJson(packageJson.result);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n const validatedPackageJson = packageJson;\n\n validateNpmSnapManifest({\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n });\n\n if (svgIcon) {\n try {\n assertIsSnapIcon(svgIcon);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n }\n\n return {\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n };\n}\n"],"names":["assertIsSnapIcon","validateNpmSnapManifest","assertIsSnapManifest","assertIsNpmSnapPackageJson","NpmSnapFileNames","EXPECTED_SNAP_FILES","SnapFileNameFromKey","manifest","Manifest","packageJson","PackageJson","sourceCode","validateNpmSnap","snapFiles","errorPrefix","forEach","key","Error","svgIcon","result","error","message","validatedManifest","iconPath","source","location","npm","validatedPackageJson"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,SAAS;AAC1C,SAASC,uBAAuB,QAAQ,sBAAsB;AAC9D,SAASC,oBAAoB,QAAQ,wBAAwB;AAE7D,SAASC,0BAA0B,EAAEC,gBAAgB,QAAQ,UAAU;AAEvE,OAAO,MAAMC,sBAAsB;IACjC;IACA;IACA;CACD,CAAU;AAEX,OAAO,MAAMC,sBAAsB;IACjCC,UAAUH,iBAAiBI,QAAQ;IACnCC,aAAaL,iBAAiBM,WAAW;IACzCC,YAAY;AACd,EAAW;AAEX,+DAA+D;AAE/D;;;;;;;;;CASC,GACD,OAAO,SAASC,gBACdC,SAA+B,EAC/BC,WAA2B;IAE3BT,oBAAoBU,OAAO,CAAC,CAACC;QAC3B,IAAI,CAACH,SAAS,CAACG,IAAI,EAAE;YACnB,MAAM,IAAIC,MACR,CAAC,EAAEH,eAAe,GAAG,cAAc,EAAER,mBAAmB,CAACU,IAAI,CAAC,EAAE,CAAC;QAErE;IACF;IAEA,yEAAyE;IACzE,MAAM,EAAET,QAAQ,EAAEE,WAAW,EAAEE,UAAU,EAAEO,OAAO,EAAE,GAAGL;IACvD,IAAI;QACFX,qBAAqBK,SAASY,MAAM;IACtC,EAAE,OAAOC,OAAO;QACd,MAAM,IAAIH,MAAM,CAAC,EAAEH,eAAe,GAAG,EAAEM,MAAMC,OAAO,CAAC,CAAC;IACxD;IACA,MAAMC,oBAAoBf;IAE1B,MAAM,EAAEgB,QAAQ,EAAE,GAAGD,kBAAkBH,MAAM,CAACK,MAAM,CAACC,QAAQ,CAACC,GAAG;IACjE,IAAIH,YAAY,CAACL,SAAS;QACxB,MAAM,IAAID,MAAM,CAAC,cAAc,EAAEM,SAAS,EAAE,CAAC;IAC/C;IAEA,IAAI;QACFpB,2BAA2BM,YAAYU,MAAM;IAC/C,EAAE,OAAOC,OAAO;QACd,MAAM,IAAIH,MAAM,CAAC,EAAEH,eAAe,GAAG,EAAEM,MAAMC,OAAO,CAAC,CAAC;IACxD;IACA,MAAMM,uBAAuBlB;IAE7BR,wBAAwB;QACtBM,UAAUe;QACVb,aAAakB;QACbhB;QACAO;IACF;IAEA,IAAIA,SAAS;QACX,IAAI;YACFlB,iBAAiBkB;QACnB,EAAE,OAAOE,OAAO;YACd,MAAM,IAAIH,MAAM,CAAC,EAAEH,eAAe,GAAG,EAAEM,MAAMC,OAAO,CAAC,CAAC;QACxD;IACF;IAEA,OAAO;QACLd,UAAUe;QACVb,aAAakB;QACbhB;QACAO;IACF;AACF"}
@@ -0,0 +1,17 @@
1
+ import { assert } from '@metamask/utils';
2
+ /**
3
+ * Normalizes relative paths by optionally removing `./` prefix.
4
+ *
5
+ * @param path - Path to make normalize.
6
+ * @returns The same path, with `./` prefix remove.
7
+ */ // TODO(ritave): Include NodeJS path polyfill and use path.normalize as well
8
+ export function normalizeRelative(path) {
9
+ assert(!path.startsWith('/'));
10
+ assert(path.search(/:|\/\//u) === -1, `Path "${path}" potentially an URI instead of local relative`);
11
+ if (path.startsWith('./')) {
12
+ return path.slice(2);
13
+ }
14
+ return path;
15
+ }
16
+
17
+ //# sourceMappingURL=path.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/path.ts"],"sourcesContent":["import { assert } from '@metamask/utils';\n\n/**\n * Normalizes relative paths by optionally removing `./` prefix.\n *\n * @param path - Path to make normalize.\n * @returns The same path, with `./` prefix remove.\n */\n// TODO(ritave): Include NodeJS path polyfill and use path.normalize as well\nexport function normalizeRelative(path: string): string {\n assert(!path.startsWith('/'));\n assert(\n path.search(/:|\\/\\//u) === -1,\n `Path \"${path}\" potentially an URI instead of local relative`,\n );\n\n if (path.startsWith('./')) {\n return path.slice(2);\n }\n return path;\n}\n"],"names":["assert","normalizeRelative","path","startsWith","search","slice"],"mappings":"AAAA,SAASA,MAAM,QAAQ,kBAAkB;AAEzC;;;;;CAKC,GACD,4EAA4E;AAC5E,OAAO,SAASC,kBAAkBC,IAAY;IAC5CF,OAAO,CAACE,KAAKC,UAAU,CAAC;IACxBH,OACEE,KAAKE,MAAM,CAAC,eAAe,CAAC,GAC5B,CAAC,MAAM,EAAEF,KAAK,8CAA8C,CAAC;IAG/D,IAAIA,KAAKC,UAAU,CAAC,OAAO;QACzB,OAAOD,KAAKG,KAAK,CAAC;IACpB;IACA,OAAOH;AACT"}