@naturalcycles/internal-web-lib 1.0.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.
@@ -0,0 +1,1334 @@
1
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.87.0_undici@8.10.2/node_modules/@naturalcycles/js-lib/dist/is.util.js
2
+ var e = (e) => !!e;
3
+ function t(e) {
4
+ return typeof e == "object" && !!e && !Array.isArray(e) || !1;
5
+ }
6
+ function n(e) {
7
+ for (let t in e) if (Object.hasOwn(e, t)) return !1;
8
+ return !0;
9
+ }
10
+ //#endregion
11
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.87.0_undici@8.10.2/node_modules/@naturalcycles/js-lib/dist/abort.js
12
+ function r(e) {
13
+ return e ? i(e) : void 0;
14
+ }
15
+ function i(e) {
16
+ return typeof AbortSignal.timeout == "function" ? AbortSignal.timeout(e) : a(e);
17
+ }
18
+ function a(e) {
19
+ let t = new AbortController();
20
+ return setTimeout(() => {
21
+ t.abort(new DOMException("The operation was aborted due to timeout", "TimeoutError"));
22
+ }, e), t.signal;
23
+ }
24
+ function o(t) {
25
+ let n = t.filter(e);
26
+ return n.length ? s(n) : void 0;
27
+ }
28
+ function s(e) {
29
+ return e.length === 1 ? e[0] : typeof AbortSignal.any == "function" ? AbortSignal.any(e) : c(e);
30
+ }
31
+ function c(e) {
32
+ let t = new AbortController();
33
+ for (let n of e) if (n.aborted) return t.abort(n.reason), t.signal;
34
+ for (let n of e) n.addEventListener("abort", () => t.abort(n.reason), {
35
+ once: !0,
36
+ signal: t.signal
37
+ });
38
+ return t.signal;
39
+ }
40
+ //#endregion
41
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.87.0_undici@8.10.2/node_modules/@naturalcycles/js-lib/dist/types.js
42
+ var l = (...e) => void 0, u = Object.entries;
43
+ //#endregion
44
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.87.0_undici@8.10.2/node_modules/@naturalcycles/js-lib/dist/object/object.util.js
45
+ function d(e, t, n = {}) {
46
+ if (n.mutate) {
47
+ for (let n of Object.keys(e)) t.includes(n) || delete e[n];
48
+ return e;
49
+ }
50
+ let r = {};
51
+ for (let n of t) n in e && (r[n] = e[n]);
52
+ return r;
53
+ }
54
+ function f(e, t, n = {}) {
55
+ if (n.mutate) {
56
+ for (let n of t) delete e[n];
57
+ return e;
58
+ }
59
+ let r = {};
60
+ for (let n of Object.keys(e)) t.includes(n) || (r[n] = e[n]);
61
+ return r;
62
+ }
63
+ function ee(e, t = {}) {
64
+ return h(e, (e, t) => !!t, t);
65
+ }
66
+ function p(e, t = {}) {
67
+ return h(e, (e, t) => t != null, t);
68
+ }
69
+ function m(e, t = {}) {
70
+ return h(e, (e, t) => t !== void 0, t);
71
+ }
72
+ function h(e, t, n = {}) {
73
+ if (n.mutate) {
74
+ for (let [n, r] of u(e)) t(n, r, e) || delete e[n];
75
+ return e;
76
+ }
77
+ let r = {};
78
+ for (let [n, i] of u(e)) t(n, i, e) && (r[n] = i);
79
+ return r;
80
+ }
81
+ function g(e, t) {
82
+ let n = {};
83
+ for (let [r, i] of Object.entries(e)) n[t(r, i, e)] = i;
84
+ return n;
85
+ }
86
+ function _(e, ...n) {
87
+ for (let r of n) if (t(r)) for (let n of Object.keys(r)) n !== "__proto__" && n !== "constructor" && n !== "prototype" && (t(r[n]) ? (e[n] ||= {}, _(e[n], r[n])) : e[n] = r[n]);
88
+ return e;
89
+ }
90
+ //#endregion
91
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.87.0_undici@8.10.2/node_modules/@naturalcycles/js-lib/dist/env.js
92
+ function v() {
93
+ return !y();
94
+ }
95
+ function y() {
96
+ return typeof window < "u" && !!window?.document;
97
+ }
98
+ //#endregion
99
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.87.0_undici@8.10.2/node_modules/@naturalcycles/js-lib/dist/string/json.util.js
100
+ var te = /^\s*[{["\-\d]/;
101
+ function b(e, t) {
102
+ if (typeof e == "string" && e && te.test(e)) try {
103
+ return JSON.parse(e, t);
104
+ } catch {}
105
+ return e;
106
+ }
107
+ function x(e, t) {
108
+ try {
109
+ return JSON.parse(e, t);
110
+ } catch {
111
+ throw new ne({ text: e });
112
+ }
113
+ }
114
+ //#endregion
115
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.87.0_undici@8.10.2/node_modules/@naturalcycles/js-lib/dist/string/string.util.js
116
+ function S(e, t, n = "...") {
117
+ if (!e || e.length <= t) return e;
118
+ if (t <= n.length) return n;
119
+ let r = Math.round((t - n.length) / 2), i = e.length - Math.floor((t - n.length) / 2);
120
+ return e.slice(0, r) + n + e.slice(i);
121
+ }
122
+ //#endregion
123
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.87.0_undici@8.10.2/node_modules/@naturalcycles/js-lib/dist/error/error.util.js
124
+ function C(e, t = Error, n) {
125
+ let r;
126
+ return r = e instanceof t ? e : E(w(e), t), n && (r.data ||= {}, Object.assign(r.data, n)), r;
127
+ }
128
+ function w(e, t) {
129
+ let n;
130
+ return k(e) ? n = T(e) : (e = b(e), n = D(e) ? e.error : O(e) ? e : k(e) ? T(e) : {
131
+ name: "Error",
132
+ message: F(e),
133
+ data: {}
134
+ }), Object.assign(n.data, t), n;
135
+ }
136
+ function T(e) {
137
+ if (!(e instanceof Error) && O(e)) return e;
138
+ let t = {
139
+ name: e.name,
140
+ message: e.message,
141
+ data: { ...e.data }
142
+ };
143
+ return e.stack && (t.stack = e.stack), e.cause && (t.cause = w(e.cause)), t;
144
+ }
145
+ function E(e, t = Error) {
146
+ if (e instanceof t) return e;
147
+ let { name: n, cause: r } = e, i = new t(e.message, e.data, {
148
+ name: n,
149
+ cause: r
150
+ });
151
+ return e.stack && Object.defineProperty(i, "stack", { value: e.stack }), i instanceof j || (Object.defineProperties(i, {
152
+ name: {
153
+ value: n,
154
+ configurable: !0,
155
+ writable: !0
156
+ },
157
+ data: {
158
+ value: e.data,
159
+ writable: !0,
160
+ configurable: !0,
161
+ enumerable: !1
162
+ },
163
+ cause: {
164
+ value: r,
165
+ writable: !0,
166
+ configurable: !0,
167
+ enumerable: !0
168
+ }
169
+ }), Object.defineProperty(i.constructor, "name", {
170
+ value: n,
171
+ configurable: !0,
172
+ writable: !0
173
+ })), i;
174
+ }
175
+ function D(e) {
176
+ try {
177
+ return O(e?.error);
178
+ } catch {
179
+ return !1;
180
+ }
181
+ }
182
+ function O(e) {
183
+ try {
184
+ return !!e && typeof e == "object" && typeof e.name == "string" && typeof e.message == "string" && typeof e.data == "object";
185
+ } catch {
186
+ return !1;
187
+ }
188
+ }
189
+ function k(e) {
190
+ try {
191
+ return !!e && typeof e == "object" && typeof e.name == "string" && typeof e.message == "string";
192
+ } catch {
193
+ return !1;
194
+ }
195
+ }
196
+ function A(e, t) {
197
+ return t ? C(e, void 0, t) : e;
198
+ }
199
+ var j = class e extends Error {
200
+ data;
201
+ cause;
202
+ static of(t) {
203
+ return new e(t.message, t.data, {
204
+ name: t.name,
205
+ cause: t.cause
206
+ });
207
+ }
208
+ constructor(e, t = {}, n = {}) {
209
+ super(e);
210
+ let { name: r = v() ? this.constructor.name : "AppError", cause: i } = n;
211
+ Object.defineProperties(this, {
212
+ name: {
213
+ value: r,
214
+ configurable: !0,
215
+ writable: !0
216
+ },
217
+ data: {
218
+ value: t,
219
+ writable: !0,
220
+ configurable: !0,
221
+ enumerable: !1
222
+ }
223
+ }), i ? Object.defineProperty(this, "cause", {
224
+ value: w(i),
225
+ writable: !0,
226
+ configurable: !0,
227
+ enumerable: !0
228
+ }) : delete this.cause, Object.defineProperty(this.constructor, "name", {
229
+ value: r,
230
+ configurable: !0,
231
+ writable: !0
232
+ });
233
+ }
234
+ }, M = class extends j {
235
+ constructor(e, t, n) {
236
+ t.response && Object.defineProperty(t, "response", { enumerable: !1 }), super(e, t, {
237
+ ...n,
238
+ name: "HttpRequestError"
239
+ });
240
+ }
241
+ }, N = class extends j {
242
+ constructor(e, t) {
243
+ super(e, t, { name: "AssertionError" });
244
+ }
245
+ }, ne = class extends j {
246
+ constructor(e) {
247
+ let t = ["Failed to parse", e.text && S(e.text, 200)].filter(Boolean).join(": ");
248
+ super(t, e, { name: "JsonParseError" });
249
+ }
250
+ }, re = class extends j {
251
+ constructor(e, t, n) {
252
+ super(e, t, {
253
+ ...n,
254
+ name: "TimeoutError"
255
+ });
256
+ }
257
+ }, ie = class extends j {
258
+ constructor(e) {
259
+ super(e || "expected error was not thrown", {}, { name: "UnexpectedPassError" });
260
+ }
261
+ };
262
+ //#endregion
263
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.87.0_undici@8.10.2/node_modules/@naturalcycles/js-lib/dist/string/safeJsonStringify.js
264
+ function P(e, t, n, r) {
265
+ try {
266
+ return JSON.stringify(e, t, n);
267
+ } catch {
268
+ return JSON.stringify(e, ae(t, r), n);
269
+ }
270
+ }
271
+ function ae(e, t) {
272
+ let n = [], r = [];
273
+ return t ??= (e, t) => n[0] === t ? "[Circular ~]" : "[Circular ~." + r.slice(0, n.indexOf(t)).join(".") + "]", function(i, a) {
274
+ if (n.length > 0) {
275
+ let e = n.indexOf(this);
276
+ e === -1 ? (n.push(this), r.push(i)) : (n.splice(e + 1), r.splice(e, Infinity, i)), n.includes(a) && (a = t.call(this, i, a));
277
+ } else n.push(a);
278
+ return e == null ? a : e.call(this, i, a);
279
+ };
280
+ }
281
+ //#endregion
282
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.87.0_undici@8.10.2/node_modules/@naturalcycles/js-lib/dist/string/stringify.js
283
+ var oe = typeof globalThis.AggregateError == "function", se = P;
284
+ function F(e, t = {}) {
285
+ if (e === void 0) return "undefined";
286
+ if (e === null) return "null";
287
+ if (typeof e == "function") return "function";
288
+ if (typeof e == "symbol") return e.toString();
289
+ let n;
290
+ if (e = b(e), D(e)) return F(e.error, t);
291
+ if (e instanceof Error || k(e)) n = ce(e, t);
292
+ else if (typeof e == "string") n = e.trim() || "empty_string";
293
+ else if (typeof e == "number") n = String(e);
294
+ else {
295
+ e instanceof Map ? e = Object.fromEntries(e) : e instanceof Set && (e = Array.from(e));
296
+ try {
297
+ let { stringifyFn: r = se } = t;
298
+ n = r(e, void 0, 2);
299
+ } catch {
300
+ n = String(e);
301
+ }
302
+ }
303
+ if (n === void 0) return "undefined";
304
+ let { maxLen: r = 1e4 } = t;
305
+ return r && n.length > r ? S(n, r, `\n... ${Math.ceil(n.length / 1024)} Kb message truncated ...\n`) : n;
306
+ }
307
+ function ce(e, t) {
308
+ let { includeErrorCause: n = !0 } = t, r = [e.name, e.message].filter(Boolean).join(": ");
309
+ if (typeof e.code == "string" && (r += `\ncode: ${e.code}`), t.includeErrorData && O(e) && Object.keys(e.data).length && (r += "\n" + F(e.data, t)), t.includeErrorStack && e.stack) {
310
+ let t = r.split("\n").length;
311
+ r = [r, ...e.stack.split("\n").slice(t)].join("\n");
312
+ }
313
+ return oe && e instanceof AggregateError && e.errors.length && (r = [
314
+ r,
315
+ `${e.errors.length} error(s):`,
316
+ ...e.errors.map((e, n) => `${n + 1}. ${F(e, t)}`)
317
+ ].join("\n")), e.cause && n && (r = r + "\nCaused by: " + F(e.cause, t)), r;
318
+ }
319
+ //#endregion
320
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.87.0_undici@8.10.2/node_modules/@naturalcycles/js-lib/dist/error/assert.js
321
+ function le(e, t = Error) {
322
+ if (!(e instanceof t)) throw new N(`Expected to be instanceof ${t.name}, actual typeof: ${typeof e}`);
323
+ }
324
+ function I(e, t) {
325
+ if (!(e instanceof t)) throw e;
326
+ }
327
+ //#endregion
328
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.87.0_undici@8.10.2/node_modules/@naturalcycles/js-lib/dist/promise/pDelay.js
329
+ async function L(e, t) {
330
+ t?.aborted || await new Promise((n) => {
331
+ let r = setTimeout(i, e);
332
+ function i() {
333
+ clearTimeout(r), t?.removeEventListener("abort", i), n();
334
+ }
335
+ t?.addEventListener("abort", i);
336
+ });
337
+ }
338
+ //#endregion
339
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.87.0_undici@8.10.2/node_modules/@naturalcycles/js-lib/dist/datetime/time.util.js
340
+ function R(e, t = Date.now()) {
341
+ return z(t - e);
342
+ }
343
+ function z(e) {
344
+ if (e < 1e3) return `${Math.round(e)} ms`;
345
+ if (e < 1e4) return `${(e / 1e3).toFixed(2)} sec`;
346
+ let t = Math.floor(e / 1e3) % 60, n = Math.floor(e / 6e4) % 60, r = Math.floor(e / 36e5);
347
+ return r === 0 ? n === 0 ? `${t} sec` : `${n}m${t}s` : r < 24 ? `${r}h${n}m` : r < 48 ? `${Math.round(r + n / 60)}h` : `${Math.floor(r / 24)} days`;
348
+ }
349
+ //#endregion
350
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.87.0_undici@8.10.2/node_modules/@naturalcycles/js-lib/dist/number/number.util.js
351
+ function B(e, t, n) {
352
+ return e <= t ? t : e >= n ? n : e;
353
+ }
354
+ //#endregion
355
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.87.0_undici@8.10.2/node_modules/@naturalcycles/js-lib/dist/analytics/analytics.model.js
356
+ var V = "identify";
357
+ function H(e) {
358
+ return e.length <= 255 ? e : Array.from(e).slice(0, 255).join("");
359
+ }
360
+ var U = [
361
+ "utm_source",
362
+ "utm_medium",
363
+ "utm_campaign",
364
+ "utm_content",
365
+ "utm_term",
366
+ "utm_id",
367
+ "utm_source_platform",
368
+ "utm_campaign_id",
369
+ "utm_creative_format",
370
+ "utm_marketing_tactic"
371
+ ];
372
+ //#endregion
373
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.87.0_undici@8.10.2/node_modules/@naturalcycles/js-lib/dist/array/array.util.js
374
+ function W(e, t) {
375
+ let n = {};
376
+ for (let r of e) {
377
+ let e = t(r);
378
+ e && (n[e[0]] = e[1]);
379
+ }
380
+ return n;
381
+ }
382
+ //#endregion
383
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.87.0_undici@8.10.2/node_modules/@naturalcycles/js-lib/dist/promise/pTimeout.js
384
+ async function ue(e, t) {
385
+ let n = new AbortController(), { signal: r } = n;
386
+ if (!t.timeout) return await e(r);
387
+ let { timeout: i, name: a = e.name || "pTimeout function", onTimeout: o } = t, s = t.fakeError || /* @__PURE__ */ Error("TimeoutError");
388
+ return await new Promise(async (c, l) => {
389
+ let u = setTimeout(() => {
390
+ let e = new re(`"${a}" timed out after ${i} ms`, t.errorData);
391
+ if (e.stack = s.stack.replace("Error: TimeoutError", "TimeoutError: " + e.message), o) {
392
+ try {
393
+ c(o(e));
394
+ } catch (e) {
395
+ e.stack = s.stack.replace("Error: TimeoutError", e.name + ": " + e.message), l(A(e, t.errorData));
396
+ }
397
+ n.abort(e);
398
+ return;
399
+ }
400
+ l(e), n.abort(e);
401
+ }, i);
402
+ try {
403
+ c(await e(r));
404
+ } catch (e) {
405
+ l(e);
406
+ } finally {
407
+ clearTimeout(u);
408
+ }
409
+ });
410
+ }
411
+ //#endregion
412
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.87.0_undici@8.10.2/node_modules/@naturalcycles/js-lib/dist/string/url.util.js
413
+ function de(e, t) {
414
+ if (typeof e != "string") return null;
415
+ try {
416
+ return new URL(e, t || void 0);
417
+ } catch {
418
+ return null;
419
+ }
420
+ }
421
+ //#endregion
422
+ //#region ../../node_modules/.pnpm/@naturalcycles+js-lib@15.87.0_undici@8.10.2/node_modules/@naturalcycles/js-lib/dist/http/http.model.js
423
+ var fe = [
424
+ "GET",
425
+ "POST",
426
+ "PUT",
427
+ "PATCH",
428
+ "DELETE",
429
+ "HEAD"
430
+ ], pe = class e {
431
+ static VERSION = 5;
432
+ static userAgent = v() ? `fetcher/${this.VERSION}` : void 0;
433
+ constructor(e = {}) {
434
+ if (typeof globalThis.fetch != "function") throw TypeError("globalThis.fetch is not available");
435
+ this.cfg = this.normalizeCfg(e);
436
+ for (let e of fe) {
437
+ let t = e.toLowerCase();
438
+ this[`${t}Void`] = async (t, n) => await this.fetch({
439
+ url: t,
440
+ method: e,
441
+ responseType: "void",
442
+ ...n
443
+ }), e !== "HEAD" && (this[`${t}Text`] = async (t, n) => await this.fetch({
444
+ url: t,
445
+ method: e,
446
+ responseType: "text",
447
+ ...n
448
+ }), this[t] = async (t, n) => await this.fetch({
449
+ url: t,
450
+ method: e,
451
+ responseType: "json",
452
+ ...n
453
+ }));
454
+ }
455
+ }
456
+ onBeforeRequest(e) {
457
+ return (this.cfg.hooks.beforeRequest ||= []).push(e), this;
458
+ }
459
+ onAfterResponse(e) {
460
+ return (this.cfg.hooks.afterResponse ||= []).push(e), this;
461
+ }
462
+ onBeforeRetry(e) {
463
+ return (this.cfg.hooks.beforeRetry ||= []).push(e), this;
464
+ }
465
+ onError(e) {
466
+ return (this.cfg.hooks.onError ||= []).push(e), this;
467
+ }
468
+ onInit(e) {
469
+ return (this.cfg.hooks.init ||= []).push(e), this;
470
+ }
471
+ resetInit() {
472
+ this.initPromise = void 0, this.initGeneration++;
473
+ }
474
+ cfg;
475
+ initPromise;
476
+ initGeneration = 0;
477
+ static create(t = {}) {
478
+ return new e(t);
479
+ }
480
+ get;
481
+ post;
482
+ put;
483
+ patch;
484
+ delete;
485
+ getText;
486
+ postText;
487
+ putText;
488
+ patchText;
489
+ deleteText;
490
+ getVoid;
491
+ postVoid;
492
+ putVoid;
493
+ patchVoid;
494
+ deleteVoid;
495
+ headVoid;
496
+ async queryGraphQL(e) {
497
+ e = { ...e }, e.method ||= this.cfg.init.method;
498
+ let t = ee({
499
+ query: e.query,
500
+ variables: e.variables
501
+ });
502
+ e.method === "GET" && e.query.length > 1900 && (e.method = "POST"), e.method === "GET" ? e.searchParams = {
503
+ ...e.searchParams,
504
+ ...t
505
+ } : e.json = t;
506
+ let n = await this.doFetch(e);
507
+ if (n.err) throw n.err;
508
+ if (n.body.errors) {
509
+ let e = n.body.errors[0];
510
+ throw new M(e.message, {
511
+ ...t,
512
+ errors: n.body.errors,
513
+ response: n.fetchResponse,
514
+ responseStatusCode: n.statusCode,
515
+ requestUrl: n.req.fullUrl,
516
+ requestBaseUrl: this.cfg.baseUrl,
517
+ requestMethod: n.req.init.method,
518
+ requestSignature: n.signature,
519
+ requestName: n.req.requestName,
520
+ fetcherName: this.cfg.name,
521
+ requestDuration: Date.now() - n.req.started
522
+ });
523
+ }
524
+ let { data: r } = n.body;
525
+ return e.unwrapObject ? r[e.unwrapObject] : r;
526
+ }
527
+ async getBytes(e, t) {
528
+ return await this.fetch({
529
+ url: e,
530
+ responseType: "bytes",
531
+ ...t
532
+ });
533
+ }
534
+ async getReadableStream(e, t) {
535
+ return await this.fetch({
536
+ url: e,
537
+ responseType: "readableStream",
538
+ ...t
539
+ });
540
+ }
541
+ async fetch(e) {
542
+ let t = await this.doFetch(e);
543
+ if (t.err && (t.req.throwHttpErrors || t.fetchResponse?.ok !== !1)) throw t.err;
544
+ return t.body;
545
+ }
546
+ async fetchWithMeta(e) {
547
+ let t = await this.doFetch(e);
548
+ if (t.err) throw t.err;
549
+ return t;
550
+ }
551
+ async expectError(e) {
552
+ let t = await this.doFetch(e);
553
+ if (!t.err) throw new ie("Fetch was expected to error");
554
+ return le(t.err, M), t.err;
555
+ }
556
+ async tryFetch(e) {
557
+ let t = await this.doFetch(e);
558
+ return t.err ? (I(t.err, M), [t.err, null]) : [null, t.body];
559
+ }
560
+ async doFetch(t) {
561
+ let n = 0;
562
+ if (this.cfg.hooks.init) {
563
+ try {
564
+ await (this.initPromise ??= this.runInitHooks());
565
+ } catch (e) {
566
+ throw this.resetInit(), e;
567
+ }
568
+ n = this.initGeneration;
569
+ }
570
+ let i = this.normalizeOptions(t), { logger: a } = this.cfg, { init: { method: s } } = i, c = i.timeoutSeconds ? i.timeoutSeconds * 1e3 : void 0;
571
+ for (let e of this.cfg.hooks.beforeRequest || []) await e(i);
572
+ let l = i.fullUrl.includes("://") ? new URL(i.fullUrl) : void 0, u = [s, l ? this.getShortUrl(l) : i.fullUrl].join(" "), d = {
573
+ req: i,
574
+ retryStatus: {
575
+ retryAttempt: 0,
576
+ retryStopped: !1,
577
+ retryTimeout: i.retry.timeout
578
+ },
579
+ signature: u
580
+ };
581
+ for (; !d.retryStatus.retryStopped;) {
582
+ if (i.started = Date.now(), d.body = void 0, i.init.signal = o([r(c), t.signal]), i.logRequest) {
583
+ let { retryAttempt: e } = d.retryStatus;
584
+ a.log([
585
+ " >>",
586
+ u,
587
+ e && `try#${e + 1}/${i.retry.count + 1}`
588
+ ].filter(Boolean).join(" ")), i.logRequestBody && i.init.body && a.log(i.init.body);
589
+ }
590
+ try {
591
+ d.fetchResponse = await (i.overrideFetchFn || e.callNativeFetch)(i.fullUrl, i.init, i.fetchFn), d.ok = d.fetchResponse.ok, d.err = void 0;
592
+ } catch (e) {
593
+ d.err = C(e), d.ok = !1, d.fetchResponse = void 0;
594
+ }
595
+ if (d.statusFamily = this.getStatusFamily(d), d.statusCode = d.fetchResponse?.status, d.fetchResponse?.ok) try {
596
+ await ue(async () => await this.onOkResponse(d), {
597
+ timeout: c ?? 0,
598
+ name: "Fetcher.downloadBody"
599
+ });
600
+ } catch (e) {
601
+ d.err = C(e), d.ok = !1, await this.onNotOkResponse(d);
602
+ }
603
+ else await this.onNotOkResponse(d);
604
+ }
605
+ if (d.err) {
606
+ A(d.err, i.errorData), i.onError?.(d.err);
607
+ for (let e of this.cfg.hooks.onError || []) await e(d.err);
608
+ }
609
+ for (let e of this.cfg.hooks.afterResponse || []) await e(d);
610
+ return d.err && await this.detectStaleInit(t, d, n) ? await this.doFetch({
611
+ ...t,
612
+ [G]: !0
613
+ }) : d;
614
+ }
615
+ async detectStaleInit(e, t, n) {
616
+ let { shouldReinit: r, init: i } = this.cfg.hooks;
617
+ return !r || !i || e[G] || !await r(t) ? !1 : (n === this.initGeneration && this.resetInit(), !0);
618
+ }
619
+ async runInitHooks() {
620
+ for (let e of this.cfg.hooks.init || []) await e(this.cfg);
621
+ }
622
+ async onOkResponse(e) {
623
+ let { req: t } = e, { responseType: n } = e.req;
624
+ if (n === "json") {
625
+ if (e.fetchResponse.body) {
626
+ let n = await e.fetchResponse.text();
627
+ n ? (e.body = n, e.body = x(n, t.jsonReviver)) : e.body = {};
628
+ } else e.body = {};
629
+ } else if (n === "text") e.body = e.fetchResponse.body ? await e.fetchResponse.text() : "";
630
+ else if (n === "arrayBuffer") e.body = e.fetchResponse.body ? await e.fetchResponse.arrayBuffer() : /* @__PURE__ */ new ArrayBuffer(0);
631
+ else if (n === "bytes") e.body = e.fetchResponse.body ? new Uint8Array(await e.fetchResponse.arrayBuffer()) : /* @__PURE__ */ new Uint8Array();
632
+ else if (n === "blob") e.body = e.fetchResponse.body ? await e.fetchResponse.blob() : new Blob();
633
+ else if (n === "void") await e.fetchResponse.body?.cancel();
634
+ else if (n === "readableStream" && (e.body = e.fetchResponse.body, e.body === null)) throw Error("fetchResponse.body is null");
635
+ if (e.retryStatus.retryStopped = !0, t.logResponse) {
636
+ let { retryAttempt: n } = e.retryStatus, { logger: r } = this.cfg;
637
+ r.log([
638
+ " <<",
639
+ e.fetchResponse.status,
640
+ e.signature,
641
+ n && `try#${n + 1}/${t.retry.count + 1}`,
642
+ R(e.req.started)
643
+ ].filter(Boolean).join(" ")), t.logResponseBody && e.body !== void 0 && r.log(e.body);
644
+ }
645
+ }
646
+ static async callNativeFetch(e, t, n) {
647
+ return await (n || globalThis.fetch)(e, t);
648
+ }
649
+ async onNotOkResponse(e) {
650
+ let t;
651
+ if (!e.body && e.fetchResponse) try {
652
+ e.body = b(await e.fetchResponse.text());
653
+ } catch {}
654
+ t = e.err ? T(e.err) : e.body ? w(e.body) : {
655
+ name: "Error",
656
+ message: "Fetch failed",
657
+ data: {}
658
+ };
659
+ let n = e.fetchResponse?.status || 0;
660
+ e.statusFamily === 2 && (e.statusFamily = void 0, e.statusCode = void 0, n = 0), e.err = new M([e.statusCode, e.signature].filter(Boolean).join(" "), p({
661
+ response: e.fetchResponse,
662
+ responseStatusCode: n,
663
+ requestUrl: e.req.fullUrl,
664
+ requestBaseUrl: this.cfg.baseUrl || void 0,
665
+ requestMethod: e.req.init.method,
666
+ requestSignature: e.signature,
667
+ requestName: e.req.requestName,
668
+ fetcherName: this.cfg.name,
669
+ requestDuration: Date.now() - e.req.started
670
+ }), { cause: t }), await this.processRetry(e);
671
+ }
672
+ async processRetry(e) {
673
+ let { retryStatus: t } = e;
674
+ this.shouldRetry(e) || (t.retryStopped = !0);
675
+ for (let t of this.cfg.hooks.beforeRetry || []) await t(e);
676
+ let { count: n, timeoutMultiplier: r, timeoutMax: i } = e.req.retry;
677
+ if (t.retryAttempt >= n && (t.retryStopped = !0), e.err && (!t.retryStopped || e.req.logResponse) && this.cfg.logger.error([
678
+ " <<",
679
+ e.fetchResponse?.status || 0,
680
+ e.signature,
681
+ n && (t.retryAttempt || !t.retryStopped) && `try#${t.retryAttempt + 1}/${n + 1}`,
682
+ R(e.req.started)
683
+ ].filter(Boolean).join(" ") + "\n", F(e.err.cause || e.err)), t.retryStopped) return;
684
+ t.retryAttempt++;
685
+ let a = this.getRetryTimeout(e);
686
+ if (a === null) {
687
+ this.cfg.logger.warn(`${e.signature} server-indicated delay exceeds maxRetryAfter, will not retry`), t.retryStopped = !0;
688
+ return;
689
+ }
690
+ t.retryTimeout = B(t.retryTimeout * r, 0, i), e.req.debug && this.cfg.logger.log(` .. ${e.signature} waiting ${z(a)}`), await L(a, e.req.signal), e.req.signal?.aborted && (t.retryStopped = !0);
691
+ }
692
+ getRetryTimeout(e) {
693
+ let t = 0;
694
+ if (e.fetchResponse && [429, 503].includes(e.fetchResponse.status)) {
695
+ let n = e.fetchResponse.headers.get("retry-after") ?? e.fetchResponse.headers.get("x-ratelimit-reset");
696
+ if (n) {
697
+ let e = Number(n);
698
+ if (e) t = e > 10 ** 9 ? e * 1e3 - Date.now() : e * 1e3;
699
+ else {
700
+ let e = new Date(n);
701
+ Number.isNaN(e.getTime()) || (t = e.getTime() - Date.now());
702
+ }
703
+ this.cfg.logger.log(`retry-after: ${n}`), t || this.cfg.logger.warn("retry-after could not be parsed");
704
+ }
705
+ }
706
+ if (t) return t > e.req.retry.maxRetryAfter ? null : Math.max(0, t);
707
+ let n = Math.random() * 500;
708
+ return e.retryStatus.retryTimeout + n;
709
+ }
710
+ shouldRetry(e) {
711
+ if (e.req.signal?.aborted) return !1;
712
+ let { retryPost: t, retry3xx: n, retry4xx: r, retry5xx: i } = e.req, { method: a } = e.req.init;
713
+ if (a === "POST" && !t) return !1;
714
+ let { statusFamily: o } = e, s = e.fetchResponse?.status || 0;
715
+ return o === 5 && !i ? !1 : [408, 429].includes(s) ? !0 : !(o === 4 && !r || o === 3 && !n || e.err?.cause?.cause?.message?.includes("unexpected redirect"));
716
+ }
717
+ getStatusFamily(e) {
718
+ let t = e.fetchResponse?.status;
719
+ if (t) {
720
+ if (t >= 500) return 5;
721
+ if (t >= 400) return 4;
722
+ if (t >= 300) return 3;
723
+ if (t >= 200) return 2;
724
+ if (t >= 100) return 1;
725
+ }
726
+ }
727
+ getShortUrl(e) {
728
+ let { baseUrl: t } = this.cfg;
729
+ e.password && (e = new URL(e.toString()), e.password = "[redacted]");
730
+ let n = e.toString();
731
+ return this.cfg.logWithSearchParams || (n = n.split("?")[0]), !this.cfg.logWithBaseUrl && t && n.startsWith(t) && (n = n.slice(t.length)), n;
732
+ }
733
+ normalizeCfg(t) {
734
+ let { debug: n = !1, logger: r = console } = t;
735
+ t.baseUrl?.endsWith("/") && (r.warn(`Fetcher: baseUrl should not end with slash: ${t.baseUrl}`), t.baseUrl = t.baseUrl.slice(0, t.baseUrl.length - 1));
736
+ let i = _({
737
+ baseUrl: "",
738
+ name: this.getFetcherName(t),
739
+ inputUrl: "",
740
+ responseType: "json",
741
+ searchParams: {},
742
+ timeoutSeconds: 30,
743
+ retryPost: !1,
744
+ retry3xx: !1,
745
+ retry4xx: !1,
746
+ retry5xx: !0,
747
+ logger: r,
748
+ debug: n,
749
+ logRequest: n,
750
+ logRequestBody: n,
751
+ logResponse: n,
752
+ logResponseBody: n,
753
+ logWithBaseUrl: v(),
754
+ logWithSearchParams: !0,
755
+ retry: { ...ge },
756
+ init: {
757
+ method: t.method || "GET",
758
+ headers: p({
759
+ "user-agent": e.userAgent,
760
+ ...t.headers
761
+ }),
762
+ credentials: t.credentials,
763
+ redirect: t.redirect,
764
+ dispatcher: t.dispatcher,
765
+ keepalive: t.keepalive
766
+ },
767
+ hooks: {},
768
+ throwHttpErrors: !0,
769
+ errorData: {}
770
+ }, f(t, [
771
+ "method",
772
+ "credentials",
773
+ "headers",
774
+ "redirect",
775
+ "logger",
776
+ "name",
777
+ "keepalive"
778
+ ]));
779
+ return i.init.headers = g(i.init.headers, (e) => e.toLowerCase()), i;
780
+ }
781
+ getFetcherName(e) {
782
+ let { name: t } = e;
783
+ if (!t && e.baseUrl) {
784
+ let n = de(e.baseUrl);
785
+ n && (t = n.hostname);
786
+ }
787
+ return t;
788
+ }
789
+ normalizeOptions(t) {
790
+ let n = {
791
+ ...d(this.cfg, [
792
+ "timeoutSeconds",
793
+ "retryPost",
794
+ "retry3xx",
795
+ "retry4xx",
796
+ "retry5xx",
797
+ "responseType",
798
+ "jsonReviver",
799
+ "logRequest",
800
+ "logRequestBody",
801
+ "logResponse",
802
+ "logResponseBody",
803
+ "debug",
804
+ "throwHttpErrors",
805
+ "errorData",
806
+ "fetchFn",
807
+ "overrideFetchFn"
808
+ ]),
809
+ started: Date.now(),
810
+ ...f(t, [
811
+ "method",
812
+ "headers",
813
+ "credentials"
814
+ ]),
815
+ inputUrl: t.url || "",
816
+ fullUrl: t.url || "",
817
+ retry: {
818
+ ...this.cfg.retry,
819
+ ...m(t.retry || {})
820
+ },
821
+ init: _({
822
+ ...this.cfg.init,
823
+ headers: {
824
+ ...this.cfg.init.headers,
825
+ "user-agent": e.userAgent
826
+ },
827
+ method: t.method || this.cfg.init.method,
828
+ credentials: t.credentials || this.cfg.init.credentials,
829
+ redirect: t.redirect || this.cfg.init.redirect || "follow",
830
+ keepalive: t.keepalive ?? this.cfg.init.keepalive
831
+ }, { headers: g(t.headers || {}, (e) => e.toLowerCase()) })
832
+ };
833
+ p(n.init.headers, { mutate: !0 });
834
+ let r = t.baseUrl || this.cfg.baseUrl;
835
+ if (r) {
836
+ let { inputUrl: e } = n;
837
+ e.startsWith("/") && (this.cfg.logger.warn("Fetcher: url should not start with / when baseUrl is specified"), e = e.slice(1)), n.fullUrl = `${r}/${e}`;
838
+ }
839
+ let i = m({
840
+ ...this.cfg.searchParams,
841
+ ...t.searchParams
842
+ });
843
+ if (Object.keys(i).length) {
844
+ let e = new URLSearchParams(i).toString();
845
+ n.fullUrl += (n.fullUrl.includes("?") ? "&" : "?") + e;
846
+ }
847
+ return t.json === void 0 ? t.text === void 0 ? t.form ? t.form instanceof URLSearchParams || t.form instanceof FormData ? n.init.body = t.form : (n.init.body = new URLSearchParams(t.form), n.init.headers["content-type"] ||= "application/x-www-form-urlencoded") : t.body !== void 0 && (n.init.body = t.body) : (n.init.body = t.text, n.init.headers["content-type"] ||= "text/plain") : (n.init.body = JSON.stringify(t.json), n.init.headers["content-type"] ||= "application/json"), n.init.headers.accept ||= he[n.responseType], n;
848
+ }
849
+ };
850
+ function me(e = {}) {
851
+ return pe.create(e);
852
+ }
853
+ var G = Symbol("reinitAttempted"), he = {
854
+ text: "text/plain",
855
+ json: "application/json",
856
+ void: "*/*",
857
+ readableStream: "application/octet-stream",
858
+ arrayBuffer: "application/octet-stream",
859
+ bytes: "application/octet-stream",
860
+ blob: "application/octet-stream"
861
+ }, ge = {
862
+ count: 2,
863
+ timeout: 1e3,
864
+ timeoutMax: 3e4,
865
+ timeoutMultiplier: 2,
866
+ maxRetryAfter: 6e5
867
+ }, _e = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
868
+ function ve(e = 21) {
869
+ let t = "", n = globalThis.crypto.getRandomValues(new Uint8Array(e));
870
+ for (; e--;) t += _e[n[e] & 63];
871
+ return t;
872
+ }
873
+ var ye = (e) => globalThis.crypto.getRandomValues(new Uint8Array(e));
874
+ function be(e, t = 21) {
875
+ return xe(e, t, ye);
876
+ }
877
+ function xe(e, t, n) {
878
+ let r = (2 << Math.log2(e.length - 1)) - 1, i = -~(1.6 * r * t / e.length);
879
+ return (a = t) => {
880
+ let o = "";
881
+ for (;;) {
882
+ let t = n(i), s = i;
883
+ for (; s--;) if (o += e[t[s] & r] || "", o.length === a) return o;
884
+ }
885
+ };
886
+ }
887
+ //#endregion
888
+ //#region src/analytics/analyticsClient.ts
889
+ var Se = 3800, Ce = "utm_", we = [
890
+ "dclid",
891
+ "fbclid",
892
+ "gclid",
893
+ "ko_click_id",
894
+ "li_fat_id",
895
+ "msclkid",
896
+ "sccid",
897
+ "ttclid",
898
+ "twclid",
899
+ "wbraid"
900
+ ], Te = be("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 16), Ee = class {
901
+ constructor(e) {
902
+ let t = e.localStorageKeyPrefix || "nca";
903
+ this.cfg = {
904
+ onError: l,
905
+ firstTouchUrl: "",
906
+ isEnabled: () => !0,
907
+ getCommonProps: () => ({}),
908
+ flushInterval: 5e3,
909
+ maxBatchSize: 50,
910
+ maxBatchBytes: 6e4,
911
+ maxQueueSize: 1e3,
912
+ maxRetryBackoff: 6e5,
913
+ requestTimeout: 3e4,
914
+ persistQueue: !0,
915
+ maxPersistedAge: 864e5,
916
+ localStorageKeyPrefix: t,
917
+ logger: console,
918
+ debug: !1,
919
+ ...e
920
+ }, this.identity = new K(this.cfg.identity), this.firstTouchFetcher = me({
921
+ logger: this.cfg.logger,
922
+ retryPost: !0,
923
+ timeoutSeconds: 10
924
+ }), !v() && (this.restoreOrphanedQueues(), globalThis.addEventListener("pagehide", this.handlePageHide), document.addEventListener("visibilitychange", this.handleVisibilityChange));
925
+ }
926
+ cfg;
927
+ firstTouchFetcher;
928
+ identity;
929
+ tabId = ve(10);
930
+ queue = [];
931
+ flushTimer;
932
+ isFlushing = !1;
933
+ consecutiveFailures = 0;
934
+ retryAfter = 0;
935
+ hasUpdatedAcquisitionProps = !1;
936
+ eventListeners = /* @__PURE__ */ new Set();
937
+ handlePageHide = () => {
938
+ this.flushNow();
939
+ };
940
+ handleVisibilityChange = () => {
941
+ document.visibilityState === "hidden" && this.flushNow();
942
+ };
943
+ init() {
944
+ this.canTrack() && (this.ensureAcquisitionProps(), this.replayFromStub());
945
+ }
946
+ track(e, t) {
947
+ let n = this.enqueue(e, t);
948
+ n && this.notifyEventListeners(n);
949
+ }
950
+ replayFromStub() {
951
+ let e = globalThis.analyticsClient;
952
+ if (e && "q" in e) {
953
+ for (let t of e.q) try {
954
+ if (t.method === "identify") this.identify(t.args[0]);
955
+ else {
956
+ let e = this.enqueue(t.args[0], t.args[1], t.ts);
957
+ e && this.notifyEventListeners(e);
958
+ }
959
+ } catch (e) {
960
+ this.cfg.logger.warn("[analytics] could not replay a stubbed call", e);
961
+ }
962
+ e.q.length = 0;
963
+ }
964
+ }
965
+ onEvent(e) {
966
+ return this.eventListeners.add(e), () => this.eventListeners.delete(e);
967
+ }
968
+ notifyEventListeners(e) {
969
+ if (!this.eventListeners.size) return;
970
+ let t = e.userId || this.identity.getDistinctId(), n = {
971
+ ...e,
972
+ props: { ...e.props }
973
+ };
974
+ for (let e of this.eventListeners) try {
975
+ e(n, t);
976
+ } catch (e) {
977
+ this.cfg.logger.warn("[analytics] onEvent listener threw", e);
978
+ }
979
+ }
980
+ identify(e) {
981
+ if (!this.canTrack()) return;
982
+ let t = this.identity.getDistinctId();
983
+ this.identity.identify(e), t !== e && (this.enqueue(V, { anon_distinct_id: t }), this.flush(), this.sendFirstTouch());
984
+ }
985
+ enqueue(e, t, n) {
986
+ if (!this.canTrack()) return;
987
+ this.ensureAcquisitionProps();
988
+ let r = {
989
+ id: Te(),
990
+ name: e,
991
+ ts: n || Date.now(),
992
+ props: {
993
+ ...this.getDefaultProps(),
994
+ ...this.cfg.getCommonProps(),
995
+ ...t
996
+ },
997
+ userId: this.identity.getDistinctId()
998
+ };
999
+ return this.cfg.debug && this.cfg.logger.log(`[analytics] ${r.name}`, r.props), this.queue.push(r), this.queue.length > this.cfg.maxQueueSize && (this.queue.shift(), this.cfg.logger.warn("[analytics] queue overflow, dropped the oldest event")), this.persistQueue(), this.queue.length >= this.cfg.maxBatchSize && !this.consecutiveFailures ? this.flush() : this.scheduleFlush(), r;
1000
+ }
1001
+ canTrack() {
1002
+ return !v() && this.cfg.isEnabled();
1003
+ }
1004
+ reset() {
1005
+ this.clearPendingEvents(), this.identity.reset(), this.hasUpdatedAcquisitionProps = !1;
1006
+ }
1007
+ async flush() {
1008
+ if (!(v() || this.isFlushing)) {
1009
+ this.isFlushing = !0, this.clearFlushTimer();
1010
+ try {
1011
+ for (; this.queue.length;) for (let e of this.prepareBatches()) {
1012
+ if (await this.sendBatch(e) === "retry") {
1013
+ this.consecutiveFailures++, this.scheduleFlush();
1014
+ return;
1015
+ }
1016
+ this.removeFromQueue(e.events), this.consecutiveFailures = 0, this.retryAfter = 0;
1017
+ }
1018
+ } finally {
1019
+ this.isFlushing = !1;
1020
+ }
1021
+ }
1022
+ }
1023
+ flushNow() {
1024
+ if (this.queue.length) {
1025
+ this.clearFlushTimer();
1026
+ for (let e of this.prepareBatches()) this.postBatch(e, !0).catch((e) => {
1027
+ this.cfg.logger.warn("[analytics] lifecycle batch failed to send; retained for retry", e);
1028
+ });
1029
+ this.scheduleFlush();
1030
+ }
1031
+ }
1032
+ destroy() {
1033
+ this.clearFlushTimer(), !v() && (globalThis.removeEventListener("pagehide", this.handlePageHide), document.removeEventListener("visibilitychange", this.handleVisibilityChange));
1034
+ }
1035
+ ensureAcquisitionProps() {
1036
+ this.hasUpdatedAcquisitionProps || (this.hasUpdatedAcquisitionProps = !0, this.identity.updateAcquisitionProps(), this.sendFirstTouch());
1037
+ }
1038
+ async sendFirstTouch() {
1039
+ let { firstTouchUrl: e } = this.cfg;
1040
+ if (!e) return;
1041
+ let t = this.identity.getFirstTouchProps();
1042
+ if (!t) return;
1043
+ let n = {
1044
+ clientId: this.cfg.clientId,
1045
+ userId: this.identity.getDistinctId(),
1046
+ props: t
1047
+ }, r = await this.firstTouchFetcher.doFetch({
1048
+ url: e,
1049
+ method: "POST",
1050
+ text: P(n),
1051
+ responseType: "void"
1052
+ });
1053
+ if (r.err) try {
1054
+ this.cfg.onError(A(r.err, { firstTouch: !0 }));
1055
+ } catch (e) {
1056
+ this.cfg.logger.warn("[analytics] onError hook threw", e);
1057
+ }
1058
+ }
1059
+ getDefaultProps() {
1060
+ let e = document.referrer, t = new URL(globalThis.location.href);
1061
+ return {
1062
+ ...e && { referrer: e },
1063
+ current_url: globalThis.location.href,
1064
+ screen_height: globalThis.screen.height,
1065
+ screen_width: globalThis.screen.width,
1066
+ ...this.identity.getAcquisitionProps(),
1067
+ ...q(t),
1068
+ ...J(t, we)
1069
+ };
1070
+ }
1071
+ clearPendingEvents() {
1072
+ this.clearFlushTimer(), this.queue = [], this.consecutiveFailures = 0, this.retryAfter = 0, this.persistQueue();
1073
+ }
1074
+ async sendBatch(e) {
1075
+ let t;
1076
+ try {
1077
+ t = await this.postBatch(e, !1, AbortSignal.timeout?.(this.cfg.requestTimeout));
1078
+ } catch (e) {
1079
+ return this.cfg.logger.warn("[analytics] batch failed to send, will retry", e), "retry";
1080
+ }
1081
+ if (t.ok) return "ok";
1082
+ if (t.status === 429 || t.status >= 500) {
1083
+ let e = Number(t.headers.get("retry-after"));
1084
+ return e && (this.retryAfter = e * 1e3), this.cfg.logger.warn(`[analytics] batch rejected with ${t.status}, will retry`), "retry";
1085
+ }
1086
+ this.cfg.logger.error(`[analytics] batch rejected with ${t.status}, dropping ${e.events.length} event(s)`);
1087
+ try {
1088
+ this.cfg.onError(new j("batch dropped on a non-retryable status", {
1089
+ status: t.status,
1090
+ eventCount: e.events.length
1091
+ }));
1092
+ } catch (e) {
1093
+ this.cfg.logger.warn("[analytics] onError hook threw", e);
1094
+ }
1095
+ return "drop";
1096
+ }
1097
+ async postBatch(e, t, n) {
1098
+ return fetch(this.cfg.url, {
1099
+ method: "POST",
1100
+ headers: { "content-type": "text/plain" },
1101
+ body: e.body,
1102
+ ...t && { keepalive: !0 },
1103
+ signal: n
1104
+ });
1105
+ }
1106
+ prepareBatches() {
1107
+ let e = [], t, n = this.identity.getDistinctId();
1108
+ for (let r of this.queue) {
1109
+ let i = Y(P(r)), a = t?.events.length === this.cfg.maxBatchSize, o = +!!t?.events.length, s = !!t && t.bodyBytes + o + i > this.cfg.maxBatchBytes;
1110
+ t && (a || s) && (e.push(this.finalizeBatch(t)), t = void 0), t ||= this.createPendingBatch(n);
1111
+ let c = +!!t.events.length;
1112
+ t.events.push(r), t.bodyBytes += c + i;
1113
+ }
1114
+ return t?.events.length && e.push(this.finalizeBatch(t)), e;
1115
+ }
1116
+ createPendingBatch(e) {
1117
+ let t = Date.now(), n = {
1118
+ sentAt: t,
1119
+ clientId: this.cfg.clientId,
1120
+ userId: e,
1121
+ events: []
1122
+ };
1123
+ return {
1124
+ sentAt: t,
1125
+ userId: e,
1126
+ events: [],
1127
+ bodyBytes: Y(JSON.stringify(n))
1128
+ };
1129
+ }
1130
+ finalizeBatch(e) {
1131
+ let t = {
1132
+ sentAt: e.sentAt,
1133
+ clientId: this.cfg.clientId,
1134
+ userId: e.userId,
1135
+ events: e.events
1136
+ };
1137
+ return {
1138
+ events: e.events,
1139
+ body: P(t)
1140
+ };
1141
+ }
1142
+ restoreOrphanedQueues() {
1143
+ if (this.cfg.persistQueue) try {
1144
+ let e = `${this.cfg.localStorageKeyPrefix}.q.`, t = [];
1145
+ for (let n = 0; n < localStorage.length; n++) {
1146
+ let r = localStorage.key(n);
1147
+ r?.startsWith(e) && t.push(r);
1148
+ }
1149
+ if (!t.length) return;
1150
+ let n = Date.now() - this.cfg.maxPersistedAge;
1151
+ for (let e of t) try {
1152
+ let t = JSON.parse(localStorage.getItem(e) || "[]");
1153
+ localStorage.removeItem(e), this.queue.push(...t.filter((e) => e.ts >= n));
1154
+ } catch {
1155
+ localStorage.removeItem(e);
1156
+ }
1157
+ this.queue.length > this.cfg.maxQueueSize && this.queue.splice(0, this.queue.length - this.cfg.maxQueueSize), this.queue.length && (this.persistQueue(), this.scheduleFlush());
1158
+ } catch {}
1159
+ }
1160
+ scheduleFlush() {
1161
+ if (this.flushTimer || v()) return;
1162
+ let e = this.cfg.flushInterval;
1163
+ this.consecutiveFailures && (e = Math.min(this.cfg.flushInterval * 2 ** this.consecutiveFailures, this.cfg.maxRetryBackoff), e = Math.max(e, this.retryAfter)), this.flushTimer = setTimeout(() => {
1164
+ this.flushTimer = void 0, this.flush();
1165
+ }, e);
1166
+ }
1167
+ clearFlushTimer() {
1168
+ this.flushTimer &&= (clearTimeout(this.flushTimer), void 0);
1169
+ }
1170
+ removeFromQueue(e) {
1171
+ let t = new Set(e.map((e) => e.id));
1172
+ this.queue = this.queue.filter((e) => !t.has(e.id)), this.persistQueue();
1173
+ }
1174
+ persistQueue() {
1175
+ if (this.cfg.persistQueue) try {
1176
+ this.queue.length ? localStorage.setItem(this.queueKey, P(this.queue)) : localStorage.removeItem(this.queueKey);
1177
+ } catch {}
1178
+ }
1179
+ get queueKey() {
1180
+ return `${this.cfg.localStorageKeyPrefix}.q.${this.tabId}`;
1181
+ }
1182
+ }, K = class {
1183
+ constructor(e) {
1184
+ this.cfg = {
1185
+ onError: l,
1186
+ cookieDomain: "",
1187
+ expireDays: 365,
1188
+ secureCookie: !1,
1189
+ generateDistinctId: (e) => `$device:${e}`,
1190
+ ...e
1191
+ };
1192
+ }
1193
+ cfg;
1194
+ memoryEntry = {};
1195
+ hasRefreshedExpiry = !1;
1196
+ getDistinctId() {
1197
+ return this.ensureIdentity().distinct_id;
1198
+ }
1199
+ getDeviceId() {
1200
+ return this.ensureIdentity().$device_id;
1201
+ }
1202
+ getProperty(e) {
1203
+ return this.loadEntry()[e];
1204
+ }
1205
+ getAcquisitionProps() {
1206
+ let e = this.loadEntry(), t = h(e, (e) => String(e).startsWith(Ce)), { firstTouch: n } = e;
1207
+ return n && (t.initial_referrer = n.referrer), t;
1208
+ }
1209
+ getFirstTouchProps() {
1210
+ let { firstTouch: e } = this.loadEntry();
1211
+ if (e) return {
1212
+ ...e.utms,
1213
+ initial_referrer: e.referrer
1214
+ };
1215
+ }
1216
+ identify(e) {
1217
+ let t = this.ensureIdentity();
1218
+ t.$device_id ||= t.distinct_id, t.user_id = e, t.distinct_id = t.user_id, this.saveEntry(t);
1219
+ }
1220
+ reset() {
1221
+ let e = crypto.randomUUID();
1222
+ this.saveEntry({
1223
+ distinct_id: this.cfg.generateDistinctId(e),
1224
+ $device_id: e
1225
+ });
1226
+ }
1227
+ updateAcquisitionProps() {
1228
+ if (v()) return;
1229
+ let e = this.loadEntry(), t = new URL(globalThis.location.href);
1230
+ Object.assign(e, q(t)), e.firstTouch ||= { referrer: De() }, e.firstTouch.utms ||= Oe(t), this.saveEntry(e);
1231
+ }
1232
+ ensureIdentity() {
1233
+ let e = this.loadEntry();
1234
+ if (e.distinct_id) this.refreshExpiry(e);
1235
+ else {
1236
+ let t = crypto.randomUUID();
1237
+ e.distinct_id = this.cfg.generateDistinctId(t), e.$device_id = t, this.saveEntry(e);
1238
+ }
1239
+ return e;
1240
+ }
1241
+ refreshExpiry(e) {
1242
+ this.hasRefreshedExpiry || this.cfg.persistence !== "cookie" || this.saveEntry(e);
1243
+ }
1244
+ loadEntry() {
1245
+ try {
1246
+ let e = this.cfg.persistence === "cookie" ? X(this.cfg.persistenceKey) : localStorage.getItem(this.cfg.persistenceKey);
1247
+ e && (this.memoryEntry = JSON.parse(e));
1248
+ } catch {}
1249
+ return this.memoryEntry;
1250
+ }
1251
+ saveEntry(e) {
1252
+ this.memoryEntry = e, this.hasRefreshedExpiry = !0;
1253
+ let t = 0;
1254
+ try {
1255
+ let n = JSON.stringify(e);
1256
+ if (t = n.length, this.cfg.persistence === "cookie") {
1257
+ if (t = this.cookieLength(e), t > Se) {
1258
+ this.reportError(new $("cookie exceeded the length limit", { bytes: t }));
1259
+ return;
1260
+ }
1261
+ Q(this.cfg.persistenceKey, n, this.cfg.expireDays, this.cfg.cookieDomain, this.cfg.secureCookie);
1262
+ let r = Z(this.cfg.persistenceKey);
1263
+ r.includes(n) || this.reportError(new $("cookie write did not persist", {
1264
+ bytes: t,
1265
+ hadPreviousCookie: r.length > 0
1266
+ }));
1267
+ } else localStorage.setItem(this.cfg.persistenceKey, n);
1268
+ } catch (e) {
1269
+ this.reportError(A(e, { bytes: t }));
1270
+ }
1271
+ }
1272
+ cookieLength(e) {
1273
+ return this.cfg.persistenceKey.length + encodeURIComponent(JSON.stringify(e)).length;
1274
+ }
1275
+ reportError(e) {
1276
+ try {
1277
+ this.cfg.onError(e);
1278
+ } catch {}
1279
+ }
1280
+ };
1281
+ function q(e) {
1282
+ let t = {};
1283
+ for (let n of U) {
1284
+ let r = e.searchParams.get(n);
1285
+ r && (t[n] = H(r));
1286
+ }
1287
+ return t;
1288
+ }
1289
+ function De() {
1290
+ return H(document.referrer) || null;
1291
+ }
1292
+ function Oe(e) {
1293
+ let t = W(U, (t) => {
1294
+ let n = e.searchParams.get(t);
1295
+ return [`initial_${t}`, n ? H(n) : null];
1296
+ });
1297
+ if (!n(p(t))) return t;
1298
+ }
1299
+ function J(e, t) {
1300
+ return Object.fromEntries(t.flatMap((t) => {
1301
+ let n = e.searchParams.get(t);
1302
+ return n ? [[t, n]] : [];
1303
+ }));
1304
+ }
1305
+ var ke = new TextEncoder();
1306
+ function Y(e) {
1307
+ return ke.encode(e).byteLength;
1308
+ }
1309
+ function X(e) {
1310
+ return e ? Z(e)[0] ?? null : null;
1311
+ }
1312
+ function Z(e) {
1313
+ let t = `${e}=`, n = [];
1314
+ for (let e of document.cookie.split(";")) {
1315
+ for (; e.startsWith(" ");) e = e.slice(1);
1316
+ e.startsWith(t) && n.push(decodeURIComponent(e.slice(t.length)));
1317
+ }
1318
+ return n;
1319
+ }
1320
+ function Q(e, t, n, r, i) {
1321
+ let a = [`${e}=${encodeURIComponent(t)}`];
1322
+ n && a.push(`expires=${new Date(Date.now() + n * 24 * 3600 * 1e3).toUTCString()}`), a.push("path=/"), r && a.push(`domain=${r}`), i && a.push("secure");
1323
+ let o = a.join("; ");
1324
+ return document.cookie = o, o;
1325
+ }
1326
+ var $ = class extends j {
1327
+ constructor(e, t) {
1328
+ super(e, t, { name: "AnalyticsClientError" });
1329
+ }
1330
+ };
1331
+ //#endregion
1332
+ export { Ee as AnalyticsClient, $ as AnalyticsClientError, K as AnalyticsIdentity, X as getCookie, Q as setCookie };
1333
+
1334
+ //# sourceMappingURL=analyticsClient.js.map