@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.
- package/CHANGELOG.md +37 -1
- package/dist/{chunk-WP3DAIFM.mjs → chunk-23PVLQFV.mjs} +62 -2
- package/dist/chunk-23PVLQFV.mjs.map +1 -0
- package/dist/chunk-272IFIK7.mjs +1 -0
- package/dist/chunk-272IFIK7.mjs.map +1 -0
- package/dist/{chunk-42ODFZSH.mjs → chunk-2AEM5R2M.mjs} +4 -4
- package/dist/{chunk-NZKBY2N7.mjs → chunk-2MH7QYBP.mjs} +47 -11
- package/dist/chunk-2MH7QYBP.mjs.map +1 -0
- package/dist/chunk-2XQD4P2S.mjs +1 -0
- package/dist/chunk-2XQD4P2S.mjs.map +1 -0
- package/dist/{chunk-XSFI32LB.mjs → chunk-33RRV7F4.mjs} +1 -1
- package/dist/{chunk-SAAURQ5A.mjs → chunk-6WGCLJGC.mjs} +2 -2
- package/dist/{chunk-FPGAQ6MT.js → chunk-7BUNUNUC.js} +3 -3
- package/dist/{chunk-CDTGUNSA.js → chunk-B6KTRDBK.js} +9 -9
- package/dist/chunk-B6KTRDBK.js.map +1 -0
- package/dist/{chunk-3AANDIXT.js → chunk-D66YLO7T.js} +3 -3
- package/dist/{chunk-E52MHHG4.js → chunk-FKQTV3LO.js} +55 -19
- package/dist/chunk-FKQTV3LO.js.map +1 -0
- package/dist/{chunk-KH72WRHR.js → chunk-FZOI4WPB.js} +3 -3
- package/dist/chunk-G245VWEY.mjs +275 -0
- package/dist/chunk-G245VWEY.mjs.map +1 -0
- package/dist/{chunk-7IJQGFT5.mjs → chunk-HLQQTAMM.mjs} +2 -2
- package/dist/chunk-IDCWJJCQ.js +1 -0
- package/dist/chunk-IDCWJJCQ.js.map +1 -0
- package/dist/{chunk-BUHS4M6F.js → chunk-JLIW4CNS.js} +62 -2
- package/dist/chunk-JLIW4CNS.js.map +1 -0
- package/dist/{chunk-RW7AYHRG.js → chunk-KELDSV7H.js} +3 -3
- package/dist/{chunk-567BFPSL.mjs → chunk-KRI4OKC3.mjs} +10 -10
- package/dist/chunk-KRI4OKC3.mjs.map +1 -0
- package/dist/{chunk-PMZXFAQI.mjs → chunk-KYRKZ3RH.mjs} +2 -2
- package/dist/{chunk-LRVK45HN.mjs → chunk-LDL6LJ3P.mjs} +2 -2
- package/dist/chunk-M7DWHPVM.js +1 -0
- package/dist/chunk-M7DWHPVM.js.map +1 -0
- package/dist/{chunk-6ERB63FH.js → chunk-OVATPF5I.js} +3 -3
- package/dist/{chunk-HQ6HMINL.js → chunk-P66VIDFG.js} +3 -3
- package/dist/{chunk-PT22IXNS.js → chunk-POQSARDG.js} +3 -3
- package/dist/{chunk-ZRC46TUF.js → chunk-PYSDWIVK.js} +3 -3
- package/dist/{chunk-S775IABY.js → chunk-QRISQRFI.js} +13 -14
- package/dist/{chunk-S775IABY.js.map → chunk-QRISQRFI.js.map} +1 -1
- package/dist/chunk-QYQLJCPR.js +275 -0
- package/dist/chunk-QYQLJCPR.js.map +1 -0
- package/dist/{chunk-QLFH3MC6.mjs → chunk-TSDUJNOP.mjs} +5 -6
- package/dist/chunk-TSDUJNOP.mjs.map +1 -0
- package/dist/{chunk-YUWYMNIX.mjs → chunk-VKMY6CKT.mjs} +2 -2
- package/dist/{chunk-CIFVYFJW.mjs → chunk-WR7CVDEY.mjs} +2 -2
- package/dist/{chunk-GRBWVPLF.js → chunk-XFUP7RFI.js} +1 -1
- package/dist/{chunk-3A72M4GC.mjs → chunk-XOSHP4J3.mjs} +2 -2
- package/dist/cronjob/CronjobController.js +19 -17
- package/dist/cronjob/CronjobController.mjs +18 -16
- package/dist/cronjob/index.js +19 -17
- package/dist/cronjob/index.mjs +18 -16
- package/dist/index.js +31 -28
- package/dist/index.mjs +31 -28
- package/dist/insights/SnapInsightsController.js +25 -0
- package/dist/insights/SnapInsightsController.js.map +1 -0
- package/dist/insights/SnapInsightsController.mjs +25 -0
- package/dist/insights/SnapInsightsController.mjs.map +1 -0
- package/dist/insights/index.js +26 -0
- package/dist/insights/index.js.map +1 -0
- package/dist/insights/index.mjs +26 -0
- package/dist/insights/index.mjs.map +1 -0
- package/dist/interface/SnapInterfaceController.js +2 -2
- package/dist/interface/SnapInterfaceController.mjs +1 -1
- package/dist/interface/index.js +2 -2
- package/dist/interface/index.mjs +1 -1
- package/dist/node.js +33 -30
- package/dist/node.mjs +35 -32
- package/dist/react-native.js +32 -29
- package/dist/react-native.mjs +32 -29
- package/dist/services/AbstractExecutionService.js +3 -3
- package/dist/services/AbstractExecutionService.mjs +2 -2
- package/dist/services/browser.js +10 -10
- package/dist/services/browser.mjs +10 -10
- package/dist/services/iframe/IframeExecutionService.js +4 -4
- package/dist/services/iframe/IframeExecutionService.mjs +3 -3
- package/dist/services/iframe/index.js +4 -4
- package/dist/services/iframe/index.mjs +3 -3
- package/dist/services/index.js +9 -9
- package/dist/services/index.mjs +9 -9
- package/dist/services/node-js/NodeProcessExecutionService.js +9 -9
- package/dist/services/node-js/NodeProcessExecutionService.mjs +8 -8
- package/dist/services/node-js/NodeThreadExecutionService.js +9 -9
- package/dist/services/node-js/NodeThreadExecutionService.mjs +8 -8
- package/dist/services/node-js/index.js +10 -10
- package/dist/services/node-js/index.mjs +11 -11
- package/dist/services/node.js +11 -11
- package/dist/services/node.mjs +13 -13
- package/dist/services/offscreen/OffscreenExecutionService.js +5 -5
- package/dist/services/offscreen/OffscreenExecutionService.mjs +4 -4
- package/dist/services/offscreen/index.js +5 -5
- package/dist/services/offscreen/index.mjs +4 -4
- package/dist/services/proxy/ProxyExecutionService.js +4 -4
- package/dist/services/proxy/ProxyExecutionService.mjs +3 -3
- package/dist/services/react-native.js +10 -10
- package/dist/services/react-native.mjs +10 -10
- package/dist/services/webview/WebViewExecutionService.js +5 -5
- package/dist/services/webview/WebViewExecutionService.mjs +4 -4
- package/dist/services/webview/index.js +5 -5
- package/dist/services/webview/index.mjs +4 -4
- package/dist/services/webworker/WebWorkerExecutionService.js +4 -4
- package/dist/services/webworker/WebWorkerExecutionService.mjs +3 -3
- package/dist/services/webworker/index.js +4 -4
- package/dist/services/webworker/index.mjs +3 -3
- package/dist/snaps/SnapController.js +5 -5
- package/dist/snaps/SnapController.mjs +4 -4
- package/dist/snaps/index.js +10 -10
- package/dist/snaps/index.mjs +9 -9
- package/dist/snaps/location/index.js +4 -4
- package/dist/snaps/location/index.mjs +4 -4
- package/dist/snaps/location/location.js +3 -3
- package/dist/snaps/location/location.mjs +2 -2
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/dist/types/controllers.js +2 -0
- package/dist/types/controllers.js.map +1 -0
- package/dist/types/controllers.mjs +2 -0
- package/dist/types/controllers.mjs.map +1 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.js +2 -1
- package/dist/types/index.mjs +1 -0
- package/dist/types/insights/SnapInsightsController.d.ts +33 -0
- package/dist/types/insights/index.d.ts +1 -0
- package/dist/types/interface/SnapInterfaceController.d.ts +17 -2
- package/dist/types/types/controllers.d.ts +131 -0
- package/dist/types/types/index.d.ts +1 -0
- package/dist/types/utils.d.ts +0 -13
- package/dist/utils.js +2 -4
- package/dist/utils.mjs +1 -3
- package/package.json +14 -14
- package/dist/chunk-567BFPSL.mjs.map +0 -1
- package/dist/chunk-BUHS4M6F.js.map +0 -1
- package/dist/chunk-CDTGUNSA.js.map +0 -1
- package/dist/chunk-E52MHHG4.js.map +0 -1
- package/dist/chunk-NZKBY2N7.mjs.map +0 -1
- package/dist/chunk-QLFH3MC6.mjs.map +0 -1
- package/dist/chunk-WP3DAIFM.mjs.map +0 -1
- /package/dist/{chunk-42ODFZSH.mjs.map → chunk-2AEM5R2M.mjs.map} +0 -0
- /package/dist/{chunk-XSFI32LB.mjs.map → chunk-33RRV7F4.mjs.map} +0 -0
- /package/dist/{chunk-SAAURQ5A.mjs.map → chunk-6WGCLJGC.mjs.map} +0 -0
- /package/dist/{chunk-FPGAQ6MT.js.map → chunk-7BUNUNUC.js.map} +0 -0
- /package/dist/{chunk-3AANDIXT.js.map → chunk-D66YLO7T.js.map} +0 -0
- /package/dist/{chunk-KH72WRHR.js.map → chunk-FZOI4WPB.js.map} +0 -0
- /package/dist/{chunk-7IJQGFT5.mjs.map → chunk-HLQQTAMM.mjs.map} +0 -0
- /package/dist/{chunk-RW7AYHRG.js.map → chunk-KELDSV7H.js.map} +0 -0
- /package/dist/{chunk-PMZXFAQI.mjs.map → chunk-KYRKZ3RH.mjs.map} +0 -0
- /package/dist/{chunk-LRVK45HN.mjs.map → chunk-LDL6LJ3P.mjs.map} +0 -0
- /package/dist/{chunk-6ERB63FH.js.map → chunk-OVATPF5I.js.map} +0 -0
- /package/dist/{chunk-HQ6HMINL.js.map → chunk-P66VIDFG.js.map} +0 -0
- /package/dist/{chunk-PT22IXNS.js.map → chunk-POQSARDG.js.map} +0 -0
- /package/dist/{chunk-ZRC46TUF.js.map → chunk-PYSDWIVK.js.map} +0 -0
- /package/dist/{chunk-YUWYMNIX.mjs.map → chunk-VKMY6CKT.mjs.map} +0 -0
- /package/dist/{chunk-CIFVYFJW.mjs.map → chunk-WR7CVDEY.mjs.map} +0 -0
- /package/dist/{chunk-GRBWVPLF.js.map → chunk-XFUP7RFI.js.map} +0 -0
- /package/dist/{chunk-3A72M4GC.mjs.map → chunk-XOSHP4J3.mjs.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":""}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/dist/types/index.d.ts
CHANGED
package/dist/types/index.js
CHANGED
package/dist/types/index.mjs
CHANGED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { RestrictedControllerMessenger } from '@metamask/base-controller';
|
|
2
|
+
import { BaseController } from '@metamask/base-controller';
|
|
3
|
+
import type { GetPermissions } from '@metamask/permission-controller';
|
|
4
|
+
import type { SnapId } from '@metamask/snaps-sdk';
|
|
5
|
+
import type { DeleteInterface } from '../interface';
|
|
6
|
+
import type { GetAllSnaps, HandleSnapRequest } from '../snaps';
|
|
7
|
+
import type { TransactionControllerUnapprovedTransactionAddedEvent, SignatureStateChange, TransactionControllerTransactionStatusUpdatedEvent } from '../types';
|
|
8
|
+
declare const controllerName = "SnapInsightsController";
|
|
9
|
+
export declare type SnapInsightsControllerAllowedActions = HandleSnapRequest | GetAllSnaps | GetPermissions | DeleteInterface;
|
|
10
|
+
export declare type SnapInsightsControllerActions = never;
|
|
11
|
+
export declare type SnapInsightsControllerAllowedEvents = TransactionControllerUnapprovedTransactionAddedEvent | TransactionControllerTransactionStatusUpdatedEvent | SignatureStateChange;
|
|
12
|
+
export declare type SnapInsightsControllerMessenger = RestrictedControllerMessenger<typeof controllerName, SnapInsightsControllerActions | SnapInsightsControllerAllowedActions, SnapInsightsControllerAllowedEvents, SnapInsightsControllerAllowedActions['type'], SnapInsightsControllerAllowedEvents['type']>;
|
|
13
|
+
export declare type SnapInsight = {
|
|
14
|
+
snapId: SnapId;
|
|
15
|
+
interfaceId?: string | null;
|
|
16
|
+
error?: string;
|
|
17
|
+
loading: boolean;
|
|
18
|
+
};
|
|
19
|
+
export declare type SnapInsightsControllerState = {
|
|
20
|
+
insights: Record<string, Record<SnapId, SnapInsight>>;
|
|
21
|
+
};
|
|
22
|
+
export declare type SnapInsightsControllerArgs = {
|
|
23
|
+
messenger: SnapInsightsControllerMessenger;
|
|
24
|
+
state?: SnapInsightsControllerState;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Controller for monitoring for new transactions and signatures to provide insight for.
|
|
28
|
+
*/
|
|
29
|
+
export declare class SnapInsightsController extends BaseController<typeof controllerName, SnapInsightsControllerState, SnapInsightsControllerMessenger> {
|
|
30
|
+
#private;
|
|
31
|
+
constructor({ messenger, state }: SnapInsightsControllerArgs);
|
|
32
|
+
}
|
|
33
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './SnapInsightsController';
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import type { AcceptRequest, HasApprovalRequest } from '@metamask/approval-controller';
|
|
1
2
|
import type { RestrictedControllerMessenger } from '@metamask/base-controller';
|
|
2
3
|
import { BaseController } from '@metamask/base-controller';
|
|
3
4
|
import type { MaybeUpdateState, TestOrigin } from '@metamask/phishing-controller';
|
|
4
5
|
import type { InterfaceState, SnapId, ComponentOrElement, InterfaceContext } from '@metamask/snaps-sdk';
|
|
5
6
|
import type { JSXElement } from '@metamask/snaps-sdk/jsx';
|
|
7
|
+
import type { Json } from '@metamask/utils';
|
|
6
8
|
declare const controllerName = "SnapInterfaceController";
|
|
7
9
|
export declare type CreateInterface = {
|
|
8
10
|
type: `${typeof controllerName}:createInterface`;
|
|
@@ -24,8 +26,12 @@ export declare type UpdateInterfaceState = {
|
|
|
24
26
|
type: `${typeof controllerName}:updateInterfaceState`;
|
|
25
27
|
handler: SnapInterfaceController['updateInterfaceState'];
|
|
26
28
|
};
|
|
27
|
-
export declare type
|
|
28
|
-
|
|
29
|
+
export declare type ResolveInterface = {
|
|
30
|
+
type: `${typeof controllerName}:resolveInterface`;
|
|
31
|
+
handler: SnapInterfaceController['resolveInterface'];
|
|
32
|
+
};
|
|
33
|
+
export declare type SnapInterfaceControllerAllowedActions = TestOrigin | MaybeUpdateState | HasApprovalRequest | AcceptRequest;
|
|
34
|
+
export declare type SnapInterfaceControllerActions = CreateInterface | GetInterface | UpdateInterface | DeleteInterface | UpdateInterfaceState | ResolveInterface;
|
|
29
35
|
export declare type SnapInterfaceControllerMessenger = RestrictedControllerMessenger<typeof controllerName, SnapInterfaceControllerActions | SnapInterfaceControllerAllowedActions, never, SnapInterfaceControllerAllowedActions['type'], never>;
|
|
30
36
|
export declare type StoredInterface = {
|
|
31
37
|
snapId: SnapId;
|
|
@@ -84,5 +90,14 @@ export declare class SnapInterfaceController extends BaseController<typeof contr
|
|
|
84
90
|
* @param state - The new state.
|
|
85
91
|
*/
|
|
86
92
|
updateInterfaceState(id: string, state: InterfaceState): void;
|
|
93
|
+
/**
|
|
94
|
+
* Resolve the promise of a given interface approval request.
|
|
95
|
+
* The approval needs to have the same ID as the interface.
|
|
96
|
+
*
|
|
97
|
+
* @param snapId - The snap id.
|
|
98
|
+
* @param id - The interface id.
|
|
99
|
+
* @param value - The value to resolve the promise with.
|
|
100
|
+
*/
|
|
101
|
+
resolveInterface(snapId: SnapId, id: string, value: Json): Promise<void>;
|
|
87
102
|
}
|
|
88
103
|
export {};
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import type { ControllerStateChangeEvent } from '@metamask/base-controller';
|
|
2
|
+
import type { Hex, Json } from '@metamask/utils';
|
|
3
|
+
export declare type TransactionMeta = {
|
|
4
|
+
/**
|
|
5
|
+
* Generated UUID associated with this transaction.
|
|
6
|
+
*/
|
|
7
|
+
id: string;
|
|
8
|
+
/**
|
|
9
|
+
* Network code as per EIP-155 for this transaction.
|
|
10
|
+
*/
|
|
11
|
+
chainId: Hex;
|
|
12
|
+
/**
|
|
13
|
+
* Origin this transaction was sent from.
|
|
14
|
+
*/
|
|
15
|
+
origin?: string;
|
|
16
|
+
/**
|
|
17
|
+
* Underlying Transaction object.
|
|
18
|
+
*/
|
|
19
|
+
txParams: TransactionParams;
|
|
20
|
+
/**
|
|
21
|
+
* The status of the transaction.
|
|
22
|
+
*/
|
|
23
|
+
status: string;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Standard data concerning a transaction to be processed by the blockchain.
|
|
27
|
+
*/
|
|
28
|
+
export declare type TransactionParams = {
|
|
29
|
+
/**
|
|
30
|
+
* Network ID as per EIP-155.
|
|
31
|
+
*/
|
|
32
|
+
chainId?: Hex;
|
|
33
|
+
/**
|
|
34
|
+
* Data to pass with this transaction.
|
|
35
|
+
*/
|
|
36
|
+
data?: string;
|
|
37
|
+
/**
|
|
38
|
+
* Error message for gas estimation failure.
|
|
39
|
+
*/
|
|
40
|
+
estimateGasError?: string;
|
|
41
|
+
/**
|
|
42
|
+
* Estimated base fee for this transaction.
|
|
43
|
+
*/
|
|
44
|
+
estimatedBaseFee?: string;
|
|
45
|
+
/**
|
|
46
|
+
* Which estimate level that the API suggested.
|
|
47
|
+
*/
|
|
48
|
+
estimateSuggested?: string;
|
|
49
|
+
/**
|
|
50
|
+
* Which estimate level was used
|
|
51
|
+
*/
|
|
52
|
+
estimateUsed?: string;
|
|
53
|
+
/**
|
|
54
|
+
* Address to send this transaction from.
|
|
55
|
+
*/
|
|
56
|
+
from: string;
|
|
57
|
+
/**
|
|
58
|
+
* same as gasLimit?
|
|
59
|
+
*/
|
|
60
|
+
gas?: string;
|
|
61
|
+
/**
|
|
62
|
+
* Maxmimum number of units of gas to use for this transaction.
|
|
63
|
+
*/
|
|
64
|
+
gasLimit?: string;
|
|
65
|
+
/**
|
|
66
|
+
* Price per gas for legacy txs
|
|
67
|
+
*/
|
|
68
|
+
gasPrice?: string;
|
|
69
|
+
/**
|
|
70
|
+
* Gas used in the transaction.
|
|
71
|
+
*/
|
|
72
|
+
gasUsed?: string;
|
|
73
|
+
/**
|
|
74
|
+
* Maximum amount per gas to pay for the transaction, including the priority
|
|
75
|
+
* fee.
|
|
76
|
+
*/
|
|
77
|
+
maxFeePerGas?: string;
|
|
78
|
+
/**
|
|
79
|
+
* Maximum amount per gas to give to validator as incentive.
|
|
80
|
+
*/
|
|
81
|
+
maxPriorityFeePerGas?: string;
|
|
82
|
+
/**
|
|
83
|
+
* Unique number to prevent replay attacks.
|
|
84
|
+
*/
|
|
85
|
+
nonce?: string;
|
|
86
|
+
/**
|
|
87
|
+
* Address to send this transaction to.
|
|
88
|
+
*/
|
|
89
|
+
to?: string;
|
|
90
|
+
/**
|
|
91
|
+
* Value associated with this transaction.
|
|
92
|
+
*/
|
|
93
|
+
value?: string;
|
|
94
|
+
/**
|
|
95
|
+
* Type of transaction.
|
|
96
|
+
* 0x0 indicates a legacy transaction.
|
|
97
|
+
*/
|
|
98
|
+
type?: string;
|
|
99
|
+
};
|
|
100
|
+
export declare type TransactionControllerUnapprovedTransactionAddedEvent = {
|
|
101
|
+
type: `TransactionController:unapprovedTransactionAdded`;
|
|
102
|
+
payload: [transactionMeta: TransactionMeta];
|
|
103
|
+
};
|
|
104
|
+
export declare type TransactionControllerTransactionStatusUpdatedEvent = {
|
|
105
|
+
type: `TransactionController:transactionStatusUpdated`;
|
|
106
|
+
payload: [
|
|
107
|
+
{
|
|
108
|
+
transactionMeta: TransactionMeta;
|
|
109
|
+
}
|
|
110
|
+
];
|
|
111
|
+
};
|
|
112
|
+
export declare type StateSignatureParams = {
|
|
113
|
+
from: string;
|
|
114
|
+
origin?: string;
|
|
115
|
+
deferSetAsSigned?: boolean;
|
|
116
|
+
data: string | Record<string, Json>;
|
|
117
|
+
signatureMethod: string;
|
|
118
|
+
};
|
|
119
|
+
export declare type StateSignature = {
|
|
120
|
+
id: string;
|
|
121
|
+
msgParams: StateSignatureParams;
|
|
122
|
+
};
|
|
123
|
+
export declare type SignatureControllerState = {
|
|
124
|
+
unapprovedPersonalMsgs: Record<string, StateSignature>;
|
|
125
|
+
unapprovedTypedMessages: Record<string, StateSignature>;
|
|
126
|
+
unapprovedPersonalMsgCount: number;
|
|
127
|
+
unapprovedTypedMessagesCount: number;
|
|
128
|
+
};
|
|
129
|
+
declare const signatureControllerName = "SignatureController";
|
|
130
|
+
export declare type SignatureStateChange = ControllerStateChangeEvent<typeof signatureControllerName, SignatureControllerState>;
|
|
131
|
+
export {};
|
package/dist/types/utils.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import type { PermissionConstraint } from '@metamask/permission-controller';
|
|
2
2
|
import type { SnapId } from '@metamask/snaps-sdk';
|
|
3
|
-
import type { Json } from '@metamask/utils';
|
|
4
3
|
import type { SnapLocation } from './snaps';
|
|
5
4
|
import { Timer } from './snaps/Timer';
|
|
6
5
|
/**
|
|
@@ -242,16 +241,4 @@ export declare function fetchSnap(snapId: SnapId, location: SnapLocation): Promi
|
|
|
242
241
|
}>;
|
|
243
242
|
}>[];
|
|
244
243
|
}>;
|
|
245
|
-
/**
|
|
246
|
-
* Calculate change of initialConnections.
|
|
247
|
-
*
|
|
248
|
-
* @param oldConnectionsSet - Previously approved connections.
|
|
249
|
-
* @param desiredConnectionsSet - New connections.
|
|
250
|
-
* @returns Object containing newConnections, unusedConnections and approvedConnections.
|
|
251
|
-
*/
|
|
252
|
-
export declare function calculateConnectionsChange(oldConnectionsSet: Record<string, Json>, desiredConnectionsSet: Record<string, Json>): {
|
|
253
|
-
newConnections: Record<string, Json>;
|
|
254
|
-
unusedConnections: Record<string, Json>;
|
|
255
|
-
approvedConnections: Record<string, Json>;
|
|
256
|
-
};
|
|
257
244
|
export {};
|
package/dist/utils.js
CHANGED
|
@@ -7,8 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
|
|
10
|
-
|
|
11
|
-
var _chunkCDTGUNSAjs = require('./chunk-CDTGUNSA.js');
|
|
10
|
+
var _chunkB6KTRDBKjs = require('./chunk-B6KTRDBK.js');
|
|
12
11
|
require('./chunk-BOFPNIRX.js');
|
|
13
12
|
require('./chunk-EXN2TFDJ.js');
|
|
14
13
|
|
|
@@ -20,6 +19,5 @@ require('./chunk-EXN2TFDJ.js');
|
|
|
20
19
|
|
|
21
20
|
|
|
22
21
|
|
|
23
|
-
|
|
24
|
-
exports.calculateConnectionsChange = _chunkCDTGUNSAjs.calculateConnectionsChange; exports.delay = _chunkCDTGUNSAjs.delay; exports.delayWithTimer = _chunkCDTGUNSAjs.delayWithTimer; exports.fetchSnap = _chunkCDTGUNSAjs.fetchSnap; exports.getSnapFiles = _chunkCDTGUNSAjs.getSnapFiles; exports.hasTimedOut = _chunkCDTGUNSAjs.hasTimedOut; exports.permissionsDiff = _chunkCDTGUNSAjs.permissionsDiff; exports.setDiff = _chunkCDTGUNSAjs.setDiff; exports.withTimeout = _chunkCDTGUNSAjs.withTimeout;
|
|
22
|
+
exports.delay = _chunkB6KTRDBKjs.delay; exports.delayWithTimer = _chunkB6KTRDBKjs.delayWithTimer; exports.fetchSnap = _chunkB6KTRDBKjs.fetchSnap; exports.getSnapFiles = _chunkB6KTRDBKjs.getSnapFiles; exports.hasTimedOut = _chunkB6KTRDBKjs.hasTimedOut; exports.permissionsDiff = _chunkB6KTRDBKjs.permissionsDiff; exports.setDiff = _chunkB6KTRDBKjs.setDiff; exports.withTimeout = _chunkB6KTRDBKjs.withTimeout;
|
|
25
23
|
//# sourceMappingURL=utils.js.map
|
package/dist/utils.mjs
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import {
|
|
2
|
-
calculateConnectionsChange,
|
|
3
2
|
delay,
|
|
4
3
|
delayWithTimer,
|
|
5
4
|
fetchSnap,
|
|
@@ -8,11 +7,10 @@ import {
|
|
|
8
7
|
permissionsDiff,
|
|
9
8
|
setDiff,
|
|
10
9
|
withTimeout
|
|
11
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-KRI4OKC3.mjs";
|
|
12
11
|
import "./chunk-XO7KDFBY.mjs";
|
|
13
12
|
import "./chunk-YRZVIDCF.mjs";
|
|
14
13
|
export {
|
|
15
|
-
calculateConnectionsChange,
|
|
16
14
|
delay,
|
|
17
15
|
delayWithTimer,
|
|
18
16
|
fetchSnap,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/snaps-controllers",
|
|
3
|
-
"version": "9.
|
|
3
|
+
"version": "9.3.1",
|
|
4
4
|
"description": "Controllers for MetaMask Snaps.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -53,20 +53,20 @@
|
|
|
53
53
|
"build:ci": "tsup --clean"
|
|
54
54
|
},
|
|
55
55
|
"dependencies": {
|
|
56
|
-
"@metamask/approval-controller": "^7.0.
|
|
57
|
-
"@metamask/base-controller": "^6.0.
|
|
58
|
-
"@metamask/json-rpc-engine": "^9.0.
|
|
59
|
-
"@metamask/json-rpc-middleware-stream": "^8.0.
|
|
56
|
+
"@metamask/approval-controller": "^7.0.2",
|
|
57
|
+
"@metamask/base-controller": "^6.0.2",
|
|
58
|
+
"@metamask/json-rpc-engine": "^9.0.2",
|
|
59
|
+
"@metamask/json-rpc-middleware-stream": "^8.0.2",
|
|
60
60
|
"@metamask/object-multiplex": "^2.0.0",
|
|
61
|
-
"@metamask/permission-controller": "^
|
|
62
|
-
"@metamask/phishing-controller": "^10.
|
|
61
|
+
"@metamask/permission-controller": "^11.0.0",
|
|
62
|
+
"@metamask/phishing-controller": "^10.1.1",
|
|
63
63
|
"@metamask/post-message-stream": "^8.1.0",
|
|
64
|
-
"@metamask/rpc-errors": "^6.
|
|
65
|
-
"@metamask/snaps-registry": "^3.1
|
|
66
|
-
"@metamask/snaps-rpc-methods": "^
|
|
67
|
-
"@metamask/snaps-sdk": "^6.
|
|
68
|
-
"@metamask/snaps-utils": "^7.
|
|
69
|
-
"@metamask/utils": "^
|
|
64
|
+
"@metamask/rpc-errors": "^6.3.1",
|
|
65
|
+
"@metamask/snaps-registry": "^3.2.1",
|
|
66
|
+
"@metamask/snaps-rpc-methods": "^10.0.1",
|
|
67
|
+
"@metamask/snaps-sdk": "^6.1.0",
|
|
68
|
+
"@metamask/snaps-utils": "^7.8.1",
|
|
69
|
+
"@metamask/utils": "^9.1.0",
|
|
70
70
|
"@xstate/fsm": "^2.0.0",
|
|
71
71
|
"browserify-zlib": "^0.2.0",
|
|
72
72
|
"concat-stream": "^2.0.0",
|
|
@@ -138,7 +138,7 @@
|
|
|
138
138
|
"webdriverio": "^8.19.0"
|
|
139
139
|
},
|
|
140
140
|
"peerDependencies": {
|
|
141
|
-
"@metamask/snaps-execution-environments": "^6.
|
|
141
|
+
"@metamask/snaps-execution-environments": "^6.6.2"
|
|
142
142
|
},
|
|
143
143
|
"peerDependenciesMeta": {
|
|
144
144
|
"@metamask/snaps-execution-environments": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils.ts"],"sourcesContent":["import type { PermissionConstraint } from '@metamask/permission-controller';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport { getErrorMessage } from '@metamask/snaps-sdk';\nimport {\n encodeBase64,\n getValidatedLocalizationFiles,\n validateFetchedSnap,\n} from '@metamask/snaps-utils';\nimport type { Json } from '@metamask/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 const sourceCode = await location.fetch(\n manifest.result.source.location.npm.filePath,\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 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\n/**\n * Calculate change of initialConnections.\n *\n * @param oldConnectionsSet - Previously approved connections.\n * @param desiredConnectionsSet - New connections.\n * @returns Object containing newConnections, unusedConnections and approvedConnections.\n */\nexport function calculateConnectionsChange(\n oldConnectionsSet: Record<string, Json>,\n desiredConnectionsSet: Record<string, Json>,\n): {\n newConnections: Record<string, Json>;\n unusedConnections: Record<string, Json>;\n approvedConnections: Record<string, Json>;\n} {\n const newConnections = setDiff(desiredConnectionsSet, oldConnectionsSet);\n\n const unusedConnections = setDiff(oldConnectionsSet, desiredConnectionsSet);\n\n // It's a Set Intersection of oldConnections and desiredConnectionsSet\n // oldConnections ∖ (oldConnections ∖ desiredConnectionsSet) ⟺ oldConnections ∩ desiredConnectionsSet\n const approvedConnections = setDiff(oldConnectionsSet, unusedConnections);\n\n return { newConnections, unusedConnections, approvedConnections };\n}\n"],"mappings":";;;;;AAEA,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,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,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E;AAAA,EAC1B;AACA;AAAA,IACE,kBAAkB,WAAW;AAAA,IAC7B,4BAA4B,MAAM;AAAA,EACpC;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;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 { 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 { 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 SnapInterfaceControllerAllowedActions =\n | TestOrigin\n | MaybeUpdateState;\n\nexport type SnapInterfaceControllerActions =\n | CreateInterface\n | GetInterface\n | UpdateInterface\n | DeleteInterface\n | UpdateInterfaceState;\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\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 * 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 * 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 * 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 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils.ts"],"names":[],"mappings":";;;;;AAEA,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,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,C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AAM,EAAE,SAAS,IAAI,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,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;AASO,SAAS,2BACd,mBACA,uBAKA;AACA,QAAM,iBAAiB,QAAQ,uBAAuB,iBAAiB;AAEvE,QAAM,oBAAoB,QAAQ,mBAAmB,qBAAqB;AAI1E,QAAM,sBAAsB,QAAQ,mBAAmB,iBAAiB;AAExE,SAAO,EAAE,gBAAgB,mBAAmB,oBAAoB;AAClE","sourcesContent":["import type { PermissionConstraint } from '@metamask/permission-controller';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport { getErrorMessage } from '@metamask/snaps-sdk';\nimport {\n encodeBase64,\n getValidatedLocalizationFiles,\n validateFetchedSnap,\n} from '@metamask/snaps-utils';\nimport type { Json } from '@metamask/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 const sourceCode = await location.fetch(\n manifest.result.source.location.npm.filePath,\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 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\n/**\n * Calculate change of initialConnections.\n *\n * @param oldConnectionsSet - Previously approved connections.\n * @param desiredConnectionsSet - New connections.\n * @returns Object containing newConnections, unusedConnections and approvedConnections.\n */\nexport function calculateConnectionsChange(\n oldConnectionsSet: Record<string, Json>,\n desiredConnectionsSet: Record<string, Json>,\n): {\n newConnections: Record<string, Json>;\n unusedConnections: Record<string, Json>;\n approvedConnections: Record<string, Json>;\n} {\n const newConnections = setDiff(desiredConnectionsSet, oldConnectionsSet);\n\n const unusedConnections = setDiff(oldConnectionsSet, desiredConnectionsSet);\n\n // It's a Set Intersection of oldConnections and desiredConnectionsSet\n // oldConnections ∖ (oldConnections ∖ desiredConnectionsSet) ⟺ oldConnections ∩ desiredConnectionsSet\n const approvedConnections = setDiff(oldConnectionsSet, unusedConnections);\n\n return { newConnections, unusedConnections, approvedConnections };\n}\n"]}
|