larapi 0.2.45 → 0.2.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,952 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
21
+ var __async = (__this, __arguments, generator) => {
22
+ return new Promise((resolve, reject) => {
23
+ var fulfilled = (value) => {
24
+ try {
25
+ step(generator.next(value));
26
+ } catch (e) {
27
+ reject(e);
28
+ }
29
+ };
30
+ var rejected = (value) => {
31
+ try {
32
+ step(generator.throw(value));
33
+ } catch (e) {
34
+ reject(e);
35
+ }
36
+ };
37
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
38
+ step((generator = generator.apply(__this, __arguments)).next());
39
+ });
40
+ };
41
+
42
+ // src/Core.ts
43
+ import EventEmitter from "easy-event-emitter";
44
+ var Core = class {
45
+ constructor(context) {
46
+ __publicField(this, "cache");
47
+ __publicField(this, "initData");
48
+ __publicField(this, "events");
49
+ __publicField(this, "config");
50
+ __publicField(this, "headers", {});
51
+ this.events = new EventEmitter();
52
+ this.config = {
53
+ host: "http://127.0.0.1/"
54
+ };
55
+ this.cache = {};
56
+ this.initData = {};
57
+ this.setConfig = this.setConfig.bind(this);
58
+ this.getConfig = this.getConfig.bind(this);
59
+ this.setHost = this.setHost.bind(this);
60
+ this.setInitData = this.setInitData.bind(this);
61
+ this.triggerByCacheGroup = this.triggerByCacheGroup.bind(this);
62
+ this.clearCacheGroup = this.clearCacheGroup.bind(this);
63
+ this.updateCacheGroup = this.updateCacheGroup.bind(this);
64
+ this.setGlobalInitData = this.setGlobalInitData.bind(this);
65
+ if (context) {
66
+ Object.assign(this, {
67
+ config: context == null ? void 0 : context.config,
68
+ events: context == null ? void 0 : context.events,
69
+ cache: context == null ? void 0 : context.cache,
70
+ initData: context == null ? void 0 : context.initData,
71
+ headers: context.headers
72
+ });
73
+ }
74
+ }
75
+ setConfig(config) {
76
+ this.config = config;
77
+ }
78
+ getConfig() {
79
+ return this.config;
80
+ }
81
+ getCache(key) {
82
+ if (this.cache[key]) {
83
+ if ((/* @__PURE__ */ new Date()).getTime() <= this.cache[key].time + 36e8) {
84
+ return this.cache[key].data;
85
+ } else {
86
+ delete this.cache[key];
87
+ }
88
+ }
89
+ }
90
+ isJsonString(str) {
91
+ try {
92
+ JSON.parse(str);
93
+ } catch (e) {
94
+ return false;
95
+ }
96
+ return true;
97
+ }
98
+ compileRevivers() {
99
+ const fieldRevivers = {};
100
+ const objectRevivers = [];
101
+ const replace = this.config.dataReviver;
102
+ if (!replace) return { fieldRevivers, objectRevivers };
103
+ for (const [key, fn] of Object.entries(replace)) {
104
+ if (typeof fn !== "function") continue;
105
+ if (key.includes("&")) {
106
+ objectRevivers.push({
107
+ keys: new Set(key.split("&")),
108
+ fn
109
+ });
110
+ } else {
111
+ fieldRevivers[key] = fn;
112
+ }
113
+ }
114
+ return { fieldRevivers, objectRevivers };
115
+ }
116
+ applyObjectRevivers(value, objectRevivers, depth = 0, isArrayItem = false) {
117
+ if (!value || typeof value !== "object") {
118
+ return value;
119
+ }
120
+ if (Array.isArray(value)) {
121
+ for (let i = 0; i < value.length; i++) {
122
+ value[i] = this.applyObjectRevivers(value[i], objectRevivers, depth + 1, true);
123
+ }
124
+ return value;
125
+ }
126
+ let obj = value;
127
+ const shouldApply = depth === 0 || isArrayItem;
128
+ if (shouldApply) {
129
+ for (const rule of objectRevivers) {
130
+ const keys = Object.keys(obj);
131
+ if (rule.keys.size > keys.length) continue;
132
+ let match = true;
133
+ for (const k of rule.keys) {
134
+ if (!(k in obj)) {
135
+ match = false;
136
+ break;
137
+ }
138
+ }
139
+ if (match) {
140
+ obj = rule.fn(obj);
141
+ }
142
+ }
143
+ }
144
+ for (const k of Object.keys(obj)) {
145
+ obj[k] = this.applyObjectRevivers(obj[k], objectRevivers, depth + 1, false);
146
+ }
147
+ return obj;
148
+ }
149
+ dataPrepare(data) {
150
+ const json = JSON.stringify(data);
151
+ return this.jsonParse(json);
152
+ }
153
+ jsonParse(str) {
154
+ if (typeof this.config.reviver === "function") {
155
+ return JSON.parse(str, this.config.reviver);
156
+ }
157
+ const { fieldRevivers, objectRevivers } = this.compileRevivers();
158
+ const data = JSON.parse(str, (key, value) => {
159
+ const reviver = fieldRevivers[key];
160
+ return reviver ? reviver(value) : value;
161
+ });
162
+ return this.applyObjectRevivers(data, objectRevivers);
163
+ }
164
+ setHost(host) {
165
+ this.config.host = host;
166
+ }
167
+ setHeader(name, value) {
168
+ this.headers[name] = value;
169
+ this.events.emit("header-update", {
170
+ name,
171
+ value
172
+ });
173
+ }
174
+ getHeader(name) {
175
+ return this.headers[name];
176
+ }
177
+ getHeaders() {
178
+ return Object.entries(this.headers).map(([name, value]) => ({ name, value }));
179
+ }
180
+ hasHeader(name) {
181
+ return this.headers[name] ? true : false;
182
+ }
183
+ deleteHeader(name) {
184
+ delete this.headers[name];
185
+ }
186
+ setCache(key, data, group) {
187
+ this.cache[key] = {
188
+ time: (/* @__PURE__ */ new Date()).getTime(),
189
+ data,
190
+ group
191
+ };
192
+ }
193
+ groupFromArray(groups, callback, withoutSplit = false) {
194
+ const currentCallback = (group) => {
195
+ if (typeof group === "string" && !withoutSplit) {
196
+ const params = group.split(".");
197
+ const current = params.shift();
198
+ callback(current, params);
199
+ } else {
200
+ callback(group);
201
+ }
202
+ };
203
+ if (Array.isArray(groups)) {
204
+ groups.map(currentCallback);
205
+ } else if (typeof groups === "string") {
206
+ currentCallback(groups);
207
+ }
208
+ }
209
+ triggerByCacheGroup(groups) {
210
+ this.groupFromArray(groups, (group) => this.events.emit("trigger-request-by-cache-" + group, void 0));
211
+ }
212
+ clearCacheGroup(groups, data, fieldKey = "id") {
213
+ this.groupFromArray(groups, (group) => {
214
+ if (data) {
215
+ const clear = (cacheData) => {
216
+ if (fieldKey && (cacheData == null ? void 0 : cacheData[fieldKey]) === (data == null ? void 0 : data[fieldKey]) || fieldKey === null) {
217
+ for (const key in cacheData) {
218
+ if (key in data) {
219
+ return false;
220
+ }
221
+ }
222
+ }
223
+ return true;
224
+ };
225
+ for (const key in this.cache) {
226
+ if (this.cache[key].group === group) {
227
+ if (Array.isArray(this.cache[key].data)) {
228
+ this.cache[key].data = Object.values(this.cache[key].data).filter(clear);
229
+ } else {
230
+ if (!clear(this.cache[key].data))
231
+ delete this.cache[key];
232
+ }
233
+ }
234
+ }
235
+ } else {
236
+ for (const key in this.cache) {
237
+ if (this.cache[key].group === group) {
238
+ delete this.cache[key];
239
+ }
240
+ }
241
+ }
242
+ });
243
+ }
244
+ setDataTree(obj, path, val) {
245
+ const keys = path.split(".");
246
+ const lastKey = keys.pop();
247
+ const lastObj = keys.reduce(
248
+ (obj2, key) => obj2[key] = obj2[key] || {},
249
+ obj
250
+ );
251
+ if (typeof lastKey === "string") {
252
+ lastObj[lastKey] = val;
253
+ }
254
+ return obj;
255
+ }
256
+ updateCacheGroup(groups, data, fieldKey = "id") {
257
+ const update = (cacheData) => {
258
+ const retData = cacheData;
259
+ const fieldList = fieldKey.split(".");
260
+ if (fieldList.length > 1) {
261
+ for (const key of fieldList) {
262
+ cacheData = cacheData[key];
263
+ }
264
+ }
265
+ if (fieldKey && cacheData[fieldKey] === data[fieldKey] || fieldKey === null) {
266
+ for (const key in cacheData) {
267
+ if (key in data) {
268
+ cacheData[key] = data[key];
269
+ }
270
+ }
271
+ }
272
+ return retData;
273
+ };
274
+ this.groupFromArray(groups, (group, params) => {
275
+ for (const key in this.cache) {
276
+ if (this.cache[key].group === group) {
277
+ if (Array.isArray(this.cache[key].data)) {
278
+ this.cache[key].data = Object.values(this.cache[key].data).map(update);
279
+ } else {
280
+ this.cache[key].data = update(this.cache[key].data);
281
+ }
282
+ }
283
+ }
284
+ });
285
+ }
286
+ appendCacheGroup(group, data) {
287
+ }
288
+ getCacheByIndex(index) {
289
+ return this.cache[index];
290
+ }
291
+ deleteCache(key) {
292
+ if (!this.cache[key])
293
+ return;
294
+ const group = this.cache[key].group;
295
+ if (group) {
296
+ this.clearCacheGroup(group);
297
+ }
298
+ delete this.cache[key];
299
+ }
300
+ setGlobalInitData(name, data) {
301
+ this.initData[name] = data;
302
+ }
303
+ setInitData(data) {
304
+ this.initData = data;
305
+ }
306
+ };
307
+ var Core_default = Core;
308
+
309
+ // src/Http.ts
310
+ import md5 from "md5";
311
+
312
+ // src/Queue.ts
313
+ var _Queue = class _Queue {
314
+ constructor(http) {
315
+ __publicField(this, "queue", _Queue._Queue);
316
+ __publicField(this, "http");
317
+ this.http = http;
318
+ this.has = this.has.bind(this);
319
+ this.get = this.get.bind(this);
320
+ this.clear = this.clear.bind(this);
321
+ this.push = this.push.bind(this);
322
+ }
323
+ has(request) {
324
+ return request in this.queue;
325
+ }
326
+ get(request) {
327
+ return this.has(request) ? this.queue[request] : void 0;
328
+ }
329
+ clear(request) {
330
+ if (this.has(request)) {
331
+ delete this.queue[request];
332
+ }
333
+ }
334
+ push(request) {
335
+ const refInstance = this.get(request);
336
+ if (!refInstance) {
337
+ this.queue[request] = this.http;
338
+ } else {
339
+ refInstance == null ? void 0 : refInstance.addListener("api-request-success", this.http.handleSuccess);
340
+ refInstance == null ? void 0 : refInstance.addListener("api-request-error", this.http.handleError);
341
+ refInstance == null ? void 0 : refInstance.addListener("api-request-fail", this.http.handleFail);
342
+ refInstance == null ? void 0 : refInstance.addListener("api-request-complete", this.http.handleComplete);
343
+ refInstance == null ? void 0 : refInstance.addListener("api-request-abort", this.http.handleAbort);
344
+ }
345
+ return refInstance instanceof Http_default;
346
+ }
347
+ };
348
+ __publicField(_Queue, "_Queue", {});
349
+ var Queue = _Queue;
350
+ var Queue_default = Queue;
351
+
352
+ // src/Http.ts
353
+ import EventEmitter2 from "easy-event-emitter";
354
+ var Http = class _Http extends Core_default {
355
+ constructor(method, params, context) {
356
+ super(context);
357
+ __publicField(this, "cacheIndex");
358
+ __publicField(this, "currentCache");
359
+ __publicField(this, "currentEvents");
360
+ __publicField(this, "requestParams");
361
+ __publicField(this, "method");
362
+ __publicField(this, "params");
363
+ __publicField(this, "path");
364
+ __publicField(this, "queue");
365
+ __publicField(this, "queueName");
366
+ __publicField(this, "_promise");
367
+ __publicField(this, "xhr");
368
+ __publicField(this, "tryRequestCount", 0);
369
+ __publicField(this, "tryRequestTimeout");
370
+ this.currentEvents = new EventEmitter2();
371
+ this._promise = new Promise(() => {
372
+ });
373
+ this.queue = new Queue_default(this);
374
+ this.cacheIndex = "";
375
+ this.queueName = "";
376
+ this.method = method;
377
+ this.headers = __spreadValues(__spreadValues({}, this.headers), params.headers);
378
+ this.params = __spreadValues(__spreadProps(__spreadValues({}, this.config), {
379
+ headers: this.headers
380
+ }), params);
381
+ this.path = this.params.path;
382
+ this.requestParams = {
383
+ method: this.method
384
+ };
385
+ this.handleSuccess = this.handleSuccess.bind(this);
386
+ this.handleAbort = this.handleAbort.bind(this);
387
+ this.handleFail = this.handleFail.bind(this);
388
+ this.handleError = this.handleError.bind(this);
389
+ this.handleComplete = this.handleComplete.bind(this);
390
+ this.handleProgress = this.handleProgress.bind(this);
391
+ this.setEmit = this.setEmit.bind(this);
392
+ this.request = this.request.bind(this);
393
+ this.httpRequest = this.httpRequest.bind(this);
394
+ this.tryHttpRequest = this.tryHttpRequest.bind(this);
395
+ this.initRequest();
396
+ this.initCache();
397
+ this.initQueue();
398
+ }
399
+ initRequest() {
400
+ var _a;
401
+ if (typeof XMLHttpRequest !== "undefined") {
402
+ this.xhr = new XMLHttpRequest();
403
+ }
404
+ if (this.params.clearUndifinedData)
405
+ this.params.data = this.params.data ? this.cuteUndifinedParams(this.params.data) : this.params.data;
406
+ if (["GET", "HEAD"].includes(this.method)) {
407
+ if (this.params.data)
408
+ this.path = this.params.path + "?" + this.encodeUrlParams(this.params.data);
409
+ if (this.method === "HEAD") {
410
+ this.requestParams.withoutResponse = true;
411
+ }
412
+ }
413
+ if (["POST", "PUT", "CONNECT", "PATH"].includes(this.method)) {
414
+ this.requestParams.body = (_a = this.params.body) != null ? _a : JSON.stringify(this.params.data);
415
+ }
416
+ if (["PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE"].includes(this.method)) {
417
+ this.params.cache = false;
418
+ }
419
+ }
420
+ initCache() {
421
+ var _a;
422
+ this.cacheIndex = md5(this.path + JSON.stringify(this.params.data));
423
+ if (this.params.globalName) {
424
+ if (this.initData[this.params.globalName]) {
425
+ const data = this.config.globalDataWithoutDataPrepare ? this.initData[this.params.globalName] : this.dataPrepare(this.initData[this.params.globalName]);
426
+ this.setCache(this.cacheIndex, data, typeof this.params.cache === "boolean" ? void 0 : this.params.cache);
427
+ this.params.cache = (_a = this.params.cache) != null ? _a : true;
428
+ delete this.initData[this.params.globalName];
429
+ }
430
+ }
431
+ if (this.params.cache) {
432
+ if (typeof this.params.cache === "string") {
433
+ this.events.addListener("trigger-request-by-cache-" + this.params.cache, this.request);
434
+ }
435
+ this._promise = new Promise((resolve) => __async(this, null, function* () {
436
+ if (this.currentCache = this.getCache(this.cacheIndex)) {
437
+ resolve(this.currentCache);
438
+ this.handleSuccess(this.currentCache);
439
+ this.handleComplete(this.currentCache);
440
+ }
441
+ }));
442
+ } else {
443
+ this.deleteCache(this.cacheIndex);
444
+ }
445
+ }
446
+ get host() {
447
+ return this.params.host;
448
+ }
449
+ get promise() {
450
+ return this._promise;
451
+ }
452
+ get url() {
453
+ return this.params.host + this.path;
454
+ }
455
+ initQueue() {
456
+ this.queueName = this.params.queueThrottling ? md5(this.path) : this.cacheIndex;
457
+ }
458
+ setEmit(event, data) {
459
+ this.currentEvents.emit(event, data);
460
+ this.events.emit(event, {
461
+ cacheIndex: this.cacheIndex,
462
+ data
463
+ });
464
+ }
465
+ //Заголовки от 200 до 299
466
+ handleSuccess(data) {
467
+ if (typeof this.params.success === "function" && this.xhr)
468
+ this.params.success(data, this.xhr);
469
+ if (this.params.cacheUpdate && this.params.data) {
470
+ this.groupFromArray(this.params.cacheUpdate, (cacheUpdate, params) => {
471
+ var _a;
472
+ this.updateCacheGroup(
473
+ typeof cacheUpdate === "string" ? cacheUpdate : cacheUpdate.group,
474
+ (_a = this.params.data) != null ? _a : {},
475
+ typeof cacheUpdate === "string" ? void 0 : cacheUpdate.fieldKey
476
+ );
477
+ }, true);
478
+ }
479
+ if (this.params.cacheClear && this.params.data) {
480
+ this.groupFromArray(this.params.cacheClear, (cacheClear) => {
481
+ this.clearCacheGroup(
482
+ typeof cacheClear === "string" ? cacheClear : cacheClear.group,
483
+ this.params.data,
484
+ typeof cacheClear === "string" ? void 0 : cacheClear.fieldKey
485
+ );
486
+ });
487
+ }
488
+ this.setEmit("api-request-success", data);
489
+ }
490
+ handleAbort(data) {
491
+ if (typeof this.params.abort === "function") {
492
+ this.params.abort(data);
493
+ }
494
+ this.setEmit("api-request-abort", data);
495
+ }
496
+ //Заголовки от 400 до 499
497
+ handleFail(data) {
498
+ if (typeof this.params.fail === "function") {
499
+ this.params.fail(data);
500
+ }
501
+ this.setEmit("api-request-fail", data);
502
+ }
503
+ //Все остальные
504
+ handleError(data) {
505
+ var _a;
506
+ if (((_a = this.xhr) == null ? void 0 : _a.status) === 0 && this.xhr.readyState === 4) {
507
+ return;
508
+ }
509
+ if (typeof this.params.error === "function") {
510
+ this.params.error(data);
511
+ }
512
+ this.setEmit("api-request-error", data);
513
+ }
514
+ handleComplete(data) {
515
+ if (typeof this.params.complete === "function") {
516
+ this.params.complete(data);
517
+ }
518
+ this.setEmit("api-request-complete", data);
519
+ }
520
+ handleProgress(progress) {
521
+ if (typeof this.params.progress === "function") {
522
+ this.params.progress(progress);
523
+ }
524
+ this.setEmit("api-request-progress", progress);
525
+ }
526
+ encodeUrlParams(data, prefix = "") {
527
+ return Object.entries(data).filter(([_, value]) => value !== void 0 && value !== null).map(([key, value]) => {
528
+ const encodedKey = prefix ? `${prefix}[${encodeURIComponent(key)}]` : encodeURIComponent(key);
529
+ if (Array.isArray(value)) {
530
+ if (value.length === 0) return `${encodedKey}[]=`;
531
+ return value.map((val) => `${encodedKey}[]=${encodeURIComponent(String(val))}`).join("&");
532
+ }
533
+ if (typeof value === "object" && value !== null) {
534
+ return this.encodeUrlParams(value, encodedKey);
535
+ }
536
+ return `${encodedKey}=${encodeURIComponent(String(value))}`;
537
+ }).filter((str) => str !== "").join("&");
538
+ }
539
+ cuteUndifinedParams(data) {
540
+ if (typeof data !== "object" || data === null) {
541
+ return data;
542
+ }
543
+ for (const key in data) {
544
+ if (typeof data[key] === "undefined") {
545
+ delete data[key];
546
+ }
547
+ }
548
+ return data;
549
+ }
550
+ tryHttpRequest() {
551
+ return new Promise((resolve, reject) => {
552
+ var _a;
553
+ if (this.params.tryRequest && this.params.tryRequest > this.tryRequestCount) {
554
+ if (this.tryRequestTimeout) {
555
+ clearTimeout(this.tryRequestTimeout);
556
+ }
557
+ this.tryRequestTimeout = setTimeout(() => {
558
+ var _a2;
559
+ (_a2 = this.xhr) == null ? void 0 : _a2.abort();
560
+ this.httpRequest().then((value) => {
561
+ resolve(value);
562
+ this.tryRequestCount = 0;
563
+ }).catch(reject);
564
+ }, (_a = this.params.tryRequestDelay) != null ? _a : 1e3);
565
+ ++this.tryRequestCount;
566
+ } else {
567
+ reject();
568
+ }
569
+ });
570
+ }
571
+ fileRequest() {
572
+ return new Promise((resolve, reject) => __async(this, null, function* () {
573
+ if (!this.params.file) return;
574
+ const data = this.params.file;
575
+ const chunkSize = this.params.fileSizeChunk ? this.params.fileSizeChunk * 1024 * 1024 : this.params.file.byteLength;
576
+ const totalChunks = Math.ceil(this.params.file.byteLength / chunkSize);
577
+ let fileId = this.params.fileIdByServer ? void 0 : `file-${(/* @__PURE__ */ new Date()).getTime()}`;
578
+ for (let i = 0; i < totalChunks; i++) {
579
+ try {
580
+ const start = i * chunkSize;
581
+ const end = Math.min(start + chunkSize, data.byteLength);
582
+ const chunk = data.slice(start, end);
583
+ const headers = __spreadValues({}, this.headers);
584
+ let body = void 0;
585
+ if (this.params.fileType === "binary") {
586
+ const u8 = chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);
587
+ headers["Content-Type"] = "application/octet-stream";
588
+ headers["Content-Range"] = `bytes ${start}-${end - 1}/${this.params.file.byteLength}`;
589
+ headers["X-Chunk-Index"] = String(i);
590
+ headers["X-Chunk-Total"] = String(totalChunks);
591
+ if (fileId && (!this.params.fileIdByServer || this.params.fileIdByServer && i > 0)) {
592
+ headers[typeof this.params.fileIdByServer === "string" ? this.params.fileIdByServer : "X-File-ID"] = fileId;
593
+ }
594
+ body = u8;
595
+ } else {
596
+ const formData = new FormData();
597
+ formData.append("file", new Blob([chunk]));
598
+ if (fileId && (!this.params.fileIdByServer || this.params.fileIdByServer && i > 0)) {
599
+ formData.append(typeof this.params.fileIdByServer === "string" ? this.params.fileIdByServer : "file_id", fileId);
600
+ }
601
+ formData.append("chunk_index", String(i));
602
+ formData.append("total_chunks", String(totalChunks));
603
+ if (this.params.data && totalChunks - 1 === i) {
604
+ for (const key in this.params.data) {
605
+ formData.append(key, this.params.data[key]);
606
+ }
607
+ }
608
+ delete headers["Content-Type"];
609
+ body = formData;
610
+ }
611
+ delete headers["Accept"];
612
+ const http = new _Http(this.method, __spreadProps(__spreadValues({}, this.params), {
613
+ file: void 0,
614
+ headers,
615
+ data: void 0,
616
+ fileSizeChunk: void 0,
617
+ body,
618
+ success: totalChunks - 1 > i ? void 0 : (data2) => {
619
+ resolve(data2);
620
+ this.handleSuccess(data2);
621
+ },
622
+ complete: totalChunks - 1 > i ? void 0 : (e) => {
623
+ this.handleComplete(e);
624
+ },
625
+ progress: (progres) => {
626
+ const loaded = start + progres.loaded;
627
+ this.handleProgress({
628
+ percent: loaded / data.byteLength * 100,
629
+ total: data.byteLength,
630
+ loaded
631
+ });
632
+ },
633
+ fail: reject,
634
+ error: reject
635
+ }), this);
636
+ this.xhr = http.xhr;
637
+ const result = yield http.request(true).promise;
638
+ if (result == null ? void 0 : result.file_id) {
639
+ fileId = result == null ? void 0 : result.file_id;
640
+ }
641
+ } catch (e) {
642
+ reject(e);
643
+ break;
644
+ }
645
+ }
646
+ }));
647
+ }
648
+ httpRequest() {
649
+ return new Promise((resolve, reject) => {
650
+ var _a;
651
+ if (typeof this.xhr === "undefined") return;
652
+ try {
653
+ this.xhr.open(this.method, this.url, (_a = this.params.requestAsync) != null ? _a : true);
654
+ if (this.params.timeout) {
655
+ this.xhr.timeout = this.params.timeout;
656
+ }
657
+ for (const header in this.headers) {
658
+ this.xhr.setRequestHeader(header, this.headers[header]);
659
+ }
660
+ if (this.xhr.upload) {
661
+ this.xhr.upload.onprogress = ({ lengthComputable, loaded, total }) => {
662
+ if (lengthComputable) {
663
+ this.handleProgress({
664
+ percent: loaded / total * 100,
665
+ total,
666
+ loaded
667
+ });
668
+ }
669
+ };
670
+ }
671
+ this.xhr.onabort = () => {
672
+ reject({
673
+ type: "abort",
674
+ message: "request abort"
675
+ });
676
+ this.handleAbort({
677
+ message: "request abort"
678
+ });
679
+ };
680
+ this.xhr.ontimeout = () => {
681
+ this.tryHttpRequest().then(resolve).catch(reject);
682
+ };
683
+ this.xhr.onerror = (event) => __async(this, null, function* () {
684
+ yield this.tryHttpRequest().then(resolve).catch(reject);
685
+ reject({
686
+ type: "error",
687
+ message: "request error",
688
+ event
689
+ });
690
+ this.handleError({
691
+ message: "request error",
692
+ event
693
+ });
694
+ });
695
+ this.xhr.onreadystatechange = () => {
696
+ var _a2, _b;
697
+ if (((_a2 = this.xhr) == null ? void 0 : _a2.readyState) !== XMLHttpRequest.DONE) return;
698
+ const result = !this.requestParams.withoutResponse && this.isJsonString(this.xhr.responseText) ? this.jsonParse(this.xhr.responseText) : {};
699
+ if (((_b = this.xhr) == null ? void 0 : _b.status) >= 200 && this.xhr.status <= 299) {
700
+ if (this.params.cache) {
701
+ this.setCache(this.cacheIndex, result, typeof this.params.cache === "boolean" ? void 0 : this.params.cache);
702
+ }
703
+ resolve(result);
704
+ this.handleSuccess(result);
705
+ } else {
706
+ if (this.xhr.status >= 100 && this.xhr.status <= 500) {
707
+ reject(result);
708
+ this.handleFail(result);
709
+ }
710
+ }
711
+ this.handleComplete(result);
712
+ this.queue.clear(this.queueName);
713
+ };
714
+ this.xhr.send(this.requestParams.body);
715
+ } catch (e) {
716
+ reject(e);
717
+ }
718
+ });
719
+ }
720
+ streamRequest() {
721
+ return new Promise((resolve, reject) => {
722
+ fetch(this.url, {
723
+ method: this.method,
724
+ headers: this.headers,
725
+ body: this.requestParams.body
726
+ }).then((response) => {
727
+ this.handleSuccess(response);
728
+ resolve(response);
729
+ }).catch((e) => {
730
+ this.handleFail(e);
731
+ reject(e);
732
+ });
733
+ });
734
+ }
735
+ request(force) {
736
+ if (!force && !this.params.forceRequest && (this.currentCache || this.queue.push(this.queueName))) return this;
737
+ this._promise = new Promise((resolve, reject) => __async(this, null, function* () {
738
+ try {
739
+ let result;
740
+ if (this.params.stream) {
741
+ result = yield this.streamRequest();
742
+ } else if (this.params.file) {
743
+ result = yield this.fileRequest();
744
+ } else {
745
+ result = yield this.httpRequest();
746
+ }
747
+ resolve(result);
748
+ } catch (e) {
749
+ reject(e);
750
+ }
751
+ }));
752
+ return this;
753
+ }
754
+ abort() {
755
+ var _a;
756
+ (_a = this.xhr) == null ? void 0 : _a.abort();
757
+ }
758
+ addListener(event, callback) {
759
+ return this.currentEvents.addListener(event, callback);
760
+ }
761
+ updateCache(data, fieldKey = "id") {
762
+ const cache = this.getCacheByIndex(this.cacheIndex);
763
+ if (cache && cache.group) {
764
+ this.updateCacheGroup(cache.group, data, fieldKey);
765
+ }
766
+ }
767
+ clearCache(data, fieldKey = "id") {
768
+ if (data) {
769
+ const cache = this.getCacheByIndex(this.cacheIndex);
770
+ if (cache && cache.group) {
771
+ this.clearCacheGroup(cache.group, data, fieldKey);
772
+ }
773
+ } else {
774
+ this.deleteCache(this.cacheIndex);
775
+ }
776
+ }
777
+ };
778
+ var Http_default = Http;
779
+
780
+ // src/index.ts
781
+ var _API = class _API extends Core_default {
782
+ constructor(config) {
783
+ super();
784
+ __publicField(this, "_user");
785
+ __publicField(this, "token");
786
+ __publicField(this, "csrfToken");
787
+ this.headers = __spreadValues({
788
+ "Accept": "application/json",
789
+ "Content-Type": "application/json"
790
+ }, config.headers);
791
+ this.setConfig(config);
792
+ this._user = {};
793
+ this.setToken = this.setToken.bind(this);
794
+ this.setCSRFToken = this.setCSRFToken.bind(this);
795
+ this.setLogin = this.setLogin.bind(this);
796
+ this.setUser = this.setUser.bind(this);
797
+ this.updateUser = this.updateUser.bind(this);
798
+ this.logout = this.logout.bind(this);
799
+ this.getToken = this.getToken.bind(this);
800
+ this.getCSRFToken = this.getCSRFToken.bind(this);
801
+ this.http = this.http.bind(this);
802
+ this.get = this.get.bind(this);
803
+ this.head = this.head.bind(this);
804
+ this.post = this.post.bind(this);
805
+ this.put = this.put.bind(this);
806
+ this.patch = this.patch.bind(this);
807
+ this.delete = this.delete.bind(this);
808
+ this.options = this.options.bind(this);
809
+ this.connect = this.connect.bind(this);
810
+ this.trace = this.trace.bind(this);
811
+ this.getUid = this.getUid.bind(this);
812
+ this.getUser = this.getUser.bind(this);
813
+ this.addListener = this.addListener.bind(this);
814
+ this.getConfig = this.getConfig.bind(this);
815
+ }
816
+ http(method, params) {
817
+ const http = new Http_default(method, params, this);
818
+ if (this.token) http.setHeader("Authorization", `Bearer ${this.token}`);
819
+ if (this.csrfToken) http.setHeader("X-CSRF-TOKEN", this.csrfToken);
820
+ return http;
821
+ }
822
+ get(params) {
823
+ return this.http("GET", params).request();
824
+ }
825
+ head(params) {
826
+ return this.http("HEAD", params).request();
827
+ }
828
+ post(params) {
829
+ return this.http("POST", params).request();
830
+ }
831
+ put(params) {
832
+ return this.http("PUT", params).request();
833
+ }
834
+ patch(params) {
835
+ return this.http("PATCH", params).request();
836
+ }
837
+ delete(params) {
838
+ return this.http("DELETE", params).request();
839
+ }
840
+ options(params) {
841
+ return this.http("OPTIONS", params).request();
842
+ }
843
+ connect(params) {
844
+ return this.http("CONNECT", params).request();
845
+ }
846
+ trace(params) {
847
+ return this.http("TRACE", params).request();
848
+ }
849
+ addListener(event, callback) {
850
+ return this.events.addListener(event, callback);
851
+ }
852
+ setToken(token) {
853
+ this.token = token;
854
+ this.events.emit("token-update", token);
855
+ }
856
+ setCSRFToken(csrfToken) {
857
+ this.csrfToken = csrfToken;
858
+ this.events.emit("csrf-token-update", csrfToken);
859
+ }
860
+ getConfig() {
861
+ return this.config;
862
+ }
863
+ getToken() {
864
+ return this.token;
865
+ }
866
+ getCSRFToken() {
867
+ return this.csrfToken;
868
+ }
869
+ getUid() {
870
+ return typeof this._user === "object" && "id" in this._user ? Number(this._user.id) : 0;
871
+ }
872
+ getUser() {
873
+ return this._user;
874
+ }
875
+ get uid() {
876
+ return this.getUid();
877
+ }
878
+ get user() {
879
+ return this.getUser();
880
+ }
881
+ get host() {
882
+ return this.config.host;
883
+ }
884
+ setLogin(user, token = "") {
885
+ this.setUser(user);
886
+ this.setToken(token);
887
+ this.events.emit("login", {
888
+ user,
889
+ token
890
+ });
891
+ }
892
+ setUser(user) {
893
+ this._user = user;
894
+ this.events.emit("user-set", user);
895
+ }
896
+ updateUser(user) {
897
+ const updatedUser = __spreadValues(__spreadValues({}, this.user), user);
898
+ this.setUser(updatedUser);
899
+ this.events.emit("user-update", updatedUser);
900
+ }
901
+ logout() {
902
+ return __async(this, null, function* () {
903
+ const user = this.user;
904
+ this.setUser({});
905
+ this.setToken("");
906
+ this.events.emit("logout", user);
907
+ });
908
+ }
909
+ };
910
+ __publicField(_API, "instance", new _API({
911
+ host: ""
912
+ }));
913
+ __publicField(_API, "http", _API.instance.http);
914
+ __publicField(_API, "get", _API.instance.get);
915
+ __publicField(_API, "head", _API.instance.head);
916
+ __publicField(_API, "post", _API.instance.post);
917
+ __publicField(_API, "put", _API.instance.put);
918
+ __publicField(_API, "patch", _API.instance.patch);
919
+ __publicField(_API, "delete", _API.instance.delete);
920
+ __publicField(_API, "options", _API.instance.options);
921
+ __publicField(_API, "connect", _API.instance.connect);
922
+ __publicField(_API, "trace", _API.instance.trace);
923
+ __publicField(_API, "setConfig", _API.instance.setConfig);
924
+ __publicField(_API, "setHost", _API.instance.setHost);
925
+ __publicField(_API, "setUser", _API.instance.setUser);
926
+ __publicField(_API, "updateUser", _API.instance.updateUser);
927
+ __publicField(_API, "logout", _API.instance.logout);
928
+ __publicField(_API, "setToken", _API.instance.setToken);
929
+ __publicField(_API, "setLogin", _API.instance.setLogin);
930
+ __publicField(_API, "addListener", _API.instance.addListener);
931
+ __publicField(_API, "setInitData", _API.instance.setInitData);
932
+ __publicField(_API, "setCSRFToken", _API.instance.setCSRFToken);
933
+ __publicField(_API, "getCSRFToken", _API.instance.getCSRFToken);
934
+ __publicField(_API, "triggerByCacheGroup", _API.instance.triggerByCacheGroup);
935
+ __publicField(_API, "clearCacheGroup", _API.instance.clearCacheGroup);
936
+ __publicField(_API, "updateCacheGroup", _API.instance.updateCacheGroup);
937
+ __publicField(_API, "getToken", _API.instance.getToken);
938
+ __publicField(_API, "getUid", _API.instance.getUid);
939
+ __publicField(_API, "getUser", _API.instance.getUser);
940
+ __publicField(_API, "user", _API.instance.user);
941
+ __publicField(_API, "uid", _API.instance.uid);
942
+ /**
943
+ * @deprecated The method should not be used
944
+ */
945
+ __publicField(_API, "deleteCacheGroup", _API.instance.clearCacheGroup);
946
+ var API = _API;
947
+ globalThis.apiSetInitData = API.setInitData;
948
+ var index_default = API;
949
+ export {
950
+ index_default as default
951
+ };
952
+ //# sourceMappingURL=index.mjs.map