@dodopayments/nextjs 0.2.2 → 0.3.1

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 CHANGED
@@ -2322,6 +2322,7 @@ function requireReact_production () {
2322
2322
  REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"),
2323
2323
  REACT_MEMO_TYPE = Symbol.for("react.memo"),
2324
2324
  REACT_LAZY_TYPE = Symbol.for("react.lazy"),
2325
+ REACT_ACTIVITY_TYPE = Symbol.for("react.activity"),
2325
2326
  MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
2326
2327
  function getIteratorFn(maybeIterable) {
2327
2328
  if (null === maybeIterable || "object" !== typeof maybeIterable) return null;
@@ -2373,28 +2374,22 @@ function requireReact_production () {
2373
2374
  pureComponentPrototype.constructor = PureComponent;
2374
2375
  assign(pureComponentPrototype, Component.prototype);
2375
2376
  pureComponentPrototype.isPureReactComponent = true;
2376
- var isArrayImpl = Array.isArray,
2377
- ReactSharedInternals = { H: null, A: null, T: null, S: null, V: null },
2377
+ var isArrayImpl = Array.isArray;
2378
+ function noop() {}
2379
+ var ReactSharedInternals = { H: null, A: null, T: null, S: null },
2378
2380
  hasOwnProperty = Object.prototype.hasOwnProperty;
2379
- function ReactElement(type, key, self, source, owner, props) {
2380
- self = props.ref;
2381
+ function ReactElement(type, key, props) {
2382
+ var refProp = props.ref;
2381
2383
  return {
2382
2384
  $$typeof: REACT_ELEMENT_TYPE,
2383
2385
  type: type,
2384
2386
  key: key,
2385
- ref: void 0 !== self ? self : null,
2387
+ ref: void 0 !== refProp ? refProp : null,
2386
2388
  props: props
2387
2389
  };
2388
2390
  }
2389
2391
  function cloneAndReplaceKey(oldElement, newKey) {
2390
- return ReactElement(
2391
- oldElement.type,
2392
- newKey,
2393
- void 0,
2394
- void 0,
2395
- void 0,
2396
- oldElement.props
2397
- );
2392
+ return ReactElement(oldElement.type, newKey, oldElement.props);
2398
2393
  }
2399
2394
  function isValidElement(object) {
2400
2395
  return (
@@ -2418,7 +2413,6 @@ function requireReact_production () {
2418
2413
  ? escape("" + element.key)
2419
2414
  : index.toString(36);
2420
2415
  }
2421
- function noop$1() {}
2422
2416
  function resolveThenable(thenable) {
2423
2417
  switch (thenable.status) {
2424
2418
  case "fulfilled":
@@ -2428,7 +2422,7 @@ function requireReact_production () {
2428
2422
  default:
2429
2423
  switch (
2430
2424
  ("string" === typeof thenable.status
2431
- ? thenable.then(noop$1, noop$1)
2425
+ ? thenable.then(noop, noop)
2432
2426
  : ((thenable.status = "pending"),
2433
2427
  thenable.then(
2434
2428
  function (fulfilledValue) {
@@ -2589,68 +2583,69 @@ function requireReact_production () {
2589
2583
  throw payload._result;
2590
2584
  }
2591
2585
  var reportGlobalError =
2592
- "function" === typeof reportError
2593
- ? reportError
2594
- : function (error) {
2595
- if (
2596
- "object" === typeof window &&
2597
- "function" === typeof window.ErrorEvent
2598
- ) {
2599
- var event = new window.ErrorEvent("error", {
2600
- bubbles: true,
2601
- cancelable: true,
2602
- message:
2603
- "object" === typeof error &&
2604
- null !== error &&
2605
- "string" === typeof error.message
2606
- ? String(error.message)
2607
- : String(error),
2608
- error: error
2609
- });
2610
- if (!window.dispatchEvent(event)) return;
2611
- } else if (
2612
- "object" === typeof process &&
2613
- "function" === typeof process.emit
2614
- ) {
2615
- process.emit("uncaughtException", error);
2616
- return;
2617
- }
2618
- console.error(error);
2619
- };
2620
- function noop() {}
2621
- react_production.Children = {
2622
- map: mapChildren,
2623
- forEach: function (children, forEachFunc, forEachContext) {
2624
- mapChildren(
2625
- children,
2626
- function () {
2627
- forEachFunc.apply(this, arguments);
2628
- },
2629
- forEachContext
2630
- );
2631
- },
2632
- count: function (children) {
2633
- var n = 0;
2634
- mapChildren(children, function () {
2635
- n++;
2636
- });
2637
- return n;
2638
- },
2639
- toArray: function (children) {
2640
- return (
2641
- mapChildren(children, function (child) {
2642
- return child;
2643
- }) || []
2644
- );
2645
- },
2646
- only: function (children) {
2647
- if (!isValidElement(children))
2648
- throw Error(
2649
- "React.Children.only expected to receive a single React element child."
2586
+ "function" === typeof reportError
2587
+ ? reportError
2588
+ : function (error) {
2589
+ if (
2590
+ "object" === typeof window &&
2591
+ "function" === typeof window.ErrorEvent
2592
+ ) {
2593
+ var event = new window.ErrorEvent("error", {
2594
+ bubbles: true,
2595
+ cancelable: true,
2596
+ message:
2597
+ "object" === typeof error &&
2598
+ null !== error &&
2599
+ "string" === typeof error.message
2600
+ ? String(error.message)
2601
+ : String(error),
2602
+ error: error
2603
+ });
2604
+ if (!window.dispatchEvent(event)) return;
2605
+ } else if (
2606
+ "object" === typeof process &&
2607
+ "function" === typeof process.emit
2608
+ ) {
2609
+ process.emit("uncaughtException", error);
2610
+ return;
2611
+ }
2612
+ console.error(error);
2613
+ },
2614
+ Children = {
2615
+ map: mapChildren,
2616
+ forEach: function (children, forEachFunc, forEachContext) {
2617
+ mapChildren(
2618
+ children,
2619
+ function () {
2620
+ forEachFunc.apply(this, arguments);
2621
+ },
2622
+ forEachContext
2650
2623
  );
2651
- return children;
2652
- }
2653
- };
2624
+ },
2625
+ count: function (children) {
2626
+ var n = 0;
2627
+ mapChildren(children, function () {
2628
+ n++;
2629
+ });
2630
+ return n;
2631
+ },
2632
+ toArray: function (children) {
2633
+ return (
2634
+ mapChildren(children, function (child) {
2635
+ return child;
2636
+ }) || []
2637
+ );
2638
+ },
2639
+ only: function (children) {
2640
+ if (!isValidElement(children))
2641
+ throw Error(
2642
+ "React.Children.only expected to receive a single React element child."
2643
+ );
2644
+ return children;
2645
+ }
2646
+ };
2647
+ react_production.Activity = REACT_ACTIVITY_TYPE;
2648
+ react_production.Children = Children;
2654
2649
  react_production.Component = Component;
2655
2650
  react_production.Fragment = REACT_FRAGMENT_TYPE;
2656
2651
  react_production.Profiler = REACT_PROFILER_TYPE;
@@ -2670,18 +2665,18 @@ function requireReact_production () {
2670
2665
  return fn.apply(null, arguments);
2671
2666
  };
2672
2667
  };
2668
+ react_production.cacheSignal = function () {
2669
+ return null;
2670
+ };
2673
2671
  react_production.cloneElement = function (element, config, children) {
2674
2672
  if (null === element || void 0 === element)
2675
2673
  throw Error(
2676
2674
  "The argument must be a React element, but you passed " + element + "."
2677
2675
  );
2678
2676
  var props = assign({}, element.props),
2679
- key = element.key,
2680
- owner = void 0;
2677
+ key = element.key;
2681
2678
  if (null != config)
2682
- for (propName in (void 0 !== config.ref && (owner = void 0),
2683
- void 0 !== config.key && (key = "" + config.key),
2684
- config))
2679
+ for (propName in (void 0 !== config.key && (key = "" + config.key), config))
2685
2680
  !hasOwnProperty.call(config, propName) ||
2686
2681
  "key" === propName ||
2687
2682
  "__self" === propName ||
@@ -2695,7 +2690,7 @@ function requireReact_production () {
2695
2690
  childArray[i] = arguments[i + 2];
2696
2691
  props.children = childArray;
2697
2692
  }
2698
- return ReactElement(element.type, key, void 0, void 0, owner, props);
2693
+ return ReactElement(element.type, key, props);
2699
2694
  };
2700
2695
  react_production.createContext = function (defaultValue) {
2701
2696
  defaultValue = {
@@ -2735,7 +2730,7 @@ function requireReact_production () {
2735
2730
  for (propName in ((childrenLength = type.defaultProps), childrenLength))
2736
2731
  void 0 === props[propName] &&
2737
2732
  (props[propName] = childrenLength[propName]);
2738
- return ReactElement(type, key, void 0, void 0, null, props);
2733
+ return ReactElement(type, key, props);
2739
2734
  };
2740
2735
  react_production.createRef = function () {
2741
2736
  return { current: null };
@@ -2774,7 +2769,10 @@ function requireReact_production () {
2774
2769
  } catch (error) {
2775
2770
  reportGlobalError(error);
2776
2771
  } finally {
2777
- ReactSharedInternals.T = prevTransition;
2772
+ null !== prevTransition &&
2773
+ null !== currentTransition.types &&
2774
+ (prevTransition.types = currentTransition.types),
2775
+ (ReactSharedInternals.T = prevTransition);
2778
2776
  }
2779
2777
  };
2780
2778
  react_production.unstable_useCacheRefresh = function () {
@@ -2796,13 +2794,11 @@ function requireReact_production () {
2796
2794
  react_production.useDeferredValue = function (value, initialValue) {
2797
2795
  return ReactSharedInternals.H.useDeferredValue(value, initialValue);
2798
2796
  };
2799
- react_production.useEffect = function (create, createDeps, update) {
2800
- var dispatcher = ReactSharedInternals.H;
2801
- if ("function" === typeof update)
2802
- throw Error(
2803
- "useEffect CRUD overload is not enabled in this build of React."
2804
- );
2805
- return dispatcher.useEffect(create, createDeps);
2797
+ react_production.useEffect = function (create, deps) {
2798
+ return ReactSharedInternals.H.useEffect(create, deps);
2799
+ };
2800
+ react_production.useEffectEvent = function (callback) {
2801
+ return ReactSharedInternals.H.useEffectEvent(callback);
2806
2802
  };
2807
2803
  react_production.useId = function () {
2808
2804
  return ReactSharedInternals.H.useId();
@@ -2845,7 +2841,7 @@ function requireReact_production () {
2845
2841
  react_production.useTransition = function () {
2846
2842
  return ReactSharedInternals.H.useTransition();
2847
2843
  };
2848
- react_production.version = "19.1.0";
2844
+ react_production.version = "19.2.0";
2849
2845
  return react_production;
2850
2846
  }
2851
2847
 
@@ -2916,6 +2912,7 @@ function requireReact_development () {
2916
2912
  this.refs = emptyObject;
2917
2913
  this.updater = updater || ReactNoopUpdateQueue;
2918
2914
  }
2915
+ function noop() {}
2919
2916
  function testStringCoercion(value) {
2920
2917
  return "" + value;
2921
2918
  }
@@ -2975,7 +2972,7 @@ function requireReact_development () {
2975
2972
  case REACT_PORTAL_TYPE:
2976
2973
  return "Portal";
2977
2974
  case REACT_CONTEXT_TYPE:
2978
- return (type.displayName || "Context") + ".Provider";
2975
+ return type.displayName || "Context";
2979
2976
  case REACT_CONSUMER_TYPE:
2980
2977
  return (type._context.displayName || "Context") + ".Consumer";
2981
2978
  case REACT_FORWARD_REF_TYPE:
@@ -3055,17 +3052,8 @@ function requireReact_development () {
3055
3052
  componentName = this.props.ref;
3056
3053
  return void 0 !== componentName ? componentName : null;
3057
3054
  }
3058
- function ReactElement(
3059
- type,
3060
- key,
3061
- self,
3062
- source,
3063
- owner,
3064
- props,
3065
- debugStack,
3066
- debugTask
3067
- ) {
3068
- self = props.ref;
3055
+ function ReactElement(type, key, props, owner, debugStack, debugTask) {
3056
+ var refProp = props.ref;
3069
3057
  type = {
3070
3058
  $$typeof: REACT_ELEMENT_TYPE,
3071
3059
  type: type,
@@ -3073,7 +3061,7 @@ function requireReact_development () {
3073
3061
  props: props,
3074
3062
  _owner: owner
3075
3063
  };
3076
- null !== (void 0 !== self ? self : null)
3064
+ null !== (void 0 !== refProp ? refProp : null)
3077
3065
  ? Object.defineProperty(type, "ref", {
3078
3066
  enumerable: false,
3079
3067
  get: elementRefGetterWithDeprecationWarning
@@ -3111,10 +3099,8 @@ function requireReact_development () {
3111
3099
  newKey = ReactElement(
3112
3100
  oldElement.type,
3113
3101
  newKey,
3114
- void 0,
3115
- void 0,
3116
- oldElement._owner,
3117
3102
  oldElement.props,
3103
+ oldElement._owner,
3118
3104
  oldElement._debugStack,
3119
3105
  oldElement._debugTask
3120
3106
  );
@@ -3122,6 +3108,18 @@ function requireReact_development () {
3122
3108
  (newKey._store.validated = oldElement._store.validated);
3123
3109
  return newKey;
3124
3110
  }
3111
+ function validateChildKeys(node) {
3112
+ isValidElement(node)
3113
+ ? node._store && (node._store.validated = 1)
3114
+ : "object" === typeof node &&
3115
+ null !== node &&
3116
+ node.$$typeof === REACT_LAZY_TYPE &&
3117
+ ("fulfilled" === node._payload.status
3118
+ ? isValidElement(node._payload.value) &&
3119
+ node._payload.value._store &&
3120
+ (node._payload.value._store.validated = 1)
3121
+ : node._store && (node._store.validated = 1));
3122
+ }
3125
3123
  function isValidElement(object) {
3126
3124
  return (
3127
3125
  "object" === typeof object &&
@@ -3145,7 +3143,6 @@ function requireReact_development () {
3145
3143
  ? (checkKeyStringCoercion(element.key), escape("" + element.key))
3146
3144
  : index.toString(36);
3147
3145
  }
3148
- function noop$1() {}
3149
3146
  function resolveThenable(thenable) {
3150
3147
  switch (thenable.status) {
3151
3148
  case "fulfilled":
@@ -3155,7 +3152,7 @@ function requireReact_development () {
3155
3152
  default:
3156
3153
  switch (
3157
3154
  ("string" === typeof thenable.status
3158
- ? thenable.then(noop$1, noop$1)
3155
+ ? thenable.then(noop, noop)
3159
3156
  : ((thenable.status = "pending"),
3160
3157
  thenable.then(
3161
3158
  function (fulfilledValue) {
@@ -3317,35 +3314,56 @@ function requireReact_development () {
3317
3314
  }
3318
3315
  function lazyInitializer(payload) {
3319
3316
  if (-1 === payload._status) {
3320
- var ctor = payload._result;
3321
- ctor = ctor();
3322
- ctor.then(
3317
+ var ioInfo = payload._ioInfo;
3318
+ null != ioInfo && (ioInfo.start = ioInfo.end = performance.now());
3319
+ ioInfo = payload._result;
3320
+ var thenable = ioInfo();
3321
+ thenable.then(
3323
3322
  function (moduleObject) {
3324
- if (0 === payload._status || -1 === payload._status)
3325
- (payload._status = 1), (payload._result = moduleObject);
3323
+ if (0 === payload._status || -1 === payload._status) {
3324
+ payload._status = 1;
3325
+ payload._result = moduleObject;
3326
+ var _ioInfo = payload._ioInfo;
3327
+ null != _ioInfo && (_ioInfo.end = performance.now());
3328
+ void 0 === thenable.status &&
3329
+ ((thenable.status = "fulfilled"),
3330
+ (thenable.value = moduleObject));
3331
+ }
3326
3332
  },
3327
3333
  function (error) {
3328
- if (0 === payload._status || -1 === payload._status)
3329
- (payload._status = 2), (payload._result = error);
3334
+ if (0 === payload._status || -1 === payload._status) {
3335
+ payload._status = 2;
3336
+ payload._result = error;
3337
+ var _ioInfo2 = payload._ioInfo;
3338
+ null != _ioInfo2 && (_ioInfo2.end = performance.now());
3339
+ void 0 === thenable.status &&
3340
+ ((thenable.status = "rejected"), (thenable.reason = error));
3341
+ }
3330
3342
  }
3331
3343
  );
3344
+ ioInfo = payload._ioInfo;
3345
+ if (null != ioInfo) {
3346
+ ioInfo.value = thenable;
3347
+ var displayName = thenable.displayName;
3348
+ "string" === typeof displayName && (ioInfo.name = displayName);
3349
+ }
3332
3350
  -1 === payload._status &&
3333
- ((payload._status = 0), (payload._result = ctor));
3351
+ ((payload._status = 0), (payload._result = thenable));
3334
3352
  }
3335
3353
  if (1 === payload._status)
3336
3354
  return (
3337
- (ctor = payload._result),
3338
- void 0 === ctor &&
3355
+ (ioInfo = payload._result),
3356
+ void 0 === ioInfo &&
3339
3357
  console.error(
3340
3358
  "lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?",
3341
- ctor
3359
+ ioInfo
3342
3360
  ),
3343
- "default" in ctor ||
3361
+ "default" in ioInfo ||
3344
3362
  console.error(
3345
3363
  "lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))",
3346
- ctor
3364
+ ioInfo
3347
3365
  ),
3348
- ctor.default
3366
+ ioInfo.default
3349
3367
  );
3350
3368
  throw payload._result;
3351
3369
  }
@@ -3357,7 +3375,9 @@ function requireReact_development () {
3357
3375
  );
3358
3376
  return dispatcher;
3359
3377
  }
3360
- function noop() {}
3378
+ function releaseAsyncTransition() {
3379
+ ReactSharedInternals.asyncTransitions--;
3380
+ }
3361
3381
  function enqueueTask(task) {
3362
3382
  if (null === enqueueTaskImpl)
3363
3383
  try {
@@ -3449,8 +3469,8 @@ function requireReact_development () {
3449
3469
  REACT_PORTAL_TYPE = Symbol.for("react.portal"),
3450
3470
  REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"),
3451
3471
  REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"),
3452
- REACT_PROFILER_TYPE = Symbol.for("react.profiler");
3453
- var REACT_CONSUMER_TYPE = Symbol.for("react.consumer"),
3472
+ REACT_PROFILER_TYPE = Symbol.for("react.profiler"),
3473
+ REACT_CONSUMER_TYPE = Symbol.for("react.consumer"),
3454
3474
  REACT_CONTEXT_TYPE = Symbol.for("react.context"),
3455
3475
  REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"),
3456
3476
  REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"),
@@ -3493,16 +3513,15 @@ function requireReact_development () {
3493
3513
  this.updater.enqueueForceUpdate(this, callback, "forceUpdate");
3494
3514
  };
3495
3515
  var deprecatedAPIs = {
3496
- isMounted: [
3497
- "isMounted",
3498
- "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."
3499
- ],
3500
- replaceState: [
3501
- "replaceState",
3502
- "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."
3503
- ]
3504
- },
3505
- fnName;
3516
+ isMounted: [
3517
+ "isMounted",
3518
+ "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."
3519
+ ],
3520
+ replaceState: [
3521
+ "replaceState",
3522
+ "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."
3523
+ ]
3524
+ };
3506
3525
  for (fnName in deprecatedAPIs)
3507
3526
  deprecatedAPIs.hasOwnProperty(fnName) &&
3508
3527
  defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
@@ -3518,8 +3537,8 @@ function requireReact_development () {
3518
3537
  A: null,
3519
3538
  T: null,
3520
3539
  S: null,
3521
- V: null,
3522
3540
  actQueue: null,
3541
+ asyncTransitions: 0,
3523
3542
  isBatchingLegacy: false,
3524
3543
  didScheduleLegacyUpdate: false,
3525
3544
  didUsePromise: false,
@@ -3534,15 +3553,16 @@ function requireReact_development () {
3534
3553
  return null;
3535
3554
  };
3536
3555
  deprecatedAPIs = {
3537
- "react-stack-bottom-frame": function (callStackForError) {
3556
+ react_stack_bottom_frame: function (callStackForError) {
3538
3557
  return callStackForError();
3539
3558
  }
3540
3559
  };
3541
3560
  var specialPropKeyWarningShown, didWarnAboutOldJSXRuntime;
3542
3561
  var didWarnAboutElementRef = {};
3543
- var unknownOwnerDebugStack = deprecatedAPIs[
3544
- "react-stack-bottom-frame"
3545
- ].bind(deprecatedAPIs, UnknownOwner)();
3562
+ var unknownOwnerDebugStack = deprecatedAPIs.react_stack_bottom_frame.bind(
3563
+ deprecatedAPIs,
3564
+ UnknownOwner
3565
+ )();
3546
3566
  var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
3547
3567
  var didWarnAboutMaps = false,
3548
3568
  userProvidedKeyEscapeRegex = /\/+/g,
@@ -3594,7 +3614,7 @@ function requireReact_development () {
3594
3614
  return resolveDispatcher().useMemoCache(size);
3595
3615
  }
3596
3616
  });
3597
- exports.Children = {
3617
+ var fnName = {
3598
3618
  map: mapChildren,
3599
3619
  forEach: function (children, forEachFunc, forEachContext) {
3600
3620
  mapChildren(
@@ -3627,6 +3647,8 @@ function requireReact_development () {
3627
3647
  return children;
3628
3648
  }
3629
3649
  };
3650
+ exports.Activity = REACT_ACTIVITY_TYPE;
3651
+ exports.Children = fnName;
3630
3652
  exports.Component = Component;
3631
3653
  exports.Fragment = REACT_FRAGMENT_TYPE;
3632
3654
  exports.Profiler = REACT_PROFILER_TYPE;
@@ -3752,6 +3774,9 @@ function requireReact_development () {
3752
3774
  return fn.apply(null, arguments);
3753
3775
  };
3754
3776
  };
3777
+ exports.cacheSignal = function () {
3778
+ return null;
3779
+ };
3755
3780
  exports.captureOwnerStack = function () {
3756
3781
  var getCurrentStack = ReactSharedInternals.getCurrentStack;
3757
3782
  return null === getCurrentStack ? null : getCurrentStack();
@@ -3804,16 +3829,13 @@ function requireReact_development () {
3804
3829
  props = ReactElement(
3805
3830
  element.type,
3806
3831
  key,
3807
- void 0,
3808
- void 0,
3809
- owner,
3810
3832
  props,
3833
+ owner,
3811
3834
  element._debugStack,
3812
3835
  element._debugTask
3813
3836
  );
3814
3837
  for (key = 2; key < arguments.length; key++)
3815
- (owner = arguments[key]),
3816
- isValidElement(owner) && owner._store && (owner._store.validated = 1);
3838
+ validateChildKeys(arguments[key]);
3817
3839
  return props;
3818
3840
  };
3819
3841
  exports.createContext = function (defaultValue) {
@@ -3835,12 +3857,10 @@ function requireReact_development () {
3835
3857
  return defaultValue;
3836
3858
  };
3837
3859
  exports.createElement = function (type, config, children) {
3838
- for (var i = 2; i < arguments.length; i++) {
3839
- var node = arguments[i];
3840
- isValidElement(node) && node._store && (node._store.validated = 1);
3841
- }
3860
+ for (var i = 2; i < arguments.length; i++)
3861
+ validateChildKeys(arguments[i]);
3842
3862
  i = {};
3843
- node = null;
3863
+ var key = null;
3844
3864
  if (null != config)
3845
3865
  for (propName in (didWarnAboutOldJSXRuntime ||
3846
3866
  !("__self" in config) ||
@@ -3850,7 +3870,7 @@ function requireReact_development () {
3850
3870
  "Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform"
3851
3871
  )),
3852
3872
  hasValidKey(config) &&
3853
- (checkKeyStringCoercion(config.key), (node = "" + config.key)),
3873
+ (checkKeyStringCoercion(config.key), (key = "" + config.key)),
3854
3874
  config))
3855
3875
  hasOwnProperty.call(config, propName) &&
3856
3876
  "key" !== propName &&
@@ -3872,7 +3892,7 @@ function requireReact_development () {
3872
3892
  if (type && type.defaultProps)
3873
3893
  for (propName in ((childrenLength = type.defaultProps), childrenLength))
3874
3894
  void 0 === i[propName] && (i[propName] = childrenLength[propName]);
3875
- node &&
3895
+ key &&
3876
3896
  defineKeyPropWarningGetter(
3877
3897
  i,
3878
3898
  "function" === typeof type
@@ -3882,11 +3902,9 @@ function requireReact_development () {
3882
3902
  var propName = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
3883
3903
  return ReactElement(
3884
3904
  type,
3885
- node,
3886
- void 0,
3887
- void 0,
3888
- getOwner(),
3905
+ key,
3889
3906
  i,
3907
+ getOwner(),
3890
3908
  propName ? Error("react-stack-top-frame") : unknownOwnerDebugStack,
3891
3909
  propName ? createTask(getTaskName(type)) : unknownOwnerDebugTask
3892
3910
  );
@@ -3939,11 +3957,24 @@ function requireReact_development () {
3939
3957
  };
3940
3958
  exports.isValidElement = isValidElement;
3941
3959
  exports.lazy = function (ctor) {
3942
- return {
3943
- $$typeof: REACT_LAZY_TYPE,
3944
- _payload: { _status: -1, _result: ctor },
3945
- _init: lazyInitializer
3946
- };
3960
+ ctor = { _status: -1, _result: ctor };
3961
+ var lazyType = {
3962
+ $$typeof: REACT_LAZY_TYPE,
3963
+ _payload: ctor,
3964
+ _init: lazyInitializer
3965
+ },
3966
+ ioInfo = {
3967
+ name: "lazy",
3968
+ start: -1,
3969
+ end: -1,
3970
+ value: null,
3971
+ owner: null,
3972
+ debugStack: Error("react-stack-top-frame"),
3973
+ debugTask: console.createTask ? console.createTask("lazy()") : null
3974
+ };
3975
+ ctor._ioInfo = ioInfo;
3976
+ lazyType._debugInfo = [{ awaited: ioInfo }];
3977
+ return lazyType;
3947
3978
  };
3948
3979
  exports.memo = function (type, compare) {
3949
3980
  null == type &&
@@ -3976,8 +4007,8 @@ function requireReact_development () {
3976
4007
  exports.startTransition = function (scope) {
3977
4008
  var prevTransition = ReactSharedInternals.T,
3978
4009
  currentTransition = {};
3979
- ReactSharedInternals.T = currentTransition;
3980
4010
  currentTransition._updatedFibers = new Set();
4011
+ ReactSharedInternals.T = currentTransition;
3981
4012
  try {
3982
4013
  var returnValue = scope(),
3983
4014
  onStartTransitionFinish = ReactSharedInternals.S;
@@ -3986,7 +4017,9 @@ function requireReact_development () {
3986
4017
  "object" === typeof returnValue &&
3987
4018
  null !== returnValue &&
3988
4019
  "function" === typeof returnValue.then &&
3989
- returnValue.then(noop, reportGlobalError);
4020
+ (ReactSharedInternals.asyncTransitions++,
4021
+ returnValue.then(releaseAsyncTransition, releaseAsyncTransition),
4022
+ returnValue.then(noop, reportGlobalError));
3990
4023
  } catch (error) {
3991
4024
  reportGlobalError(error);
3992
4025
  } finally {
@@ -3998,6 +4031,14 @@ function requireReact_development () {
3998
4031
  console.warn(
3999
4032
  "Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."
4000
4033
  )),
4034
+ null !== prevTransition &&
4035
+ null !== currentTransition.types &&
4036
+ (null !== prevTransition.types &&
4037
+ prevTransition.types !== currentTransition.types &&
4038
+ console.error(
4039
+ "We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."
4040
+ ),
4041
+ (prevTransition.types = currentTransition.types)),
4001
4042
  (ReactSharedInternals.T = prevTransition);
4002
4043
  }
4003
4044
  };
@@ -4031,17 +4072,15 @@ function requireReact_development () {
4031
4072
  exports.useDeferredValue = function (value, initialValue) {
4032
4073
  return resolveDispatcher().useDeferredValue(value, initialValue);
4033
4074
  };
4034
- exports.useEffect = function (create, createDeps, update) {
4075
+ exports.useEffect = function (create, deps) {
4035
4076
  null == create &&
4036
4077
  console.warn(
4037
4078
  "React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?"
4038
4079
  );
4039
- var dispatcher = resolveDispatcher();
4040
- if ("function" === typeof update)
4041
- throw Error(
4042
- "useEffect CRUD overload is not enabled in this build of React."
4043
- );
4044
- return dispatcher.useEffect(create, createDeps);
4080
+ return resolveDispatcher().useEffect(create, deps);
4081
+ };
4082
+ exports.useEffectEvent = function (callback) {
4083
+ return resolveDispatcher().useEffectEvent(callback);
4045
4084
  };
4046
4085
  exports.useId = function () {
4047
4086
  return resolveDispatcher().useId();
@@ -4092,7 +4131,7 @@ function requireReact_development () {
4092
4131
  exports.useTransition = function () {
4093
4132
  return resolveDispatcher().useTransition();
4094
4133
  };
4095
- exports.version = "19.1.0";
4134
+ exports.version = "19.2.0";
4096
4135
  "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&
4097
4136
  "function" ===
4098
4137
  typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop &&
@@ -9303,7 +9342,7 @@ const unknownType = ZodUnknown.create;
9303
9342
  ZodNever.create;
9304
9343
  const arrayType = ZodArray.create;
9305
9344
  const objectType = ZodObject.create;
9306
- ZodUnion.create;
9345
+ const unionType = ZodUnion.create;
9307
9346
  const discriminatedUnionType = ZodDiscriminatedUnion.create;
9308
9347
  ZodIntersection.create;
9309
9348
  ZodTuple.create;
@@ -9522,7 +9561,7 @@ const safeJSON = (text) => {
9522
9561
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
9523
9562
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
9524
9563
 
9525
- const VERSION = '2.2.0'; // x-release-please-version
9564
+ const VERSION = '2.4.6'; // x-release-please-version
9526
9565
 
9527
9566
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
9528
9567
  /**
@@ -10272,6 +10311,9 @@ class CheckoutSessions extends APIResource {
10272
10311
  create(body, options) {
10273
10312
  return this._client.post('/checkouts', { body, ...options });
10274
10313
  }
10314
+ retrieve(id, options) {
10315
+ return this._client.get(path `/checkouts/${id}`, options);
10316
+ }
10275
10317
  }
10276
10318
 
10277
10319
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
@@ -10950,1395 +10992,320 @@ let Headers$1 = class Headers extends APIResource {
10950
10992
  }
10951
10993
  };
10952
10994
 
10953
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
10954
- let Webhooks$1 = class Webhooks extends APIResource {
10955
- constructor() {
10956
- super(...arguments);
10957
- this.headers = new Headers$1(this._client);
10958
- }
10959
- /**
10960
- * Create a new webhook
10961
- */
10962
- create(body, options) {
10963
- return this._client.post('/webhooks', { body, ...options });
10964
- }
10965
- /**
10966
- * Get a webhook by id
10967
- */
10968
- retrieve(webhookID, options) {
10969
- return this._client.get(path `/webhooks/${webhookID}`, options);
10995
+ var dist = {};
10996
+
10997
+ var timing_safe_equal = {};
10998
+
10999
+ Object.defineProperty(timing_safe_equal, "__esModule", { value: true });
11000
+ timing_safe_equal.timingSafeEqual = void 0;
11001
+ function assert(expr, msg = "") {
11002
+ if (!expr) {
11003
+ throw new Error(msg);
10970
11004
  }
10971
- /**
10972
- * Patch a webhook by id
10973
- */
10974
- update(webhookID, body, options) {
10975
- return this._client.patch(path `/webhooks/${webhookID}`, { body, ...options });
11005
+ }
11006
+ function timingSafeEqual(a, b) {
11007
+ if (a.byteLength !== b.byteLength) {
11008
+ return false;
10976
11009
  }
10977
- /**
10978
- * List all webhooks
10979
- */
10980
- list(query = {}, options) {
10981
- return this._client.getAPIList('/webhooks', (CursorPagePagination), { query, ...options });
11010
+ if (!(a instanceof DataView)) {
11011
+ a = new DataView(ArrayBuffer.isView(a) ? a.buffer : a);
10982
11012
  }
10983
- /**
10984
- * Delete a webhook by id
10985
- */
10986
- delete(webhookID, options) {
10987
- return this._client.delete(path `/webhooks/${webhookID}`, {
10988
- ...options,
10989
- headers: buildHeaders([{ Accept: '*/*' }, options?.headers]),
10990
- });
11013
+ if (!(b instanceof DataView)) {
11014
+ b = new DataView(ArrayBuffer.isView(b) ? b.buffer : b);
10991
11015
  }
10992
- /**
10993
- * Get webhook secret by id
10994
- */
10995
- retrieveSecret(webhookID, options) {
10996
- return this._client.get(path `/webhooks/${webhookID}/secret`, options);
11016
+ assert(a instanceof DataView);
11017
+ assert(b instanceof DataView);
11018
+ const length = a.byteLength;
11019
+ let out = 0;
11020
+ let i = -1;
11021
+ while (++i < length) {
11022
+ out |= a.getUint8(i) ^ b.getUint8(i);
10997
11023
  }
10998
- };
10999
- Webhooks$1.Headers = Headers$1;
11024
+ return out === 0;
11025
+ }
11026
+ timing_safe_equal.timingSafeEqual = timingSafeEqual;
11000
11027
 
11001
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
11028
+ var base64$1 = {};
11029
+
11030
+ // Copyright (C) 2016 Dmitry Chestnykh
11031
+ // MIT License. See LICENSE file for details.
11032
+ var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
11033
+ var extendStatics = function (d, b) {
11034
+ extendStatics = Object.setPrototypeOf ||
11035
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
11036
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
11037
+ return extendStatics(d, b);
11038
+ };
11039
+ return function (d, b) {
11040
+ extendStatics(d, b);
11041
+ function __() { this.constructor = d; }
11042
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11043
+ };
11044
+ })();
11045
+ Object.defineProperty(base64$1, "__esModule", { value: true });
11002
11046
  /**
11003
- * Read an environment variable.
11004
- *
11005
- * Trims beginning and trailing whitespace.
11006
- *
11007
- * Will return undefined if the environment variable doesn't exist or cannot be accessed.
11047
+ * Package base64 implements Base64 encoding and decoding.
11008
11048
  */
11009
- const readEnv = (env) => {
11010
- if (typeof globalThis.process !== 'undefined') {
11011
- return globalThis.process.env?.[env]?.trim() ?? undefined;
11012
- }
11013
- if (typeof globalThis.Deno !== 'undefined') {
11014
- return globalThis.Deno.env?.get?.(env)?.trim();
11015
- }
11016
- return undefined;
11017
- };
11018
-
11019
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
11020
- var _DodoPayments_instances, _a, _DodoPayments_encoder, _DodoPayments_baseURLOverridden;
11021
- const environments = {
11022
- live_mode: 'https://live.dodopayments.com',
11023
- test_mode: 'https://test.dodopayments.com',
11024
- };
11049
+ // Invalid character used in decoding to indicate
11050
+ // that the character to decode is out of range of
11051
+ // alphabet and cannot be decoded.
11052
+ var INVALID_BYTE = 256;
11025
11053
  /**
11026
- * API Client for interfacing with the Dodo Payments API.
11054
+ * Implements standard Base64 encoding.
11055
+ *
11056
+ * Operates in constant time.
11027
11057
  */
11028
- class DodoPayments {
11029
- /**
11030
- * API Client for interfacing with the Dodo Payments API.
11031
- *
11032
- * @param {string | undefined} [opts.bearerToken=process.env['DODO_PAYMENTS_API_KEY'] ?? undefined]
11033
- * @param {Environment} [opts.environment=live_mode] - Specifies the environment URL to use for the API.
11034
- * @param {string} [opts.baseURL=process.env['DODO_PAYMENTS_BASE_URL'] ?? https://live.dodopayments.com] - Override the default base URL for the API.
11035
- * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
11036
- * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
11037
- * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
11038
- * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
11039
- * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
11040
- * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
11041
- */
11042
- constructor({ baseURL = readEnv('DODO_PAYMENTS_BASE_URL'), bearerToken = readEnv('DODO_PAYMENTS_API_KEY'), ...opts } = {}) {
11043
- _DodoPayments_instances.add(this);
11044
- _DodoPayments_encoder.set(this, void 0);
11045
- this.checkoutSessions = new CheckoutSessions(this);
11046
- this.payments = new Payments(this);
11047
- this.subscriptions = new Subscriptions(this);
11048
- this.invoices = new Invoices(this);
11049
- this.licenses = new Licenses(this);
11050
- this.licenseKeys = new LicenseKeys(this);
11051
- this.licenseKeyInstances = new LicenseKeyInstances(this);
11052
- this.customers = new Customers(this);
11053
- this.refunds = new Refunds(this);
11054
- this.disputes = new Disputes(this);
11055
- this.payouts = new Payouts(this);
11056
- this.webhookEvents = new WebhookEvents(this);
11057
- this.products = new Products(this);
11058
- this.misc = new Misc(this);
11059
- this.discounts = new Discounts(this);
11060
- this.addons = new Addons(this);
11061
- this.brands = new Brands(this);
11062
- this.webhooks = new Webhooks$1(this);
11063
- this.usageEvents = new UsageEvents(this);
11064
- this.meters = new Meters(this);
11065
- if (bearerToken === undefined) {
11066
- throw new DodoPaymentsError("The DODO_PAYMENTS_API_KEY environment variable is missing or empty; either provide it, or instantiate the DodoPayments client with an bearerToken option, like new DodoPayments({ bearerToken: 'My Bearer Token' }).");
11058
+ var Coder = /** @class */ (function () {
11059
+ // TODO(dchest): methods to encode chunk-by-chunk.
11060
+ function Coder(_paddingCharacter) {
11061
+ if (_paddingCharacter === void 0) { _paddingCharacter = "="; }
11062
+ this._paddingCharacter = _paddingCharacter;
11063
+ }
11064
+ Coder.prototype.encodedLength = function (length) {
11065
+ if (!this._paddingCharacter) {
11066
+ return (length * 8 + 5) / 6 | 0;
11067
11067
  }
11068
- const options = {
11069
- bearerToken,
11070
- ...opts,
11071
- baseURL,
11072
- environment: opts.environment ?? 'live_mode',
11073
- };
11074
- if (baseURL && opts.environment) {
11075
- throw new DodoPaymentsError('Ambiguous URL; The `baseURL` option (or DODO_PAYMENTS_BASE_URL env var) and the `environment` option are given. If you want to use the environment you must pass baseURL: null');
11068
+ return (length + 2) / 3 * 4 | 0;
11069
+ };
11070
+ Coder.prototype.encode = function (data) {
11071
+ var out = "";
11072
+ var i = 0;
11073
+ for (; i < data.length - 2; i += 3) {
11074
+ var c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);
11075
+ out += this._encodeByte((c >>> 3 * 6) & 63);
11076
+ out += this._encodeByte((c >>> 2 * 6) & 63);
11077
+ out += this._encodeByte((c >>> 1 * 6) & 63);
11078
+ out += this._encodeByte((c >>> 0 * 6) & 63);
11076
11079
  }
11077
- this.baseURL = options.baseURL || environments[options.environment || 'live_mode'];
11078
- this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 1 minute */;
11079
- this.logger = options.logger ?? console;
11080
- const defaultLogLevel = 'warn';
11081
- // Set default logLevel early so that we can log a warning in parseLogLevel.
11082
- this.logLevel = defaultLogLevel;
11083
- this.logLevel =
11084
- parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??
11085
- parseLogLevel(readEnv('DODO_PAYMENTS_LOG'), "process.env['DODO_PAYMENTS_LOG']", this) ??
11086
- defaultLogLevel;
11087
- this.fetchOptions = options.fetchOptions;
11088
- this.maxRetries = options.maxRetries ?? 2;
11089
- this.fetch = options.fetch ?? getDefaultFetch();
11090
- __classPrivateFieldSet(this, _DodoPayments_encoder, FallbackEncoder);
11091
- this._options = options;
11092
- this.bearerToken = bearerToken;
11093
- }
11094
- /**
11095
- * Create a new client instance re-using the same options given to the current client with optional overriding.
11096
- */
11097
- withOptions(options) {
11098
- const client = new this.constructor({
11099
- ...this._options,
11100
- environment: options.environment ? options.environment : undefined,
11101
- baseURL: options.environment ? undefined : this.baseURL,
11102
- maxRetries: this.maxRetries,
11103
- timeout: this.timeout,
11104
- logger: this.logger,
11105
- logLevel: this.logLevel,
11106
- fetch: this.fetch,
11107
- fetchOptions: this.fetchOptions,
11108
- bearerToken: this.bearerToken,
11109
- ...options,
11110
- });
11111
- return client;
11112
- }
11113
- defaultQuery() {
11114
- return this._options.defaultQuery;
11115
- }
11116
- validateHeaders({ values, nulls }) {
11117
- return;
11118
- }
11119
- async authHeaders(opts) {
11120
- return buildHeaders([{ Authorization: `Bearer ${this.bearerToken}` }]);
11121
- }
11122
- /**
11123
- * Basic re-implementation of `qs.stringify` for primitive types.
11124
- */
11125
- stringifyQuery(query) {
11126
- return Object.entries(query)
11127
- .filter(([_, value]) => typeof value !== 'undefined')
11128
- .map(([key, value]) => {
11129
- if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
11130
- return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
11080
+ var left = data.length - i;
11081
+ if (left > 0) {
11082
+ var c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0);
11083
+ out += this._encodeByte((c >>> 3 * 6) & 63);
11084
+ out += this._encodeByte((c >>> 2 * 6) & 63);
11085
+ if (left === 2) {
11086
+ out += this._encodeByte((c >>> 1 * 6) & 63);
11131
11087
  }
11132
- if (value === null) {
11133
- return `${encodeURIComponent(key)}=`;
11088
+ else {
11089
+ out += this._paddingCharacter || "";
11134
11090
  }
11135
- throw new DodoPaymentsError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
11136
- })
11137
- .join('&');
11138
- }
11139
- getUserAgent() {
11140
- return `${this.constructor.name}/JS ${VERSION}`;
11141
- }
11142
- defaultIdempotencyKey() {
11143
- return `stainless-node-retry-${uuid4()}`;
11144
- }
11145
- makeStatusError(status, error, message, headers) {
11146
- return APIError.generate(status, error, message, headers);
11147
- }
11148
- buildURL(path, query, defaultBaseURL) {
11149
- const baseURL = (!__classPrivateFieldGet(this, _DodoPayments_instances, "m", _DodoPayments_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;
11150
- const url = isAbsoluteURL(path) ?
11151
- new URL(path)
11152
- : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
11153
- const defaultQuery = this.defaultQuery();
11154
- if (!isEmptyObj(defaultQuery)) {
11155
- query = { ...defaultQuery, ...query };
11091
+ out += this._paddingCharacter || "";
11156
11092
  }
11157
- if (typeof query === 'object' && query && !Array.isArray(query)) {
11158
- url.search = this.stringifyQuery(query);
11093
+ return out;
11094
+ };
11095
+ Coder.prototype.maxDecodedLength = function (length) {
11096
+ if (!this._paddingCharacter) {
11097
+ return (length * 6 + 7) / 8 | 0;
11159
11098
  }
11160
- return url.toString();
11161
- }
11162
- /**
11163
- * Used as a callback for mutating the given `FinalRequestOptions` object.
11164
- */
11165
- async prepareOptions(options) { }
11166
- /**
11167
- * Used as a callback for mutating the given `RequestInit` object.
11168
- *
11169
- * This is useful for cases where you want to add certain headers based off of
11170
- * the request properties, e.g. `method` or `url`.
11171
- */
11172
- async prepareRequest(request, { url, options }) { }
11173
- get(path, opts) {
11174
- return this.methodRequest('get', path, opts);
11175
- }
11176
- post(path, opts) {
11177
- return this.methodRequest('post', path, opts);
11178
- }
11179
- patch(path, opts) {
11180
- return this.methodRequest('patch', path, opts);
11181
- }
11182
- put(path, opts) {
11183
- return this.methodRequest('put', path, opts);
11184
- }
11185
- delete(path, opts) {
11186
- return this.methodRequest('delete', path, opts);
11187
- }
11188
- methodRequest(method, path, opts) {
11189
- return this.request(Promise.resolve(opts).then((opts) => {
11190
- return { method, path, ...opts };
11191
- }));
11192
- }
11193
- request(options, remainingRetries = null) {
11194
- return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
11195
- }
11196
- async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
11197
- const options = await optionsInput;
11198
- const maxRetries = options.maxRetries ?? this.maxRetries;
11199
- if (retriesRemaining == null) {
11200
- retriesRemaining = maxRetries;
11099
+ return length / 4 * 3 | 0;
11100
+ };
11101
+ Coder.prototype.decodedLength = function (s) {
11102
+ return this.maxDecodedLength(s.length - this._getPaddingLength(s));
11103
+ };
11104
+ Coder.prototype.decode = function (s) {
11105
+ if (s.length === 0) {
11106
+ return new Uint8Array(0);
11201
11107
  }
11202
- await this.prepareOptions(options);
11203
- const { req, url, timeout } = await this.buildRequest(options, {
11204
- retryCount: maxRetries - retriesRemaining,
11205
- });
11206
- await this.prepareRequest(req, { url, options });
11207
- /** Not an API request ID, just for correlating local log entries. */
11208
- const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
11209
- const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
11210
- const startTime = Date.now();
11211
- loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
11212
- retryOfRequestLogID,
11213
- method: options.method,
11214
- url,
11215
- options,
11216
- headers: req.headers,
11217
- }));
11218
- if (options.signal?.aborted) {
11219
- throw new APIUserAbortError();
11108
+ var paddingLength = this._getPaddingLength(s);
11109
+ var length = s.length - paddingLength;
11110
+ var out = new Uint8Array(this.maxDecodedLength(length));
11111
+ var op = 0;
11112
+ var i = 0;
11113
+ var haveBad = 0;
11114
+ var v0 = 0, v1 = 0, v2 = 0, v3 = 0;
11115
+ for (; i < length - 4; i += 4) {
11116
+ v0 = this._decodeChar(s.charCodeAt(i + 0));
11117
+ v1 = this._decodeChar(s.charCodeAt(i + 1));
11118
+ v2 = this._decodeChar(s.charCodeAt(i + 2));
11119
+ v3 = this._decodeChar(s.charCodeAt(i + 3));
11120
+ out[op++] = (v0 << 2) | (v1 >>> 4);
11121
+ out[op++] = (v1 << 4) | (v2 >>> 2);
11122
+ out[op++] = (v2 << 6) | v3;
11123
+ haveBad |= v0 & INVALID_BYTE;
11124
+ haveBad |= v1 & INVALID_BYTE;
11125
+ haveBad |= v2 & INVALID_BYTE;
11126
+ haveBad |= v3 & INVALID_BYTE;
11220
11127
  }
11221
- const controller = new AbortController();
11222
- const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
11223
- const headersTime = Date.now();
11224
- if (response instanceof globalThis.Error) {
11225
- const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
11226
- if (options.signal?.aborted) {
11227
- throw new APIUserAbortError();
11228
- }
11229
- // detect native connection timeout errors
11230
- // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)"
11231
- // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
11232
- // others do not provide enough information to distinguish timeouts from other connection errors
11233
- const isTimeout = isAbortError(response) ||
11234
- /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
11235
- if (retriesRemaining) {
11236
- loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
11237
- loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({
11238
- retryOfRequestLogID,
11239
- url,
11240
- durationMs: headersTime - startTime,
11241
- message: response.message,
11242
- }));
11243
- return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
11244
- }
11245
- loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
11246
- loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({
11247
- retryOfRequestLogID,
11248
- url,
11249
- durationMs: headersTime - startTime,
11250
- message: response.message,
11251
- }));
11252
- if (isTimeout) {
11253
- throw new APIConnectionTimeoutError();
11254
- }
11255
- throw new APIConnectionError({ cause: response });
11128
+ if (i < length - 1) {
11129
+ v0 = this._decodeChar(s.charCodeAt(i));
11130
+ v1 = this._decodeChar(s.charCodeAt(i + 1));
11131
+ out[op++] = (v0 << 2) | (v1 >>> 4);
11132
+ haveBad |= v0 & INVALID_BYTE;
11133
+ haveBad |= v1 & INVALID_BYTE;
11256
11134
  }
11257
- const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
11258
- if (!response.ok) {
11259
- const shouldRetry = await this.shouldRetry(response);
11260
- if (retriesRemaining && shouldRetry) {
11261
- const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
11262
- // We don't need the body of this response.
11263
- await CancelReadableStream(response.body);
11264
- loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
11265
- loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
11266
- retryOfRequestLogID,
11267
- url: response.url,
11268
- status: response.status,
11269
- headers: response.headers,
11270
- durationMs: headersTime - startTime,
11271
- }));
11272
- return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
11273
- }
11274
- const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
11275
- loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
11276
- const errText = await response.text().catch((err) => castToError(err).message);
11277
- const errJSON = safeJSON(errText);
11278
- const errMessage = errJSON ? undefined : errText;
11279
- loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
11280
- retryOfRequestLogID,
11281
- url: response.url,
11282
- status: response.status,
11283
- headers: response.headers,
11284
- message: errMessage,
11285
- durationMs: Date.now() - startTime,
11286
- }));
11287
- const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
11288
- throw err;
11135
+ if (i < length - 2) {
11136
+ v2 = this._decodeChar(s.charCodeAt(i + 2));
11137
+ out[op++] = (v1 << 4) | (v2 >>> 2);
11138
+ haveBad |= v2 & INVALID_BYTE;
11289
11139
  }
11290
- loggerFor(this).info(responseInfo);
11291
- loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
11292
- retryOfRequestLogID,
11293
- url: response.url,
11294
- status: response.status,
11295
- headers: response.headers,
11296
- durationMs: headersTime - startTime,
11297
- }));
11298
- return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
11299
- }
11300
- getAPIList(path, Page, opts) {
11301
- return this.requestAPIList(Page, { method: 'get', path, ...opts });
11302
- }
11303
- requestAPIList(Page, options) {
11304
- const request = this.makeRequest(options, null, undefined);
11305
- return new PagePromise(this, request, Page);
11306
- }
11307
- async fetchWithTimeout(url, init, ms, controller) {
11308
- const { signal, method, ...options } = init || {};
11309
- if (signal)
11310
- signal.addEventListener('abort', () => controller.abort());
11311
- const timeout = setTimeout(() => controller.abort(), ms);
11312
- const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
11313
- (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
11314
- const fetchOptions = {
11315
- signal: controller.signal,
11316
- ...(isReadableBody ? { duplex: 'half' } : {}),
11317
- method: 'GET',
11318
- ...options,
11319
- };
11320
- if (method) {
11321
- // Custom methods like 'patch' need to be uppercased
11322
- // See https://github.com/nodejs/undici/issues/2294
11323
- fetchOptions.method = method.toUpperCase();
11324
- }
11325
- try {
11326
- // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
11327
- return await this.fetch.call(undefined, url, fetchOptions);
11328
- }
11329
- finally {
11330
- clearTimeout(timeout);
11140
+ if (i < length - 3) {
11141
+ v3 = this._decodeChar(s.charCodeAt(i + 3));
11142
+ out[op++] = (v2 << 6) | v3;
11143
+ haveBad |= v3 & INVALID_BYTE;
11331
11144
  }
11332
- }
11333
- async shouldRetry(response) {
11334
- // Note this is not a standard header.
11335
- const shouldRetryHeader = response.headers.get('x-should-retry');
11336
- // If the server explicitly says whether or not to retry, obey.
11337
- if (shouldRetryHeader === 'true')
11338
- return true;
11339
- if (shouldRetryHeader === 'false')
11340
- return false;
11341
- // Retry on request timeouts.
11342
- if (response.status === 408)
11343
- return true;
11344
- // Retry on lock timeouts.
11345
- if (response.status === 409)
11346
- return true;
11347
- // Retry on rate limits.
11348
- if (response.status === 429)
11349
- return true;
11350
- // Retry internal errors.
11351
- if (response.status >= 500)
11352
- return true;
11353
- return false;
11354
- }
11355
- async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
11356
- let timeoutMillis;
11357
- // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
11358
- const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
11359
- if (retryAfterMillisHeader) {
11360
- const timeoutMs = parseFloat(retryAfterMillisHeader);
11361
- if (!Number.isNaN(timeoutMs)) {
11362
- timeoutMillis = timeoutMs;
11363
- }
11145
+ if (haveBad !== 0) {
11146
+ throw new Error("Base64Coder: incorrect characters for decoding");
11364
11147
  }
11365
- // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
11366
- const retryAfterHeader = responseHeaders?.get('retry-after');
11367
- if (retryAfterHeader && !timeoutMillis) {
11368
- const timeoutSeconds = parseFloat(retryAfterHeader);
11369
- if (!Number.isNaN(timeoutSeconds)) {
11370
- timeoutMillis = timeoutSeconds * 1000;
11148
+ return out;
11149
+ };
11150
+ // Standard encoding have the following encoded/decoded ranges,
11151
+ // which we need to convert between.
11152
+ //
11153
+ // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + /
11154
+ // Index: 0 - 25 26 - 51 52 - 61 62 63
11155
+ // ASCII: 65 - 90 97 - 122 48 - 57 43 47
11156
+ //
11157
+ // Encode 6 bits in b into a new character.
11158
+ Coder.prototype._encodeByte = function (b) {
11159
+ // Encoding uses constant time operations as follows:
11160
+ //
11161
+ // 1. Define comparison of A with B using (A - B) >>> 8:
11162
+ // if A > B, then result is positive integer
11163
+ // if A <= B, then result is 0
11164
+ //
11165
+ // 2. Define selection of C or 0 using bitwise AND: X & C:
11166
+ // if X == 0, then result is 0
11167
+ // if X != 0, then result is C
11168
+ //
11169
+ // 3. Start with the smallest comparison (b >= 0), which is always
11170
+ // true, so set the result to the starting ASCII value (65).
11171
+ //
11172
+ // 4. Continue comparing b to higher ASCII values, and selecting
11173
+ // zero if comparison isn't true, otherwise selecting a value
11174
+ // to add to result, which:
11175
+ //
11176
+ // a) undoes the previous addition
11177
+ // b) provides new value to add
11178
+ //
11179
+ var result = b;
11180
+ // b >= 0
11181
+ result += 65;
11182
+ // b > 25
11183
+ result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
11184
+ // b > 51
11185
+ result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
11186
+ // b > 61
11187
+ result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43);
11188
+ // b > 62
11189
+ result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47);
11190
+ return String.fromCharCode(result);
11191
+ };
11192
+ // Decode a character code into a byte.
11193
+ // Must return 256 if character is out of alphabet range.
11194
+ Coder.prototype._decodeChar = function (c) {
11195
+ // Decoding works similar to encoding: using the same comparison
11196
+ // function, but now it works on ranges: result is always incremented
11197
+ // by value, but this value becomes zero if the range is not
11198
+ // satisfied.
11199
+ //
11200
+ // Decoding starts with invalid value, 256, which is then
11201
+ // subtracted when the range is satisfied. If none of the ranges
11202
+ // apply, the function returns 256, which is then checked by
11203
+ // the caller to throw error.
11204
+ var result = INVALID_BYTE; // start with invalid character
11205
+ // c == 43 (c > 42 and c < 44)
11206
+ result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62);
11207
+ // c == 47 (c > 46 and c < 48)
11208
+ result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63);
11209
+ // c > 47 and c < 58
11210
+ result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
11211
+ // c > 64 and c < 91
11212
+ result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
11213
+ // c > 96 and c < 123
11214
+ result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
11215
+ return result;
11216
+ };
11217
+ Coder.prototype._getPaddingLength = function (s) {
11218
+ var paddingLength = 0;
11219
+ if (this._paddingCharacter) {
11220
+ for (var i = s.length - 1; i >= 0; i--) {
11221
+ if (s[i] !== this._paddingCharacter) {
11222
+ break;
11223
+ }
11224
+ paddingLength++;
11371
11225
  }
11372
- else {
11373
- timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
11226
+ if (s.length < 4 || paddingLength > 2) {
11227
+ throw new Error("Base64Coder: incorrect padding");
11374
11228
  }
11375
11229
  }
11376
- // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
11377
- // just do what it says, but otherwise calculate a default
11378
- if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
11379
- const maxRetries = options.maxRetries ?? this.maxRetries;
11380
- timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
11381
- }
11382
- await sleep(timeoutMillis);
11383
- return this.makeRequest(options, retriesRemaining - 1, requestLogID);
11384
- }
11385
- calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
11386
- const initialRetryDelay = 0.5;
11387
- const maxRetryDelay = 8.0;
11388
- const numRetries = maxRetries - retriesRemaining;
11389
- // Apply exponential backoff, but not more than the max.
11390
- const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
11391
- // Apply some jitter, take up to at most 25 percent of the retry time.
11392
- const jitter = 1 - Math.random() * 0.25;
11393
- return sleepSeconds * jitter * 1000;
11394
- }
11395
- async buildRequest(inputOptions, { retryCount = 0 } = {}) {
11396
- const options = { ...inputOptions };
11397
- const { method, path, query, defaultBaseURL } = options;
11398
- const url = this.buildURL(path, query, defaultBaseURL);
11399
- if ('timeout' in options)
11400
- validatePositiveInteger('timeout', options.timeout);
11401
- options.timeout = options.timeout ?? this.timeout;
11402
- const { bodyHeaders, body } = this.buildBody({ options });
11403
- const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
11404
- const req = {
11405
- method,
11406
- headers: reqHeaders,
11407
- ...(options.signal && { signal: options.signal }),
11408
- ...(globalThis.ReadableStream &&
11409
- body instanceof globalThis.ReadableStream && { duplex: 'half' }),
11410
- ...(body && { body }),
11411
- ...(this.fetchOptions ?? {}),
11412
- ...(options.fetchOptions ?? {}),
11413
- };
11414
- return { req, url, timeout: options.timeout };
11415
- }
11416
- async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
11417
- let idempotencyHeaders = {};
11418
- if (this.idempotencyHeader && method !== 'get') {
11419
- if (!options.idempotencyKey)
11420
- options.idempotencyKey = this.defaultIdempotencyKey();
11421
- idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
11422
- }
11423
- const headers = buildHeaders([
11424
- idempotencyHeaders,
11425
- {
11426
- Accept: 'application/json',
11427
- 'User-Agent': this.getUserAgent(),
11428
- 'X-Stainless-Retry-Count': String(retryCount),
11429
- ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
11430
- ...getPlatformHeaders(),
11431
- },
11432
- await this.authHeaders(options),
11433
- this._options.defaultHeaders,
11434
- bodyHeaders,
11435
- options.headers,
11436
- ]);
11437
- this.validateHeaders(headers);
11438
- return headers.values;
11439
- }
11440
- buildBody({ options: { body, headers: rawHeaders } }) {
11441
- if (!body) {
11442
- return { bodyHeaders: undefined, body: undefined };
11443
- }
11444
- const headers = buildHeaders([rawHeaders]);
11445
- if (
11446
- // Pass raw type verbatim
11447
- ArrayBuffer.isView(body) ||
11448
- body instanceof ArrayBuffer ||
11449
- body instanceof DataView ||
11450
- (typeof body === 'string' &&
11451
- // Preserve legacy string encoding behavior for now
11452
- headers.values.has('content-type')) ||
11453
- // `Blob` is superset of `File`
11454
- (globalThis.Blob && body instanceof globalThis.Blob) ||
11455
- // `FormData` -> `multipart/form-data`
11456
- body instanceof FormData ||
11457
- // `URLSearchParams` -> `application/x-www-form-urlencoded`
11458
- body instanceof URLSearchParams ||
11459
- // Send chunked stream (each chunk has own `length`)
11460
- (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
11461
- return { bodyHeaders: undefined, body: body };
11462
- }
11463
- else if (typeof body === 'object' &&
11464
- (Symbol.asyncIterator in body ||
11465
- (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
11466
- return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
11467
- }
11468
- else {
11469
- return __classPrivateFieldGet(this, _DodoPayments_encoder, "f").call(this, { body, headers });
11470
- }
11230
+ return paddingLength;
11231
+ };
11232
+ return Coder;
11233
+ }());
11234
+ base64$1.Coder = Coder;
11235
+ var stdCoder = new Coder();
11236
+ function encode(data) {
11237
+ return stdCoder.encode(data);
11238
+ }
11239
+ base64$1.encode = encode;
11240
+ function decode(s) {
11241
+ return stdCoder.decode(s);
11242
+ }
11243
+ base64$1.decode = decode;
11244
+ /**
11245
+ * Implements URL-safe Base64 encoding.
11246
+ * (Same as Base64, but '+' is replaced with '-', and '/' with '_').
11247
+ *
11248
+ * Operates in constant time.
11249
+ */
11250
+ var URLSafeCoder = /** @class */ (function (_super) {
11251
+ __extends(URLSafeCoder, _super);
11252
+ function URLSafeCoder() {
11253
+ return _super !== null && _super.apply(this, arguments) || this;
11471
11254
  }
11255
+ // URL-safe encoding have the following encoded/decoded ranges:
11256
+ //
11257
+ // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _
11258
+ // Index: 0 - 25 26 - 51 52 - 61 62 63
11259
+ // ASCII: 65 - 90 97 - 122 48 - 57 45 95
11260
+ //
11261
+ URLSafeCoder.prototype._encodeByte = function (b) {
11262
+ var result = b;
11263
+ // b >= 0
11264
+ result += 65;
11265
+ // b > 25
11266
+ result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
11267
+ // b > 51
11268
+ result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
11269
+ // b > 61
11270
+ result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45);
11271
+ // b > 62
11272
+ result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95);
11273
+ return String.fromCharCode(result);
11274
+ };
11275
+ URLSafeCoder.prototype._decodeChar = function (c) {
11276
+ var result = INVALID_BYTE;
11277
+ // c == 45 (c > 44 and c < 46)
11278
+ result += (((44 - c) & (c - 46)) >>> 8) & (-INVALID_BYTE + c - 45 + 62);
11279
+ // c == 95 (c > 94 and c < 96)
11280
+ result += (((94 - c) & (c - 96)) >>> 8) & (-INVALID_BYTE + c - 95 + 63);
11281
+ // c > 47 and c < 58
11282
+ result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
11283
+ // c > 64 and c < 91
11284
+ result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
11285
+ // c > 96 and c < 123
11286
+ result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
11287
+ return result;
11288
+ };
11289
+ return URLSafeCoder;
11290
+ }(Coder));
11291
+ base64$1.URLSafeCoder = URLSafeCoder;
11292
+ var urlSafeCoder = new URLSafeCoder();
11293
+ function encodeURLSafe(data) {
11294
+ return urlSafeCoder.encode(data);
11472
11295
  }
11473
- _a = DodoPayments, _DodoPayments_encoder = new WeakMap(), _DodoPayments_instances = new WeakSet(), _DodoPayments_baseURLOverridden = function _DodoPayments_baseURLOverridden() {
11474
- return this.baseURL !== environments[this._options.environment || 'live_mode'];
11475
- };
11476
- DodoPayments.DodoPayments = _a;
11477
- DodoPayments.DEFAULT_TIMEOUT = 60000; // 1 minute
11478
- DodoPayments.DodoPaymentsError = DodoPaymentsError;
11479
- DodoPayments.APIError = APIError;
11480
- DodoPayments.APIConnectionError = APIConnectionError;
11481
- DodoPayments.APIConnectionTimeoutError = APIConnectionTimeoutError;
11482
- DodoPayments.APIUserAbortError = APIUserAbortError;
11483
- DodoPayments.NotFoundError = NotFoundError;
11484
- DodoPayments.ConflictError = ConflictError;
11485
- DodoPayments.RateLimitError = RateLimitError;
11486
- DodoPayments.BadRequestError = BadRequestError;
11487
- DodoPayments.AuthenticationError = AuthenticationError;
11488
- DodoPayments.InternalServerError = InternalServerError;
11489
- DodoPayments.PermissionDeniedError = PermissionDeniedError;
11490
- DodoPayments.UnprocessableEntityError = UnprocessableEntityError;
11491
- DodoPayments.toFile = toFile;
11492
- DodoPayments.CheckoutSessions = CheckoutSessions;
11493
- DodoPayments.Payments = Payments;
11494
- DodoPayments.Subscriptions = Subscriptions;
11495
- DodoPayments.Invoices = Invoices;
11496
- DodoPayments.Licenses = Licenses;
11497
- DodoPayments.LicenseKeys = LicenseKeys;
11498
- DodoPayments.LicenseKeyInstances = LicenseKeyInstances;
11499
- DodoPayments.Customers = Customers;
11500
- DodoPayments.Refunds = Refunds;
11501
- DodoPayments.Disputes = Disputes;
11502
- DodoPayments.Payouts = Payouts;
11503
- DodoPayments.WebhookEvents = WebhookEvents;
11504
- DodoPayments.Products = Products;
11505
- DodoPayments.Misc = Misc;
11506
- DodoPayments.Discounts = Discounts;
11507
- DodoPayments.Addons = Addons;
11508
- DodoPayments.Brands = Brands;
11509
- DodoPayments.Webhooks = Webhooks$1;
11510
- DodoPayments.UsageEvents = UsageEvents;
11511
- DodoPayments.Meters = Meters;
11512
-
11513
- // src/checkout/checkout.ts
11514
- var checkoutQuerySchema = objectType({
11515
- productId: stringType(),
11516
- quantity: stringType().optional(),
11517
- // Customer fields
11518
- fullName: stringType().optional(),
11519
- firstName: stringType().optional(),
11520
- lastName: stringType().optional(),
11521
- email: stringType().optional(),
11522
- country: stringType().optional(),
11523
- addressLine: stringType().optional(),
11524
- city: stringType().optional(),
11525
- state: stringType().optional(),
11526
- zipCode: stringType().optional(),
11527
- // Disable flags
11528
- disableFullName: stringType().optional(),
11529
- disableFirstName: stringType().optional(),
11530
- disableLastName: stringType().optional(),
11531
- disableEmail: stringType().optional(),
11532
- disableCountry: stringType().optional(),
11533
- disableAddressLine: stringType().optional(),
11534
- disableCity: stringType().optional(),
11535
- disableState: stringType().optional(),
11536
- disableZipCode: stringType().optional(),
11537
- // Advanced controls
11538
- paymentCurrency: stringType().optional(),
11539
- showCurrencySelector: stringType().optional(),
11540
- paymentAmount: stringType().optional(),
11541
- showDiscounts: stringType().optional()
11542
- // Metadata (allow any key starting with metadata_)
11543
- // We'll handle metadata separately in the handler
11544
- }).catchall(unknownType());
11545
- var dynamicCheckoutBodySchema = objectType({
11546
- // For subscription
11547
- product_id: stringType().optional(),
11548
- quantity: numberType().optional(),
11549
- // For one-time payment
11550
- product_cart: arrayType(
11551
- objectType({
11552
- product_id: stringType(),
11553
- quantity: numberType()
11554
- })
11555
- ).optional(),
11556
- // Common fields
11557
- billing: objectType({
11558
- city: stringType(),
11559
- country: stringType(),
11560
- state: stringType(),
11561
- street: stringType(),
11562
- zipcode: stringType()
11563
- }),
11564
- customer: objectType({
11565
- customer_id: stringType().optional(),
11566
- email: stringType().optional(),
11567
- name: stringType().optional()
11568
- }),
11569
- discount_id: stringType().optional(),
11570
- addons: arrayType(
11571
- objectType({
11572
- addon_id: stringType(),
11573
- quantity: numberType()
11574
- })
11575
- ).optional(),
11576
- metadata: recordType(stringType(), stringType()).optional(),
11577
- currency: stringType().optional()
11578
- // Allow any additional fields (for future compatibility)
11579
- }).catchall(unknownType());
11580
- var checkoutSessionProductCartItemSchema = objectType({
11581
- product_id: stringType().min(1, "Product ID is required"),
11582
- quantity: numberType().int().positive("Quantity must be a positive integer")
11583
- });
11584
- var checkoutSessionCustomerSchema = objectType({
11585
- email: stringType().email().optional(),
11586
- name: stringType().min(1).optional(),
11587
- phone_number: stringType().optional()
11588
- }).optional();
11589
- var checkoutSessionBillingAddressSchema = objectType({
11590
- street: stringType().optional(),
11591
- city: stringType().optional(),
11592
- state: stringType().optional(),
11593
- country: stringType().length(2, "Country must be a 2-letter ISO code"),
11594
- zipcode: stringType().optional()
11595
- }).optional();
11596
- var paymentMethodTypeSchema = enumType([
11597
- "credit",
11598
- "debit",
11599
- "upi_collect",
11600
- "upi_intent",
11601
- "apple_pay",
11602
- "google_pay",
11603
- "amazon_pay",
11604
- "klarna",
11605
- "affirm",
11606
- "afterpay_clearpay",
11607
- "sepa",
11608
- "ach"
11609
- ]);
11610
- var checkoutSessionCustomizationSchema = objectType({
11611
- theme: enumType(["light", "dark", "system"]).optional(),
11612
- show_order_details: booleanType().optional(),
11613
- show_on_demand_tag: booleanType().optional()
11614
- }).optional();
11615
- var checkoutSessionFeatureFlagsSchema = objectType({
11616
- allow_currency_selection: booleanType().optional(),
11617
- allow_discount_code: booleanType().optional(),
11618
- allow_phone_number_collection: booleanType().optional(),
11619
- allow_tax_id: booleanType().optional(),
11620
- always_create_new_customer: booleanType().optional()
11621
- }).optional();
11622
- var checkoutSessionSubscriptionDataSchema = objectType({
11623
- trial_period_days: numberType().int().nonnegative().optional()
11624
- }).optional();
11625
- var checkoutSessionPayloadSchema = objectType({
11626
- // Required fields
11627
- product_cart: arrayType(checkoutSessionProductCartItemSchema).min(1, "At least one product is required"),
11628
- // Optional fields
11629
- customer: checkoutSessionCustomerSchema,
11630
- billing_address: checkoutSessionBillingAddressSchema,
11631
- return_url: stringType().url().optional(),
11632
- allowed_payment_method_types: arrayType(paymentMethodTypeSchema).optional(),
11633
- billing_currency: stringType().length(3, "Currency must be a 3-letter ISO code").optional(),
11634
- show_saved_payment_methods: booleanType().optional(),
11635
- confirm: booleanType().optional(),
11636
- discount_code: stringType().optional(),
11637
- metadata: recordType(stringType(), stringType()).optional(),
11638
- customization: checkoutSessionCustomizationSchema,
11639
- feature_flags: checkoutSessionFeatureFlagsSchema,
11640
- subscription_data: checkoutSessionSubscriptionDataSchema
11641
- });
11642
- var checkoutSessionResponseSchema = objectType({
11643
- session_id: stringType().min(1, "Session ID is required"),
11644
- checkout_url: stringType().url("Invalid checkout URL")
11645
- });
11646
- var createCheckoutSession = async (payload, config) => {
11647
- const validation = checkoutSessionPayloadSchema.safeParse(payload);
11648
- if (!validation.success) {
11649
- throw new Error(
11650
- `Invalid checkout session payload: ${validation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
11651
- );
11652
- }
11653
- const dodopayments = new DodoPayments({
11654
- bearerToken: config.bearerToken,
11655
- environment: config.environment
11656
- });
11657
- try {
11658
- const sdkPayload = {
11659
- ...validation.data,
11660
- ...validation.data.billing_address && {
11661
- billing_address: {
11662
- ...validation.data.billing_address,
11663
- country: validation.data.billing_address.country
11664
- }
11665
- }
11666
- };
11667
- const session = await dodopayments.checkoutSessions.create(
11668
- sdkPayload
11669
- );
11670
- const responseValidation = checkoutSessionResponseSchema.safeParse(session);
11671
- if (!responseValidation.success) {
11672
- throw new Error(
11673
- `Invalid checkout session response from API: ${responseValidation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
11674
- );
11675
- }
11676
- return responseValidation.data;
11677
- } catch (error) {
11678
- if (error instanceof Error) {
11679
- console.error("Dodo Payments Checkout Session API Error:", {
11680
- message: error.message,
11681
- payload: validation.data,
11682
- config: {
11683
- environment: config.environment,
11684
- hasBearerToken: !!config.bearerToken
11685
- }
11686
- });
11687
- throw new Error(`Failed to create checkout session: ${error.message}`);
11688
- }
11689
- console.error("Unknown error creating checkout session:", error);
11690
- throw new Error(
11691
- "Failed to create checkout session due to an unknown error"
11692
- );
11693
- }
11694
- };
11695
- var buildCheckoutUrl = async ({
11696
- queryParams,
11697
- body,
11698
- sessionPayload,
11699
- returnUrl,
11700
- bearerToken,
11701
- environment,
11702
- type = "static"
11703
- }) => {
11704
- if (type === "session") {
11705
- if (!sessionPayload) {
11706
- throw new Error("sessionPayload is required when type is 'session'");
11707
- }
11708
- const session = await createCheckoutSession(sessionPayload, {
11709
- bearerToken,
11710
- environment
11711
- });
11712
- return session.checkout_url;
11713
- }
11714
- const inputData = type === "dynamic" ? body : queryParams;
11715
- let parseResult;
11716
- if (type === "dynamic") {
11717
- parseResult = dynamicCheckoutBodySchema.safeParse(inputData);
11718
- } else {
11719
- parseResult = checkoutQuerySchema.safeParse(inputData);
11720
- }
11721
- const { success, data, error } = parseResult;
11722
- if (!success) {
11723
- throw new Error(
11724
- `Invalid ${type === "dynamic" ? "body" : "query parameters"}.
11725
- ${error.message}`
11726
- );
11727
- }
11728
- if (type !== "dynamic") {
11729
- const {
11730
- productId,
11731
- quantity: quantity2,
11732
- fullName,
11733
- firstName,
11734
- lastName,
11735
- email,
11736
- country,
11737
- addressLine,
11738
- city,
11739
- state,
11740
- zipCode,
11741
- disableFullName,
11742
- disableFirstName,
11743
- disableLastName,
11744
- disableEmail,
11745
- disableCountry,
11746
- disableAddressLine,
11747
- disableCity,
11748
- disableState,
11749
- disableZipCode,
11750
- paymentCurrency,
11751
- showCurrencySelector,
11752
- paymentAmount,
11753
- showDiscounts
11754
- // metadata handled below
11755
- } = data;
11756
- const dodopayments2 = new DodoPayments({
11757
- bearerToken,
11758
- environment
11759
- });
11760
- if (!productId) throw new Error("Missing required field: productId");
11761
- try {
11762
- await dodopayments2.products.retrieve(productId);
11763
- } catch (err) {
11764
- console.error(err);
11765
- throw new Error("Product not found");
11766
- }
11767
- const url = new URL(
11768
- `${environment === "test_mode" ? "https://test.checkout.dodopayments.com" : "https://checkout.dodopayments.com"}/buy/${productId}`
11769
- );
11770
- url.searchParams.set("quantity", quantity2 ? String(quantity2) : "1");
11771
- if (returnUrl) url.searchParams.set("redirect_url", returnUrl);
11772
- if (fullName) url.searchParams.set("fullName", String(fullName));
11773
- if (firstName) url.searchParams.set("firstName", String(firstName));
11774
- if (lastName) url.searchParams.set("lastName", String(lastName));
11775
- if (email) url.searchParams.set("email", String(email));
11776
- if (country) url.searchParams.set("country", String(country));
11777
- if (addressLine) url.searchParams.set("addressLine", String(addressLine));
11778
- if (city) url.searchParams.set("city", String(city));
11779
- if (state) url.searchParams.set("state", String(state));
11780
- if (zipCode) url.searchParams.set("zipCode", String(zipCode));
11781
- if (disableFullName === "true")
11782
- url.searchParams.set("disableFullName", "true");
11783
- if (disableFirstName === "true")
11784
- url.searchParams.set("disableFirstName", "true");
11785
- if (disableLastName === "true")
11786
- url.searchParams.set("disableLastName", "true");
11787
- if (disableEmail === "true") url.searchParams.set("disableEmail", "true");
11788
- if (disableCountry === "true")
11789
- url.searchParams.set("disableCountry", "true");
11790
- if (disableAddressLine === "true")
11791
- url.searchParams.set("disableAddressLine", "true");
11792
- if (disableCity === "true") url.searchParams.set("disableCity", "true");
11793
- if (disableState === "true") url.searchParams.set("disableState", "true");
11794
- if (disableZipCode === "true")
11795
- url.searchParams.set("disableZipCode", "true");
11796
- if (paymentCurrency)
11797
- url.searchParams.set("paymentCurrency", String(paymentCurrency));
11798
- if (showCurrencySelector)
11799
- url.searchParams.set(
11800
- "showCurrencySelector",
11801
- String(showCurrencySelector)
11802
- );
11803
- if (paymentAmount)
11804
- url.searchParams.set("paymentAmount", String(paymentAmount));
11805
- if (showDiscounts)
11806
- url.searchParams.set("showDiscounts", String(showDiscounts));
11807
- for (const [key, value] of Object.entries(queryParams || {})) {
11808
- if (key.startsWith("metadata_") && value && typeof value !== "object") {
11809
- url.searchParams.set(key, String(value));
11810
- }
11811
- }
11812
- return url.toString();
11813
- }
11814
- const dyn = data;
11815
- const {
11816
- product_id,
11817
- product_cart,
11818
- quantity,
11819
- billing,
11820
- customer,
11821
- addons,
11822
- metadata,
11823
- allowed_payment_method_types,
11824
- billing_currency,
11825
- discount_code,
11826
- on_demand,
11827
- return_url: bodyReturnUrl,
11828
- show_saved_payment_methods,
11829
- tax_id,
11830
- trial_period_days
11831
- } = dyn;
11832
- const dodopayments = new DodoPayments({
11833
- bearerToken,
11834
- environment
11835
- });
11836
- let isSubscription = false;
11837
- let productIdToFetch = product_id;
11838
- if (!product_id && product_cart && product_cart.length > 0) {
11839
- productIdToFetch = product_cart[0].product_id;
11840
- }
11841
- if (!productIdToFetch)
11842
- throw new Error(
11843
- "Missing required field: product_id or product_cart[0].product_id"
11844
- );
11845
- let product;
11846
- try {
11847
- product = await dodopayments.products.retrieve(productIdToFetch);
11848
- } catch (err) {
11849
- console.error(err);
11850
- throw new Error("Product not found");
11851
- }
11852
- isSubscription = Boolean(product.is_recurring);
11853
- if (isSubscription && !product_id)
11854
- throw new Error("Missing required field: product_id for subscription");
11855
- if (!billing) throw new Error("Missing required field: billing");
11856
- if (!customer) throw new Error("Missing required field: customer");
11857
- if (isSubscription) {
11858
- const subscriptionPayload = {
11859
- billing,
11860
- customer,
11861
- product_id,
11862
- quantity: quantity ? Number(quantity) : 1
11863
- };
11864
- if (metadata) subscriptionPayload.metadata = metadata;
11865
- if (discount_code) subscriptionPayload.discount_code = discount_code;
11866
- if (addons) subscriptionPayload.addons = addons;
11867
- if (allowed_payment_method_types)
11868
- subscriptionPayload.allowed_payment_method_types = allowed_payment_method_types;
11869
- if (billing_currency)
11870
- subscriptionPayload.billing_currency = billing_currency;
11871
- if (on_demand) subscriptionPayload.on_demand = on_demand;
11872
- subscriptionPayload.payment_link = true;
11873
- if (bodyReturnUrl) {
11874
- subscriptionPayload.return_url = bodyReturnUrl;
11875
- } else if (returnUrl) {
11876
- subscriptionPayload.return_url = returnUrl;
11877
- }
11878
- if (show_saved_payment_methods)
11879
- subscriptionPayload.show_saved_payment_methods = show_saved_payment_methods;
11880
- if (tax_id) subscriptionPayload.tax_id = tax_id;
11881
- if (trial_period_days)
11882
- subscriptionPayload.trial_period_days = trial_period_days;
11883
- let subscription;
11884
- try {
11885
- subscription = await dodopayments.subscriptions.create(subscriptionPayload);
11886
- } catch (err) {
11887
- console.error("Error when creating subscription", err);
11888
- throw new Error(err instanceof Error ? err.message : String(err));
11889
- }
11890
- if (!subscription || !subscription.payment_link) {
11891
- throw new Error(
11892
- "No payment link returned from Dodo Payments API (subscription). Make sure to set payment_link as true in payload"
11893
- );
11894
- }
11895
- return subscription.payment_link;
11896
- } else {
11897
- let cart = product_cart;
11898
- if (!cart && product_id) {
11899
- cart = [
11900
- { product_id, quantity: quantity ? Number(quantity) : 1 }
11901
- ];
11902
- }
11903
- if (!cart || cart.length === 0)
11904
- throw new Error("Missing required field: product_cart or product_id");
11905
- const paymentPayload = {
11906
- billing,
11907
- customer,
11908
- product_cart: cart
11909
- };
11910
- if (metadata) paymentPayload.metadata = metadata;
11911
- paymentPayload.payment_link = true;
11912
- if (allowed_payment_method_types)
11913
- paymentPayload.allowed_payment_method_types = allowed_payment_method_types;
11914
- if (billing_currency) paymentPayload.billing_currency = billing_currency;
11915
- if (discount_code) paymentPayload.discount_code = discount_code;
11916
- if (bodyReturnUrl) {
11917
- paymentPayload.return_url = bodyReturnUrl;
11918
- } else if (returnUrl) {
11919
- paymentPayload.return_url = returnUrl;
11920
- }
11921
- if (show_saved_payment_methods)
11922
- paymentPayload.show_saved_payment_methods = show_saved_payment_methods;
11923
- if (tax_id) paymentPayload.tax_id = tax_id;
11924
- let payment;
11925
- try {
11926
- payment = await dodopayments.payments.create(paymentPayload);
11927
- } catch (err) {
11928
- console.error("Error when creating payment link", err);
11929
- throw new Error(err instanceof Error ? err.message : String(err));
11930
- }
11931
- if (!payment || !payment.payment_link) {
11932
- throw new Error(
11933
- "No payment link returned from Dodo Payments API. Make sure to set payment_link as true in payload."
11934
- );
11935
- }
11936
- return payment.payment_link;
11937
- }
11938
- };
11939
-
11940
- const Checkout = (config) => {
11941
- const getHandler = async (req) => {
11942
- const { searchParams } = new URL(req.url);
11943
- const queryParams = Object.fromEntries(searchParams);
11944
- if (!queryParams.productId) {
11945
- return new serverExports.NextResponse("Please provide productId query parameter", {
11946
- status: 400,
11947
- });
11948
- }
11949
- const { success, data, error } = checkoutQuerySchema.safeParse(queryParams);
11950
- if (!success) {
11951
- if (error.errors.some((e) => e.path.toString() === "productId")) {
11952
- return new serverExports.NextResponse("Please provide productId query parameter", {
11953
- status: 400,
11954
- });
11955
- }
11956
- return new serverExports.NextResponse(`Invalid query parameters.\n ${error.message}`, {
11957
- status: 400,
11958
- });
11959
- }
11960
- let url = "";
11961
- try {
11962
- url = await buildCheckoutUrl({ queryParams: data, ...config });
11963
- }
11964
- catch (error) {
11965
- return new serverExports.NextResponse(error.message, { status: 400 });
11966
- }
11967
- return serverExports.NextResponse.json({ checkout_url: url });
11968
- };
11969
- const postHandler = async (req) => {
11970
- let body;
11971
- try {
11972
- body = await req.json();
11973
- }
11974
- catch (e) {
11975
- return new serverExports.NextResponse("Invalid JSON body", { status: 400 });
11976
- }
11977
- if (config.type === "dynamic") {
11978
- // Handle dynamic checkout
11979
- const { success, data, error } = dynamicCheckoutBodySchema.safeParse(body);
11980
- if (!success) {
11981
- return new serverExports.NextResponse(`Invalid request body.\n ${error.message}`, {
11982
- status: 400,
11983
- });
11984
- }
11985
- let url = "";
11986
- try {
11987
- url = await buildCheckoutUrl({
11988
- body: data,
11989
- ...config,
11990
- type: "dynamic",
11991
- });
11992
- }
11993
- catch (error) {
11994
- return new serverExports.NextResponse(error.message, { status: 400 });
11995
- }
11996
- return serverExports.NextResponse.json({ checkout_url: url });
11997
- }
11998
- else {
11999
- // Handle checkout session
12000
- const { success, data, error } = checkoutSessionPayloadSchema.safeParse(body);
12001
- if (!success) {
12002
- return new serverExports.NextResponse(`Invalid checkout session payload.\n ${error.message}`, {
12003
- status: 400,
12004
- });
12005
- }
12006
- let url = "";
12007
- try {
12008
- url = await buildCheckoutUrl({
12009
- sessionPayload: data,
12010
- ...config,
12011
- type: "session",
12012
- });
12013
- }
12014
- catch (error) {
12015
- return new serverExports.NextResponse(error.message, { status: 400 });
12016
- }
12017
- return serverExports.NextResponse.json({ checkout_url: url });
12018
- }
12019
- };
12020
- return (req) => {
12021
- if (req.method === "POST") {
12022
- return postHandler(req);
12023
- }
12024
- return getHandler(req);
12025
- };
12026
- };
12027
-
12028
- var dist = {};
12029
-
12030
- var timing_safe_equal = {};
12031
-
12032
- Object.defineProperty(timing_safe_equal, "__esModule", { value: true });
12033
- timing_safe_equal.timingSafeEqual = void 0;
12034
- function assert(expr, msg = "") {
12035
- if (!expr) {
12036
- throw new Error(msg);
12037
- }
12038
- }
12039
- function timingSafeEqual(a, b) {
12040
- if (a.byteLength !== b.byteLength) {
12041
- return false;
12042
- }
12043
- if (!(a instanceof DataView)) {
12044
- a = new DataView(ArrayBuffer.isView(a) ? a.buffer : a);
12045
- }
12046
- if (!(b instanceof DataView)) {
12047
- b = new DataView(ArrayBuffer.isView(b) ? b.buffer : b);
12048
- }
12049
- assert(a instanceof DataView);
12050
- assert(b instanceof DataView);
12051
- const length = a.byteLength;
12052
- let out = 0;
12053
- let i = -1;
12054
- while (++i < length) {
12055
- out |= a.getUint8(i) ^ b.getUint8(i);
12056
- }
12057
- return out === 0;
12058
- }
12059
- timing_safe_equal.timingSafeEqual = timingSafeEqual;
12060
-
12061
- var base64$1 = {};
12062
-
12063
- // Copyright (C) 2016 Dmitry Chestnykh
12064
- // MIT License. See LICENSE file for details.
12065
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
12066
- var extendStatics = function (d, b) {
12067
- extendStatics = Object.setPrototypeOf ||
12068
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
12069
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
12070
- return extendStatics(d, b);
12071
- };
12072
- return function (d, b) {
12073
- extendStatics(d, b);
12074
- function __() { this.constructor = d; }
12075
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12076
- };
12077
- })();
12078
- Object.defineProperty(base64$1, "__esModule", { value: true });
12079
- /**
12080
- * Package base64 implements Base64 encoding and decoding.
12081
- */
12082
- // Invalid character used in decoding to indicate
12083
- // that the character to decode is out of range of
12084
- // alphabet and cannot be decoded.
12085
- var INVALID_BYTE = 256;
12086
- /**
12087
- * Implements standard Base64 encoding.
12088
- *
12089
- * Operates in constant time.
12090
- */
12091
- var Coder = /** @class */ (function () {
12092
- // TODO(dchest): methods to encode chunk-by-chunk.
12093
- function Coder(_paddingCharacter) {
12094
- if (_paddingCharacter === void 0) { _paddingCharacter = "="; }
12095
- this._paddingCharacter = _paddingCharacter;
12096
- }
12097
- Coder.prototype.encodedLength = function (length) {
12098
- if (!this._paddingCharacter) {
12099
- return (length * 8 + 5) / 6 | 0;
12100
- }
12101
- return (length + 2) / 3 * 4 | 0;
12102
- };
12103
- Coder.prototype.encode = function (data) {
12104
- var out = "";
12105
- var i = 0;
12106
- for (; i < data.length - 2; i += 3) {
12107
- var c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);
12108
- out += this._encodeByte((c >>> 3 * 6) & 63);
12109
- out += this._encodeByte((c >>> 2 * 6) & 63);
12110
- out += this._encodeByte((c >>> 1 * 6) & 63);
12111
- out += this._encodeByte((c >>> 0 * 6) & 63);
12112
- }
12113
- var left = data.length - i;
12114
- if (left > 0) {
12115
- var c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0);
12116
- out += this._encodeByte((c >>> 3 * 6) & 63);
12117
- out += this._encodeByte((c >>> 2 * 6) & 63);
12118
- if (left === 2) {
12119
- out += this._encodeByte((c >>> 1 * 6) & 63);
12120
- }
12121
- else {
12122
- out += this._paddingCharacter || "";
12123
- }
12124
- out += this._paddingCharacter || "";
12125
- }
12126
- return out;
12127
- };
12128
- Coder.prototype.maxDecodedLength = function (length) {
12129
- if (!this._paddingCharacter) {
12130
- return (length * 6 + 7) / 8 | 0;
12131
- }
12132
- return length / 4 * 3 | 0;
12133
- };
12134
- Coder.prototype.decodedLength = function (s) {
12135
- return this.maxDecodedLength(s.length - this._getPaddingLength(s));
12136
- };
12137
- Coder.prototype.decode = function (s) {
12138
- if (s.length === 0) {
12139
- return new Uint8Array(0);
12140
- }
12141
- var paddingLength = this._getPaddingLength(s);
12142
- var length = s.length - paddingLength;
12143
- var out = new Uint8Array(this.maxDecodedLength(length));
12144
- var op = 0;
12145
- var i = 0;
12146
- var haveBad = 0;
12147
- var v0 = 0, v1 = 0, v2 = 0, v3 = 0;
12148
- for (; i < length - 4; i += 4) {
12149
- v0 = this._decodeChar(s.charCodeAt(i + 0));
12150
- v1 = this._decodeChar(s.charCodeAt(i + 1));
12151
- v2 = this._decodeChar(s.charCodeAt(i + 2));
12152
- v3 = this._decodeChar(s.charCodeAt(i + 3));
12153
- out[op++] = (v0 << 2) | (v1 >>> 4);
12154
- out[op++] = (v1 << 4) | (v2 >>> 2);
12155
- out[op++] = (v2 << 6) | v3;
12156
- haveBad |= v0 & INVALID_BYTE;
12157
- haveBad |= v1 & INVALID_BYTE;
12158
- haveBad |= v2 & INVALID_BYTE;
12159
- haveBad |= v3 & INVALID_BYTE;
12160
- }
12161
- if (i < length - 1) {
12162
- v0 = this._decodeChar(s.charCodeAt(i));
12163
- v1 = this._decodeChar(s.charCodeAt(i + 1));
12164
- out[op++] = (v0 << 2) | (v1 >>> 4);
12165
- haveBad |= v0 & INVALID_BYTE;
12166
- haveBad |= v1 & INVALID_BYTE;
12167
- }
12168
- if (i < length - 2) {
12169
- v2 = this._decodeChar(s.charCodeAt(i + 2));
12170
- out[op++] = (v1 << 4) | (v2 >>> 2);
12171
- haveBad |= v2 & INVALID_BYTE;
12172
- }
12173
- if (i < length - 3) {
12174
- v3 = this._decodeChar(s.charCodeAt(i + 3));
12175
- out[op++] = (v2 << 6) | v3;
12176
- haveBad |= v3 & INVALID_BYTE;
12177
- }
12178
- if (haveBad !== 0) {
12179
- throw new Error("Base64Coder: incorrect characters for decoding");
12180
- }
12181
- return out;
12182
- };
12183
- // Standard encoding have the following encoded/decoded ranges,
12184
- // which we need to convert between.
12185
- //
12186
- // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + /
12187
- // Index: 0 - 25 26 - 51 52 - 61 62 63
12188
- // ASCII: 65 - 90 97 - 122 48 - 57 43 47
12189
- //
12190
- // Encode 6 bits in b into a new character.
12191
- Coder.prototype._encodeByte = function (b) {
12192
- // Encoding uses constant time operations as follows:
12193
- //
12194
- // 1. Define comparison of A with B using (A - B) >>> 8:
12195
- // if A > B, then result is positive integer
12196
- // if A <= B, then result is 0
12197
- //
12198
- // 2. Define selection of C or 0 using bitwise AND: X & C:
12199
- // if X == 0, then result is 0
12200
- // if X != 0, then result is C
12201
- //
12202
- // 3. Start with the smallest comparison (b >= 0), which is always
12203
- // true, so set the result to the starting ASCII value (65).
12204
- //
12205
- // 4. Continue comparing b to higher ASCII values, and selecting
12206
- // zero if comparison isn't true, otherwise selecting a value
12207
- // to add to result, which:
12208
- //
12209
- // a) undoes the previous addition
12210
- // b) provides new value to add
12211
- //
12212
- var result = b;
12213
- // b >= 0
12214
- result += 65;
12215
- // b > 25
12216
- result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
12217
- // b > 51
12218
- result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
12219
- // b > 61
12220
- result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43);
12221
- // b > 62
12222
- result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47);
12223
- return String.fromCharCode(result);
12224
- };
12225
- // Decode a character code into a byte.
12226
- // Must return 256 if character is out of alphabet range.
12227
- Coder.prototype._decodeChar = function (c) {
12228
- // Decoding works similar to encoding: using the same comparison
12229
- // function, but now it works on ranges: result is always incremented
12230
- // by value, but this value becomes zero if the range is not
12231
- // satisfied.
12232
- //
12233
- // Decoding starts with invalid value, 256, which is then
12234
- // subtracted when the range is satisfied. If none of the ranges
12235
- // apply, the function returns 256, which is then checked by
12236
- // the caller to throw error.
12237
- var result = INVALID_BYTE; // start with invalid character
12238
- // c == 43 (c > 42 and c < 44)
12239
- result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62);
12240
- // c == 47 (c > 46 and c < 48)
12241
- result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63);
12242
- // c > 47 and c < 58
12243
- result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
12244
- // c > 64 and c < 91
12245
- result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
12246
- // c > 96 and c < 123
12247
- result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
12248
- return result;
12249
- };
12250
- Coder.prototype._getPaddingLength = function (s) {
12251
- var paddingLength = 0;
12252
- if (this._paddingCharacter) {
12253
- for (var i = s.length - 1; i >= 0; i--) {
12254
- if (s[i] !== this._paddingCharacter) {
12255
- break;
12256
- }
12257
- paddingLength++;
12258
- }
12259
- if (s.length < 4 || paddingLength > 2) {
12260
- throw new Error("Base64Coder: incorrect padding");
12261
- }
12262
- }
12263
- return paddingLength;
12264
- };
12265
- return Coder;
12266
- }());
12267
- base64$1.Coder = Coder;
12268
- var stdCoder = new Coder();
12269
- function encode(data) {
12270
- return stdCoder.encode(data);
12271
- }
12272
- base64$1.encode = encode;
12273
- function decode(s) {
12274
- return stdCoder.decode(s);
12275
- }
12276
- base64$1.decode = decode;
12277
- /**
12278
- * Implements URL-safe Base64 encoding.
12279
- * (Same as Base64, but '+' is replaced with '-', and '/' with '_').
12280
- *
12281
- * Operates in constant time.
12282
- */
12283
- var URLSafeCoder = /** @class */ (function (_super) {
12284
- __extends(URLSafeCoder, _super);
12285
- function URLSafeCoder() {
12286
- return _super !== null && _super.apply(this, arguments) || this;
12287
- }
12288
- // URL-safe encoding have the following encoded/decoded ranges:
12289
- //
12290
- // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _
12291
- // Index: 0 - 25 26 - 51 52 - 61 62 63
12292
- // ASCII: 65 - 90 97 - 122 48 - 57 45 95
12293
- //
12294
- URLSafeCoder.prototype._encodeByte = function (b) {
12295
- var result = b;
12296
- // b >= 0
12297
- result += 65;
12298
- // b > 25
12299
- result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
12300
- // b > 51
12301
- result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
12302
- // b > 61
12303
- result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45);
12304
- // b > 62
12305
- result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95);
12306
- return String.fromCharCode(result);
12307
- };
12308
- URLSafeCoder.prototype._decodeChar = function (c) {
12309
- var result = INVALID_BYTE;
12310
- // c == 45 (c > 44 and c < 46)
12311
- result += (((44 - c) & (c - 46)) >>> 8) & (-INVALID_BYTE + c - 45 + 62);
12312
- // c == 95 (c > 94 and c < 96)
12313
- result += (((94 - c) & (c - 96)) >>> 8) & (-INVALID_BYTE + c - 95 + 63);
12314
- // c > 47 and c < 58
12315
- result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
12316
- // c > 64 and c < 91
12317
- result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
12318
- // c > 96 and c < 123
12319
- result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
12320
- return result;
12321
- };
12322
- return URLSafeCoder;
12323
- }(Coder));
12324
- base64$1.URLSafeCoder = URLSafeCoder;
12325
- var urlSafeCoder = new URLSafeCoder();
12326
- function encodeURLSafe(data) {
12327
- return urlSafeCoder.encode(data);
12328
- }
12329
- base64$1.encodeURLSafe = encodeURLSafe;
12330
- function decodeURLSafe(s) {
12331
- return urlSafeCoder.decode(s);
12332
- }
12333
- base64$1.decodeURLSafe = decodeURLSafe;
12334
- base64$1.encodedLength = function (length) {
12335
- return stdCoder.encodedLength(length);
12336
- };
12337
- base64$1.maxDecodedLength = function (length) {
12338
- return stdCoder.maxDecodedLength(length);
12339
- };
12340
- base64$1.decodedLength = function (s) {
12341
- return stdCoder.decodedLength(s);
11296
+ base64$1.encodeURLSafe = encodeURLSafe;
11297
+ function decodeURLSafe(s) {
11298
+ return urlSafeCoder.decode(s);
11299
+ }
11300
+ base64$1.decodeURLSafe = decodeURLSafe;
11301
+ base64$1.encodedLength = function (length) {
11302
+ return stdCoder.encodedLength(length);
11303
+ };
11304
+ base64$1.maxDecodedLength = function (length) {
11305
+ return stdCoder.maxDecodedLength(length);
11306
+ };
11307
+ base64$1.decodedLength = function (s) {
11308
+ return stdCoder.decodedLength(s);
12342
11309
  };
12343
11310
 
12344
11311
  var sha256$1 = {exports: {}};
@@ -12770,109 +11737,1232 @@ var sha256$1 = {exports: {}};
12770
11737
 
12771
11738
  var sha256Exports = sha256$1.exports;
12772
11739
 
12773
- Object.defineProperty(dist, "__esModule", { value: true });
12774
- var Webhook_1 = dist.Webhook = WebhookVerificationError_1 = dist.WebhookVerificationError = void 0;
12775
- const timing_safe_equal_1 = timing_safe_equal;
12776
- const base64 = base64$1;
12777
- const sha256 = sha256Exports;
12778
- const WEBHOOK_TOLERANCE_IN_SECONDS = 5 * 60;
12779
- class ExtendableError extends Error {
12780
- constructor(message) {
12781
- super(message);
12782
- Object.setPrototypeOf(this, ExtendableError.prototype);
12783
- this.name = "ExtendableError";
12784
- this.stack = new Error(message).stack;
11740
+ Object.defineProperty(dist, "__esModule", { value: true });
11741
+ var Webhook_1 = dist.Webhook = WebhookVerificationError_1 = dist.WebhookVerificationError = void 0;
11742
+ const timing_safe_equal_1 = timing_safe_equal;
11743
+ const base64 = base64$1;
11744
+ const sha256 = sha256Exports;
11745
+ const WEBHOOK_TOLERANCE_IN_SECONDS = 5 * 60;
11746
+ class ExtendableError extends Error {
11747
+ constructor(message) {
11748
+ super(message);
11749
+ Object.setPrototypeOf(this, ExtendableError.prototype);
11750
+ this.name = "ExtendableError";
11751
+ this.stack = new Error(message).stack;
11752
+ }
11753
+ }
11754
+ class WebhookVerificationError extends ExtendableError {
11755
+ constructor(message) {
11756
+ super(message);
11757
+ Object.setPrototypeOf(this, WebhookVerificationError.prototype);
11758
+ this.name = "WebhookVerificationError";
11759
+ }
11760
+ }
11761
+ var WebhookVerificationError_1 = dist.WebhookVerificationError = WebhookVerificationError;
11762
+ class Webhook {
11763
+ constructor(secret, options) {
11764
+ if (!secret) {
11765
+ throw new Error("Secret can't be empty.");
11766
+ }
11767
+ if ((options === null || options === void 0 ? void 0 : options.format) === "raw") {
11768
+ if (secret instanceof Uint8Array) {
11769
+ this.key = secret;
11770
+ }
11771
+ else {
11772
+ this.key = Uint8Array.from(secret, (c) => c.charCodeAt(0));
11773
+ }
11774
+ }
11775
+ else {
11776
+ if (typeof secret !== "string") {
11777
+ throw new Error("Expected secret to be of type string");
11778
+ }
11779
+ if (secret.startsWith(Webhook.prefix)) {
11780
+ secret = secret.substring(Webhook.prefix.length);
11781
+ }
11782
+ this.key = base64.decode(secret);
11783
+ }
11784
+ }
11785
+ verify(payload, headers_) {
11786
+ const headers = {};
11787
+ for (const key of Object.keys(headers_)) {
11788
+ headers[key.toLowerCase()] = headers_[key];
11789
+ }
11790
+ const msgId = headers["webhook-id"];
11791
+ const msgSignature = headers["webhook-signature"];
11792
+ const msgTimestamp = headers["webhook-timestamp"];
11793
+ if (!msgSignature || !msgId || !msgTimestamp) {
11794
+ throw new WebhookVerificationError("Missing required headers");
11795
+ }
11796
+ const timestamp = this.verifyTimestamp(msgTimestamp);
11797
+ const computedSignature = this.sign(msgId, timestamp, payload);
11798
+ const expectedSignature = computedSignature.split(",")[1];
11799
+ const passedSignatures = msgSignature.split(" ");
11800
+ const encoder = new globalThis.TextEncoder();
11801
+ for (const versionedSignature of passedSignatures) {
11802
+ const [version, signature] = versionedSignature.split(",");
11803
+ if (version !== "v1") {
11804
+ continue;
11805
+ }
11806
+ if ((0, timing_safe_equal_1.timingSafeEqual)(encoder.encode(signature), encoder.encode(expectedSignature))) {
11807
+ return JSON.parse(payload.toString());
11808
+ }
11809
+ }
11810
+ throw new WebhookVerificationError("No matching signature found");
11811
+ }
11812
+ sign(msgId, timestamp, payload) {
11813
+ if (typeof payload === "string") ;
11814
+ else if (payload.constructor.name === "Buffer") {
11815
+ payload = payload.toString();
11816
+ }
11817
+ else {
11818
+ throw new Error("Expected payload to be of type string or Buffer.");
11819
+ }
11820
+ const encoder = new TextEncoder();
11821
+ const timestampNumber = Math.floor(timestamp.getTime() / 1000);
11822
+ const toSign = encoder.encode(`${msgId}.${timestampNumber}.${payload}`);
11823
+ const expectedSignature = base64.encode(sha256.hmac(this.key, toSign));
11824
+ return `v1,${expectedSignature}`;
11825
+ }
11826
+ verifyTimestamp(timestampHeader) {
11827
+ const now = Math.floor(Date.now() / 1000);
11828
+ const timestamp = parseInt(timestampHeader, 10);
11829
+ if (isNaN(timestamp)) {
11830
+ throw new WebhookVerificationError("Invalid Signature Headers");
11831
+ }
11832
+ if (now - timestamp > WEBHOOK_TOLERANCE_IN_SECONDS) {
11833
+ throw new WebhookVerificationError("Message timestamp too old");
11834
+ }
11835
+ if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) {
11836
+ throw new WebhookVerificationError("Message timestamp too new");
11837
+ }
11838
+ return new Date(timestamp * 1000);
11839
+ }
11840
+ }
11841
+ Webhook_1 = dist.Webhook = Webhook;
11842
+ Webhook.prefix = "whsec_";
11843
+
11844
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
11845
+ let Webhooks$1 = class Webhooks extends APIResource {
11846
+ constructor() {
11847
+ super(...arguments);
11848
+ this.headers = new Headers$1(this._client);
11849
+ }
11850
+ /**
11851
+ * Create a new webhook
11852
+ */
11853
+ create(body, options) {
11854
+ return this._client.post('/webhooks', { body, ...options });
11855
+ }
11856
+ /**
11857
+ * Get a webhook by id
11858
+ */
11859
+ retrieve(webhookID, options) {
11860
+ return this._client.get(path `/webhooks/${webhookID}`, options);
11861
+ }
11862
+ /**
11863
+ * Patch a webhook by id
11864
+ */
11865
+ update(webhookID, body, options) {
11866
+ return this._client.patch(path `/webhooks/${webhookID}`, { body, ...options });
11867
+ }
11868
+ /**
11869
+ * List all webhooks
11870
+ */
11871
+ list(query = {}, options) {
11872
+ return this._client.getAPIList('/webhooks', (CursorPagePagination), { query, ...options });
11873
+ }
11874
+ /**
11875
+ * Delete a webhook by id
11876
+ */
11877
+ delete(webhookID, options) {
11878
+ return this._client.delete(path `/webhooks/${webhookID}`, {
11879
+ ...options,
11880
+ headers: buildHeaders([{ Accept: '*/*' }, options?.headers]),
11881
+ });
11882
+ }
11883
+ /**
11884
+ * Get webhook secret by id
11885
+ */
11886
+ retrieveSecret(webhookID, options) {
11887
+ return this._client.get(path `/webhooks/${webhookID}/secret`, options);
11888
+ }
11889
+ unsafeUnwrap(body) {
11890
+ return JSON.parse(body);
11891
+ }
11892
+ unwrap(body, { headers, key }) {
11893
+ if (headers !== undefined) {
11894
+ const keyStr = key === undefined ? this._client.webhookKey : key;
11895
+ if (keyStr === null)
11896
+ throw new Error('Webhook key must not be null in order to unwrap');
11897
+ const wh = new Webhook_1(keyStr);
11898
+ wh.verify(body, headers);
11899
+ }
11900
+ return JSON.parse(body);
11901
+ }
11902
+ };
11903
+ Webhooks$1.Headers = Headers$1;
11904
+
11905
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
11906
+ /**
11907
+ * Read an environment variable.
11908
+ *
11909
+ * Trims beginning and trailing whitespace.
11910
+ *
11911
+ * Will return undefined if the environment variable doesn't exist or cannot be accessed.
11912
+ */
11913
+ const readEnv = (env) => {
11914
+ if (typeof globalThis.process !== 'undefined') {
11915
+ return globalThis.process.env?.[env]?.trim() ?? undefined;
11916
+ }
11917
+ if (typeof globalThis.Deno !== 'undefined') {
11918
+ return globalThis.Deno.env?.get?.(env)?.trim();
11919
+ }
11920
+ return undefined;
11921
+ };
11922
+
11923
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
11924
+ var _DodoPayments_instances, _a, _DodoPayments_encoder, _DodoPayments_baseURLOverridden;
11925
+ const environments = {
11926
+ live_mode: 'https://live.dodopayments.com',
11927
+ test_mode: 'https://test.dodopayments.com',
11928
+ };
11929
+ /**
11930
+ * API Client for interfacing with the Dodo Payments API.
11931
+ */
11932
+ class DodoPayments {
11933
+ /**
11934
+ * API Client for interfacing with the Dodo Payments API.
11935
+ *
11936
+ * @param {string | undefined} [opts.bearerToken=process.env['DODO_PAYMENTS_API_KEY'] ?? undefined]
11937
+ * @param {string | null | undefined} [opts.webhookKey=process.env['DODO_PAYMENTS_WEBHOOK_KEY'] ?? null]
11938
+ * @param {Environment} [opts.environment=live_mode] - Specifies the environment URL to use for the API.
11939
+ * @param {string} [opts.baseURL=process.env['DODO_PAYMENTS_BASE_URL'] ?? https://live.dodopayments.com] - Override the default base URL for the API.
11940
+ * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
11941
+ * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
11942
+ * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
11943
+ * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
11944
+ * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
11945
+ * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
11946
+ */
11947
+ constructor({ baseURL = readEnv('DODO_PAYMENTS_BASE_URL'), bearerToken = readEnv('DODO_PAYMENTS_API_KEY'), webhookKey = readEnv('DODO_PAYMENTS_WEBHOOK_KEY') ?? null, ...opts } = {}) {
11948
+ _DodoPayments_instances.add(this);
11949
+ _DodoPayments_encoder.set(this, void 0);
11950
+ this.checkoutSessions = new CheckoutSessions(this);
11951
+ this.payments = new Payments(this);
11952
+ this.subscriptions = new Subscriptions(this);
11953
+ this.invoices = new Invoices(this);
11954
+ this.licenses = new Licenses(this);
11955
+ this.licenseKeys = new LicenseKeys(this);
11956
+ this.licenseKeyInstances = new LicenseKeyInstances(this);
11957
+ this.customers = new Customers(this);
11958
+ this.refunds = new Refunds(this);
11959
+ this.disputes = new Disputes(this);
11960
+ this.payouts = new Payouts(this);
11961
+ this.products = new Products(this);
11962
+ this.misc = new Misc(this);
11963
+ this.discounts = new Discounts(this);
11964
+ this.addons = new Addons(this);
11965
+ this.brands = new Brands(this);
11966
+ this.webhooks = new Webhooks$1(this);
11967
+ this.webhookEvents = new WebhookEvents(this);
11968
+ this.usageEvents = new UsageEvents(this);
11969
+ this.meters = new Meters(this);
11970
+ if (bearerToken === undefined) {
11971
+ throw new DodoPaymentsError("The DODO_PAYMENTS_API_KEY environment variable is missing or empty; either provide it, or instantiate the DodoPayments client with an bearerToken option, like new DodoPayments({ bearerToken: 'My Bearer Token' }).");
11972
+ }
11973
+ const options = {
11974
+ bearerToken,
11975
+ webhookKey,
11976
+ ...opts,
11977
+ baseURL,
11978
+ environment: opts.environment ?? 'live_mode',
11979
+ };
11980
+ if (baseURL && opts.environment) {
11981
+ throw new DodoPaymentsError('Ambiguous URL; The `baseURL` option (or DODO_PAYMENTS_BASE_URL env var) and the `environment` option are given. If you want to use the environment you must pass baseURL: null');
11982
+ }
11983
+ this.baseURL = options.baseURL || environments[options.environment || 'live_mode'];
11984
+ this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 1 minute */;
11985
+ this.logger = options.logger ?? console;
11986
+ const defaultLogLevel = 'warn';
11987
+ // Set default logLevel early so that we can log a warning in parseLogLevel.
11988
+ this.logLevel = defaultLogLevel;
11989
+ this.logLevel =
11990
+ parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??
11991
+ parseLogLevel(readEnv('DODO_PAYMENTS_LOG'), "process.env['DODO_PAYMENTS_LOG']", this) ??
11992
+ defaultLogLevel;
11993
+ this.fetchOptions = options.fetchOptions;
11994
+ this.maxRetries = options.maxRetries ?? 2;
11995
+ this.fetch = options.fetch ?? getDefaultFetch();
11996
+ __classPrivateFieldSet(this, _DodoPayments_encoder, FallbackEncoder);
11997
+ this._options = options;
11998
+ this.bearerToken = bearerToken;
11999
+ this.webhookKey = webhookKey;
12000
+ }
12001
+ /**
12002
+ * Create a new client instance re-using the same options given to the current client with optional overriding.
12003
+ */
12004
+ withOptions(options) {
12005
+ const client = new this.constructor({
12006
+ ...this._options,
12007
+ environment: options.environment ? options.environment : undefined,
12008
+ baseURL: options.environment ? undefined : this.baseURL,
12009
+ maxRetries: this.maxRetries,
12010
+ timeout: this.timeout,
12011
+ logger: this.logger,
12012
+ logLevel: this.logLevel,
12013
+ fetch: this.fetch,
12014
+ fetchOptions: this.fetchOptions,
12015
+ bearerToken: this.bearerToken,
12016
+ webhookKey: this.webhookKey,
12017
+ ...options,
12018
+ });
12019
+ return client;
12020
+ }
12021
+ defaultQuery() {
12022
+ return this._options.defaultQuery;
12023
+ }
12024
+ validateHeaders({ values, nulls }) {
12025
+ return;
12026
+ }
12027
+ async authHeaders(opts) {
12028
+ return buildHeaders([{ Authorization: `Bearer ${this.bearerToken}` }]);
12029
+ }
12030
+ /**
12031
+ * Basic re-implementation of `qs.stringify` for primitive types.
12032
+ */
12033
+ stringifyQuery(query) {
12034
+ return Object.entries(query)
12035
+ .filter(([_, value]) => typeof value !== 'undefined')
12036
+ .map(([key, value]) => {
12037
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
12038
+ return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
12039
+ }
12040
+ if (value === null) {
12041
+ return `${encodeURIComponent(key)}=`;
12042
+ }
12043
+ throw new DodoPaymentsError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
12044
+ })
12045
+ .join('&');
12046
+ }
12047
+ getUserAgent() {
12048
+ return `${this.constructor.name}/JS ${VERSION}`;
12049
+ }
12050
+ defaultIdempotencyKey() {
12051
+ return `stainless-node-retry-${uuid4()}`;
12052
+ }
12053
+ makeStatusError(status, error, message, headers) {
12054
+ return APIError.generate(status, error, message, headers);
12055
+ }
12056
+ buildURL(path, query, defaultBaseURL) {
12057
+ const baseURL = (!__classPrivateFieldGet(this, _DodoPayments_instances, "m", _DodoPayments_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;
12058
+ const url = isAbsoluteURL(path) ?
12059
+ new URL(path)
12060
+ : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
12061
+ const defaultQuery = this.defaultQuery();
12062
+ if (!isEmptyObj(defaultQuery)) {
12063
+ query = { ...defaultQuery, ...query };
12064
+ }
12065
+ if (typeof query === 'object' && query && !Array.isArray(query)) {
12066
+ url.search = this.stringifyQuery(query);
12067
+ }
12068
+ return url.toString();
12069
+ }
12070
+ /**
12071
+ * Used as a callback for mutating the given `FinalRequestOptions` object.
12072
+ */
12073
+ async prepareOptions(options) { }
12074
+ /**
12075
+ * Used as a callback for mutating the given `RequestInit` object.
12076
+ *
12077
+ * This is useful for cases where you want to add certain headers based off of
12078
+ * the request properties, e.g. `method` or `url`.
12079
+ */
12080
+ async prepareRequest(request, { url, options }) { }
12081
+ get(path, opts) {
12082
+ return this.methodRequest('get', path, opts);
12083
+ }
12084
+ post(path, opts) {
12085
+ return this.methodRequest('post', path, opts);
12086
+ }
12087
+ patch(path, opts) {
12088
+ return this.methodRequest('patch', path, opts);
12089
+ }
12090
+ put(path, opts) {
12091
+ return this.methodRequest('put', path, opts);
12092
+ }
12093
+ delete(path, opts) {
12094
+ return this.methodRequest('delete', path, opts);
12095
+ }
12096
+ methodRequest(method, path, opts) {
12097
+ return this.request(Promise.resolve(opts).then((opts) => {
12098
+ return { method, path, ...opts };
12099
+ }));
12100
+ }
12101
+ request(options, remainingRetries = null) {
12102
+ return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
12103
+ }
12104
+ async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
12105
+ const options = await optionsInput;
12106
+ const maxRetries = options.maxRetries ?? this.maxRetries;
12107
+ if (retriesRemaining == null) {
12108
+ retriesRemaining = maxRetries;
12109
+ }
12110
+ await this.prepareOptions(options);
12111
+ const { req, url, timeout } = await this.buildRequest(options, {
12112
+ retryCount: maxRetries - retriesRemaining,
12113
+ });
12114
+ await this.prepareRequest(req, { url, options });
12115
+ /** Not an API request ID, just for correlating local log entries. */
12116
+ const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
12117
+ const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
12118
+ const startTime = Date.now();
12119
+ loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
12120
+ retryOfRequestLogID,
12121
+ method: options.method,
12122
+ url,
12123
+ options,
12124
+ headers: req.headers,
12125
+ }));
12126
+ if (options.signal?.aborted) {
12127
+ throw new APIUserAbortError();
12128
+ }
12129
+ const controller = new AbortController();
12130
+ const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
12131
+ const headersTime = Date.now();
12132
+ if (response instanceof globalThis.Error) {
12133
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
12134
+ if (options.signal?.aborted) {
12135
+ throw new APIUserAbortError();
12136
+ }
12137
+ // detect native connection timeout errors
12138
+ // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)"
12139
+ // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
12140
+ // others do not provide enough information to distinguish timeouts from other connection errors
12141
+ const isTimeout = isAbortError(response) ||
12142
+ /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
12143
+ if (retriesRemaining) {
12144
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
12145
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({
12146
+ retryOfRequestLogID,
12147
+ url,
12148
+ durationMs: headersTime - startTime,
12149
+ message: response.message,
12150
+ }));
12151
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
12152
+ }
12153
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
12154
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({
12155
+ retryOfRequestLogID,
12156
+ url,
12157
+ durationMs: headersTime - startTime,
12158
+ message: response.message,
12159
+ }));
12160
+ if (isTimeout) {
12161
+ throw new APIConnectionTimeoutError();
12162
+ }
12163
+ throw new APIConnectionError({ cause: response });
12164
+ }
12165
+ const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
12166
+ if (!response.ok) {
12167
+ const shouldRetry = await this.shouldRetry(response);
12168
+ if (retriesRemaining && shouldRetry) {
12169
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
12170
+ // We don't need the body of this response.
12171
+ await CancelReadableStream(response.body);
12172
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
12173
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
12174
+ retryOfRequestLogID,
12175
+ url: response.url,
12176
+ status: response.status,
12177
+ headers: response.headers,
12178
+ durationMs: headersTime - startTime,
12179
+ }));
12180
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
12181
+ }
12182
+ const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
12183
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
12184
+ const errText = await response.text().catch((err) => castToError(err).message);
12185
+ const errJSON = safeJSON(errText);
12186
+ const errMessage = errJSON ? undefined : errText;
12187
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
12188
+ retryOfRequestLogID,
12189
+ url: response.url,
12190
+ status: response.status,
12191
+ headers: response.headers,
12192
+ message: errMessage,
12193
+ durationMs: Date.now() - startTime,
12194
+ }));
12195
+ const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
12196
+ throw err;
12197
+ }
12198
+ loggerFor(this).info(responseInfo);
12199
+ loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
12200
+ retryOfRequestLogID,
12201
+ url: response.url,
12202
+ status: response.status,
12203
+ headers: response.headers,
12204
+ durationMs: headersTime - startTime,
12205
+ }));
12206
+ return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
12207
+ }
12208
+ getAPIList(path, Page, opts) {
12209
+ return this.requestAPIList(Page, { method: 'get', path, ...opts });
12210
+ }
12211
+ requestAPIList(Page, options) {
12212
+ const request = this.makeRequest(options, null, undefined);
12213
+ return new PagePromise(this, request, Page);
12214
+ }
12215
+ async fetchWithTimeout(url, init, ms, controller) {
12216
+ const { signal, method, ...options } = init || {};
12217
+ if (signal)
12218
+ signal.addEventListener('abort', () => controller.abort());
12219
+ const timeout = setTimeout(() => controller.abort(), ms);
12220
+ const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
12221
+ (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
12222
+ const fetchOptions = {
12223
+ signal: controller.signal,
12224
+ ...(isReadableBody ? { duplex: 'half' } : {}),
12225
+ method: 'GET',
12226
+ ...options,
12227
+ };
12228
+ if (method) {
12229
+ // Custom methods like 'patch' need to be uppercased
12230
+ // See https://github.com/nodejs/undici/issues/2294
12231
+ fetchOptions.method = method.toUpperCase();
12232
+ }
12233
+ try {
12234
+ // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
12235
+ return await this.fetch.call(undefined, url, fetchOptions);
12236
+ }
12237
+ finally {
12238
+ clearTimeout(timeout);
12239
+ }
12240
+ }
12241
+ async shouldRetry(response) {
12242
+ // Note this is not a standard header.
12243
+ const shouldRetryHeader = response.headers.get('x-should-retry');
12244
+ // If the server explicitly says whether or not to retry, obey.
12245
+ if (shouldRetryHeader === 'true')
12246
+ return true;
12247
+ if (shouldRetryHeader === 'false')
12248
+ return false;
12249
+ // Retry on request timeouts.
12250
+ if (response.status === 408)
12251
+ return true;
12252
+ // Retry on lock timeouts.
12253
+ if (response.status === 409)
12254
+ return true;
12255
+ // Retry on rate limits.
12256
+ if (response.status === 429)
12257
+ return true;
12258
+ // Retry internal errors.
12259
+ if (response.status >= 500)
12260
+ return true;
12261
+ return false;
12262
+ }
12263
+ async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
12264
+ let timeoutMillis;
12265
+ // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
12266
+ const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
12267
+ if (retryAfterMillisHeader) {
12268
+ const timeoutMs = parseFloat(retryAfterMillisHeader);
12269
+ if (!Number.isNaN(timeoutMs)) {
12270
+ timeoutMillis = timeoutMs;
12271
+ }
12272
+ }
12273
+ // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
12274
+ const retryAfterHeader = responseHeaders?.get('retry-after');
12275
+ if (retryAfterHeader && !timeoutMillis) {
12276
+ const timeoutSeconds = parseFloat(retryAfterHeader);
12277
+ if (!Number.isNaN(timeoutSeconds)) {
12278
+ timeoutMillis = timeoutSeconds * 1000;
12279
+ }
12280
+ else {
12281
+ timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
12282
+ }
12283
+ }
12284
+ // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
12285
+ // just do what it says, but otherwise calculate a default
12286
+ if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
12287
+ const maxRetries = options.maxRetries ?? this.maxRetries;
12288
+ timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
12289
+ }
12290
+ await sleep(timeoutMillis);
12291
+ return this.makeRequest(options, retriesRemaining - 1, requestLogID);
12292
+ }
12293
+ calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
12294
+ const initialRetryDelay = 0.5;
12295
+ const maxRetryDelay = 8.0;
12296
+ const numRetries = maxRetries - retriesRemaining;
12297
+ // Apply exponential backoff, but not more than the max.
12298
+ const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
12299
+ // Apply some jitter, take up to at most 25 percent of the retry time.
12300
+ const jitter = 1 - Math.random() * 0.25;
12301
+ return sleepSeconds * jitter * 1000;
12302
+ }
12303
+ async buildRequest(inputOptions, { retryCount = 0 } = {}) {
12304
+ const options = { ...inputOptions };
12305
+ const { method, path, query, defaultBaseURL } = options;
12306
+ const url = this.buildURL(path, query, defaultBaseURL);
12307
+ if ('timeout' in options)
12308
+ validatePositiveInteger('timeout', options.timeout);
12309
+ options.timeout = options.timeout ?? this.timeout;
12310
+ const { bodyHeaders, body } = this.buildBody({ options });
12311
+ const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
12312
+ const req = {
12313
+ method,
12314
+ headers: reqHeaders,
12315
+ ...(options.signal && { signal: options.signal }),
12316
+ ...(globalThis.ReadableStream &&
12317
+ body instanceof globalThis.ReadableStream && { duplex: 'half' }),
12318
+ ...(body && { body }),
12319
+ ...(this.fetchOptions ?? {}),
12320
+ ...(options.fetchOptions ?? {}),
12321
+ };
12322
+ return { req, url, timeout: options.timeout };
12323
+ }
12324
+ async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
12325
+ let idempotencyHeaders = {};
12326
+ if (this.idempotencyHeader && method !== 'get') {
12327
+ if (!options.idempotencyKey)
12328
+ options.idempotencyKey = this.defaultIdempotencyKey();
12329
+ idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
12330
+ }
12331
+ const headers = buildHeaders([
12332
+ idempotencyHeaders,
12333
+ {
12334
+ Accept: 'application/json',
12335
+ 'User-Agent': this.getUserAgent(),
12336
+ 'X-Stainless-Retry-Count': String(retryCount),
12337
+ ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
12338
+ ...getPlatformHeaders(),
12339
+ },
12340
+ await this.authHeaders(options),
12341
+ this._options.defaultHeaders,
12342
+ bodyHeaders,
12343
+ options.headers,
12344
+ ]);
12345
+ this.validateHeaders(headers);
12346
+ return headers.values;
12347
+ }
12348
+ buildBody({ options: { body, headers: rawHeaders } }) {
12349
+ if (!body) {
12350
+ return { bodyHeaders: undefined, body: undefined };
12351
+ }
12352
+ const headers = buildHeaders([rawHeaders]);
12353
+ if (
12354
+ // Pass raw type verbatim
12355
+ ArrayBuffer.isView(body) ||
12356
+ body instanceof ArrayBuffer ||
12357
+ body instanceof DataView ||
12358
+ (typeof body === 'string' &&
12359
+ // Preserve legacy string encoding behavior for now
12360
+ headers.values.has('content-type')) ||
12361
+ // `Blob` is superset of `File`
12362
+ (globalThis.Blob && body instanceof globalThis.Blob) ||
12363
+ // `FormData` -> `multipart/form-data`
12364
+ body instanceof FormData ||
12365
+ // `URLSearchParams` -> `application/x-www-form-urlencoded`
12366
+ body instanceof URLSearchParams ||
12367
+ // Send chunked stream (each chunk has own `length`)
12368
+ (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
12369
+ return { bodyHeaders: undefined, body: body };
12370
+ }
12371
+ else if (typeof body === 'object' &&
12372
+ (Symbol.asyncIterator in body ||
12373
+ (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
12374
+ return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
12375
+ }
12376
+ else {
12377
+ return __classPrivateFieldGet(this, _DodoPayments_encoder, "f").call(this, { body, headers });
12378
+ }
12379
+ }
12380
+ }
12381
+ _a = DodoPayments, _DodoPayments_encoder = new WeakMap(), _DodoPayments_instances = new WeakSet(), _DodoPayments_baseURLOverridden = function _DodoPayments_baseURLOverridden() {
12382
+ return this.baseURL !== environments[this._options.environment || 'live_mode'];
12383
+ };
12384
+ DodoPayments.DodoPayments = _a;
12385
+ DodoPayments.DEFAULT_TIMEOUT = 60000; // 1 minute
12386
+ DodoPayments.DodoPaymentsError = DodoPaymentsError;
12387
+ DodoPayments.APIError = APIError;
12388
+ DodoPayments.APIConnectionError = APIConnectionError;
12389
+ DodoPayments.APIConnectionTimeoutError = APIConnectionTimeoutError;
12390
+ DodoPayments.APIUserAbortError = APIUserAbortError;
12391
+ DodoPayments.NotFoundError = NotFoundError;
12392
+ DodoPayments.ConflictError = ConflictError;
12393
+ DodoPayments.RateLimitError = RateLimitError;
12394
+ DodoPayments.BadRequestError = BadRequestError;
12395
+ DodoPayments.AuthenticationError = AuthenticationError;
12396
+ DodoPayments.InternalServerError = InternalServerError;
12397
+ DodoPayments.PermissionDeniedError = PermissionDeniedError;
12398
+ DodoPayments.UnprocessableEntityError = UnprocessableEntityError;
12399
+ DodoPayments.toFile = toFile;
12400
+ DodoPayments.CheckoutSessions = CheckoutSessions;
12401
+ DodoPayments.Payments = Payments;
12402
+ DodoPayments.Subscriptions = Subscriptions;
12403
+ DodoPayments.Invoices = Invoices;
12404
+ DodoPayments.Licenses = Licenses;
12405
+ DodoPayments.LicenseKeys = LicenseKeys;
12406
+ DodoPayments.LicenseKeyInstances = LicenseKeyInstances;
12407
+ DodoPayments.Customers = Customers;
12408
+ DodoPayments.Refunds = Refunds;
12409
+ DodoPayments.Disputes = Disputes;
12410
+ DodoPayments.Payouts = Payouts;
12411
+ DodoPayments.Products = Products;
12412
+ DodoPayments.Misc = Misc;
12413
+ DodoPayments.Discounts = Discounts;
12414
+ DodoPayments.Addons = Addons;
12415
+ DodoPayments.Brands = Brands;
12416
+ DodoPayments.Webhooks = Webhooks$1;
12417
+ DodoPayments.WebhookEvents = WebhookEvents;
12418
+ DodoPayments.UsageEvents = UsageEvents;
12419
+ DodoPayments.Meters = Meters;
12420
+
12421
+ // src/checkout/checkout.ts
12422
+ var checkoutQuerySchema = objectType({
12423
+ productId: stringType(),
12424
+ quantity: stringType().optional(),
12425
+ // Customer fields
12426
+ fullName: stringType().optional(),
12427
+ firstName: stringType().optional(),
12428
+ lastName: stringType().optional(),
12429
+ email: stringType().optional(),
12430
+ country: stringType().optional(),
12431
+ addressLine: stringType().optional(),
12432
+ city: stringType().optional(),
12433
+ state: stringType().optional(),
12434
+ zipCode: stringType().optional(),
12435
+ // Disable flags
12436
+ disableFullName: stringType().optional(),
12437
+ disableFirstName: stringType().optional(),
12438
+ disableLastName: stringType().optional(),
12439
+ disableEmail: stringType().optional(),
12440
+ disableCountry: stringType().optional(),
12441
+ disableAddressLine: stringType().optional(),
12442
+ disableCity: stringType().optional(),
12443
+ disableState: stringType().optional(),
12444
+ disableZipCode: stringType().optional(),
12445
+ // Advanced controls
12446
+ paymentCurrency: stringType().optional(),
12447
+ showCurrencySelector: stringType().optional(),
12448
+ paymentAmount: stringType().optional(),
12449
+ showDiscounts: stringType().optional()
12450
+ // Metadata (allow any key starting with metadata_)
12451
+ // We'll handle metadata separately in the handler
12452
+ }).catchall(unknownType());
12453
+ var dynamicCheckoutBodySchema = objectType({
12454
+ // For subscription
12455
+ product_id: stringType().optional(),
12456
+ quantity: numberType().optional(),
12457
+ // For one-time payment
12458
+ product_cart: arrayType(
12459
+ objectType({
12460
+ product_id: stringType(),
12461
+ quantity: numberType()
12462
+ })
12463
+ ).optional(),
12464
+ // Common fields
12465
+ billing: objectType({
12466
+ city: stringType(),
12467
+ country: stringType(),
12468
+ state: stringType(),
12469
+ street: stringType(),
12470
+ zipcode: stringType()
12471
+ }),
12472
+ customer: objectType({
12473
+ customer_id: stringType().optional(),
12474
+ email: stringType().optional(),
12475
+ name: stringType().optional()
12476
+ }),
12477
+ discount_id: stringType().optional(),
12478
+ addons: arrayType(
12479
+ objectType({
12480
+ addon_id: stringType(),
12481
+ quantity: numberType()
12482
+ })
12483
+ ).optional(),
12484
+ metadata: recordType(stringType(), stringType()).optional(),
12485
+ currency: stringType().optional()
12486
+ // Allow any additional fields (for future compatibility)
12487
+ }).catchall(unknownType());
12488
+ var checkoutSessionProductCartItemSchema = objectType({
12489
+ product_id: stringType().min(1, "Product ID is required"),
12490
+ quantity: numberType().int().positive("Quantity must be a positive integer"),
12491
+ addons: arrayType(
12492
+ objectType({
12493
+ addon_id: stringType(),
12494
+ quantity: numberType().int().nonnegative()
12495
+ })
12496
+ ).optional(),
12497
+ amount: numberType().int().nonnegative(
12498
+ "Amount must be a non-negative integer (for pay-what-you-want products)"
12499
+ ).optional()
12500
+ });
12501
+ var checkoutSessionCustomerSchema = unionType([
12502
+ objectType({
12503
+ email: stringType().email(),
12504
+ name: stringType().min(1).optional(),
12505
+ phone_number: stringType().optional()
12506
+ }),
12507
+ objectType({
12508
+ customer_id: stringType()
12509
+ })
12510
+ ]).optional();
12511
+ var checkoutSessionBillingAddressSchema = objectType({
12512
+ street: stringType().optional(),
12513
+ city: stringType().optional(),
12514
+ state: stringType().optional(),
12515
+ country: stringType().length(2, "Country must be a 2-letter ISO code"),
12516
+ zipcode: stringType().optional()
12517
+ }).optional();
12518
+ var paymentMethodTypeSchema = enumType([
12519
+ "credit",
12520
+ "debit",
12521
+ "upi_collect",
12522
+ "upi_intent",
12523
+ "apple_pay",
12524
+ "cashapp",
12525
+ "google_pay",
12526
+ "multibanco",
12527
+ "bancontact_card",
12528
+ "eps",
12529
+ "ideal",
12530
+ "przelewy24",
12531
+ "paypal",
12532
+ "affirm",
12533
+ "klarna",
12534
+ "sepa",
12535
+ "ach",
12536
+ "amazon_pay",
12537
+ "afterpay_clearpay"
12538
+ ]);
12539
+ var checkoutSessionCustomizationSchema = objectType({
12540
+ theme: enumType(["light", "dark", "system"]).optional(),
12541
+ show_order_details: booleanType().optional(),
12542
+ show_on_demand_tag: booleanType().optional(),
12543
+ force_language: stringType().optional()
12544
+ }).optional();
12545
+ var checkoutSessionFeatureFlagsSchema = objectType({
12546
+ allow_currency_selection: booleanType().optional(),
12547
+ allow_discount_code: booleanType().optional(),
12548
+ allow_phone_number_collection: booleanType().optional(),
12549
+ allow_tax_id: booleanType().optional(),
12550
+ always_create_new_customer: booleanType().optional()
12551
+ }).optional();
12552
+ var checkoutSessionOnDemandSchema = objectType({
12553
+ mandate_only: booleanType(),
12554
+ product_price: numberType().int().optional(),
12555
+ product_currency: stringType().length(3).optional(),
12556
+ product_description: stringType().optional(),
12557
+ adaptive_currency_fees_inclusive: booleanType().optional()
12558
+ }).optional();
12559
+ var checkoutSessionSubscriptionDataSchema = objectType({
12560
+ trial_period_days: numberType().int().nonnegative().optional(),
12561
+ on_demand: checkoutSessionOnDemandSchema
12562
+ }).optional();
12563
+ var checkoutSessionPayloadSchema = objectType({
12564
+ // Required fields
12565
+ product_cart: arrayType(checkoutSessionProductCartItemSchema).min(1, "At least one product is required"),
12566
+ // Optional fields
12567
+ customer: checkoutSessionCustomerSchema,
12568
+ billing_address: checkoutSessionBillingAddressSchema,
12569
+ return_url: stringType().url().optional(),
12570
+ allowed_payment_method_types: arrayType(paymentMethodTypeSchema).optional(),
12571
+ billing_currency: stringType().length(3, "Currency must be a 3-letter ISO code").optional(),
12572
+ show_saved_payment_methods: booleanType().optional(),
12573
+ confirm: booleanType().optional(),
12574
+ discount_code: stringType().optional(),
12575
+ metadata: recordType(stringType(), stringType()).optional(),
12576
+ customization: checkoutSessionCustomizationSchema,
12577
+ feature_flags: checkoutSessionFeatureFlagsSchema,
12578
+ subscription_data: checkoutSessionSubscriptionDataSchema,
12579
+ force_3ds: booleanType().optional()
12580
+ });
12581
+ var checkoutSessionResponseSchema = objectType({
12582
+ session_id: stringType().min(1, "Session ID is required"),
12583
+ checkout_url: stringType().url("Invalid checkout URL")
12584
+ });
12585
+ var createCheckoutSession = async (payload, config) => {
12586
+ const validation = checkoutSessionPayloadSchema.safeParse(payload);
12587
+ if (!validation.success) {
12588
+ throw new Error(
12589
+ `Invalid checkout session payload: ${validation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
12590
+ );
12591
+ }
12592
+ const dodopayments = new DodoPayments({
12593
+ bearerToken: config.bearerToken,
12594
+ environment: config.environment
12595
+ });
12596
+ try {
12597
+ const sdkPayload = {
12598
+ ...validation.data,
12599
+ ...validation.data.billing_address && {
12600
+ billing_address: {
12601
+ ...validation.data.billing_address,
12602
+ country: validation.data.billing_address.country
12603
+ }
12604
+ }
12605
+ };
12606
+ const session = await dodopayments.checkoutSessions.create(
12607
+ sdkPayload
12608
+ );
12609
+ const responseValidation = checkoutSessionResponseSchema.safeParse(session);
12610
+ if (!responseValidation.success) {
12611
+ throw new Error(
12612
+ `Invalid checkout session response from API: ${responseValidation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
12613
+ );
12614
+ }
12615
+ return responseValidation.data;
12616
+ } catch (error) {
12617
+ if (error instanceof Error) {
12618
+ console.error("Dodo Payments Checkout Session API Error:", {
12619
+ message: error.message,
12620
+ payload: validation.data,
12621
+ config: {
12622
+ environment: config.environment,
12623
+ hasBearerToken: !!config.bearerToken
12624
+ }
12625
+ });
12626
+ throw new Error(`Failed to create checkout session: ${error.message}`);
12627
+ }
12628
+ console.error("Unknown error creating checkout session:", error);
12629
+ throw new Error(
12630
+ "Failed to create checkout session due to an unknown error"
12631
+ );
12632
+ }
12633
+ };
12634
+ var buildCheckoutUrl = async ({
12635
+ queryParams,
12636
+ body,
12637
+ sessionPayload,
12638
+ returnUrl,
12639
+ bearerToken,
12640
+ environment,
12641
+ type = "static"
12642
+ }) => {
12643
+ if (type === "session") {
12644
+ if (!sessionPayload) {
12645
+ throw new Error("sessionPayload is required when type is 'session'");
12646
+ }
12647
+ const session = await createCheckoutSession(sessionPayload, {
12648
+ bearerToken,
12649
+ environment
12650
+ });
12651
+ return session.checkout_url;
12652
+ }
12653
+ const inputData = type === "dynamic" ? body : queryParams;
12654
+ let parseResult;
12655
+ if (type === "dynamic") {
12656
+ parseResult = dynamicCheckoutBodySchema.safeParse(inputData);
12657
+ } else {
12658
+ parseResult = checkoutQuerySchema.safeParse(inputData);
12659
+ }
12660
+ const { success, data, error } = parseResult;
12661
+ if (!success) {
12662
+ throw new Error(
12663
+ `Invalid ${type === "dynamic" ? "body" : "query parameters"}.
12664
+ ${error.message}`
12665
+ );
12666
+ }
12667
+ if (type !== "dynamic") {
12668
+ const {
12669
+ productId,
12670
+ quantity: quantity2,
12671
+ fullName,
12672
+ firstName,
12673
+ lastName,
12674
+ email,
12675
+ country,
12676
+ addressLine,
12677
+ city,
12678
+ state,
12679
+ zipCode,
12680
+ disableFullName,
12681
+ disableFirstName,
12682
+ disableLastName,
12683
+ disableEmail,
12684
+ disableCountry,
12685
+ disableAddressLine,
12686
+ disableCity,
12687
+ disableState,
12688
+ disableZipCode,
12689
+ paymentCurrency,
12690
+ showCurrencySelector,
12691
+ paymentAmount,
12692
+ showDiscounts
12693
+ // metadata handled below
12694
+ } = data;
12695
+ const dodopayments2 = new DodoPayments({
12696
+ bearerToken,
12697
+ environment
12698
+ });
12699
+ if (!productId) throw new Error("Missing required field: productId");
12700
+ try {
12701
+ await dodopayments2.products.retrieve(productId);
12702
+ } catch (err) {
12703
+ console.error(err);
12704
+ throw new Error("Product not found");
12705
+ }
12706
+ const url = new URL(
12707
+ `${environment === "test_mode" ? "https://test.checkout.dodopayments.com" : "https://checkout.dodopayments.com"}/buy/${productId}`
12708
+ );
12709
+ url.searchParams.set("quantity", quantity2 ? String(quantity2) : "1");
12710
+ if (returnUrl) url.searchParams.set("redirect_url", returnUrl);
12711
+ if (fullName) url.searchParams.set("fullName", String(fullName));
12712
+ if (firstName) url.searchParams.set("firstName", String(firstName));
12713
+ if (lastName) url.searchParams.set("lastName", String(lastName));
12714
+ if (email) url.searchParams.set("email", String(email));
12715
+ if (country) url.searchParams.set("country", String(country));
12716
+ if (addressLine) url.searchParams.set("addressLine", String(addressLine));
12717
+ if (city) url.searchParams.set("city", String(city));
12718
+ if (state) url.searchParams.set("state", String(state));
12719
+ if (zipCode) url.searchParams.set("zipCode", String(zipCode));
12720
+ if (disableFullName === "true")
12721
+ url.searchParams.set("disableFullName", "true");
12722
+ if (disableFirstName === "true")
12723
+ url.searchParams.set("disableFirstName", "true");
12724
+ if (disableLastName === "true")
12725
+ url.searchParams.set("disableLastName", "true");
12726
+ if (disableEmail === "true") url.searchParams.set("disableEmail", "true");
12727
+ if (disableCountry === "true")
12728
+ url.searchParams.set("disableCountry", "true");
12729
+ if (disableAddressLine === "true")
12730
+ url.searchParams.set("disableAddressLine", "true");
12731
+ if (disableCity === "true") url.searchParams.set("disableCity", "true");
12732
+ if (disableState === "true") url.searchParams.set("disableState", "true");
12733
+ if (disableZipCode === "true")
12734
+ url.searchParams.set("disableZipCode", "true");
12735
+ if (paymentCurrency)
12736
+ url.searchParams.set("paymentCurrency", String(paymentCurrency));
12737
+ if (showCurrencySelector)
12738
+ url.searchParams.set(
12739
+ "showCurrencySelector",
12740
+ String(showCurrencySelector)
12741
+ );
12742
+ if (paymentAmount)
12743
+ url.searchParams.set("paymentAmount", String(paymentAmount));
12744
+ if (showDiscounts)
12745
+ url.searchParams.set("showDiscounts", String(showDiscounts));
12746
+ for (const [key, value] of Object.entries(queryParams || {})) {
12747
+ if (key.startsWith("metadata_") && value && typeof value !== "object") {
12748
+ url.searchParams.set(key, String(value));
12749
+ }
12750
+ }
12751
+ return url.toString();
12752
+ }
12753
+ const dyn = data;
12754
+ const {
12755
+ product_id,
12756
+ product_cart,
12757
+ quantity,
12758
+ billing,
12759
+ customer,
12760
+ addons,
12761
+ metadata,
12762
+ allowed_payment_method_types,
12763
+ billing_currency,
12764
+ discount_code,
12765
+ on_demand,
12766
+ return_url: bodyReturnUrl,
12767
+ show_saved_payment_methods,
12768
+ tax_id,
12769
+ trial_period_days
12770
+ } = dyn;
12771
+ const dodopayments = new DodoPayments({
12772
+ bearerToken,
12773
+ environment
12774
+ });
12775
+ let isSubscription = false;
12776
+ let productIdToFetch = product_id;
12777
+ if (!product_id && product_cart && product_cart.length > 0) {
12778
+ productIdToFetch = product_cart[0].product_id;
12779
+ }
12780
+ if (!productIdToFetch)
12781
+ throw new Error(
12782
+ "Missing required field: product_id or product_cart[0].product_id"
12783
+ );
12784
+ let product;
12785
+ try {
12786
+ product = await dodopayments.products.retrieve(productIdToFetch);
12787
+ } catch (err) {
12788
+ console.error(err);
12789
+ throw new Error("Product not found");
12790
+ }
12791
+ isSubscription = Boolean(product.is_recurring);
12792
+ if (isSubscription && !product_id)
12793
+ throw new Error("Missing required field: product_id for subscription");
12794
+ if (!billing) throw new Error("Missing required field: billing");
12795
+ if (!customer) throw new Error("Missing required field: customer");
12796
+ if (isSubscription) {
12797
+ const subscriptionPayload = {
12798
+ billing,
12799
+ customer,
12800
+ product_id,
12801
+ quantity: quantity ? Number(quantity) : 1
12802
+ };
12803
+ if (metadata) subscriptionPayload.metadata = metadata;
12804
+ if (discount_code) subscriptionPayload.discount_code = discount_code;
12805
+ if (addons) subscriptionPayload.addons = addons;
12806
+ if (allowed_payment_method_types)
12807
+ subscriptionPayload.allowed_payment_method_types = allowed_payment_method_types;
12808
+ if (billing_currency)
12809
+ subscriptionPayload.billing_currency = billing_currency;
12810
+ if (on_demand) subscriptionPayload.on_demand = on_demand;
12811
+ subscriptionPayload.payment_link = true;
12812
+ if (bodyReturnUrl) {
12813
+ subscriptionPayload.return_url = bodyReturnUrl;
12814
+ } else if (returnUrl) {
12815
+ subscriptionPayload.return_url = returnUrl;
12785
12816
  }
12786
- }
12787
- class WebhookVerificationError extends ExtendableError {
12788
- constructor(message) {
12789
- super(message);
12790
- Object.setPrototypeOf(this, WebhookVerificationError.prototype);
12791
- this.name = "WebhookVerificationError";
12817
+ if (show_saved_payment_methods)
12818
+ subscriptionPayload.show_saved_payment_methods = show_saved_payment_methods;
12819
+ if (tax_id) subscriptionPayload.tax_id = tax_id;
12820
+ if (trial_period_days)
12821
+ subscriptionPayload.trial_period_days = trial_period_days;
12822
+ let subscription;
12823
+ try {
12824
+ subscription = await dodopayments.subscriptions.create(subscriptionPayload);
12825
+ } catch (err) {
12826
+ console.error("Error when creating subscription", err);
12827
+ throw new Error(err instanceof Error ? err.message : String(err));
12792
12828
  }
12793
- }
12794
- var WebhookVerificationError_1 = dist.WebhookVerificationError = WebhookVerificationError;
12795
- class Webhook {
12796
- constructor(secret, options) {
12797
- if (!secret) {
12798
- throw new Error("Secret can't be empty.");
12829
+ if (!subscription || !subscription.payment_link) {
12830
+ throw new Error(
12831
+ "No payment link returned from Dodo Payments API (subscription). Make sure to set payment_link as true in payload"
12832
+ );
12833
+ }
12834
+ return subscription.payment_link;
12835
+ } else {
12836
+ let cart = product_cart;
12837
+ if (!cart && product_id) {
12838
+ cart = [
12839
+ { product_id, quantity: quantity ? Number(quantity) : 1 }
12840
+ ];
12841
+ }
12842
+ if (!cart || cart.length === 0)
12843
+ throw new Error("Missing required field: product_cart or product_id");
12844
+ const paymentPayload = {
12845
+ billing,
12846
+ customer,
12847
+ product_cart: cart
12848
+ };
12849
+ if (metadata) paymentPayload.metadata = metadata;
12850
+ paymentPayload.payment_link = true;
12851
+ if (allowed_payment_method_types)
12852
+ paymentPayload.allowed_payment_method_types = allowed_payment_method_types;
12853
+ if (billing_currency) paymentPayload.billing_currency = billing_currency;
12854
+ if (discount_code) paymentPayload.discount_code = discount_code;
12855
+ if (bodyReturnUrl) {
12856
+ paymentPayload.return_url = bodyReturnUrl;
12857
+ } else if (returnUrl) {
12858
+ paymentPayload.return_url = returnUrl;
12859
+ }
12860
+ if (show_saved_payment_methods)
12861
+ paymentPayload.show_saved_payment_methods = show_saved_payment_methods;
12862
+ if (tax_id) paymentPayload.tax_id = tax_id;
12863
+ let payment;
12864
+ try {
12865
+ payment = await dodopayments.payments.create(paymentPayload);
12866
+ } catch (err) {
12867
+ console.error("Error when creating payment link", err);
12868
+ throw new Error(err instanceof Error ? err.message : String(err));
12869
+ }
12870
+ if (!payment || !payment.payment_link) {
12871
+ throw new Error(
12872
+ "No payment link returned from Dodo Payments API. Make sure to set payment_link as true in payload."
12873
+ );
12874
+ }
12875
+ return payment.payment_link;
12876
+ }
12877
+ };
12878
+
12879
+ const Checkout = (config) => {
12880
+ const getHandler = async (req) => {
12881
+ const { searchParams } = new URL(req.url);
12882
+ const queryParams = Object.fromEntries(searchParams);
12883
+ if (!queryParams.productId) {
12884
+ return new serverExports.NextResponse("Please provide productId query parameter", {
12885
+ status: 400,
12886
+ });
12799
12887
  }
12800
- if ((options === null || options === void 0 ? void 0 : options.format) === "raw") {
12801
- if (secret instanceof Uint8Array) {
12802
- this.key = secret;
12803
- }
12804
- else {
12805
- this.key = Uint8Array.from(secret, (c) => c.charCodeAt(0));
12888
+ const { success, data, error } = checkoutQuerySchema.safeParse(queryParams);
12889
+ if (!success) {
12890
+ if (error.errors.some((e) => e.path.toString() === "productId")) {
12891
+ return new serverExports.NextResponse("Please provide productId query parameter", {
12892
+ status: 400,
12893
+ });
12806
12894
  }
12895
+ return new serverExports.NextResponse(`Invalid query parameters.\n ${error.message}`, {
12896
+ status: 400,
12897
+ });
12807
12898
  }
12808
- else {
12809
- if (typeof secret !== "string") {
12810
- throw new Error("Expected secret to be of type string");
12811
- }
12812
- if (secret.startsWith(Webhook.prefix)) {
12813
- secret = secret.substring(Webhook.prefix.length);
12814
- }
12815
- this.key = base64.decode(secret);
12899
+ let url = "";
12900
+ try {
12901
+ url = await buildCheckoutUrl({ queryParams: data, ...config });
12816
12902
  }
12817
- }
12818
- verify(payload, headers_) {
12819
- const headers = {};
12820
- for (const key of Object.keys(headers_)) {
12821
- headers[key.toLowerCase()] = headers_[key];
12903
+ catch (error) {
12904
+ return new serverExports.NextResponse(error.message, { status: 400 });
12822
12905
  }
12823
- const msgId = headers["webhook-id"];
12824
- const msgSignature = headers["webhook-signature"];
12825
- const msgTimestamp = headers["webhook-timestamp"];
12826
- if (!msgSignature || !msgId || !msgTimestamp) {
12827
- throw new WebhookVerificationError("Missing required headers");
12906
+ return serverExports.NextResponse.json({ checkout_url: url });
12907
+ };
12908
+ const postHandler = async (req) => {
12909
+ let body;
12910
+ try {
12911
+ body = await req.json();
12828
12912
  }
12829
- const timestamp = this.verifyTimestamp(msgTimestamp);
12830
- const computedSignature = this.sign(msgId, timestamp, payload);
12831
- const expectedSignature = computedSignature.split(",")[1];
12832
- const passedSignatures = msgSignature.split(" ");
12833
- const encoder = new globalThis.TextEncoder();
12834
- for (const versionedSignature of passedSignatures) {
12835
- const [version, signature] = versionedSignature.split(",");
12836
- if (version !== "v1") {
12837
- continue;
12913
+ catch (e) {
12914
+ return new serverExports.NextResponse("Invalid JSON body", { status: 400 });
12915
+ }
12916
+ if (config.type === "dynamic") {
12917
+ // Handle dynamic checkout
12918
+ const { success, data, error } = dynamicCheckoutBodySchema.safeParse(body);
12919
+ if (!success) {
12920
+ return new serverExports.NextResponse(`Invalid request body.\n ${error.message}`, {
12921
+ status: 400,
12922
+ });
12838
12923
  }
12839
- if ((0, timing_safe_equal_1.timingSafeEqual)(encoder.encode(signature), encoder.encode(expectedSignature))) {
12840
- return JSON.parse(payload.toString());
12924
+ let url = "";
12925
+ try {
12926
+ url = await buildCheckoutUrl({
12927
+ body: data,
12928
+ ...config,
12929
+ type: "dynamic",
12930
+ });
12841
12931
  }
12842
- }
12843
- throw new WebhookVerificationError("No matching signature found");
12844
- }
12845
- sign(msgId, timestamp, payload) {
12846
- if (typeof payload === "string") ;
12847
- else if (payload.constructor.name === "Buffer") {
12848
- payload = payload.toString();
12932
+ catch (error) {
12933
+ return new serverExports.NextResponse(error.message, { status: 400 });
12934
+ }
12935
+ return serverExports.NextResponse.json({ checkout_url: url });
12849
12936
  }
12850
12937
  else {
12851
- throw new Error("Expected payload to be of type string or Buffer.");
12852
- }
12853
- const encoder = new TextEncoder();
12854
- const timestampNumber = Math.floor(timestamp.getTime() / 1000);
12855
- const toSign = encoder.encode(`${msgId}.${timestampNumber}.${payload}`);
12856
- const expectedSignature = base64.encode(sha256.hmac(this.key, toSign));
12857
- return `v1,${expectedSignature}`;
12858
- }
12859
- verifyTimestamp(timestampHeader) {
12860
- const now = Math.floor(Date.now() / 1000);
12861
- const timestamp = parseInt(timestampHeader, 10);
12862
- if (isNaN(timestamp)) {
12863
- throw new WebhookVerificationError("Invalid Signature Headers");
12864
- }
12865
- if (now - timestamp > WEBHOOK_TOLERANCE_IN_SECONDS) {
12866
- throw new WebhookVerificationError("Message timestamp too old");
12938
+ // Handle checkout session
12939
+ const { success, data, error } = checkoutSessionPayloadSchema.safeParse(body);
12940
+ if (!success) {
12941
+ return new serverExports.NextResponse(`Invalid checkout session payload.\n ${error.message}`, {
12942
+ status: 400,
12943
+ });
12944
+ }
12945
+ let url = "";
12946
+ try {
12947
+ url = await buildCheckoutUrl({
12948
+ sessionPayload: data,
12949
+ ...config,
12950
+ type: "session",
12951
+ });
12952
+ }
12953
+ catch (error) {
12954
+ return new serverExports.NextResponse(error.message, { status: 400 });
12955
+ }
12956
+ return serverExports.NextResponse.json({ checkout_url: url });
12867
12957
  }
12868
- if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) {
12869
- throw new WebhookVerificationError("Message timestamp too new");
12958
+ };
12959
+ return (req) => {
12960
+ if (req.method === "POST") {
12961
+ return postHandler(req);
12870
12962
  }
12871
- return new Date(timestamp * 1000);
12872
- }
12873
- }
12874
- Webhook_1 = dist.Webhook = Webhook;
12875
- Webhook.prefix = "whsec_";
12963
+ return getHandler(req);
12964
+ };
12965
+ };
12876
12966
 
12877
12967
  // src/schemas/webhook.ts
12878
12968
  var PaymentSchema = objectType({