@metamask-previews/subscription-controller 5.4.2-preview-5ff83bad8 → 5.4.2-preview-55087dcda

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.
@@ -9,91 +9,55 @@ 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, _SubscriptionService_makeRequest, _SubscriptionService_getAuthorizationHeader, _SubscriptionService_getSubscriptionApiUrl;
13
- import { getEnvUrls, SubscriptionControllerErrorMessage, SubscriptionServiceErrorMessage } from "./constants.mjs";
14
- import { createSentryError, getErrorFromResponse, SubscriptionServiceError } from "./errors.mjs";
12
+ var _SubscriptionService_instances, _SubscriptionService_env, _SubscriptionService_makeRequest, _SubscriptionService_getAuthorizationHeader;
13
+ import { handleFetch } from "@metamask/controller-utils";
14
+ import { getEnvUrls, SubscriptionControllerErrorMessage } from "./constants.mjs";
15
+ import { SubscriptionServiceError } from "./errors.mjs";
15
16
  export const SUBSCRIPTION_URL = (env, path) => `${getEnvUrls(env).subscriptionApiUrl}/v1/${path}`;
16
17
  export class SubscriptionService {
17
18
  constructor(config) {
18
19
  _SubscriptionService_instances.add(this);
19
20
  _SubscriptionService_env.set(this, void 0);
20
- _SubscriptionService_fetch.set(this, void 0);
21
- _SubscriptionService_captureException.set(this, void 0);
22
21
  __classPrivateFieldSet(this, _SubscriptionService_env, config.env, "f");
23
22
  this.authUtils = config.auth;
24
- __classPrivateFieldSet(this, _SubscriptionService_fetch, config.fetchFunction, "f");
25
- __classPrivateFieldSet(this, _SubscriptionService_captureException, config.captureException, "f");
26
23
  }
27
24
  async getSubscriptions() {
28
25
  const path = 'subscriptions';
29
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
30
- path,
31
- errorMessage: SubscriptionServiceErrorMessage.FailedToGetSubscriptions,
32
- });
26
+ return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path);
33
27
  }
34
28
  async cancelSubscription(params) {
35
29
  const path = `subscriptions/${params.subscriptionId}/cancel`;
36
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
37
- path,
38
- method: 'POST',
39
- body: {
40
- cancelAtPeriodEnd: params.cancelAtPeriodEnd,
41
- },
42
- errorMessage: SubscriptionServiceErrorMessage.FailedToCancelSubscription,
30
+ return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path, 'POST', {
31
+ cancelAtPeriodEnd: params.cancelAtPeriodEnd,
43
32
  });
44
33
  }
45
34
  async unCancelSubscription(params) {
46
35
  const path = `subscriptions/${params.subscriptionId}/uncancel`;
47
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
48
- path,
49
- method: 'POST',
50
- body: {},
51
- errorMessage: SubscriptionServiceErrorMessage.FailedToUncancelSubscription,
52
- });
36
+ return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path, 'POST', {});
53
37
  }
54
38
  async startSubscriptionWithCard(request) {
55
39
  if (request.products.length === 0) {
56
40
  throw new SubscriptionServiceError(SubscriptionControllerErrorMessage.SubscriptionProductsEmpty);
57
41
  }
58
42
  const path = 'subscriptions/card';
59
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
60
- path,
61
- method: 'POST',
62
- body: request,
63
- errorMessage: SubscriptionServiceErrorMessage.FailedToStartSubscriptionWithCard,
64
- });
43
+ return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path, 'POST', request);
65
44
  }
66
45
  async startSubscriptionWithCrypto(request) {
67
46
  const path = 'subscriptions/crypto';
68
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
69
- path,
70
- method: 'POST',
71
- body: request,
72
- errorMessage: SubscriptionServiceErrorMessage.FailedToStartSubscriptionWithCrypto,
73
- });
47
+ return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path, 'POST', request);
74
48
  }
75
49
  async updatePaymentMethodCard(request) {
76
50
  const path = `subscriptions/${request.subscriptionId}/payment-method/card`;
77
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
78
- path,
79
- method: 'PATCH',
80
- body: {
81
- ...request,
82
- subscriptionId: undefined,
83
- },
84
- errorMessage: SubscriptionServiceErrorMessage.FailedToUpdatePaymentMethodCard,
51
+ return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path, 'PATCH', {
52
+ ...request,
53
+ subscriptionId: undefined,
85
54
  });
86
55
  }
87
56
  async updatePaymentMethodCrypto(request) {
88
57
  const path = `subscriptions/${request.subscriptionId}/payment-method/crypto`;
89
- await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
90
- path,
91
- method: 'PATCH',
92
- body: {
93
- ...request,
94
- subscriptionId: undefined,
95
- },
96
- errorMessage: SubscriptionServiceErrorMessage.FailedToUpdatePaymentMethodCrypto,
58
+ await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path, 'PATCH', {
59
+ ...request,
60
+ subscriptionId: undefined,
97
61
  });
98
62
  }
99
63
  /**
@@ -108,11 +72,7 @@ export class SubscriptionService {
108
72
  if (request?.balanceCategory !== undefined) {
109
73
  query = { balanceCategory: request.balanceCategory };
110
74
  }
111
- const results = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
112
- path,
113
- queryParams: query,
114
- errorMessage: SubscriptionServiceErrorMessage.FailedToGetSubscriptionsEligibilities,
115
- });
75
+ const results = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path, 'GET', undefined, query);
116
76
  return results.map((result) => ({
117
77
  ...result,
118
78
  canSubscribe: result.canSubscribe || false,
@@ -130,12 +90,7 @@ export class SubscriptionService {
130
90
  */
131
91
  async submitUserEvent(request) {
132
92
  const path = 'user-events';
133
- await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
134
- path,
135
- method: 'POST',
136
- body: request,
137
- errorMessage: SubscriptionServiceErrorMessage.FailedToSubmitUserEvent,
138
- });
93
+ await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path, 'POST', request);
139
94
  }
140
95
  /**
141
96
  * Assign user to a cohort.
@@ -145,12 +100,7 @@ export class SubscriptionService {
145
100
  */
146
101
  async assignUserToCohort(request) {
147
102
  const path = 'cohorts/assign';
148
- await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
149
- path,
150
- method: 'POST',
151
- body: request,
152
- errorMessage: SubscriptionServiceErrorMessage.FailedToAssignUserToCohort,
153
- });
103
+ await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path, 'POST', request);
154
104
  }
155
105
  /**
156
106
  * Submit sponsorship intents to the Subscription Service backend.
@@ -163,12 +113,7 @@ export class SubscriptionService {
163
113
  */
164
114
  async submitSponsorshipIntents(request) {
165
115
  const path = 'transaction-sponsorship/intents';
166
- await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
167
- path,
168
- method: 'POST',
169
- body: request,
170
- errorMessage: SubscriptionServiceErrorMessage.FailedToSubmitSponsorshipIntents,
171
- });
116
+ await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path, 'POST', request);
172
117
  }
173
118
  /**
174
119
  * Link rewards to a subscription.
@@ -179,50 +124,27 @@ export class SubscriptionService {
179
124
  */
180
125
  async linkRewards(request) {
181
126
  const path = 'rewards/link';
182
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
183
- path,
184
- method: 'POST',
185
- body: request,
186
- errorMessage: SubscriptionServiceErrorMessage.FailedToLinkRewards,
187
- });
127
+ return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path, 'POST', request);
188
128
  }
189
129
  async getPricing() {
190
130
  const path = 'pricing';
191
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
192
- path,
193
- errorMessage: SubscriptionServiceErrorMessage.FailedToGetPricing,
194
- });
131
+ return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path);
195
132
  }
196
133
  async getBillingPortalUrl() {
197
134
  const path = 'billing-portal';
198
- return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, {
199
- path,
200
- errorMessage: SubscriptionServiceErrorMessage.FailedToGetBillingPortalUrl,
201
- });
135
+ return await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_makeRequest).call(this, path);
202
136
  }
203
137
  }
204
- _SubscriptionService_env = new WeakMap(), _SubscriptionService_fetch = new WeakMap(), _SubscriptionService_captureException = new WeakMap(), _SubscriptionService_instances = new WeakSet(), _SubscriptionService_makeRequest =
205
- /**
206
- * Makes a request to the Subscription Service backend.
207
- *
208
- * @param params - The request object containing the path, method, body, query parameters, and error message.
209
- * @param params.path - The path of the request.
210
- * @param params.method - The method of the request.
211
- * @param params.body - The body of the request.
212
- * @param params.queryParams - The query parameters of the request.
213
- * @param params.errorMessage - The error message to throw if the request fails.
214
- * @returns The result of the request.
215
- */
216
- async function _SubscriptionService_makeRequest({ path, method = 'GET', body, queryParams, errorMessage, }) {
217
- const url = __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getSubscriptionApiUrl).call(this, path);
218
- const headers = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthorizationHeader).call(this);
138
+ _SubscriptionService_env = new WeakMap(), _SubscriptionService_instances = new WeakSet(), _SubscriptionService_makeRequest = async function _SubscriptionService_makeRequest(path, method = 'GET', body, queryParams) {
219
139
  try {
140
+ const headers = await __classPrivateFieldGet(this, _SubscriptionService_instances, "m", _SubscriptionService_getAuthorizationHeader).call(this);
141
+ const url = new URL(SUBSCRIPTION_URL(__classPrivateFieldGet(this, _SubscriptionService_env, "f"), path));
220
142
  if (queryParams) {
221
143
  Object.entries(queryParams).forEach(([key, value]) => {
222
144
  url.searchParams.append(key, value);
223
145
  });
224
146
  }
225
- const response = await __classPrivateFieldGet(this, _SubscriptionService_fetch, "f").call(this, url.toString(), {
147
+ const response = await handleFetch(url.toString(), {
226
148
  method,
227
149
  headers: {
228
150
  'Content-Type': 'application/json',
@@ -230,49 +152,16 @@ async function _SubscriptionService_makeRequest({ path, method = 'GET', body, qu
230
152
  },
231
153
  body: body ? JSON.stringify(body) : undefined,
232
154
  });
233
- if (!response.ok) {
234
- const error = await getErrorFromResponse(response);
235
- throw error;
236
- }
237
- const data = await response.json();
238
- return data;
155
+ return response;
239
156
  }
240
157
  catch (error) {
241
- console.error(errorMessage, error);
242
- const errorMessageWithUrl = `${errorMessage} (url: ${url.toString()})`;
243
- const errorToCapture = error instanceof Error ? error : new Error(errorMessage);
244
- __classPrivateFieldGet(this, _SubscriptionService_captureException, "f")?.call(this, createSentryError(errorMessageWithUrl, errorToCapture));
245
- throw new SubscriptionServiceError(`Failed to make request. ${errorMessageWithUrl}`, {
246
- cause: errorToCapture,
247
- });
158
+ const errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
159
+ throw new SubscriptionServiceError(`failed to make request. ${errorMessage}`);
248
160
  }
249
161
  }, _SubscriptionService_getAuthorizationHeader =
250
162
  // eslint-disable-next-line @typescript-eslint/naming-convention
251
163
  async function _SubscriptionService_getAuthorizationHeader() {
252
- try {
253
- const accessToken = await this.authUtils.getAccessToken();
254
- return { Authorization: `Bearer ${accessToken}` };
255
- }
256
- catch (error) {
257
- const errorMessage = error instanceof Error
258
- ? error.message
259
- : 'Unknown error when getting authorization header';
260
- __classPrivateFieldGet(this, _SubscriptionService_captureException, "f")?.call(this, createSentryError(`Failed to get authorization header. ${errorMessage}`, error instanceof Error ? error : new Error(errorMessage)));
261
- throw new SubscriptionServiceError(`Failed to get authorization header. ${errorMessage}`, {
262
- cause: error instanceof Error ? error : new Error(errorMessage),
263
- });
264
- }
265
- }, _SubscriptionService_getSubscriptionApiUrl = function _SubscriptionService_getSubscriptionApiUrl(path) {
266
- try {
267
- const url = new URL(SUBSCRIPTION_URL(__classPrivateFieldGet(this, _SubscriptionService_env, "f"), path));
268
- return url;
269
- }
270
- catch (error) {
271
- const errorMessage = error instanceof Error
272
- ? error.message
273
- : 'Unknown error when getting subscription API URL';
274
- __classPrivateFieldGet(this, _SubscriptionService_captureException, "f")?.call(this, createSentryError(`Failed to get subscription API URL. ${errorMessage}`, error instanceof Error ? error : new Error(errorMessage)));
275
- throw error;
276
- }
164
+ const accessToken = await this.authUtils.getAccessToken();
165
+ return { Authorization: `Bearer ${accessToken}` };
277
166
  };
278
167
  //# sourceMappingURL=SubscriptionService.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"SubscriptionService.mjs","sourceRoot":"","sources":["../src/SubscriptionService.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EACL,UAAU,EACV,kCAAkC,EAClC,+BAA+B,EAChC,wBAAoB;AAErB,OAAO,EACL,iBAAiB,EACjB,oBAAoB,EACpB,wBAAwB,EACzB,qBAAiB;AAgClB,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,GAAQ,EA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,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';\nimport type { Env } from './constants';\nimport {\n createSentryError,\n getErrorFromResponse,\n SubscriptionServiceError,\n} from './errors';\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';\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\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 getErrorFromResponse(response);\n throw error;\n }\n\n const data = await response.json();\n return data;\n } catch (error) {\n console.error(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":";;;;;;;;;;;;AAAA,OAAO,EAAE,WAAW,EAAE,mCAAmC;AAEzD,OAAO,EAAE,UAAU,EAAE,kCAAkC,EAAE,wBAAoB;AAE7E,OAAO,EAAE,wBAAwB,EAAE,qBAAiB;AA8BpD,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,GAAQ,EAAE,IAAY,EAAU,EAAE,CACjE,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC,kBAAkB,OAAO,IAAI,EAAE,CAAC;AAErD,MAAM,OAAO,mBAAmB;IAK9B,YAAY,MAAiC;;QAJpC,2CAAU;QAKjB,uBAAA,IAAI,4BAAQ,MAAM,CAAC,GAAG,MAAA,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC;IAC/B,CAAC;IAED,KAAK,CAAC,gBAAgB;QACpB,MAAM,IAAI,GAAG,eAAe,CAAC;QAC7B,OAAO,MAAM,uBAAA,IAAI,wEAAa,MAAjB,IAAI,EAAc,IAAI,CAAC,CAAC;IACvC,CAAC;IAED,KAAK,CAAC,kBAAkB,CACtB,MAAiC;QAEjC,MAAM,IAAI,GAAG,iBAAiB,MAAM,CAAC,cAAc,SAAS,CAAC;QAC7D,OAAO,MAAM,uBAAA,IAAI,wEAAa,MAAjB,IAAI,EAAc,IAAI,EAAE,MAAM,EAAE;YAC3C,iBAAiB,EAAE,MAAM,CAAC,iBAAiB;SAC5C,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,oBAA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AAM;YACN,OAAO,EAAE;gBACP,cAAc,EAAE,kBAAkB;gBAClC,GAAG,OAAO;aACX;YACD,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS;SAC9C,CAAC,CAAC;QAEH,OAAO,QAAQ,CAAC;IAClB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,YAAY,GAChB,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;QAEjE,MAAM,IAAI,wBAAwB,CAChC,2BAA2B,YAAY,EAAE,CAC1C,CAAC;IACJ,CAAC;AACH,CAAC;AAED,gEAAgE;AAChE,KAAK;IACH,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,cAAc,EAAE,CAAC;IAC1D,OAAO,EAAE,aAAa,EAAE,UAAU,WAAW,EAAE,EAAE,CAAC;AACpD,CAAC","sourcesContent":["import { handleFetch } from '@metamask/controller-utils';\n\nimport { getEnvUrls, SubscriptionControllerErrorMessage } from './constants';\nimport type { Env } from './constants';\nimport { SubscriptionServiceError } from './errors';\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';\n\nexport type SubscriptionServiceConfig = {\n env: Env;\n auth: AuthUtils;\n};\n\nexport const SUBSCRIPTION_URL = (env: Env, path: string): string =>\n `${getEnvUrls(env).subscriptionApiUrl}/v1/${path}`;\n\nexport class SubscriptionService implements ISubscriptionService {\n readonly #env: Env;\n\n public authUtils: AuthUtils;\n\n constructor(config: SubscriptionServiceConfig) {\n this.#env = config.env;\n this.authUtils = config.auth;\n }\n\n async getSubscriptions(): Promise<GetSubscriptionsResponse> {\n const path = 'subscriptions';\n return await this.#makeRequest(path);\n }\n\n async cancelSubscription(\n params: CancelSubscriptionRequest,\n ): Promise<Subscription> {\n const path = `subscriptions/${params.subscriptionId}/cancel`;\n return await this.#makeRequest(path, 'POST', {\n cancelAtPeriodEnd: params.cancelAtPeriodEnd,\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(path, 'POST', {});\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(path, 'POST', request);\n }\n\n async startSubscriptionWithCrypto(\n request: StartCryptoSubscriptionRequest,\n ): Promise<StartCryptoSubscriptionResponse> {\n const path = 'subscriptions/crypto';\n return await this.#makeRequest(path, 'POST', request);\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 'PATCH',\n {\n ...request,\n subscriptionId: undefined,\n },\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(path, 'PATCH', {\n ...request,\n subscriptionId: undefined,\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 'GET',\n undefined,\n query,\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(path, 'POST', request);\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(path, 'POST', request);\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(path, 'POST', request);\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 'POST',\n request,\n );\n }\n\n async #makeRequest<Result>(\n path: string,\n method: 'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH' = 'GET',\n body?: Record<string, unknown>,\n queryParams?: Record<string, string>,\n ): Promise<Result> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const url = new URL(SUBSCRIPTION_URL(this.#env, path));\n\n if (queryParams) {\n Object.entries(queryParams).forEach(([key, value]) => {\n url.searchParams.append(key, value);\n });\n }\n\n const response = await handleFetch(url.toString(), {\n method,\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n\n return response;\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : JSON.stringify(error);\n\n throw new SubscriptionServiceError(\n `failed to make request. ${errorMessage}`,\n );\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/naming-convention\n async #getAuthorizationHeader(): Promise<{ Authorization: string }> {\n const accessToken = await this.authUtils.getAccessToken();\n return { Authorization: `Bearer ${accessToken}` };\n }\n\n async getPricing(): Promise<PricingResponse> {\n const path = 'pricing';\n return await this.#makeRequest<PricingResponse>(path);\n }\n\n async getBillingPortalUrl(): Promise<BillingPortalResponse> {\n const path = 'billing-portal';\n return await this.#makeRequest<BillingPortalResponse>(path);\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ACTIVE_SUBSCRIPTION_STATUSES = exports.DEFAULT_POLLING_INTERVAL = exports.SubscriptionServiceErrorMessage = exports.SubscriptionControllerErrorMessage = exports.getEnvUrls = exports.Env = exports.controllerName = void 0;
3
+ exports.ACTIVE_SUBSCRIPTION_STATUSES = exports.DEFAULT_POLLING_INTERVAL = exports.SubscriptionControllerErrorMessage = exports.getEnvUrls = exports.Env = exports.controllerName = void 0;
4
4
  const types_1 = require("./types.cjs");
5
5
  exports.controllerName = 'SubscriptionController';
6
6
  var Env;
@@ -45,23 +45,6 @@ var SubscriptionControllerErrorMessage;
45
45
  SubscriptionControllerErrorMessage["SubscriptionNotValidForCryptoApproval"] = "SubscriptionController - Subscription is not valid for crypto approval";
46
46
  SubscriptionControllerErrorMessage["LinkRewardsFailed"] = "SubscriptionController - Failed to link rewards";
47
47
  })(SubscriptionControllerErrorMessage || (exports.SubscriptionControllerErrorMessage = SubscriptionControllerErrorMessage = {}));
48
- var SubscriptionServiceErrorMessage;
49
- (function (SubscriptionServiceErrorMessage) {
50
- SubscriptionServiceErrorMessage["FailedToGetSubscriptions"] = "Failed to get subscriptions";
51
- SubscriptionServiceErrorMessage["FailedToCancelSubscription"] = "Failed to cancel subscription";
52
- SubscriptionServiceErrorMessage["FailedToUncancelSubscription"] = "Failed to uncancel subscription";
53
- SubscriptionServiceErrorMessage["FailedToStartSubscriptionWithCard"] = "Failed to start subscription with card";
54
- SubscriptionServiceErrorMessage["FailedToStartSubscriptionWithCrypto"] = "Failed to start subscription with crypto";
55
- SubscriptionServiceErrorMessage["FailedToUpdatePaymentMethodCard"] = "Failed to update payment method card";
56
- SubscriptionServiceErrorMessage["FailedToUpdatePaymentMethodCrypto"] = "Failed to update payment method crypto";
57
- SubscriptionServiceErrorMessage["FailedToGetSubscriptionsEligibilities"] = "Failed to get subscriptions eligibilities";
58
- SubscriptionServiceErrorMessage["FailedToSubmitUserEvent"] = "Failed to submit user event";
59
- SubscriptionServiceErrorMessage["FailedToAssignUserToCohort"] = "Failed to assign user to cohort";
60
- SubscriptionServiceErrorMessage["FailedToSubmitSponsorshipIntents"] = "Failed to submit sponsorship intents";
61
- SubscriptionServiceErrorMessage["FailedToLinkRewards"] = "Failed to link rewards";
62
- SubscriptionServiceErrorMessage["FailedToGetPricing"] = "Failed to get pricing";
63
- SubscriptionServiceErrorMessage["FailedToGetBillingPortalUrl"] = "Failed to get billing portal url";
64
- })(SubscriptionServiceErrorMessage || (exports.SubscriptionServiceErrorMessage = SubscriptionServiceErrorMessage = {}));
65
48
  exports.DEFAULT_POLLING_INTERVAL = 5 * 60 * 1000; // 5 minutes
66
49
  exports.ACTIVE_SUBSCRIPTION_STATUSES = [
67
50
  types_1.SUBSCRIPTION_STATUSES.active,
@@ -1 +1 @@
1
- {"version":3,"file":"constants.cjs","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":";;;AAAA,uCAAgD;AAEnC,QAAA,cAAc,GAAG,wBAAwB,CAAC;AAEvD,IAAY,GAIX;AAJD,WAAY,GAAG;IACb,kBAAW,CAAA;IACX,kBAAW,CAAA;IACX,kBAAW,CAAA;AACb,CAAC,EAJW,GAAG,mBAAH,GAAG,QAId;AAMD,MAAM,QAAQ,GAA8B;IAC1C,GAAG,EAAE;QACH,kBAAkB,EAAE,6CAA6C;KAClE;IACD,GAAG,EAAE;QACH,kBAAkB,EAAE,6CAA6C;KAClE;IACD,GAAG,EAAE;QACH,kBAAkB,EAAE,yCAAyC;KAC9D;CACF,CAAC;AAEF;;;;;;GAMG;AACH,SAAgB,UAAU,CAAC,GAAQ;IACjC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;IACvD,CAAC;IACD,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;AACvB,CAAC;AALD,gCAKC;AAED,IAAY,kCASX;AATD,WAAY,kCAAkC;IAC5C,mHAAwE,CAAA;IACxE,2GAAgE,CAAA;IAChE,wIAA6F,CAAA;IAC7F,iLAAsI,CAAA;IACtI,sHAA2E,CAAA;IAC3E,+GAAoE,CAAA;IACpE,sJAA2G,CAAA;IAC3G,2GAAgE,CAAA;AAClE,CAAC,EATW,kCAAkC,kDAAlC,kCAAkC,QAS7C;AAED,IAAY,+BAeX;AAfD,WAAY,+BAA+B;IACzC,2FAAwD,CAAA;IACxD,+FAA4D,CAAA;IAC5D,mGAAgE,CAAA;IAChE,+GAA4E,CAAA;IAC5E,mHAAgF,CAAA;IAChF,2GAAwE,CAAA;IACxE,+GAA4E,CAAA;IAC5E,sHAAmF,CAAA;IACnF,0FAAuD,CAAA;IACvD,iGAA8D,CAAA;IAC9D,4GAAyE,CAAA;IACzE,iFAA8C,CAAA;IAC9C,+EAA4C,CAAA;IAC5C,mGAAgE,CAAA;AAClE,CAAC,EAfW,+BAA+B,+CAA/B,+BAA+B,QAe1C;AAEY,QAAA,wBAAwB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAK,CAAC,CAAC,YAAY;AAEvD,QAAA,4BAA4B,GAAG;IAC1C,6BAAqB,CAAC,MAAM;IAC5B,6BAAqB,CAAC,QAAQ;IAC9B,6BAAqB,CAAC,WAAW;CACtB,CAAC","sourcesContent":["import { SUBSCRIPTION_STATUSES } from './types';\n\nexport const controllerName = 'SubscriptionController';\n\nexport enum Env {\n DEV = 'dev',\n UAT = 'uat',\n PRD = 'prd',\n}\n\ntype EnvUrlsEntry = {\n subscriptionApiUrl: string;\n};\n\nconst ENV_URLS: Record<Env, EnvUrlsEntry> = {\n dev: {\n subscriptionApiUrl: 'https://subscription.dev-api.cx.metamask.io',\n },\n uat: {\n subscriptionApiUrl: 'https://subscription.uat-api.cx.metamask.io',\n },\n prd: {\n subscriptionApiUrl: 'https://subscription.api.cx.metamask.io',\n },\n};\n\n/**\n * Validates and returns correct environment endpoints\n *\n * @param env - environment field\n * @returns the correct environment url\n * @throws on invalid environment passed\n */\nexport function getEnvUrls(env: Env): EnvUrlsEntry {\n if (!ENV_URLS[env]) {\n throw new Error('invalid environment configuration');\n }\n return ENV_URLS[env];\n}\n\nexport enum SubscriptionControllerErrorMessage {\n UserAlreadySubscribed = `${controllerName} - User is already subscribed`,\n UserNotSubscribed = `${controllerName} - User is not subscribed`,\n SubscriptionProductsEmpty = `${controllerName} - Subscription products array cannot be empty`,\n PaymentTokenAddressAndSymbolRequiredForCrypto = `${controllerName} - Payment token address and symbol are required for crypto payment`,\n PaymentMethodNotCrypto = `${controllerName} - Payment method is not crypto`,\n ProductPriceNotFound = `${controllerName} - Product price not found`,\n SubscriptionNotValidForCryptoApproval = `${controllerName} - Subscription is not valid for crypto approval`,\n LinkRewardsFailed = `${controllerName} - Failed to link rewards`,\n}\n\nexport enum SubscriptionServiceErrorMessage {\n FailedToGetSubscriptions = 'Failed to get subscriptions',\n FailedToCancelSubscription = 'Failed to cancel subscription',\n FailedToUncancelSubscription = 'Failed to uncancel subscription',\n FailedToStartSubscriptionWithCard = 'Failed to start subscription with card',\n FailedToStartSubscriptionWithCrypto = 'Failed to start subscription with crypto',\n FailedToUpdatePaymentMethodCard = 'Failed to update payment method card',\n FailedToUpdatePaymentMethodCrypto = 'Failed to update payment method crypto',\n FailedToGetSubscriptionsEligibilities = 'Failed to get subscriptions eligibilities',\n FailedToSubmitUserEvent = 'Failed to submit user event',\n FailedToAssignUserToCohort = 'Failed to assign user to cohort',\n FailedToSubmitSponsorshipIntents = 'Failed to submit sponsorship intents',\n FailedToLinkRewards = 'Failed to link rewards',\n FailedToGetPricing = 'Failed to get pricing',\n FailedToGetBillingPortalUrl = 'Failed to get billing portal url',\n}\n\nexport const DEFAULT_POLLING_INTERVAL = 5 * 60 * 1_000; // 5 minutes\n\nexport const ACTIVE_SUBSCRIPTION_STATUSES = [\n SUBSCRIPTION_STATUSES.active,\n SUBSCRIPTION_STATUSES.trialing,\n SUBSCRIPTION_STATUSES.provisional,\n] as string[];\n"]}
1
+ {"version":3,"file":"constants.cjs","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":";;;AAAA,uCAAgD;AAEnC,QAAA,cAAc,GAAG,wBAAwB,CAAC;AAEvD,IAAY,GAIX;AAJD,WAAY,GAAG;IACb,kBAAW,CAAA;IACX,kBAAW,CAAA;IACX,kBAAW,CAAA;AACb,CAAC,EAJW,GAAG,mBAAH,GAAG,QAId;AAMD,MAAM,QAAQ,GAA8B;IAC1C,GAAG,EAAE;QACH,kBAAkB,EAAE,6CAA6C;KAClE;IACD,GAAG,EAAE;QACH,kBAAkB,EAAE,6CAA6C;KAClE;IACD,GAAG,EAAE;QACH,kBAAkB,EAAE,yCAAyC;KAC9D;CACF,CAAC;AAEF;;;;;;GAMG;AACH,SAAgB,UAAU,CAAC,GAAQ;IACjC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;IACvD,CAAC;IACD,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;AACvB,CAAC;AALD,gCAKC;AAED,IAAY,kCASX;AATD,WAAY,kCAAkC;IAC5C,mHAAwE,CAAA;IACxE,2GAAgE,CAAA;IAChE,wIAA6F,CAAA;IAC7F,iLAAsI,CAAA;IACtI,sHAA2E,CAAA;IAC3E,+GAAoE,CAAA;IACpE,sJAA2G,CAAA;IAC3G,2GAAgE,CAAA;AAClE,CAAC,EATW,kCAAkC,kDAAlC,kCAAkC,QAS7C;AAEY,QAAA,wBAAwB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAK,CAAC,CAAC,YAAY;AAEvD,QAAA,4BAA4B,GAAG;IAC1C,6BAAqB,CAAC,MAAM;IAC5B,6BAAqB,CAAC,QAAQ;IAC9B,6BAAqB,CAAC,WAAW;CACtB,CAAC","sourcesContent":["import { SUBSCRIPTION_STATUSES } from './types';\n\nexport const controllerName = 'SubscriptionController';\n\nexport enum Env {\n DEV = 'dev',\n UAT = 'uat',\n PRD = 'prd',\n}\n\ntype EnvUrlsEntry = {\n subscriptionApiUrl: string;\n};\n\nconst ENV_URLS: Record<Env, EnvUrlsEntry> = {\n dev: {\n subscriptionApiUrl: 'https://subscription.dev-api.cx.metamask.io',\n },\n uat: {\n subscriptionApiUrl: 'https://subscription.uat-api.cx.metamask.io',\n },\n prd: {\n subscriptionApiUrl: 'https://subscription.api.cx.metamask.io',\n },\n};\n\n/**\n * Validates and returns correct environment endpoints\n *\n * @param env - environment field\n * @returns the correct environment url\n * @throws on invalid environment passed\n */\nexport function getEnvUrls(env: Env): EnvUrlsEntry {\n if (!ENV_URLS[env]) {\n throw new Error('invalid environment configuration');\n }\n return ENV_URLS[env];\n}\n\nexport enum SubscriptionControllerErrorMessage {\n UserAlreadySubscribed = `${controllerName} - User is already subscribed`,\n UserNotSubscribed = `${controllerName} - User is not subscribed`,\n SubscriptionProductsEmpty = `${controllerName} - Subscription products array cannot be empty`,\n PaymentTokenAddressAndSymbolRequiredForCrypto = `${controllerName} - Payment token address and symbol are required for crypto payment`,\n PaymentMethodNotCrypto = `${controllerName} - Payment method is not crypto`,\n ProductPriceNotFound = `${controllerName} - Product price not found`,\n SubscriptionNotValidForCryptoApproval = `${controllerName} - Subscription is not valid for crypto approval`,\n LinkRewardsFailed = `${controllerName} - Failed to link rewards`,\n}\n\nexport const DEFAULT_POLLING_INTERVAL = 5 * 60 * 1_000; // 5 minutes\n\nexport const ACTIVE_SUBSCRIPTION_STATUSES = [\n SUBSCRIPTION_STATUSES.active,\n SUBSCRIPTION_STATUSES.trialing,\n SUBSCRIPTION_STATUSES.provisional,\n] as string[];\n"]}
@@ -25,22 +25,6 @@ export declare enum SubscriptionControllerErrorMessage {
25
25
  SubscriptionNotValidForCryptoApproval = "SubscriptionController - Subscription is not valid for crypto approval",
26
26
  LinkRewardsFailed = "SubscriptionController - Failed to link rewards"
27
27
  }
28
- export declare enum SubscriptionServiceErrorMessage {
29
- FailedToGetSubscriptions = "Failed to get subscriptions",
30
- FailedToCancelSubscription = "Failed to cancel subscription",
31
- FailedToUncancelSubscription = "Failed to uncancel subscription",
32
- FailedToStartSubscriptionWithCard = "Failed to start subscription with card",
33
- FailedToStartSubscriptionWithCrypto = "Failed to start subscription with crypto",
34
- FailedToUpdatePaymentMethodCard = "Failed to update payment method card",
35
- FailedToUpdatePaymentMethodCrypto = "Failed to update payment method crypto",
36
- FailedToGetSubscriptionsEligibilities = "Failed to get subscriptions eligibilities",
37
- FailedToSubmitUserEvent = "Failed to submit user event",
38
- FailedToAssignUserToCohort = "Failed to assign user to cohort",
39
- FailedToSubmitSponsorshipIntents = "Failed to submit sponsorship intents",
40
- FailedToLinkRewards = "Failed to link rewards",
41
- FailedToGetPricing = "Failed to get pricing",
42
- FailedToGetBillingPortalUrl = "Failed to get billing portal url"
43
- }
44
28
  export declare const DEFAULT_POLLING_INTERVAL: number;
45
29
  export declare const ACTIVE_SUBSCRIPTION_STATUSES: string[];
46
30
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"constants.d.cts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,cAAc,2BAA2B,CAAC;AAEvD,oBAAY,GAAG;IACb,GAAG,QAAQ;IACX,GAAG,QAAQ;IACX,GAAG,QAAQ;CACZ;AAED,KAAK,YAAY,GAAG;IAClB,kBAAkB,EAAE,MAAM,CAAC;CAC5B,CAAC;AAcF;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,GAAG,GAAG,YAAY,CAKjD;AAED,oBAAY,kCAAkC;IAC5C,qBAAqB,wDAAmD;IACxE,iBAAiB,oDAA+C;IAChE,yBAAyB,yEAAoE;IAC7F,6CAA6C,8FAAyF;IACtI,sBAAsB,0DAAqD;IAC3E,oBAAoB,qDAAgD;IACpE,qCAAqC,2EAAsE;IAC3G,iBAAiB,oDAA+C;CACjE;AAED,oBAAY,+BAA+B;IACzC,wBAAwB,gCAAgC;IACxD,0BAA0B,kCAAkC;IAC5D,4BAA4B,oCAAoC;IAChE,iCAAiC,2CAA2C;IAC5E,mCAAmC,6CAA6C;IAChF,+BAA+B,yCAAyC;IACxE,iCAAiC,2CAA2C;IAC5E,qCAAqC,8CAA8C;IACnF,uBAAuB,gCAAgC;IACvD,0BAA0B,oCAAoC;IAC9D,gCAAgC,yCAAyC;IACzE,mBAAmB,2BAA2B;IAC9C,kBAAkB,0BAA0B;IAC5C,2BAA2B,qCAAqC;CACjE;AAED,eAAO,MAAM,wBAAwB,QAAiB,CAAC;AAEvD,eAAO,MAAM,4BAA4B,UAI5B,CAAC"}
1
+ {"version":3,"file":"constants.d.cts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,cAAc,2BAA2B,CAAC;AAEvD,oBAAY,GAAG;IACb,GAAG,QAAQ;IACX,GAAG,QAAQ;IACX,GAAG,QAAQ;CACZ;AAED,KAAK,YAAY,GAAG;IAClB,kBAAkB,EAAE,MAAM,CAAC;CAC5B,CAAC;AAcF;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,GAAG,GAAG,YAAY,CAKjD;AAED,oBAAY,kCAAkC;IAC5C,qBAAqB,wDAAmD;IACxE,iBAAiB,oDAA+C;IAChE,yBAAyB,yEAAoE;IAC7F,6CAA6C,8FAAyF;IACtI,sBAAsB,0DAAqD;IAC3E,oBAAoB,qDAAgD;IACpE,qCAAqC,2EAAsE;IAC3G,iBAAiB,oDAA+C;CACjE;AAED,eAAO,MAAM,wBAAwB,QAAiB,CAAC;AAEvD,eAAO,MAAM,4BAA4B,UAI5B,CAAC"}
@@ -25,22 +25,6 @@ export declare enum SubscriptionControllerErrorMessage {
25
25
  SubscriptionNotValidForCryptoApproval = "SubscriptionController - Subscription is not valid for crypto approval",
26
26
  LinkRewardsFailed = "SubscriptionController - Failed to link rewards"
27
27
  }
28
- export declare enum SubscriptionServiceErrorMessage {
29
- FailedToGetSubscriptions = "Failed to get subscriptions",
30
- FailedToCancelSubscription = "Failed to cancel subscription",
31
- FailedToUncancelSubscription = "Failed to uncancel subscription",
32
- FailedToStartSubscriptionWithCard = "Failed to start subscription with card",
33
- FailedToStartSubscriptionWithCrypto = "Failed to start subscription with crypto",
34
- FailedToUpdatePaymentMethodCard = "Failed to update payment method card",
35
- FailedToUpdatePaymentMethodCrypto = "Failed to update payment method crypto",
36
- FailedToGetSubscriptionsEligibilities = "Failed to get subscriptions eligibilities",
37
- FailedToSubmitUserEvent = "Failed to submit user event",
38
- FailedToAssignUserToCohort = "Failed to assign user to cohort",
39
- FailedToSubmitSponsorshipIntents = "Failed to submit sponsorship intents",
40
- FailedToLinkRewards = "Failed to link rewards",
41
- FailedToGetPricing = "Failed to get pricing",
42
- FailedToGetBillingPortalUrl = "Failed to get billing portal url"
43
- }
44
28
  export declare const DEFAULT_POLLING_INTERVAL: number;
45
29
  export declare const ACTIVE_SUBSCRIPTION_STATUSES: string[];
46
30
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"constants.d.mts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,cAAc,2BAA2B,CAAC;AAEvD,oBAAY,GAAG;IACb,GAAG,QAAQ;IACX,GAAG,QAAQ;IACX,GAAG,QAAQ;CACZ;AAED,KAAK,YAAY,GAAG;IAClB,kBAAkB,EAAE,MAAM,CAAC;CAC5B,CAAC;AAcF;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,GAAG,GAAG,YAAY,CAKjD;AAED,oBAAY,kCAAkC;IAC5C,qBAAqB,wDAAmD;IACxE,iBAAiB,oDAA+C;IAChE,yBAAyB,yEAAoE;IAC7F,6CAA6C,8FAAyF;IACtI,sBAAsB,0DAAqD;IAC3E,oBAAoB,qDAAgD;IACpE,qCAAqC,2EAAsE;IAC3G,iBAAiB,oDAA+C;CACjE;AAED,oBAAY,+BAA+B;IACzC,wBAAwB,gCAAgC;IACxD,0BAA0B,kCAAkC;IAC5D,4BAA4B,oCAAoC;IAChE,iCAAiC,2CAA2C;IAC5E,mCAAmC,6CAA6C;IAChF,+BAA+B,yCAAyC;IACxE,iCAAiC,2CAA2C;IAC5E,qCAAqC,8CAA8C;IACnF,uBAAuB,gCAAgC;IACvD,0BAA0B,oCAAoC;IAC9D,gCAAgC,yCAAyC;IACzE,mBAAmB,2BAA2B;IAC9C,kBAAkB,0BAA0B;IAC5C,2BAA2B,qCAAqC;CACjE;AAED,eAAO,MAAM,wBAAwB,QAAiB,CAAC;AAEvD,eAAO,MAAM,4BAA4B,UAI5B,CAAC"}
1
+ {"version":3,"file":"constants.d.mts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,cAAc,2BAA2B,CAAC;AAEvD,oBAAY,GAAG;IACb,GAAG,QAAQ;IACX,GAAG,QAAQ;IACX,GAAG,QAAQ;CACZ;AAED,KAAK,YAAY,GAAG;IAClB,kBAAkB,EAAE,MAAM,CAAC;CAC5B,CAAC;AAcF;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,GAAG,GAAG,YAAY,CAKjD;AAED,oBAAY,kCAAkC;IAC5C,qBAAqB,wDAAmD;IACxE,iBAAiB,oDAA+C;IAChE,yBAAyB,yEAAoE;IAC7F,6CAA6C,8FAAyF;IACtI,sBAAsB,0DAAqD;IAC3E,oBAAoB,qDAAgD;IACpE,qCAAqC,2EAAsE;IAC3G,iBAAiB,oDAA+C;CACjE;AAED,eAAO,MAAM,wBAAwB,QAAiB,CAAC;AAEvD,eAAO,MAAM,4BAA4B,UAI5B,CAAC"}
@@ -41,23 +41,6 @@ export var SubscriptionControllerErrorMessage;
41
41
  SubscriptionControllerErrorMessage["SubscriptionNotValidForCryptoApproval"] = "SubscriptionController - Subscription is not valid for crypto approval";
42
42
  SubscriptionControllerErrorMessage["LinkRewardsFailed"] = "SubscriptionController - Failed to link rewards";
43
43
  })(SubscriptionControllerErrorMessage || (SubscriptionControllerErrorMessage = {}));
44
- export var SubscriptionServiceErrorMessage;
45
- (function (SubscriptionServiceErrorMessage) {
46
- SubscriptionServiceErrorMessage["FailedToGetSubscriptions"] = "Failed to get subscriptions";
47
- SubscriptionServiceErrorMessage["FailedToCancelSubscription"] = "Failed to cancel subscription";
48
- SubscriptionServiceErrorMessage["FailedToUncancelSubscription"] = "Failed to uncancel subscription";
49
- SubscriptionServiceErrorMessage["FailedToStartSubscriptionWithCard"] = "Failed to start subscription with card";
50
- SubscriptionServiceErrorMessage["FailedToStartSubscriptionWithCrypto"] = "Failed to start subscription with crypto";
51
- SubscriptionServiceErrorMessage["FailedToUpdatePaymentMethodCard"] = "Failed to update payment method card";
52
- SubscriptionServiceErrorMessage["FailedToUpdatePaymentMethodCrypto"] = "Failed to update payment method crypto";
53
- SubscriptionServiceErrorMessage["FailedToGetSubscriptionsEligibilities"] = "Failed to get subscriptions eligibilities";
54
- SubscriptionServiceErrorMessage["FailedToSubmitUserEvent"] = "Failed to submit user event";
55
- SubscriptionServiceErrorMessage["FailedToAssignUserToCohort"] = "Failed to assign user to cohort";
56
- SubscriptionServiceErrorMessage["FailedToSubmitSponsorshipIntents"] = "Failed to submit sponsorship intents";
57
- SubscriptionServiceErrorMessage["FailedToLinkRewards"] = "Failed to link rewards";
58
- SubscriptionServiceErrorMessage["FailedToGetPricing"] = "Failed to get pricing";
59
- SubscriptionServiceErrorMessage["FailedToGetBillingPortalUrl"] = "Failed to get billing portal url";
60
- })(SubscriptionServiceErrorMessage || (SubscriptionServiceErrorMessage = {}));
61
44
  export const DEFAULT_POLLING_INTERVAL = 5 * 60 * 1000; // 5 minutes
62
45
  export const ACTIVE_SUBSCRIPTION_STATUSES = [
63
46
  SUBSCRIPTION_STATUSES.active,
@@ -1 +1 @@
1
- {"version":3,"file":"constants.mjs","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,oBAAgB;AAEhD,MAAM,CAAC,MAAM,cAAc,GAAG,wBAAwB,CAAC;AAEvD,MAAM,CAAN,IAAY,GAIX;AAJD,WAAY,GAAG;IACb,kBAAW,CAAA;IACX,kBAAW,CAAA;IACX,kBAAW,CAAA;AACb,CAAC,EAJW,GAAG,KAAH,GAAG,QAId;AAMD,MAAM,QAAQ,GAA8B;IAC1C,GAAG,EAAE;QACH,kBAAkB,EAAE,6CAA6C;KAClE;IACD,GAAG,EAAE;QACH,k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';\n\nexport const controllerName = 'SubscriptionController';\n\nexport enum Env {\n DEV = 'dev',\n UAT = 'uat',\n PRD = 'prd',\n}\n\ntype EnvUrlsEntry = {\n subscriptionApiUrl: string;\n};\n\nconst ENV_URLS: Record<Env, EnvUrlsEntry> = {\n dev: {\n subscriptionApiUrl: 'https://subscription.dev-api.cx.metamask.io',\n },\n uat: {\n subscriptionApiUrl: 'https://subscription.uat-api.cx.metamask.io',\n },\n prd: {\n subscriptionApiUrl: 'https://subscription.api.cx.metamask.io',\n },\n};\n\n/**\n * Validates and returns correct environment endpoints\n *\n * @param env - environment field\n * @returns the correct environment url\n * @throws on invalid environment passed\n */\nexport function getEnvUrls(env: Env): EnvUrlsEntry {\n if (!ENV_URLS[env]) {\n throw new Error('invalid environment configuration');\n }\n return ENV_URLS[env];\n}\n\nexport enum SubscriptionControllerErrorMessage {\n UserAlreadySubscribed = `${controllerName} - User is already subscribed`,\n UserNotSubscribed = `${controllerName} - User is not subscribed`,\n SubscriptionProductsEmpty = `${controllerName} - Subscription products array cannot be empty`,\n PaymentTokenAddressAndSymbolRequiredForCrypto = `${controllerName} - Payment token address and symbol are required for crypto payment`,\n PaymentMethodNotCrypto = `${controllerName} - Payment method is not crypto`,\n ProductPriceNotFound = `${controllerName} - Product price not found`,\n SubscriptionNotValidForCryptoApproval = `${controllerName} - Subscription is not valid for crypto approval`,\n LinkRewardsFailed = `${controllerName} - Failed to link rewards`,\n}\n\nexport enum SubscriptionServiceErrorMessage {\n FailedToGetSubscriptions = 'Failed to get subscriptions',\n FailedToCancelSubscription = 'Failed to cancel subscription',\n FailedToUncancelSubscription = 'Failed to uncancel subscription',\n FailedToStartSubscriptionWithCard = 'Failed to start subscription with card',\n FailedToStartSubscriptionWithCrypto = 'Failed to start subscription with crypto',\n FailedToUpdatePaymentMethodCard = 'Failed to update payment method card',\n FailedToUpdatePaymentMethodCrypto = 'Failed to update payment method crypto',\n FailedToGetSubscriptionsEligibilities = 'Failed to get subscriptions eligibilities',\n FailedToSubmitUserEvent = 'Failed to submit user event',\n FailedToAssignUserToCohort = 'Failed to assign user to cohort',\n FailedToSubmitSponsorshipIntents = 'Failed to submit sponsorship intents',\n FailedToLinkRewards = 'Failed to link rewards',\n FailedToGetPricing = 'Failed to get pricing',\n FailedToGetBillingPortalUrl = 'Failed to get billing portal url',\n}\n\nexport const DEFAULT_POLLING_INTERVAL = 5 * 60 * 1_000; // 5 minutes\n\nexport const ACTIVE_SUBSCRIPTION_STATUSES = [\n SUBSCRIPTION_STATUSES.active,\n SUBSCRIPTION_STATUSES.trialing,\n SUBSCRIPTION_STATUSES.provisional,\n] as string[];\n"]}
1
+ {"version":3,"file":"constants.mjs","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,oBAAgB;AAEhD,MAAM,CAAC,MAAM,cAAc,GAAG,wBAAwB,CAAC;AAEvD,MAAM,CAAN,IAAY,GAIX;AAJD,WAAY,GAAG;IACb,kBAAW,CAAA;IACX,kBAAW,CAAA;IACX,kBAAW,CAAA;AACb,CAAC,EAJW,GAAG,KAAH,GAAG,QAId;AAMD,MAAM,QAAQ,GAA8B;IAC1C,GAAG,EAAE;QACH,kBAAkB,EAAE,6CAA6C;KAClE;IACD,GAAG,EAAE;QACH,kBAAkB,EAAE,6CAA6C;KAClE;IACD,GAAG,EAAE;QACH,kBAAkB,EAAE,yCAAyC;KAC9D;CACF,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,UAAU,UAAU,CAAC,GAAQ;IACjC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;IACvD,CAAC;IACD,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;AACvB,CAAC;AAED,MAAM,CAAN,IAAY,kCASX;AATD,WAAY,kCAAkC;IAC5C,mHAAwE,CAAA;IACxE,2GAAgE,CAAA;IAChE,wIAA6F,CAAA;IAC7F,iLAAsI,CAAA;IACtI,sHAA2E,CAAA;IAC3E,+GAAoE,CAAA;IACpE,sJAA2G,CAAA;IAC3G,2GAAgE,CAAA;AAClE,CAAC,EATW,kCAAkC,KAAlC,kCAAkC,QAS7C;AAED,MAAM,CAAC,MAAM,wBAAwB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAK,CAAC,CAAC,YAAY;AAEpE,MAAM,CAAC,MAAM,4BAA4B,GAAG;IAC1C,qBAAqB,CAAC,MAAM;IAC5B,qBAAqB,CAAC,QAAQ;IAC9B,qBAAqB,CAAC,WAAW;CACtB,CAAC","sourcesContent":["import { SUBSCRIPTION_STATUSES } from './types';\n\nexport const controllerName = 'SubscriptionController';\n\nexport enum Env {\n DEV = 'dev',\n UAT = 'uat',\n PRD = 'prd',\n}\n\ntype EnvUrlsEntry = {\n subscriptionApiUrl: string;\n};\n\nconst ENV_URLS: Record<Env, EnvUrlsEntry> = {\n dev: {\n subscriptionApiUrl: 'https://subscription.dev-api.cx.metamask.io',\n },\n uat: {\n subscriptionApiUrl: 'https://subscription.uat-api.cx.metamask.io',\n },\n prd: {\n subscriptionApiUrl: 'https://subscription.api.cx.metamask.io',\n },\n};\n\n/**\n * Validates and returns correct environment endpoints\n *\n * @param env - environment field\n * @returns the correct environment url\n * @throws on invalid environment passed\n */\nexport function getEnvUrls(env: Env): EnvUrlsEntry {\n if (!ENV_URLS[env]) {\n throw new Error('invalid environment configuration');\n }\n return ENV_URLS[env];\n}\n\nexport enum SubscriptionControllerErrorMessage {\n UserAlreadySubscribed = `${controllerName} - User is already subscribed`,\n UserNotSubscribed = `${controllerName} - User is not subscribed`,\n SubscriptionProductsEmpty = `${controllerName} - Subscription products array cannot be empty`,\n PaymentTokenAddressAndSymbolRequiredForCrypto = `${controllerName} - Payment token address and symbol are required for crypto payment`,\n PaymentMethodNotCrypto = `${controllerName} - Payment method is not crypto`,\n ProductPriceNotFound = `${controllerName} - Product price not found`,\n SubscriptionNotValidForCryptoApproval = `${controllerName} - Subscription is not valid for crypto approval`,\n LinkRewardsFailed = `${controllerName} - Failed to link rewards`,\n}\n\nexport const DEFAULT_POLLING_INTERVAL = 5 * 60 * 1_000; // 5 minutes\n\nexport const ACTIVE_SUBSCRIPTION_STATUSES = [\n SUBSCRIPTION_STATUSES.active,\n SUBSCRIPTION_STATUSES.trialing,\n SUBSCRIPTION_STATUSES.provisional,\n] as string[];\n"]}
package/dist/errors.cjs CHANGED
@@ -1,57 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createSentryError = exports.getErrorFromResponse = exports.SubscriptionServiceError = void 0;
3
+ exports.SubscriptionServiceError = void 0;
4
4
  class SubscriptionServiceError extends Error {
5
- constructor(message, options) {
5
+ constructor(message) {
6
6
  super(message);
7
7
  this.name = 'SubscriptionServiceError';
8
- this.cause = options?.cause;
9
8
  }
10
9
  }
11
10
  exports.SubscriptionServiceError = SubscriptionServiceError;
12
- /**
13
- * Get an error from a response.
14
- *
15
- * @param response - The response to get an error from.
16
- * @returns An error.
17
- */
18
- async function getErrorFromResponse(response) {
19
- const contentType = response.headers?.get('content-type');
20
- const statusCode = response.status;
21
- try {
22
- if (contentType?.includes('application/json')) {
23
- const json = await response.json();
24
- const errorMessage = json?.error ?? json?.message ?? 'Unknown error';
25
- const networkError = `error: ${errorMessage}, statusCode: ${statusCode}`;
26
- return new Error(networkError);
27
- }
28
- else if (contentType?.includes('text/plain')) {
29
- const text = await response.text();
30
- const networkError = `error: ${text}, statusCode: ${statusCode}`;
31
- return new Error(networkError);
32
- }
33
- const error = 'data' in response && typeof response.data === 'string'
34
- ? response.data
35
- : 'Unknown error';
36
- const networkError = `error: ${error}, statusCode: ${statusCode}`;
37
- return new Error(networkError);
38
- }
39
- catch {
40
- return new Error(`HTTP ${statusCode} error`);
41
- }
42
- }
43
- exports.getErrorFromResponse = getErrorFromResponse;
44
- /**
45
- * Creates an error instance with a readable message and the root cause.
46
- *
47
- * @param message - The error message to create a Sentry error from.
48
- * @param cause - The inner error to create a Sentry error from.
49
- * @returns A Sentry error.
50
- */
51
- function createSentryError(message, cause) {
52
- const sentryError = new Error(message);
53
- sentryError.cause = cause;
54
- return sentryError;
55
- }
56
- exports.createSentryError = createSentryError;
57
11
  //# sourceMappingURL=errors.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.cjs","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":";;;AAAA,MAAa,wBAAyB,SAAQ,KAAK;IAMjD,YACE,OAAe,EACf,OAEC;QAED,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAC;QACvC,IAAI,CAAC,KAAK,GAAG,OAAO,EAAE,KAAK,CAAC;IAC9B,CAAC;CACF;AAhBD,4DAgBC;AAED;;;;;GAKG;AACI,KAAK,UAAU,oBAAoB,CAAC,QAAkB;IAC3D,MAAM,WAAW,GAAG,QAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,cAAc,CAAC,CAAC;IAC1D,MAAM,UAAU,GAAG,QAAQ,CAAC,MAAM,CAAC;IACnC,IAAI,CAAC;QACH,IAAI,WAAW,EAAE,QAAQ,CAAC,kBAAkB,CAAC,EAAE,CAAC;YAC9C,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;YACnC,MAAM,YAAY,GAAG,IAAI,EAAE,KAAK,IAAI,IAAI,EAAE,OAAO,IAAI,eAAe,CAAC;YACrE,MAAM,YAAY,GAAG,UAAU,YAAY,iBAAiB,UAAU,EAAE,CAAC;YACzE,OAAO,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;QACjC,CAAC;aAAM,IAAI,WAAW,EAAE,QAAQ,CAAC,YAAY,CAAC,EAAE,CAAC;YAC/C,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;YACnC,MAAM,YAAY,GAAG,UAAU,IAAI,iBAAiB,UAAU,EAAE,CAAC;YACjE,OAAO,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;QACjC,CAAC;QAED,MAAM,KAAK,GACT,MAAM,IAAI,QAAQ,IAAI,OAAO,QAAQ,CAAC,IAAI,KAAK,QAAQ;YACrD,CAAC,CAAC,QAAQ,CAAC,IAAI;YACf,CAAC,CAAC,eAAe,CAAC;QACtB,MAAM,YAAY,GAAG,UAAU,KAAK,iBAAiB,UAAU,EAAE,CAAC;QAClE,OAAO,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;IACjC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,KAAK,CAAC,QAAQ,UAAU,QAAQ,CAAC,CAAC;IAC/C,CAAC;AACH,CAAC;AAxBD,oDAwBC;AAED;;;;;;GAMG;AACH,SAAgB,iBAAiB,CAAC,OAAe,EAAE,KAAY;IAC7D,MAAM,WAAW,GAAG,IAAI,KAAK,CAAC,OAAO,CAEpC,CAAC;IACF,WAAW,CAAC,KAAK,GAAG,KAAK,CAAC;IAE1B,OAAO,WAAW,CAAC;AACrB,CAAC;AAPD,8CAOC","sourcesContent":["export class SubscriptionServiceError extends Error {\n /**\n * The underlying error that caused this error.\n */\n cause?: Error;\n\n constructor(\n message: string,\n options?: {\n cause?: Error;\n },\n ) {\n super(message);\n this.name = 'SubscriptionServiceError';\n this.cause = options?.cause;\n }\n}\n\n/**\n * Get an error from a response.\n *\n * @param response - The response to get an error from.\n * @returns An error.\n */\nexport async function getErrorFromResponse(response: Response): Promise<Error> {\n const contentType = response.headers?.get('content-type');\n const statusCode = response.status;\n try {\n if (contentType?.includes('application/json')) {\n const json = await response.json();\n const errorMessage = json?.error ?? json?.message ?? 'Unknown error';\n const networkError = `error: ${errorMessage}, statusCode: ${statusCode}`;\n return new Error(networkError);\n } else if (contentType?.includes('text/plain')) {\n const text = await response.text();\n const networkError = `error: ${text}, statusCode: ${statusCode}`;\n return new Error(networkError);\n }\n\n const error =\n 'data' in response && typeof response.data === 'string'\n ? response.data\n : 'Unknown error';\n const networkError = `error: ${error}, statusCode: ${statusCode}`;\n return new Error(networkError);\n } catch {\n return new Error(`HTTP ${statusCode} error`);\n }\n}\n\n/**\n * Creates an error instance with a readable message and the root cause.\n *\n * @param message - The error message to create a Sentry error from.\n * @param cause - The inner error to create a Sentry error from.\n * @returns A Sentry error.\n */\nexport function createSentryError(message: string, cause: Error): Error {\n const sentryError = new Error(message) as Error & {\n cause: Error;\n };\n sentryError.cause = cause;\n\n return sentryError;\n}\n"]}
1
+ {"version":3,"file":"errors.cjs","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":";;;AAAA,MAAa,wBAAyB,SAAQ,KAAK;IACjD,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAC;IACzC,CAAC;CACF;AALD,4DAKC","sourcesContent":["export class SubscriptionServiceError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'SubscriptionServiceError';\n }\n}\n"]}
package/dist/errors.d.cts CHANGED
@@ -1,25 +1,4 @@
1
1
  export declare class SubscriptionServiceError extends Error {
2
- /**
3
- * The underlying error that caused this error.
4
- */
5
- cause?: Error;
6
- constructor(message: string, options?: {
7
- cause?: Error;
8
- });
2
+ constructor(message: string);
9
3
  }
10
- /**
11
- * Get an error from a response.
12
- *
13
- * @param response - The response to get an error from.
14
- * @returns An error.
15
- */
16
- export declare function getErrorFromResponse(response: Response): Promise<Error>;
17
- /**
18
- * Creates an error instance with a readable message and the root cause.
19
- *
20
- * @param message - The error message to create a Sentry error from.
21
- * @param cause - The inner error to create a Sentry error from.
22
- * @returns A Sentry error.
23
- */
24
- export declare function createSentryError(message: string, cause: Error): Error;
25
4
  //# sourceMappingURL=errors.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.cts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,qBAAa,wBAAyB,SAAQ,KAAK;IACjD;;OAEG;IACH,KAAK,CAAC,EAAE,KAAK,CAAC;gBAGZ,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE;QACR,KAAK,CAAC,EAAE,KAAK,CAAC;KACf;CAMJ;AAED;;;;;GAKG;AACH,wBAAsB,oBAAoB,CAAC,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC,KAAK,CAAC,CAwB7E;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,GAAG,KAAK,CAOtE"}
1
+ {"version":3,"file":"errors.d.cts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,qBAAa,wBAAyB,SAAQ,KAAK;gBACrC,OAAO,EAAE,MAAM;CAI5B"}