@metamask/snaps-controllers 9.2.0 → 9.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/CHANGELOG.md +37 -1
  2. package/dist/{chunk-WP3DAIFM.mjs → chunk-23PVLQFV.mjs} +62 -2
  3. package/dist/chunk-23PVLQFV.mjs.map +1 -0
  4. package/dist/chunk-272IFIK7.mjs +1 -0
  5. package/dist/chunk-272IFIK7.mjs.map +1 -0
  6. package/dist/{chunk-42ODFZSH.mjs → chunk-2AEM5R2M.mjs} +4 -4
  7. package/dist/{chunk-NZKBY2N7.mjs → chunk-2MH7QYBP.mjs} +47 -11
  8. package/dist/chunk-2MH7QYBP.mjs.map +1 -0
  9. package/dist/chunk-2XQD4P2S.mjs +1 -0
  10. package/dist/chunk-2XQD4P2S.mjs.map +1 -0
  11. package/dist/{chunk-XSFI32LB.mjs → chunk-33RRV7F4.mjs} +1 -1
  12. package/dist/{chunk-SAAURQ5A.mjs → chunk-6WGCLJGC.mjs} +2 -2
  13. package/dist/{chunk-FPGAQ6MT.js → chunk-7BUNUNUC.js} +3 -3
  14. package/dist/{chunk-CDTGUNSA.js → chunk-B6KTRDBK.js} +9 -9
  15. package/dist/chunk-B6KTRDBK.js.map +1 -0
  16. package/dist/{chunk-3AANDIXT.js → chunk-D66YLO7T.js} +3 -3
  17. package/dist/{chunk-E52MHHG4.js → chunk-FKQTV3LO.js} +55 -19
  18. package/dist/chunk-FKQTV3LO.js.map +1 -0
  19. package/dist/{chunk-KH72WRHR.js → chunk-FZOI4WPB.js} +3 -3
  20. package/dist/chunk-G245VWEY.mjs +275 -0
  21. package/dist/chunk-G245VWEY.mjs.map +1 -0
  22. package/dist/{chunk-7IJQGFT5.mjs → chunk-HLQQTAMM.mjs} +2 -2
  23. package/dist/chunk-IDCWJJCQ.js +1 -0
  24. package/dist/chunk-IDCWJJCQ.js.map +1 -0
  25. package/dist/{chunk-BUHS4M6F.js → chunk-JLIW4CNS.js} +62 -2
  26. package/dist/chunk-JLIW4CNS.js.map +1 -0
  27. package/dist/{chunk-RW7AYHRG.js → chunk-KELDSV7H.js} +3 -3
  28. package/dist/{chunk-567BFPSL.mjs → chunk-KRI4OKC3.mjs} +10 -10
  29. package/dist/chunk-KRI4OKC3.mjs.map +1 -0
  30. package/dist/{chunk-PMZXFAQI.mjs → chunk-KYRKZ3RH.mjs} +2 -2
  31. package/dist/{chunk-LRVK45HN.mjs → chunk-LDL6LJ3P.mjs} +2 -2
  32. package/dist/chunk-M7DWHPVM.js +1 -0
  33. package/dist/chunk-M7DWHPVM.js.map +1 -0
  34. package/dist/{chunk-6ERB63FH.js → chunk-OVATPF5I.js} +3 -3
  35. package/dist/{chunk-HQ6HMINL.js → chunk-P66VIDFG.js} +3 -3
  36. package/dist/{chunk-PT22IXNS.js → chunk-POQSARDG.js} +3 -3
  37. package/dist/{chunk-ZRC46TUF.js → chunk-PYSDWIVK.js} +3 -3
  38. package/dist/{chunk-S775IABY.js → chunk-QRISQRFI.js} +13 -14
  39. package/dist/{chunk-S775IABY.js.map → chunk-QRISQRFI.js.map} +1 -1
  40. package/dist/chunk-QYQLJCPR.js +275 -0
  41. package/dist/chunk-QYQLJCPR.js.map +1 -0
  42. package/dist/{chunk-QLFH3MC6.mjs → chunk-TSDUJNOP.mjs} +5 -6
  43. package/dist/chunk-TSDUJNOP.mjs.map +1 -0
  44. package/dist/{chunk-YUWYMNIX.mjs → chunk-VKMY6CKT.mjs} +2 -2
  45. package/dist/{chunk-CIFVYFJW.mjs → chunk-WR7CVDEY.mjs} +2 -2
  46. package/dist/{chunk-GRBWVPLF.js → chunk-XFUP7RFI.js} +1 -1
  47. package/dist/{chunk-3A72M4GC.mjs → chunk-XOSHP4J3.mjs} +2 -2
  48. package/dist/cronjob/CronjobController.js +19 -17
  49. package/dist/cronjob/CronjobController.mjs +18 -16
  50. package/dist/cronjob/index.js +19 -17
  51. package/dist/cronjob/index.mjs +18 -16
  52. package/dist/index.js +31 -28
  53. package/dist/index.mjs +31 -28
  54. package/dist/insights/SnapInsightsController.js +25 -0
  55. package/dist/insights/SnapInsightsController.js.map +1 -0
  56. package/dist/insights/SnapInsightsController.mjs +25 -0
  57. package/dist/insights/SnapInsightsController.mjs.map +1 -0
  58. package/dist/insights/index.js +26 -0
  59. package/dist/insights/index.js.map +1 -0
  60. package/dist/insights/index.mjs +26 -0
  61. package/dist/insights/index.mjs.map +1 -0
  62. package/dist/interface/SnapInterfaceController.js +2 -2
  63. package/dist/interface/SnapInterfaceController.mjs +1 -1
  64. package/dist/interface/index.js +2 -2
  65. package/dist/interface/index.mjs +1 -1
  66. package/dist/node.js +33 -30
  67. package/dist/node.mjs +35 -32
  68. package/dist/react-native.js +32 -29
  69. package/dist/react-native.mjs +32 -29
  70. package/dist/services/AbstractExecutionService.js +3 -3
  71. package/dist/services/AbstractExecutionService.mjs +2 -2
  72. package/dist/services/browser.js +10 -10
  73. package/dist/services/browser.mjs +10 -10
  74. package/dist/services/iframe/IframeExecutionService.js +4 -4
  75. package/dist/services/iframe/IframeExecutionService.mjs +3 -3
  76. package/dist/services/iframe/index.js +4 -4
  77. package/dist/services/iframe/index.mjs +3 -3
  78. package/dist/services/index.js +9 -9
  79. package/dist/services/index.mjs +9 -9
  80. package/dist/services/node-js/NodeProcessExecutionService.js +9 -9
  81. package/dist/services/node-js/NodeProcessExecutionService.mjs +8 -8
  82. package/dist/services/node-js/NodeThreadExecutionService.js +9 -9
  83. package/dist/services/node-js/NodeThreadExecutionService.mjs +8 -8
  84. package/dist/services/node-js/index.js +10 -10
  85. package/dist/services/node-js/index.mjs +11 -11
  86. package/dist/services/node.js +11 -11
  87. package/dist/services/node.mjs +13 -13
  88. package/dist/services/offscreen/OffscreenExecutionService.js +5 -5
  89. package/dist/services/offscreen/OffscreenExecutionService.mjs +4 -4
  90. package/dist/services/offscreen/index.js +5 -5
  91. package/dist/services/offscreen/index.mjs +4 -4
  92. package/dist/services/proxy/ProxyExecutionService.js +4 -4
  93. package/dist/services/proxy/ProxyExecutionService.mjs +3 -3
  94. package/dist/services/react-native.js +10 -10
  95. package/dist/services/react-native.mjs +10 -10
  96. package/dist/services/webview/WebViewExecutionService.js +5 -5
  97. package/dist/services/webview/WebViewExecutionService.mjs +4 -4
  98. package/dist/services/webview/index.js +5 -5
  99. package/dist/services/webview/index.mjs +4 -4
  100. package/dist/services/webworker/WebWorkerExecutionService.js +4 -4
  101. package/dist/services/webworker/WebWorkerExecutionService.mjs +3 -3
  102. package/dist/services/webworker/index.js +4 -4
  103. package/dist/services/webworker/index.mjs +3 -3
  104. package/dist/snaps/SnapController.js +5 -5
  105. package/dist/snaps/SnapController.mjs +4 -4
  106. package/dist/snaps/index.js +10 -10
  107. package/dist/snaps/index.mjs +9 -9
  108. package/dist/snaps/location/index.js +4 -4
  109. package/dist/snaps/location/index.mjs +4 -4
  110. package/dist/snaps/location/location.js +3 -3
  111. package/dist/snaps/location/location.mjs +2 -2
  112. package/dist/tsconfig.build.tsbuildinfo +1 -1
  113. package/dist/types/controllers.js +2 -0
  114. package/dist/types/controllers.js.map +1 -0
  115. package/dist/types/controllers.mjs +2 -0
  116. package/dist/types/controllers.mjs.map +1 -0
  117. package/dist/types/index.d.ts +1 -0
  118. package/dist/types/index.js +2 -1
  119. package/dist/types/index.mjs +1 -0
  120. package/dist/types/insights/SnapInsightsController.d.ts +33 -0
  121. package/dist/types/insights/index.d.ts +1 -0
  122. package/dist/types/interface/SnapInterfaceController.d.ts +17 -2
  123. package/dist/types/types/controllers.d.ts +131 -0
  124. package/dist/types/types/index.d.ts +1 -0
  125. package/dist/types/utils.d.ts +0 -13
  126. package/dist/utils.js +2 -4
  127. package/dist/utils.mjs +1 -3
  128. package/package.json +14 -14
  129. package/dist/chunk-567BFPSL.mjs.map +0 -1
  130. package/dist/chunk-BUHS4M6F.js.map +0 -1
  131. package/dist/chunk-CDTGUNSA.js.map +0 -1
  132. package/dist/chunk-E52MHHG4.js.map +0 -1
  133. package/dist/chunk-NZKBY2N7.mjs.map +0 -1
  134. package/dist/chunk-QLFH3MC6.mjs.map +0 -1
  135. package/dist/chunk-WP3DAIFM.mjs.map +0 -1
  136. /package/dist/{chunk-42ODFZSH.mjs.map → chunk-2AEM5R2M.mjs.map} +0 -0
  137. /package/dist/{chunk-XSFI32LB.mjs.map → chunk-33RRV7F4.mjs.map} +0 -0
  138. /package/dist/{chunk-SAAURQ5A.mjs.map → chunk-6WGCLJGC.mjs.map} +0 -0
  139. /package/dist/{chunk-FPGAQ6MT.js.map → chunk-7BUNUNUC.js.map} +0 -0
  140. /package/dist/{chunk-3AANDIXT.js.map → chunk-D66YLO7T.js.map} +0 -0
  141. /package/dist/{chunk-KH72WRHR.js.map → chunk-FZOI4WPB.js.map} +0 -0
  142. /package/dist/{chunk-7IJQGFT5.mjs.map → chunk-HLQQTAMM.mjs.map} +0 -0
  143. /package/dist/{chunk-RW7AYHRG.js.map → chunk-KELDSV7H.js.map} +0 -0
  144. /package/dist/{chunk-PMZXFAQI.mjs.map → chunk-KYRKZ3RH.mjs.map} +0 -0
  145. /package/dist/{chunk-LRVK45HN.mjs.map → chunk-LDL6LJ3P.mjs.map} +0 -0
  146. /package/dist/{chunk-6ERB63FH.js.map → chunk-OVATPF5I.js.map} +0 -0
  147. /package/dist/{chunk-HQ6HMINL.js.map → chunk-P66VIDFG.js.map} +0 -0
  148. /package/dist/{chunk-PT22IXNS.js.map → chunk-POQSARDG.js.map} +0 -0
  149. /package/dist/{chunk-ZRC46TUF.js.map → chunk-PYSDWIVK.js.map} +0 -0
  150. /package/dist/{chunk-YUWYMNIX.mjs.map → chunk-VKMY6CKT.mjs.map} +0 -0
  151. /package/dist/{chunk-CIFVYFJW.mjs.map → chunk-WR7CVDEY.mjs.map} +0 -0
  152. /package/dist/{chunk-GRBWVPLF.js.map → chunk-XFUP7RFI.js.map} +0 -0
  153. /package/dist/{chunk-3A72M4GC.mjs.map → chunk-XOSHP4J3.mjs.map} +0 -0
@@ -0,0 +1,275 @@
1
+ import {
2
+ getRunnableSnaps
3
+ } from "./chunk-P7Y6MIZW.mjs";
4
+ import {
5
+ __privateAdd,
6
+ __privateMethod
7
+ } from "./chunk-YRZVIDCF.mjs";
8
+
9
+ // src/insights/SnapInsightsController.ts
10
+ import { BaseController } from "@metamask/base-controller";
11
+ import {
12
+ getSignatureOriginCaveat,
13
+ getTransactionOriginCaveat,
14
+ SnapEndowments
15
+ } from "@metamask/snaps-rpc-methods";
16
+ import { HandlerType } from "@metamask/snaps-utils";
17
+ import { hasProperty } from "@metamask/utils";
18
+ var controllerName = "SnapInsightsController";
19
+ var _hasInsight, hasInsight_fn, _getSnapsWithPermission, getSnapsWithPermission_fn, _handleTransaction, handleTransaction_fn, _handleSignatureStateChange, handleSignatureStateChange_fn, _handleSignature, handleSignature_fn, _handleTransactionStatusUpdate, handleTransactionStatusUpdate_fn, _handleInsightCleanup, handleInsightCleanup_fn, _handleSnapRequest, handleSnapRequest_fn, _handleSnapResponse, handleSnapResponse_fn;
20
+ var SnapInsightsController = class extends BaseController {
21
+ constructor({ messenger, state }) {
22
+ super({
23
+ messenger,
24
+ metadata: {
25
+ insights: { persist: false, anonymous: false }
26
+ },
27
+ name: controllerName,
28
+ state: { insights: {}, ...state }
29
+ });
30
+ /**
31
+ * Check if an insight already exists for a given ID.
32
+ *
33
+ * @param id - The ID.
34
+ * @returns True if the insight already exists, otherwise false.
35
+ */
36
+ __privateAdd(this, _hasInsight);
37
+ /**
38
+ * Get a list of runnable Snaps that have a given permission.
39
+ * Also includes the permission object itself.
40
+ *
41
+ * @param permissionName - The permission name.
42
+ * @returns A list of objects containing Snap IDs and the permission object.
43
+ */
44
+ __privateAdd(this, _getSnapsWithPermission);
45
+ /**
46
+ * Handle a newly added unapproved transaction.
47
+ * This function fetches insights from all available Snaps
48
+ * and populates the insights state blob with the responses.
49
+ *
50
+ * @param transaction - The transaction object.
51
+ */
52
+ __privateAdd(this, _handleTransaction);
53
+ /**
54
+ * Handle the stateChange event emitted by the SignatureController.
55
+ * This function will remove existing insights from the state when applicable, as well as
56
+ * trigger insight fetching for newly added signatures.
57
+ *
58
+ * @param state - The SignatureController state blob.
59
+ */
60
+ __privateAdd(this, _handleSignatureStateChange);
61
+ /**
62
+ * Handle a newly added unapproved signature.
63
+ * This function fetches insights from all available Snaps
64
+ * and populates the insights state blob with the responses.
65
+ *
66
+ * @param snaps - A list of Snaps to invoke.
67
+ * @param signature - The signature object.
68
+ */
69
+ __privateAdd(this, _handleSignature);
70
+ /**
71
+ * Handle the transactionStatusUpdated event emitted by the TransactionController.
72
+ * This function will remove insights for the transaction in question
73
+ * once the transaction status has changed from unapproved.
74
+ *
75
+ * @param args - An options bag.
76
+ * @param args.transactionMeta - The transaction.
77
+ */
78
+ __privateAdd(this, _handleTransactionStatusUpdate);
79
+ __privateAdd(this, _handleInsightCleanup);
80
+ /**
81
+ * Handle sending a request to a given Snap with a given payload.
82
+ *
83
+ * @param args - An options bag.
84
+ * @param args.snapId - The Snap ID.
85
+ * @param args.handler - The handler to invoke.
86
+ * @param args.params - The JSON-RPC params to send.
87
+ * @returns The response from the Snap.
88
+ */
89
+ __privateAdd(this, _handleSnapRequest);
90
+ /**
91
+ * Handle response from a given Snap by persisting the response or error in state.
92
+ *
93
+ * @param args - An options bag.
94
+ * @param args.id - The transaction or signature ID.
95
+ * @param args.snapId - The Snap ID.
96
+ * @param args.response - An optional response object returned by the Snap.
97
+ * @param args.error - An optional error returned by the Snap.
98
+ */
99
+ __privateAdd(this, _handleSnapResponse);
100
+ this.messagingSystem.subscribe(
101
+ "TransactionController:unapprovedTransactionAdded",
102
+ __privateMethod(this, _handleTransaction, handleTransaction_fn).bind(this)
103
+ );
104
+ this.messagingSystem.subscribe(
105
+ "TransactionController:transactionStatusUpdated",
106
+ __privateMethod(this, _handleTransactionStatusUpdate, handleTransactionStatusUpdate_fn).bind(this)
107
+ );
108
+ this.messagingSystem.subscribe(
109
+ "SignatureController:stateChange",
110
+ __privateMethod(this, _handleSignatureStateChange, handleSignatureStateChange_fn).bind(this)
111
+ );
112
+ }
113
+ };
114
+ _hasInsight = new WeakSet();
115
+ hasInsight_fn = function(id) {
116
+ return hasProperty(this.state.insights, id);
117
+ };
118
+ _getSnapsWithPermission = new WeakSet();
119
+ getSnapsWithPermission_fn = function(permissionName) {
120
+ const allSnaps = this.messagingSystem.call("SnapController:getAll");
121
+ const filteredSnaps = getRunnableSnaps(allSnaps);
122
+ return filteredSnaps.reduce((accumulator, snap) => {
123
+ const permissions = this.messagingSystem.call(
124
+ "PermissionController:getPermissions",
125
+ snap.id
126
+ );
127
+ if (permissions && hasProperty(permissions, permissionName)) {
128
+ accumulator.push({
129
+ snapId: snap.id,
130
+ permission: permissions[permissionName]
131
+ });
132
+ }
133
+ return accumulator;
134
+ }, []);
135
+ };
136
+ _handleTransaction = new WeakSet();
137
+ handleTransaction_fn = function(transaction) {
138
+ const { id, txParams, chainId, origin } = transaction;
139
+ const caipChainId = `eip155:${parseInt(chainId, 16)}`;
140
+ const snaps = __privateMethod(this, _getSnapsWithPermission, getSnapsWithPermission_fn).call(this, SnapEndowments.TransactionInsight);
141
+ snaps.forEach(({ snapId, permission }) => {
142
+ const hasTransactionOriginCaveat = getTransactionOriginCaveat(permission);
143
+ const transactionOrigin = hasTransactionOriginCaveat && origin ? origin : null;
144
+ this.update((state) => {
145
+ var _a;
146
+ (_a = state.insights)[id] ?? (_a[id] = {});
147
+ state.insights[id][snapId] = { snapId, loading: true };
148
+ });
149
+ __privateMethod(this, _handleSnapRequest, handleSnapRequest_fn).call(this, {
150
+ snapId,
151
+ handler: HandlerType.OnTransaction,
152
+ params: {
153
+ transaction: txParams,
154
+ chainId: caipChainId,
155
+ transactionOrigin
156
+ }
157
+ }).then(
158
+ (response) => __privateMethod(this, _handleSnapResponse, handleSnapResponse_fn).call(this, {
159
+ id,
160
+ snapId,
161
+ response
162
+ })
163
+ ).catch((error) => __privateMethod(this, _handleSnapResponse, handleSnapResponse_fn).call(this, { id, snapId, error }));
164
+ });
165
+ };
166
+ _handleSignatureStateChange = new WeakSet();
167
+ handleSignatureStateChange_fn = function(state) {
168
+ for (const id of Object.keys(this.state.insights)) {
169
+ if (!hasProperty(state.unapprovedTypedMessages, id) && !hasProperty(state.unapprovedPersonalMsgs, id)) {
170
+ __privateMethod(this, _handleInsightCleanup, handleInsightCleanup_fn).call(this, id);
171
+ }
172
+ }
173
+ if (state.unapprovedPersonalMsgCount > 0 || state.unapprovedTypedMessagesCount > 0) {
174
+ const snaps = __privateMethod(this, _getSnapsWithPermission, getSnapsWithPermission_fn).call(this, SnapEndowments.SignatureInsight);
175
+ for (const personalSignature of Object.values(
176
+ state.unapprovedPersonalMsgs
177
+ )) {
178
+ __privateMethod(this, _handleSignature, handleSignature_fn).call(this, snaps, personalSignature);
179
+ }
180
+ for (const typedMessage of Object.values(state.unapprovedTypedMessages)) {
181
+ __privateMethod(this, _handleSignature, handleSignature_fn).call(this, snaps, typedMessage);
182
+ }
183
+ }
184
+ };
185
+ _handleSignature = new WeakSet();
186
+ handleSignature_fn = function(snaps, signature) {
187
+ const { id, msgParams } = signature;
188
+ if (__privateMethod(this, _hasInsight, hasInsight_fn).call(this, id)) {
189
+ return;
190
+ }
191
+ const { from, data, signatureMethod, origin } = msgParams;
192
+ const shouldParse = signatureMethod === "eth_signTypedData_v3" || signatureMethod === "eth_signTypedData_v4";
193
+ const payload = {
194
+ from,
195
+ data: shouldParse ? JSON.parse(data) : data,
196
+ signatureMethod
197
+ };
198
+ snaps.forEach(({ snapId, permission }) => {
199
+ const hasSignatureOriginCaveat = getSignatureOriginCaveat(permission);
200
+ const signatureOrigin = origin && hasSignatureOriginCaveat ? origin : null;
201
+ this.update((state) => {
202
+ var _a;
203
+ (_a = state.insights)[id] ?? (_a[id] = {});
204
+ state.insights[id][snapId] = { snapId, loading: true };
205
+ });
206
+ __privateMethod(this, _handleSnapRequest, handleSnapRequest_fn).call(this, {
207
+ snapId,
208
+ handler: HandlerType.OnSignature,
209
+ params: { signature: payload, signatureOrigin }
210
+ }).then(
211
+ (response) => __privateMethod(this, _handleSnapResponse, handleSnapResponse_fn).call(this, {
212
+ id,
213
+ snapId,
214
+ response
215
+ })
216
+ ).catch((error) => __privateMethod(this, _handleSnapResponse, handleSnapResponse_fn).call(this, { id, snapId, error }));
217
+ });
218
+ };
219
+ _handleTransactionStatusUpdate = new WeakSet();
220
+ handleTransactionStatusUpdate_fn = function({
221
+ transactionMeta
222
+ }) {
223
+ if (transactionMeta.status !== "unapproved") {
224
+ __privateMethod(this, _handleInsightCleanup, handleInsightCleanup_fn).call(this, transactionMeta.id);
225
+ }
226
+ };
227
+ _handleInsightCleanup = new WeakSet();
228
+ handleInsightCleanup_fn = function(id) {
229
+ if (!__privateMethod(this, _hasInsight, hasInsight_fn).call(this, id)) {
230
+ return;
231
+ }
232
+ Object.values(this.state.insights[id]).filter((insight) => insight.interfaceId).forEach((insight) => {
233
+ this.messagingSystem.call(
234
+ "SnapInterfaceController:deleteInterface",
235
+ insight.interfaceId
236
+ );
237
+ });
238
+ this.update((state) => {
239
+ delete state.insights[id];
240
+ });
241
+ };
242
+ _handleSnapRequest = new WeakSet();
243
+ handleSnapRequest_fn = async function({
244
+ snapId,
245
+ handler,
246
+ params
247
+ }) {
248
+ return this.messagingSystem.call("SnapController:handleRequest", {
249
+ snapId,
250
+ origin: "",
251
+ handler,
252
+ request: {
253
+ method: "",
254
+ params
255
+ }
256
+ });
257
+ };
258
+ _handleSnapResponse = new WeakSet();
259
+ handleSnapResponse_fn = function({
260
+ id,
261
+ snapId,
262
+ response,
263
+ error
264
+ }) {
265
+ this.update((state) => {
266
+ state.insights[id][snapId].loading = false;
267
+ state.insights[id][snapId].interfaceId = response?.id;
268
+ state.insights[id][snapId].error = error?.message;
269
+ });
270
+ };
271
+
272
+ export {
273
+ SnapInsightsController
274
+ };
275
+ //# sourceMappingURL=chunk-G245VWEY.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/insights/SnapInsightsController.ts"],"sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n Caveat,\n GetPermissions,\n ValidPermission,\n} from '@metamask/permission-controller';\nimport {\n getSignatureOriginCaveat,\n getTransactionOriginCaveat,\n SnapEndowments,\n} from '@metamask/snaps-rpc-methods';\nimport type { Json, SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport type { DeleteInterface } from '../interface';\nimport type { GetAllSnaps, HandleSnapRequest } from '../snaps';\nimport { getRunnableSnaps } from '../snaps';\nimport type {\n TransactionControllerUnapprovedTransactionAddedEvent,\n TransactionMeta,\n SignatureStateChange,\n SignatureControllerState,\n StateSignature,\n TransactionControllerTransactionStatusUpdatedEvent,\n} from '../types';\n\nconst controllerName = 'SnapInsightsController';\n\nexport type SnapInsightsControllerAllowedActions =\n | HandleSnapRequest\n | GetAllSnaps\n | GetPermissions\n | DeleteInterface;\n\nexport type SnapInsightsControllerActions = never;\n\nexport type SnapInsightsControllerAllowedEvents =\n | TransactionControllerUnapprovedTransactionAddedEvent\n | TransactionControllerTransactionStatusUpdatedEvent\n | SignatureStateChange;\n\nexport type SnapInsightsControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n SnapInsightsControllerActions | SnapInsightsControllerAllowedActions,\n SnapInsightsControllerAllowedEvents,\n SnapInsightsControllerAllowedActions['type'],\n SnapInsightsControllerAllowedEvents['type']\n>;\n\nexport type SnapInsight = {\n snapId: SnapId;\n interfaceId?: string | null;\n error?: string;\n loading: boolean;\n};\n\nexport type SnapInsightsControllerState = {\n insights: Record<string, Record<SnapId, SnapInsight>>;\n};\n\nexport type SnapInsightsControllerArgs = {\n messenger: SnapInsightsControllerMessenger;\n state?: SnapInsightsControllerState;\n};\n\ntype SnapWithPermission = {\n snapId: SnapId;\n permission: ValidPermission<string, Caveat<string, Json>>;\n};\n\n/**\n * Controller for monitoring for new transactions and signatures to provide insight for.\n */\nexport class SnapInsightsController extends BaseController<\n typeof controllerName,\n SnapInsightsControllerState,\n SnapInsightsControllerMessenger\n> {\n constructor({ messenger, state }: SnapInsightsControllerArgs) {\n super({\n messenger,\n metadata: {\n insights: { persist: false, anonymous: false },\n },\n name: controllerName,\n state: { insights: {}, ...state },\n });\n\n this.messagingSystem.subscribe(\n 'TransactionController:unapprovedTransactionAdded',\n this.#handleTransaction.bind(this),\n );\n\n this.messagingSystem.subscribe(\n 'TransactionController:transactionStatusUpdated',\n this.#handleTransactionStatusUpdate.bind(this),\n );\n\n this.messagingSystem.subscribe(\n 'SignatureController:stateChange',\n this.#handleSignatureStateChange.bind(this),\n );\n }\n\n /**\n * Check if an insight already exists for a given ID.\n *\n * @param id - The ID.\n * @returns True if the insight already exists, otherwise false.\n */\n #hasInsight(id: string) {\n return hasProperty(this.state.insights, id);\n }\n\n /**\n * Get a list of runnable Snaps that have a given permission.\n * Also includes the permission object itself.\n *\n * @param permissionName - The permission name.\n * @returns A list of objects containing Snap IDs and the permission object.\n */\n #getSnapsWithPermission(permissionName: string) {\n const allSnaps = this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(allSnaps);\n\n return filteredSnaps.reduce<SnapWithPermission[]>((accumulator, snap) => {\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snap.id,\n );\n if (permissions && hasProperty(permissions, permissionName)) {\n accumulator.push({\n snapId: snap.id,\n permission: permissions[permissionName],\n });\n }\n\n return accumulator;\n }, []);\n }\n\n /**\n * Handle a newly added unapproved transaction.\n * This function fetches insights from all available Snaps\n * and populates the insights state blob with the responses.\n *\n * @param transaction - The transaction object.\n */\n #handleTransaction(transaction: TransactionMeta) {\n const { id, txParams, chainId, origin } = transaction;\n\n // This assumes that the transactions are EVM-compatible for now.\n const caipChainId = `eip155:${parseInt(chainId, 16)}`;\n\n const snaps = this.#getSnapsWithPermission(\n SnapEndowments.TransactionInsight,\n );\n\n snaps.forEach(({ snapId, permission }) => {\n const hasTransactionOriginCaveat = getTransactionOriginCaveat(permission);\n const transactionOrigin =\n hasTransactionOriginCaveat && origin ? origin : null;\n\n this.update((state) => {\n state.insights[id] ??= {};\n state.insights[id][snapId] = { snapId, loading: true };\n });\n\n this.#handleSnapRequest({\n snapId,\n handler: HandlerType.OnTransaction,\n params: {\n transaction: txParams,\n chainId: caipChainId,\n transactionOrigin,\n },\n })\n .then((response) =>\n this.#handleSnapResponse({\n id,\n snapId,\n response: response as Record<string, Json>,\n }),\n )\n .catch((error) => this.#handleSnapResponse({ id, snapId, error }));\n });\n }\n\n /**\n * Handle the stateChange event emitted by the SignatureController.\n * This function will remove existing insights from the state when applicable, as well as\n * trigger insight fetching for newly added signatures.\n *\n * @param state - The SignatureController state blob.\n */\n #handleSignatureStateChange(state: SignatureControllerState) {\n // If any IDs have disappeared since the last state update, the insight may be cleaned up.\n for (const id of Object.keys(this.state.insights)) {\n if (\n !hasProperty(state.unapprovedTypedMessages, id) &&\n !hasProperty(state.unapprovedPersonalMsgs, id)\n ) {\n this.#handleInsightCleanup(id);\n }\n }\n\n if (\n state.unapprovedPersonalMsgCount > 0 ||\n state.unapprovedTypedMessagesCount > 0\n ) {\n const snaps = this.#getSnapsWithPermission(\n SnapEndowments.SignatureInsight,\n );\n\n // This isn't very efficient, but SignatureController doesn't expose a better event for us to use yet.\n for (const personalSignature of Object.values(\n state.unapprovedPersonalMsgs,\n )) {\n this.#handleSignature(snaps, personalSignature);\n }\n\n for (const typedMessage of Object.values(state.unapprovedTypedMessages)) {\n this.#handleSignature(snaps, typedMessage);\n }\n }\n }\n\n /**\n * Handle a newly added unapproved signature.\n * This function fetches insights from all available Snaps\n * and populates the insights state blob with the responses.\n *\n * @param snaps - A list of Snaps to invoke.\n * @param signature - The signature object.\n */\n #handleSignature(snaps: SnapWithPermission[], signature: StateSignature) {\n const { id, msgParams } = signature;\n\n if (this.#hasInsight(id)) {\n return;\n }\n\n const { from, data, signatureMethod, origin } = msgParams;\n\n /**\n * Both eth_signTypedData_v3 and eth_signTypedData_v4 methods\n * need to be parsed because their data is stringified. All other\n * signature methods do not, so they are ignored.\n */\n const shouldParse =\n signatureMethod === 'eth_signTypedData_v3' ||\n signatureMethod === 'eth_signTypedData_v4';\n\n const payload = {\n from,\n data: shouldParse ? JSON.parse(data as string) : data,\n signatureMethod,\n };\n\n snaps.forEach(({ snapId, permission }) => {\n const hasSignatureOriginCaveat = getSignatureOriginCaveat(permission);\n const signatureOrigin =\n origin && hasSignatureOriginCaveat ? origin : null;\n\n this.update((state) => {\n state.insights[id] ??= {};\n state.insights[id][snapId] = { snapId, loading: true };\n });\n\n this.#handleSnapRequest({\n snapId,\n handler: HandlerType.OnSignature,\n params: { signature: payload, signatureOrigin },\n })\n .then((response) =>\n this.#handleSnapResponse({\n id,\n snapId,\n response: response as Record<string, Json>,\n }),\n )\n .catch((error) => this.#handleSnapResponse({ id, snapId, error }));\n });\n }\n\n /**\n * Handle the transactionStatusUpdated event emitted by the TransactionController.\n * This function will remove insights for the transaction in question\n * once the transaction status has changed from unapproved.\n *\n * @param args - An options bag.\n * @param args.transactionMeta - The transaction.\n */\n #handleTransactionStatusUpdate({\n transactionMeta,\n }: {\n transactionMeta: TransactionMeta;\n }) {\n if (transactionMeta.status !== 'unapproved') {\n this.#handleInsightCleanup(transactionMeta.id);\n }\n }\n\n #handleInsightCleanup(id: string) {\n if (!this.#hasInsight(id)) {\n return;\n }\n\n // Delete interfaces from interface controller.\n Object.values(this.state.insights[id])\n .filter((insight) => insight.interfaceId)\n .forEach((insight) => {\n this.messagingSystem.call(\n 'SnapInterfaceController:deleteInterface',\n insight.interfaceId as string,\n );\n });\n\n this.update((state) => {\n delete state.insights[id];\n });\n }\n\n /**\n * Handle sending a request to a given Snap with a given payload.\n *\n * @param args - An options bag.\n * @param args.snapId - The Snap ID.\n * @param args.handler - The handler to invoke.\n * @param args.params - The JSON-RPC params to send.\n * @returns The response from the Snap.\n */\n async #handleSnapRequest({\n snapId,\n handler,\n params,\n }: {\n snapId: SnapId;\n handler: HandlerType.OnTransaction | HandlerType.OnSignature;\n params: Record<string, Json>;\n }) {\n return this.messagingSystem.call('SnapController:handleRequest', {\n snapId,\n origin: '',\n handler,\n request: {\n method: '',\n params,\n },\n });\n }\n\n /**\n * Handle response from a given Snap by persisting the response or error in state.\n *\n * @param args - An options bag.\n * @param args.id - The transaction or signature ID.\n * @param args.snapId - The Snap ID.\n * @param args.response - An optional response object returned by the Snap.\n * @param args.error - An optional error returned by the Snap.\n */\n #handleSnapResponse({\n id,\n snapId,\n response,\n error,\n }: {\n id: string;\n snapId: SnapId;\n response?: Record<string, Json>;\n error?: Error;\n }) {\n this.update((state) => {\n state.insights[id][snapId].loading = false;\n state.insights[id][snapId].interfaceId = response?.id as string;\n state.insights[id][snapId].error = error?.message;\n });\n }\n}\n"],"mappings":";;;;;;;;;AACA,SAAS,sBAAsB;AAM/B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,mBAAmB;AAC5B,SAAS,mBAAmB;AAc5B,IAAM,iBAAiB;AA5BvB;AA2EO,IAAM,yBAAN,cAAqC,eAI1C;AAAA,EACA,YAAY,EAAE,WAAW,MAAM,GAA+B;AAC5D,UAAM;AAAA,MACJ;AAAA,MACA,UAAU;AAAA,QACR,UAAU,EAAE,SAAS,OAAO,WAAW,MAAM;AAAA,MAC/C;AAAA,MACA,MAAM;AAAA,MACN,OAAO,EAAE,UAAU,CAAC,GAAG,GAAG,MAAM;AAAA,IAClC,CAAC;AAwBH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA2BA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA+CA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAwCA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA0DA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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AAS,EAAE;AAAA,EAC1B,CAAC;AACH;AAWM;AAAA,uBAAkB,eAAC;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AACF,GAIG;AACD,SAAO,KAAK,gBAAgB,KAAK,gCAAgC;AAAA,IAC/D;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA,SAAS;AAAA,MACP,QAAQ;AAAA,MACR;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAWA;AAAA,wBAAmB,SAAC;AAAA,EAClB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAKG;AACD,OAAK,OAAO,CAAC,UAAU;AACrB,UAAM,SAAS,EAAE,EAAE,MAAM,EAAE,UAAU;AACrC,UAAM,SAAS,EAAE,EAAE,MAAM,EAAE,cAAc,UAAU;AACnD,UAAM,SAAS,EAAE,EAAE,MAAM,EAAE,QAAQ,OAAO;AAAA,EAC5C,CAAC;AACH;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  AbstractExecutionService
3
- } from "./chunk-QLFH3MC6.mjs";
3
+ } from "./chunk-TSDUJNOP.mjs";
4
4
  import {
5
5
  ProxyPostMessageStream
6
6
  } from "./chunk-ZVOYOZFT.mjs";
@@ -102,4 +102,4 @@ export {
102
102
  WORKER_POOL_ID,
103
103
  WebWorkerExecutionService
104
104
  };
105
- //# sourceMappingURL=chunk-7IJQGFT5.mjs.map
105
+ //# sourceMappingURL=chunk-HLQQTAMM.mjs.map
@@ -0,0 +1 @@
1
+ "use strict";//# sourceMappingURL=chunk-IDCWJJCQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":""}
@@ -15,7 +15,7 @@ var _utils = require('@metamask/utils');
15
15
  var _nanoid = require('nanoid');
16
16
  var MAX_UI_CONTENT_SIZE = 1e7;
17
17
  var controllerName = "SnapInterfaceController";
18
- var _registerMessageHandlers, registerMessageHandlers_fn, _validateArgs, validateArgs_fn, _triggerPhishingListUpdate, triggerPhishingListUpdate_fn, _checkPhishingList, checkPhishingList_fn, _validateContent, validateContent_fn;
18
+ var _registerMessageHandlers, registerMessageHandlers_fn, _validateArgs, validateArgs_fn, _validateApproval, validateApproval_fn, _triggerPhishingListUpdate, triggerPhishingListUpdate_fn, _checkPhishingList, checkPhishingList_fn, _hasApprovalRequest, hasApprovalRequest_fn, _acceptApprovalRequest, acceptApprovalRequest_fn, _validateContent, validateContent_fn;
19
19
  var SnapInterfaceController = class extends _basecontroller.BaseController {
20
20
  constructor({ messenger, state }) {
21
21
  super({
@@ -38,6 +38,12 @@ var SnapInterfaceController = class extends _basecontroller.BaseController {
38
38
  * @param id - The interface id.
39
39
  */
40
40
  _chunkEXN2TFDJjs.__privateAdd.call(void 0, this, _validateArgs);
41
+ /**
42
+ * Utility function to validate that the approval request exists.
43
+ *
44
+ * @param id - The interface id.
45
+ */
46
+ _chunkEXN2TFDJjs.__privateAdd.call(void 0, this, _validateApproval);
41
47
  /**
42
48
  * Trigger a Phishing list update if needed.
43
49
  */
@@ -49,6 +55,21 @@ var SnapInterfaceController = class extends _basecontroller.BaseController {
49
55
  * @returns True if the origin is on the phishing list, otherwise false.
50
56
  */
51
57
  _chunkEXN2TFDJjs.__privateAdd.call(void 0, this, _checkPhishingList);
58
+ /**
59
+ * Check if an approval request exists for a given interface by looking up
60
+ * if the ApprovalController has a request with the given interface ID.
61
+ *
62
+ * @param id - The interface id.
63
+ * @returns True if an approval request exists, otherwise false.
64
+ */
65
+ _chunkEXN2TFDJjs.__privateAdd.call(void 0, this, _hasApprovalRequest);
66
+ /**
67
+ * Accept an approval request for a given interface.
68
+ *
69
+ * @param id - The interface id.
70
+ * @param value - The value to resolve the promise with.
71
+ */
72
+ _chunkEXN2TFDJjs.__privateAdd.call(void 0, this, _acceptApprovalRequest);
52
73
  /**
53
74
  * Utility function to validate the components of an interface.
54
75
  * Throws if something is invalid.
@@ -132,6 +153,20 @@ var SnapInterfaceController = class extends _basecontroller.BaseController {
132
153
  draftState.interfaces[id].state = state;
133
154
  });
134
155
  }
156
+ /**
157
+ * Resolve the promise of a given interface approval request.
158
+ * The approval needs to have the same ID as the interface.
159
+ *
160
+ * @param snapId - The snap id.
161
+ * @param id - The interface id.
162
+ * @param value - The value to resolve the promise with.
163
+ */
164
+ async resolveInterface(snapId, id, value) {
165
+ _chunkEXN2TFDJjs.__privateMethod.call(void 0, this, _validateArgs, validateArgs_fn).call(this, snapId, id);
166
+ _chunkEXN2TFDJjs.__privateMethod.call(void 0, this, _validateApproval, validateApproval_fn).call(this, id);
167
+ await _chunkEXN2TFDJjs.__privateMethod.call(void 0, this, _acceptApprovalRequest, acceptApprovalRequest_fn).call(this, id, value);
168
+ this.deleteInterface(id);
169
+ }
135
170
  };
136
171
  _registerMessageHandlers = new WeakSet();
137
172
  registerMessageHandlers_fn = function() {
@@ -155,6 +190,10 @@ registerMessageHandlers_fn = function() {
155
190
  `${controllerName}:updateInterfaceState`,
156
191
  this.updateInterfaceState.bind(this)
157
192
  );
193
+ this.messagingSystem.registerActionHandler(
194
+ `${controllerName}:resolveInterface`,
195
+ this.resolveInterface.bind(this)
196
+ );
158
197
  };
159
198
  _validateArgs = new WeakSet();
160
199
  validateArgs_fn = function(snapId, id) {
@@ -168,6 +207,13 @@ validateArgs_fn = function(snapId, id) {
168
207
  `Interface not created by ${snapId}.`
169
208
  );
170
209
  };
210
+ _validateApproval = new WeakSet();
211
+ validateApproval_fn = function(id) {
212
+ _utils.assert.call(void 0,
213
+ _chunkEXN2TFDJjs.__privateMethod.call(void 0, this, _hasApprovalRequest, hasApprovalRequest_fn).call(this, id),
214
+ `Approval request with id '${id}' not found.`
215
+ );
216
+ };
171
217
  _triggerPhishingListUpdate = new WeakSet();
172
218
  triggerPhishingListUpdate_fn = async function() {
173
219
  await this.messagingSystem.call("PhishingController:maybeUpdateState");
@@ -176,6 +222,20 @@ _checkPhishingList = new WeakSet();
176
222
  checkPhishingList_fn = function(origin) {
177
223
  return this.messagingSystem.call("PhishingController:testOrigin", origin).result;
178
224
  };
225
+ _hasApprovalRequest = new WeakSet();
226
+ hasApprovalRequest_fn = function(id) {
227
+ return this.messagingSystem.call("ApprovalController:hasRequest", {
228
+ id
229
+ });
230
+ };
231
+ _acceptApprovalRequest = new WeakSet();
232
+ acceptApprovalRequest_fn = async function(id, value) {
233
+ await this.messagingSystem.call(
234
+ "ApprovalController:acceptRequest",
235
+ id,
236
+ value
237
+ );
238
+ };
179
239
  _validateContent = new WeakSet();
180
240
  validateContent_fn = async function(element) {
181
241
  const size = _snapsutils.getJsonSizeUnsafe.call(void 0, element);
@@ -190,4 +250,4 @@ validateContent_fn = async function(element) {
190
250
 
191
251
 
192
252
  exports.SnapInterfaceController = SnapInterfaceController;
193
- //# sourceMappingURL=chunk-BUHS4M6F.js.map
253
+ //# sourceMappingURL=chunk-JLIW4CNS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/interface/SnapInterfaceController.ts"],"names":[],"mappings":";;;;;;;;;;;AAKA,SAAS,sBAAsB;AAY/B,SAAS,mBAAmB,wBAAwB;AAEpD,SAAS,cAAc;AACvB,SAAS,cAAc;AAQvB,IAAM,sBAAsB;AAE5B,IAAM,iBAAiB;AA9BvB;AAuGO,IAAM,0BAAN,cAAsC,eAI3C;AAAA,EACA,YAAY,EAAE,WAAW,MAAM,GAAgC;AAC7D,UAAM;AAAA,MACJ;AAAA,MACA,UAAU;AAAA,QACR,YAAY,EAAE,SAAS,OAAO,WAAW,MAAM;AAAA,MACjD;AAAA,MACA,MAAM;AAAA,MACN,OAAO,EAAE,YAAY,CAAC,GAAG,GAAG,MAAM;AAAA,IACpC,CAAC;AASH;AAAA;AAAA;AAAA;AAAA;AAsJA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkBA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUA;AAAA;AAAA;AAAA,uBAAM;AAUN;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA;AAAA;AAA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,4BAA4B,MAAM;AAAA,EACpC;AACF;AAOA;AAAA,sBAAiB,SAAC,IAAY;AAC5B;AAAA,IACE,sBAAK,4CAAL,WAAyB;AAAA,IACzB,6BAA6B,EAAE;AAAA,EACjC;AACF;AAKM;AAAA,+BAA0B,iBAAG;AACjC,QAAM,KAAK,gBAAgB,KAAK,qCAAqC;AACvE;AAQA;AAAA,uBAAkB,SAAC,QAAgB;AACjC,SAAO,KAAK,gBAAgB,KAAK,iCAAiC,MAAM,EACrE;AACL;AASA;AAAA,wBAAmB,SAAC,IAAY;AAC9B,SAAO,KAAK,gBAAgB,KAAK,iCAAiC;AAAA,IAChE;AAAA,EACF,CAAC;AACH;AAQM;AAAA,2BAAsB,eAAC,IAAY,OAAa;AACpD,QAAM,KAAK,gBAAgB;AAAA,IACzB;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAQM;AAAA,qBAAgB,eAAC,SAAqB;AAG1C,QAAM,OAAO,kBAAkB,OAAO;AACtC;AAAA,IACE,QAAQ;AAAA,IACR,oCAAoC,sBAAsB,GAAO;AAAA,EACnE;AAEA,QAAM,sBAAK,0DAAL;AACN,mBAAiB,SAAS,sBAAK,0CAAmB,KAAK,IAAI,CAAC;AAC9D","sourcesContent":["import type {\n AcceptRequest,\n HasApprovalRequest,\n} from '@metamask/approval-controller';\nimport type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n MaybeUpdateState,\n TestOrigin,\n} from '@metamask/phishing-controller';\nimport type {\n InterfaceState,\n SnapId,\n ComponentOrElement,\n InterfaceContext,\n} from '@metamask/snaps-sdk';\nimport type { JSXElement } from '@metamask/snaps-sdk/jsx';\nimport { getJsonSizeUnsafe, validateJsxLinks } from '@metamask/snaps-utils';\nimport type { Json } from '@metamask/utils';\nimport { assert } from '@metamask/utils';\nimport { nanoid } from 'nanoid';\n\nimport {\n constructState,\n getJsxInterface,\n validateInterfaceContext,\n} from './utils';\n\nconst MAX_UI_CONTENT_SIZE = 10_000_000; // 10 mb\n\nconst controllerName = 'SnapInterfaceController';\n\nexport type CreateInterface = {\n type: `${typeof controllerName}:createInterface`;\n handler: SnapInterfaceController['createInterface'];\n};\n\nexport type GetInterface = {\n type: `${typeof controllerName}:getInterface`;\n handler: SnapInterfaceController['getInterface'];\n};\n\nexport type UpdateInterface = {\n type: `${typeof controllerName}:updateInterface`;\n handler: SnapInterfaceController['updateInterface'];\n};\n\nexport type DeleteInterface = {\n type: `${typeof controllerName}:deleteInterface`;\n handler: SnapInterfaceController['deleteInterface'];\n};\n\nexport type UpdateInterfaceState = {\n type: `${typeof controllerName}:updateInterfaceState`;\n handler: SnapInterfaceController['updateInterfaceState'];\n};\n\nexport type ResolveInterface = {\n type: `${typeof controllerName}:resolveInterface`;\n handler: SnapInterfaceController['resolveInterface'];\n};\n\nexport type SnapInterfaceControllerAllowedActions =\n | TestOrigin\n | MaybeUpdateState\n | HasApprovalRequest\n | AcceptRequest;\n\nexport type SnapInterfaceControllerActions =\n | CreateInterface\n | GetInterface\n | UpdateInterface\n | DeleteInterface\n | UpdateInterfaceState\n | ResolveInterface;\n\nexport type SnapInterfaceControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n SnapInterfaceControllerActions | SnapInterfaceControllerAllowedActions,\n never,\n SnapInterfaceControllerAllowedActions['type'],\n never\n>;\n\nexport type StoredInterface = {\n snapId: SnapId;\n content: JSXElement;\n state: InterfaceState;\n context: InterfaceContext | null;\n};\n\nexport type SnapInterfaceControllerState = {\n interfaces: Record<string, StoredInterface>;\n};\n\nexport type SnapInterfaceControllerArgs = {\n messenger: SnapInterfaceControllerMessenger;\n state?: SnapInterfaceControllerState;\n};\n\n/**\n * Use this controller to manage snaps UI interfaces using RPC method hooks.\n */\nexport class SnapInterfaceController extends BaseController<\n typeof controllerName,\n SnapInterfaceControllerState,\n SnapInterfaceControllerMessenger\n> {\n constructor({ messenger, state }: SnapInterfaceControllerArgs) {\n super({\n messenger,\n metadata: {\n interfaces: { persist: false, anonymous: false },\n },\n name: controllerName,\n state: { interfaces: {}, ...state },\n });\n\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers() {\n this.messagingSystem.registerActionHandler(\n `${controllerName}:createInterface`,\n this.createInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getInterface`,\n this.getInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateInterface`,\n this.updateInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:deleteInterface`,\n this.deleteInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateInterfaceState`,\n this.updateInterfaceState.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:resolveInterface`,\n this.resolveInterface.bind(this),\n );\n }\n\n /**\n * Create an interface in the controller state with the associated data.\n *\n * @param snapId - The snap id that created the interface.\n * @param content - The interface content.\n * @param context - An optional interface context object.\n * @returns The newly interface id.\n */\n async createInterface(\n snapId: SnapId,\n content: ComponentOrElement,\n context?: InterfaceContext,\n ) {\n const element = getJsxInterface(content);\n await this.#validateContent(element);\n validateInterfaceContext(context);\n\n const id = nanoid();\n const componentState = constructState({}, element);\n\n this.update((draftState) => {\n // @ts-expect-error - TS2589: Type instantiation is excessively deep and\n // possibly infinite.\n draftState.interfaces[id] = {\n snapId,\n content: element,\n state: componentState,\n context: context ?? null,\n };\n });\n\n return id;\n }\n\n /**\n * Get the data of a given interface id.\n *\n * @param snapId - The snap id requesting the interface data.\n * @param id - The interface id.\n * @returns The interface state.\n */\n getInterface(snapId: SnapId, id: string) {\n this.#validateArgs(snapId, id);\n\n return this.state.interfaces[id];\n }\n\n /**\n * Update the interface with the given content.\n *\n * @param snapId - The snap id requesting the update.\n * @param id - The interface id.\n * @param content - The new content.\n */\n async updateInterface(\n snapId: SnapId,\n id: string,\n content: ComponentOrElement,\n ) {\n this.#validateArgs(snapId, id);\n const element = getJsxInterface(content);\n await this.#validateContent(element);\n\n const oldState = this.state.interfaces[id].state;\n const newState = constructState(oldState, element);\n\n this.update((draftState) => {\n draftState.interfaces[id].state = newState;\n draftState.interfaces[id].content = element;\n });\n }\n\n /**\n * Delete an interface from state.\n *\n * @param id - The interface id.\n */\n deleteInterface(id: string) {\n this.update((draftState) => {\n delete draftState.interfaces[id];\n });\n }\n\n /**\n * Update the interface state.\n *\n * @param id - The interface id.\n * @param state - The new state.\n */\n updateInterfaceState(id: string, state: InterfaceState) {\n this.update((draftState) => {\n draftState.interfaces[id].state = state;\n });\n }\n\n /**\n * Resolve the promise of a given interface approval request.\n * The approval needs to have the same ID as the interface.\n *\n * @param snapId - The snap id.\n * @param id - The interface id.\n * @param value - The value to resolve the promise with.\n */\n async resolveInterface(snapId: SnapId, id: string, value: Json) {\n this.#validateArgs(snapId, id);\n this.#validateApproval(id);\n\n await this.#acceptApprovalRequest(id, value);\n\n this.deleteInterface(id);\n }\n\n /**\n * Utility function to validate the args passed to the other methods.\n *\n * @param snapId - The snap id.\n * @param id - The interface id.\n */\n #validateArgs(snapId: SnapId, id: string) {\n const existingInterface = this.state.interfaces[id];\n\n assert(\n existingInterface !== undefined,\n `Interface with id '${id}' not found.`,\n );\n assert(\n existingInterface.snapId === snapId,\n `Interface not created by ${snapId}.`,\n );\n }\n\n /**\n * Utility function to validate that the approval request exists.\n *\n * @param id - The interface id.\n */\n #validateApproval(id: string) {\n assert(\n this.#hasApprovalRequest(id),\n `Approval request with id '${id}' not found.`,\n );\n }\n\n /**\n * Trigger a Phishing list update if needed.\n */\n async #triggerPhishingListUpdate() {\n await this.messagingSystem.call('PhishingController:maybeUpdateState');\n }\n\n /**\n * Check an origin against the phishing list.\n *\n * @param origin - The origin to check.\n * @returns True if the origin is on the phishing list, otherwise false.\n */\n #checkPhishingList(origin: string) {\n return this.messagingSystem.call('PhishingController:testOrigin', origin)\n .result;\n }\n\n /**\n * Check if an approval request exists for a given interface by looking up\n * if the ApprovalController has a request with the given interface ID.\n *\n * @param id - The interface id.\n * @returns True if an approval request exists, otherwise false.\n */\n #hasApprovalRequest(id: string) {\n return this.messagingSystem.call('ApprovalController:hasRequest', {\n id,\n });\n }\n\n /**\n * Accept an approval request for a given interface.\n *\n * @param id - The interface id.\n * @param value - The value to resolve the promise with.\n */\n async #acceptApprovalRequest(id: string, value: Json) {\n await this.messagingSystem.call(\n 'ApprovalController:acceptRequest',\n id,\n value,\n );\n }\n\n /**\n * Utility function to validate the components of an interface.\n * Throws if something is invalid.\n *\n * @param element - The JSX element to verify.\n */\n async #validateContent(element: JSXElement) {\n // We assume the validity of this JSON to be validated by the caller.\n // E.g., in the RPC method implementation.\n const size = getJsonSizeUnsafe(element);\n assert(\n size <= MAX_UI_CONTENT_SIZE,\n `A Snap UI may not be larger than ${MAX_UI_CONTENT_SIZE / 1000000} MB.`,\n );\n\n await this.#triggerPhishingListUpdate();\n validateJsxLinks(element, this.#checkPhishingList.bind(this));\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
- var _chunkS775IABYjs = require('./chunk-S775IABY.js');
3
+ var _chunkQRISQRFIjs = require('./chunk-QRISQRFI.js');
4
4
 
5
5
 
6
6
  var _chunkEXN2TFDJjs = require('./chunk-EXN2TFDJ.js');
@@ -8,7 +8,7 @@ var _chunkEXN2TFDJjs = require('./chunk-EXN2TFDJ.js');
8
8
  // src/services/node-js/NodeThreadExecutionService.ts
9
9
  var _postmessagestream = require('@metamask/post-message-stream');
10
10
  var _worker_threads = require('worker_threads');
11
- var NodeThreadExecutionService = class extends _chunkS775IABYjs.AbstractExecutionService {
11
+ var NodeThreadExecutionService = class extends _chunkQRISQRFIjs.AbstractExecutionService {
12
12
  async initEnvStream() {
13
13
  const worker = new (0, _worker_threads.Worker)(
14
14
  _chunkEXN2TFDJjs.__require.resolve(
@@ -36,4 +36,4 @@ var NodeThreadExecutionService = class extends _chunkS775IABYjs.AbstractExecutio
36
36
 
37
37
 
38
38
  exports.NodeThreadExecutionService = NodeThreadExecutionService;
39
- //# sourceMappingURL=chunk-RW7AYHRG.js.map
39
+ //# sourceMappingURL=chunk-KELDSV7H.js.map
@@ -3,10 +3,12 @@ import {
3
3
  } from "./chunk-XO7KDFBY.mjs";
4
4
 
5
5
  // src/utils.ts
6
- import { getErrorMessage } from "@metamask/snaps-sdk";
6
+ import { assert, getErrorMessage } from "@metamask/snaps-sdk";
7
7
  import {
8
+ MAX_FILE_SIZE,
8
9
  encodeBase64,
9
10
  getValidatedLocalizationFiles,
11
+ validateAuxiliaryFiles,
10
12
  validateFetchedSnap
11
13
  } from "@metamask/snaps-utils";
12
14
  import deepEqual from "fast-deep-equal";
@@ -75,12 +77,17 @@ async function fetchSnap(snapId, location) {
75
77
  const sourceCode = await location.fetch(
76
78
  manifest.result.source.location.npm.filePath
77
79
  );
80
+ assert(
81
+ sourceCode.size < MAX_FILE_SIZE,
82
+ "Snap source code must be smaller than 64 MB."
83
+ );
78
84
  const { iconPath } = manifest.result.source.location.npm;
79
85
  const svgIcon = iconPath ? await location.fetch(iconPath) : void 0;
80
86
  const auxiliaryFiles = await getSnapFiles(
81
87
  location,
82
88
  manifest.result.source.files
83
89
  );
90
+ validateAuxiliaryFiles(auxiliaryFiles);
84
91
  await Promise.all(
85
92
  auxiliaryFiles.map(async (file) => {
86
93
  file.data.base64 = await encodeBase64(file);
@@ -106,12 +113,6 @@ async function fetchSnap(snapId, location) {
106
113
  );
107
114
  }
108
115
  }
109
- function calculateConnectionsChange(oldConnectionsSet, desiredConnectionsSet) {
110
- const newConnections = setDiff(desiredConnectionsSet, oldConnectionsSet);
111
- const unusedConnections = setDiff(oldConnectionsSet, desiredConnectionsSet);
112
- const approvedConnections = setDiff(oldConnectionsSet, unusedConnections);
113
- return { newConnections, unusedConnections, approvedConnections };
114
- }
115
116
 
116
117
  export {
117
118
  setDiff,
@@ -121,7 +122,6 @@ export {
121
122
  hasTimedOut,
122
123
  withTimeout,
123
124
  getSnapFiles,
124
- fetchSnap,
125
- calculateConnectionsChange
125
+ fetchSnap
126
126
  };
127
- //# sourceMappingURL=chunk-567BFPSL.mjs.map
127
+ //# sourceMappingURL=chunk-KRI4OKC3.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils.ts"],"sourcesContent":["import type { PermissionConstraint } from '@metamask/permission-controller';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport { assert, getErrorMessage } from '@metamask/snaps-sdk';\nimport {\n MAX_FILE_SIZE,\n encodeBase64,\n getValidatedLocalizationFiles,\n validateAuxiliaryFiles,\n validateFetchedSnap,\n} from '@metamask/snaps-utils';\nimport deepEqual from 'fast-deep-equal';\n\nimport type { SnapLocation } from './snaps';\nimport { Timer } from './snaps/Timer';\n\n/**\n * Takes two objects and does a Set Difference of them.\n * Set Difference is generally defined as follows:\n * ```\n * 𝑥 ∈ A ∖ B ⟺ 𝑥 ∈ A ∧ 𝑥 ∉ B\n * ```\n * Meaning that the returned object contains all properties of A expect those that also\n * appear in B. Notice that properties that appear in B, but not in A, have no effect.\n *\n * @see [Set Difference]{@link https://proofwiki.org/wiki/Definition:Set_Difference}\n * @param objectA - The object on which the difference is being calculated.\n * @param objectB - The object whose properties will be removed from objectA.\n * @returns The objectA without properties from objectB.\n */\nexport function setDiff<\n ObjectA extends Record<any, unknown>,\n ObjectB extends Record<any, unknown>,\n>(objectA: ObjectA, objectB: ObjectB): Diff<ObjectA, ObjectB> {\n return Object.entries(objectA).reduce<Record<any, unknown>>(\n (acc, [key, value]) => {\n if (!(key in objectB)) {\n acc[key] = value;\n }\n return acc;\n },\n {},\n ) as Diff<ObjectA, ObjectB>;\n}\n\n/**\n * Calculate a difference between two permissions objects.\n *\n * Similar to `setDiff` except for one additional condition:\n * Permissions in B should be removed from A if they exist in both and have differing caveats.\n *\n * @param permissionsA - An object containing one or more partial permissions.\n * @param permissionsB - An object containing one or more partial permissions to be subtracted from A.\n * @returns The permissions set A without properties from B.\n */\nexport function permissionsDiff<\n PermissionsA extends Record<string, Pick<PermissionConstraint, 'caveats'>>,\n PermissionsB extends Record<string, Pick<PermissionConstraint, 'caveats'>>,\n>(\n permissionsA: PermissionsA,\n permissionsB: PermissionsB,\n): Diff<PermissionsA, PermissionsB> {\n return Object.entries(permissionsA).reduce<\n Record<string, Pick<PermissionConstraint, 'caveats'>>\n >((acc, [key, value]) => {\n const isIncluded = key in permissionsB;\n if (\n !isIncluded ||\n (isIncluded &&\n !deepEqual(value.caveats ?? [], permissionsB[key].caveats ?? []))\n ) {\n acc[key] = value;\n }\n return acc;\n }, {}) as Diff<PermissionsA, PermissionsB>;\n}\n\n/**\n * A Promise that delays its return for a given amount of milliseconds.\n *\n * @param ms - Milliseconds to delay the execution for.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delay<Result = void>(\n ms: number,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n return delayWithTimer(new Timer(ms), result);\n}\n\n/**\n * A Promise that delays it's return by using a pausable Timer.\n *\n * @param timer - Timer used to control the delay.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delayWithTimer<Result = void>(\n timer: Timer,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n let rejectFunc: (reason: Error) => void;\n const promise: any = new Promise<Result>((resolve: any, reject) => {\n timer.start(() => {\n result === undefined ? resolve() : resolve(result);\n });\n rejectFunc = reject;\n });\n\n promise.cancel = () => {\n if (timer.status !== 'finished') {\n timer.cancel();\n rejectFunc(new Error('The delay has been canceled.'));\n }\n };\n return promise;\n}\n\n/*\n * We use a Symbol instead of rejecting the promise so that Errors thrown\n * by the main promise will propagate.\n */\nexport const hasTimedOut = Symbol(\n 'Used to check if the requested promise has timeout (see withTimeout)',\n);\n\n/**\n * Executes the given Promise, if the Timer expires before the Promise settles, we return earlier.\n *\n * NOTE:** The given Promise is not cancelled or interrupted, and will continue to execute uninterrupted. We will just discard its result if it does not complete before the timeout.\n *\n * @param promise - The promise that you want to execute.\n * @param timerOrMs - The timer controlling the timeout or a ms value.\n * @returns The resolved `PromiseValue`, or the hasTimedOut symbol if\n * returning early.\n * @template PromiseValue - The value of the Promise.\n */\nexport async function withTimeout<PromiseValue = void>(\n promise: Promise<PromiseValue>,\n timerOrMs: Timer | number,\n): Promise<PromiseValue | typeof hasTimedOut> {\n const timer =\n typeof timerOrMs === 'number' ? new Timer(timerOrMs) : timerOrMs;\n const delayPromise = delayWithTimer(timer, hasTimedOut);\n try {\n return await Promise.race([promise, delayPromise]);\n } finally {\n delayPromise.cancel();\n }\n}\n\n/**\n * Checks whether the type is composed of literal types\n *\n * @returns @type {true} if whole type is composed of literals, @type {false} if whole type is not literals, @type {boolean} if mixed\n * @example\n * ```\n * type t1 = IsLiteral<1 | 2 | \"asd\" | true>;\n * // t1 = true\n *\n * type t2 = IsLiteral<number | string>;\n * // t2 = false\n *\n * type t3 = IsLiteral<1 | string>;\n * // t3 = boolean\n *\n * const s = Symbol();\n * type t4 = IsLiteral<typeof s>;\n * // t4 = true\n *\n * type t5 = IsLiteral<symbol>\n * // t5 = false;\n * ```\n */\ntype IsLiteral<Type> = Type extends string | number | boolean | symbol\n ? Extract<string | number | boolean | symbol, Type> extends never\n ? true\n : false\n : false;\n\n/**\n * Returns all keys of an object, that are literal, as an union\n *\n * @example\n * ```\n * type t1 = _LiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'b' | 'c'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype LiteralKeys<Type> = NonNullable<\n {\n [Key in keyof Type]: IsLiteral<Key> extends true ? Key : never;\n }[keyof Type]\n>;\n\n/**\n * Returns all keys of an object, that are not literal, as an union\n *\n * @example\n * ```\n * type t1 = _NonLiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'a' | 'd'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype NonLiteralKeys<Type> = NonNullable<\n {\n [Key in keyof Type]: IsLiteral<Key> extends false ? Key : never;\n }[keyof Type]\n>;\n\n/**\n * A set difference of two objects based on their keys\n *\n * @example\n * ```\n * type t1 = Diff<{a: string, b: string}, {a: number}>\n * // t1 = {b: string};\n * type t2 = Diff<{a: string, 0: string}, Record<string, unknown>>;\n * // t2 = { a?: string, 0: string};\n * type t3 = Diff<{a: string, 0: string, 1: string}, Record<1 | string, unknown>>;\n * // t3 = {a?: string, 0: string}\n * ```\n * @see {@link setDiff} for the main use-case\n */\nexport type Diff<First, Second> = Omit<First, LiteralKeys<Second>> &\n Partial<Pick<First, Extract<keyof First, NonLiteralKeys<Second>>>>;\n\n/**\n * Makes every specified property of the specified object type mutable.\n *\n * @template Type - The object whose readonly properties to make mutable.\n * @template TargetKey - The property key(s) to make mutable.\n */\nexport type Mutable<\n Type extends Record<string, unknown>,\n TargetKey extends string,\n> = {\n -readonly [Key in keyof Pick<Type, TargetKey>]: Type[Key];\n} & {\n [Key in keyof Omit<Type, TargetKey>]: Type[Key];\n};\n\n/**\n * Get all files in a Snap from an array of file paths.\n *\n * @param location - The location of the Snap.\n * @param files - The array of file paths.\n * @returns The array of files as {@link VirtualFile}s.\n */\nexport async function getSnapFiles(\n location: SnapLocation,\n files?: string[] | undefined,\n) {\n if (!files || files.length === 0) {\n return [];\n }\n\n return await Promise.all(\n files.map(async (filePath) => location.fetch(filePath)),\n );\n}\n\n/**\n * Fetch the Snap manifest, source code, and any other files from the given\n * location.\n *\n * @param snapId - The ID of the Snap to fetch.\n * @param location - The location of the Snap.\n * @returns The Snap files and location.\n * @throws If the Snap files are invalid, or if the Snap could not be fetched.\n */\nexport async function fetchSnap(snapId: SnapId, location: SnapLocation) {\n try {\n const manifest = await location.manifest();\n\n const sourceCode = await location.fetch(\n manifest.result.source.location.npm.filePath,\n );\n\n assert(\n sourceCode.size < MAX_FILE_SIZE,\n 'Snap source code must be smaller than 64 MB.',\n );\n\n const { iconPath } = manifest.result.source.location.npm;\n const svgIcon = iconPath ? await location.fetch(iconPath) : undefined;\n\n const auxiliaryFiles = await getSnapFiles(\n location,\n manifest.result.source.files,\n );\n\n validateAuxiliaryFiles(auxiliaryFiles);\n\n await Promise.all(\n auxiliaryFiles.map(async (file) => {\n // This should still be safe\n // eslint-disable-next-line require-atomic-updates\n file.data.base64 = await encodeBase64(file);\n }),\n );\n\n const localizationFiles = await getSnapFiles(\n location,\n manifest.result.source.locales,\n );\n\n const validatedLocalizationFiles =\n getValidatedLocalizationFiles(localizationFiles);\n\n const files = {\n manifest,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles: validatedLocalizationFiles,\n };\n\n await validateFetchedSnap(files);\n\n return files;\n } catch (error) {\n throw new Error(\n `Failed to fetch snap \"${snapId}\": ${getErrorMessage(error)}.`,\n );\n }\n}\n"],"mappings":";;;;;AAEA,SAAS,QAAQ,uBAAuB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,OAAO,eAAe;AAmBf,SAAS,QAGd,SAAkB,SAA0C;AAC5D,SAAO,OAAO,QAAQ,OAAO,EAAE;AAAA,IAC7B,CAAC,KAAK,CAAC,KAAK,KAAK,MAAM;AACrB,UAAI,EAAE,OAAO,UAAU;AACrB,YAAI,GAAG,IAAI;AAAA,MACb;AACA,aAAO;AAAA,IACT;AAAA,IACA,CAAC;AAAA,EACH;AACF;AAYO,SAAS,gBAId,cACA,cACkC;AAClC,SAAO,OAAO,QAAQ,YAAY,EAAE,OAElC,CAAC,KAAK,CAAC,KAAK,KAAK,MAAM;AACvB,UAAM,aAAa,OAAO;AAC1B,QACE,CAAC,cACA,cACC,CAAC,UAAU,MAAM,WAAW,CAAC,GAAG,aAAa,GAAG,EAAE,WAAW,CAAC,CAAC,GACjE;AACA,UAAI,GAAG,IAAI;A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SAAS,OAAO,OAAO,SAAS;AACrD,UAAM,UAAU,WAAW,MAAM,SAAS,MAAM,QAAQ,IAAI;AAE5D,UAAM,iBAAiB,MAAM;AAAA,MAC3B;AAAA,MACA,SAAS,OAAO,OAAO;AAAA,IACzB;AAEA,2BAAuB,cAAc;AAErC,UAAM,QAAQ;AAAA,MACZ,eAAe,IAAI,OAAO,SAAS;AAGjC,aAAK,KAAK,SAAS,MAAM,aAAa,IAAI;AAAA,MAC5C,CAAC;AAAA,IACH;AAEA,UAAM,oBAAoB,MAAM;AAAA,MAC9B;AAAA,MACA,SAAS,OAAO,OAAO;AAAA,IACzB;AAEA,UAAM,6BACJ,8BAA8B,iBAAiB;AAEjD,UAAM,QAAQ;AAAA,MACZ;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,mBAAmB;AAAA,IACrB;AAEA,UAAM,oBAAoB,KAAK;AAE/B,WAAO;AAAA,EACT,SAAS,OAAO;AACd,UAAM,IAAI;AAAA,MACR,yBAAyB,MAAM,MAAM,gBAAgB,KAAK,CAAC;AAAA,IAC7D;AAAA,EACF;AACF;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  AbstractExecutionService
3
- } from "./chunk-QLFH3MC6.mjs";
3
+ } from "./chunk-TSDUJNOP.mjs";
4
4
  import {
5
5
  __require
6
6
  } from "./chunk-YRZVIDCF.mjs";
@@ -35,4 +35,4 @@ var NodeProcessExecutionService = class extends AbstractExecutionService {
35
35
  export {
36
36
  NodeProcessExecutionService
37
37
  };
38
- //# sourceMappingURL=chunk-PMZXFAQI.mjs.map
38
+ //# sourceMappingURL=chunk-KYRKZ3RH.mjs.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  AbstractExecutionService
3
- } from "./chunk-QLFH3MC6.mjs";
3
+ } from "./chunk-TSDUJNOP.mjs";
4
4
 
5
5
  // src/services/iframe/IframeExecutionService.ts
6
6
  import { WindowPostMessageStream } from "@metamask/post-message-stream";
@@ -35,4 +35,4 @@ var IframeExecutionService = class extends AbstractExecutionService {
35
35
  export {
36
36
  IframeExecutionService
37
37
  };
38
- //# sourceMappingURL=chunk-LRVK45HN.mjs.map
38
+ //# sourceMappingURL=chunk-LDL6LJ3P.mjs.map
@@ -0,0 +1 @@
1
+ "use strict";//# sourceMappingURL=chunk-M7DWHPVM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":""}
@@ -1,6 +1,6 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
- var _chunkKH72WRHRjs = require('./chunk-KH72WRHR.js');
3
+ var _chunkFZOI4WPBjs = require('./chunk-FZOI4WPB.js');
4
4
 
5
5
 
6
6
 
@@ -10,7 +10,7 @@ var _chunkEXN2TFDJjs = require('./chunk-EXN2TFDJ.js');
10
10
  // src/services/offscreen/OffscreenExecutionService.ts
11
11
  var _postmessagestream = require('@metamask/post-message-stream');
12
12
  var _offscreenPromise;
13
- var OffscreenExecutionService = class extends _chunkKH72WRHRjs.ProxyExecutionService {
13
+ var OffscreenExecutionService = class extends _chunkFZOI4WPBjs.ProxyExecutionService {
14
14
  /**
15
15
  * Create a new offscreen execution service.
16
16
  *
@@ -55,4 +55,4 @@ _offscreenPromise = new WeakMap();
55
55
 
56
56
 
57
57
  exports.OffscreenExecutionService = OffscreenExecutionService;
58
- //# sourceMappingURL=chunk-6ERB63FH.js.map
58
+ //# sourceMappingURL=chunk-OVATPF5I.js.map