@metamask-previews/profile-controller 1.0.1-preview-2750df1dc → 1.0.1-preview-df8d6c7ea
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 +3 -0
- package/dist/ProfileController-method-action-types.d.ts +12 -5
- package/dist/ProfileController-method-action-types.d.ts.map +1 -1
- package/dist/ProfileController-method-action-types.js.map +1 -1
- package/dist/ProfileController.d.ts +10 -6
- package/dist/ProfileController.d.ts.map +1 -1
- package/dist/ProfileController.js +17 -8
- package/dist/ProfileController.js.map +1 -1
- package/dist/ProfileService.d.ts +3 -3
- package/dist/ProfileService.js +1 -1
- package/dist/ProfileService.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
13
13
|
- Add `getXAuthorizationUrl` method to `ProfileController` for initiating the X OAuth flow. It requires a profile to exist, fetches the authorization URL via `ProfileService:getXAuthUrl` (the profile is resolved server-side from the verified bearer token), and returns the authorization URL and state parameter as ephemeral session data, without storing them in controller state ([#10668](https://github.com/MetaMask/core/pull/10668))
|
|
14
14
|
- Add `disconnectX` method to `ProfileController` for unlinking the X account from a profile. It delegates to `ProfileService:disconnectX`, and when the disconnected profile matches the profile in state, clears `xProfile` from controller state and sets `connectedToX` to `false` ([#10668](https://github.com/MetaMask/core/pull/10668))
|
|
15
15
|
- Add `disconnectX` method to `ProfileService` for sending an authenticated `DELETE` request to the `profiles/{profileId}/x` endpoint; a `404` response is treated as success (the X account is already disconnected) ([#10668](https://github.com/MetaMask/core/pull/10668))
|
|
16
|
+
- Add `fetchAndUpdateProfile` method to the `ProfileController` to fetch a profile from the profile-api and update the controller's state ([#10793](https://github.com/MetaMask/core/pull/10793))
|
|
16
17
|
|
|
17
18
|
### Changed
|
|
18
19
|
|
|
@@ -23,6 +24,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
23
24
|
### Fixed
|
|
24
25
|
|
|
25
26
|
- Fix the `ProfileController` messenger event type: the controller exposes `ProfileController:stateChanged` (emitted on state changes), not `ProfileController:stateChange` ([#10668](https://github.com/MetaMask/core/pull/10668))
|
|
27
|
+
- Fix the `ProfileController`'s `connectX` and `getXAuthorizationUrl` methods to prevent throwing when a profile ID doesn't exist in state ([#10793](https://github.com/MetaMask/core/pull/10793))
|
|
28
|
+
- Fix the `ProfileService`'s response type to not have `avatar_url` as nullable ([#10793](https://github.com/MetaMask/core/pull/10793))
|
|
26
29
|
|
|
27
30
|
## [1.0.1]
|
|
28
31
|
|
|
@@ -72,14 +72,12 @@ export type ProfileControllerCheckUsernameAvailabilityAction = {
|
|
|
72
72
|
};
|
|
73
73
|
/**
|
|
74
74
|
* Completes the X OAuth flow for the profile in state and returns the
|
|
75
|
-
* linked X profile. Updates controller state with the linked X profile
|
|
76
|
-
* and marks the profile in state as connected to X.
|
|
75
|
+
* linked X profile. Updates controller state with the linked X profile.
|
|
77
76
|
*
|
|
78
77
|
* @param params - The parameters for the X OAuth flow.
|
|
79
78
|
* @param params.code - The OAuth authorization code from the X redirect.
|
|
80
79
|
* @param params.state - The state parameter returned by the X redirect.
|
|
81
80
|
* @returns The linked X profile.
|
|
82
|
-
* @throws If no profile has been created yet.
|
|
83
81
|
*/
|
|
84
82
|
export type ProfileControllerConnectXAction = {
|
|
85
83
|
type: `ProfileController:connectX`;
|
|
@@ -96,13 +94,22 @@ export type ProfileControllerFetchAndUpdateXAccountAction = {
|
|
|
96
94
|
type: `ProfileController:fetchAndUpdateXAccount`;
|
|
97
95
|
handler: ProfileController['fetchAndUpdateXAccount'];
|
|
98
96
|
};
|
|
97
|
+
/**
|
|
98
|
+
* Fetches a profile by its identifier and updates state.
|
|
99
|
+
*
|
|
100
|
+
* @param profileId - The profile identifier to fetch.
|
|
101
|
+
* @returns The fetched profile.
|
|
102
|
+
*/
|
|
103
|
+
export type ProfileControllerFetchAndUpdateProfileAction = {
|
|
104
|
+
type: `ProfileController:fetchAndUpdateProfile`;
|
|
105
|
+
handler: ProfileController['fetchAndUpdateProfile'];
|
|
106
|
+
};
|
|
99
107
|
/**
|
|
100
108
|
* Initiates the X OAuth flow by fetching the authorization URL from the backend.
|
|
101
109
|
* The profile is resolved server-side from the verified bearer token.
|
|
102
110
|
* Returns session data for the caller to use; nothing is stored in controller state.
|
|
103
111
|
*
|
|
104
112
|
* @returns The X authorization URL and state parameter.
|
|
105
|
-
* @throws If no profile has been created yet.
|
|
106
113
|
*/
|
|
107
114
|
export type ProfileControllerGetXAuthorizationUrlAction = {
|
|
108
115
|
type: `ProfileController:getXAuthorizationUrl`;
|
|
@@ -123,5 +130,5 @@ export type ProfileControllerDisconnectXAction = {
|
|
|
123
130
|
/**
|
|
124
131
|
* Union of all ProfileController action types.
|
|
125
132
|
*/
|
|
126
|
-
export type ProfileControllerMethodActions = ProfileControllerGetProfileAction | ProfileControllerGetXProfileAction | ProfileControllerCreateProfileAction | ProfileControllerReplaceProfileAction | ProfileControllerUpdateProfileAction | ProfileControllerDeleteProfileAction | ProfileControllerCheckUsernameAvailabilityAction | ProfileControllerConnectXAction | ProfileControllerFetchAndUpdateXAccountAction | ProfileControllerGetXAuthorizationUrlAction | ProfileControllerDisconnectXAction;
|
|
133
|
+
export type ProfileControllerMethodActions = ProfileControllerGetProfileAction | ProfileControllerGetXProfileAction | ProfileControllerCreateProfileAction | ProfileControllerReplaceProfileAction | ProfileControllerUpdateProfileAction | ProfileControllerDeleteProfileAction | ProfileControllerCheckUsernameAvailabilityAction | ProfileControllerConnectXAction | ProfileControllerFetchAndUpdateXAccountAction | ProfileControllerFetchAndUpdateProfileAction | ProfileControllerGetXAuthorizationUrlAction | ProfileControllerDisconnectXAction;
|
|
127
134
|
//# sourceMappingURL=ProfileController-method-action-types.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProfileController-method-action-types.d.ts","sourceRoot":"","sources":["../src/ProfileController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAEhE;;;;GAIG;AACH,MAAM,MAAM,iCAAiC,GAAG;IAC9C,IAAI,EAAE,8BAA8B,CAAC;IACrC,OAAO,EAAE,iBAAiB,CAAC,YAAY,CAAC,CAAC;CAC1C,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,kCAAkC,GAAG;IAC/C,IAAI,EAAE,+BAA+B,CAAC;IACtC,OAAO,EAAE,iBAAiB,CAAC,aAAa,CAAC,CAAC;CAC3C,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,oCAAoC,GAAG;IACjD,IAAI,EAAE,iCAAiC,CAAC;IACxC,OAAO,EAAE,iBAAiB,CAAC,eAAe,CAAC,CAAC;CAC7C,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,qCAAqC,GAAG;IAClD,IAAI,EAAE,kCAAkC,CAAC;IACzC,OAAO,EAAE,iBAAiB,CAAC,gBAAgB,CAAC,CAAC;CAC9C,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,oCAAoC,GAAG;IACjD,IAAI,EAAE,iCAAiC,CAAC;IACxC,OAAO,EAAE,iBAAiB,CAAC,eAAe,CAAC,CAAC;CAC7C,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,oCAAoC,GAAG;IACjD,IAAI,EAAE,iCAAiC,CAAC;IACxC,OAAO,EAAE,iBAAiB,CAAC,eAAe,CAAC,CAAC;CAC7C,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,gDAAgD,GAAG;IAC7D,IAAI,EAAE,6CAA6C,CAAC;IACpD,OAAO,EAAE,iBAAiB,CAAC,2BAA2B,CAAC,CAAC;CACzD,CAAC;AAEF
|
|
1
|
+
{"version":3,"file":"ProfileController-method-action-types.d.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nC,OAAO,EAAE,iBAAiB,CAAC,UAAU,CAAC,CAAC;CACxC,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,6CAA6C,GAAG;IAC1D,IAAI,EAAE,0CAA0C,CAAC;IACjD,OAAO,EAAE,iBAAiB,CAAC,wBAAwB,CAAC,CAAC;CACtD,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,4CAA4C,GAAG;IACzD,IAAI,EAAE,yCAAyC,CAAC;IAChD,OAAO,EAAE,iBAAiB,CAAC,uBAAuB,CAAC,CAAC;CACrD,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,2CAA2C,GAAG;IACxD,IAAI,EAAE,wCAAwC,CAAC;IAC/C,OAAO,EAAE,iBAAiB,CAAC,sBAAsB,CAAC,CAAC;CACpD,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,MAAM,kCAAkC,GAAG;IAC/C,IAAI,EAAE,+BAA+B,CAAC;IACtC,OAAO,EAAE,iBAAiB,CAAC,aAAa,CAAC,CAAC;CAC3C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,8BAA8B,GACtC,iCAAiC,GACjC,kCAAkC,GAClC,oCAAoC,GACpC,qCAAqC,GACrC,oCAAoC,GACpC,oCAAoC,GACpC,gDAAgD,GAChD,+BAA+B,GAC/B,6CAA6C,GAC7C,4CAA4C,GAC5C,2CAA2C,GAC3C,kCAAkC,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProfileController-method-action-types.js","sourceRoot":"","sources":["../src/ProfileController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { ProfileController } from './ProfileController.js';\n\n/**\n * Returns the current MetaMask profile from state, or undefined if none has been created.\n *\n * @returns The MetaMask profile, or undefined.\n */\nexport type ProfileControllerGetProfileAction = {\n type: `ProfileController:getProfile`;\n handler: ProfileController['getProfile'];\n};\n\n/**\n * Returns the currently linked X profile from state, or undefined if none has been connected.\n *\n * @returns The X profile, or undefined.\n */\nexport type ProfileControllerGetXProfileAction = {\n type: `ProfileController:getXProfile`;\n handler: ProfileController['getXProfile'];\n};\n\n/**\n * Creates a new MetaMask profile, updates state, and returns the created profile.\n *\n * @param params - The profile creation parameters.\n * @returns The created MetaMask profile.\n */\nexport type ProfileControllerCreateProfileAction = {\n type: `ProfileController:createProfile`;\n handler: ProfileController['createProfile'];\n};\n\n/**\n * Fully replaces the current profile and updates state.\n *\n * @param input - The replacement profile data.\n * @throws If no profile has been created yet.\n */\nexport type ProfileControllerReplaceProfileAction = {\n type: `ProfileController:replaceProfile`;\n handler: ProfileController['replaceProfile'];\n};\n\n/**\n * Partially updates the current profile and updates state.\n *\n * @param input - The fields to update.\n * @throws If no profile has been created yet.\n */\nexport type ProfileControllerUpdateProfileAction = {\n type: `ProfileController:updateProfile`;\n handler: ProfileController['updateProfile'];\n};\n\n/**\n * Deletes the current profile and resets state, including clearing any linked X profile.\n *\n * @throws If no profile has been created yet.\n */\nexport type ProfileControllerDeleteProfileAction = {\n type: `ProfileController:deleteProfile`;\n handler: ProfileController['deleteProfile'];\n};\n\n/**\n * Checks whether a username is available.\n *\n * @param username - The username to check.\n * @returns Availability details including validity and normalized form.\n */\nexport type ProfileControllerCheckUsernameAvailabilityAction = {\n type: `ProfileController:checkUsernameAvailability`;\n handler: ProfileController['checkUsernameAvailability'];\n};\n\n/**\n * Completes the X OAuth flow for the profile in state and returns the\n * linked X profile. Updates controller state with the linked X profile
|
|
1
|
+
{"version":3,"file":"ProfileController-method-action-types.js","sourceRoot":"","sources":["../src/ProfileController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { ProfileController } from './ProfileController.js';\n\n/**\n * Returns the current MetaMask profile from state, or undefined if none has been created.\n *\n * @returns The MetaMask profile, or undefined.\n */\nexport type ProfileControllerGetProfileAction = {\n type: `ProfileController:getProfile`;\n handler: ProfileController['getProfile'];\n};\n\n/**\n * Returns the currently linked X profile from state, or undefined if none has been connected.\n *\n * @returns The X profile, or undefined.\n */\nexport type ProfileControllerGetXProfileAction = {\n type: `ProfileController:getXProfile`;\n handler: ProfileController['getXProfile'];\n};\n\n/**\n * Creates a new MetaMask profile, updates state, and returns the created profile.\n *\n * @param params - The profile creation parameters.\n * @returns The created MetaMask profile.\n */\nexport type ProfileControllerCreateProfileAction = {\n type: `ProfileController:createProfile`;\n handler: ProfileController['createProfile'];\n};\n\n/**\n * Fully replaces the current profile and updates state.\n *\n * @param input - The replacement profile data.\n * @throws If no profile has been created yet.\n */\nexport type ProfileControllerReplaceProfileAction = {\n type: `ProfileController:replaceProfile`;\n handler: ProfileController['replaceProfile'];\n};\n\n/**\n * Partially updates the current profile and updates state.\n *\n * @param input - The fields to update.\n * @throws If no profile has been created yet.\n */\nexport type ProfileControllerUpdateProfileAction = {\n type: `ProfileController:updateProfile`;\n handler: ProfileController['updateProfile'];\n};\n\n/**\n * Deletes the current profile and resets state, including clearing any linked X profile.\n *\n * @throws If no profile has been created yet.\n */\nexport type ProfileControllerDeleteProfileAction = {\n type: `ProfileController:deleteProfile`;\n handler: ProfileController['deleteProfile'];\n};\n\n/**\n * Checks whether a username is available.\n *\n * @param username - The username to check.\n * @returns Availability details including validity and normalized form.\n */\nexport type ProfileControllerCheckUsernameAvailabilityAction = {\n type: `ProfileController:checkUsernameAvailability`;\n handler: ProfileController['checkUsernameAvailability'];\n};\n\n/**\n * Completes the X OAuth flow for the profile in state and returns the\n * linked X profile. Updates controller state with the linked X profile.\n *\n * @param params - The parameters for the X OAuth flow.\n * @param params.code - The OAuth authorization code from the X redirect.\n * @param params.state - The state parameter returned by the X redirect.\n * @returns The linked X profile.\n */\nexport type ProfileControllerConnectXAction = {\n type: `ProfileController:connectX`;\n handler: ProfileController['connectX'];\n};\n\n/**\n * Fetches the X account linked to the authenticated profile, updates state,\n * and returns the X profile. The profile is resolved server-side from the\n * verified bearer token.\n *\n * @returns The linked X profile.\n */\nexport type ProfileControllerFetchAndUpdateXAccountAction = {\n type: `ProfileController:fetchAndUpdateXAccount`;\n handler: ProfileController['fetchAndUpdateXAccount'];\n};\n\n/**\n * Fetches a profile by its identifier and updates state.\n *\n * @param profileId - The profile identifier to fetch.\n * @returns The fetched profile.\n */\nexport type ProfileControllerFetchAndUpdateProfileAction = {\n type: `ProfileController:fetchAndUpdateProfile`;\n handler: ProfileController['fetchAndUpdateProfile'];\n};\n\n/**\n * Initiates the X OAuth flow by fetching the authorization URL from the backend.\n * The profile is resolved server-side from the verified bearer token.\n * Returns session data for the caller to use; nothing is stored in controller state.\n *\n * @returns The X authorization URL and state parameter.\n */\nexport type ProfileControllerGetXAuthorizationUrlAction = {\n type: `ProfileController:getXAuthorizationUrl`;\n handler: ProfileController['getXAuthorizationUrl'];\n};\n\n/**\n * Disconnects the X account linked to the given profile. If the given\n * profile matches the profile in state, clears `xProfile` from state and\n * marks the profile in state as no longer connected to X.\n *\n * @param profileId - The ID of the profile to disconnect the linked X account\n * from (sourced from {@link getProfile}).\n */\nexport type ProfileControllerDisconnectXAction = {\n type: `ProfileController:disconnectX`;\n handler: ProfileController['disconnectX'];\n};\n\n/**\n * Union of all ProfileController action types.\n */\nexport type ProfileControllerMethodActions =\n | ProfileControllerGetProfileAction\n | ProfileControllerGetXProfileAction\n | ProfileControllerCreateProfileAction\n | ProfileControllerReplaceProfileAction\n | ProfileControllerUpdateProfileAction\n | ProfileControllerDeleteProfileAction\n | ProfileControllerCheckUsernameAvailabilityAction\n | ProfileControllerConnectXAction\n | ProfileControllerFetchAndUpdateXAccountAction\n | ProfileControllerFetchAndUpdateProfileAction\n | ProfileControllerGetXAuthorizationUrlAction\n | ProfileControllerDisconnectXAction;\n"]}
|
|
@@ -3,7 +3,7 @@ import type { ControllerGetStateAction, ControllerStateChangedEvent } from '@met
|
|
|
3
3
|
import type { Messenger } from '@metamask/messenger';
|
|
4
4
|
import type { CaipAccountId } from '@metamask/utils';
|
|
5
5
|
import type { ProfileControllerMethodActions } from './ProfileController-method-action-types.js';
|
|
6
|
-
import type { ProfileServiceCheckUsernameAvailabilityAction, ProfileServiceConnectXAction, ProfileServiceCreateProfileAction, ProfileServiceDeleteProfileAction, ProfileServiceDisconnectXAction, ProfileServiceGetXAccountAction, ProfileServiceGetXAuthUrlAction, ProfileServiceReplaceProfileAction, ProfileServiceUpdateProfileAction } from './ProfileService-method-action-types.js';
|
|
6
|
+
import type { ProfileServiceCheckUsernameAvailabilityAction, ProfileServiceConnectXAction, ProfileServiceCreateProfileAction, ProfileServiceDeleteProfileAction, ProfileServiceDisconnectXAction, ProfileServiceGetProfileAction, ProfileServiceGetXAccountAction, ProfileServiceGetXAuthUrlAction, ProfileServiceReplaceProfileAction, ProfileServiceUpdateProfileAction } from './ProfileService-method-action-types.js';
|
|
7
7
|
import type { CreateProfileParams, ReplaceProfileParams, UpdateProfileParams, UsernameAvailabilityResponse } from './ProfileService.js';
|
|
8
8
|
declare const controllerName = "ProfileController";
|
|
9
9
|
/** Representation of a profile stored in controller state. */
|
|
@@ -66,7 +66,7 @@ export type ProfileControllerActions = ProfileControllerGetStateAction | Profile
|
|
|
66
66
|
export type ProfileControllerChangeEvent = ControllerStateChangedEvent<typeof controllerName, ProfileControllerState>;
|
|
67
67
|
/** Union of all events emitted by ProfileController. */
|
|
68
68
|
export type ProfileControllerEvents = ProfileControllerChangeEvent;
|
|
69
|
-
type AllowedActions = ProfileServiceCreateProfileAction | ProfileServiceReplaceProfileAction | ProfileServiceUpdateProfileAction | ProfileServiceDeleteProfileAction | ProfileServiceCheckUsernameAvailabilityAction | ProfileServiceConnectXAction | ProfileServiceGetXAccountAction | ProfileServiceGetXAuthUrlAction | ProfileServiceDisconnectXAction;
|
|
69
|
+
type AllowedActions = ProfileServiceCreateProfileAction | ProfileServiceReplaceProfileAction | ProfileServiceUpdateProfileAction | ProfileServiceDeleteProfileAction | ProfileServiceCheckUsernameAvailabilityAction | ProfileServiceConnectXAction | ProfileServiceGetXAccountAction | ProfileServiceGetXAuthUrlAction | ProfileServiceDisconnectXAction | ProfileServiceGetProfileAction;
|
|
70
70
|
export type AllowedEvents = never;
|
|
71
71
|
/** Messenger type for ProfileController, scoped to its actions, events, and allowed service calls. */
|
|
72
72
|
export type ProfileControllerMessenger = Messenger<typeof controllerName, ProfileControllerActions | AllowedActions, ProfileControllerEvents | AllowedEvents>;
|
|
@@ -138,14 +138,12 @@ export declare class ProfileController extends BaseController<typeof controllerN
|
|
|
138
138
|
checkUsernameAvailability(username: string): Promise<UsernameAvailabilityResponse>;
|
|
139
139
|
/**
|
|
140
140
|
* Completes the X OAuth flow for the profile in state and returns the
|
|
141
|
-
* linked X profile. Updates controller state with the linked X profile
|
|
142
|
-
* and marks the profile in state as connected to X.
|
|
141
|
+
* linked X profile. Updates controller state with the linked X profile.
|
|
143
142
|
*
|
|
144
143
|
* @param params - The parameters for the X OAuth flow.
|
|
145
144
|
* @param params.code - The OAuth authorization code from the X redirect.
|
|
146
145
|
* @param params.state - The state parameter returned by the X redirect.
|
|
147
146
|
* @returns The linked X profile.
|
|
148
|
-
* @throws If no profile has been created yet.
|
|
149
147
|
*/
|
|
150
148
|
connectX(params: {
|
|
151
149
|
code: string;
|
|
@@ -159,13 +157,19 @@ export declare class ProfileController extends BaseController<typeof controllerN
|
|
|
159
157
|
* @returns The linked X profile.
|
|
160
158
|
*/
|
|
161
159
|
fetchAndUpdateXAccount(): Promise<XProfile>;
|
|
160
|
+
/**
|
|
161
|
+
* Fetches a profile by its identifier and updates state.
|
|
162
|
+
*
|
|
163
|
+
* @param profileId - The profile identifier to fetch.
|
|
164
|
+
* @returns The fetched profile.
|
|
165
|
+
*/
|
|
166
|
+
fetchAndUpdateProfile(profileId: string): Promise<Profile>;
|
|
162
167
|
/**
|
|
163
168
|
* Initiates the X OAuth flow by fetching the authorization URL from the backend.
|
|
164
169
|
* The profile is resolved server-side from the verified bearer token.
|
|
165
170
|
* Returns session data for the caller to use; nothing is stored in controller state.
|
|
166
171
|
*
|
|
167
172
|
* @returns The X authorization URL and state parameter.
|
|
168
|
-
* @throws If no profile has been created yet.
|
|
169
173
|
*/
|
|
170
174
|
getXAuthorizationUrl(): Promise<ConnectXSession>;
|
|
171
175
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProfileController.d.ts","sourceRoot":"","sources":["../src/ProfileController.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,KAAK,EACV,wBAAwB,EACxB,2BAA2B,EAE5B,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAErD,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,4CAA4C,CAAC;AACjG,OAAO,KAAK,EACV,6CAA6C,EAC7C,4BAA4B,EAC5B,iCAAiC,EACjC,iCAAiC,EACjC,+BAA+B,EAC/B,+BAA+B,EAC/B,+BAA+B,EAC/B,kCAAkC,EAClC,iCAAiC,EAClC,MAAM,yCAAyC,CAAC;AACjD,OAAO,KAAK,EACV,mBAAmB,EAGnB,oBAAoB,EACpB,mBAAmB,EACnB,4BAA4B,EAE7B,MAAM,qBAAqB,CAAC;AAE7B,QAAA,MAAM,cAAc,sBAAsB,CAAC;AAI3C,8DAA8D;AAC9D,MAAM,MAAM,OAAO,GAAG;IACpB,yDAAyD;IACzD,SAAS,EAAE,MAAM,CAAC;IAClB,oCAAoC;IACpC,QAAQ,EAAE,MAAM,CAAC;IACjB,wCAAwC;IACxC,WAAW,EAAE,MAAM,CAAC;IACpB,+BAA+B;IAC/B,GAAG,EAAE,MAAM,CAAC;IACZ,4CAA4C;IAC5C,eAAe,EAAE,aAAa,EAAE,CAAC;IACjC,sCAAsC;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB,uEAAuE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AAC,QAAQ,CAAC,CAUzE;IAED;;;;;;OAMG;IACG,sBAAsB,IAAI,OAAO,CAAC,QAAQ,CAAC,CAOhD;IAED;;;;;OAKG;IACG,qBAAqB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAU/D;IAED;;;;;;OAMG;IACG,oBAAoB,IAAI,OAAO,CAAC,eAAe,CAAC,CAGrD;IAED;;;;;;;OAOG;IACG,WAAW,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAQlD;CACF"}
|
|
@@ -46,6 +46,7 @@ const MESSENGER_EXPOSED_METHODS = [
|
|
|
46
46
|
'checkUsernameAvailability',
|
|
47
47
|
'connectX',
|
|
48
48
|
'fetchAndUpdateXAccount',
|
|
49
|
+
'fetchAndUpdateProfile',
|
|
49
50
|
'getXAuthorizationUrl',
|
|
50
51
|
'disconnectX',
|
|
51
52
|
];
|
|
@@ -105,7 +106,7 @@ export class ProfileController extends BaseController {
|
|
|
105
106
|
displayName: response.display_name,
|
|
106
107
|
bio: response.bio ?? '',
|
|
107
108
|
linkedAddresses: response.linked_addresses,
|
|
108
|
-
avatarUrl: response.avatar_url
|
|
109
|
+
avatarUrl: response.avatar_url,
|
|
109
110
|
tradingPrivacy: response.trading_privacy,
|
|
110
111
|
connectedToX: response.connected_to_x,
|
|
111
112
|
createdAt: response.created_at,
|
|
@@ -212,17 +213,14 @@ export class ProfileController extends BaseController {
|
|
|
212
213
|
}
|
|
213
214
|
/**
|
|
214
215
|
* Completes the X OAuth flow for the profile in state and returns the
|
|
215
|
-
* linked X profile. Updates controller state with the linked X profile
|
|
216
|
-
* and marks the profile in state as connected to X.
|
|
216
|
+
* linked X profile. Updates controller state with the linked X profile.
|
|
217
217
|
*
|
|
218
218
|
* @param params - The parameters for the X OAuth flow.
|
|
219
219
|
* @param params.code - The OAuth authorization code from the X redirect.
|
|
220
220
|
* @param params.state - The state parameter returned by the X redirect.
|
|
221
221
|
* @returns The linked X profile.
|
|
222
|
-
* @throws If no profile has been created yet.
|
|
223
222
|
*/
|
|
224
223
|
async connectX(params) {
|
|
225
|
-
this.#getProfileIdOrThrow();
|
|
226
224
|
const response = await this.messenger.call('ProfileService:connectX', {
|
|
227
225
|
code: params.code,
|
|
228
226
|
state: params.state,
|
|
@@ -230,7 +228,6 @@ export class ProfileController extends BaseController {
|
|
|
230
228
|
const mapped = this.#mapXResponseToXProfile(response);
|
|
231
229
|
this.update((state) => {
|
|
232
230
|
state.xProfile = mapped;
|
|
233
|
-
state.profile.connectedToX = true;
|
|
234
231
|
});
|
|
235
232
|
return mapped;
|
|
236
233
|
}
|
|
@@ -249,16 +246,28 @@ export class ProfileController extends BaseController {
|
|
|
249
246
|
});
|
|
250
247
|
return mapped;
|
|
251
248
|
}
|
|
249
|
+
/**
|
|
250
|
+
* Fetches a profile by its identifier and updates state.
|
|
251
|
+
*
|
|
252
|
+
* @param profileId - The profile identifier to fetch.
|
|
253
|
+
* @returns The fetched profile.
|
|
254
|
+
*/
|
|
255
|
+
async fetchAndUpdateProfile(profileId) {
|
|
256
|
+
const response = await this.messenger.call('ProfileService:getProfile', profileId);
|
|
257
|
+
const mapped = this.#mapApiResponseToProfile(response);
|
|
258
|
+
this.update((state) => {
|
|
259
|
+
state.profile = mapped;
|
|
260
|
+
});
|
|
261
|
+
return mapped;
|
|
262
|
+
}
|
|
252
263
|
/**
|
|
253
264
|
* Initiates the X OAuth flow by fetching the authorization URL from the backend.
|
|
254
265
|
* The profile is resolved server-side from the verified bearer token.
|
|
255
266
|
* Returns session data for the caller to use; nothing is stored in controller state.
|
|
256
267
|
*
|
|
257
268
|
* @returns The X authorization URL and state parameter.
|
|
258
|
-
* @throws If no profile has been created yet.
|
|
259
269
|
*/
|
|
260
270
|
async getXAuthorizationUrl() {
|
|
261
|
-
this.#getProfileIdOrThrow();
|
|
262
271
|
const response = await this.messenger.call('ProfileService:getXAuthUrl');
|
|
263
272
|
return { authorizationUrl: response.url, state: response.state };
|
|
264
273
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProfileController.js","sourceRoot":"","sources":["../src/ProfileController.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AA+B3D,MAAM,cAAc,GAAG,mBAAmB,CAAC;AAsG3C,gBAAgB;AAEhB,MAAM,yBAAyB,GAAG;IAChC,OAAO,EAAE;QACP,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;IACD,QAAQ,EAAE;QACR,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;CAC8C,CAAC;AAElD;;;;GAIG;AACH,MAAM,UAAU,gCAAgC;IAC9C,OAAO;QACL,OAAO,EAAE;YACP,SAAS,EAAE,EAAE;YACb,QAAQ,EAAE,EAAE;YACZ,WAAW,EAAE,EAAE;YACf,GAAG,EAAE,EAAE;YACP,eAAe,EAAE,EAAE;YACnB,SAAS,EAAE,EAAE;YACb,cAAc,EAAE,QAAQ;YACxB,YAAY,EAAE,KAAK;YACnB,SAAS,EAAE,EAAE;YACb,SAAS,EAAE,EAAE;SACd;KACF,CAAC;AACJ,CAAC;AAED,MAAM,yBAAyB,GAAG;IAChC,YAAY;IACZ,aAAa;IACb,eAAe;IACf,gBAAgB;IAChB,eAAe;IACf,eAAe;IACf,2BAA2B;IAC3B,UAAU;IACV,wBAAwB;IACxB,sBAAsB;IACtB,aAAa;CACL,CAAC;AAEX,qBAAqB;AAErB,qFAAqF;AACrF,MAAM,OAAO,iBAAkB,SAAQ,cAItC;IACC;;;;;;OAMG;IACH,YAAY,EACV,SAAS,EACT,KAAK,GAIN;QACC,KAAK,CAAC;YACJ,SAAS;YACT,IAAI,EAAE,cAAc;YACpB,QAAQ,EAAE,yBAAyB;YACnC,KAAK,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GetStateAction,\n ControllerStateChangedEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { CaipAccountId } from '@metamask/utils';\n\nimport type { ProfileControllerMethodActions } from './ProfileController-method-action-types.js';\nimport type {\n ProfileServiceCheckUsernameAvailabilityAction,\n ProfileServiceConnectXAction,\n ProfileServiceCreateProfileAction,\n ProfileServiceDeleteProfileAction,\n ProfileServiceDisconnectXAction,\n ProfileServiceGetXAccountAction,\n ProfileServiceGetXAuthUrlAction,\n ProfileServiceReplaceProfileAction,\n ProfileServiceUpdateProfileAction,\n} from './ProfileService-method-action-types.js';\nimport type {\n CreateProfileParams,\n CreateProfileResponse,\n ProfileApiResponse,\n ReplaceProfileParams,\n UpdateProfileParams,\n UsernameAvailabilityResponse,\n ConnectXResponse,\n} from './ProfileService.js';\n\nconst controllerName = 'ProfileController';\n\n// === TYPES ===\n\n/** Representation of a profile stored in controller state. */\nexport type Profile = {\n /** The canonical profile ID connected to the profile. */\n profileId: string;\n /** The username for the profile. */\n username: string;\n /** The display name for the profile. */\n displayName: string;\n /** The bio for the profile. */\n bio: string;\n /** The linked addresses for the profile. */\n linkedAddresses: CaipAccountId[];\n /** The avatar URL for the profile. */\n avatarUrl: string;\n /** Whether the profile's trading activity is visible to the public. */\n tradingPrivacy: 'public' | 'private';\n /** Whether the profile is connected to X. */\n connectedToX: boolean;\n /** The date and time the profile was created. */\n createdAt: string;\n /** The date and time the profile was updated. */\n updatedAt: string;\n};\n\n/** Representation of a linked X (Twitter) profile stored in controller state. */\nexport type XProfile = {\n /** The unique identifier for the X profile. This is the user ID of the X profile. */\n xUserId: string;\n /** The URL for the X profile. */\n xProfileUrl: string;\n /** The username for the X profile. */\n username: string;\n /** The display name for the X profile. */\n displayName: string;\n /** The avatar URL for the X profile. */\n avatarUrl: string;\n /** The date and time the X profile was created. */\n createdAt: string;\n /** The date and time the X profile was updated. */\n updatedAt: string;\n};\n\n/** Ephemeral session data for initiating the X OAuth flow. Not stored in controller state. */\nexport type ConnectXSession = {\n /** The X authorization URL to open in a system browser. */\n authorizationUrl: string;\n /** The OAuth state parameter to compare against the X redirect callback. */\n state: string;\n};\n\n/** State managed by ProfileController. */\nexport type ProfileControllerState = {\n profile: Profile;\n xProfile?: XProfile;\n};\n\n// === MESSENGER ===\n\n/** The `ProfileController:getState` action type. */\nexport type ProfileControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n ProfileControllerState\n>;\n\n/** Union of all actions exposed by ProfileController. */\nexport type ProfileControllerActions =\n | ProfileControllerGetStateAction\n | ProfileControllerMethodActions;\n\n/** The `ProfileController:stateChanged` event type. */\nexport type ProfileControllerChangeEvent = ControllerStateChangedEvent<\n typeof controllerName,\n ProfileControllerState\n>;\n\n/** Union of all events emitted by ProfileController. */\nexport type ProfileControllerEvents = ProfileControllerChangeEvent;\n\ntype AllowedActions =\n | ProfileServiceCreateProfileAction\n | ProfileServiceReplaceProfileAction\n | ProfileServiceUpdateProfileAction\n | ProfileServiceDeleteProfileAction\n | ProfileServiceCheckUsernameAvailabilityAction\n | ProfileServiceConnectXAction\n | ProfileServiceGetXAccountAction\n | ProfileServiceGetXAuthUrlAction\n | ProfileServiceDisconnectXAction;\n\nexport type AllowedEvents = never;\n\n/** Messenger type for ProfileController, scoped to its actions, events, and allowed service calls. */\nexport type ProfileControllerMessenger = Messenger<\n typeof controllerName,\n ProfileControllerActions | AllowedActions,\n ProfileControllerEvents | AllowedEvents\n>;\n\n// === STATE ===\n\nconst profileControllerMetadata = {\n profile: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n xProfile: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n} satisfies StateMetadata<ProfileControllerState>;\n\n/**\n * Returns the default initial state for ProfileController.\n *\n * @returns A ProfileControllerState with empty profile fields and no X profile.\n */\nexport function getDefaultProfileControllerState(): ProfileControllerState {\n return {\n profile: {\n profileId: '',\n username: '',\n displayName: '',\n bio: '',\n linkedAddresses: [],\n avatarUrl: '',\n tradingPrivacy: 'public',\n connectedToX: false,\n createdAt: '',\n updatedAt: '',\n },\n };\n}\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'getProfile',\n 'getXProfile',\n 'createProfile',\n 'replaceProfile',\n 'updateProfile',\n 'deleteProfile',\n 'checkUsernameAvailability',\n 'connectX',\n 'fetchAndUpdateXAccount',\n 'getXAuthorizationUrl',\n 'disconnectX',\n] as const;\n\n// === CONTROLLER ===\n\n/** Manages MetaMask profile state and delegates API operations to ProfileService. */\nexport class ProfileController extends BaseController<\n typeof controllerName,\n ProfileControllerState,\n ProfileControllerMessenger\n> {\n /**\n * Creates a new ProfileController instance.\n *\n * @param options - Constructor options.\n * @param options.messenger - The messenger scoped to ProfileController.\n * @param options.state - Optional partial initial state to merge with defaults.\n */\n constructor({\n messenger,\n state,\n }: {\n messenger: ProfileControllerMessenger;\n state?: Partial<ProfileControllerState>;\n }) {\n super({\n messenger,\n name: controllerName,\n metadata: profileControllerMetadata,\n state: {\n ...getDefaultProfileControllerState(),\n ...state,\n },\n });\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Returns true if a profile has been created and exists in state.\n *\n * @returns True if a profile exists, false otherwise.\n */\n #hasProfile(): boolean {\n return this.state.profile.profileId !== '';\n }\n\n /**\n * Returns the profile ID from state, throwing if no profile exists yet.\n *\n * @returns The current profile ID.\n * @throws If no profile has been created.\n */\n #getProfileIdOrThrow(): string {\n const { profileId } = this.state.profile;\n if (!profileId) {\n throw new Error('ProfileController: no profile found in state');\n }\n return profileId;\n }\n\n /**\n * Maps an API response to a MetaMask profile.\n *\n * @param response - The API response to map.\n * @returns The mapped MetaMask profile.\n */\n #mapApiResponseToProfile(response: ProfileApiResponse): Profile {\n return {\n profileId: response.profile_id,\n username: response.username,\n displayName: response.display_name,\n bio: response.bio ?? '',\n linkedAddresses: response.linked_addresses,\n avatarUrl: response.avatar_url ?? '',\n tradingPrivacy: response.trading_privacy,\n connectedToX: response.connected_to_x,\n createdAt: response.created_at,\n updatedAt: response.updated_at,\n };\n }\n\n /**\n * Maps an API response to an X profile.\n *\n * @param response - The API response to map.\n * @returns The mapped X profile.\n */\n #mapXResponseToXProfile(response: ConnectXResponse): XProfile {\n return {\n xUserId: response.x_user_id,\n xProfileUrl: response.x_profile_url,\n username: response.username,\n displayName: response.display_name,\n avatarUrl: response.avatar_url,\n createdAt: response.created_at,\n updatedAt: response.updated_at,\n };\n }\n\n /**\n * Returns the current MetaMask profile from state, or undefined if none has been created.\n *\n * @returns The MetaMask profile, or undefined.\n */\n getProfile(): Profile | undefined {\n if (!this.#hasProfile()) {\n return undefined;\n }\n return this.state.profile;\n }\n\n /**\n * Returns the currently linked X profile from state, or undefined if none has been connected.\n *\n * @returns The X profile, or undefined.\n */\n getXProfile(): XProfile | undefined {\n return this.state.xProfile;\n }\n\n /**\n * Creates a new MetaMask profile, updates state, and returns the created profile.\n *\n * @param params - The profile creation parameters.\n * @returns The created MetaMask profile.\n */\n async createProfile(params: CreateProfileParams): Promise<Profile> {\n const response: CreateProfileResponse = await this.messenger.call(\n 'ProfileService:createProfile',\n params,\n );\n const mapped = this.#mapApiResponseToProfile(response);\n this.update((state) => {\n state.profile = mapped;\n });\n return mapped;\n }\n\n /**\n * Fully replaces the current profile and updates state.\n *\n * @param input - The replacement profile data.\n * @throws If no profile has been created yet.\n */\n async replaceProfile(input: ReplaceProfileParams): Promise<void> {\n const profileId = this.#getProfileIdOrThrow();\n const response = await this.messenger.call(\n 'ProfileService:replaceProfile',\n profileId,\n input,\n );\n this.update((state) => {\n state.profile = this.#mapApiResponseToProfile(response);\n });\n }\n\n /**\n * Partially updates the current profile and updates state.\n *\n * @param input - The fields to update.\n * @throws If no profile has been created yet.\n */\n async updateProfile(input: UpdateProfileParams): Promise<void> {\n const profileId = this.#getProfileIdOrThrow();\n const response = await this.messenger.call(\n 'ProfileService:updateProfile',\n profileId,\n input,\n );\n this.update((state) => {\n state.profile = this.#mapApiResponseToProfile(response);\n });\n }\n\n /**\n * Deletes the current profile and resets state, including clearing any linked X profile.\n *\n * @throws If no profile has been created yet.\n */\n async deleteProfile(): Promise<void> {\n const profileId = this.#getProfileIdOrThrow();\n await this.messenger.call('ProfileService:deleteProfile', profileId);\n this.update((state) => {\n state.profile = getDefaultProfileControllerState().profile;\n state.xProfile = undefined;\n });\n }\n\n /**\n * Checks whether a username is available.\n *\n * @param username - The username to check.\n * @returns Availability details including validity and normalized form.\n */\n async checkUsernameAvailability(\n username: string,\n ): Promise<UsernameAvailabilityResponse> {\n return await this.messenger.call(\n 'ProfileService:checkUsernameAvailability',\n username,\n );\n }\n\n /**\n * Completes the X OAuth flow for the profile in state and returns the\n * linked X profile. Updates controller state with the linked X profile\n * and marks the profile in state as connected to X.\n *\n * @param params - The parameters for the X OAuth flow.\n * @param params.code - The OAuth authorization code from the X redirect.\n * @param params.state - The state parameter returned by the X redirect.\n * @returns The linked X profile.\n * @throws If no profile has been created yet.\n */\n async connectX(params: { code: string; state: string }): Promise<XProfile> {\n this.#getProfileIdOrThrow();\n const response = await this.messenger.call('ProfileService:connectX', {\n code: params.code,\n state: params.state,\n });\n const mapped = this.#mapXResponseToXProfile(response);\n this.update((state) => {\n state.xProfile = mapped;\n state.profile.connectedToX = true;\n });\n return mapped;\n }\n\n /**\n * Fetches the X account linked to the authenticated profile, updates state,\n * and returns the X profile. The profile is resolved server-side from the\n * verified bearer token.\n *\n * @returns The linked X profile.\n */\n async fetchAndUpdateXAccount(): Promise<XProfile> {\n const response = await this.messenger.call('ProfileService:getXAccount');\n const mapped = this.#mapXResponseToXProfile(response);\n this.update((state) => {\n state.xProfile = mapped;\n });\n return mapped;\n }\n\n /**\n * Initiates the X OAuth flow by fetching the authorization URL from the backend.\n * The profile is resolved server-side from the verified bearer token.\n * Returns session data for the caller to use; nothing is stored in controller state.\n *\n * @returns The X authorization URL and state parameter.\n * @throws If no profile has been created yet.\n */\n async getXAuthorizationUrl(): Promise<ConnectXSession> {\n this.#getProfileIdOrThrow();\n const response = await this.messenger.call('ProfileService:getXAuthUrl');\n return { authorizationUrl: response.url, state: response.state };\n }\n\n /**\n * Disconnects the X account linked to the given profile. If the given\n * profile matches the profile in state, clears `xProfile` from state and\n * marks the profile in state as no longer connected to X.\n *\n * @param profileId - The ID of the profile to disconnect the linked X account\n * from (sourced from {@link getProfile}).\n */\n async disconnectX(profileId: string): Promise<void> {\n await this.messenger.call('ProfileService:disconnectX', profileId);\n this.update((state) => {\n if (state.profile.profileId === profileId) {\n state.xProfile = undefined;\n state.profile.connectedToX = false;\n }\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ProfileController.js","sourceRoot":"","sources":["../src/ProfileController.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAgC3D,MAAM,cAAc,GAAG,mBAAmB,CAAC;AAuG3C,gBAAgB;AAEhB,MAAM,yBAAyB,GAAG;IAChC,OAAO,EAAE;QACP,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;IACD,QAAQ,EAAE;QACR,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;CAC8C,CAAC;AAElD;;;;GAIG;AACH,MAAM,UAAU,gCAAgC;IAC9C,OAAO;QACL,OAAO,EAAE;YACP,SAAS,EAAE,EAAE;YACb,QAAQ,EAAE,EAAE;YACZ,WAAW,EAAE,EAAE;YACf,GAAG,EAAE,EAAE;YACP,eAAe,EAAE,EAAE;YACnB,SAAS,EAAE,EAAE;YACb,cAAc,EAAE,QAAQ;YACxB,YAAY,EAAE,KAAK;YACnB,SAAS,EAAE,EAAE;YACb,SAAS,EAAE,EAAE;SACd;KACF,CAAC;AACJ,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AQ,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,4BAA4B,CAAC,CAAC;QACzE,OAAO,EAAE,gBAAgB,EAAE,QAAQ,CAAC,GAAG,EAAE,KAAK,EAAE,QAAQ,CAAC,KAAK,EAAE,CAAC;IACnE,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CAAC,WAAW,CAAC,SAAiB;QACjC,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,4BAA4B,EAAE,SAAS,CAAC,CAAC;QACnE,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,IAAI,KAAK,CAAC,OAAO,CAAC,SAAS,KAAK,SAAS,EAAE,CAAC;gBAC1C,KAAK,CAAC,QAAQ,GAAG,SAAS,CAAC;gBAC3B,KAAK,CAAC,OAAO,CAAC,YAAY,GAAG,KAAK,CAAC;YACrC,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { BaseController } from '@metamask/base-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangedEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { CaipAccountId } from '@metamask/utils';\n\nimport type { ProfileControllerMethodActions } from './ProfileController-method-action-types.js';\nimport type {\n ProfileServiceCheckUsernameAvailabilityAction,\n ProfileServiceConnectXAction,\n ProfileServiceCreateProfileAction,\n ProfileServiceDeleteProfileAction,\n ProfileServiceDisconnectXAction,\n ProfileServiceGetProfileAction,\n ProfileServiceGetXAccountAction,\n ProfileServiceGetXAuthUrlAction,\n ProfileServiceReplaceProfileAction,\n ProfileServiceUpdateProfileAction,\n} from './ProfileService-method-action-types.js';\nimport type {\n CreateProfileParams,\n CreateProfileResponse,\n ProfileApiResponse,\n ReplaceProfileParams,\n UpdateProfileParams,\n UsernameAvailabilityResponse,\n ConnectXResponse,\n} from './ProfileService.js';\n\nconst controllerName = 'ProfileController';\n\n// === TYPES ===\n\n/** Representation of a profile stored in controller state. */\nexport type Profile = {\n /** The canonical profile ID connected to the profile. */\n profileId: string;\n /** The username for the profile. */\n username: string;\n /** The display name for the profile. */\n displayName: string;\n /** The bio for the profile. */\n bio: string;\n /** The linked addresses for the profile. */\n linkedAddresses: CaipAccountId[];\n /** The avatar URL for the profile. */\n avatarUrl: string;\n /** Whether the profile's trading activity is visible to the public. */\n tradingPrivacy: 'public' | 'private';\n /** Whether the profile is connected to X. */\n connectedToX: boolean;\n /** The date and time the profile was created. */\n createdAt: string;\n /** The date and time the profile was updated. */\n updatedAt: string;\n};\n\n/** Representation of a linked X (Twitter) profile stored in controller state. */\nexport type XProfile = {\n /** The unique identifier for the X profile. This is the user ID of the X profile. */\n xUserId: string;\n /** The URL for the X profile. */\n xProfileUrl: string;\n /** The username for the X profile. */\n username: string;\n /** The display name for the X profile. */\n displayName: string;\n /** The avatar URL for the X profile. */\n avatarUrl: string;\n /** The date and time the X profile was created. */\n createdAt: string;\n /** The date and time the X profile was updated. */\n updatedAt: string;\n};\n\n/** Ephemeral session data for initiating the X OAuth flow. Not stored in controller state. */\nexport type ConnectXSession = {\n /** The X authorization URL to open in a system browser. */\n authorizationUrl: string;\n /** The OAuth state parameter to compare against the X redirect callback. */\n state: string;\n};\n\n/** State managed by ProfileController. */\nexport type ProfileControllerState = {\n profile: Profile;\n xProfile?: XProfile;\n};\n\n// === MESSENGER ===\n\n/** The `ProfileController:getState` action type. */\nexport type ProfileControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n ProfileControllerState\n>;\n\n/** Union of all actions exposed by ProfileController. */\nexport type ProfileControllerActions =\n | ProfileControllerGetStateAction\n | ProfileControllerMethodActions;\n\n/** The `ProfileController:stateChanged` event type. */\nexport type ProfileControllerChangeEvent = ControllerStateChangedEvent<\n typeof controllerName,\n ProfileControllerState\n>;\n\n/** Union of all events emitted by ProfileController. */\nexport type ProfileControllerEvents = ProfileControllerChangeEvent;\n\ntype AllowedActions =\n | ProfileServiceCreateProfileAction\n | ProfileServiceReplaceProfileAction\n | ProfileServiceUpdateProfileAction\n | ProfileServiceDeleteProfileAction\n | ProfileServiceCheckUsernameAvailabilityAction\n | ProfileServiceConnectXAction\n | ProfileServiceGetXAccountAction\n | ProfileServiceGetXAuthUrlAction\n | ProfileServiceDisconnectXAction\n | ProfileServiceGetProfileAction;\n\nexport type AllowedEvents = never;\n\n/** Messenger type for ProfileController, scoped to its actions, events, and allowed service calls. */\nexport type ProfileControllerMessenger = Messenger<\n typeof controllerName,\n ProfileControllerActions | AllowedActions,\n ProfileControllerEvents | AllowedEvents\n>;\n\n// === STATE ===\n\nconst profileControllerMetadata = {\n profile: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n xProfile: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n} satisfies StateMetadata<ProfileControllerState>;\n\n/**\n * Returns the default initial state for ProfileController.\n *\n * @returns A ProfileControllerState with empty profile fields and no X profile.\n */\nexport function getDefaultProfileControllerState(): ProfileControllerState {\n return {\n profile: {\n profileId: '',\n username: '',\n displayName: '',\n bio: '',\n linkedAddresses: [],\n avatarUrl: '',\n tradingPrivacy: 'public',\n connectedToX: false,\n createdAt: '',\n updatedAt: '',\n },\n };\n}\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'getProfile',\n 'getXProfile',\n 'createProfile',\n 'replaceProfile',\n 'updateProfile',\n 'deleteProfile',\n 'checkUsernameAvailability',\n 'connectX',\n 'fetchAndUpdateXAccount',\n 'fetchAndUpdateProfile',\n 'getXAuthorizationUrl',\n 'disconnectX',\n] as const;\n\n// === CONTROLLER ===\n\n/** Manages MetaMask profile state and delegates API operations to ProfileService. */\nexport class ProfileController extends BaseController<\n typeof controllerName,\n ProfileControllerState,\n ProfileControllerMessenger\n> {\n /**\n * Creates a new ProfileController instance.\n *\n * @param options - Constructor options.\n * @param options.messenger - The messenger scoped to ProfileController.\n * @param options.state - Optional partial initial state to merge with defaults.\n */\n constructor({\n messenger,\n state,\n }: {\n messenger: ProfileControllerMessenger;\n state?: Partial<ProfileControllerState>;\n }) {\n super({\n messenger,\n name: controllerName,\n metadata: profileControllerMetadata,\n state: {\n ...getDefaultProfileControllerState(),\n ...state,\n },\n });\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Returns true if a profile has been created and exists in state.\n *\n * @returns True if a profile exists, false otherwise.\n */\n #hasProfile(): boolean {\n return this.state.profile.profileId !== '';\n }\n\n /**\n * Returns the profile ID from state, throwing if no profile exists yet.\n *\n * @returns The current profile ID.\n * @throws If no profile has been created.\n */\n #getProfileIdOrThrow(): string {\n const { profileId } = this.state.profile;\n if (!profileId) {\n throw new Error('ProfileController: no profile found in state');\n }\n return profileId;\n }\n\n /**\n * Maps an API response to a MetaMask profile.\n *\n * @param response - The API response to map.\n * @returns The mapped MetaMask profile.\n */\n #mapApiResponseToProfile(response: ProfileApiResponse): Profile {\n return {\n profileId: response.profile_id,\n username: response.username,\n displayName: response.display_name,\n bio: response.bio ?? '',\n linkedAddresses: response.linked_addresses,\n avatarUrl: response.avatar_url,\n tradingPrivacy: response.trading_privacy,\n connectedToX: response.connected_to_x,\n createdAt: response.created_at,\n updatedAt: response.updated_at,\n };\n }\n\n /**\n * Maps an API response to an X profile.\n *\n * @param response - The API response to map.\n * @returns The mapped X profile.\n */\n #mapXResponseToXProfile(response: ConnectXResponse): XProfile {\n return {\n xUserId: response.x_user_id,\n xProfileUrl: response.x_profile_url,\n username: response.username,\n displayName: response.display_name,\n avatarUrl: response.avatar_url,\n createdAt: response.created_at,\n updatedAt: response.updated_at,\n };\n }\n\n /**\n * Returns the current MetaMask profile from state, or undefined if none has been created.\n *\n * @returns The MetaMask profile, or undefined.\n */\n getProfile(): Profile | undefined {\n if (!this.#hasProfile()) {\n return undefined;\n }\n return this.state.profile;\n }\n\n /**\n * Returns the currently linked X profile from state, or undefined if none has been connected.\n *\n * @returns The X profile, or undefined.\n */\n getXProfile(): XProfile | undefined {\n return this.state.xProfile;\n }\n\n /**\n * Creates a new MetaMask profile, updates state, and returns the created profile.\n *\n * @param params - The profile creation parameters.\n * @returns The created MetaMask profile.\n */\n async createProfile(params: CreateProfileParams): Promise<Profile> {\n const response: CreateProfileResponse = await this.messenger.call(\n 'ProfileService:createProfile',\n params,\n );\n const mapped = this.#mapApiResponseToProfile(response);\n this.update((state) => {\n state.profile = mapped;\n });\n return mapped;\n }\n\n /**\n * Fully replaces the current profile and updates state.\n *\n * @param input - The replacement profile data.\n * @throws If no profile has been created yet.\n */\n async replaceProfile(input: ReplaceProfileParams): Promise<void> {\n const profileId = this.#getProfileIdOrThrow();\n const response = await this.messenger.call(\n 'ProfileService:replaceProfile',\n profileId,\n input,\n );\n this.update((state) => {\n state.profile = this.#mapApiResponseToProfile(response);\n });\n }\n\n /**\n * Partially updates the current profile and updates state.\n *\n * @param input - The fields to update.\n * @throws If no profile has been created yet.\n */\n async updateProfile(input: UpdateProfileParams): Promise<void> {\n const profileId = this.#getProfileIdOrThrow();\n const response = await this.messenger.call(\n 'ProfileService:updateProfile',\n profileId,\n input,\n );\n this.update((state) => {\n state.profile = this.#mapApiResponseToProfile(response);\n });\n }\n\n /**\n * Deletes the current profile and resets state, including clearing any linked X profile.\n *\n * @throws If no profile has been created yet.\n */\n async deleteProfile(): Promise<void> {\n const profileId = this.#getProfileIdOrThrow();\n await this.messenger.call('ProfileService:deleteProfile', profileId);\n this.update((state) => {\n state.profile = getDefaultProfileControllerState().profile;\n state.xProfile = undefined;\n });\n }\n\n /**\n * Checks whether a username is available.\n *\n * @param username - The username to check.\n * @returns Availability details including validity and normalized form.\n */\n async checkUsernameAvailability(\n username: string,\n ): Promise<UsernameAvailabilityResponse> {\n return await this.messenger.call(\n 'ProfileService:checkUsernameAvailability',\n username,\n );\n }\n\n /**\n * Completes the X OAuth flow for the profile in state and returns the\n * linked X profile. Updates controller state with the linked X profile.\n *\n * @param params - The parameters for the X OAuth flow.\n * @param params.code - The OAuth authorization code from the X redirect.\n * @param params.state - The state parameter returned by the X redirect.\n * @returns The linked X profile.\n */\n async connectX(params: { code: string; state: string }): Promise<XProfile> {\n const response = await this.messenger.call('ProfileService:connectX', {\n code: params.code,\n state: params.state,\n });\n const mapped = this.#mapXResponseToXProfile(response);\n this.update((state) => {\n state.xProfile = mapped;\n });\n return mapped;\n }\n\n /**\n * Fetches the X account linked to the authenticated profile, updates state,\n * and returns the X profile. The profile is resolved server-side from the\n * verified bearer token.\n *\n * @returns The linked X profile.\n */\n async fetchAndUpdateXAccount(): Promise<XProfile> {\n const response = await this.messenger.call('ProfileService:getXAccount');\n const mapped = this.#mapXResponseToXProfile(response);\n this.update((state) => {\n state.xProfile = mapped;\n });\n return mapped;\n }\n\n /**\n * Fetches a profile by its identifier and updates state.\n *\n * @param profileId - The profile identifier to fetch.\n * @returns The fetched profile.\n */\n async fetchAndUpdateProfile(profileId: string): Promise<Profile> {\n const response = await this.messenger.call(\n 'ProfileService:getProfile',\n profileId,\n );\n const mapped = this.#mapApiResponseToProfile(response);\n this.update((state) => {\n state.profile = mapped;\n });\n return mapped;\n }\n\n /**\n * Initiates the X OAuth flow by fetching the authorization URL from the backend.\n * The profile is resolved server-side from the verified bearer token.\n * Returns session data for the caller to use; nothing is stored in controller state.\n *\n * @returns The X authorization URL and state parameter.\n */\n async getXAuthorizationUrl(): Promise<ConnectXSession> {\n const response = await this.messenger.call('ProfileService:getXAuthUrl');\n return { authorizationUrl: response.url, state: response.state };\n }\n\n /**\n * Disconnects the X account linked to the given profile. If the given\n * profile matches the profile in state, clears `xProfile` from state and\n * marks the profile in state as no longer connected to X.\n *\n * @param profileId - The ID of the profile to disconnect the linked X account\n * from (sourced from {@link getProfile}).\n */\n async disconnectX(profileId: string): Promise<void> {\n await this.messenger.call('ProfileService:disconnectX', profileId);\n this.update((state) => {\n if (state.profile.profileId === profileId) {\n state.xProfile = undefined;\n state.profile.connectedToX = false;\n }\n });\n }\n}\n"]}
|
package/dist/ProfileService.d.ts
CHANGED
|
@@ -24,7 +24,7 @@ declare const ProfileApiResponseStruct: import("@metamask/superstruct").Struct<{
|
|
|
24
24
|
display_name: string;
|
|
25
25
|
bio: string | null;
|
|
26
26
|
linked_addresses: `${string}:${string}:${string}`[];
|
|
27
|
-
avatar_url: string
|
|
27
|
+
avatar_url: string;
|
|
28
28
|
trading_privacy: "private" | "public";
|
|
29
29
|
connected_to_x: boolean;
|
|
30
30
|
created_at: string;
|
|
@@ -35,7 +35,7 @@ declare const ProfileApiResponseStruct: import("@metamask/superstruct").Struct<{
|
|
|
35
35
|
display_name: import("@metamask/superstruct").Struct<string, null>;
|
|
36
36
|
bio: import("@metamask/superstruct").Struct<string | null, null>;
|
|
37
37
|
linked_addresses: import("@metamask/superstruct").Struct<`${string}:${string}:${string}`[], import("@metamask/superstruct").Struct<`${string}:${string}:${string}`, null>>;
|
|
38
|
-
avatar_url: import("@metamask/superstruct").Struct<string
|
|
38
|
+
avatar_url: import("@metamask/superstruct").Struct<string, null>;
|
|
39
39
|
trading_privacy: import("@metamask/superstruct").Struct<"private" | "public", {
|
|
40
40
|
private: "private";
|
|
41
41
|
public: "public";
|
|
@@ -99,7 +99,7 @@ declare const CreateProfileResponseStruct: import("@metamask/superstruct").Struc
|
|
|
99
99
|
display_name: string;
|
|
100
100
|
bio: string | null;
|
|
101
101
|
linked_addresses: `${string}:${string}:${string}`[];
|
|
102
|
-
avatar_url: string
|
|
102
|
+
avatar_url: string;
|
|
103
103
|
trading_privacy: "private" | "public";
|
|
104
104
|
connected_to_x: boolean;
|
|
105
105
|
created_at: string;
|
package/dist/ProfileService.js
CHANGED
|
@@ -29,7 +29,7 @@ const ProfileApiResponseStruct = structType({
|
|
|
29
29
|
display_name: string(),
|
|
30
30
|
bio: nullable(string()),
|
|
31
31
|
linked_addresses: array(CaipAccountIdStruct),
|
|
32
|
-
avatar_url:
|
|
32
|
+
avatar_url: string(),
|
|
33
33
|
trading_privacy: TradingPrivacyStruct,
|
|
34
34
|
connected_to_x: boolean(),
|
|
35
35
|
created_at: string(),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProfileService.js","sourceRoot":"","sources":["../src/ProfileService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAO9D,OAAO,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAC;AAGvD,OAAO,EACL,KAAK,EACL,OAAO,EACP,KAAK,EACL,YAAY,EACZ,QAAQ,EACR,QAAQ,EACR,SAAS,EACT,MAAM,EACN,IAAI,IAAI,UAAU,GACnB,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAItD,MAAM,CAAC,MAAM,WAAW,GAAG,gBAAgB,CAAC;AAE5C,8EAA8E;AAC9E,iBAAiB;AACjB,8EAA8E;AAE9E,uEAAuE;AACvE,MAAM,CAAC,MAAM,0BAA0B,GAAG;IACxC,kBAAkB,EAAE,yCAAyC;IAC7D,qBAAqB,EAAE,0CAA0C;IACjE,sBAAsB,EAAE,2CAA2C;IACnE,qBAAqB,EAAE,0CAA0C;IACjE,qBAAqB,EAAE,0CAA0C;IACjE,kCAAkC,EAChC,uDAAuD;IACzD,qBAAqB,EAAE,oDAAoD;IAC3E,gBAAgB,EAAE,6CAA6C;IAC/D,oBAAoB,EAAE,yCAAyC;IAC/D,mBAAmB,EAAE,gDAAgD;CAC7D,CAAC;AAEX,8EAA8E;AAC9E,sBAAsB;AACtB,8EAA8E;AAE9E,MAAM,oBAAoB,GAAG,KAAK,CAAC,CAAC,QAAQ,EAAE,SAAS,CAAU,CAAC,CAAC;AAEnE,MAAM,wBAAwB,GAAG,UAAU,CAAC;IAC1C,UAAU,EAAE,MAAM,EAAE;IACpB,QAAQ,EAAE,MAAM,EAAE;IAClB,YAAY,EAAE,MAAM,EAAE;IACtB,GAAG,EAAE,QAAQ,CAAC,MAAM,EAAE,CAA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E,0BAA0B,CAAC,mBAAmB;qBACtD,CACF,CAAC;gBACJ,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBACf,IAAI,KAAK,YAAY,SAAS,IAAI,KAAK,CAAC,UAAU,KAAK,GAAG,EAAE,CAAC;wBAC3D,OAAO,IAAI,CAAC;oBACd,CAAC;oBACD,MAAM,KAAK,CAAC;gBACd,CAAC;YACH,CAAC;SACF,CAAC,CAAC;QACH,0DAA0D;QAC1D,MAAM,IAAI,CAAC,iBAAiB,CAAC;YAC3B,QAAQ,EAAE,CAAC,GAAG,IAAI,CAAC,IAAI,aAAa,EAAE,SAAS,CAAC;SACjD,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { BaseDataService } from '@metamask/base-data-service';\nimport type {\n CreateServicePolicyOptions,\n DataServiceCacheUpdatedEvent,\n DataServiceGranularCacheUpdatedEvent,\n DataServiceInvalidateQueriesAction,\n} from '@metamask/base-data-service';\nimport { HttpError } from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\nimport {\n array,\n boolean,\n enums,\n intersection,\n nullable,\n optional,\n sensitive,\n string,\n type as structType,\n} from '@metamask/superstruct';\nimport type { Infer } from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { CaipAccountIdStruct } from '@metamask/utils';\n\nimport type { ProfileServiceMethodActions } from './ProfileService-method-action-types.js';\n\nexport const serviceName = 'ProfileService';\n\n// ---------------------------------------------------------------------------\n// Error messages\n// ---------------------------------------------------------------------------\n\n/** Human-readable error messages for each ProfileService operation. */\nexport const ProfileServiceErrorMessage = {\n GET_PROFILE_FAILED: 'ProfileService: failed to fetch profile',\n CREATE_PROFILE_FAILED: 'ProfileService: failed to create profile',\n REPLACE_PROFILE_FAILED: 'ProfileService: failed to replace profile',\n UPDATE_PROFILE_FAILED: 'ProfileService: failed to update profile',\n DELETE_PROFILE_FAILED: 'ProfileService: failed to delete profile',\n CHECK_USERNAME_AVAILABILITY_FAILED:\n 'ProfileService: failed to check username availability',\n GET_X_AUTH_URL_FAILED: 'ProfileService: failed to get X authentication URL',\n CONNECT_X_FAILED: 'ProfileService: failed to connect X account',\n GET_X_ACCOUNT_FAILED: 'ProfileService: failed to get X account',\n DISCONNECT_X_FAILED: 'ProfileService: failed to disconnect X account',\n} as const;\n\n// ---------------------------------------------------------------------------\n// Superstruct schemas\n// ---------------------------------------------------------------------------\n\nconst TradingPrivacyStruct = enums(['public', 'private'] as const);\n\nconst ProfileApiResponseStruct = structType({\n profile_id: string(),\n username: string(),\n display_name: string(),\n bio: nullable(string()),\n linked_addresses: array(CaipAccountIdStruct),\n avatar_url: nullable(string()),\n trading_privacy: TradingPrivacyStruct,\n connected_to_x: boolean(),\n created_at: string(),\n updated_at: string(),\n});\n\nconst UsernameAvailabilityErrorStruct = structType({\n code: string(),\n message: string(),\n});\n\nconst UsernameAvailabilityResponseStruct = structType({\n username: string(),\n available: boolean(),\n valid: boolean(),\n normalized: string(),\n errors: array(UsernameAvailabilityErrorStruct),\n});\n\nconst XAuthUrlResponseStruct = structType({\n url: sensitive(string()),\n state: sensitive(string()),\n});\n\nconst ConnectXResponseStruct = structType({\n x_user_id: string(),\n x_profile_url: string(),\n username: string(),\n display_name: string(),\n avatar_url: string(),\n created_at: string(),\n updated_at: string(),\n});\n\nconst CreateProfileResponseStruct = intersection([\n ProfileApiResponseStruct,\n structType({ x_profile: optional(ConnectXResponseStruct) }),\n]);\n\nconst ConnectXParamsStruct = structType({\n code: sensitive(string()),\n state: sensitive(string()),\n});\n\nconst CreateProfileParamsStruct = structType({\n profile_id: string(),\n username: string(),\n display_name: string(),\n bio: optional(nullable(string())),\n linked_addresses: array(CaipAccountIdStruct),\n avatar_url: optional(string()),\n trading_privacy: TradingPrivacyStruct,\n});\n\nconst ReplaceProfileParamsStruct = structType({\n username: string(),\n display_name: string(),\n bio: optional(nullable(string())),\n linked_addresses: array(CaipAccountIdStruct),\n avatar_url: optional(string()),\n trading_privacy: TradingPrivacyStruct,\n});\n\nconst UpdateProfileParamsStruct = structType({\n username: optional(string()),\n display_name: optional(string()),\n bio: optional(nullable(string())),\n linked_addresses: optional(array(CaipAccountIdStruct)),\n avatar_url: optional(string()),\n trading_privacy: optional(TradingPrivacyStruct),\n});\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'getProfile',\n 'createProfile',\n 'replaceProfile',\n 'updateProfile',\n 'deleteProfile',\n 'checkUsernameAvailability',\n 'getXAuthUrl',\n 'connectX',\n 'getXAccount',\n 'disconnectX',\n] as const;\n\n/** The shape of a profile returned by the MetaMask Profile API. */\nexport type ProfileApiResponse = Infer<typeof ProfileApiResponseStruct>;\n\n/** The response shape for createProfile — includes an optional linked X profile if the user had already connected X. */\nexport type CreateProfileResponse = Infer<typeof CreateProfileResponseStruct>;\n\n/** The response shape for a username availability check. */\nexport type UsernameAvailabilityResponse = Infer<\n typeof UsernameAvailabilityResponseStruct\n>;\n\n/** The response shape returned when connecting or fetching an X account. */\nexport type ConnectXResponse = Infer<typeof ConnectXResponseStruct>;\n\n/** The response shape returned when requesting the X OAuth authentication URL. */\nexport type XAuthUrlResponse = Infer<typeof XAuthUrlResponseStruct>;\n\n/** Alias for {@link ConnectXResponse} returned when fetching the linked X account. */\nexport type XAccountResponse = ConnectXResponse;\n\n/** Parameters for creating a new MetaMask profile. */\nexport type CreateProfileParams = Infer<typeof CreateProfileParamsStruct>;\n\n/** Parameters for fully replacing an existing MetaMask profile (PUT). */\nexport type ReplaceProfileParams = Infer<typeof ReplaceProfileParamsStruct>;\n\n/** Parameters for partially updating an existing MetaMask profile (PATCH). */\nexport type UpdateProfileParams = Infer<typeof UpdateProfileParamsStruct>;\n\n/** Parameters for completing the X OAuth PKCE flow. */\nexport type ConnectXParams = Infer<typeof ConnectXParamsStruct>;\n\n// ---------------------------------------------------------------------------\n// Messenger types\n// ---------------------------------------------------------------------------\n\n/** Union of all actions exposed by ProfileService, including cache invalidation. */\nexport type ProfileServiceActions =\n | ProfileServiceMethodActions\n | DataServiceInvalidateQueriesAction<typeof serviceName>;\n\n/** Event emitted when the ProfileService query cache is updated. */\nexport type ProfileServiceCacheUpdatedEvent = DataServiceCacheUpdatedEvent<\n typeof serviceName\n>;\n\n/** Event emitted with per-query granularity when the ProfileService cache is updated. */\nexport type ProfileServiceGranularCacheUpdatedEvent =\n DataServiceGranularCacheUpdatedEvent<typeof serviceName>;\n\n/** Union of all events emitted by ProfileService. */\nexport type ProfileServiceEvents =\n | ProfileServiceCacheUpdatedEvent\n | ProfileServiceGranularCacheUpdatedEvent;\n\ntype AllowedActions =\n AuthenticationController.AuthenticationControllerGetBearerTokenAction;\n\ntype AllowedEvents = never;\n\n/** Messenger type for ProfileService, scoped to its actions and events. */\nexport type ProfileServiceMessenger = Messenger<\n typeof serviceName,\n ProfileServiceActions | AllowedActions,\n ProfileServiceEvents | AllowedEvents\n>;\n\n// ---------------------------------------------------------------------------\n// Service\n// ---------------------------------------------------------------------------\n\n/** Communicates with the MetaMask Profile API and exposes all operations via the messenger. */\nexport class ProfileService extends BaseDataService<\n typeof serviceName,\n ProfileServiceMessenger\n> {\n readonly #baseUrl: string;\n\n get #v1Url(): string {\n return `${this.#baseUrl}/v1`;\n }\n\n /**\n * Creates a new ProfileService instance.\n *\n * @param options - Constructor options.\n * @param options.messenger - The messenger scoped to ProfileService.\n * @param options.baseUrl - Base URL for the MetaMask Profile API.\n * @param options.policyOptions - Optional service policy configuration.\n */\n constructor({\n messenger,\n baseUrl,\n policyOptions,\n }: {\n messenger: ProfileServiceMessenger;\n baseUrl: string;\n policyOptions?: CreateServicePolicyOptions;\n }) {\n super({ name: serviceName, messenger, policyOptions });\n this.#baseUrl = baseUrl;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Gets the authentication headers for the request.\n *\n * @returns The authentication headers.\n */\n async #getAuthHeaders(): Promise<Record<string, string>> {\n const token = await this.messenger.call(\n 'AuthenticationController:getBearerToken',\n );\n return { Authorization: `Bearer ${token}` };\n }\n\n /**\n * Executes an authenticated HTTP request and returns the parsed JSON response.\n *\n * @param endpoint - The path relative to the v1 base URL.\n * @param options - Request options.\n * @param options.method - The HTTP method. Defaults to 'GET'.\n * @param options.error - The error message to use if the response is not OK.\n * @param options.json - Optional JSON body. If provided, sets Content-Type and serializes as body.\n * @returns The parsed JSON response.\n * @throws {HttpError} If the response is not a 2xx status code.\n */\n async #fetch(\n endpoint: string,\n options: { method: 'DELETE'; error: string },\n ): Promise<null>;\n\n async #fetch<ResponseType extends Json>(\n endpoint: string,\n options: {\n method?: string;\n error: string;\n json?: unknown;\n searchParams?: Record<string, string>;\n },\n ): Promise<ResponseType>;\n\n async #fetch<ResponseType extends Json>(\n endpoint: string,\n {\n method = 'GET',\n error,\n json,\n searchParams,\n }: {\n method?: string;\n error: string;\n json?: unknown;\n searchParams?: Record<string, string>;\n },\n ): Promise<ResponseType | null> {\n const authHeaders = await this.#getAuthHeaders();\n const url = new URL(`${this.#v1Url}/${endpoint}`);\n if (searchParams) {\n for (const [key, value] of Object.entries(searchParams)) {\n url.searchParams.append(key, value);\n }\n }\n const response = await fetch(url.toString(), {\n ...(method === 'GET' ? {} : { method }),\n headers: {\n ...authHeaders,\n ...(json === undefined ? {} : { 'Content-Type': 'application/json' }),\n },\n ...(json === undefined ? {} : { body: JSON.stringify(json) }),\n });\n if (!response.ok) {\n throw new HttpError(response.status, `${error}: ${response.status}`);\n }\n if (method === 'DELETE') {\n return null;\n }\n return (await response.json()) as ResponseType;\n }\n\n /**\n * Fetches a profile by its identifier.\n *\n * @param profileId - The profile identifier to fetch.\n * @returns The profile data from the API.\n * @throws {HttpError} If the API returns a non-2xx response.\n * @throws {StructError} If the response does not match the expected shape.\n */\n async getProfile(profileId: string): Promise<ProfileApiResponse> {\n return this.fetchQuery({\n queryKey: [`${this.name}:getProfile`, profileId],\n responseStruct: ProfileApiResponseStruct,\n queryFn: async () =>\n this.#fetch<ProfileApiResponse>(\n `profiles/${encodeURIComponent(profileId)}`,\n {\n error: ProfileServiceErrorMessage.GET_PROFILE_FAILED,\n },\n ),\n });\n }\n\n /**\n * Creates a new MetaMask profile.\n *\n * @param params - The profile creation parameters.\n * @returns The created profile data.\n * @throws {HttpError} If the API returns a non-2xx response.\n * @throws {StructError} If the response do not match the expected shape.\n */\n async createProfile(\n params: CreateProfileParams,\n ): Promise<CreateProfileResponse> {\n return this.executeMutation({\n mutationKey: [`${this.name}:createProfile`],\n responseStruct: CreateProfileResponseStruct,\n mutationFn: async () =>\n this.#fetch<CreateProfileResponse>('profiles', {\n method: 'POST',\n error: ProfileServiceErrorMessage.CREATE_PROFILE_FAILED,\n json: params,\n }),\n });\n }\n\n /**\n * Fully replaces an existing profile (PUT).\n *\n * @param profileId - The identifier of the profile to replace.\n * @param params - The replacement profile data.\n * @returns The updated profile data.\n * @throws {HttpError} If the API returns a non-2xx response.\n * @throws {StructError} If the response do not match the expected shape.\n */\n async replaceProfile(\n profileId: string,\n params: ReplaceProfileParams,\n ): Promise<ProfileApiResponse> {\n return this.executeMutation({\n mutationKey: [`${this.name}:replaceProfile`, profileId],\n responseStruct: ProfileApiResponseStruct,\n mutationFn: async () =>\n this.#fetch<ProfileApiResponse>(\n `profiles/${encodeURIComponent(profileId)}`,\n {\n method: 'PUT',\n error: ProfileServiceErrorMessage.REPLACE_PROFILE_FAILED,\n json: params,\n },\n ),\n });\n }\n\n /**\n * Partially updates an existing profile (PATCH).\n *\n * @param profileId - The identifier of the profile to update.\n * @param params - The fields to update.\n * @returns The updated profile data.\n * @throws {HttpError} If the API returns a non-2xx response.\n * @throws {StructError} If the response do not match the expected shape.\n */\n async updateProfile(\n profileId: string,\n params: UpdateProfileParams,\n ): Promise<ProfileApiResponse> {\n return this.executeMutation({\n mutationKey: [`${this.name}:updateProfile`, profileId],\n responseStruct: ProfileApiResponseStruct,\n mutationFn: async () =>\n this.#fetch<ProfileApiResponse>(\n `profiles/${encodeURIComponent(profileId)}`,\n {\n method: 'PATCH',\n error: ProfileServiceErrorMessage.UPDATE_PROFILE_FAILED,\n json: params,\n },\n ),\n });\n }\n\n /**\n * Deletes a profile by its identifier.\n *\n * @param profileId - The identifier of the profile to delete.\n * @returns The result of the mutation.\n * @throws {HttpError} If the API returns a non-2xx response.\n */\n async deleteProfile(profileId: string): Promise<void> {\n return this.executeMutation({\n mutationKey: [`${this.name}:deleteProfile`, profileId],\n mutationFn: async () =>\n this.#fetch(`profiles/${encodeURIComponent(profileId)}`, {\n method: 'DELETE',\n error: ProfileServiceErrorMessage.DELETE_PROFILE_FAILED,\n }),\n });\n }\n\n /**\n * Checks whether a username is available.\n *\n * @param username - The username to check.\n * @returns Availability details including validity and normalized form.\n * @throws {HttpError} If the API returns a non-2xx response.\n * @throws {StructError} If the response does not match the expected shape.\n */\n async checkUsernameAvailability(\n username: string,\n ): Promise<UsernameAvailabilityResponse> {\n return this.fetchQuery({\n queryKey: [`${this.name}:checkUsernameAvailability`, username],\n staleTime: 0,\n responseStruct: UsernameAvailabilityResponseStruct,\n queryFn: async () =>\n this.#fetch<UsernameAvailabilityResponse>(\n 'profiles/username/availability',\n {\n error:\n ProfileServiceErrorMessage.CHECK_USERNAME_AVAILABILITY_FAILED,\n searchParams: { username },\n },\n ),\n });\n }\n\n /**\n * Fetches the X OAuth PKCE authorization URL and its associated state parameter.\n * The profile is resolved server-side from the verified bearer token.\n *\n * @returns An object containing the authorization URL and the state token.\n * @throws {HttpError} If the API returns a non-2xx response.\n * @throws {StructError} If the response does not match the expected shape.\n */\n async getXAuthUrl(): Promise<XAuthUrlResponse> {\n return this.executeMutation({\n mutationKey: [`${this.name}:getXAuthUrl`],\n responseStruct: XAuthUrlResponseStruct,\n mutationFn: async () =>\n this.#fetch<XAuthUrlResponse>('profiles/x/authentication-url', {\n error: ProfileServiceErrorMessage.GET_X_AUTH_URL_FAILED,\n }),\n });\n }\n\n /**\n * Completes the X OAuth PKCE flow and links the X account to the profile.\n * The profile is resolved server-side from the verified bearer token.\n *\n * @param params - The OAuth callback code and state from the X redirect.\n * @returns The linked X account data.\n * @throws {HttpError} If the API returns a non-2xx response.\n * @throws {StructError} If the response does not match the expected shape.\n */\n async connectX(params: ConnectXParams): Promise<ConnectXResponse> {\n const response = await this.executeMutation({\n mutationKey: [`${this.name}:connectX`],\n responseStruct: ConnectXResponseStruct,\n mutationFn: async () =>\n this.#fetch<ConnectXResponse>('profiles/x/connect', {\n method: 'POST',\n error: ProfileServiceErrorMessage.CONNECT_X_FAILED,\n json: params,\n }),\n });\n // The response does not identify the profile, so drop every cached\n // profile: `connected_to_x` is now out of date.\n await this.invalidateQueries({ queryKey: [`${this.name}:getProfile`] });\n return response;\n }\n\n /**\n * Fetches the X account currently linked to the authenticated profile.\n * The profile is resolved server-side from the verified bearer token.\n *\n * @returns The linked X account data.\n * @throws {HttpError} If the API returns a non-2xx response.\n * @throws {StructError} If the response does not match the expected shape.\n */\n async getXAccount(): Promise<XAccountResponse> {\n return this.fetchQuery({\n queryKey: [`${this.name}:getXAccount`],\n staleTime: 0,\n responseStruct: ConnectXResponseStruct,\n queryFn: async () =>\n this.#fetch<ConnectXResponse>('profiles/x/account', {\n error: ProfileServiceErrorMessage.GET_X_ACCOUNT_FAILED,\n }),\n });\n }\n\n /**\n * Disconnects the X account linked to the given profile.\n * A `404` response is treated as success (the X account is already\n * disconnected, or the profile is unknown), making the operation idempotent.\n *\n * @param profileId - The ID of the profile to disconnect the linked X account from.\n * @returns The result of the mutation.\n * @throws {HttpError} If the API returns a non-2xx response other than `404`.\n */\n async disconnectX(profileId: string): Promise<void> {\n await this.executeMutation({\n mutationKey: [`${this.name}:disconnectX`, profileId],\n mutationFn: async () => {\n try {\n return await this.#fetch(\n `profiles/${encodeURIComponent(profileId)}/x`,\n {\n method: 'DELETE',\n error: ProfileServiceErrorMessage.DISCONNECT_X_FAILED,\n },\n );\n } catch (error) {\n if (error instanceof HttpError && error.httpStatus === 404) {\n return null;\n }\n throw error;\n }\n },\n });\n // The cached profile no longer reflects `connected_to_x`.\n await this.invalidateQueries({\n queryKey: [`${this.name}:getProfile`, profileId],\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ProfileService.js","sourceRoot":"","sources":["../src/ProfileService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAO9D,OAAO,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAC;AAGvD,OAAO,EACL,KAAK,EACL,OAAO,EACP,KAAK,EACL,YAAY,EACZ,QAAQ,EACR,QAAQ,EACR,SAAS,EACT,MAAM,EACN,IAAI,IAAI,UAAU,GACnB,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAItD,MAAM,CAAC,MAAM,WAAW,GAAG,gBAAgB,CAAC;AAE5C,8EAA8E;AAC9E,iBAAiB;AACjB,8EAA8E;AAE9E,uEAAuE;AACvE,MAAM,CAAC,MAAM,0BAA0B,GAAG;IACxC,kBAAkB,EAAE,yCAAyC;IAC7D,qBAAqB,EAAE,0CAA0C;IACjE,sBAAsB,EAAE,2CAA2C;IACnE,qBAAqB,EAAE,0CAA0C;IACjE,qBAAqB,EAAE,0CAA0C;IACjE,kCAAkC,EAChC,uDAAuD;IACzD,qBAAqB,EAAE,oDAAoD;IAC3E,gBAAgB,EAAE,6CAA6C;IAC/D,oBAAoB,EAAE,yCAAyC;IAC/D,mBAAmB,EAAE,gDAAgD;CAC7D,CAAC;AAEX,8EAA8E;AAC9E,sBAAsB;AACtB,8EAA8E;AAE9E,MAAM,oBAAoB,GAAG,KAAK,CAAC,CAAC,QAAQ,EAAE,SAAS,CAAU,CAAC,CAAC;AAEnE,MAAM,wBAAwB,GAAG,UAAU,CAAC;IAC1C,UAAU,EAAE,MAAM,EAAE;IACpB,QAAQ,EAAE,MAAM,EAAE;IAClB,YAAY,EAAE,MAAM,EAAE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AE,QAAQ;wBAChB,KAAK,EAAE,0BAA0B,CAAC,mBAAmB;qBACtD,CACF,CAAC;gBACJ,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBACf,IAAI,KAAK,YAAY,SAAS,IAAI,KAAK,CAAC,UAAU,KAAK,GAAG,EAAE,CAAC;wBAC3D,OAAO,IAAI,CAAC;oBACd,CAAC;oBACD,MAAM,KAAK,CAAC;gBACd,CAAC;YACH,CAAC;SACF,CAAC,CAAC;QACH,0DAA0D;QAC1D,MAAM,IAAI,CAAC,iBAAiB,CAAC;YAC3B,QAAQ,EAAE,CAAC,GAAG,IAAI,CAAC,IAAI,aAAa,EAAE,SAAS,CAAC;SACjD,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { BaseDataService } from '@metamask/base-data-service';\nimport type {\n CreateServicePolicyOptions,\n DataServiceCacheUpdatedEvent,\n DataServiceGranularCacheUpdatedEvent,\n DataServiceInvalidateQueriesAction,\n} from '@metamask/base-data-service';\nimport { HttpError } from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\nimport {\n array,\n boolean,\n enums,\n intersection,\n nullable,\n optional,\n sensitive,\n string,\n type as structType,\n} from '@metamask/superstruct';\nimport type { Infer } from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { CaipAccountIdStruct } from '@metamask/utils';\n\nimport type { ProfileServiceMethodActions } from './ProfileService-method-action-types.js';\n\nexport const serviceName = 'ProfileService';\n\n// ---------------------------------------------------------------------------\n// Error messages\n// ---------------------------------------------------------------------------\n\n/** Human-readable error messages for each ProfileService operation. */\nexport const ProfileServiceErrorMessage = {\n GET_PROFILE_FAILED: 'ProfileService: failed to fetch profile',\n CREATE_PROFILE_FAILED: 'ProfileService: failed to create profile',\n REPLACE_PROFILE_FAILED: 'ProfileService: failed to replace profile',\n UPDATE_PROFILE_FAILED: 'ProfileService: failed to update profile',\n DELETE_PROFILE_FAILED: 'ProfileService: failed to delete profile',\n CHECK_USERNAME_AVAILABILITY_FAILED:\n 'ProfileService: failed to check username availability',\n GET_X_AUTH_URL_FAILED: 'ProfileService: failed to get X authentication URL',\n CONNECT_X_FAILED: 'ProfileService: failed to connect X account',\n GET_X_ACCOUNT_FAILED: 'ProfileService: failed to get X account',\n DISCONNECT_X_FAILED: 'ProfileService: failed to disconnect X account',\n} as const;\n\n// ---------------------------------------------------------------------------\n// Superstruct schemas\n// ---------------------------------------------------------------------------\n\nconst TradingPrivacyStruct = enums(['public', 'private'] as const);\n\nconst ProfileApiResponseStruct = structType({\n profile_id: string(),\n username: string(),\n display_name: string(),\n bio: nullable(string()),\n linked_addresses: array(CaipAccountIdStruct),\n avatar_url: string(),\n trading_privacy: TradingPrivacyStruct,\n connected_to_x: boolean(),\n created_at: string(),\n updated_at: string(),\n});\n\nconst UsernameAvailabilityErrorStruct = structType({\n code: string(),\n message: string(),\n});\n\nconst UsernameAvailabilityResponseStruct = structType({\n username: string(),\n available: boolean(),\n valid: boolean(),\n normalized: string(),\n errors: array(UsernameAvailabilityErrorStruct),\n});\n\nconst XAuthUrlResponseStruct = structType({\n url: sensitive(string()),\n state: sensitive(string()),\n});\n\nconst ConnectXResponseStruct = structType({\n x_user_id: string(),\n x_profile_url: string(),\n username: string(),\n display_name: string(),\n avatar_url: string(),\n created_at: string(),\n updated_at: string(),\n});\n\nconst CreateProfileResponseStruct = intersection([\n ProfileApiResponseStruct,\n structType({ x_profile: optional(ConnectXResponseStruct) }),\n]);\n\nconst ConnectXParamsStruct = structType({\n code: sensitive(string()),\n state: sensitive(string()),\n});\n\nconst CreateProfileParamsStruct = structType({\n profile_id: string(),\n username: string(),\n display_name: string(),\n bio: optional(nullable(string())),\n linked_addresses: array(CaipAccountIdStruct),\n avatar_url: optional(string()),\n trading_privacy: TradingPrivacyStruct,\n});\n\nconst ReplaceProfileParamsStruct = structType({\n username: string(),\n display_name: string(),\n bio: optional(nullable(string())),\n linked_addresses: array(CaipAccountIdStruct),\n avatar_url: optional(string()),\n trading_privacy: TradingPrivacyStruct,\n});\n\nconst UpdateProfileParamsStruct = structType({\n username: optional(string()),\n display_name: optional(string()),\n bio: optional(nullable(string())),\n linked_addresses: optional(array(CaipAccountIdStruct)),\n avatar_url: optional(string()),\n trading_privacy: optional(TradingPrivacyStruct),\n});\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'getProfile',\n 'createProfile',\n 'replaceProfile',\n 'updateProfile',\n 'deleteProfile',\n 'checkUsernameAvailability',\n 'getXAuthUrl',\n 'connectX',\n 'getXAccount',\n 'disconnectX',\n] as const;\n\n/** The shape of a profile returned by the MetaMask Profile API. */\nexport type ProfileApiResponse = Infer<typeof ProfileApiResponseStruct>;\n\n/** The response shape for createProfile — includes an optional linked X profile if the user had already connected X. */\nexport type CreateProfileResponse = Infer<typeof CreateProfileResponseStruct>;\n\n/** The response shape for a username availability check. */\nexport type UsernameAvailabilityResponse = Infer<\n typeof UsernameAvailabilityResponseStruct\n>;\n\n/** The response shape returned when connecting or fetching an X account. */\nexport type ConnectXResponse = Infer<typeof ConnectXResponseStruct>;\n\n/** The response shape returned when requesting the X OAuth authentication URL. */\nexport type XAuthUrlResponse = Infer<typeof XAuthUrlResponseStruct>;\n\n/** Alias for {@link ConnectXResponse} returned when fetching the linked X account. */\nexport type XAccountResponse = ConnectXResponse;\n\n/** Parameters for creating a new MetaMask profile. */\nexport type CreateProfileParams = Infer<typeof CreateProfileParamsStruct>;\n\n/** Parameters for fully replacing an existing MetaMask profile (PUT). */\nexport type ReplaceProfileParams = Infer<typeof ReplaceProfileParamsStruct>;\n\n/** Parameters for partially updating an existing MetaMask profile (PATCH). */\nexport type UpdateProfileParams = Infer<typeof UpdateProfileParamsStruct>;\n\n/** Parameters for completing the X OAuth PKCE flow. */\nexport type ConnectXParams = Infer<typeof ConnectXParamsStruct>;\n\n// ---------------------------------------------------------------------------\n// Messenger types\n// ---------------------------------------------------------------------------\n\n/** Union of all actions exposed by ProfileService, including cache invalidation. */\nexport type ProfileServiceActions =\n | ProfileServiceMethodActions\n | DataServiceInvalidateQueriesAction<typeof serviceName>;\n\n/** Event emitted when the ProfileService query cache is updated. */\nexport type ProfileServiceCacheUpdatedEvent = DataServiceCacheUpdatedEvent<\n typeof serviceName\n>;\n\n/** Event emitted with per-query granularity when the ProfileService cache is updated. */\nexport type ProfileServiceGranularCacheUpdatedEvent =\n DataServiceGranularCacheUpdatedEvent<typeof serviceName>;\n\n/** Union of all events emitted by ProfileService. */\nexport type ProfileServiceEvents =\n | ProfileServiceCacheUpdatedEvent\n | ProfileServiceGranularCacheUpdatedEvent;\n\ntype AllowedActions =\n AuthenticationController.AuthenticationControllerGetBearerTokenAction;\n\ntype AllowedEvents = never;\n\n/** Messenger type for ProfileService, scoped to its actions and events. */\nexport type ProfileServiceMessenger = Messenger<\n typeof serviceName,\n ProfileServiceActions | AllowedActions,\n ProfileServiceEvents | AllowedEvents\n>;\n\n// ---------------------------------------------------------------------------\n// Service\n// ---------------------------------------------------------------------------\n\n/** Communicates with the MetaMask Profile API and exposes all operations via the messenger. */\nexport class ProfileService extends BaseDataService<\n typeof serviceName,\n ProfileServiceMessenger\n> {\n readonly #baseUrl: string;\n\n get #v1Url(): string {\n return `${this.#baseUrl}/v1`;\n }\n\n /**\n * Creates a new ProfileService instance.\n *\n * @param options - Constructor options.\n * @param options.messenger - The messenger scoped to ProfileService.\n * @param options.baseUrl - Base URL for the MetaMask Profile API.\n * @param options.policyOptions - Optional service policy configuration.\n */\n constructor({\n messenger,\n baseUrl,\n policyOptions,\n }: {\n messenger: ProfileServiceMessenger;\n baseUrl: string;\n policyOptions?: CreateServicePolicyOptions;\n }) {\n super({ name: serviceName, messenger, policyOptions });\n this.#baseUrl = baseUrl;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Gets the authentication headers for the request.\n *\n * @returns The authentication headers.\n */\n async #getAuthHeaders(): Promise<Record<string, string>> {\n const token = await this.messenger.call(\n 'AuthenticationController:getBearerToken',\n );\n return { Authorization: `Bearer ${token}` };\n }\n\n /**\n * Executes an authenticated HTTP request and returns the parsed JSON response.\n *\n * @param endpoint - The path relative to the v1 base URL.\n * @param options - Request options.\n * @param options.method - The HTTP method. Defaults to 'GET'.\n * @param options.error - The error message to use if the response is not OK.\n * @param options.json - Optional JSON body. If provided, sets Content-Type and serializes as body.\n * @returns The parsed JSON response.\n * @throws {HttpError} If the response is not a 2xx status code.\n */\n async #fetch(\n endpoint: string,\n options: { method: 'DELETE'; error: string },\n ): Promise<null>;\n\n async #fetch<ResponseType extends Json>(\n endpoint: string,\n options: {\n method?: string;\n error: string;\n json?: unknown;\n searchParams?: Record<string, string>;\n },\n ): Promise<ResponseType>;\n\n async #fetch<ResponseType extends Json>(\n endpoint: string,\n {\n method = 'GET',\n error,\n json,\n searchParams,\n }: {\n method?: string;\n error: string;\n json?: unknown;\n searchParams?: Record<string, string>;\n },\n ): Promise<ResponseType | null> {\n const authHeaders = await this.#getAuthHeaders();\n const url = new URL(`${this.#v1Url}/${endpoint}`);\n if (searchParams) {\n for (const [key, value] of Object.entries(searchParams)) {\n url.searchParams.append(key, value);\n }\n }\n const response = await fetch(url.toString(), {\n ...(method === 'GET' ? {} : { method }),\n headers: {\n ...authHeaders,\n ...(json === undefined ? {} : { 'Content-Type': 'application/json' }),\n },\n ...(json === undefined ? {} : { body: JSON.stringify(json) }),\n });\n if (!response.ok) {\n throw new HttpError(response.status, `${error}: ${response.status}`);\n }\n if (method === 'DELETE') {\n return null;\n }\n return (await response.json()) as ResponseType;\n }\n\n /**\n * Fetches a profile by its identifier.\n *\n * @param profileId - The profile identifier to fetch.\n * @returns The profile data from the API.\n * @throws {HttpError} If the API returns a non-2xx response.\n * @throws {StructError} If the response does not match the expected shape.\n */\n async getProfile(profileId: string): Promise<ProfileApiResponse> {\n return this.fetchQuery({\n queryKey: [`${this.name}:getProfile`, profileId],\n responseStruct: ProfileApiResponseStruct,\n queryFn: async () =>\n this.#fetch<ProfileApiResponse>(\n `profiles/${encodeURIComponent(profileId)}`,\n {\n error: ProfileServiceErrorMessage.GET_PROFILE_FAILED,\n },\n ),\n });\n }\n\n /**\n * Creates a new MetaMask profile.\n *\n * @param params - The profile creation parameters.\n * @returns The created profile data.\n * @throws {HttpError} If the API returns a non-2xx response.\n * @throws {StructError} If the response do not match the expected shape.\n */\n async createProfile(\n params: CreateProfileParams,\n ): Promise<CreateProfileResponse> {\n return this.executeMutation({\n mutationKey: [`${this.name}:createProfile`],\n responseStruct: CreateProfileResponseStruct,\n mutationFn: async () =>\n this.#fetch<CreateProfileResponse>('profiles', {\n method: 'POST',\n error: ProfileServiceErrorMessage.CREATE_PROFILE_FAILED,\n json: params,\n }),\n });\n }\n\n /**\n * Fully replaces an existing profile (PUT).\n *\n * @param profileId - The identifier of the profile to replace.\n * @param params - The replacement profile data.\n * @returns The updated profile data.\n * @throws {HttpError} If the API returns a non-2xx response.\n * @throws {StructError} If the response do not match the expected shape.\n */\n async replaceProfile(\n profileId: string,\n params: ReplaceProfileParams,\n ): Promise<ProfileApiResponse> {\n return this.executeMutation({\n mutationKey: [`${this.name}:replaceProfile`, profileId],\n responseStruct: ProfileApiResponseStruct,\n mutationFn: async () =>\n this.#fetch<ProfileApiResponse>(\n `profiles/${encodeURIComponent(profileId)}`,\n {\n method: 'PUT',\n error: ProfileServiceErrorMessage.REPLACE_PROFILE_FAILED,\n json: params,\n },\n ),\n });\n }\n\n /**\n * Partially updates an existing profile (PATCH).\n *\n * @param profileId - The identifier of the profile to update.\n * @param params - The fields to update.\n * @returns The updated profile data.\n * @throws {HttpError} If the API returns a non-2xx response.\n * @throws {StructError} If the response do not match the expected shape.\n */\n async updateProfile(\n profileId: string,\n params: UpdateProfileParams,\n ): Promise<ProfileApiResponse> {\n return this.executeMutation({\n mutationKey: [`${this.name}:updateProfile`, profileId],\n responseStruct: ProfileApiResponseStruct,\n mutationFn: async () =>\n this.#fetch<ProfileApiResponse>(\n `profiles/${encodeURIComponent(profileId)}`,\n {\n method: 'PATCH',\n error: ProfileServiceErrorMessage.UPDATE_PROFILE_FAILED,\n json: params,\n },\n ),\n });\n }\n\n /**\n * Deletes a profile by its identifier.\n *\n * @param profileId - The identifier of the profile to delete.\n * @returns The result of the mutation.\n * @throws {HttpError} If the API returns a non-2xx response.\n */\n async deleteProfile(profileId: string): Promise<void> {\n return this.executeMutation({\n mutationKey: [`${this.name}:deleteProfile`, profileId],\n mutationFn: async () =>\n this.#fetch(`profiles/${encodeURIComponent(profileId)}`, {\n method: 'DELETE',\n error: ProfileServiceErrorMessage.DELETE_PROFILE_FAILED,\n }),\n });\n }\n\n /**\n * Checks whether a username is available.\n *\n * @param username - The username to check.\n * @returns Availability details including validity and normalized form.\n * @throws {HttpError} If the API returns a non-2xx response.\n * @throws {StructError} If the response does not match the expected shape.\n */\n async checkUsernameAvailability(\n username: string,\n ): Promise<UsernameAvailabilityResponse> {\n return this.fetchQuery({\n queryKey: [`${this.name}:checkUsernameAvailability`, username],\n staleTime: 0,\n responseStruct: UsernameAvailabilityResponseStruct,\n queryFn: async () =>\n this.#fetch<UsernameAvailabilityResponse>(\n 'profiles/username/availability',\n {\n error:\n ProfileServiceErrorMessage.CHECK_USERNAME_AVAILABILITY_FAILED,\n searchParams: { username },\n },\n ),\n });\n }\n\n /**\n * Fetches the X OAuth PKCE authorization URL and its associated state parameter.\n * The profile is resolved server-side from the verified bearer token.\n *\n * @returns An object containing the authorization URL and the state token.\n * @throws {HttpError} If the API returns a non-2xx response.\n * @throws {StructError} If the response does not match the expected shape.\n */\n async getXAuthUrl(): Promise<XAuthUrlResponse> {\n return this.executeMutation({\n mutationKey: [`${this.name}:getXAuthUrl`],\n responseStruct: XAuthUrlResponseStruct,\n mutationFn: async () =>\n this.#fetch<XAuthUrlResponse>('profiles/x/authentication-url', {\n error: ProfileServiceErrorMessage.GET_X_AUTH_URL_FAILED,\n }),\n });\n }\n\n /**\n * Completes the X OAuth PKCE flow and links the X account to the profile.\n * The profile is resolved server-side from the verified bearer token.\n *\n * @param params - The OAuth callback code and state from the X redirect.\n * @returns The linked X account data.\n * @throws {HttpError} If the API returns a non-2xx response.\n * @throws {StructError} If the response does not match the expected shape.\n */\n async connectX(params: ConnectXParams): Promise<ConnectXResponse> {\n const response = await this.executeMutation({\n mutationKey: [`${this.name}:connectX`],\n responseStruct: ConnectXResponseStruct,\n mutationFn: async () =>\n this.#fetch<ConnectXResponse>('profiles/x/connect', {\n method: 'POST',\n error: ProfileServiceErrorMessage.CONNECT_X_FAILED,\n json: params,\n }),\n });\n // The response does not identify the profile, so drop every cached\n // profile: `connected_to_x` is now out of date.\n await this.invalidateQueries({ queryKey: [`${this.name}:getProfile`] });\n return response;\n }\n\n /**\n * Fetches the X account currently linked to the authenticated profile.\n * The profile is resolved server-side from the verified bearer token.\n *\n * @returns The linked X account data.\n * @throws {HttpError} If the API returns a non-2xx response.\n * @throws {StructError} If the response does not match the expected shape.\n */\n async getXAccount(): Promise<XAccountResponse> {\n return this.fetchQuery({\n queryKey: [`${this.name}:getXAccount`],\n staleTime: 0,\n responseStruct: ConnectXResponseStruct,\n queryFn: async () =>\n this.#fetch<ConnectXResponse>('profiles/x/account', {\n error: ProfileServiceErrorMessage.GET_X_ACCOUNT_FAILED,\n }),\n });\n }\n\n /**\n * Disconnects the X account linked to the given profile.\n * A `404` response is treated as success (the X account is already\n * disconnected, or the profile is unknown), making the operation idempotent.\n *\n * @param profileId - The ID of the profile to disconnect the linked X account from.\n * @returns The result of the mutation.\n * @throws {HttpError} If the API returns a non-2xx response other than `404`.\n */\n async disconnectX(profileId: string): Promise<void> {\n await this.executeMutation({\n mutationKey: [`${this.name}:disconnectX`, profileId],\n mutationFn: async () => {\n try {\n return await this.#fetch(\n `profiles/${encodeURIComponent(profileId)}/x`,\n {\n method: 'DELETE',\n error: ProfileServiceErrorMessage.DISCONNECT_X_FAILED,\n },\n );\n } catch (error) {\n if (error instanceof HttpError && error.httpStatus === 404) {\n return null;\n }\n throw error;\n }\n },\n });\n // The cached profile no longer reflects `connected_to_x`.\n await this.invalidateQueries({\n queryKey: [`${this.name}:getProfile`, profileId],\n });\n }\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export type { Profile, XProfile, ConnectXSession, ProfileControllerState, ProfileControllerGetStateAction, ProfileControllerActions, ProfileControllerChangeEvent, ProfileControllerEvents, ProfileControllerMessenger, } from './ProfileController.js';
|
|
2
2
|
export { ProfileController, getDefaultProfileControllerState, } from './ProfileController.js';
|
|
3
|
-
export type { ProfileControllerCheckUsernameAvailabilityAction, ProfileControllerConnectXAction, ProfileControllerCreateProfileAction, ProfileControllerDeleteProfileAction, ProfileControllerDisconnectXAction, ProfileControllerGetProfileAction, ProfileControllerFetchAndUpdateXAccountAction, ProfileControllerGetXProfileAction, ProfileControllerReplaceProfileAction, ProfileControllerGetXAuthorizationUrlAction, ProfileControllerUpdateProfileAction, } from './ProfileController-method-action-types.js';
|
|
3
|
+
export type { ProfileControllerCheckUsernameAvailabilityAction, ProfileControllerConnectXAction, ProfileControllerCreateProfileAction, ProfileControllerDeleteProfileAction, ProfileControllerDisconnectXAction, ProfileControllerGetProfileAction, ProfileControllerFetchAndUpdateXAccountAction, ProfileControllerFetchAndUpdateProfileAction, ProfileControllerGetXProfileAction, ProfileControllerReplaceProfileAction, ProfileControllerGetXAuthorizationUrlAction, ProfileControllerUpdateProfileAction, } from './ProfileController-method-action-types.js';
|
|
4
4
|
export type { ProfileApiResponse, CreateProfileResponse, CreateProfileParams, ReplaceProfileParams, UpdateProfileParams, ConnectXParams, UsernameAvailabilityResponse, XAuthUrlResponse, ConnectXResponse, XAccountResponse, ProfileServiceActions, ProfileServiceEvents, ProfileServiceMessenger, } from './ProfileService.js';
|
|
5
5
|
export { ProfileService, ProfileServiceErrorMessage, } from './ProfileService.js';
|
|
6
6
|
export type { MockProfileServiceHandlers } from './ProfileServiceMock.js';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,OAAO,EACP,QAAQ,EACR,eAAe,EACf,sBAAsB,EACtB,+BAA+B,EAC/B,wBAAwB,EACxB,4BAA4B,EAC5B,uBAAuB,EACvB,0BAA0B,GAC3B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,iBAAiB,EACjB,gCAAgC,GACjC,MAAM,wBAAwB,CAAC;AAChC,YAAY,EACV,gDAAgD,EAChD,+BAA+B,EAC/B,oCAAoC,EACpC,oCAAoC,EACpC,kCAAkC,EAClC,iCAAiC,EACjC,6CAA6C,EAC7C,kCAAkC,EAClC,qCAAqC,EACrC,2CAA2C,EAC3C,oCAAoC,GACrC,MAAM,4CAA4C,CAAC;AACpD,YAAY,EACV,kBAAkB,EAClB,qBAAqB,EACrB,mBAAmB,EACnB,oBAAoB,EACpB,mBAAmB,EACnB,cAAc,EACd,4BAA4B,EAC5B,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,qBAAqB,EACrB,oBAAoB,EACpB,uBAAuB,GACxB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,cAAc,EACd,0BAA0B,GAC3B,MAAM,qBAAqB,CAAC;AAC7B,YAAY,EAAE,0BAA0B,EAAE,MAAM,yBAAyB,CAAC;AAC1E,OAAO,EACL,uBAAuB,EACvB,yBAAyB,EACzB,uBAAuB,EACvB,wBAAwB,GACzB,MAAM,yBAAyB,CAAC;AACjC,YAAY,EACV,6CAA6C,EAC7C,4BAA4B,EAC5B,iCAAiC,EACjC,iCAAiC,EACjC,+BAA+B,EAC/B,8BAA8B,EAC9B,+BAA+B,EAC/B,+BAA+B,EAC/B,kCAAkC,EAClC,iCAAiC,GAClC,MAAM,yCAAyC,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,OAAO,EACP,QAAQ,EACR,eAAe,EACf,sBAAsB,EACtB,+BAA+B,EAC/B,wBAAwB,EACxB,4BAA4B,EAC5B,uBAAuB,EACvB,0BAA0B,GAC3B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,iBAAiB,EACjB,gCAAgC,GACjC,MAAM,wBAAwB,CAAC;AAChC,YAAY,EACV,gDAAgD,EAChD,+BAA+B,EAC/B,oCAAoC,EACpC,oCAAoC,EACpC,kCAAkC,EAClC,iCAAiC,EACjC,6CAA6C,EAC7C,4CAA4C,EAC5C,kCAAkC,EAClC,qCAAqC,EACrC,2CAA2C,EAC3C,oCAAoC,GACrC,MAAM,4CAA4C,CAAC;AACpD,YAAY,EACV,kBAAkB,EAClB,qBAAqB,EACrB,mBAAmB,EACnB,oBAAoB,EACpB,mBAAmB,EACnB,cAAc,EACd,4BAA4B,EAC5B,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,qBAAqB,EACrB,oBAAoB,EACpB,uBAAuB,GACxB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,cAAc,EACd,0BAA0B,GAC3B,MAAM,qBAAqB,CAAC;AAC7B,YAAY,EAAE,0BAA0B,EAAE,MAAM,yBAAyB,CAAC;AAC1E,OAAO,EACL,uBAAuB,EACvB,yBAAyB,EACzB,uBAAuB,EACvB,wBAAwB,GACzB,MAAM,yBAAyB,CAAC;AACjC,YAAY,EACV,6CAA6C,EAC7C,4BAA4B,EAC5B,iCAAiC,EACjC,iCAAiC,EACjC,+BAA+B,EAC/B,8BAA8B,EAC9B,+BAA+B,EAC/B,+BAA+B,EAC/B,kCAAkC,EAClC,iCAAiC,GAClC,MAAM,yCAAyC,CAAC"}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAWA,OAAO,EACL,iBAAiB,EACjB,gCAAgC,GACjC,MAAM,wBAAwB,CAAC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAWA,OAAO,EACL,iBAAiB,EACjB,gCAAgC,GACjC,MAAM,wBAAwB,CAAC;AA8BhC,OAAO,EACL,cAAc,EACd,0BAA0B,GAC3B,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EACL,uBAAuB,EACvB,yBAAyB,EACzB,uBAAuB,EACvB,wBAAwB,GACzB,MAAM,yBAAyB,CAAC","sourcesContent":["export type {\n Profile,\n XProfile,\n ConnectXSession,\n ProfileControllerState,\n ProfileControllerGetStateAction,\n ProfileControllerActions,\n ProfileControllerChangeEvent,\n ProfileControllerEvents,\n ProfileControllerMessenger,\n} from './ProfileController.js';\nexport {\n ProfileController,\n getDefaultProfileControllerState,\n} from './ProfileController.js';\nexport type {\n ProfileControllerCheckUsernameAvailabilityAction,\n ProfileControllerConnectXAction,\n ProfileControllerCreateProfileAction,\n ProfileControllerDeleteProfileAction,\n ProfileControllerDisconnectXAction,\n ProfileControllerGetProfileAction,\n ProfileControllerFetchAndUpdateXAccountAction,\n ProfileControllerFetchAndUpdateProfileAction,\n ProfileControllerGetXProfileAction,\n ProfileControllerReplaceProfileAction,\n ProfileControllerGetXAuthorizationUrlAction,\n ProfileControllerUpdateProfileAction,\n} from './ProfileController-method-action-types.js';\nexport type {\n ProfileApiResponse,\n CreateProfileResponse,\n CreateProfileParams,\n ReplaceProfileParams,\n UpdateProfileParams,\n ConnectXParams,\n UsernameAvailabilityResponse,\n XAuthUrlResponse,\n ConnectXResponse,\n XAccountResponse,\n ProfileServiceActions,\n ProfileServiceEvents,\n ProfileServiceMessenger,\n} from './ProfileService.js';\nexport {\n ProfileService,\n ProfileServiceErrorMessage,\n} from './ProfileService.js';\nexport type { MockProfileServiceHandlers } from './ProfileServiceMock.js';\nexport {\n buildMockProfileService,\n MOCK_PROFILE_API_RESPONSE,\n MOCK_X_CONNECT_RESPONSE,\n MOCK_X_AUTH_URL_RESPONSE,\n} from './ProfileServiceMock.js';\nexport type {\n ProfileServiceCheckUsernameAvailabilityAction,\n ProfileServiceConnectXAction,\n ProfileServiceCreateProfileAction,\n ProfileServiceDeleteProfileAction,\n ProfileServiceDisconnectXAction,\n ProfileServiceGetProfileAction,\n ProfileServiceGetXAccountAction,\n ProfileServiceGetXAuthUrlAction,\n ProfileServiceReplaceProfileAction,\n ProfileServiceUpdateProfileAction,\n} from './ProfileService-method-action-types.js';\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/profile-controller",
|
|
3
|
-
"version": "1.0.1-preview-
|
|
3
|
+
"version": "1.0.1-preview-df8d6c7ea",
|
|
4
4
|
"description": "Controller for managing user profile data including username, bio, avatar, and linked accounts via the MetaMask Profile API",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"Ethereum",
|