@metamask-previews/base-controller 3.2.3-preview.4ae7d84 → 3.2.3-preview.5736db0
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/dist/BaseController.d.ts.map +1 -1
- package/dist/BaseController.js.map +1 -1
- package/dist/BaseControllerV2.d.ts +26 -15
- package/dist/BaseControllerV2.d.ts.map +1 -1
- package/dist/BaseControllerV2.js +22 -8
- package/dist/BaseControllerV2.js.map +1 -1
- package/dist/ControllerMessenger.d.ts +53 -211
- package/dist/ControllerMessenger.d.ts.map +1 -1
- package/dist/ControllerMessenger.js +34 -200
- package/dist/ControllerMessenger.js.map +1 -1
- package/dist/RestrictedControllerMessenger.d.ts +158 -0
- package/dist/RestrictedControllerMessenger.d.ts.map +1 -0
- package/dist/RestrictedControllerMessenger.js +199 -0
- package/dist/RestrictedControllerMessenger.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseController.d.ts","sourceRoot":"","sources":["../src/BaseController.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,oBAAY,QAAQ,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC,KAAK,IAAI,CAAC;AAE7C;;;;;GAKG;
|
|
1
|
+
{"version":3,"file":"BaseController.d.ts","sourceRoot":"","sources":["../src/BaseController.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,oBAAY,QAAQ,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC,KAAK,IAAI,CAAC;AAE7C;;;;;GAKG;AAIH,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAED;;;;;GAKG;AAIH,MAAM,WAAW,SAAS;IACxB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED;;;;;;GAMG;AACH,qBAAa,cAAc,CAAC,CAAC,SAAS,UAAU,EAAE,CAAC,SAAS,SAAS;IACnE;;OAEG;IACH,aAAa,EAAE,CAAC,CAAW;IAE3B;;OAEG;IACH,YAAY,EAAE,CAAC,CAAW;IAE1B;;OAEG;IACH,QAAQ,UAAS;IAEjB;;OAEG;IACH,IAAI,SAAoB;IAExB,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAI;IAElC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAI;IAEjC,OAAO,CAAC,cAAc,CAAyB;IAE/C,OAAO,CAAC,aAAa,CAAwB;IAE7C,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAqB;IAEvD;;;;;;OAMG;gBACS,MAAM,GAAE,OAAO,CAAC,CAAC,CAAW,EAAE,KAAK,GAAE,OAAO,CAAC,CAAC,CAAW;IAMrE;;;;;;OAMG;IACH,SAAS,CAAC,UAAU;IAQpB;;;;OAIG;IACH,IAAI,MAAM,MAET;IAED;;;;OAIG;IACH,IAAI,KAAK,MAER;IAED;;;;;;OAMG;IACH,SAAS,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,SAAS,UAAQ,EAAE,UAAU,UAAO;IAsBlE;;OAEG;IACH,MAAM;IAUN;;;;OAIG;IACH,SAAS,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC;IAI/B;;;;;OAKG;IACH,WAAW,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC;IAMjC;;;;;OAKG;IACH,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,SAAS,UAAQ;CAM5C;AAED,eAAe,cAAc,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseController.js","sourceRoot":"","sources":["../src/BaseController.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"BaseController.js","sourceRoot":"","sources":["../src/BaseController.ts"],"names":[],"mappings":";;;AA+BA;;;;;;GAMG;AAC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AC,KAAiB,EAAE,SAAS,GAAG,KAAK;QACzC,IAAI,CAAC,aAAa,GAAG,SAAS;YAC5B,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,KAAU,CAAC;YAC/B,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;QACjD,IAAI,CAAC,MAAM,EAAE,CAAC;IAChB,CAAC;CACF;AAxJD,wCAwJC;AAED,kBAAe,cAAc,CAAC","sourcesContent":["/**\n * State change callbacks\n */\nexport type Listener<T> = (state: T) => void;\n\n/**\n * @type BaseConfig\n *\n * Base controller configuration\n * @property disabled - Determines if this controller is enabled\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface BaseConfig {\n disabled?: boolean;\n}\n\n/**\n * @type BaseState\n *\n * Base state representation\n * @property name - Unique name for this controller\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface BaseState {\n name?: string;\n}\n\n/**\n * Controller class that provides configuration, state management, and subscriptions.\n *\n * The core purpose of every controller is to maintain an internal data object\n * called \"state\". Each controller is responsible for its own state, and all global wallet state\n * is tracked in a controller as state.\n */\nexport class BaseController<C extends BaseConfig, S extends BaseState> {\n /**\n * Default options used to configure this controller\n */\n defaultConfig: C = {} as C;\n\n /**\n * Default state set on this controller\n */\n defaultState: S = {} as S;\n\n /**\n * Determines if listeners are notified of state changes\n */\n disabled = false;\n\n /**\n * Name of this controller used during composition\n */\n name = 'BaseController';\n\n private readonly initialConfig: C;\n\n private readonly initialState: S;\n\n private internalConfig: C = this.defaultConfig;\n\n private internalState: S = this.defaultState;\n\n private readonly internalListeners: Listener<S>[] = [];\n\n /**\n * Creates a BaseController instance. Both initial state and initial\n * configuration options are merged with defaults upon initialization.\n *\n * @param config - Initial options used to configure this controller.\n * @param state - Initial state to set on this controller.\n */\n constructor(config: Partial<C> = {} as C, state: Partial<S> = {} as S) {\n // Use assign since generics can't be spread: https://git.io/vpRhY\n this.initialState = state as S;\n this.initialConfig = config as C;\n }\n\n /**\n * Enables the controller. This sets each config option as a member\n * variable on this instance and triggers any defined setters. This\n * also sets initial state and triggers any listeners.\n *\n * @returns This controller instance.\n */\n protected initialize() {\n this.internalState = this.defaultState;\n this.internalConfig = this.defaultConfig;\n this.configure(this.initialConfig);\n this.update(this.initialState);\n return this;\n }\n\n /**\n * Retrieves current controller configuration options.\n *\n * @returns The current configuration.\n */\n get config() {\n return this.internalConfig;\n }\n\n /**\n * Retrieves current controller state.\n *\n * @returns The current state.\n */\n get state() {\n return this.internalState;\n }\n\n /**\n * Updates controller configuration.\n *\n * @param config - New configuration options.\n * @param overwrite - Overwrite config instead of merging.\n * @param fullUpdate - Boolean that defines if the update is partial or not.\n */\n configure(config: Partial<C>, overwrite = false, fullUpdate = true) {\n if (fullUpdate) {\n this.internalConfig = overwrite\n ? (config as C)\n : Object.assign(this.internalConfig, config);\n\n for (const [key, value] of Object.entries(this.internalConfig)) {\n if (value !== undefined) {\n (this as any)[key] = value;\n }\n }\n } else {\n for (const key of Object.keys(config) as (keyof C)[]) {\n /* istanbul ignore else */\n if (typeof this.internalConfig[key] !== 'undefined') {\n this.internalConfig[key] = (config as C)[key];\n (this as any)[key] = config[key];\n }\n }\n }\n }\n\n /**\n * Notifies all subscribed listeners of current state.\n */\n notify() {\n if (this.disabled) {\n return;\n }\n\n this.internalListeners.forEach((listener) => {\n listener(this.internalState);\n });\n }\n\n /**\n * Adds new listener to be notified of state changes.\n *\n * @param listener - The callback triggered when state changes.\n */\n subscribe(listener: Listener<S>) {\n this.internalListeners.push(listener);\n }\n\n /**\n * Removes existing listener from receiving state changes.\n *\n * @param listener - The callback to remove.\n * @returns `true` if a listener is found and unsubscribed.\n */\n unsubscribe(listener: Listener<S>) {\n const index = this.internalListeners.findIndex((cb) => listener === cb);\n index > -1 && this.internalListeners.splice(index, 1);\n return index > -1;\n }\n\n /**\n * Updates controller state.\n *\n * @param state - The new state.\n * @param overwrite - Overwrite state instead of merging.\n */\n update(state: Partial<S>, overwrite = false) {\n this.internalState = overwrite\n ? Object.assign({}, state as S)\n : Object.assign({}, this.internalState, state);\n this.notify();\n }\n}\n\nexport default BaseController;\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Json } from '@metamask/utils';
|
|
2
2
|
import type { Draft, Patch } from 'immer';
|
|
3
|
-
import type {
|
|
3
|
+
import type { ActionConstraint, EventConstraint } from './ControllerMessenger';
|
|
4
|
+
import type { RestrictedControllerMessenger } from './RestrictedControllerMessenger';
|
|
4
5
|
/**
|
|
5
6
|
* A state change listener.
|
|
6
7
|
*
|
|
@@ -47,19 +48,29 @@ export interface StatePropertyMetadata<T extends Json> {
|
|
|
47
48
|
persist: boolean | StateDeriver<T>;
|
|
48
49
|
anonymous: boolean | StateDeriver<T>;
|
|
49
50
|
}
|
|
51
|
+
export declare type ControllerGetStateAction<ControllerName extends string, ControllerState extends Record<string, unknown>> = {
|
|
52
|
+
type: `${ControllerName}:getState`;
|
|
53
|
+
handler: () => ControllerState;
|
|
54
|
+
};
|
|
55
|
+
export declare type ControllerStateChangeEvent<ControllerName extends string, ControllerState extends Record<string, unknown>> = {
|
|
56
|
+
type: `${ControllerName}:stateChange`;
|
|
57
|
+
payload: [ControllerState, Patch[]];
|
|
58
|
+
};
|
|
59
|
+
export declare type ControllerActions<ControllerName extends string, ControllerState extends Record<string, unknown>> = ControllerGetStateAction<ControllerName, ControllerState>;
|
|
60
|
+
export declare type ControllerEvents<ControllerName extends string, ControllerState extends Record<string, unknown>> = ControllerStateChangeEvent<ControllerName, ControllerState>;
|
|
50
61
|
/**
|
|
51
62
|
* Controller class that provides state management, subscriptions, and state metadata
|
|
52
63
|
*/
|
|
53
|
-
export declare class BaseController<
|
|
54
|
-
private
|
|
64
|
+
export declare class BaseController<ControllerName extends string, ControllerState extends Record<string, Json>, messenger extends RestrictedControllerMessenger<ControllerName, ActionConstraint | ControllerActions<ControllerName, ControllerState>, EventConstraint | ControllerEvents<ControllerName, ControllerState>, string, string>> {
|
|
65
|
+
#private;
|
|
55
66
|
protected messagingSystem: messenger;
|
|
56
67
|
/**
|
|
57
68
|
* The name of the controller.
|
|
58
69
|
*
|
|
59
70
|
* This is used by the ComposableController to construct a composed application state.
|
|
60
71
|
*/
|
|
61
|
-
readonly name:
|
|
62
|
-
readonly metadata: StateMetadata<
|
|
72
|
+
readonly name: ControllerName;
|
|
73
|
+
readonly metadata: StateMetadata<ControllerState>;
|
|
63
74
|
/**
|
|
64
75
|
* The existence of the `subscribe` property is how the ComposableController detects whether a
|
|
65
76
|
* controller extends the old BaseController or the new one. We set it to `undefined` here to
|
|
@@ -71,24 +82,24 @@ export declare class BaseController<N extends string, S extends Record<string, J
|
|
|
71
82
|
*
|
|
72
83
|
* @param options - Controller options.
|
|
73
84
|
* @param options.messenger - Controller messaging system.
|
|
74
|
-
* @param options.metadata -
|
|
85
|
+
* @param options.metadata - ControllerState metadata, describing how to "anonymize" the state, and which
|
|
75
86
|
* parts should be persisted.
|
|
76
87
|
* @param options.name - The name of the controller, used as a namespace for events and actions.
|
|
77
88
|
* @param options.state - Initial controller state.
|
|
78
89
|
*/
|
|
79
90
|
constructor({ messenger, metadata, name, state, }: {
|
|
80
91
|
messenger: messenger;
|
|
81
|
-
metadata: StateMetadata<
|
|
82
|
-
name:
|
|
83
|
-
state:
|
|
92
|
+
metadata: StateMetadata<ControllerState>;
|
|
93
|
+
name: ControllerName;
|
|
94
|
+
state: ControllerState;
|
|
84
95
|
});
|
|
85
96
|
/**
|
|
86
97
|
* Retrieves current controller state.
|
|
87
98
|
*
|
|
88
99
|
* @returns The current state.
|
|
89
100
|
*/
|
|
90
|
-
get state():
|
|
91
|
-
set state(_:
|
|
101
|
+
get state(): ControllerState;
|
|
102
|
+
set state(_: ControllerState);
|
|
92
103
|
/**
|
|
93
104
|
* Updates controller state. Accepts a callback that is passed a draft copy
|
|
94
105
|
* of the controller state. If a value is returned, it is set as the new
|
|
@@ -100,8 +111,8 @@ export declare class BaseController<N extends string, S extends Record<string, J
|
|
|
100
111
|
* @returns An object that has the next state, patches applied in the update and inverse patches to
|
|
101
112
|
* rollback the update.
|
|
102
113
|
*/
|
|
103
|
-
protected update(callback: (state: Draft<
|
|
104
|
-
nextState:
|
|
114
|
+
protected update(callback: (state: Draft<ControllerState>) => void | ControllerState): {
|
|
115
|
+
nextState: ControllerState;
|
|
105
116
|
patches: Patch[];
|
|
106
117
|
inversePatches: Patch[];
|
|
107
118
|
};
|
|
@@ -135,7 +146,7 @@ export declare class BaseController<N extends string, S extends Record<string, J
|
|
|
135
146
|
* anonymized state.
|
|
136
147
|
* @returns The anonymized controller state.
|
|
137
148
|
*/
|
|
138
|
-
export declare function getAnonymizedState<
|
|
149
|
+
export declare function getAnonymizedState<ControllerState extends Record<string, Json>>(state: ControllerState, metadata: StateMetadata<ControllerState>): Record<string, Json>;
|
|
139
150
|
/**
|
|
140
151
|
* Returns the subset of state that should be persisted.
|
|
141
152
|
*
|
|
@@ -143,5 +154,5 @@ export declare function getAnonymizedState<S extends Record<string, Json>>(state
|
|
|
143
154
|
* @param metadata - The controller state metadata, which describes which pieces of state should be persisted.
|
|
144
155
|
* @returns The subset of controller state that should be persisted.
|
|
145
156
|
*/
|
|
146
|
-
export declare function getPersistentState<
|
|
157
|
+
export declare function getPersistentState<ControllerState extends Record<string, Json>>(state: ControllerState, metadata: StateMetadata<ControllerState>): Record<string, Json>;
|
|
147
158
|
//# sourceMappingURL=BaseControllerV2.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseControllerV2.d.ts","sourceRoot":"","sources":["../src/BaseControllerV2.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAE5C,OAAO,KAAK,EAAE,KAAK,EAAE,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,eAAe,CAAC;KACxB;IAYD;;;;OAIG;IACH,IAAI,KAAK,oBAER;IAED,IAAI,KAAK,CAAC,CAAC,iBAAA,EAIV;IAED;;;;;;;;;;OAUG;IACH,SAAS,CAAC,MAAM,CACd,QAAQ,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,eAAe,CAAC,KAAK,IAAI,GAAG,eAAe,GAClE;QACD,SAAS,EAAE,eAAe,CAAC;QAC3B,OAAO,EAAE,KAAK,EAAE,CAAC;QACjB,cAAc,EAAE,KAAK,EAAE,CAAC;KACzB;IAoBD;;;;;;OAMG;IACH,SAAS,CAAC,YAAY,CAAC,OAAO,EAAE,KAAK,EAAE;IAUvC;;;;;;;;OAQG;IACH,SAAS,CAAC,OAAO;CAGlB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,kBAAkB,CAChC,eAAe,SAAS,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,EAE5C,KAAK,EAAE,eAAe,EACtB,QAAQ,EAAE,aAAa,CAAC,eAAe,CAAC,GACvC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAEtB;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,eAAe,SAAS,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,EAE5C,KAAK,EAAE,eAAe,EACtB,QAAQ,EAAE,aAAa,CAAC,eAAe,CAAC,GACvC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAEtB"}
|
package/dist/BaseControllerV2.js
CHANGED
|
@@ -1,4 +1,16 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
3
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
4
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
5
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
6
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
7
|
+
};
|
|
8
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
9
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
10
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
11
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
12
|
+
};
|
|
13
|
+
var _BaseController_internalState;
|
|
2
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
15
|
exports.getPersistentState = exports.getAnonymizedState = exports.BaseController = void 0;
|
|
4
16
|
const immer_1 = require("immer");
|
|
@@ -12,15 +24,16 @@ class BaseController {
|
|
|
12
24
|
*
|
|
13
25
|
* @param options - Controller options.
|
|
14
26
|
* @param options.messenger - Controller messaging system.
|
|
15
|
-
* @param options.metadata -
|
|
27
|
+
* @param options.metadata - ControllerState metadata, describing how to "anonymize" the state, and which
|
|
16
28
|
* parts should be persisted.
|
|
17
29
|
* @param options.name - The name of the controller, used as a namespace for events and actions.
|
|
18
30
|
* @param options.state - Initial controller state.
|
|
19
31
|
*/
|
|
20
32
|
constructor({ messenger, metadata, name, state, }) {
|
|
33
|
+
_BaseController_internalState.set(this, void 0);
|
|
21
34
|
this.messagingSystem = messenger;
|
|
22
35
|
this.name = name;
|
|
23
|
-
this
|
|
36
|
+
__classPrivateFieldSet(this, _BaseController_internalState, state, "f");
|
|
24
37
|
this.metadata = metadata;
|
|
25
38
|
this.messagingSystem.registerActionHandler(`${name}:getState`, () => this.state);
|
|
26
39
|
}
|
|
@@ -30,7 +43,7 @@ class BaseController {
|
|
|
30
43
|
* @returns The current state.
|
|
31
44
|
*/
|
|
32
45
|
get state() {
|
|
33
|
-
return this
|
|
46
|
+
return __classPrivateFieldGet(this, _BaseController_internalState, "f");
|
|
34
47
|
}
|
|
35
48
|
set state(_) {
|
|
36
49
|
throw new Error(`Controller state cannot be directly mutated; use 'update' method instead.`);
|
|
@@ -49,8 +62,8 @@ class BaseController {
|
|
|
49
62
|
update(callback) {
|
|
50
63
|
// We run into ts2589, "infinite type depth", if we don't cast
|
|
51
64
|
// produceWithPatches here.
|
|
52
|
-
const [nextState, patches, inversePatches] = immer_1.produceWithPatches(this
|
|
53
|
-
this
|
|
65
|
+
const [nextState, patches, inversePatches] = immer_1.produceWithPatches(__classPrivateFieldGet(this, _BaseController_internalState, "f"), callback);
|
|
66
|
+
__classPrivateFieldSet(this, _BaseController_internalState, nextState, "f");
|
|
54
67
|
this.messagingSystem.publish(`${this.name}:stateChange`, nextState, patches);
|
|
55
68
|
return { nextState, patches, inversePatches };
|
|
56
69
|
}
|
|
@@ -62,8 +75,8 @@ class BaseController {
|
|
|
62
75
|
* or undo changes.
|
|
63
76
|
*/
|
|
64
77
|
applyPatches(patches) {
|
|
65
|
-
const nextState = (0, immer_1.applyPatches)(this
|
|
66
|
-
this
|
|
78
|
+
const nextState = (0, immer_1.applyPatches)(__classPrivateFieldGet(this, _BaseController_internalState, "f"), patches);
|
|
79
|
+
__classPrivateFieldSet(this, _BaseController_internalState, nextState, "f");
|
|
67
80
|
this.messagingSystem.publish(`${this.name}:stateChange`, nextState, patches);
|
|
68
81
|
}
|
|
69
82
|
/**
|
|
@@ -80,6 +93,7 @@ class BaseController {
|
|
|
80
93
|
}
|
|
81
94
|
}
|
|
82
95
|
exports.BaseController = BaseController;
|
|
96
|
+
_BaseController_internalState = new WeakMap();
|
|
83
97
|
/**
|
|
84
98
|
* Returns an anonymized representation of the controller state.
|
|
85
99
|
*
|
|
@@ -119,7 +133,7 @@ function deriveStateFromMetadata(state, metadata, metadataProperty) {
|
|
|
119
133
|
try {
|
|
120
134
|
const stateMetadata = metadata[key];
|
|
121
135
|
if (!stateMetadata) {
|
|
122
|
-
throw new Error(`No metadata found for '${key}'`);
|
|
136
|
+
throw new Error(`No metadata found for '${String(key)}'`);
|
|
123
137
|
}
|
|
124
138
|
const propertyMetadata = stateMetadata[metadataProperty];
|
|
125
139
|
const stateProperty = state[key];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseControllerV2.js","sourceRoot":"","sources":["../src/BaseControllerV2.ts"],"names":[],"mappings":";;;AACA,iCAAwE;AAQxE,IAAA,qBAAa,GAAE,CAAC;AAoDhB;;GAEG;AACH,MAAa,cAAc;IAyBzB;;;;;;;;;OASG;IACH,YAAY,EACV,SAAS,EACT,QAAQ,EACR,IAAI,EACJ,KAAK,GAMN;QACC,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;QACjC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,aAAa,GAAG,KAAK,CAAC;QAC3B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAEzB,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,GAAG,IAAI,WAAW,EAClB,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CACjB,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACH,IAAI,KAAK;QACP,OAAO,IAAI,CAAC,aAAa,CAAC;IAC5B,CAAC;IAED,IAAI,KAAK,CAAC,CAAC;QACT,MAAM,IAAI,KAAK,CACb,2EAA2E,CAC5E,CAAC;IACJ,CAAC;IAED;;;;;;;;;;OAUG;IACO,MAAM,CAAC,QAAuC;QAKtD,8DAA8D;QAC9D,2BAA2B;QAC3B,MAAM,CAAC,SAAS,EAAE,OAAO,EAAE,cAAc,CAAC,GACxC,0BAID,CAAC,IAAI,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAC;QAEhC,IAAI,CAAC,aAAa,GAAG,SAAS,CAAC;QAC/B,IAAI,CAAC,eAAe,CAAC,OAAO,CAC1B,GAAG,IAAI,CAAC,IAAI,cAAoC,EAChD,SAAS,EACT,OAAO,CACR,CAAC;QAEF,OAAO,EAAE,SAAS,EAAE,OAAO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,KAAK,CAAC,GAAG,CAAC,CAAC;YACjC,IAAI,OAAO,gBAAgB,KAAK,UAAU,EAAE;gBAC1C,cAAc,CAAC,GAAa,CAAC,GAAG,gBAAgB,CAC9C,aAA2B,CAC5B,CAAC;aACH;iBAAM,IAAI,gBAAgB,EAAE;gBAC3B,cAAc,CAAC,GAAa,CAAC,GAAG,aAAa,CAAC;aAC/C;YACD,OAAO,cAAc,CAAC;SACvB;QAAC,OAAO,KAAK,EAAE;YACd,sEAAsE;YACtE,gEAAgE;YAChE,UAAU,CAAC,GAAG,EAAE;gBACd,MAAM,KAAK,CAAC;YACd,CAAC,CAAC,CAAC;YACH,OAAO,cAAc,CAAC;SACvB;IACH,CAAC,EAAE,EAA0B,CAAC,CAAC;AACjC,CAAC","sourcesContent":["import type { Json } from '@metamask/utils';\nimport { enablePatches, produceWithPatches, applyPatches } from 'immer';\nimport type { Draft, Patch } from 'immer';\n\nimport type {\n RestrictedControllerMessenger,\n Namespaced,\n} from './ControllerMessenger';\n\nenablePatches();\n\n/**\n * A state change listener.\n *\n * This function will get called for each state change, and is given a copy of\n * the new state along with a set of patches describing the changes since the\n * last update.\n *\n * @param state - The new controller state.\n * @param patches - A list of patches describing any changes (see here for more\n * information: https://immerjs.github.io/immer/docs/patches)\n */\nexport type Listener<T> = (state: T, patches: Patch[]) => void;\n\n/**\n * An function to derive state.\n *\n * This function will accept one piece of the controller state (one property),\n * and will return some derivation of that state.\n *\n * @param value - A piece of controller state.\n * @returns Something derived from controller state.\n */\nexport type StateDeriver<T extends Json> = (value: T) => Json;\n\n/**\n * State metadata.\n *\n * This metadata describes which parts of state should be persisted, and how to\n * get an anonymized representation of the state.\n */\nexport type StateMetadata<T extends Record<string, Json>> = {\n [P in keyof T]: StatePropertyMetadata<T[P]>;\n};\n\n/**\n * Metadata for a single state property\n *\n * @property persist - Indicates whether this property should be persisted\n * (`true` for persistent, `false` for transient), or is set to a function\n * that derives the persistent state from the state.\n * @property anonymous - Indicates whether this property is already anonymous,\n * (`true` for anonymous, `false` if it has potential to be personally\n * identifiable), or is set to a function that returns an anonymized\n * representation of this state.\n */\nexport interface StatePropertyMetadata<T extends Json> {\n persist: boolean | StateDeriver<T>;\n anonymous: boolean | StateDeriver<T>;\n}\n\n/**\n * Controller class that provides state management, subscriptions, and state metadata\n */\nexport class BaseController<\n N extends string,\n S extends Record<string, Json>,\n messenger extends RestrictedControllerMessenger<N, any, any, string, string>,\n> {\n private internalState: S;\n\n protected messagingSystem: messenger;\n\n /**\n * The name of the controller.\n *\n * This is used by the ComposableController to construct a composed application state.\n */\n public readonly name: N;\n\n public readonly metadata: StateMetadata<S>;\n\n /**\n * The existence of the `subscribe` property is how the ComposableController detects whether a\n * controller extends the old BaseController or the new one. We set it to `undefined` here to\n * ensure the ComposableController never mistakes them for an older style controller.\n */\n public readonly subscribe: undefined;\n\n /**\n * Creates a BaseController instance.\n *\n * @param options - Controller options.\n * @param options.messenger - Controller messaging system.\n * @param options.metadata - State metadata, describing how to \"anonymize\" the state, and which\n * parts should be persisted.\n * @param options.name - The name of the controller, used as a namespace for events and actions.\n * @param options.state - Initial controller state.\n */\n constructor({\n messenger,\n metadata,\n name,\n state,\n }: {\n messenger: messenger;\n metadata: StateMetadata<S>;\n name: N;\n state: S;\n }) {\n this.messagingSystem = messenger;\n this.name = name;\n this.internalState = state;\n this.metadata = metadata;\n\n this.messagingSystem.registerActionHandler(\n `${name}:getState`,\n () => this.state,\n );\n }\n\n /**\n * Retrieves current controller state.\n *\n * @returns The current state.\n */\n get state() {\n return this.internalState;\n }\n\n set state(_) {\n throw new Error(\n `Controller state cannot be directly mutated; use 'update' method instead.`,\n );\n }\n\n /**\n * Updates controller state. Accepts a callback that is passed a draft copy\n * of the controller state. If a value is returned, it is set as the new\n * state. Otherwise, any changes made within that callback to the draft are\n * applied to the controller state.\n *\n * @param callback - Callback for updating state, passed a draft state\n * object. Return a new state object or mutate the draft to update state.\n * @returns An object that has the next state, patches applied in the update and inverse patches to\n * rollback the update.\n */\n protected update(callback: (state: Draft<S>) => void | S): {\n nextState: S;\n patches: Patch[];\n inversePatches: Patch[];\n } {\n // We run into ts2589, \"infinite type depth\", if we don't cast\n // produceWithPatches here.\n const [nextState, patches, inversePatches] = (\n produceWithPatches as unknown as (\n state: S,\n cb: typeof callback,\n ) => [S, Patch[], Patch[]]\n )(this.internalState, callback);\n\n this.internalState = nextState;\n this.messagingSystem.publish(\n `${this.name}:stateChange` as Namespaced<N, any>,\n nextState,\n patches,\n );\n\n return { nextState, patches, inversePatches };\n }\n\n /**\n * Applies immer patches to the current state. The patches come from the\n * update function itself and can either be normal or inverse patches.\n *\n * @param patches - An array of immer patches that are to be applied to make\n * or undo changes.\n */\n protected applyPatches(patches: Patch[]) {\n const nextState = applyPatches(this.internalState, patches);\n this.internalState = nextState;\n this.messagingSystem.publish(\n `${this.name}:stateChange` as Namespaced<N, any>,\n nextState,\n patches,\n );\n }\n\n /**\n * Prepares the controller for garbage collection. This should be extended\n * by any subclasses to clean up any additional connections or events.\n *\n * The only cleanup performed here is to remove listeners. While technically\n * this is not required to ensure this instance is garbage collected, it at\n * least ensures this instance won't be responsible for preventing the\n * listeners from being garbage collected.\n */\n protected destroy() {\n this.messagingSystem.clearEventSubscriptions(\n `${this.name}:stateChange` as Namespaced<N, any>,\n );\n }\n}\n\n/**\n * Returns an anonymized representation of the controller state.\n *\n * By \"anonymized\" we mean that it should not contain any information that could be personally\n * identifiable.\n *\n * @param state - The controller state.\n * @param metadata - The controller state metadata, which describes how to derive the\n * anonymized state.\n * @returns The anonymized controller state.\n */\nexport function getAnonymizedState<S extends Record<string, Json>>(\n state: S,\n metadata: StateMetadata<S>,\n): Record<string, Json> {\n return deriveStateFromMetadata(state, metadata, 'anonymous');\n}\n\n/**\n * Returns the subset of state that should be persisted.\n *\n * @param state - The controller state.\n * @param metadata - The controller state metadata, which describes which pieces of state should be persisted.\n * @returns The subset of controller state that should be persisted.\n */\nexport function getPersistentState<S extends Record<string, Json>>(\n state: S,\n metadata: StateMetadata<S>,\n): Record<string, Json> {\n return deriveStateFromMetadata(state, metadata, 'persist');\n}\n\n/**\n * Use the metadata to derive state according to the given metadata property.\n *\n * @param state - The full controller state.\n * @param metadata - The controller metadata.\n * @param metadataProperty - The metadata property to use to derive state.\n * @returns The metadata-derived controller state.\n */\nfunction deriveStateFromMetadata<S extends Record<string, Json>>(\n state: S,\n metadata: StateMetadata<S>,\n metadataProperty: 'anonymous' | 'persist',\n): Record<string, Json> {\n return Object.keys(state).reduce((persistedState, key) => {\n try {\n const stateMetadata = metadata[key as keyof S];\n if (!stateMetadata) {\n throw new Error(`No metadata found for '${key}'`);\n }\n const propertyMetadata = stateMetadata[metadataProperty];\n const stateProperty = state[key];\n if (typeof propertyMetadata === 'function') {\n persistedState[key as string] = propertyMetadata(\n stateProperty as S[keyof S],\n );\n } else if (propertyMetadata) {\n persistedState[key as string] = stateProperty;\n }\n return persistedState;\n } catch (error) {\n // Throw error after timeout so that it is captured as a console error\n // (and by Sentry) without interrupting state-related operations\n setTimeout(() => {\n throw error;\n });\n return persistedState;\n }\n }, {} as Record<string, Json>);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"BaseControllerV2.js","sourceRoot":"","sources":["../src/BaseControllerV2.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,iCAAwE;AAMxE,IAAA,qBAAa,GAAE,CAAC;AAiFhB;;GAEG;AACH,MAAa,cAAc;IA+BzB;;;;;;;;;OASG;IACH,YAAY,EACV,SAAS,EACT,QAAQ,EACR,IAAI,EACJ,KAAK,GAMN;QAxCD,gDAAgC;QAyC9B,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;QACjC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,uBAAA,IAAI,iCAAkB,KAAK,MAAA,CAAC;QAC5B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAEzB,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,GAAG,IAAI,WAAW,EAClB,GAAG,EAAE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C/D,CAAC;AAPD,gDAOC;AAED;;;;;;GAMG;AACH,SAAgB,kBAAkB,CAGhC,KAAsB,EACtB,QAAwC;IAExC,OAAO,uBAAuB,CAAC,KAAK,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;AAC7D,CAAC;AAPD,gDAOC;AAED;;;;;;;GAOG;AACH,SAAS,uBAAuB,CAC9B,KAAsB,EACtB,QAAwC,EACxC,gBAAyC;IAEzC,OAAQ,MAAM,CAAC,IAAI,CAAC,KAAK,CAA+B,CAAC,MAAM,CAE7D,CAAC,cAAc,EAAE,GAAG,EAAE,EAAE;QACxB,IAAI;YACF,MAAM,aAAa,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;YACpC,IAAI,CAAC,aAAa,EAAE;gBAClB,MAAM,IAAI,KAAK,CAAC,0BAA0B,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;aAC3D;YACD,MAAM,gBAAgB,GAAG,aAAa,CAAC,gBAAgB,CAAC,CAAC;YACzD,MAAM,aAAa,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC;YACjC,IAAI,OAAO,gBAAgB,KAAK,UAAU,EAAE;gBAC1C,cAAc,CAAC,GAAG,CAAC,GAAG,gBAAgB,CAAC,aAAa,CAAC,CAAC;aACvD;iBAAM,IAAI,gBAAgB,EAAE;gBAC3B,cAAc,CAAC,GAAG,CAAC,GAAG,aAAa,CAAC;aACrC;YACD,OAAO,cAAc,CAAC;SACvB;QAAC,OAAO,KAAK,EAAE;YACd,sEAAsE;YACtE,gEAAgE;YAChE,UAAU,CAAC,GAAG,EAAE;gBACd,MAAM,KAAK,CAAC;YACd,CAAC,CAAC,CAAC;YACH,OAAO,cAAc,CAAC;SACvB;IACH,CAAC,EAAE,EAAE,CAAwC,CAAC;AAChD,CAAC","sourcesContent":["import type { Json } from '@metamask/utils';\nimport { enablePatches, produceWithPatches, applyPatches } from 'immer';\nimport type { Draft, Patch } from 'immer';\n\nimport type { ActionConstraint, EventConstraint } from './ControllerMessenger';\nimport type { RestrictedControllerMessenger } from './RestrictedControllerMessenger';\n\nenablePatches();\n\n/**\n * A state change listener.\n *\n * This function will get called for each state change, and is given a copy of\n * the new state along with a set of patches describing the changes since the\n * last update.\n *\n * @param state - The new controller state.\n * @param patches - A list of patches describing any changes (see here for more\n * information: https://immerjs.github.io/immer/docs/patches)\n */\nexport type Listener<T> = (state: T, patches: Patch[]) => void;\n\n/**\n * An function to derive state.\n *\n * This function will accept one piece of the controller state (one property),\n * and will return some derivation of that state.\n *\n * @param value - A piece of controller state.\n * @returns Something derived from controller state.\n */\nexport type StateDeriver<T extends Json> = (value: T) => Json;\n\n/**\n * State metadata.\n *\n * This metadata describes which parts of state should be persisted, and how to\n * get an anonymized representation of the state.\n */\nexport type StateMetadata<T extends Record<string, Json>> = {\n [P in keyof T]: StatePropertyMetadata<T[P]>;\n};\n\n/**\n * Metadata for a single state property\n *\n * @property persist - Indicates whether this property should be persisted\n * (`true` for persistent, `false` for transient), or is set to a function\n * that derives the persistent state from the state.\n * @property anonymous - Indicates whether this property is already anonymous,\n * (`true` for anonymous, `false` if it has potential to be personally\n * identifiable), or is set to a function that returns an anonymized\n * representation of this state.\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface StatePropertyMetadata<T extends Json> {\n persist: boolean | StateDeriver<T>;\n anonymous: boolean | StateDeriver<T>;\n}\n\nexport type ControllerGetStateAction<\n ControllerName extends string,\n ControllerState extends Record<string, unknown>,\n> = {\n type: `${ControllerName}:getState`;\n handler: () => ControllerState;\n};\n\nexport type ControllerStateChangeEvent<\n ControllerName extends string,\n ControllerState extends Record<string, unknown>,\n> = {\n type: `${ControllerName}:stateChange`;\n payload: [ControllerState, Patch[]];\n};\n\nexport type ControllerActions<\n ControllerName extends string,\n ControllerState extends Record<string, unknown>,\n> = ControllerGetStateAction<ControllerName, ControllerState>;\n\nexport type ControllerEvents<\n ControllerName extends string,\n ControllerState extends Record<string, unknown>,\n> = ControllerStateChangeEvent<ControllerName, ControllerState>;\n\n/**\n * Controller class that provides state management, subscriptions, and state metadata\n */\nexport class BaseController<\n ControllerName extends string,\n ControllerState extends Record<string, Json>,\n messenger extends RestrictedControllerMessenger<\n ControllerName,\n ActionConstraint | ControllerActions<ControllerName, ControllerState>,\n EventConstraint | ControllerEvents<ControllerName, ControllerState>,\n string,\n string\n >,\n> {\n #internalState: ControllerState;\n\n protected messagingSystem: messenger;\n\n /**\n * The name of the controller.\n *\n * This is used by the ComposableController to construct a composed application state.\n */\n public readonly name: ControllerName;\n\n public readonly metadata: StateMetadata<ControllerState>;\n\n /**\n * The existence of the `subscribe` property is how the ComposableController detects whether a\n * controller extends the old BaseController or the new one. We set it to `undefined` here to\n * ensure the ComposableController never mistakes them for an older style controller.\n */\n public readonly subscribe: undefined;\n\n /**\n * Creates a BaseController instance.\n *\n * @param options - Controller options.\n * @param options.messenger - Controller messaging system.\n * @param options.metadata - ControllerState metadata, describing how to \"anonymize\" the state, and which\n * parts should be persisted.\n * @param options.name - The name of the controller, used as a namespace for events and actions.\n * @param options.state - Initial controller state.\n */\n constructor({\n messenger,\n metadata,\n name,\n state,\n }: {\n messenger: messenger;\n metadata: StateMetadata<ControllerState>;\n name: ControllerName;\n state: ControllerState;\n }) {\n this.messagingSystem = messenger;\n this.name = name;\n this.#internalState = state;\n this.metadata = metadata;\n\n this.messagingSystem.registerActionHandler(\n `${name}:getState`,\n () => this.state,\n );\n }\n\n /**\n * Retrieves current controller state.\n *\n * @returns The current state.\n */\n get state() {\n return this.#internalState;\n }\n\n set state(_) {\n throw new Error(\n `Controller state cannot be directly mutated; use 'update' method instead.`,\n );\n }\n\n /**\n * Updates controller state. Accepts a callback that is passed a draft copy\n * of the controller state. If a value is returned, it is set as the new\n * state. Otherwise, any changes made within that callback to the draft are\n * applied to the controller state.\n *\n * @param callback - Callback for updating state, passed a draft state\n * object. Return a new state object or mutate the draft to update state.\n * @returns An object that has the next state, patches applied in the update and inverse patches to\n * rollback the update.\n */\n protected update(\n callback: (state: Draft<ControllerState>) => void | ControllerState,\n ): {\n nextState: ControllerState;\n patches: Patch[];\n inversePatches: Patch[];\n } {\n // We run into ts2589, \"infinite type depth\", if we don't cast\n // produceWithPatches here.\n const [nextState, patches, inversePatches] = (\n produceWithPatches as unknown as (\n state: ControllerState,\n cb: typeof callback,\n ) => [ControllerState, Patch[], Patch[]]\n )(this.#internalState, callback);\n\n this.#internalState = nextState;\n this.messagingSystem.publish(\n `${this.name}:stateChange`,\n nextState,\n patches,\n );\n\n return { nextState, patches, inversePatches };\n }\n\n /**\n * Applies immer patches to the current state. The patches come from the\n * update function itself and can either be normal or inverse patches.\n *\n * @param patches - An array of immer patches that are to be applied to make\n * or undo changes.\n */\n protected applyPatches(patches: Patch[]) {\n const nextState = applyPatches(this.#internalState, patches);\n this.#internalState = nextState;\n this.messagingSystem.publish(\n `${this.name}:stateChange`,\n nextState,\n patches,\n );\n }\n\n /**\n * Prepares the controller for garbage collection. This should be extended\n * by any subclasses to clean up any additional connections or events.\n *\n * The only cleanup performed here is to remove listeners. While technically\n * this is not required to ensure this instance is garbage collected, it at\n * least ensures this instance won't be responsible for preventing the\n * listeners from being garbage collected.\n */\n protected destroy() {\n this.messagingSystem.clearEventSubscriptions(`${this.name}:stateChange`);\n }\n}\n\n/**\n * Returns an anonymized representation of the controller state.\n *\n * By \"anonymized\" we mean that it should not contain any information that could be personally\n * identifiable.\n *\n * @param state - The controller state.\n * @param metadata - The controller state metadata, which describes how to derive the\n * anonymized state.\n * @returns The anonymized controller state.\n */\nexport function getAnonymizedState<\n ControllerState extends Record<string, Json>,\n>(\n state: ControllerState,\n metadata: StateMetadata<ControllerState>,\n): Record<string, Json> {\n return deriveStateFromMetadata(state, metadata, 'anonymous');\n}\n\n/**\n * Returns the subset of state that should be persisted.\n *\n * @param state - The controller state.\n * @param metadata - The controller state metadata, which describes which pieces of state should be persisted.\n * @returns The subset of controller state that should be persisted.\n */\nexport function getPersistentState<\n ControllerState extends Record<string, Json>,\n>(\n state: ControllerState,\n metadata: StateMetadata<ControllerState>,\n): Record<string, Json> {\n return deriveStateFromMetadata(state, metadata, 'persist');\n}\n\n/**\n * Use the metadata to derive state according to the given metadata property.\n *\n * @param state - The full controller state.\n * @param metadata - The controller metadata.\n * @param metadataProperty - The metadata property to use to derive state.\n * @returns The metadata-derived controller state.\n */\nfunction deriveStateFromMetadata<ControllerState extends Record<string, Json>>(\n state: ControllerState,\n metadata: StateMetadata<ControllerState>,\n metadataProperty: 'anonymous' | 'persist',\n): Record<string, Json> {\n return (Object.keys(state) as (keyof ControllerState)[]).reduce<\n Partial<Record<keyof ControllerState, Json>>\n >((persistedState, key) => {\n try {\n const stateMetadata = metadata[key];\n if (!stateMetadata) {\n throw new Error(`No metadata found for '${String(key)}'`);\n }\n const propertyMetadata = stateMetadata[metadataProperty];\n const stateProperty = state[key];\n if (typeof propertyMetadata === 'function') {\n persistedState[key] = propertyMetadata(stateProperty);\n } else if (propertyMetadata) {\n persistedState[key] = stateProperty;\n }\n return persistedState;\n } catch (error) {\n // Throw error after timeout so that it is captured as a console error\n // (and by Sentry) without interrupting state-related operations\n setTimeout(() => {\n throw error;\n });\n return persistedState;\n }\n }, {}) as Record<keyof ControllerState, Json>;\n}\n"]}
|