@metamask/snaps-utils 0.38.0-flask.1 → 1.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 +222 -11
  2. package/dist/{esm/array.js → array.js} +7 -3
  3. package/dist/array.js.map +1 -0
  4. package/dist/{types/caveats.d.ts → caveats.d.ts} +4 -0
  5. package/dist/caveats.js +35 -0
  6. package/dist/caveats.js.map +1 -0
  7. package/dist/checksum.js +42 -0
  8. package/dist/checksum.js.map +1 -0
  9. package/dist/{types/cronjob.d.ts → cronjob.d.ts} +1 -1
  10. package/dist/cronjob.js +71 -0
  11. package/dist/cronjob.js.map +1 -0
  12. package/dist/deep-clone.js +9 -0
  13. package/dist/deep-clone.js.map +1 -0
  14. package/dist/{esm/default-endowments.js → default-endowments.js} +6 -3
  15. package/dist/default-endowments.js.map +1 -0
  16. package/dist/entropy.js +8 -0
  17. package/dist/entropy.js.map +1 -0
  18. package/dist/{cjs/eval-worker.js → eval-worker.js} +21 -22
  19. package/dist/eval-worker.js.map +1 -0
  20. package/dist/{types/eval.d.ts → eval.d.ts} +1 -9
  21. package/dist/eval.js +27 -0
  22. package/dist/eval.js.map +1 -0
  23. package/dist/{types/fs.d.ts → fs.d.ts} +2 -2
  24. package/dist/{esm/fs.js → fs.js} +56 -33
  25. package/dist/fs.js.map +1 -0
  26. package/dist/handlers.d.ts +105 -0
  27. package/dist/handlers.js +3 -0
  28. package/dist/handlers.js.map +1 -0
  29. package/dist/{types/iframe.d.ts → iframe.d.ts} +2 -3
  30. package/dist/{esm/iframe.js → iframe.js} +18 -16
  31. package/dist/iframe.js.map +1 -0
  32. package/dist/iframe.test.browser.js +15 -0
  33. package/dist/iframe.test.browser.js.map +1 -0
  34. package/dist/{types/index.browser.d.ts → index.browser.d.ts} +1 -5
  35. package/dist/index.browser.js +37 -0
  36. package/dist/index.browser.js.map +1 -0
  37. package/dist/{types/index.d.ts → index.d.ts} +1 -5
  38. package/dist/index.executionenv.js +22 -0
  39. package/dist/index.executionenv.js.map +1 -0
  40. package/dist/index.js +42 -0
  41. package/dist/index.js.map +1 -0
  42. package/dist/{types/json-rpc.d.ts → json-rpc.d.ts} +2 -2
  43. package/dist/json-rpc.js +46 -0
  44. package/dist/json-rpc.js.map +1 -0
  45. package/dist/json.d.ts +9 -0
  46. package/dist/json.js +18 -0
  47. package/dist/json.js.map +1 -0
  48. package/dist/{esm/logging.js → logging.js} +14 -6
  49. package/dist/logging.js.map +1 -0
  50. package/dist/manifest/index.browser.js +18 -0
  51. package/dist/manifest/index.browser.js.map +1 -0
  52. package/dist/manifest/index.js +19 -0
  53. package/dist/manifest/index.js.map +1 -0
  54. package/dist/{types/manifest → manifest}/manifest.d.ts +4 -6
  55. package/dist/{esm/manifest → manifest}/manifest.js +115 -101
  56. package/dist/manifest/manifest.js.map +1 -0
  57. package/dist/{types/manifest → manifest}/validation.d.ts +76 -34
  58. package/dist/manifest/validation.js +141 -0
  59. package/dist/manifest/validation.js.map +1 -0
  60. package/dist/{esm/mock.js → mock.js} +40 -42
  61. package/dist/mock.js.map +1 -0
  62. package/dist/namespace.d.ts +275 -0
  63. package/dist/namespace.js +225 -0
  64. package/dist/namespace.js.map +1 -0
  65. package/dist/notification.d.ts +66 -0
  66. package/dist/notification.js +58 -0
  67. package/dist/notification.js.map +1 -0
  68. package/dist/{types/npm.d.ts → npm.d.ts} +3 -2
  69. package/dist/npm.js +74 -0
  70. package/dist/npm.js.map +1 -0
  71. package/dist/path.js +21 -0
  72. package/dist/path.js.map +1 -0
  73. package/dist/{esm/post-process.js → post-process.js} +99 -110
  74. package/dist/post-process.js.map +1 -0
  75. package/dist/{types/snaps.d.ts → snaps.d.ts} +9 -17
  76. package/dist/snaps.js +202 -0
  77. package/dist/snaps.js.map +1 -0
  78. package/dist/{types/types.d.ts → types.d.ts} +22 -15
  79. package/dist/types.js +103 -0
  80. package/dist/types.js.map +1 -0
  81. package/dist/{types/versions.d.ts → versions.d.ts} +1 -1
  82. package/dist/{esm/versions.js → versions.js} +18 -15
  83. package/dist/versions.js.map +1 -0
  84. package/dist/{esm/virtual-file → virtual-file}/VirtualFile.js +33 -47
  85. package/dist/virtual-file/VirtualFile.js.map +1 -0
  86. package/dist/virtual-file/index.browser.js +18 -0
  87. package/dist/virtual-file/index.browser.js.map +1 -0
  88. package/dist/virtual-file/index.js +19 -0
  89. package/dist/virtual-file/index.js.map +1 -0
  90. package/dist/virtual-file/toVirtualFile.js +30 -0
  91. package/dist/virtual-file/toVirtualFile.js.map +1 -0
  92. package/package.json +40 -59
  93. package/dist/cjs/array.js +0 -23
  94. package/dist/cjs/array.js.map +0 -1
  95. package/dist/cjs/caveats.js +0 -33
  96. package/dist/cjs/caveats.js.map +0 -1
  97. package/dist/cjs/checksum.js +0 -38
  98. package/dist/cjs/checksum.js.map +0 -1
  99. package/dist/cjs/cronjob.js +0 -84
  100. package/dist/cjs/cronjob.js.map +0 -1
  101. package/dist/cjs/deep-clone.js +0 -22
  102. package/dist/cjs/deep-clone.js.map +0 -1
  103. package/dist/cjs/default-endowments.js +0 -49
  104. package/dist/cjs/default-endowments.js.map +0 -1
  105. package/dist/cjs/entropy.js +0 -23
  106. package/dist/cjs/entropy.js.map +0 -1
  107. package/dist/cjs/enum.js +0 -16
  108. package/dist/cjs/enum.js.map +0 -1
  109. package/dist/cjs/errors.js +0 -19
  110. package/dist/cjs/errors.js.map +0 -1
  111. package/dist/cjs/eval-worker.js.map +0 -1
  112. package/dist/cjs/eval.js +0 -77
  113. package/dist/cjs/eval.js.map +0 -1
  114. package/dist/cjs/fs.js +0 -126
  115. package/dist/cjs/fs.js.map +0 -1
  116. package/dist/cjs/handlers.js +0 -65
  117. package/dist/cjs/handlers.js.map +0 -1
  118. package/dist/cjs/icon.js +0 -37
  119. package/dist/cjs/icon.js.map +0 -1
  120. package/dist/cjs/iframe.js +0 -59
  121. package/dist/cjs/iframe.js.map +0 -1
  122. package/dist/cjs/index.browser.js +0 -43
  123. package/dist/cjs/index.browser.js.map +0 -1
  124. package/dist/cjs/index.executionenv.js +0 -24
  125. package/dist/cjs/index.executionenv.js.map +0 -1
  126. package/dist/cjs/index.js +0 -48
  127. package/dist/cjs/index.js.map +0 -1
  128. package/dist/cjs/json-rpc.js +0 -46
  129. package/dist/cjs/json-rpc.js.map +0 -1
  130. package/dist/cjs/json.js +0 -16
  131. package/dist/cjs/json.js.map +0 -1
  132. package/dist/cjs/logging.js +0 -40
  133. package/dist/cjs/logging.js.map +0 -1
  134. package/dist/cjs/manifest/index.browser.js +0 -20
  135. package/dist/cjs/manifest/index.browser.js.map +0 -1
  136. package/dist/cjs/manifest/index.js +0 -21
  137. package/dist/cjs/manifest/index.js.map +0 -1
  138. package/dist/cjs/manifest/manifest.js +0 -239
  139. package/dist/cjs/manifest/manifest.js.map +0 -1
  140. package/dist/cjs/manifest/validation.js +0 -183
  141. package/dist/cjs/manifest/validation.js.map +0 -1
  142. package/dist/cjs/mock.js +0 -128
  143. package/dist/cjs/mock.js.map +0 -1
  144. package/dist/cjs/namespace.js +0 -124
  145. package/dist/cjs/namespace.js.map +0 -1
  146. package/dist/cjs/npm.js +0 -81
  147. package/dist/cjs/npm.js.map +0 -1
  148. package/dist/cjs/path.js +0 -21
  149. package/dist/cjs/path.js.map +0 -1
  150. package/dist/cjs/post-process.js +0 -328
  151. package/dist/cjs/post-process.js.map +0 -1
  152. package/dist/cjs/snaps.js +0 -230
  153. package/dist/cjs/snaps.js.map +0 -1
  154. package/dist/cjs/strings.js +0 -21
  155. package/dist/cjs/strings.js.map +0 -1
  156. package/dist/cjs/structs.js +0 -163
  157. package/dist/cjs/structs.js.map +0 -1
  158. package/dist/cjs/types.js +0 -109
  159. package/dist/cjs/types.js.map +0 -1
  160. package/dist/cjs/validation.js +0 -22
  161. package/dist/cjs/validation.js.map +0 -1
  162. package/dist/cjs/versions.js +0 -47
  163. package/dist/cjs/versions.js.map +0 -1
  164. package/dist/cjs/virtual-file/VirtualFile.js +0 -85
  165. package/dist/cjs/virtual-file/VirtualFile.js.map +0 -1
  166. package/dist/cjs/virtual-file/index.browser.js +0 -20
  167. package/dist/cjs/virtual-file/index.browser.js.map +0 -1
  168. package/dist/cjs/virtual-file/index.js +0 -21
  169. package/dist/cjs/virtual-file/index.js.map +0 -1
  170. package/dist/cjs/virtual-file/toVirtualFile.js +0 -33
  171. package/dist/cjs/virtual-file/toVirtualFile.js.map +0 -1
  172. package/dist/esm/array.js.map +0 -1
  173. package/dist/esm/caveats.js +0 -23
  174. package/dist/esm/caveats.js.map +0 -1
  175. package/dist/esm/checksum.js +0 -36
  176. package/dist/esm/checksum.js.map +0 -1
  177. package/dist/esm/cronjob.js +0 -66
  178. package/dist/esm/cronjob.js.map +0 -1
  179. package/dist/esm/deep-clone.js +0 -7
  180. package/dist/esm/deep-clone.js.map +0 -1
  181. package/dist/esm/default-endowments.js.map +0 -1
  182. package/dist/esm/entropy.js +0 -6
  183. package/dist/esm/entropy.js.map +0 -1
  184. package/dist/esm/enum.js +0 -12
  185. package/dist/esm/enum.js.map +0 -1
  186. package/dist/esm/errors.js +0 -17
  187. package/dist/esm/errors.js.map +0 -1
  188. package/dist/esm/eval-worker.js +0 -47
  189. package/dist/esm/eval-worker.js.map +0 -1
  190. package/dist/esm/eval.js +0 -65
  191. package/dist/esm/eval.js.map +0 -1
  192. package/dist/esm/fs.js.map +0 -1
  193. package/dist/esm/handlers.js +0 -47
  194. package/dist/esm/handlers.js.map +0 -1
  195. package/dist/esm/icon.js +0 -11
  196. package/dist/esm/icon.js.map +0 -1
  197. package/dist/esm/iframe.js.map +0 -1
  198. package/dist/esm/index.browser.js +0 -26
  199. package/dist/esm/index.browser.js.map +0 -1
  200. package/dist/esm/index.executionenv.js +0 -7
  201. package/dist/esm/index.executionenv.js.map +0 -1
  202. package/dist/esm/index.js +0 -31
  203. package/dist/esm/index.js.map +0 -1
  204. package/dist/esm/json-rpc.js +0 -39
  205. package/dist/esm/json-rpc.js.map +0 -1
  206. package/dist/esm/json.js +0 -17
  207. package/dist/esm/json.js.map +0 -1
  208. package/dist/esm/logging.js.map +0 -1
  209. package/dist/esm/manifest/index.browser.js +0 -3
  210. package/dist/esm/manifest/index.browser.js.map +0 -1
  211. package/dist/esm/manifest/index.js +0 -4
  212. package/dist/esm/manifest/index.js.map +0 -1
  213. package/dist/esm/manifest/manifest.js.map +0 -1
  214. package/dist/esm/manifest/validation.js +0 -152
  215. package/dist/esm/manifest/validation.js.map +0 -1
  216. package/dist/esm/mock.js.map +0 -1
  217. package/dist/esm/namespace.js +0 -110
  218. package/dist/esm/namespace.js.map +0 -1
  219. package/dist/esm/npm.js +0 -70
  220. package/dist/esm/npm.js.map +0 -1
  221. package/dist/esm/path.js +0 -17
  222. package/dist/esm/path.js.map +0 -1
  223. package/dist/esm/post-process.js.map +0 -1
  224. package/dist/esm/snaps.js +0 -215
  225. package/dist/esm/snaps.js.map +0 -1
  226. package/dist/esm/strings.js +0 -11
  227. package/dist/esm/strings.js.map +0 -1
  228. package/dist/esm/structs.js +0 -230
  229. package/dist/esm/structs.js.map +0 -1
  230. package/dist/esm/types.js +0 -80
  231. package/dist/esm/types.js.map +0 -1
  232. package/dist/esm/validation.js +0 -17
  233. package/dist/esm/validation.js.map +0 -1
  234. package/dist/esm/versions.js.map +0 -1
  235. package/dist/esm/virtual-file/VirtualFile.js.map +0 -1
  236. package/dist/esm/virtual-file/index.browser.js +0 -3
  237. package/dist/esm/virtual-file/index.browser.js.map +0 -1
  238. package/dist/esm/virtual-file/index.js +0 -4
  239. package/dist/esm/virtual-file/index.js.map +0 -1
  240. package/dist/esm/virtual-file/toVirtualFile.js +0 -26
  241. package/dist/esm/virtual-file/toVirtualFile.js.map +0 -1
  242. package/dist/types/enum.d.ts +0 -30
  243. package/dist/types/errors.d.ts +0 -10
  244. package/dist/types/handlers.d.ts +0 -144
  245. package/dist/types/icon.d.ts +0 -4
  246. package/dist/types/json.d.ts +0 -13
  247. package/dist/types/namespace.d.ts +0 -124
  248. package/dist/types/strings.d.ts +0 -8
  249. package/dist/types/structs.d.ts +0 -158
  250. package/dist/types/validation.d.ts +0 -8
  251. /package/dist/{types/array.d.ts → array.d.ts} +0 -0
  252. /package/dist/{types/checksum.d.ts → checksum.d.ts} +0 -0
  253. /package/dist/{types/deep-clone.d.ts → deep-clone.d.ts} +0 -0
  254. /package/dist/{types/default-endowments.d.ts → default-endowments.d.ts} +0 -0
  255. /package/dist/{types/entropy.d.ts → entropy.d.ts} +0 -0
  256. /package/dist/{types/eval-worker.d.ts → eval-worker.d.ts} +0 -0
  257. /package/dist/{types/iframe.test.browser.d.ts → iframe.test.browser.d.ts} +0 -0
  258. /package/dist/{types/index.executionenv.d.ts → index.executionenv.d.ts} +0 -0
  259. /package/dist/{types/logging.d.ts → logging.d.ts} +0 -0
  260. /package/dist/{types/manifest → manifest}/index.browser.d.ts +0 -0
  261. /package/dist/{types/manifest → manifest}/index.d.ts +0 -0
  262. /package/dist/{types/mock.d.ts → mock.d.ts} +0 -0
  263. /package/dist/{types/path.d.ts → path.d.ts} +0 -0
  264. /package/dist/{types/post-process.d.ts → post-process.d.ts} +0 -0
  265. /package/dist/{types/virtual-file → virtual-file}/VirtualFile.d.ts +0 -0
  266. /package/dist/{types/virtual-file → virtual-file}/index.browser.d.ts +0 -0
  267. /package/dist/{types/virtual-file → virtual-file}/index.d.ts +0 -0
  268. /package/dist/{types/virtual-file → virtual-file}/toVirtualFile.d.ts +0 -0
@@ -1,328 +0,0 @@
1
- // eslint-disable-next-line @typescript-eslint/no-shadow
2
- "use strict";
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- function _export(target, all) {
7
- for(var name in all)Object.defineProperty(target, name, {
8
- enumerable: true,
9
- get: all[name]
10
- });
11
- }
12
- _export(exports, {
13
- PostProcessWarning: function() {
14
- return PostProcessWarning;
15
- },
16
- postProcessBundle: function() {
17
- return postProcessBundle;
18
- }
19
- });
20
- const _core = require("@babel/core");
21
- const _types = require("@babel/types");
22
- var PostProcessWarning;
23
- (function(PostProcessWarning) {
24
- PostProcessWarning["UnsafeMathRandom"] = '`Math.random` was detected in the bundle. This is not a secure source of randomness.';
25
- })(PostProcessWarning || (PostProcessWarning = {}));
26
- // The RegEx below consists of multiple groups joined by a boolean OR.
27
- // Each part consists of two groups which capture a part of each string
28
- // which needs to be split up, e.g., `<!--` is split into `<!` and `--`.
29
- const TOKEN_REGEX = /(<!)(--)|(--)(>)|(import)(\(.*?\))/gu;
30
- // An empty template element, i.e., a part of a template literal without any
31
- // value ("").
32
- const EMPTY_TEMPLATE_ELEMENT = (0, _types.templateElement)({
33
- raw: '',
34
- cooked: ''
35
- });
36
- const evalWrapper = _core.template.statement(`
37
- (1, REF)(ARGS)
38
- `);
39
- const objectEvalWrapper = _core.template.statement(`
40
- (1, OBJECT.REF)
41
- `);
42
- const regeneratorRuntimeWrapper = _core.template.statement(`
43
- var regeneratorRuntime;
44
- `);
45
- /**
46
- * Breaks up tokens that would otherwise result in SES errors. The tokens are
47
- * broken up in a non-destructive way where possible. Currently works with:
48
- * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,
49
- * `>`.
50
- * - `import(n)` statements, broken up into `import`, `(n)`.
51
- *
52
- * @param value - The string value to break up.
53
- * @returns The string split into an array, in a way that it can be joined
54
- * together to form the same string, but with the tokens separated into single
55
- * array elements.
56
- */ function breakTokens(value) {
57
- const tokens = value.split(TOKEN_REGEX);
58
- return tokens// TODO: The `split` above results in some values being `undefined`.
59
- // There may be a better solution to avoid having to filter those out.
60
- .filter((token)=>token !== '' && token !== undefined);
61
- }
62
- /**
63
- * Breaks up tokens that would otherwise result in SES errors. The tokens are
64
- * broken up in a non-destructive way where possible. Currently works with:
65
- * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,
66
- * `>`.
67
- * - `import(n)` statements, broken up into `import`, `(n)`.
68
- *
69
- * @param value - The string value to break up.
70
- * @returns The string split into a tuple consisting of the new template
71
- * elements and string literal expressions.
72
- */ function breakTokensTemplateLiteral(value) {
73
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
74
- // @ts-ignore `matchAll` is not available in ES2017, but this code
75
- // should only be used in environments where the function is supported.
76
- const matches = Array.from(value.matchAll(TOKEN_REGEX));
77
- if (matches.length > 0) {
78
- const output = matches.reduce(([elements, expressions], rawMatch, index, values)=>{
79
- const [, first, last] = rawMatch.filter((raw)=>raw !== undefined);
80
- // Slice the text in front of the match, which does not need to be
81
- // broken up.
82
- const prefix = value.slice(index === 0 ? 0 : values[index - 1].index + values[index - 1][0].length, rawMatch.index);
83
- return [
84
- [
85
- ...elements,
86
- (0, _types.templateElement)({
87
- raw: getRawTemplateValue(prefix),
88
- cooked: prefix
89
- }),
90
- EMPTY_TEMPLATE_ELEMENT
91
- ],
92
- [
93
- ...expressions,
94
- (0, _types.stringLiteral)(first),
95
- (0, _types.stringLiteral)(last)
96
- ]
97
- ];
98
- }, [
99
- [],
100
- []
101
- ]);
102
- // Add the text after the last match to the output.
103
- const lastMatch = matches[matches.length - 1];
104
- const suffix = value.slice(lastMatch.index + lastMatch[0].length);
105
- return [
106
- [
107
- ...output[0],
108
- (0, _types.templateElement)({
109
- raw: getRawTemplateValue(suffix),
110
- cooked: suffix
111
- })
112
- ],
113
- output[1]
114
- ];
115
- }
116
- // If there are no matches, simply return the original value.
117
- return [
118
- [
119
- (0, _types.templateElement)({
120
- raw: getRawTemplateValue(value),
121
- cooked: value
122
- })
123
- ],
124
- []
125
- ];
126
- }
127
- /**
128
- * Get a raw template literal value from a cooked value. This adds a backslash
129
- * before every '`', '\' and '${' characters.
130
- *
131
- * @see https://github.com/babel/babel/issues/9242#issuecomment-532529613
132
- * @param value - The cooked string to get the raw string for.
133
- * @returns The value as raw value.
134
- */ function getRawTemplateValue(value) {
135
- return value.replace(/\\|`|\$\{/gu, '\\$&');
136
- }
137
- function postProcessBundle(code, { stripComments = true, sourceMap: sourceMaps, inputSourceMap } = {}) {
138
- const warnings = new Set();
139
- const pre = ({ ast })=>{
140
- ast.comments?.forEach((comment)=>{
141
- // Break up tokens that could be parsed as HTML comment terminators. The
142
- // regular expressions below are written strangely so as to avoid the
143
- // appearance of such tokens in our source code. For reference:
144
- // https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md
145
- comment.value = comment.value.replace(new RegExp(`<!${'--'}`, 'gu'), '< !--').replace(new RegExp(`${'--'}>`, 'gu'), '-- >').replace(/import(\(.*\))/gu, 'import\\$1');
146
- });
147
- };
148
- const visitor = {
149
- FunctionExpression (path) {
150
- const { node } = path;
151
- // Browserify provides the `Buffer` global as an argument to modules that
152
- // use it, but this does not work in SES. Since we pass in `Buffer` as an
153
- // endowment, we can simply remove the argument.
154
- //
155
- // Note that this only removes `Buffer` from a wrapped function
156
- // expression, e.g., `(function (Buffer) { ... })`. Regular functions
157
- // are not affected.
158
- //
159
- // TODO: Since we're working on the AST level, we could check the scope
160
- // of the function expression, and possibly prevent false positives?
161
- if (node.type === 'FunctionExpression' && node.extra?.parenthesized) {
162
- node.params = node.params.filter((param)=>!(param.type === 'Identifier' && param.name === 'Buffer'));
163
- }
164
- },
165
- CallExpression (path) {
166
- const { node } = path;
167
- // Replace `eval(foo)` with `(1, eval)(foo)`.
168
- if (node.callee.type === 'Identifier' && node.callee.name === 'eval') {
169
- path.replaceWith(evalWrapper({
170
- REF: node.callee,
171
- ARGS: node.arguments
172
- }));
173
- }
174
- // Detect the use of `Math.random()` and add a warning.
175
- if (node.callee.type === 'MemberExpression' && node.callee.object.type === 'Identifier' && node.callee.object.name === 'Math' && node.callee.property.type === 'Identifier' && node.callee.property.name === 'random') {
176
- warnings.add(PostProcessWarning.UnsafeMathRandom);
177
- }
178
- },
179
- MemberExpression (path) {
180
- const { node } = path;
181
- // Replace `object.eval(foo)` with `(1, object.eval)(foo)`.
182
- if (node.property.type === 'Identifier' && node.property.name === 'eval' && // We only apply this to MemberExpressions that are the callee of CallExpression
183
- path.parent.type === 'CallExpression' && path.parent.callee === node) {
184
- path.replaceWith(objectEvalWrapper({
185
- OBJECT: node.object,
186
- REF: node.property
187
- }));
188
- }
189
- },
190
- Identifier (path) {
191
- const { node } = path;
192
- // Insert `regeneratorRuntime` global if it's used in the code.
193
- if (node.name === 'regeneratorRuntime') {
194
- const program = path.findParent((parent)=>parent.node.type === 'Program');
195
- // We know that `program` is a Program node here, but this keeps
196
- // TypeScript happy.
197
- if (program?.node.type === 'Program') {
198
- const body = program.node.body[0];
199
- // This stops it from inserting `regeneratorRuntime` multiple times.
200
- if (body.type === 'VariableDeclaration' && body.declarations[0].id.name === 'regeneratorRuntime') {
201
- return;
202
- }
203
- program?.node.body.unshift(regeneratorRuntimeWrapper());
204
- }
205
- }
206
- },
207
- TemplateLiteral (path) {
208
- const { node } = path;
209
- // This checks if the template literal was visited before. Without this,
210
- // it would cause an infinite loop resulting in a stack overflow. We can't
211
- // skip the path here, because we need to visit the children of the node.
212
- if (path.getData('visited')) {
213
- return;
214
- }
215
- // Break up tokens that could be parsed as HTML comment terminators, or
216
- // `import()` statements.
217
- // For reference:
218
- // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md
219
- // - https://github.com/MetaMask/snaps-monorepo/issues/505
220
- const [replacementQuasis, replacementExpressions] = node.quasis.reduce(([elements, expressions], quasi, index)=>{
221
- // Note: Template literals have two variants, "cooked" and "raw". Here
222
- // we use the cooked version.
223
- // https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw
224
- const tokens = breakTokensTemplateLiteral(quasi.value.cooked);
225
- // Only update the node if something changed.
226
- if (tokens[0].length <= 1) {
227
- return [
228
- [
229
- ...elements,
230
- quasi
231
- ],
232
- [
233
- ...expressions,
234
- node.expressions[index]
235
- ]
236
- ];
237
- }
238
- return [
239
- [
240
- ...elements,
241
- ...tokens[0]
242
- ],
243
- [
244
- ...expressions,
245
- ...tokens[1],
246
- node.expressions[index]
247
- ]
248
- ];
249
- }, [
250
- [],
251
- []
252
- ]);
253
- path.replaceWith((0, _types.templateLiteral)(replacementQuasis, replacementExpressions.filter((expression)=>expression !== undefined)));
254
- path.setData('visited', true);
255
- },
256
- StringLiteral (path) {
257
- const { node } = path;
258
- // Break up tokens that could be parsed as HTML comment terminators, or
259
- // `import()` statements.
260
- // For reference:
261
- // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md
262
- // - https://github.com/MetaMask/snaps-monorepo/issues/505
263
- const tokens = breakTokens(node.value);
264
- // Only update the node if the string literal was broken up.
265
- if (tokens.length <= 1) {
266
- return;
267
- }
268
- const replacement = tokens.slice(1).reduce((acc, value)=>(0, _types.binaryExpression)('+', acc, (0, _types.stringLiteral)(value)), (0, _types.stringLiteral)(tokens[0]));
269
- path.replaceWith(replacement);
270
- path.skip();
271
- },
272
- BinaryExpression (path) {
273
- const { node } = path;
274
- const errorMessage = 'Using HTML comments (`<!--` and `-->`) as operators is not allowed. The behaviour of ' + 'these comments is ambiguous, and differs per browser and environment. If you want ' + 'to use them as operators, break them up into separate characters, i.e., `a-- > b` ' + 'and `a < ! --b`.';
275
- if (node.operator === '<' && (0, _types.isUnaryExpression)(node.right) && (0, _types.isUpdateExpression)(node.right.argument) && node.right.argument.operator === '--' && node.left.end && node.right.argument.argument.start) {
276
- const expression = code.slice(node.left.end, node.right.argument.argument.start);
277
- if (expression.includes('<!--')) {
278
- throw new Error(errorMessage);
279
- }
280
- }
281
- if (node.operator === '>' && (0, _types.isUpdateExpression)(node.left) && node.left.operator === '--' && node.left.argument.end && node.right.start) {
282
- const expression = code.slice(node.left.argument.end, node.right.start);
283
- if (expression.includes('-->')) {
284
- throw new Error(errorMessage);
285
- }
286
- }
287
- }
288
- };
289
- try {
290
- const file = (0, _core.transformSync)(code, {
291
- // Prevent Babel from searching for a config file.
292
- configFile: false,
293
- parserOpts: {
294
- // Strict mode isn't enabled by default, so we need to enable it here.
295
- strictMode: true,
296
- // If this is disabled, the AST does not include any comments. This is
297
- // useful for performance reasons, and we use it for stripping comments.
298
- attachComment: !stripComments
299
- },
300
- // By default, Babel optimises bundles that exceed 500 KB, but that
301
- // results in characters which look like HTML comments, which breaks SES.
302
- compact: false,
303
- // This configures Babel to generate a new source map from the existing
304
- // source map if specified. If `sourceMap` is `true` but an input source
305
- // map is not provided, a new source map will be generated instead.
306
- inputSourceMap,
307
- sourceMaps,
308
- plugins: [
309
- ()=>({
310
- pre,
311
- visitor
312
- })
313
- ]
314
- });
315
- if (!file?.code) {
316
- throw new Error('Bundled code is empty.');
317
- }
318
- return {
319
- code: file.code,
320
- sourceMap: file.map,
321
- warnings: Array.from(warnings)
322
- };
323
- } catch (error) {
324
- throw new Error(`Failed to post process code:\n${error.message}`);
325
- }
326
- }
327
-
328
- //# sourceMappingURL=post-process.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/post-process.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-shadow\nimport type { Node, Visitor, PluginObj } from '@babel/core';\nimport { transformSync, template } from '@babel/core';\nimport type { Expression, Identifier, TemplateElement } from '@babel/types';\nimport {\n binaryExpression,\n isUnaryExpression,\n isUpdateExpression,\n stringLiteral,\n templateElement,\n templateLiteral,\n} from '@babel/types';\n\n/**\n * Source map declaration taken from `@babel/core`. Babel doesn't export the\n * type for this, so it's copied from the source code instead here.\n */\nexport type SourceMap = {\n version: number;\n sources: string[];\n names: string[];\n sourceRoot?: string | undefined;\n sourcesContent?: string[] | undefined;\n mappings: string;\n file: string;\n};\n\n/**\n * The post process options.\n *\n * @property stripComments - Whether to strip comments. Defaults to `true`.\n * @property sourceMap - Whether to generate a source map for the modified code.\n * See also `inputSourceMap`.\n * @property inputSourceMap - The source map for the input code. When provided,\n * the source map will be used to generate a source map for the modified code.\n * This ensures that the source map is correct for the modified code, and still\n * points to the original source. If not provided, a new source map will be\n * generated instead.\n */\nexport type PostProcessOptions = {\n stripComments?: boolean;\n sourceMap?: boolean | 'inline';\n inputSourceMap?: SourceMap;\n};\n\n/**\n * The post processed bundle output.\n *\n * @property code - The modified code.\n * @property sourceMap - The source map for the modified code, if the source map\n * option was enabled.\n * @property warnings - Any warnings that occurred during the post-processing.\n */\nexport type PostProcessedBundle = {\n code: string;\n sourceMap?: SourceMap | null;\n warnings: PostProcessWarning[];\n};\n\nexport enum PostProcessWarning {\n UnsafeMathRandom = '`Math.random` was detected in the bundle. This is not a secure source of randomness.',\n}\n\n// The RegEx below consists of multiple groups joined by a boolean OR.\n// Each part consists of two groups which capture a part of each string\n// which needs to be split up, e.g., `<!--` is split into `<!` and `--`.\nconst TOKEN_REGEX = /(<!)(--)|(--)(>)|(import)(\\(.*?\\))/gu;\n\n// An empty template element, i.e., a part of a template literal without any\n// value (\"\").\nconst EMPTY_TEMPLATE_ELEMENT = templateElement({ raw: '', cooked: '' });\n\nconst evalWrapper = template.statement(`\n (1, REF)(ARGS)\n`);\n\nconst objectEvalWrapper = template.statement(`\n (1, OBJECT.REF)\n`);\n\nconst regeneratorRuntimeWrapper = template.statement(`\n var regeneratorRuntime;\n`);\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into an array, in a way that it can be joined\n * together to form the same string, but with the tokens separated into single\n * array elements.\n */\nfunction breakTokens(value: string): string[] {\n const tokens = value.split(TOKEN_REGEX);\n return (\n tokens\n // TODO: The `split` above results in some values being `undefined`.\n // There may be a better solution to avoid having to filter those out.\n .filter((token) => token !== '' && token !== undefined)\n );\n}\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into a tuple consisting of the new template\n * elements and string literal expressions.\n */\nfunction breakTokensTemplateLiteral(\n value: string,\n): [TemplateElement[], Expression[]] {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore `matchAll` is not available in ES2017, but this code\n // should only be used in environments where the function is supported.\n const matches: RegExpMatchArray[] = Array.from(value.matchAll(TOKEN_REGEX));\n\n if (matches.length > 0) {\n const output = matches.reduce<[TemplateElement[], Expression[]]>(\n ([elements, expressions], rawMatch, index, values) => {\n const [, first, last] = rawMatch.filter((raw) => raw !== undefined);\n\n // Slice the text in front of the match, which does not need to be\n // broken up.\n const prefix = value.slice(\n index === 0\n ? 0\n : (values[index - 1].index as number) + values[index - 1][0].length,\n rawMatch.index,\n );\n\n return [\n [\n ...elements,\n templateElement({\n raw: getRawTemplateValue(prefix),\n cooked: prefix,\n }),\n EMPTY_TEMPLATE_ELEMENT,\n ],\n [...expressions, stringLiteral(first), stringLiteral(last)],\n ];\n },\n [[], []],\n );\n\n // Add the text after the last match to the output.\n const lastMatch = matches[matches.length - 1];\n const suffix = value.slice(\n (lastMatch.index as number) + lastMatch[0].length,\n );\n\n return [\n [\n ...output[0],\n templateElement({ raw: getRawTemplateValue(suffix), cooked: suffix }),\n ],\n output[1],\n ];\n }\n\n // If there are no matches, simply return the original value.\n return [\n [templateElement({ raw: getRawTemplateValue(value), cooked: value })],\n [],\n ];\n}\n\n/**\n * Get a raw template literal value from a cooked value. This adds a backslash\n * before every '`', '\\' and '${' characters.\n *\n * @see https://github.com/babel/babel/issues/9242#issuecomment-532529613\n * @param value - The cooked string to get the raw string for.\n * @returns The value as raw value.\n */\nfunction getRawTemplateValue(value: string) {\n return value.replace(/\\\\|`|\\$\\{/gu, '\\\\$&');\n}\n\n/**\n * Post process code with AST such that it can be evaluated in SES.\n *\n * Currently:\n * - Makes all direct calls to eval indirect.\n * - Handles certain Babel-related edge cases.\n * - Removes the `Buffer` provided by Browserify.\n * - Optionally removes comments.\n * - Breaks up tokens that would otherwise result in SES errors, such as HTML\n * comment tags `<!--` and `-->` and `import(n)` statements.\n *\n * @param code - The code to post process.\n * @param options - The post-process options.\n * @param options.stripComments - Whether to strip comments. Defaults to `true`.\n * @param options.sourceMap - Whether to generate a source map for the modified\n * code. See also `inputSourceMap`.\n * @param options.inputSourceMap - The source map for the input code. When\n * provided, the source map will be used to generate a source map for the\n * modified code. This ensures that the source map is correct for the modified\n * code, and still points to the original source. If not provided, a new source\n * map will be generated instead.\n * @returns An object containing the modified code, and source map, or null if\n * the provided code is null.\n */\nexport function postProcessBundle(\n code: string,\n {\n stripComments = true,\n sourceMap: sourceMaps,\n inputSourceMap,\n }: Partial<PostProcessOptions> = {},\n): PostProcessedBundle {\n const warnings = new Set<PostProcessWarning>();\n\n const pre: PluginObj['pre'] = ({ ast }) => {\n ast.comments?.forEach((comment) => {\n // Break up tokens that could be parsed as HTML comment terminators. The\n // regular expressions below are written strangely so as to avoid the\n // appearance of such tokens in our source code. For reference:\n // https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n comment.value = comment.value\n .replace(new RegExp(`<!${'--'}`, 'gu'), '< !--')\n .replace(new RegExp(`${'--'}>`, 'gu'), '-- >')\n .replace(/import(\\(.*\\))/gu, 'import\\\\$1');\n });\n };\n\n const visitor: Visitor<Node> = {\n FunctionExpression(path) {\n const { node } = path;\n\n // Browserify provides the `Buffer` global as an argument to modules that\n // use it, but this does not work in SES. Since we pass in `Buffer` as an\n // endowment, we can simply remove the argument.\n //\n // Note that this only removes `Buffer` from a wrapped function\n // expression, e.g., `(function (Buffer) { ... })`. Regular functions\n // are not affected.\n //\n // TODO: Since we're working on the AST level, we could check the scope\n // of the function expression, and possibly prevent false positives?\n if (node.type === 'FunctionExpression' && node.extra?.parenthesized) {\n node.params = node.params.filter(\n (param) => !(param.type === 'Identifier' && param.name === 'Buffer'),\n );\n }\n },\n\n CallExpression(path) {\n const { node } = path;\n\n // Replace `eval(foo)` with `(1, eval)(foo)`.\n if (node.callee.type === 'Identifier' && node.callee.name === 'eval') {\n path.replaceWith(\n evalWrapper({\n REF: node.callee,\n ARGS: node.arguments,\n }),\n );\n }\n\n // Detect the use of `Math.random()` and add a warning.\n if (\n node.callee.type === 'MemberExpression' &&\n node.callee.object.type === 'Identifier' &&\n node.callee.object.name === 'Math' &&\n node.callee.property.type === 'Identifier' &&\n node.callee.property.name === 'random'\n ) {\n warnings.add(PostProcessWarning.UnsafeMathRandom);\n }\n },\n\n MemberExpression(path) {\n const { node } = path;\n\n // Replace `object.eval(foo)` with `(1, object.eval)(foo)`.\n if (\n node.property.type === 'Identifier' &&\n node.property.name === 'eval' &&\n // We only apply this to MemberExpressions that are the callee of CallExpression\n path.parent.type === 'CallExpression' &&\n path.parent.callee === node\n ) {\n path.replaceWith(\n objectEvalWrapper({\n OBJECT: node.object,\n REF: node.property,\n }),\n );\n }\n },\n\n Identifier(path) {\n const { node } = path;\n\n // Insert `regeneratorRuntime` global if it's used in the code.\n if (node.name === 'regeneratorRuntime') {\n const program = path.findParent(\n (parent) => parent.node.type === 'Program',\n );\n\n // We know that `program` is a Program node here, but this keeps\n // TypeScript happy.\n if (program?.node.type === 'Program') {\n const body = program.node.body[0];\n\n // This stops it from inserting `regeneratorRuntime` multiple times.\n if (\n body.type === 'VariableDeclaration' &&\n (body.declarations[0].id as Identifier).name ===\n 'regeneratorRuntime'\n ) {\n return;\n }\n\n program?.node.body.unshift(regeneratorRuntimeWrapper());\n }\n }\n },\n\n TemplateLiteral(path) {\n const { node } = path;\n\n // This checks if the template literal was visited before. Without this,\n // it would cause an infinite loop resulting in a stack overflow. We can't\n // skip the path here, because we need to visit the children of the node.\n if (path.getData('visited')) {\n return;\n }\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const [replacementQuasis, replacementExpressions] = node.quasis.reduce<\n [TemplateElement[], Expression[]]\n >(\n ([elements, expressions], quasi, index) => {\n // Note: Template literals have two variants, \"cooked\" and \"raw\". Here\n // we use the cooked version.\n // https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw\n const tokens = breakTokensTemplateLiteral(\n quasi.value.cooked as string,\n );\n\n // Only update the node if something changed.\n if (tokens[0].length <= 1) {\n return [\n [...elements, quasi],\n [...expressions, node.expressions[index] as Expression],\n ];\n }\n\n return [\n [...elements, ...tokens[0]],\n [\n ...expressions,\n ...tokens[1],\n node.expressions[index] as Expression,\n ],\n ];\n },\n [[], []],\n );\n\n path.replaceWith(\n templateLiteral(\n replacementQuasis,\n replacementExpressions.filter(\n (expression) => expression !== undefined,\n ),\n ) as Node,\n );\n\n path.setData('visited', true);\n },\n\n StringLiteral(path) {\n const { node } = path;\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const tokens = breakTokens(node.value);\n\n // Only update the node if the string literal was broken up.\n if (tokens.length <= 1) {\n return;\n }\n\n const replacement = tokens\n .slice(1)\n .reduce<Expression>(\n (acc, value) => binaryExpression('+', acc, stringLiteral(value)),\n stringLiteral(tokens[0]),\n );\n\n path.replaceWith(replacement as Node);\n path.skip();\n },\n\n BinaryExpression(path) {\n const { node } = path;\n\n const errorMessage =\n 'Using HTML comments (`<!--` and `-->`) as operators is not allowed. The behaviour of ' +\n 'these comments is ambiguous, and differs per browser and environment. If you want ' +\n 'to use them as operators, break them up into separate characters, i.e., `a-- > b` ' +\n 'and `a < ! --b`.';\n\n if (\n node.operator === '<' &&\n isUnaryExpression(node.right) &&\n isUpdateExpression(node.right.argument) &&\n node.right.argument.operator === '--' &&\n node.left.end &&\n node.right.argument.argument.start\n ) {\n const expression = code.slice(\n node.left.end,\n node.right.argument.argument.start,\n );\n\n if (expression.includes('<!--')) {\n throw new Error(errorMessage);\n }\n }\n\n if (\n node.operator === '>' &&\n isUpdateExpression(node.left) &&\n node.left.operator === '--' &&\n node.left.argument.end &&\n node.right.start\n ) {\n const expression = code.slice(node.left.argument.end, node.right.start);\n\n if (expression.includes('-->')) {\n throw new Error(errorMessage);\n }\n }\n },\n };\n\n try {\n const file = transformSync(code, {\n // Prevent Babel from searching for a config file.\n configFile: false,\n\n parserOpts: {\n // Strict mode isn't enabled by default, so we need to enable it here.\n strictMode: true,\n\n // If this is disabled, the AST does not include any comments. This is\n // useful for performance reasons, and we use it for stripping comments.\n attachComment: !stripComments,\n },\n\n // By default, Babel optimises bundles that exceed 500 KB, but that\n // results in characters which look like HTML comments, which breaks SES.\n compact: false,\n\n // This configures Babel to generate a new source map from the existing\n // source map if specified. If `sourceMap` is `true` but an input source\n // map is not provided, a new source map will be generated instead.\n inputSourceMap,\n sourceMaps,\n\n plugins: [\n () => ({\n pre,\n visitor,\n }),\n ],\n });\n\n if (!file?.code) {\n throw new Error('Bundled code is empty.');\n }\n\n return {\n code: file.code,\n sourceMap: file.map,\n warnings: Array.from(warnings),\n };\n } catch (error) {\n throw new Error(`Failed to post process code:\\n${error.message}`);\n }\n}\n"],"names":["postProcessBundle","PostProcessWarning","UnsafeMathRandom","TOKEN_REGEX","EMPTY_TEMPLATE_ELEMENT","templateElement","raw","cooked","evalWrapper","template","statement","objectEvalWrapper","regeneratorRuntimeWrapper","breakTokens","value","tokens","split","filter","token","undefined","breakTokensTemplateLiteral","matches","Array","from","matchAll","length","output","reduce","elements","expressions","rawMatch","index","values","first","last","prefix","slice","getRawTemplateValue","stringLiteral","lastMatch","suffix","replace","code","stripComments","sourceMap","sourceMaps","inputSourceMap","warnings","Set","pre","ast","comments","forEach","comment","RegExp","visitor","FunctionExpression","path","node","type","extra","parenthesized","params","param","name","CallExpression","callee","replaceWith","REF","ARGS","arguments","object","property","add","MemberExpression","parent","OBJECT","Identifier","program","findParent","body","declarations","id","unshift","TemplateLiteral","getData","replacementQuasis","replacementExpressions","quasis","quasi","templateLiteral","expression","setData","StringLiteral","replacement","acc","binaryExpression","skip","BinaryExpression","errorMessage","operator","isUnaryExpression","right","isUpdateExpression","argument","left","end","start","includes","Error","file","transformSync","configFile","parserOpts","strictMode","attachComment","compact","plugins","map","error","message"],"mappings":"AAAA,wDAAwD;;;;;;;;;;;;;;;IAoNxCA,iBAAiB;eAAjBA;;;sBAlNwB;uBASjC;IAgDA;UAAKC,kBAAkB;IAAlBA,mBACVC,sBAAmB;GADTD,uBAAAA;AAIZ,sEAAsE;AACtE,uEAAuE;AACvE,wEAAwE;AACxE,MAAME,cAAc;AAEpB,4EAA4E;AAC5E,cAAc;AACd,MAAMC,yBAAyBC,IAAAA,sBAAe,EAAC;IAAEC,KAAK;IAAIC,QAAQ;AAAG;AAErE,MAAMC,cAAcC,cAAQ,CAACC,SAAS,CAAC,CAAC;;AAExC,CAAC;AAED,MAAMC,oBAAoBF,cAAQ,CAACC,SAAS,CAAC,CAAC;;AAE9C,CAAC;AAED,MAAME,4BAA4BH,cAAQ,CAACC,SAAS,CAAC,CAAC;;AAEtD,CAAC;AAED;;;;;;;;;;;CAWC,GACD,SAASG,YAAYC,KAAa;IAChC,MAAMC,SAASD,MAAME,KAAK,CAACb;IAC3B,OACEY,MACE,oEAAoE;IACpE,sEAAsE;KACrEE,MAAM,CAAC,CAACC,QAAUA,UAAU,MAAMA,UAAUC;AAEnD;AAEA;;;;;;;;;;CAUC,GACD,SAASC,2BACPN,KAAa;IAEb,6DAA6D;IAC7D,kEAAkE;IAClE,uEAAuE;IACvE,MAAMO,UAA8BC,MAAMC,IAAI,CAACT,MAAMU,QAAQ,CAACrB;I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AAEhD,KAAK4C,KAAK,CAACK,KAAK;gBAEtE,IAAIhB,WAAWiB,QAAQ,CAAC,QAAQ;oBAC9B,MAAM,IAAIC,MAAMV;gBAClB;YACF;QACF;IACF;IAEA,IAAI;QACF,MAAMW,OAAOC,IAAAA,mBAAa,EAACrE,MAAM;YAC/B,kDAAkD;YAClDsE,YAAY;YAEZC,YAAY;gBACV,sEAAsE;gBACtEC,YAAY;gBAEZ,sEAAsE;gBACtE,wEAAwE;gBACxEC,eAAe,CAACxE;YAClB;YAEA,mEAAmE;YACnE,yEAAyE;YACzEyE,SAAS;YAET,uEAAuE;YACvE,wEAAwE;YACxE,mEAAmE;YACnEtE;YACAD;YAEAwE,SAAS;gBACP,IAAO,CAAA;wBACLpE;wBACAM;oBACF,CAAA;aACD;QACH;QAEA,IAAI,CAACuD,MAAMpE,MAAM;YACf,MAAM,IAAImE,MAAM;QAClB;QAEA,OAAO;YACLnE,MAAMoE,KAAKpE,IAAI;YACfE,WAAWkE,KAAKQ,GAAG;YACnBvE,UAAUzB,MAAMC,IAAI,CAACwB;QACvB;IACF,EAAE,OAAOwE,OAAO;QACd,MAAM,IAAIV,MAAM,CAAC,8BAA8B,EAAEU,MAAMC,OAAO,CAAC,CAAC;IAClE;AACF"}
package/dist/cjs/snaps.js DELETED
@@ -1,230 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", {
3
- value: true
4
- });
5
- function _export(target, all) {
6
- for(var name in all)Object.defineProperty(target, name, {
7
- enumerable: true,
8
- get: all[name]
9
- });
10
- }
11
- _export(exports, {
12
- SnapStatus: function() {
13
- return SnapStatus;
14
- },
15
- SnapStatusEvents: function() {
16
- return SnapStatusEvents;
17
- },
18
- PROPOSED_NAME_REGEX: function() {
19
- return PROPOSED_NAME_REGEX;
20
- },
21
- ProgrammaticallyFixableSnapError: function() {
22
- return ProgrammaticallyFixableSnapError;
23
- },
24
- getSnapChecksum: function() {
25
- return getSnapChecksum;
26
- },
27
- validateSnapShasum: function() {
28
- return validateSnapShasum;
29
- },
30
- LOCALHOST_HOSTNAMES: function() {
31
- return LOCALHOST_HOSTNAMES;
32
- },
33
- BaseSnapIdStruct: function() {
34
- return BaseSnapIdStruct;
35
- },
36
- LocalSnapIdStruct: function() {
37
- return LocalSnapIdStruct;
38
- },
39
- NpmSnapIdStruct: function() {
40
- return NpmSnapIdStruct;
41
- },
42
- HttpSnapIdStruct: function() {
43
- return HttpSnapIdStruct;
44
- },
45
- SnapIdStruct: function() {
46
- return SnapIdStruct;
47
- },
48
- getSnapPrefix: function() {
49
- return getSnapPrefix;
50
- },
51
- stripSnapPrefix: function() {
52
- return stripSnapPrefix;
53
- },
54
- assertIsValidSnapId: function() {
55
- return assertIsValidSnapId;
56
- },
57
- isCaipChainId: function() {
58
- return isCaipChainId;
59
- },
60
- isSnapPermitted: function() {
61
- return isSnapPermitted;
62
- },
63
- verifyRequestedSnapPermissions: function() {
64
- return verifyRequestedSnapPermissions;
65
- }
66
- });
67
- const _utils = require("@metamask/utils");
68
- const _base = require("@scure/base");
69
- const _fastjsonstablestringify = /*#__PURE__*/ _interop_require_default(require("fast-json-stable-stringify"));
70
- const _superstruct = require("superstruct");
71
- const _validatenpmpackagename = /*#__PURE__*/ _interop_require_default(require("validate-npm-package-name"));
72
- const _caveats = require("./caveats");
73
- const _checksum = require("./checksum");
74
- const _types = require("./types");
75
- function _define_property(obj, key, value) {
76
- if (key in obj) {
77
- Object.defineProperty(obj, key, {
78
- value: value,
79
- enumerable: true,
80
- configurable: true,
81
- writable: true
82
- });
83
- } else {
84
- obj[key] = value;
85
- }
86
- return obj;
87
- }
88
- function _interop_require_default(obj) {
89
- return obj && obj.__esModule ? obj : {
90
- default: obj
91
- };
92
- }
93
- const PROPOSED_NAME_REGEX = /^(?:[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;
94
- var SnapStatus;
95
- (function(SnapStatus) {
96
- SnapStatus["Installing"] = 'installing';
97
- SnapStatus["Updating"] = 'updating';
98
- SnapStatus["Running"] = 'running';
99
- SnapStatus["Stopped"] = 'stopped';
100
- SnapStatus["Crashed"] = 'crashed';
101
- })(SnapStatus || (SnapStatus = {}));
102
- var SnapStatusEvents;
103
- (function(SnapStatusEvents) {
104
- SnapStatusEvents["Start"] = 'START';
105
- SnapStatusEvents["Stop"] = 'STOP';
106
- SnapStatusEvents["Crash"] = 'CRASH';
107
- SnapStatusEvents["Update"] = 'UPDATE';
108
- })(SnapStatusEvents || (SnapStatusEvents = {}));
109
- class ProgrammaticallyFixableSnapError extends Error {
110
- constructor(message, reason){
111
- super(message);
112
- _define_property(this, "reason", void 0);
113
- this.reason = reason;
114
- }
115
- }
116
- /**
117
- * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.
118
- *
119
- * @param manifest - The manifest itself.
120
- * @returns A virtual file containing the checksummable manifest.
121
- */ function getChecksummableManifest(manifest) {
122
- const manifestCopy = manifest.clone();
123
- delete manifestCopy.result.source.shasum;
124
- // We use fast-json-stable-stringify to deterministically serialize the JSON
125
- // This is required before checksumming so we get reproducible checksums across platforms etc
126
- manifestCopy.value = (0, _fastjsonstablestringify.default)(manifestCopy.result);
127
- return manifestCopy;
128
- }
129
- function getSnapChecksum(files) {
130
- const { manifest, sourceCode, svgIcon } = files;
131
- const all = [
132
- getChecksummableManifest(manifest),
133
- sourceCode,
134
- svgIcon
135
- ].filter((file)=>file !== undefined);
136
- return _base.base64.encode((0, _checksum.checksumFiles)(all));
137
- }
138
- function validateSnapShasum(files, errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.') {
139
- if (files.manifest.result.source.shasum !== getSnapChecksum(files)) {
140
- throw new ProgrammaticallyFixableSnapError(errorMessage, _types.SnapValidationFailureReason.ShasumMismatch);
141
- }
142
- }
143
- const LOCALHOST_HOSTNAMES = [
144
- 'localhost',
145
- '127.0.0.1',
146
- '[::1]'
147
- ];
148
- const BaseSnapIdStruct = (0, _superstruct.pattern)((0, _superstruct.string)(), /^[\x21-\x7E]*$/u);
149
- const LocalSnapIdSubUrlStruct = (0, _types.uri)({
150
- protocol: (0, _superstruct.enums)([
151
- 'http:',
152
- 'https:'
153
- ]),
154
- hostname: (0, _superstruct.enums)(LOCALHOST_HOSTNAMES),
155
- hash: (0, _superstruct.empty)((0, _superstruct.string)()),
156
- search: (0, _superstruct.empty)((0, _superstruct.string)())
157
- });
158
- const LocalSnapIdStruct = (0, _superstruct.refine)(BaseSnapIdStruct, 'local Snap Id', (value)=>{
159
- if (!value.startsWith(_types.SnapIdPrefixes.local)) {
160
- return `Expected local snap ID, got "${value}".`;
161
- }
162
- const [error] = (0, _superstruct.validate)(value.slice(_types.SnapIdPrefixes.local.length), LocalSnapIdSubUrlStruct);
163
- return error ?? true;
164
- });
165
- const NpmSnapIdStruct = (0, _superstruct.intersection)([
166
- BaseSnapIdStruct,
167
- (0, _types.uri)({
168
- protocol: (0, _superstruct.literal)(_types.SnapIdPrefixes.npm),
169
- pathname: (0, _superstruct.refine)((0, _superstruct.string)(), 'package name', function*(value) {
170
- const normalized = value.startsWith('/') ? value.slice(1) : value;
171
- const { errors, validForNewPackages, warnings } = (0, _validatenpmpackagename.default)(normalized);
172
- if (!validForNewPackages) {
173
- if (errors === undefined) {
174
- (0, _utils.assert)(warnings !== undefined);
175
- yield* warnings;
176
- } else {
177
- yield* errors;
178
- }
179
- }
180
- return true;
181
- }),
182
- search: (0, _superstruct.empty)((0, _superstruct.string)()),
183
- hash: (0, _superstruct.empty)((0, _superstruct.string)())
184
- })
185
- ]);
186
- const HttpSnapIdStruct = (0, _superstruct.intersection)([
187
- BaseSnapIdStruct,
188
- (0, _types.uri)({
189
- protocol: (0, _superstruct.enums)([
190
- 'http:',
191
- 'https:'
192
- ]),
193
- search: (0, _superstruct.empty)((0, _superstruct.string)()),
194
- hash: (0, _superstruct.empty)((0, _superstruct.string)())
195
- })
196
- ]);
197
- const SnapIdStruct = (0, _superstruct.union)([
198
- NpmSnapIdStruct,
199
- LocalSnapIdStruct
200
- ]);
201
- function getSnapPrefix(snapId) {
202
- const prefix = Object.values(_types.SnapIdPrefixes).find((possiblePrefix)=>snapId.startsWith(possiblePrefix));
203
- if (prefix !== undefined) {
204
- return prefix;
205
- }
206
- throw new Error(`Invalid or no prefix found for "${snapId}"`);
207
- }
208
- function stripSnapPrefix(snapId) {
209
- return snapId.replace(getSnapPrefix(snapId), '');
210
- }
211
- function assertIsValidSnapId(value) {
212
- (0, _utils.assertStruct)(value, SnapIdStruct, 'Invalid snap ID');
213
- }
214
- function isCaipChainId(chainId) {
215
- return typeof chainId === 'string' && RegExp("^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$", "u").test(chainId);
216
- }
217
- function isSnapPermitted(permissions, snapId) {
218
- return Boolean((permissions?.wallet_snap?.caveats?.find((caveat)=>caveat.type === _caveats.SnapCaveatType.SnapIds) ?? {}).value?.[snapId]);
219
- }
220
- function verifyRequestedSnapPermissions(requestedPermissions) {
221
- (0, _utils.assert)((0, _utils.isObject)(requestedPermissions), 'Requested permissions must be an object.');
222
- const { wallet_snap: walletSnapPermission } = requestedPermissions;
223
- (0, _utils.assert)((0, _utils.isObject)(walletSnapPermission), 'wallet_snap is missing from the requested permissions.');
224
- const { caveats } = walletSnapPermission;
225
- (0, _utils.assert)(Array.isArray(caveats) && caveats.length === 1, 'wallet_snap must have a caveat property with a single-item array value.');
226
- const [caveat] = caveats;
227
- (0, _utils.assert)((0, _utils.isObject)(caveat) && caveat.type === _caveats.SnapCaveatType.SnapIds && (0, _utils.isObject)(caveat.value), `The requested permissions do not have a valid ${_caveats.SnapCaveatType.SnapIds} caveat.`);
228
- }
229
-
230
- //# sourceMappingURL=snaps.js.map