@fctc/interface-logic 1.5.1 → 1.5.3

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,3072 @@
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 __pow = Math.pow;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __spreadValues = (a, b) => {
10
+ for (var prop in b || (b = {}))
11
+ if (__hasOwnProp.call(b, prop))
12
+ __defNormalProp(a, prop, b[prop]);
13
+ if (__getOwnPropSymbols)
14
+ for (var prop of __getOwnPropSymbols(b)) {
15
+ if (__propIsEnum.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ }
18
+ return a;
19
+ };
20
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
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/configs/axios-client.ts
43
+ import axios from "axios";
44
+
45
+ // src/utils/format.ts
46
+ import moment from "moment";
47
+
48
+ // src/utils/domain/py_tokenizer.ts
49
+ var TokenizerError = class extends Error {
50
+ };
51
+ var directMap = {
52
+ "\\": "\\",
53
+ '"': '"',
54
+ "'": "'",
55
+ a: "\x07",
56
+ b: "\b",
57
+ f: "\f",
58
+ n: "\n",
59
+ r: "\r",
60
+ t: " ",
61
+ v: "\v"
62
+ };
63
+ function decodeStringLiteral(str, unicode) {
64
+ const out = [];
65
+ let code;
66
+ for (let i = 0; i < str.length; ++i) {
67
+ if (str[i] !== "\\") {
68
+ out.push(str[i]);
69
+ continue;
70
+ }
71
+ const escape = str[i + 1];
72
+ if (escape in directMap) {
73
+ out.push(directMap[escape]);
74
+ ++i;
75
+ continue;
76
+ }
77
+ switch (escape) {
78
+ case "\n":
79
+ ++i;
80
+ continue;
81
+ case "N":
82
+ if (!unicode) {
83
+ break;
84
+ }
85
+ throw new TokenizerError("SyntaxError: \\N{} escape not implemented");
86
+ case "u":
87
+ if (!unicode) {
88
+ break;
89
+ }
90
+ const uni = str.slice(i + 2, i + 6);
91
+ if (!/[0-9a-f]{4}/i.test(uni)) {
92
+ throw new TokenizerError(
93
+ [
94
+ "SyntaxError: (unicode error) 'unicodeescape' codec",
95
+ " can't decode bytes in position ",
96
+ i,
97
+ "-",
98
+ i + 4,
99
+ ": truncated \\uXXXX escape"
100
+ ].join("")
101
+ );
102
+ }
103
+ code = parseInt(uni, 16);
104
+ out.push(String.fromCharCode(code));
105
+ i += 5;
106
+ continue;
107
+ case "U":
108
+ if (!unicode) {
109
+ break;
110
+ }
111
+ throw new TokenizerError("SyntaxError: \\U escape not implemented");
112
+ case "x":
113
+ const hex = str.slice(i + 2, i + 4);
114
+ if (!/[0-9a-f]{2}/i.test(hex)) {
115
+ if (!unicode) {
116
+ throw new TokenizerError("ValueError: invalid \\x escape");
117
+ }
118
+ throw new TokenizerError(
119
+ [
120
+ "SyntaxError: (unicode error) 'unicodeescape'",
121
+ " codec can't decode bytes in position ",
122
+ i,
123
+ "-",
124
+ i + 2,
125
+ ": truncated \\xXX escape"
126
+ ].join("")
127
+ );
128
+ }
129
+ code = parseInt(hex, 16);
130
+ out.push(String.fromCharCode(code));
131
+ i += 3;
132
+ continue;
133
+ default:
134
+ if (!/[0-8]/.test(escape)) {
135
+ break;
136
+ }
137
+ const r = /[0-8]{1,3}/g;
138
+ r.lastIndex = i + 1;
139
+ const m = r.exec(str);
140
+ if (!m) break;
141
+ const oct = m[0];
142
+ code = parseInt(oct, 8);
143
+ out.push(String.fromCharCode(code));
144
+ i += oct.length;
145
+ continue;
146
+ }
147
+ out.push("\\");
148
+ }
149
+ return out.join("");
150
+ }
151
+ var constants = /* @__PURE__ */ new Set(["None", "False", "True"]);
152
+ var comparators = [
153
+ "in",
154
+ "not",
155
+ "not in",
156
+ "is",
157
+ "is not",
158
+ "<",
159
+ "<=",
160
+ ">",
161
+ ">=",
162
+ "<>",
163
+ "!=",
164
+ "=="
165
+ ];
166
+ var binaryOperators = [
167
+ "or",
168
+ "and",
169
+ "|",
170
+ "^",
171
+ "&",
172
+ "<<",
173
+ ">>",
174
+ "+",
175
+ "-",
176
+ "*",
177
+ "/",
178
+ "//",
179
+ "%",
180
+ "~",
181
+ "**",
182
+ "."
183
+ ];
184
+ var unaryOperators = ["-"];
185
+ var symbols = /* @__PURE__ */ new Set([
186
+ ...["(", ")", "[", "]", "{", "}", ":", ","],
187
+ ...["if", "else", "lambda", "="],
188
+ ...comparators,
189
+ ...binaryOperators,
190
+ ...unaryOperators
191
+ ]);
192
+ function group(...args) {
193
+ return "(" + args.join("|") + ")";
194
+ }
195
+ var Name = "[a-zA-Z_]\\w*";
196
+ var Whitespace = "[ \\f\\t]*";
197
+ var DecNumber = "\\d+(L|l)?";
198
+ var IntNumber = DecNumber;
199
+ var Exponent = "[eE][+-]?\\d+";
200
+ var PointFloat = group(`\\d+\\.\\d*(${Exponent})?`, `\\.\\d+(${Exponent})?`);
201
+ var FloatNumber = group(PointFloat, `\\d+${Exponent}`);
202
+ var Number2 = group(FloatNumber, IntNumber);
203
+ var Operator = group(
204
+ "\\*\\*=?",
205
+ ">>=?",
206
+ "<<=?",
207
+ "<>",
208
+ "!=",
209
+ "//=?",
210
+ "[+\\-*/%&|^=<>]=?",
211
+ "~"
212
+ );
213
+ var Bracket = "[\\[\\]\\(\\)\\{\\}]";
214
+ var Special = "[:;.,`@]";
215
+ var Funny = group(Operator, Bracket, Special);
216
+ var ContStr = group(
217
+ "([uU])?'([^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*)'",
218
+ '([uU])?"([^\\n"\\\\]*(?:\\\\.[^\\n"\\\\]*)*)"'
219
+ );
220
+ var PseudoToken = Whitespace + group(Number2, Funny, ContStr, Name);
221
+ var NumberPattern = new RegExp("^" + Number2 + "$");
222
+ var StringPattern = new RegExp("^" + ContStr + "$");
223
+ var NamePattern = new RegExp("^" + Name + "$");
224
+ var strip = new RegExp("^" + Whitespace);
225
+ function tokenize(str) {
226
+ const tokens = [];
227
+ const max = str.length;
228
+ let start = 0;
229
+ let end = 0;
230
+ const pseudoprog = new RegExp(PseudoToken, "g");
231
+ while (pseudoprog.lastIndex < max) {
232
+ const pseudomatch = pseudoprog.exec(str);
233
+ if (!pseudomatch) {
234
+ if (/^\s+$/.test(str.slice(end))) {
235
+ break;
236
+ }
237
+ throw new TokenizerError(
238
+ "Failed to tokenize <<" + str + ">> at index " + (end || 0) + "; parsed so far: " + tokens
239
+ );
240
+ }
241
+ if (pseudomatch.index > end) {
242
+ if (str.slice(end, pseudomatch.index).trim()) {
243
+ throw new TokenizerError("Invalid expression");
244
+ }
245
+ }
246
+ start = pseudomatch.index;
247
+ end = pseudoprog.lastIndex;
248
+ let token = str.slice(start, end).replace(strip, "");
249
+ if (NumberPattern.test(token)) {
250
+ tokens.push({
251
+ type: 0,
252
+ value: parseFloat(token)
253
+ });
254
+ } else if (StringPattern.test(token)) {
255
+ const m = StringPattern.exec(token);
256
+ if (!m) throw new TokenizerError("Invalid string match");
257
+ tokens.push({
258
+ type: 1,
259
+ value: decodeStringLiteral(
260
+ m[3] !== void 0 ? m[3] : m[5],
261
+ !!(m[2] || m[4])
262
+ )
263
+ });
264
+ } else if (symbols.has(token)) {
265
+ if (token === "in" && tokens.length > 0 && tokens[tokens.length - 1].value === "not") {
266
+ token = "not in";
267
+ tokens.pop();
268
+ } else if (token === "not" && tokens.length > 0 && tokens[tokens.length - 1].value === "is") {
269
+ token = "is not";
270
+ tokens.pop();
271
+ }
272
+ tokens.push({
273
+ type: 2,
274
+ value: token
275
+ });
276
+ } else if (constants.has(token)) {
277
+ tokens.push({
278
+ type: 4,
279
+ value: token
280
+ });
281
+ } else if (NamePattern.test(token)) {
282
+ tokens.push({
283
+ type: 3,
284
+ value: token
285
+ });
286
+ } else {
287
+ throw new TokenizerError("Invalid expression");
288
+ }
289
+ }
290
+ return tokens;
291
+ }
292
+
293
+ // src/utils/domain/py_parser.ts
294
+ var ParserError = class extends Error {
295
+ };
296
+ var chainedOperators = new Set(comparators);
297
+ var infixOperators = /* @__PURE__ */ new Set([...binaryOperators, ...comparators]);
298
+ function bp(symbol) {
299
+ switch (symbol) {
300
+ case "=":
301
+ return 10;
302
+ case "if":
303
+ return 20;
304
+ case "in":
305
+ case "not in":
306
+ case "is":
307
+ case "is not":
308
+ case "<":
309
+ case "<=":
310
+ case ">":
311
+ case ">=":
312
+ case "<>":
313
+ case "==":
314
+ case "!=":
315
+ return 60;
316
+ case "or":
317
+ return 30;
318
+ case "and":
319
+ return 40;
320
+ case "not":
321
+ return 50;
322
+ case "|":
323
+ return 70;
324
+ case "^":
325
+ return 80;
326
+ case "&":
327
+ return 90;
328
+ case "<<":
329
+ case ">>":
330
+ return 100;
331
+ case "+":
332
+ case "-":
333
+ return 110;
334
+ case "*":
335
+ case "/":
336
+ case "//":
337
+ case "%":
338
+ return 120;
339
+ case "**":
340
+ return 140;
341
+ case ".":
342
+ case "(":
343
+ case "[":
344
+ return 150;
345
+ default:
346
+ return 0;
347
+ }
348
+ }
349
+ function bindingPower(token) {
350
+ return token.type === 2 ? bp(token.value) : 0;
351
+ }
352
+ function isSymbol(token, value) {
353
+ return token.type === 2 && token.value === value;
354
+ }
355
+ function parsePrefix(current, tokens) {
356
+ switch (current.type) {
357
+ case 0:
358
+ return { type: 0, value: current.value };
359
+ case 1:
360
+ return { type: 1, value: current.value };
361
+ case 4:
362
+ if (current.value === "None") {
363
+ return {
364
+ type: 3
365
+ /* None */
366
+ };
367
+ } else {
368
+ return { type: 2, value: current.value === "True" };
369
+ }
370
+ case 3:
371
+ return { type: 5, value: current.value };
372
+ case 2:
373
+ switch (current.value) {
374
+ case "-":
375
+ case "+":
376
+ case "~":
377
+ return {
378
+ type: 6,
379
+ op: current.value,
380
+ right: _parse(tokens, 130)
381
+ };
382
+ case "not":
383
+ return {
384
+ type: 6,
385
+ op: current.value,
386
+ right: _parse(tokens, 50)
387
+ };
388
+ case "(":
389
+ const content = [];
390
+ let isTuple = false;
391
+ while (tokens[0] && !isSymbol(tokens[0], ")")) {
392
+ content.push(_parse(tokens, 0));
393
+ if (tokens[0]) {
394
+ if (tokens[0] && isSymbol(tokens[0], ",")) {
395
+ isTuple = true;
396
+ tokens.shift();
397
+ } else if (!isSymbol(tokens[0], ")")) {
398
+ throw new ParserError("parsing error");
399
+ }
400
+ } else {
401
+ throw new ParserError("parsing error");
402
+ }
403
+ }
404
+ if (!tokens[0] || !isSymbol(tokens[0], ")")) {
405
+ throw new ParserError("parsing error");
406
+ }
407
+ tokens.shift();
408
+ isTuple = isTuple || content.length === 0;
409
+ return isTuple ? { type: 10, value: content } : content[0];
410
+ case "[":
411
+ const value = [];
412
+ while (tokens[0] && !isSymbol(tokens[0], "]")) {
413
+ value.push(_parse(tokens, 0));
414
+ if (tokens[0]) {
415
+ if (isSymbol(tokens[0], ",")) {
416
+ tokens.shift();
417
+ } else if (!isSymbol(tokens[0], "]")) {
418
+ throw new ParserError("parsing error");
419
+ }
420
+ }
421
+ }
422
+ if (!tokens[0] || !isSymbol(tokens[0], "]")) {
423
+ throw new ParserError("parsing error");
424
+ }
425
+ tokens.shift();
426
+ return { type: 4, value };
427
+ case "{":
428
+ const dict = {};
429
+ while (tokens[0] && !isSymbol(tokens[0], "}")) {
430
+ const key = _parse(tokens, 0);
431
+ if (key.type !== 1 && key.type !== 0 || !tokens[0] || !isSymbol(tokens[0], ":")) {
432
+ throw new ParserError("parsing error");
433
+ }
434
+ tokens.shift();
435
+ const val = _parse(tokens, 0);
436
+ dict[key.value] = val;
437
+ if (isSymbol(tokens[0], ",")) {
438
+ tokens.shift();
439
+ }
440
+ }
441
+ if (!tokens.shift()) {
442
+ throw new ParserError("parsing error");
443
+ }
444
+ return { type: 11, value: dict };
445
+ default:
446
+ throw new ParserError("Token cannot be parsed");
447
+ }
448
+ default:
449
+ throw new ParserError("Token cannot be parsed");
450
+ }
451
+ }
452
+ function parseInfix(left, current, tokens) {
453
+ switch (current.type) {
454
+ case 2:
455
+ if (infixOperators.has(current.value)) {
456
+ let right = _parse(tokens, bindingPower(current));
457
+ if (current.value === "and" || current.value === "or") {
458
+ return {
459
+ type: 14,
460
+ op: current.value,
461
+ left,
462
+ right
463
+ };
464
+ } else if (current.value === ".") {
465
+ if (right.type === 5) {
466
+ return {
467
+ type: 15,
468
+ obj: left,
469
+ key: right.value
470
+ };
471
+ } else {
472
+ throw new ParserError("invalid obj lookup");
473
+ }
474
+ }
475
+ let op = {
476
+ type: 7,
477
+ op: current.value,
478
+ left,
479
+ right
480
+ };
481
+ while (chainedOperators.has(current.value) && tokens[0] && tokens[0].type === 2 && chainedOperators.has(tokens[0].value)) {
482
+ const nextToken = tokens.shift();
483
+ op = {
484
+ type: 14,
485
+ op: "and",
486
+ left: op,
487
+ right: {
488
+ type: 7,
489
+ op: nextToken.value,
490
+ left: right,
491
+ right: _parse(tokens, bindingPower(nextToken))
492
+ }
493
+ };
494
+ right = op.right;
495
+ }
496
+ return op;
497
+ }
498
+ switch (current.value) {
499
+ case "(":
500
+ const args = [];
501
+ const kwargs = {};
502
+ while (tokens[0] && !isSymbol(tokens[0], ")")) {
503
+ const arg = _parse(tokens, 0);
504
+ if (arg.type === 9) {
505
+ kwargs[arg.name.value] = arg.value;
506
+ } else {
507
+ args.push(arg);
508
+ }
509
+ if (tokens[0] && isSymbol(tokens[0], ",")) {
510
+ tokens.shift();
511
+ }
512
+ }
513
+ if (!tokens[0] || !isSymbol(tokens[0], ")")) {
514
+ throw new ParserError("parsing error");
515
+ }
516
+ tokens.shift();
517
+ return { type: 8, fn: left, args, kwargs };
518
+ case "=":
519
+ if (left.type === 5) {
520
+ return {
521
+ type: 9,
522
+ name: left,
523
+ value: _parse(tokens, 10)
524
+ };
525
+ }
526
+ break;
527
+ case "[":
528
+ const key = _parse(tokens);
529
+ if (!tokens[0] || !isSymbol(tokens[0], "]")) {
530
+ throw new ParserError("parsing error");
531
+ }
532
+ tokens.shift();
533
+ return {
534
+ type: 12,
535
+ target: left,
536
+ key
537
+ };
538
+ case "if":
539
+ const condition = _parse(tokens);
540
+ if (!tokens[0] || !isSymbol(tokens[0], "else")) {
541
+ throw new ParserError("parsing error");
542
+ }
543
+ tokens.shift();
544
+ const ifFalse = _parse(tokens);
545
+ return {
546
+ type: 13,
547
+ condition,
548
+ ifTrue: left,
549
+ ifFalse
550
+ };
551
+ default:
552
+ break;
553
+ }
554
+ }
555
+ throw new ParserError("Token cannot be parsed");
556
+ }
557
+ function _parse(tokens, bp2 = 0) {
558
+ const token = tokens.shift();
559
+ if (!token) {
560
+ throw new ParserError("Unexpected end of input");
561
+ }
562
+ let expr = parsePrefix(token, tokens);
563
+ while (tokens[0] && bindingPower(tokens[0]) > bp2) {
564
+ expr = parseInfix(expr, tokens.shift(), tokens);
565
+ }
566
+ return expr;
567
+ }
568
+ function parse(tokens) {
569
+ if (tokens.length) {
570
+ return _parse(tokens, 0);
571
+ }
572
+ throw new ParserError("Missing token");
573
+ }
574
+ function parseArgs(args, spec) {
575
+ const last = args[args.length - 1];
576
+ const unnamedArgs = typeof last === "object" ? args.slice(0, -1) : args;
577
+ const kwargs = typeof last === "object" ? last : {};
578
+ for (const [index, val] of unnamedArgs.entries()) {
579
+ kwargs[spec[index]] = val;
580
+ }
581
+ return kwargs;
582
+ }
583
+
584
+ // src/utils/domain/py_date.ts
585
+ var AssertionError = class extends Error {
586
+ };
587
+ var ValueError = class extends Error {
588
+ };
589
+ var NotSupportedError = class extends Error {
590
+ };
591
+ function fmt2(n) {
592
+ return String(n).padStart(2, "0");
593
+ }
594
+ function fmt4(n) {
595
+ return String(n).padStart(4, "0");
596
+ }
597
+ function divmod(a, b, fn) {
598
+ let mod = a % b;
599
+ if (mod > 0 && b < 0 || mod < 0 && b > 0) {
600
+ mod += b;
601
+ }
602
+ return fn(Math.floor(a / b), mod);
603
+ }
604
+ function assert(bool, message = "AssertionError") {
605
+ if (!bool) {
606
+ throw new AssertionError(message);
607
+ }
608
+ }
609
+ var DAYS_IN_MONTH = [
610
+ null,
611
+ 31,
612
+ 28,
613
+ 31,
614
+ 30,
615
+ 31,
616
+ 30,
617
+ 31,
618
+ 31,
619
+ 30,
620
+ 31,
621
+ 30,
622
+ 31
623
+ ];
624
+ var DAYS_BEFORE_MONTH = [null];
625
+ for (let dbm = 0, i = 1; i < DAYS_IN_MONTH.length; ++i) {
626
+ DAYS_BEFORE_MONTH.push(dbm);
627
+ dbm += DAYS_IN_MONTH[i];
628
+ }
629
+ function daysInMonth(year, month) {
630
+ if (month === 2 && isLeap(year)) {
631
+ return 29;
632
+ }
633
+ return DAYS_IN_MONTH[month];
634
+ }
635
+ function isLeap(year) {
636
+ return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
637
+ }
638
+ function daysBeforeYear(year) {
639
+ const y = year - 1;
640
+ return y * 365 + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400);
641
+ }
642
+ function daysBeforeMonth(year, month) {
643
+ const postLeapFeb = month > 2 && isLeap(year);
644
+ return DAYS_BEFORE_MONTH[month] + (postLeapFeb ? 1 : 0);
645
+ }
646
+ function ymd2ord(year, month, day) {
647
+ const dim = daysInMonth(year, month);
648
+ if (!(1 <= day && day <= dim)) {
649
+ throw new ValueError(`day must be in 1..${dim}`);
650
+ }
651
+ return daysBeforeYear(year) + daysBeforeMonth(year, month) + day;
652
+ }
653
+ var DI400Y = daysBeforeYear(401);
654
+ var DI100Y = daysBeforeYear(101);
655
+ var DI4Y = daysBeforeYear(5);
656
+ function ord2ymd(n) {
657
+ --n;
658
+ let n400 = 0, n100 = 0, n4 = 0, n1 = 0, n0 = 0;
659
+ divmod(n, DI400Y, (_n400, n2) => {
660
+ n400 = _n400;
661
+ divmod(n2, DI100Y, (_n100, n3) => {
662
+ n100 = _n100;
663
+ divmod(n3, DI4Y, (_n4, n5) => {
664
+ n4 = _n4;
665
+ divmod(n5, 365, (_n1, n6) => {
666
+ n1 = _n1;
667
+ n0 = n6;
668
+ });
669
+ });
670
+ });
671
+ });
672
+ n = n0;
673
+ const year = n400 * 400 + 1 + n100 * 100 + n4 * 4 + n1;
674
+ if (n1 === 4 || n100 === 100) {
675
+ assert(n0 === 0);
676
+ return {
677
+ year: year - 1,
678
+ month: 12,
679
+ day: 31
680
+ };
681
+ }
682
+ const leapyear = n1 === 3 && (n4 !== 24 || n100 === 3);
683
+ assert(leapyear === isLeap(year));
684
+ let month = n + 50 >> 5;
685
+ let preceding = DAYS_BEFORE_MONTH[month] + (month > 2 && leapyear ? 1 : 0);
686
+ if (preceding > n) {
687
+ --month;
688
+ preceding -= DAYS_IN_MONTH[month] + (month === 2 && leapyear ? 1 : 0);
689
+ }
690
+ n -= preceding;
691
+ return {
692
+ year,
693
+ month,
694
+ day: n + 1
695
+ };
696
+ }
697
+ function tmxxx(year, month, day, hour, minute, second, microsecond) {
698
+ hour = hour || 0;
699
+ minute = minute || 0;
700
+ second = second || 0;
701
+ microsecond = microsecond || 0;
702
+ if (microsecond < 0 || microsecond > 999999) {
703
+ divmod(microsecond, 1e6, (carry, ms) => {
704
+ microsecond = ms;
705
+ second += carry;
706
+ });
707
+ }
708
+ if (second < 0 || second > 59) {
709
+ divmod(second, 60, (carry, s) => {
710
+ second = s;
711
+ minute += carry;
712
+ });
713
+ }
714
+ if (minute < 0 || minute > 59) {
715
+ divmod(minute, 60, (carry, m) => {
716
+ minute = m;
717
+ hour += carry;
718
+ });
719
+ }
720
+ if (hour < 0 || hour > 23) {
721
+ divmod(hour, 24, (carry, h) => {
722
+ hour = h;
723
+ day += carry;
724
+ });
725
+ }
726
+ if (month < 1 || month > 12) {
727
+ divmod(month - 1, 12, (carry, m) => {
728
+ month = m + 1;
729
+ year += carry;
730
+ });
731
+ }
732
+ const dim = daysInMonth(year, month);
733
+ if (day < 1 || day > dim) {
734
+ if (day === 0) {
735
+ --month;
736
+ if (month > 0) {
737
+ day = daysInMonth(year, month);
738
+ } else {
739
+ --year;
740
+ month = 12;
741
+ day = 31;
742
+ }
743
+ } else if (day === dim + 1) {
744
+ ++month;
745
+ day = 1;
746
+ if (month > 12) {
747
+ month = 1;
748
+ ++year;
749
+ }
750
+ } else {
751
+ const r = ord2ymd(ymd2ord(year, month, 1) + (day - 1));
752
+ year = r.year;
753
+ month = r.month;
754
+ day = r.day;
755
+ }
756
+ }
757
+ return {
758
+ year,
759
+ month,
760
+ day,
761
+ hour,
762
+ minute,
763
+ second,
764
+ microsecond
765
+ };
766
+ }
767
+ var PyDate = class _PyDate {
768
+ constructor(year, month, day) {
769
+ this.year = year;
770
+ this.month = month;
771
+ this.day = day;
772
+ }
773
+ static today() {
774
+ return this.convertDate(/* @__PURE__ */ new Date());
775
+ }
776
+ static convertDate(date) {
777
+ const year = date.getFullYear();
778
+ const month = date.getMonth() + 1;
779
+ const day = date.getDate();
780
+ return new _PyDate(year, month, day);
781
+ }
782
+ static create(...args) {
783
+ const { year, month, day } = parseArgs(args, ["year", "month", "day"]);
784
+ return new _PyDate(year, month, day);
785
+ }
786
+ add(timedelta) {
787
+ const s = tmxxx(this.year, this.month, this.day + timedelta.days, 0, 0, 0);
788
+ return new _PyDate(s.year, s.month, s.day);
789
+ }
790
+ isEqual(other) {
791
+ if (!(other instanceof _PyDate)) {
792
+ return false;
793
+ }
794
+ return this.year === other.year && this.month === other.month && this.day === other.day;
795
+ }
796
+ strftime(format) {
797
+ return format.replace(/%([A-Za-z])/g, (m, c) => {
798
+ switch (c) {
799
+ case "Y":
800
+ return fmt4(this.year);
801
+ case "m":
802
+ return fmt2(this.month);
803
+ case "d":
804
+ return fmt2(this.day);
805
+ default:
806
+ throw new ValueError(`No known conversion for ${m}`);
807
+ }
808
+ });
809
+ }
810
+ substract(other) {
811
+ if (other instanceof PyTimeDelta) {
812
+ return this.add(other.negate());
813
+ }
814
+ if (other instanceof _PyDate) {
815
+ return PyTimeDelta.create(this.toordinal() - other.toordinal());
816
+ }
817
+ throw new NotSupportedError();
818
+ }
819
+ toJSON() {
820
+ return this.strftime("%Y-%m-%d");
821
+ }
822
+ toordinal() {
823
+ return ymd2ord(this.year, this.month, this.day);
824
+ }
825
+ };
826
+ var PyDateTime = class _PyDateTime {
827
+ constructor(year, month, day, hour, minute, second, microsecond) {
828
+ this.year = year;
829
+ this.month = month;
830
+ this.day = day;
831
+ this.hour = hour;
832
+ this.minute = minute;
833
+ this.second = second;
834
+ this.microsecond = microsecond;
835
+ }
836
+ static now() {
837
+ return this.convertDate(/* @__PURE__ */ new Date());
838
+ }
839
+ static convertDate(date) {
840
+ const year = date.getFullYear();
841
+ const month = date.getMonth() + 1;
842
+ const day = date.getDate();
843
+ const hour = date.getHours();
844
+ const minute = date.getMinutes();
845
+ const second = date.getSeconds();
846
+ return new _PyDateTime(year, month, day, hour, minute, second, 0);
847
+ }
848
+ static create(...args) {
849
+ const namedArgs = parseArgs(args, [
850
+ "year",
851
+ "month",
852
+ "day",
853
+ "hour",
854
+ "minute",
855
+ "second",
856
+ "microsecond"
857
+ ]);
858
+ const year = namedArgs.year;
859
+ const month = namedArgs.month;
860
+ const day = namedArgs.day;
861
+ const hour = namedArgs.hour || 0;
862
+ const minute = namedArgs.minute || 0;
863
+ const second = namedArgs.second || 0;
864
+ const ms = namedArgs.microsecond / 1e3 || 0;
865
+ return new _PyDateTime(year, month, day, hour, minute, second, ms);
866
+ }
867
+ static combine(...args) {
868
+ const { date, time } = parseArgs(args, ["date", "time"]);
869
+ return _PyDateTime.create(
870
+ date.year,
871
+ date.month,
872
+ date.day,
873
+ time.hour,
874
+ time.minute,
875
+ time.second
876
+ );
877
+ }
878
+ add(timedelta) {
879
+ const s = tmxxx(
880
+ this.year,
881
+ this.month,
882
+ this.day + timedelta.days,
883
+ this.hour,
884
+ this.minute,
885
+ this.second + timedelta.seconds,
886
+ this.microsecond + timedelta.microseconds
887
+ );
888
+ return new _PyDateTime(
889
+ s.year,
890
+ s.month,
891
+ s.day,
892
+ s.hour,
893
+ s.minute,
894
+ s.second,
895
+ s.microsecond
896
+ );
897
+ }
898
+ isEqual(other) {
899
+ if (!(other instanceof _PyDateTime)) {
900
+ return false;
901
+ }
902
+ return this.year === other.year && this.month === other.month && this.day === other.day && this.hour === other.hour && this.minute === other.minute && this.second === other.second && this.microsecond === other.microsecond;
903
+ }
904
+ strftime(format) {
905
+ return format.replace(/%([A-Za-z])/g, (m, c) => {
906
+ switch (c) {
907
+ case "Y":
908
+ return fmt4(this.year);
909
+ case "m":
910
+ return fmt2(this.month);
911
+ case "d":
912
+ return fmt2(this.day);
913
+ case "H":
914
+ return fmt2(this.hour);
915
+ case "M":
916
+ return fmt2(this.minute);
917
+ case "S":
918
+ return fmt2(this.second);
919
+ default:
920
+ throw new ValueError(`No known conversion for ${m}`);
921
+ }
922
+ });
923
+ }
924
+ substract(timedelta) {
925
+ return this.add(timedelta.negate());
926
+ }
927
+ toJSON() {
928
+ return this.strftime("%Y-%m-%d %H:%M:%S");
929
+ }
930
+ to_utc() {
931
+ const d = new Date(
932
+ this.year,
933
+ this.month - 1,
934
+ this.day,
935
+ this.hour,
936
+ this.minute,
937
+ this.second
938
+ );
939
+ const timedelta = PyTimeDelta.create({ minutes: d.getTimezoneOffset() });
940
+ return this.add(timedelta);
941
+ }
942
+ };
943
+ var PyTime = class _PyTime extends PyDate {
944
+ constructor(hour, minute, second) {
945
+ const now = /* @__PURE__ */ new Date();
946
+ const year = now.getFullYear();
947
+ const month = now.getMonth() + 1;
948
+ const day = now.getDate();
949
+ super(year, month, day);
950
+ this.hour = hour;
951
+ this.minute = minute;
952
+ this.second = second;
953
+ this.hour = hour;
954
+ this.minute = minute;
955
+ this.second = second;
956
+ }
957
+ static create(...args) {
958
+ const namedArgs = parseArgs(args, ["hour", "minute", "second"]);
959
+ const hour = namedArgs.hour || 0;
960
+ const minute = namedArgs.minute || 0;
961
+ const second = namedArgs.second || 0;
962
+ return new _PyTime(hour, minute, second);
963
+ }
964
+ strftime(format) {
965
+ return format.replace(/%([A-Za-z])/g, (m, c) => {
966
+ switch (c) {
967
+ case "Y":
968
+ return fmt4(this.year);
969
+ case "m":
970
+ return fmt2(this.month);
971
+ case "d":
972
+ return fmt2(this.day);
973
+ case "H":
974
+ return fmt2(this.hour);
975
+ case "M":
976
+ return fmt2(this.minute);
977
+ case "S":
978
+ return fmt2(this.second);
979
+ default:
980
+ throw new ValueError(`No known conversion for ${m}`);
981
+ }
982
+ });
983
+ }
984
+ toJSON() {
985
+ return this.strftime("%H:%M:%S");
986
+ }
987
+ };
988
+ var DAYS_IN_YEAR = [
989
+ 31,
990
+ 59,
991
+ 90,
992
+ 120,
993
+ 151,
994
+ 181,
995
+ 212,
996
+ 243,
997
+ 273,
998
+ 304,
999
+ 334,
1000
+ 366
1001
+ ];
1002
+ var TIME_PERIODS = ["hour", "minute", "second"];
1003
+ var PERIODS = ["year", "month", "day", ...TIME_PERIODS];
1004
+ var RELATIVE_KEYS = "years months weeks days hours minutes seconds microseconds leapdays".split(
1005
+ " "
1006
+ );
1007
+ var ABSOLUTE_KEYS = "year month day hour minute second microsecond weekday nlyearday yearday".split(
1008
+ " "
1009
+ );
1010
+ var argsSpec = ["dt1", "dt2"];
1011
+ var PyRelativeDelta = class _PyRelativeDelta {
1012
+ static create(...args) {
1013
+ const params = parseArgs(args, argsSpec);
1014
+ if ("dt1" in params) {
1015
+ throw new Error("relativedelta(dt1, dt2) is not supported for now");
1016
+ }
1017
+ for (const period of PERIODS) {
1018
+ if (period in params) {
1019
+ const val = params[period];
1020
+ assert(val >= 0, `${period} ${val} is out of range`);
1021
+ }
1022
+ }
1023
+ for (const key of RELATIVE_KEYS) {
1024
+ params[key] = params[key] || 0;
1025
+ }
1026
+ for (const key of ABSOLUTE_KEYS) {
1027
+ params[key] = key in params ? params[key] : null;
1028
+ }
1029
+ params.days += 7 * params.weeks;
1030
+ let yearDay = 0;
1031
+ if (params.nlyearday) {
1032
+ yearDay = params.nlyearday;
1033
+ } else if (params.yearday) {
1034
+ yearDay = params.yearday;
1035
+ if (yearDay > 59) {
1036
+ params.leapDays = -1;
1037
+ }
1038
+ }
1039
+ if (yearDay) {
1040
+ for (let monthIndex = 0; monthIndex < DAYS_IN_YEAR.length; monthIndex++) {
1041
+ if (yearDay <= DAYS_IN_YEAR[monthIndex]) {
1042
+ params.month = monthIndex + 1;
1043
+ if (monthIndex === 0) {
1044
+ params.day = yearDay;
1045
+ } else {
1046
+ params.day = yearDay - DAYS_IN_YEAR[monthIndex - 1];
1047
+ }
1048
+ break;
1049
+ }
1050
+ }
1051
+ }
1052
+ return new _PyRelativeDelta(params);
1053
+ }
1054
+ static add(date, delta) {
1055
+ if (!(date instanceof PyDate || date instanceof PyDateTime)) {
1056
+ throw new NotSupportedError();
1057
+ }
1058
+ const s = tmxxx(
1059
+ (delta.year || date.year) + delta.years,
1060
+ (delta.month || date.month) + delta.months,
1061
+ delta.day || date.day,
1062
+ delta.hour || (date instanceof PyDateTime ? date.hour : 0),
1063
+ delta.minute || (date instanceof PyDateTime ? date.minute : 0),
1064
+ delta.second || (date instanceof PyDateTime ? date.second : 0),
1065
+ delta.microseconds || (date instanceof PyDateTime ? date.microsecond : 0)
1066
+ );
1067
+ const newDateTime = new PyDateTime(
1068
+ s.year,
1069
+ s.month,
1070
+ s.day,
1071
+ s.hour,
1072
+ s.minute,
1073
+ s.second,
1074
+ s.microsecond
1075
+ );
1076
+ let leapDays = 0;
1077
+ if (delta.leapDays && newDateTime.month > 2 && isLeap(newDateTime.year)) {
1078
+ leapDays = delta.leapDays;
1079
+ }
1080
+ const temp = newDateTime.add(
1081
+ PyTimeDelta.create({
1082
+ days: delta.days + leapDays,
1083
+ hours: delta.hours,
1084
+ minutes: delta.minutes,
1085
+ seconds: delta.seconds,
1086
+ microseconds: delta.microseconds
1087
+ })
1088
+ );
1089
+ const hasTime = Boolean(
1090
+ temp.hour || temp.minute || temp.second || temp.microsecond
1091
+ );
1092
+ const returnDate = !hasTime && date instanceof PyDate ? new PyDate(temp.year, temp.month, temp.day) : temp;
1093
+ if (delta.weekday !== null) {
1094
+ const wantedDow = delta.weekday + 1;
1095
+ const _date = new Date(
1096
+ returnDate.year,
1097
+ returnDate.month - 1,
1098
+ returnDate.day
1099
+ );
1100
+ const days = (7 - _date.getDay() + wantedDow) % 7;
1101
+ return returnDate.add(new PyTimeDelta(days, 0, 0));
1102
+ }
1103
+ return returnDate;
1104
+ }
1105
+ static substract(date, delta) {
1106
+ return _PyRelativeDelta.add(date, delta.negate());
1107
+ }
1108
+ constructor(params = {}, sign = 1) {
1109
+ this.years = sign * params.years;
1110
+ this.months = sign * params.months;
1111
+ this.days = sign * params.days;
1112
+ this.hours = sign * params.hours;
1113
+ this.minutes = sign * params.minutes;
1114
+ this.seconds = sign * params.seconds;
1115
+ this.microseconds = sign * params.microseconds;
1116
+ this.leapDays = params.leapDays;
1117
+ this.year = params.year;
1118
+ this.month = params.month;
1119
+ this.day = params.day;
1120
+ this.hour = params.hour;
1121
+ this.minute = params.minute;
1122
+ this.second = params.second;
1123
+ this.microsecond = params.microsecond;
1124
+ this.weekday = params.weekday;
1125
+ }
1126
+ negate() {
1127
+ return new _PyRelativeDelta(this, -1);
1128
+ }
1129
+ isEqual() {
1130
+ throw new NotSupportedError();
1131
+ }
1132
+ };
1133
+ var TIME_DELTA_KEYS = "weeks days hours minutes seconds milliseconds microseconds".split(" ");
1134
+ function modf(x) {
1135
+ const mod = x % 1;
1136
+ return [mod < 0 ? mod + 1 : mod, Math.floor(x)];
1137
+ }
1138
+ var PyTimeDelta = class _PyTimeDelta {
1139
+ constructor(days, seconds, microseconds) {
1140
+ this.days = days;
1141
+ this.seconds = seconds;
1142
+ this.microseconds = microseconds;
1143
+ }
1144
+ static create(...args) {
1145
+ const namedArgs = parseArgs(args, ["days", "seconds", "microseconds"]);
1146
+ for (const key of TIME_DELTA_KEYS) {
1147
+ namedArgs[key] = namedArgs[key] || 0;
1148
+ }
1149
+ let d = 0;
1150
+ let s = 0;
1151
+ let us = 0;
1152
+ const days = namedArgs.days + namedArgs.weeks * 7;
1153
+ let seconds = namedArgs.seconds + 60 * namedArgs.minutes + 3600 * namedArgs.hours;
1154
+ let microseconds = namedArgs.microseconds + 1e3 * namedArgs.milliseconds;
1155
+ const [dFrac, dInt] = modf(days);
1156
+ d = dInt;
1157
+ let daysecondsfrac = 0;
1158
+ if (dFrac) {
1159
+ const [dsFrac, dsInt] = modf(dFrac * 24 * 3600);
1160
+ s = dsInt;
1161
+ daysecondsfrac = dsFrac;
1162
+ }
1163
+ const [sFrac, sInt] = modf(seconds);
1164
+ seconds = sInt;
1165
+ const secondsfrac = sFrac + daysecondsfrac;
1166
+ divmod(seconds, 24 * 3600, (days2, seconds2) => {
1167
+ d += days2;
1168
+ s += seconds2;
1169
+ });
1170
+ microseconds += secondsfrac * 1e6;
1171
+ divmod(microseconds, 1e6, (seconds2, microseconds2) => {
1172
+ divmod(seconds2, 24 * 3600, (days2, seconds3) => {
1173
+ d += days2;
1174
+ s += seconds3;
1175
+ us += Math.round(microseconds2);
1176
+ });
1177
+ });
1178
+ return new _PyTimeDelta(d, s, us);
1179
+ }
1180
+ add(other) {
1181
+ return _PyTimeDelta.create({
1182
+ days: this.days + other.days,
1183
+ seconds: this.seconds + other.seconds,
1184
+ microseconds: this.microseconds + other.microseconds
1185
+ });
1186
+ }
1187
+ divide(n) {
1188
+ const us = (this.days * 24 * 3600 + this.seconds) * 1e6 + this.microseconds;
1189
+ return _PyTimeDelta.create({ microseconds: Math.floor(us / n) });
1190
+ }
1191
+ isEqual(other) {
1192
+ if (!(other instanceof _PyTimeDelta)) {
1193
+ return false;
1194
+ }
1195
+ return this.days === other.days && this.seconds === other.seconds && this.microseconds === other.microseconds;
1196
+ }
1197
+ isTrue() {
1198
+ return this.days !== 0 || this.seconds !== 0 || this.microseconds !== 0;
1199
+ }
1200
+ multiply(n) {
1201
+ return _PyTimeDelta.create({
1202
+ days: n * this.days,
1203
+ seconds: n * this.seconds,
1204
+ microseconds: n * this.microseconds
1205
+ });
1206
+ }
1207
+ negate() {
1208
+ return _PyTimeDelta.create({
1209
+ days: -this.days,
1210
+ seconds: -this.seconds,
1211
+ microseconds: -this.microseconds
1212
+ });
1213
+ }
1214
+ substract(other) {
1215
+ return _PyTimeDelta.create({
1216
+ days: this.days - other.days,
1217
+ seconds: this.seconds - other.seconds,
1218
+ microseconds: this.microseconds - other.microseconds
1219
+ });
1220
+ }
1221
+ total_seconds() {
1222
+ return this.days * 86400 + this.seconds + this.microseconds / 1e6;
1223
+ }
1224
+ };
1225
+
1226
+ // src/utils/domain/py_builtin.ts
1227
+ var EvaluationError = class extends Error {
1228
+ constructor(message) {
1229
+ super(message);
1230
+ this.name = "EvaluationError";
1231
+ }
1232
+ };
1233
+ function execOnIterable(iterable, func) {
1234
+ if (iterable === null) {
1235
+ throw new EvaluationError("value not iterable");
1236
+ }
1237
+ if (typeof iterable === "object" && !Array.isArray(iterable) && !(iterable instanceof Set)) {
1238
+ iterable = Object.keys(iterable);
1239
+ }
1240
+ if (typeof (iterable == null ? void 0 : iterable[Symbol.iterator]) !== "function") {
1241
+ throw new EvaluationError("value not iterable");
1242
+ }
1243
+ return func(iterable);
1244
+ }
1245
+ var BUILTINS = {
1246
+ /**
1247
+ * @param {any} value
1248
+ * @returns {boolean}
1249
+ */
1250
+ bool(value) {
1251
+ switch (typeof value) {
1252
+ case "number":
1253
+ return value !== 0;
1254
+ case "string":
1255
+ return value !== "";
1256
+ case "boolean":
1257
+ return value;
1258
+ case "object":
1259
+ if (value === null || value === void 0) {
1260
+ return false;
1261
+ }
1262
+ if ("isTrue" in value && typeof value.isTrue === "function") {
1263
+ return value.isTrue();
1264
+ }
1265
+ if (value instanceof Array) {
1266
+ return !!value.length;
1267
+ }
1268
+ if (value instanceof Set) {
1269
+ return !!value.size;
1270
+ }
1271
+ return Object.keys(value).length !== 0;
1272
+ default:
1273
+ return true;
1274
+ }
1275
+ },
1276
+ set(iterable) {
1277
+ if (arguments.length > 2) {
1278
+ throw new EvaluationError(
1279
+ `set expected at most 1 argument, got (${arguments.length - 1})`
1280
+ );
1281
+ }
1282
+ return execOnIterable(
1283
+ iterable,
1284
+ (iterable2) => new Set(iterable2)
1285
+ );
1286
+ },
1287
+ time: {
1288
+ strftime(format) {
1289
+ return PyDateTime.now().strftime(format);
1290
+ }
1291
+ },
1292
+ context_today() {
1293
+ return PyDate.today();
1294
+ },
1295
+ get current_date() {
1296
+ return this.today;
1297
+ },
1298
+ get today() {
1299
+ return PyDate.today().strftime("%Y-%m-%d");
1300
+ },
1301
+ get now() {
1302
+ return PyDateTime.now().strftime("%Y-%m-%d %H:%M:%S");
1303
+ },
1304
+ datetime: {
1305
+ time: PyTime,
1306
+ timedelta: PyTimeDelta,
1307
+ datetime: PyDateTime,
1308
+ date: PyDate
1309
+ },
1310
+ relativedelta: PyRelativeDelta,
1311
+ true: true,
1312
+ false: false
1313
+ };
1314
+
1315
+ // src/utils/domain/py_utils.ts
1316
+ function toPyValue(value) {
1317
+ switch (typeof value) {
1318
+ case "string":
1319
+ return { type: 1, value };
1320
+ case "number":
1321
+ return { type: 0, value };
1322
+ case "boolean":
1323
+ return { type: 2, value };
1324
+ case "object":
1325
+ if (Array.isArray(value)) {
1326
+ return { type: 4, value: value.map(toPyValue) };
1327
+ } else if (value === null) {
1328
+ return {
1329
+ type: 3
1330
+ /* None */
1331
+ };
1332
+ } else if (value instanceof Date) {
1333
+ return {
1334
+ type: 1,
1335
+ value: String(PyDateTime.convertDate(value))
1336
+ };
1337
+ } else if (value instanceof PyDate || value instanceof PyDateTime) {
1338
+ return { type: 1, value };
1339
+ } else {
1340
+ const content = {};
1341
+ for (const key in value) {
1342
+ content[key] = toPyValue(value[key]);
1343
+ }
1344
+ return { type: 11, value: content };
1345
+ }
1346
+ default:
1347
+ throw new Error("Invalid type");
1348
+ }
1349
+ }
1350
+ function formatAST(ast, lbp = 0) {
1351
+ switch (ast.type) {
1352
+ case 3:
1353
+ return "None";
1354
+ case 1:
1355
+ return JSON.stringify(ast.value);
1356
+ case 0:
1357
+ return String(ast.value);
1358
+ case 2:
1359
+ return ast.value ? "True" : "False";
1360
+ case 4:
1361
+ return `[${ast.value.map(formatAST).join(", ")}]`;
1362
+ case 6:
1363
+ if (ast.op === "not") {
1364
+ return `not ${formatAST(ast.right, 50)}`;
1365
+ }
1366
+ return `${ast.op}${formatAST(ast.right, 130)}`;
1367
+ case 7:
1368
+ const abp = bp(ast.op);
1369
+ const binaryStr = `${formatAST(ast.left, abp)} ${ast.op} ${formatAST(ast.right, abp)}`;
1370
+ return abp < lbp ? `(${binaryStr})` : binaryStr;
1371
+ case 11:
1372
+ const pairs = [];
1373
+ for (const k in ast.value) {
1374
+ pairs.push(`"${k}": ${formatAST(ast.value[k])}`);
1375
+ }
1376
+ return `{${pairs.join(", ")}}`;
1377
+ case 10:
1378
+ return `(${ast.value.map(formatAST).join(", ")})`;
1379
+ case 5:
1380
+ return ast.value;
1381
+ case 12:
1382
+ return `${formatAST(ast.target)}[${formatAST(ast.key)}]`;
1383
+ case 13:
1384
+ const { ifTrue, condition, ifFalse } = ast;
1385
+ return `${formatAST(ifTrue)} if ${formatAST(condition)} else ${formatAST(ifFalse)}`;
1386
+ case 14:
1387
+ const boolAbp = bp(ast.op);
1388
+ const boolStr = `${formatAST(ast.left, boolAbp)} ${ast.op} ${formatAST(ast.right, boolAbp)}`;
1389
+ return boolAbp < lbp ? `(${boolStr})` : boolStr;
1390
+ case 15:
1391
+ return `${formatAST(ast.obj, 150)}.${ast.key}`;
1392
+ case 8:
1393
+ const args = ast.args.map(formatAST);
1394
+ const kwargs = [];
1395
+ for (const kwarg in ast.kwargs) {
1396
+ kwargs.push(`${kwarg} = ${formatAST(ast.kwargs[kwarg])}`);
1397
+ }
1398
+ const argStr = args.concat(kwargs).join(", ");
1399
+ return `${formatAST(ast.fn)}(${argStr})`;
1400
+ default:
1401
+ throw new Error("invalid expression: " + JSON.stringify(ast));
1402
+ }
1403
+ }
1404
+ var PY_DICT = /* @__PURE__ */ Object.create(null);
1405
+ function toPyDict(obj) {
1406
+ return new Proxy(obj, {
1407
+ getPrototypeOf() {
1408
+ return PY_DICT;
1409
+ }
1410
+ });
1411
+ }
1412
+
1413
+ // src/utils/domain/py_interpreter.ts
1414
+ var isTrue = BUILTINS.bool;
1415
+ function applyUnaryOp(ast, context) {
1416
+ const value = evaluate(ast.right, context);
1417
+ switch (ast.op) {
1418
+ case "-":
1419
+ if (value instanceof Object && "negate" in value) {
1420
+ return value.negate();
1421
+ }
1422
+ return -value;
1423
+ case "+":
1424
+ return value;
1425
+ case "not":
1426
+ return !isTrue(value);
1427
+ default:
1428
+ throw new EvaluationError(`Unknown unary operator: ${ast.op}`);
1429
+ }
1430
+ }
1431
+ function pytypeIndex(val) {
1432
+ switch (typeof val) {
1433
+ case "object":
1434
+ return val === null ? 1 : Array.isArray(val) ? 5 : 3;
1435
+ case "number":
1436
+ return 2;
1437
+ case "string":
1438
+ return 4;
1439
+ default:
1440
+ throw new EvaluationError(`Unknown type: ${typeof val}`);
1441
+ }
1442
+ }
1443
+ function isLess(left, right) {
1444
+ if (typeof left === "number" && typeof right === "number") {
1445
+ return left < right;
1446
+ }
1447
+ if (typeof left === "boolean") {
1448
+ left = left ? 1 : 0;
1449
+ }
1450
+ if (typeof right === "boolean") {
1451
+ right = right ? 1 : 0;
1452
+ }
1453
+ const leftIndex = pytypeIndex(left);
1454
+ const rightIndex = pytypeIndex(right);
1455
+ if (leftIndex === rightIndex) {
1456
+ return left < right;
1457
+ }
1458
+ return leftIndex < rightIndex;
1459
+ }
1460
+ function isEqual(left, right) {
1461
+ if (typeof left !== typeof right) {
1462
+ if (typeof left === "boolean" && typeof right === "number") {
1463
+ return right === (left ? 1 : 0);
1464
+ }
1465
+ if (typeof left === "number" && typeof right === "boolean") {
1466
+ return left === (right ? 1 : 0);
1467
+ }
1468
+ return false;
1469
+ }
1470
+ if (left instanceof Object && "isEqual" in left) {
1471
+ return left.isEqual(right);
1472
+ }
1473
+ return left === right;
1474
+ }
1475
+ function isIn(left, right) {
1476
+ if (Array.isArray(right)) {
1477
+ return right.includes(left);
1478
+ }
1479
+ if (typeof right === "string" && typeof left === "string") {
1480
+ return right.includes(left);
1481
+ }
1482
+ if (typeof right === "object") {
1483
+ return left in right;
1484
+ }
1485
+ return false;
1486
+ }
1487
+ function applyBinaryOp(ast, context) {
1488
+ const left = evaluate(ast.left, context);
1489
+ const right = evaluate(ast.right, context);
1490
+ switch (ast.op) {
1491
+ case "+": {
1492
+ const relativeDeltaOnLeft = left instanceof PyRelativeDelta;
1493
+ const relativeDeltaOnRight = right instanceof PyRelativeDelta;
1494
+ if (relativeDeltaOnLeft || relativeDeltaOnRight) {
1495
+ const date = relativeDeltaOnLeft ? right : left;
1496
+ const delta = relativeDeltaOnLeft ? left : right;
1497
+ return PyRelativeDelta.add(date, delta);
1498
+ }
1499
+ const timeDeltaOnLeft = left instanceof PyTimeDelta;
1500
+ const timeDeltaOnRight = right instanceof PyTimeDelta;
1501
+ if (timeDeltaOnLeft && timeDeltaOnRight) {
1502
+ return left.add(right);
1503
+ }
1504
+ if (timeDeltaOnLeft) {
1505
+ if (right instanceof PyDate || right instanceof PyDateTime) {
1506
+ return right.add(left);
1507
+ } else {
1508
+ throw new NotSupportedError();
1509
+ }
1510
+ }
1511
+ if (timeDeltaOnRight) {
1512
+ if (left instanceof PyDate || left instanceof PyDateTime) {
1513
+ return left.add(right);
1514
+ } else {
1515
+ throw new NotSupportedError();
1516
+ }
1517
+ }
1518
+ if (left instanceof Array && right instanceof Array) {
1519
+ return [...left, ...right];
1520
+ }
1521
+ return left + right;
1522
+ }
1523
+ case "-": {
1524
+ const isRightDelta = right instanceof PyRelativeDelta;
1525
+ if (isRightDelta) {
1526
+ return PyRelativeDelta.substract(left, right);
1527
+ }
1528
+ const timeDeltaOnRight = right instanceof PyTimeDelta;
1529
+ if (timeDeltaOnRight) {
1530
+ if (left instanceof PyTimeDelta) {
1531
+ return left.substract(right);
1532
+ } else if (left instanceof PyDate || left instanceof PyDateTime) {
1533
+ return left.substract(right);
1534
+ } else {
1535
+ throw new NotSupportedError();
1536
+ }
1537
+ }
1538
+ if (left instanceof PyDate) {
1539
+ return left.substract(right);
1540
+ }
1541
+ return left - right;
1542
+ }
1543
+ case "*": {
1544
+ const timeDeltaOnLeft = left instanceof PyTimeDelta;
1545
+ const timeDeltaOnRight = right instanceof PyTimeDelta;
1546
+ if (timeDeltaOnLeft || timeDeltaOnRight) {
1547
+ const number = timeDeltaOnLeft ? right : left;
1548
+ const delta = timeDeltaOnLeft ? left : right;
1549
+ return delta.multiply(number);
1550
+ }
1551
+ return left * right;
1552
+ }
1553
+ case "/":
1554
+ return left / right;
1555
+ case "%":
1556
+ return left % right;
1557
+ case "//":
1558
+ if (left instanceof PyTimeDelta) {
1559
+ return left.divide(right);
1560
+ }
1561
+ return Math.floor(left / right);
1562
+ case "**":
1563
+ return __pow(left, right);
1564
+ case "==":
1565
+ return isEqual(left, right);
1566
+ case "<>":
1567
+ case "!=":
1568
+ return !isEqual(left, right);
1569
+ case "<":
1570
+ return isLess(left, right);
1571
+ case ">":
1572
+ return isLess(right, left);
1573
+ case ">=":
1574
+ return isEqual(left, right) || isLess(right, left);
1575
+ case "<=":
1576
+ return isEqual(left, right) || isLess(left, right);
1577
+ case "in":
1578
+ return isIn(left, right);
1579
+ case "not in":
1580
+ return !isIn(left, right);
1581
+ default:
1582
+ throw new EvaluationError(`Unknown binary operator: ${ast.op}`);
1583
+ }
1584
+ }
1585
+ var DICT = {
1586
+ get(...args) {
1587
+ const { key, defValue } = parseArgs(args, ["key", "defValue"]);
1588
+ const self = this;
1589
+ if (key in self) {
1590
+ return self[key];
1591
+ } else if (defValue !== void 0) {
1592
+ return defValue;
1593
+ }
1594
+ return null;
1595
+ }
1596
+ };
1597
+ var STRING = {
1598
+ lower() {
1599
+ return this.toLowerCase();
1600
+ },
1601
+ upper() {
1602
+ return this.toUpperCase();
1603
+ }
1604
+ };
1605
+ function applyFunc(key, func, set, ...args) {
1606
+ if (args.length === 1) {
1607
+ return new Set(set);
1608
+ }
1609
+ if (args.length > 2) {
1610
+ throw new EvaluationError(
1611
+ `${key}: py_js supports at most 1 argument, got (${args.length - 1})`
1612
+ );
1613
+ }
1614
+ return execOnIterable(args[0], func);
1615
+ }
1616
+ var SET = {
1617
+ intersection(...args) {
1618
+ return applyFunc(
1619
+ "intersection",
1620
+ (iterable) => {
1621
+ const intersection = /* @__PURE__ */ new Set();
1622
+ for (const i of iterable) {
1623
+ if (this.has(i)) {
1624
+ intersection.add(i);
1625
+ }
1626
+ }
1627
+ return intersection;
1628
+ },
1629
+ this,
1630
+ ...args
1631
+ );
1632
+ },
1633
+ difference(...args) {
1634
+ return applyFunc(
1635
+ "difference",
1636
+ (iterable) => {
1637
+ iterable = new Set(iterable);
1638
+ const difference = /* @__PURE__ */ new Set();
1639
+ for (const e of this) {
1640
+ if (!iterable.has(e)) {
1641
+ difference.add(e);
1642
+ }
1643
+ }
1644
+ return difference;
1645
+ },
1646
+ this,
1647
+ ...args
1648
+ );
1649
+ },
1650
+ union(...args) {
1651
+ return applyFunc(
1652
+ "union",
1653
+ (iterable) => {
1654
+ return /* @__PURE__ */ new Set([...this, ...iterable]);
1655
+ },
1656
+ this,
1657
+ ...args
1658
+ );
1659
+ }
1660
+ };
1661
+ function methods(_class) {
1662
+ return Object.getOwnPropertyNames(_class.prototype).map(
1663
+ (prop) => _class.prototype[prop]
1664
+ );
1665
+ }
1666
+ var allowedFns = /* @__PURE__ */ new Set([
1667
+ BUILTINS.time.strftime,
1668
+ BUILTINS.set,
1669
+ BUILTINS.bool,
1670
+ BUILTINS.context_today,
1671
+ BUILTINS.datetime.datetime.now,
1672
+ BUILTINS.datetime.datetime.combine,
1673
+ BUILTINS.datetime.date.today,
1674
+ ...methods(BUILTINS.relativedelta),
1675
+ ...Object.values(BUILTINS.datetime).flatMap((obj) => methods(obj)),
1676
+ ...Object.values(SET),
1677
+ ...Object.values(DICT),
1678
+ ...Object.values(STRING)
1679
+ ]);
1680
+ var unboundFn = Symbol("unbound function");
1681
+ function evaluate(ast, context = {}) {
1682
+ const dicts = /* @__PURE__ */ new Set();
1683
+ let pyContext;
1684
+ const evalContext = Object.create(context);
1685
+ if (!(evalContext == null ? void 0 : evalContext.context)) {
1686
+ Object.defineProperty(evalContext, "context", {
1687
+ get() {
1688
+ if (!pyContext) {
1689
+ pyContext = toPyDict(context);
1690
+ }
1691
+ return pyContext;
1692
+ }
1693
+ });
1694
+ }
1695
+ function _innerEvaluate(ast2) {
1696
+ var _a, _b, _c;
1697
+ switch (ast2 == null ? void 0 : ast2.type) {
1698
+ case 0:
1699
+ // Number
1700
+ case 1:
1701
+ return ast2.value;
1702
+ case 5:
1703
+ if (ast2.value in evalContext) {
1704
+ if (typeof evalContext[ast2.value] === "object" && ((_a = evalContext[ast2.value]) == null ? void 0 : _a.id)) {
1705
+ return (_b = evalContext[ast2.value]) == null ? void 0 : _b.id;
1706
+ }
1707
+ return (_c = evalContext[ast2.value]) != null ? _c : false;
1708
+ } else if (ast2.value in BUILTINS) {
1709
+ return BUILTINS[ast2.value];
1710
+ } else {
1711
+ return false;
1712
+ }
1713
+ case 3:
1714
+ return null;
1715
+ case 2:
1716
+ return ast2.value;
1717
+ case 6:
1718
+ return applyUnaryOp(ast2, evalContext);
1719
+ case 7:
1720
+ return applyBinaryOp(ast2, evalContext);
1721
+ case 14:
1722
+ const left = _evaluate(ast2.left);
1723
+ if (ast2.op === "and") {
1724
+ return isTrue(left) ? _evaluate(ast2.right) : left;
1725
+ } else {
1726
+ return isTrue(left) ? left : _evaluate(ast2.right);
1727
+ }
1728
+ case 4:
1729
+ // List
1730
+ case 10:
1731
+ return ast2.value.map(_evaluate);
1732
+ case 11:
1733
+ const dict = {};
1734
+ for (const key2 in ast2.value) {
1735
+ dict[key2] = _evaluate(ast2.value[key2]);
1736
+ }
1737
+ dicts.add(dict);
1738
+ return dict;
1739
+ case 8:
1740
+ const fnValue = _evaluate(ast2.fn);
1741
+ const args = ast2.args.map(_evaluate);
1742
+ const kwargs = {};
1743
+ for (const kwarg in ast2.kwargs) {
1744
+ kwargs[kwarg] = _evaluate(ast2 == null ? void 0 : ast2.kwargs[kwarg]);
1745
+ }
1746
+ if (fnValue === PyDate || fnValue === PyDateTime || fnValue === PyTime || fnValue === PyRelativeDelta || fnValue === PyTimeDelta) {
1747
+ return fnValue.create(...args, kwargs);
1748
+ }
1749
+ return fnValue(...args, kwargs);
1750
+ case 12:
1751
+ const dictVal = _evaluate(ast2.target);
1752
+ const key = _evaluate(ast2.key);
1753
+ return dictVal[key];
1754
+ case 13:
1755
+ if (isTrue(_evaluate(ast2.condition))) {
1756
+ return _evaluate(ast2.ifTrue);
1757
+ } else {
1758
+ return _evaluate(ast2.ifFalse);
1759
+ }
1760
+ case 15:
1761
+ let leftVal = _evaluate(ast2.obj);
1762
+ let result;
1763
+ if (dicts.has(leftVal) || Object.isPrototypeOf.call(PY_DICT, leftVal)) {
1764
+ result = DICT[ast2.key];
1765
+ } else if (typeof leftVal === "string") {
1766
+ result = STRING[ast2.key];
1767
+ } else if (leftVal instanceof Set) {
1768
+ result = SET[ast2.key];
1769
+ } else if (ast2.key === "get" && typeof leftVal === "object") {
1770
+ result = DICT[ast2.key];
1771
+ leftVal = toPyDict(leftVal);
1772
+ } else {
1773
+ result = leftVal[ast2.key];
1774
+ }
1775
+ if (typeof result === "function") {
1776
+ const bound = result.bind(leftVal);
1777
+ bound[unboundFn] = result;
1778
+ return bound;
1779
+ }
1780
+ return result;
1781
+ default:
1782
+ throw new EvaluationError(`AST of type ${ast2.type} cannot be evaluated`);
1783
+ }
1784
+ }
1785
+ function _evaluate(ast2) {
1786
+ const val = _innerEvaluate(ast2);
1787
+ if (typeof val === "function" && !allowedFns.has(val) && !allowedFns.has(val[unboundFn])) {
1788
+ throw new Error("Invalid Function Call");
1789
+ }
1790
+ return val;
1791
+ }
1792
+ return _evaluate(ast);
1793
+ }
1794
+
1795
+ // src/utils/domain/py.ts
1796
+ function parseExpr(expr) {
1797
+ const tokens = tokenize(expr);
1798
+ return parse(tokens);
1799
+ }
1800
+
1801
+ // src/utils/domain/objects.ts
1802
+ function shallowEqual(obj1, obj2, comparisonFn = (a, b) => a === b) {
1803
+ if (!obj1 || !obj2 || typeof obj1 !== "object" || typeof obj2 !== "object") {
1804
+ return obj1 === obj2;
1805
+ }
1806
+ const obj1Keys = Object.keys(obj1);
1807
+ return obj1Keys.length === Object.keys(obj2).length && obj1Keys.every((key) => comparisonFn(obj1[key], obj2[key]));
1808
+ }
1809
+
1810
+ // src/utils/domain/arrays.ts
1811
+ var shallowEqual2 = shallowEqual;
1812
+
1813
+ // src/utils/domain/strings.ts
1814
+ var escapeMethod = Symbol("html");
1815
+ function escapeRegExp(str) {
1816
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1817
+ }
1818
+
1819
+ // src/utils/domain/domain.ts
1820
+ var InvalidDomainError = class extends Error {
1821
+ };
1822
+ var Domain = class _Domain {
1823
+ constructor(descr = []) {
1824
+ this.ast = { type: -1, value: null };
1825
+ if (descr instanceof _Domain) {
1826
+ return new _Domain(descr.toString());
1827
+ } else {
1828
+ let rawAST;
1829
+ try {
1830
+ rawAST = typeof descr === "string" ? parseExpr(descr) : toAST(descr);
1831
+ } catch (error) {
1832
+ throw new InvalidDomainError(
1833
+ `Invalid domain representation: ${descr}`,
1834
+ {
1835
+ cause: error
1836
+ }
1837
+ );
1838
+ }
1839
+ this.ast = normalizeDomainAST(rawAST);
1840
+ }
1841
+ }
1842
+ static combine(domains, operator) {
1843
+ if (domains.length === 0) {
1844
+ return new _Domain([]);
1845
+ }
1846
+ const domain1 = domains[0] instanceof _Domain ? domains[0] : new _Domain(domains[0]);
1847
+ if (domains.length === 1) {
1848
+ return domain1;
1849
+ }
1850
+ const domain2 = _Domain.combine(domains.slice(1), operator);
1851
+ const result = new _Domain([]);
1852
+ const astValues1 = domain1.ast.value;
1853
+ const astValues2 = domain2.ast.value;
1854
+ const op = operator === "AND" ? "&" : "|";
1855
+ const combinedAST = {
1856
+ type: 4,
1857
+ value: astValues1.concat(astValues2)
1858
+ };
1859
+ result.ast = normalizeDomainAST(combinedAST, op);
1860
+ return result;
1861
+ }
1862
+ static and(domains) {
1863
+ return _Domain.combine(domains, "AND");
1864
+ }
1865
+ static or(domains) {
1866
+ return _Domain.combine(domains, "OR");
1867
+ }
1868
+ static not(domain) {
1869
+ const result = new _Domain(domain);
1870
+ result.ast.value.unshift({ type: 1, value: "!" });
1871
+ return result;
1872
+ }
1873
+ static removeDomainLeaves(domain, keysToRemove) {
1874
+ function processLeaf(elements, idx, operatorCtx, newDomain2) {
1875
+ const leaf = elements[idx];
1876
+ if (leaf.type === 10) {
1877
+ if (keysToRemove.includes(leaf.value[0].value)) {
1878
+ if (operatorCtx === "&") {
1879
+ newDomain2.ast.value.push(..._Domain.TRUE.ast.value);
1880
+ } else if (operatorCtx === "|") {
1881
+ newDomain2.ast.value.push(..._Domain.FALSE.ast.value);
1882
+ }
1883
+ } else {
1884
+ newDomain2.ast.value.push(leaf);
1885
+ }
1886
+ return 1;
1887
+ } else if (leaf.type === 1) {
1888
+ if (leaf.value === "|" && elements[idx + 1].type === 10 && elements[idx + 2].type === 10 && keysToRemove.includes(elements[idx + 1].value[0].value) && keysToRemove.includes(elements[idx + 2].value[0].value)) {
1889
+ newDomain2.ast.value.push(..._Domain.TRUE.ast.value);
1890
+ return 3;
1891
+ }
1892
+ newDomain2.ast.value.push(leaf);
1893
+ if (leaf.value === "!") {
1894
+ return 1 + processLeaf(elements, idx + 1, "&", newDomain2);
1895
+ }
1896
+ const firstLeafSkip = processLeaf(
1897
+ elements,
1898
+ idx + 1,
1899
+ leaf.value,
1900
+ newDomain2
1901
+ );
1902
+ const secondLeafSkip = processLeaf(
1903
+ elements,
1904
+ idx + 1 + firstLeafSkip,
1905
+ leaf.value,
1906
+ newDomain2
1907
+ );
1908
+ return 1 + firstLeafSkip + secondLeafSkip;
1909
+ }
1910
+ return 0;
1911
+ }
1912
+ const d = new _Domain(domain);
1913
+ if (d.ast.value.length === 0) {
1914
+ return d;
1915
+ }
1916
+ const newDomain = new _Domain([]);
1917
+ processLeaf(d.ast.value, 0, "&", newDomain);
1918
+ return newDomain;
1919
+ }
1920
+ contains(record) {
1921
+ const expr = evaluate(this.ast, record);
1922
+ return matchDomain(record, expr);
1923
+ }
1924
+ toString() {
1925
+ return formatAST(this.ast);
1926
+ }
1927
+ toList(context) {
1928
+ return evaluate(this.ast, context);
1929
+ }
1930
+ toJson() {
1931
+ try {
1932
+ const evaluatedAsList = this.toList({});
1933
+ const evaluatedDomain = new _Domain(evaluatedAsList);
1934
+ if (evaluatedDomain.toString() === this.toString()) {
1935
+ return evaluatedAsList;
1936
+ }
1937
+ return this.toString();
1938
+ } catch (e) {
1939
+ return this.toString();
1940
+ }
1941
+ }
1942
+ };
1943
+ var TRUE_LEAF = [1, "=", 1];
1944
+ var FALSE_LEAF = [0, "=", 1];
1945
+ var TRUE_DOMAIN = new Domain([TRUE_LEAF]);
1946
+ var FALSE_DOMAIN = new Domain([FALSE_LEAF]);
1947
+ Domain.TRUE = TRUE_DOMAIN;
1948
+ Domain.FALSE = FALSE_DOMAIN;
1949
+ function toAST(domain) {
1950
+ const elems = domain.map((elem) => {
1951
+ switch (elem) {
1952
+ case "!":
1953
+ case "&":
1954
+ case "|":
1955
+ return { type: 1, value: elem };
1956
+ default:
1957
+ return {
1958
+ type: 10,
1959
+ value: elem.map(toPyValue)
1960
+ };
1961
+ }
1962
+ });
1963
+ return { type: 4, value: elems };
1964
+ }
1965
+ function normalizeDomainAST(domain, op = "&") {
1966
+ if (domain.type !== 4) {
1967
+ if (domain.type === 10) {
1968
+ const value = domain.value;
1969
+ if (value.findIndex((e) => e.type === 10) === -1 || !value.every((e) => e.type === 10 || e.type === 1)) {
1970
+ throw new InvalidDomainError("Invalid domain AST");
1971
+ }
1972
+ } else {
1973
+ throw new InvalidDomainError("Invalid domain AST");
1974
+ }
1975
+ }
1976
+ if (domain.value.length === 0) {
1977
+ return domain;
1978
+ }
1979
+ let expected = 1;
1980
+ for (const child of domain.value) {
1981
+ switch (child.type) {
1982
+ case 1:
1983
+ if (child.value === "&" || child.value === "|") {
1984
+ expected++;
1985
+ } else if (child.value !== "!") {
1986
+ throw new InvalidDomainError("Invalid domain AST");
1987
+ }
1988
+ break;
1989
+ case 4:
1990
+ /* list */
1991
+ case 10:
1992
+ if (child.value.length === 3) {
1993
+ expected--;
1994
+ break;
1995
+ }
1996
+ throw new InvalidDomainError("Invalid domain AST");
1997
+ default:
1998
+ throw new InvalidDomainError("Invalid domain AST");
1999
+ }
2000
+ }
2001
+ const values = domain.value.slice();
2002
+ while (expected < 0) {
2003
+ expected++;
2004
+ values.unshift({ type: 1, value: op });
2005
+ }
2006
+ if (expected > 0) {
2007
+ throw new InvalidDomainError(
2008
+ `invalid domain ${formatAST(domain)} (missing ${expected} segment(s))`
2009
+ );
2010
+ }
2011
+ return { type: 4, value: values };
2012
+ }
2013
+ function matchCondition(record, condition) {
2014
+ if (typeof condition === "boolean") {
2015
+ return condition;
2016
+ }
2017
+ const [field, operator, value] = condition;
2018
+ if (typeof field === "string") {
2019
+ const names = field.split(".");
2020
+ if (names.length >= 2) {
2021
+ return matchCondition(record[names[0]], [
2022
+ names.slice(1).join("."),
2023
+ operator,
2024
+ value
2025
+ ]);
2026
+ }
2027
+ }
2028
+ let likeRegexp, ilikeRegexp;
2029
+ if (["like", "not like", "ilike", "not ilike"].includes(operator)) {
2030
+ likeRegexp = new RegExp(
2031
+ `(.*)${escapeRegExp(value).replaceAll("%", "(.*)")}(.*)`,
2032
+ "g"
2033
+ );
2034
+ ilikeRegexp = new RegExp(
2035
+ `(.*)${escapeRegExp(value).replaceAll("%", "(.*)")}(.*)`,
2036
+ "gi"
2037
+ );
2038
+ }
2039
+ const fieldValue = typeof field === "number" ? field : record[field];
2040
+ switch (operator) {
2041
+ case "=?":
2042
+ if ([false, null].includes(value)) {
2043
+ return true;
2044
+ }
2045
+ // eslint-disable-next-line no-fallthrough
2046
+ case "=":
2047
+ case "==":
2048
+ if (Array.isArray(fieldValue) && Array.isArray(value)) {
2049
+ return shallowEqual2(fieldValue, value);
2050
+ }
2051
+ return fieldValue === value;
2052
+ case "!=":
2053
+ case "<>":
2054
+ return !matchCondition(record, [field, "==", value]);
2055
+ case "<":
2056
+ return fieldValue < value;
2057
+ case "<=":
2058
+ return fieldValue <= value;
2059
+ case ">":
2060
+ return fieldValue > value;
2061
+ case ">=":
2062
+ return fieldValue >= value;
2063
+ case "in": {
2064
+ const val = Array.isArray(value) ? value : [value];
2065
+ const fieldVal = Array.isArray(fieldValue) ? fieldValue : [fieldValue];
2066
+ return fieldVal.some((fv) => val.includes(fv));
2067
+ }
2068
+ case "not in": {
2069
+ const val = Array.isArray(value) ? value : [value];
2070
+ const fieldVal = Array.isArray(fieldValue) ? fieldValue : [fieldValue];
2071
+ return !fieldVal.some((fv) => val.includes(fv));
2072
+ }
2073
+ case "like":
2074
+ if (fieldValue === false) {
2075
+ return false;
2076
+ }
2077
+ return Boolean(fieldValue.match(likeRegexp));
2078
+ case "not like":
2079
+ if (fieldValue === false) {
2080
+ return false;
2081
+ }
2082
+ return Boolean(!fieldValue.match(likeRegexp));
2083
+ case "=like":
2084
+ if (fieldValue === false) {
2085
+ return false;
2086
+ }
2087
+ return new RegExp(escapeRegExp(value).replace(/%/g, ".*")).test(
2088
+ fieldValue
2089
+ );
2090
+ case "ilike":
2091
+ if (fieldValue === false) {
2092
+ return false;
2093
+ }
2094
+ return Boolean(fieldValue.match(ilikeRegexp));
2095
+ case "not ilike":
2096
+ if (fieldValue === false) {
2097
+ return false;
2098
+ }
2099
+ return Boolean(!fieldValue.match(ilikeRegexp));
2100
+ case "=ilike":
2101
+ if (fieldValue === false) {
2102
+ return false;
2103
+ }
2104
+ return new RegExp(escapeRegExp(value).replace(/%/g, ".*"), "i").test(
2105
+ fieldValue
2106
+ );
2107
+ }
2108
+ throw new InvalidDomainError("could not match domain");
2109
+ }
2110
+ function makeOperators(record) {
2111
+ const match = matchCondition.bind(null, record);
2112
+ return {
2113
+ "!": (x) => !match(x),
2114
+ "&": (a, b) => match(a) && match(b),
2115
+ "|": (a, b) => match(a) || match(b)
2116
+ };
2117
+ }
2118
+ function matchDomain(record, domain) {
2119
+ if (domain.length === 0) {
2120
+ return true;
2121
+ }
2122
+ const operators = makeOperators(record);
2123
+ const reversedDomain = Array.from(domain).reverse();
2124
+ const condStack = [];
2125
+ for (const item of reversedDomain) {
2126
+ const operator = typeof item === "string" && operators[item];
2127
+ if (operator) {
2128
+ const operands = condStack.splice(-operator.length);
2129
+ condStack.push(operator(...operands));
2130
+ } else {
2131
+ condStack.push(item);
2132
+ }
2133
+ }
2134
+ return matchCondition(record, condStack.pop());
2135
+ }
2136
+
2137
+ // src/utils/function.ts
2138
+ import { useEffect, useState } from "react";
2139
+ var updateTokenParamInOriginalRequest = (originalRequest, newAccessToken) => {
2140
+ if (!originalRequest.data) return originalRequest.data;
2141
+ if (typeof originalRequest.data === "string") {
2142
+ try {
2143
+ const parsedData = JSON.parse(originalRequest.data);
2144
+ if (parsedData.with_context && typeof parsedData.with_context === "object") {
2145
+ parsedData.with_context.token = newAccessToken;
2146
+ }
2147
+ return JSON.stringify(parsedData);
2148
+ } catch (e) {
2149
+ console.warn("Failed to parse originalRequest.data", e);
2150
+ return originalRequest.data;
2151
+ }
2152
+ }
2153
+ if (typeof originalRequest.data === "object" && originalRequest.data.with_context) {
2154
+ originalRequest.data.with_context.token = newAccessToken;
2155
+ }
2156
+ return originalRequest.data;
2157
+ };
2158
+
2159
+ // src/utils/storage/local-storage.ts
2160
+ var localStorageUtils = () => {
2161
+ const setToken = (access_token) => __async(null, null, function* () {
2162
+ localStorage.setItem("accessToken", access_token);
2163
+ });
2164
+ const setRefreshToken = (refresh_token) => __async(null, null, function* () {
2165
+ localStorage.setItem("refreshToken", refresh_token);
2166
+ });
2167
+ const getAccessToken = () => __async(null, null, function* () {
2168
+ return localStorage.getItem("accessToken");
2169
+ });
2170
+ const getRefreshToken = () => __async(null, null, function* () {
2171
+ return localStorage.getItem("refreshToken");
2172
+ });
2173
+ const clearToken = () => __async(null, null, function* () {
2174
+ localStorage.removeItem("accessToken");
2175
+ localStorage.removeItem("refreshToken");
2176
+ });
2177
+ return {
2178
+ setToken,
2179
+ setRefreshToken,
2180
+ getAccessToken,
2181
+ getRefreshToken,
2182
+ clearToken
2183
+ };
2184
+ };
2185
+
2186
+ // src/utils/storage/session-storage.ts
2187
+ var sessionStorageUtils = () => {
2188
+ const getBrowserSession = () => __async(null, null, function* () {
2189
+ return sessionStorage.getItem("browserSession");
2190
+ });
2191
+ return {
2192
+ getBrowserSession
2193
+ };
2194
+ };
2195
+
2196
+ // src/configs/axios-client.ts
2197
+ var axiosClient = {
2198
+ init(config) {
2199
+ var _a, _b;
2200
+ const localStorage2 = (_a = config.localStorageUtils) != null ? _a : localStorageUtils();
2201
+ const sessionStorage2 = (_b = config.sessionStorageUtils) != null ? _b : sessionStorageUtils();
2202
+ const db = config.db;
2203
+ let isRefreshing = false;
2204
+ let failedQueue = [];
2205
+ const processQueue = (error, token = null) => {
2206
+ failedQueue == null ? void 0 : failedQueue.forEach((prom) => {
2207
+ if (error) {
2208
+ prom.reject(error);
2209
+ } else {
2210
+ prom.resolve(token);
2211
+ }
2212
+ });
2213
+ failedQueue = [];
2214
+ };
2215
+ const instance = axios.create({
2216
+ adapter: axios.defaults.adapter,
2217
+ baseURL: config.baseUrl,
2218
+ timeout: 5e4,
2219
+ paramsSerializer: (params) => new URLSearchParams(params).toString()
2220
+ });
2221
+ instance.interceptors.request.use(
2222
+ (config2) => __async(null, null, function* () {
2223
+ const useRefreshToken = config2.useRefreshToken;
2224
+ const token = useRefreshToken ? yield localStorage2.getRefreshToken() : yield localStorage2.getAccessToken();
2225
+ if (token) {
2226
+ config2.headers["Authorization"] = "Bearer " + token;
2227
+ }
2228
+ return config2;
2229
+ }),
2230
+ (error) => {
2231
+ Promise.reject(error);
2232
+ }
2233
+ );
2234
+ instance.interceptors.response.use(
2235
+ (response) => {
2236
+ return handleResponse(response);
2237
+ },
2238
+ (error) => __async(null, null, function* () {
2239
+ var _a2, _b2, _c;
2240
+ const handleError3 = (error2) => __async(null, null, function* () {
2241
+ var _a3;
2242
+ if (!error2.response) {
2243
+ return error2;
2244
+ }
2245
+ const { data } = error2.response;
2246
+ if (data && data.code === 400 && ["invalid_grant"].includes((_a3 = data.data) == null ? void 0 : _a3.error)) {
2247
+ yield clearAuthToken();
2248
+ }
2249
+ return data;
2250
+ });
2251
+ const originalRequest = error.config;
2252
+ if ((((_a2 = error.response) == null ? void 0 : _a2.status) === 403 || ((_b2 = error.response) == null ? void 0 : _b2.status) === 401 || ((_c = error.response) == null ? void 0 : _c.status) === 404) && ["TOKEN_EXPIRED", "AUTHEN_FAIL", 401, "ERR_2FA_006"].includes(
2253
+ error.response.data.code
2254
+ )) {
2255
+ if (isRefreshing) {
2256
+ return new Promise(function(resolve, reject) {
2257
+ failedQueue.push({ resolve, reject });
2258
+ }).then((token) => {
2259
+ originalRequest.headers["Authorization"] = "Bearer " + token;
2260
+ originalRequest.data = updateTokenParamInOriginalRequest(
2261
+ originalRequest,
2262
+ token
2263
+ );
2264
+ return instance.request(originalRequest);
2265
+ }).catch((err) => __async(null, null, function* () {
2266
+ var _a3, _b3;
2267
+ if ((((_a3 = err.response) == null ? void 0 : _a3.status) === 400 || ((_b3 = err.response) == null ? void 0 : _b3.status) === 401) && ["invalid_grant"].includes(err.response.data.error)) {
2268
+ yield clearAuthToken();
2269
+ }
2270
+ }));
2271
+ }
2272
+ const browserSession = yield sessionStorage2.getBrowserSession();
2273
+ const refreshToken = yield localStorage2.getRefreshToken();
2274
+ const accessTokenExp = yield localStorage2.getAccessToken();
2275
+ isRefreshing = true;
2276
+ if (!refreshToken && (!browserSession || browserSession == "unActive")) {
2277
+ yield clearAuthToken();
2278
+ } else {
2279
+ const payload = Object.fromEntries(
2280
+ Object.entries({
2281
+ refresh_token: refreshToken,
2282
+ grant_type: "refresh_token",
2283
+ client_id: config.config.clientId,
2284
+ client_secret: config.config.clientSecret
2285
+ }).filter(([_, value]) => !!value)
2286
+ );
2287
+ return new Promise(function(resolve) {
2288
+ var _a3;
2289
+ axios.post(
2290
+ `${config.baseUrl}${(_a3 = config.refreshTokenEndpoint) != null ? _a3 : "/authentication/oauth2/token" /* AUTH_TOKEN_PATH */}`,
2291
+ payload,
2292
+ {
2293
+ headers: {
2294
+ "Content-Type": config.refreshTokenEndpoint ? "application/x-www-form-urlencoded" : "multipart/form-data",
2295
+ Authorization: `Bearer ${accessTokenExp}`
2296
+ }
2297
+ }
2298
+ ).then((res) => __async(null, null, function* () {
2299
+ const data = res.data;
2300
+ yield localStorage2.setToken(data.access_token);
2301
+ yield localStorage2.setRefreshToken(data.refresh_token);
2302
+ axios.defaults.headers.common["Authorization"] = "Bearer " + data.access_token;
2303
+ originalRequest.headers["Authorization"] = "Bearer " + data.access_token;
2304
+ originalRequest.data = updateTokenParamInOriginalRequest(
2305
+ originalRequest,
2306
+ data.access_token
2307
+ );
2308
+ processQueue(null, data.access_token);
2309
+ resolve(instance.request(originalRequest));
2310
+ })).catch((err) => __async(null, null, function* () {
2311
+ var _a4;
2312
+ if (err && ((err == null ? void 0 : err.error_code) === "AUTHEN_FAIL" || (err == null ? void 0 : err.error_code) === "TOKEN_EXPIRED" || (err == null ? void 0 : err.error_code) === "TOKEN_INCORRECT" || (err == null ? void 0 : err.code) === "ERR_BAD_REQUEST") || (err == null ? void 0 : err.error_code) === "ERR_2FA_006") {
2313
+ yield clearAuthToken();
2314
+ }
2315
+ if (err && err.response) {
2316
+ const { error_code } = ((_a4 = err.response) == null ? void 0 : _a4.data) || {};
2317
+ if (error_code === "AUTHEN_FAIL") {
2318
+ yield clearAuthToken();
2319
+ }
2320
+ }
2321
+ processQueue(err, null);
2322
+ })).finally(() => {
2323
+ isRefreshing = false;
2324
+ });
2325
+ });
2326
+ }
2327
+ }
2328
+ return Promise.reject(yield handleError3(error));
2329
+ })
2330
+ );
2331
+ const handleResponse = (res) => {
2332
+ if (res && res.data) {
2333
+ return res.data;
2334
+ }
2335
+ return res;
2336
+ };
2337
+ const handleError2 = (error) => {
2338
+ var _a2, _b2, _c;
2339
+ if (error.isAxiosError && error.code === "ECONNABORTED") {
2340
+ console.error("Request Timeout Error:", error);
2341
+ return "Request Timeout Error";
2342
+ } else if (error.isAxiosError && !error.response) {
2343
+ console.error("Network Error:", error);
2344
+ return "Network Error";
2345
+ } else {
2346
+ console.error("Other Error:", error == null ? void 0 : error.response);
2347
+ const errorMessage = ((_b2 = (_a2 = error == null ? void 0 : error.response) == null ? void 0 : _a2.data) == null ? void 0 : _b2.message) || "An error occurred";
2348
+ return { message: errorMessage, status: (_c = error == null ? void 0 : error.response) == null ? void 0 : _c.status };
2349
+ }
2350
+ };
2351
+ const clearAuthToken = () => __async(null, null, function* () {
2352
+ yield localStorage2.clearToken();
2353
+ if (typeof window !== "undefined") {
2354
+ window.location.href = `/login`;
2355
+ }
2356
+ });
2357
+ function formatUrl(url, db2) {
2358
+ return url + (db2 ? "?db=" + db2 : "");
2359
+ }
2360
+ const responseBody = (response) => response;
2361
+ const requests = {
2362
+ get: (url, headers) => instance.get(formatUrl(url, db), headers).then(responseBody),
2363
+ post: (url, body, headers) => instance.post(formatUrl(url, db), body, headers).then(responseBody),
2364
+ post_excel: (url, body, headers) => instance.post(formatUrl(url, db), body, {
2365
+ responseType: "arraybuffer",
2366
+ headers: {
2367
+ "Content-Type": typeof window !== "undefined" ? "application/json" : "application/javascript",
2368
+ Accept: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
2369
+ }
2370
+ }).then(responseBody),
2371
+ put: (url, body, headers) => instance.put(formatUrl(url, db), body, headers).then(responseBody),
2372
+ patch: (url, body) => instance.patch(formatUrl(url, db), body).then(responseBody),
2373
+ delete: (url, body) => instance.delete(formatUrl(url, db), body).then(responseBody)
2374
+ };
2375
+ return requests;
2376
+ }
2377
+ };
2378
+
2379
+ // src/store/index.ts
2380
+ import { useDispatch, useSelector } from "react-redux";
2381
+
2382
+ // src/store/reducers/breadcrums-slice/index.ts
2383
+ import { createSlice } from "@reduxjs/toolkit";
2384
+ var initialState = {
2385
+ breadCrumbs: []
2386
+ };
2387
+ var breadcrumbsSlice = createSlice({
2388
+ name: "breadcrumbs",
2389
+ initialState,
2390
+ reducers: {
2391
+ setBreadCrumbs: (state, action) => {
2392
+ state.breadCrumbs = [...state.breadCrumbs, action.payload];
2393
+ }
2394
+ }
2395
+ });
2396
+ var { setBreadCrumbs } = breadcrumbsSlice.actions;
2397
+ var breadcrums_slice_default = breadcrumbsSlice.reducer;
2398
+
2399
+ // src/store/reducers/env-slice/index.ts
2400
+ import { createSlice as createSlice2 } from "@reduxjs/toolkit";
2401
+ var initialState2 = {
2402
+ baseUrl: "",
2403
+ requests: null,
2404
+ companies: [],
2405
+ user: {},
2406
+ config: null,
2407
+ envFile: null,
2408
+ defaultCompany: {
2409
+ id: null,
2410
+ logo: "",
2411
+ secondary_color: "",
2412
+ primary_color: ""
2413
+ },
2414
+ context: {
2415
+ uid: null,
2416
+ allowed_company_ids: [],
2417
+ lang: "vi_VN",
2418
+ tz: "Asia/Saigon"
2419
+ }
2420
+ };
2421
+ var envSlice = createSlice2({
2422
+ name: "env",
2423
+ initialState: initialState2,
2424
+ reducers: {
2425
+ setEnv: (state, action) => {
2426
+ Object.assign(state, action.payload);
2427
+ },
2428
+ setUid: (state, action) => {
2429
+ state.context.uid = action.payload;
2430
+ },
2431
+ setAllowCompanies: (state, action) => {
2432
+ state.context.allowed_company_ids = action.payload;
2433
+ },
2434
+ setCompanies: (state, action) => {
2435
+ state.companies = action.payload;
2436
+ },
2437
+ setDefaultCompany: (state, action) => {
2438
+ state.defaultCompany = action.payload;
2439
+ },
2440
+ setLang: (state, action) => {
2441
+ state.context.lang = action.payload;
2442
+ },
2443
+ setUser: (state, action) => {
2444
+ state.user = action.payload;
2445
+ },
2446
+ setConfig: (state, action) => {
2447
+ state.config = action.payload;
2448
+ },
2449
+ setEnvFile: (state, action) => {
2450
+ state.envFile = action.payload;
2451
+ }
2452
+ }
2453
+ });
2454
+ var {
2455
+ setEnv,
2456
+ setUid,
2457
+ setLang,
2458
+ setAllowCompanies,
2459
+ setCompanies,
2460
+ setDefaultCompany,
2461
+ setUser,
2462
+ setConfig,
2463
+ setEnvFile
2464
+ } = envSlice.actions;
2465
+ var env_slice_default = envSlice.reducer;
2466
+
2467
+ // src/store/reducers/excel-slice/index.ts
2468
+ import { createSlice as createSlice3 } from "@reduxjs/toolkit";
2469
+ var initialState3 = {
2470
+ dataParse: null,
2471
+ idFile: null,
2472
+ isFileLoaded: false,
2473
+ loadingImport: false,
2474
+ selectedFile: null,
2475
+ errorData: null
2476
+ };
2477
+ var excelSlice = createSlice3({
2478
+ name: "excel",
2479
+ initialState: initialState3,
2480
+ reducers: {
2481
+ setDataParse: (state, action) => {
2482
+ state.dataParse = action.payload;
2483
+ },
2484
+ setIdFile: (state, action) => {
2485
+ state.idFile = action.payload;
2486
+ },
2487
+ setIsFileLoaded: (state, action) => {
2488
+ state.isFileLoaded = action.payload;
2489
+ },
2490
+ setLoadingImport: (state, action) => {
2491
+ state.loadingImport = action.payload;
2492
+ },
2493
+ setSelectedFile: (state, action) => {
2494
+ state.selectedFile = action.payload;
2495
+ },
2496
+ setErrorData: (state, action) => {
2497
+ state.errorData = action.payload;
2498
+ }
2499
+ }
2500
+ });
2501
+ var {
2502
+ setDataParse,
2503
+ setIdFile,
2504
+ setIsFileLoaded,
2505
+ setLoadingImport,
2506
+ setSelectedFile,
2507
+ setErrorData
2508
+ } = excelSlice.actions;
2509
+ var excel_slice_default = excelSlice.reducer;
2510
+
2511
+ // src/store/reducers/form-slice/index.ts
2512
+ import { createSlice as createSlice4 } from "@reduxjs/toolkit";
2513
+ var initialState4 = {
2514
+ viewDataStore: {},
2515
+ isShowingModalDetail: false,
2516
+ isShowModalTranslate: false,
2517
+ formSubmitComponent: {},
2518
+ fieldTranslation: null,
2519
+ listSubject: {},
2520
+ dataUser: {}
2521
+ };
2522
+ var formSlice = createSlice4({
2523
+ name: "form",
2524
+ initialState: initialState4,
2525
+ reducers: {
2526
+ setViewDataStore: (state, action) => {
2527
+ state.viewDataStore = action.payload;
2528
+ },
2529
+ setIsShowingModalDetail: (state, action) => {
2530
+ state.isShowingModalDetail = action.payload;
2531
+ },
2532
+ setIsShowModalTranslate: (state, action) => {
2533
+ state.isShowModalTranslate = action.payload;
2534
+ },
2535
+ setFormSubmitComponent: (state, action) => {
2536
+ state.formSubmitComponent[action.payload.key] = action.payload.component;
2537
+ },
2538
+ setFieldTranslate: (state, action) => {
2539
+ state.fieldTranslation = action.payload;
2540
+ },
2541
+ setListSubject: (state, action) => {
2542
+ state.listSubject = action.payload;
2543
+ },
2544
+ setDataUser: (state, action) => {
2545
+ state.dataUser = action.payload;
2546
+ }
2547
+ }
2548
+ });
2549
+ var {
2550
+ setViewDataStore,
2551
+ setIsShowingModalDetail,
2552
+ setIsShowModalTranslate,
2553
+ setFormSubmitComponent,
2554
+ setFieldTranslate,
2555
+ setListSubject,
2556
+ setDataUser
2557
+ } = formSlice.actions;
2558
+ var form_slice_default = formSlice.reducer;
2559
+
2560
+ // src/store/reducers/header-slice/index.ts
2561
+ import { createSlice as createSlice5 } from "@reduxjs/toolkit";
2562
+ var headerSlice = createSlice5({
2563
+ name: "header",
2564
+ initialState: {
2565
+ value: { allowedCompanyIds: [] }
2566
+ },
2567
+ reducers: {
2568
+ setHeader: (state, action) => {
2569
+ state.value = __spreadValues(__spreadValues({}, state.value), action.payload);
2570
+ },
2571
+ setAllowedCompanyIds: (state, action) => {
2572
+ state.value.allowedCompanyIds = action.payload;
2573
+ }
2574
+ }
2575
+ });
2576
+ var { setAllowedCompanyIds, setHeader } = headerSlice.actions;
2577
+ var header_slice_default = headerSlice.reducer;
2578
+
2579
+ // src/store/reducers/list-slice/index.ts
2580
+ import { createSlice as createSlice6 } from "@reduxjs/toolkit";
2581
+ var initialState5 = {
2582
+ pageLimit: 10,
2583
+ fields: {},
2584
+ order: "",
2585
+ selectedRowKeys: [],
2586
+ selectedRadioKey: 0,
2587
+ indexRowTableModal: -2,
2588
+ isUpdateTableModal: false,
2589
+ footerGroupTable: {},
2590
+ transferDetail: null,
2591
+ page: 0,
2592
+ domainTable: []
2593
+ };
2594
+ var listSlice = createSlice6({
2595
+ name: "list",
2596
+ initialState: initialState5,
2597
+ reducers: {
2598
+ setPageLimit: (state, action) => {
2599
+ state.pageLimit = action.payload;
2600
+ },
2601
+ setFields: (state, action) => {
2602
+ state.fields = action.payload;
2603
+ },
2604
+ setOrder: (state, action) => {
2605
+ state.order = action.payload;
2606
+ },
2607
+ setSelectedRowKeys: (state, action) => {
2608
+ state.selectedRowKeys = action.payload;
2609
+ },
2610
+ setSelectedRadioKey: (state, action) => {
2611
+ state.selectedRadioKey = action.payload;
2612
+ },
2613
+ setIndexRowTableModal: (state, action) => {
2614
+ state.indexRowTableModal = action.payload;
2615
+ },
2616
+ setTransferDetail: (state, action) => {
2617
+ state.transferDetail = action.payload;
2618
+ },
2619
+ setIsUpdateTableModal: (state, action) => {
2620
+ state.isUpdateTableModal = action.payload;
2621
+ },
2622
+ setPage: (state, action) => {
2623
+ state.page = action.payload;
2624
+ },
2625
+ setDomainTable: (state, action) => {
2626
+ state.domainTable = action.payload;
2627
+ }
2628
+ }
2629
+ });
2630
+ var {
2631
+ setPageLimit,
2632
+ setFields,
2633
+ setOrder,
2634
+ setSelectedRowKeys,
2635
+ setIndexRowTableModal,
2636
+ setIsUpdateTableModal,
2637
+ setPage,
2638
+ setSelectedRadioKey,
2639
+ setTransferDetail,
2640
+ setDomainTable
2641
+ } = listSlice.actions;
2642
+ var list_slice_default = listSlice.reducer;
2643
+
2644
+ // src/store/reducers/login-slice/index.ts
2645
+ import { createSlice as createSlice7 } from "@reduxjs/toolkit";
2646
+ var initialState6 = {
2647
+ db: "",
2648
+ redirectTo: "/",
2649
+ forgotPasswordUrl: "/"
2650
+ };
2651
+ var loginSlice = createSlice7({
2652
+ name: "login",
2653
+ initialState: initialState6,
2654
+ reducers: {
2655
+ setDb: (state, action) => {
2656
+ state.db = action.payload;
2657
+ },
2658
+ setRedirectTo: (state, action) => {
2659
+ state.redirectTo = action.payload;
2660
+ },
2661
+ setForgotPasswordUrl: (state, action) => {
2662
+ state.forgotPasswordUrl = action.payload;
2663
+ }
2664
+ }
2665
+ });
2666
+ var { setDb, setRedirectTo, setForgotPasswordUrl } = loginSlice.actions;
2667
+ var login_slice_default = loginSlice.reducer;
2668
+
2669
+ // src/store/reducers/navbar-slice/index.ts
2670
+ import { createSlice as createSlice8 } from "@reduxjs/toolkit";
2671
+ var initialState7 = {
2672
+ menuFocus: {},
2673
+ menuAction: {},
2674
+ navbarWidth: 250,
2675
+ menuList: []
2676
+ };
2677
+ var navbarSlice = createSlice8({
2678
+ name: "navbar",
2679
+ initialState: initialState7,
2680
+ reducers: {
2681
+ setMenuFocus: (state, action) => {
2682
+ state.menuFocus = action.payload;
2683
+ },
2684
+ setMenuFocusAction: (state, action) => {
2685
+ state.menuAction = action.payload;
2686
+ },
2687
+ setNavbarWidth: (state, action) => {
2688
+ state.navbarWidth = action.payload;
2689
+ },
2690
+ setMenuList: (state, action) => {
2691
+ state.menuList = action.payload;
2692
+ }
2693
+ }
2694
+ });
2695
+ var { setMenuFocus, setMenuFocusAction, setNavbarWidth, setMenuList } = navbarSlice.actions;
2696
+ var navbar_slice_default = navbarSlice.reducer;
2697
+
2698
+ // src/store/reducers/profile-slice/index.ts
2699
+ import { createSlice as createSlice9 } from "@reduxjs/toolkit";
2700
+ var initialState8 = {
2701
+ profile: {}
2702
+ };
2703
+ var profileSlice = createSlice9({
2704
+ name: "profile",
2705
+ initialState: initialState8,
2706
+ reducers: {
2707
+ setProfile: (state, action) => {
2708
+ state.profile = action.payload;
2709
+ }
2710
+ }
2711
+ });
2712
+ var { setProfile } = profileSlice.actions;
2713
+ var profile_slice_default = profileSlice.reducer;
2714
+
2715
+ // src/store/reducers/search-slice/index.ts
2716
+ import { createSlice as createSlice10 } from "@reduxjs/toolkit";
2717
+ var initialState9 = {
2718
+ groupByDomain: null,
2719
+ searchBy: [],
2720
+ searchString: "",
2721
+ hoveredIndexSearchList: null,
2722
+ selectedTags: [],
2723
+ firstDomain: null,
2724
+ searchMap: {},
2725
+ filterBy: [],
2726
+ groupBy: []
2727
+ };
2728
+ var searchSlice = createSlice10({
2729
+ name: "search",
2730
+ initialState: initialState9,
2731
+ reducers: {
2732
+ setGroupByDomain: (state, action) => {
2733
+ state.groupByDomain = action.payload;
2734
+ },
2735
+ setSearchBy: (state, action) => {
2736
+ state.searchBy = action.payload;
2737
+ },
2738
+ setSearchString: (state, action) => {
2739
+ state.searchString = action.payload;
2740
+ },
2741
+ setHoveredIndexSearchList: (state, action) => {
2742
+ state.hoveredIndexSearchList = action.payload;
2743
+ },
2744
+ setSelectedTags: (state, action) => {
2745
+ state.selectedTags = action.payload;
2746
+ },
2747
+ setFirstDomain: (state, action) => {
2748
+ state.firstDomain = action.payload;
2749
+ },
2750
+ setFilterBy: (state, action) => {
2751
+ state.filterBy = action.payload;
2752
+ },
2753
+ setGroupBy: (state, action) => {
2754
+ state.groupBy = action.payload;
2755
+ },
2756
+ setSearchMap: (state, action) => {
2757
+ state.searchMap = action.payload;
2758
+ },
2759
+ updateSearchMap: (state, action) => {
2760
+ if (!state.searchMap[action.payload.key]) {
2761
+ state.searchMap[action.payload.key] = [];
2762
+ }
2763
+ state.searchMap[action.payload.key].push(action.payload.value);
2764
+ },
2765
+ removeKeyFromSearchMap: (state, action) => {
2766
+ const { key, item } = action.payload;
2767
+ const values = state.searchMap[key];
2768
+ if (!values) return;
2769
+ if (item) {
2770
+ const filtered = values.filter((value) => value.name !== item.name);
2771
+ if (filtered.length > 0) {
2772
+ state.searchMap[key] = filtered;
2773
+ } else {
2774
+ delete state.searchMap[key];
2775
+ }
2776
+ } else {
2777
+ delete state.searchMap[key];
2778
+ }
2779
+ },
2780
+ clearSearchMap: (state) => {
2781
+ state.searchMap = {};
2782
+ }
2783
+ }
2784
+ });
2785
+ var {
2786
+ setGroupByDomain,
2787
+ setSelectedTags,
2788
+ setSearchString,
2789
+ setHoveredIndexSearchList,
2790
+ setFirstDomain,
2791
+ setSearchBy,
2792
+ setFilterBy,
2793
+ setSearchMap,
2794
+ updateSearchMap,
2795
+ removeKeyFromSearchMap,
2796
+ setGroupBy,
2797
+ clearSearchMap
2798
+ } = searchSlice.actions;
2799
+ var search_slice_default = searchSlice.reducer;
2800
+
2801
+ // src/store/store.ts
2802
+ import { configureStore } from "@reduxjs/toolkit";
2803
+
2804
+ // node_modules/redux/dist/redux.mjs
2805
+ function formatProdErrorMessage(code) {
2806
+ return `Minified Redux error #${code}; visit https://redux.js.org/Errors?code=${code} for the full message or use the non-minified dev environment for full errors. `;
2807
+ }
2808
+ var randomString = () => Math.random().toString(36).substring(7).split("").join(".");
2809
+ var ActionTypes = {
2810
+ INIT: `@@redux/INIT${/* @__PURE__ */ randomString()}`,
2811
+ REPLACE: `@@redux/REPLACE${/* @__PURE__ */ randomString()}`,
2812
+ PROBE_UNKNOWN_ACTION: () => `@@redux/PROBE_UNKNOWN_ACTION${randomString()}`
2813
+ };
2814
+ var actionTypes_default = ActionTypes;
2815
+ function isPlainObject(obj) {
2816
+ if (typeof obj !== "object" || obj === null)
2817
+ return false;
2818
+ let proto = obj;
2819
+ while (Object.getPrototypeOf(proto) !== null) {
2820
+ proto = Object.getPrototypeOf(proto);
2821
+ }
2822
+ return Object.getPrototypeOf(obj) === proto || Object.getPrototypeOf(obj) === null;
2823
+ }
2824
+ function miniKindOf(val) {
2825
+ if (val === void 0)
2826
+ return "undefined";
2827
+ if (val === null)
2828
+ return "null";
2829
+ const type = typeof val;
2830
+ switch (type) {
2831
+ case "boolean":
2832
+ case "string":
2833
+ case "number":
2834
+ case "symbol":
2835
+ case "function": {
2836
+ return type;
2837
+ }
2838
+ }
2839
+ if (Array.isArray(val))
2840
+ return "array";
2841
+ if (isDate(val))
2842
+ return "date";
2843
+ if (isError(val))
2844
+ return "error";
2845
+ const constructorName = ctorName(val);
2846
+ switch (constructorName) {
2847
+ case "Symbol":
2848
+ case "Promise":
2849
+ case "WeakMap":
2850
+ case "WeakSet":
2851
+ case "Map":
2852
+ case "Set":
2853
+ return constructorName;
2854
+ }
2855
+ return Object.prototype.toString.call(val).slice(8, -1).toLowerCase().replace(/\s/g, "");
2856
+ }
2857
+ function ctorName(val) {
2858
+ return typeof val.constructor === "function" ? val.constructor.name : null;
2859
+ }
2860
+ function isError(val) {
2861
+ return val instanceof Error || typeof val.message === "string" && val.constructor && typeof val.constructor.stackTraceLimit === "number";
2862
+ }
2863
+ function isDate(val) {
2864
+ if (val instanceof Date)
2865
+ return true;
2866
+ return typeof val.toDateString === "function" && typeof val.getDate === "function" && typeof val.setDate === "function";
2867
+ }
2868
+ function kindOf(val) {
2869
+ let typeOfVal = typeof val;
2870
+ if (process.env.NODE_ENV !== "production") {
2871
+ typeOfVal = miniKindOf(val);
2872
+ }
2873
+ return typeOfVal;
2874
+ }
2875
+ function warning(message) {
2876
+ if (typeof console !== "undefined" && typeof console.error === "function") {
2877
+ console.error(message);
2878
+ }
2879
+ try {
2880
+ throw new Error(message);
2881
+ } catch (e) {
2882
+ }
2883
+ }
2884
+ function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
2885
+ const reducerKeys = Object.keys(reducers);
2886
+ const argumentName = action && action.type === actionTypes_default.INIT ? "preloadedState argument passed to createStore" : "previous state received by the reducer";
2887
+ if (reducerKeys.length === 0) {
2888
+ return "Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.";
2889
+ }
2890
+ if (!isPlainObject(inputState)) {
2891
+ return `The ${argumentName} has unexpected type of "${kindOf(inputState)}". Expected argument to be an object with the following keys: "${reducerKeys.join('", "')}"`;
2892
+ }
2893
+ const unexpectedKeys = Object.keys(inputState).filter((key) => !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]);
2894
+ unexpectedKeys.forEach((key) => {
2895
+ unexpectedKeyCache[key] = true;
2896
+ });
2897
+ if (action && action.type === actionTypes_default.REPLACE)
2898
+ return;
2899
+ if (unexpectedKeys.length > 0) {
2900
+ return `Unexpected ${unexpectedKeys.length > 1 ? "keys" : "key"} "${unexpectedKeys.join('", "')}" found in ${argumentName}. Expected to find one of the known reducer keys instead: "${reducerKeys.join('", "')}". Unexpected keys will be ignored.`;
2901
+ }
2902
+ }
2903
+ function assertReducerShape(reducers) {
2904
+ Object.keys(reducers).forEach((key) => {
2905
+ const reducer = reducers[key];
2906
+ const initialState10 = reducer(void 0, {
2907
+ type: actionTypes_default.INIT
2908
+ });
2909
+ if (typeof initialState10 === "undefined") {
2910
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(12) : `The slice reducer for key "${key}" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.`);
2911
+ }
2912
+ if (typeof reducer(void 0, {
2913
+ type: actionTypes_default.PROBE_UNKNOWN_ACTION()
2914
+ }) === "undefined") {
2915
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(13) : `The slice reducer for key "${key}" returned undefined when probed with a random type. Don't try to handle '${actionTypes_default.INIT}' or other actions in "redux/*" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null.`);
2916
+ }
2917
+ });
2918
+ }
2919
+ function combineReducers(reducers) {
2920
+ const reducerKeys = Object.keys(reducers);
2921
+ const finalReducers = {};
2922
+ for (let i = 0; i < reducerKeys.length; i++) {
2923
+ const key = reducerKeys[i];
2924
+ if (process.env.NODE_ENV !== "production") {
2925
+ if (typeof reducers[key] === "undefined") {
2926
+ warning(`No reducer provided for key "${key}"`);
2927
+ }
2928
+ }
2929
+ if (typeof reducers[key] === "function") {
2930
+ finalReducers[key] = reducers[key];
2931
+ }
2932
+ }
2933
+ const finalReducerKeys = Object.keys(finalReducers);
2934
+ let unexpectedKeyCache;
2935
+ if (process.env.NODE_ENV !== "production") {
2936
+ unexpectedKeyCache = {};
2937
+ }
2938
+ let shapeAssertionError;
2939
+ try {
2940
+ assertReducerShape(finalReducers);
2941
+ } catch (e) {
2942
+ shapeAssertionError = e;
2943
+ }
2944
+ return function combination(state = {}, action) {
2945
+ if (shapeAssertionError) {
2946
+ throw shapeAssertionError;
2947
+ }
2948
+ if (process.env.NODE_ENV !== "production") {
2949
+ const warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);
2950
+ if (warningMessage) {
2951
+ warning(warningMessage);
2952
+ }
2953
+ }
2954
+ let hasChanged = false;
2955
+ const nextState = {};
2956
+ for (let i = 0; i < finalReducerKeys.length; i++) {
2957
+ const key = finalReducerKeys[i];
2958
+ const reducer = finalReducers[key];
2959
+ const previousStateForKey = state[key];
2960
+ const nextStateForKey = reducer(previousStateForKey, action);
2961
+ if (typeof nextStateForKey === "undefined") {
2962
+ const actionType = action && action.type;
2963
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(14) : `When called with an action of type ${actionType ? `"${String(actionType)}"` : "(unknown type)"}, the slice reducer for key "${key}" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.`);
2964
+ }
2965
+ nextState[key] = nextStateForKey;
2966
+ hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
2967
+ }
2968
+ hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length;
2969
+ return hasChanged ? nextState : state;
2970
+ };
2971
+ }
2972
+
2973
+ // src/store/store.ts
2974
+ var rootReducer = combineReducers({
2975
+ env: env_slice_default,
2976
+ header: header_slice_default,
2977
+ navbar: navbar_slice_default,
2978
+ list: list_slice_default,
2979
+ search: search_slice_default,
2980
+ form: form_slice_default,
2981
+ breadcrumbs: breadcrums_slice_default,
2982
+ login: login_slice_default,
2983
+ excel: excel_slice_default,
2984
+ profile: profile_slice_default
2985
+ });
2986
+ var envStore = configureStore({
2987
+ reducer: rootReducer,
2988
+ middleware: (getDefaultMiddleware) => getDefaultMiddleware({
2989
+ serializableCheck: false
2990
+ })
2991
+ });
2992
+
2993
+ // src/environment/EnvStore.ts
2994
+ var EnvStore = class {
2995
+ constructor(envStore2, localStorageUtils2, sessionStorageUtils2) {
2996
+ this.envStore = envStore2;
2997
+ this.localStorageUtils = localStorageUtils2;
2998
+ this.sessionStorageUtils = sessionStorageUtils2;
2999
+ this.setup();
3000
+ }
3001
+ setup() {
3002
+ const env2 = this.envStore.getState().env;
3003
+ this.baseUrl = env2 == null ? void 0 : env2.baseUrl;
3004
+ this.requests = env2 == null ? void 0 : env2.requests;
3005
+ this.context = env2 == null ? void 0 : env2.context;
3006
+ this.defaultCompany = env2 == null ? void 0 : env2.defaultCompany;
3007
+ this.config = env2 == null ? void 0 : env2.config;
3008
+ this.companies = (env2 == null ? void 0 : env2.companies) || [];
3009
+ this.user = env2 == null ? void 0 : env2.user;
3010
+ this.db = env2 == null ? void 0 : env2.db;
3011
+ this.refreshTokenEndpoint = env2 == null ? void 0 : env2.refreshTokenEndpoint;
3012
+ }
3013
+ setupEnv(envConfig) {
3014
+ const dispatch = this.envStore.dispatch;
3015
+ const env2 = __spreadProps(__spreadValues({}, envConfig), {
3016
+ localStorageUtils: this.localStorageUtils,
3017
+ sessionStorageUtils: this.sessionStorageUtils
3018
+ });
3019
+ const requests = axiosClient.init(env2);
3020
+ dispatch(setEnv(__spreadProps(__spreadValues({}, env2), { requests })));
3021
+ this.setup();
3022
+ }
3023
+ setUid(uid) {
3024
+ const dispatch = this.envStore.dispatch;
3025
+ dispatch(setUid(uid));
3026
+ this.setup();
3027
+ }
3028
+ setLang(lang) {
3029
+ const dispatch = this.envStore.dispatch;
3030
+ dispatch(setLang(lang));
3031
+ this.setup();
3032
+ }
3033
+ setAllowCompanies(allowCompanies) {
3034
+ const dispatch = this.envStore.dispatch;
3035
+ dispatch(setAllowCompanies(allowCompanies));
3036
+ this.setup();
3037
+ }
3038
+ setCompanies(companies) {
3039
+ const dispatch = this.envStore.dispatch;
3040
+ dispatch(setCompanies(companies));
3041
+ this.setup();
3042
+ }
3043
+ setDefaultCompany(company) {
3044
+ const dispatch = this.envStore.dispatch;
3045
+ dispatch(setDefaultCompany(company));
3046
+ this.setup();
3047
+ }
3048
+ setUserInfo(userInfo) {
3049
+ const dispatch = this.envStore.dispatch;
3050
+ dispatch(setUser(userInfo));
3051
+ this.setup();
3052
+ }
3053
+ };
3054
+ var env = null;
3055
+ function initEnv({
3056
+ localStorageUtils: localStorageUtils2,
3057
+ sessionStorageUtils: sessionStorageUtils2
3058
+ }) {
3059
+ env = new EnvStore(envStore, localStorageUtils2, sessionStorageUtils2);
3060
+ return env;
3061
+ }
3062
+ function getEnv() {
3063
+ if (!env)
3064
+ env = new EnvStore(envStore, localStorageUtils(), sessionStorageUtils());
3065
+ return env;
3066
+ }
3067
+ export {
3068
+ EnvStore,
3069
+ env,
3070
+ getEnv,
3071
+ initEnv
3072
+ };