@dodopayments/sveltekit 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -4055,7 +4055,7 @@ const unknownType = ZodUnknown.create;
4055
4055
  ZodNever.create;
4056
4056
  const arrayType = ZodArray.create;
4057
4057
  const objectType = ZodObject.create;
4058
- ZodUnion.create;
4058
+ const unionType = ZodUnion.create;
4059
4059
  const discriminatedUnionType = ZodDiscriminatedUnion.create;
4060
4060
  ZodIntersection.create;
4061
4061
  ZodTuple.create;
@@ -4274,7 +4274,7 @@ const safeJSON = (text) => {
4274
4274
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
4275
4275
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
4276
4276
 
4277
- const VERSION = '2.2.0'; // x-release-please-version
4277
+ const VERSION = '2.4.6'; // x-release-please-version
4278
4278
 
4279
4279
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
4280
4280
  /**
@@ -5024,6 +5024,9 @@ class CheckoutSessions extends APIResource {
5024
5024
  create(body, options) {
5025
5025
  return this._client.post('/checkouts', { body, ...options });
5026
5026
  }
5027
+ retrieve(id, options) {
5028
+ return this._client.get(path `/checkouts/${id}`, options);
5029
+ }
5027
5030
  }
5028
5031
 
5029
5032
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
@@ -5702,1489 +5705,325 @@ let Headers$1 = class Headers extends APIResource {
5702
5705
  }
5703
5706
  };
5704
5707
 
5705
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
5706
- let Webhooks$1 = class Webhooks extends APIResource {
5707
- constructor() {
5708
- super(...arguments);
5709
- this.headers = new Headers$1(this._client);
5710
- }
5711
- /**
5712
- * Create a new webhook
5713
- */
5714
- create(body, options) {
5715
- return this._client.post('/webhooks', { body, ...options });
5716
- }
5717
- /**
5718
- * Get a webhook by id
5719
- */
5720
- retrieve(webhookID, options) {
5721
- return this._client.get(path `/webhooks/${webhookID}`, options);
5708
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
5709
+
5710
+ var dist = {};
5711
+
5712
+ var timing_safe_equal = {};
5713
+
5714
+ Object.defineProperty(timing_safe_equal, "__esModule", { value: true });
5715
+ timing_safe_equal.timingSafeEqual = void 0;
5716
+ function assert(expr, msg = "") {
5717
+ if (!expr) {
5718
+ throw new Error(msg);
5722
5719
  }
5723
- /**
5724
- * Patch a webhook by id
5725
- */
5726
- update(webhookID, body, options) {
5727
- return this._client.patch(path `/webhooks/${webhookID}`, { body, ...options });
5720
+ }
5721
+ function timingSafeEqual(a, b) {
5722
+ if (a.byteLength !== b.byteLength) {
5723
+ return false;
5728
5724
  }
5729
- /**
5730
- * List all webhooks
5731
- */
5732
- list(query = {}, options) {
5733
- return this._client.getAPIList('/webhooks', (CursorPagePagination), { query, ...options });
5725
+ if (!(a instanceof DataView)) {
5726
+ a = new DataView(ArrayBuffer.isView(a) ? a.buffer : a);
5734
5727
  }
5735
- /**
5736
- * Delete a webhook by id
5737
- */
5738
- delete(webhookID, options) {
5739
- return this._client.delete(path `/webhooks/${webhookID}`, {
5740
- ...options,
5741
- headers: buildHeaders([{ Accept: '*/*' }, options?.headers]),
5742
- });
5728
+ if (!(b instanceof DataView)) {
5729
+ b = new DataView(ArrayBuffer.isView(b) ? b.buffer : b);
5743
5730
  }
5744
- /**
5745
- * Get webhook secret by id
5746
- */
5747
- retrieveSecret(webhookID, options) {
5748
- return this._client.get(path `/webhooks/${webhookID}/secret`, options);
5731
+ assert(a instanceof DataView);
5732
+ assert(b instanceof DataView);
5733
+ const length = a.byteLength;
5734
+ let out = 0;
5735
+ let i = -1;
5736
+ while (++i < length) {
5737
+ out |= a.getUint8(i) ^ b.getUint8(i);
5749
5738
  }
5750
- };
5751
- Webhooks$1.Headers = Headers$1;
5739
+ return out === 0;
5740
+ }
5741
+ timing_safe_equal.timingSafeEqual = timingSafeEqual;
5752
5742
 
5753
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
5743
+ var base64$1 = {};
5744
+
5745
+ // Copyright (C) 2016 Dmitry Chestnykh
5746
+ // MIT License. See LICENSE file for details.
5747
+ var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
5748
+ var extendStatics = function (d, b) {
5749
+ extendStatics = Object.setPrototypeOf ||
5750
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
5751
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
5752
+ return extendStatics(d, b);
5753
+ };
5754
+ return function (d, b) {
5755
+ extendStatics(d, b);
5756
+ function __() { this.constructor = d; }
5757
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5758
+ };
5759
+ })();
5760
+ Object.defineProperty(base64$1, "__esModule", { value: true });
5754
5761
  /**
5755
- * Read an environment variable.
5756
- *
5757
- * Trims beginning and trailing whitespace.
5758
- *
5759
- * Will return undefined if the environment variable doesn't exist or cannot be accessed.
5762
+ * Package base64 implements Base64 encoding and decoding.
5760
5763
  */
5761
- const readEnv = (env) => {
5762
- if (typeof globalThis.process !== 'undefined') {
5763
- return globalThis.process.env?.[env]?.trim() ?? undefined;
5764
- }
5765
- if (typeof globalThis.Deno !== 'undefined') {
5766
- return globalThis.Deno.env?.get?.(env)?.trim();
5767
- }
5768
- return undefined;
5769
- };
5770
-
5771
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
5772
- var _DodoPayments_instances, _a, _DodoPayments_encoder, _DodoPayments_baseURLOverridden;
5773
- const environments = {
5774
- live_mode: 'https://live.dodopayments.com',
5775
- test_mode: 'https://test.dodopayments.com',
5776
- };
5764
+ // Invalid character used in decoding to indicate
5765
+ // that the character to decode is out of range of
5766
+ // alphabet and cannot be decoded.
5767
+ var INVALID_BYTE = 256;
5777
5768
  /**
5778
- * API Client for interfacing with the Dodo Payments API.
5769
+ * Implements standard Base64 encoding.
5770
+ *
5771
+ * Operates in constant time.
5779
5772
  */
5780
- class DodoPayments {
5781
- /**
5782
- * API Client for interfacing with the Dodo Payments API.
5783
- *
5784
- * @param {string | undefined} [opts.bearerToken=process.env['DODO_PAYMENTS_API_KEY'] ?? undefined]
5785
- * @param {Environment} [opts.environment=live_mode] - Specifies the environment URL to use for the API.
5786
- * @param {string} [opts.baseURL=process.env['DODO_PAYMENTS_BASE_URL'] ?? https://live.dodopayments.com] - Override the default base URL for the API.
5787
- * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
5788
- * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
5789
- * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
5790
- * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
5791
- * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
5792
- * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
5793
- */
5794
- constructor({ baseURL = readEnv('DODO_PAYMENTS_BASE_URL'), bearerToken = readEnv('DODO_PAYMENTS_API_KEY'), ...opts } = {}) {
5795
- _DodoPayments_instances.add(this);
5796
- _DodoPayments_encoder.set(this, void 0);
5797
- this.checkoutSessions = new CheckoutSessions(this);
5798
- this.payments = new Payments(this);
5799
- this.subscriptions = new Subscriptions(this);
5800
- this.invoices = new Invoices(this);
5801
- this.licenses = new Licenses(this);
5802
- this.licenseKeys = new LicenseKeys(this);
5803
- this.licenseKeyInstances = new LicenseKeyInstances(this);
5804
- this.customers = new Customers(this);
5805
- this.refunds = new Refunds(this);
5806
- this.disputes = new Disputes(this);
5807
- this.payouts = new Payouts(this);
5808
- this.webhookEvents = new WebhookEvents(this);
5809
- this.products = new Products(this);
5810
- this.misc = new Misc(this);
5811
- this.discounts = new Discounts(this);
5812
- this.addons = new Addons(this);
5813
- this.brands = new Brands(this);
5814
- this.webhooks = new Webhooks$1(this);
5815
- this.usageEvents = new UsageEvents(this);
5816
- this.meters = new Meters(this);
5817
- if (bearerToken === undefined) {
5818
- 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' }).");
5773
+ var Coder = /** @class */ (function () {
5774
+ // TODO(dchest): methods to encode chunk-by-chunk.
5775
+ function Coder(_paddingCharacter) {
5776
+ if (_paddingCharacter === void 0) { _paddingCharacter = "="; }
5777
+ this._paddingCharacter = _paddingCharacter;
5778
+ }
5779
+ Coder.prototype.encodedLength = function (length) {
5780
+ if (!this._paddingCharacter) {
5781
+ return (length * 8 + 5) / 6 | 0;
5819
5782
  }
5820
- const options = {
5821
- bearerToken,
5822
- ...opts,
5823
- baseURL,
5824
- environment: opts.environment ?? 'live_mode',
5825
- };
5826
- if (baseURL && opts.environment) {
5827
- 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');
5783
+ return (length + 2) / 3 * 4 | 0;
5784
+ };
5785
+ Coder.prototype.encode = function (data) {
5786
+ var out = "";
5787
+ var i = 0;
5788
+ for (; i < data.length - 2; i += 3) {
5789
+ var c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);
5790
+ out += this._encodeByte((c >>> 3 * 6) & 63);
5791
+ out += this._encodeByte((c >>> 2 * 6) & 63);
5792
+ out += this._encodeByte((c >>> 1 * 6) & 63);
5793
+ out += this._encodeByte((c >>> 0 * 6) & 63);
5828
5794
  }
5829
- this.baseURL = options.baseURL || environments[options.environment || 'live_mode'];
5830
- this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 1 minute */;
5831
- this.logger = options.logger ?? console;
5832
- const defaultLogLevel = 'warn';
5833
- // Set default logLevel early so that we can log a warning in parseLogLevel.
5834
- this.logLevel = defaultLogLevel;
5835
- this.logLevel =
5836
- parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??
5837
- parseLogLevel(readEnv('DODO_PAYMENTS_LOG'), "process.env['DODO_PAYMENTS_LOG']", this) ??
5838
- defaultLogLevel;
5839
- this.fetchOptions = options.fetchOptions;
5840
- this.maxRetries = options.maxRetries ?? 2;
5841
- this.fetch = options.fetch ?? getDefaultFetch();
5842
- __classPrivateFieldSet(this, _DodoPayments_encoder, FallbackEncoder);
5843
- this._options = options;
5844
- this.bearerToken = bearerToken;
5845
- }
5846
- /**
5847
- * Create a new client instance re-using the same options given to the current client with optional overriding.
5848
- */
5849
- withOptions(options) {
5850
- const client = new this.constructor({
5851
- ...this._options,
5852
- environment: options.environment ? options.environment : undefined,
5853
- baseURL: options.environment ? undefined : this.baseURL,
5854
- maxRetries: this.maxRetries,
5855
- timeout: this.timeout,
5856
- logger: this.logger,
5857
- logLevel: this.logLevel,
5858
- fetch: this.fetch,
5859
- fetchOptions: this.fetchOptions,
5860
- bearerToken: this.bearerToken,
5861
- ...options,
5862
- });
5863
- return client;
5864
- }
5865
- defaultQuery() {
5866
- return this._options.defaultQuery;
5867
- }
5868
- validateHeaders({ values, nulls }) {
5869
- return;
5870
- }
5871
- async authHeaders(opts) {
5872
- return buildHeaders([{ Authorization: `Bearer ${this.bearerToken}` }]);
5873
- }
5874
- /**
5875
- * Basic re-implementation of `qs.stringify` for primitive types.
5876
- */
5877
- stringifyQuery(query) {
5878
- return Object.entries(query)
5879
- .filter(([_, value]) => typeof value !== 'undefined')
5880
- .map(([key, value]) => {
5881
- if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
5882
- return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
5795
+ var left = data.length - i;
5796
+ if (left > 0) {
5797
+ var c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0);
5798
+ out += this._encodeByte((c >>> 3 * 6) & 63);
5799
+ out += this._encodeByte((c >>> 2 * 6) & 63);
5800
+ if (left === 2) {
5801
+ out += this._encodeByte((c >>> 1 * 6) & 63);
5883
5802
  }
5884
- if (value === null) {
5885
- return `${encodeURIComponent(key)}=`;
5803
+ else {
5804
+ out += this._paddingCharacter || "";
5886
5805
  }
5887
- 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.`);
5888
- })
5889
- .join('&');
5890
- }
5891
- getUserAgent() {
5892
- return `${this.constructor.name}/JS ${VERSION}`;
5893
- }
5894
- defaultIdempotencyKey() {
5895
- return `stainless-node-retry-${uuid4()}`;
5896
- }
5897
- makeStatusError(status, error, message, headers) {
5898
- return APIError.generate(status, error, message, headers);
5899
- }
5900
- buildURL(path, query, defaultBaseURL) {
5901
- const baseURL = (!__classPrivateFieldGet(this, _DodoPayments_instances, "m", _DodoPayments_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;
5902
- const url = isAbsoluteURL(path) ?
5903
- new URL(path)
5904
- : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
5905
- const defaultQuery = this.defaultQuery();
5906
- if (!isEmptyObj(defaultQuery)) {
5907
- query = { ...defaultQuery, ...query };
5908
- }
5909
- if (typeof query === 'object' && query && !Array.isArray(query)) {
5910
- url.search = this.stringifyQuery(query);
5806
+ out += this._paddingCharacter || "";
5911
5807
  }
5912
- return url.toString();
5913
- }
5914
- /**
5915
- * Used as a callback for mutating the given `FinalRequestOptions` object.
5916
- */
5917
- async prepareOptions(options) { }
5918
- /**
5919
- * Used as a callback for mutating the given `RequestInit` object.
5920
- *
5921
- * This is useful for cases where you want to add certain headers based off of
5922
- * the request properties, e.g. `method` or `url`.
5923
- */
5924
- async prepareRequest(request, { url, options }) { }
5925
- get(path, opts) {
5926
- return this.methodRequest('get', path, opts);
5927
- }
5928
- post(path, opts) {
5929
- return this.methodRequest('post', path, opts);
5930
- }
5931
- patch(path, opts) {
5932
- return this.methodRequest('patch', path, opts);
5933
- }
5934
- put(path, opts) {
5935
- return this.methodRequest('put', path, opts);
5936
- }
5937
- delete(path, opts) {
5938
- return this.methodRequest('delete', path, opts);
5939
- }
5940
- methodRequest(method, path, opts) {
5941
- return this.request(Promise.resolve(opts).then((opts) => {
5942
- return { method, path, ...opts };
5943
- }));
5944
- }
5945
- request(options, remainingRetries = null) {
5946
- return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
5947
- }
5948
- async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
5949
- const options = await optionsInput;
5950
- const maxRetries = options.maxRetries ?? this.maxRetries;
5951
- if (retriesRemaining == null) {
5952
- retriesRemaining = maxRetries;
5808
+ return out;
5809
+ };
5810
+ Coder.prototype.maxDecodedLength = function (length) {
5811
+ if (!this._paddingCharacter) {
5812
+ return (length * 6 + 7) / 8 | 0;
5953
5813
  }
5954
- await this.prepareOptions(options);
5955
- const { req, url, timeout } = await this.buildRequest(options, {
5956
- retryCount: maxRetries - retriesRemaining,
5957
- });
5958
- await this.prepareRequest(req, { url, options });
5959
- /** Not an API request ID, just for correlating local log entries. */
5960
- const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
5961
- const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
5962
- const startTime = Date.now();
5963
- loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
5964
- retryOfRequestLogID,
5965
- method: options.method,
5966
- url,
5967
- options,
5968
- headers: req.headers,
5969
- }));
5970
- if (options.signal?.aborted) {
5971
- throw new APIUserAbortError();
5814
+ return length / 4 * 3 | 0;
5815
+ };
5816
+ Coder.prototype.decodedLength = function (s) {
5817
+ return this.maxDecodedLength(s.length - this._getPaddingLength(s));
5818
+ };
5819
+ Coder.prototype.decode = function (s) {
5820
+ if (s.length === 0) {
5821
+ return new Uint8Array(0);
5972
5822
  }
5973
- const controller = new AbortController();
5974
- const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
5975
- const headersTime = Date.now();
5976
- if (response instanceof globalThis.Error) {
5977
- const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
5978
- if (options.signal?.aborted) {
5979
- throw new APIUserAbortError();
5980
- }
5981
- // detect native connection timeout errors
5982
- // 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)"
5983
- // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
5984
- // others do not provide enough information to distinguish timeouts from other connection errors
5985
- const isTimeout = isAbortError(response) ||
5986
- /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
5987
- if (retriesRemaining) {
5988
- loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
5989
- loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({
5990
- retryOfRequestLogID,
5991
- url,
5992
- durationMs: headersTime - startTime,
5993
- message: response.message,
5994
- }));
5995
- return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
5996
- }
5997
- loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
5998
- loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({
5999
- retryOfRequestLogID,
6000
- url,
6001
- durationMs: headersTime - startTime,
6002
- message: response.message,
6003
- }));
6004
- if (isTimeout) {
6005
- throw new APIConnectionTimeoutError();
6006
- }
6007
- throw new APIConnectionError({ cause: response });
5823
+ var paddingLength = this._getPaddingLength(s);
5824
+ var length = s.length - paddingLength;
5825
+ var out = new Uint8Array(this.maxDecodedLength(length));
5826
+ var op = 0;
5827
+ var i = 0;
5828
+ var haveBad = 0;
5829
+ var v0 = 0, v1 = 0, v2 = 0, v3 = 0;
5830
+ for (; i < length - 4; i += 4) {
5831
+ v0 = this._decodeChar(s.charCodeAt(i + 0));
5832
+ v1 = this._decodeChar(s.charCodeAt(i + 1));
5833
+ v2 = this._decodeChar(s.charCodeAt(i + 2));
5834
+ v3 = this._decodeChar(s.charCodeAt(i + 3));
5835
+ out[op++] = (v0 << 2) | (v1 >>> 4);
5836
+ out[op++] = (v1 << 4) | (v2 >>> 2);
5837
+ out[op++] = (v2 << 6) | v3;
5838
+ haveBad |= v0 & INVALID_BYTE;
5839
+ haveBad |= v1 & INVALID_BYTE;
5840
+ haveBad |= v2 & INVALID_BYTE;
5841
+ haveBad |= v3 & INVALID_BYTE;
6008
5842
  }
6009
- const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
6010
- if (!response.ok) {
6011
- const shouldRetry = await this.shouldRetry(response);
6012
- if (retriesRemaining && shouldRetry) {
6013
- const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
6014
- // We don't need the body of this response.
6015
- await CancelReadableStream(response.body);
6016
- loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
6017
- loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
6018
- retryOfRequestLogID,
6019
- url: response.url,
6020
- status: response.status,
6021
- headers: response.headers,
6022
- durationMs: headersTime - startTime,
6023
- }));
6024
- return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
6025
- }
6026
- const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
6027
- loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
6028
- const errText = await response.text().catch((err) => castToError(err).message);
6029
- const errJSON = safeJSON(errText);
6030
- const errMessage = errJSON ? undefined : errText;
6031
- loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
6032
- retryOfRequestLogID,
6033
- url: response.url,
6034
- status: response.status,
6035
- headers: response.headers,
6036
- message: errMessage,
6037
- durationMs: Date.now() - startTime,
6038
- }));
6039
- const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
6040
- throw err;
5843
+ if (i < length - 1) {
5844
+ v0 = this._decodeChar(s.charCodeAt(i));
5845
+ v1 = this._decodeChar(s.charCodeAt(i + 1));
5846
+ out[op++] = (v0 << 2) | (v1 >>> 4);
5847
+ haveBad |= v0 & INVALID_BYTE;
5848
+ haveBad |= v1 & INVALID_BYTE;
6041
5849
  }
6042
- loggerFor(this).info(responseInfo);
6043
- loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
6044
- retryOfRequestLogID,
6045
- url: response.url,
6046
- status: response.status,
6047
- headers: response.headers,
6048
- durationMs: headersTime - startTime,
6049
- }));
6050
- return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
6051
- }
6052
- getAPIList(path, Page, opts) {
6053
- return this.requestAPIList(Page, { method: 'get', path, ...opts });
6054
- }
6055
- requestAPIList(Page, options) {
6056
- const request = this.makeRequest(options, null, undefined);
6057
- return new PagePromise(this, request, Page);
6058
- }
6059
- async fetchWithTimeout(url, init, ms, controller) {
6060
- const { signal, method, ...options } = init || {};
6061
- if (signal)
6062
- signal.addEventListener('abort', () => controller.abort());
6063
- const timeout = setTimeout(() => controller.abort(), ms);
6064
- const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
6065
- (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
6066
- const fetchOptions = {
6067
- signal: controller.signal,
6068
- ...(isReadableBody ? { duplex: 'half' } : {}),
6069
- method: 'GET',
6070
- ...options,
6071
- };
6072
- if (method) {
6073
- // Custom methods like 'patch' need to be uppercased
6074
- // See https://github.com/nodejs/undici/issues/2294
6075
- fetchOptions.method = method.toUpperCase();
5850
+ if (i < length - 2) {
5851
+ v2 = this._decodeChar(s.charCodeAt(i + 2));
5852
+ out[op++] = (v1 << 4) | (v2 >>> 2);
5853
+ haveBad |= v2 & INVALID_BYTE;
6076
5854
  }
6077
- try {
6078
- // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
6079
- return await this.fetch.call(undefined, url, fetchOptions);
5855
+ if (i < length - 3) {
5856
+ v3 = this._decodeChar(s.charCodeAt(i + 3));
5857
+ out[op++] = (v2 << 6) | v3;
5858
+ haveBad |= v3 & INVALID_BYTE;
6080
5859
  }
6081
- finally {
6082
- clearTimeout(timeout);
5860
+ if (haveBad !== 0) {
5861
+ throw new Error("Base64Coder: incorrect characters for decoding");
6083
5862
  }
6084
- }
6085
- async shouldRetry(response) {
6086
- // Note this is not a standard header.
6087
- const shouldRetryHeader = response.headers.get('x-should-retry');
6088
- // If the server explicitly says whether or not to retry, obey.
6089
- if (shouldRetryHeader === 'true')
6090
- return true;
6091
- if (shouldRetryHeader === 'false')
6092
- return false;
6093
- // Retry on request timeouts.
6094
- if (response.status === 408)
6095
- return true;
6096
- // Retry on lock timeouts.
6097
- if (response.status === 409)
6098
- return true;
6099
- // Retry on rate limits.
6100
- if (response.status === 429)
6101
- return true;
6102
- // Retry internal errors.
6103
- if (response.status >= 500)
6104
- return true;
6105
- return false;
6106
- }
6107
- async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
6108
- let timeoutMillis;
6109
- // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
6110
- const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
6111
- if (retryAfterMillisHeader) {
6112
- const timeoutMs = parseFloat(retryAfterMillisHeader);
6113
- if (!Number.isNaN(timeoutMs)) {
6114
- timeoutMillis = timeoutMs;
6115
- }
6116
- }
6117
- // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
6118
- const retryAfterHeader = responseHeaders?.get('retry-after');
6119
- if (retryAfterHeader && !timeoutMillis) {
6120
- const timeoutSeconds = parseFloat(retryAfterHeader);
6121
- if (!Number.isNaN(timeoutSeconds)) {
6122
- timeoutMillis = timeoutSeconds * 1000;
5863
+ return out;
5864
+ };
5865
+ // Standard encoding have the following encoded/decoded ranges,
5866
+ // which we need to convert between.
5867
+ //
5868
+ // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + /
5869
+ // Index: 0 - 25 26 - 51 52 - 61 62 63
5870
+ // ASCII: 65 - 90 97 - 122 48 - 57 43 47
5871
+ //
5872
+ // Encode 6 bits in b into a new character.
5873
+ Coder.prototype._encodeByte = function (b) {
5874
+ // Encoding uses constant time operations as follows:
5875
+ //
5876
+ // 1. Define comparison of A with B using (A - B) >>> 8:
5877
+ // if A > B, then result is positive integer
5878
+ // if A <= B, then result is 0
5879
+ //
5880
+ // 2. Define selection of C or 0 using bitwise AND: X & C:
5881
+ // if X == 0, then result is 0
5882
+ // if X != 0, then result is C
5883
+ //
5884
+ // 3. Start with the smallest comparison (b >= 0), which is always
5885
+ // true, so set the result to the starting ASCII value (65).
5886
+ //
5887
+ // 4. Continue comparing b to higher ASCII values, and selecting
5888
+ // zero if comparison isn't true, otherwise selecting a value
5889
+ // to add to result, which:
5890
+ //
5891
+ // a) undoes the previous addition
5892
+ // b) provides new value to add
5893
+ //
5894
+ var result = b;
5895
+ // b >= 0
5896
+ result += 65;
5897
+ // b > 25
5898
+ result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
5899
+ // b > 51
5900
+ result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
5901
+ // b > 61
5902
+ result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43);
5903
+ // b > 62
5904
+ result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47);
5905
+ return String.fromCharCode(result);
5906
+ };
5907
+ // Decode a character code into a byte.
5908
+ // Must return 256 if character is out of alphabet range.
5909
+ Coder.prototype._decodeChar = function (c) {
5910
+ // Decoding works similar to encoding: using the same comparison
5911
+ // function, but now it works on ranges: result is always incremented
5912
+ // by value, but this value becomes zero if the range is not
5913
+ // satisfied.
5914
+ //
5915
+ // Decoding starts with invalid value, 256, which is then
5916
+ // subtracted when the range is satisfied. If none of the ranges
5917
+ // apply, the function returns 256, which is then checked by
5918
+ // the caller to throw error.
5919
+ var result = INVALID_BYTE; // start with invalid character
5920
+ // c == 43 (c > 42 and c < 44)
5921
+ result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62);
5922
+ // c == 47 (c > 46 and c < 48)
5923
+ result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63);
5924
+ // c > 47 and c < 58
5925
+ result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
5926
+ // c > 64 and c < 91
5927
+ result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
5928
+ // c > 96 and c < 123
5929
+ result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
5930
+ return result;
5931
+ };
5932
+ Coder.prototype._getPaddingLength = function (s) {
5933
+ var paddingLength = 0;
5934
+ if (this._paddingCharacter) {
5935
+ for (var i = s.length - 1; i >= 0; i--) {
5936
+ if (s[i] !== this._paddingCharacter) {
5937
+ break;
5938
+ }
5939
+ paddingLength++;
6123
5940
  }
6124
- else {
6125
- timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
5941
+ if (s.length < 4 || paddingLength > 2) {
5942
+ throw new Error("Base64Coder: incorrect padding");
6126
5943
  }
6127
5944
  }
6128
- // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
6129
- // just do what it says, but otherwise calculate a default
6130
- if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
6131
- const maxRetries = options.maxRetries ?? this.maxRetries;
6132
- timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
6133
- }
6134
- await sleep(timeoutMillis);
6135
- return this.makeRequest(options, retriesRemaining - 1, requestLogID);
6136
- }
6137
- calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
6138
- const initialRetryDelay = 0.5;
6139
- const maxRetryDelay = 8.0;
6140
- const numRetries = maxRetries - retriesRemaining;
6141
- // Apply exponential backoff, but not more than the max.
6142
- const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
6143
- // Apply some jitter, take up to at most 25 percent of the retry time.
6144
- const jitter = 1 - Math.random() * 0.25;
6145
- return sleepSeconds * jitter * 1000;
6146
- }
6147
- async buildRequest(inputOptions, { retryCount = 0 } = {}) {
6148
- const options = { ...inputOptions };
6149
- const { method, path, query, defaultBaseURL } = options;
6150
- const url = this.buildURL(path, query, defaultBaseURL);
6151
- if ('timeout' in options)
6152
- validatePositiveInteger('timeout', options.timeout);
6153
- options.timeout = options.timeout ?? this.timeout;
6154
- const { bodyHeaders, body } = this.buildBody({ options });
6155
- const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
6156
- const req = {
6157
- method,
6158
- headers: reqHeaders,
6159
- ...(options.signal && { signal: options.signal }),
6160
- ...(globalThis.ReadableStream &&
6161
- body instanceof globalThis.ReadableStream && { duplex: 'half' }),
6162
- ...(body && { body }),
6163
- ...(this.fetchOptions ?? {}),
6164
- ...(options.fetchOptions ?? {}),
6165
- };
6166
- return { req, url, timeout: options.timeout };
6167
- }
6168
- async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
6169
- let idempotencyHeaders = {};
6170
- if (this.idempotencyHeader && method !== 'get') {
6171
- if (!options.idempotencyKey)
6172
- options.idempotencyKey = this.defaultIdempotencyKey();
6173
- idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
6174
- }
6175
- const headers = buildHeaders([
6176
- idempotencyHeaders,
6177
- {
6178
- Accept: 'application/json',
6179
- 'User-Agent': this.getUserAgent(),
6180
- 'X-Stainless-Retry-Count': String(retryCount),
6181
- ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
6182
- ...getPlatformHeaders(),
6183
- },
6184
- await this.authHeaders(options),
6185
- this._options.defaultHeaders,
6186
- bodyHeaders,
6187
- options.headers,
6188
- ]);
6189
- this.validateHeaders(headers);
6190
- return headers.values;
6191
- }
6192
- buildBody({ options: { body, headers: rawHeaders } }) {
6193
- if (!body) {
6194
- return { bodyHeaders: undefined, body: undefined };
6195
- }
6196
- const headers = buildHeaders([rawHeaders]);
6197
- if (
6198
- // Pass raw type verbatim
6199
- ArrayBuffer.isView(body) ||
6200
- body instanceof ArrayBuffer ||
6201
- body instanceof DataView ||
6202
- (typeof body === 'string' &&
6203
- // Preserve legacy string encoding behavior for now
6204
- headers.values.has('content-type')) ||
6205
- // `Blob` is superset of `File`
6206
- (globalThis.Blob && body instanceof globalThis.Blob) ||
6207
- // `FormData` -> `multipart/form-data`
6208
- body instanceof FormData ||
6209
- // `URLSearchParams` -> `application/x-www-form-urlencoded`
6210
- body instanceof URLSearchParams ||
6211
- // Send chunked stream (each chunk has own `length`)
6212
- (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
6213
- return { bodyHeaders: undefined, body: body };
6214
- }
6215
- else if (typeof body === 'object' &&
6216
- (Symbol.asyncIterator in body ||
6217
- (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
6218
- return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
6219
- }
6220
- else {
6221
- return __classPrivateFieldGet(this, _DodoPayments_encoder, "f").call(this, { body, headers });
6222
- }
6223
- }
6224
- }
6225
- _a = DodoPayments, _DodoPayments_encoder = new WeakMap(), _DodoPayments_instances = new WeakSet(), _DodoPayments_baseURLOverridden = function _DodoPayments_baseURLOverridden() {
6226
- return this.baseURL !== environments[this._options.environment || 'live_mode'];
6227
- };
6228
- DodoPayments.DodoPayments = _a;
6229
- DodoPayments.DEFAULT_TIMEOUT = 60000; // 1 minute
6230
- DodoPayments.DodoPaymentsError = DodoPaymentsError;
6231
- DodoPayments.APIError = APIError;
6232
- DodoPayments.APIConnectionError = APIConnectionError;
6233
- DodoPayments.APIConnectionTimeoutError = APIConnectionTimeoutError;
6234
- DodoPayments.APIUserAbortError = APIUserAbortError;
6235
- DodoPayments.NotFoundError = NotFoundError;
6236
- DodoPayments.ConflictError = ConflictError;
6237
- DodoPayments.RateLimitError = RateLimitError;
6238
- DodoPayments.BadRequestError = BadRequestError;
6239
- DodoPayments.AuthenticationError = AuthenticationError;
6240
- DodoPayments.InternalServerError = InternalServerError;
6241
- DodoPayments.PermissionDeniedError = PermissionDeniedError;
6242
- DodoPayments.UnprocessableEntityError = UnprocessableEntityError;
6243
- DodoPayments.toFile = toFile;
6244
- DodoPayments.CheckoutSessions = CheckoutSessions;
6245
- DodoPayments.Payments = Payments;
6246
- DodoPayments.Subscriptions = Subscriptions;
6247
- DodoPayments.Invoices = Invoices;
6248
- DodoPayments.Licenses = Licenses;
6249
- DodoPayments.LicenseKeys = LicenseKeys;
6250
- DodoPayments.LicenseKeyInstances = LicenseKeyInstances;
6251
- DodoPayments.Customers = Customers;
6252
- DodoPayments.Refunds = Refunds;
6253
- DodoPayments.Disputes = Disputes;
6254
- DodoPayments.Payouts = Payouts;
6255
- DodoPayments.WebhookEvents = WebhookEvents;
6256
- DodoPayments.Products = Products;
6257
- DodoPayments.Misc = Misc;
6258
- DodoPayments.Discounts = Discounts;
6259
- DodoPayments.Addons = Addons;
6260
- DodoPayments.Brands = Brands;
6261
- DodoPayments.Webhooks = Webhooks$1;
6262
- DodoPayments.UsageEvents = UsageEvents;
6263
- DodoPayments.Meters = Meters;
6264
-
6265
- var __assign = (undefined && undefined.__assign) || function () {
6266
- __assign = Object.assign || function(t) {
6267
- for (var s, i = 1, n = arguments.length; i < n; i++) {
6268
- s = arguments[i];
6269
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
6270
- t[p] = s[p];
6271
- }
6272
- return t;
5945
+ return paddingLength;
6273
5946
  };
6274
- return __assign.apply(this, arguments);
6275
- };
6276
- var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
6277
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
6278
- return new (P || (P = Promise))(function (resolve, reject) {
6279
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6280
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6281
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
6282
- step((generator = generator.apply(thisArg, _arguments || [])).next());
6283
- });
6284
- };
6285
- var __generator$1 = (undefined && undefined.__generator) || function (thisArg, body) {
6286
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
6287
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
6288
- function verb(n) { return function (v) { return step([n, v]); }; }
6289
- function step(op) {
6290
- if (f) throw new TypeError("Generator is already executing.");
6291
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
6292
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
6293
- if (y = 0, t) op = [op[0] & 2, t.value];
6294
- switch (op[0]) {
6295
- case 0: case 1: t = op; break;
6296
- case 4: _.label++; return { value: op[1], done: false };
6297
- case 5: _.label++; y = op[1]; op = [0]; continue;
6298
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
6299
- default:
6300
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
6301
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
6302
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
6303
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
6304
- if (t[2]) _.ops.pop();
6305
- _.trys.pop(); continue;
6306
- }
6307
- op = body.call(thisArg, _);
6308
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
6309
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
6310
- }
6311
- };
6312
- var checkoutQuerySchema = objectType({
6313
- productId: stringType(),
6314
- quantity: stringType().optional(),
6315
- // Customer fields
6316
- fullName: stringType().optional(),
6317
- firstName: stringType().optional(),
6318
- lastName: stringType().optional(),
6319
- email: stringType().optional(),
6320
- country: stringType().optional(),
6321
- addressLine: stringType().optional(),
6322
- city: stringType().optional(),
6323
- state: stringType().optional(),
6324
- zipCode: stringType().optional(),
6325
- // Disable flags
6326
- disableFullName: stringType().optional(),
6327
- disableFirstName: stringType().optional(),
6328
- disableLastName: stringType().optional(),
6329
- disableEmail: stringType().optional(),
6330
- disableCountry: stringType().optional(),
6331
- disableAddressLine: stringType().optional(),
6332
- disableCity: stringType().optional(),
6333
- disableState: stringType().optional(),
6334
- disableZipCode: stringType().optional(),
6335
- // Advanced controls
6336
- paymentCurrency: stringType().optional(),
6337
- showCurrencySelector: stringType().optional(),
6338
- paymentAmount: stringType().optional(),
6339
- showDiscounts: stringType().optional(),
6340
- // Metadata (allow any key starting with metadata_)
6341
- // We'll handle metadata separately in the handler
6342
- })
6343
- .catchall(unknownType());
6344
- // Add Zod schema for dynamic checkout body
6345
- var dynamicCheckoutBodySchema = objectType({
6346
- // For subscription
6347
- product_id: stringType().optional(),
6348
- quantity: numberType().optional(),
6349
- // For one-time payment
6350
- product_cart: arrayType(objectType({
6351
- product_id: stringType(),
6352
- quantity: numberType(),
6353
- }))
6354
- .optional(),
6355
- // Common fields
6356
- billing: objectType({
6357
- city: stringType(),
6358
- country: stringType(),
6359
- state: stringType(),
6360
- street: stringType(),
6361
- zipcode: stringType(),
6362
- }),
6363
- customer: objectType({
6364
- customer_id: stringType().optional(),
6365
- email: stringType().optional(),
6366
- name: stringType().optional(),
6367
- }),
6368
- discount_id: stringType().optional(),
6369
- addons: arrayType(objectType({
6370
- addon_id: stringType(),
6371
- quantity: numberType(),
6372
- }))
6373
- .optional(),
6374
- metadata: recordType(stringType(), stringType()).optional(),
6375
- currency: stringType().optional(),
6376
- // Allow any additional fields (for future compatibility)
6377
- })
6378
- .catchall(unknownType());
6379
- // ========================================
6380
- // CHECKOUT SESSIONS SCHEMAS & TYPES
6381
- // ========================================
6382
- // Product cart item schema for checkout sessions
6383
- var checkoutSessionProductCartItemSchema = objectType({
6384
- product_id: stringType().min(1, "Product ID is required"),
6385
- quantity: numberType().int().positive("Quantity must be a positive integer"),
6386
- });
6387
- // Customer information schema for checkout sessions
6388
- var checkoutSessionCustomerSchema = objectType({
6389
- email: stringType().email().optional(),
6390
- name: stringType().min(1).optional(),
6391
- phone_number: stringType().optional(),
6392
- })
6393
- .optional();
6394
- // Billing address schema for checkout sessions
6395
- var checkoutSessionBillingAddressSchema = objectType({
6396
- street: stringType().optional(),
6397
- city: stringType().optional(),
6398
- state: stringType().optional(),
6399
- country: stringType().length(2, "Country must be a 2-letter ISO code"),
6400
- zipcode: stringType().optional(),
6401
- })
6402
- .optional();
6403
- // Payment method types enum based on Dodo Payments documentation
6404
- var paymentMethodTypeSchema = enumType([
6405
- "credit",
6406
- "debit",
6407
- "upi_collect",
6408
- "upi_intent",
6409
- "apple_pay",
6410
- "google_pay",
6411
- "amazon_pay",
6412
- "klarna",
6413
- "affirm",
6414
- "afterpay_clearpay",
6415
- "sepa",
6416
- "ach",
6417
- ]);
6418
- // Customization options schema
6419
- var checkoutSessionCustomizationSchema = objectType({
6420
- theme: enumType(["light", "dark", "system"]).optional(),
6421
- show_order_details: booleanType().optional(),
6422
- show_on_demand_tag: booleanType().optional(),
6423
- })
6424
- .optional();
6425
- // Feature flags schema
6426
- var checkoutSessionFeatureFlagsSchema = objectType({
6427
- allow_currency_selection: booleanType().optional(),
6428
- allow_discount_code: booleanType().optional(),
6429
- allow_phone_number_collection: booleanType().optional(),
6430
- allow_tax_id: booleanType().optional(),
6431
- always_create_new_customer: booleanType().optional(),
6432
- })
6433
- .optional();
6434
- // Subscription data schema
6435
- var checkoutSessionSubscriptionDataSchema = objectType({
6436
- trial_period_days: numberType().int().nonnegative().optional(),
6437
- })
6438
- .optional();
6439
- // Main checkout session payload schema
6440
- var checkoutSessionPayloadSchema = objectType({
6441
- // Required fields
6442
- product_cart: arrayType(checkoutSessionProductCartItemSchema)
6443
- .min(1, "At least one product is required"),
6444
- // Optional fields
6445
- customer: checkoutSessionCustomerSchema,
6446
- billing_address: checkoutSessionBillingAddressSchema,
6447
- return_url: stringType().url().optional(),
6448
- allowed_payment_method_types: arrayType(paymentMethodTypeSchema).optional(),
6449
- billing_currency: stringType()
6450
- .length(3, "Currency must be a 3-letter ISO code")
6451
- .optional(),
6452
- show_saved_payment_methods: booleanType().optional(),
6453
- confirm: booleanType().optional(),
6454
- discount_code: stringType().optional(),
6455
- metadata: recordType(stringType(), stringType()).optional(),
6456
- customization: checkoutSessionCustomizationSchema,
6457
- feature_flags: checkoutSessionFeatureFlagsSchema,
6458
- subscription_data: checkoutSessionSubscriptionDataSchema,
6459
- });
6460
- // Checkout session response schema
6461
- var checkoutSessionResponseSchema = objectType({
6462
- session_id: stringType().min(1, "Session ID is required"),
6463
- checkout_url: stringType().url("Invalid checkout URL"),
6464
- });
5947
+ return Coder;
5948
+ }());
5949
+ base64$1.Coder = Coder;
5950
+ var stdCoder = new Coder();
5951
+ function encode(data) {
5952
+ return stdCoder.encode(data);
5953
+ }
5954
+ base64$1.encode = encode;
5955
+ function decode(s) {
5956
+ return stdCoder.decode(s);
5957
+ }
5958
+ base64$1.decode = decode;
6465
5959
  /**
6466
- * Creates a new Dodo Payments Checkout Session using the modern /checkouts endpoint.
6467
- * This function provides a clean, type-safe interface to the Checkout Sessions API.
6468
- *
6469
- * @param payload - The checkout session data, validated against CheckoutSessionPayloadSchema
6470
- * @param config - Dodo Payments client configuration (bearerToken, environment)
6471
- * @returns Promise<CheckoutSessionResponse> - The checkout session with session_id and checkout_url
6472
- *
6473
- * @throws {Error} When payload validation fails or API request fails
6474
- *
6475
- * @example
6476
- * ```typescript
6477
- * const session = await createCheckoutSession({
6478
- * product_cart: [{ product_id: 'prod_123', quantity: 1 }],
6479
- * customer: { email: 'customer@example.com' },
6480
- * return_url: 'https://yoursite.com/success'
6481
- * }, {
6482
- * bearerToken: process.env.DODO_PAYMENTS_API_KEY,
6483
- * environment: 'test_mode'
6484
- * });
5960
+ * Implements URL-safe Base64 encoding.
5961
+ * (Same as Base64, but '+' is replaced with '-', and '/' with '_').
6485
5962
  *
6486
- * ```
5963
+ * Operates in constant time.
6487
5964
  */
6488
- var createCheckoutSession = function (payload, config) { return __awaiter$1(void 0, void 0, void 0, function () {
6489
- var validation, dodopayments, sdkPayload, session, responseValidation, error_1;
6490
- return __generator$1(this, function (_a) {
6491
- switch (_a.label) {
6492
- case 0:
6493
- validation = checkoutSessionPayloadSchema.safeParse(payload);
6494
- if (!validation.success) {
6495
- throw new Error("Invalid checkout session payload: ".concat(validation.error.issues
6496
- .map(function (issue) { return "".concat(issue.path.join("."), ": ").concat(issue.message); })
6497
- .join(", ")));
6498
- }
6499
- dodopayments = new DodoPayments({
6500
- bearerToken: config.bearerToken,
6501
- environment: config.environment,
6502
- });
6503
- _a.label = 1;
6504
- case 1:
6505
- _a.trys.push([1, 3, , 4]);
6506
- sdkPayload = __assign(__assign({}, validation.data), (validation.data.billing_address && {
6507
- billing_address: __assign(__assign({}, validation.data.billing_address), { country: validation.data.billing_address.country }),
6508
- }));
6509
- return [4 /*yield*/, dodopayments.checkoutSessions.create(sdkPayload)];
6510
- case 2:
6511
- session = _a.sent();
6512
- responseValidation = checkoutSessionResponseSchema.safeParse(session);
6513
- if (!responseValidation.success) {
6514
- throw new Error("Invalid checkout session response from API: ".concat(responseValidation.error.issues
6515
- .map(function (issue) { return "".concat(issue.path.join("."), ": ").concat(issue.message); })
6516
- .join(", ")));
6517
- }
6518
- return [2 /*return*/, responseValidation.data];
6519
- case 3:
6520
- error_1 = _a.sent();
6521
- if (error_1 instanceof Error) {
6522
- console.error("Dodo Payments Checkout Session API Error:", {
6523
- message: error_1.message,
6524
- payload: validation.data,
6525
- config: {
6526
- environment: config.environment,
6527
- hasBearerToken: !!config.bearerToken,
6528
- },
6529
- });
6530
- // Re-throw with a more user-friendly message
6531
- throw new Error("Failed to create checkout session: ".concat(error_1.message));
6532
- }
6533
- // Handle non-Error objects
6534
- console.error("Unknown error creating checkout session:", error_1);
6535
- throw new Error("Failed to create checkout session due to an unknown error");
6536
- case 4: return [2 /*return*/];
6537
- }
6538
- });
6539
- }); };
6540
- var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0, function (_b) {
6541
- var session, inputData, parseResult, success, data, error, _c, productId, quantity_1, fullName, firstName, lastName, email, country, addressLine, city, state, zipCode, disableFullName, disableFirstName, disableLastName, disableEmail, disableCountry, disableAddressLine, disableCity, disableState, disableZipCode, paymentCurrency, showCurrencySelector, paymentAmount, showDiscounts, dodopayments_1, err_1, url, _i, _d, _e, key, value, dyn, product_id, product_cart, quantity, billing, customer, addons, metadata, allowed_payment_method_types, billing_currency, discount_code, on_demand, bodyReturnUrl, show_saved_payment_methods, tax_id, trial_period_days, dodopayments, isSubscription, productIdToFetch, product, err_2, subscriptionPayload, subscription, err_3, cart, paymentPayload, payment, err_4;
6542
- var queryParams = _b.queryParams, body = _b.body, sessionPayload = _b.sessionPayload, returnUrl = _b.returnUrl, bearerToken = _b.bearerToken, environment = _b.environment, _f = _b.type, type = _f === void 0 ? "static" : _f;
6543
- return __generator$1(this, function (_g) {
6544
- switch (_g.label) {
6545
- case 0:
6546
- if (!(type === "session")) return [3 /*break*/, 2];
6547
- if (!sessionPayload) {
6548
- throw new Error("sessionPayload is required when type is 'session'");
6549
- }
6550
- return [4 /*yield*/, createCheckoutSession(sessionPayload, {
6551
- bearerToken: bearerToken,
6552
- environment: environment,
6553
- })];
6554
- case 1:
6555
- session = _g.sent();
6556
- return [2 /*return*/, session.checkout_url];
6557
- case 2:
6558
- inputData = type === "dynamic" ? body : queryParams;
6559
- if (type === "dynamic") {
6560
- parseResult = dynamicCheckoutBodySchema.safeParse(inputData);
6561
- }
6562
- else {
6563
- parseResult = checkoutQuerySchema.safeParse(inputData);
6564
- }
6565
- success = parseResult.success, data = parseResult.data, error = parseResult.error;
6566
- if (!success) {
6567
- throw new Error("Invalid ".concat(type === "dynamic" ? "body" : "query parameters", ".\n ").concat(error.message));
6568
- }
6569
- if (!(type !== "dynamic")) return [3 /*break*/, 7];
6570
- _c = data, productId = _c.productId, quantity_1 = _c.quantity, fullName = _c.fullName, firstName = _c.firstName, lastName = _c.lastName, email = _c.email, country = _c.country, addressLine = _c.addressLine, city = _c.city, state = _c.state, zipCode = _c.zipCode, disableFullName = _c.disableFullName, disableFirstName = _c.disableFirstName, disableLastName = _c.disableLastName, disableEmail = _c.disableEmail, disableCountry = _c.disableCountry, disableAddressLine = _c.disableAddressLine, disableCity = _c.disableCity, disableState = _c.disableState, disableZipCode = _c.disableZipCode, paymentCurrency = _c.paymentCurrency, showCurrencySelector = _c.showCurrencySelector, paymentAmount = _c.paymentAmount, showDiscounts = _c.showDiscounts;
6571
- dodopayments_1 = new DodoPayments({
6572
- bearerToken: bearerToken,
6573
- environment: environment,
6574
- });
6575
- // Check that the product exists for this merchant
6576
- if (!productId)
6577
- throw new Error("Missing required field: productId");
6578
- _g.label = 3;
6579
- case 3:
6580
- _g.trys.push([3, 5, , 6]);
6581
- return [4 /*yield*/, dodopayments_1.products.retrieve(productId)];
6582
- case 4:
6583
- _g.sent();
6584
- return [3 /*break*/, 6];
6585
- case 5:
6586
- err_1 = _g.sent();
6587
- console.error(err_1);
6588
- throw new Error("Product not found");
6589
- case 6:
6590
- url = new URL("".concat(environment === "test_mode" ? "https://test.checkout.dodopayments.com" : "https://checkout.dodopayments.com", "/buy/").concat(productId));
6591
- url.searchParams.set("quantity", quantity_1 ? String(quantity_1) : "1");
6592
- if (returnUrl)
6593
- url.searchParams.set("redirect_url", returnUrl);
6594
- // Customer/billing fields
6595
- if (fullName)
6596
- url.searchParams.set("fullName", String(fullName));
6597
- if (firstName)
6598
- url.searchParams.set("firstName", String(firstName));
6599
- if (lastName)
6600
- url.searchParams.set("lastName", String(lastName));
6601
- if (email)
6602
- url.searchParams.set("email", String(email));
6603
- if (country)
6604
- url.searchParams.set("country", String(country));
6605
- if (addressLine)
6606
- url.searchParams.set("addressLine", String(addressLine));
6607
- if (city)
6608
- url.searchParams.set("city", String(city));
6609
- if (state)
6610
- url.searchParams.set("state", String(state));
6611
- if (zipCode)
6612
- url.searchParams.set("zipCode", String(zipCode));
6613
- // Disable flags (must be set to 'true' to disable)
6614
- if (disableFullName === "true")
6615
- url.searchParams.set("disableFullName", "true");
6616
- if (disableFirstName === "true")
6617
- url.searchParams.set("disableFirstName", "true");
6618
- if (disableLastName === "true")
6619
- url.searchParams.set("disableLastName", "true");
6620
- if (disableEmail === "true")
6621
- url.searchParams.set("disableEmail", "true");
6622
- if (disableCountry === "true")
6623
- url.searchParams.set("disableCountry", "true");
6624
- if (disableAddressLine === "true")
6625
- url.searchParams.set("disableAddressLine", "true");
6626
- if (disableCity === "true")
6627
- url.searchParams.set("disableCity", "true");
6628
- if (disableState === "true")
6629
- url.searchParams.set("disableState", "true");
6630
- if (disableZipCode === "true")
6631
- url.searchParams.set("disableZipCode", "true");
6632
- // Advanced controls
6633
- if (paymentCurrency)
6634
- url.searchParams.set("paymentCurrency", String(paymentCurrency));
6635
- if (showCurrencySelector)
6636
- url.searchParams.set("showCurrencySelector", String(showCurrencySelector));
6637
- if (paymentAmount)
6638
- url.searchParams.set("paymentAmount", String(paymentAmount));
6639
- if (showDiscounts)
6640
- url.searchParams.set("showDiscounts", String(showDiscounts));
6641
- // Metadata: add all query params starting with metadata_
6642
- for (_i = 0, _d = Object.entries(queryParams || {}); _i < _d.length; _i++) {
6643
- _e = _d[_i], key = _e[0], value = _e[1];
6644
- if (key.startsWith("metadata_") && value && typeof value !== "object") {
6645
- url.searchParams.set(key, String(value));
6646
- }
6647
- }
6648
- return [2 /*return*/, url.toString()];
6649
- case 7:
6650
- dyn = data;
6651
- product_id = dyn.product_id, product_cart = dyn.product_cart, quantity = dyn.quantity, billing = dyn.billing, customer = dyn.customer, addons = dyn.addons, metadata = dyn.metadata, allowed_payment_method_types = dyn.allowed_payment_method_types, billing_currency = dyn.billing_currency, discount_code = dyn.discount_code, on_demand = dyn.on_demand, bodyReturnUrl = dyn.return_url, show_saved_payment_methods = dyn.show_saved_payment_methods, tax_id = dyn.tax_id, trial_period_days = dyn.trial_period_days;
6652
- dodopayments = new DodoPayments({
6653
- bearerToken: bearerToken,
6654
- environment: environment,
6655
- });
6656
- isSubscription = false;
6657
- productIdToFetch = product_id;
6658
- if (!product_id && product_cart && product_cart.length > 0) {
6659
- productIdToFetch = product_cart[0].product_id;
6660
- }
6661
- if (!productIdToFetch)
6662
- throw new Error("Missing required field: product_id or product_cart[0].product_id");
6663
- _g.label = 8;
6664
- case 8:
6665
- _g.trys.push([8, 10, , 11]);
6666
- return [4 /*yield*/, dodopayments.products.retrieve(productIdToFetch)];
6667
- case 9:
6668
- product = _g.sent();
6669
- return [3 /*break*/, 11];
6670
- case 10:
6671
- err_2 = _g.sent();
6672
- console.error(err_2);
6673
- throw new Error("Product not found");
6674
- case 11:
6675
- isSubscription = Boolean(product.is_recurring);
6676
- // Required field validation
6677
- if (isSubscription && !product_id)
6678
- throw new Error("Missing required field: product_id for subscription");
6679
- if (!billing)
6680
- throw new Error("Missing required field: billing");
6681
- if (!customer)
6682
- throw new Error("Missing required field: customer");
6683
- if (!isSubscription) return [3 /*break*/, 16];
6684
- subscriptionPayload = {
6685
- billing: billing,
6686
- customer: customer,
6687
- product_id: product_id,
6688
- quantity: quantity ? Number(quantity) : 1,
6689
- };
6690
- if (metadata)
6691
- subscriptionPayload.metadata = metadata;
6692
- if (discount_code)
6693
- subscriptionPayload.discount_code = discount_code;
6694
- if (addons)
6695
- subscriptionPayload.addons = addons;
6696
- if (allowed_payment_method_types)
6697
- subscriptionPayload.allowed_payment_method_types =
6698
- allowed_payment_method_types;
6699
- if (billing_currency)
6700
- subscriptionPayload.billing_currency = billing_currency;
6701
- if (on_demand)
6702
- subscriptionPayload.on_demand = on_demand;
6703
- subscriptionPayload.payment_link = true;
6704
- // Use bodyReturnUrl if present, otherwise use top-level returnUrl
6705
- if (bodyReturnUrl) {
6706
- subscriptionPayload.return_url = bodyReturnUrl;
6707
- }
6708
- else if (returnUrl) {
6709
- subscriptionPayload.return_url = returnUrl;
6710
- }
6711
- if (show_saved_payment_methods)
6712
- subscriptionPayload.show_saved_payment_methods =
6713
- show_saved_payment_methods;
6714
- if (tax_id)
6715
- subscriptionPayload.tax_id = tax_id;
6716
- if (trial_period_days)
6717
- subscriptionPayload.trial_period_days = trial_period_days;
6718
- subscription = void 0;
6719
- _g.label = 12;
6720
- case 12:
6721
- _g.trys.push([12, 14, , 15]);
6722
- return [4 /*yield*/, dodopayments.subscriptions.create(subscriptionPayload)];
6723
- case 13:
6724
- subscription =
6725
- _g.sent();
6726
- return [3 /*break*/, 15];
6727
- case 14:
6728
- err_3 = _g.sent();
6729
- console.error("Error when creating subscription", err_3);
6730
- throw new Error(err_3 instanceof Error ? err_3.message : String(err_3));
6731
- case 15:
6732
- if (!subscription || !subscription.payment_link) {
6733
- throw new Error("No payment link returned from Dodo Payments API (subscription). Make sure to set payment_link as true in payload");
6734
- }
6735
- return [2 /*return*/, subscription.payment_link];
6736
- case 16:
6737
- cart = product_cart;
6738
- if (!cart && product_id) {
6739
- cart = [
6740
- { product_id: product_id, quantity: quantity ? Number(quantity) : 1 },
6741
- ];
6742
- }
6743
- if (!cart || cart.length === 0)
6744
- throw new Error("Missing required field: product_cart or product_id");
6745
- paymentPayload = {
6746
- billing: billing,
6747
- customer: customer,
6748
- product_cart: cart,
6749
- };
6750
- if (metadata)
6751
- paymentPayload.metadata = metadata;
6752
- paymentPayload.payment_link = true;
6753
- if (allowed_payment_method_types)
6754
- paymentPayload.allowed_payment_method_types =
6755
- allowed_payment_method_types;
6756
- if (billing_currency)
6757
- paymentPayload.billing_currency = billing_currency;
6758
- if (discount_code)
6759
- paymentPayload.discount_code = discount_code;
6760
- // Use bodyReturnUrl if present, otherwise use top-level returnUrl
6761
- if (bodyReturnUrl) {
6762
- paymentPayload.return_url = bodyReturnUrl;
6763
- }
6764
- else if (returnUrl) {
6765
- paymentPayload.return_url = returnUrl;
6766
- }
6767
- if (show_saved_payment_methods)
6768
- paymentPayload.show_saved_payment_methods = show_saved_payment_methods;
6769
- if (tax_id)
6770
- paymentPayload.tax_id = tax_id;
6771
- payment = void 0;
6772
- _g.label = 17;
6773
- case 17:
6774
- _g.trys.push([17, 19, , 20]);
6775
- return [4 /*yield*/, dodopayments.payments.create(paymentPayload)];
6776
- case 18:
6777
- payment = _g.sent();
6778
- return [3 /*break*/, 20];
6779
- case 19:
6780
- err_4 = _g.sent();
6781
- console.error("Error when creating payment link", err_4);
6782
- throw new Error(err_4 instanceof Error ? err_4.message : String(err_4));
6783
- case 20:
6784
- if (!payment || !payment.payment_link) {
6785
- throw new Error("No payment link returned from Dodo Payments API. Make sure to set payment_link as true in payload.");
6786
- }
6787
- return [2 /*return*/, payment.payment_link];
6788
- }
6789
- });
6790
- }); };
6791
-
6792
- const Checkout = (config) => {
6793
- const getHandler = async (event) => {
6794
- const searchParams = event.url.searchParams;
6795
- const queryParams = Object.fromEntries(searchParams);
6796
- if (!queryParams.productId) {
6797
- throw error(400, "Please provide productId query parameter");
6798
- }
6799
- const { success, data, error: zodError, } = checkoutQuerySchema.safeParse(queryParams);
6800
- if (!success) {
6801
- if (zodError.errors.some((e) => e.path.toString() === "productId")) {
6802
- throw error(400, "Please provide productId query parameter");
6803
- }
6804
- throw error(400, `Invalid query parameters.\n ${zodError.message}`);
6805
- }
6806
- let urlStr = "";
6807
- try {
6808
- urlStr = await buildCheckoutUrl({ queryParams: data, ...config });
6809
- }
6810
- catch (err) {
6811
- throw error(400, err.message);
6812
- }
6813
- return Response.json({ checkout_url: urlStr });
6814
- };
6815
- const postHandler = async (event) => {
6816
- let body;
6817
- try {
6818
- body = await event.request.json();
6819
- }
6820
- catch (e) {
6821
- throw error(400, "Invalid JSON body");
6822
- }
6823
- if (config.type === "dynamic") {
6824
- // Handle dynamic checkout
6825
- const { success, data, error: zodError, } = dynamicCheckoutBodySchema.safeParse(body);
6826
- if (!success) {
6827
- throw error(400, `Invalid request body.\n ${zodError.message}`);
6828
- }
6829
- let urlStr = "";
6830
- try {
6831
- urlStr = await buildCheckoutUrl({
6832
- body: data,
6833
- ...config,
6834
- type: "dynamic",
6835
- });
6836
- }
6837
- catch (err) {
6838
- throw error(400, err.message);
6839
- }
6840
- return Response.json({ checkout_url: urlStr });
6841
- }
6842
- else {
6843
- // Handle checkout session
6844
- const { success, data, error: zodError, } = checkoutSessionPayloadSchema.safeParse(body);
6845
- if (!success) {
6846
- throw error(400, `Invalid checkout session payload.\n ${zodError.message}`);
6847
- }
6848
- let urlStr = "";
6849
- try {
6850
- urlStr = await buildCheckoutUrl({
6851
- sessionPayload: data,
6852
- ...config,
6853
- type: "session",
6854
- });
6855
- }
6856
- catch (err) {
6857
- throw error(400, err.message);
6858
- }
6859
- return Response.json({ checkout_url: urlStr });
6860
- }
5965
+ var URLSafeCoder = /** @class */ (function (_super) {
5966
+ __extends(URLSafeCoder, _super);
5967
+ function URLSafeCoder() {
5968
+ return _super !== null && _super.apply(this, arguments) || this;
5969
+ }
5970
+ // URL-safe encoding have the following encoded/decoded ranges:
5971
+ //
5972
+ // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _
5973
+ // Index: 0 - 25 26 - 51 52 - 61 62 63
5974
+ // ASCII: 65 - 90 97 - 122 48 - 57 45 95
5975
+ //
5976
+ URLSafeCoder.prototype._encodeByte = function (b) {
5977
+ var result = b;
5978
+ // b >= 0
5979
+ result += 65;
5980
+ // b > 25
5981
+ result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
5982
+ // b > 51
5983
+ result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
5984
+ // b > 61
5985
+ result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45);
5986
+ // b > 62
5987
+ result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95);
5988
+ return String.fromCharCode(result);
6861
5989
  };
6862
- // SvelteKit expects named exports for HTTP verbs
6863
- return {
6864
- GET: getHandler,
6865
- POST: postHandler,
5990
+ URLSafeCoder.prototype._decodeChar = function (c) {
5991
+ var result = INVALID_BYTE;
5992
+ // c == 45 (c > 44 and c < 46)
5993
+ result += (((44 - c) & (c - 46)) >>> 8) & (-INVALID_BYTE + c - 45 + 62);
5994
+ // c == 95 (c > 94 and c < 96)
5995
+ result += (((94 - c) & (c - 96)) >>> 8) & (-INVALID_BYTE + c - 95 + 63);
5996
+ // c > 47 and c < 58
5997
+ result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
5998
+ // c > 64 and c < 91
5999
+ result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
6000
+ // c > 96 and c < 123
6001
+ result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
6002
+ return result;
6866
6003
  };
6867
- };
6868
-
6869
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
6870
-
6871
- var dist = {};
6872
-
6873
- var timing_safe_equal = {};
6874
-
6875
- Object.defineProperty(timing_safe_equal, "__esModule", { value: true });
6876
- timing_safe_equal.timingSafeEqual = void 0;
6877
- function assert(expr, msg = "") {
6878
- if (!expr) {
6879
- throw new Error(msg);
6880
- }
6004
+ return URLSafeCoder;
6005
+ }(Coder));
6006
+ base64$1.URLSafeCoder = URLSafeCoder;
6007
+ var urlSafeCoder = new URLSafeCoder();
6008
+ function encodeURLSafe(data) {
6009
+ return urlSafeCoder.encode(data);
6881
6010
  }
6882
- function timingSafeEqual(a, b) {
6883
- if (a.byteLength !== b.byteLength) {
6884
- return false;
6885
- }
6886
- if (!(a instanceof DataView)) {
6887
- a = new DataView(ArrayBuffer.isView(a) ? a.buffer : a);
6888
- }
6889
- if (!(b instanceof DataView)) {
6890
- b = new DataView(ArrayBuffer.isView(b) ? b.buffer : b);
6891
- }
6892
- assert(a instanceof DataView);
6893
- assert(b instanceof DataView);
6894
- const length = a.byteLength;
6895
- let out = 0;
6896
- let i = -1;
6897
- while (++i < length) {
6898
- out |= a.getUint8(i) ^ b.getUint8(i);
6899
- }
6900
- return out === 0;
6011
+ base64$1.encodeURLSafe = encodeURLSafe;
6012
+ function decodeURLSafe(s) {
6013
+ return urlSafeCoder.decode(s);
6901
6014
  }
6902
- timing_safe_equal.timingSafeEqual = timingSafeEqual;
6015
+ base64$1.decodeURLSafe = decodeURLSafe;
6016
+ base64$1.encodedLength = function (length) {
6017
+ return stdCoder.encodedLength(length);
6018
+ };
6019
+ base64$1.maxDecodedLength = function (length) {
6020
+ return stdCoder.maxDecodedLength(length);
6021
+ };
6022
+ base64$1.decodedLength = function (s) {
6023
+ return stdCoder.decodedLength(s);
6024
+ };
6903
6025
 
6904
- var base64$1 = {};
6905
-
6906
- // Copyright (C) 2016 Dmitry Chestnykh
6907
- // MIT License. See LICENSE file for details.
6908
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
6909
- var extendStatics = function (d, b) {
6910
- extendStatics = Object.setPrototypeOf ||
6911
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6912
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
6913
- return extendStatics(d, b);
6914
- };
6915
- return function (d, b) {
6916
- extendStatics(d, b);
6917
- function __() { this.constructor = d; }
6918
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6919
- };
6920
- })();
6921
- Object.defineProperty(base64$1, "__esModule", { value: true });
6922
- /**
6923
- * Package base64 implements Base64 encoding and decoding.
6924
- */
6925
- // Invalid character used in decoding to indicate
6926
- // that the character to decode is out of range of
6927
- // alphabet and cannot be decoded.
6928
- var INVALID_BYTE = 256;
6929
- /**
6930
- * Implements standard Base64 encoding.
6931
- *
6932
- * Operates in constant time.
6933
- */
6934
- var Coder = /** @class */ (function () {
6935
- // TODO(dchest): methods to encode chunk-by-chunk.
6936
- function Coder(_paddingCharacter) {
6937
- if (_paddingCharacter === void 0) { _paddingCharacter = "="; }
6938
- this._paddingCharacter = _paddingCharacter;
6939
- }
6940
- Coder.prototype.encodedLength = function (length) {
6941
- if (!this._paddingCharacter) {
6942
- return (length * 8 + 5) / 6 | 0;
6943
- }
6944
- return (length + 2) / 3 * 4 | 0;
6945
- };
6946
- Coder.prototype.encode = function (data) {
6947
- var out = "";
6948
- var i = 0;
6949
- for (; i < data.length - 2; i += 3) {
6950
- var c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);
6951
- out += this._encodeByte((c >>> 3 * 6) & 63);
6952
- out += this._encodeByte((c >>> 2 * 6) & 63);
6953
- out += this._encodeByte((c >>> 1 * 6) & 63);
6954
- out += this._encodeByte((c >>> 0 * 6) & 63);
6955
- }
6956
- var left = data.length - i;
6957
- if (left > 0) {
6958
- var c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0);
6959
- out += this._encodeByte((c >>> 3 * 6) & 63);
6960
- out += this._encodeByte((c >>> 2 * 6) & 63);
6961
- if (left === 2) {
6962
- out += this._encodeByte((c >>> 1 * 6) & 63);
6963
- }
6964
- else {
6965
- out += this._paddingCharacter || "";
6966
- }
6967
- out += this._paddingCharacter || "";
6968
- }
6969
- return out;
6970
- };
6971
- Coder.prototype.maxDecodedLength = function (length) {
6972
- if (!this._paddingCharacter) {
6973
- return (length * 6 + 7) / 8 | 0;
6974
- }
6975
- return length / 4 * 3 | 0;
6976
- };
6977
- Coder.prototype.decodedLength = function (s) {
6978
- return this.maxDecodedLength(s.length - this._getPaddingLength(s));
6979
- };
6980
- Coder.prototype.decode = function (s) {
6981
- if (s.length === 0) {
6982
- return new Uint8Array(0);
6983
- }
6984
- var paddingLength = this._getPaddingLength(s);
6985
- var length = s.length - paddingLength;
6986
- var out = new Uint8Array(this.maxDecodedLength(length));
6987
- var op = 0;
6988
- var i = 0;
6989
- var haveBad = 0;
6990
- var v0 = 0, v1 = 0, v2 = 0, v3 = 0;
6991
- for (; i < length - 4; i += 4) {
6992
- v0 = this._decodeChar(s.charCodeAt(i + 0));
6993
- v1 = this._decodeChar(s.charCodeAt(i + 1));
6994
- v2 = this._decodeChar(s.charCodeAt(i + 2));
6995
- v3 = this._decodeChar(s.charCodeAt(i + 3));
6996
- out[op++] = (v0 << 2) | (v1 >>> 4);
6997
- out[op++] = (v1 << 4) | (v2 >>> 2);
6998
- out[op++] = (v2 << 6) | v3;
6999
- haveBad |= v0 & INVALID_BYTE;
7000
- haveBad |= v1 & INVALID_BYTE;
7001
- haveBad |= v2 & INVALID_BYTE;
7002
- haveBad |= v3 & INVALID_BYTE;
7003
- }
7004
- if (i < length - 1) {
7005
- v0 = this._decodeChar(s.charCodeAt(i));
7006
- v1 = this._decodeChar(s.charCodeAt(i + 1));
7007
- out[op++] = (v0 << 2) | (v1 >>> 4);
7008
- haveBad |= v0 & INVALID_BYTE;
7009
- haveBad |= v1 & INVALID_BYTE;
7010
- }
7011
- if (i < length - 2) {
7012
- v2 = this._decodeChar(s.charCodeAt(i + 2));
7013
- out[op++] = (v1 << 4) | (v2 >>> 2);
7014
- haveBad |= v2 & INVALID_BYTE;
7015
- }
7016
- if (i < length - 3) {
7017
- v3 = this._decodeChar(s.charCodeAt(i + 3));
7018
- out[op++] = (v2 << 6) | v3;
7019
- haveBad |= v3 & INVALID_BYTE;
7020
- }
7021
- if (haveBad !== 0) {
7022
- throw new Error("Base64Coder: incorrect characters for decoding");
7023
- }
7024
- return out;
7025
- };
7026
- // Standard encoding have the following encoded/decoded ranges,
7027
- // which we need to convert between.
7028
- //
7029
- // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + /
7030
- // Index: 0 - 25 26 - 51 52 - 61 62 63
7031
- // ASCII: 65 - 90 97 - 122 48 - 57 43 47
7032
- //
7033
- // Encode 6 bits in b into a new character.
7034
- Coder.prototype._encodeByte = function (b) {
7035
- // Encoding uses constant time operations as follows:
7036
- //
7037
- // 1. Define comparison of A with B using (A - B) >>> 8:
7038
- // if A > B, then result is positive integer
7039
- // if A <= B, then result is 0
7040
- //
7041
- // 2. Define selection of C or 0 using bitwise AND: X & C:
7042
- // if X == 0, then result is 0
7043
- // if X != 0, then result is C
7044
- //
7045
- // 3. Start with the smallest comparison (b >= 0), which is always
7046
- // true, so set the result to the starting ASCII value (65).
7047
- //
7048
- // 4. Continue comparing b to higher ASCII values, and selecting
7049
- // zero if comparison isn't true, otherwise selecting a value
7050
- // to add to result, which:
7051
- //
7052
- // a) undoes the previous addition
7053
- // b) provides new value to add
7054
- //
7055
- var result = b;
7056
- // b >= 0
7057
- result += 65;
7058
- // b > 25
7059
- result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
7060
- // b > 51
7061
- result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
7062
- // b > 61
7063
- result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43);
7064
- // b > 62
7065
- result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47);
7066
- return String.fromCharCode(result);
7067
- };
7068
- // Decode a character code into a byte.
7069
- // Must return 256 if character is out of alphabet range.
7070
- Coder.prototype._decodeChar = function (c) {
7071
- // Decoding works similar to encoding: using the same comparison
7072
- // function, but now it works on ranges: result is always incremented
7073
- // by value, but this value becomes zero if the range is not
7074
- // satisfied.
7075
- //
7076
- // Decoding starts with invalid value, 256, which is then
7077
- // subtracted when the range is satisfied. If none of the ranges
7078
- // apply, the function returns 256, which is then checked by
7079
- // the caller to throw error.
7080
- var result = INVALID_BYTE; // start with invalid character
7081
- // c == 43 (c > 42 and c < 44)
7082
- result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62);
7083
- // c == 47 (c > 46 and c < 48)
7084
- result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63);
7085
- // c > 47 and c < 58
7086
- result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
7087
- // c > 64 and c < 91
7088
- result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
7089
- // c > 96 and c < 123
7090
- result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
7091
- return result;
7092
- };
7093
- Coder.prototype._getPaddingLength = function (s) {
7094
- var paddingLength = 0;
7095
- if (this._paddingCharacter) {
7096
- for (var i = s.length - 1; i >= 0; i--) {
7097
- if (s[i] !== this._paddingCharacter) {
7098
- break;
7099
- }
7100
- paddingLength++;
7101
- }
7102
- if (s.length < 4 || paddingLength > 2) {
7103
- throw new Error("Base64Coder: incorrect padding");
7104
- }
7105
- }
7106
- return paddingLength;
7107
- };
7108
- return Coder;
7109
- }());
7110
- base64$1.Coder = Coder;
7111
- var stdCoder = new Coder();
7112
- function encode(data) {
7113
- return stdCoder.encode(data);
7114
- }
7115
- base64$1.encode = encode;
7116
- function decode(s) {
7117
- return stdCoder.decode(s);
7118
- }
7119
- base64$1.decode = decode;
7120
- /**
7121
- * Implements URL-safe Base64 encoding.
7122
- * (Same as Base64, but '+' is replaced with '-', and '/' with '_').
7123
- *
7124
- * Operates in constant time.
7125
- */
7126
- var URLSafeCoder = /** @class */ (function (_super) {
7127
- __extends(URLSafeCoder, _super);
7128
- function URLSafeCoder() {
7129
- return _super !== null && _super.apply(this, arguments) || this;
7130
- }
7131
- // URL-safe encoding have the following encoded/decoded ranges:
7132
- //
7133
- // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _
7134
- // Index: 0 - 25 26 - 51 52 - 61 62 63
7135
- // ASCII: 65 - 90 97 - 122 48 - 57 45 95
7136
- //
7137
- URLSafeCoder.prototype._encodeByte = function (b) {
7138
- var result = b;
7139
- // b >= 0
7140
- result += 65;
7141
- // b > 25
7142
- result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
7143
- // b > 51
7144
- result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
7145
- // b > 61
7146
- result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45);
7147
- // b > 62
7148
- result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95);
7149
- return String.fromCharCode(result);
7150
- };
7151
- URLSafeCoder.prototype._decodeChar = function (c) {
7152
- var result = INVALID_BYTE;
7153
- // c == 45 (c > 44 and c < 46)
7154
- result += (((44 - c) & (c - 46)) >>> 8) & (-INVALID_BYTE + c - 45 + 62);
7155
- // c == 95 (c > 94 and c < 96)
7156
- result += (((94 - c) & (c - 96)) >>> 8) & (-INVALID_BYTE + c - 95 + 63);
7157
- // c > 47 and c < 58
7158
- result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
7159
- // c > 64 and c < 91
7160
- result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
7161
- // c > 96 and c < 123
7162
- result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
7163
- return result;
7164
- };
7165
- return URLSafeCoder;
7166
- }(Coder));
7167
- base64$1.URLSafeCoder = URLSafeCoder;
7168
- var urlSafeCoder = new URLSafeCoder();
7169
- function encodeURLSafe(data) {
7170
- return urlSafeCoder.encode(data);
7171
- }
7172
- base64$1.encodeURLSafe = encodeURLSafe;
7173
- function decodeURLSafe(s) {
7174
- return urlSafeCoder.decode(s);
7175
- }
7176
- base64$1.decodeURLSafe = decodeURLSafe;
7177
- base64$1.encodedLength = function (length) {
7178
- return stdCoder.encodedLength(length);
7179
- };
7180
- base64$1.maxDecodedLength = function (length) {
7181
- return stdCoder.maxDecodedLength(length);
7182
- };
7183
- base64$1.decodedLength = function (s) {
7184
- return stdCoder.decodedLength(s);
7185
- };
7186
-
7187
- var sha256$1 = {exports: {}};
6026
+ var sha256$1 = {exports: {}};
7188
6027
 
7189
6028
  (function (module) {
7190
6029
  (function (root, factory) {
@@ -7640,619 +6479,1611 @@ class Webhook {
7640
6479
  if (!secret) {
7641
6480
  throw new Error("Secret can't be empty.");
7642
6481
  }
7643
- if ((options === null || options === void 0 ? void 0 : options.format) === "raw") {
7644
- if (secret instanceof Uint8Array) {
7645
- this.key = secret;
7646
- }
7647
- else {
7648
- this.key = Uint8Array.from(secret, (c) => c.charCodeAt(0));
7649
- }
6482
+ if ((options === null || options === void 0 ? void 0 : options.format) === "raw") {
6483
+ if (secret instanceof Uint8Array) {
6484
+ this.key = secret;
6485
+ }
6486
+ else {
6487
+ this.key = Uint8Array.from(secret, (c) => c.charCodeAt(0));
6488
+ }
6489
+ }
6490
+ else {
6491
+ if (typeof secret !== "string") {
6492
+ throw new Error("Expected secret to be of type string");
6493
+ }
6494
+ if (secret.startsWith(Webhook.prefix)) {
6495
+ secret = secret.substring(Webhook.prefix.length);
6496
+ }
6497
+ this.key = base64.decode(secret);
6498
+ }
6499
+ }
6500
+ verify(payload, headers_) {
6501
+ const headers = {};
6502
+ for (const key of Object.keys(headers_)) {
6503
+ headers[key.toLowerCase()] = headers_[key];
6504
+ }
6505
+ const msgId = headers["webhook-id"];
6506
+ const msgSignature = headers["webhook-signature"];
6507
+ const msgTimestamp = headers["webhook-timestamp"];
6508
+ if (!msgSignature || !msgId || !msgTimestamp) {
6509
+ throw new WebhookVerificationError("Missing required headers");
6510
+ }
6511
+ const timestamp = this.verifyTimestamp(msgTimestamp);
6512
+ const computedSignature = this.sign(msgId, timestamp, payload);
6513
+ const expectedSignature = computedSignature.split(",")[1];
6514
+ const passedSignatures = msgSignature.split(" ");
6515
+ const encoder = new globalThis.TextEncoder();
6516
+ for (const versionedSignature of passedSignatures) {
6517
+ const [version, signature] = versionedSignature.split(",");
6518
+ if (version !== "v1") {
6519
+ continue;
6520
+ }
6521
+ if ((0, timing_safe_equal_1.timingSafeEqual)(encoder.encode(signature), encoder.encode(expectedSignature))) {
6522
+ return JSON.parse(payload.toString());
6523
+ }
6524
+ }
6525
+ throw new WebhookVerificationError("No matching signature found");
6526
+ }
6527
+ sign(msgId, timestamp, payload) {
6528
+ if (typeof payload === "string") ;
6529
+ else if (payload.constructor.name === "Buffer") {
6530
+ payload = payload.toString();
6531
+ }
6532
+ else {
6533
+ throw new Error("Expected payload to be of type string or Buffer.");
6534
+ }
6535
+ const encoder = new TextEncoder();
6536
+ const timestampNumber = Math.floor(timestamp.getTime() / 1000);
6537
+ const toSign = encoder.encode(`${msgId}.${timestampNumber}.${payload}`);
6538
+ const expectedSignature = base64.encode(sha256.hmac(this.key, toSign));
6539
+ return `v1,${expectedSignature}`;
6540
+ }
6541
+ verifyTimestamp(timestampHeader) {
6542
+ const now = Math.floor(Date.now() / 1000);
6543
+ const timestamp = parseInt(timestampHeader, 10);
6544
+ if (isNaN(timestamp)) {
6545
+ throw new WebhookVerificationError("Invalid Signature Headers");
6546
+ }
6547
+ if (now - timestamp > WEBHOOK_TOLERANCE_IN_SECONDS) {
6548
+ throw new WebhookVerificationError("Message timestamp too old");
6549
+ }
6550
+ if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) {
6551
+ throw new WebhookVerificationError("Message timestamp too new");
6552
+ }
6553
+ return new Date(timestamp * 1000);
6554
+ }
6555
+ }
6556
+ Webhook_1 = dist.Webhook = Webhook;
6557
+ Webhook.prefix = "whsec_";
6558
+
6559
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
6560
+ let Webhooks$1 = class Webhooks extends APIResource {
6561
+ constructor() {
6562
+ super(...arguments);
6563
+ this.headers = new Headers$1(this._client);
6564
+ }
6565
+ /**
6566
+ * Create a new webhook
6567
+ */
6568
+ create(body, options) {
6569
+ return this._client.post('/webhooks', { body, ...options });
6570
+ }
6571
+ /**
6572
+ * Get a webhook by id
6573
+ */
6574
+ retrieve(webhookID, options) {
6575
+ return this._client.get(path `/webhooks/${webhookID}`, options);
6576
+ }
6577
+ /**
6578
+ * Patch a webhook by id
6579
+ */
6580
+ update(webhookID, body, options) {
6581
+ return this._client.patch(path `/webhooks/${webhookID}`, { body, ...options });
6582
+ }
6583
+ /**
6584
+ * List all webhooks
6585
+ */
6586
+ list(query = {}, options) {
6587
+ return this._client.getAPIList('/webhooks', (CursorPagePagination), { query, ...options });
6588
+ }
6589
+ /**
6590
+ * Delete a webhook by id
6591
+ */
6592
+ delete(webhookID, options) {
6593
+ return this._client.delete(path `/webhooks/${webhookID}`, {
6594
+ ...options,
6595
+ headers: buildHeaders([{ Accept: '*/*' }, options?.headers]),
6596
+ });
6597
+ }
6598
+ /**
6599
+ * Get webhook secret by id
6600
+ */
6601
+ retrieveSecret(webhookID, options) {
6602
+ return this._client.get(path `/webhooks/${webhookID}/secret`, options);
6603
+ }
6604
+ unsafeUnwrap(body) {
6605
+ return JSON.parse(body);
6606
+ }
6607
+ unwrap(body, { headers, key }) {
6608
+ if (headers !== undefined) {
6609
+ const keyStr = key === undefined ? this._client.webhookKey : key;
6610
+ if (keyStr === null)
6611
+ throw new Error('Webhook key must not be null in order to unwrap');
6612
+ const wh = new Webhook_1(keyStr);
6613
+ wh.verify(body, headers);
6614
+ }
6615
+ return JSON.parse(body);
6616
+ }
6617
+ };
6618
+ Webhooks$1.Headers = Headers$1;
6619
+
6620
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
6621
+ /**
6622
+ * Read an environment variable.
6623
+ *
6624
+ * Trims beginning and trailing whitespace.
6625
+ *
6626
+ * Will return undefined if the environment variable doesn't exist or cannot be accessed.
6627
+ */
6628
+ const readEnv = (env) => {
6629
+ if (typeof globalThis.process !== 'undefined') {
6630
+ return globalThis.process.env?.[env]?.trim() ?? undefined;
6631
+ }
6632
+ if (typeof globalThis.Deno !== 'undefined') {
6633
+ return globalThis.Deno.env?.get?.(env)?.trim();
6634
+ }
6635
+ return undefined;
6636
+ };
6637
+
6638
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
6639
+ var _DodoPayments_instances, _a, _DodoPayments_encoder, _DodoPayments_baseURLOverridden;
6640
+ const environments = {
6641
+ live_mode: 'https://live.dodopayments.com',
6642
+ test_mode: 'https://test.dodopayments.com',
6643
+ };
6644
+ /**
6645
+ * API Client for interfacing with the Dodo Payments API.
6646
+ */
6647
+ class DodoPayments {
6648
+ /**
6649
+ * API Client for interfacing with the Dodo Payments API.
6650
+ *
6651
+ * @param {string | undefined} [opts.bearerToken=process.env['DODO_PAYMENTS_API_KEY'] ?? undefined]
6652
+ * @param {string | null | undefined} [opts.webhookKey=process.env['DODO_PAYMENTS_WEBHOOK_KEY'] ?? null]
6653
+ * @param {Environment} [opts.environment=live_mode] - Specifies the environment URL to use for the API.
6654
+ * @param {string} [opts.baseURL=process.env['DODO_PAYMENTS_BASE_URL'] ?? https://live.dodopayments.com] - Override the default base URL for the API.
6655
+ * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
6656
+ * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
6657
+ * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
6658
+ * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
6659
+ * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
6660
+ * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
6661
+ */
6662
+ constructor({ baseURL = readEnv('DODO_PAYMENTS_BASE_URL'), bearerToken = readEnv('DODO_PAYMENTS_API_KEY'), webhookKey = readEnv('DODO_PAYMENTS_WEBHOOK_KEY') ?? null, ...opts } = {}) {
6663
+ _DodoPayments_instances.add(this);
6664
+ _DodoPayments_encoder.set(this, void 0);
6665
+ this.checkoutSessions = new CheckoutSessions(this);
6666
+ this.payments = new Payments(this);
6667
+ this.subscriptions = new Subscriptions(this);
6668
+ this.invoices = new Invoices(this);
6669
+ this.licenses = new Licenses(this);
6670
+ this.licenseKeys = new LicenseKeys(this);
6671
+ this.licenseKeyInstances = new LicenseKeyInstances(this);
6672
+ this.customers = new Customers(this);
6673
+ this.refunds = new Refunds(this);
6674
+ this.disputes = new Disputes(this);
6675
+ this.payouts = new Payouts(this);
6676
+ this.products = new Products(this);
6677
+ this.misc = new Misc(this);
6678
+ this.discounts = new Discounts(this);
6679
+ this.addons = new Addons(this);
6680
+ this.brands = new Brands(this);
6681
+ this.webhooks = new Webhooks$1(this);
6682
+ this.webhookEvents = new WebhookEvents(this);
6683
+ this.usageEvents = new UsageEvents(this);
6684
+ this.meters = new Meters(this);
6685
+ if (bearerToken === undefined) {
6686
+ 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' }).");
6687
+ }
6688
+ const options = {
6689
+ bearerToken,
6690
+ webhookKey,
6691
+ ...opts,
6692
+ baseURL,
6693
+ environment: opts.environment ?? 'live_mode',
6694
+ };
6695
+ if (baseURL && opts.environment) {
6696
+ 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');
6697
+ }
6698
+ this.baseURL = options.baseURL || environments[options.environment || 'live_mode'];
6699
+ this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 1 minute */;
6700
+ this.logger = options.logger ?? console;
6701
+ const defaultLogLevel = 'warn';
6702
+ // Set default logLevel early so that we can log a warning in parseLogLevel.
6703
+ this.logLevel = defaultLogLevel;
6704
+ this.logLevel =
6705
+ parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??
6706
+ parseLogLevel(readEnv('DODO_PAYMENTS_LOG'), "process.env['DODO_PAYMENTS_LOG']", this) ??
6707
+ defaultLogLevel;
6708
+ this.fetchOptions = options.fetchOptions;
6709
+ this.maxRetries = options.maxRetries ?? 2;
6710
+ this.fetch = options.fetch ?? getDefaultFetch();
6711
+ __classPrivateFieldSet(this, _DodoPayments_encoder, FallbackEncoder);
6712
+ this._options = options;
6713
+ this.bearerToken = bearerToken;
6714
+ this.webhookKey = webhookKey;
6715
+ }
6716
+ /**
6717
+ * Create a new client instance re-using the same options given to the current client with optional overriding.
6718
+ */
6719
+ withOptions(options) {
6720
+ const client = new this.constructor({
6721
+ ...this._options,
6722
+ environment: options.environment ? options.environment : undefined,
6723
+ baseURL: options.environment ? undefined : this.baseURL,
6724
+ maxRetries: this.maxRetries,
6725
+ timeout: this.timeout,
6726
+ logger: this.logger,
6727
+ logLevel: this.logLevel,
6728
+ fetch: this.fetch,
6729
+ fetchOptions: this.fetchOptions,
6730
+ bearerToken: this.bearerToken,
6731
+ webhookKey: this.webhookKey,
6732
+ ...options,
6733
+ });
6734
+ return client;
6735
+ }
6736
+ defaultQuery() {
6737
+ return this._options.defaultQuery;
6738
+ }
6739
+ validateHeaders({ values, nulls }) {
6740
+ return;
6741
+ }
6742
+ async authHeaders(opts) {
6743
+ return buildHeaders([{ Authorization: `Bearer ${this.bearerToken}` }]);
6744
+ }
6745
+ /**
6746
+ * Basic re-implementation of `qs.stringify` for primitive types.
6747
+ */
6748
+ stringifyQuery(query) {
6749
+ return Object.entries(query)
6750
+ .filter(([_, value]) => typeof value !== 'undefined')
6751
+ .map(([key, value]) => {
6752
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
6753
+ return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
6754
+ }
6755
+ if (value === null) {
6756
+ return `${encodeURIComponent(key)}=`;
6757
+ }
6758
+ 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.`);
6759
+ })
6760
+ .join('&');
6761
+ }
6762
+ getUserAgent() {
6763
+ return `${this.constructor.name}/JS ${VERSION}`;
6764
+ }
6765
+ defaultIdempotencyKey() {
6766
+ return `stainless-node-retry-${uuid4()}`;
6767
+ }
6768
+ makeStatusError(status, error, message, headers) {
6769
+ return APIError.generate(status, error, message, headers);
6770
+ }
6771
+ buildURL(path, query, defaultBaseURL) {
6772
+ const baseURL = (!__classPrivateFieldGet(this, _DodoPayments_instances, "m", _DodoPayments_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;
6773
+ const url = isAbsoluteURL(path) ?
6774
+ new URL(path)
6775
+ : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
6776
+ const defaultQuery = this.defaultQuery();
6777
+ if (!isEmptyObj(defaultQuery)) {
6778
+ query = { ...defaultQuery, ...query };
6779
+ }
6780
+ if (typeof query === 'object' && query && !Array.isArray(query)) {
6781
+ url.search = this.stringifyQuery(query);
6782
+ }
6783
+ return url.toString();
6784
+ }
6785
+ /**
6786
+ * Used as a callback for mutating the given `FinalRequestOptions` object.
6787
+ */
6788
+ async prepareOptions(options) { }
6789
+ /**
6790
+ * Used as a callback for mutating the given `RequestInit` object.
6791
+ *
6792
+ * This is useful for cases where you want to add certain headers based off of
6793
+ * the request properties, e.g. `method` or `url`.
6794
+ */
6795
+ async prepareRequest(request, { url, options }) { }
6796
+ get(path, opts) {
6797
+ return this.methodRequest('get', path, opts);
6798
+ }
6799
+ post(path, opts) {
6800
+ return this.methodRequest('post', path, opts);
6801
+ }
6802
+ patch(path, opts) {
6803
+ return this.methodRequest('patch', path, opts);
6804
+ }
6805
+ put(path, opts) {
6806
+ return this.methodRequest('put', path, opts);
6807
+ }
6808
+ delete(path, opts) {
6809
+ return this.methodRequest('delete', path, opts);
6810
+ }
6811
+ methodRequest(method, path, opts) {
6812
+ return this.request(Promise.resolve(opts).then((opts) => {
6813
+ return { method, path, ...opts };
6814
+ }));
6815
+ }
6816
+ request(options, remainingRetries = null) {
6817
+ return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
6818
+ }
6819
+ async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
6820
+ const options = await optionsInput;
6821
+ const maxRetries = options.maxRetries ?? this.maxRetries;
6822
+ if (retriesRemaining == null) {
6823
+ retriesRemaining = maxRetries;
6824
+ }
6825
+ await this.prepareOptions(options);
6826
+ const { req, url, timeout } = await this.buildRequest(options, {
6827
+ retryCount: maxRetries - retriesRemaining,
6828
+ });
6829
+ await this.prepareRequest(req, { url, options });
6830
+ /** Not an API request ID, just for correlating local log entries. */
6831
+ const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
6832
+ const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
6833
+ const startTime = Date.now();
6834
+ loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
6835
+ retryOfRequestLogID,
6836
+ method: options.method,
6837
+ url,
6838
+ options,
6839
+ headers: req.headers,
6840
+ }));
6841
+ if (options.signal?.aborted) {
6842
+ throw new APIUserAbortError();
6843
+ }
6844
+ const controller = new AbortController();
6845
+ const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
6846
+ const headersTime = Date.now();
6847
+ if (response instanceof globalThis.Error) {
6848
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
6849
+ if (options.signal?.aborted) {
6850
+ throw new APIUserAbortError();
6851
+ }
6852
+ // detect native connection timeout errors
6853
+ // 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)"
6854
+ // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
6855
+ // others do not provide enough information to distinguish timeouts from other connection errors
6856
+ const isTimeout = isAbortError(response) ||
6857
+ /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
6858
+ if (retriesRemaining) {
6859
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
6860
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({
6861
+ retryOfRequestLogID,
6862
+ url,
6863
+ durationMs: headersTime - startTime,
6864
+ message: response.message,
6865
+ }));
6866
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
6867
+ }
6868
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
6869
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({
6870
+ retryOfRequestLogID,
6871
+ url,
6872
+ durationMs: headersTime - startTime,
6873
+ message: response.message,
6874
+ }));
6875
+ if (isTimeout) {
6876
+ throw new APIConnectionTimeoutError();
6877
+ }
6878
+ throw new APIConnectionError({ cause: response });
6879
+ }
6880
+ const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
6881
+ if (!response.ok) {
6882
+ const shouldRetry = await this.shouldRetry(response);
6883
+ if (retriesRemaining && shouldRetry) {
6884
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
6885
+ // We don't need the body of this response.
6886
+ await CancelReadableStream(response.body);
6887
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
6888
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
6889
+ retryOfRequestLogID,
6890
+ url: response.url,
6891
+ status: response.status,
6892
+ headers: response.headers,
6893
+ durationMs: headersTime - startTime,
6894
+ }));
6895
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
6896
+ }
6897
+ const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
6898
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
6899
+ const errText = await response.text().catch((err) => castToError(err).message);
6900
+ const errJSON = safeJSON(errText);
6901
+ const errMessage = errJSON ? undefined : errText;
6902
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
6903
+ retryOfRequestLogID,
6904
+ url: response.url,
6905
+ status: response.status,
6906
+ headers: response.headers,
6907
+ message: errMessage,
6908
+ durationMs: Date.now() - startTime,
6909
+ }));
6910
+ const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
6911
+ throw err;
6912
+ }
6913
+ loggerFor(this).info(responseInfo);
6914
+ loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
6915
+ retryOfRequestLogID,
6916
+ url: response.url,
6917
+ status: response.status,
6918
+ headers: response.headers,
6919
+ durationMs: headersTime - startTime,
6920
+ }));
6921
+ return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
6922
+ }
6923
+ getAPIList(path, Page, opts) {
6924
+ return this.requestAPIList(Page, { method: 'get', path, ...opts });
6925
+ }
6926
+ requestAPIList(Page, options) {
6927
+ const request = this.makeRequest(options, null, undefined);
6928
+ return new PagePromise(this, request, Page);
6929
+ }
6930
+ async fetchWithTimeout(url, init, ms, controller) {
6931
+ const { signal, method, ...options } = init || {};
6932
+ if (signal)
6933
+ signal.addEventListener('abort', () => controller.abort());
6934
+ const timeout = setTimeout(() => controller.abort(), ms);
6935
+ const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
6936
+ (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
6937
+ const fetchOptions = {
6938
+ signal: controller.signal,
6939
+ ...(isReadableBody ? { duplex: 'half' } : {}),
6940
+ method: 'GET',
6941
+ ...options,
6942
+ };
6943
+ if (method) {
6944
+ // Custom methods like 'patch' need to be uppercased
6945
+ // See https://github.com/nodejs/undici/issues/2294
6946
+ fetchOptions.method = method.toUpperCase();
6947
+ }
6948
+ try {
6949
+ // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
6950
+ return await this.fetch.call(undefined, url, fetchOptions);
6951
+ }
6952
+ finally {
6953
+ clearTimeout(timeout);
6954
+ }
6955
+ }
6956
+ async shouldRetry(response) {
6957
+ // Note this is not a standard header.
6958
+ const shouldRetryHeader = response.headers.get('x-should-retry');
6959
+ // If the server explicitly says whether or not to retry, obey.
6960
+ if (shouldRetryHeader === 'true')
6961
+ return true;
6962
+ if (shouldRetryHeader === 'false')
6963
+ return false;
6964
+ // Retry on request timeouts.
6965
+ if (response.status === 408)
6966
+ return true;
6967
+ // Retry on lock timeouts.
6968
+ if (response.status === 409)
6969
+ return true;
6970
+ // Retry on rate limits.
6971
+ if (response.status === 429)
6972
+ return true;
6973
+ // Retry internal errors.
6974
+ if (response.status >= 500)
6975
+ return true;
6976
+ return false;
6977
+ }
6978
+ async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
6979
+ let timeoutMillis;
6980
+ // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
6981
+ const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
6982
+ if (retryAfterMillisHeader) {
6983
+ const timeoutMs = parseFloat(retryAfterMillisHeader);
6984
+ if (!Number.isNaN(timeoutMs)) {
6985
+ timeoutMillis = timeoutMs;
6986
+ }
6987
+ }
6988
+ // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
6989
+ const retryAfterHeader = responseHeaders?.get('retry-after');
6990
+ if (retryAfterHeader && !timeoutMillis) {
6991
+ const timeoutSeconds = parseFloat(retryAfterHeader);
6992
+ if (!Number.isNaN(timeoutSeconds)) {
6993
+ timeoutMillis = timeoutSeconds * 1000;
6994
+ }
6995
+ else {
6996
+ timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
6997
+ }
6998
+ }
6999
+ // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
7000
+ // just do what it says, but otherwise calculate a default
7001
+ if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
7002
+ const maxRetries = options.maxRetries ?? this.maxRetries;
7003
+ timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
7004
+ }
7005
+ await sleep(timeoutMillis);
7006
+ return this.makeRequest(options, retriesRemaining - 1, requestLogID);
7007
+ }
7008
+ calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
7009
+ const initialRetryDelay = 0.5;
7010
+ const maxRetryDelay = 8.0;
7011
+ const numRetries = maxRetries - retriesRemaining;
7012
+ // Apply exponential backoff, but not more than the max.
7013
+ const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
7014
+ // Apply some jitter, take up to at most 25 percent of the retry time.
7015
+ const jitter = 1 - Math.random() * 0.25;
7016
+ return sleepSeconds * jitter * 1000;
7017
+ }
7018
+ async buildRequest(inputOptions, { retryCount = 0 } = {}) {
7019
+ const options = { ...inputOptions };
7020
+ const { method, path, query, defaultBaseURL } = options;
7021
+ const url = this.buildURL(path, query, defaultBaseURL);
7022
+ if ('timeout' in options)
7023
+ validatePositiveInteger('timeout', options.timeout);
7024
+ options.timeout = options.timeout ?? this.timeout;
7025
+ const { bodyHeaders, body } = this.buildBody({ options });
7026
+ const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
7027
+ const req = {
7028
+ method,
7029
+ headers: reqHeaders,
7030
+ ...(options.signal && { signal: options.signal }),
7031
+ ...(globalThis.ReadableStream &&
7032
+ body instanceof globalThis.ReadableStream && { duplex: 'half' }),
7033
+ ...(body && { body }),
7034
+ ...(this.fetchOptions ?? {}),
7035
+ ...(options.fetchOptions ?? {}),
7036
+ };
7037
+ return { req, url, timeout: options.timeout };
7038
+ }
7039
+ async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
7040
+ let idempotencyHeaders = {};
7041
+ if (this.idempotencyHeader && method !== 'get') {
7042
+ if (!options.idempotencyKey)
7043
+ options.idempotencyKey = this.defaultIdempotencyKey();
7044
+ idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
7045
+ }
7046
+ const headers = buildHeaders([
7047
+ idempotencyHeaders,
7048
+ {
7049
+ Accept: 'application/json',
7050
+ 'User-Agent': this.getUserAgent(),
7051
+ 'X-Stainless-Retry-Count': String(retryCount),
7052
+ ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
7053
+ ...getPlatformHeaders(),
7054
+ },
7055
+ await this.authHeaders(options),
7056
+ this._options.defaultHeaders,
7057
+ bodyHeaders,
7058
+ options.headers,
7059
+ ]);
7060
+ this.validateHeaders(headers);
7061
+ return headers.values;
7062
+ }
7063
+ buildBody({ options: { body, headers: rawHeaders } }) {
7064
+ if (!body) {
7065
+ return { bodyHeaders: undefined, body: undefined };
7066
+ }
7067
+ const headers = buildHeaders([rawHeaders]);
7068
+ if (
7069
+ // Pass raw type verbatim
7070
+ ArrayBuffer.isView(body) ||
7071
+ body instanceof ArrayBuffer ||
7072
+ body instanceof DataView ||
7073
+ (typeof body === 'string' &&
7074
+ // Preserve legacy string encoding behavior for now
7075
+ headers.values.has('content-type')) ||
7076
+ // `Blob` is superset of `File`
7077
+ (globalThis.Blob && body instanceof globalThis.Blob) ||
7078
+ // `FormData` -> `multipart/form-data`
7079
+ body instanceof FormData ||
7080
+ // `URLSearchParams` -> `application/x-www-form-urlencoded`
7081
+ body instanceof URLSearchParams ||
7082
+ // Send chunked stream (each chunk has own `length`)
7083
+ (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
7084
+ return { bodyHeaders: undefined, body: body };
7085
+ }
7086
+ else if (typeof body === 'object' &&
7087
+ (Symbol.asyncIterator in body ||
7088
+ (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
7089
+ return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
7650
7090
  }
7651
7091
  else {
7652
- if (typeof secret !== "string") {
7653
- throw new Error("Expected secret to be of type string");
7654
- }
7655
- if (secret.startsWith(Webhook.prefix)) {
7656
- secret = secret.substring(Webhook.prefix.length);
7657
- }
7658
- this.key = base64.decode(secret);
7092
+ return __classPrivateFieldGet(this, _DodoPayments_encoder, "f").call(this, { body, headers });
7659
7093
  }
7660
7094
  }
7661
- verify(payload, headers_) {
7662
- const headers = {};
7663
- for (const key of Object.keys(headers_)) {
7664
- headers[key.toLowerCase()] = headers_[key];
7665
- }
7666
- const msgId = headers["webhook-id"];
7667
- const msgSignature = headers["webhook-signature"];
7668
- const msgTimestamp = headers["webhook-timestamp"];
7669
- if (!msgSignature || !msgId || !msgTimestamp) {
7670
- throw new WebhookVerificationError("Missing required headers");
7095
+ }
7096
+ _a = DodoPayments, _DodoPayments_encoder = new WeakMap(), _DodoPayments_instances = new WeakSet(), _DodoPayments_baseURLOverridden = function _DodoPayments_baseURLOverridden() {
7097
+ return this.baseURL !== environments[this._options.environment || 'live_mode'];
7098
+ };
7099
+ DodoPayments.DodoPayments = _a;
7100
+ DodoPayments.DEFAULT_TIMEOUT = 60000; // 1 minute
7101
+ DodoPayments.DodoPaymentsError = DodoPaymentsError;
7102
+ DodoPayments.APIError = APIError;
7103
+ DodoPayments.APIConnectionError = APIConnectionError;
7104
+ DodoPayments.APIConnectionTimeoutError = APIConnectionTimeoutError;
7105
+ DodoPayments.APIUserAbortError = APIUserAbortError;
7106
+ DodoPayments.NotFoundError = NotFoundError;
7107
+ DodoPayments.ConflictError = ConflictError;
7108
+ DodoPayments.RateLimitError = RateLimitError;
7109
+ DodoPayments.BadRequestError = BadRequestError;
7110
+ DodoPayments.AuthenticationError = AuthenticationError;
7111
+ DodoPayments.InternalServerError = InternalServerError;
7112
+ DodoPayments.PermissionDeniedError = PermissionDeniedError;
7113
+ DodoPayments.UnprocessableEntityError = UnprocessableEntityError;
7114
+ DodoPayments.toFile = toFile;
7115
+ DodoPayments.CheckoutSessions = CheckoutSessions;
7116
+ DodoPayments.Payments = Payments;
7117
+ DodoPayments.Subscriptions = Subscriptions;
7118
+ DodoPayments.Invoices = Invoices;
7119
+ DodoPayments.Licenses = Licenses;
7120
+ DodoPayments.LicenseKeys = LicenseKeys;
7121
+ DodoPayments.LicenseKeyInstances = LicenseKeyInstances;
7122
+ DodoPayments.Customers = Customers;
7123
+ DodoPayments.Refunds = Refunds;
7124
+ DodoPayments.Disputes = Disputes;
7125
+ DodoPayments.Payouts = Payouts;
7126
+ DodoPayments.Products = Products;
7127
+ DodoPayments.Misc = Misc;
7128
+ DodoPayments.Discounts = Discounts;
7129
+ DodoPayments.Addons = Addons;
7130
+ DodoPayments.Brands = Brands;
7131
+ DodoPayments.Webhooks = Webhooks$1;
7132
+ DodoPayments.WebhookEvents = WebhookEvents;
7133
+ DodoPayments.UsageEvents = UsageEvents;
7134
+ DodoPayments.Meters = Meters;
7135
+
7136
+ // src/checkout/checkout.ts
7137
+ var checkoutQuerySchema = objectType({
7138
+ productId: stringType(),
7139
+ quantity: stringType().optional(),
7140
+ // Customer fields
7141
+ fullName: stringType().optional(),
7142
+ firstName: stringType().optional(),
7143
+ lastName: stringType().optional(),
7144
+ email: stringType().optional(),
7145
+ country: stringType().optional(),
7146
+ addressLine: stringType().optional(),
7147
+ city: stringType().optional(),
7148
+ state: stringType().optional(),
7149
+ zipCode: stringType().optional(),
7150
+ // Disable flags
7151
+ disableFullName: stringType().optional(),
7152
+ disableFirstName: stringType().optional(),
7153
+ disableLastName: stringType().optional(),
7154
+ disableEmail: stringType().optional(),
7155
+ disableCountry: stringType().optional(),
7156
+ disableAddressLine: stringType().optional(),
7157
+ disableCity: stringType().optional(),
7158
+ disableState: stringType().optional(),
7159
+ disableZipCode: stringType().optional(),
7160
+ // Advanced controls
7161
+ paymentCurrency: stringType().optional(),
7162
+ showCurrencySelector: stringType().optional(),
7163
+ paymentAmount: stringType().optional(),
7164
+ showDiscounts: stringType().optional()
7165
+ // Metadata (allow any key starting with metadata_)
7166
+ // We'll handle metadata separately in the handler
7167
+ }).catchall(unknownType());
7168
+ var dynamicCheckoutBodySchema = objectType({
7169
+ // For subscription
7170
+ product_id: stringType().optional(),
7171
+ quantity: numberType().optional(),
7172
+ // For one-time payment
7173
+ product_cart: arrayType(
7174
+ objectType({
7175
+ product_id: stringType(),
7176
+ quantity: numberType()
7177
+ })
7178
+ ).optional(),
7179
+ // Common fields
7180
+ billing: objectType({
7181
+ city: stringType(),
7182
+ country: stringType(),
7183
+ state: stringType(),
7184
+ street: stringType(),
7185
+ zipcode: stringType()
7186
+ }),
7187
+ customer: objectType({
7188
+ customer_id: stringType().optional(),
7189
+ email: stringType().optional(),
7190
+ name: stringType().optional()
7191
+ }),
7192
+ discount_id: stringType().optional(),
7193
+ addons: arrayType(
7194
+ objectType({
7195
+ addon_id: stringType(),
7196
+ quantity: numberType()
7197
+ })
7198
+ ).optional(),
7199
+ metadata: recordType(stringType(), stringType()).optional(),
7200
+ currency: stringType().optional()
7201
+ // Allow any additional fields (for future compatibility)
7202
+ }).catchall(unknownType());
7203
+ var checkoutSessionProductCartItemSchema = objectType({
7204
+ product_id: stringType().min(1, "Product ID is required"),
7205
+ quantity: numberType().int().positive("Quantity must be a positive integer"),
7206
+ addons: arrayType(
7207
+ objectType({
7208
+ addon_id: stringType(),
7209
+ quantity: numberType().int().nonnegative()
7210
+ })
7211
+ ).optional(),
7212
+ amount: numberType().int().nonnegative(
7213
+ "Amount must be a non-negative integer (for pay-what-you-want products)"
7214
+ ).optional()
7215
+ });
7216
+ var checkoutSessionCustomerSchema = unionType([
7217
+ objectType({
7218
+ email: stringType().email(),
7219
+ name: stringType().min(1).optional(),
7220
+ phone_number: stringType().optional()
7221
+ }),
7222
+ objectType({
7223
+ customer_id: stringType()
7224
+ })
7225
+ ]).optional();
7226
+ var checkoutSessionBillingAddressSchema = objectType({
7227
+ street: stringType().optional(),
7228
+ city: stringType().optional(),
7229
+ state: stringType().optional(),
7230
+ country: stringType().length(2, "Country must be a 2-letter ISO code"),
7231
+ zipcode: stringType().optional()
7232
+ }).optional();
7233
+ var paymentMethodTypeSchema = enumType([
7234
+ "credit",
7235
+ "debit",
7236
+ "upi_collect",
7237
+ "upi_intent",
7238
+ "apple_pay",
7239
+ "cashapp",
7240
+ "google_pay",
7241
+ "multibanco",
7242
+ "bancontact_card",
7243
+ "eps",
7244
+ "ideal",
7245
+ "przelewy24",
7246
+ "paypal",
7247
+ "affirm",
7248
+ "klarna",
7249
+ "sepa",
7250
+ "ach",
7251
+ "amazon_pay",
7252
+ "afterpay_clearpay"
7253
+ ]);
7254
+ var checkoutSessionCustomizationSchema = objectType({
7255
+ theme: enumType(["light", "dark", "system"]).optional(),
7256
+ show_order_details: booleanType().optional(),
7257
+ show_on_demand_tag: booleanType().optional(),
7258
+ force_language: stringType().optional()
7259
+ }).optional();
7260
+ var checkoutSessionFeatureFlagsSchema = objectType({
7261
+ allow_currency_selection: booleanType().optional(),
7262
+ allow_discount_code: booleanType().optional(),
7263
+ allow_phone_number_collection: booleanType().optional(),
7264
+ allow_tax_id: booleanType().optional(),
7265
+ always_create_new_customer: booleanType().optional()
7266
+ }).optional();
7267
+ var checkoutSessionOnDemandSchema = objectType({
7268
+ mandate_only: booleanType(),
7269
+ product_price: numberType().int().optional(),
7270
+ product_currency: stringType().length(3).optional(),
7271
+ product_description: stringType().optional(),
7272
+ adaptive_currency_fees_inclusive: booleanType().optional()
7273
+ }).optional();
7274
+ var checkoutSessionSubscriptionDataSchema = objectType({
7275
+ trial_period_days: numberType().int().nonnegative().optional(),
7276
+ on_demand: checkoutSessionOnDemandSchema
7277
+ }).optional();
7278
+ var checkoutSessionPayloadSchema = objectType({
7279
+ // Required fields
7280
+ product_cart: arrayType(checkoutSessionProductCartItemSchema).min(1, "At least one product is required"),
7281
+ // Optional fields
7282
+ customer: checkoutSessionCustomerSchema,
7283
+ billing_address: checkoutSessionBillingAddressSchema,
7284
+ return_url: stringType().url().optional(),
7285
+ allowed_payment_method_types: arrayType(paymentMethodTypeSchema).optional(),
7286
+ billing_currency: stringType().length(3, "Currency must be a 3-letter ISO code").optional(),
7287
+ show_saved_payment_methods: booleanType().optional(),
7288
+ confirm: booleanType().optional(),
7289
+ discount_code: stringType().optional(),
7290
+ metadata: recordType(stringType(), stringType()).optional(),
7291
+ customization: checkoutSessionCustomizationSchema,
7292
+ feature_flags: checkoutSessionFeatureFlagsSchema,
7293
+ subscription_data: checkoutSessionSubscriptionDataSchema,
7294
+ force_3ds: booleanType().optional()
7295
+ });
7296
+ var checkoutSessionResponseSchema = objectType({
7297
+ session_id: stringType().min(1, "Session ID is required"),
7298
+ checkout_url: stringType().url("Invalid checkout URL")
7299
+ });
7300
+ var createCheckoutSession = async (payload, config) => {
7301
+ const validation = checkoutSessionPayloadSchema.safeParse(payload);
7302
+ if (!validation.success) {
7303
+ throw new Error(
7304
+ `Invalid checkout session payload: ${validation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
7305
+ );
7306
+ }
7307
+ const dodopayments = new DodoPayments({
7308
+ bearerToken: config.bearerToken,
7309
+ environment: config.environment
7310
+ });
7311
+ try {
7312
+ const sdkPayload = {
7313
+ ...validation.data,
7314
+ ...validation.data.billing_address && {
7315
+ billing_address: {
7316
+ ...validation.data.billing_address,
7317
+ country: validation.data.billing_address.country
7318
+ }
7319
+ }
7320
+ };
7321
+ const session = await dodopayments.checkoutSessions.create(
7322
+ sdkPayload
7323
+ );
7324
+ const responseValidation = checkoutSessionResponseSchema.safeParse(session);
7325
+ if (!responseValidation.success) {
7326
+ throw new Error(
7327
+ `Invalid checkout session response from API: ${responseValidation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
7328
+ );
7329
+ }
7330
+ return responseValidation.data;
7331
+ } catch (error) {
7332
+ if (error instanceof Error) {
7333
+ console.error("Dodo Payments Checkout Session API Error:", {
7334
+ message: error.message,
7335
+ payload: validation.data,
7336
+ config: {
7337
+ environment: config.environment,
7338
+ hasBearerToken: !!config.bearerToken
7339
+ }
7340
+ });
7341
+ throw new Error(`Failed to create checkout session: ${error.message}`);
7342
+ }
7343
+ console.error("Unknown error creating checkout session:", error);
7344
+ throw new Error(
7345
+ "Failed to create checkout session due to an unknown error"
7346
+ );
7347
+ }
7348
+ };
7349
+ var buildCheckoutUrl = async ({
7350
+ queryParams,
7351
+ body,
7352
+ sessionPayload,
7353
+ returnUrl,
7354
+ bearerToken,
7355
+ environment,
7356
+ type = "static"
7357
+ }) => {
7358
+ if (type === "session") {
7359
+ if (!sessionPayload) {
7360
+ throw new Error("sessionPayload is required when type is 'session'");
7361
+ }
7362
+ const session = await createCheckoutSession(sessionPayload, {
7363
+ bearerToken,
7364
+ environment
7365
+ });
7366
+ return session.checkout_url;
7367
+ }
7368
+ const inputData = type === "dynamic" ? body : queryParams;
7369
+ let parseResult;
7370
+ if (type === "dynamic") {
7371
+ parseResult = dynamicCheckoutBodySchema.safeParse(inputData);
7372
+ } else {
7373
+ parseResult = checkoutQuerySchema.safeParse(inputData);
7374
+ }
7375
+ const { success, data, error } = parseResult;
7376
+ if (!success) {
7377
+ throw new Error(
7378
+ `Invalid ${type === "dynamic" ? "body" : "query parameters"}.
7379
+ ${error.message}`
7380
+ );
7381
+ }
7382
+ if (type !== "dynamic") {
7383
+ const {
7384
+ productId,
7385
+ quantity: quantity2,
7386
+ fullName,
7387
+ firstName,
7388
+ lastName,
7389
+ email,
7390
+ country,
7391
+ addressLine,
7392
+ city,
7393
+ state,
7394
+ zipCode,
7395
+ disableFullName,
7396
+ disableFirstName,
7397
+ disableLastName,
7398
+ disableEmail,
7399
+ disableCountry,
7400
+ disableAddressLine,
7401
+ disableCity,
7402
+ disableState,
7403
+ disableZipCode,
7404
+ paymentCurrency,
7405
+ showCurrencySelector,
7406
+ paymentAmount,
7407
+ showDiscounts
7408
+ // metadata handled below
7409
+ } = data;
7410
+ const dodopayments2 = new DodoPayments({
7411
+ bearerToken,
7412
+ environment
7413
+ });
7414
+ if (!productId) throw new Error("Missing required field: productId");
7415
+ try {
7416
+ await dodopayments2.products.retrieve(productId);
7417
+ } catch (err) {
7418
+ console.error(err);
7419
+ throw new Error("Product not found");
7420
+ }
7421
+ const url = new URL(
7422
+ `${environment === "test_mode" ? "https://test.checkout.dodopayments.com" : "https://checkout.dodopayments.com"}/buy/${productId}`
7423
+ );
7424
+ url.searchParams.set("quantity", quantity2 ? String(quantity2) : "1");
7425
+ if (returnUrl) url.searchParams.set("redirect_url", returnUrl);
7426
+ if (fullName) url.searchParams.set("fullName", String(fullName));
7427
+ if (firstName) url.searchParams.set("firstName", String(firstName));
7428
+ if (lastName) url.searchParams.set("lastName", String(lastName));
7429
+ if (email) url.searchParams.set("email", String(email));
7430
+ if (country) url.searchParams.set("country", String(country));
7431
+ if (addressLine) url.searchParams.set("addressLine", String(addressLine));
7432
+ if (city) url.searchParams.set("city", String(city));
7433
+ if (state) url.searchParams.set("state", String(state));
7434
+ if (zipCode) url.searchParams.set("zipCode", String(zipCode));
7435
+ if (disableFullName === "true")
7436
+ url.searchParams.set("disableFullName", "true");
7437
+ if (disableFirstName === "true")
7438
+ url.searchParams.set("disableFirstName", "true");
7439
+ if (disableLastName === "true")
7440
+ url.searchParams.set("disableLastName", "true");
7441
+ if (disableEmail === "true") url.searchParams.set("disableEmail", "true");
7442
+ if (disableCountry === "true")
7443
+ url.searchParams.set("disableCountry", "true");
7444
+ if (disableAddressLine === "true")
7445
+ url.searchParams.set("disableAddressLine", "true");
7446
+ if (disableCity === "true") url.searchParams.set("disableCity", "true");
7447
+ if (disableState === "true") url.searchParams.set("disableState", "true");
7448
+ if (disableZipCode === "true")
7449
+ url.searchParams.set("disableZipCode", "true");
7450
+ if (paymentCurrency)
7451
+ url.searchParams.set("paymentCurrency", String(paymentCurrency));
7452
+ if (showCurrencySelector)
7453
+ url.searchParams.set(
7454
+ "showCurrencySelector",
7455
+ String(showCurrencySelector)
7456
+ );
7457
+ if (paymentAmount)
7458
+ url.searchParams.set("paymentAmount", String(paymentAmount));
7459
+ if (showDiscounts)
7460
+ url.searchParams.set("showDiscounts", String(showDiscounts));
7461
+ for (const [key, value] of Object.entries(queryParams || {})) {
7462
+ if (key.startsWith("metadata_") && value && typeof value !== "object") {
7463
+ url.searchParams.set(key, String(value));
7464
+ }
7465
+ }
7466
+ return url.toString();
7467
+ }
7468
+ const dyn = data;
7469
+ const {
7470
+ product_id,
7471
+ product_cart,
7472
+ quantity,
7473
+ billing,
7474
+ customer,
7475
+ addons,
7476
+ metadata,
7477
+ allowed_payment_method_types,
7478
+ billing_currency,
7479
+ discount_code,
7480
+ on_demand,
7481
+ return_url: bodyReturnUrl,
7482
+ show_saved_payment_methods,
7483
+ tax_id,
7484
+ trial_period_days
7485
+ } = dyn;
7486
+ const dodopayments = new DodoPayments({
7487
+ bearerToken,
7488
+ environment
7489
+ });
7490
+ let isSubscription = false;
7491
+ let productIdToFetch = product_id;
7492
+ if (!product_id && product_cart && product_cart.length > 0) {
7493
+ productIdToFetch = product_cart[0].product_id;
7494
+ }
7495
+ if (!productIdToFetch)
7496
+ throw new Error(
7497
+ "Missing required field: product_id or product_cart[0].product_id"
7498
+ );
7499
+ let product;
7500
+ try {
7501
+ product = await dodopayments.products.retrieve(productIdToFetch);
7502
+ } catch (err) {
7503
+ console.error(err);
7504
+ throw new Error("Product not found");
7505
+ }
7506
+ isSubscription = Boolean(product.is_recurring);
7507
+ if (isSubscription && !product_id)
7508
+ throw new Error("Missing required field: product_id for subscription");
7509
+ if (!billing) throw new Error("Missing required field: billing");
7510
+ if (!customer) throw new Error("Missing required field: customer");
7511
+ if (isSubscription) {
7512
+ const subscriptionPayload = {
7513
+ billing,
7514
+ customer,
7515
+ product_id,
7516
+ quantity: quantity ? Number(quantity) : 1
7517
+ };
7518
+ if (metadata) subscriptionPayload.metadata = metadata;
7519
+ if (discount_code) subscriptionPayload.discount_code = discount_code;
7520
+ if (addons) subscriptionPayload.addons = addons;
7521
+ if (allowed_payment_method_types)
7522
+ subscriptionPayload.allowed_payment_method_types = allowed_payment_method_types;
7523
+ if (billing_currency)
7524
+ subscriptionPayload.billing_currency = billing_currency;
7525
+ if (on_demand) subscriptionPayload.on_demand = on_demand;
7526
+ subscriptionPayload.payment_link = true;
7527
+ if (bodyReturnUrl) {
7528
+ subscriptionPayload.return_url = bodyReturnUrl;
7529
+ } else if (returnUrl) {
7530
+ subscriptionPayload.return_url = returnUrl;
7531
+ }
7532
+ if (show_saved_payment_methods)
7533
+ subscriptionPayload.show_saved_payment_methods = show_saved_payment_methods;
7534
+ if (tax_id) subscriptionPayload.tax_id = tax_id;
7535
+ if (trial_period_days)
7536
+ subscriptionPayload.trial_period_days = trial_period_days;
7537
+ let subscription;
7538
+ try {
7539
+ subscription = await dodopayments.subscriptions.create(subscriptionPayload);
7540
+ } catch (err) {
7541
+ console.error("Error when creating subscription", err);
7542
+ throw new Error(err instanceof Error ? err.message : String(err));
7543
+ }
7544
+ if (!subscription || !subscription.payment_link) {
7545
+ throw new Error(
7546
+ "No payment link returned from Dodo Payments API (subscription). Make sure to set payment_link as true in payload"
7547
+ );
7548
+ }
7549
+ return subscription.payment_link;
7550
+ } else {
7551
+ let cart = product_cart;
7552
+ if (!cart && product_id) {
7553
+ cart = [
7554
+ { product_id, quantity: quantity ? Number(quantity) : 1 }
7555
+ ];
7556
+ }
7557
+ if (!cart || cart.length === 0)
7558
+ throw new Error("Missing required field: product_cart or product_id");
7559
+ const paymentPayload = {
7560
+ billing,
7561
+ customer,
7562
+ product_cart: cart
7563
+ };
7564
+ if (metadata) paymentPayload.metadata = metadata;
7565
+ paymentPayload.payment_link = true;
7566
+ if (allowed_payment_method_types)
7567
+ paymentPayload.allowed_payment_method_types = allowed_payment_method_types;
7568
+ if (billing_currency) paymentPayload.billing_currency = billing_currency;
7569
+ if (discount_code) paymentPayload.discount_code = discount_code;
7570
+ if (bodyReturnUrl) {
7571
+ paymentPayload.return_url = bodyReturnUrl;
7572
+ } else if (returnUrl) {
7573
+ paymentPayload.return_url = returnUrl;
7574
+ }
7575
+ if (show_saved_payment_methods)
7576
+ paymentPayload.show_saved_payment_methods = show_saved_payment_methods;
7577
+ if (tax_id) paymentPayload.tax_id = tax_id;
7578
+ let payment;
7579
+ try {
7580
+ payment = await dodopayments.payments.create(paymentPayload);
7581
+ } catch (err) {
7582
+ console.error("Error when creating payment link", err);
7583
+ throw new Error(err instanceof Error ? err.message : String(err));
7584
+ }
7585
+ if (!payment || !payment.payment_link) {
7586
+ throw new Error(
7587
+ "No payment link returned from Dodo Payments API. Make sure to set payment_link as true in payload."
7588
+ );
7589
+ }
7590
+ return payment.payment_link;
7591
+ }
7592
+ };
7593
+
7594
+ const Checkout = (config) => {
7595
+ const getHandler = async (event) => {
7596
+ const searchParams = event.url.searchParams;
7597
+ const queryParams = Object.fromEntries(searchParams);
7598
+ if (!queryParams.productId) {
7599
+ throw error(400, "Please provide productId query parameter");
7671
7600
  }
7672
- const timestamp = this.verifyTimestamp(msgTimestamp);
7673
- const computedSignature = this.sign(msgId, timestamp, payload);
7674
- const expectedSignature = computedSignature.split(",")[1];
7675
- const passedSignatures = msgSignature.split(" ");
7676
- const encoder = new globalThis.TextEncoder();
7677
- for (const versionedSignature of passedSignatures) {
7678
- const [version, signature] = versionedSignature.split(",");
7679
- if (version !== "v1") {
7680
- continue;
7681
- }
7682
- if ((0, timing_safe_equal_1.timingSafeEqual)(encoder.encode(signature), encoder.encode(expectedSignature))) {
7683
- return JSON.parse(payload.toString());
7601
+ const { success, data, error: zodError, } = checkoutQuerySchema.safeParse(queryParams);
7602
+ if (!success) {
7603
+ if (zodError.errors.some((e) => e.path.toString() === "productId")) {
7604
+ throw error(400, "Please provide productId query parameter");
7684
7605
  }
7606
+ throw error(400, `Invalid query parameters.\n ${zodError.message}`);
7685
7607
  }
7686
- throw new WebhookVerificationError("No matching signature found");
7687
- }
7688
- sign(msgId, timestamp, payload) {
7689
- if (typeof payload === "string") ;
7690
- else if (payload.constructor.name === "Buffer") {
7691
- payload = payload.toString();
7608
+ let urlStr = "";
7609
+ try {
7610
+ urlStr = await buildCheckoutUrl({ queryParams: data, ...config });
7692
7611
  }
7693
- else {
7694
- throw new Error("Expected payload to be of type string or Buffer.");
7612
+ catch (err) {
7613
+ throw error(400, err.message);
7695
7614
  }
7696
- const encoder = new TextEncoder();
7697
- const timestampNumber = Math.floor(timestamp.getTime() / 1000);
7698
- const toSign = encoder.encode(`${msgId}.${timestampNumber}.${payload}`);
7699
- const expectedSignature = base64.encode(sha256.hmac(this.key, toSign));
7700
- return `v1,${expectedSignature}`;
7701
- }
7702
- verifyTimestamp(timestampHeader) {
7703
- const now = Math.floor(Date.now() / 1000);
7704
- const timestamp = parseInt(timestampHeader, 10);
7705
- if (isNaN(timestamp)) {
7706
- throw new WebhookVerificationError("Invalid Signature Headers");
7615
+ return Response.json({ checkout_url: urlStr });
7616
+ };
7617
+ const postHandler = async (event) => {
7618
+ let body;
7619
+ try {
7620
+ body = await event.request.json();
7707
7621
  }
7708
- if (now - timestamp > WEBHOOK_TOLERANCE_IN_SECONDS) {
7709
- throw new WebhookVerificationError("Message timestamp too old");
7622
+ catch (e) {
7623
+ throw error(400, "Invalid JSON body");
7710
7624
  }
7711
- if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) {
7712
- throw new WebhookVerificationError("Message timestamp too new");
7625
+ if (config.type === "dynamic") {
7626
+ // Handle dynamic checkout
7627
+ const { success, data, error: zodError, } = dynamicCheckoutBodySchema.safeParse(body);
7628
+ if (!success) {
7629
+ throw error(400, `Invalid request body.\n ${zodError.message}`);
7630
+ }
7631
+ let urlStr = "";
7632
+ try {
7633
+ urlStr = await buildCheckoutUrl({
7634
+ body: data,
7635
+ ...config,
7636
+ type: "dynamic",
7637
+ });
7638
+ }
7639
+ catch (err) {
7640
+ throw error(400, err.message);
7641
+ }
7642
+ return Response.json({ checkout_url: urlStr });
7713
7643
  }
7714
- return new Date(timestamp * 1000);
7715
- }
7716
- }
7717
- Webhook_1 = dist.Webhook = Webhook;
7718
- Webhook.prefix = "whsec_";
7644
+ else {
7645
+ // Handle checkout session
7646
+ const { success, data, error: zodError, } = checkoutSessionPayloadSchema.safeParse(body);
7647
+ if (!success) {
7648
+ throw error(400, `Invalid checkout session payload.\n ${zodError.message}`);
7649
+ }
7650
+ let urlStr = "";
7651
+ try {
7652
+ urlStr = await buildCheckoutUrl({
7653
+ sessionPayload: data,
7654
+ ...config,
7655
+ type: "session",
7656
+ });
7657
+ }
7658
+ catch (err) {
7659
+ throw error(400, err.message);
7660
+ }
7661
+ return Response.json({ checkout_url: urlStr });
7662
+ }
7663
+ };
7664
+ // SvelteKit expects named exports for HTTP verbs
7665
+ return {
7666
+ GET: getHandler,
7667
+ POST: postHandler,
7668
+ };
7669
+ };
7719
7670
 
7671
+ // src/schemas/webhook.ts
7720
7672
  var PaymentSchema = objectType({
7721
- payload_type: literalType("Payment"),
7722
- billing: objectType({
7723
- city: stringType().nullable(),
7724
- country: stringType().nullable(),
7725
- state: stringType().nullable(),
7726
- street: stringType().nullable(),
7727
- zipcode: stringType().nullable(),
7728
- }),
7729
- brand_id: stringType(),
7730
- business_id: stringType(),
7731
- card_issuing_country: stringType().nullable(),
7732
- card_last_four: stringType().nullable(),
7733
- card_network: stringType().nullable(),
7734
- card_type: stringType().nullable(),
7735
- created_at: stringType().transform(function (d) { return new Date(d); }),
7736
- currency: stringType(),
7737
- customer: objectType({
7738
- customer_id: stringType(),
7739
- email: stringType(),
7740
- name: stringType().nullable(),
7741
- }),
7742
- digital_products_delivered: booleanType(),
7743
- discount_id: stringType().nullable(),
7744
- disputes: arrayType(objectType({
7745
- amount: stringType(),
7746
- business_id: stringType(),
7747
- created_at: stringType().transform(function (d) { return new Date(d); }),
7748
- currency: stringType(),
7749
- dispute_id: stringType(),
7750
- dispute_stage: enumType([
7751
- "pre_dispute",
7752
- "dispute_opened",
7753
- "dispute_won",
7754
- "dispute_lost",
7755
- ]),
7756
- dispute_status: enumType([
7757
- "dispute_opened",
7758
- "dispute_won",
7759
- "dispute_lost",
7760
- "dispute_accepted",
7761
- "dispute_cancelled",
7762
- "dispute_challenged",
7763
- ]),
7764
- payment_id: stringType(),
7765
- remarks: stringType().nullable(),
7766
- }))
7767
- .nullable(),
7768
- error_code: stringType().nullable(),
7769
- error_message: stringType().nullable(),
7770
- metadata: recordType(anyType()).nullable(),
7771
- payment_id: stringType(),
7772
- payment_link: stringType().nullable(),
7773
- payment_method: stringType().nullable(),
7774
- payment_method_type: stringType().nullable(),
7775
- product_cart: arrayType(objectType({
7776
- product_id: stringType(),
7777
- quantity: numberType(),
7778
- }))
7779
- .nullable(),
7780
- refunds: arrayType(objectType({
7781
- amount: numberType(),
7782
- business_id: stringType(),
7783
- created_at: stringType().transform(function (d) { return new Date(d); }),
7784
- currency: stringType(),
7785
- is_partial: booleanType(),
7786
- payment_id: stringType(),
7787
- reason: stringType().nullable(),
7788
- refund_id: stringType(),
7789
- status: enumType(["succeeded", "failed", "pending"]),
7790
- }))
7791
- .nullable(),
7792
- settlement_amount: numberType(),
7793
- settlement_currency: stringType(),
7794
- settlement_tax: numberType().nullable(),
7795
- status: enumType(["succeeded", "failed", "pending", "processing", "cancelled"]),
7796
- subscription_id: stringType().nullable(),
7797
- tax: numberType().nullable(),
7798
- total_amount: numberType(),
7799
- updated_at: stringType()
7800
- .transform(function (d) { return new Date(d); })
7801
- .nullable(),
7802
- });
7803
- var SubscriptionSchema = objectType({
7804
- payload_type: literalType("Subscription"),
7805
- addons: arrayType(objectType({
7806
- addon_id: stringType(),
7807
- quantity: numberType(),
7808
- }))
7809
- .nullable(),
7810
- billing: objectType({
7811
- city: stringType().nullable(),
7812
- country: stringType().nullable(),
7813
- state: stringType().nullable(),
7814
- street: stringType().nullable(),
7815
- zipcode: stringType().nullable(),
7816
- }),
7817
- cancel_at_next_billing_date: booleanType(),
7818
- cancelled_at: stringType()
7819
- .transform(function (d) { return new Date(d); })
7820
- .nullable(),
7821
- created_at: stringType().transform(function (d) { return new Date(d); }),
7822
- currency: stringType(),
7823
- customer: objectType({
7824
- customer_id: stringType(),
7825
- email: stringType(),
7826
- name: stringType().nullable(),
7827
- }),
7828
- discount_id: stringType().nullable(),
7829
- metadata: recordType(anyType()).nullable(),
7830
- next_billing_date: stringType()
7831
- .transform(function (d) { return new Date(d); })
7832
- .nullable(),
7833
- on_demand: booleanType(),
7834
- payment_frequency_count: numberType(),
7835
- payment_frequency_interval: enumType(["Day", "Week", "Month", "Year"]),
7836
- previous_billing_date: stringType()
7837
- .transform(function (d) { return new Date(d); })
7838
- .nullable(),
7839
- product_id: stringType(),
7840
- quantity: numberType(),
7841
- recurring_pre_tax_amount: numberType(),
7842
- status: enumType([
7843
- "pending",
7844
- "active",
7845
- "on_hold",
7846
- "paused",
7847
- "cancelled",
7848
- "expired",
7849
- "failed",
7850
- ]),
7851
- subscription_id: stringType(),
7852
- subscription_period_count: numberType(),
7853
- subscription_period_interval: enumType(["Day", "Week", "Month", "Year"]),
7854
- tax_inclusive: booleanType(),
7855
- trial_period_days: numberType(),
7856
- });
7857
- var RefundSchema = objectType({
7858
- payload_type: literalType("Refund"),
7859
- amount: numberType(),
7860
- business_id: stringType(),
7861
- created_at: stringType().transform(function (d) { return new Date(d); }),
7862
- currency: stringType(),
7863
- is_partial: booleanType(),
7864
- payment_id: stringType(),
7865
- reason: stringType().nullable(),
7866
- refund_id: stringType(),
7867
- status: enumType(["succeeded", "failed", "pending"]),
7868
- });
7869
- var DisputeSchema = objectType({
7870
- payload_type: literalType("Dispute"),
7871
- amount: stringType(),
7872
- business_id: stringType(),
7873
- created_at: stringType().transform(function (d) { return new Date(d); }),
7874
- currency: stringType(),
7875
- dispute_id: stringType(),
7876
- dispute_stage: enumType([
7673
+ payload_type: literalType("Payment"),
7674
+ billing: objectType({
7675
+ city: stringType().nullable(),
7676
+ country: stringType().nullable(),
7677
+ state: stringType().nullable(),
7678
+ street: stringType().nullable(),
7679
+ zipcode: stringType().nullable()
7680
+ }),
7681
+ brand_id: stringType(),
7682
+ business_id: stringType(),
7683
+ card_issuing_country: stringType().nullable(),
7684
+ card_last_four: stringType().nullable(),
7685
+ card_network: stringType().nullable(),
7686
+ card_type: stringType().nullable(),
7687
+ created_at: stringType().transform((d) => new Date(d)),
7688
+ currency: stringType(),
7689
+ customer: objectType({
7690
+ customer_id: stringType(),
7691
+ email: stringType(),
7692
+ name: stringType().nullable()
7693
+ }),
7694
+ digital_products_delivered: booleanType(),
7695
+ discount_id: stringType().nullable(),
7696
+ disputes: arrayType(
7697
+ objectType({
7698
+ amount: stringType(),
7699
+ business_id: stringType(),
7700
+ created_at: stringType().transform((d) => new Date(d)),
7701
+ currency: stringType(),
7702
+ dispute_id: stringType(),
7703
+ dispute_stage: enumType([
7877
7704
  "pre_dispute",
7878
7705
  "dispute_opened",
7879
7706
  "dispute_won",
7880
- "dispute_lost",
7881
- ]),
7882
- dispute_status: enumType([
7707
+ "dispute_lost"
7708
+ ]),
7709
+ dispute_status: enumType([
7883
7710
  "dispute_opened",
7884
7711
  "dispute_won",
7885
7712
  "dispute_lost",
7886
7713
  "dispute_accepted",
7887
7714
  "dispute_cancelled",
7888
- "dispute_challenged",
7889
- ]),
7890
- payment_id: stringType(),
7891
- remarks: stringType().nullable(),
7715
+ "dispute_challenged"
7716
+ ]),
7717
+ payment_id: stringType(),
7718
+ remarks: stringType().nullable()
7719
+ })
7720
+ ).nullable(),
7721
+ error_code: stringType().nullable(),
7722
+ error_message: stringType().nullable(),
7723
+ metadata: recordType(anyType()).nullable(),
7724
+ payment_id: stringType(),
7725
+ payment_link: stringType().nullable(),
7726
+ payment_method: stringType().nullable(),
7727
+ payment_method_type: stringType().nullable(),
7728
+ product_cart: arrayType(
7729
+ objectType({
7730
+ product_id: stringType(),
7731
+ quantity: numberType()
7732
+ })
7733
+ ).nullable(),
7734
+ refunds: arrayType(
7735
+ objectType({
7736
+ amount: numberType(),
7737
+ business_id: stringType(),
7738
+ created_at: stringType().transform((d) => new Date(d)),
7739
+ currency: stringType(),
7740
+ is_partial: booleanType(),
7741
+ payment_id: stringType(),
7742
+ reason: stringType().nullable(),
7743
+ refund_id: stringType(),
7744
+ status: enumType(["succeeded", "failed", "pending"])
7745
+ })
7746
+ ).nullable(),
7747
+ settlement_amount: numberType(),
7748
+ settlement_currency: stringType(),
7749
+ settlement_tax: numberType().nullable(),
7750
+ status: enumType(["succeeded", "failed", "pending", "processing", "cancelled"]),
7751
+ subscription_id: stringType().nullable(),
7752
+ tax: numberType().nullable(),
7753
+ total_amount: numberType(),
7754
+ updated_at: stringType().transform((d) => new Date(d)).nullable()
7892
7755
  });
7893
- var LicenseKeySchema = objectType({
7894
- payload_type: literalType("LicenseKey"),
7895
- activations_limit: numberType(),
7896
- business_id: stringType(),
7897
- created_at: stringType().transform(function (d) { return new Date(d); }),
7756
+ var SubscriptionSchema = objectType({
7757
+ payload_type: literalType("Subscription"),
7758
+ addons: arrayType(
7759
+ objectType({
7760
+ addon_id: stringType(),
7761
+ quantity: numberType()
7762
+ })
7763
+ ).nullable(),
7764
+ billing: objectType({
7765
+ city: stringType().nullable(),
7766
+ country: stringType().nullable(),
7767
+ state: stringType().nullable(),
7768
+ street: stringType().nullable(),
7769
+ zipcode: stringType().nullable()
7770
+ }),
7771
+ cancel_at_next_billing_date: booleanType(),
7772
+ cancelled_at: stringType().transform((d) => new Date(d)).nullable(),
7773
+ created_at: stringType().transform((d) => new Date(d)),
7774
+ currency: stringType(),
7775
+ customer: objectType({
7898
7776
  customer_id: stringType(),
7899
- expires_at: stringType()
7900
- .transform(function (d) { return new Date(d); })
7901
- .nullable(),
7902
- id: stringType(),
7903
- instances_count: numberType(),
7904
- key: stringType(),
7905
- payment_id: stringType(),
7906
- product_id: stringType(),
7907
- status: enumType(["active", "inactive", "expired"]),
7908
- subscription_id: stringType().nullable(),
7777
+ email: stringType(),
7778
+ name: stringType().nullable()
7779
+ }),
7780
+ discount_id: stringType().nullable(),
7781
+ metadata: recordType(anyType()).nullable(),
7782
+ next_billing_date: stringType().transform((d) => new Date(d)).nullable(),
7783
+ on_demand: booleanType(),
7784
+ payment_frequency_count: numberType(),
7785
+ payment_frequency_interval: enumType(["Day", "Week", "Month", "Year"]),
7786
+ previous_billing_date: stringType().transform((d) => new Date(d)).nullable(),
7787
+ product_id: stringType(),
7788
+ quantity: numberType(),
7789
+ recurring_pre_tax_amount: numberType(),
7790
+ status: enumType([
7791
+ "pending",
7792
+ "active",
7793
+ "on_hold",
7794
+ "paused",
7795
+ "cancelled",
7796
+ "expired",
7797
+ "failed"
7798
+ ]),
7799
+ subscription_id: stringType(),
7800
+ subscription_period_count: numberType(),
7801
+ subscription_period_interval: enumType(["Day", "Week", "Month", "Year"]),
7802
+ tax_inclusive: booleanType(),
7803
+ trial_period_days: numberType()
7804
+ });
7805
+ var RefundSchema = objectType({
7806
+ payload_type: literalType("Refund"),
7807
+ amount: numberType(),
7808
+ business_id: stringType(),
7809
+ created_at: stringType().transform((d) => new Date(d)),
7810
+ currency: stringType(),
7811
+ is_partial: booleanType(),
7812
+ payment_id: stringType(),
7813
+ reason: stringType().nullable(),
7814
+ refund_id: stringType(),
7815
+ status: enumType(["succeeded", "failed", "pending"])
7816
+ });
7817
+ var DisputeSchema = objectType({
7818
+ payload_type: literalType("Dispute"),
7819
+ amount: stringType(),
7820
+ business_id: stringType(),
7821
+ created_at: stringType().transform((d) => new Date(d)),
7822
+ currency: stringType(),
7823
+ dispute_id: stringType(),
7824
+ dispute_stage: enumType([
7825
+ "pre_dispute",
7826
+ "dispute_opened",
7827
+ "dispute_won",
7828
+ "dispute_lost"
7829
+ ]),
7830
+ dispute_status: enumType([
7831
+ "dispute_opened",
7832
+ "dispute_won",
7833
+ "dispute_lost",
7834
+ "dispute_accepted",
7835
+ "dispute_cancelled",
7836
+ "dispute_challenged"
7837
+ ]),
7838
+ payment_id: stringType(),
7839
+ remarks: stringType().nullable()
7840
+ });
7841
+ var LicenseKeySchema = objectType({
7842
+ payload_type: literalType("LicenseKey"),
7843
+ activations_limit: numberType(),
7844
+ business_id: stringType(),
7845
+ created_at: stringType().transform((d) => new Date(d)),
7846
+ customer_id: stringType(),
7847
+ expires_at: stringType().transform((d) => new Date(d)).nullable(),
7848
+ id: stringType(),
7849
+ instances_count: numberType(),
7850
+ key: stringType(),
7851
+ payment_id: stringType(),
7852
+ product_id: stringType(),
7853
+ status: enumType(["active", "inactive", "expired"]),
7854
+ subscription_id: stringType().nullable()
7909
7855
  });
7910
7856
  var PaymentSucceededPayloadSchema = objectType({
7911
- business_id: stringType(),
7912
- type: literalType("payment.succeeded"),
7913
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7914
- data: PaymentSchema,
7857
+ business_id: stringType(),
7858
+ type: literalType("payment.succeeded"),
7859
+ timestamp: stringType().transform((d) => new Date(d)),
7860
+ data: PaymentSchema
7915
7861
  });
7916
7862
  var PaymentFailedPayloadSchema = objectType({
7917
- business_id: stringType(),
7918
- type: literalType("payment.failed"),
7919
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7920
- data: PaymentSchema,
7863
+ business_id: stringType(),
7864
+ type: literalType("payment.failed"),
7865
+ timestamp: stringType().transform((d) => new Date(d)),
7866
+ data: PaymentSchema
7921
7867
  });
7922
7868
  var PaymentProcessingPayloadSchema = objectType({
7923
- business_id: stringType(),
7924
- type: literalType("payment.processing"),
7925
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7926
- data: PaymentSchema,
7869
+ business_id: stringType(),
7870
+ type: literalType("payment.processing"),
7871
+ timestamp: stringType().transform((d) => new Date(d)),
7872
+ data: PaymentSchema
7927
7873
  });
7928
7874
  var PaymentCancelledPayloadSchema = objectType({
7929
- business_id: stringType(),
7930
- type: literalType("payment.cancelled"),
7931
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7932
- data: PaymentSchema,
7875
+ business_id: stringType(),
7876
+ type: literalType("payment.cancelled"),
7877
+ timestamp: stringType().transform((d) => new Date(d)),
7878
+ data: PaymentSchema
7933
7879
  });
7934
7880
  var RefundSucceededPayloadSchema = objectType({
7935
- business_id: stringType(),
7936
- type: literalType("refund.succeeded"),
7937
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7938
- data: RefundSchema,
7881
+ business_id: stringType(),
7882
+ type: literalType("refund.succeeded"),
7883
+ timestamp: stringType().transform((d) => new Date(d)),
7884
+ data: RefundSchema
7939
7885
  });
7940
7886
  var RefundFailedPayloadSchema = objectType({
7941
- business_id: stringType(),
7942
- type: literalType("refund.failed"),
7943
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7944
- data: RefundSchema,
7887
+ business_id: stringType(),
7888
+ type: literalType("refund.failed"),
7889
+ timestamp: stringType().transform((d) => new Date(d)),
7890
+ data: RefundSchema
7945
7891
  });
7946
7892
  var DisputeOpenedPayloadSchema = objectType({
7947
- business_id: stringType(),
7948
- type: literalType("dispute.opened"),
7949
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7950
- data: DisputeSchema,
7893
+ business_id: stringType(),
7894
+ type: literalType("dispute.opened"),
7895
+ timestamp: stringType().transform((d) => new Date(d)),
7896
+ data: DisputeSchema
7951
7897
  });
7952
7898
  var DisputeExpiredPayloadSchema = objectType({
7953
- business_id: stringType(),
7954
- type: literalType("dispute.expired"),
7955
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7956
- data: DisputeSchema,
7899
+ business_id: stringType(),
7900
+ type: literalType("dispute.expired"),
7901
+ timestamp: stringType().transform((d) => new Date(d)),
7902
+ data: DisputeSchema
7957
7903
  });
7958
7904
  var DisputeAcceptedPayloadSchema = objectType({
7959
- business_id: stringType(),
7960
- type: literalType("dispute.accepted"),
7961
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7962
- data: DisputeSchema,
7905
+ business_id: stringType(),
7906
+ type: literalType("dispute.accepted"),
7907
+ timestamp: stringType().transform((d) => new Date(d)),
7908
+ data: DisputeSchema
7963
7909
  });
7964
7910
  var DisputeCancelledPayloadSchema = objectType({
7965
- business_id: stringType(),
7966
- type: literalType("dispute.cancelled"),
7967
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7968
- data: DisputeSchema,
7911
+ business_id: stringType(),
7912
+ type: literalType("dispute.cancelled"),
7913
+ timestamp: stringType().transform((d) => new Date(d)),
7914
+ data: DisputeSchema
7969
7915
  });
7970
7916
  var DisputeChallengedPayloadSchema = objectType({
7971
- business_id: stringType(),
7972
- type: literalType("dispute.challenged"),
7973
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7974
- data: DisputeSchema,
7917
+ business_id: stringType(),
7918
+ type: literalType("dispute.challenged"),
7919
+ timestamp: stringType().transform((d) => new Date(d)),
7920
+ data: DisputeSchema
7975
7921
  });
7976
7922
  var DisputeWonPayloadSchema = objectType({
7977
- business_id: stringType(),
7978
- type: literalType("dispute.won"),
7979
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7980
- data: DisputeSchema,
7923
+ business_id: stringType(),
7924
+ type: literalType("dispute.won"),
7925
+ timestamp: stringType().transform((d) => new Date(d)),
7926
+ data: DisputeSchema
7981
7927
  });
7982
7928
  var DisputeLostPayloadSchema = objectType({
7983
- business_id: stringType(),
7984
- type: literalType("dispute.lost"),
7985
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7986
- data: DisputeSchema,
7929
+ business_id: stringType(),
7930
+ type: literalType("dispute.lost"),
7931
+ timestamp: stringType().transform((d) => new Date(d)),
7932
+ data: DisputeSchema
7987
7933
  });
7988
7934
  var SubscriptionActivePayloadSchema = objectType({
7989
- business_id: stringType(),
7990
- type: literalType("subscription.active"),
7991
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7992
- data: SubscriptionSchema,
7935
+ business_id: stringType(),
7936
+ type: literalType("subscription.active"),
7937
+ timestamp: stringType().transform((d) => new Date(d)),
7938
+ data: SubscriptionSchema
7993
7939
  });
7994
7940
  var SubscriptionOnHoldPayloadSchema = objectType({
7995
- business_id: stringType(),
7996
- type: literalType("subscription.on_hold"),
7997
- timestamp: stringType().transform(function (d) { return new Date(d); }),
7998
- data: SubscriptionSchema,
7941
+ business_id: stringType(),
7942
+ type: literalType("subscription.on_hold"),
7943
+ timestamp: stringType().transform((d) => new Date(d)),
7944
+ data: SubscriptionSchema
7999
7945
  });
8000
7946
  var SubscriptionRenewedPayloadSchema = objectType({
8001
- business_id: stringType(),
8002
- type: literalType("subscription.renewed"),
8003
- timestamp: stringType().transform(function (d) { return new Date(d); }),
8004
- data: SubscriptionSchema,
7947
+ business_id: stringType(),
7948
+ type: literalType("subscription.renewed"),
7949
+ timestamp: stringType().transform((d) => new Date(d)),
7950
+ data: SubscriptionSchema
8005
7951
  });
8006
7952
  var SubscriptionPausedPayloadSchema = objectType({
8007
- business_id: stringType(),
8008
- type: literalType("subscription.paused"),
8009
- timestamp: stringType().transform(function (d) { return new Date(d); }),
8010
- data: SubscriptionSchema,
7953
+ business_id: stringType(),
7954
+ type: literalType("subscription.paused"),
7955
+ timestamp: stringType().transform((d) => new Date(d)),
7956
+ data: SubscriptionSchema
8011
7957
  });
8012
7958
  var SubscriptionPlanChangedPayloadSchema = objectType({
8013
- business_id: stringType(),
8014
- type: literalType("subscription.plan_changed"),
8015
- timestamp: stringType().transform(function (d) { return new Date(d); }),
8016
- data: SubscriptionSchema,
7959
+ business_id: stringType(),
7960
+ type: literalType("subscription.plan_changed"),
7961
+ timestamp: stringType().transform((d) => new Date(d)),
7962
+ data: SubscriptionSchema
8017
7963
  });
8018
7964
  var SubscriptionCancelledPayloadSchema = objectType({
8019
- business_id: stringType(),
8020
- type: literalType("subscription.cancelled"),
8021
- timestamp: stringType().transform(function (d) { return new Date(d); }),
8022
- data: SubscriptionSchema,
7965
+ business_id: stringType(),
7966
+ type: literalType("subscription.cancelled"),
7967
+ timestamp: stringType().transform((d) => new Date(d)),
7968
+ data: SubscriptionSchema
8023
7969
  });
8024
7970
  var SubscriptionFailedPayloadSchema = objectType({
8025
- business_id: stringType(),
8026
- type: literalType("subscription.failed"),
8027
- timestamp: stringType().transform(function (d) { return new Date(d); }),
8028
- data: SubscriptionSchema,
7971
+ business_id: stringType(),
7972
+ type: literalType("subscription.failed"),
7973
+ timestamp: stringType().transform((d) => new Date(d)),
7974
+ data: SubscriptionSchema
8029
7975
  });
8030
7976
  var SubscriptionExpiredPayloadSchema = objectType({
8031
- business_id: stringType(),
8032
- type: literalType("subscription.expired"),
8033
- timestamp: stringType().transform(function (d) { return new Date(d); }),
8034
- data: SubscriptionSchema,
7977
+ business_id: stringType(),
7978
+ type: literalType("subscription.expired"),
7979
+ timestamp: stringType().transform((d) => new Date(d)),
7980
+ data: SubscriptionSchema
8035
7981
  });
8036
7982
  var LicenseKeyCreatedPayloadSchema = objectType({
8037
- business_id: stringType(),
8038
- type: literalType("license_key.created"),
8039
- timestamp: stringType().transform(function (d) { return new Date(d); }),
8040
- data: LicenseKeySchema,
7983
+ business_id: stringType(),
7984
+ type: literalType("license_key.created"),
7985
+ timestamp: stringType().transform((d) => new Date(d)),
7986
+ data: LicenseKeySchema
8041
7987
  });
8042
7988
  var WebhookPayloadSchema = discriminatedUnionType("type", [
8043
- PaymentSucceededPayloadSchema,
8044
- PaymentFailedPayloadSchema,
8045
- PaymentProcessingPayloadSchema,
8046
- PaymentCancelledPayloadSchema,
8047
- RefundSucceededPayloadSchema,
8048
- RefundFailedPayloadSchema,
8049
- DisputeOpenedPayloadSchema,
8050
- DisputeExpiredPayloadSchema,
8051
- DisputeAcceptedPayloadSchema,
8052
- DisputeCancelledPayloadSchema,
8053
- DisputeChallengedPayloadSchema,
8054
- DisputeWonPayloadSchema,
8055
- DisputeLostPayloadSchema,
8056
- SubscriptionActivePayloadSchema,
8057
- SubscriptionOnHoldPayloadSchema,
8058
- SubscriptionRenewedPayloadSchema,
8059
- SubscriptionPausedPayloadSchema,
8060
- SubscriptionPlanChangedPayloadSchema,
8061
- SubscriptionCancelledPayloadSchema,
8062
- SubscriptionFailedPayloadSchema,
8063
- SubscriptionExpiredPayloadSchema,
8064
- LicenseKeyCreatedPayloadSchema,
7989
+ PaymentSucceededPayloadSchema,
7990
+ PaymentFailedPayloadSchema,
7991
+ PaymentProcessingPayloadSchema,
7992
+ PaymentCancelledPayloadSchema,
7993
+ RefundSucceededPayloadSchema,
7994
+ RefundFailedPayloadSchema,
7995
+ DisputeOpenedPayloadSchema,
7996
+ DisputeExpiredPayloadSchema,
7997
+ DisputeAcceptedPayloadSchema,
7998
+ DisputeCancelledPayloadSchema,
7999
+ DisputeChallengedPayloadSchema,
8000
+ DisputeWonPayloadSchema,
8001
+ DisputeLostPayloadSchema,
8002
+ SubscriptionActivePayloadSchema,
8003
+ SubscriptionOnHoldPayloadSchema,
8004
+ SubscriptionRenewedPayloadSchema,
8005
+ SubscriptionPausedPayloadSchema,
8006
+ SubscriptionPlanChangedPayloadSchema,
8007
+ SubscriptionCancelledPayloadSchema,
8008
+ SubscriptionFailedPayloadSchema,
8009
+ SubscriptionExpiredPayloadSchema,
8010
+ LicenseKeyCreatedPayloadSchema
8065
8011
  ]);
8066
8012
 
8067
- var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
8068
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
8069
- return new (P || (P = Promise))(function (resolve, reject) {
8070
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
8071
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
8072
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8073
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8074
- });
8075
- };
8076
- var __generator = (undefined && undefined.__generator) || function (thisArg, body) {
8077
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
8078
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
8079
- function verb(n) { return function (v) { return step([n, v]); }; }
8080
- function step(op) {
8081
- if (f) throw new TypeError("Generator is already executing.");
8082
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
8083
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
8084
- if (y = 0, t) op = [op[0] & 2, t.value];
8085
- switch (op[0]) {
8086
- case 0: case 1: t = op; break;
8087
- case 4: _.label++; return { value: op[1], done: false };
8088
- case 5: _.label++; y = op[1]; op = [0]; continue;
8089
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
8090
- default:
8091
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
8092
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
8093
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
8094
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
8095
- if (t[2]) _.ops.pop();
8096
- _.trys.pop(); continue;
8097
- }
8098
- op = body.call(thisArg, _);
8099
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
8100
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
8101
- }
8102
- };
8103
- // Implementation
8104
- function handleWebhookPayload(payload, config, context) {
8105
- return __awaiter(this, void 0, void 0, function () {
8106
- var callHandler;
8107
- return __generator(this, function (_a) {
8108
- switch (_a.label) {
8109
- case 0:
8110
- callHandler = function (handler, payload) {
8111
- if (!handler)
8112
- return;
8113
- return handler(payload);
8114
- };
8115
- if (!config.onPayload) return [3 /*break*/, 2];
8116
- return [4 /*yield*/, callHandler(config.onPayload, payload)];
8117
- case 1:
8118
- _a.sent();
8119
- _a.label = 2;
8120
- case 2:
8121
- if (!(payload.type === "payment.succeeded")) return [3 /*break*/, 4];
8122
- return [4 /*yield*/, callHandler(config.onPaymentSucceeded, payload)];
8123
- case 3:
8124
- _a.sent();
8125
- _a.label = 4;
8126
- case 4:
8127
- if (!(payload.type === "payment.failed")) return [3 /*break*/, 6];
8128
- return [4 /*yield*/, callHandler(config.onPaymentFailed, payload)];
8129
- case 5:
8130
- _a.sent();
8131
- _a.label = 6;
8132
- case 6:
8133
- if (!(payload.type === "payment.processing")) return [3 /*break*/, 8];
8134
- return [4 /*yield*/, callHandler(config.onPaymentProcessing, payload)];
8135
- case 7:
8136
- _a.sent();
8137
- _a.label = 8;
8138
- case 8:
8139
- if (!(payload.type === "payment.cancelled")) return [3 /*break*/, 10];
8140
- return [4 /*yield*/, callHandler(config.onPaymentCancelled, payload)];
8141
- case 9:
8142
- _a.sent();
8143
- _a.label = 10;
8144
- case 10:
8145
- if (!(payload.type === "refund.succeeded")) return [3 /*break*/, 12];
8146
- return [4 /*yield*/, callHandler(config.onRefundSucceeded, payload)];
8147
- case 11:
8148
- _a.sent();
8149
- _a.label = 12;
8150
- case 12:
8151
- if (!(payload.type === "refund.failed")) return [3 /*break*/, 14];
8152
- return [4 /*yield*/, callHandler(config.onRefundFailed, payload)];
8153
- case 13:
8154
- _a.sent();
8155
- _a.label = 14;
8156
- case 14:
8157
- if (!(payload.type === "dispute.opened")) return [3 /*break*/, 16];
8158
- return [4 /*yield*/, callHandler(config.onDisputeOpened, payload)];
8159
- case 15:
8160
- _a.sent();
8161
- _a.label = 16;
8162
- case 16:
8163
- if (!(payload.type === "dispute.expired")) return [3 /*break*/, 18];
8164
- return [4 /*yield*/, callHandler(config.onDisputeExpired, payload)];
8165
- case 17:
8166
- _a.sent();
8167
- _a.label = 18;
8168
- case 18:
8169
- if (!(payload.type === "dispute.accepted")) return [3 /*break*/, 20];
8170
- return [4 /*yield*/, callHandler(config.onDisputeAccepted, payload)];
8171
- case 19:
8172
- _a.sent();
8173
- _a.label = 20;
8174
- case 20:
8175
- if (!(payload.type === "dispute.cancelled")) return [3 /*break*/, 22];
8176
- return [4 /*yield*/, callHandler(config.onDisputeCancelled, payload)];
8177
- case 21:
8178
- _a.sent();
8179
- _a.label = 22;
8180
- case 22:
8181
- if (!(payload.type === "dispute.challenged")) return [3 /*break*/, 24];
8182
- return [4 /*yield*/, callHandler(config.onDisputeChallenged, payload)];
8183
- case 23:
8184
- _a.sent();
8185
- _a.label = 24;
8186
- case 24:
8187
- if (!(payload.type === "dispute.won")) return [3 /*break*/, 26];
8188
- return [4 /*yield*/, callHandler(config.onDisputeWon, payload)];
8189
- case 25:
8190
- _a.sent();
8191
- _a.label = 26;
8192
- case 26:
8193
- if (!(payload.type === "dispute.lost")) return [3 /*break*/, 28];
8194
- return [4 /*yield*/, callHandler(config.onDisputeLost, payload)];
8195
- case 27:
8196
- _a.sent();
8197
- _a.label = 28;
8198
- case 28:
8199
- if (!(payload.type === "subscription.active")) return [3 /*break*/, 30];
8200
- return [4 /*yield*/, callHandler(config.onSubscriptionActive, payload)];
8201
- case 29:
8202
- _a.sent();
8203
- _a.label = 30;
8204
- case 30:
8205
- if (!(payload.type === "subscription.on_hold")) return [3 /*break*/, 32];
8206
- return [4 /*yield*/, callHandler(config.onSubscriptionOnHold, payload)];
8207
- case 31:
8208
- _a.sent();
8209
- _a.label = 32;
8210
- case 32:
8211
- if (!(payload.type === "subscription.renewed")) return [3 /*break*/, 34];
8212
- return [4 /*yield*/, callHandler(config.onSubscriptionRenewed, payload)];
8213
- case 33:
8214
- _a.sent();
8215
- _a.label = 34;
8216
- case 34:
8217
- if (!(payload.type === "subscription.paused")) return [3 /*break*/, 36];
8218
- return [4 /*yield*/, callHandler(config.onSubscriptionPaused, payload)];
8219
- case 35:
8220
- _a.sent();
8221
- _a.label = 36;
8222
- case 36:
8223
- if (!(payload.type === "subscription.plan_changed")) return [3 /*break*/, 38];
8224
- return [4 /*yield*/, callHandler(config.onSubscriptionPlanChanged, payload)];
8225
- case 37:
8226
- _a.sent();
8227
- _a.label = 38;
8228
- case 38:
8229
- if (!(payload.type === "subscription.cancelled")) return [3 /*break*/, 40];
8230
- return [4 /*yield*/, callHandler(config.onSubscriptionCancelled, payload)];
8231
- case 39:
8232
- _a.sent();
8233
- _a.label = 40;
8234
- case 40:
8235
- if (!(payload.type === "subscription.failed")) return [3 /*break*/, 42];
8236
- return [4 /*yield*/, callHandler(config.onSubscriptionFailed, payload)];
8237
- case 41:
8238
- _a.sent();
8239
- _a.label = 42;
8240
- case 42:
8241
- if (!(payload.type === "subscription.expired")) return [3 /*break*/, 44];
8242
- return [4 /*yield*/, callHandler(config.onSubscriptionExpired, payload)];
8243
- case 43:
8244
- _a.sent();
8245
- _a.label = 44;
8246
- case 44:
8247
- if (!(payload.type === "license_key.created")) return [3 /*break*/, 46];
8248
- return [4 /*yield*/, callHandler(config.onLicenseKeyCreated, payload)];
8249
- case 45:
8250
- _a.sent();
8251
- _a.label = 46;
8252
- case 46: return [2 /*return*/];
8253
- }
8254
- });
8255
- });
8013
+ async function handleWebhookPayload(payload, config, context) {
8014
+ const callHandler = (handler, payload2) => {
8015
+ if (!handler) return;
8016
+ return handler(payload2);
8017
+ };
8018
+ if (config.onPayload) {
8019
+ await callHandler(config.onPayload, payload);
8020
+ }
8021
+ if (payload.type === "payment.succeeded") {
8022
+ await callHandler(config.onPaymentSucceeded, payload);
8023
+ }
8024
+ if (payload.type === "payment.failed") {
8025
+ await callHandler(config.onPaymentFailed, payload);
8026
+ }
8027
+ if (payload.type === "payment.processing") {
8028
+ await callHandler(config.onPaymentProcessing, payload);
8029
+ }
8030
+ if (payload.type === "payment.cancelled") {
8031
+ await callHandler(config.onPaymentCancelled, payload);
8032
+ }
8033
+ if (payload.type === "refund.succeeded") {
8034
+ await callHandler(config.onRefundSucceeded, payload);
8035
+ }
8036
+ if (payload.type === "refund.failed") {
8037
+ await callHandler(config.onRefundFailed, payload);
8038
+ }
8039
+ if (payload.type === "dispute.opened") {
8040
+ await callHandler(config.onDisputeOpened, payload);
8041
+ }
8042
+ if (payload.type === "dispute.expired") {
8043
+ await callHandler(config.onDisputeExpired, payload);
8044
+ }
8045
+ if (payload.type === "dispute.accepted") {
8046
+ await callHandler(config.onDisputeAccepted, payload);
8047
+ }
8048
+ if (payload.type === "dispute.cancelled") {
8049
+ await callHandler(config.onDisputeCancelled, payload);
8050
+ }
8051
+ if (payload.type === "dispute.challenged") {
8052
+ await callHandler(config.onDisputeChallenged, payload);
8053
+ }
8054
+ if (payload.type === "dispute.won") {
8055
+ await callHandler(config.onDisputeWon, payload);
8056
+ }
8057
+ if (payload.type === "dispute.lost") {
8058
+ await callHandler(config.onDisputeLost, payload);
8059
+ }
8060
+ if (payload.type === "subscription.active") {
8061
+ await callHandler(config.onSubscriptionActive, payload);
8062
+ }
8063
+ if (payload.type === "subscription.on_hold") {
8064
+ await callHandler(config.onSubscriptionOnHold, payload);
8065
+ }
8066
+ if (payload.type === "subscription.renewed") {
8067
+ await callHandler(config.onSubscriptionRenewed, payload);
8068
+ }
8069
+ if (payload.type === "subscription.paused") {
8070
+ await callHandler(config.onSubscriptionPaused, payload);
8071
+ }
8072
+ if (payload.type === "subscription.plan_changed") {
8073
+ await callHandler(config.onSubscriptionPlanChanged, payload);
8074
+ }
8075
+ if (payload.type === "subscription.cancelled") {
8076
+ await callHandler(config.onSubscriptionCancelled, payload);
8077
+ }
8078
+ if (payload.type === "subscription.failed") {
8079
+ await callHandler(config.onSubscriptionFailed, payload);
8080
+ }
8081
+ if (payload.type === "subscription.expired") {
8082
+ await callHandler(config.onSubscriptionExpired, payload);
8083
+ }
8084
+ if (payload.type === "license_key.created") {
8085
+ await callHandler(config.onLicenseKeyCreated, payload);
8086
+ }
8256
8087
  }
8257
8088
 
8258
8089
  const Webhooks = ({ webhookKey, ...eventHandlers }) => {