chargebee 2.40.0 → 3.0.0-beta.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.
Files changed (118) hide show
  1. package/CHANGELOG.md +10 -1
  2. package/LICENSE +1 -1
  3. package/README.md +90 -172
  4. package/cjs/RequestWrapper.js +81 -0
  5. package/cjs/asyncApiSupport.js +39 -0
  6. package/cjs/chargebee.cjs.js +13 -0
  7. package/cjs/chargebee.cjs.worker.js +9 -0
  8. package/cjs/chargebeeError.js +17 -0
  9. package/cjs/coreCommon.js +72 -0
  10. package/cjs/createChargebee.js +92 -0
  11. package/cjs/environment.js +18 -0
  12. package/cjs/filter.js +1 -0
  13. package/cjs/net/ClientInterface.js +40 -0
  14. package/cjs/net/FetchClient.js +86 -0
  15. package/cjs/net/NodeClient.js +61 -0
  16. package/cjs/package.json +1 -0
  17. package/cjs/resources/api_endpoints.js +1086 -0
  18. package/cjs/util.js +218 -0
  19. package/esm/RequestWrapper.js +77 -0
  20. package/esm/asyncApiSupport.js +35 -0
  21. package/esm/chargebee.esm.js +9 -0
  22. package/esm/chargebee.esm.worker.js +5 -0
  23. package/esm/chargebeeError.js +13 -0
  24. package/esm/coreCommon.js +67 -0
  25. package/esm/createChargebee.js +88 -0
  26. package/esm/environment.js +15 -0
  27. package/esm/filter.js +1 -0
  28. package/esm/net/ClientInterface.js +35 -0
  29. package/esm/net/FetchClient.js +81 -0
  30. package/esm/net/NodeClient.js +56 -0
  31. package/esm/package.json +1 -0
  32. package/esm/resources/api_endpoints.js +1083 -0
  33. package/esm/util.js +202 -0
  34. package/package.json +69 -38
  35. package/types/core.d.ts +558 -89
  36. package/types/index.d.ts +91 -54
  37. package/types/resources/Address.d.ts +57 -272
  38. package/types/resources/AdvanceInvoiceSchedule.d.ts +21 -94
  39. package/types/resources/AttachedItem.d.ts +91 -329
  40. package/types/resources/Attribute.d.ts +5 -5
  41. package/types/resources/BusinessEntity.d.ts +49 -69
  42. package/types/resources/BusinessEntityTransfer.d.ts +11 -17
  43. package/types/resources/Card.d.ts +146 -424
  44. package/types/resources/Comment.d.ts +72 -189
  45. package/types/resources/Contact.d.ts +12 -64
  46. package/types/resources/ContractTerm.d.ts +15 -96
  47. package/types/resources/Coupon.d.ts +282 -758
  48. package/types/resources/CouponCode.d.ts +56 -52
  49. package/types/resources/CouponSet.d.ts +92 -234
  50. package/types/resources/CreditNote.d.ts +588 -1758
  51. package/types/resources/CreditNoteEstimate.d.ts +131 -157
  52. package/types/resources/Currency.d.ts +75 -62
  53. package/types/resources/Customer.d.ts +892 -835
  54. package/types/resources/CustomerEntitlement.d.ts +36 -0
  55. package/types/resources/DifferentialPrice.d.ts +116 -314
  56. package/types/resources/Discount.d.ts +20 -125
  57. package/types/resources/Download.d.ts +6 -22
  58. package/types/resources/Entitlement.d.ts +51 -160
  59. package/types/resources/EntitlementOverride.d.ts +58 -139
  60. package/types/resources/Estimate.d.ts +1178 -527
  61. package/types/resources/Event.d.ts +67 -178
  62. package/types/resources/Export.d.ts +563 -723
  63. package/types/resources/Feature.d.ts +117 -433
  64. package/types/resources/GatewayErrorDetail.d.ts +16 -72
  65. package/types/resources/Gift.d.ts +265 -432
  66. package/types/resources/Hierarchy.d.ts +8 -36
  67. package/types/resources/HostedPage.d.ts +1017 -1153
  68. package/types/resources/ImpactedItem.d.ts +13 -50
  69. package/types/resources/ImpactedItemPrice.d.ts +13 -15
  70. package/types/resources/ImpactedSubscription.d.ts +13 -45
  71. package/types/resources/InAppSubscription.d.ts +93 -389
  72. package/types/resources/Installment.d.ts +35 -110
  73. package/types/resources/InstallmentConfig.d.ts +54 -155
  74. package/types/resources/InstallmentDetail.d.ts +19 -27
  75. package/types/resources/Invoice.d.ts +1574 -3157
  76. package/types/resources/InvoiceEstimate.d.ts +131 -161
  77. package/types/resources/Item.d.ts +133 -611
  78. package/types/resources/ItemEntitlement.d.ts +78 -215
  79. package/types/resources/ItemFamily.d.ts +69 -178
  80. package/types/resources/ItemPrice.d.ts +291 -1203
  81. package/types/resources/Metadata.d.ts +3 -5
  82. package/types/resources/Order.d.ts +538 -1471
  83. package/types/resources/PaymentIntent.d.ts +163 -347
  84. package/types/resources/PaymentReferenceNumber.d.ts +7 -29
  85. package/types/resources/PaymentSource.d.ts +476 -1272
  86. package/types/resources/PaymentVoucher.d.ts +87 -306
  87. package/types/resources/PortalSession.d.ts +71 -207
  88. package/types/resources/PriceVariant.d.ts +91 -279
  89. package/types/resources/PricingPageSession.d.ts +92 -41
  90. package/types/resources/PromotionalCredit.d.ts +90 -346
  91. package/types/resources/Purchase.d.ts +185 -315
  92. package/types/resources/Quote.d.ts +1406 -887
  93. package/types/resources/QuoteLineGroup.d.ts +125 -452
  94. package/types/resources/QuotedCharge.d.ts +45 -274
  95. package/types/resources/QuotedSubscription.d.ts +100 -488
  96. package/types/resources/Ramp.d.ts +233 -724
  97. package/types/resources/ResourceMigration.d.ts +25 -80
  98. package/types/resources/SiteMigrationDetail.d.ts +34 -112
  99. package/types/resources/Subscription.d.ts +2390 -4335
  100. package/types/resources/SubscriptionEntitlement.d.ts +59 -160
  101. package/types/resources/SubscriptionEstimate.d.ts +51 -75
  102. package/types/resources/TaxWithheld.d.ts +15 -40
  103. package/types/resources/ThirdPartyPaymentMethod.d.ts +7 -29
  104. package/types/resources/TimeMachine.d.ts +43 -97
  105. package/types/resources/Token.d.ts +15 -85
  106. package/types/resources/Transaction.d.ts +278 -900
  107. package/types/resources/UnbilledCharge.d.ts +189 -164
  108. package/types/resources/Usage.d.ts +89 -279
  109. package/types/resources/VirtualBankAccount.d.ts +103 -255
  110. package/types/resources/filter.d.ts +52 -0
  111. package/.github/ISSUE_TEMPLATE/bug_report.yml +0 -81
  112. package/.github/ISSUE_TEMPLATE/config.yml +0 -6
  113. package/.github/ISSUE_TEMPLATE/feature_request.yml +0 -34
  114. package/.github/PULL_REQUEST_TEMPLATE.md +0 -8
  115. package/lib/chargebee.js +0 -512
  116. package/lib/resources/api_endpoints.js +0 -2912
  117. package/types/resources/NonSubscription.d.ts +0 -30
  118. package/types/resources/Session.d.ts +0 -41
package/cjs/util.js ADDED
@@ -0,0 +1,218 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sleep = exports.isFunction = exports.isNotUndefinedNEmpty = exports.trim = exports.isObject = exports.isArray = exports.extend = void 0;
4
+ exports.callbackifyPromise = callbackifyPromise;
5
+ exports.getApiURL = getApiURL;
6
+ exports.serialize = serialize;
7
+ exports.encodeListParams = encodeListParams;
8
+ exports.getHost = getHost;
9
+ exports.encodeParams = encodeParams;
10
+ const extend = (deep, target, copy) => {
11
+ _extendsFn(deep, target, copy);
12
+ };
13
+ exports.extend = extend;
14
+ const _extendsFn = (...args) => {
15
+ {
16
+ let options, name, src, copy, copyIsArray, clone, target = args[0] || {}, i = 1, length = args.length, deep = false;
17
+ if (typeof target === 'boolean') {
18
+ deep = target;
19
+ target = args[1] || {};
20
+ i = 2;
21
+ }
22
+ if (typeof target !== 'object' && typeof target !== 'function') {
23
+ target = {};
24
+ }
25
+ if (length === i) {
26
+ target = this;
27
+ --i;
28
+ }
29
+ for (; i < length; i++) {
30
+ if ((options = args[i]) !== null) {
31
+ for (name in options) {
32
+ src = target[name];
33
+ copy = options[name];
34
+ if (target === copy) {
35
+ continue;
36
+ }
37
+ if (deep &&
38
+ copy &&
39
+ (typeof copy === 'object' || (copyIsArray = (0, exports.isArray)(copy)))) {
40
+ if (copyIsArray) {
41
+ copyIsArray = false;
42
+ clone = src && (0, exports.isArray)(src) ? src : [];
43
+ }
44
+ else {
45
+ clone = src && typeof src === 'object' ? src : {};
46
+ }
47
+ target[name] = (0, exports.extend)(deep, clone, copy);
48
+ }
49
+ else if (copy !== undefined) {
50
+ target[name] = copy;
51
+ }
52
+ }
53
+ }
54
+ }
55
+ return target;
56
+ }
57
+ };
58
+ const isArray = (obj) => {
59
+ return (Array.isArray(obj) ||
60
+ Object.prototype.toString.call(obj) === '[object Array]');
61
+ };
62
+ exports.isArray = isArray;
63
+ const isObject = (obj) => {
64
+ return Object.prototype.toString.call(obj) === '[object Object]';
65
+ };
66
+ exports.isObject = isObject;
67
+ // const indexOf = (array, item) => {
68
+ // if (![].indexOf(undefined)) {
69
+ // for (let i = 0; i < array.length; i++) {
70
+ // if (array[i] === item) {
71
+ // return i;
72
+ // }
73
+ // }
74
+ // return -1;
75
+ // } else {
76
+ // return array.indexOf(item);
77
+ // }
78
+ // }
79
+ const trim = (str) => {
80
+ return str !== '' ? str : str.replace(/^\s+|\s+$/g, '');
81
+ };
82
+ exports.trim = trim;
83
+ const isEmptyObject = (obj) => {
84
+ let name;
85
+ for (name in obj) {
86
+ return false;
87
+ }
88
+ return true;
89
+ };
90
+ const isNotUndefinedNEmpty = (obj) => {
91
+ if (typeof obj !== 'undefined' && !isEmptyObject(obj)) {
92
+ return true;
93
+ }
94
+ return false;
95
+ };
96
+ exports.isNotUndefinedNEmpty = isNotUndefinedNEmpty;
97
+ const isFunction = (obj) => {
98
+ return typeof obj === 'function';
99
+ };
100
+ exports.isFunction = isFunction;
101
+ const sleep = (milliseconds) => {
102
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
103
+ };
104
+ exports.sleep = sleep;
105
+ function callbackifyPromise(promise, callback) {
106
+ if (callback) {
107
+ return promise.then((res) => {
108
+ setTimeout(() => {
109
+ callback(null, res);
110
+ }, 0);
111
+ }, (err) => {
112
+ setTimeout(() => {
113
+ callback(err, null);
114
+ }, 0);
115
+ });
116
+ }
117
+ return promise;
118
+ }
119
+ function getApiURL(env, urlPrefix, urlSuffix, urlIdParam) {
120
+ if (typeof env.apiKey === 'undefined' || typeof env.site === 'undefined') {
121
+ throw new Error('Your site or api key is not configured.');
122
+ }
123
+ return (env.apiPath +
124
+ urlPrefix +
125
+ (urlIdParam !== null //
126
+ ? '/' + encodeURIComponent(urlIdParam).replace(/%2F/g, '/')
127
+ : '') +
128
+ (urlSuffix !== null ? urlSuffix : ''));
129
+ }
130
+ function serialize(paramObj) {
131
+ let key, value;
132
+ let array_ops = ['in', 'not_in', 'between'];
133
+ for (key in paramObj) {
134
+ value = paramObj[key];
135
+ if (typeof value === 'object' && (0, exports.isObject)(value)) {
136
+ let old_key = key;
137
+ let child_key;
138
+ for (child_key in value) {
139
+ key = key + '[' + child_key + ']';
140
+ paramObj[key] = value[child_key];
141
+ if (array_ops.includes(child_key)) {
142
+ paramObj[key] = JSON.stringify(value[child_key]);
143
+ }
144
+ }
145
+ delete paramObj[old_key];
146
+ serialize(paramObj);
147
+ }
148
+ else {
149
+ paramObj[key] = value;
150
+ }
151
+ }
152
+ return paramObj;
153
+ }
154
+ function encodeListParams(paramObj) {
155
+ let key, value;
156
+ for (key in paramObj) {
157
+ value = paramObj[key];
158
+ if (typeof value !== 'undefined' && value !== null && (0, exports.isArray)(value)) {
159
+ paramObj[key] = JSON.stringify(value);
160
+ }
161
+ else {
162
+ paramObj[key] = value;
163
+ }
164
+ }
165
+ return encodeParams(paramObj);
166
+ }
167
+ function getHost(env) {
168
+ return env.site + env.hostSuffix;
169
+ }
170
+ function encodeParams(paramObj, serialized, scope, index) {
171
+ let key, value;
172
+ if (typeof serialized === 'undefined' || serialized === null) {
173
+ serialized = [];
174
+ }
175
+ for (key in paramObj) {
176
+ value = paramObj[key];
177
+ if (scope) {
178
+ key = '' + scope + '[' + key + ']';
179
+ }
180
+ if (typeof index !== 'undefined' && index !== null) {
181
+ key = key + '[' + index + ']';
182
+ }
183
+ if ((0, exports.isArray)(value)) {
184
+ for (let arrIdx = 0; arrIdx < value.length; arrIdx++) {
185
+ if (typeof value[arrIdx] === 'object' || (0, exports.isArray)(value[arrIdx])) {
186
+ encodeParams(value[arrIdx], serialized, key, arrIdx);
187
+ }
188
+ else {
189
+ if (typeof value[arrIdx] !== 'undefined') {
190
+ serialized.push(encodeURIComponent(key + '[' + arrIdx + ']') +
191
+ '=' +
192
+ encodeURIComponent((0, exports.trim)(value[arrIdx]) !== '' ? value[arrIdx] : ''));
193
+ }
194
+ }
195
+ }
196
+ }
197
+ else if (key === 'meta_data') {
198
+ let attrVal = '';
199
+ if (value !== null) {
200
+ attrVal = encodeURIComponent(Object.prototype.toString.call(value) === '[object String]'
201
+ ? (0, exports.trim)(value)
202
+ : JSON.stringify(value));
203
+ }
204
+ serialized.push(encodeURIComponent(key) + '=' + attrVal);
205
+ }
206
+ else if (typeof value === 'object' && !(0, exports.isArray)(value)) {
207
+ encodeParams(value, serialized, key);
208
+ }
209
+ else {
210
+ if (typeof value !== 'undefined') {
211
+ serialized.push(encodeURIComponent(key) +
212
+ '=' +
213
+ encodeURIComponent((0, exports.trim)(value) !== '' ? value : ''));
214
+ }
215
+ }
216
+ }
217
+ return serialized.join('&').replace(/%20/g, '+');
218
+ }
@@ -0,0 +1,77 @@
1
+ import { extend, callbackifyPromise, getApiURL, encodeListParams, encodeParams, serialize, getHost, } from './util.js';
2
+ import { handleResponse } from './coreCommon.js';
3
+ import { Buffer } from 'node:buffer';
4
+ const IDEMPOTENCY_HEADER = 'chargebee-idempotency-key';
5
+ export class RequestWrapper {
6
+ constructor(args, apiCall, envArg) {
7
+ this.getRequest = () => {
8
+ return this.request();
9
+ };
10
+ this.args = args;
11
+ this.apiCall = apiCall;
12
+ this.envArg = envArg;
13
+ this.httpHeaders = {};
14
+ if (this.apiCall.hasIdInUrl) {
15
+ RequestWrapper._validateIdParam(this.args[0]);
16
+ }
17
+ }
18
+ static _validateIdParam(idParam) {
19
+ if (!idParam || typeof idParam !== 'string' || idParam.trim().length < 1) {
20
+ throw new Error('the required id parameter missing or wrong');
21
+ }
22
+ return idParam;
23
+ }
24
+ request() {
25
+ let env = {};
26
+ extend(true, env, this.envArg);
27
+ const urlIdParam = this.apiCall.hasIdInUrl ? this.args[0] : null;
28
+ let params = this.apiCall.hasIdInUrl
29
+ ? this.args[1]
30
+ : this.args[0];
31
+ let headers = this.apiCall.hasIdInUrl ? this.args[2] : this.args[1];
32
+ Object.assign(this.httpHeaders, headers);
33
+ const promise = new Promise(async (resolve, reject) => {
34
+ function callBackWrapper(err, response) {
35
+ if (err) {
36
+ reject(err);
37
+ }
38
+ else {
39
+ resolve(response);
40
+ }
41
+ }
42
+ let path = getApiURL(env, this.apiCall.urlPrefix, this.apiCall.urlSuffix, urlIdParam);
43
+ if (typeof params === 'undefined' || params === null) {
44
+ params = {};
45
+ }
46
+ if (this.apiCall.httpMethod === 'GET') {
47
+ params = serialize(params);
48
+ let queryParam = this.apiCall.isListReq
49
+ ? encodeListParams(params)
50
+ : encodeParams(params);
51
+ path += '?' + queryParam;
52
+ params = {};
53
+ }
54
+ let data = encodeParams(params);
55
+ extend(true, this.httpHeaders, {
56
+ Authorization: 'Basic ' + Buffer.from(env.apiKey + ':').toString('base64'),
57
+ Accept: 'application/json',
58
+ 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
59
+ 'Content-Length': data.length,
60
+ 'User-Agent': 'Chargebee-NodeJs-Client ' + env.clientVersion,
61
+ 'Lang-Version': typeof process === 'undefined' ? '' : process.version,
62
+ });
63
+ const resp = await this.envArg.httpClient.makeApiRequest({
64
+ host: getHost(env),
65
+ port: env.port,
66
+ path,
67
+ method: this.apiCall.httpMethod,
68
+ protocol: env.protocol,
69
+ headers: this.httpHeaders,
70
+ data: data,
71
+ timeout: env.timeout,
72
+ });
73
+ handleResponse(callBackWrapper, resp);
74
+ });
75
+ return callbackifyPromise(promise);
76
+ }
77
+ }
@@ -0,0 +1,35 @@
1
+ import { isFunction, extend, callbackifyPromise } from './util.js';
2
+ export const waitForProcessToComplete = (retrieveHandling, env) => {
3
+ if (typeof retrieveHandling == 'undefined' || !isFunction(retrieveHandling)) {
4
+ throw new Error('The handling parameter should be a method.');
5
+ }
6
+ const DummyRequestWrapper = function () {
7
+ this.request = _request;
8
+ };
9
+ const _request = function (callBack, envOptions) {
10
+ const jsonConstructor = {}.constructor;
11
+ if (typeof envOptions !== 'undefined') {
12
+ extend(true, env, envOptions);
13
+ }
14
+ else if (typeof callBack !== 'undefined' &&
15
+ callBack.constructor === jsonConstructor &&
16
+ !isFunction(callBack)) {
17
+ extend(true, env, callBack);
18
+ callBack = undefined;
19
+ }
20
+ if (typeof callBack !== 'undefined' && !isFunction(callBack)) {
21
+ throw new Error('The callback parameter passed is incorrect.');
22
+ }
23
+ const promise = new Promise((resolve, reject) => {
24
+ try {
25
+ const result = retrieveHandling();
26
+ resolve(result);
27
+ }
28
+ catch (err) {
29
+ reject(err);
30
+ }
31
+ });
32
+ return callbackifyPromise(promise, callBack);
33
+ };
34
+ return new DummyRequestWrapper();
35
+ };
@@ -0,0 +1,9 @@
1
+ import { CreateChargebee } from './createChargebee.js';
2
+ import { NodeHttpClient } from './net/NodeClient.js';
3
+ import { FetchHttpClient } from './net/FetchClient.js';
4
+ //@ts-ignore
5
+ const httpClient = globalThis.fetch
6
+ ? new NodeHttpClient()
7
+ : new FetchHttpClient();
8
+ const Chargebee = CreateChargebee(httpClient);
9
+ export default Chargebee;
@@ -0,0 +1,5 @@
1
+ import { CreateChargebee } from './createChargebee.js';
2
+ import { FetchHttpClient } from './net/FetchClient.js';
3
+ const httpClient = new FetchHttpClient();
4
+ const Chargebee = CreateChargebee(httpClient);
5
+ export default Chargebee;
@@ -0,0 +1,13 @@
1
+ export class ChargebeeError extends Error {
2
+ constructor(rawError, headers) {
3
+ super(rawError.message);
4
+ this.message = rawError.message;
5
+ this.type = rawError.type;
6
+ this.api_error_code = rawError.api_error_code;
7
+ this.http_status_code = rawError.http_status_code;
8
+ this.http_code = rawError.http_code;
9
+ this.error_code = rawError.error_code;
10
+ this.detail = rawError === null || rawError === void 0 ? void 0 : rawError.detail;
11
+ this.headers = headers;
12
+ }
13
+ }
@@ -0,0 +1,67 @@
1
+ import { ChargebeeError } from './chargebeeError.js';
2
+ import { isNotUndefinedNEmpty } from './util.js';
3
+ const IDEMPOTENCY_REPLAYED_HEADER = 'chargebee-idempotency-replayed';
4
+ export function throwError(callBack, rawError, headers) {
5
+ const error = new ChargebeeError({
6
+ message: rawError.message,
7
+ type: rawError.type,
8
+ api_error_code: rawError.errorCode,
9
+ http_status_code: rawError.httpStatusCode,
10
+ http_code: rawError.httpStatusCode,
11
+ error_code: rawError.errorCode,
12
+ }, headers);
13
+ if (rawError['detail'] !== 'undefined') {
14
+ error['detail'] = rawError['detail'];
15
+ }
16
+ return callBack(error, null);
17
+ }
18
+ export const handleResponse = async (callback, response) => {
19
+ try {
20
+ const res = await response.toJson();
21
+ const status = response.getStatusCode();
22
+ const headers = response.getHeaders();
23
+ if (status && (status < 200 || status > 299)) {
24
+ res.http_status_code = status;
25
+ res.headers = headers;
26
+ return callback(res, null);
27
+ }
28
+ else {
29
+ res.isIdempotencyReplayed = false;
30
+ if (isNotUndefinedNEmpty(headers[IDEMPOTENCY_REPLAYED_HEADER])) {
31
+ res.isIdempotencyReplayed = headers[IDEMPOTENCY_REPLAYED_HEADER];
32
+ }
33
+ res.headers = headers;
34
+ return callback(null, res);
35
+ }
36
+ }
37
+ catch (error) {
38
+ const status = response.getStatusCode();
39
+ const headers = response.getHeaders();
40
+ switch (status) {
41
+ case 503:
42
+ return throwError(callback, {
43
+ type: 'internal_temporary_error',
44
+ httpStatusCode: 503,
45
+ errorCode: 'internal_temporary_error',
46
+ message: 'Sorry, the server is currently unable to handle the request due to a temporary overload or scheduled maintenance. Please retry after sometime.',
47
+ detail: error,
48
+ }, headers);
49
+ case 504:
50
+ return throwError(callback, {
51
+ type: 'gateway_timeout',
52
+ httpStatusCode: 504,
53
+ errorCode: 'gateway_timeout',
54
+ message: 'The server did not receive a timely response from an upstream server, request aborted. If this problem persists, contact us at support@chargebee.com.',
55
+ detail: error,
56
+ }, headers);
57
+ default:
58
+ return throwError(callback, {
59
+ type: 'internal_error',
60
+ httpStatusCode: 500,
61
+ errorCode: 'internal_error',
62
+ message: 'Sorry, something went wrong when trying to process the request. If this problem persists, contact us at support@chargebee.com.',
63
+ detail: error,
64
+ }, headers);
65
+ }
66
+ }
67
+ };
@@ -0,0 +1,88 @@
1
+ import { RequestWrapper } from './RequestWrapper.js';
2
+ import { Environment } from './environment.js';
3
+ import { Endpoints } from './resources/api_endpoints.js';
4
+ import { extend, sleep } from './util.js';
5
+ import { waitForProcessToComplete } from './asyncApiSupport.js';
6
+ export const CreateChargebee = (httpClient) => {
7
+ const Chargebee = function (conf) {
8
+ this._env = Object.assign({}, Environment);
9
+ extend(true, this._env, conf);
10
+ // @ts-ignore
11
+ this._env.httpClient = httpClient;
12
+ this._buildResources();
13
+ this._endpoints = Endpoints;
14
+ };
15
+ Chargebee.prototype = {
16
+ _createApiFunc(apiCall, env) {
17
+ return async function () {
18
+ const rw = new RequestWrapper(arguments, apiCall, env);
19
+ return rw.getRequest();
20
+ };
21
+ },
22
+ _waitForExport(exportId) {
23
+ let count = 0;
24
+ const retrieve = async () => {
25
+ while (count++ < 30) {
26
+ const result = await this.export.retrieve(exportId).request();
27
+ const exportObj = result.export;
28
+ if (exportObj.status === 'completed') {
29
+ return result;
30
+ }
31
+ else if (exportObj.status === 'in_process') {
32
+ await sleep(this._env.exportWaitInMillis);
33
+ continue;
34
+ }
35
+ else {
36
+ return result;
37
+ }
38
+ }
39
+ throw new Error('Export is taking too long');
40
+ };
41
+ return waitForProcessToComplete(retrieve);
42
+ },
43
+ _timeMachineWait() {
44
+ let count = 0;
45
+ const retrieve = async () => {
46
+ while (count++ < 30) {
47
+ const result = await this.time_machine.retrieve('delorean').request();
48
+ const time_machine = result.time_machine;
49
+ if (time_machine.time_travel_status === 'succeeded') {
50
+ return result;
51
+ }
52
+ else if (time_machine.time_travel_status === 'in_progress') {
53
+ await sleep(this._env.timemachineWaitInMillis);
54
+ continue;
55
+ }
56
+ else {
57
+ return result;
58
+ }
59
+ }
60
+ throw new Error('The time travel is taking too much time');
61
+ };
62
+ return waitForProcessToComplete(retrieve);
63
+ },
64
+ _buildResources() {
65
+ for (const res in Endpoints) {
66
+ this[res] = {};
67
+ // @ts-ignore
68
+ const apiCalls = Endpoints[res];
69
+ for (let apiIdx = 0; apiIdx < apiCalls.length; apiIdx++) {
70
+ const metaArr = apiCalls[apiIdx];
71
+ const apiCall = {
72
+ methodName: metaArr[0],
73
+ httpMethod: metaArr[1],
74
+ urlPrefix: metaArr[2],
75
+ urlSuffix: metaArr[3],
76
+ hasIdInUrl: metaArr[4],
77
+ isListReq: metaArr[0] === 'list',
78
+ };
79
+ this[res][apiCall.methodName] = this._createApiFunc(apiCall, this._env);
80
+ }
81
+ }
82
+ this.export.wait_for_export_completion = this._waitForExport.bind(this);
83
+ this.timeMachine.wait_for_time_travel_completion =
84
+ this._timeMachineWait.bind(this);
85
+ },
86
+ };
87
+ return Chargebee;
88
+ };
@@ -0,0 +1,15 @@
1
+ const DEFAULT_PROTOCOL = 'https';
2
+ const DEFAULT_TIME_OUT = 80000;
3
+ const DEFAULT_PORT = 443;
4
+ const DEFAULT_TIME_MACHINE_WAIT = 3000;
5
+ const DEFAULT_EXPORT_WAIT = 3000;
6
+ export const Environment = {
7
+ protocol: DEFAULT_PROTOCOL,
8
+ hostSuffix: '.chargebee.com',
9
+ apiPath: '/api/v2',
10
+ timeout: DEFAULT_TIME_OUT,
11
+ clientVersion: 'v3.0.0-beta.1',
12
+ port: DEFAULT_PORT,
13
+ timemachineWaitInMillis: DEFAULT_TIME_MACHINE_WAIT,
14
+ exportWaitInMillis: DEFAULT_EXPORT_WAIT,
15
+ };
package/esm/filter.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";
@@ -0,0 +1,35 @@
1
+ import { ChargebeeError } from '../chargebeeError.js';
2
+ export class HttpClient {
3
+ async makeApiRequest(props) {
4
+ throw new Error('makeApiRequest is not implemented');
5
+ }
6
+ static timeOutError() {
7
+ const error = new ChargebeeError({
8
+ message: 'io_error',
9
+ type: 'timeout',
10
+ api_error_code: 'request aborted due to timeout.',
11
+ http_status_code: 504,
12
+ http_code: 504,
13
+ error_code: 'request aborted due to timeout.',
14
+ }, null);
15
+ return error;
16
+ }
17
+ }
18
+ export class HttpClientResponse {
19
+ constructor(statusCode, headers) {
20
+ this._statusCode = statusCode;
21
+ this._headers = headers;
22
+ }
23
+ getStatusCode() {
24
+ return this._statusCode;
25
+ }
26
+ getHeaders() {
27
+ return this._headers;
28
+ }
29
+ getRawResponse() {
30
+ throw new Error('getRawResponse not implemented.');
31
+ }
32
+ toJson() {
33
+ throw new Error('toJSON not implemented.');
34
+ }
35
+ }
@@ -0,0 +1,81 @@
1
+ import { HttpClient, HttpClientResponse, } from './ClientInterface.js';
2
+ export class FetchHttpClient extends HttpClient {
3
+ async makeApiRequest(props) {
4
+ const headers = this._createHeaders(props.headers);
5
+ let url = `${props.protocol}://${props.host}:${props.port}${props.path}`;
6
+ let fetchOptions = {
7
+ method: props.method,
8
+ headers: headers,
9
+ body: props.data ? props.data : undefined,
10
+ };
11
+ const response = globalThis.AbortController
12
+ ? await this.fetchWithAbortTimeout(url, fetchOptions, props.timeout)
13
+ : await this.fetchWithTimeout(url, fetchOptions, props.timeout);
14
+ return new FetchHttpClientResponse(response);
15
+ }
16
+ _createHeaders(httpHeaders) {
17
+ const headers = new Headers();
18
+ Object.entries(httpHeaders).forEach(([key, value]) => {
19
+ headers.append(key, String(value));
20
+ });
21
+ return headers;
22
+ }
23
+ async fetchWithTimeout(url, fetchOptions, timeout) {
24
+ let pendingTimeoutId;
25
+ const timeoutPromise = new Promise((_, reject) => {
26
+ pendingTimeoutId = setTimeout(() => {
27
+ pendingTimeoutId = null;
28
+ reject(HttpClient.timeOutError());
29
+ }, timeout);
30
+ });
31
+ const fetchPromise = fetch(url, fetchOptions);
32
+ return Promise.race([fetchPromise, timeoutPromise]).finally(() => {
33
+ if (pendingTimeoutId) {
34
+ clearTimeout(pendingTimeoutId);
35
+ }
36
+ });
37
+ }
38
+ async fetchWithAbortTimeout(url, fetchOptions, timeout) {
39
+ const abort = new AbortController();
40
+ let timeoutId = setTimeout(() => {
41
+ timeoutId = null;
42
+ abort.abort(HttpClient.timeOutError());
43
+ }, timeout);
44
+ const fetchPromise = fetch(url, Object.assign(Object.assign({}, fetchOptions), { signal: abort.signal }));
45
+ fetchPromise.finally(() => {
46
+ if (timeoutId) {
47
+ clearTimeout(timeoutId);
48
+ }
49
+ });
50
+ return fetchPromise.catch((err) => {
51
+ if (err.name === 'AbortError') {
52
+ throw HttpClient.timeOutError();
53
+ }
54
+ else {
55
+ throw err;
56
+ }
57
+ });
58
+ }
59
+ }
60
+ export class FetchHttpClientResponse extends HttpClientResponse {
61
+ constructor(response) {
62
+ super(response.status, FetchHttpClientResponse._transformHeadersToObject(response.headers));
63
+ this._res = response;
64
+ }
65
+ getRawResponse() {
66
+ return this._res;
67
+ }
68
+ toJson() {
69
+ return this._res.json();
70
+ }
71
+ static _transformHeadersToObject(headers) {
72
+ const headersObj = {};
73
+ for (const entry of headers) {
74
+ if (!Array.isArray(entry) || entry.length != 2) {
75
+ throw new Error('Headers should be an iterable object.');
76
+ }
77
+ headersObj[entry[0]] = entry[1];
78
+ }
79
+ return headersObj;
80
+ }
81
+ }