@paykit-sdk/polar 1.1.92 → 1.1.93

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.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { schema, validateRequiredKeys, AbstractPayKitProvider, createCheckoutSchema, ValidationError, updateCheckoutSchema, retrieveCheckoutSchema, ProviderNotSupportedError, createCustomerSchema, PAYKIT_METADATA_KEY, updateCustomerSchema, retrieveCustomerSchema, retrieveSubscriptionSchema, updateSubscriptionSchema, createPaymentSchema, updatePaymentSchema, capturePaymentSchema, createRefundSchema, ResourceNotFoundError, OperationFailedError, headersExtractor, paykitEvent$InboundSchema, billingModeSchema, omitInternalMetadata } from '@paykit-sdk/core';
1
+ import { schema, validateRequiredKeys, AbstractPayKitProvider, createCheckoutSchema, ValidationError, stringifyMetadataValues, updateCheckoutSchema, retrieveCheckoutSchema, ProviderNotSupportedError, createCustomerSchema, PAYKIT_METADATA_KEY, updateCustomerSchema, retrieveCustomerSchema, retrieveSubscriptionSchema, updateSubscriptionSchema, createPaymentSchema, updatePaymentSchema, capturePaymentSchema, createRefundSchema, ResourceNotFoundError, OperationFailedError, paykitEvent$InboundSchema, billingModeSchema, omitInternalMetadata } from '@paykit-sdk/core';
2
2
  import { ServerList, Polar } from '@polar-sh/sdk';
3
3
  import { Refunds } from '@polar-sh/sdk/sdk/refunds.js';
4
4
  import { validateEvent } from '@polar-sh/sdk/webhooks';
@@ -4126,7 +4126,7 @@ var paykitPayment$InboundSchema = (checkout) => {
4126
4126
  customer: checkout.customerId ? checkout.customerId : { email: checkout.customerEmail ?? "" },
4127
4127
  status: statusMap[checkout.status],
4128
4128
  metadata: checkout.metadata ?? {},
4129
- product_id: checkout.products.length > 0 ? checkout.products[0].id : null
4129
+ item_id: checkout.products.length > 0 ? checkout.products[0].id : null
4130
4130
  };
4131
4131
  };
4132
4132
  var mapRefundReason = (debug, reason) => {
@@ -4138,7 +4138,9 @@ var mapRefundReason = (debug, reason) => {
4138
4138
  };
4139
4139
  const mapped = reasonMap[reason.toLowerCase()] ?? "other";
4140
4140
  if (debug && mapped === "other" && !reason.toLowerCase().includes("other")) {
4141
- console.warn(`[Polar Provider] Unmapped refund reason: "${reason}" -> defaulting to "other"`);
4141
+ console.warn(
4142
+ `[Polar Provider] Unmapped refund reason: "${reason}" -> defaulting to "other"`
4143
+ );
4142
4144
  }
4143
4145
  return mapped;
4144
4146
  };
@@ -4180,8 +4182,9 @@ var PolarProvider = class extends AbstractPayKitProvider {
4180
4182
  throw ValidationError.fromZodError(error, this.providerName, "createCheckout");
4181
4183
  }
4182
4184
  const { metadata, item_id, provider_metadata } = data;
4185
+ const checkoutMetadata = stringifyMetadataValues(metadata ?? {});
4183
4186
  const checkoutCreateOptions = {
4184
- metadata: Object.fromEntries(Object.entries(metadata ?? {}).map(([key, value]) => [key, JSON.stringify(value)])),
4187
+ metadata: checkoutMetadata,
4185
4188
  products: [item_id],
4186
4189
  ...provider_metadata
4187
4190
  };
@@ -4195,7 +4198,7 @@ var PolarProvider = class extends AbstractPayKitProvider {
4195
4198
  state: data.billing.address.state
4196
4199
  };
4197
4200
  checkoutCreateOptions.metadata = {
4198
- ...metadata,
4201
+ ...checkoutMetadata,
4199
4202
  _shipping_phone: data.billing.address.phone ?? "",
4200
4203
  _shipping_carrier: data.billing.carrier ?? ""
4201
4204
  };
@@ -4213,7 +4216,7 @@ var PolarProvider = class extends AbstractPayKitProvider {
4213
4216
  id,
4214
4217
  checkoutUpdate: {
4215
4218
  ...restData,
4216
- ...metadata && { metadata: Object.fromEntries(Object.entries(metadata).map(([key, value]) => [key, JSON.stringify(value)])) },
4219
+ ...metadata && { metadata: stringifyMetadataValues(metadata ?? {}) },
4217
4220
  ...item_id && { products: [item_id] },
4218
4221
  ...provider_metadata
4219
4222
  }
@@ -4246,7 +4249,10 @@ var PolarProvider = class extends AbstractPayKitProvider {
4246
4249
  const response = await this.polar.customers.create({
4247
4250
  email,
4248
4251
  name,
4249
- metadata: { ...metadata, [PAYKIT_METADATA_KEY]: JSON.stringify({ phone: data?.phone ?? "" }) }
4252
+ metadata: {
4253
+ ...metadata,
4254
+ [PAYKIT_METADATA_KEY]: JSON.stringify({ phone: data?.phone ?? "" })
4255
+ }
4250
4256
  });
4251
4257
  return paykitCustomer$InboundSchema(response);
4252
4258
  };
@@ -4258,7 +4264,12 @@ var PolarProvider = class extends AbstractPayKitProvider {
4258
4264
  const { email, name, metadata, provider_metadata } = data;
4259
4265
  const response = await this.polar.customers.update({
4260
4266
  id,
4261
- customerUpdate: { ...email && { email }, ...name && { name }, ...metadata && { metadata }, ...provider_metadata }
4267
+ customerUpdate: {
4268
+ ...email && { email },
4269
+ ...name && { name },
4270
+ ...metadata && { metadata },
4271
+ ...provider_metadata
4272
+ }
4262
4273
  });
4263
4274
  return paykitCustomer$InboundSchema(response);
4264
4275
  };
@@ -4285,7 +4296,11 @@ var PolarProvider = class extends AbstractPayKitProvider {
4285
4296
  this.cancelSubscription = async (id) => {
4286
4297
  const { error } = retrieveSubscriptionSchema.safeParse({ id });
4287
4298
  if (error) {
4288
- throw ValidationError.fromZodError(error, this.providerName, "retrieveSubscription");
4299
+ throw ValidationError.fromZodError(
4300
+ error,
4301
+ this.providerName,
4302
+ "retrieveSubscription"
4303
+ );
4289
4304
  }
4290
4305
  const subscription = await this.polar.subscriptions.revoke({ id });
4291
4306
  return paykitSubscription$InboundSchema(subscription);
@@ -4293,7 +4308,11 @@ var PolarProvider = class extends AbstractPayKitProvider {
4293
4308
  this.retrieveSubscription = async (id) => {
4294
4309
  const { error } = retrieveSubscriptionSchema.safeParse({ id });
4295
4310
  if (error) {
4296
- throw ValidationError.fromZodError(error, this.providerName, "retrieveSubscription");
4311
+ throw ValidationError.fromZodError(
4312
+ error,
4313
+ this.providerName,
4314
+ "retrieveSubscription"
4315
+ );
4297
4316
  }
4298
4317
  const response = await this.polar.subscriptions.get({ id });
4299
4318
  return paykitSubscription$InboundSchema(response);
@@ -4303,7 +4322,10 @@ var PolarProvider = class extends AbstractPayKitProvider {
4303
4322
  if (error) {
4304
4323
  throw ValidationError.fromZodError(error, this.providerName, "updateSubscription");
4305
4324
  }
4306
- const response = await this.polar.subscriptions.update({ id, subscriptionUpdate: { ...data.metadata ?? {} } });
4325
+ const response = await this.polar.subscriptions.update({
4326
+ id,
4327
+ subscriptionUpdate: { ...data.metadata ?? {} }
4328
+ });
4307
4329
  return paykitSubscription$InboundSchema(response);
4308
4330
  };
4309
4331
  this.deleteSubscription = async (id) => {
@@ -4316,17 +4338,20 @@ var PolarProvider = class extends AbstractPayKitProvider {
4316
4338
  this.createPayment = async (params) => {
4317
4339
  const { error, data } = createPaymentSchema.safeParse(params);
4318
4340
  if (error) {
4319
- throw ValidationError.fromZodError(error, "polar", "createPayment");
4341
+ throw ValidationError.fromZodError(error, this.providerName, "createPayment");
4320
4342
  }
4321
- const metadataCore = Object.fromEntries(Object.entries(data.metadata ?? {}).map(([key, value]) => [key, JSON.stringify(value)]));
4343
+ const paymentMetadata = stringifyMetadataValues(data.metadata ?? {});
4322
4344
  const checkoutCreateOptions = {
4345
+ ...data.provider_metadata && { ...data.provider_metadata },
4323
4346
  amount: data.amount,
4324
- ...typeof data.customer === "string" && { customerId: data.customer },
4325
- ...typeof data.customer === "object" && { customerEmail: data.customer.email },
4326
- metadata: metadataCore,
4327
- products: data.product_id ? [data.product_id] : [],
4328
- ...data.provider_metadata && { ...data.provider_metadata }
4347
+ metadata: paymentMetadata,
4348
+ products: data.item_id ? [data.item_id] : []
4329
4349
  };
4350
+ if (typeof data.customer === "string") {
4351
+ checkoutCreateOptions.customerId = data.customer;
4352
+ } else if (typeof data.customer === "object") {
4353
+ checkoutCreateOptions.customerEmail = data.customer.email;
4354
+ }
4330
4355
  if (data.billing) {
4331
4356
  checkoutCreateOptions.customerBillingAddress = {
4332
4357
  line1: data.billing.address.line1,
@@ -4337,9 +4362,11 @@ var PolarProvider = class extends AbstractPayKitProvider {
4337
4362
  state: data.billing.address.state
4338
4363
  };
4339
4364
  checkoutCreateOptions.metadata = {
4340
- ...metadataCore,
4341
- _shipping_phone: data.billing.address.phone ?? "",
4342
- _shipping_carrier: data.billing.carrier ?? ""
4365
+ ...paymentMetadata,
4366
+ [PAYKIT_METADATA_KEY]: JSON.stringify({
4367
+ _shipping_phone: data.billing.address.phone ?? "",
4368
+ _shipping_carrier: data.billing.carrier ?? ""
4369
+ })
4343
4370
  };
4344
4371
  }
4345
4372
  const checkoutResponse = await this.polar.checkouts.create(checkoutCreateOptions);
@@ -4348,16 +4375,16 @@ var PolarProvider = class extends AbstractPayKitProvider {
4348
4375
  this.updatePayment = async (id, params) => {
4349
4376
  const { error, data } = updatePaymentSchema.safeParse(params);
4350
4377
  if (error) {
4351
- throw ValidationError.fromZodError(error, "polar", "updatePayment");
4378
+ throw ValidationError.fromZodError(error, this.providerName, "updatePayment");
4352
4379
  }
4353
4380
  const { provider_metadata, ...rest } = data;
4354
- const metadata = Object.fromEntries(Object.entries(rest.metadata ?? {}).map(([key, value]) => [key, JSON.stringify(value)]));
4381
+ const paymentMetadata = stringifyMetadataValues(rest.metadata ?? {});
4355
4382
  const checkoutResponse = await this.polar.checkouts.update({
4356
4383
  id,
4357
4384
  checkoutUpdate: {
4358
4385
  ...rest,
4359
- ...rest.metadata && { metadata },
4360
- ...rest.product_id && { products: [rest.product_id] },
4386
+ ...rest.metadata && { metadata: paymentMetadata },
4387
+ ...rest.item_id && { products: [rest.item_id] },
4361
4388
  ...provider_metadata
4362
4389
  }
4363
4390
  });
@@ -4409,17 +4436,10 @@ var PolarProvider = class extends AbstractPayKitProvider {
4409
4436
  */
4410
4437
  this.handleWebhook = async (params) => {
4411
4438
  const { body, headers, webhookSecret } = params;
4412
- const requiredHeaders = ["webhook-id", "webhook-timestamp", "webhook-signature"];
4413
- const webhookHeaders = headersExtractor(headers, requiredHeaders).reduce(
4414
- (acc, kv) => {
4415
- acc[kv.key] = Array.isArray(kv.value) ? kv.value.join(",") : kv.value;
4416
- return acc;
4417
- },
4418
- {}
4419
- );
4420
- const { data, type } = validateEvent(body, webhookHeaders, webhookSecret);
4421
- const id = webhookHeaders["webhook-id"];
4422
- const timestamp = webhookHeaders["webhook-timestamp"];
4439
+ const webhookId = headers.get("webhook-id");
4440
+ const webhookTimestamp = headers.get("webhook-timestamp");
4441
+ const plainHeaders = Object.fromEntries(headers.entries());
4442
+ const { data, type } = validateEvent(body, plainHeaders, webhookSecret);
4423
4443
  const webhookHandlers = {
4424
4444
  /**
4425
4445
  * Invoice
@@ -4438,12 +4458,22 @@ var PolarProvider = class extends AbstractPayKitProvider {
4438
4458
  currency: data2.currency,
4439
4459
  customer: data2.customerId ? data2.customerId : { email: data2.customer.email ?? "" },
4440
4460
  status: data2.status === "paid" ? "succeeded" : "pending",
4441
- metadata: Object.fromEntries(Object.entries(metadata ?? {}).map(([key, value]) => [key, JSON.stringify(value)])),
4442
- product_id: data2.product.id
4461
+ metadata: stringifyMetadataValues(metadata ?? {}),
4462
+ item_id: data2.product.id
4443
4463
  };
4444
4464
  return [
4445
- paykitEvent$InboundSchema({ type: "payment.updated", created: parseInt(timestamp), id, data: payment }),
4446
- paykitEvent$InboundSchema({ type: "invoice.generated", created: parseInt(timestamp), id, data: invoice })
4465
+ paykitEvent$InboundSchema({
4466
+ type: "payment.updated",
4467
+ created: parseInt(webhookTimestamp),
4468
+ id: webhookId,
4469
+ data: payment
4470
+ }),
4471
+ paykitEvent$InboundSchema({
4472
+ type: "invoice.generated",
4473
+ created: parseInt(webhookTimestamp),
4474
+ id: webhookId,
4475
+ data: invoice
4476
+ })
4447
4477
  ];
4448
4478
  }
4449
4479
  return null;
@@ -4462,12 +4492,22 @@ var PolarProvider = class extends AbstractPayKitProvider {
4462
4492
  currency: data2.currency,
4463
4493
  customer: data2.customerId ? data2.customerId : { email: data2.customer.email ?? "" },
4464
4494
  status: data2.status === "paid" ? "succeeded" : "pending",
4465
- metadata: Object.fromEntries(Object.entries(metadata ?? {}).map(([key, value]) => [key, JSON.stringify(value)])),
4466
- product_id: data2.product.id
4495
+ metadata: stringifyMetadataValues(metadata ?? {}),
4496
+ item_id: data2.product.id
4467
4497
  };
4468
4498
  return [
4469
- paykitEvent$InboundSchema({ type: "payment.created", created: parseInt(timestamp), id, data: payment }),
4470
- paykitEvent$InboundSchema({ type: "invoice.generated", created: parseInt(timestamp), id, data: invoice })
4499
+ paykitEvent$InboundSchema({
4500
+ type: "payment.created",
4501
+ created: parseInt(webhookTimestamp),
4502
+ id: webhookId,
4503
+ data: payment
4504
+ }),
4505
+ paykitEvent$InboundSchema({
4506
+ type: "invoice.generated",
4507
+ created: parseInt(webhookTimestamp),
4508
+ id: webhookId,
4509
+ data: invoice
4510
+ })
4471
4511
  ];
4472
4512
  }
4473
4513
  return null;
@@ -4477,40 +4517,91 @@ var PolarProvider = class extends AbstractPayKitProvider {
4477
4517
  */
4478
4518
  "customer.created": (data2) => {
4479
4519
  const customer = paykitCustomer$InboundSchema(data2);
4480
- return [paykitEvent$InboundSchema({ type: "customer.created", created: parseInt(timestamp), id, data: customer })];
4520
+ return [
4521
+ paykitEvent$InboundSchema({
4522
+ type: "customer.created",
4523
+ created: parseInt(webhookTimestamp),
4524
+ id: webhookId,
4525
+ data: customer
4526
+ })
4527
+ ];
4481
4528
  },
4482
4529
  "customer.updated": (data2) => {
4483
4530
  const customer = paykitCustomer$InboundSchema(data2);
4484
- return [paykitEvent$InboundSchema({ type: "customer.updated", created: parseInt(timestamp), id, data: customer })];
4531
+ return [
4532
+ paykitEvent$InboundSchema({
4533
+ type: "customer.updated",
4534
+ created: parseInt(webhookTimestamp),
4535
+ id: webhookId,
4536
+ data: customer
4537
+ })
4538
+ ];
4485
4539
  },
4486
4540
  "customer.deleted": (data2) => {
4487
4541
  const customer = paykitCustomer$InboundSchema(data2);
4488
- return [paykitEvent$InboundSchema({ type: "customer.deleted", created: parseInt(timestamp), id, data: customer })];
4542
+ return [
4543
+ paykitEvent$InboundSchema({
4544
+ type: "customer.deleted",
4545
+ created: parseInt(webhookTimestamp),
4546
+ id: webhookId,
4547
+ data: customer
4548
+ })
4549
+ ];
4489
4550
  },
4490
4551
  /**
4491
4552
  * Subscription
4492
4553
  */
4493
4554
  "subscription.updated": (data2) => {
4494
4555
  const subscription = paykitSubscription$InboundSchema(data2);
4495
- return [paykitEvent$InboundSchema({ type: "subscription.updated", created: parseInt(timestamp), id, data: subscription })];
4556
+ return [
4557
+ paykitEvent$InboundSchema({
4558
+ type: "subscription.updated",
4559
+ created: parseInt(webhookTimestamp),
4560
+ id: webhookId,
4561
+ data: subscription
4562
+ })
4563
+ ];
4496
4564
  },
4497
4565
  "subscription.created": (data2) => {
4498
4566
  const subscription = paykitSubscription$InboundSchema(data2);
4499
- return [paykitEvent$InboundSchema({ type: "subscription.created", created: parseInt(timestamp), id, data: subscription })];
4567
+ return [
4568
+ paykitEvent$InboundSchema({
4569
+ type: "subscription.created",
4570
+ created: parseInt(webhookTimestamp),
4571
+ id: webhookId,
4572
+ data: subscription
4573
+ })
4574
+ ];
4500
4575
  },
4501
4576
  "subscription.revoked": (data2) => {
4502
4577
  const subscription = paykitSubscription$InboundSchema(data2);
4503
- return [paykitEvent$InboundSchema({ type: "subscription.canceled", created: parseInt(timestamp), id, data: subscription })];
4578
+ return [
4579
+ paykitEvent$InboundSchema({
4580
+ type: "subscription.canceled",
4581
+ created: parseInt(webhookTimestamp),
4582
+ id: webhookId,
4583
+ data: subscription
4584
+ })
4585
+ ];
4504
4586
  },
4505
4587
  "refund.created": (data2) => {
4506
4588
  const refund = paykitRefund$InboundSchema(data2);
4507
- return [paykitEvent$InboundSchema({ type: "refund.created", created: parseInt(timestamp), id, data: refund })];
4589
+ return [
4590
+ paykitEvent$InboundSchema({
4591
+ type: "refund.created",
4592
+ created: parseInt(webhookTimestamp),
4593
+ id: webhookId,
4594
+ data: refund
4595
+ })
4596
+ ];
4508
4597
  }
4509
4598
  };
4510
4599
  const handler = webhookHandlers[type];
4511
- if (!handler) throw new Error(`Unhandled event type: ${type} for provider: ${this.providerName}`);
4600
+ if (!handler)
4601
+ throw new Error(`Unhandled event type: ${type} for provider: ${this.providerName}`);
4512
4602
  const results = handler(data);
4513
- if (!results) throw new Error(`Unhandled event type: ${type} for provider: ${this.providerName}`);
4603
+ if (!results)
4604
+ throw new Error(`Unhandled event type: ${type} for provider: ${this.providerName}`);
4514
4605
  return results;
4515
4606
  };
4516
4607
  const { accessToken, isSandbox, debug = true, ...rest } = config;
@@ -4530,7 +4621,11 @@ var polar = () => {
4530
4621
  process.env,
4531
4622
  "Missing required environment variables: {keys}"
4532
4623
  );
4533
- return createPolar({ debug: true, accessToken: envVars.POLAR_ACCESS_TOKEN, isSandbox: envVars.POLAR_SANDBOX == "true" });
4624
+ return createPolar({
4625
+ debug: true,
4626
+ accessToken: envVars.POLAR_ACCESS_TOKEN,
4627
+ isSandbox: envVars.POLAR_SANDBOX == "true"
4628
+ });
4534
4629
  };
4535
4630
 
4536
4631
  export { createPolar, polar };