@dodopayments/hono 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +274 -0
- package/dist/checkout/checkout.d.ts +4 -0
- package/dist/checkout/checkout.d.ts.map +1 -0
- package/dist/customer-portal/customer-portal.d.ts +5 -0
- package/dist/customer-portal/customer-portal.d.ts.map +1 -0
- package/dist/index.cjs +3617 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3613 -0
- package/dist/index.js.map +1 -0
- package/dist/webhooks/webhooks.d.ts +4 -0
- package/dist/webhooks/webhooks.d.ts.map +1 -0
- package/package.json +57 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,3617 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var zod = require('zod');
|
|
4
|
+
|
|
5
|
+
const VERSION = '1.42.0'; // x-release-please-version
|
|
6
|
+
|
|
7
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
8
|
+
class DodoPaymentsError extends Error {
|
|
9
|
+
}
|
|
10
|
+
class APIError extends DodoPaymentsError {
|
|
11
|
+
constructor(status, error, message, headers) {
|
|
12
|
+
super(`${APIError.makeMessage(status, error, message)}`);
|
|
13
|
+
this.status = status;
|
|
14
|
+
this.headers = headers;
|
|
15
|
+
this.error = error;
|
|
16
|
+
}
|
|
17
|
+
static makeMessage(status, error, message) {
|
|
18
|
+
const msg = error?.message ?
|
|
19
|
+
typeof error.message === 'string' ?
|
|
20
|
+
error.message
|
|
21
|
+
: JSON.stringify(error.message)
|
|
22
|
+
: error ? JSON.stringify(error)
|
|
23
|
+
: message;
|
|
24
|
+
if (status && msg) {
|
|
25
|
+
return `${status} ${msg}`;
|
|
26
|
+
}
|
|
27
|
+
if (status) {
|
|
28
|
+
return `${status} status code (no body)`;
|
|
29
|
+
}
|
|
30
|
+
if (msg) {
|
|
31
|
+
return msg;
|
|
32
|
+
}
|
|
33
|
+
return '(no status code or body)';
|
|
34
|
+
}
|
|
35
|
+
static generate(status, errorResponse, message, headers) {
|
|
36
|
+
if (!status || !headers) {
|
|
37
|
+
return new APIConnectionError({ message, cause: castToError(errorResponse) });
|
|
38
|
+
}
|
|
39
|
+
const error = errorResponse;
|
|
40
|
+
if (status === 400) {
|
|
41
|
+
return new BadRequestError(status, error, message, headers);
|
|
42
|
+
}
|
|
43
|
+
if (status === 401) {
|
|
44
|
+
return new AuthenticationError(status, error, message, headers);
|
|
45
|
+
}
|
|
46
|
+
if (status === 403) {
|
|
47
|
+
return new PermissionDeniedError(status, error, message, headers);
|
|
48
|
+
}
|
|
49
|
+
if (status === 404) {
|
|
50
|
+
return new NotFoundError(status, error, message, headers);
|
|
51
|
+
}
|
|
52
|
+
if (status === 409) {
|
|
53
|
+
return new ConflictError(status, error, message, headers);
|
|
54
|
+
}
|
|
55
|
+
if (status === 422) {
|
|
56
|
+
return new UnprocessableEntityError(status, error, message, headers);
|
|
57
|
+
}
|
|
58
|
+
if (status === 429) {
|
|
59
|
+
return new RateLimitError(status, error, message, headers);
|
|
60
|
+
}
|
|
61
|
+
if (status >= 500) {
|
|
62
|
+
return new InternalServerError(status, error, message, headers);
|
|
63
|
+
}
|
|
64
|
+
return new APIError(status, error, message, headers);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
class APIUserAbortError extends APIError {
|
|
68
|
+
constructor({ message } = {}) {
|
|
69
|
+
super(undefined, undefined, message || 'Request was aborted.', undefined);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
class APIConnectionError extends APIError {
|
|
73
|
+
constructor({ message, cause }) {
|
|
74
|
+
super(undefined, undefined, message || 'Connection error.', undefined);
|
|
75
|
+
// in some environments the 'cause' property is already declared
|
|
76
|
+
// @ts-ignore
|
|
77
|
+
if (cause)
|
|
78
|
+
this.cause = cause;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
class APIConnectionTimeoutError extends APIConnectionError {
|
|
82
|
+
constructor({ message } = {}) {
|
|
83
|
+
super({ message: message ?? 'Request timed out.' });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
class BadRequestError extends APIError {
|
|
87
|
+
}
|
|
88
|
+
class AuthenticationError extends APIError {
|
|
89
|
+
}
|
|
90
|
+
class PermissionDeniedError extends APIError {
|
|
91
|
+
}
|
|
92
|
+
class NotFoundError extends APIError {
|
|
93
|
+
}
|
|
94
|
+
class ConflictError extends APIError {
|
|
95
|
+
}
|
|
96
|
+
class UnprocessableEntityError extends APIError {
|
|
97
|
+
}
|
|
98
|
+
class RateLimitError extends APIError {
|
|
99
|
+
}
|
|
100
|
+
class InternalServerError extends APIError {
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
let auto = false;
|
|
104
|
+
let kind = undefined;
|
|
105
|
+
let fetch$1 = undefined;
|
|
106
|
+
let File$1 = undefined;
|
|
107
|
+
let getDefaultAgent = undefined;
|
|
108
|
+
let fileFromPath = undefined;
|
|
109
|
+
function setShims(shims, options = { auto: false }) {
|
|
110
|
+
if (auto) {
|
|
111
|
+
throw new Error(`you must \`import 'dodopayments/shims/${shims.kind}'\` before importing anything else from dodopayments`);
|
|
112
|
+
}
|
|
113
|
+
if (kind) {
|
|
114
|
+
throw new Error(`can't \`import 'dodopayments/shims/${shims.kind}'\` after \`import 'dodopayments/shims/${kind}'\``);
|
|
115
|
+
}
|
|
116
|
+
auto = options.auto;
|
|
117
|
+
kind = shims.kind;
|
|
118
|
+
fetch$1 = shims.fetch;
|
|
119
|
+
File$1 = shims.File;
|
|
120
|
+
getDefaultAgent = shims.getDefaultAgent;
|
|
121
|
+
fileFromPath = shims.fileFromPath;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
|
|
126
|
+
*/
|
|
127
|
+
class MultipartBody {
|
|
128
|
+
constructor(body) {
|
|
129
|
+
this.body = body;
|
|
130
|
+
}
|
|
131
|
+
get [Symbol.toStringTag]() {
|
|
132
|
+
return 'MultipartBody';
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function getRuntime({ manuallyImported } = {}) {
|
|
137
|
+
const recommendation = manuallyImported ?
|
|
138
|
+
`You may need to use polyfills`
|
|
139
|
+
: `Add one of these imports before your first \`import … from 'dodopayments'\`:
|
|
140
|
+
- \`import 'dodopayments/shims/node'\` (if you're running on Node)
|
|
141
|
+
- \`import 'dodopayments/shims/web'\` (otherwise)
|
|
142
|
+
`;
|
|
143
|
+
let _fetch, _Request, _Response, _Headers;
|
|
144
|
+
try {
|
|
145
|
+
// @ts-ignore
|
|
146
|
+
_fetch = fetch;
|
|
147
|
+
// @ts-ignore
|
|
148
|
+
_Request = Request;
|
|
149
|
+
// @ts-ignore
|
|
150
|
+
_Response = Response;
|
|
151
|
+
// @ts-ignore
|
|
152
|
+
_Headers = Headers;
|
|
153
|
+
}
|
|
154
|
+
catch (error) {
|
|
155
|
+
throw new Error(`this environment is missing the following Web Fetch API type: ${error.message}. ${recommendation}`);
|
|
156
|
+
}
|
|
157
|
+
return {
|
|
158
|
+
kind: 'web',
|
|
159
|
+
fetch: _fetch,
|
|
160
|
+
Request: _Request,
|
|
161
|
+
Response: _Response,
|
|
162
|
+
Headers: _Headers,
|
|
163
|
+
FormData:
|
|
164
|
+
// @ts-ignore
|
|
165
|
+
typeof FormData !== 'undefined' ? FormData : (class FormData {
|
|
166
|
+
// @ts-ignore
|
|
167
|
+
constructor() {
|
|
168
|
+
throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${recommendation}`);
|
|
169
|
+
}
|
|
170
|
+
}),
|
|
171
|
+
Blob: typeof Blob !== 'undefined' ? Blob : (class Blob {
|
|
172
|
+
constructor() {
|
|
173
|
+
throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${recommendation}`);
|
|
174
|
+
}
|
|
175
|
+
}),
|
|
176
|
+
File:
|
|
177
|
+
// @ts-ignore
|
|
178
|
+
typeof File !== 'undefined' ? File : (class File {
|
|
179
|
+
// @ts-ignore
|
|
180
|
+
constructor() {
|
|
181
|
+
throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${recommendation}`);
|
|
182
|
+
}
|
|
183
|
+
}),
|
|
184
|
+
ReadableStream:
|
|
185
|
+
// @ts-ignore
|
|
186
|
+
typeof ReadableStream !== 'undefined' ? ReadableStream : (class ReadableStream {
|
|
187
|
+
// @ts-ignore
|
|
188
|
+
constructor() {
|
|
189
|
+
throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${recommendation}`);
|
|
190
|
+
}
|
|
191
|
+
}),
|
|
192
|
+
getMultipartRequestOptions: async (
|
|
193
|
+
// @ts-ignore
|
|
194
|
+
form, opts) => ({
|
|
195
|
+
...opts,
|
|
196
|
+
body: new MultipartBody(form),
|
|
197
|
+
}),
|
|
198
|
+
getDefaultAgent: (url) => undefined,
|
|
199
|
+
fileFromPath: () => {
|
|
200
|
+
throw new Error('The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/dodopayments/dodopayments-node#file-uploads');
|
|
201
|
+
},
|
|
202
|
+
isFsReadStream: (value) => false,
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Disclaimer: modules in _shims aren't intended to be imported by SDK users.
|
|
208
|
+
*/
|
|
209
|
+
const init = () => {
|
|
210
|
+
if (!kind) setShims(getRuntime(), { auto: true });
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
init();
|
|
214
|
+
|
|
215
|
+
const isResponseLike = (value) => value != null &&
|
|
216
|
+
typeof value === 'object' &&
|
|
217
|
+
typeof value.url === 'string' &&
|
|
218
|
+
typeof value.blob === 'function';
|
|
219
|
+
const isFileLike = (value) => value != null &&
|
|
220
|
+
typeof value === 'object' &&
|
|
221
|
+
typeof value.name === 'string' &&
|
|
222
|
+
typeof value.lastModified === 'number' &&
|
|
223
|
+
isBlobLike(value);
|
|
224
|
+
/**
|
|
225
|
+
* The BlobLike type omits arrayBuffer() because @types/node-fetch@^2.6.4 lacks it; but this check
|
|
226
|
+
* adds the arrayBuffer() method type because it is available and used at runtime
|
|
227
|
+
*/
|
|
228
|
+
const isBlobLike = (value) => value != null &&
|
|
229
|
+
typeof value === 'object' &&
|
|
230
|
+
typeof value.size === 'number' &&
|
|
231
|
+
typeof value.type === 'string' &&
|
|
232
|
+
typeof value.text === 'function' &&
|
|
233
|
+
typeof value.slice === 'function' &&
|
|
234
|
+
typeof value.arrayBuffer === 'function';
|
|
235
|
+
/**
|
|
236
|
+
* Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats
|
|
237
|
+
* @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s
|
|
238
|
+
* @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible
|
|
239
|
+
* @param {Object=} options additional properties
|
|
240
|
+
* @param {string=} options.type the MIME type of the content
|
|
241
|
+
* @param {number=} options.lastModified the last modified timestamp
|
|
242
|
+
* @returns a {@link File} with the given properties
|
|
243
|
+
*/
|
|
244
|
+
async function toFile(value, name, options) {
|
|
245
|
+
// If it's a promise, resolve it.
|
|
246
|
+
value = await value;
|
|
247
|
+
// If we've been given a `File` we don't need to do anything
|
|
248
|
+
if (isFileLike(value)) {
|
|
249
|
+
return value;
|
|
250
|
+
}
|
|
251
|
+
if (isResponseLike(value)) {
|
|
252
|
+
const blob = await value.blob();
|
|
253
|
+
name || (name = new URL(value.url).pathname.split(/[\\/]/).pop() ?? 'unknown_file');
|
|
254
|
+
// we need to convert the `Blob` into an array buffer because the `Blob` class
|
|
255
|
+
// that `node-fetch` defines is incompatible with the web standard which results
|
|
256
|
+
// in `new File` interpreting it as a string instead of binary data.
|
|
257
|
+
const data = isBlobLike(blob) ? [(await blob.arrayBuffer())] : [blob];
|
|
258
|
+
return new File$1(data, name, options);
|
|
259
|
+
}
|
|
260
|
+
const bits = await getBytes(value);
|
|
261
|
+
name || (name = getName(value) ?? 'unknown_file');
|
|
262
|
+
if (!options?.type) {
|
|
263
|
+
const type = bits[0]?.type;
|
|
264
|
+
if (typeof type === 'string') {
|
|
265
|
+
options = { ...options, type };
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
return new File$1(bits, name, options);
|
|
269
|
+
}
|
|
270
|
+
async function getBytes(value) {
|
|
271
|
+
let parts = [];
|
|
272
|
+
if (typeof value === 'string' ||
|
|
273
|
+
ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
|
|
274
|
+
value instanceof ArrayBuffer) {
|
|
275
|
+
parts.push(value);
|
|
276
|
+
}
|
|
277
|
+
else if (isBlobLike(value)) {
|
|
278
|
+
parts.push(await value.arrayBuffer());
|
|
279
|
+
}
|
|
280
|
+
else if (isAsyncIterableIterator(value) // includes Readable, ReadableStream, etc.
|
|
281
|
+
) {
|
|
282
|
+
for await (const chunk of value) {
|
|
283
|
+
parts.push(chunk); // TODO, consider validating?
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
else {
|
|
287
|
+
throw new Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor
|
|
288
|
+
?.name}; props: ${propsForError(value)}`);
|
|
289
|
+
}
|
|
290
|
+
return parts;
|
|
291
|
+
}
|
|
292
|
+
function propsForError(value) {
|
|
293
|
+
const props = Object.getOwnPropertyNames(value);
|
|
294
|
+
return `[${props.map((p) => `"${p}"`).join(', ')}]`;
|
|
295
|
+
}
|
|
296
|
+
function getName(value) {
|
|
297
|
+
return (getStringFromMaybeBuffer(value.name) ||
|
|
298
|
+
getStringFromMaybeBuffer(value.filename) ||
|
|
299
|
+
// For fs.ReadStream
|
|
300
|
+
getStringFromMaybeBuffer(value.path)?.split(/[\\/]/).pop());
|
|
301
|
+
}
|
|
302
|
+
const getStringFromMaybeBuffer = (x) => {
|
|
303
|
+
if (typeof x === 'string')
|
|
304
|
+
return x;
|
|
305
|
+
if (typeof Buffer !== 'undefined' && x instanceof Buffer)
|
|
306
|
+
return String(x);
|
|
307
|
+
return undefined;
|
|
308
|
+
};
|
|
309
|
+
const isAsyncIterableIterator = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function';
|
|
310
|
+
const isMultipartBody = (body) => body && typeof body === 'object' && body.body && body[Symbol.toStringTag] === 'MultipartBody';
|
|
311
|
+
|
|
312
|
+
var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
313
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
314
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
315
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
316
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
317
|
+
};
|
|
318
|
+
var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
319
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
320
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
321
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
322
|
+
};
|
|
323
|
+
var _APIClient_baseURLOverridden, _AbstractPage_client;
|
|
324
|
+
// try running side effects outside of _shims/index to workaround https://github.com/vercel/next.js/issues/76881
|
|
325
|
+
init();
|
|
326
|
+
async function defaultParseResponse(props) {
|
|
327
|
+
const { response } = props;
|
|
328
|
+
// fetch refuses to read the body when the status code is 204.
|
|
329
|
+
if (response.status === 204) {
|
|
330
|
+
return null;
|
|
331
|
+
}
|
|
332
|
+
if (props.options.__binaryResponse) {
|
|
333
|
+
return response;
|
|
334
|
+
}
|
|
335
|
+
const contentType = response.headers.get('content-type');
|
|
336
|
+
const mediaType = contentType?.split(';')[0]?.trim();
|
|
337
|
+
const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json');
|
|
338
|
+
if (isJSON) {
|
|
339
|
+
const json = await response.json();
|
|
340
|
+
debug('response', response.status, response.url, response.headers, json);
|
|
341
|
+
return json;
|
|
342
|
+
}
|
|
343
|
+
const text = await response.text();
|
|
344
|
+
debug('response', response.status, response.url, response.headers, text);
|
|
345
|
+
// TODO handle blob, arraybuffer, other content types, etc.
|
|
346
|
+
return text;
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* A subclass of `Promise` providing additional helper methods
|
|
350
|
+
* for interacting with the SDK.
|
|
351
|
+
*/
|
|
352
|
+
class APIPromise extends Promise {
|
|
353
|
+
constructor(responsePromise, parseResponse = defaultParseResponse) {
|
|
354
|
+
super((resolve) => {
|
|
355
|
+
// this is maybe a bit weird but this has to be a no-op to not implicitly
|
|
356
|
+
// parse the response body; instead .then, .catch, .finally are overridden
|
|
357
|
+
// to parse the response
|
|
358
|
+
resolve(null);
|
|
359
|
+
});
|
|
360
|
+
this.responsePromise = responsePromise;
|
|
361
|
+
this.parseResponse = parseResponse;
|
|
362
|
+
}
|
|
363
|
+
_thenUnwrap(transform) {
|
|
364
|
+
return new APIPromise(this.responsePromise, async (props) => transform(await this.parseResponse(props), props));
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* Gets the raw `Response` instance instead of parsing the response
|
|
368
|
+
* data.
|
|
369
|
+
*
|
|
370
|
+
* If you want to parse the response body but still get the `Response`
|
|
371
|
+
* instance, you can use {@link withResponse()}.
|
|
372
|
+
*
|
|
373
|
+
* 👋 Getting the wrong TypeScript type for `Response`?
|
|
374
|
+
* Try setting `"moduleResolution": "NodeNext"` if you can,
|
|
375
|
+
* or add one of these imports before your first `import … from 'dodopayments'`:
|
|
376
|
+
* - `import 'dodopayments/shims/node'` (if you're running on Node)
|
|
377
|
+
* - `import 'dodopayments/shims/web'` (otherwise)
|
|
378
|
+
*/
|
|
379
|
+
asResponse() {
|
|
380
|
+
return this.responsePromise.then((p) => p.response);
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* Gets the parsed response data and the raw `Response` instance.
|
|
384
|
+
*
|
|
385
|
+
* If you just want to get the raw `Response` instance without parsing it,
|
|
386
|
+
* you can use {@link asResponse()}.
|
|
387
|
+
*
|
|
388
|
+
*
|
|
389
|
+
* 👋 Getting the wrong TypeScript type for `Response`?
|
|
390
|
+
* Try setting `"moduleResolution": "NodeNext"` if you can,
|
|
391
|
+
* or add one of these imports before your first `import … from 'dodopayments'`:
|
|
392
|
+
* - `import 'dodopayments/shims/node'` (if you're running on Node)
|
|
393
|
+
* - `import 'dodopayments/shims/web'` (otherwise)
|
|
394
|
+
*/
|
|
395
|
+
async withResponse() {
|
|
396
|
+
const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
|
|
397
|
+
return { data, response };
|
|
398
|
+
}
|
|
399
|
+
parse() {
|
|
400
|
+
if (!this.parsedPromise) {
|
|
401
|
+
this.parsedPromise = this.responsePromise.then(this.parseResponse);
|
|
402
|
+
}
|
|
403
|
+
return this.parsedPromise;
|
|
404
|
+
}
|
|
405
|
+
then(onfulfilled, onrejected) {
|
|
406
|
+
return this.parse().then(onfulfilled, onrejected);
|
|
407
|
+
}
|
|
408
|
+
catch(onrejected) {
|
|
409
|
+
return this.parse().catch(onrejected);
|
|
410
|
+
}
|
|
411
|
+
finally(onfinally) {
|
|
412
|
+
return this.parse().finally(onfinally);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
class APIClient {
|
|
416
|
+
constructor({ baseURL, baseURLOverridden, maxRetries = 2, timeout = 60000, // 1 minute
|
|
417
|
+
httpAgent, fetch: overriddenFetch, }) {
|
|
418
|
+
_APIClient_baseURLOverridden.set(this, void 0);
|
|
419
|
+
this.baseURL = baseURL;
|
|
420
|
+
__classPrivateFieldSet(this, _APIClient_baseURLOverridden, baseURLOverridden, "f");
|
|
421
|
+
this.maxRetries = validatePositiveInteger('maxRetries', maxRetries);
|
|
422
|
+
this.timeout = validatePositiveInteger('timeout', timeout);
|
|
423
|
+
this.httpAgent = httpAgent;
|
|
424
|
+
this.fetch = overriddenFetch ?? fetch$1;
|
|
425
|
+
}
|
|
426
|
+
authHeaders(opts) {
|
|
427
|
+
return {};
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* Override this to add your own default headers, for example:
|
|
431
|
+
*
|
|
432
|
+
* {
|
|
433
|
+
* ...super.defaultHeaders(),
|
|
434
|
+
* Authorization: 'Bearer 123',
|
|
435
|
+
* }
|
|
436
|
+
*/
|
|
437
|
+
defaultHeaders(opts) {
|
|
438
|
+
return {
|
|
439
|
+
Accept: 'application/json',
|
|
440
|
+
...(['head', 'get'].includes(opts.method) ? {} : { 'Content-Type': 'application/json' }),
|
|
441
|
+
'User-Agent': this.getUserAgent(),
|
|
442
|
+
...getPlatformHeaders(),
|
|
443
|
+
...this.authHeaders(opts),
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* Override this to add your own headers validation:
|
|
448
|
+
*/
|
|
449
|
+
validateHeaders(headers, customHeaders) { }
|
|
450
|
+
defaultIdempotencyKey() {
|
|
451
|
+
return `stainless-node-retry-${uuid4()}`;
|
|
452
|
+
}
|
|
453
|
+
get(path, opts) {
|
|
454
|
+
return this.methodRequest('get', path, opts);
|
|
455
|
+
}
|
|
456
|
+
post(path, opts) {
|
|
457
|
+
return this.methodRequest('post', path, opts);
|
|
458
|
+
}
|
|
459
|
+
patch(path, opts) {
|
|
460
|
+
return this.methodRequest('patch', path, opts);
|
|
461
|
+
}
|
|
462
|
+
put(path, opts) {
|
|
463
|
+
return this.methodRequest('put', path, opts);
|
|
464
|
+
}
|
|
465
|
+
delete(path, opts) {
|
|
466
|
+
return this.methodRequest('delete', path, opts);
|
|
467
|
+
}
|
|
468
|
+
methodRequest(method, path, opts) {
|
|
469
|
+
return this.request(Promise.resolve(opts).then(async (opts) => {
|
|
470
|
+
const body = opts && isBlobLike(opts?.body) ? new DataView(await opts.body.arrayBuffer())
|
|
471
|
+
: opts?.body instanceof DataView ? opts.body
|
|
472
|
+
: opts?.body instanceof ArrayBuffer ? new DataView(opts.body)
|
|
473
|
+
: opts && ArrayBuffer.isView(opts?.body) ? new DataView(opts.body.buffer)
|
|
474
|
+
: opts?.body;
|
|
475
|
+
return { method, path, ...opts, body };
|
|
476
|
+
}));
|
|
477
|
+
}
|
|
478
|
+
getAPIList(path, Page, opts) {
|
|
479
|
+
return this.requestAPIList(Page, { method: 'get', path, ...opts });
|
|
480
|
+
}
|
|
481
|
+
calculateContentLength(body) {
|
|
482
|
+
if (typeof body === 'string') {
|
|
483
|
+
if (typeof Buffer !== 'undefined') {
|
|
484
|
+
return Buffer.byteLength(body, 'utf8').toString();
|
|
485
|
+
}
|
|
486
|
+
if (typeof TextEncoder !== 'undefined') {
|
|
487
|
+
const encoder = new TextEncoder();
|
|
488
|
+
const encoded = encoder.encode(body);
|
|
489
|
+
return encoded.length.toString();
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
else if (ArrayBuffer.isView(body)) {
|
|
493
|
+
return body.byteLength.toString();
|
|
494
|
+
}
|
|
495
|
+
return null;
|
|
496
|
+
}
|
|
497
|
+
async buildRequest(inputOptions, { retryCount = 0 } = {}) {
|
|
498
|
+
const options = { ...inputOptions };
|
|
499
|
+
const { method, path, query, defaultBaseURL, headers: headers = {} } = options;
|
|
500
|
+
const body = ArrayBuffer.isView(options.body) || (options.__binaryRequest && typeof options.body === 'string') ?
|
|
501
|
+
options.body
|
|
502
|
+
: isMultipartBody(options.body) ? options.body.body
|
|
503
|
+
: options.body ? JSON.stringify(options.body, null, 2)
|
|
504
|
+
: null;
|
|
505
|
+
const contentLength = this.calculateContentLength(body);
|
|
506
|
+
const url = this.buildURL(path, query, defaultBaseURL);
|
|
507
|
+
if ('timeout' in options)
|
|
508
|
+
validatePositiveInteger('timeout', options.timeout);
|
|
509
|
+
options.timeout = options.timeout ?? this.timeout;
|
|
510
|
+
const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url);
|
|
511
|
+
const minAgentTimeout = options.timeout + 1000;
|
|
512
|
+
if (typeof httpAgent?.options?.timeout === 'number' &&
|
|
513
|
+
minAgentTimeout > (httpAgent.options.timeout ?? 0)) {
|
|
514
|
+
// Allow any given request to bump our agent active socket timeout.
|
|
515
|
+
// This may seem strange, but leaking active sockets should be rare and not particularly problematic,
|
|
516
|
+
// and without mutating agent we would need to create more of them.
|
|
517
|
+
// This tradeoff optimizes for performance.
|
|
518
|
+
httpAgent.options.timeout = minAgentTimeout;
|
|
519
|
+
}
|
|
520
|
+
if (this.idempotencyHeader && method !== 'get') {
|
|
521
|
+
if (!inputOptions.idempotencyKey)
|
|
522
|
+
inputOptions.idempotencyKey = this.defaultIdempotencyKey();
|
|
523
|
+
headers[this.idempotencyHeader] = inputOptions.idempotencyKey;
|
|
524
|
+
}
|
|
525
|
+
const reqHeaders = this.buildHeaders({ options, headers, contentLength, retryCount });
|
|
526
|
+
const req = {
|
|
527
|
+
method,
|
|
528
|
+
...(body && { body: body }),
|
|
529
|
+
headers: reqHeaders,
|
|
530
|
+
...(httpAgent && { agent: httpAgent }),
|
|
531
|
+
// @ts-ignore node-fetch uses a custom AbortSignal type that is
|
|
532
|
+
// not compatible with standard web types
|
|
533
|
+
signal: options.signal ?? null,
|
|
534
|
+
};
|
|
535
|
+
return { req, url, timeout: options.timeout };
|
|
536
|
+
}
|
|
537
|
+
buildHeaders({ options, headers, contentLength, retryCount, }) {
|
|
538
|
+
const reqHeaders = {};
|
|
539
|
+
if (contentLength) {
|
|
540
|
+
reqHeaders['content-length'] = contentLength;
|
|
541
|
+
}
|
|
542
|
+
const defaultHeaders = this.defaultHeaders(options);
|
|
543
|
+
applyHeadersMut(reqHeaders, defaultHeaders);
|
|
544
|
+
applyHeadersMut(reqHeaders, headers);
|
|
545
|
+
// let builtin fetch set the Content-Type for multipart bodies
|
|
546
|
+
if (isMultipartBody(options.body) && kind !== 'node') {
|
|
547
|
+
delete reqHeaders['content-type'];
|
|
548
|
+
}
|
|
549
|
+
// Don't set theses headers if they were already set or removed through default headers or by the caller.
|
|
550
|
+
// We check `defaultHeaders` and `headers`, which can contain nulls, instead of `reqHeaders` to account
|
|
551
|
+
// for the removal case.
|
|
552
|
+
if (getHeader(defaultHeaders, 'x-stainless-retry-count') === undefined &&
|
|
553
|
+
getHeader(headers, 'x-stainless-retry-count') === undefined) {
|
|
554
|
+
reqHeaders['x-stainless-retry-count'] = String(retryCount);
|
|
555
|
+
}
|
|
556
|
+
if (getHeader(defaultHeaders, 'x-stainless-timeout') === undefined &&
|
|
557
|
+
getHeader(headers, 'x-stainless-timeout') === undefined &&
|
|
558
|
+
options.timeout) {
|
|
559
|
+
reqHeaders['x-stainless-timeout'] = String(Math.trunc(options.timeout / 1000));
|
|
560
|
+
}
|
|
561
|
+
this.validateHeaders(reqHeaders, headers);
|
|
562
|
+
return reqHeaders;
|
|
563
|
+
}
|
|
564
|
+
/**
|
|
565
|
+
* Used as a callback for mutating the given `FinalRequestOptions` object.
|
|
566
|
+
*/
|
|
567
|
+
async prepareOptions(options) { }
|
|
568
|
+
/**
|
|
569
|
+
* Used as a callback for mutating the given `RequestInit` object.
|
|
570
|
+
*
|
|
571
|
+
* This is useful for cases where you want to add certain headers based off of
|
|
572
|
+
* the request properties, e.g. `method` or `url`.
|
|
573
|
+
*/
|
|
574
|
+
async prepareRequest(request, { url, options }) { }
|
|
575
|
+
parseHeaders(headers) {
|
|
576
|
+
return (!headers ? {}
|
|
577
|
+
: Symbol.iterator in headers ?
|
|
578
|
+
Object.fromEntries(Array.from(headers).map((header) => [...header]))
|
|
579
|
+
: { ...headers });
|
|
580
|
+
}
|
|
581
|
+
makeStatusError(status, error, message, headers) {
|
|
582
|
+
return APIError.generate(status, error, message, headers);
|
|
583
|
+
}
|
|
584
|
+
request(options, remainingRetries = null) {
|
|
585
|
+
return new APIPromise(this.makeRequest(options, remainingRetries));
|
|
586
|
+
}
|
|
587
|
+
async makeRequest(optionsInput, retriesRemaining) {
|
|
588
|
+
const options = await optionsInput;
|
|
589
|
+
const maxRetries = options.maxRetries ?? this.maxRetries;
|
|
590
|
+
if (retriesRemaining == null) {
|
|
591
|
+
retriesRemaining = maxRetries;
|
|
592
|
+
}
|
|
593
|
+
await this.prepareOptions(options);
|
|
594
|
+
const { req, url, timeout } = await this.buildRequest(options, {
|
|
595
|
+
retryCount: maxRetries - retriesRemaining,
|
|
596
|
+
});
|
|
597
|
+
await this.prepareRequest(req, { url, options });
|
|
598
|
+
debug('request', url, options, req.headers);
|
|
599
|
+
if (options.signal?.aborted) {
|
|
600
|
+
throw new APIUserAbortError();
|
|
601
|
+
}
|
|
602
|
+
const controller = new AbortController();
|
|
603
|
+
const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
|
|
604
|
+
if (response instanceof Error) {
|
|
605
|
+
if (options.signal?.aborted) {
|
|
606
|
+
throw new APIUserAbortError();
|
|
607
|
+
}
|
|
608
|
+
if (retriesRemaining) {
|
|
609
|
+
return this.retryRequest(options, retriesRemaining);
|
|
610
|
+
}
|
|
611
|
+
if (response.name === 'AbortError') {
|
|
612
|
+
throw new APIConnectionTimeoutError();
|
|
613
|
+
}
|
|
614
|
+
throw new APIConnectionError({ cause: response });
|
|
615
|
+
}
|
|
616
|
+
const responseHeaders = createResponseHeaders(response.headers);
|
|
617
|
+
if (!response.ok) {
|
|
618
|
+
if (retriesRemaining && this.shouldRetry(response)) {
|
|
619
|
+
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
|
|
620
|
+
debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders);
|
|
621
|
+
return this.retryRequest(options, retriesRemaining, responseHeaders);
|
|
622
|
+
}
|
|
623
|
+
const errText = await response.text().catch((e) => castToError(e).message);
|
|
624
|
+
const errJSON = safeJSON(errText);
|
|
625
|
+
const errMessage = errJSON ? undefined : errText;
|
|
626
|
+
const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`;
|
|
627
|
+
debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders, errMessage);
|
|
628
|
+
const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);
|
|
629
|
+
throw err;
|
|
630
|
+
}
|
|
631
|
+
return { response, options, controller };
|
|
632
|
+
}
|
|
633
|
+
requestAPIList(Page, options) {
|
|
634
|
+
const request = this.makeRequest(options, null);
|
|
635
|
+
return new PagePromise(this, request, Page);
|
|
636
|
+
}
|
|
637
|
+
buildURL(path, query, defaultBaseURL) {
|
|
638
|
+
const baseURL = (!__classPrivateFieldGet(this, _APIClient_baseURLOverridden, "f") && defaultBaseURL) || this.baseURL;
|
|
639
|
+
const url = isAbsoluteURL(path) ?
|
|
640
|
+
new URL(path)
|
|
641
|
+
: new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
|
|
642
|
+
const defaultQuery = this.defaultQuery();
|
|
643
|
+
if (!isEmptyObj(defaultQuery)) {
|
|
644
|
+
query = { ...defaultQuery, ...query };
|
|
645
|
+
}
|
|
646
|
+
if (typeof query === 'object' && query && !Array.isArray(query)) {
|
|
647
|
+
url.search = this.stringifyQuery(query);
|
|
648
|
+
}
|
|
649
|
+
return url.toString();
|
|
650
|
+
}
|
|
651
|
+
stringifyQuery(query) {
|
|
652
|
+
return Object.entries(query)
|
|
653
|
+
.filter(([_, value]) => typeof value !== 'undefined')
|
|
654
|
+
.map(([key, value]) => {
|
|
655
|
+
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
|
656
|
+
return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
|
|
657
|
+
}
|
|
658
|
+
if (value === null) {
|
|
659
|
+
return `${encodeURIComponent(key)}=`;
|
|
660
|
+
}
|
|
661
|
+
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.`);
|
|
662
|
+
})
|
|
663
|
+
.join('&');
|
|
664
|
+
}
|
|
665
|
+
async fetchWithTimeout(url, init, ms, controller) {
|
|
666
|
+
const { signal, ...options } = init || {};
|
|
667
|
+
if (signal)
|
|
668
|
+
signal.addEventListener('abort', () => controller.abort());
|
|
669
|
+
const timeout = setTimeout(() => controller.abort(), ms);
|
|
670
|
+
const fetchOptions = {
|
|
671
|
+
signal: controller.signal,
|
|
672
|
+
...options,
|
|
673
|
+
};
|
|
674
|
+
if (fetchOptions.method) {
|
|
675
|
+
// Custom methods like 'patch' need to be uppercased
|
|
676
|
+
// See https://github.com/nodejs/undici/issues/2294
|
|
677
|
+
fetchOptions.method = fetchOptions.method.toUpperCase();
|
|
678
|
+
}
|
|
679
|
+
return (
|
|
680
|
+
// use undefined this binding; fetch errors if bound to something else in browser/cloudflare
|
|
681
|
+
this.fetch.call(undefined, url, fetchOptions).finally(() => {
|
|
682
|
+
clearTimeout(timeout);
|
|
683
|
+
}));
|
|
684
|
+
}
|
|
685
|
+
shouldRetry(response) {
|
|
686
|
+
// Note this is not a standard header.
|
|
687
|
+
const shouldRetryHeader = response.headers.get('x-should-retry');
|
|
688
|
+
// If the server explicitly says whether or not to retry, obey.
|
|
689
|
+
if (shouldRetryHeader === 'true')
|
|
690
|
+
return true;
|
|
691
|
+
if (shouldRetryHeader === 'false')
|
|
692
|
+
return false;
|
|
693
|
+
// Retry on request timeouts.
|
|
694
|
+
if (response.status === 408)
|
|
695
|
+
return true;
|
|
696
|
+
// Retry on lock timeouts.
|
|
697
|
+
if (response.status === 409)
|
|
698
|
+
return true;
|
|
699
|
+
// Retry on rate limits.
|
|
700
|
+
if (response.status === 429)
|
|
701
|
+
return true;
|
|
702
|
+
// Retry internal errors.
|
|
703
|
+
if (response.status >= 500)
|
|
704
|
+
return true;
|
|
705
|
+
return false;
|
|
706
|
+
}
|
|
707
|
+
async retryRequest(options, retriesRemaining, responseHeaders) {
|
|
708
|
+
let timeoutMillis;
|
|
709
|
+
// Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
|
|
710
|
+
const retryAfterMillisHeader = responseHeaders?.['retry-after-ms'];
|
|
711
|
+
if (retryAfterMillisHeader) {
|
|
712
|
+
const timeoutMs = parseFloat(retryAfterMillisHeader);
|
|
713
|
+
if (!Number.isNaN(timeoutMs)) {
|
|
714
|
+
timeoutMillis = timeoutMs;
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
// About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
|
|
718
|
+
const retryAfterHeader = responseHeaders?.['retry-after'];
|
|
719
|
+
if (retryAfterHeader && !timeoutMillis) {
|
|
720
|
+
const timeoutSeconds = parseFloat(retryAfterHeader);
|
|
721
|
+
if (!Number.isNaN(timeoutSeconds)) {
|
|
722
|
+
timeoutMillis = timeoutSeconds * 1000;
|
|
723
|
+
}
|
|
724
|
+
else {
|
|
725
|
+
timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
// If the API asks us to wait a certain amount of time (and it's a reasonable amount),
|
|
729
|
+
// just do what it says, but otherwise calculate a default
|
|
730
|
+
if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
|
|
731
|
+
const maxRetries = options.maxRetries ?? this.maxRetries;
|
|
732
|
+
timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
|
|
733
|
+
}
|
|
734
|
+
await sleep(timeoutMillis);
|
|
735
|
+
return this.makeRequest(options, retriesRemaining - 1);
|
|
736
|
+
}
|
|
737
|
+
calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
|
|
738
|
+
const initialRetryDelay = 0.5;
|
|
739
|
+
const maxRetryDelay = 8.0;
|
|
740
|
+
const numRetries = maxRetries - retriesRemaining;
|
|
741
|
+
// Apply exponential backoff, but not more than the max.
|
|
742
|
+
const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
|
|
743
|
+
// Apply some jitter, take up to at most 25 percent of the retry time.
|
|
744
|
+
const jitter = 1 - Math.random() * 0.25;
|
|
745
|
+
return sleepSeconds * jitter * 1000;
|
|
746
|
+
}
|
|
747
|
+
getUserAgent() {
|
|
748
|
+
return `${this.constructor.name}/JS ${VERSION}`;
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
_APIClient_baseURLOverridden = new WeakMap();
|
|
752
|
+
class AbstractPage {
|
|
753
|
+
constructor(client, response, body, options) {
|
|
754
|
+
_AbstractPage_client.set(this, void 0);
|
|
755
|
+
__classPrivateFieldSet(this, _AbstractPage_client, client, "f");
|
|
756
|
+
this.options = options;
|
|
757
|
+
this.response = response;
|
|
758
|
+
this.body = body;
|
|
759
|
+
}
|
|
760
|
+
hasNextPage() {
|
|
761
|
+
const items = this.getPaginatedItems();
|
|
762
|
+
if (!items.length)
|
|
763
|
+
return false;
|
|
764
|
+
return this.nextPageInfo() != null;
|
|
765
|
+
}
|
|
766
|
+
async getNextPage() {
|
|
767
|
+
const nextInfo = this.nextPageInfo();
|
|
768
|
+
if (!nextInfo) {
|
|
769
|
+
throw new DodoPaymentsError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.');
|
|
770
|
+
}
|
|
771
|
+
const nextOptions = { ...this.options };
|
|
772
|
+
if ('params' in nextInfo && typeof nextOptions.query === 'object') {
|
|
773
|
+
nextOptions.query = { ...nextOptions.query, ...nextInfo.params };
|
|
774
|
+
}
|
|
775
|
+
else if ('url' in nextInfo) {
|
|
776
|
+
const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];
|
|
777
|
+
for (const [key, value] of params) {
|
|
778
|
+
nextInfo.url.searchParams.set(key, value);
|
|
779
|
+
}
|
|
780
|
+
nextOptions.query = undefined;
|
|
781
|
+
nextOptions.path = nextInfo.url.toString();
|
|
782
|
+
}
|
|
783
|
+
return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
|
|
784
|
+
}
|
|
785
|
+
async *iterPages() {
|
|
786
|
+
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
787
|
+
let page = this;
|
|
788
|
+
yield page;
|
|
789
|
+
while (page.hasNextPage()) {
|
|
790
|
+
page = await page.getNextPage();
|
|
791
|
+
yield page;
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() {
|
|
795
|
+
for await (const page of this.iterPages()) {
|
|
796
|
+
for (const item of page.getPaginatedItems()) {
|
|
797
|
+
yield item;
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
/**
|
|
803
|
+
* This subclass of Promise will resolve to an instantiated Page once the request completes.
|
|
804
|
+
*
|
|
805
|
+
* It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:
|
|
806
|
+
*
|
|
807
|
+
* for await (const item of client.items.list()) {
|
|
808
|
+
* console.log(item)
|
|
809
|
+
* }
|
|
810
|
+
*/
|
|
811
|
+
class PagePromise extends APIPromise {
|
|
812
|
+
constructor(client, request, Page) {
|
|
813
|
+
super(request, async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options));
|
|
814
|
+
}
|
|
815
|
+
/**
|
|
816
|
+
* Allow auto-paginating iteration on an unawaited list call, eg:
|
|
817
|
+
*
|
|
818
|
+
* for await (const item of client.items.list()) {
|
|
819
|
+
* console.log(item)
|
|
820
|
+
* }
|
|
821
|
+
*/
|
|
822
|
+
async *[Symbol.asyncIterator]() {
|
|
823
|
+
const page = await this;
|
|
824
|
+
for await (const item of page) {
|
|
825
|
+
yield item;
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
const createResponseHeaders = (headers) => {
|
|
830
|
+
return new Proxy(Object.fromEntries(
|
|
831
|
+
// @ts-ignore
|
|
832
|
+
headers.entries()), {
|
|
833
|
+
get(target, name) {
|
|
834
|
+
const key = name.toString();
|
|
835
|
+
return target[key.toLowerCase()] || target[key];
|
|
836
|
+
},
|
|
837
|
+
});
|
|
838
|
+
};
|
|
839
|
+
// This is required so that we can determine if a given object matches the RequestOptions
|
|
840
|
+
// type at runtime. While this requires duplication, it is enforced by the TypeScript
|
|
841
|
+
// compiler such that any missing / extraneous keys will cause an error.
|
|
842
|
+
const requestOptionsKeys = {
|
|
843
|
+
method: true,
|
|
844
|
+
path: true,
|
|
845
|
+
query: true,
|
|
846
|
+
body: true,
|
|
847
|
+
headers: true,
|
|
848
|
+
defaultBaseURL: true,
|
|
849
|
+
maxRetries: true,
|
|
850
|
+
stream: true,
|
|
851
|
+
timeout: true,
|
|
852
|
+
httpAgent: true,
|
|
853
|
+
signal: true,
|
|
854
|
+
idempotencyKey: true,
|
|
855
|
+
__binaryRequest: true,
|
|
856
|
+
__binaryResponse: true,
|
|
857
|
+
};
|
|
858
|
+
const isRequestOptions = (obj) => {
|
|
859
|
+
return (typeof obj === 'object' &&
|
|
860
|
+
obj !== null &&
|
|
861
|
+
!isEmptyObj(obj) &&
|
|
862
|
+
Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k)));
|
|
863
|
+
};
|
|
864
|
+
const getPlatformProperties = () => {
|
|
865
|
+
if (typeof Deno !== 'undefined' && Deno.build != null) {
|
|
866
|
+
return {
|
|
867
|
+
'X-Stainless-Lang': 'js',
|
|
868
|
+
'X-Stainless-Package-Version': VERSION,
|
|
869
|
+
'X-Stainless-OS': normalizePlatform(Deno.build.os),
|
|
870
|
+
'X-Stainless-Arch': normalizeArch(Deno.build.arch),
|
|
871
|
+
'X-Stainless-Runtime': 'deno',
|
|
872
|
+
'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown',
|
|
873
|
+
};
|
|
874
|
+
}
|
|
875
|
+
if (typeof EdgeRuntime !== 'undefined') {
|
|
876
|
+
return {
|
|
877
|
+
'X-Stainless-Lang': 'js',
|
|
878
|
+
'X-Stainless-Package-Version': VERSION,
|
|
879
|
+
'X-Stainless-OS': 'Unknown',
|
|
880
|
+
'X-Stainless-Arch': `other:${EdgeRuntime}`,
|
|
881
|
+
'X-Stainless-Runtime': 'edge',
|
|
882
|
+
'X-Stainless-Runtime-Version': process.version,
|
|
883
|
+
};
|
|
884
|
+
}
|
|
885
|
+
// Check if Node.js
|
|
886
|
+
if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') {
|
|
887
|
+
return {
|
|
888
|
+
'X-Stainless-Lang': 'js',
|
|
889
|
+
'X-Stainless-Package-Version': VERSION,
|
|
890
|
+
'X-Stainless-OS': normalizePlatform(process.platform),
|
|
891
|
+
'X-Stainless-Arch': normalizeArch(process.arch),
|
|
892
|
+
'X-Stainless-Runtime': 'node',
|
|
893
|
+
'X-Stainless-Runtime-Version': process.version,
|
|
894
|
+
};
|
|
895
|
+
}
|
|
896
|
+
const browserInfo = getBrowserInfo();
|
|
897
|
+
if (browserInfo) {
|
|
898
|
+
return {
|
|
899
|
+
'X-Stainless-Lang': 'js',
|
|
900
|
+
'X-Stainless-Package-Version': VERSION,
|
|
901
|
+
'X-Stainless-OS': 'Unknown',
|
|
902
|
+
'X-Stainless-Arch': 'unknown',
|
|
903
|
+
'X-Stainless-Runtime': `browser:${browserInfo.browser}`,
|
|
904
|
+
'X-Stainless-Runtime-Version': browserInfo.version,
|
|
905
|
+
};
|
|
906
|
+
}
|
|
907
|
+
// TODO add support for Cloudflare workers, etc.
|
|
908
|
+
return {
|
|
909
|
+
'X-Stainless-Lang': 'js',
|
|
910
|
+
'X-Stainless-Package-Version': VERSION,
|
|
911
|
+
'X-Stainless-OS': 'Unknown',
|
|
912
|
+
'X-Stainless-Arch': 'unknown',
|
|
913
|
+
'X-Stainless-Runtime': 'unknown',
|
|
914
|
+
'X-Stainless-Runtime-Version': 'unknown',
|
|
915
|
+
};
|
|
916
|
+
};
|
|
917
|
+
// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts
|
|
918
|
+
function getBrowserInfo() {
|
|
919
|
+
if (typeof navigator === 'undefined' || !navigator) {
|
|
920
|
+
return null;
|
|
921
|
+
}
|
|
922
|
+
// NOTE: The order matters here!
|
|
923
|
+
const browserPatterns = [
|
|
924
|
+
{ key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
925
|
+
{ key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
926
|
+
{ key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
927
|
+
{ key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
928
|
+
{ key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
929
|
+
{ key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ },
|
|
930
|
+
];
|
|
931
|
+
// Find the FIRST matching browser
|
|
932
|
+
for (const { key, pattern } of browserPatterns) {
|
|
933
|
+
const match = pattern.exec(navigator.userAgent);
|
|
934
|
+
if (match) {
|
|
935
|
+
const major = match[1] || 0;
|
|
936
|
+
const minor = match[2] || 0;
|
|
937
|
+
const patch = match[3] || 0;
|
|
938
|
+
return { browser: key, version: `${major}.${minor}.${patch}` };
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
return null;
|
|
942
|
+
}
|
|
943
|
+
const normalizeArch = (arch) => {
|
|
944
|
+
// Node docs:
|
|
945
|
+
// - https://nodejs.org/api/process.html#processarch
|
|
946
|
+
// Deno docs:
|
|
947
|
+
// - https://doc.deno.land/deno/stable/~/Deno.build
|
|
948
|
+
if (arch === 'x32')
|
|
949
|
+
return 'x32';
|
|
950
|
+
if (arch === 'x86_64' || arch === 'x64')
|
|
951
|
+
return 'x64';
|
|
952
|
+
if (arch === 'arm')
|
|
953
|
+
return 'arm';
|
|
954
|
+
if (arch === 'aarch64' || arch === 'arm64')
|
|
955
|
+
return 'arm64';
|
|
956
|
+
if (arch)
|
|
957
|
+
return `other:${arch}`;
|
|
958
|
+
return 'unknown';
|
|
959
|
+
};
|
|
960
|
+
const normalizePlatform = (platform) => {
|
|
961
|
+
// Node platforms:
|
|
962
|
+
// - https://nodejs.org/api/process.html#processplatform
|
|
963
|
+
// Deno platforms:
|
|
964
|
+
// - https://doc.deno.land/deno/stable/~/Deno.build
|
|
965
|
+
// - https://github.com/denoland/deno/issues/14799
|
|
966
|
+
platform = platform.toLowerCase();
|
|
967
|
+
// NOTE: this iOS check is untested and may not work
|
|
968
|
+
// Node does not work natively on IOS, there is a fork at
|
|
969
|
+
// https://github.com/nodejs-mobile/nodejs-mobile
|
|
970
|
+
// however it is unknown at the time of writing how to detect if it is running
|
|
971
|
+
if (platform.includes('ios'))
|
|
972
|
+
return 'iOS';
|
|
973
|
+
if (platform === 'android')
|
|
974
|
+
return 'Android';
|
|
975
|
+
if (platform === 'darwin')
|
|
976
|
+
return 'MacOS';
|
|
977
|
+
if (platform === 'win32')
|
|
978
|
+
return 'Windows';
|
|
979
|
+
if (platform === 'freebsd')
|
|
980
|
+
return 'FreeBSD';
|
|
981
|
+
if (platform === 'openbsd')
|
|
982
|
+
return 'OpenBSD';
|
|
983
|
+
if (platform === 'linux')
|
|
984
|
+
return 'Linux';
|
|
985
|
+
if (platform)
|
|
986
|
+
return `Other:${platform}`;
|
|
987
|
+
return 'Unknown';
|
|
988
|
+
};
|
|
989
|
+
let _platformHeaders;
|
|
990
|
+
const getPlatformHeaders = () => {
|
|
991
|
+
return (_platformHeaders ?? (_platformHeaders = getPlatformProperties()));
|
|
992
|
+
};
|
|
993
|
+
const safeJSON = (text) => {
|
|
994
|
+
try {
|
|
995
|
+
return JSON.parse(text);
|
|
996
|
+
}
|
|
997
|
+
catch (err) {
|
|
998
|
+
return undefined;
|
|
999
|
+
}
|
|
1000
|
+
};
|
|
1001
|
+
// https://url.spec.whatwg.org/#url-scheme-string
|
|
1002
|
+
const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;
|
|
1003
|
+
const isAbsoluteURL = (url) => {
|
|
1004
|
+
return startsWithSchemeRegexp.test(url);
|
|
1005
|
+
};
|
|
1006
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
1007
|
+
const validatePositiveInteger = (name, n) => {
|
|
1008
|
+
if (typeof n !== 'number' || !Number.isInteger(n)) {
|
|
1009
|
+
throw new DodoPaymentsError(`${name} must be an integer`);
|
|
1010
|
+
}
|
|
1011
|
+
if (n < 0) {
|
|
1012
|
+
throw new DodoPaymentsError(`${name} must be a positive integer`);
|
|
1013
|
+
}
|
|
1014
|
+
return n;
|
|
1015
|
+
};
|
|
1016
|
+
const castToError = (err) => {
|
|
1017
|
+
if (err instanceof Error)
|
|
1018
|
+
return err;
|
|
1019
|
+
if (typeof err === 'object' && err !== null) {
|
|
1020
|
+
try {
|
|
1021
|
+
return new Error(JSON.stringify(err));
|
|
1022
|
+
}
|
|
1023
|
+
catch { }
|
|
1024
|
+
}
|
|
1025
|
+
return new Error(err);
|
|
1026
|
+
};
|
|
1027
|
+
/**
|
|
1028
|
+
* Read an environment variable.
|
|
1029
|
+
*
|
|
1030
|
+
* Trims beginning and trailing whitespace.
|
|
1031
|
+
*
|
|
1032
|
+
* Will return undefined if the environment variable doesn't exist or cannot be accessed.
|
|
1033
|
+
*/
|
|
1034
|
+
const readEnv = (env) => {
|
|
1035
|
+
if (typeof process !== 'undefined') {
|
|
1036
|
+
return process.env?.[env]?.trim() ?? undefined;
|
|
1037
|
+
}
|
|
1038
|
+
if (typeof Deno !== 'undefined') {
|
|
1039
|
+
return Deno.env?.get?.(env)?.trim();
|
|
1040
|
+
}
|
|
1041
|
+
return undefined;
|
|
1042
|
+
};
|
|
1043
|
+
// https://stackoverflow.com/a/34491287
|
|
1044
|
+
function isEmptyObj(obj) {
|
|
1045
|
+
if (!obj)
|
|
1046
|
+
return true;
|
|
1047
|
+
for (const _k in obj)
|
|
1048
|
+
return false;
|
|
1049
|
+
return true;
|
|
1050
|
+
}
|
|
1051
|
+
// https://eslint.org/docs/latest/rules/no-prototype-builtins
|
|
1052
|
+
function hasOwn(obj, key) {
|
|
1053
|
+
return Object.prototype.hasOwnProperty.call(obj, key);
|
|
1054
|
+
}
|
|
1055
|
+
/**
|
|
1056
|
+
* Copies headers from "newHeaders" onto "targetHeaders",
|
|
1057
|
+
* using lower-case for all properties,
|
|
1058
|
+
* ignoring any keys with undefined values,
|
|
1059
|
+
* and deleting any keys with null values.
|
|
1060
|
+
*/
|
|
1061
|
+
function applyHeadersMut(targetHeaders, newHeaders) {
|
|
1062
|
+
for (const k in newHeaders) {
|
|
1063
|
+
if (!hasOwn(newHeaders, k))
|
|
1064
|
+
continue;
|
|
1065
|
+
const lowerKey = k.toLowerCase();
|
|
1066
|
+
if (!lowerKey)
|
|
1067
|
+
continue;
|
|
1068
|
+
const val = newHeaders[k];
|
|
1069
|
+
if (val === null) {
|
|
1070
|
+
delete targetHeaders[lowerKey];
|
|
1071
|
+
}
|
|
1072
|
+
else if (val !== undefined) {
|
|
1073
|
+
targetHeaders[lowerKey] = val;
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
function debug(action, ...args) {
|
|
1078
|
+
if (typeof process !== 'undefined' && process?.env?.['DEBUG'] === 'true') {
|
|
1079
|
+
console.log(`DodoPayments:DEBUG:${action}`, ...args);
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
/**
|
|
1083
|
+
* https://stackoverflow.com/a/2117523
|
|
1084
|
+
*/
|
|
1085
|
+
const uuid4 = () => {
|
|
1086
|
+
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
|
|
1087
|
+
const r = (Math.random() * 16) | 0;
|
|
1088
|
+
const v = c === 'x' ? r : (r & 0x3) | 0x8;
|
|
1089
|
+
return v.toString(16);
|
|
1090
|
+
});
|
|
1091
|
+
};
|
|
1092
|
+
const isHeadersProtocol = (headers) => {
|
|
1093
|
+
return typeof headers?.get === 'function';
|
|
1094
|
+
};
|
|
1095
|
+
const getHeader = (headers, header) => {
|
|
1096
|
+
const lowerCasedHeader = header.toLowerCase();
|
|
1097
|
+
if (isHeadersProtocol(headers)) {
|
|
1098
|
+
// to deal with the case where the header looks like Stainless-Event-Id
|
|
1099
|
+
const intercapsHeader = header[0]?.toUpperCase() +
|
|
1100
|
+
header.substring(1).replace(/([^\w])(\w)/g, (_m, g1, g2) => g1 + g2.toUpperCase());
|
|
1101
|
+
for (const key of [header, lowerCasedHeader, header.toUpperCase(), intercapsHeader]) {
|
|
1102
|
+
const value = headers.get(key);
|
|
1103
|
+
if (value) {
|
|
1104
|
+
return value;
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
1109
|
+
if (key.toLowerCase() === lowerCasedHeader) {
|
|
1110
|
+
if (Array.isArray(value)) {
|
|
1111
|
+
if (value.length <= 1)
|
|
1112
|
+
return value[0];
|
|
1113
|
+
console.warn(`Received ${value.length} entries for the ${header} header, using the first entry.`);
|
|
1114
|
+
return value[0];
|
|
1115
|
+
}
|
|
1116
|
+
return value;
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
return undefined;
|
|
1120
|
+
};
|
|
1121
|
+
|
|
1122
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
1123
|
+
class DefaultPageNumberPagination extends AbstractPage {
|
|
1124
|
+
constructor(client, response, body, options) {
|
|
1125
|
+
super(client, response, body, options);
|
|
1126
|
+
this.items = body.items || [];
|
|
1127
|
+
}
|
|
1128
|
+
getPaginatedItems() {
|
|
1129
|
+
return this.items ?? [];
|
|
1130
|
+
}
|
|
1131
|
+
// @deprecated Please use `nextPageInfo()` instead
|
|
1132
|
+
nextPageParams() {
|
|
1133
|
+
const info = this.nextPageInfo();
|
|
1134
|
+
if (!info)
|
|
1135
|
+
return null;
|
|
1136
|
+
if ('params' in info)
|
|
1137
|
+
return info.params;
|
|
1138
|
+
const params = Object.fromEntries(info.url.searchParams);
|
|
1139
|
+
if (!Object.keys(params).length)
|
|
1140
|
+
return null;
|
|
1141
|
+
return params;
|
|
1142
|
+
}
|
|
1143
|
+
nextPageInfo() {
|
|
1144
|
+
const query = this.options.query;
|
|
1145
|
+
const currentPage = query?.page_number ?? 1;
|
|
1146
|
+
return { params: { page_number: currentPage + 1 } };
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
1151
|
+
class APIResource {
|
|
1152
|
+
constructor(client) {
|
|
1153
|
+
this._client = client;
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
1158
|
+
class Addons extends APIResource {
|
|
1159
|
+
create(body, options) {
|
|
1160
|
+
return this._client.post('/addons', { body, ...options });
|
|
1161
|
+
}
|
|
1162
|
+
retrieve(id, options) {
|
|
1163
|
+
return this._client.get(`/addons/${id}`, options);
|
|
1164
|
+
}
|
|
1165
|
+
update(id, body, options) {
|
|
1166
|
+
return this._client.patch(`/addons/${id}`, { body, ...options });
|
|
1167
|
+
}
|
|
1168
|
+
list(query = {}, options) {
|
|
1169
|
+
if (isRequestOptions(query)) {
|
|
1170
|
+
return this.list({}, query);
|
|
1171
|
+
}
|
|
1172
|
+
return this._client.getAPIList('/addons', AddonResponsesDefaultPageNumberPagination, {
|
|
1173
|
+
query,
|
|
1174
|
+
...options,
|
|
1175
|
+
});
|
|
1176
|
+
}
|
|
1177
|
+
updateImages(id, options) {
|
|
1178
|
+
return this._client.put(`/addons/${id}/images`, options);
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
class AddonResponsesDefaultPageNumberPagination extends DefaultPageNumberPagination {
|
|
1182
|
+
}
|
|
1183
|
+
Addons.AddonResponsesDefaultPageNumberPagination = AddonResponsesDefaultPageNumberPagination;
|
|
1184
|
+
|
|
1185
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
1186
|
+
class Brands extends APIResource {
|
|
1187
|
+
create(body, options) {
|
|
1188
|
+
return this._client.post('/brands', { body, ...options });
|
|
1189
|
+
}
|
|
1190
|
+
/**
|
|
1191
|
+
* Thin handler just calls `get_brand` and wraps in `Json(...)`
|
|
1192
|
+
*/
|
|
1193
|
+
retrieve(id, options) {
|
|
1194
|
+
return this._client.get(`/brands/${id}`, options);
|
|
1195
|
+
}
|
|
1196
|
+
update(id, body, options) {
|
|
1197
|
+
return this._client.patch(`/brands/${id}`, { body, ...options });
|
|
1198
|
+
}
|
|
1199
|
+
list(options) {
|
|
1200
|
+
return this._client.get('/brands', options);
|
|
1201
|
+
}
|
|
1202
|
+
updateImages(id, options) {
|
|
1203
|
+
return this._client.put(`/brands/${id}/images`, options);
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
1208
|
+
let CustomerPortal$1 = class CustomerPortal extends APIResource {
|
|
1209
|
+
create(customerId, params = {}, options) {
|
|
1210
|
+
if (isRequestOptions(params)) {
|
|
1211
|
+
return this.create(customerId, {}, params);
|
|
1212
|
+
}
|
|
1213
|
+
const { send_email } = params;
|
|
1214
|
+
return this._client.post(`/customers/${customerId}/customer-portal/session`, {
|
|
1215
|
+
query: { send_email },
|
|
1216
|
+
...options,
|
|
1217
|
+
});
|
|
1218
|
+
}
|
|
1219
|
+
};
|
|
1220
|
+
|
|
1221
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
1222
|
+
class Customers extends APIResource {
|
|
1223
|
+
constructor() {
|
|
1224
|
+
super(...arguments);
|
|
1225
|
+
this.customerPortal = new CustomerPortal$1(this._client);
|
|
1226
|
+
}
|
|
1227
|
+
create(body, options) {
|
|
1228
|
+
return this._client.post('/customers', { body, ...options });
|
|
1229
|
+
}
|
|
1230
|
+
retrieve(customerId, options) {
|
|
1231
|
+
return this._client.get(`/customers/${customerId}`, options);
|
|
1232
|
+
}
|
|
1233
|
+
update(customerId, body, options) {
|
|
1234
|
+
return this._client.patch(`/customers/${customerId}`, { body, ...options });
|
|
1235
|
+
}
|
|
1236
|
+
list(query = {}, options) {
|
|
1237
|
+
if (isRequestOptions(query)) {
|
|
1238
|
+
return this.list({}, query);
|
|
1239
|
+
}
|
|
1240
|
+
return this._client.getAPIList('/customers', CustomersDefaultPageNumberPagination, { query, ...options });
|
|
1241
|
+
}
|
|
1242
|
+
}
|
|
1243
|
+
class CustomersDefaultPageNumberPagination extends DefaultPageNumberPagination {
|
|
1244
|
+
}
|
|
1245
|
+
Customers.CustomersDefaultPageNumberPagination = CustomersDefaultPageNumberPagination;
|
|
1246
|
+
Customers.CustomerPortal = CustomerPortal$1;
|
|
1247
|
+
|
|
1248
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
1249
|
+
class Discounts extends APIResource {
|
|
1250
|
+
/**
|
|
1251
|
+
* POST /discounts If `code` is omitted or empty, a random 16-char uppercase code
|
|
1252
|
+
* is generated.
|
|
1253
|
+
*/
|
|
1254
|
+
create(body, options) {
|
|
1255
|
+
return this._client.post('/discounts', { body, ...options });
|
|
1256
|
+
}
|
|
1257
|
+
/**
|
|
1258
|
+
* GET /discounts/{discount_id}
|
|
1259
|
+
*/
|
|
1260
|
+
retrieve(discountId, options) {
|
|
1261
|
+
return this._client.get(`/discounts/${discountId}`, options);
|
|
1262
|
+
}
|
|
1263
|
+
/**
|
|
1264
|
+
* PATCH /discounts/{discount_id}
|
|
1265
|
+
*/
|
|
1266
|
+
update(discountId, body, options) {
|
|
1267
|
+
return this._client.patch(`/discounts/${discountId}`, { body, ...options });
|
|
1268
|
+
}
|
|
1269
|
+
list(query = {}, options) {
|
|
1270
|
+
if (isRequestOptions(query)) {
|
|
1271
|
+
return this.list({}, query);
|
|
1272
|
+
}
|
|
1273
|
+
return this._client.getAPIList('/discounts', DiscountsDefaultPageNumberPagination, { query, ...options });
|
|
1274
|
+
}
|
|
1275
|
+
/**
|
|
1276
|
+
* DELETE /discounts/{discount_id}
|
|
1277
|
+
*/
|
|
1278
|
+
delete(discountId, options) {
|
|
1279
|
+
return this._client.delete(`/discounts/${discountId}`, {
|
|
1280
|
+
...options,
|
|
1281
|
+
headers: { Accept: '*/*', ...options?.headers },
|
|
1282
|
+
});
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
class DiscountsDefaultPageNumberPagination extends DefaultPageNumberPagination {
|
|
1286
|
+
}
|
|
1287
|
+
Discounts.DiscountsDefaultPageNumberPagination = DiscountsDefaultPageNumberPagination;
|
|
1288
|
+
|
|
1289
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
1290
|
+
class Disputes extends APIResource {
|
|
1291
|
+
retrieve(disputeId, options) {
|
|
1292
|
+
return this._client.get(`/disputes/${disputeId}`, options);
|
|
1293
|
+
}
|
|
1294
|
+
list(query = {}, options) {
|
|
1295
|
+
if (isRequestOptions(query)) {
|
|
1296
|
+
return this.list({}, query);
|
|
1297
|
+
}
|
|
1298
|
+
return this._client.getAPIList('/disputes', DisputeListResponsesDefaultPageNumberPagination, {
|
|
1299
|
+
query,
|
|
1300
|
+
...options,
|
|
1301
|
+
});
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
class DisputeListResponsesDefaultPageNumberPagination extends DefaultPageNumberPagination {
|
|
1305
|
+
}
|
|
1306
|
+
Disputes.DisputeListResponsesDefaultPageNumberPagination = DisputeListResponsesDefaultPageNumberPagination;
|
|
1307
|
+
|
|
1308
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
1309
|
+
let Payments$1 = class Payments extends APIResource {
|
|
1310
|
+
retrieve(paymentId, options) {
|
|
1311
|
+
return this._client.get(`/invoices/payments/${paymentId}`, {
|
|
1312
|
+
...options,
|
|
1313
|
+
headers: { Accept: 'application/pdf', ...options?.headers },
|
|
1314
|
+
__binaryResponse: true,
|
|
1315
|
+
});
|
|
1316
|
+
}
|
|
1317
|
+
};
|
|
1318
|
+
|
|
1319
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
1320
|
+
class Invoices extends APIResource {
|
|
1321
|
+
constructor() {
|
|
1322
|
+
super(...arguments);
|
|
1323
|
+
this.payments = new Payments$1(this._client);
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
Invoices.Payments = Payments$1;
|
|
1327
|
+
|
|
1328
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
1329
|
+
class LicenseKeyInstances extends APIResource {
|
|
1330
|
+
/**
|
|
1331
|
+
* @example
|
|
1332
|
+
* ```ts
|
|
1333
|
+
* const licenseKeyInstance =
|
|
1334
|
+
* await client.licenseKeyInstances.retrieve('lki_123');
|
|
1335
|
+
* ```
|
|
1336
|
+
*/
|
|
1337
|
+
retrieve(id, options) {
|
|
1338
|
+
return this._client.get(`/license_key_instances/${id}`, options);
|
|
1339
|
+
}
|
|
1340
|
+
/**
|
|
1341
|
+
* @example
|
|
1342
|
+
* ```ts
|
|
1343
|
+
* const licenseKeyInstance =
|
|
1344
|
+
* await client.licenseKeyInstances.update('lki_123', {
|
|
1345
|
+
* name: 'name',
|
|
1346
|
+
* });
|
|
1347
|
+
* ```
|
|
1348
|
+
*/
|
|
1349
|
+
update(id, body, options) {
|
|
1350
|
+
return this._client.patch(`/license_key_instances/${id}`, { body, ...options });
|
|
1351
|
+
}
|
|
1352
|
+
list(query = {}, options) {
|
|
1353
|
+
if (isRequestOptions(query)) {
|
|
1354
|
+
return this.list({}, query);
|
|
1355
|
+
}
|
|
1356
|
+
return this._client.getAPIList('/license_key_instances', LicenseKeyInstancesDefaultPageNumberPagination, {
|
|
1357
|
+
query,
|
|
1358
|
+
...options,
|
|
1359
|
+
});
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
class LicenseKeyInstancesDefaultPageNumberPagination extends DefaultPageNumberPagination {
|
|
1363
|
+
}
|
|
1364
|
+
LicenseKeyInstances.LicenseKeyInstancesDefaultPageNumberPagination =
|
|
1365
|
+
LicenseKeyInstancesDefaultPageNumberPagination;
|
|
1366
|
+
|
|
1367
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
1368
|
+
class LicenseKeys extends APIResource {
|
|
1369
|
+
/**
|
|
1370
|
+
* @example
|
|
1371
|
+
* ```ts
|
|
1372
|
+
* const licenseKey = await client.licenseKeys.retrieve(
|
|
1373
|
+
* 'lic_123',
|
|
1374
|
+
* );
|
|
1375
|
+
* ```
|
|
1376
|
+
*/
|
|
1377
|
+
retrieve(id, options) {
|
|
1378
|
+
return this._client.get(`/license_keys/${id}`, options);
|
|
1379
|
+
}
|
|
1380
|
+
/**
|
|
1381
|
+
* @example
|
|
1382
|
+
* ```ts
|
|
1383
|
+
* const licenseKey = await client.licenseKeys.update(
|
|
1384
|
+
* 'lic_123',
|
|
1385
|
+
* );
|
|
1386
|
+
* ```
|
|
1387
|
+
*/
|
|
1388
|
+
update(id, body, options) {
|
|
1389
|
+
return this._client.patch(`/license_keys/${id}`, { body, ...options });
|
|
1390
|
+
}
|
|
1391
|
+
list(query = {}, options) {
|
|
1392
|
+
if (isRequestOptions(query)) {
|
|
1393
|
+
return this.list({}, query);
|
|
1394
|
+
}
|
|
1395
|
+
return this._client.getAPIList('/license_keys', LicenseKeysDefaultPageNumberPagination, {
|
|
1396
|
+
query,
|
|
1397
|
+
...options,
|
|
1398
|
+
});
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
class LicenseKeysDefaultPageNumberPagination extends DefaultPageNumberPagination {
|
|
1402
|
+
}
|
|
1403
|
+
LicenseKeys.LicenseKeysDefaultPageNumberPagination = LicenseKeysDefaultPageNumberPagination;
|
|
1404
|
+
|
|
1405
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
1406
|
+
class Licenses extends APIResource {
|
|
1407
|
+
/**
|
|
1408
|
+
* @example
|
|
1409
|
+
* ```ts
|
|
1410
|
+
* const licenseKeyInstance = await client.licenses.activate({
|
|
1411
|
+
* license_key: 'license_key',
|
|
1412
|
+
* name: 'name',
|
|
1413
|
+
* });
|
|
1414
|
+
* ```
|
|
1415
|
+
*/
|
|
1416
|
+
activate(body, options) {
|
|
1417
|
+
return this._client.post('/licenses/activate', { body, ...options });
|
|
1418
|
+
}
|
|
1419
|
+
/**
|
|
1420
|
+
* @example
|
|
1421
|
+
* ```ts
|
|
1422
|
+
* await client.licenses.deactivate({
|
|
1423
|
+
* license_key: 'license_key',
|
|
1424
|
+
* license_key_instance_id: 'license_key_instance_id',
|
|
1425
|
+
* });
|
|
1426
|
+
* ```
|
|
1427
|
+
*/
|
|
1428
|
+
deactivate(body, options) {
|
|
1429
|
+
return this._client.post('/licenses/deactivate', {
|
|
1430
|
+
body,
|
|
1431
|
+
...options,
|
|
1432
|
+
headers: { Accept: '*/*', ...options?.headers },
|
|
1433
|
+
});
|
|
1434
|
+
}
|
|
1435
|
+
/**
|
|
1436
|
+
* @example
|
|
1437
|
+
* ```ts
|
|
1438
|
+
* const response = await client.licenses.validate({
|
|
1439
|
+
* license_key: '2b1f8e2d-c41e-4e8f-b2d3-d9fd61c38f43',
|
|
1440
|
+
* });
|
|
1441
|
+
* ```
|
|
1442
|
+
*/
|
|
1443
|
+
validate(body, options) {
|
|
1444
|
+
return this._client.post('/licenses/validate', { body, ...options });
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
1449
|
+
class Misc extends APIResource {
|
|
1450
|
+
listSupportedCountries(options) {
|
|
1451
|
+
return this._client.get('/checkout/supported_countries', options);
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
|
|
1455
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
1456
|
+
class Payments extends APIResource {
|
|
1457
|
+
create(body, options) {
|
|
1458
|
+
return this._client.post('/payments', { body, ...options });
|
|
1459
|
+
}
|
|
1460
|
+
retrieve(paymentId, options) {
|
|
1461
|
+
return this._client.get(`/payments/${paymentId}`, options);
|
|
1462
|
+
}
|
|
1463
|
+
list(query = {}, options) {
|
|
1464
|
+
if (isRequestOptions(query)) {
|
|
1465
|
+
return this.list({}, query);
|
|
1466
|
+
}
|
|
1467
|
+
return this._client.getAPIList('/payments', PaymentListResponsesDefaultPageNumberPagination, {
|
|
1468
|
+
query,
|
|
1469
|
+
...options,
|
|
1470
|
+
});
|
|
1471
|
+
}
|
|
1472
|
+
retrieveLineItems(paymentId, options) {
|
|
1473
|
+
return this._client.get(`/payments/${paymentId}/line-items`, options);
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
class PaymentListResponsesDefaultPageNumberPagination extends DefaultPageNumberPagination {
|
|
1477
|
+
}
|
|
1478
|
+
Payments.PaymentListResponsesDefaultPageNumberPagination = PaymentListResponsesDefaultPageNumberPagination;
|
|
1479
|
+
|
|
1480
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
1481
|
+
class Payouts extends APIResource {
|
|
1482
|
+
list(query = {}, options) {
|
|
1483
|
+
if (isRequestOptions(query)) {
|
|
1484
|
+
return this.list({}, query);
|
|
1485
|
+
}
|
|
1486
|
+
return this._client.getAPIList('/payouts', PayoutListResponsesDefaultPageNumberPagination, {
|
|
1487
|
+
query,
|
|
1488
|
+
...options,
|
|
1489
|
+
});
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1492
|
+
class PayoutListResponsesDefaultPageNumberPagination extends DefaultPageNumberPagination {
|
|
1493
|
+
}
|
|
1494
|
+
Payouts.PayoutListResponsesDefaultPageNumberPagination = PayoutListResponsesDefaultPageNumberPagination;
|
|
1495
|
+
|
|
1496
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
1497
|
+
class Images extends APIResource {
|
|
1498
|
+
update(id, params = {}, options) {
|
|
1499
|
+
if (isRequestOptions(params)) {
|
|
1500
|
+
return this.update(id, {}, params);
|
|
1501
|
+
}
|
|
1502
|
+
const { force_update } = params;
|
|
1503
|
+
return this._client.put(`/products/${id}/images`, { query: { force_update }, ...options });
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
|
|
1507
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
1508
|
+
class Products extends APIResource {
|
|
1509
|
+
constructor() {
|
|
1510
|
+
super(...arguments);
|
|
1511
|
+
this.images = new Images(this._client);
|
|
1512
|
+
}
|
|
1513
|
+
create(body, options) {
|
|
1514
|
+
return this._client.post('/products', { body, ...options });
|
|
1515
|
+
}
|
|
1516
|
+
retrieve(id, options) {
|
|
1517
|
+
return this._client.get(`/products/${id}`, options);
|
|
1518
|
+
}
|
|
1519
|
+
update(id, body, options) {
|
|
1520
|
+
return this._client.patch(`/products/${id}`, {
|
|
1521
|
+
body,
|
|
1522
|
+
...options,
|
|
1523
|
+
headers: { Accept: '*/*', ...options?.headers },
|
|
1524
|
+
});
|
|
1525
|
+
}
|
|
1526
|
+
list(query = {}, options) {
|
|
1527
|
+
if (isRequestOptions(query)) {
|
|
1528
|
+
return this.list({}, query);
|
|
1529
|
+
}
|
|
1530
|
+
return this._client.getAPIList('/products', ProductListResponsesDefaultPageNumberPagination, {
|
|
1531
|
+
query,
|
|
1532
|
+
...options,
|
|
1533
|
+
});
|
|
1534
|
+
}
|
|
1535
|
+
delete(id, options) {
|
|
1536
|
+
return this._client.delete(`/products/${id}`, {
|
|
1537
|
+
...options,
|
|
1538
|
+
headers: { Accept: '*/*', ...options?.headers },
|
|
1539
|
+
});
|
|
1540
|
+
}
|
|
1541
|
+
unarchive(id, options) {
|
|
1542
|
+
return this._client.post(`/products/${id}/unarchive`, {
|
|
1543
|
+
...options,
|
|
1544
|
+
headers: { Accept: '*/*', ...options?.headers },
|
|
1545
|
+
});
|
|
1546
|
+
}
|
|
1547
|
+
updateFiles(id, body, options) {
|
|
1548
|
+
return this._client.put(`/products/${id}/files`, { body, ...options });
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
class ProductListResponsesDefaultPageNumberPagination extends DefaultPageNumberPagination {
|
|
1552
|
+
}
|
|
1553
|
+
Products.ProductListResponsesDefaultPageNumberPagination = ProductListResponsesDefaultPageNumberPagination;
|
|
1554
|
+
Products.Images = Images;
|
|
1555
|
+
|
|
1556
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
1557
|
+
class Refunds extends APIResource {
|
|
1558
|
+
create(body, options) {
|
|
1559
|
+
return this._client.post('/refunds', { body, ...options });
|
|
1560
|
+
}
|
|
1561
|
+
retrieve(refundId, options) {
|
|
1562
|
+
return this._client.get(`/refunds/${refundId}`, options);
|
|
1563
|
+
}
|
|
1564
|
+
list(query = {}, options) {
|
|
1565
|
+
if (isRequestOptions(query)) {
|
|
1566
|
+
return this.list({}, query);
|
|
1567
|
+
}
|
|
1568
|
+
return this._client.getAPIList('/refunds', RefundsDefaultPageNumberPagination, { query, ...options });
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
class RefundsDefaultPageNumberPagination extends DefaultPageNumberPagination {
|
|
1572
|
+
}
|
|
1573
|
+
Refunds.RefundsDefaultPageNumberPagination = RefundsDefaultPageNumberPagination;
|
|
1574
|
+
|
|
1575
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
1576
|
+
class Subscriptions extends APIResource {
|
|
1577
|
+
create(body, options) {
|
|
1578
|
+
return this._client.post('/subscriptions', { body, ...options });
|
|
1579
|
+
}
|
|
1580
|
+
retrieve(subscriptionId, options) {
|
|
1581
|
+
return this._client.get(`/subscriptions/${subscriptionId}`, options);
|
|
1582
|
+
}
|
|
1583
|
+
update(subscriptionId, body, options) {
|
|
1584
|
+
return this._client.patch(`/subscriptions/${subscriptionId}`, { body, ...options });
|
|
1585
|
+
}
|
|
1586
|
+
list(query = {}, options) {
|
|
1587
|
+
if (isRequestOptions(query)) {
|
|
1588
|
+
return this.list({}, query);
|
|
1589
|
+
}
|
|
1590
|
+
return this._client.getAPIList('/subscriptions', SubscriptionListResponsesDefaultPageNumberPagination, {
|
|
1591
|
+
query,
|
|
1592
|
+
...options,
|
|
1593
|
+
});
|
|
1594
|
+
}
|
|
1595
|
+
changePlan(subscriptionId, body, options) {
|
|
1596
|
+
return this._client.post(`/subscriptions/${subscriptionId}/change-plan`, {
|
|
1597
|
+
body,
|
|
1598
|
+
...options,
|
|
1599
|
+
headers: { Accept: '*/*', ...options?.headers },
|
|
1600
|
+
});
|
|
1601
|
+
}
|
|
1602
|
+
charge(subscriptionId, body, options) {
|
|
1603
|
+
return this._client.post(`/subscriptions/${subscriptionId}/charge`, { body, ...options });
|
|
1604
|
+
}
|
|
1605
|
+
}
|
|
1606
|
+
class SubscriptionListResponsesDefaultPageNumberPagination extends DefaultPageNumberPagination {
|
|
1607
|
+
}
|
|
1608
|
+
Subscriptions.SubscriptionListResponsesDefaultPageNumberPagination =
|
|
1609
|
+
SubscriptionListResponsesDefaultPageNumberPagination;
|
|
1610
|
+
|
|
1611
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
1612
|
+
class WebhookEvents extends APIResource {
|
|
1613
|
+
/**
|
|
1614
|
+
* @deprecated
|
|
1615
|
+
*/
|
|
1616
|
+
retrieve(webhookEventId, options) {
|
|
1617
|
+
return this._client.get(`/webhook_events/${webhookEventId}`, options);
|
|
1618
|
+
}
|
|
1619
|
+
list(query = {}, options) {
|
|
1620
|
+
if (isRequestOptions(query)) {
|
|
1621
|
+
return this.list({}, query);
|
|
1622
|
+
}
|
|
1623
|
+
return this._client.getAPIList('/webhook_events', WebhookEventsDefaultPageNumberPagination, {
|
|
1624
|
+
query,
|
|
1625
|
+
...options,
|
|
1626
|
+
});
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
class WebhookEventsDefaultPageNumberPagination extends DefaultPageNumberPagination {
|
|
1630
|
+
}
|
|
1631
|
+
WebhookEvents.WebhookEventsDefaultPageNumberPagination = WebhookEventsDefaultPageNumberPagination;
|
|
1632
|
+
|
|
1633
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
1634
|
+
var _DodoPayments_instances, _a;
|
|
1635
|
+
const environments = {
|
|
1636
|
+
live_mode: 'https://live.dodopayments.com',
|
|
1637
|
+
test_mode: 'https://test.dodopayments.com',
|
|
1638
|
+
};
|
|
1639
|
+
/**
|
|
1640
|
+
* API Client for interfacing with the Dodo Payments API.
|
|
1641
|
+
*/
|
|
1642
|
+
class DodoPayments extends APIClient {
|
|
1643
|
+
/**
|
|
1644
|
+
* API Client for interfacing with the Dodo Payments API.
|
|
1645
|
+
*
|
|
1646
|
+
* @param {string | undefined} [opts.bearerToken=process.env['DODO_PAYMENTS_API_KEY'] ?? undefined]
|
|
1647
|
+
* @param {Environment} [opts.environment=live_mode] - Specifies the environment URL to use for the API.
|
|
1648
|
+
* @param {string} [opts.baseURL=process.env['DODO_PAYMENTS_BASE_URL'] ?? https://live.dodopayments.com] - Override the default base URL for the API.
|
|
1649
|
+
* @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
|
|
1650
|
+
* @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.
|
|
1651
|
+
* @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
|
|
1652
|
+
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
|
|
1653
|
+
* @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.
|
|
1654
|
+
* @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.
|
|
1655
|
+
*/
|
|
1656
|
+
constructor({ baseURL = readEnv('DODO_PAYMENTS_BASE_URL'), bearerToken = readEnv('DODO_PAYMENTS_API_KEY'), ...opts } = {}) {
|
|
1657
|
+
if (bearerToken === undefined) {
|
|
1658
|
+
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' }).");
|
|
1659
|
+
}
|
|
1660
|
+
const options = {
|
|
1661
|
+
bearerToken,
|
|
1662
|
+
...opts,
|
|
1663
|
+
baseURL,
|
|
1664
|
+
environment: opts.environment ?? 'live_mode',
|
|
1665
|
+
};
|
|
1666
|
+
if (baseURL && opts.environment) {
|
|
1667
|
+
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');
|
|
1668
|
+
}
|
|
1669
|
+
super({
|
|
1670
|
+
baseURL: options.baseURL || environments[options.environment || 'live_mode'],
|
|
1671
|
+
baseURLOverridden: baseURL ? baseURL !== environments[options.environment || 'live_mode'] : false,
|
|
1672
|
+
timeout: options.timeout ?? 60000 /* 1 minute */,
|
|
1673
|
+
httpAgent: options.httpAgent,
|
|
1674
|
+
maxRetries: options.maxRetries,
|
|
1675
|
+
fetch: options.fetch,
|
|
1676
|
+
});
|
|
1677
|
+
_DodoPayments_instances.add(this);
|
|
1678
|
+
this.payments = new Payments(this);
|
|
1679
|
+
this.subscriptions = new Subscriptions(this);
|
|
1680
|
+
this.invoices = new Invoices(this);
|
|
1681
|
+
this.licenses = new Licenses(this);
|
|
1682
|
+
this.licenseKeys = new LicenseKeys(this);
|
|
1683
|
+
this.licenseKeyInstances = new LicenseKeyInstances(this);
|
|
1684
|
+
this.customers = new Customers(this);
|
|
1685
|
+
this.refunds = new Refunds(this);
|
|
1686
|
+
this.disputes = new Disputes(this);
|
|
1687
|
+
this.payouts = new Payouts(this);
|
|
1688
|
+
this.webhookEvents = new WebhookEvents(this);
|
|
1689
|
+
this.products = new Products(this);
|
|
1690
|
+
this.misc = new Misc(this);
|
|
1691
|
+
this.discounts = new Discounts(this);
|
|
1692
|
+
this.addons = new Addons(this);
|
|
1693
|
+
this.brands = new Brands(this);
|
|
1694
|
+
this._options = options;
|
|
1695
|
+
this.bearerToken = bearerToken;
|
|
1696
|
+
}
|
|
1697
|
+
defaultQuery() {
|
|
1698
|
+
return this._options.defaultQuery;
|
|
1699
|
+
}
|
|
1700
|
+
defaultHeaders(opts) {
|
|
1701
|
+
return {
|
|
1702
|
+
...super.defaultHeaders(opts),
|
|
1703
|
+
...this._options.defaultHeaders,
|
|
1704
|
+
};
|
|
1705
|
+
}
|
|
1706
|
+
authHeaders(opts) {
|
|
1707
|
+
return { Authorization: `Bearer ${this.bearerToken}` };
|
|
1708
|
+
}
|
|
1709
|
+
}
|
|
1710
|
+
_a = DodoPayments, _DodoPayments_instances = new WeakSet();
|
|
1711
|
+
DodoPayments.DodoPayments = _a;
|
|
1712
|
+
DodoPayments.DEFAULT_TIMEOUT = 60000; // 1 minute
|
|
1713
|
+
DodoPayments.DodoPaymentsError = DodoPaymentsError;
|
|
1714
|
+
DodoPayments.APIError = APIError;
|
|
1715
|
+
DodoPayments.APIConnectionError = APIConnectionError;
|
|
1716
|
+
DodoPayments.APIConnectionTimeoutError = APIConnectionTimeoutError;
|
|
1717
|
+
DodoPayments.APIUserAbortError = APIUserAbortError;
|
|
1718
|
+
DodoPayments.NotFoundError = NotFoundError;
|
|
1719
|
+
DodoPayments.ConflictError = ConflictError;
|
|
1720
|
+
DodoPayments.RateLimitError = RateLimitError;
|
|
1721
|
+
DodoPayments.BadRequestError = BadRequestError;
|
|
1722
|
+
DodoPayments.AuthenticationError = AuthenticationError;
|
|
1723
|
+
DodoPayments.InternalServerError = InternalServerError;
|
|
1724
|
+
DodoPayments.PermissionDeniedError = PermissionDeniedError;
|
|
1725
|
+
DodoPayments.UnprocessableEntityError = UnprocessableEntityError;
|
|
1726
|
+
DodoPayments.toFile = toFile;
|
|
1727
|
+
DodoPayments.fileFromPath = fileFromPath;
|
|
1728
|
+
DodoPayments.Payments = Payments;
|
|
1729
|
+
DodoPayments.PaymentListResponsesDefaultPageNumberPagination =
|
|
1730
|
+
PaymentListResponsesDefaultPageNumberPagination;
|
|
1731
|
+
DodoPayments.Subscriptions = Subscriptions;
|
|
1732
|
+
DodoPayments.SubscriptionListResponsesDefaultPageNumberPagination =
|
|
1733
|
+
SubscriptionListResponsesDefaultPageNumberPagination;
|
|
1734
|
+
DodoPayments.Invoices = Invoices;
|
|
1735
|
+
DodoPayments.Licenses = Licenses;
|
|
1736
|
+
DodoPayments.LicenseKeys = LicenseKeys;
|
|
1737
|
+
DodoPayments.LicenseKeysDefaultPageNumberPagination = LicenseKeysDefaultPageNumberPagination;
|
|
1738
|
+
DodoPayments.LicenseKeyInstances = LicenseKeyInstances;
|
|
1739
|
+
DodoPayments.LicenseKeyInstancesDefaultPageNumberPagination = LicenseKeyInstancesDefaultPageNumberPagination;
|
|
1740
|
+
DodoPayments.Customers = Customers;
|
|
1741
|
+
DodoPayments.CustomersDefaultPageNumberPagination = CustomersDefaultPageNumberPagination;
|
|
1742
|
+
DodoPayments.Refunds = Refunds;
|
|
1743
|
+
DodoPayments.RefundsDefaultPageNumberPagination = RefundsDefaultPageNumberPagination;
|
|
1744
|
+
DodoPayments.Disputes = Disputes;
|
|
1745
|
+
DodoPayments.DisputeListResponsesDefaultPageNumberPagination =
|
|
1746
|
+
DisputeListResponsesDefaultPageNumberPagination;
|
|
1747
|
+
DodoPayments.Payouts = Payouts;
|
|
1748
|
+
DodoPayments.PayoutListResponsesDefaultPageNumberPagination = PayoutListResponsesDefaultPageNumberPagination;
|
|
1749
|
+
DodoPayments.WebhookEvents = WebhookEvents;
|
|
1750
|
+
DodoPayments.WebhookEventsDefaultPageNumberPagination = WebhookEventsDefaultPageNumberPagination;
|
|
1751
|
+
DodoPayments.Products = Products;
|
|
1752
|
+
DodoPayments.ProductListResponsesDefaultPageNumberPagination =
|
|
1753
|
+
ProductListResponsesDefaultPageNumberPagination;
|
|
1754
|
+
DodoPayments.Misc = Misc;
|
|
1755
|
+
DodoPayments.Discounts = Discounts;
|
|
1756
|
+
DodoPayments.DiscountsDefaultPageNumberPagination = DiscountsDefaultPageNumberPagination;
|
|
1757
|
+
DodoPayments.Addons = Addons;
|
|
1758
|
+
DodoPayments.AddonResponsesDefaultPageNumberPagination = AddonResponsesDefaultPageNumberPagination;
|
|
1759
|
+
DodoPayments.Brands = Brands;
|
|
1760
|
+
|
|
1761
|
+
var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
1762
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
1763
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
1764
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
1765
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
1766
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
1767
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
1768
|
+
});
|
|
1769
|
+
};
|
|
1770
|
+
var __generator$1 = (undefined && undefined.__generator) || function (thisArg, body) {
|
|
1771
|
+
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
|
|
1772
|
+
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
|
1773
|
+
function verb(n) { return function (v) { return step([n, v]); }; }
|
|
1774
|
+
function step(op) {
|
|
1775
|
+
if (f) throw new TypeError("Generator is already executing.");
|
|
1776
|
+
while (g && (g = 0, op[0] && (_ = 0)), _) try {
|
|
1777
|
+
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
|
1778
|
+
if (y = 0, t) op = [op[0] & 2, t.value];
|
|
1779
|
+
switch (op[0]) {
|
|
1780
|
+
case 0: case 1: t = op; break;
|
|
1781
|
+
case 4: _.label++; return { value: op[1], done: false };
|
|
1782
|
+
case 5: _.label++; y = op[1]; op = [0]; continue;
|
|
1783
|
+
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
|
1784
|
+
default:
|
|
1785
|
+
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
|
1786
|
+
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
|
1787
|
+
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
|
1788
|
+
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
|
1789
|
+
if (t[2]) _.ops.pop();
|
|
1790
|
+
_.trys.pop(); continue;
|
|
1791
|
+
}
|
|
1792
|
+
op = body.call(thisArg, _);
|
|
1793
|
+
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
|
1794
|
+
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
|
1795
|
+
}
|
|
1796
|
+
};
|
|
1797
|
+
var checkoutQuerySchema = zod.z.object({
|
|
1798
|
+
productId: zod.z.string(),
|
|
1799
|
+
quantity: zod.z.string().optional(),
|
|
1800
|
+
// Customer fields
|
|
1801
|
+
fullName: zod.z.string().optional(),
|
|
1802
|
+
firstName: zod.z.string().optional(),
|
|
1803
|
+
lastName: zod.z.string().optional(),
|
|
1804
|
+
email: zod.z.string().optional(),
|
|
1805
|
+
country: zod.z.string().optional(),
|
|
1806
|
+
addressLine: zod.z.string().optional(),
|
|
1807
|
+
city: zod.z.string().optional(),
|
|
1808
|
+
state: zod.z.string().optional(),
|
|
1809
|
+
zipCode: zod.z.string().optional(),
|
|
1810
|
+
// Disable flags
|
|
1811
|
+
disableFullName: zod.z.string().optional(),
|
|
1812
|
+
disableFirstName: zod.z.string().optional(),
|
|
1813
|
+
disableLastName: zod.z.string().optional(),
|
|
1814
|
+
disableEmail: zod.z.string().optional(),
|
|
1815
|
+
disableCountry: zod.z.string().optional(),
|
|
1816
|
+
disableAddressLine: zod.z.string().optional(),
|
|
1817
|
+
disableCity: zod.z.string().optional(),
|
|
1818
|
+
disableState: zod.z.string().optional(),
|
|
1819
|
+
disableZipCode: zod.z.string().optional(),
|
|
1820
|
+
// Advanced controls
|
|
1821
|
+
paymentCurrency: zod.z.string().optional(),
|
|
1822
|
+
showCurrencySelector: zod.z.string().optional(),
|
|
1823
|
+
paymentAmount: zod.z.string().optional(),
|
|
1824
|
+
showDiscounts: zod.z.string().optional(),
|
|
1825
|
+
// Metadata (allow any key starting with metadata_)
|
|
1826
|
+
// We'll handle metadata separately in the handler
|
|
1827
|
+
});
|
|
1828
|
+
// Add Zod schema for dynamic checkout body
|
|
1829
|
+
var dynamicCheckoutBodySchema = zod.z
|
|
1830
|
+
.object({
|
|
1831
|
+
// For subscription
|
|
1832
|
+
product_id: zod.z.string().optional(),
|
|
1833
|
+
quantity: zod.z.number().optional(),
|
|
1834
|
+
// For one-time payment
|
|
1835
|
+
product_cart: zod.z
|
|
1836
|
+
.array(zod.z.object({
|
|
1837
|
+
product_id: zod.z.string(),
|
|
1838
|
+
quantity: zod.z.number(),
|
|
1839
|
+
}))
|
|
1840
|
+
.optional(),
|
|
1841
|
+
// Common fields
|
|
1842
|
+
billing: zod.z.object({
|
|
1843
|
+
city: zod.z.string(),
|
|
1844
|
+
country: zod.z.string(),
|
|
1845
|
+
state: zod.z.string(),
|
|
1846
|
+
street: zod.z.string(),
|
|
1847
|
+
zipcode: zod.z.string(),
|
|
1848
|
+
}),
|
|
1849
|
+
customer: zod.z.object({
|
|
1850
|
+
customer_id: zod.z.string().optional(),
|
|
1851
|
+
email: zod.z.string().optional(),
|
|
1852
|
+
name: zod.z.string().optional(),
|
|
1853
|
+
}),
|
|
1854
|
+
discount_id: zod.z.string().optional(),
|
|
1855
|
+
addons: zod.z
|
|
1856
|
+
.array(zod.z.object({
|
|
1857
|
+
addon_id: zod.z.string(),
|
|
1858
|
+
quantity: zod.z.number(),
|
|
1859
|
+
}))
|
|
1860
|
+
.optional(),
|
|
1861
|
+
metadata: zod.z.record(zod.z.string(), zod.z.string()).optional(),
|
|
1862
|
+
currency: zod.z.string().optional(),
|
|
1863
|
+
// Allow any additional fields (for future compatibility)
|
|
1864
|
+
})
|
|
1865
|
+
.catchall(zod.z.unknown());
|
|
1866
|
+
var buildCheckoutUrl = function (_a) { return __awaiter$1(void 0, [_a], void 0, function (_b) {
|
|
1867
|
+
var inputData, parseResult, success, data, error, _c, productId, quantity_1, fullName, firstName, lastName, email, country, addressLine, city, state, zipCode, disableFullName, disableFirstName, disableLastName, disableEmail, disableCountry, disableAddressLine, disableCity, disableState, disableZipCode, paymentCurrency, showCurrencySelector, paymentAmount, showDiscounts, dodopayments_1, err_1, url, _i, _d, _e, key, value, dyn, product_id, product_cart, quantity, billing, customer, addons, metadata, allowed_payment_method_types, billing_currency, discount_code, on_demand, bodyReturnUrl, show_saved_payment_methods, tax_id, trial_period_days, dodopayments, isSubscription, productIdToFetch, product, err_2, subscriptionPayload, subscription, err_3, cart, paymentPayload, payment, err_4;
|
|
1868
|
+
var queryParams = _b.queryParams, body = _b.body, returnUrl = _b.returnUrl, bearerToken = _b.bearerToken, environment = _b.environment, _f = _b.type, type = _f === void 0 ? "static" : _f;
|
|
1869
|
+
return __generator$1(this, function (_g) {
|
|
1870
|
+
switch (_g.label) {
|
|
1871
|
+
case 0:
|
|
1872
|
+
inputData = type === "dynamic" ? body : queryParams;
|
|
1873
|
+
if (type === "dynamic") {
|
|
1874
|
+
parseResult = dynamicCheckoutBodySchema.safeParse(inputData);
|
|
1875
|
+
}
|
|
1876
|
+
else {
|
|
1877
|
+
parseResult = checkoutQuerySchema.safeParse(inputData);
|
|
1878
|
+
}
|
|
1879
|
+
success = parseResult.success, data = parseResult.data, error = parseResult.error;
|
|
1880
|
+
if (!success) {
|
|
1881
|
+
throw new Error("Invalid ".concat(type === "dynamic" ? "body" : "query parameters", ".\n ").concat(error.message));
|
|
1882
|
+
}
|
|
1883
|
+
if (!(type !== "dynamic")) return [3 /*break*/, 5];
|
|
1884
|
+
_c = data, productId = _c.productId, quantity_1 = _c.quantity, fullName = _c.fullName, firstName = _c.firstName, lastName = _c.lastName, email = _c.email, country = _c.country, addressLine = _c.addressLine, city = _c.city, state = _c.state, zipCode = _c.zipCode, disableFullName = _c.disableFullName, disableFirstName = _c.disableFirstName, disableLastName = _c.disableLastName, disableEmail = _c.disableEmail, disableCountry = _c.disableCountry, disableAddressLine = _c.disableAddressLine, disableCity = _c.disableCity, disableState = _c.disableState, disableZipCode = _c.disableZipCode, paymentCurrency = _c.paymentCurrency, showCurrencySelector = _c.showCurrencySelector, paymentAmount = _c.paymentAmount, showDiscounts = _c.showDiscounts;
|
|
1885
|
+
dodopayments_1 = new DodoPayments({
|
|
1886
|
+
bearerToken: bearerToken,
|
|
1887
|
+
environment: environment,
|
|
1888
|
+
});
|
|
1889
|
+
// Check that the product exists for this merchant
|
|
1890
|
+
if (!productId)
|
|
1891
|
+
throw new Error("Missing required field: productId");
|
|
1892
|
+
_g.label = 1;
|
|
1893
|
+
case 1:
|
|
1894
|
+
_g.trys.push([1, 3, , 4]);
|
|
1895
|
+
return [4 /*yield*/, dodopayments_1.products.retrieve(productId)];
|
|
1896
|
+
case 2:
|
|
1897
|
+
_g.sent();
|
|
1898
|
+
return [3 /*break*/, 4];
|
|
1899
|
+
case 3:
|
|
1900
|
+
err_1 = _g.sent();
|
|
1901
|
+
console.error(err_1);
|
|
1902
|
+
throw new Error("Product not found");
|
|
1903
|
+
case 4:
|
|
1904
|
+
url = new URL("".concat(environment === "test_mode" ? "https://test.checkout.dodopayments.com" : "https://checkout.dodopayments.com", "/buy/").concat(productId));
|
|
1905
|
+
url.searchParams.set("quantity", quantity_1 ? String(quantity_1) : "1");
|
|
1906
|
+
if (returnUrl)
|
|
1907
|
+
url.searchParams.set("redirect_url", returnUrl);
|
|
1908
|
+
// Customer/billing fields
|
|
1909
|
+
if (fullName)
|
|
1910
|
+
url.searchParams.set("fullName", String(fullName));
|
|
1911
|
+
if (firstName)
|
|
1912
|
+
url.searchParams.set("firstName", String(firstName));
|
|
1913
|
+
if (lastName)
|
|
1914
|
+
url.searchParams.set("lastName", String(lastName));
|
|
1915
|
+
if (email)
|
|
1916
|
+
url.searchParams.set("email", String(email));
|
|
1917
|
+
if (country)
|
|
1918
|
+
url.searchParams.set("country", String(country));
|
|
1919
|
+
if (addressLine)
|
|
1920
|
+
url.searchParams.set("addressLine", String(addressLine));
|
|
1921
|
+
if (city)
|
|
1922
|
+
url.searchParams.set("city", String(city));
|
|
1923
|
+
if (state)
|
|
1924
|
+
url.searchParams.set("state", String(state));
|
|
1925
|
+
if (zipCode)
|
|
1926
|
+
url.searchParams.set("zipCode", String(zipCode));
|
|
1927
|
+
// Disable flags (must be set to 'true' to disable)
|
|
1928
|
+
if (disableFullName === "true")
|
|
1929
|
+
url.searchParams.set("disableFullName", "true");
|
|
1930
|
+
if (disableFirstName === "true")
|
|
1931
|
+
url.searchParams.set("disableFirstName", "true");
|
|
1932
|
+
if (disableLastName === "true")
|
|
1933
|
+
url.searchParams.set("disableLastName", "true");
|
|
1934
|
+
if (disableEmail === "true")
|
|
1935
|
+
url.searchParams.set("disableEmail", "true");
|
|
1936
|
+
if (disableCountry === "true")
|
|
1937
|
+
url.searchParams.set("disableCountry", "true");
|
|
1938
|
+
if (disableAddressLine === "true")
|
|
1939
|
+
url.searchParams.set("disableAddressLine", "true");
|
|
1940
|
+
if (disableCity === "true")
|
|
1941
|
+
url.searchParams.set("disableCity", "true");
|
|
1942
|
+
if (disableState === "true")
|
|
1943
|
+
url.searchParams.set("disableState", "true");
|
|
1944
|
+
if (disableZipCode === "true")
|
|
1945
|
+
url.searchParams.set("disableZipCode", "true");
|
|
1946
|
+
// Advanced controls
|
|
1947
|
+
if (paymentCurrency)
|
|
1948
|
+
url.searchParams.set("paymentCurrency", String(paymentCurrency));
|
|
1949
|
+
if (showCurrencySelector)
|
|
1950
|
+
url.searchParams.set("showCurrencySelector", String(showCurrencySelector));
|
|
1951
|
+
if (paymentAmount)
|
|
1952
|
+
url.searchParams.set("paymentAmount", String(paymentAmount));
|
|
1953
|
+
if (showDiscounts)
|
|
1954
|
+
url.searchParams.set("showDiscounts", String(showDiscounts));
|
|
1955
|
+
// Metadata: add all query params starting with metadata_
|
|
1956
|
+
for (_i = 0, _d = Object.entries(queryParams || {}); _i < _d.length; _i++) {
|
|
1957
|
+
_e = _d[_i], key = _e[0], value = _e[1];
|
|
1958
|
+
if (key.startsWith("metadata_") && value && typeof value !== "object") {
|
|
1959
|
+
url.searchParams.set(key, String(value));
|
|
1960
|
+
}
|
|
1961
|
+
}
|
|
1962
|
+
return [2 /*return*/, url.toString()];
|
|
1963
|
+
case 5:
|
|
1964
|
+
dyn = data;
|
|
1965
|
+
product_id = dyn.product_id, product_cart = dyn.product_cart, quantity = dyn.quantity, billing = dyn.billing, customer = dyn.customer, addons = dyn.addons, metadata = dyn.metadata, allowed_payment_method_types = dyn.allowed_payment_method_types, billing_currency = dyn.billing_currency, discount_code = dyn.discount_code, on_demand = dyn.on_demand, bodyReturnUrl = dyn.return_url, show_saved_payment_methods = dyn.show_saved_payment_methods, tax_id = dyn.tax_id, trial_period_days = dyn.trial_period_days;
|
|
1966
|
+
dodopayments = new DodoPayments({
|
|
1967
|
+
bearerToken: bearerToken,
|
|
1968
|
+
environment: environment,
|
|
1969
|
+
});
|
|
1970
|
+
isSubscription = false;
|
|
1971
|
+
productIdToFetch = product_id;
|
|
1972
|
+
if (!product_id && product_cart && product_cart.length > 0) {
|
|
1973
|
+
productIdToFetch = product_cart[0].product_id;
|
|
1974
|
+
}
|
|
1975
|
+
if (!productIdToFetch)
|
|
1976
|
+
throw new Error("Missing required field: product_id or product_cart[0].product_id");
|
|
1977
|
+
_g.label = 6;
|
|
1978
|
+
case 6:
|
|
1979
|
+
_g.trys.push([6, 8, , 9]);
|
|
1980
|
+
return [4 /*yield*/, dodopayments.products.retrieve(productIdToFetch)];
|
|
1981
|
+
case 7:
|
|
1982
|
+
product = _g.sent();
|
|
1983
|
+
return [3 /*break*/, 9];
|
|
1984
|
+
case 8:
|
|
1985
|
+
err_2 = _g.sent();
|
|
1986
|
+
console.error(err_2);
|
|
1987
|
+
throw new Error("Product not found");
|
|
1988
|
+
case 9:
|
|
1989
|
+
isSubscription = Boolean(product.is_recurring);
|
|
1990
|
+
// Required field validation
|
|
1991
|
+
if (isSubscription && !product_id)
|
|
1992
|
+
throw new Error("Missing required field: product_id for subscription");
|
|
1993
|
+
if (!billing)
|
|
1994
|
+
throw new Error("Missing required field: billing");
|
|
1995
|
+
if (!customer)
|
|
1996
|
+
throw new Error("Missing required field: customer");
|
|
1997
|
+
if (!isSubscription) return [3 /*break*/, 14];
|
|
1998
|
+
subscriptionPayload = {
|
|
1999
|
+
billing: billing,
|
|
2000
|
+
customer: customer,
|
|
2001
|
+
product_id: product_id,
|
|
2002
|
+
quantity: quantity ? Number(quantity) : 1,
|
|
2003
|
+
};
|
|
2004
|
+
if (metadata)
|
|
2005
|
+
subscriptionPayload.metadata = metadata;
|
|
2006
|
+
if (discount_code)
|
|
2007
|
+
subscriptionPayload.discount_code = discount_code;
|
|
2008
|
+
if (addons)
|
|
2009
|
+
subscriptionPayload.addons = addons;
|
|
2010
|
+
if (allowed_payment_method_types)
|
|
2011
|
+
subscriptionPayload.allowed_payment_method_types =
|
|
2012
|
+
allowed_payment_method_types;
|
|
2013
|
+
if (billing_currency)
|
|
2014
|
+
subscriptionPayload.billing_currency = billing_currency;
|
|
2015
|
+
if (on_demand)
|
|
2016
|
+
subscriptionPayload.on_demand = on_demand;
|
|
2017
|
+
subscriptionPayload.payment_link = true;
|
|
2018
|
+
// Use bodyReturnUrl if present, otherwise use top-level returnUrl
|
|
2019
|
+
if (bodyReturnUrl) {
|
|
2020
|
+
subscriptionPayload.return_url = bodyReturnUrl;
|
|
2021
|
+
}
|
|
2022
|
+
else if (returnUrl) {
|
|
2023
|
+
subscriptionPayload.return_url = returnUrl;
|
|
2024
|
+
}
|
|
2025
|
+
if (show_saved_payment_methods)
|
|
2026
|
+
subscriptionPayload.show_saved_payment_methods =
|
|
2027
|
+
show_saved_payment_methods;
|
|
2028
|
+
if (tax_id)
|
|
2029
|
+
subscriptionPayload.tax_id = tax_id;
|
|
2030
|
+
if (trial_period_days)
|
|
2031
|
+
subscriptionPayload.trial_period_days = trial_period_days;
|
|
2032
|
+
subscription = void 0;
|
|
2033
|
+
_g.label = 10;
|
|
2034
|
+
case 10:
|
|
2035
|
+
_g.trys.push([10, 12, , 13]);
|
|
2036
|
+
return [4 /*yield*/, dodopayments.subscriptions.create(subscriptionPayload)];
|
|
2037
|
+
case 11:
|
|
2038
|
+
subscription =
|
|
2039
|
+
_g.sent();
|
|
2040
|
+
return [3 /*break*/, 13];
|
|
2041
|
+
case 12:
|
|
2042
|
+
err_3 = _g.sent();
|
|
2043
|
+
console.error("Error when creating subscription", err_3);
|
|
2044
|
+
throw new Error(err_3 instanceof Error ? err_3.message : String(err_3));
|
|
2045
|
+
case 13:
|
|
2046
|
+
if (!subscription || !subscription.payment_link) {
|
|
2047
|
+
throw new Error("No payment link returned from Dodo Payments API (subscription). Make sure to set payment_link as true in payload");
|
|
2048
|
+
}
|
|
2049
|
+
return [2 /*return*/, subscription.payment_link];
|
|
2050
|
+
case 14:
|
|
2051
|
+
cart = product_cart;
|
|
2052
|
+
if (!cart && product_id) {
|
|
2053
|
+
cart = [
|
|
2054
|
+
{ product_id: product_id, quantity: quantity ? Number(quantity) : 1 },
|
|
2055
|
+
];
|
|
2056
|
+
}
|
|
2057
|
+
if (!cart || cart.length === 0)
|
|
2058
|
+
throw new Error("Missing required field: product_cart or product_id");
|
|
2059
|
+
paymentPayload = {
|
|
2060
|
+
billing: billing,
|
|
2061
|
+
customer: customer,
|
|
2062
|
+
product_cart: cart,
|
|
2063
|
+
};
|
|
2064
|
+
if (metadata)
|
|
2065
|
+
paymentPayload.metadata = metadata;
|
|
2066
|
+
paymentPayload.payment_link = true;
|
|
2067
|
+
if (allowed_payment_method_types)
|
|
2068
|
+
paymentPayload.allowed_payment_method_types =
|
|
2069
|
+
allowed_payment_method_types;
|
|
2070
|
+
if (billing_currency)
|
|
2071
|
+
paymentPayload.billing_currency = billing_currency;
|
|
2072
|
+
if (discount_code)
|
|
2073
|
+
paymentPayload.discount_code = discount_code;
|
|
2074
|
+
// Use bodyReturnUrl if present, otherwise use top-level returnUrl
|
|
2075
|
+
if (bodyReturnUrl) {
|
|
2076
|
+
paymentPayload.return_url = bodyReturnUrl;
|
|
2077
|
+
}
|
|
2078
|
+
else if (returnUrl) {
|
|
2079
|
+
paymentPayload.return_url = returnUrl;
|
|
2080
|
+
}
|
|
2081
|
+
if (show_saved_payment_methods)
|
|
2082
|
+
paymentPayload.show_saved_payment_methods = show_saved_payment_methods;
|
|
2083
|
+
if (tax_id)
|
|
2084
|
+
paymentPayload.tax_id = tax_id;
|
|
2085
|
+
payment = void 0;
|
|
2086
|
+
_g.label = 15;
|
|
2087
|
+
case 15:
|
|
2088
|
+
_g.trys.push([15, 17, , 18]);
|
|
2089
|
+
return [4 /*yield*/, dodopayments.payments.create(paymentPayload)];
|
|
2090
|
+
case 16:
|
|
2091
|
+
payment = _g.sent();
|
|
2092
|
+
return [3 /*break*/, 18];
|
|
2093
|
+
case 17:
|
|
2094
|
+
err_4 = _g.sent();
|
|
2095
|
+
console.error("Error when creating payment link", err_4);
|
|
2096
|
+
throw new Error(err_4 instanceof Error ? err_4.message : String(err_4));
|
|
2097
|
+
case 18:
|
|
2098
|
+
if (!payment || !payment.payment_link) {
|
|
2099
|
+
throw new Error("No payment link returned from Dodo Payments API. Make sure to set payment_link as true in payload.");
|
|
2100
|
+
}
|
|
2101
|
+
return [2 /*return*/, payment.payment_link];
|
|
2102
|
+
}
|
|
2103
|
+
});
|
|
2104
|
+
}); };
|
|
2105
|
+
|
|
2106
|
+
const Checkout = (config) => {
|
|
2107
|
+
const getHandler = async (c) => {
|
|
2108
|
+
const queryParams = c.req.query();
|
|
2109
|
+
if (!queryParams.productId) {
|
|
2110
|
+
return c.text("Please provide productId query parameter", 400);
|
|
2111
|
+
}
|
|
2112
|
+
const { success, data, error } = checkoutQuerySchema.safeParse(queryParams);
|
|
2113
|
+
if (!success) {
|
|
2114
|
+
if (error.errors.some((e) => e.path.toString() === "productId")) {
|
|
2115
|
+
return c.text("Please provide productId query parameter", 400);
|
|
2116
|
+
}
|
|
2117
|
+
return c.text(`Invalid query parameters.\n ${error.message}`, 400);
|
|
2118
|
+
}
|
|
2119
|
+
let url = "";
|
|
2120
|
+
try {
|
|
2121
|
+
url = await buildCheckoutUrl({ queryParams: data, ...config });
|
|
2122
|
+
}
|
|
2123
|
+
catch (error) {
|
|
2124
|
+
return c.text(error.message, 400);
|
|
2125
|
+
}
|
|
2126
|
+
return c.redirect(url);
|
|
2127
|
+
};
|
|
2128
|
+
const postHandler = async (c) => {
|
|
2129
|
+
let body;
|
|
2130
|
+
try {
|
|
2131
|
+
body = await c.req.json();
|
|
2132
|
+
}
|
|
2133
|
+
catch (e) {
|
|
2134
|
+
return c.text("Invalid JSON body", 400);
|
|
2135
|
+
}
|
|
2136
|
+
const { success, data, error } = dynamicCheckoutBodySchema.safeParse(body);
|
|
2137
|
+
if (!success) {
|
|
2138
|
+
return c.text(`Invalid request body.\n ${error.message}`, 400);
|
|
2139
|
+
}
|
|
2140
|
+
let url = "";
|
|
2141
|
+
try {
|
|
2142
|
+
url = await buildCheckoutUrl({ body: data, ...config });
|
|
2143
|
+
}
|
|
2144
|
+
catch (error) {
|
|
2145
|
+
return c.text(error.message, 400);
|
|
2146
|
+
}
|
|
2147
|
+
return c.redirect(url);
|
|
2148
|
+
};
|
|
2149
|
+
return (c) => {
|
|
2150
|
+
if (c.req.method === "POST") {
|
|
2151
|
+
return postHandler(c);
|
|
2152
|
+
}
|
|
2153
|
+
return getHandler(c);
|
|
2154
|
+
};
|
|
2155
|
+
};
|
|
2156
|
+
|
|
2157
|
+
const CustomerPortal = ({ bearerToken, environment, }) => {
|
|
2158
|
+
const getHandler = async (c) => {
|
|
2159
|
+
// Extract customerId from query parameters
|
|
2160
|
+
const customerId = c.req.query("customer_id");
|
|
2161
|
+
const sendEmail = c.req.query("send_email");
|
|
2162
|
+
const params = {
|
|
2163
|
+
send_email: false,
|
|
2164
|
+
};
|
|
2165
|
+
if (sendEmail === "true") {
|
|
2166
|
+
params.send_email = true;
|
|
2167
|
+
}
|
|
2168
|
+
if (!customerId) {
|
|
2169
|
+
return c.text("Missing customerId in query parameters", 400);
|
|
2170
|
+
}
|
|
2171
|
+
const dodopayments = new DodoPayments({
|
|
2172
|
+
bearerToken,
|
|
2173
|
+
environment,
|
|
2174
|
+
});
|
|
2175
|
+
try {
|
|
2176
|
+
const session = await dodopayments.customers.customerPortal.create(customerId, params);
|
|
2177
|
+
return c.redirect(session.link);
|
|
2178
|
+
}
|
|
2179
|
+
catch (error) {
|
|
2180
|
+
console.error("Error creating customer portal session:", error);
|
|
2181
|
+
return c.text(`Failed to create customer portal session: ${error.message}`, 500);
|
|
2182
|
+
}
|
|
2183
|
+
};
|
|
2184
|
+
return getHandler;
|
|
2185
|
+
};
|
|
2186
|
+
|
|
2187
|
+
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
|
|
2188
|
+
|
|
2189
|
+
var dist = {};
|
|
2190
|
+
|
|
2191
|
+
var timing_safe_equal = {};
|
|
2192
|
+
|
|
2193
|
+
Object.defineProperty(timing_safe_equal, "__esModule", { value: true });
|
|
2194
|
+
timing_safe_equal.timingSafeEqual = void 0;
|
|
2195
|
+
function assert(expr, msg = "") {
|
|
2196
|
+
if (!expr) {
|
|
2197
|
+
throw new Error(msg);
|
|
2198
|
+
}
|
|
2199
|
+
}
|
|
2200
|
+
function timingSafeEqual(a, b) {
|
|
2201
|
+
if (a.byteLength !== b.byteLength) {
|
|
2202
|
+
return false;
|
|
2203
|
+
}
|
|
2204
|
+
if (!(a instanceof DataView)) {
|
|
2205
|
+
a = new DataView(ArrayBuffer.isView(a) ? a.buffer : a);
|
|
2206
|
+
}
|
|
2207
|
+
if (!(b instanceof DataView)) {
|
|
2208
|
+
b = new DataView(ArrayBuffer.isView(b) ? b.buffer : b);
|
|
2209
|
+
}
|
|
2210
|
+
assert(a instanceof DataView);
|
|
2211
|
+
assert(b instanceof DataView);
|
|
2212
|
+
const length = a.byteLength;
|
|
2213
|
+
let out = 0;
|
|
2214
|
+
let i = -1;
|
|
2215
|
+
while (++i < length) {
|
|
2216
|
+
out |= a.getUint8(i) ^ b.getUint8(i);
|
|
2217
|
+
}
|
|
2218
|
+
return out === 0;
|
|
2219
|
+
}
|
|
2220
|
+
timing_safe_equal.timingSafeEqual = timingSafeEqual;
|
|
2221
|
+
|
|
2222
|
+
var base64$1 = {};
|
|
2223
|
+
|
|
2224
|
+
// Copyright (C) 2016 Dmitry Chestnykh
|
|
2225
|
+
// MIT License. See LICENSE file for details.
|
|
2226
|
+
var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
|
|
2227
|
+
var extendStatics = function (d, b) {
|
|
2228
|
+
extendStatics = Object.setPrototypeOf ||
|
|
2229
|
+
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
|
|
2230
|
+
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
|
|
2231
|
+
return extendStatics(d, b);
|
|
2232
|
+
};
|
|
2233
|
+
return function (d, b) {
|
|
2234
|
+
extendStatics(d, b);
|
|
2235
|
+
function __() { this.constructor = d; }
|
|
2236
|
+
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
|
2237
|
+
};
|
|
2238
|
+
})();
|
|
2239
|
+
Object.defineProperty(base64$1, "__esModule", { value: true });
|
|
2240
|
+
/**
|
|
2241
|
+
* Package base64 implements Base64 encoding and decoding.
|
|
2242
|
+
*/
|
|
2243
|
+
// Invalid character used in decoding to indicate
|
|
2244
|
+
// that the character to decode is out of range of
|
|
2245
|
+
// alphabet and cannot be decoded.
|
|
2246
|
+
var INVALID_BYTE = 256;
|
|
2247
|
+
/**
|
|
2248
|
+
* Implements standard Base64 encoding.
|
|
2249
|
+
*
|
|
2250
|
+
* Operates in constant time.
|
|
2251
|
+
*/
|
|
2252
|
+
var Coder = /** @class */ (function () {
|
|
2253
|
+
// TODO(dchest): methods to encode chunk-by-chunk.
|
|
2254
|
+
function Coder(_paddingCharacter) {
|
|
2255
|
+
if (_paddingCharacter === void 0) { _paddingCharacter = "="; }
|
|
2256
|
+
this._paddingCharacter = _paddingCharacter;
|
|
2257
|
+
}
|
|
2258
|
+
Coder.prototype.encodedLength = function (length) {
|
|
2259
|
+
if (!this._paddingCharacter) {
|
|
2260
|
+
return (length * 8 + 5) / 6 | 0;
|
|
2261
|
+
}
|
|
2262
|
+
return (length + 2) / 3 * 4 | 0;
|
|
2263
|
+
};
|
|
2264
|
+
Coder.prototype.encode = function (data) {
|
|
2265
|
+
var out = "";
|
|
2266
|
+
var i = 0;
|
|
2267
|
+
for (; i < data.length - 2; i += 3) {
|
|
2268
|
+
var c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);
|
|
2269
|
+
out += this._encodeByte((c >>> 3 * 6) & 63);
|
|
2270
|
+
out += this._encodeByte((c >>> 2 * 6) & 63);
|
|
2271
|
+
out += this._encodeByte((c >>> 1 * 6) & 63);
|
|
2272
|
+
out += this._encodeByte((c >>> 0 * 6) & 63);
|
|
2273
|
+
}
|
|
2274
|
+
var left = data.length - i;
|
|
2275
|
+
if (left > 0) {
|
|
2276
|
+
var c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0);
|
|
2277
|
+
out += this._encodeByte((c >>> 3 * 6) & 63);
|
|
2278
|
+
out += this._encodeByte((c >>> 2 * 6) & 63);
|
|
2279
|
+
if (left === 2) {
|
|
2280
|
+
out += this._encodeByte((c >>> 1 * 6) & 63);
|
|
2281
|
+
}
|
|
2282
|
+
else {
|
|
2283
|
+
out += this._paddingCharacter || "";
|
|
2284
|
+
}
|
|
2285
|
+
out += this._paddingCharacter || "";
|
|
2286
|
+
}
|
|
2287
|
+
return out;
|
|
2288
|
+
};
|
|
2289
|
+
Coder.prototype.maxDecodedLength = function (length) {
|
|
2290
|
+
if (!this._paddingCharacter) {
|
|
2291
|
+
return (length * 6 + 7) / 8 | 0;
|
|
2292
|
+
}
|
|
2293
|
+
return length / 4 * 3 | 0;
|
|
2294
|
+
};
|
|
2295
|
+
Coder.prototype.decodedLength = function (s) {
|
|
2296
|
+
return this.maxDecodedLength(s.length - this._getPaddingLength(s));
|
|
2297
|
+
};
|
|
2298
|
+
Coder.prototype.decode = function (s) {
|
|
2299
|
+
if (s.length === 0) {
|
|
2300
|
+
return new Uint8Array(0);
|
|
2301
|
+
}
|
|
2302
|
+
var paddingLength = this._getPaddingLength(s);
|
|
2303
|
+
var length = s.length - paddingLength;
|
|
2304
|
+
var out = new Uint8Array(this.maxDecodedLength(length));
|
|
2305
|
+
var op = 0;
|
|
2306
|
+
var i = 0;
|
|
2307
|
+
var haveBad = 0;
|
|
2308
|
+
var v0 = 0, v1 = 0, v2 = 0, v3 = 0;
|
|
2309
|
+
for (; i < length - 4; i += 4) {
|
|
2310
|
+
v0 = this._decodeChar(s.charCodeAt(i + 0));
|
|
2311
|
+
v1 = this._decodeChar(s.charCodeAt(i + 1));
|
|
2312
|
+
v2 = this._decodeChar(s.charCodeAt(i + 2));
|
|
2313
|
+
v3 = this._decodeChar(s.charCodeAt(i + 3));
|
|
2314
|
+
out[op++] = (v0 << 2) | (v1 >>> 4);
|
|
2315
|
+
out[op++] = (v1 << 4) | (v2 >>> 2);
|
|
2316
|
+
out[op++] = (v2 << 6) | v3;
|
|
2317
|
+
haveBad |= v0 & INVALID_BYTE;
|
|
2318
|
+
haveBad |= v1 & INVALID_BYTE;
|
|
2319
|
+
haveBad |= v2 & INVALID_BYTE;
|
|
2320
|
+
haveBad |= v3 & INVALID_BYTE;
|
|
2321
|
+
}
|
|
2322
|
+
if (i < length - 1) {
|
|
2323
|
+
v0 = this._decodeChar(s.charCodeAt(i));
|
|
2324
|
+
v1 = this._decodeChar(s.charCodeAt(i + 1));
|
|
2325
|
+
out[op++] = (v0 << 2) | (v1 >>> 4);
|
|
2326
|
+
haveBad |= v0 & INVALID_BYTE;
|
|
2327
|
+
haveBad |= v1 & INVALID_BYTE;
|
|
2328
|
+
}
|
|
2329
|
+
if (i < length - 2) {
|
|
2330
|
+
v2 = this._decodeChar(s.charCodeAt(i + 2));
|
|
2331
|
+
out[op++] = (v1 << 4) | (v2 >>> 2);
|
|
2332
|
+
haveBad |= v2 & INVALID_BYTE;
|
|
2333
|
+
}
|
|
2334
|
+
if (i < length - 3) {
|
|
2335
|
+
v3 = this._decodeChar(s.charCodeAt(i + 3));
|
|
2336
|
+
out[op++] = (v2 << 6) | v3;
|
|
2337
|
+
haveBad |= v3 & INVALID_BYTE;
|
|
2338
|
+
}
|
|
2339
|
+
if (haveBad !== 0) {
|
|
2340
|
+
throw new Error("Base64Coder: incorrect characters for decoding");
|
|
2341
|
+
}
|
|
2342
|
+
return out;
|
|
2343
|
+
};
|
|
2344
|
+
// Standard encoding have the following encoded/decoded ranges,
|
|
2345
|
+
// which we need to convert between.
|
|
2346
|
+
//
|
|
2347
|
+
// ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + /
|
|
2348
|
+
// Index: 0 - 25 26 - 51 52 - 61 62 63
|
|
2349
|
+
// ASCII: 65 - 90 97 - 122 48 - 57 43 47
|
|
2350
|
+
//
|
|
2351
|
+
// Encode 6 bits in b into a new character.
|
|
2352
|
+
Coder.prototype._encodeByte = function (b) {
|
|
2353
|
+
// Encoding uses constant time operations as follows:
|
|
2354
|
+
//
|
|
2355
|
+
// 1. Define comparison of A with B using (A - B) >>> 8:
|
|
2356
|
+
// if A > B, then result is positive integer
|
|
2357
|
+
// if A <= B, then result is 0
|
|
2358
|
+
//
|
|
2359
|
+
// 2. Define selection of C or 0 using bitwise AND: X & C:
|
|
2360
|
+
// if X == 0, then result is 0
|
|
2361
|
+
// if X != 0, then result is C
|
|
2362
|
+
//
|
|
2363
|
+
// 3. Start with the smallest comparison (b >= 0), which is always
|
|
2364
|
+
// true, so set the result to the starting ASCII value (65).
|
|
2365
|
+
//
|
|
2366
|
+
// 4. Continue comparing b to higher ASCII values, and selecting
|
|
2367
|
+
// zero if comparison isn't true, otherwise selecting a value
|
|
2368
|
+
// to add to result, which:
|
|
2369
|
+
//
|
|
2370
|
+
// a) undoes the previous addition
|
|
2371
|
+
// b) provides new value to add
|
|
2372
|
+
//
|
|
2373
|
+
var result = b;
|
|
2374
|
+
// b >= 0
|
|
2375
|
+
result += 65;
|
|
2376
|
+
// b > 25
|
|
2377
|
+
result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
|
|
2378
|
+
// b > 51
|
|
2379
|
+
result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
|
|
2380
|
+
// b > 61
|
|
2381
|
+
result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43);
|
|
2382
|
+
// b > 62
|
|
2383
|
+
result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47);
|
|
2384
|
+
return String.fromCharCode(result);
|
|
2385
|
+
};
|
|
2386
|
+
// Decode a character code into a byte.
|
|
2387
|
+
// Must return 256 if character is out of alphabet range.
|
|
2388
|
+
Coder.prototype._decodeChar = function (c) {
|
|
2389
|
+
// Decoding works similar to encoding: using the same comparison
|
|
2390
|
+
// function, but now it works on ranges: result is always incremented
|
|
2391
|
+
// by value, but this value becomes zero if the range is not
|
|
2392
|
+
// satisfied.
|
|
2393
|
+
//
|
|
2394
|
+
// Decoding starts with invalid value, 256, which is then
|
|
2395
|
+
// subtracted when the range is satisfied. If none of the ranges
|
|
2396
|
+
// apply, the function returns 256, which is then checked by
|
|
2397
|
+
// the caller to throw error.
|
|
2398
|
+
var result = INVALID_BYTE; // start with invalid character
|
|
2399
|
+
// c == 43 (c > 42 and c < 44)
|
|
2400
|
+
result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62);
|
|
2401
|
+
// c == 47 (c > 46 and c < 48)
|
|
2402
|
+
result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63);
|
|
2403
|
+
// c > 47 and c < 58
|
|
2404
|
+
result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
|
|
2405
|
+
// c > 64 and c < 91
|
|
2406
|
+
result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
|
|
2407
|
+
// c > 96 and c < 123
|
|
2408
|
+
result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
|
|
2409
|
+
return result;
|
|
2410
|
+
};
|
|
2411
|
+
Coder.prototype._getPaddingLength = function (s) {
|
|
2412
|
+
var paddingLength = 0;
|
|
2413
|
+
if (this._paddingCharacter) {
|
|
2414
|
+
for (var i = s.length - 1; i >= 0; i--) {
|
|
2415
|
+
if (s[i] !== this._paddingCharacter) {
|
|
2416
|
+
break;
|
|
2417
|
+
}
|
|
2418
|
+
paddingLength++;
|
|
2419
|
+
}
|
|
2420
|
+
if (s.length < 4 || paddingLength > 2) {
|
|
2421
|
+
throw new Error("Base64Coder: incorrect padding");
|
|
2422
|
+
}
|
|
2423
|
+
}
|
|
2424
|
+
return paddingLength;
|
|
2425
|
+
};
|
|
2426
|
+
return Coder;
|
|
2427
|
+
}());
|
|
2428
|
+
base64$1.Coder = Coder;
|
|
2429
|
+
var stdCoder = new Coder();
|
|
2430
|
+
function encode(data) {
|
|
2431
|
+
return stdCoder.encode(data);
|
|
2432
|
+
}
|
|
2433
|
+
base64$1.encode = encode;
|
|
2434
|
+
function decode(s) {
|
|
2435
|
+
return stdCoder.decode(s);
|
|
2436
|
+
}
|
|
2437
|
+
base64$1.decode = decode;
|
|
2438
|
+
/**
|
|
2439
|
+
* Implements URL-safe Base64 encoding.
|
|
2440
|
+
* (Same as Base64, but '+' is replaced with '-', and '/' with '_').
|
|
2441
|
+
*
|
|
2442
|
+
* Operates in constant time.
|
|
2443
|
+
*/
|
|
2444
|
+
var URLSafeCoder = /** @class */ (function (_super) {
|
|
2445
|
+
__extends(URLSafeCoder, _super);
|
|
2446
|
+
function URLSafeCoder() {
|
|
2447
|
+
return _super !== null && _super.apply(this, arguments) || this;
|
|
2448
|
+
}
|
|
2449
|
+
// URL-safe encoding have the following encoded/decoded ranges:
|
|
2450
|
+
//
|
|
2451
|
+
// ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _
|
|
2452
|
+
// Index: 0 - 25 26 - 51 52 - 61 62 63
|
|
2453
|
+
// ASCII: 65 - 90 97 - 122 48 - 57 45 95
|
|
2454
|
+
//
|
|
2455
|
+
URLSafeCoder.prototype._encodeByte = function (b) {
|
|
2456
|
+
var result = b;
|
|
2457
|
+
// b >= 0
|
|
2458
|
+
result += 65;
|
|
2459
|
+
// b > 25
|
|
2460
|
+
result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97);
|
|
2461
|
+
// b > 51
|
|
2462
|
+
result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48);
|
|
2463
|
+
// b > 61
|
|
2464
|
+
result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45);
|
|
2465
|
+
// b > 62
|
|
2466
|
+
result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95);
|
|
2467
|
+
return String.fromCharCode(result);
|
|
2468
|
+
};
|
|
2469
|
+
URLSafeCoder.prototype._decodeChar = function (c) {
|
|
2470
|
+
var result = INVALID_BYTE;
|
|
2471
|
+
// c == 45 (c > 44 and c < 46)
|
|
2472
|
+
result += (((44 - c) & (c - 46)) >>> 8) & (-INVALID_BYTE + c - 45 + 62);
|
|
2473
|
+
// c == 95 (c > 94 and c < 96)
|
|
2474
|
+
result += (((94 - c) & (c - 96)) >>> 8) & (-INVALID_BYTE + c - 95 + 63);
|
|
2475
|
+
// c > 47 and c < 58
|
|
2476
|
+
result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52);
|
|
2477
|
+
// c > 64 and c < 91
|
|
2478
|
+
result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0);
|
|
2479
|
+
// c > 96 and c < 123
|
|
2480
|
+
result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26);
|
|
2481
|
+
return result;
|
|
2482
|
+
};
|
|
2483
|
+
return URLSafeCoder;
|
|
2484
|
+
}(Coder));
|
|
2485
|
+
base64$1.URLSafeCoder = URLSafeCoder;
|
|
2486
|
+
var urlSafeCoder = new URLSafeCoder();
|
|
2487
|
+
function encodeURLSafe(data) {
|
|
2488
|
+
return urlSafeCoder.encode(data);
|
|
2489
|
+
}
|
|
2490
|
+
base64$1.encodeURLSafe = encodeURLSafe;
|
|
2491
|
+
function decodeURLSafe(s) {
|
|
2492
|
+
return urlSafeCoder.decode(s);
|
|
2493
|
+
}
|
|
2494
|
+
base64$1.decodeURLSafe = decodeURLSafe;
|
|
2495
|
+
base64$1.encodedLength = function (length) {
|
|
2496
|
+
return stdCoder.encodedLength(length);
|
|
2497
|
+
};
|
|
2498
|
+
base64$1.maxDecodedLength = function (length) {
|
|
2499
|
+
return stdCoder.maxDecodedLength(length);
|
|
2500
|
+
};
|
|
2501
|
+
base64$1.decodedLength = function (s) {
|
|
2502
|
+
return stdCoder.decodedLength(s);
|
|
2503
|
+
};
|
|
2504
|
+
|
|
2505
|
+
var sha256$1 = {exports: {}};
|
|
2506
|
+
|
|
2507
|
+
(function (module) {
|
|
2508
|
+
(function (root, factory) {
|
|
2509
|
+
// Hack to make all exports of this module sha256 function object properties.
|
|
2510
|
+
var exports = {};
|
|
2511
|
+
factory(exports);
|
|
2512
|
+
var sha256 = exports["default"];
|
|
2513
|
+
for (var k in exports) {
|
|
2514
|
+
sha256[k] = exports[k];
|
|
2515
|
+
}
|
|
2516
|
+
|
|
2517
|
+
{
|
|
2518
|
+
module.exports = sha256;
|
|
2519
|
+
}
|
|
2520
|
+
})(commonjsGlobal, function(exports) {
|
|
2521
|
+
exports.__esModule = true;
|
|
2522
|
+
// SHA-256 (+ HMAC and PBKDF2) for JavaScript.
|
|
2523
|
+
//
|
|
2524
|
+
// Written in 2014-2016 by Dmitry Chestnykh.
|
|
2525
|
+
// Public domain, no warranty.
|
|
2526
|
+
//
|
|
2527
|
+
// Functions (accept and return Uint8Arrays):
|
|
2528
|
+
//
|
|
2529
|
+
// sha256(message) -> hash
|
|
2530
|
+
// sha256.hmac(key, message) -> mac
|
|
2531
|
+
// sha256.pbkdf2(password, salt, rounds, dkLen) -> dk
|
|
2532
|
+
//
|
|
2533
|
+
// Classes:
|
|
2534
|
+
//
|
|
2535
|
+
// new sha256.Hash()
|
|
2536
|
+
// new sha256.HMAC(key)
|
|
2537
|
+
//
|
|
2538
|
+
exports.digestLength = 32;
|
|
2539
|
+
exports.blockSize = 64;
|
|
2540
|
+
// SHA-256 constants
|
|
2541
|
+
var K = new Uint32Array([
|
|
2542
|
+
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b,
|
|
2543
|
+
0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,
|
|
2544
|
+
0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7,
|
|
2545
|
+
0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
|
|
2546
|
+
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152,
|
|
2547
|
+
0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
|
|
2548
|
+
0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
|
|
2549
|
+
0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
|
2550
|
+
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,
|
|
2551
|
+
0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08,
|
|
2552
|
+
0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,
|
|
2553
|
+
0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
|
|
2554
|
+
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
|
|
2555
|
+
]);
|
|
2556
|
+
function hashBlocks(w, v, p, pos, len) {
|
|
2557
|
+
var a, b, c, d, e, f, g, h, u, i, j, t1, t2;
|
|
2558
|
+
while (len >= 64) {
|
|
2559
|
+
a = v[0];
|
|
2560
|
+
b = v[1];
|
|
2561
|
+
c = v[2];
|
|
2562
|
+
d = v[3];
|
|
2563
|
+
e = v[4];
|
|
2564
|
+
f = v[5];
|
|
2565
|
+
g = v[6];
|
|
2566
|
+
h = v[7];
|
|
2567
|
+
for (i = 0; i < 16; i++) {
|
|
2568
|
+
j = pos + i * 4;
|
|
2569
|
+
w[i] = (((p[j] & 0xff) << 24) | ((p[j + 1] & 0xff) << 16) |
|
|
2570
|
+
((p[j + 2] & 0xff) << 8) | (p[j + 3] & 0xff));
|
|
2571
|
+
}
|
|
2572
|
+
for (i = 16; i < 64; i++) {
|
|
2573
|
+
u = w[i - 2];
|
|
2574
|
+
t1 = (u >>> 17 | u << (32 - 17)) ^ (u >>> 19 | u << (32 - 19)) ^ (u >>> 10);
|
|
2575
|
+
u = w[i - 15];
|
|
2576
|
+
t2 = (u >>> 7 | u << (32 - 7)) ^ (u >>> 18 | u << (32 - 18)) ^ (u >>> 3);
|
|
2577
|
+
w[i] = (t1 + w[i - 7] | 0) + (t2 + w[i - 16] | 0);
|
|
2578
|
+
}
|
|
2579
|
+
for (i = 0; i < 64; i++) {
|
|
2580
|
+
t1 = (((((e >>> 6 | e << (32 - 6)) ^ (e >>> 11 | e << (32 - 11)) ^
|
|
2581
|
+
(e >>> 25 | e << (32 - 25))) + ((e & f) ^ (~e & g))) | 0) +
|
|
2582
|
+
((h + ((K[i] + w[i]) | 0)) | 0)) | 0;
|
|
2583
|
+
t2 = (((a >>> 2 | a << (32 - 2)) ^ (a >>> 13 | a << (32 - 13)) ^
|
|
2584
|
+
(a >>> 22 | a << (32 - 22))) + ((a & b) ^ (a & c) ^ (b & c))) | 0;
|
|
2585
|
+
h = g;
|
|
2586
|
+
g = f;
|
|
2587
|
+
f = e;
|
|
2588
|
+
e = (d + t1) | 0;
|
|
2589
|
+
d = c;
|
|
2590
|
+
c = b;
|
|
2591
|
+
b = a;
|
|
2592
|
+
a = (t1 + t2) | 0;
|
|
2593
|
+
}
|
|
2594
|
+
v[0] += a;
|
|
2595
|
+
v[1] += b;
|
|
2596
|
+
v[2] += c;
|
|
2597
|
+
v[3] += d;
|
|
2598
|
+
v[4] += e;
|
|
2599
|
+
v[5] += f;
|
|
2600
|
+
v[6] += g;
|
|
2601
|
+
v[7] += h;
|
|
2602
|
+
pos += 64;
|
|
2603
|
+
len -= 64;
|
|
2604
|
+
}
|
|
2605
|
+
return pos;
|
|
2606
|
+
}
|
|
2607
|
+
// Hash implements SHA256 hash algorithm.
|
|
2608
|
+
var Hash = /** @class */ (function () {
|
|
2609
|
+
function Hash() {
|
|
2610
|
+
this.digestLength = exports.digestLength;
|
|
2611
|
+
this.blockSize = exports.blockSize;
|
|
2612
|
+
// Note: Int32Array is used instead of Uint32Array for performance reasons.
|
|
2613
|
+
this.state = new Int32Array(8); // hash state
|
|
2614
|
+
this.temp = new Int32Array(64); // temporary state
|
|
2615
|
+
this.buffer = new Uint8Array(128); // buffer for data to hash
|
|
2616
|
+
this.bufferLength = 0; // number of bytes in buffer
|
|
2617
|
+
this.bytesHashed = 0; // number of total bytes hashed
|
|
2618
|
+
this.finished = false; // indicates whether the hash was finalized
|
|
2619
|
+
this.reset();
|
|
2620
|
+
}
|
|
2621
|
+
// Resets hash state making it possible
|
|
2622
|
+
// to re-use this instance to hash other data.
|
|
2623
|
+
Hash.prototype.reset = function () {
|
|
2624
|
+
this.state[0] = 0x6a09e667;
|
|
2625
|
+
this.state[1] = 0xbb67ae85;
|
|
2626
|
+
this.state[2] = 0x3c6ef372;
|
|
2627
|
+
this.state[3] = 0xa54ff53a;
|
|
2628
|
+
this.state[4] = 0x510e527f;
|
|
2629
|
+
this.state[5] = 0x9b05688c;
|
|
2630
|
+
this.state[6] = 0x1f83d9ab;
|
|
2631
|
+
this.state[7] = 0x5be0cd19;
|
|
2632
|
+
this.bufferLength = 0;
|
|
2633
|
+
this.bytesHashed = 0;
|
|
2634
|
+
this.finished = false;
|
|
2635
|
+
return this;
|
|
2636
|
+
};
|
|
2637
|
+
// Cleans internal buffers and re-initializes hash state.
|
|
2638
|
+
Hash.prototype.clean = function () {
|
|
2639
|
+
for (var i = 0; i < this.buffer.length; i++) {
|
|
2640
|
+
this.buffer[i] = 0;
|
|
2641
|
+
}
|
|
2642
|
+
for (var i = 0; i < this.temp.length; i++) {
|
|
2643
|
+
this.temp[i] = 0;
|
|
2644
|
+
}
|
|
2645
|
+
this.reset();
|
|
2646
|
+
};
|
|
2647
|
+
// Updates hash state with the given data.
|
|
2648
|
+
//
|
|
2649
|
+
// Optionally, length of the data can be specified to hash
|
|
2650
|
+
// fewer bytes than data.length.
|
|
2651
|
+
//
|
|
2652
|
+
// Throws error when trying to update already finalized hash:
|
|
2653
|
+
// instance must be reset to use it again.
|
|
2654
|
+
Hash.prototype.update = function (data, dataLength) {
|
|
2655
|
+
if (dataLength === void 0) { dataLength = data.length; }
|
|
2656
|
+
if (this.finished) {
|
|
2657
|
+
throw new Error("SHA256: can't update because hash was finished.");
|
|
2658
|
+
}
|
|
2659
|
+
var dataPos = 0;
|
|
2660
|
+
this.bytesHashed += dataLength;
|
|
2661
|
+
if (this.bufferLength > 0) {
|
|
2662
|
+
while (this.bufferLength < 64 && dataLength > 0) {
|
|
2663
|
+
this.buffer[this.bufferLength++] = data[dataPos++];
|
|
2664
|
+
dataLength--;
|
|
2665
|
+
}
|
|
2666
|
+
if (this.bufferLength === 64) {
|
|
2667
|
+
hashBlocks(this.temp, this.state, this.buffer, 0, 64);
|
|
2668
|
+
this.bufferLength = 0;
|
|
2669
|
+
}
|
|
2670
|
+
}
|
|
2671
|
+
if (dataLength >= 64) {
|
|
2672
|
+
dataPos = hashBlocks(this.temp, this.state, data, dataPos, dataLength);
|
|
2673
|
+
dataLength %= 64;
|
|
2674
|
+
}
|
|
2675
|
+
while (dataLength > 0) {
|
|
2676
|
+
this.buffer[this.bufferLength++] = data[dataPos++];
|
|
2677
|
+
dataLength--;
|
|
2678
|
+
}
|
|
2679
|
+
return this;
|
|
2680
|
+
};
|
|
2681
|
+
// Finalizes hash state and puts hash into out.
|
|
2682
|
+
//
|
|
2683
|
+
// If hash was already finalized, puts the same value.
|
|
2684
|
+
Hash.prototype.finish = function (out) {
|
|
2685
|
+
if (!this.finished) {
|
|
2686
|
+
var bytesHashed = this.bytesHashed;
|
|
2687
|
+
var left = this.bufferLength;
|
|
2688
|
+
var bitLenHi = (bytesHashed / 0x20000000) | 0;
|
|
2689
|
+
var bitLenLo = bytesHashed << 3;
|
|
2690
|
+
var padLength = (bytesHashed % 64 < 56) ? 64 : 128;
|
|
2691
|
+
this.buffer[left] = 0x80;
|
|
2692
|
+
for (var i = left + 1; i < padLength - 8; i++) {
|
|
2693
|
+
this.buffer[i] = 0;
|
|
2694
|
+
}
|
|
2695
|
+
this.buffer[padLength - 8] = (bitLenHi >>> 24) & 0xff;
|
|
2696
|
+
this.buffer[padLength - 7] = (bitLenHi >>> 16) & 0xff;
|
|
2697
|
+
this.buffer[padLength - 6] = (bitLenHi >>> 8) & 0xff;
|
|
2698
|
+
this.buffer[padLength - 5] = (bitLenHi >>> 0) & 0xff;
|
|
2699
|
+
this.buffer[padLength - 4] = (bitLenLo >>> 24) & 0xff;
|
|
2700
|
+
this.buffer[padLength - 3] = (bitLenLo >>> 16) & 0xff;
|
|
2701
|
+
this.buffer[padLength - 2] = (bitLenLo >>> 8) & 0xff;
|
|
2702
|
+
this.buffer[padLength - 1] = (bitLenLo >>> 0) & 0xff;
|
|
2703
|
+
hashBlocks(this.temp, this.state, this.buffer, 0, padLength);
|
|
2704
|
+
this.finished = true;
|
|
2705
|
+
}
|
|
2706
|
+
for (var i = 0; i < 8; i++) {
|
|
2707
|
+
out[i * 4 + 0] = (this.state[i] >>> 24) & 0xff;
|
|
2708
|
+
out[i * 4 + 1] = (this.state[i] >>> 16) & 0xff;
|
|
2709
|
+
out[i * 4 + 2] = (this.state[i] >>> 8) & 0xff;
|
|
2710
|
+
out[i * 4 + 3] = (this.state[i] >>> 0) & 0xff;
|
|
2711
|
+
}
|
|
2712
|
+
return this;
|
|
2713
|
+
};
|
|
2714
|
+
// Returns the final hash digest.
|
|
2715
|
+
Hash.prototype.digest = function () {
|
|
2716
|
+
var out = new Uint8Array(this.digestLength);
|
|
2717
|
+
this.finish(out);
|
|
2718
|
+
return out;
|
|
2719
|
+
};
|
|
2720
|
+
// Internal function for use in HMAC for optimization.
|
|
2721
|
+
Hash.prototype._saveState = function (out) {
|
|
2722
|
+
for (var i = 0; i < this.state.length; i++) {
|
|
2723
|
+
out[i] = this.state[i];
|
|
2724
|
+
}
|
|
2725
|
+
};
|
|
2726
|
+
// Internal function for use in HMAC for optimization.
|
|
2727
|
+
Hash.prototype._restoreState = function (from, bytesHashed) {
|
|
2728
|
+
for (var i = 0; i < this.state.length; i++) {
|
|
2729
|
+
this.state[i] = from[i];
|
|
2730
|
+
}
|
|
2731
|
+
this.bytesHashed = bytesHashed;
|
|
2732
|
+
this.finished = false;
|
|
2733
|
+
this.bufferLength = 0;
|
|
2734
|
+
};
|
|
2735
|
+
return Hash;
|
|
2736
|
+
}());
|
|
2737
|
+
exports.Hash = Hash;
|
|
2738
|
+
// HMAC implements HMAC-SHA256 message authentication algorithm.
|
|
2739
|
+
var HMAC = /** @class */ (function () {
|
|
2740
|
+
function HMAC(key) {
|
|
2741
|
+
this.inner = new Hash();
|
|
2742
|
+
this.outer = new Hash();
|
|
2743
|
+
this.blockSize = this.inner.blockSize;
|
|
2744
|
+
this.digestLength = this.inner.digestLength;
|
|
2745
|
+
var pad = new Uint8Array(this.blockSize);
|
|
2746
|
+
if (key.length > this.blockSize) {
|
|
2747
|
+
(new Hash()).update(key).finish(pad).clean();
|
|
2748
|
+
}
|
|
2749
|
+
else {
|
|
2750
|
+
for (var i = 0; i < key.length; i++) {
|
|
2751
|
+
pad[i] = key[i];
|
|
2752
|
+
}
|
|
2753
|
+
}
|
|
2754
|
+
for (var i = 0; i < pad.length; i++) {
|
|
2755
|
+
pad[i] ^= 0x36;
|
|
2756
|
+
}
|
|
2757
|
+
this.inner.update(pad);
|
|
2758
|
+
for (var i = 0; i < pad.length; i++) {
|
|
2759
|
+
pad[i] ^= 0x36 ^ 0x5c;
|
|
2760
|
+
}
|
|
2761
|
+
this.outer.update(pad);
|
|
2762
|
+
this.istate = new Uint32Array(8);
|
|
2763
|
+
this.ostate = new Uint32Array(8);
|
|
2764
|
+
this.inner._saveState(this.istate);
|
|
2765
|
+
this.outer._saveState(this.ostate);
|
|
2766
|
+
for (var i = 0; i < pad.length; i++) {
|
|
2767
|
+
pad[i] = 0;
|
|
2768
|
+
}
|
|
2769
|
+
}
|
|
2770
|
+
// Returns HMAC state to the state initialized with key
|
|
2771
|
+
// to make it possible to run HMAC over the other data with the same
|
|
2772
|
+
// key without creating a new instance.
|
|
2773
|
+
HMAC.prototype.reset = function () {
|
|
2774
|
+
this.inner._restoreState(this.istate, this.inner.blockSize);
|
|
2775
|
+
this.outer._restoreState(this.ostate, this.outer.blockSize);
|
|
2776
|
+
return this;
|
|
2777
|
+
};
|
|
2778
|
+
// Cleans HMAC state.
|
|
2779
|
+
HMAC.prototype.clean = function () {
|
|
2780
|
+
for (var i = 0; i < this.istate.length; i++) {
|
|
2781
|
+
this.ostate[i] = this.istate[i] = 0;
|
|
2782
|
+
}
|
|
2783
|
+
this.inner.clean();
|
|
2784
|
+
this.outer.clean();
|
|
2785
|
+
};
|
|
2786
|
+
// Updates state with provided data.
|
|
2787
|
+
HMAC.prototype.update = function (data) {
|
|
2788
|
+
this.inner.update(data);
|
|
2789
|
+
return this;
|
|
2790
|
+
};
|
|
2791
|
+
// Finalizes HMAC and puts the result in out.
|
|
2792
|
+
HMAC.prototype.finish = function (out) {
|
|
2793
|
+
if (this.outer.finished) {
|
|
2794
|
+
this.outer.finish(out);
|
|
2795
|
+
}
|
|
2796
|
+
else {
|
|
2797
|
+
this.inner.finish(out);
|
|
2798
|
+
this.outer.update(out, this.digestLength).finish(out);
|
|
2799
|
+
}
|
|
2800
|
+
return this;
|
|
2801
|
+
};
|
|
2802
|
+
// Returns message authentication code.
|
|
2803
|
+
HMAC.prototype.digest = function () {
|
|
2804
|
+
var out = new Uint8Array(this.digestLength);
|
|
2805
|
+
this.finish(out);
|
|
2806
|
+
return out;
|
|
2807
|
+
};
|
|
2808
|
+
return HMAC;
|
|
2809
|
+
}());
|
|
2810
|
+
exports.HMAC = HMAC;
|
|
2811
|
+
// Returns SHA256 hash of data.
|
|
2812
|
+
function hash(data) {
|
|
2813
|
+
var h = (new Hash()).update(data);
|
|
2814
|
+
var digest = h.digest();
|
|
2815
|
+
h.clean();
|
|
2816
|
+
return digest;
|
|
2817
|
+
}
|
|
2818
|
+
exports.hash = hash;
|
|
2819
|
+
// Function hash is both available as module.hash and as default export.
|
|
2820
|
+
exports["default"] = hash;
|
|
2821
|
+
// Returns HMAC-SHA256 of data under the key.
|
|
2822
|
+
function hmac(key, data) {
|
|
2823
|
+
var h = (new HMAC(key)).update(data);
|
|
2824
|
+
var digest = h.digest();
|
|
2825
|
+
h.clean();
|
|
2826
|
+
return digest;
|
|
2827
|
+
}
|
|
2828
|
+
exports.hmac = hmac;
|
|
2829
|
+
// Fills hkdf buffer like this:
|
|
2830
|
+
// T(1) = HMAC-Hash(PRK, T(0) | info | 0x01)
|
|
2831
|
+
function fillBuffer(buffer, hmac, info, counter) {
|
|
2832
|
+
// Counter is a byte value: check if it overflowed.
|
|
2833
|
+
var num = counter[0];
|
|
2834
|
+
if (num === 0) {
|
|
2835
|
+
throw new Error("hkdf: cannot expand more");
|
|
2836
|
+
}
|
|
2837
|
+
// Prepare HMAC instance for new data with old key.
|
|
2838
|
+
hmac.reset();
|
|
2839
|
+
// Hash in previous output if it was generated
|
|
2840
|
+
// (i.e. counter is greater than 1).
|
|
2841
|
+
if (num > 1) {
|
|
2842
|
+
hmac.update(buffer);
|
|
2843
|
+
}
|
|
2844
|
+
// Hash in info if it exists.
|
|
2845
|
+
if (info) {
|
|
2846
|
+
hmac.update(info);
|
|
2847
|
+
}
|
|
2848
|
+
// Hash in the counter.
|
|
2849
|
+
hmac.update(counter);
|
|
2850
|
+
// Output result to buffer and clean HMAC instance.
|
|
2851
|
+
hmac.finish(buffer);
|
|
2852
|
+
// Increment counter inside typed array, this works properly.
|
|
2853
|
+
counter[0]++;
|
|
2854
|
+
}
|
|
2855
|
+
var hkdfSalt = new Uint8Array(exports.digestLength); // Filled with zeroes.
|
|
2856
|
+
function hkdf(key, salt, info, length) {
|
|
2857
|
+
if (salt === void 0) { salt = hkdfSalt; }
|
|
2858
|
+
if (length === void 0) { length = 32; }
|
|
2859
|
+
var counter = new Uint8Array([1]);
|
|
2860
|
+
// HKDF-Extract uses salt as HMAC key, and key as data.
|
|
2861
|
+
var okm = hmac(salt, key);
|
|
2862
|
+
// Initialize HMAC for expanding with extracted key.
|
|
2863
|
+
// Ensure no collisions with `hmac` function.
|
|
2864
|
+
var hmac_ = new HMAC(okm);
|
|
2865
|
+
// Allocate buffer.
|
|
2866
|
+
var buffer = new Uint8Array(hmac_.digestLength);
|
|
2867
|
+
var bufpos = buffer.length;
|
|
2868
|
+
var out = new Uint8Array(length);
|
|
2869
|
+
for (var i = 0; i < length; i++) {
|
|
2870
|
+
if (bufpos === buffer.length) {
|
|
2871
|
+
fillBuffer(buffer, hmac_, info, counter);
|
|
2872
|
+
bufpos = 0;
|
|
2873
|
+
}
|
|
2874
|
+
out[i] = buffer[bufpos++];
|
|
2875
|
+
}
|
|
2876
|
+
hmac_.clean();
|
|
2877
|
+
buffer.fill(0);
|
|
2878
|
+
counter.fill(0);
|
|
2879
|
+
return out;
|
|
2880
|
+
}
|
|
2881
|
+
exports.hkdf = hkdf;
|
|
2882
|
+
// Derives a key from password and salt using PBKDF2-HMAC-SHA256
|
|
2883
|
+
// with the given number of iterations.
|
|
2884
|
+
//
|
|
2885
|
+
// The number of bytes returned is equal to dkLen.
|
|
2886
|
+
//
|
|
2887
|
+
// (For better security, avoid dkLen greater than hash length - 32 bytes).
|
|
2888
|
+
function pbkdf2(password, salt, iterations, dkLen) {
|
|
2889
|
+
var prf = new HMAC(password);
|
|
2890
|
+
var len = prf.digestLength;
|
|
2891
|
+
var ctr = new Uint8Array(4);
|
|
2892
|
+
var t = new Uint8Array(len);
|
|
2893
|
+
var u = new Uint8Array(len);
|
|
2894
|
+
var dk = new Uint8Array(dkLen);
|
|
2895
|
+
for (var i = 0; i * len < dkLen; i++) {
|
|
2896
|
+
var c = i + 1;
|
|
2897
|
+
ctr[0] = (c >>> 24) & 0xff;
|
|
2898
|
+
ctr[1] = (c >>> 16) & 0xff;
|
|
2899
|
+
ctr[2] = (c >>> 8) & 0xff;
|
|
2900
|
+
ctr[3] = (c >>> 0) & 0xff;
|
|
2901
|
+
prf.reset();
|
|
2902
|
+
prf.update(salt);
|
|
2903
|
+
prf.update(ctr);
|
|
2904
|
+
prf.finish(u);
|
|
2905
|
+
for (var j = 0; j < len; j++) {
|
|
2906
|
+
t[j] = u[j];
|
|
2907
|
+
}
|
|
2908
|
+
for (var j = 2; j <= iterations; j++) {
|
|
2909
|
+
prf.reset();
|
|
2910
|
+
prf.update(u).finish(u);
|
|
2911
|
+
for (var k = 0; k < len; k++) {
|
|
2912
|
+
t[k] ^= u[k];
|
|
2913
|
+
}
|
|
2914
|
+
}
|
|
2915
|
+
for (var j = 0; j < len && i * len + j < dkLen; j++) {
|
|
2916
|
+
dk[i * len + j] = t[j];
|
|
2917
|
+
}
|
|
2918
|
+
}
|
|
2919
|
+
for (var i = 0; i < len; i++) {
|
|
2920
|
+
t[i] = u[i] = 0;
|
|
2921
|
+
}
|
|
2922
|
+
for (var i = 0; i < 4; i++) {
|
|
2923
|
+
ctr[i] = 0;
|
|
2924
|
+
}
|
|
2925
|
+
prf.clean();
|
|
2926
|
+
return dk;
|
|
2927
|
+
}
|
|
2928
|
+
exports.pbkdf2 = pbkdf2;
|
|
2929
|
+
});
|
|
2930
|
+
} (sha256$1));
|
|
2931
|
+
|
|
2932
|
+
var sha256Exports = sha256$1.exports;
|
|
2933
|
+
|
|
2934
|
+
Object.defineProperty(dist, "__esModule", { value: true });
|
|
2935
|
+
var Webhook_1 = dist.Webhook = WebhookVerificationError_1 = dist.WebhookVerificationError = void 0;
|
|
2936
|
+
const timing_safe_equal_1 = timing_safe_equal;
|
|
2937
|
+
const base64 = base64$1;
|
|
2938
|
+
const sha256 = sha256Exports;
|
|
2939
|
+
const WEBHOOK_TOLERANCE_IN_SECONDS = 5 * 60;
|
|
2940
|
+
class ExtendableError extends Error {
|
|
2941
|
+
constructor(message) {
|
|
2942
|
+
super(message);
|
|
2943
|
+
Object.setPrototypeOf(this, ExtendableError.prototype);
|
|
2944
|
+
this.name = "ExtendableError";
|
|
2945
|
+
this.stack = new Error(message).stack;
|
|
2946
|
+
}
|
|
2947
|
+
}
|
|
2948
|
+
class WebhookVerificationError extends ExtendableError {
|
|
2949
|
+
constructor(message) {
|
|
2950
|
+
super(message);
|
|
2951
|
+
Object.setPrototypeOf(this, WebhookVerificationError.prototype);
|
|
2952
|
+
this.name = "WebhookVerificationError";
|
|
2953
|
+
}
|
|
2954
|
+
}
|
|
2955
|
+
var WebhookVerificationError_1 = dist.WebhookVerificationError = WebhookVerificationError;
|
|
2956
|
+
class Webhook {
|
|
2957
|
+
constructor(secret, options) {
|
|
2958
|
+
if (!secret) {
|
|
2959
|
+
throw new Error("Secret can't be empty.");
|
|
2960
|
+
}
|
|
2961
|
+
if ((options === null || options === void 0 ? void 0 : options.format) === "raw") {
|
|
2962
|
+
if (secret instanceof Uint8Array) {
|
|
2963
|
+
this.key = secret;
|
|
2964
|
+
}
|
|
2965
|
+
else {
|
|
2966
|
+
this.key = Uint8Array.from(secret, (c) => c.charCodeAt(0));
|
|
2967
|
+
}
|
|
2968
|
+
}
|
|
2969
|
+
else {
|
|
2970
|
+
if (typeof secret !== "string") {
|
|
2971
|
+
throw new Error("Expected secret to be of type string");
|
|
2972
|
+
}
|
|
2973
|
+
if (secret.startsWith(Webhook.prefix)) {
|
|
2974
|
+
secret = secret.substring(Webhook.prefix.length);
|
|
2975
|
+
}
|
|
2976
|
+
this.key = base64.decode(secret);
|
|
2977
|
+
}
|
|
2978
|
+
}
|
|
2979
|
+
verify(payload, headers_) {
|
|
2980
|
+
const headers = {};
|
|
2981
|
+
for (const key of Object.keys(headers_)) {
|
|
2982
|
+
headers[key.toLowerCase()] = headers_[key];
|
|
2983
|
+
}
|
|
2984
|
+
const msgId = headers["webhook-id"];
|
|
2985
|
+
const msgSignature = headers["webhook-signature"];
|
|
2986
|
+
const msgTimestamp = headers["webhook-timestamp"];
|
|
2987
|
+
if (!msgSignature || !msgId || !msgTimestamp) {
|
|
2988
|
+
throw new WebhookVerificationError("Missing required headers");
|
|
2989
|
+
}
|
|
2990
|
+
const timestamp = this.verifyTimestamp(msgTimestamp);
|
|
2991
|
+
const computedSignature = this.sign(msgId, timestamp, payload);
|
|
2992
|
+
const expectedSignature = computedSignature.split(",")[1];
|
|
2993
|
+
const passedSignatures = msgSignature.split(" ");
|
|
2994
|
+
const encoder = new globalThis.TextEncoder();
|
|
2995
|
+
for (const versionedSignature of passedSignatures) {
|
|
2996
|
+
const [version, signature] = versionedSignature.split(",");
|
|
2997
|
+
if (version !== "v1") {
|
|
2998
|
+
continue;
|
|
2999
|
+
}
|
|
3000
|
+
if ((0, timing_safe_equal_1.timingSafeEqual)(encoder.encode(signature), encoder.encode(expectedSignature))) {
|
|
3001
|
+
return JSON.parse(payload.toString());
|
|
3002
|
+
}
|
|
3003
|
+
}
|
|
3004
|
+
throw new WebhookVerificationError("No matching signature found");
|
|
3005
|
+
}
|
|
3006
|
+
sign(msgId, timestamp, payload) {
|
|
3007
|
+
if (typeof payload === "string") ;
|
|
3008
|
+
else if (payload.constructor.name === "Buffer") {
|
|
3009
|
+
payload = payload.toString();
|
|
3010
|
+
}
|
|
3011
|
+
else {
|
|
3012
|
+
throw new Error("Expected payload to be of type string or Buffer.");
|
|
3013
|
+
}
|
|
3014
|
+
const encoder = new TextEncoder();
|
|
3015
|
+
const timestampNumber = Math.floor(timestamp.getTime() / 1000);
|
|
3016
|
+
const toSign = encoder.encode(`${msgId}.${timestampNumber}.${payload}`);
|
|
3017
|
+
const expectedSignature = base64.encode(sha256.hmac(this.key, toSign));
|
|
3018
|
+
return `v1,${expectedSignature}`;
|
|
3019
|
+
}
|
|
3020
|
+
verifyTimestamp(timestampHeader) {
|
|
3021
|
+
const now = Math.floor(Date.now() / 1000);
|
|
3022
|
+
const timestamp = parseInt(timestampHeader, 10);
|
|
3023
|
+
if (isNaN(timestamp)) {
|
|
3024
|
+
throw new WebhookVerificationError("Invalid Signature Headers");
|
|
3025
|
+
}
|
|
3026
|
+
if (now - timestamp > WEBHOOK_TOLERANCE_IN_SECONDS) {
|
|
3027
|
+
throw new WebhookVerificationError("Message timestamp too old");
|
|
3028
|
+
}
|
|
3029
|
+
if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) {
|
|
3030
|
+
throw new WebhookVerificationError("Message timestamp too new");
|
|
3031
|
+
}
|
|
3032
|
+
return new Date(timestamp * 1000);
|
|
3033
|
+
}
|
|
3034
|
+
}
|
|
3035
|
+
Webhook_1 = dist.Webhook = Webhook;
|
|
3036
|
+
Webhook.prefix = "whsec_";
|
|
3037
|
+
|
|
3038
|
+
var PaymentSchema = zod.z.object({
|
|
3039
|
+
payload_type: zod.z.literal("Payment"),
|
|
3040
|
+
billing: zod.z.object({
|
|
3041
|
+
city: zod.z.string().nullable(),
|
|
3042
|
+
country: zod.z.string().nullable(),
|
|
3043
|
+
state: zod.z.string().nullable(),
|
|
3044
|
+
street: zod.z.string().nullable(),
|
|
3045
|
+
zipcode: zod.z.string().nullable(),
|
|
3046
|
+
}),
|
|
3047
|
+
brand_id: zod.z.string(),
|
|
3048
|
+
business_id: zod.z.string(),
|
|
3049
|
+
card_issuing_country: zod.z.string().nullable(),
|
|
3050
|
+
card_last_four: zod.z.string().nullable(),
|
|
3051
|
+
card_network: zod.z.string().nullable(),
|
|
3052
|
+
card_type: zod.z.string().nullable(),
|
|
3053
|
+
created_at: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3054
|
+
currency: zod.z.string(),
|
|
3055
|
+
customer: zod.z.object({
|
|
3056
|
+
customer_id: zod.z.string(),
|
|
3057
|
+
email: zod.z.string(),
|
|
3058
|
+
name: zod.z.string().nullable(),
|
|
3059
|
+
}),
|
|
3060
|
+
digital_products_delivered: zod.z.boolean(),
|
|
3061
|
+
discount_id: zod.z.string().nullable(),
|
|
3062
|
+
disputes: zod.z
|
|
3063
|
+
.array(zod.z.object({
|
|
3064
|
+
amount: zod.z.string(),
|
|
3065
|
+
business_id: zod.z.string(),
|
|
3066
|
+
created_at: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3067
|
+
currency: zod.z.string(),
|
|
3068
|
+
dispute_id: zod.z.string(),
|
|
3069
|
+
dispute_stage: zod.z.enum([
|
|
3070
|
+
"pre_dispute",
|
|
3071
|
+
"dispute_opened",
|
|
3072
|
+
"dispute_won",
|
|
3073
|
+
"dispute_lost",
|
|
3074
|
+
]),
|
|
3075
|
+
dispute_status: zod.z.enum([
|
|
3076
|
+
"dispute_opened",
|
|
3077
|
+
"dispute_won",
|
|
3078
|
+
"dispute_lost",
|
|
3079
|
+
"dispute_accepted",
|
|
3080
|
+
"dispute_cancelled",
|
|
3081
|
+
"dispute_challenged",
|
|
3082
|
+
]),
|
|
3083
|
+
payment_id: zod.z.string(),
|
|
3084
|
+
remarks: zod.z.string().nullable(),
|
|
3085
|
+
}))
|
|
3086
|
+
.nullable(),
|
|
3087
|
+
error_code: zod.z.string().nullable(),
|
|
3088
|
+
error_message: zod.z.string().nullable(),
|
|
3089
|
+
metadata: zod.z.record(zod.z.any()).nullable(),
|
|
3090
|
+
payment_id: zod.z.string(),
|
|
3091
|
+
payment_link: zod.z.string().nullable(),
|
|
3092
|
+
payment_method: zod.z.string().nullable(),
|
|
3093
|
+
payment_method_type: zod.z.string().nullable(),
|
|
3094
|
+
product_cart: zod.z
|
|
3095
|
+
.array(zod.z.object({
|
|
3096
|
+
product_id: zod.z.string(),
|
|
3097
|
+
quantity: zod.z.number(),
|
|
3098
|
+
}))
|
|
3099
|
+
.nullable(),
|
|
3100
|
+
refunds: zod.z
|
|
3101
|
+
.array(zod.z.object({
|
|
3102
|
+
amount: zod.z.number(),
|
|
3103
|
+
business_id: zod.z.string(),
|
|
3104
|
+
created_at: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3105
|
+
currency: zod.z.string(),
|
|
3106
|
+
is_partial: zod.z.boolean(),
|
|
3107
|
+
payment_id: zod.z.string(),
|
|
3108
|
+
reason: zod.z.string().nullable(),
|
|
3109
|
+
refund_id: zod.z.string(),
|
|
3110
|
+
status: zod.z.enum(["succeeded", "failed", "pending"]),
|
|
3111
|
+
}))
|
|
3112
|
+
.nullable(),
|
|
3113
|
+
settlement_amount: zod.z.number(),
|
|
3114
|
+
settlement_currency: zod.z.string(),
|
|
3115
|
+
settlement_tax: zod.z.number().nullable(),
|
|
3116
|
+
status: zod.z.enum(["succeeded", "failed", "pending", "processing", "cancelled"]),
|
|
3117
|
+
subscription_id: zod.z.string().nullable(),
|
|
3118
|
+
tax: zod.z.number().nullable(),
|
|
3119
|
+
total_amount: zod.z.number(),
|
|
3120
|
+
updated_at: zod.z
|
|
3121
|
+
.string()
|
|
3122
|
+
.transform(function (d) { return new Date(d); })
|
|
3123
|
+
.nullable(),
|
|
3124
|
+
});
|
|
3125
|
+
var SubscriptionSchema = zod.z.object({
|
|
3126
|
+
payload_type: zod.z.literal("Subscription"),
|
|
3127
|
+
addons: zod.z
|
|
3128
|
+
.array(zod.z.object({
|
|
3129
|
+
addon_id: zod.z.string(),
|
|
3130
|
+
quantity: zod.z.number(),
|
|
3131
|
+
}))
|
|
3132
|
+
.nullable(),
|
|
3133
|
+
billing: zod.z.object({
|
|
3134
|
+
city: zod.z.string().nullable(),
|
|
3135
|
+
country: zod.z.string().nullable(),
|
|
3136
|
+
state: zod.z.string().nullable(),
|
|
3137
|
+
street: zod.z.string().nullable(),
|
|
3138
|
+
zipcode: zod.z.string().nullable(),
|
|
3139
|
+
}),
|
|
3140
|
+
cancel_at_next_billing_date: zod.z.boolean(),
|
|
3141
|
+
cancelled_at: zod.z
|
|
3142
|
+
.string()
|
|
3143
|
+
.transform(function (d) { return new Date(d); })
|
|
3144
|
+
.nullable(),
|
|
3145
|
+
created_at: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3146
|
+
currency: zod.z.string(),
|
|
3147
|
+
customer: zod.z.object({
|
|
3148
|
+
customer_id: zod.z.string(),
|
|
3149
|
+
email: zod.z.string(),
|
|
3150
|
+
name: zod.z.string().nullable(),
|
|
3151
|
+
}),
|
|
3152
|
+
discount_id: zod.z.string().nullable(),
|
|
3153
|
+
metadata: zod.z.record(zod.z.any()).nullable(),
|
|
3154
|
+
next_billing_date: zod.z
|
|
3155
|
+
.string()
|
|
3156
|
+
.transform(function (d) { return new Date(d); })
|
|
3157
|
+
.nullable(),
|
|
3158
|
+
on_demand: zod.z.boolean(),
|
|
3159
|
+
payment_frequency_count: zod.z.number(),
|
|
3160
|
+
payment_frequency_interval: zod.z.enum(["Day", "Week", "Month", "Year"]),
|
|
3161
|
+
previous_billing_date: zod.z
|
|
3162
|
+
.string()
|
|
3163
|
+
.transform(function (d) { return new Date(d); })
|
|
3164
|
+
.nullable(),
|
|
3165
|
+
product_id: zod.z.string(),
|
|
3166
|
+
quantity: zod.z.number(),
|
|
3167
|
+
recurring_pre_tax_amount: zod.z.number(),
|
|
3168
|
+
status: zod.z.enum([
|
|
3169
|
+
"pending",
|
|
3170
|
+
"active",
|
|
3171
|
+
"on_hold",
|
|
3172
|
+
"paused",
|
|
3173
|
+
"cancelled",
|
|
3174
|
+
"expired",
|
|
3175
|
+
"failed",
|
|
3176
|
+
]),
|
|
3177
|
+
subscription_id: zod.z.string(),
|
|
3178
|
+
subscription_period_count: zod.z.number(),
|
|
3179
|
+
subscription_period_interval: zod.z.enum(["Day", "Week", "Month", "Year"]),
|
|
3180
|
+
tax_inclusive: zod.z.boolean(),
|
|
3181
|
+
trial_period_days: zod.z.number(),
|
|
3182
|
+
});
|
|
3183
|
+
var RefundSchema = zod.z.object({
|
|
3184
|
+
payload_type: zod.z.literal("Refund"),
|
|
3185
|
+
amount: zod.z.number(),
|
|
3186
|
+
business_id: zod.z.string(),
|
|
3187
|
+
created_at: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3188
|
+
currency: zod.z.string(),
|
|
3189
|
+
is_partial: zod.z.boolean(),
|
|
3190
|
+
payment_id: zod.z.string(),
|
|
3191
|
+
reason: zod.z.string().nullable(),
|
|
3192
|
+
refund_id: zod.z.string(),
|
|
3193
|
+
status: zod.z.enum(["succeeded", "failed", "pending"]),
|
|
3194
|
+
});
|
|
3195
|
+
var DisputeSchema = zod.z.object({
|
|
3196
|
+
payload_type: zod.z.literal("Dispute"),
|
|
3197
|
+
amount: zod.z.string(),
|
|
3198
|
+
business_id: zod.z.string(),
|
|
3199
|
+
created_at: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3200
|
+
currency: zod.z.string(),
|
|
3201
|
+
dispute_id: zod.z.string(),
|
|
3202
|
+
dispute_stage: zod.z.enum([
|
|
3203
|
+
"pre_dispute",
|
|
3204
|
+
"dispute_opened",
|
|
3205
|
+
"dispute_won",
|
|
3206
|
+
"dispute_lost",
|
|
3207
|
+
]),
|
|
3208
|
+
dispute_status: zod.z.enum([
|
|
3209
|
+
"dispute_opened",
|
|
3210
|
+
"dispute_won",
|
|
3211
|
+
"dispute_lost",
|
|
3212
|
+
"dispute_accepted",
|
|
3213
|
+
"dispute_cancelled",
|
|
3214
|
+
"dispute_challenged",
|
|
3215
|
+
]),
|
|
3216
|
+
payment_id: zod.z.string(),
|
|
3217
|
+
remarks: zod.z.string().nullable(),
|
|
3218
|
+
});
|
|
3219
|
+
var LicenseKeySchema = zod.z.object({
|
|
3220
|
+
payload_type: zod.z.literal("LicenseKey"),
|
|
3221
|
+
activations_limit: zod.z.number(),
|
|
3222
|
+
business_id: zod.z.string(),
|
|
3223
|
+
created_at: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3224
|
+
customer_id: zod.z.string(),
|
|
3225
|
+
expires_at: zod.z
|
|
3226
|
+
.string()
|
|
3227
|
+
.transform(function (d) { return new Date(d); })
|
|
3228
|
+
.nullable(),
|
|
3229
|
+
id: zod.z.string(),
|
|
3230
|
+
instances_count: zod.z.number(),
|
|
3231
|
+
key: zod.z.string(),
|
|
3232
|
+
payment_id: zod.z.string(),
|
|
3233
|
+
product_id: zod.z.string(),
|
|
3234
|
+
status: zod.z.enum(["active", "inactive", "expired"]),
|
|
3235
|
+
subscription_id: zod.z.string().nullable(),
|
|
3236
|
+
});
|
|
3237
|
+
var PaymentSucceededPayloadSchema = zod.z.object({
|
|
3238
|
+
business_id: zod.z.string(),
|
|
3239
|
+
type: zod.z.literal("payment.succeeded"),
|
|
3240
|
+
timestamp: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3241
|
+
data: PaymentSchema,
|
|
3242
|
+
});
|
|
3243
|
+
var PaymentFailedPayloadSchema = zod.z.object({
|
|
3244
|
+
business_id: zod.z.string(),
|
|
3245
|
+
type: zod.z.literal("payment.failed"),
|
|
3246
|
+
timestamp: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3247
|
+
data: PaymentSchema,
|
|
3248
|
+
});
|
|
3249
|
+
var PaymentProcessingPayloadSchema = zod.z.object({
|
|
3250
|
+
business_id: zod.z.string(),
|
|
3251
|
+
type: zod.z.literal("payment.processing"),
|
|
3252
|
+
timestamp: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3253
|
+
data: PaymentSchema,
|
|
3254
|
+
});
|
|
3255
|
+
var PaymentCancelledPayloadSchema = zod.z.object({
|
|
3256
|
+
business_id: zod.z.string(),
|
|
3257
|
+
type: zod.z.literal("payment.cancelled"),
|
|
3258
|
+
timestamp: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3259
|
+
data: PaymentSchema,
|
|
3260
|
+
});
|
|
3261
|
+
var RefundSucceededPayloadSchema = zod.z.object({
|
|
3262
|
+
business_id: zod.z.string(),
|
|
3263
|
+
type: zod.z.literal("refund.succeeded"),
|
|
3264
|
+
timestamp: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3265
|
+
data: RefundSchema,
|
|
3266
|
+
});
|
|
3267
|
+
var RefundFailedPayloadSchema = zod.z.object({
|
|
3268
|
+
business_id: zod.z.string(),
|
|
3269
|
+
type: zod.z.literal("refund.failed"),
|
|
3270
|
+
timestamp: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3271
|
+
data: RefundSchema,
|
|
3272
|
+
});
|
|
3273
|
+
var DisputeOpenedPayloadSchema = zod.z.object({
|
|
3274
|
+
business_id: zod.z.string(),
|
|
3275
|
+
type: zod.z.literal("dispute.opened"),
|
|
3276
|
+
timestamp: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3277
|
+
data: DisputeSchema,
|
|
3278
|
+
});
|
|
3279
|
+
var DisputeExpiredPayloadSchema = zod.z.object({
|
|
3280
|
+
business_id: zod.z.string(),
|
|
3281
|
+
type: zod.z.literal("dispute.expired"),
|
|
3282
|
+
timestamp: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3283
|
+
data: DisputeSchema,
|
|
3284
|
+
});
|
|
3285
|
+
var DisputeAcceptedPayloadSchema = zod.z.object({
|
|
3286
|
+
business_id: zod.z.string(),
|
|
3287
|
+
type: zod.z.literal("dispute.accepted"),
|
|
3288
|
+
timestamp: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3289
|
+
data: DisputeSchema,
|
|
3290
|
+
});
|
|
3291
|
+
var DisputeCancelledPayloadSchema = zod.z.object({
|
|
3292
|
+
business_id: zod.z.string(),
|
|
3293
|
+
type: zod.z.literal("dispute.cancelled"),
|
|
3294
|
+
timestamp: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3295
|
+
data: DisputeSchema,
|
|
3296
|
+
});
|
|
3297
|
+
var DisputeChallengedPayloadSchema = zod.z.object({
|
|
3298
|
+
business_id: zod.z.string(),
|
|
3299
|
+
type: zod.z.literal("dispute.challenged"),
|
|
3300
|
+
timestamp: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3301
|
+
data: DisputeSchema,
|
|
3302
|
+
});
|
|
3303
|
+
var DisputeWonPayloadSchema = zod.z.object({
|
|
3304
|
+
business_id: zod.z.string(),
|
|
3305
|
+
type: zod.z.literal("dispute.won"),
|
|
3306
|
+
timestamp: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3307
|
+
data: DisputeSchema,
|
|
3308
|
+
});
|
|
3309
|
+
var DisputeLostPayloadSchema = zod.z.object({
|
|
3310
|
+
business_id: zod.z.string(),
|
|
3311
|
+
type: zod.z.literal("dispute.lost"),
|
|
3312
|
+
timestamp: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3313
|
+
data: DisputeSchema,
|
|
3314
|
+
});
|
|
3315
|
+
var SubscriptionActivePayloadSchema = zod.z.object({
|
|
3316
|
+
business_id: zod.z.string(),
|
|
3317
|
+
type: zod.z.literal("subscription.active"),
|
|
3318
|
+
timestamp: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3319
|
+
data: SubscriptionSchema,
|
|
3320
|
+
});
|
|
3321
|
+
var SubscriptionOnHoldPayloadSchema = zod.z.object({
|
|
3322
|
+
business_id: zod.z.string(),
|
|
3323
|
+
type: zod.z.literal("subscription.on_hold"),
|
|
3324
|
+
timestamp: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3325
|
+
data: SubscriptionSchema,
|
|
3326
|
+
});
|
|
3327
|
+
var SubscriptionRenewedPayloadSchema = zod.z.object({
|
|
3328
|
+
business_id: zod.z.string(),
|
|
3329
|
+
type: zod.z.literal("subscription.renewed"),
|
|
3330
|
+
timestamp: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3331
|
+
data: SubscriptionSchema,
|
|
3332
|
+
});
|
|
3333
|
+
var SubscriptionPausedPayloadSchema = zod.z.object({
|
|
3334
|
+
business_id: zod.z.string(),
|
|
3335
|
+
type: zod.z.literal("subscription.paused"),
|
|
3336
|
+
timestamp: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3337
|
+
data: SubscriptionSchema,
|
|
3338
|
+
});
|
|
3339
|
+
var SubscriptionPlanChangedPayloadSchema = zod.z.object({
|
|
3340
|
+
business_id: zod.z.string(),
|
|
3341
|
+
type: zod.z.literal("subscription.plan_changed"),
|
|
3342
|
+
timestamp: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3343
|
+
data: SubscriptionSchema,
|
|
3344
|
+
});
|
|
3345
|
+
var SubscriptionCancelledPayloadSchema = zod.z.object({
|
|
3346
|
+
business_id: zod.z.string(),
|
|
3347
|
+
type: zod.z.literal("subscription.cancelled"),
|
|
3348
|
+
timestamp: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3349
|
+
data: SubscriptionSchema,
|
|
3350
|
+
});
|
|
3351
|
+
var SubscriptionFailedPayloadSchema = zod.z.object({
|
|
3352
|
+
business_id: zod.z.string(),
|
|
3353
|
+
type: zod.z.literal("subscription.failed"),
|
|
3354
|
+
timestamp: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3355
|
+
data: SubscriptionSchema,
|
|
3356
|
+
});
|
|
3357
|
+
var SubscriptionExpiredPayloadSchema = zod.z.object({
|
|
3358
|
+
business_id: zod.z.string(),
|
|
3359
|
+
type: zod.z.literal("subscription.expired"),
|
|
3360
|
+
timestamp: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3361
|
+
data: SubscriptionSchema,
|
|
3362
|
+
});
|
|
3363
|
+
var LicenseKeyCreatedPayloadSchema = zod.z.object({
|
|
3364
|
+
business_id: zod.z.string(),
|
|
3365
|
+
type: zod.z.literal("license_key.created"),
|
|
3366
|
+
timestamp: zod.z.string().transform(function (d) { return new Date(d); }),
|
|
3367
|
+
data: LicenseKeySchema,
|
|
3368
|
+
});
|
|
3369
|
+
var WebhookPayloadSchema = zod.z.discriminatedUnion("type", [
|
|
3370
|
+
PaymentSucceededPayloadSchema,
|
|
3371
|
+
PaymentFailedPayloadSchema,
|
|
3372
|
+
PaymentProcessingPayloadSchema,
|
|
3373
|
+
PaymentCancelledPayloadSchema,
|
|
3374
|
+
RefundSucceededPayloadSchema,
|
|
3375
|
+
RefundFailedPayloadSchema,
|
|
3376
|
+
DisputeOpenedPayloadSchema,
|
|
3377
|
+
DisputeExpiredPayloadSchema,
|
|
3378
|
+
DisputeAcceptedPayloadSchema,
|
|
3379
|
+
DisputeCancelledPayloadSchema,
|
|
3380
|
+
DisputeChallengedPayloadSchema,
|
|
3381
|
+
DisputeWonPayloadSchema,
|
|
3382
|
+
DisputeLostPayloadSchema,
|
|
3383
|
+
SubscriptionActivePayloadSchema,
|
|
3384
|
+
SubscriptionOnHoldPayloadSchema,
|
|
3385
|
+
SubscriptionRenewedPayloadSchema,
|
|
3386
|
+
SubscriptionPausedPayloadSchema,
|
|
3387
|
+
SubscriptionPlanChangedPayloadSchema,
|
|
3388
|
+
SubscriptionCancelledPayloadSchema,
|
|
3389
|
+
SubscriptionFailedPayloadSchema,
|
|
3390
|
+
SubscriptionExpiredPayloadSchema,
|
|
3391
|
+
LicenseKeyCreatedPayloadSchema,
|
|
3392
|
+
]);
|
|
3393
|
+
|
|
3394
|
+
var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3395
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3396
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
3397
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
3398
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
3399
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
3400
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
3401
|
+
});
|
|
3402
|
+
};
|
|
3403
|
+
var __generator = (undefined && undefined.__generator) || function (thisArg, body) {
|
|
3404
|
+
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
|
|
3405
|
+
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
|
3406
|
+
function verb(n) { return function (v) { return step([n, v]); }; }
|
|
3407
|
+
function step(op) {
|
|
3408
|
+
if (f) throw new TypeError("Generator is already executing.");
|
|
3409
|
+
while (g && (g = 0, op[0] && (_ = 0)), _) try {
|
|
3410
|
+
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
|
3411
|
+
if (y = 0, t) op = [op[0] & 2, t.value];
|
|
3412
|
+
switch (op[0]) {
|
|
3413
|
+
case 0: case 1: t = op; break;
|
|
3414
|
+
case 4: _.label++; return { value: op[1], done: false };
|
|
3415
|
+
case 5: _.label++; y = op[1]; op = [0]; continue;
|
|
3416
|
+
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
|
3417
|
+
default:
|
|
3418
|
+
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
|
3419
|
+
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
|
3420
|
+
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
|
3421
|
+
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
|
3422
|
+
if (t[2]) _.ops.pop();
|
|
3423
|
+
_.trys.pop(); continue;
|
|
3424
|
+
}
|
|
3425
|
+
op = body.call(thisArg, _);
|
|
3426
|
+
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
|
3427
|
+
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
|
3428
|
+
}
|
|
3429
|
+
};
|
|
3430
|
+
var handleWebhookPayload = function (payload, config) { return __awaiter(void 0, void 0, void 0, function () {
|
|
3431
|
+
return __generator(this, function (_a) {
|
|
3432
|
+
switch (_a.label) {
|
|
3433
|
+
case 0:
|
|
3434
|
+
if (!config.onPayload) return [3 /*break*/, 2];
|
|
3435
|
+
return [4 /*yield*/, config.onPayload(payload)];
|
|
3436
|
+
case 1:
|
|
3437
|
+
_a.sent();
|
|
3438
|
+
_a.label = 2;
|
|
3439
|
+
case 2:
|
|
3440
|
+
if (!(payload.type === "payment.succeeded" && config.onPaymentSucceeded)) return [3 /*break*/, 4];
|
|
3441
|
+
return [4 /*yield*/, config.onPaymentSucceeded(payload)];
|
|
3442
|
+
case 3:
|
|
3443
|
+
_a.sent();
|
|
3444
|
+
_a.label = 4;
|
|
3445
|
+
case 4:
|
|
3446
|
+
if (!(payload.type === "payment.failed" && config.onPaymentFailed)) return [3 /*break*/, 6];
|
|
3447
|
+
return [4 /*yield*/, config.onPaymentFailed(payload)];
|
|
3448
|
+
case 5:
|
|
3449
|
+
_a.sent();
|
|
3450
|
+
_a.label = 6;
|
|
3451
|
+
case 6:
|
|
3452
|
+
if (!(payload.type === "payment.processing" && config.onPaymentProcessing)) return [3 /*break*/, 8];
|
|
3453
|
+
return [4 /*yield*/, config.onPaymentProcessing(payload)];
|
|
3454
|
+
case 7:
|
|
3455
|
+
_a.sent();
|
|
3456
|
+
_a.label = 8;
|
|
3457
|
+
case 8:
|
|
3458
|
+
if (!(payload.type === "payment.cancelled" && config.onPaymentCancelled)) return [3 /*break*/, 10];
|
|
3459
|
+
return [4 /*yield*/, config.onPaymentCancelled(payload)];
|
|
3460
|
+
case 9:
|
|
3461
|
+
_a.sent();
|
|
3462
|
+
_a.label = 10;
|
|
3463
|
+
case 10:
|
|
3464
|
+
if (!(payload.type === "refund.succeeded" && config.onRefundSucceeded)) return [3 /*break*/, 12];
|
|
3465
|
+
return [4 /*yield*/, config.onRefundSucceeded(payload)];
|
|
3466
|
+
case 11:
|
|
3467
|
+
_a.sent();
|
|
3468
|
+
_a.label = 12;
|
|
3469
|
+
case 12:
|
|
3470
|
+
if (!(payload.type === "refund.failed" && config.onRefundFailed)) return [3 /*break*/, 14];
|
|
3471
|
+
return [4 /*yield*/, config.onRefundFailed(payload)];
|
|
3472
|
+
case 13:
|
|
3473
|
+
_a.sent();
|
|
3474
|
+
_a.label = 14;
|
|
3475
|
+
case 14:
|
|
3476
|
+
if (!(payload.type === "dispute.opened" && config.onDisputeOpened)) return [3 /*break*/, 16];
|
|
3477
|
+
return [4 /*yield*/, config.onDisputeOpened(payload)];
|
|
3478
|
+
case 15:
|
|
3479
|
+
_a.sent();
|
|
3480
|
+
_a.label = 16;
|
|
3481
|
+
case 16:
|
|
3482
|
+
if (!(payload.type === "dispute.expired" && config.onDisputeExpired)) return [3 /*break*/, 18];
|
|
3483
|
+
return [4 /*yield*/, config.onDisputeExpired(payload)];
|
|
3484
|
+
case 17:
|
|
3485
|
+
_a.sent();
|
|
3486
|
+
_a.label = 18;
|
|
3487
|
+
case 18:
|
|
3488
|
+
if (!(payload.type === "dispute.accepted" && config.onDisputeAccepted)) return [3 /*break*/, 20];
|
|
3489
|
+
return [4 /*yield*/, config.onDisputeAccepted(payload)];
|
|
3490
|
+
case 19:
|
|
3491
|
+
_a.sent();
|
|
3492
|
+
_a.label = 20;
|
|
3493
|
+
case 20:
|
|
3494
|
+
if (!(payload.type === "dispute.cancelled" && config.onDisputeCancelled)) return [3 /*break*/, 22];
|
|
3495
|
+
return [4 /*yield*/, config.onDisputeCancelled(payload)];
|
|
3496
|
+
case 21:
|
|
3497
|
+
_a.sent();
|
|
3498
|
+
_a.label = 22;
|
|
3499
|
+
case 22:
|
|
3500
|
+
if (!(payload.type === "dispute.challenged" && config.onDisputeChallenged)) return [3 /*break*/, 24];
|
|
3501
|
+
return [4 /*yield*/, config.onDisputeChallenged(payload)];
|
|
3502
|
+
case 23:
|
|
3503
|
+
_a.sent();
|
|
3504
|
+
_a.label = 24;
|
|
3505
|
+
case 24:
|
|
3506
|
+
if (!(payload.type === "dispute.won" && config.onDisputeWon)) return [3 /*break*/, 26];
|
|
3507
|
+
return [4 /*yield*/, config.onDisputeWon(payload)];
|
|
3508
|
+
case 25:
|
|
3509
|
+
_a.sent();
|
|
3510
|
+
_a.label = 26;
|
|
3511
|
+
case 26:
|
|
3512
|
+
if (!(payload.type === "dispute.lost" && config.onDisputeLost)) return [3 /*break*/, 28];
|
|
3513
|
+
return [4 /*yield*/, config.onDisputeLost(payload)];
|
|
3514
|
+
case 27:
|
|
3515
|
+
_a.sent();
|
|
3516
|
+
_a.label = 28;
|
|
3517
|
+
case 28:
|
|
3518
|
+
if (!(payload.type === "subscription.active" && config.onSubscriptionActive)) return [3 /*break*/, 30];
|
|
3519
|
+
return [4 /*yield*/, config.onSubscriptionActive(payload)];
|
|
3520
|
+
case 29:
|
|
3521
|
+
_a.sent();
|
|
3522
|
+
_a.label = 30;
|
|
3523
|
+
case 30:
|
|
3524
|
+
if (!(payload.type === "subscription.on_hold" && config.onSubscriptionOnHold)) return [3 /*break*/, 32];
|
|
3525
|
+
return [4 /*yield*/, config.onSubscriptionOnHold(payload)];
|
|
3526
|
+
case 31:
|
|
3527
|
+
_a.sent();
|
|
3528
|
+
_a.label = 32;
|
|
3529
|
+
case 32:
|
|
3530
|
+
if (!(payload.type === "subscription.renewed" && config.onSubscriptionRenewed)) return [3 /*break*/, 34];
|
|
3531
|
+
return [4 /*yield*/, config.onSubscriptionRenewed(payload)];
|
|
3532
|
+
case 33:
|
|
3533
|
+
_a.sent();
|
|
3534
|
+
_a.label = 34;
|
|
3535
|
+
case 34:
|
|
3536
|
+
if (!(payload.type === "subscription.paused" && config.onSubscriptionPaused)) return [3 /*break*/, 36];
|
|
3537
|
+
return [4 /*yield*/, config.onSubscriptionPaused(payload)];
|
|
3538
|
+
case 35:
|
|
3539
|
+
_a.sent();
|
|
3540
|
+
_a.label = 36;
|
|
3541
|
+
case 36:
|
|
3542
|
+
if (!(payload.type === "subscription.plan_changed" &&
|
|
3543
|
+
config.onSubscriptionPlanChanged)) return [3 /*break*/, 38];
|
|
3544
|
+
return [4 /*yield*/, config.onSubscriptionPlanChanged(payload)];
|
|
3545
|
+
case 37:
|
|
3546
|
+
_a.sent();
|
|
3547
|
+
_a.label = 38;
|
|
3548
|
+
case 38:
|
|
3549
|
+
if (!(payload.type === "subscription.cancelled" &&
|
|
3550
|
+
config.onSubscriptionCancelled)) return [3 /*break*/, 40];
|
|
3551
|
+
return [4 /*yield*/, config.onSubscriptionCancelled(payload)];
|
|
3552
|
+
case 39:
|
|
3553
|
+
_a.sent();
|
|
3554
|
+
_a.label = 40;
|
|
3555
|
+
case 40:
|
|
3556
|
+
if (!(payload.type === "subscription.failed" && config.onSubscriptionFailed)) return [3 /*break*/, 42];
|
|
3557
|
+
return [4 /*yield*/, config.onSubscriptionFailed(payload)];
|
|
3558
|
+
case 41:
|
|
3559
|
+
_a.sent();
|
|
3560
|
+
_a.label = 42;
|
|
3561
|
+
case 42:
|
|
3562
|
+
if (!(payload.type === "subscription.expired" && config.onSubscriptionExpired)) return [3 /*break*/, 44];
|
|
3563
|
+
return [4 /*yield*/, config.onSubscriptionExpired(payload)];
|
|
3564
|
+
case 43:
|
|
3565
|
+
_a.sent();
|
|
3566
|
+
_a.label = 44;
|
|
3567
|
+
case 44:
|
|
3568
|
+
if (!(payload.type === "license_key.created" && config.onLicenseKeyCreated)) return [3 /*break*/, 46];
|
|
3569
|
+
return [4 /*yield*/, config.onLicenseKeyCreated(payload)];
|
|
3570
|
+
case 45:
|
|
3571
|
+
_a.sent();
|
|
3572
|
+
_a.label = 46;
|
|
3573
|
+
case 46: return [2 /*return*/];
|
|
3574
|
+
}
|
|
3575
|
+
});
|
|
3576
|
+
}); };
|
|
3577
|
+
|
|
3578
|
+
const Webhooks = ({ webhookKey, ...eventHandlers }) => {
|
|
3579
|
+
const standardWebhook = new Webhook_1(webhookKey);
|
|
3580
|
+
return async (c) => {
|
|
3581
|
+
if (c.req.method !== "POST") {
|
|
3582
|
+
return c.text("Method not allowed. Use POST", 405);
|
|
3583
|
+
}
|
|
3584
|
+
const headers = {
|
|
3585
|
+
"webhook-id": c.req.header("webhook-id") ?? "",
|
|
3586
|
+
"webhook-timestamp": c.req.header("webhook-timestamp") ?? "",
|
|
3587
|
+
"webhook-signature": c.req.header("webhook-signature") ?? "",
|
|
3588
|
+
};
|
|
3589
|
+
const rawBody = await c.req.text();
|
|
3590
|
+
try {
|
|
3591
|
+
standardWebhook.verify(rawBody, headers);
|
|
3592
|
+
}
|
|
3593
|
+
catch (err) {
|
|
3594
|
+
if (err instanceof WebhookVerificationError_1) {
|
|
3595
|
+
return c.text(err.message, 401);
|
|
3596
|
+
}
|
|
3597
|
+
return c.text("Error while verifying webhook", 500);
|
|
3598
|
+
}
|
|
3599
|
+
const { success, data: payload, error, } = WebhookPayloadSchema.safeParse(JSON.parse(rawBody));
|
|
3600
|
+
if (!success) {
|
|
3601
|
+
console.error("Error parsing webhook payload", error.issues);
|
|
3602
|
+
return c.text(`Error parsing webhook payload: ${error.message}`, 400);
|
|
3603
|
+
}
|
|
3604
|
+
// do not catch errors here, let them bubble up to the user
|
|
3605
|
+
// as they will originate from the handlers passed by the user
|
|
3606
|
+
await handleWebhookPayload(payload, {
|
|
3607
|
+
webhookKey,
|
|
3608
|
+
...eventHandlers,
|
|
3609
|
+
});
|
|
3610
|
+
return c.text("", 200);
|
|
3611
|
+
};
|
|
3612
|
+
};
|
|
3613
|
+
|
|
3614
|
+
exports.Checkout = Checkout;
|
|
3615
|
+
exports.CustomerPortal = CustomerPortal;
|
|
3616
|
+
exports.Webhooks = Webhooks;
|
|
3617
|
+
//# sourceMappingURL=index.cjs.map
|