@metamask-previews/profile-controller 1.0.0-preview-c2be02bd4 → 1.0.1-preview-3b264bf6d
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 +21 -1
- package/dist/ProfileController-method-action-types.d.ts +43 -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 +58 -7
- package/dist/ProfileController.d.ts.map +1 -1
- package/dist/ProfileController.js +73 -6
- package/dist/ProfileController.js.map +1 -1
- package/dist/ProfileService-method-action-types.d.ts +22 -2
- package/dist/ProfileService-method-action-types.d.ts.map +1 -1
- package/dist/ProfileService-method-action-types.js.map +1 -1
- package/dist/ProfileService.d.ts +41 -3
- package/dist/ProfileService.d.ts.map +1 -1
- package/dist/ProfileService.js +53 -3
- package/dist/ProfileService.js.map +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- Add `startXConnect` method to `ProfileController` for initiating the X OAuth flow. It fetches the authorization URL via `ProfileService:getXAuthUrl`, forwarding an optional CAIP-10 `linkedAddress` (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))
|
|
13
|
+
- Add `disconnectX` method to `ProfileController` for unlinking the X account from a profile. It delegates to `ProfileService:disconnectX`, clears `xProfile` from controller state, and sets `connectedToX` to `false` when the disconnected profile matches the profile in state ([#10668](https://github.com/MetaMask/core/pull/10668))
|
|
14
|
+
- 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))
|
|
15
|
+
|
|
16
|
+
### Changed
|
|
17
|
+
|
|
18
|
+
- **BREAKING**: `ProfileController.connectX` now takes `{ code, state, profileId }`, always fetches the profile from the backend after the connect (the backend auto-creates the profile during X connect when missing), persists both `profile` and `xProfile` in state, and returns `{ profile, xProfile, profileCreated }` instead of just the X profile ([#10668](https://github.com/MetaMask/core/pull/10668))
|
|
19
|
+
- `ProfileService.connectX` response now includes the optional `profile_created` boolean reported by the backend (optional so older backends without the field still validate) ([#10668](https://github.com/MetaMask/core/pull/10668))
|
|
20
|
+
- `ProfileService.getXAuthUrl` now accepts an optional CAIP-10 `linkedAddress` parameter, sent as the `linked_address` query parameter (required by the backend when the profile does not exist yet) ([#10668](https://github.com/MetaMask/core/pull/10668))
|
|
21
|
+
- `ProfileController.connectX` persists `xProfile` in state immediately after a successful connect; if the follow-up profile fetch fails, the X link stays persisted and a clear error is thrown ([#10668](https://github.com/MetaMask/core/pull/10668))
|
|
22
|
+
|
|
23
|
+
## [1.0.1]
|
|
24
|
+
|
|
25
|
+
### Changed
|
|
26
|
+
|
|
27
|
+
- Bump `@metamask/profile-sync-controller` from `^33.0.0` to `^34.0.0` ([#10662](https://github.com/MetaMask/core/pull/10662))
|
|
28
|
+
|
|
10
29
|
## [1.0.0]
|
|
11
30
|
|
|
12
31
|
### Added
|
|
@@ -14,5 +33,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
14
33
|
- Add `ProfileController` for managing user profile state, exposing `getMetaMaskProfile`, `getXprofile`, `createProfile`, `replaceProfile`, `updateProfile`, `deleteProfile`, `checkUsernameAvailability`, `getXAuthUrl`, `connectX`, and `getXAccount` via the messenger ([#10558](https://github.com/MetaMask/core/pull/10558))
|
|
15
34
|
- Add `ProfileService` for communicating with the MetaMask Profile API, exposing `getProfile`, `createProfile`, `replaceProfile`, `updateProfile`, `deleteProfile`, `checkUsernameAvailability`, `getXAuthUrl`, `connectX`, and `getXAccount` via the messenger, with superstruct validation on all inputs and responses ([#10558](https://github.com/MetaMask/core/pull/10558))
|
|
16
35
|
|
|
17
|
-
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/profile-controller@1.0.
|
|
36
|
+
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/profile-controller@1.0.1...HEAD
|
|
37
|
+
[1.0.1]: https://github.com/MetaMask/core/compare/@metamask/profile-controller@1.0.0...@metamask/profile-controller@1.0.1
|
|
18
38
|
[1.0.0]: https://github.com/MetaMask/core/releases/tag/@metamask/profile-controller@1.0.0
|
|
@@ -72,19 +72,32 @@ export type ProfileControllerCheckUsernameAvailabilityAction = {
|
|
|
72
72
|
handler: ProfileController['checkUsernameAvailability'];
|
|
73
73
|
};
|
|
74
74
|
/**
|
|
75
|
-
* Completes the X OAuth
|
|
75
|
+
* Completes the X OAuth flow, updates xProfile and profile in state, and
|
|
76
|
+
* returns the connect result. The backend creates the profile if it does
|
|
77
|
+
* not exist yet (username derived from the X handle), so the profile is
|
|
78
|
+
* always fetched from the backend after a successful connect.
|
|
76
79
|
*
|
|
77
|
-
*
|
|
80
|
+
* The linked X profile is persisted in state immediately after the connect
|
|
81
|
+
* succeeds. If the follow-up profile fetch fails, the X link remains
|
|
82
|
+
* persisted and a clear error is thrown — the profile in state may then be
|
|
83
|
+
* stale until the next successful fetch.
|
|
84
|
+
*
|
|
85
|
+
* @param params - The parameters for the X OAuth flow.
|
|
78
86
|
* @param params.code - The OAuth authorization code from the X redirect.
|
|
79
87
|
* @param params.state - The state parameter returned by the X redirect.
|
|
80
|
-
* @
|
|
88
|
+
* @param params.profileId - The canonical profile ID the X account is
|
|
89
|
+
* linked to (sourced from the auth session).
|
|
90
|
+
* @returns The refreshed profile, the linked X profile, and whether the
|
|
91
|
+
* backend created the profile during the connect.
|
|
81
92
|
*/
|
|
82
93
|
export type ProfileControllerConnectXAction = {
|
|
83
94
|
type: `ProfileController:connectX`;
|
|
84
95
|
handler: ProfileController['connectX'];
|
|
85
96
|
};
|
|
86
97
|
/**
|
|
87
|
-
* Fetches the X account linked to the
|
|
98
|
+
* Fetches the X account linked to the authenticated profile, updates state,
|
|
99
|
+
* and returns the X profile. The profile is resolved server-side from the
|
|
100
|
+
* verified bearer token.
|
|
88
101
|
*
|
|
89
102
|
* @returns The linked X profile.
|
|
90
103
|
*/
|
|
@@ -92,8 +105,33 @@ export type ProfileControllerFetchAndUpdateXAccountAction = {
|
|
|
92
105
|
type: `ProfileController:fetchAndUpdateXAccount`;
|
|
93
106
|
handler: ProfileController['fetchAndUpdateXAccount'];
|
|
94
107
|
};
|
|
108
|
+
/**
|
|
109
|
+
* Initiates the X OAuth flow by fetching the authorization URL from the backend.
|
|
110
|
+
* The profile is resolved server-side from the verified bearer token.
|
|
111
|
+
* Returns session data for the caller to use; nothing is stored in controller state.
|
|
112
|
+
*
|
|
113
|
+
* @param params - Optional parameters for initiating the X OAuth flow.
|
|
114
|
+
* @param params.linkedAddress - Optional CAIP-10 account ID to link to the
|
|
115
|
+
* profile when it does not exist yet.
|
|
116
|
+
* @returns The X authorization URL and state parameter.
|
|
117
|
+
*/
|
|
118
|
+
export type ProfileControllerStartXConnectAction = {
|
|
119
|
+
type: `ProfileController:startXConnect`;
|
|
120
|
+
handler: ProfileController['startXConnect'];
|
|
121
|
+
};
|
|
122
|
+
/**
|
|
123
|
+
* Disconnects the X account linked to the given profile, clears xProfile from
|
|
124
|
+
* state, and marks the profile in state as no longer connected to X.
|
|
125
|
+
*
|
|
126
|
+
* @param profileId - The ID of the profile to disconnect the linked X account
|
|
127
|
+
* from (sourced from {@link getProfile}).
|
|
128
|
+
*/
|
|
129
|
+
export type ProfileControllerDisconnectXAction = {
|
|
130
|
+
type: `ProfileController:disconnectX`;
|
|
131
|
+
handler: ProfileController['disconnectX'];
|
|
132
|
+
};
|
|
95
133
|
/**
|
|
96
134
|
* Union of all ProfileController action types.
|
|
97
135
|
*/
|
|
98
|
-
export type ProfileControllerMethodActions = ProfileControllerGetProfileAction | ProfileControllerGetXProfileAction | ProfileControllerCreateProfileAction | ProfileControllerReplaceProfileAction | ProfileControllerUpdateProfileAction | ProfileControllerDeleteProfileAction | ProfileControllerCheckUsernameAvailabilityAction | ProfileControllerConnectXAction | ProfileControllerFetchAndUpdateXAccountAction;
|
|
136
|
+
export type ProfileControllerMethodActions = ProfileControllerGetProfileAction | ProfileControllerGetXProfileAction | ProfileControllerCreateProfileAction | ProfileControllerReplaceProfileAction | ProfileControllerUpdateProfileAction | ProfileControllerDeleteProfileAction | ProfileControllerCheckUsernameAvailabilityAction | ProfileControllerConnectXAction | ProfileControllerFetchAndUpdateXAccountAction | ProfileControllerStartXConnectAction | ProfileControllerDisconnectXAction;
|
|
99
137
|
//# 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;;;;;;GAMG;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.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;;;;;;GAMG;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,CA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C/B,6CAA6C,GAC7C,oCAAoC,GACpC,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 * If the user had previously connected X, also updates xProfile in state.\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
|
|
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 * If the user had previously connected X, also updates xProfile in state.\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, updates xProfile and profile in state, and\n * returns the connect result. The backend creates the profile if it does\n * not exist yet (username derived from the X handle), so the profile is\n * always fetched from the backend after a successful connect.\n *\n * The linked X profile is persisted in state immediately after the connect\n * succeeds. If the follow-up profile fetch fails, the X link remains\n * persisted and a clear error is thrown — the profile in state may then be\n * stale until the next successful fetch.\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 * @param params.profileId - The canonical profile ID the X account is\n * linked to (sourced from the auth session).\n * @returns The refreshed profile, the linked X profile, and whether the\n * backend created the profile during the connect.\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 * 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 * @param params - Optional parameters for initiating the X OAuth flow.\n * @param params.linkedAddress - Optional CAIP-10 account ID to link to the\n * profile when it does not exist yet.\n * @returns The X authorization URL and state parameter.\n */\nexport type ProfileControllerStartXConnectAction = {\n type: `ProfileController:startXConnect`;\n handler: ProfileController['startXConnect'];\n};\n\n/**\n * Disconnects the X account linked to the given profile, clears xProfile from\n * state, and 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 | ProfileControllerStartXConnectAction\n | ProfileControllerDisconnectXAction;\n"]}
|
|
@@ -3,7 +3,7 @@ import type { ControllerGetStateAction, ControllerStateChangeEvent } from '@meta
|
|
|
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, ProfileServiceGetXAccountAction, 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. */
|
|
@@ -46,6 +46,22 @@ export type XProfile = {
|
|
|
46
46
|
/** The date and time the X profile was updated. */
|
|
47
47
|
updatedAt: string;
|
|
48
48
|
};
|
|
49
|
+
/** Ephemeral session data for initiating the X OAuth flow. Not stored in controller state. */
|
|
50
|
+
export type XConnectSession = {
|
|
51
|
+
/** The X authorization URL to open in a system browser. */
|
|
52
|
+
authorizationUrl: string;
|
|
53
|
+
/** The OAuth state parameter to compare against the X redirect callback. */
|
|
54
|
+
state: string;
|
|
55
|
+
};
|
|
56
|
+
/** Result of completing the X connect flow. */
|
|
57
|
+
export type XConnectResult = {
|
|
58
|
+
/** The MetaMask profile, refreshed from the backend after the connect. */
|
|
59
|
+
profile: Profile;
|
|
60
|
+
/** The linked X profile. */
|
|
61
|
+
xProfile: XProfile;
|
|
62
|
+
/** Whether the backend created the MetaMask profile during the connect. */
|
|
63
|
+
profileCreated: boolean;
|
|
64
|
+
};
|
|
49
65
|
/** State managed by ProfileController. */
|
|
50
66
|
export type ProfileControllerState = {
|
|
51
67
|
profile: Profile;
|
|
@@ -59,7 +75,7 @@ export type ProfileControllerActions = ProfileControllerGetStateAction | Profile
|
|
|
59
75
|
export type ProfileControllerChangeEvent = ControllerStateChangeEvent<typeof controllerName, ProfileControllerState>;
|
|
60
76
|
/** Union of all events emitted by ProfileController. */
|
|
61
77
|
export type ProfileControllerEvents = ProfileControllerChangeEvent;
|
|
62
|
-
type AllowedActions = ProfileServiceCreateProfileAction | ProfileServiceReplaceProfileAction | ProfileServiceUpdateProfileAction | ProfileServiceDeleteProfileAction | ProfileServiceCheckUsernameAvailabilityAction | ProfileServiceConnectXAction | ProfileServiceGetXAccountAction;
|
|
78
|
+
type AllowedActions = ProfileServiceCreateProfileAction | ProfileServiceReplaceProfileAction | ProfileServiceUpdateProfileAction | ProfileServiceDeleteProfileAction | ProfileServiceCheckUsernameAvailabilityAction | ProfileServiceConnectXAction | ProfileServiceGetProfileAction | ProfileServiceGetXAccountAction | ProfileServiceGetXAuthUrlAction | ProfileServiceDisconnectXAction;
|
|
63
79
|
export type AllowedEvents = never;
|
|
64
80
|
/** Messenger type for ProfileController, scoped to its actions, events, and allowed service calls. */
|
|
65
81
|
export type ProfileControllerMessenger = Messenger<typeof controllerName, ProfileControllerActions | AllowedActions, ProfileControllerEvents | AllowedEvents>;
|
|
@@ -131,23 +147,58 @@ export declare class ProfileController extends BaseController<typeof controllerN
|
|
|
131
147
|
*/
|
|
132
148
|
checkUsernameAvailability(username: string): Promise<UsernameAvailabilityResponse>;
|
|
133
149
|
/**
|
|
134
|
-
* Completes the X OAuth
|
|
150
|
+
* Completes the X OAuth flow, updates xProfile and profile in state, and
|
|
151
|
+
* returns the connect result. The backend creates the profile if it does
|
|
152
|
+
* not exist yet (username derived from the X handle), so the profile is
|
|
153
|
+
* always fetched from the backend after a successful connect.
|
|
135
154
|
*
|
|
136
|
-
*
|
|
155
|
+
* The linked X profile is persisted in state immediately after the connect
|
|
156
|
+
* succeeds. If the follow-up profile fetch fails, the X link remains
|
|
157
|
+
* persisted and a clear error is thrown — the profile in state may then be
|
|
158
|
+
* stale until the next successful fetch.
|
|
159
|
+
*
|
|
160
|
+
* @param params - The parameters for the X OAuth flow.
|
|
137
161
|
* @param params.code - The OAuth authorization code from the X redirect.
|
|
138
162
|
* @param params.state - The state parameter returned by the X redirect.
|
|
139
|
-
* @
|
|
163
|
+
* @param params.profileId - The canonical profile ID the X account is
|
|
164
|
+
* linked to (sourced from the auth session).
|
|
165
|
+
* @returns The refreshed profile, the linked X profile, and whether the
|
|
166
|
+
* backend created the profile during the connect.
|
|
140
167
|
*/
|
|
141
168
|
connectX(params: {
|
|
142
169
|
code: string;
|
|
143
170
|
state: string;
|
|
144
|
-
|
|
171
|
+
profileId: string;
|
|
172
|
+
}): Promise<XConnectResult>;
|
|
145
173
|
/**
|
|
146
|
-
* Fetches the X account linked to the
|
|
174
|
+
* Fetches the X account linked to the authenticated profile, updates state,
|
|
175
|
+
* and returns the X profile. The profile is resolved server-side from the
|
|
176
|
+
* verified bearer token.
|
|
147
177
|
*
|
|
148
178
|
* @returns The linked X profile.
|
|
149
179
|
*/
|
|
150
180
|
fetchAndUpdateXAccount(): Promise<XProfile>;
|
|
181
|
+
/**
|
|
182
|
+
* Initiates the X OAuth flow by fetching the authorization URL from the backend.
|
|
183
|
+
* The profile is resolved server-side from the verified bearer token.
|
|
184
|
+
* Returns session data for the caller to use; nothing is stored in controller state.
|
|
185
|
+
*
|
|
186
|
+
* @param params - Optional parameters for initiating the X OAuth flow.
|
|
187
|
+
* @param params.linkedAddress - Optional CAIP-10 account ID to link to the
|
|
188
|
+
* profile when it does not exist yet.
|
|
189
|
+
* @returns The X authorization URL and state parameter.
|
|
190
|
+
*/
|
|
191
|
+
startXConnect(params?: {
|
|
192
|
+
linkedAddress?: CaipAccountId;
|
|
193
|
+
}): Promise<XConnectSession>;
|
|
194
|
+
/**
|
|
195
|
+
* Disconnects the X account linked to the given profile, clears xProfile from
|
|
196
|
+
* state, and marks the profile in state as no longer connected to X.
|
|
197
|
+
*
|
|
198
|
+
* @param profileId - The ID of the profile to disconnect the linked X account
|
|
199
|
+
* from (sourced from {@link getProfile}).
|
|
200
|
+
*/
|
|
201
|
+
disconnectX(profileId: string): Promise<void>;
|
|
151
202
|
}
|
|
152
203
|
export {};
|
|
153
204
|
//# sourceMappingURL=ProfileController.d.ts.map
|
|
@@ -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,0BAA0B,EAE3B,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,E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ailability',
|
|
47
47
|
'connectX',
|
|
48
48
|
'fetchAndUpdateXAccount',
|
|
49
|
+
'startXConnect',
|
|
50
|
+
'disconnectX',
|
|
49
51
|
];
|
|
50
52
|
// === CONTROLLER ===
|
|
51
53
|
/** Manages MetaMask profile state and delegates API operations to ProfileService. */
|
|
@@ -213,19 +215,51 @@ export class ProfileController extends BaseController {
|
|
|
213
215
|
return await this.messenger.call('ProfileService:checkUsernameAvailability', username);
|
|
214
216
|
}
|
|
215
217
|
/**
|
|
216
|
-
* Completes the X OAuth
|
|
218
|
+
* Completes the X OAuth flow, updates xProfile and profile in state, and
|
|
219
|
+
* returns the connect result. The backend creates the profile if it does
|
|
220
|
+
* not exist yet (username derived from the X handle), so the profile is
|
|
221
|
+
* always fetched from the backend after a successful connect.
|
|
217
222
|
*
|
|
218
|
-
*
|
|
223
|
+
* The linked X profile is persisted in state immediately after the connect
|
|
224
|
+
* succeeds. If the follow-up profile fetch fails, the X link remains
|
|
225
|
+
* persisted and a clear error is thrown — the profile in state may then be
|
|
226
|
+
* stale until the next successful fetch.
|
|
227
|
+
*
|
|
228
|
+
* @param params - The parameters for the X OAuth flow.
|
|
219
229
|
* @param params.code - The OAuth authorization code from the X redirect.
|
|
220
230
|
* @param params.state - The state parameter returned by the X redirect.
|
|
221
|
-
* @
|
|
231
|
+
* @param params.profileId - The canonical profile ID the X account is
|
|
232
|
+
* linked to (sourced from the auth session).
|
|
233
|
+
* @returns The refreshed profile, the linked X profile, and whether the
|
|
234
|
+
* backend created the profile during the connect.
|
|
222
235
|
*/
|
|
223
236
|
async connectX(params) {
|
|
224
|
-
const response = await this.messenger.call('ProfileService:connectX',
|
|
225
|
-
|
|
237
|
+
const response = await this.messenger.call('ProfileService:connectX', {
|
|
238
|
+
code: params.code,
|
|
239
|
+
state: params.state,
|
|
240
|
+
});
|
|
241
|
+
const profileCreated = response.profile_created ?? false;
|
|
242
|
+
const xProfile = this.#mapXResponseToXProfile(response);
|
|
243
|
+
this.update((state) => {
|
|
244
|
+
state.xProfile = xProfile;
|
|
245
|
+
});
|
|
246
|
+
let profile;
|
|
247
|
+
try {
|
|
248
|
+
const profileResponse = await this.messenger.call('ProfileService:getProfile', params.profileId);
|
|
249
|
+
profile = this.#mapApiResponseToProfile(profileResponse);
|
|
250
|
+
}
|
|
251
|
+
catch (error) {
|
|
252
|
+
throw new Error('ProfileController: connected the X account, but failed to fetch the profile afterwards; the X link is persisted and the profile fetch can be retried', { cause: error });
|
|
253
|
+
}
|
|
254
|
+
this.update((state) => {
|
|
255
|
+
state.profile = profile;
|
|
256
|
+
});
|
|
257
|
+
return { profile, xProfile, profileCreated };
|
|
226
258
|
}
|
|
227
259
|
/**
|
|
228
|
-
* Fetches the X account linked to the
|
|
260
|
+
* Fetches the X account linked to the authenticated profile, updates state,
|
|
261
|
+
* and returns the X profile. The profile is resolved server-side from the
|
|
262
|
+
* verified bearer token.
|
|
229
263
|
*
|
|
230
264
|
* @returns The linked X profile.
|
|
231
265
|
*/
|
|
@@ -237,5 +271,38 @@ export class ProfileController extends BaseController {
|
|
|
237
271
|
});
|
|
238
272
|
return mapped;
|
|
239
273
|
}
|
|
274
|
+
/**
|
|
275
|
+
* Initiates the X OAuth flow by fetching the authorization URL from the backend.
|
|
276
|
+
* The profile is resolved server-side from the verified bearer token.
|
|
277
|
+
* Returns session data for the caller to use; nothing is stored in controller state.
|
|
278
|
+
*
|
|
279
|
+
* @param params - Optional parameters for initiating the X OAuth flow.
|
|
280
|
+
* @param params.linkedAddress - Optional CAIP-10 account ID to link to the
|
|
281
|
+
* profile when it does not exist yet.
|
|
282
|
+
* @returns The X authorization URL and state parameter.
|
|
283
|
+
*/
|
|
284
|
+
async startXConnect(params) {
|
|
285
|
+
const { linkedAddress } = params ?? {};
|
|
286
|
+
const response = linkedAddress === undefined
|
|
287
|
+
? await this.messenger.call('ProfileService:getXAuthUrl')
|
|
288
|
+
: await this.messenger.call('ProfileService:getXAuthUrl', linkedAddress);
|
|
289
|
+
return { authorizationUrl: response.url, state: response.state };
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Disconnects the X account linked to the given profile, clears xProfile from
|
|
293
|
+
* state, and marks the profile in state as no longer connected to X.
|
|
294
|
+
*
|
|
295
|
+
* @param profileId - The ID of the profile to disconnect the linked X account
|
|
296
|
+
* from (sourced from {@link getProfile}).
|
|
297
|
+
*/
|
|
298
|
+
async disconnectX(profileId) {
|
|
299
|
+
await this.messenger.call('ProfileService:disconnectX', profileId);
|
|
300
|
+
this.update((state) => {
|
|
301
|
+
state.xProfile = undefined;
|
|
302
|
+
if (state.profile.profileId === profileId) {
|
|
303
|
+
state.profile.connectedToX = false;
|
|
304
|
+
}
|
|
305
|
+
});
|
|
306
|
+
}
|
|
240
307
|
}
|
|
241
308
|
//# sourceMappingURL=ProfileController.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProfileController.js","sourceRoot":"","sources":["../src/ProfileController.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AA6B3D,MAAM,cAAc,GAAG,mBAAmB,CAAC;AA4F3C,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,Q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AAC;QAC7B,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,yBAAyB,CAC7B,QAAgB;QAEhB,OAAO,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CAC9B,0CAA0C,EAC1C,QAAQ,CACT,CAAC;IACJ,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CAAC,QAAQ,CAAC,MAAuC;QACpD,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CACxC,yBAAyB,EACzB,MAAM,CACP,CAAC;QACF,OAAO,IAAI,CAAC,uBAAuB,CAAC,QAAQ,CAAC,CAAC;IAChD,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,sBAAsB;QAC1B,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,4BAA4B,CAAC,CAAC;QACzE,MAAM,MAAM,GAAG,IAAI,CAAC,uBAAuB,CAAC,QAAQ,CAAC,CAAC;QACtD,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,KAAK,CAAC,QAAQ,GAAG,MAAM,CAAC;QAC1B,CAAC,CAAC,CAAC;QACH,OAAO,MAAM,CAAC;IAChB,CAAC;CACF","sourcesContent":["import { BaseController } from '@metamask/base-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\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 ProfileServiceGetXAccountAction,\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 XConnectResponse,\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/** 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 = ControllerStateChangeEvent<\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\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] 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: XConnectResponse): 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 * If the user had previously connected X, also updates xProfile in state.\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 if (response.x_profile) {\n state.xProfile = this.#mapXResponseToXProfile(response.x_profile);\n }\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 PKCE flow, updates xProfile in state, and returns the X profile.\n *\n * @param params - The parameters for the X OAuth PKCE 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(\n 'ProfileService:connectX',\n params,\n );\n return this.#mapXResponseToXProfile(response);\n }\n\n /**\n * Fetches the X account linked to the current profile, updates state, and returns the X profile.\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"]}
|
|
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;AAiH3C,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,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GAAG,IAAI,CAAC,uBAAuB,CAAC,QAAQ,CAAC,CAAC;QACtD,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,KAAK,CAAC,QAAQ,GAAG,MAAM,CAAC;QAC1B,CAAC,CAAC,CAAC;QACH,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;;;;;;;;OASG;IACH,KAAK,CAAC,aAAa,CAAC,MAEnB;QACC,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,IAAI,EAAE,CAAC;QACvC,MAAM,QAAQ,GACZ,aAAa,KAAK,SAAS;YACzB,CAAC,CAAC,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,4BAA4B,CAAC;YACzD,CAAC,CAAC,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CACvB,4BAA4B,EAC5B,aAAa,CACd,CAAC;QACR,OAAO,EAAE,gBAAgB,EAAE,QAAQ,CAAC,GAAG,EAAE,KAAK,EAAE,QAAQ,CAAC,KAAK,EAAE,CAAC;IACnE,CAAC;IAED;;;;;;OAMG;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,KAAK,CAAC,QAAQ,GAAG,SAAS,CAAC;YAC3B,IAAI,KAAK,CAAC,OAAO,CAAC,SAAS,KAAK,SAAS,EAAE,CAAC;gBAC1C,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 ControllerStateChangeEvent,\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 XConnectResponse,\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 XConnectSession = {\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/** Result of completing the X connect flow. */\nexport type XConnectResult = {\n /** The MetaMask profile, refreshed from the backend after the connect. */\n profile: Profile;\n /** The linked X profile. */\n xProfile: XProfile;\n /** Whether the backend created the MetaMask profile during the connect. */\n profileCreated: boolean;\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 = ControllerStateChangeEvent<\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 | ProfileServiceGetProfileAction\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 'startXConnect',\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: XConnectResponse): 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 * If the user had previously connected X, also updates xProfile in state.\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 if (response.x_profile) {\n state.xProfile = this.#mapXResponseToXProfile(response.x_profile);\n }\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, updates xProfile and profile in state, and\n * returns the connect result. The backend creates the profile if it does\n * not exist yet (username derived from the X handle), so the profile is\n * always fetched from the backend after a successful connect.\n *\n * The linked X profile is persisted in state immediately after the connect\n * succeeds. If the follow-up profile fetch fails, the X link remains\n * persisted and a clear error is thrown — the profile in state may then be\n * stale until the next successful fetch.\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 * @param params.profileId - The canonical profile ID the X account is\n * linked to (sourced from the auth session).\n * @returns The refreshed profile, the linked X profile, and whether the\n * backend created the profile during the connect.\n */\n async connectX(params: {\n code: string;\n state: string;\n profileId: string;\n }): Promise<XConnectResult> {\n const response = await this.messenger.call('ProfileService:connectX', {\n code: params.code,\n state: params.state,\n });\n const profileCreated = response.profile_created ?? false;\n const xProfile = this.#mapXResponseToXProfile(response);\n this.update((state) => {\n state.xProfile = xProfile;\n });\n\n let profile: Profile;\n try {\n const profileResponse = await this.messenger.call(\n 'ProfileService:getProfile',\n params.profileId,\n );\n profile = this.#mapApiResponseToProfile(profileResponse);\n } catch (error) {\n throw new Error(\n 'ProfileController: connected the X account, but failed to fetch the profile afterwards; the X link is persisted and the profile fetch can be retried',\n { cause: error },\n );\n }\n this.update((state) => {\n state.profile = profile;\n });\n\n return { profile, xProfile, profileCreated };\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 * @param params - Optional parameters for initiating the X OAuth flow.\n * @param params.linkedAddress - Optional CAIP-10 account ID to link to the\n * profile when it does not exist yet.\n * @returns The X authorization URL and state parameter.\n */\n async startXConnect(params?: {\n linkedAddress?: CaipAccountId;\n }): Promise<XConnectSession> {\n const { linkedAddress } = params ?? {};\n const response =\n linkedAddress === undefined\n ? await this.messenger.call('ProfileService:getXAuthUrl')\n : await this.messenger.call(\n 'ProfileService:getXAuthUrl',\n linkedAddress,\n );\n return { authorizationUrl: response.url, state: response.state };\n }\n\n /**\n * Disconnects the X account linked to the given profile, clears xProfile from\n * state, and 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 state.xProfile = undefined;\n if (state.profile.profileId === profileId) {\n state.profile.connectedToX = false;\n }\n });\n }\n}\n"]}
|
|
@@ -78,7 +78,10 @@ export type ProfileServiceCheckUsernameAvailabilityAction = {
|
|
|
78
78
|
};
|
|
79
79
|
/**
|
|
80
80
|
* Fetches the X OAuth PKCE authorization URL and its associated state parameter.
|
|
81
|
+
* The profile is resolved server-side from the verified bearer token.
|
|
81
82
|
*
|
|
83
|
+
* @param linkedAddress - Optional CAIP-10 account ID to link to the profile
|
|
84
|
+
* when it does not exist yet; sent as the `linked_address` query parameter.
|
|
82
85
|
* @returns An object containing the authorization URL and the state token.
|
|
83
86
|
* @throws {HttpError} If the API returns a non-2xx response.
|
|
84
87
|
* @throws {StructError} If the response does not match the expected shape.
|
|
@@ -89,9 +92,12 @@ export type ProfileServiceGetXAuthUrlAction = {
|
|
|
89
92
|
};
|
|
90
93
|
/**
|
|
91
94
|
* Completes the X OAuth PKCE flow and links the X account to the profile.
|
|
95
|
+
* The backend creates the profile if it does not exist yet (username derived
|
|
96
|
+
* from the X handle) and reports that via `profile_created`.
|
|
92
97
|
*
|
|
93
98
|
* @param params - The OAuth callback code and state from the X redirect.
|
|
94
|
-
* @returns The linked X account data
|
|
99
|
+
* @returns The linked X account data, plus `profile_created` when the
|
|
100
|
+
* backend created the profile during the connect.
|
|
95
101
|
* @throws {HttpError} If the API returns a non-2xx response.
|
|
96
102
|
* @throws {StructError} If the response does not match the expected shape.
|
|
97
103
|
*/
|
|
@@ -101,6 +107,7 @@ export type ProfileServiceConnectXAction = {
|
|
|
101
107
|
};
|
|
102
108
|
/**
|
|
103
109
|
* Fetches the X account currently linked to the authenticated profile.
|
|
110
|
+
* The profile is resolved server-side from the verified bearer token.
|
|
104
111
|
*
|
|
105
112
|
* @returns The linked X account data.
|
|
106
113
|
* @throws {HttpError} If the API returns a non-2xx response.
|
|
@@ -110,8 +117,21 @@ export type ProfileServiceGetXAccountAction = {
|
|
|
110
117
|
type: `ProfileService:getXAccount`;
|
|
111
118
|
handler: ProfileService['getXAccount'];
|
|
112
119
|
};
|
|
120
|
+
/**
|
|
121
|
+
* Disconnects the X account linked to the given profile.
|
|
122
|
+
* A `404` response is treated as success (the X account is already
|
|
123
|
+
* disconnected, or the profile is unknown), making the operation idempotent.
|
|
124
|
+
*
|
|
125
|
+
* @param profileId - The ID of the profile to disconnect the linked X account from.
|
|
126
|
+
* @returns The result of the mutation.
|
|
127
|
+
* @throws {HttpError} If the API returns a non-2xx response other than `404`.
|
|
128
|
+
*/
|
|
129
|
+
export type ProfileServiceDisconnectXAction = {
|
|
130
|
+
type: `ProfileService:disconnectX`;
|
|
131
|
+
handler: ProfileService['disconnectX'];
|
|
132
|
+
};
|
|
113
133
|
/**
|
|
114
134
|
* Union of all ProfileService action types.
|
|
115
135
|
*/
|
|
116
|
-
export type ProfileServiceMethodActions = ProfileServiceGetProfileAction | ProfileServiceCreateProfileAction | ProfileServiceReplaceProfileAction | ProfileServiceUpdateProfileAction | ProfileServiceDeleteProfileAction | ProfileServiceCheckUsernameAvailabilityAction | ProfileServiceGetXAuthUrlAction | ProfileServiceConnectXAction | ProfileServiceGetXAccountAction;
|
|
136
|
+
export type ProfileServiceMethodActions = ProfileServiceGetProfileAction | ProfileServiceCreateProfileAction | ProfileServiceReplaceProfileAction | ProfileServiceUpdateProfileAction | ProfileServiceDeleteProfileAction | ProfileServiceCheckUsernameAvailabilityAction | ProfileServiceGetXAuthUrlAction | ProfileServiceConnectXAction | ProfileServiceGetXAccountAction | ProfileServiceDisconnectXAction;
|
|
117
137
|
//# sourceMappingURL=ProfileService-method-action-types.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProfileService-method-action-types.d.ts","sourceRoot":"","sources":["../src/ProfileService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAE1D;;;;;;;GAOG;AACH,MAAM,MAAM,8BAA8B,GAAG;IAC3C,IAAI,EAAE,2BAA2B,CAAC;IAClC,OAAO,EAAE,cAAc,CAAC,YAAY,CAAC,CAAC;CACvC,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,MAAM,iCAAiC,GAAG;IAC9C,IAAI,EAAE,8BAA8B,CAAC;IACrC,OAAO,EAAE,cAAc,CAAC,eAAe,CAAC,CAAC;CAC1C,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,MAAM,kCAAkC,GAAG;IAC/C,IAAI,EAAE,+BAA+B,CAAC;IACtC,OAAO,EAAE,cAAc,CAAC,gBAAgB,CAAC,CAAC;CAC3C,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,MAAM,iCAAiC,GAAG;IAC9C,IAAI,EAAE,8BAA8B,CAAC;IACrC,OAAO,EAAE,cAAc,CAAC,eAAe,CAAC,CAAC;CAC1C,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,iCAAiC,GAAG;IAC9C,IAAI,EAAE,8BAA8B,CAAC;IACrC,OAAO,EAAE,cAAc,CAAC,eAAe,CAAC,CAAC;CAC1C,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,MAAM,6CAA6C,GAAG;IAC1D,IAAI,EAAE,0CAA0C,CAAC;IACjD,OAAO,EAAE,cAAc,CAAC,2BAA2B,CAAC,CAAC;CACtD,CAAC;AAEF
|
|
1
|
+
{"version":3,"file":"ProfileService-method-action-types.d.ts","sourceRoot":"","sources":["../src/ProfileService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAE1D;;;;;;;GAOG;AACH,MAAM,MAAM,8BAA8B,GAAG;IAC3C,IAAI,EAAE,2BAA2B,CAAC;IAClC,OAAO,EAAE,cAAc,CAAC,YAAY,CAAC,CAAC;CACvC,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,MAAM,iCAAiC,GAAG;IAC9C,IAAI,EAAE,8BAA8B,CAAC;IACrC,OAAO,EAAE,cAAc,CAAC,eAAe,CAAC,CAAC;CAC1C,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,MAAM,kCAAkC,GAAG;IAC/C,IAAI,EAAE,+BAA+B,CA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C/B,4BAA4B,GAC5B,+BAA+B,GAC/B,+BAA+B,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProfileService-method-action-types.js","sourceRoot":"","sources":["../src/ProfileService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { ProfileService } from './ProfileService.js';\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 */\nexport type ProfileServiceGetProfileAction = {\n type: `ProfileService:getProfile`;\n handler: ProfileService['getProfile'];\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 */\nexport type ProfileServiceCreateProfileAction = {\n type: `ProfileService:createProfile`;\n handler: ProfileService['createProfile'];\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 */\nexport type ProfileServiceReplaceProfileAction = {\n type: `ProfileService:replaceProfile`;\n handler: ProfileService['replaceProfile'];\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 */\nexport type ProfileServiceUpdateProfileAction = {\n type: `ProfileService:updateProfile`;\n handler: ProfileService['updateProfile'];\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 */\nexport type ProfileServiceDeleteProfileAction = {\n type: `ProfileService:deleteProfile`;\n handler: ProfileService['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 * @throws {HttpError} If the API returns a non-2xx response.\n * @throws {StructError} If the response does not match the expected shape.\n */\nexport type ProfileServiceCheckUsernameAvailabilityAction = {\n type: `ProfileService:checkUsernameAvailability`;\n handler: ProfileService['checkUsernameAvailability'];\n};\n\n/**\n * Fetches the X OAuth PKCE authorization URL and its associated state parameter.\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 */\nexport type ProfileServiceGetXAuthUrlAction = {\n type: `ProfileService:getXAuthUrl`;\n handler: ProfileService['getXAuthUrl'];\n};\n\n/**\n * Completes the X OAuth PKCE flow and links the X account to the profile.\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 */\nexport type ProfileServiceConnectXAction = {\n type: `ProfileService:connectX`;\n handler: ProfileService['connectX'];\n};\n\n/**\n * Fetches the X account currently linked to the authenticated profile.\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 */\nexport type ProfileServiceGetXAccountAction = {\n type: `ProfileService:getXAccount`;\n handler: ProfileService['getXAccount'];\n};\n\n/**\n * Union of all ProfileService action types.\n */\nexport type ProfileServiceMethodActions =\n | ProfileServiceGetProfileAction\n | ProfileServiceCreateProfileAction\n | ProfileServiceReplaceProfileAction\n | ProfileServiceUpdateProfileAction\n | ProfileServiceDeleteProfileAction\n | ProfileServiceCheckUsernameAvailabilityAction\n | ProfileServiceGetXAuthUrlAction\n | ProfileServiceConnectXAction\n | ProfileServiceGetXAccountAction;\n"]}
|
|
1
|
+
{"version":3,"file":"ProfileService-method-action-types.js","sourceRoot":"","sources":["../src/ProfileService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { ProfileService } from './ProfileService.js';\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 */\nexport type ProfileServiceGetProfileAction = {\n type: `ProfileService:getProfile`;\n handler: ProfileService['getProfile'];\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 */\nexport type ProfileServiceCreateProfileAction = {\n type: `ProfileService:createProfile`;\n handler: ProfileService['createProfile'];\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 */\nexport type ProfileServiceReplaceProfileAction = {\n type: `ProfileService:replaceProfile`;\n handler: ProfileService['replaceProfile'];\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 */\nexport type ProfileServiceUpdateProfileAction = {\n type: `ProfileService:updateProfile`;\n handler: ProfileService['updateProfile'];\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 */\nexport type ProfileServiceDeleteProfileAction = {\n type: `ProfileService:deleteProfile`;\n handler: ProfileService['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 * @throws {HttpError} If the API returns a non-2xx response.\n * @throws {StructError} If the response does not match the expected shape.\n */\nexport type ProfileServiceCheckUsernameAvailabilityAction = {\n type: `ProfileService:checkUsernameAvailability`;\n handler: ProfileService['checkUsernameAvailability'];\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 * @param linkedAddress - Optional CAIP-10 account ID to link to the profile\n * when it does not exist yet; sent as the `linked_address` query parameter.\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 */\nexport type ProfileServiceGetXAuthUrlAction = {\n type: `ProfileService:getXAuthUrl`;\n handler: ProfileService['getXAuthUrl'];\n};\n\n/**\n * Completes the X OAuth PKCE flow and links the X account to the profile.\n * The backend creates the profile if it does not exist yet (username derived\n * from the X handle) and reports that via `profile_created`.\n *\n * @param params - The OAuth callback code and state from the X redirect.\n * @returns The linked X account data, plus `profile_created` when the\n * backend created the profile during the connect.\n * @throws {HttpError} If the API returns a non-2xx response.\n * @throws {StructError} If the response does not match the expected shape.\n */\nexport type ProfileServiceConnectXAction = {\n type: `ProfileService:connectX`;\n handler: ProfileService['connectX'];\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 */\nexport type ProfileServiceGetXAccountAction = {\n type: `ProfileService:getXAccount`;\n handler: ProfileService['getXAccount'];\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 */\nexport type ProfileServiceDisconnectXAction = {\n type: `ProfileService:disconnectX`;\n handler: ProfileService['disconnectX'];\n};\n\n/**\n * Union of all ProfileService action types.\n */\nexport type ProfileServiceMethodActions =\n | ProfileServiceGetProfileAction\n | ProfileServiceCreateProfileAction\n | ProfileServiceReplaceProfileAction\n | ProfileServiceUpdateProfileAction\n | ProfileServiceDeleteProfileAction\n | ProfileServiceCheckUsernameAvailabilityAction\n | ProfileServiceGetXAuthUrlAction\n | ProfileServiceConnectXAction\n | ProfileServiceGetXAccountAction\n | ProfileServiceDisconnectXAction;\n"]}
|
package/dist/ProfileService.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type { CreateServicePolicyOptions, DataServiceCacheUpdatedEvent, DataServ
|
|
|
3
3
|
import type { Messenger } from '@metamask/messenger';
|
|
4
4
|
import type { AuthenticationController } from '@metamask/profile-sync-controller';
|
|
5
5
|
import type { Infer } from '@metamask/superstruct';
|
|
6
|
+
import type { CaipAccountId } from '@metamask/utils';
|
|
6
7
|
import type { ProfileServiceMethodActions } from './ProfileService-method-action-types.js';
|
|
7
8
|
export declare const serviceName = "ProfileService";
|
|
8
9
|
/** Human-readable error messages for each ProfileService operation. */
|
|
@@ -16,6 +17,7 @@ export declare const ProfileServiceErrorMessage: {
|
|
|
16
17
|
readonly GET_X_AUTH_URL_FAILED: 'ProfileService: failed to get X authentication URL';
|
|
17
18
|
readonly CONNECT_X_FAILED: 'ProfileService: failed to connect X account';
|
|
18
19
|
readonly GET_X_ACCOUNT_FAILED: 'ProfileService: failed to get X account';
|
|
20
|
+
readonly DISCONNECT_X_FAILED: 'ProfileService: failed to disconnect X account';
|
|
19
21
|
};
|
|
20
22
|
declare const ProfileApiResponseStruct: import("@metamask/superstruct").Struct<{
|
|
21
23
|
profile_id: string;
|
|
@@ -92,6 +94,23 @@ declare const XConnectResponseStruct: import("@metamask/superstruct").Struct<{
|
|
|
92
94
|
created_at: import("@metamask/superstruct").Struct<string, null>;
|
|
93
95
|
updated_at: import("@metamask/superstruct").Struct<string, null>;
|
|
94
96
|
}>;
|
|
97
|
+
/**
|
|
98
|
+
* Response shape for POST /v1/profiles/x/connect: the linked X account plus
|
|
99
|
+
* `profile_created`, indicating whether the backend created the MetaMask
|
|
100
|
+
* profile during the connect. Optional so older backends that do not send
|
|
101
|
+
* the field still validate.
|
|
102
|
+
*/
|
|
103
|
+
declare const ConnectXResponseStruct: import("@metamask/superstruct").Struct<{
|
|
104
|
+
x_user_id: string;
|
|
105
|
+
x_profile_url: string;
|
|
106
|
+
username: string;
|
|
107
|
+
display_name: string;
|
|
108
|
+
avatar_url: string;
|
|
109
|
+
created_at: string;
|
|
110
|
+
updated_at: string;
|
|
111
|
+
} & {
|
|
112
|
+
profile_created?: boolean | undefined;
|
|
113
|
+
}, null>;
|
|
95
114
|
declare const CreateProfileResponseStruct: import("@metamask/superstruct").Struct<{
|
|
96
115
|
profile_id: string;
|
|
97
116
|
username: string;
|
|
@@ -185,6 +204,8 @@ export type CreateProfileResponse = Infer<typeof CreateProfileResponseStruct>;
|
|
|
185
204
|
export type UsernameAvailabilityResponse = Infer<typeof UsernameAvailabilityResponseStruct>;
|
|
186
205
|
/** The response shape returned when connecting or fetching an X account. */
|
|
187
206
|
export type XConnectResponse = Infer<typeof XConnectResponseStruct>;
|
|
207
|
+
/** The response shape returned when completing the X connect flow. */
|
|
208
|
+
export type ConnectXResponse = Infer<typeof ConnectXResponseStruct>;
|
|
188
209
|
/** The response shape returned when requesting the X OAuth authentication URL. */
|
|
189
210
|
export type XAuthUrlResponse = Infer<typeof XAuthUrlResponseStruct>;
|
|
190
211
|
/** Alias for {@link XConnectResponse} returned when fetching the linked X account. */
|
|
@@ -282,29 +303,46 @@ export declare class ProfileService extends BaseDataService<typeof serviceName,
|
|
|
282
303
|
checkUsernameAvailability(username: string): Promise<UsernameAvailabilityResponse>;
|
|
283
304
|
/**
|
|
284
305
|
* Fetches the X OAuth PKCE authorization URL and its associated state parameter.
|
|
306
|
+
* The profile is resolved server-side from the verified bearer token.
|
|
285
307
|
*
|
|
308
|
+
* @param linkedAddress - Optional CAIP-10 account ID to link to the profile
|
|
309
|
+
* when it does not exist yet; sent as the `linked_address` query parameter.
|
|
286
310
|
* @returns An object containing the authorization URL and the state token.
|
|
287
311
|
* @throws {HttpError} If the API returns a non-2xx response.
|
|
288
312
|
* @throws {StructError} If the response does not match the expected shape.
|
|
289
313
|
*/
|
|
290
|
-
getXAuthUrl(): Promise<XAuthUrlResponse>;
|
|
314
|
+
getXAuthUrl(linkedAddress?: CaipAccountId): Promise<XAuthUrlResponse>;
|
|
291
315
|
/**
|
|
292
316
|
* Completes the X OAuth PKCE flow and links the X account to the profile.
|
|
317
|
+
* The backend creates the profile if it does not exist yet (username derived
|
|
318
|
+
* from the X handle) and reports that via `profile_created`.
|
|
293
319
|
*
|
|
294
320
|
* @param params - The OAuth callback code and state from the X redirect.
|
|
295
|
-
* @returns The linked X account data
|
|
321
|
+
* @returns The linked X account data, plus `profile_created` when the
|
|
322
|
+
* backend created the profile during the connect.
|
|
296
323
|
* @throws {HttpError} If the API returns a non-2xx response.
|
|
297
324
|
* @throws {StructError} If the response does not match the expected shape.
|
|
298
325
|
*/
|
|
299
|
-
connectX(params: ConnectXParams): Promise<
|
|
326
|
+
connectX(params: ConnectXParams): Promise<ConnectXResponse>;
|
|
300
327
|
/**
|
|
301
328
|
* Fetches the X account currently linked to the authenticated profile.
|
|
329
|
+
* The profile is resolved server-side from the verified bearer token.
|
|
302
330
|
*
|
|
303
331
|
* @returns The linked X account data.
|
|
304
332
|
* @throws {HttpError} If the API returns a non-2xx response.
|
|
305
333
|
* @throws {StructError} If the response does not match the expected shape.
|
|
306
334
|
*/
|
|
307
335
|
getXAccount(): Promise<XAccountResponse>;
|
|
336
|
+
/**
|
|
337
|
+
* Disconnects the X account linked to the given profile.
|
|
338
|
+
* A `404` response is treated as success (the X account is already
|
|
339
|
+
* disconnected, or the profile is unknown), making the operation idempotent.
|
|
340
|
+
*
|
|
341
|
+
* @param profileId - The ID of the profile to disconnect the linked X account from.
|
|
342
|
+
* @returns The result of the mutation.
|
|
343
|
+
* @throws {HttpError} If the API returns a non-2xx response other than `404`.
|
|
344
|
+
*/
|
|
345
|
+
disconnectX(profileId: string): Promise<void>;
|
|
308
346
|
}
|
|
309
347
|
export {};
|
|
310
348
|
//# sourceMappingURL=ProfileService.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProfileService.d.ts","sourceRoot":"","sources":["../src/ProfileService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,KAAK,EACV,0BAA0B,EAC1B,4BAA4B,EAC5B,oCAAoC,EACpC,kCAAkC,EACnC,MAAM,6BAA6B,CAAC;AAErC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,mCAAmC,CAAC;AAYlF,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;
|
|
1
|
+
{"version":3,"file":"ProfileService.d.ts","sourceRoot":"","sources":["../src/ProfileService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,KAAK,EACV,0BAA0B,EAC1B,4BAA4B,EAC5B,oCAAoC,EACpC,kCAAkC,EACnC,MAAM,6BAA6B,CAAC;AAErC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,mCAAmC,CAAC;AAYlF,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAGnD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAErD,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,yCAAyC,CAAC;AAE3F,eAAO,MAAM,WAAW,mBAAmB,CAAC;AAM5C,uEAAuE;AACvE,eAAO,MAAM,0BAA0B;aACrC,kBAAkB,EAAE,yCAAyC;aAC7D,qBAAqB,EAA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|
|
|
17
17
|
GET_X_AUTH_URL_FAILED: 'ProfileService: failed to get X authentication URL',
|
|
18
18
|
CONNECT_X_FAILED: 'ProfileService: failed to connect X account',
|
|
19
19
|
GET_X_ACCOUNT_FAILED: 'ProfileService: failed to get X account',
|
|
20
|
+
DISCONNECT_X_FAILED: 'ProfileService: failed to disconnect X account',
|
|
20
21
|
};
|
|
21
22
|
// ---------------------------------------------------------------------------
|
|
22
23
|
// Superstruct schemas
|
|
@@ -58,6 +59,16 @@ const XConnectResponseStruct = structType({
|
|
|
58
59
|
created_at: string(),
|
|
59
60
|
updated_at: string(),
|
|
60
61
|
});
|
|
62
|
+
/**
|
|
63
|
+
* Response shape for POST /v1/profiles/x/connect: the linked X account plus
|
|
64
|
+
* `profile_created`, indicating whether the backend created the MetaMask
|
|
65
|
+
* profile during the connect. Optional so older backends that do not send
|
|
66
|
+
* the field still validate.
|
|
67
|
+
*/
|
|
68
|
+
const ConnectXResponseStruct = intersection([
|
|
69
|
+
XConnectResponseStruct,
|
|
70
|
+
structType({ profile_created: optional(boolean()) }),
|
|
71
|
+
]);
|
|
61
72
|
const CreateProfileResponseStruct = intersection([
|
|
62
73
|
ProfileApiResponseStruct,
|
|
63
74
|
structType({ x_profile: optional(XConnectResponseStruct) }),
|
|
@@ -104,6 +115,7 @@ const MESSENGER_EXPOSED_METHODS = [
|
|
|
104
115
|
'getXAuthUrl',
|
|
105
116
|
'connectX',
|
|
106
117
|
'getXAccount',
|
|
118
|
+
'disconnectX',
|
|
107
119
|
];
|
|
108
120
|
// ---------------------------------------------------------------------------
|
|
109
121
|
// Service
|
|
@@ -273,32 +285,41 @@ export class ProfileService extends BaseDataService {
|
|
|
273
285
|
}
|
|
274
286
|
/**
|
|
275
287
|
* Fetches the X OAuth PKCE authorization URL and its associated state parameter.
|
|
288
|
+
* The profile is resolved server-side from the verified bearer token.
|
|
276
289
|
*
|
|
290
|
+
* @param linkedAddress - Optional CAIP-10 account ID to link to the profile
|
|
291
|
+
* when it does not exist yet; sent as the `linked_address` query parameter.
|
|
277
292
|
* @returns An object containing the authorization URL and the state token.
|
|
278
293
|
* @throws {HttpError} If the API returns a non-2xx response.
|
|
279
294
|
* @throws {StructError} If the response does not match the expected shape.
|
|
280
295
|
*/
|
|
281
|
-
async getXAuthUrl() {
|
|
296
|
+
async getXAuthUrl(linkedAddress) {
|
|
282
297
|
return this.executeMutation({
|
|
283
298
|
mutationKey: [`${this.name}:getXAuthUrl`],
|
|
284
299
|
responseStruct: XAuthUrlResponseStruct,
|
|
285
300
|
mutationFn: async () => this.#fetch('profiles/x/authentication-url', {
|
|
286
301
|
error: ProfileServiceErrorMessage.GET_X_AUTH_URL_FAILED,
|
|
302
|
+
...(linkedAddress === undefined
|
|
303
|
+
? {}
|
|
304
|
+
: { searchParams: { linked_address: linkedAddress } }),
|
|
287
305
|
}),
|
|
288
306
|
});
|
|
289
307
|
}
|
|
290
308
|
/**
|
|
291
309
|
* Completes the X OAuth PKCE flow and links the X account to the profile.
|
|
310
|
+
* The backend creates the profile if it does not exist yet (username derived
|
|
311
|
+
* from the X handle) and reports that via `profile_created`.
|
|
292
312
|
*
|
|
293
313
|
* @param params - The OAuth callback code and state from the X redirect.
|
|
294
|
-
* @returns The linked X account data
|
|
314
|
+
* @returns The linked X account data, plus `profile_created` when the
|
|
315
|
+
* backend created the profile during the connect.
|
|
295
316
|
* @throws {HttpError} If the API returns a non-2xx response.
|
|
296
317
|
* @throws {StructError} If the response does not match the expected shape.
|
|
297
318
|
*/
|
|
298
319
|
async connectX(params) {
|
|
299
320
|
return this.executeMutation({
|
|
300
321
|
mutationKey: [`${this.name}:connectX`],
|
|
301
|
-
responseStruct:
|
|
322
|
+
responseStruct: ConnectXResponseStruct,
|
|
302
323
|
mutationFn: async () => this.#fetch('profiles/x/connect', {
|
|
303
324
|
method: 'POST',
|
|
304
325
|
error: ProfileServiceErrorMessage.CONNECT_X_FAILED,
|
|
@@ -308,6 +329,7 @@ export class ProfileService extends BaseDataService {
|
|
|
308
329
|
}
|
|
309
330
|
/**
|
|
310
331
|
* Fetches the X account currently linked to the authenticated profile.
|
|
332
|
+
* The profile is resolved server-side from the verified bearer token.
|
|
311
333
|
*
|
|
312
334
|
* @returns The linked X account data.
|
|
313
335
|
* @throws {HttpError} If the API returns a non-2xx response.
|
|
@@ -323,5 +345,33 @@ export class ProfileService extends BaseDataService {
|
|
|
323
345
|
}),
|
|
324
346
|
});
|
|
325
347
|
}
|
|
348
|
+
/**
|
|
349
|
+
* Disconnects the X account linked to the given profile.
|
|
350
|
+
* A `404` response is treated as success (the X account is already
|
|
351
|
+
* disconnected, or the profile is unknown), making the operation idempotent.
|
|
352
|
+
*
|
|
353
|
+
* @param profileId - The ID of the profile to disconnect the linked X account from.
|
|
354
|
+
* @returns The result of the mutation.
|
|
355
|
+
* @throws {HttpError} If the API returns a non-2xx response other than `404`.
|
|
356
|
+
*/
|
|
357
|
+
async disconnectX(profileId) {
|
|
358
|
+
return this.executeMutation({
|
|
359
|
+
mutationKey: [`${this.name}:disconnectX`, profileId],
|
|
360
|
+
mutationFn: async () => {
|
|
361
|
+
try {
|
|
362
|
+
return await this.#fetch(`profiles/${encodeURIComponent(profileId)}/x`, {
|
|
363
|
+
method: 'DELETE',
|
|
364
|
+
error: ProfileServiceErrorMessage.DISCONNECT_X_FAILED,
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
catch (error) {
|
|
368
|
+
if (error instanceof HttpError && error.httpStatus === 404) {
|
|
369
|
+
return null;
|
|
370
|
+
}
|
|
371
|
+
throw error;
|
|
372
|
+
}
|
|
373
|
+
},
|
|
374
|
+
});
|
|
375
|
+
}
|
|
326
376
|
}
|
|
327
377
|
//# sourceMappingURL=ProfileService.js.map
|
|
@@ -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,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gB;gBAClD,IAAI,EAAE,MAAM;aACb,CAAC;SACL,CAAC,CAAC;IACL,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,WAAW;QACf,OAAO,IAAI,CAAC,UAAU,CAAC;YACrB,QAAQ,EAAE,CAAC,GAAG,IAAI,CAAC,IAAI,cAAc,CAAC;YACtC,SAAS,EAAE,CAAC;YACZ,cAAc,EAAE,sBAAsB;YACtC,OAAO,EAAE,KAAK,IAAI,EAAE,CAClB,IAAI,CAAC,MAAM,CAAmB,oBAAoB,EAAE;gBAClD,KAAK,EAAE,0BAA0B,CAAC,oBAAoB;aACvD,CAAC;SACL,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} 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 XConnectResponseStruct = 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(XConnectResponseStruct) }),\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] 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 XConnectResponse = Infer<typeof XConnectResponseStruct>;\n\n/** The response shape returned when requesting the X OAuth authentication URL. */\nexport type XAuthUrlResponse = Infer<typeof XAuthUrlResponseStruct>;\n\n/** Alias for {@link XConnectResponse} returned when fetching the linked X account. */\nexport type XAccountResponse = XConnectResponse;\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 *\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 *\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<XConnectResponse> {\n return this.executeMutation({\n mutationKey: [`${this.name}:connectX`],\n responseStruct: XConnectResponseStruct,\n mutationFn: async () =>\n this.#fetch<XConnectResponse>('profiles/x/connect', {\n method: 'POST',\n error: ProfileServiceErrorMessage.CONNECT_X_FAILED,\n json: params,\n }),\n });\n }\n\n /**\n * Fetches the X account currently linked to the authenticated profile.\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: XConnectResponseStruct,\n queryFn: async () =>\n this.#fetch<XConnectResponse>('profiles/x/account', {\n error: ProfileServiceErrorMessage.GET_X_ACCOUNT_FAILED,\n }),\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;AAKtD,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,0CA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AC,UAAU,CAAC;YACrB,QAAQ,EAAE,CAAC,GAAG,IAAI,CAAC,IAAI,cAAc,CAAC;YACtC,SAAS,EAAE,CAAC;YACZ,cAAc,EAAE,sBAAsB;YACtC,OAAO,EAAE,KAAK,IAAI,EAAE,CAClB,IAAI,CAAC,MAAM,CAAmB,oBAAoB,EAAE;gBAClD,KAAK,EAAE,0BAA0B,CAAC,oBAAoB;aACvD,CAAC;SACL,CAAC,CAAC;IACL,CAAC;IAED;;;;;;;;OAQG;IACH,KAAK,CAAC,WAAW,CAAC,SAAiB;QACjC,OAAO,IAAI,CAAC,eAAe,CAAC;YAC1B,WAAW,EAAE,CAAC,GAAG,IAAI,CAAC,IAAI,cAAc,EAAE,SAAS,CAAC;YACpD,UAAU,EAAE,KAAK,IAAI,EAAE;gBACrB,IAAI,CAAC;oBACH,OAAO,MAAM,IAAI,CAAC,MAAM,CACtB,YAAY,kBAAkB,CAAC,SAAS,CAAC,IAAI,EAC7C;wBACE,MAAM,EAAE,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;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';\nimport type { CaipAccountId } 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 XConnectResponseStruct = 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\n/**\n * Response shape for POST /v1/profiles/x/connect: the linked X account plus\n * `profile_created`, indicating whether the backend created the MetaMask\n * profile during the connect. Optional so older backends that do not send\n * the field still validate.\n */\nconst ConnectXResponseStruct = intersection([\n XConnectResponseStruct,\n structType({ profile_created: optional(boolean()) }),\n]);\n\nconst CreateProfileResponseStruct = intersection([\n ProfileApiResponseStruct,\n structType({ x_profile: optional(XConnectResponseStruct) }),\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 XConnectResponse = Infer<typeof XConnectResponseStruct>;\n\n/** The response shape returned when completing the X connect flow. */\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 XConnectResponse} returned when fetching the linked X account. */\nexport type XAccountResponse = XConnectResponse;\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 * @param linkedAddress - Optional CAIP-10 account ID to link to the profile\n * when it does not exist yet; sent as the `linked_address` query parameter.\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(linkedAddress?: CaipAccountId): 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 ...(linkedAddress === undefined\n ? {}\n : { searchParams: { linked_address: linkedAddress } }),\n }),\n });\n }\n\n /**\n * Completes the X OAuth PKCE flow and links the X account to the profile.\n * The backend creates the profile if it does not exist yet (username derived\n * from the X handle) and reports that via `profile_created`.\n *\n * @param params - The OAuth callback code and state from the X redirect.\n * @returns The linked X account data, plus `profile_created` when the\n * backend created the profile during the connect.\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 return 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 }\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: XConnectResponseStruct,\n queryFn: async () =>\n this.#fetch<XConnectResponse>('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 return 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 }\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export type { Profile, XProfile, ProfileControllerState, ProfileControllerGetStateAction, ProfileControllerActions, ProfileControllerChangeEvent, ProfileControllerEvents, ProfileControllerMessenger, } from './ProfileController.js';
|
|
1
|
+
export type { Profile, XProfile, XConnectSession, XConnectResult, ProfileControllerState, ProfileControllerGetStateAction, ProfileControllerActions, ProfileControllerChangeEvent, ProfileControllerEvents, ProfileControllerMessenger, } from './ProfileController.js';
|
|
2
2
|
export { ProfileController, getDefaultProfileControllerState, } from './ProfileController.js';
|
|
3
|
-
export type { ProfileControllerCheckUsernameAvailabilityAction, ProfileControllerConnectXAction, ProfileControllerCreateProfileAction, ProfileControllerDeleteProfileAction, ProfileControllerGetProfileAction, ProfileControllerFetchAndUpdateXAccountAction, ProfileControllerGetXProfileAction, ProfileControllerReplaceProfileAction, ProfileControllerUpdateProfileAction, } from './ProfileController-method-action-types.js';
|
|
4
|
-
export type { ProfileApiResponse, CreateProfileResponse, CreateProfileParams, ReplaceProfileParams, UpdateProfileParams, ConnectXParams, UsernameAvailabilityResponse, XAuthUrlResponse, XConnectResponse, XAccountResponse, ProfileServiceActions, ProfileServiceEvents, ProfileServiceMessenger, } from './ProfileService.js';
|
|
3
|
+
export type { ProfileControllerCheckUsernameAvailabilityAction, ProfileControllerConnectXAction, ProfileControllerCreateProfileAction, ProfileControllerDeleteProfileAction, ProfileControllerDisconnectXAction, ProfileControllerGetProfileAction, ProfileControllerFetchAndUpdateXAccountAction, ProfileControllerGetXProfileAction, ProfileControllerReplaceProfileAction, ProfileControllerStartXConnectAction, ProfileControllerUpdateProfileAction, } from './ProfileController-method-action-types.js';
|
|
4
|
+
export type { ProfileApiResponse, CreateProfileResponse, CreateProfileParams, ReplaceProfileParams, UpdateProfileParams, ConnectXParams, UsernameAvailabilityResponse, XAuthUrlResponse, XConnectResponse, ConnectXResponse, XAccountResponse, ProfileServiceActions, ProfileServiceEvents, ProfileServiceMessenger, } from './ProfileService.js';
|
|
5
5
|
export { ProfileService, ProfileServiceErrorMessage, } from './ProfileService.js';
|
|
6
|
-
export type { ProfileServiceCheckUsernameAvailabilityAction, ProfileServiceConnectXAction, ProfileServiceCreateProfileAction, ProfileServiceDeleteProfileAction, ProfileServiceGetProfileAction, ProfileServiceGetXAccountAction, ProfileServiceGetXAuthUrlAction, ProfileServiceReplaceProfileAction, ProfileServiceUpdateProfileAction, } from './ProfileService-method-action-types.js';
|
|
6
|
+
export type { ProfileServiceCheckUsernameAvailabilityAction, ProfileServiceConnectXAction, ProfileServiceCreateProfileAction, ProfileServiceDeleteProfileAction, ProfileServiceDisconnectXAction, ProfileServiceGetProfileAction, ProfileServiceGetXAccountAction, ProfileServiceGetXAuthUrlAction, ProfileServiceReplaceProfileAction, ProfileServiceUpdateProfileAction, } from './ProfileService-method-action-types.js';
|
|
7
7
|
//# sourceMappingURL=index.d.ts.map
|
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,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,iCAAiC,EACjC,6CAA6C,EAC7C,kCAAkC,EAClC,qCAAqC,EACrC,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,EACV,6CAA6C,EAC7C,4BAA4B,EAC5B,iCAAiC,EACjC,iCAAiC,EACjC,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,cAAc,EACd,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,oCAAoC,EACpC,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,gBAAgB,EAChB,qBAAqB,EACrB,oBAAoB,EACpB,uBAAuB,GACxB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,cAAc,EACd,0BAA0B,GAC3B,MAAM,qBAAqB,CAAC;AAC7B,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":"
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAYA,OAAO,EACL,iBAAiB,EACjB,gCAAgC,GACjC,MAAM,wBAAwB,CAAC;AA8BhC,OAAO,EACL,cAAc,EACd,0BAA0B,GAC3B,MAAM,qBAAqB,CAAC","sourcesContent":["export type {\n Profile,\n XProfile,\n XConnectSession,\n XConnectResult,\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 ProfileControllerGetXProfileAction,\n ProfileControllerReplaceProfileAction,\n ProfileControllerStartXConnectAction,\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 XConnectResponse,\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 {\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.
|
|
3
|
+
"version": "1.0.1-preview-3b264bf6d",
|
|
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",
|
|
@@ -54,7 +54,7 @@
|
|
|
54
54
|
"@metamask/base-data-service": "^2.1.0",
|
|
55
55
|
"@metamask/controller-utils": "^13.0.0",
|
|
56
56
|
"@metamask/messenger": "^3.0.0",
|
|
57
|
-
"@metamask/profile-sync-controller": "^
|
|
57
|
+
"@metamask/profile-sync-controller": "^34.0.0",
|
|
58
58
|
"@metamask/superstruct": "^3.4.1",
|
|
59
59
|
"@metamask/utils": "^12.0.0"
|
|
60
60
|
},
|