@metamask-previews/subscription-controller 6.2.2-preview-58a4a8b71 → 6.2.2-preview-4c8a5dfcb
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 +8 -1
- package/dist/SubscriptionController.cjs +18 -26
- package/dist/SubscriptionController.cjs.map +1 -1
- package/dist/SubscriptionController.d.cts +5 -9
- package/dist/SubscriptionController.d.cts.map +1 -1
- package/dist/SubscriptionController.d.mts +5 -9
- package/dist/SubscriptionController.d.mts.map +1 -1
- package/dist/SubscriptionController.mjs +18 -26
- package/dist/SubscriptionController.mjs.map +1 -1
- package/dist/SubscriptionService-method-action-types.cjs +7 -0
- package/dist/SubscriptionService-method-action-types.cjs.map +1 -0
- package/dist/SubscriptionService-method-action-types.d.cts +151 -0
- package/dist/SubscriptionService-method-action-types.d.cts.map +1 -0
- package/dist/SubscriptionService-method-action-types.d.mts +151 -0
- package/dist/SubscriptionService-method-action-types.d.mts.map +1 -0
- package/dist/SubscriptionService-method-action-types.mjs +6 -0
- package/dist/SubscriptionService-method-action-types.mjs.map +1 -0
- package/dist/SubscriptionService-structs.cjs +135 -0
- package/dist/SubscriptionService-structs.cjs.map +1 -0
- package/dist/SubscriptionService-structs.d.cts +773 -0
- package/dist/SubscriptionService-structs.d.cts.map +1 -0
- package/dist/SubscriptionService-structs.d.mts +773 -0
- package/dist/SubscriptionService-structs.d.mts.map +1 -0
- package/dist/SubscriptionService-structs.mjs +132 -0
- package/dist/SubscriptionService-structs.mjs.map +1 -0
- package/dist/SubscriptionService.cjs +257 -87
- package/dist/SubscriptionService.cjs.map +1 -1
- package/dist/SubscriptionService.d.cts +90 -10
- package/dist/SubscriptionService.d.cts.map +1 -1
- package/dist/SubscriptionService.d.mts +90 -10
- package/dist/SubscriptionService.d.mts.map +1 -1
- package/dist/SubscriptionService.mjs +257 -87
- package/dist/SubscriptionService.mjs.map +1 -1
- package/dist/index.cjs +3 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -3
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +4 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -2
|
@@ -9,33 +9,101 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
9
9
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
10
10
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
11
|
};
|
|
12
|
-
var _SubscriptionService_instances, _SubscriptionService_env, _SubscriptionService_fetch, _SubscriptionService_captureException,
|
|
13
|
-
import {
|
|
12
|
+
var _SubscriptionService_instances, _SubscriptionService_env, _SubscriptionService_fetch, _SubscriptionService_captureException, _SubscriptionService_fetchJson, _SubscriptionService_getAuthenticatedContext, _SubscriptionService_headersForToken, _SubscriptionService_getSubscriptionApiUrl;
|
|
13
|
+
import { BaseDataService } from "@metamask/base-data-service";
|
|
14
|
+
import { handleWhen, HttpError } from "@metamask/controller-utils";
|
|
15
|
+
import { create } from "@metamask/superstruct";
|
|
16
|
+
import { Env, getEnvUrls, SubscriptionControllerErrorMessage, SubscriptionServiceErrorMessage } from "./constants.mjs";
|
|
14
17
|
import { createSentryError, getSubscriptionErrorFromResponse, SubscriptionServiceError } from "./errors.mjs";
|
|
15
18
|
import { createModuleLogger, projectLogger } from "./logger.mjs";
|
|
19
|
+
import { BillingPortalResponseStruct, GetSubscriptionsResponseStruct, PricingResponseStruct, StartCryptoSubscriptionResponseStruct, StartSubscriptionResponseStruct, SubscriptionApiGeneralResponseStruct, SubscriptionEligibilityArrayStruct, SubscriptionStruct, UpdatePaymentMethodCardResponseStruct } from "./SubscriptionService-structs.mjs";
|
|
20
|
+
export const serviceName = 'SubscriptionService';
|
|
16
21
|
export const SUBSCRIPTION_URL = (env, path) => `${getEnvUrls(env).subscriptionApiUrl}/v1/${path}`;
|
|
22
|
+
const MESSENGER_EXPOSED_METHODS = [
|
|
23
|
+
'getSubscriptions',
|
|
24
|
+
'cancelSubscription',
|
|
25
|
+
'unCancelSubscription',
|
|
26
|
+
'startSubscriptionWithCard',
|
|
27
|
+
'startSubscriptionWithCrypto',
|
|
28
|
+
'updatePaymentMethodCard',
|
|
29
|
+
'updatePaymentMethodCrypto',
|
|
30
|
+
'getSubscriptionsEligibilities',
|
|
31
|
+
'submitUserEvent',
|
|
32
|
+
'assignUserToCohort',
|
|
33
|
+
'submitSponsorshipIntents',
|
|
34
|
+
'linkRewards',
|
|
35
|
+
'getPricing',
|
|
36
|
+
'getBillingPortalUrl',
|
|
37
|
+
];
|
|
17
38
|
const log = createModuleLogger(projectLogger, 'SubscriptionService');
|
|
18
|
-
|
|
19
|
-
|
|
39
|
+
function isRetryableError(error) {
|
|
40
|
+
if (error instanceof HttpError) {
|
|
41
|
+
if (error.httpStatus === 429) {
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
return error.httpStatus < 400 || error.httpStatus >= 500;
|
|
45
|
+
}
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
const DEFAULT_POLICY_OPTIONS = {
|
|
49
|
+
retryFilterPolicy: handleWhen(isRetryableError),
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* Data service for the Subscription API.
|
|
53
|
+
*
|
|
54
|
+
* All requests are authenticated via JWT Bearer tokens obtained from the
|
|
55
|
+
* `AuthenticationController:getBearerToken` messenger action. Cached queries
|
|
56
|
+
* are scoped by `profileId` from
|
|
57
|
+
* `AuthenticationController:getSessionProfile`.
|
|
58
|
+
*/
|
|
59
|
+
export class SubscriptionService extends BaseDataService {
|
|
60
|
+
constructor({ messenger, fetchFunction = globalThis.fetch, env = Env.PRD, captureException, queryClientConfig = {}, policyOptions = {}, }) {
|
|
61
|
+
super({
|
|
62
|
+
name: serviceName,
|
|
63
|
+
messenger,
|
|
64
|
+
queryClientConfig,
|
|
65
|
+
policyOptions: { ...DEFAULT_POLICY_OPTIONS, ...policyOptions },
|
|
66
|
+
});
|
|
20
67
|
_SubscriptionService_instances.add(this);
|
|
21
68
|
_SubscriptionService_env.set(this, void 0);
|
|
22
69
|
_SubscriptionService_fetch.set(this, void 0);
|
|
23
70
|
_SubscriptionService_captureException.set(this, void 0);
|
|
24
|
-
__classPrivateFieldSet(this, _SubscriptionService_env,
|
|
25
|
-
this
|
|
26
|
-
__classPrivateFieldSet(this,
|
|
27
|
-
|
|
71
|
+
__classPrivateFieldSet(this, _SubscriptionService_env, env, "f");
|
|
72
|
+
__classPrivateFieldSet(this, _SubscriptionService_fetch, fetchFunction, "f");
|
|
73
|
+
__classPrivateFieldSet(this, _SubscriptionService_captureException, captureException, "f");
|
|
74
|
+
this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
|
|
28
75
|
}
|
|
76
|
+
/**
|
|
77
|
+
* Fetches the user's subscriptions.
|
|
78
|
+
*
|
|
79
|
+
* @returns The subscriptions response.
|
|
80
|
+
*/
|
|
29
81
|
async getSubscriptions() {
|
|
30
|
-
const
|
|
31
|
-
|
|
32
|
-
|
|
82
|
+
const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
|
|
83
|
+
const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
|
|
84
|
+
profileKey,
|
|
85
|
+
bearerToken,
|
|
86
|
+
methodName: 'getSubscriptions',
|
|
87
|
+
requestParams: null,
|
|
88
|
+
path: 'subscriptions',
|
|
33
89
|
errorMessage: SubscriptionServiceErrorMessage.FailedToGetSubscriptions,
|
|
34
90
|
});
|
|
91
|
+
return create(jsonResponse, GetSubscriptionsResponseStruct);
|
|
35
92
|
}
|
|
93
|
+
/**
|
|
94
|
+
* Cancels a subscription.
|
|
95
|
+
*
|
|
96
|
+
* @param params - The cancel subscription request.
|
|
97
|
+
* @returns The updated subscription.
|
|
98
|
+
*/
|
|
36
99
|
async cancelSubscription(params) {
|
|
100
|
+
const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
|
|
37
101
|
const path = `subscriptions/${params.subscriptionId}/cancel`;
|
|
38
|
-
|
|
102
|
+
const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
|
|
103
|
+
profileKey,
|
|
104
|
+
bearerToken,
|
|
105
|
+
methodName: 'cancelSubscription',
|
|
106
|
+
requestParams: params,
|
|
39
107
|
path,
|
|
40
108
|
method: 'POST',
|
|
41
109
|
body: {
|
|
@@ -43,40 +111,87 @@ export class SubscriptionService {
|
|
|
43
111
|
},
|
|
44
112
|
errorMessage: SubscriptionServiceErrorMessage.FailedToCancelSubscription,
|
|
45
113
|
});
|
|
114
|
+
return create(jsonResponse, SubscriptionStruct);
|
|
46
115
|
}
|
|
116
|
+
/**
|
|
117
|
+
* Reverses a pending subscription cancellation.
|
|
118
|
+
*
|
|
119
|
+
* @param params - The uncancel subscription request.
|
|
120
|
+
* @param params.subscriptionId - The subscription ID to uncancel.
|
|
121
|
+
* @returns The updated subscription.
|
|
122
|
+
*/
|
|
47
123
|
async unCancelSubscription(params) {
|
|
124
|
+
const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
|
|
48
125
|
const path = `subscriptions/${params.subscriptionId}/uncancel`;
|
|
49
|
-
|
|
126
|
+
const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
|
|
127
|
+
profileKey,
|
|
128
|
+
bearerToken,
|
|
129
|
+
methodName: 'unCancelSubscription',
|
|
130
|
+
requestParams: params,
|
|
50
131
|
path,
|
|
51
132
|
method: 'POST',
|
|
52
133
|
body: {},
|
|
53
134
|
errorMessage: SubscriptionServiceErrorMessage.FailedToUncancelSubscription,
|
|
54
135
|
});
|
|
136
|
+
return create(jsonResponse, SubscriptionStruct);
|
|
55
137
|
}
|
|
138
|
+
/**
|
|
139
|
+
* Starts a subscription with a card payment method.
|
|
140
|
+
*
|
|
141
|
+
* @param request - The start subscription request.
|
|
142
|
+
* @returns The checkout session response.
|
|
143
|
+
*/
|
|
56
144
|
async startSubscriptionWithCard(request) {
|
|
57
145
|
if (request.products.length === 0) {
|
|
58
146
|
throw new SubscriptionServiceError(SubscriptionControllerErrorMessage.SubscriptionProductsEmpty);
|
|
59
147
|
}
|
|
60
|
-
const
|
|
61
|
-
|
|
62
|
-
|
|
148
|
+
const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
|
|
149
|
+
const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
|
|
150
|
+
profileKey,
|
|
151
|
+
bearerToken,
|
|
152
|
+
methodName: 'startSubscriptionWithCard',
|
|
153
|
+
requestParams: request,
|
|
154
|
+
path: 'subscriptions/card',
|
|
63
155
|
method: 'POST',
|
|
64
156
|
body: request,
|
|
65
157
|
errorMessage: SubscriptionServiceErrorMessage.FailedToStartSubscriptionWithCard,
|
|
66
158
|
});
|
|
159
|
+
return create(jsonResponse, StartSubscriptionResponseStruct);
|
|
67
160
|
}
|
|
161
|
+
/**
|
|
162
|
+
* Starts a subscription with a crypto payment method.
|
|
163
|
+
*
|
|
164
|
+
* @param request - The start crypto subscription request.
|
|
165
|
+
* @returns The created subscription response.
|
|
166
|
+
*/
|
|
68
167
|
async startSubscriptionWithCrypto(request) {
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
|
|
168
|
+
const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
|
|
169
|
+
const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
|
|
170
|
+
profileKey,
|
|
171
|
+
bearerToken,
|
|
172
|
+
methodName: 'startSubscriptionWithCrypto',
|
|
173
|
+
requestParams: request,
|
|
174
|
+
path: 'subscriptions/crypto',
|
|
72
175
|
method: 'POST',
|
|
73
176
|
body: request,
|
|
74
177
|
errorMessage: SubscriptionServiceErrorMessage.FailedToStartSubscriptionWithCrypto,
|
|
75
178
|
});
|
|
179
|
+
return create(jsonResponse, StartCryptoSubscriptionResponseStruct);
|
|
76
180
|
}
|
|
181
|
+
/**
|
|
182
|
+
* Updates a subscription's card payment method.
|
|
183
|
+
*
|
|
184
|
+
* @param request - The update payment method request.
|
|
185
|
+
* @returns The redirect URL response.
|
|
186
|
+
*/
|
|
77
187
|
async updatePaymentMethodCard(request) {
|
|
188
|
+
const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
|
|
78
189
|
const path = `subscriptions/${request.subscriptionId}/payment-method/card`;
|
|
79
|
-
|
|
190
|
+
const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
|
|
191
|
+
profileKey,
|
|
192
|
+
bearerToken,
|
|
193
|
+
methodName: 'updatePaymentMethodCard',
|
|
194
|
+
requestParams: request,
|
|
80
195
|
path,
|
|
81
196
|
method: 'PATCH',
|
|
82
197
|
body: {
|
|
@@ -85,10 +200,21 @@ export class SubscriptionService {
|
|
|
85
200
|
},
|
|
86
201
|
errorMessage: SubscriptionServiceErrorMessage.FailedToUpdatePaymentMethodCard,
|
|
87
202
|
});
|
|
203
|
+
return create(jsonResponse, UpdatePaymentMethodCardResponseStruct);
|
|
88
204
|
}
|
|
205
|
+
/**
|
|
206
|
+
* Updates a subscription's crypto payment method.
|
|
207
|
+
*
|
|
208
|
+
* @param request - The update payment method request.
|
|
209
|
+
*/
|
|
89
210
|
async updatePaymentMethodCrypto(request) {
|
|
211
|
+
const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
|
|
90
212
|
const path = `subscriptions/${request.subscriptionId}/payment-method/crypto`;
|
|
91
|
-
await __classPrivateFieldGet(this, _SubscriptionService_instances, "m",
|
|
213
|
+
await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
|
|
214
|
+
profileKey,
|
|
215
|
+
bearerToken,
|
|
216
|
+
methodName: 'updatePaymentMethodCrypto',
|
|
217
|
+
requestParams: request,
|
|
92
218
|
path,
|
|
93
219
|
method: 'PATCH',
|
|
94
220
|
body: {
|
|
@@ -105,23 +231,28 @@ export class SubscriptionService {
|
|
|
105
231
|
* @returns The eligibility for a shield subscription
|
|
106
232
|
*/
|
|
107
233
|
async getSubscriptionsEligibilities(request) {
|
|
108
|
-
const
|
|
109
|
-
let
|
|
234
|
+
const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
|
|
235
|
+
let queryParams;
|
|
110
236
|
if (request?.balanceCategory !== undefined) {
|
|
111
|
-
|
|
237
|
+
queryParams = { balanceCategory: request.balanceCategory };
|
|
112
238
|
}
|
|
113
|
-
const
|
|
114
|
-
|
|
115
|
-
|
|
239
|
+
const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
|
|
240
|
+
profileKey,
|
|
241
|
+
bearerToken,
|
|
242
|
+
methodName: 'getSubscriptionsEligibilities',
|
|
243
|
+
requestParams: request ?? null,
|
|
244
|
+
path: 'subscriptions/eligibility',
|
|
245
|
+
queryParams,
|
|
116
246
|
errorMessage: SubscriptionServiceErrorMessage.FailedToGetSubscriptionsEligibilities,
|
|
117
247
|
});
|
|
248
|
+
const results = create(jsonResponse, SubscriptionEligibilityArrayStruct);
|
|
118
249
|
return results.map((result) => ({
|
|
119
250
|
...result,
|
|
120
|
-
canSubscribe: result.canSubscribe
|
|
121
|
-
canViewEntryModal: result.canViewEntryModal
|
|
122
|
-
cohorts: result.cohorts
|
|
251
|
+
canSubscribe: result.canSubscribe ?? false,
|
|
252
|
+
canViewEntryModal: result.canViewEntryModal ?? false,
|
|
253
|
+
cohorts: result.cohorts ?? [],
|
|
123
254
|
assignedCohort: result.assignedCohort ?? null,
|
|
124
|
-
hasAssignedCohortExpired: result.hasAssignedCohortExpired
|
|
255
|
+
hasAssignedCohortExpired: result.hasAssignedCohortExpired ?? false,
|
|
125
256
|
}));
|
|
126
257
|
}
|
|
127
258
|
/**
|
|
@@ -131,9 +262,13 @@ export class SubscriptionService {
|
|
|
131
262
|
* @example { event: SubscriptionUserEvent.ShieldEntryModalViewed, cohort: 'post_tx' }
|
|
132
263
|
*/
|
|
133
264
|
async submitUserEvent(request) {
|
|
134
|
-
const
|
|
135
|
-
await __classPrivateFieldGet(this, _SubscriptionService_instances, "m",
|
|
136
|
-
|
|
265
|
+
const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
|
|
266
|
+
await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
|
|
267
|
+
profileKey,
|
|
268
|
+
bearerToken,
|
|
269
|
+
methodName: 'submitUserEvent',
|
|
270
|
+
requestParams: request,
|
|
271
|
+
path: 'user-events',
|
|
137
272
|
method: 'POST',
|
|
138
273
|
body: request,
|
|
139
274
|
errorMessage: SubscriptionServiceErrorMessage.FailedToSubmitUserEvent,
|
|
@@ -146,9 +281,13 @@ export class SubscriptionService {
|
|
|
146
281
|
* @example { cohort: 'post_tx' }
|
|
147
282
|
*/
|
|
148
283
|
async assignUserToCohort(request) {
|
|
149
|
-
const
|
|
150
|
-
await __classPrivateFieldGet(this, _SubscriptionService_instances, "m",
|
|
151
|
-
|
|
284
|
+
const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
|
|
285
|
+
await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
|
|
286
|
+
profileKey,
|
|
287
|
+
bearerToken,
|
|
288
|
+
methodName: 'assignUserToCohort',
|
|
289
|
+
requestParams: request,
|
|
290
|
+
path: 'cohorts/assign',
|
|
152
291
|
method: 'POST',
|
|
153
292
|
body: request,
|
|
154
293
|
errorMessage: SubscriptionServiceErrorMessage.FailedToAssignUserToCohort,
|
|
@@ -164,9 +303,13 @@ export class SubscriptionService {
|
|
|
164
303
|
* @example { address: '0x1234567890123456789012345678901234567890', products: [ProductType.Shield] }
|
|
165
304
|
*/
|
|
166
305
|
async submitSponsorshipIntents(request) {
|
|
167
|
-
const
|
|
168
|
-
await __classPrivateFieldGet(this, _SubscriptionService_instances, "m",
|
|
169
|
-
|
|
306
|
+
const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
|
|
307
|
+
await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
|
|
308
|
+
profileKey,
|
|
309
|
+
bearerToken,
|
|
310
|
+
methodName: 'submitSponsorshipIntents',
|
|
311
|
+
requestParams: request,
|
|
312
|
+
path: 'transaction-sponsorship/intents',
|
|
170
313
|
method: 'POST',
|
|
171
314
|
body: request,
|
|
172
315
|
errorMessage: SubscriptionServiceErrorMessage.FailedToSubmitSponsorshipIntents,
|
|
@@ -180,80 +323,106 @@ export class SubscriptionService {
|
|
|
180
323
|
* @returns The response from the API.
|
|
181
324
|
*/
|
|
182
325
|
async linkRewards(request) {
|
|
183
|
-
const
|
|
184
|
-
|
|
185
|
-
|
|
326
|
+
const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
|
|
327
|
+
const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
|
|
328
|
+
profileKey,
|
|
329
|
+
bearerToken,
|
|
330
|
+
methodName: 'linkRewards',
|
|
331
|
+
requestParams: request,
|
|
332
|
+
path: 'rewards/link',
|
|
186
333
|
method: 'POST',
|
|
187
334
|
body: request,
|
|
188
335
|
errorMessage: SubscriptionServiceErrorMessage.FailedToLinkRewards,
|
|
189
336
|
});
|
|
337
|
+
return create(jsonResponse, SubscriptionApiGeneralResponseStruct);
|
|
190
338
|
}
|
|
339
|
+
/**
|
|
340
|
+
* Fetches subscription pricing information.
|
|
341
|
+
*
|
|
342
|
+
* @returns The pricing response.
|
|
343
|
+
*/
|
|
191
344
|
async getPricing() {
|
|
192
|
-
const
|
|
193
|
-
|
|
194
|
-
|
|
345
|
+
const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
|
|
346
|
+
const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
|
|
347
|
+
profileKey,
|
|
348
|
+
bearerToken,
|
|
349
|
+
methodName: 'getPricing',
|
|
350
|
+
requestParams: null,
|
|
351
|
+
path: 'pricing',
|
|
195
352
|
errorMessage: SubscriptionServiceErrorMessage.FailedToGetPricing,
|
|
196
353
|
});
|
|
354
|
+
return create(jsonResponse, PricingResponseStruct);
|
|
197
355
|
}
|
|
356
|
+
/**
|
|
357
|
+
* Fetches the billing portal URL.
|
|
358
|
+
*
|
|
359
|
+
* @returns The billing portal response.
|
|
360
|
+
*/
|
|
198
361
|
async getBillingPortalUrl() {
|
|
199
|
-
const
|
|
200
|
-
|
|
201
|
-
|
|
362
|
+
const { profileKey, bearerToken } = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthenticatedContext).call(this);
|
|
363
|
+
const jsonResponse = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_fetchJson).call(this, {
|
|
364
|
+
profileKey,
|
|
365
|
+
bearerToken,
|
|
366
|
+
methodName: 'getBillingPortalUrl',
|
|
367
|
+
requestParams: null,
|
|
368
|
+
path: 'billing-portal',
|
|
202
369
|
errorMessage: SubscriptionServiceErrorMessage.FailedToGetBillingPortalUrl,
|
|
203
370
|
});
|
|
371
|
+
return create(jsonResponse, BillingPortalResponseStruct);
|
|
204
372
|
}
|
|
205
373
|
}
|
|
206
|
-
_SubscriptionService_env = new WeakMap(), _SubscriptionService_fetch = new WeakMap(), _SubscriptionService_captureException = new WeakMap(), _SubscriptionService_instances = new WeakSet(),
|
|
207
|
-
/**
|
|
208
|
-
* Makes a request to the Subscription Service backend.
|
|
209
|
-
*
|
|
210
|
-
* @param params - The request object containing the path, method, body, query parameters, and error message.
|
|
211
|
-
* @param params.path - The path of the request.
|
|
212
|
-
* @param params.method - The method of the request.
|
|
213
|
-
* @param params.body - The body of the request.
|
|
214
|
-
* @param params.queryParams - The query parameters of the request.
|
|
215
|
-
* @param params.errorMessage - The error message to throw if the request fails.
|
|
216
|
-
* @returns The result of the request.
|
|
217
|
-
*/
|
|
218
|
-
async function _SubscriptionService_makeRequest({ path, method = 'GET', body, queryParams, errorMessage, }) {
|
|
374
|
+
_SubscriptionService_env = new WeakMap(), _SubscriptionService_fetch = new WeakMap(), _SubscriptionService_captureException = new WeakMap(), _SubscriptionService_instances = new WeakSet(), _SubscriptionService_fetchJson = async function _SubscriptionService_fetchJson({ profileKey, bearerToken, methodName, requestParams, path, method = 'GET', body, queryParams, errorMessage, }) {
|
|
219
375
|
const url = __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getSubscriptionApiUrl).call(this, path);
|
|
220
|
-
|
|
376
|
+
if (queryParams) {
|
|
377
|
+
Object.entries(queryParams).forEach(([key, value]) => {
|
|
378
|
+
url.searchParams.append(key, value);
|
|
379
|
+
});
|
|
380
|
+
}
|
|
221
381
|
try {
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
382
|
+
return await this.fetchQuery({
|
|
383
|
+
queryKey: [
|
|
384
|
+
`${this.name}:${methodName}`,
|
|
385
|
+
profileKey,
|
|
386
|
+
requestParams,
|
|
387
|
+
],
|
|
388
|
+
staleTime: 0,
|
|
389
|
+
cacheTime: 0,
|
|
390
|
+
queryFn: async () => {
|
|
391
|
+
const response = await __classPrivateFieldGet(this, _SubscriptionService_fetch, "f").call(this, url.toString(), {
|
|
392
|
+
method,
|
|
393
|
+
headers: {
|
|
394
|
+
'Content-Type': 'application/json',
|
|
395
|
+
...__classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_headersForToken).call(this, bearerToken),
|
|
396
|
+
},
|
|
397
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
398
|
+
});
|
|
399
|
+
if (!response.ok) {
|
|
400
|
+
const apiError = await getSubscriptionErrorFromResponse(response);
|
|
401
|
+
throw new HttpError(response.status, apiError.message);
|
|
402
|
+
}
|
|
403
|
+
return response.json();
|
|
232
404
|
},
|
|
233
|
-
body: body ? JSON.stringify(body) : undefined,
|
|
234
405
|
});
|
|
235
|
-
if (!response.ok) {
|
|
236
|
-
const error = await getSubscriptionErrorFromResponse(response);
|
|
237
|
-
throw error;
|
|
238
|
-
}
|
|
239
|
-
const data = await response.json();
|
|
240
|
-
return data;
|
|
241
406
|
}
|
|
242
407
|
catch (error) {
|
|
243
408
|
log(errorMessage, error);
|
|
244
409
|
const errorMessageWithUrl = `${errorMessage} (url: ${url.toString()})`;
|
|
245
410
|
const errorToCapture = error instanceof Error ? error : new Error(errorMessage);
|
|
246
411
|
__classPrivateFieldGet(this, _SubscriptionService_captureException, "f")?.call(this, createSentryError(errorMessageWithUrl, errorToCapture));
|
|
412
|
+
if (error instanceof SubscriptionServiceError) {
|
|
413
|
+
throw error;
|
|
414
|
+
}
|
|
247
415
|
throw new SubscriptionServiceError(`Failed to make request. ${errorMessageWithUrl}`, {
|
|
248
416
|
cause: errorToCapture,
|
|
249
417
|
});
|
|
250
418
|
}
|
|
251
|
-
},
|
|
252
|
-
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
253
|
-
async function _SubscriptionService_getAuthorizationHeader() {
|
|
419
|
+
}, _SubscriptionService_getAuthenticatedContext = async function _SubscriptionService_getAuthenticatedContext() {
|
|
254
420
|
try {
|
|
255
|
-
const
|
|
256
|
-
|
|
421
|
+
const [bearerToken, sessionProfile] = await Promise.all([
|
|
422
|
+
this.messenger.call('AuthenticationController:getBearerToken'),
|
|
423
|
+
this.messenger.call('AuthenticationController:getSessionProfile'),
|
|
424
|
+
]);
|
|
425
|
+
return { profileKey: sessionProfile.profileId, bearerToken };
|
|
257
426
|
}
|
|
258
427
|
catch (error) {
|
|
259
428
|
const errorMessage = error instanceof Error
|
|
@@ -264,10 +433,11 @@ async function _SubscriptionService_getAuthorizationHeader() {
|
|
|
264
433
|
cause: error instanceof Error ? error : new Error(errorMessage),
|
|
265
434
|
});
|
|
266
435
|
}
|
|
436
|
+
}, _SubscriptionService_headersForToken = function _SubscriptionService_headersForToken(bearerToken) {
|
|
437
|
+
return { Authorization: `Bearer ${bearerToken}` };
|
|
267
438
|
}, _SubscriptionService_getSubscriptionApiUrl = function _SubscriptionService_getSubscriptionApiUrl(path) {
|
|
268
439
|
try {
|
|
269
|
-
|
|
270
|
-
return url;
|
|
440
|
+
return new URL(SUBSCRIPTION_URL(__classPrivateFieldGet(this, _SubscriptionService_env, "f"), path));
|
|
271
441
|
}
|
|
272
442
|
catch (error) {
|
|
273
443
|
const errorMessage = error instanceof Error
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriptionService.mjs","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EACL,UAAU,EACV,kCAAkC,EAClC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KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,YAAY,CAAC;SAChE,CACF,CAAC;IACJ,CAAC;AACH,CAAC,mGAEsB,IAAY;IACjC,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,gBAAgB,CAAC,uBAAA,IAAI,gCAAK,EAAE,IAAI,CAAC,CAAC,CAAC;QACvD,OAAO,GAAG,CAAC;IACb,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,YAAY,GAChB,KAAK,YAAY,KAAK;YACpB,CAAC,CAAC,KAAK,CAAC,OAAO;YACf,CAAC,CAAC,iDAAiD,CAAC;QACxD,uBAAA,IAAI,6CAAkB,EAAE,KAAxB,IAAI,EACF,iBAAiB,CACf,uCAAuC,YAAY,EAAE,EACrD,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,YAAY,CAAC,CACzD,CACF,CAAC;QAEF,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import {\n getEnvUrls,\n SubscriptionControllerErrorMessage,\n SubscriptionServiceErrorMessage,\n} from './constants.js';\nimport type { Env } from './constants.js';\nimport {\n createSentryError,\n getSubscriptionErrorFromResponse,\n SubscriptionServiceError,\n} from './errors.js';\nimport { createModuleLogger, projectLogger } from './logger.js';\nimport type {\n AssignCohortRequest,\n AuthUtils,\n BillingPortalResponse,\n GetSubscriptionsEligibilitiesRequest,\n GetSubscriptionsResponse,\n ISubscriptionService,\n PricingResponse,\n SubscriptionEligibility,\n StartCryptoSubscriptionRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionRequest,\n StartSubscriptionResponse,\n SubmitUserEventRequest,\n Subscription,\n UpdatePaymentMethodCardRequest,\n UpdatePaymentMethodCardResponse,\n UpdatePaymentMethodCryptoRequest,\n SubmitSponsorshipIntentsRequest,\n LinkRewardsRequest,\n SubscriptionApiGeneralResponse,\n CancelSubscriptionRequest,\n} from './types.js';\n\nexport type SubscriptionServiceConfig = {\n env: Env;\n auth: AuthUtils;\n fetchFunction: typeof fetch;\n captureException?: (error: Error) => void;\n};\n\nexport const SUBSCRIPTION_URL = (env: Env, path: string): string =>\n `${getEnvUrls(env).subscriptionApiUrl}/v1/${path}`;\n\nconst log = createModuleLogger(projectLogger, 'SubscriptionService');\n\nexport class SubscriptionService implements ISubscriptionService {\n readonly #env: Env;\n\n readonly #fetch: typeof fetch;\n\n readonly #captureException?: (error: Error) => void;\n\n public authUtils: AuthUtils;\n\n constructor(config: SubscriptionServiceConfig) {\n this.#env = config.env;\n this.authUtils = config.auth;\n this.#fetch = config.fetchFunction;\n this.#captureException = config.captureException;\n }\n\n async getSubscriptions(): Promise<GetSubscriptionsResponse> {\n const path = 'subscriptions';\n return await this.#makeRequest<GetSubscriptionsResponse>({\n path,\n errorMessage: SubscriptionServiceErrorMessage.FailedToGetSubscriptions,\n });\n }\n\n async cancelSubscription(\n params: CancelSubscriptionRequest,\n ): Promise<Subscription> {\n const path = `subscriptions/${params.subscriptionId}/cancel`;\n return await this.#makeRequest<Subscription>({\n path,\n method: 'POST',\n body: {\n cancelAtPeriodEnd: params.cancelAtPeriodEnd,\n },\n errorMessage: SubscriptionServiceErrorMessage.FailedToCancelSubscription,\n });\n }\n\n async unCancelSubscription(params: {\n subscriptionId: string;\n }): Promise<Subscription> {\n const path = `subscriptions/${params.subscriptionId}/uncancel`;\n return await this.#makeRequest<Subscription>({\n path,\n method: 'POST',\n body: {},\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToUncancelSubscription,\n });\n }\n\n async startSubscriptionWithCard(\n request: StartSubscriptionRequest,\n ): Promise<StartSubscriptionResponse> {\n if (request.products.length === 0) {\n throw new SubscriptionServiceError(\n SubscriptionControllerErrorMessage.SubscriptionProductsEmpty,\n );\n }\n const path = 'subscriptions/card';\n\n return await this.#makeRequest<StartSubscriptionResponse>({\n path,\n method: 'POST',\n body: request,\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToStartSubscriptionWithCard,\n });\n }\n\n async startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse> {\n const path = 'subscriptions/crypto';\n return await this.#makeRequest<StartCryptoSubscriptionResponse>({\n path,\n method: 'POST',\n body: request,\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToStartSubscriptionWithCrypto,\n });\n }\n\n async updatePaymentMethodCard(\n request: UpdatePaymentMethodCardRequest,\n ): Promise<UpdatePaymentMethodCardResponse> {\n const path = `subscriptions/${request.subscriptionId}/payment-method/card`;\n return await this.#makeRequest<UpdatePaymentMethodCardResponse>({\n path,\n method: 'PATCH',\n body: {\n ...request,\n subscriptionId: undefined,\n },\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToUpdatePaymentMethodCard,\n });\n }\n\n async updatePaymentMethodCrypto(\n request: UpdatePaymentMethodCryptoRequest,\n ): Promise<void> {\n const path = `subscriptions/${request.subscriptionId}/payment-method/crypto`;\n await this.#makeRequest({\n path,\n method: 'PATCH',\n body: {\n ...request,\n subscriptionId: undefined,\n },\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToUpdatePaymentMethodCrypto,\n });\n }\n\n /**\n * Get the eligibility for a shield subscription.\n *\n * @param request - Optional request object containing user balance category to check cohort eligibility\n * @returns The eligibility for a shield subscription\n */\n async getSubscriptionsEligibilities(\n request?: GetSubscriptionsEligibilitiesRequest,\n ): Promise<SubscriptionEligibility[]> {\n const path = 'subscriptions/eligibility';\n let query: Record<string, string> | undefined;\n if (request?.balanceCategory !== undefined) {\n query = { balanceCategory: request.balanceCategory };\n }\n const results = await this.#makeRequest<SubscriptionEligibility[]>({\n path,\n queryParams: query,\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToGetSubscriptionsEligibilities,\n });\n\n return results.map((result) => ({\n ...result,\n canSubscribe: result.canSubscribe || false,\n canViewEntryModal: result.canViewEntryModal || false,\n cohorts: result.cohorts || [],\n assignedCohort: result.assignedCohort ?? null,\n hasAssignedCohortExpired: result.hasAssignedCohortExpired || false,\n }));\n }\n\n /**\n * Submit a user event. (e.g. shield modal viewed)\n *\n * @param request - Request object containing the event to submit.\n * @example { event: SubscriptionUserEvent.ShieldEntryModalViewed, cohort: 'post_tx' }\n */\n async submitUserEvent(request: SubmitUserEventRequest): Promise<void> {\n const path = 'user-events';\n await this.#makeRequest({\n path,\n method: 'POST',\n body: request,\n errorMessage: SubscriptionServiceErrorMessage.FailedToSubmitUserEvent,\n });\n }\n\n /**\n * Assign user to a cohort.\n *\n * @param request - Request object containing the cohort to assign the user to.\n * @example { cohort: 'post_tx' }\n */\n async assignUserToCohort(request: AssignCohortRequest): Promise<void> {\n const path = 'cohorts/assign';\n await this.#makeRequest({\n path,\n method: 'POST',\n body: request,\n errorMessage: SubscriptionServiceErrorMessage.FailedToAssignUserToCohort,\n });\n }\n\n /**\n * Submit sponsorship intents to the Subscription Service backend.\n *\n * This is intended to be used together with the crypto subscription flow.\n * When the user has enabled the smart transaction feature, we will sponsor the gas fees for the subscription approval transaction.\n *\n * @param request - Request object containing the address and products.\n * @example { address: '0x1234567890123456789012345678901234567890', products: [ProductType.Shield] }\n */\n async submitSponsorshipIntents(\n request: SubmitSponsorshipIntentsRequest,\n ): Promise<void> {\n const path = 'transaction-sponsorship/intents';\n await this.#makeRequest({\n path,\n method: 'POST',\n body: request,\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToSubmitSponsorshipIntents,\n });\n }\n\n /**\n * Link rewards to a subscription.\n *\n * @param request - Request object containing the reward account ID.\n * @example { rewardAccountId: 'eip155:1:0x1234567890123456789012345678901234567890' }\n * @returns The response from the API.\n */\n async linkRewards(\n request: LinkRewardsRequest,\n ): Promise<SubscriptionApiGeneralResponse> {\n const path = 'rewards/link';\n return await this.#makeRequest<SubscriptionApiGeneralResponse>({\n path,\n method: 'POST',\n body: request,\n errorMessage: SubscriptionServiceErrorMessage.FailedToLinkRewards,\n });\n }\n\n async getPricing(): Promise<PricingResponse> {\n const path = 'pricing';\n return await this.#makeRequest<PricingResponse>({\n path,\n errorMessage: SubscriptionServiceErrorMessage.FailedToGetPricing,\n });\n }\n\n async getBillingPortalUrl(): Promise<BillingPortalResponse> {\n const path = 'billing-portal';\n return await this.#makeRequest<BillingPortalResponse>({\n path,\n errorMessage: SubscriptionServiceErrorMessage.FailedToGetBillingPortalUrl,\n });\n }\n\n /**\n * Makes a request to the Subscription Service backend.\n *\n * @param params - The request object containing the path, method, body, query parameters, and error message.\n * @param params.path - The path of the request.\n * @param params.method - The method of the request.\n * @param params.body - The body of the request.\n * @param params.queryParams - The query parameters of the request.\n * @param params.errorMessage - The error message to throw if the request fails.\n * @returns The result of the request.\n */\n async #makeRequest<Result>({\n path,\n method = 'GET',\n body,\n queryParams,\n errorMessage,\n }: {\n path: string;\n method?: 'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH';\n body?: Record<string, unknown>;\n queryParams?: Record<string, string>;\n errorMessage: string;\n }): Promise<Result> {\n const url = this.#getSubscriptionApiUrl(path);\n const headers = await this.#getAuthorizationHeader();\n\n try {\n if (queryParams) {\n Object.entries(queryParams).forEach(([key, value]) => {\n url.searchParams.append(key, value);\n });\n }\n\n const response = await this.#fetch(url.toString(), {\n method,\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!response.ok) {\n const error = await getSubscriptionErrorFromResponse(response);\n throw error;\n }\n\n const data = await response.json();\n return data;\n } catch (error) {\n log(errorMessage, error);\n\n const errorMessageWithUrl = `${errorMessage} (url: ${url.toString()})`;\n const errorToCapture =\n error instanceof Error ? error : new Error(errorMessage);\n this.#captureException?.(\n createSentryError(errorMessageWithUrl, errorToCapture),\n );\n\n throw new SubscriptionServiceError(\n `Failed to make request. ${errorMessageWithUrl}`,\n {\n cause: errorToCapture,\n },\n );\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/naming-convention\n async #getAuthorizationHeader(): Promise<{ Authorization: string }> {\n try {\n const accessToken = await this.authUtils.getAccessToken();\n return { Authorization: `Bearer ${accessToken}` };\n } catch (error) {\n const errorMessage =\n error instanceof Error\n ? error.message\n : 'Unknown error when getting authorization header';\n\n this.#captureException?.(\n createSentryError(\n `Failed to get authorization header. ${errorMessage}`,\n error instanceof Error ? error : new Error(errorMessage),\n ),\n );\n\n throw new SubscriptionServiceError(\n `Failed to get authorization header. ${errorMessage}`,\n {\n cause: error instanceof Error ? error : new Error(errorMessage),\n },\n );\n }\n }\n\n #getSubscriptionApiUrl(path: string): URL {\n try {\n const url = new URL(SUBSCRIPTION_URL(this.#env, path));\n return url;\n } catch (error) {\n const errorMessage =\n error instanceof Error\n ? error.message\n : 'Unknown error when getting subscription API URL';\n this.#captureException?.(\n createSentryError(\n `Failed to get subscription API URL. ${errorMessage}`,\n error instanceof Error ? error : new Error(errorMessage),\n ),\n );\n\n throw error;\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"SubscriptionService.mjs","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":";;;;;;;;;;;;AAKA,OAAO,EAAE,eAAe,EAAE,oCAAoC;AAE9D,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,mCAAmC;AAGnE,OAAO,EAAE,MAAM,EAAE,8BAA8B;AAI/C,OAAO,EACL,GAAG,EACH,UAAU,EACV,kCAAkC,EAClC,+BAA+B,EAChC,wBAAuB;AACxB,OAAO,EACL,iBAAiB,EACjB,gCAAgC,EAChC,wBAAwB,EACzB,qBAAoB;AACrB,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,qBAAoB;AAEhE,OAAO,EACL,2BAA2B,EAC3B,8BAA8B,EAC9B,qBAAqB,EACrB,qCAAqC,EACrC,+BAA+B,EAC/B,oCAAoC,EACpC,kCAAkC,EAClC,kBAAkB,EAClB,qCAAqC,EACtC,0CAAyC;AAuB1C,MAAM,CAAC,MAAM,WAAW,GAAG,qBAAqB,CAAC;AAEj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AAC,IAAI,KAAK,CAAC,YAAY,CAAC,CACzD,CACF,CAAC;QAEF,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import type {\n DataServiceCacheUpdatedEvent,\n DataServiceGranularCacheUpdatedEvent,\n DataServiceInvalidateQueriesAction,\n} from '@metamask/base-data-service';\nimport { BaseDataService } from '@metamask/base-data-service';\nimport type { CreateServicePolicyOptions } from '@metamask/controller-utils';\nimport { handleWhen, HttpError } from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\nimport { create } from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport type { QueryClientConfig } from '@tanstack/query-core';\n\nimport {\n Env,\n getEnvUrls,\n SubscriptionControllerErrorMessage,\n SubscriptionServiceErrorMessage,\n} from './constants.js';\nimport {\n createSentryError,\n getSubscriptionErrorFromResponse,\n SubscriptionServiceError,\n} from './errors.js';\nimport { createModuleLogger, projectLogger } from './logger.js';\nimport type { SubscriptionServiceMethodActions } from './SubscriptionService-method-action-types.js';\nimport {\n BillingPortalResponseStruct,\n GetSubscriptionsResponseStruct,\n PricingResponseStruct,\n StartCryptoSubscriptionResponseStruct,\n StartSubscriptionResponseStruct,\n SubscriptionApiGeneralResponseStruct,\n SubscriptionEligibilityArrayStruct,\n SubscriptionStruct,\n UpdatePaymentMethodCardResponseStruct,\n} from './SubscriptionService-structs.js';\nimport type {\n AssignCohortRequest,\n BillingPortalResponse,\n CancelSubscriptionRequest,\n GetSubscriptionsEligibilitiesRequest,\n GetSubscriptionsResponse,\n LinkRewardsRequest,\n PricingResponse,\n StartCryptoSubscriptionRequest,\n StartCryptoSubscriptionResponse,\n StartSubscriptionRequest,\n StartSubscriptionResponse,\n SubmitSponsorshipIntentsRequest,\n SubmitUserEventRequest,\n Subscription,\n SubscriptionApiGeneralResponse,\n SubscriptionEligibility,\n UpdatePaymentMethodCardRequest,\n UpdatePaymentMethodCardResponse,\n UpdatePaymentMethodCryptoRequest,\n} from './types.js';\n\nexport const serviceName = 'SubscriptionService';\n\nexport const SUBSCRIPTION_URL = (env: Env, path: string): string =>\n `${getEnvUrls(env).subscriptionApiUrl}/v1/${path}`;\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'getSubscriptions',\n 'cancelSubscription',\n 'unCancelSubscription',\n 'startSubscriptionWithCard',\n 'startSubscriptionWithCrypto',\n 'updatePaymentMethodCard',\n 'updatePaymentMethodCrypto',\n 'getSubscriptionsEligibilities',\n 'submitUserEvent',\n 'assignUserToCohort',\n 'submitSponsorshipIntents',\n 'linkRewards',\n 'getPricing',\n 'getBillingPortalUrl',\n] as const;\n\nexport type SubscriptionServiceInvalidateQueriesAction =\n DataServiceInvalidateQueriesAction<typeof serviceName>;\n\nexport type SubscriptionServiceActions =\n | SubscriptionServiceMethodActions\n | SubscriptionServiceInvalidateQueriesAction;\n\ntype AllowedActions =\n | AuthenticationController.AuthenticationControllerGetBearerTokenAction\n | AuthenticationController.AuthenticationControllerGetSessionProfileAction;\n\ntype AllowedEvents = never;\n\nexport type SubscriptionServiceCacheUpdatedEvent = DataServiceCacheUpdatedEvent<\n typeof serviceName\n>;\n\nexport type SubscriptionServiceGranularCacheUpdatedEvent =\n DataServiceGranularCacheUpdatedEvent<typeof serviceName>;\n\nexport type SubscriptionServiceEvents =\n | SubscriptionServiceCacheUpdatedEvent\n | SubscriptionServiceGranularCacheUpdatedEvent;\n\nexport type SubscriptionServiceMessenger = Messenger<\n typeof serviceName,\n SubscriptionServiceActions | AllowedActions,\n SubscriptionServiceEvents | AllowedEvents\n>;\n\nexport type SubscriptionServiceOptions = {\n messenger: SubscriptionServiceMessenger;\n /**\n * The `fetch` function to use for requests. Defaults to the global `fetch`.\n */\n fetchFunction?: typeof fetch;\n env?: Env;\n captureException?: (error: Error) => void;\n queryClientConfig?: QueryClientConfig;\n policyOptions?: CreateServicePolicyOptions;\n};\n\nconst log = createModuleLogger(projectLogger, 'SubscriptionService');\n\nfunction isRetryableError(error: unknown): boolean {\n if (error instanceof HttpError) {\n if (error.httpStatus === 429) {\n return true;\n }\n return error.httpStatus < 400 || error.httpStatus >= 500;\n }\n return true;\n}\n\nconst DEFAULT_POLICY_OPTIONS: CreateServicePolicyOptions = {\n retryFilterPolicy: handleWhen(isRetryableError),\n};\n\n/**\n * Data service for the Subscription API.\n *\n * All requests are authenticated via JWT Bearer tokens obtained from the\n * `AuthenticationController:getBearerToken` messenger action. Cached queries\n * are scoped by `profileId` from\n * `AuthenticationController:getSessionProfile`.\n */\nexport class SubscriptionService extends BaseDataService<\n typeof serviceName,\n SubscriptionServiceMessenger\n> {\n readonly #env: Env;\n\n readonly #fetch: typeof fetch;\n\n readonly #captureException?: (error: Error) => void;\n\n constructor({\n messenger,\n fetchFunction = globalThis.fetch,\n env = Env.PRD,\n captureException,\n queryClientConfig = {},\n policyOptions = {},\n }: SubscriptionServiceOptions) {\n super({\n name: serviceName,\n messenger,\n queryClientConfig,\n policyOptions: { ...DEFAULT_POLICY_OPTIONS, ...policyOptions },\n });\n\n this.#env = env;\n this.#fetch = fetchFunction;\n this.#captureException = captureException;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Fetches the user's subscriptions.\n *\n * @returns The subscriptions response.\n */\n async getSubscriptions(): Promise<GetSubscriptionsResponse> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'getSubscriptions',\n requestParams: null,\n path: 'subscriptions',\n errorMessage: SubscriptionServiceErrorMessage.FailedToGetSubscriptions,\n });\n\n return create(jsonResponse, GetSubscriptionsResponseStruct);\n }\n\n /**\n * Cancels a subscription.\n *\n * @param params - The cancel subscription request.\n * @returns The updated subscription.\n */\n async cancelSubscription(\n params: CancelSubscriptionRequest,\n ): Promise<Subscription> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const path = `subscriptions/${params.subscriptionId}/cancel`;\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'cancelSubscription',\n requestParams: params,\n path,\n method: 'POST',\n body: {\n cancelAtPeriodEnd: params.cancelAtPeriodEnd,\n },\n errorMessage: SubscriptionServiceErrorMessage.FailedToCancelSubscription,\n });\n\n return create(jsonResponse, SubscriptionStruct);\n }\n\n /**\n * Reverses a pending subscription cancellation.\n *\n * @param params - The uncancel subscription request.\n * @param params.subscriptionId - The subscription ID to uncancel.\n * @returns The updated subscription.\n */\n async unCancelSubscription(params: {\n subscriptionId: string;\n }): Promise<Subscription> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const path = `subscriptions/${params.subscriptionId}/uncancel`;\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'unCancelSubscription',\n requestParams: params,\n path,\n method: 'POST',\n body: {},\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToUncancelSubscription,\n });\n\n return create(jsonResponse, SubscriptionStruct);\n }\n\n /**\n * Starts a subscription with a card payment method.\n *\n * @param request - The start subscription request.\n * @returns The checkout session response.\n */\n async startSubscriptionWithCard(\n request: StartSubscriptionRequest,\n ): Promise<StartSubscriptionResponse> {\n if (request.products.length === 0) {\n throw new SubscriptionServiceError(\n SubscriptionControllerErrorMessage.SubscriptionProductsEmpty,\n );\n }\n\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'startSubscriptionWithCard',\n requestParams: request,\n path: 'subscriptions/card',\n method: 'POST',\n body: request,\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToStartSubscriptionWithCard,\n });\n\n return create(jsonResponse, StartSubscriptionResponseStruct);\n }\n\n /**\n * Starts a subscription with a crypto payment method.\n *\n * @param request - The start crypto subscription request.\n * @returns The created subscription response.\n */\n async startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'startSubscriptionWithCrypto',\n requestParams: request,\n path: 'subscriptions/crypto',\n method: 'POST',\n body: request,\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToStartSubscriptionWithCrypto,\n });\n\n return create(jsonResponse, StartCryptoSubscriptionResponseStruct);\n }\n\n /**\n * Updates a subscription's card payment method.\n *\n * @param request - The update payment method request.\n * @returns The redirect URL response.\n */\n async updatePaymentMethodCard(\n request: UpdatePaymentMethodCardRequest,\n ): Promise<UpdatePaymentMethodCardResponse> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const path = `subscriptions/${request.subscriptionId}/payment-method/card`;\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'updatePaymentMethodCard',\n requestParams: request,\n path,\n method: 'PATCH',\n body: {\n ...request,\n subscriptionId: undefined,\n },\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToUpdatePaymentMethodCard,\n });\n\n return create(jsonResponse, UpdatePaymentMethodCardResponseStruct);\n }\n\n /**\n * Updates a subscription's crypto payment method.\n *\n * @param request - The update payment method request.\n */\n async updatePaymentMethodCrypto(\n request: UpdatePaymentMethodCryptoRequest,\n ): Promise<void> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const path = `subscriptions/${request.subscriptionId}/payment-method/crypto`;\n await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'updatePaymentMethodCrypto',\n requestParams: request,\n path,\n method: 'PATCH',\n body: {\n ...request,\n subscriptionId: undefined,\n },\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToUpdatePaymentMethodCrypto,\n });\n }\n\n /**\n * Get the eligibility for a shield subscription.\n *\n * @param request - Optional request object containing user balance category to check cohort eligibility\n * @returns The eligibility for a shield subscription\n */\n async getSubscriptionsEligibilities(\n request?: GetSubscriptionsEligibilitiesRequest,\n ): Promise<SubscriptionEligibility[]> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n let queryParams: Record<string, string> | undefined;\n if (request?.balanceCategory !== undefined) {\n queryParams = { balanceCategory: request.balanceCategory };\n }\n\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'getSubscriptionsEligibilities',\n requestParams: request ?? null,\n path: 'subscriptions/eligibility',\n queryParams,\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToGetSubscriptionsEligibilities,\n });\n\n const results = create(jsonResponse, SubscriptionEligibilityArrayStruct);\n\n return results.map((result) => ({\n ...result,\n canSubscribe: result.canSubscribe ?? false,\n canViewEntryModal: result.canViewEntryModal ?? false,\n cohorts: result.cohorts ?? [],\n assignedCohort: result.assignedCohort ?? null,\n hasAssignedCohortExpired: result.hasAssignedCohortExpired ?? false,\n }));\n }\n\n /**\n * Submit a user event. (e.g. shield modal viewed)\n *\n * @param request - Request object containing the event to submit.\n * @example { event: SubscriptionUserEvent.ShieldEntryModalViewed, cohort: 'post_tx' }\n */\n async submitUserEvent(request: SubmitUserEventRequest): Promise<void> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'submitUserEvent',\n requestParams: request,\n path: 'user-events',\n method: 'POST',\n body: request,\n errorMessage: SubscriptionServiceErrorMessage.FailedToSubmitUserEvent,\n });\n }\n\n /**\n * Assign user to a cohort.\n *\n * @param request - Request object containing the cohort to assign the user to.\n * @example { cohort: 'post_tx' }\n */\n async assignUserToCohort(request: AssignCohortRequest): Promise<void> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'assignUserToCohort',\n requestParams: request,\n path: 'cohorts/assign',\n method: 'POST',\n body: request,\n errorMessage: SubscriptionServiceErrorMessage.FailedToAssignUserToCohort,\n });\n }\n\n /**\n * Submit sponsorship intents to the Subscription Service backend.\n *\n * This is intended to be used together with the crypto subscription flow.\n * When the user has enabled the smart transaction feature, we will sponsor the gas fees for the subscription approval transaction.\n *\n * @param request - Request object containing the address and products.\n * @example { address: '0x1234567890123456789012345678901234567890', products: [ProductType.Shield] }\n */\n async submitSponsorshipIntents(\n request: SubmitSponsorshipIntentsRequest,\n ): Promise<void> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'submitSponsorshipIntents',\n requestParams: request,\n path: 'transaction-sponsorship/intents',\n method: 'POST',\n body: request,\n errorMessage:\n SubscriptionServiceErrorMessage.FailedToSubmitSponsorshipIntents,\n });\n }\n\n /**\n * Link rewards to a subscription.\n *\n * @param request - Request object containing the reward account ID.\n * @example { rewardAccountId: 'eip155:1:0x1234567890123456789012345678901234567890' }\n * @returns The response from the API.\n */\n async linkRewards(\n request: LinkRewardsRequest,\n ): Promise<SubscriptionApiGeneralResponse> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'linkRewards',\n requestParams: request,\n path: 'rewards/link',\n method: 'POST',\n body: request,\n errorMessage: SubscriptionServiceErrorMessage.FailedToLinkRewards,\n });\n\n return create(jsonResponse, SubscriptionApiGeneralResponseStruct);\n }\n\n /**\n * Fetches subscription pricing information.\n *\n * @returns The pricing response.\n */\n async getPricing(): Promise<PricingResponse> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'getPricing',\n requestParams: null,\n path: 'pricing',\n errorMessage: SubscriptionServiceErrorMessage.FailedToGetPricing,\n });\n\n return create(jsonResponse, PricingResponseStruct);\n }\n\n /**\n * Fetches the billing portal URL.\n *\n * @returns The billing portal response.\n */\n async getBillingPortalUrl(): Promise<BillingPortalResponse> {\n const { profileKey, bearerToken } = await this.#getAuthenticatedContext();\n const jsonResponse = await this.#fetchJson({\n profileKey,\n bearerToken,\n methodName: 'getBillingPortalUrl',\n requestParams: null,\n path: 'billing-portal',\n errorMessage: SubscriptionServiceErrorMessage.FailedToGetBillingPortalUrl,\n });\n\n return create(jsonResponse, BillingPortalResponseStruct);\n }\n\n async #fetchJson({\n profileKey,\n bearerToken,\n methodName,\n requestParams,\n path,\n method = 'GET',\n body,\n queryParams,\n errorMessage,\n }: {\n profileKey: string;\n bearerToken: string;\n methodName: string;\n requestParams: unknown;\n path: string;\n method?: 'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH';\n body?: Record<string, unknown>;\n queryParams?: Record<string, string>;\n errorMessage: string;\n }): Promise<unknown> {\n const url = this.#getSubscriptionApiUrl(path);\n\n if (queryParams) {\n Object.entries(queryParams).forEach(([key, value]) => {\n url.searchParams.append(key, value);\n });\n }\n\n try {\n return await this.fetchQuery({\n queryKey: [\n `${this.name}:${methodName}`,\n profileKey,\n requestParams as Json,\n ],\n staleTime: 0,\n cacheTime: 0,\n queryFn: async () => {\n const response = await this.#fetch(url.toString(), {\n method,\n headers: {\n 'Content-Type': 'application/json',\n ...this.#headersForToken(bearerToken),\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!response.ok) {\n const apiError = await getSubscriptionErrorFromResponse(response);\n throw new HttpError(response.status, apiError.message);\n }\n\n return response.json();\n },\n });\n } catch (error) {\n log(errorMessage, error);\n\n const errorMessageWithUrl = `${errorMessage} (url: ${url.toString()})`;\n const errorToCapture =\n error instanceof Error ? error : new Error(errorMessage);\n this.#captureException?.(\n createSentryError(errorMessageWithUrl, errorToCapture),\n );\n\n if (error instanceof SubscriptionServiceError) {\n throw error;\n }\n\n throw new SubscriptionServiceError(\n `Failed to make request. ${errorMessageWithUrl}`,\n {\n cause: errorToCapture,\n },\n );\n }\n }\n\n async #getAuthenticatedContext(): Promise<{\n profileKey: string;\n bearerToken: string;\n }> {\n try {\n const [bearerToken, sessionProfile] = await Promise.all([\n this.messenger.call('AuthenticationController:getBearerToken'),\n this.messenger.call('AuthenticationController:getSessionProfile'),\n ]);\n\n return { profileKey: sessionProfile.profileId, bearerToken };\n } catch (error) {\n const errorMessage =\n error instanceof Error\n ? error.message\n : 'Unknown error when getting authorization header';\n\n this.#captureException?.(\n createSentryError(\n `Failed to get authorization header. ${errorMessage}`,\n error instanceof Error ? error : new Error(errorMessage),\n ),\n );\n\n throw new SubscriptionServiceError(\n `Failed to get authorization header. ${errorMessage}`,\n {\n cause: error instanceof Error ? error : new Error(errorMessage),\n },\n );\n }\n }\n\n #headersForToken(bearerToken: string): Record<string, string> {\n return { Authorization: `Bearer ${bearerToken}` };\n }\n\n #getSubscriptionApiUrl(path: string): URL {\n try {\n return new URL(SUBSCRIPTION_URL(this.#env, path));\n } catch (error) {\n const errorMessage =\n error instanceof Error\n ? error.message\n : 'Unknown error when getting subscription API URL';\n this.#captureException?.(\n createSentryError(\n `Failed to get subscription API URL. ${errorMessage}`,\n error instanceof Error ? error : new Error(errorMessage),\n ),\n );\n\n throw error;\n }\n }\n}\n"]}
|
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.SubscriptionService = exports.SubscriptionServiceErrorMessage = exports.SubscriptionControllerErrorMessage = exports.Env = exports.SubscriptionServiceError = exports.MODAL_TYPE = exports.BALANCE_CATEGORIES = exports.COHORT_NAMES = exports.SubscriptionUserEvent = exports.PAYMENT_TYPES = exports.RECURRING_INTERVALS = exports.PRODUCT_TYPES = exports.SUBSCRIPTION_STATUSES = exports.CRYPTO_PAYMENT_METHOD_ERRORS = exports.CANCEL_TYPES = exports.getDefaultSubscriptionControllerState = exports.SubscriptionController = void 0;
|
|
3
|
+
exports.SUBSCRIPTION_URL = exports.subscriptionServiceName = exports.SubscriptionService = exports.SubscriptionServiceErrorMessage = exports.SubscriptionControllerErrorMessage = exports.Env = exports.SubscriptionServiceError = exports.MODAL_TYPE = exports.BALANCE_CATEGORIES = exports.COHORT_NAMES = exports.SubscriptionUserEvent = exports.PAYMENT_TYPES = exports.RECURRING_INTERVALS = exports.PRODUCT_TYPES = exports.SUBSCRIPTION_STATUSES = exports.CRYPTO_PAYMENT_METHOD_ERRORS = exports.CANCEL_TYPES = exports.getDefaultSubscriptionControllerState = exports.SubscriptionController = void 0;
|
|
4
4
|
var SubscriptionController_js_1 = require("./SubscriptionController.cjs");
|
|
5
5
|
Object.defineProperty(exports, "SubscriptionController", { enumerable: true, get: function () { return SubscriptionController_js_1.SubscriptionController; } });
|
|
6
6
|
Object.defineProperty(exports, "getDefaultSubscriptionControllerState", { enumerable: true, get: function () { return SubscriptionController_js_1.getDefaultSubscriptionControllerState; } });
|
|
@@ -23,4 +23,6 @@ Object.defineProperty(exports, "SubscriptionControllerErrorMessage", { enumerabl
|
|
|
23
23
|
Object.defineProperty(exports, "SubscriptionServiceErrorMessage", { enumerable: true, get: function () { return constants_js_1.SubscriptionServiceErrorMessage; } });
|
|
24
24
|
var SubscriptionService_js_1 = require("./SubscriptionService.cjs");
|
|
25
25
|
Object.defineProperty(exports, "SubscriptionService", { enumerable: true, get: function () { return SubscriptionService_js_1.SubscriptionService; } });
|
|
26
|
+
Object.defineProperty(exports, "subscriptionServiceName", { enumerable: true, get: function () { return SubscriptionService_js_1.serviceName; } });
|
|
27
|
+
Object.defineProperty(exports, "SUBSCRIPTION_URL", { enumerable: true, get: function () { return SubscriptionService_js_1.SUBSCRIPTION_URL; } });
|
|
26
28
|
//# sourceMappingURL=index.cjs.map
|