@dodopayments/sveltekit 0.2.2 → 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,1389 +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
- }
5945
+ return paddingLength;
5946
+ };
5947
+ return Coder;
5948
+ }());
5949
+ base64$1.Coder = Coder;
5950
+ var stdCoder = new Coder();
5951
+ function encode(data) {
5952
+ return stdCoder.encode(data);
6224
5953
  }
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
- // src/checkout/checkout.ts
6266
- var checkoutQuerySchema = objectType({
6267
- productId: stringType(),
6268
- quantity: stringType().optional(),
6269
- // Customer fields
6270
- fullName: stringType().optional(),
6271
- firstName: stringType().optional(),
6272
- lastName: stringType().optional(),
6273
- email: stringType().optional(),
6274
- country: stringType().optional(),
6275
- addressLine: stringType().optional(),
6276
- city: stringType().optional(),
6277
- state: stringType().optional(),
6278
- zipCode: stringType().optional(),
6279
- // Disable flags
6280
- disableFullName: stringType().optional(),
6281
- disableFirstName: stringType().optional(),
6282
- disableLastName: stringType().optional(),
6283
- disableEmail: stringType().optional(),
6284
- disableCountry: stringType().optional(),
6285
- disableAddressLine: stringType().optional(),
6286
- disableCity: stringType().optional(),
6287
- disableState: stringType().optional(),
6288
- disableZipCode: stringType().optional(),
6289
- // Advanced controls
6290
- paymentCurrency: stringType().optional(),
6291
- showCurrencySelector: stringType().optional(),
6292
- paymentAmount: stringType().optional(),
6293
- showDiscounts: stringType().optional()
6294
- // Metadata (allow any key starting with metadata_)
6295
- // We'll handle metadata separately in the handler
6296
- }).catchall(unknownType());
6297
- var dynamicCheckoutBodySchema = objectType({
6298
- // For subscription
6299
- product_id: stringType().optional(),
6300
- quantity: numberType().optional(),
6301
- // For one-time payment
6302
- product_cart: arrayType(
6303
- objectType({
6304
- product_id: stringType(),
6305
- quantity: numberType()
6306
- })
6307
- ).optional(),
6308
- // Common fields
6309
- billing: objectType({
6310
- city: stringType(),
6311
- country: stringType(),
6312
- state: stringType(),
6313
- street: stringType(),
6314
- zipcode: stringType()
6315
- }),
6316
- customer: objectType({
6317
- customer_id: stringType().optional(),
6318
- email: stringType().optional(),
6319
- name: stringType().optional()
6320
- }),
6321
- discount_id: stringType().optional(),
6322
- addons: arrayType(
6323
- objectType({
6324
- addon_id: stringType(),
6325
- quantity: numberType()
6326
- })
6327
- ).optional(),
6328
- metadata: recordType(stringType(), stringType()).optional(),
6329
- currency: stringType().optional()
6330
- // Allow any additional fields (for future compatibility)
6331
- }).catchall(unknownType());
6332
- var checkoutSessionProductCartItemSchema = objectType({
6333
- product_id: stringType().min(1, "Product ID is required"),
6334
- quantity: numberType().int().positive("Quantity must be a positive integer")
6335
- });
6336
- var checkoutSessionCustomerSchema = objectType({
6337
- email: stringType().email().optional(),
6338
- name: stringType().min(1).optional(),
6339
- phone_number: stringType().optional()
6340
- }).optional();
6341
- var checkoutSessionBillingAddressSchema = objectType({
6342
- street: stringType().optional(),
6343
- city: stringType().optional(),
6344
- state: stringType().optional(),
6345
- country: stringType().length(2, "Country must be a 2-letter ISO code"),
6346
- zipcode: stringType().optional()
6347
- }).optional();
6348
- var paymentMethodTypeSchema = enumType([
6349
- "credit",
6350
- "debit",
6351
- "upi_collect",
6352
- "upi_intent",
6353
- "apple_pay",
6354
- "google_pay",
6355
- "amazon_pay",
6356
- "klarna",
6357
- "affirm",
6358
- "afterpay_clearpay",
6359
- "sepa",
6360
- "ach"
6361
- ]);
6362
- var checkoutSessionCustomizationSchema = objectType({
6363
- theme: enumType(["light", "dark", "system"]).optional(),
6364
- show_order_details: booleanType().optional(),
6365
- show_on_demand_tag: booleanType().optional()
6366
- }).optional();
6367
- var checkoutSessionFeatureFlagsSchema = objectType({
6368
- allow_currency_selection: booleanType().optional(),
6369
- allow_discount_code: booleanType().optional(),
6370
- allow_phone_number_collection: booleanType().optional(),
6371
- allow_tax_id: booleanType().optional(),
6372
- always_create_new_customer: booleanType().optional()
6373
- }).optional();
6374
- var checkoutSessionSubscriptionDataSchema = objectType({
6375
- trial_period_days: numberType().int().nonnegative().optional()
6376
- }).optional();
6377
- var checkoutSessionPayloadSchema = objectType({
6378
- // Required fields
6379
- product_cart: arrayType(checkoutSessionProductCartItemSchema).min(1, "At least one product is required"),
6380
- // Optional fields
6381
- customer: checkoutSessionCustomerSchema,
6382
- billing_address: checkoutSessionBillingAddressSchema,
6383
- return_url: stringType().url().optional(),
6384
- allowed_payment_method_types: arrayType(paymentMethodTypeSchema).optional(),
6385
- billing_currency: stringType().length(3, "Currency must be a 3-letter ISO code").optional(),
6386
- show_saved_payment_methods: booleanType().optional(),
6387
- confirm: booleanType().optional(),
6388
- discount_code: stringType().optional(),
6389
- metadata: recordType(stringType(), stringType()).optional(),
6390
- customization: checkoutSessionCustomizationSchema,
6391
- feature_flags: checkoutSessionFeatureFlagsSchema,
6392
- subscription_data: checkoutSessionSubscriptionDataSchema
6393
- });
6394
- var checkoutSessionResponseSchema = objectType({
6395
- session_id: stringType().min(1, "Session ID is required"),
6396
- checkout_url: stringType().url("Invalid checkout URL")
6397
- });
6398
- var createCheckoutSession = async (payload, config) => {
6399
- const validation = checkoutSessionPayloadSchema.safeParse(payload);
6400
- if (!validation.success) {
6401
- throw new Error(
6402
- `Invalid checkout session payload: ${validation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
6403
- );
6404
- }
6405
- const dodopayments = new DodoPayments({
6406
- bearerToken: config.bearerToken,
6407
- environment: config.environment
6408
- });
6409
- try {
6410
- const sdkPayload = {
6411
- ...validation.data,
6412
- ...validation.data.billing_address && {
6413
- billing_address: {
6414
- ...validation.data.billing_address,
6415
- country: validation.data.billing_address.country
6416
- }
6417
- }
6418
- };
6419
- const session = await dodopayments.checkoutSessions.create(
6420
- sdkPayload
6421
- );
6422
- const responseValidation = checkoutSessionResponseSchema.safeParse(session);
6423
- if (!responseValidation.success) {
6424
- throw new Error(
6425
- `Invalid checkout session response from API: ${responseValidation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ")}`
6426
- );
6427
- }
6428
- return responseValidation.data;
6429
- } catch (error) {
6430
- if (error instanceof Error) {
6431
- console.error("Dodo Payments Checkout Session API Error:", {
6432
- message: error.message,
6433
- payload: validation.data,
6434
- config: {
6435
- environment: config.environment,
6436
- hasBearerToken: !!config.bearerToken
6437
- }
6438
- });
6439
- throw new Error(`Failed to create checkout session: ${error.message}`);
5954
+ base64$1.encode = encode;
5955
+ function decode(s) {
5956
+ return stdCoder.decode(s);
5957
+ }
5958
+ base64$1.decode = decode;
5959
+ /**
5960
+ * Implements URL-safe Base64 encoding.
5961
+ * (Same as Base64, but '+' is replaced with '-', and '/' with '_').
5962
+ *
5963
+ * Operates in constant time.
5964
+ */
5965
+ var URLSafeCoder = /** @class */ (function (_super) {
5966
+ __extends(URLSafeCoder, _super);
5967
+ function URLSafeCoder() {
5968
+ return _super !== null && _super.apply(this, arguments) || this;
6440
5969
  }
6441
- console.error("Unknown error creating checkout session:", error);
6442
- throw new Error(
6443
- "Failed to create checkout session due to an unknown error"
6444
- );
6445
- }
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);
5989
+ };
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;
6003
+ };
6004
+ return URLSafeCoder;
6005
+ }(Coder));
6006
+ base64$1.URLSafeCoder = URLSafeCoder;
6007
+ var urlSafeCoder = new URLSafeCoder();
6008
+ function encodeURLSafe(data) {
6009
+ return urlSafeCoder.encode(data);
6010
+ }
6011
+ base64$1.encodeURLSafe = encodeURLSafe;
6012
+ function decodeURLSafe(s) {
6013
+ return urlSafeCoder.decode(s);
6014
+ }
6015
+ base64$1.decodeURLSafe = decodeURLSafe;
6016
+ base64$1.encodedLength = function (length) {
6017
+ return stdCoder.encodedLength(length);
6446
6018
  };
6447
- var buildCheckoutUrl = async ({
6448
- queryParams,
6449
- body,
6450
- sessionPayload,
6451
- returnUrl,
6452
- bearerToken,
6453
- environment,
6454
- type = "static"
6455
- }) => {
6456
- if (type === "session") {
6457
- if (!sessionPayload) {
6458
- throw new Error("sessionPayload is required when type is 'session'");
6459
- }
6460
- const session = await createCheckoutSession(sessionPayload, {
6461
- bearerToken,
6462
- environment
6463
- });
6464
- return session.checkout_url;
6465
- }
6466
- const inputData = type === "dynamic" ? body : queryParams;
6467
- let parseResult;
6468
- if (type === "dynamic") {
6469
- parseResult = dynamicCheckoutBodySchema.safeParse(inputData);
6470
- } else {
6471
- parseResult = checkoutQuerySchema.safeParse(inputData);
6472
- }
6473
- const { success, data, error } = parseResult;
6474
- if (!success) {
6475
- throw new Error(
6476
- `Invalid ${type === "dynamic" ? "body" : "query parameters"}.
6477
- ${error.message}`
6478
- );
6479
- }
6480
- if (type !== "dynamic") {
6481
- const {
6482
- productId,
6483
- quantity: quantity2,
6484
- fullName,
6485
- firstName,
6486
- lastName,
6487
- email,
6488
- country,
6489
- addressLine,
6490
- city,
6491
- state,
6492
- zipCode,
6493
- disableFullName,
6494
- disableFirstName,
6495
- disableLastName,
6496
- disableEmail,
6497
- disableCountry,
6498
- disableAddressLine,
6499
- disableCity,
6500
- disableState,
6501
- disableZipCode,
6502
- paymentCurrency,
6503
- showCurrencySelector,
6504
- paymentAmount,
6505
- showDiscounts
6506
- // metadata handled below
6507
- } = data;
6508
- const dodopayments2 = new DodoPayments({
6509
- bearerToken,
6510
- environment
6511
- });
6512
- if (!productId) throw new Error("Missing required field: productId");
6513
- try {
6514
- await dodopayments2.products.retrieve(productId);
6515
- } catch (err) {
6516
- console.error(err);
6517
- throw new Error("Product not found");
6518
- }
6519
- const url = new URL(
6520
- `${environment === "test_mode" ? "https://test.checkout.dodopayments.com" : "https://checkout.dodopayments.com"}/buy/${productId}`
6521
- );
6522
- url.searchParams.set("quantity", quantity2 ? String(quantity2) : "1");
6523
- if (returnUrl) url.searchParams.set("redirect_url", returnUrl);
6524
- if (fullName) url.searchParams.set("fullName", String(fullName));
6525
- if (firstName) url.searchParams.set("firstName", String(firstName));
6526
- if (lastName) url.searchParams.set("lastName", String(lastName));
6527
- if (email) url.searchParams.set("email", String(email));
6528
- if (country) url.searchParams.set("country", String(country));
6529
- if (addressLine) url.searchParams.set("addressLine", String(addressLine));
6530
- if (city) url.searchParams.set("city", String(city));
6531
- if (state) url.searchParams.set("state", String(state));
6532
- if (zipCode) url.searchParams.set("zipCode", String(zipCode));
6533
- if (disableFullName === "true")
6534
- url.searchParams.set("disableFullName", "true");
6535
- if (disableFirstName === "true")
6536
- url.searchParams.set("disableFirstName", "true");
6537
- if (disableLastName === "true")
6538
- url.searchParams.set("disableLastName", "true");
6539
- if (disableEmail === "true") url.searchParams.set("disableEmail", "true");
6540
- if (disableCountry === "true")
6541
- url.searchParams.set("disableCountry", "true");
6542
- if (disableAddressLine === "true")
6543
- url.searchParams.set("disableAddressLine", "true");
6544
- if (disableCity === "true") url.searchParams.set("disableCity", "true");
6545
- if (disableState === "true") url.searchParams.set("disableState", "true");
6546
- if (disableZipCode === "true")
6547
- url.searchParams.set("disableZipCode", "true");
6548
- if (paymentCurrency)
6549
- url.searchParams.set("paymentCurrency", String(paymentCurrency));
6550
- if (showCurrencySelector)
6551
- url.searchParams.set(
6552
- "showCurrencySelector",
6553
- String(showCurrencySelector)
6554
- );
6555
- if (paymentAmount)
6556
- url.searchParams.set("paymentAmount", String(paymentAmount));
6557
- if (showDiscounts)
6558
- url.searchParams.set("showDiscounts", String(showDiscounts));
6559
- for (const [key, value] of Object.entries(queryParams || {})) {
6560
- if (key.startsWith("metadata_") && value && typeof value !== "object") {
6561
- url.searchParams.set(key, String(value));
6562
- }
6563
- }
6564
- return url.toString();
6565
- }
6566
- const dyn = data;
6567
- const {
6568
- product_id,
6569
- product_cart,
6570
- quantity,
6571
- billing,
6572
- customer,
6573
- addons,
6574
- metadata,
6575
- allowed_payment_method_types,
6576
- billing_currency,
6577
- discount_code,
6578
- on_demand,
6579
- return_url: bodyReturnUrl,
6580
- show_saved_payment_methods,
6581
- tax_id,
6582
- trial_period_days
6583
- } = dyn;
6584
- const dodopayments = new DodoPayments({
6585
- bearerToken,
6586
- environment
6587
- });
6588
- let isSubscription = false;
6589
- let productIdToFetch = product_id;
6590
- if (!product_id && product_cart && product_cart.length > 0) {
6591
- productIdToFetch = product_cart[0].product_id;
6592
- }
6593
- if (!productIdToFetch)
6594
- throw new Error(
6595
- "Missing required field: product_id or product_cart[0].product_id"
6596
- );
6597
- let product;
6598
- try {
6599
- product = await dodopayments.products.retrieve(productIdToFetch);
6600
- } catch (err) {
6601
- console.error(err);
6602
- throw new Error("Product not found");
6603
- }
6604
- isSubscription = Boolean(product.is_recurring);
6605
- if (isSubscription && !product_id)
6606
- throw new Error("Missing required field: product_id for subscription");
6607
- if (!billing) throw new Error("Missing required field: billing");
6608
- if (!customer) throw new Error("Missing required field: customer");
6609
- if (isSubscription) {
6610
- const subscriptionPayload = {
6611
- billing,
6612
- customer,
6613
- product_id,
6614
- quantity: quantity ? Number(quantity) : 1
6615
- };
6616
- if (metadata) subscriptionPayload.metadata = metadata;
6617
- if (discount_code) subscriptionPayload.discount_code = discount_code;
6618
- if (addons) subscriptionPayload.addons = addons;
6619
- if (allowed_payment_method_types)
6620
- subscriptionPayload.allowed_payment_method_types = allowed_payment_method_types;
6621
- if (billing_currency)
6622
- subscriptionPayload.billing_currency = billing_currency;
6623
- if (on_demand) subscriptionPayload.on_demand = on_demand;
6624
- subscriptionPayload.payment_link = true;
6625
- if (bodyReturnUrl) {
6626
- subscriptionPayload.return_url = bodyReturnUrl;
6627
- } else if (returnUrl) {
6628
- subscriptionPayload.return_url = returnUrl;
6629
- }
6630
- if (show_saved_payment_methods)
6631
- subscriptionPayload.show_saved_payment_methods = show_saved_payment_methods;
6632
- if (tax_id) subscriptionPayload.tax_id = tax_id;
6633
- if (trial_period_days)
6634
- subscriptionPayload.trial_period_days = trial_period_days;
6635
- let subscription;
6636
- try {
6637
- subscription = await dodopayments.subscriptions.create(subscriptionPayload);
6638
- } catch (err) {
6639
- console.error("Error when creating subscription", err);
6640
- throw new Error(err instanceof Error ? err.message : String(err));
6641
- }
6642
- if (!subscription || !subscription.payment_link) {
6643
- throw new Error(
6644
- "No payment link returned from Dodo Payments API (subscription). Make sure to set payment_link as true in payload"
6645
- );
6646
- }
6647
- return subscription.payment_link;
6648
- } else {
6649
- let cart = product_cart;
6650
- if (!cart && product_id) {
6651
- cart = [
6652
- { product_id, quantity: quantity ? Number(quantity) : 1 }
6653
- ];
6654
- }
6655
- if (!cart || cart.length === 0)
6656
- throw new Error("Missing required field: product_cart or product_id");
6657
- const paymentPayload = {
6658
- billing,
6659
- customer,
6660
- product_cart: cart
6661
- };
6662
- if (metadata) paymentPayload.metadata = metadata;
6663
- paymentPayload.payment_link = true;
6664
- if (allowed_payment_method_types)
6665
- paymentPayload.allowed_payment_method_types = allowed_payment_method_types;
6666
- if (billing_currency) paymentPayload.billing_currency = billing_currency;
6667
- if (discount_code) paymentPayload.discount_code = discount_code;
6668
- if (bodyReturnUrl) {
6669
- paymentPayload.return_url = bodyReturnUrl;
6670
- } else if (returnUrl) {
6671
- paymentPayload.return_url = returnUrl;
6672
- }
6673
- if (show_saved_payment_methods)
6674
- paymentPayload.show_saved_payment_methods = show_saved_payment_methods;
6675
- if (tax_id) paymentPayload.tax_id = tax_id;
6676
- let payment;
6677
- try {
6678
- payment = await dodopayments.payments.create(paymentPayload);
6679
- } catch (err) {
6680
- console.error("Error when creating payment link", err);
6681
- throw new Error(err instanceof Error ? err.message : String(err));
6682
- }
6683
- if (!payment || !payment.payment_link) {
6684
- throw new Error(
6685
- "No payment link returned from Dodo Payments API. Make sure to set payment_link as true in payload."
6686
- );
6687
- }
6688
- return payment.payment_link;
6689
- }
6019
+ base64$1.maxDecodedLength = function (length) {
6020
+ return stdCoder.maxDecodedLength(length);
6021
+ };
6022
+ base64$1.decodedLength = function (s) {
6023
+ return stdCoder.decodedLength(s);
6690
6024
  };
6691
6025
 
6692
- const Checkout = (config) => {
6693
- const getHandler = async (event) => {
6694
- const searchParams = event.url.searchParams;
6695
- const queryParams = Object.fromEntries(searchParams);
6696
- if (!queryParams.productId) {
6697
- throw error(400, "Please provide productId query parameter");
6698
- }
6699
- const { success, data, error: zodError, } = checkoutQuerySchema.safeParse(queryParams);
6700
- if (!success) {
6701
- if (zodError.errors.some((e) => e.path.toString() === "productId")) {
6702
- throw error(400, "Please provide productId query parameter");
6703
- }
6704
- throw error(400, `Invalid query parameters.\n ${zodError.message}`);
6705
- }
6706
- let urlStr = "";
6707
- try {
6708
- urlStr = await buildCheckoutUrl({ queryParams: data, ...config });
6709
- }
6710
- catch (err) {
6711
- throw error(400, err.message);
6712
- }
6713
- return Response.json({ checkout_url: urlStr });
6714
- };
6715
- const postHandler = async (event) => {
6716
- let body;
6717
- try {
6718
- body = await event.request.json();
6719
- }
6720
- catch (e) {
6721
- throw error(400, "Invalid JSON body");
6722
- }
6723
- if (config.type === "dynamic") {
6724
- // Handle dynamic checkout
6725
- const { success, data, error: zodError, } = dynamicCheckoutBodySchema.safeParse(body);
6726
- if (!success) {
6727
- throw error(400, `Invalid request body.\n ${zodError.message}`);
6728
- }
6729
- let urlStr = "";
6730
- try {
6731
- urlStr = await buildCheckoutUrl({
6732
- body: data,
6733
- ...config,
6734
- type: "dynamic",
6735
- });
6736
- }
6737
- catch (err) {
6738
- throw error(400, err.message);
6739
- }
6740
- return Response.json({ checkout_url: urlStr });
6741
- }
6742
- else {
6743
- // Handle checkout session
6744
- const { success, data, error: zodError, } = checkoutSessionPayloadSchema.safeParse(body);
6745
- if (!success) {
6746
- throw error(400, `Invalid checkout session payload.\n ${zodError.message}`);
6747
- }
6748
- let urlStr = "";
6749
- try {
6750
- urlStr = await buildCheckoutUrl({
6751
- sessionPayload: data,
6752
- ...config,
6753
- type: "session",
6754
- });
6755
- }
6756
- catch (err) {
6757
- throw error(400, err.message);
6758
- }
6759
- return Response.json({ checkout_url: urlStr });
6760
- }
6761
- };
6762
- // SvelteKit expects named exports for HTTP verbs
6763
- return {
6764
- GET: getHandler,
6765
- POST: postHandler,
6766
- };
6767
- };
6768
-
6769
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
6770
-
6771
- var dist = {};
6772
-
6773
- var timing_safe_equal = {};
6774
-
6775
- Object.defineProperty(timing_safe_equal, "__esModule", { value: true });
6776
- timing_safe_equal.timingSafeEqual = void 0;
6777
- function assert(expr, msg = "") {
6778
- if (!expr) {
6779
- throw new Error(msg);
6780
- }
6781
- }
6782
- function timingSafeEqual(a, b) {
6783
- if (a.byteLength !== b.byteLength) {
6784
- return false;
6785
- }
6786
- if (!(a instanceof DataView)) {
6787
- a = new DataView(ArrayBuffer.isView(a) ? a.buffer : a);
6788
- }
6789
- if (!(b instanceof DataView)) {
6790
- b = new DataView(ArrayBuffer.isView(b) ? b.buffer : b);
6791
- }
6792
- assert(a instanceof DataView);
6793
- assert(b instanceof DataView);
6794
- const length = a.byteLength;
6795
- let out = 0;
6796
- let i = -1;
6797
- while (++i < length) {
6798
- out |= a.getUint8(i) ^ b.getUint8(i);
6799
- }
6800
- return out === 0;
6801
- }
6802
- timing_safe_equal.timingSafeEqual = timingSafeEqual;
6803
-
6804
- var base64$1 = {};
6805
-
6806
- // Copyright (C) 2016 Dmitry Chestnykh
6807
- // MIT License. See LICENSE file for details.
6808
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
6809
- var extendStatics = function (d, b) {
6810
- extendStatics = Object.setPrototypeOf ||
6811
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6812
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
6813
- return extendStatics(d, b);
6814
- };
6815
- return function (d, b) {
6816
- extendStatics(d, b);
6817
- function __() { this.constructor = d; }
6818
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6819
- };
6820
- })();
6821
- Object.defineProperty(base64$1, "__esModule", { value: true });
6822
- /**
6823
- * Package base64 implements Base64 encoding and decoding.
6824
- */
6825
- // Invalid character used in decoding to indicate
6826
- // that the character to decode is out of range of
6827
- // alphabet and cannot be decoded.
6828
- var INVALID_BYTE = 256;
6829
- /**
6830
- * Implements standard Base64 encoding.
6831
- *
6832
- * Operates in constant time.
6833
- */
6834
- var Coder = /** @class */ (function () {
6835
- // TODO(dchest): methods to encode chunk-by-chunk.
6836
- function Coder(_paddingCharacter) {
6837
- if (_paddingCharacter === void 0) { _paddingCharacter = "="; }
6838
- this._paddingCharacter = _paddingCharacter;
6839
- }
6840
- Coder.prototype.encodedLength = function (length) {
6841
- if (!this._paddingCharacter) {
6842
- return (length * 8 + 5) / 6 | 0;
6843
- }
6844
- return (length + 2) / 3 * 4 | 0;
6845
- };
6846
- Coder.prototype.encode = function (data) {
6847
- var out = "";
6848
- var i = 0;
6849
- for (; i < data.length - 2; i += 3) {
6850
- var c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);
6851
- out += this._encodeByte((c >>> 3 * 6) & 63);
6852
- out += this._encodeByte((c >>> 2 * 6) & 63);
6853
- out += this._encodeByte((c >>> 1 * 6) & 63);
6854
- out += this._encodeByte((c >>> 0 * 6) & 63);
6855
- }
6856
- var left = data.length - i;
6857
- if (left > 0) {
6858
- var c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0);
6859
- out += this._encodeByte((c >>> 3 * 6) & 63);
6860
- out += this._encodeByte((c >>> 2 * 6) & 63);
6861
- if (left === 2) {
6862
- out += this._encodeByte((c >>> 1 * 6) & 63);
6863
- }
6864
- else {
6865
- out += this._paddingCharacter || "";
6866
- }
6867
- out += this._paddingCharacter || "";
6868
- }
6869
- return out;
6870
- };
6871
- Coder.prototype.maxDecodedLength = function (length) {
6872
- if (!this._paddingCharacter) {
6873
- return (length * 6 + 7) / 8 | 0;
6874
- }
6875
- return length / 4 * 3 | 0;
6876
- };
6877
- Coder.prototype.decodedLength = function (s) {
6878
- return this.maxDecodedLength(s.length - this._getPaddingLength(s));
6879
- };
6880
- Coder.prototype.decode = function (s) {
6881
- if (s.length === 0) {
6882
- return new Uint8Array(0);
6883
- }
6884
- var paddingLength = this._getPaddingLength(s);
6885
- var length = s.length - paddingLength;
6886
- var out = new Uint8Array(this.maxDecodedLength(length));
6887
- var op = 0;
6888
- var i = 0;
6889
- var haveBad = 0;
6890
- var v0 = 0, v1 = 0, v2 = 0, v3 = 0;
6891
- for (; i < length - 4; i += 4) {
6892
- v0 = this._decodeChar(s.charCodeAt(i + 0));
6893
- v1 = this._decodeChar(s.charCodeAt(i + 1));
6894
- v2 = this._decodeChar(s.charCodeAt(i + 2));
6895
- v3 = this._decodeChar(s.charCodeAt(i + 3));
6896
- out[op++] = (v0 << 2) | (v1 >>> 4);
6897
- out[op++] = (v1 << 4) | (v2 >>> 2);
6898
- out[op++] = (v2 << 6) | v3;
6899
- haveBad |= v0 & INVALID_BYTE;
6900
- haveBad |= v1 & INVALID_BYTE;
6901
- haveBad |= v2 & INVALID_BYTE;
6902
- haveBad |= v3 & INVALID_BYTE;
6903
- }
6904
- if (i < length - 1) {
6905
- v0 = this._decodeChar(s.charCodeAt(i));
6906
- v1 = this._decodeChar(s.charCodeAt(i + 1));
6907
- out[op++] = (v0 << 2) | (v1 >>> 4);
6908
- haveBad |= v0 & INVALID_BYTE;
6909
- haveBad |= v1 & INVALID_BYTE;
6910
- }
6911
- if (i < length - 2) {
6912
- v2 = this._decodeChar(s.charCodeAt(i + 2));
6913
- out[op++] = (v1 << 4) | (v2 >>> 2);
6914
- haveBad |= v2 & INVALID_BYTE;
6915
- }
6916
- if (i < length - 3) {
6917
- v3 = this._decodeChar(s.charCodeAt(i + 3));
6918
- out[op++] = (v2 << 6) | v3;
6919
- haveBad |= v3 & INVALID_BYTE;
6920
- }
6921
- if (haveBad !== 0) {
6922
- throw new Error("Base64Coder: incorrect characters for decoding");
6923
- }
6924
- return out;
6925
- };
6926
- // Standard encoding have the following encoded/decoded ranges,
6927
- // which we need to convert between.
6928
- //
6929
- // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + /
6930
- // Index: 0 - 25 26 - 51 52 - 61 62 63
6931
- // ASCII: 65 - 90 97 - 122 48 - 57 43 47
6932
- //
6933
- // Encode 6 bits in b into a new character.
6934
- Coder.prototype._encodeByte = function (b) {
6935
- // Encoding uses constant time operations as follows:
6936
- //
6937
- // 1. Define comparison of A with B using (A - B) >>> 8:
6938
- // if A > B, then result is positive integer
6939
- // if A <= B, then result is 0
6940
- //
6941
- // 2. Define selection of C or 0 using bitwise AND: X & C:
6942
- // if X == 0, then result is 0
6943
- // if X != 0, then result is C
6944
- //
6945
- // 3. Start with the smallest comparison (b >= 0), which is always
6946
- // true, so set the result to the starting ASCII value (65).
6947
- //
6948
- // 4. Continue comparing b to higher ASCII values, and selecting
6949
- // zero if comparison isn't true, otherwise selecting a value
6950
- // to add to result, which:
6951
- //
6952
- // a) undoes the previous addition
6953
- // b) provides new value to add
6954
- //
6955
- var result = b;
6956
- // b >= 0
6957
- result += 65;
6958
- // b > 25
6959
- result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
6960
- // b > 51
6961
- result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
6962
- // b > 61
6963
- result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43);
6964
- // b > 62
6965
- result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47);
6966
- return String.fromCharCode(result);
6967
- };
6968
- // Decode a character code into a byte.
6969
- // Must return 256 if character is out of alphabet range.
6970
- Coder.prototype._decodeChar = function (c) {
6971
- // Decoding works similar to encoding: using the same comparison
6972
- // function, but now it works on ranges: result is always incremented
6973
- // by value, but this value becomes zero if the range is not
6974
- // satisfied.
6975
- //
6976
- // Decoding starts with invalid value, 256, which is then
6977
- // subtracted when the range is satisfied. If none of the ranges
6978
- // apply, the function returns 256, which is then checked by
6979
- // the caller to throw error.
6980
- var result = INVALID_BYTE; // start with invalid character
6981
- // c == 43 (c > 42 and c < 44)
6982
- result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62);
6983
- // c == 47 (c > 46 and c < 48)
6984
- result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63);
6985
- // c > 47 and c < 58
6986
- result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
6987
- // c > 64 and c < 91
6988
- result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
6989
- // c > 96 and c < 123
6990
- result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
6991
- return result;
6992
- };
6993
- Coder.prototype._getPaddingLength = function (s) {
6994
- var paddingLength = 0;
6995
- if (this._paddingCharacter) {
6996
- for (var i = s.length - 1; i >= 0; i--) {
6997
- if (s[i] !== this._paddingCharacter) {
6998
- break;
6999
- }
7000
- paddingLength++;
7001
- }
7002
- if (s.length < 4 || paddingLength > 2) {
7003
- throw new Error("Base64Coder: incorrect padding");
7004
- }
7005
- }
7006
- return paddingLength;
7007
- };
7008
- return Coder;
7009
- }());
7010
- base64$1.Coder = Coder;
7011
- var stdCoder = new Coder();
7012
- function encode(data) {
7013
- return stdCoder.encode(data);
7014
- }
7015
- base64$1.encode = encode;
7016
- function decode(s) {
7017
- return stdCoder.decode(s);
7018
- }
7019
- base64$1.decode = decode;
7020
- /**
7021
- * Implements URL-safe Base64 encoding.
7022
- * (Same as Base64, but '+' is replaced with '-', and '/' with '_').
7023
- *
7024
- * Operates in constant time.
7025
- */
7026
- var URLSafeCoder = /** @class */ (function (_super) {
7027
- __extends(URLSafeCoder, _super);
7028
- function URLSafeCoder() {
7029
- return _super !== null && _super.apply(this, arguments) || this;
7030
- }
7031
- // URL-safe encoding have the following encoded/decoded ranges:
7032
- //
7033
- // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _
7034
- // Index: 0 - 25 26 - 51 52 - 61 62 63
7035
- // ASCII: 65 - 90 97 - 122 48 - 57 45 95
7036
- //
7037
- URLSafeCoder.prototype._encodeByte = function (b) {
7038
- var result = b;
7039
- // b >= 0
7040
- result += 65;
7041
- // b > 25
7042
- result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
7043
- // b > 51
7044
- result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
7045
- // b > 61
7046
- result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45);
7047
- // b > 62
7048
- result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95);
7049
- return String.fromCharCode(result);
7050
- };
7051
- URLSafeCoder.prototype._decodeChar = function (c) {
7052
- var result = INVALID_BYTE;
7053
- // c == 45 (c > 44 and c < 46)
7054
- result += (((44 - c) & (c - 46)) >>> 8) & (-INVALID_BYTE + c - 45 + 62);
7055
- // c == 95 (c > 94 and c < 96)
7056
- result += (((94 - c) & (c - 96)) >>> 8) & (-INVALID_BYTE + c - 95 + 63);
7057
- // c > 47 and c < 58
7058
- result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
7059
- // c > 64 and c < 91
7060
- result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
7061
- // c > 96 and c < 123
7062
- result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
7063
- return result;
7064
- };
7065
- return URLSafeCoder;
7066
- }(Coder));
7067
- base64$1.URLSafeCoder = URLSafeCoder;
7068
- var urlSafeCoder = new URLSafeCoder();
7069
- function encodeURLSafe(data) {
7070
- return urlSafeCoder.encode(data);
7071
- }
7072
- base64$1.encodeURLSafe = encodeURLSafe;
7073
- function decodeURLSafe(s) {
7074
- return urlSafeCoder.decode(s);
7075
- }
7076
- base64$1.decodeURLSafe = decodeURLSafe;
7077
- base64$1.encodedLength = function (length) {
7078
- return stdCoder.encodedLength(length);
7079
- };
7080
- base64$1.maxDecodedLength = function (length) {
7081
- return stdCoder.maxDecodedLength(length);
7082
- };
7083
- base64$1.decodedLength = function (s) {
7084
- return stdCoder.decodedLength(s);
7085
- };
7086
-
7087
- var sha256$1 = {exports: {}};
6026
+ var sha256$1 = {exports: {}};
7088
6027
 
7089
6028
  (function (module) {
7090
6029
  (function (root, factory) {
@@ -7526,96 +6465,1208 @@ class ExtendableError extends Error {
7526
6465
  this.name = "ExtendableError";
7527
6466
  this.stack = new Error(message).stack;
7528
6467
  }
7529
- }
7530
- class WebhookVerificationError extends ExtendableError {
7531
- constructor(message) {
7532
- super(message);
7533
- Object.setPrototypeOf(this, WebhookVerificationError.prototype);
7534
- this.name = "WebhookVerificationError";
6468
+ }
6469
+ class WebhookVerificationError extends ExtendableError {
6470
+ constructor(message) {
6471
+ super(message);
6472
+ Object.setPrototypeOf(this, WebhookVerificationError.prototype);
6473
+ this.name = "WebhookVerificationError";
6474
+ }
6475
+ }
6476
+ var WebhookVerificationError_1 = dist.WebhookVerificationError = WebhookVerificationError;
6477
+ class Webhook {
6478
+ constructor(secret, options) {
6479
+ if (!secret) {
6480
+ throw new Error("Secret can't be empty.");
6481
+ }
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) };
7090
+ }
7091
+ else {
7092
+ return __classPrivateFieldGet(this, _DodoPayments_encoder, "f").call(this, { body, headers });
7093
+ }
7094
+ }
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));
7535
7543
  }
7536
- }
7537
- var WebhookVerificationError_1 = dist.WebhookVerificationError = WebhookVerificationError;
7538
- class Webhook {
7539
- constructor(secret, options) {
7540
- if (!secret) {
7541
- throw new Error("Secret can't be empty.");
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");
7542
7600
  }
7543
- if ((options === null || options === void 0 ? void 0 : options.format) === "raw") {
7544
- if (secret instanceof Uint8Array) {
7545
- this.key = secret;
7546
- }
7547
- else {
7548
- this.key = Uint8Array.from(secret, (c) => c.charCodeAt(0));
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");
7549
7605
  }
7606
+ throw error(400, `Invalid query parameters.\n ${zodError.message}`);
7550
7607
  }
7551
- else {
7552
- if (typeof secret !== "string") {
7553
- throw new Error("Expected secret to be of type string");
7554
- }
7555
- if (secret.startsWith(Webhook.prefix)) {
7556
- secret = secret.substring(Webhook.prefix.length);
7557
- }
7558
- this.key = base64.decode(secret);
7608
+ let urlStr = "";
7609
+ try {
7610
+ urlStr = await buildCheckoutUrl({ queryParams: data, ...config });
7559
7611
  }
7560
- }
7561
- verify(payload, headers_) {
7562
- const headers = {};
7563
- for (const key of Object.keys(headers_)) {
7564
- headers[key.toLowerCase()] = headers_[key];
7612
+ catch (err) {
7613
+ throw error(400, err.message);
7565
7614
  }
7566
- const msgId = headers["webhook-id"];
7567
- const msgSignature = headers["webhook-signature"];
7568
- const msgTimestamp = headers["webhook-timestamp"];
7569
- if (!msgSignature || !msgId || !msgTimestamp) {
7570
- throw new WebhookVerificationError("Missing required 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();
7571
7621
  }
7572
- const timestamp = this.verifyTimestamp(msgTimestamp);
7573
- const computedSignature = this.sign(msgId, timestamp, payload);
7574
- const expectedSignature = computedSignature.split(",")[1];
7575
- const passedSignatures = msgSignature.split(" ");
7576
- const encoder = new globalThis.TextEncoder();
7577
- for (const versionedSignature of passedSignatures) {
7578
- const [version, signature] = versionedSignature.split(",");
7579
- if (version !== "v1") {
7580
- continue;
7622
+ catch (e) {
7623
+ throw error(400, "Invalid JSON body");
7624
+ }
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}`);
7581
7630
  }
7582
- if ((0, timing_safe_equal_1.timingSafeEqual)(encoder.encode(signature), encoder.encode(expectedSignature))) {
7583
- return JSON.parse(payload.toString());
7631
+ let urlStr = "";
7632
+ try {
7633
+ urlStr = await buildCheckoutUrl({
7634
+ body: data,
7635
+ ...config,
7636
+ type: "dynamic",
7637
+ });
7584
7638
  }
7585
- }
7586
- throw new WebhookVerificationError("No matching signature found");
7587
- }
7588
- sign(msgId, timestamp, payload) {
7589
- if (typeof payload === "string") ;
7590
- else if (payload.constructor.name === "Buffer") {
7591
- payload = payload.toString();
7639
+ catch (err) {
7640
+ throw error(400, err.message);
7641
+ }
7642
+ return Response.json({ checkout_url: urlStr });
7592
7643
  }
7593
7644
  else {
7594
- throw new Error("Expected payload to be of type string or Buffer.");
7595
- }
7596
- const encoder = new TextEncoder();
7597
- const timestampNumber = Math.floor(timestamp.getTime() / 1000);
7598
- const toSign = encoder.encode(`${msgId}.${timestampNumber}.${payload}`);
7599
- const expectedSignature = base64.encode(sha256.hmac(this.key, toSign));
7600
- return `v1,${expectedSignature}`;
7601
- }
7602
- verifyTimestamp(timestampHeader) {
7603
- const now = Math.floor(Date.now() / 1000);
7604
- const timestamp = parseInt(timestampHeader, 10);
7605
- if (isNaN(timestamp)) {
7606
- throw new WebhookVerificationError("Invalid Signature Headers");
7607
- }
7608
- if (now - timestamp > WEBHOOK_TOLERANCE_IN_SECONDS) {
7609
- throw new WebhookVerificationError("Message timestamp too old");
7610
- }
7611
- if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) {
7612
- throw new WebhookVerificationError("Message timestamp too new");
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 });
7613
7662
  }
7614
- return new Date(timestamp * 1000);
7615
- }
7616
- }
7617
- Webhook_1 = dist.Webhook = Webhook;
7618
- Webhook.prefix = "whsec_";
7663
+ };
7664
+ // SvelteKit expects named exports for HTTP verbs
7665
+ return {
7666
+ GET: getHandler,
7667
+ POST: postHandler,
7668
+ };
7669
+ };
7619
7670
 
7620
7671
  // src/schemas/webhook.ts
7621
7672
  var PaymentSchema = objectType({