@talosjs/payment 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,843 @@
1
+ // @bun
2
+ var __legacyDecorateClassTS = function(decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
5
+ r = Reflect.decorate(decorators, target, key, desc);
6
+ else
7
+ for (var i = decorators.length - 1;i >= 0; i--)
8
+ if (d = decorators[i])
9
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
10
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
11
+ };
12
+ var __legacyDecorateParamTS = (index, decorator) => (target, key) => decorator(target, key, index);
13
+ var __legacyMetadataTS = (k, v) => {
14
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
15
+ return Reflect.metadata(k, v);
16
+ };
17
+
18
+ // src/PaymentException.ts
19
+ import { Exception } from "@talosjs/exception";
20
+ import { HttpStatus } from "@talosjs/http-status";
21
+
22
+ class PaymentException extends Exception {
23
+ constructor(message, key, data = {}) {
24
+ super(message, {
25
+ key,
26
+ status: HttpStatus.Code.InternalServerError,
27
+ data
28
+ });
29
+ this.name = "PaymentException";
30
+ }
31
+ }
32
+ // src/PolarAnalytics.ts
33
+ import { AppEnv } from "@talosjs/app-env";
34
+ import { inject, injectable } from "@talosjs/container";
35
+ import { Polar } from "@polar-sh/sdk";
36
+ class PolarAnalytics {
37
+ env;
38
+ client;
39
+ constructor(env) {
40
+ this.env = env;
41
+ const accessToken = this.env.POLAR_ACCESS_TOKEN;
42
+ if (!accessToken) {
43
+ throw new PaymentException("Polar access token is required. Please set the POLAR_ACCESS_TOKEN environment variable.", "TOKEN_REQUIRED");
44
+ }
45
+ this.client = new Polar({
46
+ accessToken,
47
+ server: this.env.POLAR_ENVIRONMENT || "production"
48
+ });
49
+ }
50
+ async get(options) {
51
+ const response = await this.client.metrics.get({
52
+ startDate: this.toRFCDate(options.startDate),
53
+ endDate: this.toRFCDate(options.endDate),
54
+ interval: options.interval,
55
+ organizationId: options.organizationId ?? null,
56
+ productId: options.productId ?? null,
57
+ billingType: options.billingType ?? null,
58
+ customerId: options.customerId ?? null
59
+ });
60
+ return {
61
+ periods: response.periods.map((period) => this.mapPeriod(period)),
62
+ metrics: this.mapMetrics(response.metrics)
63
+ };
64
+ }
65
+ async getLimits() {
66
+ const response = await this.client.metrics.limits();
67
+ return {
68
+ minDate: new Date(response.minDate.toString()),
69
+ intervals: this.mapIntervalsLimits(response.intervals)
70
+ };
71
+ }
72
+ toRFCDate(date) {
73
+ const year = date.getFullYear();
74
+ const month = String(date.getMonth() + 1).padStart(2, "0");
75
+ const day = String(date.getDate()).padStart(2, "0");
76
+ return `${year}-${month}-${day}`;
77
+ }
78
+ mapPeriod(period) {
79
+ return {
80
+ timestamp: period.timestamp,
81
+ orders: period.orders,
82
+ revenue: period.revenue,
83
+ cumulativeRevenue: period.cumulativeRevenue,
84
+ averageOrderValue: period.averageOrderValue,
85
+ oneTimeProducts: period.oneTimeProducts,
86
+ oneTimeProductsRevenue: period.oneTimeProductsRevenue,
87
+ newSubscriptions: period.newSubscriptions,
88
+ newSubscriptionsRevenue: period.newSubscriptionsRevenue,
89
+ renewedSubscriptions: period.renewedSubscriptions,
90
+ renewedSubscriptionsRevenue: period.renewedSubscriptionsRevenue,
91
+ activeSubscriptions: period.activeSubscriptions,
92
+ monthlyRecurringRevenue: period.monthlyRecurringRevenue
93
+ };
94
+ }
95
+ mapMetricInfo(metric) {
96
+ return {
97
+ slug: metric.slug,
98
+ displayName: metric.displayName,
99
+ type: metric.type
100
+ };
101
+ }
102
+ mapMetrics(metrics) {
103
+ return {
104
+ orders: this.mapMetricInfo(metrics.orders),
105
+ revenue: this.mapMetricInfo(metrics.revenue),
106
+ cumulativeRevenue: this.mapMetricInfo(metrics.cumulativeRevenue),
107
+ averageOrderValue: this.mapMetricInfo(metrics.averageOrderValue),
108
+ oneTimeProducts: this.mapMetricInfo(metrics.oneTimeProducts),
109
+ oneTimeProductsRevenue: this.mapMetricInfo(metrics.oneTimeProductsRevenue),
110
+ newSubscriptions: this.mapMetricInfo(metrics.newSubscriptions),
111
+ newSubscriptionsRevenue: this.mapMetricInfo(metrics.newSubscriptionsRevenue),
112
+ renewedSubscriptions: this.mapMetricInfo(metrics.renewedSubscriptions),
113
+ renewedSubscriptionsRevenue: this.mapMetricInfo(metrics.renewedSubscriptionsRevenue),
114
+ activeSubscriptions: this.mapMetricInfo(metrics.activeSubscriptions),
115
+ monthlyRecurringRevenue: this.mapMetricInfo(metrics.monthlyRecurringRevenue)
116
+ };
117
+ }
118
+ mapIntervalsLimits(intervals) {
119
+ return {
120
+ hour: { maxDays: intervals.hour.maxDays },
121
+ day: { maxDays: intervals.day.maxDays },
122
+ week: { maxDays: intervals.week.maxDays },
123
+ month: { maxDays: intervals.month.maxDays },
124
+ year: { maxDays: intervals.year.maxDays }
125
+ };
126
+ }
127
+ }
128
+ PolarAnalytics = __legacyDecorateClassTS([
129
+ injectable(),
130
+ __legacyDecorateParamTS(0, inject(AppEnv)),
131
+ __legacyMetadataTS("design:paramtypes", [
132
+ typeof AppEnv === "undefined" ? Object : AppEnv
133
+ ])
134
+ ], PolarAnalytics);
135
+ // src/PolarCheckout.ts
136
+ import { AppEnv as AppEnv2 } from "@talosjs/app-env";
137
+ import { inject as inject2, injectable as injectable2 } from "@talosjs/container";
138
+ import { Polar as Polar2 } from "@polar-sh/sdk";
139
+ class PolarCheckout {
140
+ env;
141
+ client;
142
+ constructor(env) {
143
+ this.env = env;
144
+ const accessToken = this.env.POLAR_ACCESS_TOKEN;
145
+ if (!accessToken) {
146
+ throw new PaymentException("Polar access token is required. Please set the POLAR_ACCESS_TOKEN environment variable.", "TOKEN_REQUIRED");
147
+ }
148
+ this.client = new Polar2({
149
+ accessToken,
150
+ server: this.env.POLAR_ENVIRONMENT || "production"
151
+ });
152
+ }
153
+ async create(data) {
154
+ const response = await this.client.checkouts.create({
155
+ products: data.products,
156
+ customerExternalId: data.customerExternalId ?? null,
157
+ customerId: data.customerId ?? null,
158
+ customerEmail: data.customerEmail ?? null,
159
+ customerName: data.customerName ?? null,
160
+ customerBillingAddress: data.customerBillingAddress?.country ? {
161
+ country: data.customerBillingAddress.country,
162
+ line1: data.customerBillingAddress.line1 ?? null,
163
+ line2: data.customerBillingAddress.line2 ?? null,
164
+ city: data.customerBillingAddress.city ?? null,
165
+ state: data.customerBillingAddress.state ?? null,
166
+ postalCode: data.customerBillingAddress.postalCode ?? null
167
+ } : null,
168
+ customerTaxId: data.customerTaxId ?? null,
169
+ discountId: data.discountId ?? null,
170
+ allowDiscountCodes: data.allowDiscountCodes ?? true,
171
+ successUrl: data.successUrl ?? null,
172
+ embedOrigin: data.embedOrigin ?? null,
173
+ metadata: data.metadata
174
+ });
175
+ return this.mapResponse(response);
176
+ }
177
+ async get(id) {
178
+ const response = await this.client.checkouts.get({ id });
179
+ return this.mapResponse(response);
180
+ }
181
+ mapResponse(response) {
182
+ const checkout = {
183
+ id: response.id,
184
+ status: response.status,
185
+ clientSecret: response.clientSecret
186
+ };
187
+ if (response.url) {
188
+ checkout.url = response.url;
189
+ }
190
+ if (response.embedId) {
191
+ checkout.embedId = response.embedId;
192
+ }
193
+ if (response.allowDiscountCodes !== undefined) {
194
+ checkout.allowDiscountCodes = response.allowDiscountCodes;
195
+ }
196
+ if (response.isDiscountApplicable !== undefined) {
197
+ checkout.isDiscountApplicable = response.isDiscountApplicable;
198
+ }
199
+ if (response.isPaymentRequired !== undefined) {
200
+ checkout.isPaymentRequired = response.isPaymentRequired;
201
+ }
202
+ if (response.metadata) {
203
+ checkout.metadata = response.metadata;
204
+ }
205
+ if (response.createdAt) {
206
+ checkout.createdAt = response.createdAt;
207
+ }
208
+ if (response.modifiedAt) {
209
+ checkout.updatedAt = response.modifiedAt;
210
+ }
211
+ if (response.expiresAt) {
212
+ checkout.expiresAt = response.expiresAt;
213
+ }
214
+ if (response.successUrl) {
215
+ checkout.successUrl = response.successUrl;
216
+ }
217
+ if (response.embedOrigin) {
218
+ checkout.embedOrigin = response.embedOrigin;
219
+ }
220
+ if (response.amount !== undefined) {
221
+ checkout.amount = response.amount;
222
+ }
223
+ if (response.taxAmount !== undefined) {
224
+ checkout.taxAmount = response.taxAmount;
225
+ }
226
+ if (response.currency) {
227
+ checkout.currency = response.currency;
228
+ }
229
+ if (response.subtotalAmount !== undefined) {
230
+ checkout.subtotalAmount = response.subtotalAmount;
231
+ }
232
+ if (response.totalAmount !== undefined) {
233
+ checkout.totalAmount = response.totalAmount;
234
+ }
235
+ if (response.productId) {
236
+ checkout.productId = response.productId;
237
+ }
238
+ if (response.productPriceId) {
239
+ checkout.productPriceId = response.productPriceId;
240
+ }
241
+ if (response.discountId) {
242
+ checkout.discountId = response.discountId;
243
+ }
244
+ if (response.customer) {
245
+ checkout.customer = {
246
+ id: response.customer.id,
247
+ email: response.customer.email,
248
+ name: response.customer.name,
249
+ externalId: response.customer.externalId,
250
+ taxId: response.customer.taxId
251
+ };
252
+ if (response.customer.billingAddress) {
253
+ checkout.customer.billingAddress = response.customer.billingAddress;
254
+ }
255
+ }
256
+ return checkout;
257
+ }
258
+ }
259
+ PolarCheckout = __legacyDecorateClassTS([
260
+ injectable2(),
261
+ __legacyDecorateParamTS(0, inject2(AppEnv2)),
262
+ __legacyMetadataTS("design:paramtypes", [
263
+ typeof AppEnv2 === "undefined" ? Object : AppEnv2
264
+ ])
265
+ ], PolarCheckout);
266
+ // src/PolarCustomer.ts
267
+ import { AppEnv as AppEnv3 } from "@talosjs/app-env";
268
+ import { inject as inject3, injectable as injectable3 } from "@talosjs/container";
269
+ import { Polar as Polar3 } from "@polar-sh/sdk";
270
+ class PolarCustomer {
271
+ env;
272
+ client;
273
+ constructor(env) {
274
+ this.env = env;
275
+ const accessToken = this.env.POLAR_ACCESS_TOKEN;
276
+ if (!accessToken) {
277
+ throw new PaymentException("Polar access token is required. Please set the POLAR_ACCESS_TOKEN environment variable.", "TOKEN_REQUIRED");
278
+ }
279
+ this.client = new Polar3({
280
+ accessToken,
281
+ server: this.env.POLAR_ENVIRONMENT || "production"
282
+ });
283
+ }
284
+ async create(data) {
285
+ const response = await this.client.customers.create({
286
+ email: data.email,
287
+ name: data.name ?? null,
288
+ externalId: data.externalId ?? null,
289
+ billingAddress: data.billingAddress ? this.toBillingAddress(data.billingAddress) : null,
290
+ taxId: data.taxId ? [data.taxId, null] : null,
291
+ organizationId: data.organizationId ?? null,
292
+ metadata: data.metadata
293
+ });
294
+ return this.mapResponse(response);
295
+ }
296
+ async update(id, data) {
297
+ const response = await this.client.customers.update({
298
+ id,
299
+ customerUpdate: {
300
+ email: data.email ?? null,
301
+ name: data.name ?? null,
302
+ billingAddress: data.billingAddress ? this.toBillingAddress(data.billingAddress) : null,
303
+ taxId: data.taxId ? [data.taxId, null] : null,
304
+ metadata: data.metadata
305
+ }
306
+ });
307
+ return this.mapResponse(response);
308
+ }
309
+ async remove(id) {
310
+ await this.client.customers.delete({ id });
311
+ }
312
+ async get(id) {
313
+ const response = await this.client.customers.get({ id });
314
+ return this.mapResponse(response);
315
+ }
316
+ async list(options) {
317
+ const response = await this.client.customers.list({
318
+ organizationId: options?.organizationId,
319
+ email: options?.email,
320
+ query: options?.query,
321
+ page: options?.page ?? 1,
322
+ limit: options?.limit ?? 10
323
+ });
324
+ const result = response;
325
+ return {
326
+ items: result.result.items.map((item) => this.mapResponse(item)),
327
+ pagination: {
328
+ totalCount: result.result.pagination.totalCount,
329
+ maxPage: result.result.pagination.maxPage
330
+ }
331
+ };
332
+ }
333
+ async getByExternalId(externalId) {
334
+ const response = await this.client.customers.getExternal({ externalId });
335
+ return this.mapResponse(response);
336
+ }
337
+ async updateByExternalId(externalId, data) {
338
+ const response = await this.client.customers.updateExternal({
339
+ externalId,
340
+ customerUpdate: {
341
+ email: data.email ?? null,
342
+ name: data.name ?? null,
343
+ billingAddress: data.billingAddress ? this.toBillingAddress(data.billingAddress) : null,
344
+ taxId: data.taxId ? [data.taxId, null] : null,
345
+ metadata: data.metadata
346
+ }
347
+ });
348
+ return this.mapResponse(response);
349
+ }
350
+ async removeByExternalId(externalId) {
351
+ await this.client.customers.deleteExternal({ externalId });
352
+ }
353
+ toBillingAddress(address) {
354
+ return {
355
+ country: address.country ?? "",
356
+ line1: address.line1,
357
+ line2: address.line2,
358
+ city: address.city,
359
+ state: address.state,
360
+ postalCode: address.postalCode
361
+ };
362
+ }
363
+ mapResponse(response) {
364
+ const customer = {
365
+ id: response.id,
366
+ email: response.email,
367
+ emailVerified: response.emailVerified ?? false
368
+ };
369
+ if (response.createdAt) {
370
+ customer.createdAt = response.createdAt;
371
+ }
372
+ if (response.modifiedAt) {
373
+ customer.updatedAt = response.modifiedAt;
374
+ }
375
+ if (response.deletedAt) {
376
+ customer.deletedAt = response.deletedAt;
377
+ }
378
+ if (response.name) {
379
+ customer.name = response.name;
380
+ }
381
+ if (response.externalId) {
382
+ customer.externalId = response.externalId;
383
+ }
384
+ if (response.avatarUrl) {
385
+ customer.avatarUrl = response.avatarUrl;
386
+ }
387
+ if (response.billingAddress) {
388
+ const billingAddress = {};
389
+ if (response.billingAddress.line1) {
390
+ billingAddress.line1 = response.billingAddress.line1;
391
+ }
392
+ if (response.billingAddress.line2) {
393
+ billingAddress.line2 = response.billingAddress.line2;
394
+ }
395
+ if (response.billingAddress.city) {
396
+ billingAddress.city = response.billingAddress.city;
397
+ }
398
+ if (response.billingAddress.state) {
399
+ billingAddress.state = response.billingAddress.state;
400
+ }
401
+ if (response.billingAddress.postalCode) {
402
+ billingAddress.postalCode = response.billingAddress.postalCode;
403
+ }
404
+ if (response.billingAddress.country) {
405
+ billingAddress.country = response.billingAddress.country;
406
+ }
407
+ customer.billingAddress = billingAddress;
408
+ }
409
+ if (response.taxId) {
410
+ const taxIdValue = typeof response.taxId === "string" ? response.taxId : response.taxId[1];
411
+ customer.taxId = taxIdValue;
412
+ }
413
+ if (response.organizationId) {
414
+ customer.organizationId = response.organizationId;
415
+ }
416
+ if (response.metadata) {
417
+ customer.metadata = response.metadata;
418
+ }
419
+ return customer;
420
+ }
421
+ }
422
+ PolarCustomer = __legacyDecorateClassTS([
423
+ injectable3(),
424
+ __legacyDecorateParamTS(0, inject3(AppEnv3)),
425
+ __legacyMetadataTS("design:paramtypes", [
426
+ typeof AppEnv3 === "undefined" ? Object : AppEnv3
427
+ ])
428
+ ], PolarCustomer);
429
+ // src/PolarCustomerPortal.ts
430
+ import { AppEnv as AppEnv4 } from "@talosjs/app-env";
431
+ import { inject as inject4, injectable as injectable4 } from "@talosjs/container";
432
+ import { Polar as Polar4 } from "@polar-sh/sdk";
433
+ class PolarCustomerPortal {
434
+ env;
435
+ client;
436
+ constructor(env) {
437
+ this.env = env;
438
+ const accessToken = this.env.POLAR_ACCESS_TOKEN;
439
+ if (!accessToken) {
440
+ throw new PaymentException("Polar access token is required. Please set the POLAR_ACCESS_TOKEN environment variable.", "TOKEN_REQUIRED");
441
+ }
442
+ this.client = new Polar4({
443
+ accessToken,
444
+ server: this.env.POLAR_ENVIRONMENT || "production"
445
+ });
446
+ }
447
+ async create(data) {
448
+ const response = await this.client.customerSessions.create({
449
+ customerId: data.customerId
450
+ });
451
+ return this.mapResponse(response);
452
+ }
453
+ getPortalUrl(organizationSlug) {
454
+ const baseUrl = this.env.POLAR_ENVIRONMENT === "sandbox" ? "https://sandbox.polar.sh" : "https://polar.sh";
455
+ return `${baseUrl}/${organizationSlug}/portal`;
456
+ }
457
+ mapResponse(response) {
458
+ const session = {
459
+ id: response.id,
460
+ token: response.token,
461
+ customerPortalUrl: response.customerPortalUrl
462
+ };
463
+ if (response.createdAt) {
464
+ session.createdAt = response.createdAt;
465
+ }
466
+ if (response.expiresAt) {
467
+ session.expiresAt = response.expiresAt;
468
+ }
469
+ if (response.customerId) {
470
+ session.customerId = response.customerId;
471
+ }
472
+ return session;
473
+ }
474
+ }
475
+ PolarCustomerPortal = __legacyDecorateClassTS([
476
+ injectable4(),
477
+ __legacyDecorateParamTS(0, inject4(AppEnv4)),
478
+ __legacyMetadataTS("design:paramtypes", [
479
+ typeof AppEnv4 === "undefined" ? Object : AppEnv4
480
+ ])
481
+ ], PolarCustomerPortal);
482
+ // src/PolarDiscount.ts
483
+ import { AppEnv as AppEnv5 } from "@talosjs/app-env";
484
+ import { inject as inject5, injectable as injectable5 } from "@talosjs/container";
485
+ import { Polar as Polar5 } from "@polar-sh/sdk";
486
+ class PolarDiscount {
487
+ env;
488
+ client;
489
+ constructor(env) {
490
+ this.env = env;
491
+ const accessToken = this.env.POLAR_ACCESS_TOKEN;
492
+ if (!accessToken) {
493
+ throw new PaymentException("Polar access token is required. Please set the POLAR_ACCESS_TOKEN environment variable.", "TOKEN_REQUIRED");
494
+ }
495
+ this.client = new Polar5({
496
+ accessToken,
497
+ server: this.env.POLAR_ENVIRONMENT || "production"
498
+ });
499
+ }
500
+ toDiscountType(type) {
501
+ return type === "percentage" ? "percentage" : "fixed";
502
+ }
503
+ toDiscountDuration(duration) {
504
+ switch (duration) {
505
+ case "once":
506
+ return "once";
507
+ case "repeating":
508
+ return "repeating";
509
+ case "forever":
510
+ return "forever";
511
+ default:
512
+ return "once";
513
+ }
514
+ }
515
+ async create(data) {
516
+ const discountType = this.toDiscountType(data.type);
517
+ const duration = this.toDiscountDuration(data.duration);
518
+ const basePayload = {
519
+ name: data.name,
520
+ code: data.code ?? null,
521
+ startsAt: data.startAt ?? null,
522
+ endsAt: data.endAt ?? null,
523
+ maxRedemptions: data.maxRedemptions ?? null,
524
+ organizationId: data.organizationId ?? null,
525
+ metadata: data.metadata,
526
+ products: data.applicableProducts?.map((p) => p.id) ?? null
527
+ };
528
+ let response;
529
+ if (discountType === "percentage") {
530
+ if (duration === "repeating") {
531
+ response = await this.client.discounts.create({
532
+ ...basePayload,
533
+ type: "percentage",
534
+ basisPoints: data.amount * 100,
535
+ duration: "repeating",
536
+ durationInMonths: data.durationInMonths ?? 1
537
+ });
538
+ } else {
539
+ response = await this.client.discounts.create({
540
+ ...basePayload,
541
+ type: "percentage",
542
+ basisPoints: data.amount * 100,
543
+ duration
544
+ });
545
+ }
546
+ } else {
547
+ if (duration === "repeating") {
548
+ response = await this.client.discounts.create({
549
+ ...basePayload,
550
+ type: "fixed",
551
+ amount: data.amount,
552
+ currency: data.currency ?? "usd",
553
+ duration: "repeating",
554
+ durationInMonths: data.durationInMonths ?? 1
555
+ });
556
+ } else {
557
+ response = await this.client.discounts.create({
558
+ ...basePayload,
559
+ type: "fixed",
560
+ amount: data.amount,
561
+ currency: data.currency ?? "usd",
562
+ duration
563
+ });
564
+ }
565
+ }
566
+ return this.mapResponse(response);
567
+ }
568
+ async update(id, data) {
569
+ const response = await this.client.discounts.update({
570
+ id,
571
+ discountUpdate: {
572
+ name: data.name ?? null,
573
+ code: data.code ?? null,
574
+ startsAt: data.startAt ?? null,
575
+ endsAt: data.endAt ?? null,
576
+ maxRedemptions: data.maxRedemptions ?? null,
577
+ metadata: data.metadata,
578
+ products: data.applicableProducts?.map((p) => p.id) ?? null
579
+ }
580
+ });
581
+ return this.mapResponse(response);
582
+ }
583
+ async remove(id) {
584
+ await this.client.discounts.delete({ id });
585
+ }
586
+ async get(id) {
587
+ const response = await this.client.discounts.get({ id });
588
+ return this.mapResponse(response);
589
+ }
590
+ mapResponse(response) {
591
+ const discount = {
592
+ id: response.id,
593
+ name: response.name,
594
+ type: response.type,
595
+ amount: response.type === "percentage" ? (response.basisPoints ?? 0) / 100 : response.amount ?? 0,
596
+ duration: response.duration,
597
+ redemptionsCount: response.redemptionsCount,
598
+ metadata: response.metadata
599
+ };
600
+ if (response.createdAt) {
601
+ discount.createdAt = response.createdAt;
602
+ }
603
+ if (response.modifiedAt) {
604
+ discount.updatedAt = response.modifiedAt;
605
+ }
606
+ if (response.code) {
607
+ discount.code = response.code;
608
+ }
609
+ if (response.startsAt) {
610
+ discount.startAt = response.startsAt;
611
+ }
612
+ if (response.endsAt) {
613
+ discount.endAt = response.endsAt;
614
+ }
615
+ if (response.maxRedemptions) {
616
+ discount.maxRedemptions = response.maxRedemptions;
617
+ }
618
+ if (response.durationInMonths) {
619
+ discount.durationInMonths = response.durationInMonths;
620
+ }
621
+ if (response.organizationId) {
622
+ discount.organizationId = response.organizationId;
623
+ }
624
+ if (response.currency) {
625
+ discount.currency = response.currency;
626
+ }
627
+ if (response.products) {
628
+ discount.applicableProducts = response.products.map((p) => ({
629
+ id: p.id,
630
+ name: p.name
631
+ }));
632
+ }
633
+ return discount;
634
+ }
635
+ }
636
+ PolarDiscount = __legacyDecorateClassTS([
637
+ injectable5(),
638
+ __legacyDecorateParamTS(0, inject5(AppEnv5)),
639
+ __legacyMetadataTS("design:paramtypes", [
640
+ typeof AppEnv5 === "undefined" ? Object : AppEnv5
641
+ ])
642
+ ], PolarDiscount);
643
+ // src/PolarProduct.ts
644
+ import { AppEnv as AppEnv6 } from "@talosjs/app-env";
645
+ import { inject as inject6, injectable as injectable6 } from "@talosjs/container";
646
+ import { Polar as Polar6 } from "@polar-sh/sdk";
647
+ class PolarProduct {
648
+ env;
649
+ client;
650
+ constructor(env) {
651
+ this.env = env;
652
+ const accessToken = this.env.POLAR_ACCESS_TOKEN;
653
+ if (!accessToken) {
654
+ throw new PaymentException("Polar access token is required. Please set the POLAR_ACCESS_TOKEN environment variable.", "TOKEN_REQUIRED");
655
+ }
656
+ this.client = new Polar6({
657
+ accessToken,
658
+ server: this.env.POLAR_ENVIRONMENT || "production"
659
+ });
660
+ }
661
+ toRecurringInterval(period) {
662
+ if (!period)
663
+ return null;
664
+ switch (period) {
665
+ case "monthly":
666
+ return "month";
667
+ case "yearly":
668
+ return "year";
669
+ default:
670
+ return null;
671
+ }
672
+ }
673
+ async create(data) {
674
+ const response = await this.client.products.create({
675
+ name: data.name,
676
+ description: data.description ?? null,
677
+ recurringInterval: this.toRecurringInterval(data.recurringInterval),
678
+ prices: data.prices?.map((price) => ({
679
+ type: price.type,
680
+ priceCurrency: price.priceCurrency ?? "usd",
681
+ priceAmount: price.priceAmount,
682
+ minimumAmount: price.minimumAmount,
683
+ maximumAmount: price.maximumAmount,
684
+ presetAmount: price.presetAmount
685
+ })) ?? [],
686
+ medias: data.images?.map((image) => image.url) ?? null,
687
+ organizationId: data.organizationId ?? null,
688
+ metadata: data.metadata,
689
+ attachedCustomFields: data.attachedCustomFields?.map((field) => ({
690
+ customFieldId: field.customFieldId,
691
+ required: field.required
692
+ }))
693
+ });
694
+ return this.mapResponse(response);
695
+ }
696
+ async update(id, data) {
697
+ const response = await this.client.products.update({
698
+ id,
699
+ productUpdate: {
700
+ name: data.name ?? null,
701
+ description: data.description ?? null,
702
+ isArchived: data.isArchived ?? null,
703
+ recurringInterval: this.toRecurringInterval(data.recurringInterval),
704
+ prices: data.prices?.map((price) => ({
705
+ type: price.type,
706
+ priceCurrency: price.priceCurrency ?? "usd",
707
+ priceAmount: price.priceAmount,
708
+ minimumAmount: price.minimumAmount,
709
+ maximumAmount: price.maximumAmount,
710
+ presetAmount: price.presetAmount
711
+ })) ?? null,
712
+ medias: data.images?.map((image) => image.url) ?? null,
713
+ metadata: data.metadata,
714
+ attachedCustomFields: data.attachedCustomFields?.map((field) => ({
715
+ customFieldId: field.customFieldId,
716
+ required: field.required
717
+ })) ?? null
718
+ }
719
+ });
720
+ return this.mapResponse(response);
721
+ }
722
+ async remove(id) {
723
+ await this.client.products.update({
724
+ id,
725
+ productUpdate: {
726
+ isArchived: true
727
+ }
728
+ });
729
+ }
730
+ mapResponse(response) {
731
+ const product = {
732
+ key: response.id,
733
+ name: response.name,
734
+ isRecurring: response.isRecurring,
735
+ isArchived: response.isArchived,
736
+ organizationId: response.organizationId,
737
+ metadata: response.metadata,
738
+ prices: response.prices,
739
+ benefits: response.benefits,
740
+ attachedCustomFields: response.attachedCustomFields
741
+ };
742
+ if (response.createdAt) {
743
+ product.createdAt = response.createdAt;
744
+ }
745
+ if (response.modifiedAt) {
746
+ product.updatedAt = response.modifiedAt;
747
+ }
748
+ if (response.description) {
749
+ product.description = response.description;
750
+ }
751
+ return product;
752
+ }
753
+ }
754
+ PolarProduct = __legacyDecorateClassTS([
755
+ injectable6(),
756
+ __legacyDecorateParamTS(0, inject6(AppEnv6)),
757
+ __legacyMetadataTS("design:paramtypes", [
758
+ typeof AppEnv6 === "undefined" ? Object : AppEnv6
759
+ ])
760
+ ], PolarProduct);
761
+ // src/types.ts
762
+ var EPriceType;
763
+ ((EPriceType2) => {
764
+ EPriceType2["FIXED"] = "fixed";
765
+ EPriceType2["CUSTOM"] = "custom";
766
+ EPriceType2["FREE"] = "free";
767
+ })(EPriceType ||= {});
768
+ var EDiscountType;
769
+ ((EDiscountType2) => {
770
+ EDiscountType2["PERCENTAGE"] = "percentage";
771
+ EDiscountType2["FIXED"] = "fixed";
772
+ })(EDiscountType ||= {});
773
+ var EDiscountDuration;
774
+ ((EDiscountDuration2) => {
775
+ EDiscountDuration2["ONCE"] = "once";
776
+ EDiscountDuration2["REPEATING"] = "repeating";
777
+ EDiscountDuration2["FOREVER"] = "forever";
778
+ })(EDiscountDuration ||= {});
779
+ var ESubscriptionPeriod;
780
+ ((ESubscriptionPeriod2) => {
781
+ ESubscriptionPeriod2["MONTHLY"] = "monthly";
782
+ ESubscriptionPeriod2["YEARLY"] = "yearly";
783
+ ESubscriptionPeriod2["WEEKLY"] = "weekly";
784
+ ESubscriptionPeriod2["DAILY"] = "daily";
785
+ })(ESubscriptionPeriod ||= {});
786
+ var EBenefitType;
787
+ ((EBenefitType2) => {
788
+ EBenefitType2["CREDITS"] = "credits";
789
+ EBenefitType2["LICENSE_KEYS"] = "license_keys";
790
+ EBenefitType2["FILE_DOWNLOADS"] = "file_downloads";
791
+ EBenefitType2["GITHUB_REPOSITORY_ACCESS"] = "github_repository_access";
792
+ EBenefitType2["DISCORD_ACCESS"] = "discord_access";
793
+ EBenefitType2["CUSTOM"] = "custom";
794
+ })(EBenefitType ||= {});
795
+ var EGitHubPermission;
796
+ ((EGitHubPermission2) => {
797
+ EGitHubPermission2["READ"] = "read";
798
+ EGitHubPermission2["TRIAGE"] = "triage";
799
+ EGitHubPermission2["WRITE"] = "write";
800
+ EGitHubPermission2["MAINTAIN"] = "maintain";
801
+ EGitHubPermission2["ADMIN"] = "admin";
802
+ })(EGitHubPermission ||= {});
803
+ var ECheckoutStatus;
804
+ ((ECheckoutStatus2) => {
805
+ ECheckoutStatus2["OPEN"] = "open";
806
+ ECheckoutStatus2["EXPIRED"] = "expired";
807
+ ECheckoutStatus2["CONFIRMED"] = "confirmed";
808
+ ECheckoutStatus2["SUCCEEDED"] = "succeeded";
809
+ ECheckoutStatus2["FAILED"] = "failed";
810
+ })(ECheckoutStatus ||= {});
811
+ var EAnalyticsInterval;
812
+ ((EAnalyticsInterval2) => {
813
+ EAnalyticsInterval2["YEAR"] = "year";
814
+ EAnalyticsInterval2["MONTH"] = "month";
815
+ EAnalyticsInterval2["WEEK"] = "week";
816
+ EAnalyticsInterval2["DAY"] = "day";
817
+ EAnalyticsInterval2["HOUR"] = "hour";
818
+ })(EAnalyticsInterval ||= {});
819
+ var EBillingType;
820
+ ((EBillingType2) => {
821
+ EBillingType2["ONE_TIME"] = "one_time";
822
+ EBillingType2["RECURRING"] = "recurring";
823
+ })(EBillingType ||= {});
824
+ export {
825
+ PolarProduct,
826
+ PolarDiscount,
827
+ PolarCustomerPortal,
828
+ PolarCustomer,
829
+ PolarCheckout,
830
+ PolarAnalytics,
831
+ PaymentException,
832
+ ESubscriptionPeriod,
833
+ EPriceType,
834
+ EGitHubPermission,
835
+ EDiscountType,
836
+ EDiscountDuration,
837
+ ECheckoutStatus,
838
+ EBillingType,
839
+ EBenefitType,
840
+ EAnalyticsInterval
841
+ };
842
+
843
+ //# debugId=1D32103632506D8764756E2164756E21