@dodopayments/sveltekit 0.1.2 → 0.1.3

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.cjs CHANGED
@@ -96,7 +96,7 @@ function error(status, body) {
96
96
 
97
97
  new TextEncoder();
98
98
 
99
- const VERSION = '1.42.0'; // x-release-please-version
99
+ const VERSION = '1.51.2'; // x-release-please-version
100
100
 
101
101
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
102
102
  class DodoPaymentsError extends Error {
@@ -1240,6 +1240,46 @@ class DefaultPageNumberPagination extends AbstractPage {
1240
1240
  return { params: { page_number: currentPage + 1 } };
1241
1241
  }
1242
1242
  }
1243
+ class CursorPagePagination extends AbstractPage {
1244
+ constructor(client, response, body, options) {
1245
+ super(client, response, body, options);
1246
+ this.data = body.data || [];
1247
+ this.iterator = body.iterator || '';
1248
+ this.done = body.done || false;
1249
+ }
1250
+ getPaginatedItems() {
1251
+ return this.data ?? [];
1252
+ }
1253
+ hasNextPage() {
1254
+ if (this.done === false) {
1255
+ return false;
1256
+ }
1257
+ return super.hasNextPage();
1258
+ }
1259
+ // @deprecated Please use `nextPageInfo()` instead
1260
+ nextPageParams() {
1261
+ const info = this.nextPageInfo();
1262
+ if (!info)
1263
+ return null;
1264
+ if ('params' in info)
1265
+ return info.params;
1266
+ const params = Object.fromEntries(info.url.searchParams);
1267
+ if (!Object.keys(params).length)
1268
+ return null;
1269
+ return params;
1270
+ }
1271
+ nextPageInfo() {
1272
+ const cursor = this.iterator;
1273
+ if (!cursor) {
1274
+ return null;
1275
+ }
1276
+ return {
1277
+ params: {
1278
+ iterator: cursor,
1279
+ },
1280
+ };
1281
+ }
1282
+ }
1243
1283
 
1244
1284
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1245
1285
  class APIResource {
@@ -1298,6 +1338,13 @@ class Brands extends APIResource {
1298
1338
  }
1299
1339
  }
1300
1340
 
1341
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1342
+ class CheckoutSessions extends APIResource {
1343
+ create(body, options) {
1344
+ return this._client.post('/checkouts', { body, ...options });
1345
+ }
1346
+ }
1347
+
1301
1348
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1302
1349
  let CustomerPortal$1 = class CustomerPortal extends APIResource {
1303
1350
  create(customerId, params = {}, options) {
@@ -1703,26 +1750,79 @@ Subscriptions.SubscriptionListResponsesDefaultPageNumberPagination =
1703
1750
  SubscriptionListResponsesDefaultPageNumberPagination;
1704
1751
 
1705
1752
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1706
- class WebhookEvents extends APIResource {
1753
+ let Headers$1 = class Headers extends APIResource {
1707
1754
  /**
1708
- * @deprecated
1755
+ * Get a webhook by id
1709
1756
  */
1710
- retrieve(webhookEventId, options) {
1711
- return this._client.get(`/webhook_events/${webhookEventId}`, options);
1757
+ retrieve(webhookId, options) {
1758
+ return this._client.get(`/webhooks/${webhookId}/headers`, options);
1759
+ }
1760
+ /**
1761
+ * Patch a webhook by id
1762
+ */
1763
+ update(webhookId, body, options) {
1764
+ return this._client.patch(`/webhooks/${webhookId}/headers`, {
1765
+ body,
1766
+ ...options,
1767
+ headers: { Accept: '*/*', ...options?.headers },
1768
+ });
1769
+ }
1770
+ };
1771
+
1772
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1773
+ let Webhooks$1 = class Webhooks extends APIResource {
1774
+ constructor() {
1775
+ super(...arguments);
1776
+ this.headers = new Headers$1(this._client);
1777
+ }
1778
+ /**
1779
+ * Create a new webhook
1780
+ */
1781
+ create(body, options) {
1782
+ return this._client.post('/webhooks', { body, ...options });
1783
+ }
1784
+ /**
1785
+ * Get a webhook by id
1786
+ */
1787
+ retrieve(webhookId, options) {
1788
+ return this._client.get(`/webhooks/${webhookId}`, options);
1789
+ }
1790
+ /**
1791
+ * Patch a webhook by id
1792
+ */
1793
+ update(webhookId, body, options) {
1794
+ return this._client.patch(`/webhooks/${webhookId}`, { body, ...options });
1712
1795
  }
1713
1796
  list(query = {}, options) {
1714
1797
  if (isRequestOptions(query)) {
1715
1798
  return this.list({}, query);
1716
1799
  }
1717
- return this._client.getAPIList('/webhook_events', WebhookEventsDefaultPageNumberPagination, {
1718
- query,
1800
+ return this._client.getAPIList('/webhooks', WebhookDetailsCursorPagePagination, { query, ...options });
1801
+ }
1802
+ /**
1803
+ * Delete a webhook by id
1804
+ */
1805
+ delete(webhookId, options) {
1806
+ return this._client.delete(`/webhooks/${webhookId}`, {
1719
1807
  ...options,
1808
+ headers: { Accept: '*/*', ...options?.headers },
1720
1809
  });
1721
1810
  }
1811
+ /**
1812
+ * Get webhook secret by id
1813
+ */
1814
+ retrieveSecret(webhookId, options) {
1815
+ return this._client.get(`/webhooks/${webhookId}/secret`, options);
1816
+ }
1817
+ };
1818
+ class WebhookDetailsCursorPagePagination extends CursorPagePagination {
1722
1819
  }
1723
- class WebhookEventsDefaultPageNumberPagination extends DefaultPageNumberPagination {
1820
+ Webhooks$1.WebhookDetailsCursorPagePagination = WebhookDetailsCursorPagePagination;
1821
+ Webhooks$1.Headers = Headers$1;
1822
+
1823
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1824
+ class WebhookEvents extends APIResource {
1724
1825
  }
1725
- WebhookEvents.WebhookEventsDefaultPageNumberPagination = WebhookEventsDefaultPageNumberPagination;
1726
1826
 
1727
1827
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
1728
1828
  var _DodoPayments_instances, _a;
@@ -1769,6 +1869,7 @@ class DodoPayments extends APIClient {
1769
1869
  fetch: options.fetch,
1770
1870
  });
1771
1871
  _DodoPayments_instances.add(this);
1872
+ this.checkoutSessions = new CheckoutSessions(this);
1772
1873
  this.payments = new Payments(this);
1773
1874
  this.subscriptions = new Subscriptions(this);
1774
1875
  this.invoices = new Invoices(this);
@@ -1785,6 +1886,7 @@ class DodoPayments extends APIClient {
1785
1886
  this.discounts = new Discounts(this);
1786
1887
  this.addons = new Addons(this);
1787
1888
  this.brands = new Brands(this);
1889
+ this.webhooks = new Webhooks$1(this);
1788
1890
  this._options = options;
1789
1891
  this.bearerToken = bearerToken;
1790
1892
  }
@@ -1819,6 +1921,7 @@ DodoPayments.PermissionDeniedError = PermissionDeniedError;
1819
1921
  DodoPayments.UnprocessableEntityError = UnprocessableEntityError;
1820
1922
  DodoPayments.toFile = toFile;
1821
1923
  DodoPayments.fileFromPath = fileFromPath;
1924
+ DodoPayments.CheckoutSessions = CheckoutSessions;
1822
1925
  DodoPayments.Payments = Payments;
1823
1926
  DodoPayments.PaymentListResponsesDefaultPageNumberPagination =
1824
1927
  PaymentListResponsesDefaultPageNumberPagination;
@@ -1841,7 +1944,6 @@ DodoPayments.DisputeListResponsesDefaultPageNumberPagination =
1841
1944
  DodoPayments.Payouts = Payouts;
1842
1945
  DodoPayments.PayoutListResponsesDefaultPageNumberPagination = PayoutListResponsesDefaultPageNumberPagination;
1843
1946
  DodoPayments.WebhookEvents = WebhookEvents;
1844
- DodoPayments.WebhookEventsDefaultPageNumberPagination = WebhookEventsDefaultPageNumberPagination;
1845
1947
  DodoPayments.Products = Products;
1846
1948
  DodoPayments.ProductListResponsesDefaultPageNumberPagination =
1847
1949
  ProductListResponsesDefaultPageNumberPagination;
@@ -1851,7 +1953,20 @@ DodoPayments.DiscountsDefaultPageNumberPagination = DiscountsDefaultPageNumberPa
1851
1953
  DodoPayments.Addons = Addons;
1852
1954
  DodoPayments.AddonResponsesDefaultPageNumberPagination = AddonResponsesDefaultPageNumberPagination;
1853
1955
  DodoPayments.Brands = Brands;
1956
+ DodoPayments.Webhooks = Webhooks$1;
1957
+ DodoPayments.WebhookDetailsCursorPagePagination = WebhookDetailsCursorPagePagination;
1854
1958
 
1959
+ var __assign = (undefined && undefined.__assign) || function () {
1960
+ __assign = Object.assign || function(t) {
1961
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
1962
+ s = arguments[i];
1963
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
1964
+ t[p] = s[p];
1965
+ }
1966
+ return t;
1967
+ };
1968
+ return __assign.apply(this, arguments);
1969
+ };
1855
1970
  var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
1856
1971
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1857
1972
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -1888,7 +2003,8 @@ var __generator$1 = (undefined && undefined.__generator) || function (thisArg, b
1888
2003
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
1889
2004
  }
1890
2005
  };
1891
- var checkoutQuerySchema = zod.z.object({
2006
+ var checkoutQuerySchema = zod.z
2007
+ .object({
1892
2008
  productId: zod.z.string(),
1893
2009
  quantity: zod.z.string().optional(),
1894
2010
  // Customer fields
@@ -1918,7 +2034,8 @@ var checkoutQuerySchema = zod.z.object({
1918
2034
  showDiscounts: zod.z.string().optional(),
1919
2035
  // Metadata (allow any key starting with metadata_)
1920
2036
  // We'll handle metadata separately in the handler
1921
- }).catchall(zod.z.unknown());
2037
+ })
2038
+ .catchall(zod.z.unknown());
1922
2039
  // Add Zod schema for dynamic checkout body
1923
2040
  var dynamicCheckoutBodySchema = zod.z
1924
2041
  .object({
@@ -1957,12 +2074,192 @@ var dynamicCheckoutBodySchema = zod.z
1957
2074
  // Allow any additional fields (for future compatibility)
1958
2075
  })
1959
2076
  .catchall(zod.z.unknown());
2077
+ // ========================================
2078
+ // CHECKOUT SESSIONS SCHEMAS & TYPES
2079
+ // ========================================
2080
+ // Product cart item schema for checkout sessions
2081
+ var checkoutSessionProductCartItemSchema = zod.z.object({
2082
+ product_id: zod.z.string().min(1, "Product ID is required"),
2083
+ quantity: zod.z.number().int().positive("Quantity must be a positive integer"),
2084
+ });
2085
+ // Customer information schema for checkout sessions
2086
+ var checkoutSessionCustomerSchema = zod.z
2087
+ .object({
2088
+ email: zod.z.string().email().optional(),
2089
+ name: zod.z.string().min(1).optional(),
2090
+ phone_number: zod.z.string().optional(),
2091
+ })
2092
+ .optional();
2093
+ // Billing address schema for checkout sessions
2094
+ var checkoutSessionBillingAddressSchema = zod.z
2095
+ .object({
2096
+ street: zod.z.string().optional(),
2097
+ city: zod.z.string().optional(),
2098
+ state: zod.z.string().optional(),
2099
+ country: zod.z.string().length(2, "Country must be a 2-letter ISO code"),
2100
+ zipcode: zod.z.string().optional(),
2101
+ })
2102
+ .optional();
2103
+ // Payment method types enum based on Dodo Payments documentation
2104
+ var paymentMethodTypeSchema = zod.z.enum([
2105
+ "credit",
2106
+ "debit",
2107
+ "upi_collect",
2108
+ "upi_intent",
2109
+ "apple_pay",
2110
+ "google_pay",
2111
+ "amazon_pay",
2112
+ "klarna",
2113
+ "affirm",
2114
+ "afterpay_clearpay",
2115
+ "sepa",
2116
+ "ach",
2117
+ ]);
2118
+ // Customization options schema
2119
+ var checkoutSessionCustomizationSchema = zod.z
2120
+ .object({
2121
+ theme: zod.z.enum(["light", "dark", "system"]).optional(),
2122
+ show_order_details: zod.z.boolean().optional(),
2123
+ show_on_demand_tag: zod.z.boolean().optional(),
2124
+ })
2125
+ .optional();
2126
+ // Feature flags schema
2127
+ var checkoutSessionFeatureFlagsSchema = zod.z
2128
+ .object({
2129
+ allow_currency_selection: zod.z.boolean().optional(),
2130
+ allow_discount_code: zod.z.boolean().optional(),
2131
+ allow_phone_number_collection: zod.z.boolean().optional(),
2132
+ allow_tax_id: zod.z.boolean().optional(),
2133
+ always_create_new_customer: zod.z.boolean().optional(),
2134
+ })
2135
+ .optional();
2136
+ // Subscription data schema
2137
+ var checkoutSessionSubscriptionDataSchema = zod.z
2138
+ .object({
2139
+ trial_period_days: zod.z.number().int().nonnegative().optional(),
2140
+ })
2141
+ .optional();
2142
+ // Main checkout session payload schema
2143
+ var checkoutSessionPayloadSchema = zod.z.object({
2144
+ // Required fields
2145
+ product_cart: zod.z
2146
+ .array(checkoutSessionProductCartItemSchema)
2147
+ .min(1, "At least one product is required"),
2148
+ // Optional fields
2149
+ customer: checkoutSessionCustomerSchema,
2150
+ billing_address: checkoutSessionBillingAddressSchema,
2151
+ return_url: zod.z.string().url().optional(),
2152
+ allowed_payment_method_types: zod.z.array(paymentMethodTypeSchema).optional(),
2153
+ billing_currency: zod.z
2154
+ .string()
2155
+ .length(3, "Currency must be a 3-letter ISO code")
2156
+ .optional(),
2157
+ show_saved_payment_methods: zod.z.boolean().optional(),
2158
+ confirm: zod.z.boolean().optional(),
2159
+ discount_code: zod.z.string().optional(),
2160
+ metadata: zod.z.record(zod.z.string(), zod.z.string()).optional(),
2161
+ customization: checkoutSessionCustomizationSchema,
2162
+ feature_flags: checkoutSessionFeatureFlagsSchema,
2163
+ subscription_data: checkoutSessionSubscriptionDataSchema,
2164
+ });
2165
+ // Checkout session response schema
2166
+ var checkoutSessionResponseSchema = zod.z.object({
2167
+ session_id: zod.z.string().min(1, "Session ID is required"),
2168
+ checkout_url: zod.z.string().url("Invalid checkout URL"),
2169
+ });
2170
+ /**
2171
+ * Creates a new Dodo Payments Checkout Session using the modern /checkouts endpoint.
2172
+ * This function provides a clean, type-safe interface to the Checkout Sessions API.
2173
+ *
2174
+ * @param payload - The checkout session data, validated against CheckoutSessionPayloadSchema
2175
+ * @param config - Dodo Payments client configuration (bearerToken, environment)
2176
+ * @returns Promise<CheckoutSessionResponse> - The checkout session with session_id and checkout_url
2177
+ *
2178
+ * @throws {Error} When payload validation fails or API request fails
2179
+ *
2180
+ * @example
2181
+ * ```typescript
2182
+ * const session = await createCheckoutSession({
2183
+ * product_cart: [{ product_id: 'prod_123', quantity: 1 }],
2184
+ * customer: { email: 'customer@example.com' },
2185
+ * return_url: 'https://yoursite.com/success'
2186
+ * }, {
2187
+ * bearerToken: process.env.DODO_PAYMENTS_API_KEY,
2188
+ * environment: 'test_mode'
2189
+ * });
2190
+ *
2191
+ * ```
2192
+ */
2193
+ var createCheckoutSession = function (payload, config) { return __awaiter$1(void 0, void 0, void 0, function () {
2194
+ var validation, dodopayments, sdkPayload, session, responseValidation, error_1;
2195
+ return __generator$1(this, function (_a) {
2196
+ switch (_a.label) {
2197
+ case 0:
2198
+ validation = checkoutSessionPayloadSchema.safeParse(payload);
2199
+ if (!validation.success) {
2200
+ throw new Error("Invalid checkout session payload: ".concat(validation.error.issues
2201
+ .map(function (issue) { return "".concat(issue.path.join("."), ": ").concat(issue.message); })
2202
+ .join(", ")));
2203
+ }
2204
+ dodopayments = new DodoPayments({
2205
+ bearerToken: config.bearerToken,
2206
+ environment: config.environment,
2207
+ });
2208
+ _a.label = 1;
2209
+ case 1:
2210
+ _a.trys.push([1, 3, , 4]);
2211
+ sdkPayload = __assign(__assign({}, validation.data), (validation.data.billing_address && {
2212
+ billing_address: __assign(__assign({}, validation.data.billing_address), { country: validation.data.billing_address.country }),
2213
+ }));
2214
+ return [4 /*yield*/, dodopayments.checkoutSessions.create(sdkPayload)];
2215
+ case 2:
2216
+ session = _a.sent();
2217
+ responseValidation = checkoutSessionResponseSchema.safeParse(session);
2218
+ if (!responseValidation.success) {
2219
+ throw new Error("Invalid checkout session response from API: ".concat(responseValidation.error.issues
2220
+ .map(function (issue) { return "".concat(issue.path.join("."), ": ").concat(issue.message); })
2221
+ .join(", ")));
2222
+ }
2223
+ return [2 /*return*/, responseValidation.data];
2224
+ case 3:
2225
+ error_1 = _a.sent();
2226
+ if (error_1 instanceof Error) {
2227
+ console.error("Dodo Payments Checkout Session API Error:", {
2228
+ message: error_1.message,
2229
+ payload: validation.data,
2230
+ config: {
2231
+ environment: config.environment,
2232
+ hasBearerToken: !!config.bearerToken,
2233
+ },
2234
+ });
2235
+ // Re-throw with a more user-friendly message
2236
+ throw new Error("Failed to create checkout session: ".concat(error_1.message));
2237
+ }
2238
+ // Handle non-Error objects
2239
+ console.error("Unknown error creating checkout session:", error_1);
2240
+ throw new Error("Failed to create checkout session due to an unknown error");
2241
+ case 4: return [2 /*return*/];
2242
+ }
2243
+ });
2244
+ }); };
1960
2245
  var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0, function (_b) {
1961
- var inputData, parseResult, success, data, error, _c, productId, quantity_1, fullName, firstName, lastName, email, country, addressLine, city, state, zipCode, disableFullName, disableFirstName, disableLastName, disableEmail, disableCountry, disableAddressLine, disableCity, disableState, disableZipCode, paymentCurrency, showCurrencySelector, paymentAmount, showDiscounts, dodopayments_1, err_1, url, _i, _d, _e, key, value, dyn, product_id, product_cart, quantity, billing, customer, addons, metadata, allowed_payment_method_types, billing_currency, discount_code, on_demand, bodyReturnUrl, show_saved_payment_methods, tax_id, trial_period_days, dodopayments, isSubscription, productIdToFetch, product, err_2, subscriptionPayload, subscription, err_3, cart, paymentPayload, payment, err_4;
1962
- var queryParams = _b.queryParams, body = _b.body, returnUrl = _b.returnUrl, bearerToken = _b.bearerToken, environment = _b.environment, _f = _b.type, type = _f === void 0 ? "static" : _f;
2246
+ var session, inputData, parseResult, success, data, error, _c, productId, quantity_1, fullName, firstName, lastName, email, country, addressLine, city, state, zipCode, disableFullName, disableFirstName, disableLastName, disableEmail, disableCountry, disableAddressLine, disableCity, disableState, disableZipCode, paymentCurrency, showCurrencySelector, paymentAmount, showDiscounts, dodopayments_1, err_1, url, _i, _d, _e, key, value, dyn, product_id, product_cart, quantity, billing, customer, addons, metadata, allowed_payment_method_types, billing_currency, discount_code, on_demand, bodyReturnUrl, show_saved_payment_methods, tax_id, trial_period_days, dodopayments, isSubscription, productIdToFetch, product, err_2, subscriptionPayload, subscription, err_3, cart, paymentPayload, payment, err_4;
2247
+ var queryParams = _b.queryParams, body = _b.body, sessionPayload = _b.sessionPayload, returnUrl = _b.returnUrl, bearerToken = _b.bearerToken, environment = _b.environment, _f = _b.type, type = _f === void 0 ? "static" : _f;
1963
2248
  return __generator$1(this, function (_g) {
1964
2249
  switch (_g.label) {
1965
2250
  case 0:
2251
+ if (!(type === "session")) return [3 /*break*/, 2];
2252
+ if (!sessionPayload) {
2253
+ throw new Error("sessionPayload is required when type is 'session'");
2254
+ }
2255
+ return [4 /*yield*/, createCheckoutSession(sessionPayload, {
2256
+ bearerToken: bearerToken,
2257
+ environment: environment,
2258
+ })];
2259
+ case 1:
2260
+ session = _g.sent();
2261
+ return [2 /*return*/, session.checkout_url];
2262
+ case 2:
1966
2263
  inputData = type === "dynamic" ? body : queryParams;
1967
2264
  if (type === "dynamic") {
1968
2265
  parseResult = dynamicCheckoutBodySchema.safeParse(inputData);
@@ -1974,7 +2271,7 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
1974
2271
  if (!success) {
1975
2272
  throw new Error("Invalid ".concat(type === "dynamic" ? "body" : "query parameters", ".\n ").concat(error.message));
1976
2273
  }
1977
- if (!(type !== "dynamic")) return [3 /*break*/, 5];
2274
+ if (!(type !== "dynamic")) return [3 /*break*/, 7];
1978
2275
  _c = data, productId = _c.productId, quantity_1 = _c.quantity, fullName = _c.fullName, firstName = _c.firstName, lastName = _c.lastName, email = _c.email, country = _c.country, addressLine = _c.addressLine, city = _c.city, state = _c.state, zipCode = _c.zipCode, disableFullName = _c.disableFullName, disableFirstName = _c.disableFirstName, disableLastName = _c.disableLastName, disableEmail = _c.disableEmail, disableCountry = _c.disableCountry, disableAddressLine = _c.disableAddressLine, disableCity = _c.disableCity, disableState = _c.disableState, disableZipCode = _c.disableZipCode, paymentCurrency = _c.paymentCurrency, showCurrencySelector = _c.showCurrencySelector, paymentAmount = _c.paymentAmount, showDiscounts = _c.showDiscounts;
1979
2276
  dodopayments_1 = new DodoPayments({
1980
2277
  bearerToken: bearerToken,
@@ -1983,18 +2280,18 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
1983
2280
  // Check that the product exists for this merchant
1984
2281
  if (!productId)
1985
2282
  throw new Error("Missing required field: productId");
1986
- _g.label = 1;
1987
- case 1:
1988
- _g.trys.push([1, 3, , 4]);
2283
+ _g.label = 3;
2284
+ case 3:
2285
+ _g.trys.push([3, 5, , 6]);
1989
2286
  return [4 /*yield*/, dodopayments_1.products.retrieve(productId)];
1990
- case 2:
2287
+ case 4:
1991
2288
  _g.sent();
1992
- return [3 /*break*/, 4];
1993
- case 3:
2289
+ return [3 /*break*/, 6];
2290
+ case 5:
1994
2291
  err_1 = _g.sent();
1995
2292
  console.error(err_1);
1996
2293
  throw new Error("Product not found");
1997
- case 4:
2294
+ case 6:
1998
2295
  url = new URL("".concat(environment === "test_mode" ? "https://test.checkout.dodopayments.com" : "https://checkout.dodopayments.com", "/buy/").concat(productId));
1999
2296
  url.searchParams.set("quantity", quantity_1 ? String(quantity_1) : "1");
2000
2297
  if (returnUrl)
@@ -2054,7 +2351,7 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
2054
2351
  }
2055
2352
  }
2056
2353
  return [2 /*return*/, url.toString()];
2057
- case 5:
2354
+ case 7:
2058
2355
  dyn = data;
2059
2356
  product_id = dyn.product_id, product_cart = dyn.product_cart, quantity = dyn.quantity, billing = dyn.billing, customer = dyn.customer, addons = dyn.addons, metadata = dyn.metadata, allowed_payment_method_types = dyn.allowed_payment_method_types, billing_currency = dyn.billing_currency, discount_code = dyn.discount_code, on_demand = dyn.on_demand, bodyReturnUrl = dyn.return_url, show_saved_payment_methods = dyn.show_saved_payment_methods, tax_id = dyn.tax_id, trial_period_days = dyn.trial_period_days;
2060
2357
  dodopayments = new DodoPayments({
@@ -2068,18 +2365,18 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
2068
2365
  }
2069
2366
  if (!productIdToFetch)
2070
2367
  throw new Error("Missing required field: product_id or product_cart[0].product_id");
2071
- _g.label = 6;
2072
- case 6:
2073
- _g.trys.push([6, 8, , 9]);
2368
+ _g.label = 8;
2369
+ case 8:
2370
+ _g.trys.push([8, 10, , 11]);
2074
2371
  return [4 /*yield*/, dodopayments.products.retrieve(productIdToFetch)];
2075
- case 7:
2372
+ case 9:
2076
2373
  product = _g.sent();
2077
- return [3 /*break*/, 9];
2078
- case 8:
2374
+ return [3 /*break*/, 11];
2375
+ case 10:
2079
2376
  err_2 = _g.sent();
2080
2377
  console.error(err_2);
2081
2378
  throw new Error("Product not found");
2082
- case 9:
2379
+ case 11:
2083
2380
  isSubscription = Boolean(product.is_recurring);
2084
2381
  // Required field validation
2085
2382
  if (isSubscription && !product_id)
@@ -2088,7 +2385,7 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
2088
2385
  throw new Error("Missing required field: billing");
2089
2386
  if (!customer)
2090
2387
  throw new Error("Missing required field: customer");
2091
- if (!isSubscription) return [3 /*break*/, 14];
2388
+ if (!isSubscription) return [3 /*break*/, 16];
2092
2389
  subscriptionPayload = {
2093
2390
  billing: billing,
2094
2391
  customer: customer,
@@ -2124,24 +2421,24 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
2124
2421
  if (trial_period_days)
2125
2422
  subscriptionPayload.trial_period_days = trial_period_days;
2126
2423
  subscription = void 0;
2127
- _g.label = 10;
2128
- case 10:
2129
- _g.trys.push([10, 12, , 13]);
2424
+ _g.label = 12;
2425
+ case 12:
2426
+ _g.trys.push([12, 14, , 15]);
2130
2427
  return [4 /*yield*/, dodopayments.subscriptions.create(subscriptionPayload)];
2131
- case 11:
2428
+ case 13:
2132
2429
  subscription =
2133
2430
  _g.sent();
2134
- return [3 /*break*/, 13];
2135
- case 12:
2431
+ return [3 /*break*/, 15];
2432
+ case 14:
2136
2433
  err_3 = _g.sent();
2137
2434
  console.error("Error when creating subscription", err_3);
2138
2435
  throw new Error(err_3 instanceof Error ? err_3.message : String(err_3));
2139
- case 13:
2436
+ case 15:
2140
2437
  if (!subscription || !subscription.payment_link) {
2141
2438
  throw new Error("No payment link returned from Dodo Payments API (subscription). Make sure to set payment_link as true in payload");
2142
2439
  }
2143
2440
  return [2 /*return*/, subscription.payment_link];
2144
- case 14:
2441
+ case 16:
2145
2442
  cart = product_cart;
2146
2443
  if (!cart && product_id) {
2147
2444
  cart = [
@@ -2177,18 +2474,18 @@ var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0,
2177
2474
  if (tax_id)
2178
2475
  paymentPayload.tax_id = tax_id;
2179
2476
  payment = void 0;
2180
- _g.label = 15;
2181
- case 15:
2182
- _g.trys.push([15, 17, , 18]);
2477
+ _g.label = 17;
2478
+ case 17:
2479
+ _g.trys.push([17, 19, , 20]);
2183
2480
  return [4 /*yield*/, dodopayments.payments.create(paymentPayload)];
2184
- case 16:
2481
+ case 18:
2185
2482
  payment = _g.sent();
2186
- return [3 /*break*/, 18];
2187
- case 17:
2483
+ return [3 /*break*/, 20];
2484
+ case 19:
2188
2485
  err_4 = _g.sent();
2189
2486
  console.error("Error when creating payment link", err_4);
2190
2487
  throw new Error(err_4 instanceof Error ? err_4.message : String(err_4));
2191
- case 18:
2488
+ case 20:
2192
2489
  if (!payment || !payment.payment_link) {
2193
2490
  throw new Error("No payment link returned from Dodo Payments API. Make sure to set payment_link as true in payload.");
2194
2491
  }
@@ -2218,10 +2515,7 @@ const Checkout = (config) => {
2218
2515
  catch (err) {
2219
2516
  throw error(400, err.message);
2220
2517
  }
2221
- return new Response(null, {
2222
- status: 302,
2223
- headers: { Location: urlStr },
2224
- });
2518
+ return Response.json({ checkout_url: urlStr });
2225
2519
  };
2226
2520
  const postHandler = async (event) => {
2227
2521
  let body;
@@ -2231,21 +2525,44 @@ const Checkout = (config) => {
2231
2525
  catch (e) {
2232
2526
  throw error(400, "Invalid JSON body");
2233
2527
  }
2234
- const { success, data, error: zodError, } = dynamicCheckoutBodySchema.safeParse(body);
2235
- if (!success) {
2236
- throw error(400, `Invalid request body.\n ${zodError.message}`);
2237
- }
2238
- let urlStr = "";
2239
- try {
2240
- urlStr = await buildCheckoutUrl({ body: data, ...config });
2528
+ if (config.type === "dynamic") {
2529
+ // Handle dynamic checkout
2530
+ const { success, data, error: zodError, } = dynamicCheckoutBodySchema.safeParse(body);
2531
+ if (!success) {
2532
+ throw error(400, `Invalid request body.\n ${zodError.message}`);
2533
+ }
2534
+ let urlStr = "";
2535
+ try {
2536
+ urlStr = await buildCheckoutUrl({
2537
+ body: data,
2538
+ ...config,
2539
+ type: "dynamic",
2540
+ });
2541
+ }
2542
+ catch (err) {
2543
+ throw error(400, err.message);
2544
+ }
2545
+ return Response.json({ checkout_url: urlStr });
2241
2546
  }
2242
- catch (err) {
2243
- throw error(400, err.message);
2547
+ else {
2548
+ // Handle checkout session
2549
+ const { success, data, error: zodError, } = checkoutSessionPayloadSchema.safeParse(body);
2550
+ if (!success) {
2551
+ throw error(400, `Invalid checkout session payload.\n ${zodError.message}`);
2552
+ }
2553
+ let urlStr = "";
2554
+ try {
2555
+ urlStr = await buildCheckoutUrl({
2556
+ sessionPayload: data,
2557
+ ...config,
2558
+ type: "session",
2559
+ });
2560
+ }
2561
+ catch (err) {
2562
+ throw error(400, err.message);
2563
+ }
2564
+ return Response.json({ checkout_url: urlStr });
2244
2565
  }
2245
- return new Response(null, {
2246
- status: 302,
2247
- headers: { Location: urlStr },
2248
- });
2249
2566
  };
2250
2567
  // SvelteKit expects named exports for HTTP verbs
2251
2568
  return {