@fajarmaulana/komerce-lp-helper 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/utils/api.js CHANGED
@@ -1,491 +1,318 @@
1
- var __extends = (this && this.__extends) || (function () {
2
- var extendStatics = function (d, b) {
3
- extendStatics = Object.setPrototypeOf ||
4
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
5
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
6
- return extendStatics(d, b);
7
- };
8
- return function (d, b) {
9
- if (typeof b !== "function" && b !== null)
10
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
11
- extendStatics(d, b);
12
- function __() { this.constructor = d; }
13
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14
- };
15
- })();
16
- var __assign = (this && this.__assign) || function () {
17
- __assign = Object.assign || function(t) {
18
- for (var s, i = 1, n = arguments.length; i < n; i++) {
19
- s = arguments[i];
20
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
21
- t[p] = s[p];
22
- }
23
- return t;
24
- };
25
- return __assign.apply(this, arguments);
26
- };
27
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
28
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
29
- return new (P || (P = Promise))(function (resolve, reject) {
30
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
31
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
32
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
33
- step((generator = generator.apply(thisArg, _arguments || [])).next());
34
- });
35
- };
36
- var __generator = (this && this.__generator) || function (thisArg, body) {
37
- 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);
38
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
39
- function verb(n) { return function (v) { return step([n, v]); }; }
40
- function step(op) {
41
- if (f) throw new TypeError("Generator is already executing.");
42
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
43
- 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;
44
- if (y = 0, t) op = [op[0] & 2, t.value];
45
- switch (op[0]) {
46
- case 0: case 1: t = op; break;
47
- case 4: _.label++; return { value: op[1], done: false };
48
- case 5: _.label++; y = op[1]; op = [0]; continue;
49
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
50
- default:
51
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
52
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
53
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
54
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
55
- if (t[2]) _.ops.pop();
56
- _.trys.pop(); continue;
57
- }
58
- op = body.call(thisArg, _);
59
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
60
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
61
- }
62
- };
63
- var __read = (this && this.__read) || function (o, n) {
64
- var m = typeof Symbol === "function" && o[Symbol.iterator];
65
- if (!m) return o;
66
- var i = m.call(o), r, ar = [], e;
67
- try {
68
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
69
- }
70
- catch (error) { e = { error: error }; }
71
- finally {
72
- try {
73
- if (r && !r.done && (m = i["return"])) m.call(i);
74
- }
75
- finally { if (e) throw e.error; }
76
- }
77
- return ar;
78
- };
79
- export var buildURL = function (url, params) {
1
+ export const buildURL = (url, params) => {
80
2
  if (!params)
81
3
  return url;
82
- var queryString = Object.entries(params)
83
- .map(function (_a) {
84
- var _b = __read(_a, 2), key = _b[0], value = _b[1];
4
+ const queryString = Object.entries(params)
5
+ .map(([key, value]) => {
85
6
  if (Array.isArray(value)) {
86
- var joined = value.map(function (v) { return encodeURIComponent(v); }).join(',');
87
- return "".concat(encodeURIComponent(key), "=").concat(joined);
7
+ const joined = value.map(v => encodeURIComponent(v)).join(',');
8
+ return `${encodeURIComponent(key)}=${joined}`;
88
9
  }
89
- return "".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(value));
10
+ return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
90
11
  })
91
12
  .join('&');
92
- return url.includes('?') ? "".concat(url, "&").concat(queryString) : "".concat(url, "?").concat(queryString);
13
+ return url.includes('?') ? `${url}&${queryString}` : `${url}?${queryString}`;
93
14
  };
94
- var ApiMeta = /** @class */ (function (_super) {
95
- __extends(ApiMeta, _super);
96
- function ApiMeta(code, message, status) {
97
- var _this = _super.call(this, message) || this;
98
- _this.code = code;
99
- _this.status = status;
100
- return _this;
15
+ export class ApiMeta extends Error {
16
+ constructor(code, message, status) {
17
+ super(message);
18
+ this.code = code;
19
+ this.status = status;
101
20
  }
102
- return ApiMeta;
103
- }(Error));
104
- export { ApiMeta };
105
- var ApiInstance = /** @class */ (function () {
106
- function ApiInstance(options) {
107
- if (options === void 0) { options = {}; }
21
+ }
22
+ export class ApiInstance {
23
+ constructor(options = {}) {
108
24
  this.interceptors = {};
109
25
  this.baseURL = options.baseURL || '';
110
26
  this.defaultHeaders = options.headers || {};
111
- this.source = "komcards-".concat(options.source || 'default');
27
+ this.source = `komerce-${options.source || 'default'}`;
112
28
  this.cache = new Map();
113
29
  this.maxCacheSize = options.maxCacheSize || 100;
114
30
  this.cacheAccessOrder = [];
115
31
  }
116
- ApiInstance.prototype.setInterceptors = function (interceptors) {
32
+ setInterceptors(interceptors) {
117
33
  this.interceptors = interceptors;
118
- };
119
- ApiInstance.prototype.hash = function (str) {
120
- var hash = 0;
121
- for (var i = 0; i < str.length; i++) {
122
- var char = str.charCodeAt(i);
34
+ }
35
+ hash(str) {
36
+ let hash = 0;
37
+ for (let i = 0; i < str.length; i++) {
38
+ const char = str.charCodeAt(i);
123
39
  hash = (hash << 5) - hash + char;
124
40
  hash = hash & hash;
125
41
  }
126
42
  return hash.toString(36);
127
- };
128
- ApiInstance.prototype.buildcacheKey = function (config) {
129
- var keyObj = {
43
+ }
44
+ buildcacheKey(config) {
45
+ const keyObj = {
130
46
  url: config.url,
131
47
  params: config.params,
132
48
  };
133
- var keyString = JSON.stringify(keyObj);
49
+ const keyString = JSON.stringify(keyObj);
134
50
  if (keyString.length > 200) {
135
- return "".concat(this.source, ":").concat(this.hash(keyString));
51
+ return `${this.source}:${this.hash(keyString)}`;
136
52
  }
137
- return "".concat(this.source, ":").concat(keyString);
138
- };
139
- ApiInstance.prototype.fetchWithXHR = function (input, init, onUpload, onDownload) {
140
- return __awaiter(this, void 0, void 0, function () {
141
- return __generator(this, function (_a) {
142
- return [2 /*return*/, new Promise(function (resolve, reject) {
143
- var xhr = new XMLHttpRequest();
144
- var method = (init.method || 'GET').toUpperCase();
145
- xhr.open(method, input);
146
- if (init.headers) {
147
- var headers = new Headers(init.headers);
148
- headers.forEach(function (value, key) {
149
- xhr.setRequestHeader(key, value);
150
- });
151
- }
152
- if (onUpload && xhr.upload) {
153
- xhr.upload.addEventListener('progress', function (e) {
154
- var total = e.lengthComputable ? e.total : 0;
155
- var percentage = e.lengthComputable ? Math.round((e.loaded / e.total) * 100) : 0;
156
- onUpload({
157
- loaded: e.loaded,
158
- total: total,
159
- percentage: percentage,
160
- });
161
- });
162
- }
163
- if (onDownload) {
164
- xhr.responseType = 'blob';
165
- xhr.addEventListener('progress', function (e) {
166
- var total = e.lengthComputable ? e.total : 0;
167
- var percentage = e.lengthComputable ? Math.round((e.loaded / e.total) * 100) : 0;
168
- onDownload({
169
- loaded: e.loaded,
170
- total: total,
171
- percentage: percentage,
172
- });
173
- });
174
- }
175
- if (init.signal) {
176
- init.signal.addEventListener('abort', function () {
177
- xhr.abort();
178
- reject(new DOMException('The operation was aborted.', 'AbortError'));
179
- });
180
- }
181
- xhr.onload = function () {
182
- var headers = new Headers();
183
- xhr
184
- .getAllResponseHeaders()
185
- .split('\r\n')
186
- .forEach(function (line) {
187
- var parts = line.split(': ');
188
- if (parts.length === 2) {
189
- headers.append(parts[0], parts[1]);
190
- }
191
- });
192
- var response = new Response(xhr.response, {
193
- status: xhr.status,
194
- statusText: xhr.statusText,
195
- headers: headers,
196
- });
197
- resolve(response);
198
- };
199
- xhr.onerror = function () { return reject(new TypeError('Network request failed')); };
200
- xhr.ontimeout = function () { return reject(new TypeError('Network request timeout')); };
201
- xhr.send(init.body);
202
- })];
203
- });
53
+ return `${this.source}:${keyString}`;
54
+ }
55
+ async fetchWithXHR(input, init, onUpload, onDownload) {
56
+ return new Promise((resolve, reject) => {
57
+ const xhr = new XMLHttpRequest();
58
+ const method = (init.method || 'GET').toUpperCase();
59
+ xhr.open(method, input);
60
+ if (init.headers) {
61
+ const headers = new Headers(init.headers);
62
+ headers.forEach((value, key) => {
63
+ xhr.setRequestHeader(key, value);
64
+ });
65
+ }
66
+ if (onUpload && xhr.upload) {
67
+ xhr.upload.addEventListener('progress', e => {
68
+ const total = e.lengthComputable ? e.total : 0;
69
+ const percentage = e.lengthComputable ? Math.round((e.loaded / e.total) * 100) : 0;
70
+ onUpload({
71
+ loaded: e.loaded,
72
+ total,
73
+ percentage,
74
+ });
75
+ });
76
+ }
77
+ if (onDownload) {
78
+ xhr.responseType = 'blob';
79
+ xhr.addEventListener('progress', e => {
80
+ const total = e.lengthComputable ? e.total : 0;
81
+ const percentage = e.lengthComputable ? Math.round((e.loaded / e.total) * 100) : 0;
82
+ onDownload({
83
+ loaded: e.loaded,
84
+ total,
85
+ percentage,
86
+ });
87
+ });
88
+ }
89
+ if (init.signal) {
90
+ init.signal.addEventListener('abort', () => {
91
+ xhr.abort();
92
+ reject(new DOMException('The operation was aborted.', 'AbortError'));
93
+ });
94
+ }
95
+ xhr.onload = () => {
96
+ const headers = new Headers();
97
+ xhr
98
+ .getAllResponseHeaders()
99
+ .split('\r\n')
100
+ .forEach(line => {
101
+ const parts = line.split(': ');
102
+ if (parts.length === 2) {
103
+ headers.append(parts[0], parts[1]);
104
+ }
105
+ });
106
+ const response = new Response(xhr.response, {
107
+ status: xhr.status,
108
+ statusText: xhr.statusText,
109
+ headers,
110
+ });
111
+ resolve(response);
112
+ };
113
+ xhr.onerror = () => reject(new TypeError('Network request failed'));
114
+ xhr.ontimeout = () => reject(new TypeError('Network request timeout'));
115
+ xhr.send(init.body);
204
116
  });
205
- };
206
- ApiInstance.prototype.fetchWithRetry = function (input, init, retry, signal, onUpload, onDownload) {
207
- return __awaiter(this, void 0, void 0, function () {
208
- var attempt, lastErr, _loop_1, this_1, state_1;
209
- return __generator(this, function (_a) {
210
- switch (_a.label) {
211
- case 0:
212
- attempt = 0;
213
- _loop_1 = function () {
214
- var res, clonedRes, error, code, message, status_1, err_1, delay_1;
215
- return __generator(this, function (_b) {
216
- switch (_b.label) {
217
- case 0:
218
- _b.trys.push([0, 7, , 9]);
219
- res = void 0;
220
- if (!(onUpload || onDownload)) return [3 /*break*/, 2];
221
- return [4 /*yield*/, this_1.fetchWithXHR(input, __assign(__assign({}, init), { signal: signal }), onUpload, onDownload)];
222
- case 1:
223
- res = _b.sent();
224
- return [3 /*break*/, 4];
225
- case 2: return [4 /*yield*/, fetch(input, __assign(__assign({}, init), { signal: signal }))];
226
- case 3:
227
- res = _b.sent();
228
- _b.label = 4;
229
- case 4:
230
- if (!!res.ok) return [3 /*break*/, 6];
231
- clonedRes = res.clone();
232
- return [4 /*yield*/, clonedRes.json()];
233
- case 5:
234
- error = _b.sent();
235
- if (error.meta || error.status) {
236
- code = error.code || error.meta.code || res.status;
237
- message = error.message || error.meta.message || JSON.stringify(error);
238
- status_1 = error.status || error.meta.status || res.statusText;
239
- throw new ApiMeta(code, message, status_1);
240
- }
241
- throw error;
242
- case 6: return [2 /*return*/, { value: res }];
243
- case 7:
244
- err_1 = _b.sent();
245
- if (err_1 instanceof Error && err_1.name === 'AbortError') {
246
- throw err_1;
247
- }
248
- lastErr = err_1;
249
- if (attempt === retry)
250
- throw lastErr;
251
- delay_1 = Math.pow(2, attempt) * 200;
252
- return [4 /*yield*/, new Promise(function (r) { return setTimeout(r, delay_1); })];
253
- case 8:
254
- _b.sent();
255
- attempt++;
256
- return [3 /*break*/, 9];
257
- case 9: return [2 /*return*/];
258
- }
259
- });
260
- };
261
- this_1 = this;
262
- _a.label = 1;
263
- case 1:
264
- if (!(attempt <= retry)) return [3 /*break*/, 3];
265
- return [5 /*yield**/, _loop_1()];
266
- case 2:
267
- state_1 = _a.sent();
268
- if (typeof state_1 === "object")
269
- return [2 /*return*/, state_1.value];
270
- return [3 /*break*/, 1];
271
- case 3: throw lastErr;
117
+ }
118
+ async fetchWithRetry(input, init, retry, signal, onUpload, onDownload) {
119
+ let attempt = 0;
120
+ let lastErr;
121
+ while (attempt <= retry) {
122
+ try {
123
+ let res;
124
+ if (onUpload || onDownload) {
125
+ res = await this.fetchWithXHR(input, { ...init, signal }, onUpload, onDownload);
272
126
  }
273
- });
274
- });
275
- };
276
- ApiInstance.prototype.handleInterceptors = function (config) {
277
- return __awaiter(this, void 0, void 0, function () {
278
- return __generator(this, function (_a) {
279
- switch (_a.label) {
280
- case 0:
281
- if (!this.interceptors.request) return [3 /*break*/, 2];
282
- return [4 /*yield*/, this.interceptors.request(config)];
283
- case 1: return [2 /*return*/, _a.sent()];
284
- case 2: return [2 /*return*/, config];
127
+ else {
128
+ res = await fetch(input, { ...init, signal });
285
129
  }
286
- });
287
- });
288
- };
289
- ApiInstance.prototype.handleResponse = function (response) {
290
- return __awaiter(this, void 0, void 0, function () {
291
- return __generator(this, function (_a) {
292
- switch (_a.label) {
293
- case 0:
294
- if (!this.interceptors.response) return [3 /*break*/, 2];
295
- return [4 /*yield*/, this.interceptors.response(response)];
296
- case 1: return [2 /*return*/, _a.sent()];
297
- case 2: return [2 /*return*/, response];
130
+ if (!res.ok) {
131
+ const clonedRes = res.clone();
132
+ const error = await clonedRes.json();
133
+ if (error.meta || error.status) {
134
+ const code = error.code || error.meta.code || res.status;
135
+ const message = error.message || error.meta.message || JSON.stringify(error);
136
+ const status = error.status || error.meta.status || res.statusText;
137
+ throw new ApiMeta(code, message, status);
138
+ }
139
+ throw error;
298
140
  }
299
- });
300
- });
301
- };
302
- ApiInstance.prototype.handleError = function (error) {
303
- return __awaiter(this, void 0, void 0, function () {
304
- return __generator(this, function (_a) {
305
- switch (_a.label) {
306
- case 0:
307
- if (!this.interceptors.error) return [3 /*break*/, 2];
308
- return [4 /*yield*/, this.interceptors.error(error)];
309
- case 1: return [2 /*return*/, _a.sent()];
310
- case 2: throw error;
141
+ return res;
142
+ }
143
+ catch (err) {
144
+ if (err instanceof Error && err.name === 'AbortError') {
145
+ throw err;
311
146
  }
312
- });
313
- });
314
- };
315
- ApiInstance.prototype.getCacheEntry = function (key) {
316
- var entry = this.cache.get(key);
147
+ lastErr = err;
148
+ if (attempt === retry)
149
+ throw lastErr;
150
+ const delay = Math.pow(2, attempt) * 200;
151
+ await new Promise(r => setTimeout(r, delay));
152
+ attempt++;
153
+ }
154
+ }
155
+ throw lastErr;
156
+ }
157
+ async handleInterceptors(config) {
158
+ if (this.interceptors.request) {
159
+ return await this.interceptors.request(config);
160
+ }
161
+ return config;
162
+ }
163
+ async handleResponse(response) {
164
+ if (this.interceptors.response) {
165
+ return await this.interceptors.response(response);
166
+ }
167
+ return response;
168
+ }
169
+ async handleError(error) {
170
+ if (this.interceptors.error) {
171
+ return await this.interceptors.error(error);
172
+ }
173
+ throw error;
174
+ }
175
+ getCacheEntry(key) {
176
+ const entry = this.cache.get(key);
317
177
  if (entry) {
318
- var index = this.cacheAccessOrder.indexOf(key);
178
+ const index = this.cacheAccessOrder.indexOf(key);
319
179
  if (index > -1) {
320
180
  this.cacheAccessOrder.splice(index, 1);
321
181
  }
322
182
  this.cacheAccessOrder.push(key);
323
183
  }
324
184
  return entry;
325
- };
326
- ApiInstance.prototype.setCacheEntry = function (key, entry) {
185
+ }
186
+ setCacheEntry(key, entry) {
327
187
  if (this.cache.size >= this.maxCacheSize && !this.cache.has(key)) {
328
- var oldestKey = this.cacheAccessOrder.shift();
188
+ const oldestKey = this.cacheAccessOrder.shift();
329
189
  if (oldestKey) {
330
190
  this.cache.delete(oldestKey);
331
191
  }
332
192
  }
333
193
  this.cache.set(key, entry);
334
- var index = this.cacheAccessOrder.indexOf(key);
194
+ const index = this.cacheAccessOrder.indexOf(key);
335
195
  if (index > -1) {
336
196
  this.cacheAccessOrder.splice(index, 1);
337
197
  }
338
198
  this.cacheAccessOrder.push(key);
339
- };
340
- ApiInstance.prototype.removeCacheEntry = function (key) {
199
+ }
200
+ removeCacheEntry(key) {
341
201
  this.cache.delete(key);
342
- var index = this.cacheAccessOrder.indexOf(key);
202
+ const index = this.cacheAccessOrder.indexOf(key);
343
203
  if (index > -1) {
344
204
  this.cacheAccessOrder.splice(index, 1);
345
205
  }
346
- };
347
- ApiInstance.prototype.request = function (config) {
348
- return __awaiter(this, void 0, void 0, function () {
349
- var finalConfig, cacheKey, cached, expired, url, finalURL, isFormData, response, finalResponse, error, code, message, status_2, _a, errorText, contentType, data, error_1;
350
- var _b, _c;
351
- return __generator(this, function (_d) {
352
- switch (_d.label) {
353
- case 0:
354
- _d.trys.push([0, 15, , 16]);
355
- return [4 /*yield*/, this.handleInterceptors(config)];
356
- case 1:
357
- finalConfig = _d.sent();
358
- cacheKey = this.buildcacheKey(finalConfig);
359
- if (finalConfig.cache && finalConfig.cache.enabled && finalConfig.method === 'GET') {
360
- cached = this.getCacheEntry(cacheKey);
361
- if (cached) {
362
- expired = cached.ttl && Date.now() - cached.timestamp > cached.ttl;
363
- if (!expired) {
364
- return [2 /*return*/, { data: cached.data, cacheKey: cacheKey, fromCache: true }];
365
- }
366
- this.removeCacheEntry(cacheKey);
367
- }
368
- }
369
- url = this.baseURL ? "".concat(this.baseURL).concat(finalConfig.url) : finalConfig.url;
370
- finalURL = buildURL(url, finalConfig.params);
371
- isFormData = finalConfig.body instanceof FormData;
372
- return [4 /*yield*/, this.fetchWithRetry(finalURL, {
373
- method: finalConfig.method || 'GET',
374
- headers: __assign(__assign(__assign({}, (isFormData ? {} : { 'Content-Type': 'application/json' })), this.defaultHeaders), finalConfig.headers),
375
- body: isFormData ? finalConfig.body : finalConfig.body ? JSON.stringify(finalConfig.body) : undefined,
376
- }, (_b = finalConfig.retry) !== null && _b !== void 0 ? _b : 0, finalConfig.signal, finalConfig.onUpload, finalConfig.onDownload)];
377
- case 2:
378
- response = _d.sent();
379
- return [4 /*yield*/, this.handleResponse(response)];
380
- case 3:
381
- finalResponse = _d.sent();
382
- if (!!finalResponse.ok) return [3 /*break*/, 8];
383
- _d.label = 4;
384
- case 4:
385
- _d.trys.push([4, 6, , 8]);
386
- return [4 /*yield*/, finalResponse.clone().json()];
387
- case 5:
388
- error = _d.sent();
389
- if (error.meta || error.status) {
390
- code = error.code || error.meta.code || finalResponse.status;
391
- message = error.message || error.meta.message || JSON.stringify(error);
392
- status_2 = error.status || error.meta.status || finalResponse.statusText;
393
- throw new ApiMeta(code, message, status_2);
394
- }
395
- throw error;
396
- case 6:
397
- _a = _d.sent();
398
- return [4 /*yield*/, finalResponse.text()];
399
- case 7:
400
- errorText = _d.sent();
401
- throw new Error(errorText || finalResponse.statusText);
402
- case 8:
403
- contentType = finalResponse.headers.get('content-type') || '';
404
- data = void 0;
405
- if (!contentType.includes('application/json')) return [3 /*break*/, 10];
406
- return [4 /*yield*/, finalResponse.json()];
407
- case 9:
408
- data = (_d.sent());
409
- return [3 /*break*/, 14];
410
- case 10:
411
- if (!contentType.includes('text/')) return [3 /*break*/, 12];
412
- return [4 /*yield*/, finalResponse.text()];
413
- case 11:
414
- data = (_d.sent());
415
- return [3 /*break*/, 14];
416
- case 12: return [4 /*yield*/, finalResponse.blob()];
417
- case 13:
418
- data = (_d.sent());
419
- _d.label = 14;
420
- case 14:
421
- if (finalConfig.cache && finalConfig.cache.enabled && finalConfig.method === 'GET') {
422
- this.setCacheEntry(cacheKey, {
423
- data: data,
424
- timestamp: Date.now(),
425
- ttl: (_c = finalConfig.cache) === null || _c === void 0 ? void 0 : _c.revalidate,
426
- });
427
- }
428
- return [2 /*return*/, { data: data, cacheKey: cacheKey, fromCache: false }];
429
- case 15:
430
- error_1 = _d.sent();
431
- return [2 /*return*/, this.handleError(error_1)];
432
- case 16: return [2 /*return*/];
206
+ }
207
+ async request(config) {
208
+ try {
209
+ const finalConfig = await this.handleInterceptors(config);
210
+ const cacheKey = this.buildcacheKey(finalConfig);
211
+ if (finalConfig.cache && finalConfig.cache.enabled && finalConfig.method === 'GET') {
212
+ const cached = this.getCacheEntry(cacheKey);
213
+ if (cached) {
214
+ const expired = cached.ttl && Date.now() - cached.timestamp > cached.ttl;
215
+ if (!expired) {
216
+ return { data: cached.data, cacheKey, fromCache: true };
217
+ }
218
+ this.removeCacheEntry(cacheKey);
433
219
  }
434
- });
435
- });
436
- };
437
- ApiInstance.prototype.get = function (url, config) {
438
- if (config === void 0) { config = {}; }
439
- return this.request(__assign(__assign({}, config), { url: url, method: 'GET' }));
440
- };
441
- ApiInstance.prototype.post = function (url, body, config) {
442
- if (config === void 0) { config = {}; }
443
- return this.request(__assign(__assign({}, config), { url: url, method: 'POST', body: body }));
444
- };
445
- ApiInstance.prototype.put = function (url, body, config) {
446
- if (config === void 0) { config = {}; }
447
- return this.request(__assign(__assign({}, config), { url: url, method: 'PUT', body: body }));
448
- };
449
- ApiInstance.prototype.patch = function (url, body, config) {
450
- if (config === void 0) { config = {}; }
451
- return this.request(__assign(__assign({}, config), { url: url, method: 'PATCH', body: body }));
452
- };
453
- ApiInstance.prototype.delete = function (url, body, config) {
454
- if (config === void 0) { config = {}; }
455
- return this.request(__assign(__assign({}, config), { url: url, method: 'DELETE', body: body }));
456
- };
457
- ApiInstance.prototype.getCache = function (key) {
458
- var entry = this.getCacheEntry(key);
459
- return entry === null || entry === void 0 ? void 0 : entry.data;
460
- };
461
- ApiInstance.prototype.setCache = function (key, data, ttl) {
462
- this.setCacheEntry(key, { data: data, timestamp: Date.now(), ttl: ttl });
463
- };
464
- ApiInstance.prototype.removeCache = function (key) {
220
+ }
221
+ const url = this.baseURL ? `${this.baseURL}${finalConfig.url}` : finalConfig.url;
222
+ const finalURL = buildURL(url, finalConfig.params);
223
+ const isFormData = finalConfig.body instanceof FormData;
224
+ const response = await this.fetchWithRetry(finalURL, {
225
+ method: finalConfig.method || 'GET',
226
+ headers: {
227
+ ...(isFormData ? {} : { 'Content-Type': 'application/json' }),
228
+ ...this.defaultHeaders,
229
+ ...finalConfig.headers,
230
+ },
231
+ body: isFormData ? finalConfig.body : finalConfig.body ? JSON.stringify(finalConfig.body) : undefined,
232
+ }, finalConfig.retry ?? 0, finalConfig.signal, finalConfig.onUpload, finalConfig.onDownload);
233
+ const finalResponse = await this.handleResponse(response);
234
+ if (!finalResponse.ok) {
235
+ try {
236
+ const error = await finalResponse.clone().json();
237
+ if (error.meta || error.status) {
238
+ const code = error.code || error.meta.code || finalResponse.status;
239
+ const message = error.message || error.meta.message || JSON.stringify(error);
240
+ const status = error.status || error.meta.status || finalResponse.statusText;
241
+ throw new ApiMeta(code, message, status);
242
+ }
243
+ throw error;
244
+ }
245
+ catch {
246
+ const errorText = await finalResponse.text();
247
+ throw new Error(errorText || finalResponse.statusText);
248
+ }
249
+ }
250
+ const contentType = finalResponse.headers.get('content-type') || '';
251
+ let data;
252
+ if (contentType.includes('application/json')) {
253
+ data = (await finalResponse.json());
254
+ }
255
+ else if (contentType.includes('text/')) {
256
+ data = (await finalResponse.text());
257
+ }
258
+ else {
259
+ data = (await finalResponse.blob());
260
+ }
261
+ if (finalConfig.cache && finalConfig.cache.enabled && finalConfig.method === 'GET') {
262
+ this.setCacheEntry(cacheKey, {
263
+ data,
264
+ timestamp: Date.now(),
265
+ ttl: finalConfig.cache?.revalidate,
266
+ });
267
+ }
268
+ return { data, cacheKey, fromCache: false };
269
+ }
270
+ catch (error) {
271
+ return this.handleError(error);
272
+ }
273
+ }
274
+ get(url, config = {}) {
275
+ return this.request({ ...config, url, method: 'GET' });
276
+ }
277
+ post(url, body, config = {}) {
278
+ return this.request({ ...config, url, method: 'POST', body: body });
279
+ }
280
+ put(url, body, config = {}) {
281
+ return this.request({ ...config, url, method: 'PUT', body: body });
282
+ }
283
+ patch(url, body, config = {}) {
284
+ return this.request({ ...config, url, method: 'PATCH', body: body });
285
+ }
286
+ delete(url, body, config = {}) {
287
+ return this.request({ ...config, url, method: 'DELETE', body: body });
288
+ }
289
+ getCache(key) {
290
+ const entry = this.getCacheEntry(key);
291
+ return entry?.data;
292
+ }
293
+ setCache(key, data, ttl) {
294
+ this.setCacheEntry(key, { data, timestamp: Date.now(), ttl });
295
+ }
296
+ removeCache(key) {
465
297
  this.removeCacheEntry(key);
466
- };
467
- ApiInstance.prototype.clearCache = function () {
298
+ }
299
+ clearCache() {
468
300
  this.cache.clear();
469
301
  this.cacheAccessOrder = [];
470
- };
471
- return ApiInstance;
472
- }());
473
- export { ApiInstance };
474
- var instance = new ApiInstance();
475
- var http = {
476
- get: function (url, config) { return instance.get(url, config); },
477
- post: function (url, body, config) { return instance.post(url, body, config); },
478
- put: function (url, body, config) { return instance.put(url, body, config); },
479
- patch: function (url, body, config) { return instance.patch(url, body, config); },
480
- delete: function (url, body, config) { return instance.delete(url, body, config); },
481
- getCache: function (key) { return instance.getCache(key); },
482
- setCache: function (key, data, ttl) { return instance.setCache(key, data, ttl); },
483
- removeCache: function (key) { return instance.removeCache(key); },
484
- clearCache: function () { return instance.clearCache(); },
485
- request: function (config) { return instance.request(config); },
486
- create: function (options) {
487
- if (options === void 0) { options = {}; }
488
- return new ApiInstance(options);
489
- },
302
+ }
303
+ }
304
+ const instance = new ApiInstance();
305
+ const http = {
306
+ get: (url, config) => instance.get(url, config),
307
+ post: (url, body, config) => instance.post(url, body, config),
308
+ put: (url, body, config) => instance.put(url, body, config),
309
+ patch: (url, body, config) => instance.patch(url, body, config),
310
+ delete: (url, body, config) => instance.delete(url, body, config),
311
+ getCache: (key) => instance.getCache(key),
312
+ setCache: (key, data, ttl) => instance.setCache(key, data, ttl),
313
+ removeCache: (key) => instance.removeCache(key),
314
+ clearCache: () => instance.clearCache(),
315
+ request: (config) => instance.request(config),
316
+ create: (options = {}) => new ApiInstance(options),
490
317
  };
491
318
  export default http;