manualofme-bridge 0.1.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/cli.js +3649 -59
  2. package/package.json +1 -1
package/cli.js CHANGED
@@ -1,8 +1,32 @@
1
1
  #!/usr/bin/env node
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
2
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
3
8
  var __esm = (fn, res) => function __init() {
4
9
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
10
  };
11
+ var __commonJS = (cb, mod) => function __require() {
12
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
13
+ };
14
+ var __copyProps = (to, from, except, desc) => {
15
+ if (from && typeof from === "object" || typeof from === "function") {
16
+ for (let key of __getOwnPropNames(from))
17
+ if (!__hasOwnProp.call(to, key) && key !== except)
18
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
23
+ // If the importer is in node compatibility mode or this is not an ESM
24
+ // file that has been converted to a CommonJS file using a Babel-
25
+ // compatible transform (i.e. "__esModule" has not been set), then set
26
+ // "default" to the CommonJS "module.exports" for node compatibility.
27
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
28
+ mod
29
+ ));
6
30
 
7
31
  // src/config.ts
8
32
  import { createHash } from "node:crypto";
@@ -263,6 +287,9 @@ var init_enums = __esm({
263
287
 
264
288
  // ../../packages/shared/src/schemas/common.ts
265
289
  import { z as z3 } from "zod";
290
+ function queryList(item) {
291
+ return z3.string().transform((v) => v.split(",").filter(Boolean)).pipe(z3.array(item).min(1));
292
+ }
266
293
  var Id, IsoDateTime, QueryBool, PageQuery;
267
294
  var init_common = __esm({
268
295
  "../../packages/shared/src/schemas/common.ts"() {
@@ -353,7 +380,7 @@ function deriveBridgeKey(token) {
353
380
  const digest2 = sha256(new TextEncoder().encode(`manualofme-bridge-url:${token}`));
354
381
  return `${BRIDGE_KEY_PREFIX}${base64url(digest2)}`;
355
382
  }
356
- var BRIDGE_SUBPROTOCOL, BRIDGE_CLOSE_UNAUTHORIZED, BridgeClientMessage, BridgeChatItem, BridgePermissionRequest, BridgeSessionInfo, BridgeServerMessage, BRIDGE_KEY_PREFIX, RegisterBridgeKey, BridgePublicUrl, PublishBridgeUrl, BridgeEndpoint;
383
+ var BRIDGE_SUBPROTOCOL, BRIDGE_CLOSE_UNAUTHORIZED, BRIDGE_PERMISSION_MODES, BridgePermissionMode, BridgeModel, BRIDGE_MAX_ATTACHMENTS, BridgeAttachment, BridgeClientMessage, BridgeChatItem, BridgePermissionRequest, BridgeSessionInfo, BridgeServerMessage, BRIDGE_KEY_PREFIX, RegisterBridgeKey, BridgePublicUrl, PublishBridgeUrl, BridgeEndpoint;
357
384
  var init_bridge = __esm({
358
385
  "../../packages/shared/src/schemas/bridge.ts"() {
359
386
  "use strict";
@@ -361,6 +388,20 @@ var init_bridge = __esm({
361
388
  init_notify();
362
389
  BRIDGE_SUBPROTOCOL = "manualofme-bridge";
363
390
  BRIDGE_CLOSE_UNAUTHORIZED = 4401;
391
+ BRIDGE_PERMISSION_MODES = [
392
+ "default",
393
+ "acceptEdits",
394
+ "plan",
395
+ "bypassPermissions"
396
+ ];
397
+ BridgePermissionMode = z5.enum(BRIDGE_PERMISSION_MODES);
398
+ BridgeModel = z5.string().max(100).regex(/^[A-Za-z0-9._[\]-]+$/, "T\xEAn model kh\xF4ng h\u1EE3p l\u1EC7").nullable();
399
+ BRIDGE_MAX_ATTACHMENTS = 4;
400
+ BridgeAttachment = z5.object({
401
+ name: z5.string().trim().min(1).max(200),
402
+ mimeType: z5.string().max(200),
403
+ data: z5.string().regex(/^[A-Za-z0-9+/]*={0,2}$/, "data ph\u1EA3i l\xE0 base64")
404
+ }).strict();
364
405
  BridgeClientMessage = z5.discriminatedUnion("type", [
365
406
  /** Liệt kê các session của project (cả session mở từ VS Code). */
366
407
  z5.object({ type: z5.literal("list_sessions") }).strict(),
@@ -368,9 +409,20 @@ var init_bridge = __esm({
368
409
  z5.object({ type: z5.literal("open_session"), sessionId: z5.uuid().nullable() }).strict(),
369
410
  z5.object({
370
411
  type: z5.literal("send"),
371
- text: z5.string().trim().min(1).max(2e4),
372
- clientId: z5.string().max(64).optional()
412
+ /** Rỗng được khi có tệp đính kèm. */
413
+ text: z5.string().trim().max(2e4),
414
+ clientId: z5.string().max(64).optional(),
373
415
  // bridge trả lại trong item user để app khử trùng
416
+ attachments: z5.array(BridgeAttachment).max(BRIDGE_MAX_ATTACHMENTS).optional()
417
+ }).strict(),
418
+ /**
419
+ * Đổi chế độ duyệt / model, áp cho mọi app và nhớ qua lần khởi động lại. Đổi chế độ khi đang
420
+ * chạy thì các yêu cầu duyệt mà chế độ mới tự cho phép được duyệt luôn; model áp từ lượt sau.
421
+ */
422
+ z5.object({
423
+ type: z5.literal("set_options"),
424
+ permissionMode: BridgePermissionMode.optional(),
425
+ model: BridgeModel.optional()
374
426
  }).strict(),
375
427
  /** Dừng lượt đang chạy. */
376
428
  z5.object({ type: z5.literal("interrupt") }).strict(),
@@ -417,7 +469,10 @@ var init_bridge = __esm({
417
469
  sessionId: z5.string().nullable(),
418
470
  busy: z5.boolean(),
419
471
  // đang có lượt chạy
420
- pendingPermissions: z5.array(BridgePermissionRequest)
472
+ pendingPermissions: z5.array(BridgePermissionRequest),
473
+ // Bridge bản cũ không gửi hai trường này (chưa đổi được chế độ / model từ app)
474
+ permissionMode: BridgePermissionMode.optional(),
475
+ model: BridgeModel.optional()
421
476
  }),
422
477
  /** Toàn bộ lịch sử (đã cắt bớt) của session hiện tại: khi kết nối và khi đổi session. */
423
478
  z5.object({
@@ -578,11 +633,3389 @@ var init_announce = __esm({
578
633
  }
579
634
  });
580
635
 
636
+ // ../../node_modules/.pnpm/rrule@2.8.1/node_modules/rrule/dist/es5/rrule.js
637
+ var require_rrule = __commonJS({
638
+ "../../node_modules/.pnpm/rrule@2.8.1/node_modules/rrule/dist/es5/rrule.js"(exports, module) {
639
+ (function webpackUniversalModuleDefinition(root, factory) {
640
+ if (typeof exports === "object" && typeof module === "object")
641
+ module.exports = factory();
642
+ else if (typeof define === "function" && define.amd)
643
+ define([], factory);
644
+ else if (typeof exports === "object")
645
+ exports["rrule"] = factory();
646
+ else
647
+ root["rrule"] = factory();
648
+ })(typeof self !== "undefined" ? self : exports, () => {
649
+ return (
650
+ /******/
651
+ (() => {
652
+ "use strict";
653
+ var __webpack_require__ = {};
654
+ (() => {
655
+ __webpack_require__.d = (exports2, definition) => {
656
+ for (var key in definition) {
657
+ if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports2, key)) {
658
+ Object.defineProperty(exports2, key, { enumerable: true, get: definition[key] });
659
+ }
660
+ }
661
+ };
662
+ })();
663
+ (() => {
664
+ __webpack_require__.o = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
665
+ })();
666
+ (() => {
667
+ __webpack_require__.r = (exports2) => {
668
+ if (typeof Symbol !== "undefined" && Symbol.toStringTag) {
669
+ Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
670
+ }
671
+ Object.defineProperty(exports2, "__esModule", { value: true });
672
+ };
673
+ })();
674
+ var __webpack_exports__ = {};
675
+ __webpack_require__.r(__webpack_exports__);
676
+ __webpack_require__.d(__webpack_exports__, {
677
+ "ALL_WEEKDAYS": () => (
678
+ /* reexport */
679
+ ALL_WEEKDAYS
680
+ ),
681
+ "Frequency": () => (
682
+ /* reexport */
683
+ Frequency
684
+ ),
685
+ "RRule": () => (
686
+ /* reexport */
687
+ RRule2
688
+ ),
689
+ "RRuleSet": () => (
690
+ /* reexport */
691
+ RRuleSet
692
+ ),
693
+ "Weekday": () => (
694
+ /* reexport */
695
+ Weekday
696
+ ),
697
+ "datetime": () => (
698
+ /* reexport */
699
+ datetime
700
+ ),
701
+ "rrulestr": () => (
702
+ /* reexport */
703
+ rrulestr
704
+ )
705
+ });
706
+ ;
707
+ var ALL_WEEKDAYS = [
708
+ "MO",
709
+ "TU",
710
+ "WE",
711
+ "TH",
712
+ "FR",
713
+ "SA",
714
+ "SU"
715
+ ];
716
+ var Weekday = (
717
+ /** @class */
718
+ (function() {
719
+ function Weekday2(weekday, n) {
720
+ if (n === 0)
721
+ throw new Error("Can't create weekday with n == 0");
722
+ this.weekday = weekday;
723
+ this.n = n;
724
+ }
725
+ Weekday2.fromStr = function(str) {
726
+ return new Weekday2(ALL_WEEKDAYS.indexOf(str));
727
+ };
728
+ Weekday2.prototype.nth = function(n) {
729
+ return this.n === n ? this : new Weekday2(this.weekday, n);
730
+ };
731
+ Weekday2.prototype.equals = function(other) {
732
+ return this.weekday === other.weekday && this.n === other.n;
733
+ };
734
+ Weekday2.prototype.toString = function() {
735
+ var s = ALL_WEEKDAYS[this.weekday];
736
+ if (this.n)
737
+ s = (this.n > 0 ? "+" : "") + String(this.n) + s;
738
+ return s;
739
+ };
740
+ Weekday2.prototype.getJsWeekday = function() {
741
+ return this.weekday === 6 ? 0 : this.weekday + 1;
742
+ };
743
+ return Weekday2;
744
+ })()
745
+ );
746
+ ;
747
+ var isPresent = function(value) {
748
+ return value !== null && value !== void 0;
749
+ };
750
+ var isNumber = function(value) {
751
+ return typeof value === "number";
752
+ };
753
+ var isWeekdayStr = function(value) {
754
+ return typeof value === "string" && ALL_WEEKDAYS.includes(value);
755
+ };
756
+ var isArray = Array.isArray;
757
+ var range = function(start, end) {
758
+ if (end === void 0) {
759
+ end = start;
760
+ }
761
+ if (arguments.length === 1) {
762
+ end = start;
763
+ start = 0;
764
+ }
765
+ var rang = [];
766
+ for (var i = start; i < end; i++)
767
+ rang.push(i);
768
+ return rang;
769
+ };
770
+ var clone = function(array) {
771
+ return [].concat(array);
772
+ };
773
+ var repeat = function(value, times) {
774
+ var i = 0;
775
+ var array = [];
776
+ if (isArray(value)) {
777
+ for (; i < times; i++)
778
+ array[i] = [].concat(value);
779
+ } else {
780
+ for (; i < times; i++)
781
+ array[i] = value;
782
+ }
783
+ return array;
784
+ };
785
+ var toArray = function(item) {
786
+ if (isArray(item)) {
787
+ return item;
788
+ }
789
+ return [item];
790
+ };
791
+ function padStart(item, targetLength, padString) {
792
+ if (padString === void 0) {
793
+ padString = " ";
794
+ }
795
+ var str = String(item);
796
+ targetLength = targetLength >> 0;
797
+ if (str.length > targetLength) {
798
+ return String(str);
799
+ }
800
+ targetLength = targetLength - str.length;
801
+ if (targetLength > padString.length) {
802
+ padString += repeat(padString, targetLength / padString.length);
803
+ }
804
+ return padString.slice(0, targetLength) + String(str);
805
+ }
806
+ var split = function(str, sep, num) {
807
+ var splits = str.split(sep);
808
+ return num ? splits.slice(0, num).concat([splits.slice(num).join(sep)]) : splits;
809
+ };
810
+ var pymod = function(a, b) {
811
+ var r = a % b;
812
+ return r * b < 0 ? r + b : r;
813
+ };
814
+ var divmod = function(a, b) {
815
+ return { div: Math.floor(a / b), mod: pymod(a, b) };
816
+ };
817
+ var empty = function(obj) {
818
+ return !isPresent(obj) || obj.length === 0;
819
+ };
820
+ var notEmpty = function(obj) {
821
+ return !empty(obj);
822
+ };
823
+ var includes = function(arr, val) {
824
+ return notEmpty(arr) && arr.indexOf(val) !== -1;
825
+ };
826
+ ;
827
+ var datetime = function(y, m, d, h, i, s) {
828
+ if (h === void 0) {
829
+ h = 0;
830
+ }
831
+ if (i === void 0) {
832
+ i = 0;
833
+ }
834
+ if (s === void 0) {
835
+ s = 0;
836
+ }
837
+ return new Date(Date.UTC(y, m - 1, d, h, i, s));
838
+ };
839
+ var MONTH_DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
840
+ var ONE_DAY = 1e3 * 60 * 60 * 24;
841
+ var MAXYEAR = 9999;
842
+ var ORDINAL_BASE = datetime(1970, 1, 1);
843
+ var PY_WEEKDAYS = [6, 0, 1, 2, 3, 4, 5];
844
+ var getYearDay = function(date) {
845
+ var dateNoTime = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
846
+ return Math.ceil((dateNoTime.valueOf() - new Date(date.getUTCFullYear(), 0, 1).valueOf()) / ONE_DAY) + 1;
847
+ };
848
+ var isLeapYear = function(year) {
849
+ return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
850
+ };
851
+ var isDate = function(value) {
852
+ return value instanceof Date;
853
+ };
854
+ var isValidDate = function(value) {
855
+ return isDate(value) && !isNaN(value.getTime());
856
+ };
857
+ var tzOffset = function(date) {
858
+ return date.getTimezoneOffset() * 60 * 1e3;
859
+ };
860
+ var daysBetween = function(date1, date2) {
861
+ var date1ms = date1.getTime();
862
+ var date2ms = date2.getTime();
863
+ var differencems = date1ms - date2ms;
864
+ return Math.round(differencems / ONE_DAY);
865
+ };
866
+ var toOrdinal = function(date) {
867
+ return daysBetween(date, ORDINAL_BASE);
868
+ };
869
+ var fromOrdinal = function(ordinal) {
870
+ return new Date(ORDINAL_BASE.getTime() + ordinal * ONE_DAY);
871
+ };
872
+ var getMonthDays = function(date) {
873
+ var month = date.getUTCMonth();
874
+ return month === 1 && isLeapYear(date.getUTCFullYear()) ? 29 : MONTH_DAYS[month];
875
+ };
876
+ var getWeekday = function(date) {
877
+ return PY_WEEKDAYS[date.getUTCDay()];
878
+ };
879
+ var monthRange = function(year, month) {
880
+ var date = datetime(year, month + 1, 1);
881
+ return [getWeekday(date), getMonthDays(date)];
882
+ };
883
+ var combine = function(date, time) {
884
+ time = time || date;
885
+ return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), time.getHours(), time.getMinutes(), time.getSeconds(), time.getMilliseconds()));
886
+ };
887
+ var dateutil_clone = function(date) {
888
+ var dolly = new Date(date.getTime());
889
+ return dolly;
890
+ };
891
+ var cloneDates = function(dates) {
892
+ var clones = [];
893
+ for (var i = 0; i < dates.length; i++) {
894
+ clones.push(dateutil_clone(dates[i]));
895
+ }
896
+ return clones;
897
+ };
898
+ var sort = function(dates) {
899
+ dates.sort(function(a, b) {
900
+ return a.getTime() - b.getTime();
901
+ });
902
+ };
903
+ var timeToUntilString = function(time, utc) {
904
+ if (utc === void 0) {
905
+ utc = true;
906
+ }
907
+ var date = new Date(time);
908
+ return [
909
+ padStart(date.getUTCFullYear().toString(), 4, "0"),
910
+ padStart(date.getUTCMonth() + 1, 2, "0"),
911
+ padStart(date.getUTCDate(), 2, "0"),
912
+ "T",
913
+ padStart(date.getUTCHours(), 2, "0"),
914
+ padStart(date.getUTCMinutes(), 2, "0"),
915
+ padStart(date.getUTCSeconds(), 2, "0"),
916
+ utc ? "Z" : ""
917
+ ].join("");
918
+ };
919
+ var untilStringToDate = function(until) {
920
+ var re = /^(\d{4})(\d{2})(\d{2})(T(\d{2})(\d{2})(\d{2})Z?)?$/;
921
+ var bits = re.exec(until);
922
+ if (!bits)
923
+ throw new Error("Invalid UNTIL value: ".concat(until));
924
+ return new Date(Date.UTC(parseInt(bits[1], 10), parseInt(bits[2], 10) - 1, parseInt(bits[3], 10), parseInt(bits[5], 10) || 0, parseInt(bits[6], 10) || 0, parseInt(bits[7], 10) || 0));
925
+ };
926
+ var dateTZtoISO8601 = function(date, timeZone) {
927
+ var dateStr = date.toLocaleString("sv-SE", { timeZone });
928
+ return dateStr.replace(" ", "T") + "Z";
929
+ };
930
+ var dateInTimeZone = function(date, timeZone) {
931
+ var localTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
932
+ var dateInLocalTZ = new Date(dateTZtoISO8601(date, localTimeZone));
933
+ var dateInTargetTZ = new Date(dateTZtoISO8601(date, timeZone !== null && timeZone !== void 0 ? timeZone : "UTC"));
934
+ var tzOffset2 = dateInTargetTZ.getTime() - dateInLocalTZ.getTime();
935
+ return new Date(date.getTime() - tzOffset2);
936
+ };
937
+ ;
938
+ var IterResult = (
939
+ /** @class */
940
+ (function() {
941
+ function IterResult2(method, args2) {
942
+ this.minDate = null;
943
+ this.maxDate = null;
944
+ this._result = [];
945
+ this.total = 0;
946
+ this.method = method;
947
+ this.args = args2;
948
+ if (method === "between") {
949
+ this.maxDate = args2.inc ? args2.before : new Date(args2.before.getTime() - 1);
950
+ this.minDate = args2.inc ? args2.after : new Date(args2.after.getTime() + 1);
951
+ } else if (method === "before") {
952
+ this.maxDate = args2.inc ? args2.dt : new Date(args2.dt.getTime() - 1);
953
+ } else if (method === "after") {
954
+ this.minDate = args2.inc ? args2.dt : new Date(args2.dt.getTime() + 1);
955
+ }
956
+ }
957
+ IterResult2.prototype.accept = function(date) {
958
+ ++this.total;
959
+ var tooEarly = this.minDate && date < this.minDate;
960
+ var tooLate = this.maxDate && date > this.maxDate;
961
+ if (this.method === "between") {
962
+ if (tooEarly)
963
+ return true;
964
+ if (tooLate)
965
+ return false;
966
+ } else if (this.method === "before") {
967
+ if (tooLate)
968
+ return false;
969
+ } else if (this.method === "after") {
970
+ if (tooEarly)
971
+ return true;
972
+ this.add(date);
973
+ return false;
974
+ }
975
+ return this.add(date);
976
+ };
977
+ IterResult2.prototype.add = function(date) {
978
+ this._result.push(date);
979
+ return true;
980
+ };
981
+ IterResult2.prototype.getValue = function() {
982
+ var res = this._result;
983
+ switch (this.method) {
984
+ case "all":
985
+ case "between":
986
+ return res;
987
+ case "before":
988
+ case "after":
989
+ default:
990
+ return res.length ? res[res.length - 1] : null;
991
+ }
992
+ };
993
+ IterResult2.prototype.clone = function() {
994
+ return new IterResult2(this.method, this.args);
995
+ };
996
+ return IterResult2;
997
+ })()
998
+ );
999
+ const iterresult = IterResult;
1000
+ ;
1001
+ var extendStatics = function(d, b) {
1002
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
1003
+ d2.__proto__ = b2;
1004
+ } || function(d2, b2) {
1005
+ for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
1006
+ };
1007
+ return extendStatics(d, b);
1008
+ };
1009
+ function __extends(d, b) {
1010
+ if (typeof b !== "function" && b !== null)
1011
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
1012
+ extendStatics(d, b);
1013
+ function __() {
1014
+ this.constructor = d;
1015
+ }
1016
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
1017
+ }
1018
+ var __assign = function() {
1019
+ __assign = Object.assign || function __assign2(t) {
1020
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
1021
+ s = arguments[i];
1022
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
1023
+ }
1024
+ return t;
1025
+ };
1026
+ return __assign.apply(this, arguments);
1027
+ };
1028
+ function __rest(s, e) {
1029
+ var t = {};
1030
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
1031
+ t[p] = s[p];
1032
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
1033
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
1034
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
1035
+ t[p[i]] = s[p[i]];
1036
+ }
1037
+ return t;
1038
+ }
1039
+ function __decorate(decorators, target, key, desc) {
1040
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1041
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1042
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1043
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1044
+ }
1045
+ function __param(paramIndex, decorator) {
1046
+ return function(target, key) {
1047
+ decorator(target, key, paramIndex);
1048
+ };
1049
+ }
1050
+ function __metadata(metadataKey, metadataValue) {
1051
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
1052
+ }
1053
+ function __awaiter(thisArg, _arguments, P, generator) {
1054
+ function adopt(value) {
1055
+ return value instanceof P ? value : new P(function(resolve) {
1056
+ resolve(value);
1057
+ });
1058
+ }
1059
+ return new (P || (P = Promise))(function(resolve, reject) {
1060
+ function fulfilled(value) {
1061
+ try {
1062
+ step(generator.next(value));
1063
+ } catch (e) {
1064
+ reject(e);
1065
+ }
1066
+ }
1067
+ function rejected(value) {
1068
+ try {
1069
+ step(generator["throw"](value));
1070
+ } catch (e) {
1071
+ reject(e);
1072
+ }
1073
+ }
1074
+ function step(result) {
1075
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
1076
+ }
1077
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
1078
+ });
1079
+ }
1080
+ function __generator(thisArg, body) {
1081
+ var _ = { label: 0, sent: function() {
1082
+ if (t[0] & 1) throw t[1];
1083
+ return t[1];
1084
+ }, trys: [], ops: [] }, f, y, t, g;
1085
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
1086
+ return this;
1087
+ }), g;
1088
+ function verb(n) {
1089
+ return function(v) {
1090
+ return step([n, v]);
1091
+ };
1092
+ }
1093
+ function step(op) {
1094
+ if (f) throw new TypeError("Generator is already executing.");
1095
+ while (_) try {
1096
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
1097
+ if (y = 0, t) op = [op[0] & 2, t.value];
1098
+ switch (op[0]) {
1099
+ case 0:
1100
+ case 1:
1101
+ t = op;
1102
+ break;
1103
+ case 4:
1104
+ _.label++;
1105
+ return { value: op[1], done: false };
1106
+ case 5:
1107
+ _.label++;
1108
+ y = op[1];
1109
+ op = [0];
1110
+ continue;
1111
+ case 7:
1112
+ op = _.ops.pop();
1113
+ _.trys.pop();
1114
+ continue;
1115
+ default:
1116
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
1117
+ _ = 0;
1118
+ continue;
1119
+ }
1120
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
1121
+ _.label = op[1];
1122
+ break;
1123
+ }
1124
+ if (op[0] === 6 && _.label < t[1]) {
1125
+ _.label = t[1];
1126
+ t = op;
1127
+ break;
1128
+ }
1129
+ if (t && _.label < t[2]) {
1130
+ _.label = t[2];
1131
+ _.ops.push(op);
1132
+ break;
1133
+ }
1134
+ if (t[2]) _.ops.pop();
1135
+ _.trys.pop();
1136
+ continue;
1137
+ }
1138
+ op = body.call(thisArg, _);
1139
+ } catch (e) {
1140
+ op = [6, e];
1141
+ y = 0;
1142
+ } finally {
1143
+ f = t = 0;
1144
+ }
1145
+ if (op[0] & 5) throw op[1];
1146
+ return { value: op[0] ? op[1] : void 0, done: true };
1147
+ }
1148
+ }
1149
+ var __createBinding = Object.create ? (function(o, m, k, k2) {
1150
+ if (k2 === void 0) k2 = k;
1151
+ var desc = Object.getOwnPropertyDescriptor(m, k);
1152
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1153
+ desc = { enumerable: true, get: function() {
1154
+ return m[k];
1155
+ } };
1156
+ }
1157
+ Object.defineProperty(o, k2, desc);
1158
+ }) : (function(o, m, k, k2) {
1159
+ if (k2 === void 0) k2 = k;
1160
+ o[k2] = m[k];
1161
+ });
1162
+ function __exportStar(m, o) {
1163
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
1164
+ }
1165
+ function __values(o) {
1166
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
1167
+ if (m) return m.call(o);
1168
+ if (o && typeof o.length === "number") return {
1169
+ next: function() {
1170
+ if (o && i >= o.length) o = void 0;
1171
+ return { value: o && o[i++], done: !o };
1172
+ }
1173
+ };
1174
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
1175
+ }
1176
+ function __read(o, n) {
1177
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
1178
+ if (!m) return o;
1179
+ var i = m.call(o), r, ar = [], e;
1180
+ try {
1181
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
1182
+ } catch (error) {
1183
+ e = { error };
1184
+ } finally {
1185
+ try {
1186
+ if (r && !r.done && (m = i["return"])) m.call(i);
1187
+ } finally {
1188
+ if (e) throw e.error;
1189
+ }
1190
+ }
1191
+ return ar;
1192
+ }
1193
+ function __spread() {
1194
+ for (var ar = [], i = 0; i < arguments.length; i++)
1195
+ ar = ar.concat(__read(arguments[i]));
1196
+ return ar;
1197
+ }
1198
+ function __spreadArrays() {
1199
+ for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
1200
+ for (var r = Array(s), k = 0, i = 0; i < il; i++)
1201
+ for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
1202
+ r[k] = a[j];
1203
+ return r;
1204
+ }
1205
+ function __spreadArray(to, from, pack) {
1206
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
1207
+ if (ar || !(i in from)) {
1208
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
1209
+ ar[i] = from[i];
1210
+ }
1211
+ }
1212
+ return to.concat(ar || Array.prototype.slice.call(from));
1213
+ }
1214
+ function __await(v) {
1215
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
1216
+ }
1217
+ function __asyncGenerator(thisArg, _arguments, generator) {
1218
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
1219
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
1220
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
1221
+ return this;
1222
+ }, i;
1223
+ function verb(n) {
1224
+ if (g[n]) i[n] = function(v) {
1225
+ return new Promise(function(a, b) {
1226
+ q.push([n, v, a, b]) > 1 || resume(n, v);
1227
+ });
1228
+ };
1229
+ }
1230
+ function resume(n, v) {
1231
+ try {
1232
+ step(g[n](v));
1233
+ } catch (e) {
1234
+ settle(q[0][3], e);
1235
+ }
1236
+ }
1237
+ function step(r) {
1238
+ r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
1239
+ }
1240
+ function fulfill(value) {
1241
+ resume("next", value);
1242
+ }
1243
+ function reject(value) {
1244
+ resume("throw", value);
1245
+ }
1246
+ function settle(f, v) {
1247
+ if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
1248
+ }
1249
+ }
1250
+ function __asyncDelegator(o) {
1251
+ var i, p;
1252
+ return i = {}, verb("next"), verb("throw", function(e) {
1253
+ throw e;
1254
+ }), verb("return"), i[Symbol.iterator] = function() {
1255
+ return this;
1256
+ }, i;
1257
+ function verb(n, f) {
1258
+ i[n] = o[n] ? function(v) {
1259
+ return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v;
1260
+ } : f;
1261
+ }
1262
+ }
1263
+ function __asyncValues(o) {
1264
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
1265
+ var m = o[Symbol.asyncIterator], i;
1266
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
1267
+ return this;
1268
+ }, i);
1269
+ function verb(n) {
1270
+ i[n] = o[n] && function(v) {
1271
+ return new Promise(function(resolve, reject) {
1272
+ v = o[n](v), settle(resolve, reject, v.done, v.value);
1273
+ });
1274
+ };
1275
+ }
1276
+ function settle(resolve, reject, d, v) {
1277
+ Promise.resolve(v).then(function(v2) {
1278
+ resolve({ value: v2, done: d });
1279
+ }, reject);
1280
+ }
1281
+ }
1282
+ function __makeTemplateObject(cooked, raw) {
1283
+ if (Object.defineProperty) {
1284
+ Object.defineProperty(cooked, "raw", { value: raw });
1285
+ } else {
1286
+ cooked.raw = raw;
1287
+ }
1288
+ return cooked;
1289
+ }
1290
+ ;
1291
+ var __setModuleDefault = Object.create ? (function(o, v) {
1292
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
1293
+ }) : function(o, v) {
1294
+ o["default"] = v;
1295
+ };
1296
+ function __importStar(mod) {
1297
+ if (mod && mod.__esModule) return mod;
1298
+ var result = {};
1299
+ if (mod != null) {
1300
+ for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
1301
+ }
1302
+ __setModuleDefault(result, mod);
1303
+ return result;
1304
+ }
1305
+ function __importDefault(mod) {
1306
+ return mod && mod.__esModule ? mod : { default: mod };
1307
+ }
1308
+ function __classPrivateFieldGet(receiver, state2, kind, f) {
1309
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
1310
+ if (typeof state2 === "function" ? receiver !== state2 || !f : !state2.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
1311
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state2.get(receiver);
1312
+ }
1313
+ function __classPrivateFieldSet(receiver, state2, value, kind, f) {
1314
+ if (kind === "m") throw new TypeError("Private method is not writable");
1315
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
1316
+ if (typeof state2 === "function" ? receiver !== state2 || !f : !state2.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
1317
+ return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state2.set(receiver, value), value;
1318
+ }
1319
+ function __classPrivateFieldIn(state2, receiver) {
1320
+ if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object");
1321
+ return typeof state2 === "function" ? receiver === state2 : state2.has(receiver);
1322
+ }
1323
+ ;
1324
+ var CallbackIterResult = (
1325
+ /** @class */
1326
+ (function(_super) {
1327
+ __extends(CallbackIterResult2, _super);
1328
+ function CallbackIterResult2(method, args2, iterator) {
1329
+ var _this = _super.call(this, method, args2) || this;
1330
+ _this.iterator = iterator;
1331
+ return _this;
1332
+ }
1333
+ CallbackIterResult2.prototype.add = function(date) {
1334
+ if (this.iterator(date, this._result.length)) {
1335
+ this._result.push(date);
1336
+ return true;
1337
+ }
1338
+ return false;
1339
+ };
1340
+ return CallbackIterResult2;
1341
+ })(iterresult)
1342
+ );
1343
+ const callbackiterresult = CallbackIterResult;
1344
+ ;
1345
+ var ENGLISH = {
1346
+ dayNames: [
1347
+ "Sunday",
1348
+ "Monday",
1349
+ "Tuesday",
1350
+ "Wednesday",
1351
+ "Thursday",
1352
+ "Friday",
1353
+ "Saturday"
1354
+ ],
1355
+ monthNames: [
1356
+ "January",
1357
+ "February",
1358
+ "March",
1359
+ "April",
1360
+ "May",
1361
+ "June",
1362
+ "July",
1363
+ "August",
1364
+ "September",
1365
+ "October",
1366
+ "November",
1367
+ "December"
1368
+ ],
1369
+ tokens: {
1370
+ SKIP: /^[ \r\n\t]+|^\.$/,
1371
+ number: /^[1-9][0-9]*/,
1372
+ numberAsText: /^(one|two|three)/i,
1373
+ every: /^every/i,
1374
+ "day(s)": /^days?/i,
1375
+ "weekday(s)": /^weekdays?/i,
1376
+ "week(s)": /^weeks?/i,
1377
+ "hour(s)": /^hours?/i,
1378
+ "minute(s)": /^minutes?/i,
1379
+ "month(s)": /^months?/i,
1380
+ "year(s)": /^years?/i,
1381
+ on: /^(on|in)/i,
1382
+ at: /^(at)/i,
1383
+ the: /^the/i,
1384
+ first: /^first/i,
1385
+ second: /^second/i,
1386
+ third: /^third/i,
1387
+ nth: /^([1-9][0-9]*)(\.|th|nd|rd|st)/i,
1388
+ last: /^last/i,
1389
+ for: /^for/i,
1390
+ "time(s)": /^times?/i,
1391
+ until: /^(un)?til/i,
1392
+ monday: /^mo(n(day)?)?/i,
1393
+ tuesday: /^tu(e(s(day)?)?)?/i,
1394
+ wednesday: /^we(d(n(esday)?)?)?/i,
1395
+ thursday: /^th(u(r(sday)?)?)?/i,
1396
+ friday: /^fr(i(day)?)?/i,
1397
+ saturday: /^sa(t(urday)?)?/i,
1398
+ sunday: /^su(n(day)?)?/i,
1399
+ january: /^jan(uary)?/i,
1400
+ february: /^feb(ruary)?/i,
1401
+ march: /^mar(ch)?/i,
1402
+ april: /^apr(il)?/i,
1403
+ may: /^may/i,
1404
+ june: /^june?/i,
1405
+ july: /^july?/i,
1406
+ august: /^aug(ust)?/i,
1407
+ september: /^sep(t(ember)?)?/i,
1408
+ october: /^oct(ober)?/i,
1409
+ november: /^nov(ember)?/i,
1410
+ december: /^dec(ember)?/i,
1411
+ comma: /^(,\s*|(and|or)\s*)+/i
1412
+ }
1413
+ };
1414
+ const i18n = ENGLISH;
1415
+ ;
1416
+ var contains = function(arr, val) {
1417
+ return arr.indexOf(val) !== -1;
1418
+ };
1419
+ var defaultGetText = function(id) {
1420
+ return id.toString();
1421
+ };
1422
+ var defaultDateFormatter = function(year, month, day) {
1423
+ return "".concat(month, " ").concat(day, ", ").concat(year);
1424
+ };
1425
+ var ToText = (
1426
+ /** @class */
1427
+ (function() {
1428
+ function ToText2(rrule, gettext, language, dateFormatter) {
1429
+ if (gettext === void 0) {
1430
+ gettext = defaultGetText;
1431
+ }
1432
+ if (language === void 0) {
1433
+ language = i18n;
1434
+ }
1435
+ if (dateFormatter === void 0) {
1436
+ dateFormatter = defaultDateFormatter;
1437
+ }
1438
+ this.text = [];
1439
+ this.language = language || i18n;
1440
+ this.gettext = gettext;
1441
+ this.dateFormatter = dateFormatter;
1442
+ this.rrule = rrule;
1443
+ this.options = rrule.options;
1444
+ this.origOptions = rrule.origOptions;
1445
+ if (this.origOptions.bymonthday) {
1446
+ var bymonthday = [].concat(this.options.bymonthday);
1447
+ var bynmonthday = [].concat(this.options.bynmonthday);
1448
+ bymonthday.sort(function(a, b) {
1449
+ return a - b;
1450
+ });
1451
+ bynmonthday.sort(function(a, b) {
1452
+ return b - a;
1453
+ });
1454
+ this.bymonthday = bymonthday.concat(bynmonthday);
1455
+ if (!this.bymonthday.length)
1456
+ this.bymonthday = null;
1457
+ }
1458
+ if (isPresent(this.origOptions.byweekday)) {
1459
+ var byweekday = !isArray(this.origOptions.byweekday) ? [this.origOptions.byweekday] : this.origOptions.byweekday;
1460
+ var days = String(byweekday);
1461
+ this.byweekday = {
1462
+ allWeeks: byweekday.filter(function(weekday) {
1463
+ return !weekday.n;
1464
+ }),
1465
+ someWeeks: byweekday.filter(function(weekday) {
1466
+ return Boolean(weekday.n);
1467
+ }),
1468
+ isWeekdays: days.indexOf("MO") !== -1 && days.indexOf("TU") !== -1 && days.indexOf("WE") !== -1 && days.indexOf("TH") !== -1 && days.indexOf("FR") !== -1 && days.indexOf("SA") === -1 && days.indexOf("SU") === -1,
1469
+ isEveryDay: days.indexOf("MO") !== -1 && days.indexOf("TU") !== -1 && days.indexOf("WE") !== -1 && days.indexOf("TH") !== -1 && days.indexOf("FR") !== -1 && days.indexOf("SA") !== -1 && days.indexOf("SU") !== -1
1470
+ };
1471
+ var sortWeekDays = function(a, b) {
1472
+ return a.weekday - b.weekday;
1473
+ };
1474
+ this.byweekday.allWeeks.sort(sortWeekDays);
1475
+ this.byweekday.someWeeks.sort(sortWeekDays);
1476
+ if (!this.byweekday.allWeeks.length)
1477
+ this.byweekday.allWeeks = null;
1478
+ if (!this.byweekday.someWeeks.length)
1479
+ this.byweekday.someWeeks = null;
1480
+ } else {
1481
+ this.byweekday = null;
1482
+ }
1483
+ }
1484
+ ToText2.isFullyConvertible = function(rrule) {
1485
+ var canConvert = true;
1486
+ if (!(rrule.options.freq in ToText2.IMPLEMENTED))
1487
+ return false;
1488
+ if (rrule.origOptions.until && rrule.origOptions.count)
1489
+ return false;
1490
+ for (var key in rrule.origOptions) {
1491
+ if (contains(["dtstart", "tzid", "wkst", "freq"], key))
1492
+ return true;
1493
+ if (!contains(ToText2.IMPLEMENTED[rrule.options.freq], key))
1494
+ return false;
1495
+ }
1496
+ return canConvert;
1497
+ };
1498
+ ToText2.prototype.isFullyConvertible = function() {
1499
+ return ToText2.isFullyConvertible(this.rrule);
1500
+ };
1501
+ ToText2.prototype.toString = function() {
1502
+ var gettext = this.gettext;
1503
+ if (!(this.options.freq in ToText2.IMPLEMENTED)) {
1504
+ return gettext("RRule error: Unable to fully convert this rrule to text");
1505
+ }
1506
+ this.text = [gettext("every")];
1507
+ this[RRule2.FREQUENCIES[this.options.freq]]();
1508
+ if (this.options.until) {
1509
+ this.add(gettext("until"));
1510
+ var until = this.options.until;
1511
+ this.add(this.dateFormatter(until.getUTCFullYear(), this.language.monthNames[until.getUTCMonth()], until.getUTCDate()));
1512
+ } else if (this.options.count) {
1513
+ this.add(gettext("for")).add(this.options.count.toString()).add(this.plural(this.options.count) ? gettext("times") : gettext("time"));
1514
+ }
1515
+ if (!this.isFullyConvertible())
1516
+ this.add(gettext("(~ approximate)"));
1517
+ return this.text.join("");
1518
+ };
1519
+ ToText2.prototype.HOURLY = function() {
1520
+ var gettext = this.gettext;
1521
+ if (this.options.interval !== 1)
1522
+ this.add(this.options.interval.toString());
1523
+ this.add(this.plural(this.options.interval) ? gettext("hours") : gettext("hour"));
1524
+ };
1525
+ ToText2.prototype.MINUTELY = function() {
1526
+ var gettext = this.gettext;
1527
+ if (this.options.interval !== 1)
1528
+ this.add(this.options.interval.toString());
1529
+ this.add(this.plural(this.options.interval) ? gettext("minutes") : gettext("minute"));
1530
+ };
1531
+ ToText2.prototype.DAILY = function() {
1532
+ var gettext = this.gettext;
1533
+ if (this.options.interval !== 1)
1534
+ this.add(this.options.interval.toString());
1535
+ if (this.byweekday && this.byweekday.isWeekdays) {
1536
+ this.add(this.plural(this.options.interval) ? gettext("weekdays") : gettext("weekday"));
1537
+ } else {
1538
+ this.add(this.plural(this.options.interval) ? gettext("days") : gettext("day"));
1539
+ }
1540
+ if (this.origOptions.bymonth) {
1541
+ this.add(gettext("in"));
1542
+ this._bymonth();
1543
+ }
1544
+ if (this.bymonthday) {
1545
+ this._bymonthday();
1546
+ } else if (this.byweekday) {
1547
+ this._byweekday();
1548
+ } else if (this.origOptions.byhour) {
1549
+ this._byhour();
1550
+ }
1551
+ };
1552
+ ToText2.prototype.WEEKLY = function() {
1553
+ var gettext = this.gettext;
1554
+ if (this.options.interval !== 1) {
1555
+ this.add(this.options.interval.toString()).add(this.plural(this.options.interval) ? gettext("weeks") : gettext("week"));
1556
+ }
1557
+ if (this.byweekday && this.byweekday.isWeekdays) {
1558
+ if (this.options.interval === 1) {
1559
+ this.add(this.plural(this.options.interval) ? gettext("weekdays") : gettext("weekday"));
1560
+ } else {
1561
+ this.add(gettext("on")).add(gettext("weekdays"));
1562
+ }
1563
+ } else if (this.byweekday && this.byweekday.isEveryDay) {
1564
+ this.add(this.plural(this.options.interval) ? gettext("days") : gettext("day"));
1565
+ } else {
1566
+ if (this.options.interval === 1)
1567
+ this.add(gettext("week"));
1568
+ if (this.origOptions.bymonth) {
1569
+ this.add(gettext("in"));
1570
+ this._bymonth();
1571
+ }
1572
+ if (this.bymonthday) {
1573
+ this._bymonthday();
1574
+ } else if (this.byweekday) {
1575
+ this._byweekday();
1576
+ }
1577
+ if (this.origOptions.byhour) {
1578
+ this._byhour();
1579
+ }
1580
+ }
1581
+ };
1582
+ ToText2.prototype.MONTHLY = function() {
1583
+ var gettext = this.gettext;
1584
+ if (this.origOptions.bymonth) {
1585
+ if (this.options.interval !== 1) {
1586
+ this.add(this.options.interval.toString()).add(gettext("months"));
1587
+ if (this.plural(this.options.interval))
1588
+ this.add(gettext("in"));
1589
+ } else {
1590
+ }
1591
+ this._bymonth();
1592
+ } else {
1593
+ if (this.options.interval !== 1) {
1594
+ this.add(this.options.interval.toString());
1595
+ }
1596
+ this.add(this.plural(this.options.interval) ? gettext("months") : gettext("month"));
1597
+ }
1598
+ if (this.bymonthday) {
1599
+ this._bymonthday();
1600
+ } else if (this.byweekday && this.byweekday.isWeekdays) {
1601
+ this.add(gettext("on")).add(gettext("weekdays"));
1602
+ } else if (this.byweekday) {
1603
+ this._byweekday();
1604
+ }
1605
+ };
1606
+ ToText2.prototype.YEARLY = function() {
1607
+ var gettext = this.gettext;
1608
+ if (this.origOptions.bymonth) {
1609
+ if (this.options.interval !== 1) {
1610
+ this.add(this.options.interval.toString());
1611
+ this.add(gettext("years"));
1612
+ } else {
1613
+ }
1614
+ this._bymonth();
1615
+ } else {
1616
+ if (this.options.interval !== 1) {
1617
+ this.add(this.options.interval.toString());
1618
+ }
1619
+ this.add(this.plural(this.options.interval) ? gettext("years") : gettext("year"));
1620
+ }
1621
+ if (this.bymonthday) {
1622
+ this._bymonthday();
1623
+ } else if (this.byweekday) {
1624
+ this._byweekday();
1625
+ }
1626
+ if (this.options.byyearday) {
1627
+ this.add(gettext("on the")).add(this.list(this.options.byyearday, this.nth, gettext("and"))).add(gettext("day"));
1628
+ }
1629
+ if (this.options.byweekno) {
1630
+ this.add(gettext("in")).add(this.plural(this.options.byweekno.length) ? gettext("weeks") : gettext("week")).add(this.list(this.options.byweekno, void 0, gettext("and")));
1631
+ }
1632
+ };
1633
+ ToText2.prototype._bymonthday = function() {
1634
+ var gettext = this.gettext;
1635
+ if (this.byweekday && this.byweekday.allWeeks) {
1636
+ this.add(gettext("on")).add(this.list(this.byweekday.allWeeks, this.weekdaytext, gettext("or"))).add(gettext("the")).add(this.list(this.bymonthday, this.nth, gettext("or")));
1637
+ } else {
1638
+ this.add(gettext("on the")).add(this.list(this.bymonthday, this.nth, gettext("and")));
1639
+ }
1640
+ };
1641
+ ToText2.prototype._byweekday = function() {
1642
+ var gettext = this.gettext;
1643
+ if (this.byweekday.allWeeks && !this.byweekday.isWeekdays) {
1644
+ this.add(gettext("on")).add(this.list(this.byweekday.allWeeks, this.weekdaytext));
1645
+ }
1646
+ if (this.byweekday.someWeeks) {
1647
+ if (this.byweekday.allWeeks)
1648
+ this.add(gettext("and"));
1649
+ this.add(gettext("on the")).add(this.list(this.byweekday.someWeeks, this.weekdaytext, gettext("and")));
1650
+ }
1651
+ };
1652
+ ToText2.prototype._byhour = function() {
1653
+ var gettext = this.gettext;
1654
+ this.add(gettext("at")).add(this.list(this.origOptions.byhour, void 0, gettext("and")));
1655
+ };
1656
+ ToText2.prototype._bymonth = function() {
1657
+ this.add(this.list(this.options.bymonth, this.monthtext, this.gettext("and")));
1658
+ };
1659
+ ToText2.prototype.nth = function(n) {
1660
+ n = parseInt(n.toString(), 10);
1661
+ var nth;
1662
+ var gettext = this.gettext;
1663
+ if (n === -1)
1664
+ return gettext("last");
1665
+ var npos = Math.abs(n);
1666
+ switch (npos) {
1667
+ case 1:
1668
+ case 21:
1669
+ case 31:
1670
+ nth = npos + gettext("st");
1671
+ break;
1672
+ case 2:
1673
+ case 22:
1674
+ nth = npos + gettext("nd");
1675
+ break;
1676
+ case 3:
1677
+ case 23:
1678
+ nth = npos + gettext("rd");
1679
+ break;
1680
+ default:
1681
+ nth = npos + gettext("th");
1682
+ }
1683
+ return n < 0 ? nth + " " + gettext("last") : nth;
1684
+ };
1685
+ ToText2.prototype.monthtext = function(m) {
1686
+ return this.language.monthNames[m - 1];
1687
+ };
1688
+ ToText2.prototype.weekdaytext = function(wday) {
1689
+ var weekday = isNumber(wday) ? (wday + 1) % 7 : wday.getJsWeekday();
1690
+ return (wday.n ? this.nth(wday.n) + " " : "") + this.language.dayNames[weekday];
1691
+ };
1692
+ ToText2.prototype.plural = function(n) {
1693
+ return n % 100 !== 1;
1694
+ };
1695
+ ToText2.prototype.add = function(s) {
1696
+ this.text.push(" ");
1697
+ this.text.push(s);
1698
+ return this;
1699
+ };
1700
+ ToText2.prototype.list = function(arr, callback, finalDelim, delim) {
1701
+ var _this = this;
1702
+ if (delim === void 0) {
1703
+ delim = ",";
1704
+ }
1705
+ if (!isArray(arr)) {
1706
+ arr = [arr];
1707
+ }
1708
+ var delimJoin = function(array, delimiter, finalDelimiter) {
1709
+ var list = "";
1710
+ for (var i = 0; i < array.length; i++) {
1711
+ if (i !== 0) {
1712
+ if (i === array.length - 1) {
1713
+ list += " " + finalDelimiter + " ";
1714
+ } else {
1715
+ list += delimiter + " ";
1716
+ }
1717
+ }
1718
+ list += array[i];
1719
+ }
1720
+ return list;
1721
+ };
1722
+ callback = callback || function(o) {
1723
+ return o.toString();
1724
+ };
1725
+ var realCallback = function(arg) {
1726
+ return callback && callback.call(_this, arg);
1727
+ };
1728
+ if (finalDelim) {
1729
+ return delimJoin(arr.map(realCallback), delim, finalDelim);
1730
+ } else {
1731
+ return arr.map(realCallback).join(delim + " ");
1732
+ }
1733
+ };
1734
+ return ToText2;
1735
+ })()
1736
+ );
1737
+ const totext = ToText;
1738
+ ;
1739
+ var Parser = (
1740
+ /** @class */
1741
+ (function() {
1742
+ function Parser2(rules) {
1743
+ this.done = true;
1744
+ this.rules = rules;
1745
+ }
1746
+ Parser2.prototype.start = function(text) {
1747
+ this.text = text;
1748
+ this.done = false;
1749
+ return this.nextSymbol();
1750
+ };
1751
+ Parser2.prototype.isDone = function() {
1752
+ return this.done && this.symbol === null;
1753
+ };
1754
+ Parser2.prototype.nextSymbol = function() {
1755
+ var best;
1756
+ var bestSymbol;
1757
+ this.symbol = null;
1758
+ this.value = null;
1759
+ do {
1760
+ if (this.done)
1761
+ return false;
1762
+ var rule = void 0;
1763
+ best = null;
1764
+ for (var name_1 in this.rules) {
1765
+ rule = this.rules[name_1];
1766
+ var match = rule.exec(this.text);
1767
+ if (match) {
1768
+ if (best === null || match[0].length > best[0].length) {
1769
+ best = match;
1770
+ bestSymbol = name_1;
1771
+ }
1772
+ }
1773
+ }
1774
+ if (best != null) {
1775
+ this.text = this.text.substr(best[0].length);
1776
+ if (this.text === "")
1777
+ this.done = true;
1778
+ }
1779
+ if (best == null) {
1780
+ this.done = true;
1781
+ this.symbol = null;
1782
+ this.value = null;
1783
+ return;
1784
+ }
1785
+ } while (bestSymbol === "SKIP");
1786
+ this.symbol = bestSymbol;
1787
+ this.value = best;
1788
+ return true;
1789
+ };
1790
+ Parser2.prototype.accept = function(name) {
1791
+ if (this.symbol === name) {
1792
+ if (this.value) {
1793
+ var v = this.value;
1794
+ this.nextSymbol();
1795
+ return v;
1796
+ }
1797
+ this.nextSymbol();
1798
+ return true;
1799
+ }
1800
+ return false;
1801
+ };
1802
+ Parser2.prototype.acceptNumber = function() {
1803
+ return this.accept("number");
1804
+ };
1805
+ Parser2.prototype.expect = function(name) {
1806
+ if (this.accept(name))
1807
+ return true;
1808
+ throw new Error("expected " + name + " but found " + this.symbol);
1809
+ };
1810
+ return Parser2;
1811
+ })()
1812
+ );
1813
+ function parseText(text, language) {
1814
+ if (language === void 0) {
1815
+ language = i18n;
1816
+ }
1817
+ var options = {};
1818
+ var ttr = new Parser(language.tokens);
1819
+ if (!ttr.start(text))
1820
+ return null;
1821
+ S();
1822
+ return options;
1823
+ function S() {
1824
+ ttr.expect("every");
1825
+ var n = ttr.acceptNumber();
1826
+ if (n)
1827
+ options.interval = parseInt(n[0], 10);
1828
+ if (ttr.isDone())
1829
+ throw new Error("Unexpected end");
1830
+ switch (ttr.symbol) {
1831
+ case "day(s)":
1832
+ options.freq = RRule2.DAILY;
1833
+ if (ttr.nextSymbol()) {
1834
+ AT();
1835
+ F();
1836
+ }
1837
+ break;
1838
+ // FIXME Note: every 2 weekdays != every two weeks on weekdays.
1839
+ // DAILY on weekdays is not a valid rule
1840
+ case "weekday(s)":
1841
+ options.freq = RRule2.WEEKLY;
1842
+ options.byweekday = [RRule2.MO, RRule2.TU, RRule2.WE, RRule2.TH, RRule2.FR];
1843
+ ttr.nextSymbol();
1844
+ AT();
1845
+ F();
1846
+ break;
1847
+ case "week(s)":
1848
+ options.freq = RRule2.WEEKLY;
1849
+ if (ttr.nextSymbol()) {
1850
+ ON();
1851
+ AT();
1852
+ F();
1853
+ }
1854
+ break;
1855
+ case "hour(s)":
1856
+ options.freq = RRule2.HOURLY;
1857
+ if (ttr.nextSymbol()) {
1858
+ ON();
1859
+ F();
1860
+ }
1861
+ break;
1862
+ case "minute(s)":
1863
+ options.freq = RRule2.MINUTELY;
1864
+ if (ttr.nextSymbol()) {
1865
+ ON();
1866
+ F();
1867
+ }
1868
+ break;
1869
+ case "month(s)":
1870
+ options.freq = RRule2.MONTHLY;
1871
+ if (ttr.nextSymbol()) {
1872
+ ON();
1873
+ F();
1874
+ }
1875
+ break;
1876
+ case "year(s)":
1877
+ options.freq = RRule2.YEARLY;
1878
+ if (ttr.nextSymbol()) {
1879
+ ON();
1880
+ F();
1881
+ }
1882
+ break;
1883
+ case "monday":
1884
+ case "tuesday":
1885
+ case "wednesday":
1886
+ case "thursday":
1887
+ case "friday":
1888
+ case "saturday":
1889
+ case "sunday":
1890
+ options.freq = RRule2.WEEKLY;
1891
+ var key = ttr.symbol.substr(0, 2).toUpperCase();
1892
+ options.byweekday = [RRule2[key]];
1893
+ if (!ttr.nextSymbol())
1894
+ return;
1895
+ while (ttr.accept("comma")) {
1896
+ if (ttr.isDone())
1897
+ throw new Error("Unexpected end");
1898
+ var wkd = decodeWKD();
1899
+ if (!wkd) {
1900
+ throw new Error("Unexpected symbol " + ttr.symbol + ", expected weekday");
1901
+ }
1902
+ options.byweekday.push(RRule2[wkd]);
1903
+ ttr.nextSymbol();
1904
+ }
1905
+ AT();
1906
+ MDAYs();
1907
+ F();
1908
+ break;
1909
+ case "january":
1910
+ case "february":
1911
+ case "march":
1912
+ case "april":
1913
+ case "may":
1914
+ case "june":
1915
+ case "july":
1916
+ case "august":
1917
+ case "september":
1918
+ case "october":
1919
+ case "november":
1920
+ case "december":
1921
+ options.freq = RRule2.YEARLY;
1922
+ options.bymonth = [decodeM()];
1923
+ if (!ttr.nextSymbol())
1924
+ return;
1925
+ while (ttr.accept("comma")) {
1926
+ if (ttr.isDone())
1927
+ throw new Error("Unexpected end");
1928
+ var m = decodeM();
1929
+ if (!m) {
1930
+ throw new Error("Unexpected symbol " + ttr.symbol + ", expected month");
1931
+ }
1932
+ options.bymonth.push(m);
1933
+ ttr.nextSymbol();
1934
+ }
1935
+ ON();
1936
+ F();
1937
+ break;
1938
+ default:
1939
+ throw new Error("Unknown symbol");
1940
+ }
1941
+ }
1942
+ function ON() {
1943
+ var on = ttr.accept("on");
1944
+ var the = ttr.accept("the");
1945
+ if (!(on || the))
1946
+ return;
1947
+ do {
1948
+ var nth = decodeNTH();
1949
+ var wkd = decodeWKD();
1950
+ var m = decodeM();
1951
+ if (nth) {
1952
+ if (wkd) {
1953
+ ttr.nextSymbol();
1954
+ if (!options.byweekday)
1955
+ options.byweekday = [];
1956
+ options.byweekday.push(RRule2[wkd].nth(nth));
1957
+ } else {
1958
+ if (!options.bymonthday)
1959
+ options.bymonthday = [];
1960
+ options.bymonthday.push(nth);
1961
+ ttr.accept("day(s)");
1962
+ }
1963
+ } else if (wkd) {
1964
+ ttr.nextSymbol();
1965
+ if (!options.byweekday)
1966
+ options.byweekday = [];
1967
+ options.byweekday.push(RRule2[wkd]);
1968
+ } else if (ttr.symbol === "weekday(s)") {
1969
+ ttr.nextSymbol();
1970
+ if (!options.byweekday) {
1971
+ options.byweekday = [RRule2.MO, RRule2.TU, RRule2.WE, RRule2.TH, RRule2.FR];
1972
+ }
1973
+ } else if (ttr.symbol === "week(s)") {
1974
+ ttr.nextSymbol();
1975
+ var n = ttr.acceptNumber();
1976
+ if (!n) {
1977
+ throw new Error("Unexpected symbol " + ttr.symbol + ", expected week number");
1978
+ }
1979
+ options.byweekno = [parseInt(n[0], 10)];
1980
+ while (ttr.accept("comma")) {
1981
+ n = ttr.acceptNumber();
1982
+ if (!n) {
1983
+ throw new Error("Unexpected symbol " + ttr.symbol + "; expected monthday");
1984
+ }
1985
+ options.byweekno.push(parseInt(n[0], 10));
1986
+ }
1987
+ } else if (m) {
1988
+ ttr.nextSymbol();
1989
+ if (!options.bymonth)
1990
+ options.bymonth = [];
1991
+ options.bymonth.push(m);
1992
+ } else {
1993
+ return;
1994
+ }
1995
+ } while (ttr.accept("comma") || ttr.accept("the") || ttr.accept("on"));
1996
+ }
1997
+ function AT() {
1998
+ var at = ttr.accept("at");
1999
+ if (!at)
2000
+ return;
2001
+ do {
2002
+ var n = ttr.acceptNumber();
2003
+ if (!n) {
2004
+ throw new Error("Unexpected symbol " + ttr.symbol + ", expected hour");
2005
+ }
2006
+ options.byhour = [parseInt(n[0], 10)];
2007
+ while (ttr.accept("comma")) {
2008
+ n = ttr.acceptNumber();
2009
+ if (!n) {
2010
+ throw new Error("Unexpected symbol " + ttr.symbol + "; expected hour");
2011
+ }
2012
+ options.byhour.push(parseInt(n[0], 10));
2013
+ }
2014
+ } while (ttr.accept("comma") || ttr.accept("at"));
2015
+ }
2016
+ function decodeM() {
2017
+ switch (ttr.symbol) {
2018
+ case "january":
2019
+ return 1;
2020
+ case "february":
2021
+ return 2;
2022
+ case "march":
2023
+ return 3;
2024
+ case "april":
2025
+ return 4;
2026
+ case "may":
2027
+ return 5;
2028
+ case "june":
2029
+ return 6;
2030
+ case "july":
2031
+ return 7;
2032
+ case "august":
2033
+ return 8;
2034
+ case "september":
2035
+ return 9;
2036
+ case "october":
2037
+ return 10;
2038
+ case "november":
2039
+ return 11;
2040
+ case "december":
2041
+ return 12;
2042
+ default:
2043
+ return false;
2044
+ }
2045
+ }
2046
+ function decodeWKD() {
2047
+ switch (ttr.symbol) {
2048
+ case "monday":
2049
+ case "tuesday":
2050
+ case "wednesday":
2051
+ case "thursday":
2052
+ case "friday":
2053
+ case "saturday":
2054
+ case "sunday":
2055
+ return ttr.symbol.substr(0, 2).toUpperCase();
2056
+ default:
2057
+ return false;
2058
+ }
2059
+ }
2060
+ function decodeNTH() {
2061
+ switch (ttr.symbol) {
2062
+ case "last":
2063
+ ttr.nextSymbol();
2064
+ return -1;
2065
+ case "first":
2066
+ ttr.nextSymbol();
2067
+ return 1;
2068
+ case "second":
2069
+ ttr.nextSymbol();
2070
+ return ttr.accept("last") ? -2 : 2;
2071
+ case "third":
2072
+ ttr.nextSymbol();
2073
+ return ttr.accept("last") ? -3 : 3;
2074
+ case "nth":
2075
+ var v = parseInt(ttr.value[1], 10);
2076
+ if (v < -366 || v > 366)
2077
+ throw new Error("Nth out of range: " + v);
2078
+ ttr.nextSymbol();
2079
+ return ttr.accept("last") ? -v : v;
2080
+ default:
2081
+ return false;
2082
+ }
2083
+ }
2084
+ function MDAYs() {
2085
+ ttr.accept("on");
2086
+ ttr.accept("the");
2087
+ var nth = decodeNTH();
2088
+ if (!nth)
2089
+ return;
2090
+ options.bymonthday = [nth];
2091
+ ttr.nextSymbol();
2092
+ while (ttr.accept("comma")) {
2093
+ nth = decodeNTH();
2094
+ if (!nth) {
2095
+ throw new Error("Unexpected symbol " + ttr.symbol + "; expected monthday");
2096
+ }
2097
+ options.bymonthday.push(nth);
2098
+ ttr.nextSymbol();
2099
+ }
2100
+ }
2101
+ function F() {
2102
+ if (ttr.symbol === "until") {
2103
+ var date = Date.parse(ttr.text);
2104
+ if (!date)
2105
+ throw new Error("Cannot parse until date:" + ttr.text);
2106
+ options.until = new Date(date);
2107
+ } else if (ttr.accept("for")) {
2108
+ options.count = parseInt(ttr.value[0], 10);
2109
+ ttr.expect("number");
2110
+ }
2111
+ }
2112
+ }
2113
+ ;
2114
+ var Frequency;
2115
+ (function(Frequency2) {
2116
+ Frequency2[Frequency2["YEARLY"] = 0] = "YEARLY";
2117
+ Frequency2[Frequency2["MONTHLY"] = 1] = "MONTHLY";
2118
+ Frequency2[Frequency2["WEEKLY"] = 2] = "WEEKLY";
2119
+ Frequency2[Frequency2["DAILY"] = 3] = "DAILY";
2120
+ Frequency2[Frequency2["HOURLY"] = 4] = "HOURLY";
2121
+ Frequency2[Frequency2["MINUTELY"] = 5] = "MINUTELY";
2122
+ Frequency2[Frequency2["SECONDLY"] = 6] = "SECONDLY";
2123
+ })(Frequency || (Frequency = {}));
2124
+ function freqIsDailyOrGreater(freq) {
2125
+ return freq < Frequency.HOURLY;
2126
+ }
2127
+ ;
2128
+ var fromText = function(text, language) {
2129
+ if (language === void 0) {
2130
+ language = i18n;
2131
+ }
2132
+ return new RRule2(parseText(text, language) || void 0);
2133
+ };
2134
+ var common = [
2135
+ "count",
2136
+ "until",
2137
+ "interval",
2138
+ "byweekday",
2139
+ "bymonthday",
2140
+ "bymonth"
2141
+ ];
2142
+ totext.IMPLEMENTED = [];
2143
+ totext.IMPLEMENTED[Frequency.HOURLY] = common;
2144
+ totext.IMPLEMENTED[Frequency.MINUTELY] = common;
2145
+ totext.IMPLEMENTED[Frequency.DAILY] = ["byhour"].concat(common);
2146
+ totext.IMPLEMENTED[Frequency.WEEKLY] = common;
2147
+ totext.IMPLEMENTED[Frequency.MONTHLY] = common;
2148
+ totext.IMPLEMENTED[Frequency.YEARLY] = ["byweekno", "byyearday"].concat(common);
2149
+ var toText = function(rrule, gettext, language, dateFormatter) {
2150
+ return new totext(rrule, gettext, language, dateFormatter).toString();
2151
+ };
2152
+ var isFullyConvertible = totext.isFullyConvertible;
2153
+ ;
2154
+ var Time = (
2155
+ /** @class */
2156
+ (function() {
2157
+ function Time2(hour, minute, second, millisecond) {
2158
+ this.hour = hour;
2159
+ this.minute = minute;
2160
+ this.second = second;
2161
+ this.millisecond = millisecond || 0;
2162
+ }
2163
+ Time2.prototype.getHours = function() {
2164
+ return this.hour;
2165
+ };
2166
+ Time2.prototype.getMinutes = function() {
2167
+ return this.minute;
2168
+ };
2169
+ Time2.prototype.getSeconds = function() {
2170
+ return this.second;
2171
+ };
2172
+ Time2.prototype.getMilliseconds = function() {
2173
+ return this.millisecond;
2174
+ };
2175
+ Time2.prototype.getTime = function() {
2176
+ return (this.hour * 60 * 60 + this.minute * 60 + this.second) * 1e3 + this.millisecond;
2177
+ };
2178
+ return Time2;
2179
+ })()
2180
+ );
2181
+ var DateTime = (
2182
+ /** @class */
2183
+ (function(_super) {
2184
+ __extends(DateTime2, _super);
2185
+ function DateTime2(year, month, day, hour, minute, second, millisecond) {
2186
+ var _this = _super.call(this, hour, minute, second, millisecond) || this;
2187
+ _this.year = year;
2188
+ _this.month = month;
2189
+ _this.day = day;
2190
+ return _this;
2191
+ }
2192
+ DateTime2.fromDate = function(date) {
2193
+ return new this(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.valueOf() % 1e3);
2194
+ };
2195
+ DateTime2.prototype.getWeekday = function() {
2196
+ return getWeekday(new Date(this.getTime()));
2197
+ };
2198
+ DateTime2.prototype.getTime = function() {
2199
+ return new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, this.millisecond)).getTime();
2200
+ };
2201
+ DateTime2.prototype.getDay = function() {
2202
+ return this.day;
2203
+ };
2204
+ DateTime2.prototype.getMonth = function() {
2205
+ return this.month;
2206
+ };
2207
+ DateTime2.prototype.getYear = function() {
2208
+ return this.year;
2209
+ };
2210
+ DateTime2.prototype.addYears = function(years) {
2211
+ this.year += years;
2212
+ };
2213
+ DateTime2.prototype.addMonths = function(months) {
2214
+ this.month += months;
2215
+ if (this.month > 12) {
2216
+ var yearDiv = Math.floor(this.month / 12);
2217
+ var monthMod = pymod(this.month, 12);
2218
+ this.month = monthMod;
2219
+ this.year += yearDiv;
2220
+ if (this.month === 0) {
2221
+ this.month = 12;
2222
+ --this.year;
2223
+ }
2224
+ }
2225
+ };
2226
+ DateTime2.prototype.addWeekly = function(days, wkst) {
2227
+ if (wkst > this.getWeekday()) {
2228
+ this.day += -(this.getWeekday() + 1 + (6 - wkst)) + days * 7;
2229
+ } else {
2230
+ this.day += -(this.getWeekday() - wkst) + days * 7;
2231
+ }
2232
+ this.fixDay();
2233
+ };
2234
+ DateTime2.prototype.addDaily = function(days) {
2235
+ this.day += days;
2236
+ this.fixDay();
2237
+ };
2238
+ DateTime2.prototype.addHours = function(hours, filtered, byhour) {
2239
+ if (filtered) {
2240
+ this.hour += Math.floor((23 - this.hour) / hours) * hours;
2241
+ }
2242
+ for (; ; ) {
2243
+ this.hour += hours;
2244
+ var _a = divmod(this.hour, 24), dayDiv = _a.div, hourMod = _a.mod;
2245
+ if (dayDiv) {
2246
+ this.hour = hourMod;
2247
+ this.addDaily(dayDiv);
2248
+ }
2249
+ if (empty(byhour) || includes(byhour, this.hour))
2250
+ break;
2251
+ }
2252
+ };
2253
+ DateTime2.prototype.addMinutes = function(minutes, filtered, byhour, byminute) {
2254
+ if (filtered) {
2255
+ this.minute += Math.floor((1439 - (this.hour * 60 + this.minute)) / minutes) * minutes;
2256
+ }
2257
+ for (; ; ) {
2258
+ this.minute += minutes;
2259
+ var _a = divmod(this.minute, 60), hourDiv = _a.div, minuteMod = _a.mod;
2260
+ if (hourDiv) {
2261
+ this.minute = minuteMod;
2262
+ this.addHours(hourDiv, false, byhour);
2263
+ }
2264
+ if ((empty(byhour) || includes(byhour, this.hour)) && (empty(byminute) || includes(byminute, this.minute))) {
2265
+ break;
2266
+ }
2267
+ }
2268
+ };
2269
+ DateTime2.prototype.addSeconds = function(seconds, filtered, byhour, byminute, bysecond) {
2270
+ if (filtered) {
2271
+ this.second += Math.floor((86399 - (this.hour * 3600 + this.minute * 60 + this.second)) / seconds) * seconds;
2272
+ }
2273
+ for (; ; ) {
2274
+ this.second += seconds;
2275
+ var _a = divmod(this.second, 60), minuteDiv = _a.div, secondMod = _a.mod;
2276
+ if (minuteDiv) {
2277
+ this.second = secondMod;
2278
+ this.addMinutes(minuteDiv, false, byhour, byminute);
2279
+ }
2280
+ if ((empty(byhour) || includes(byhour, this.hour)) && (empty(byminute) || includes(byminute, this.minute)) && (empty(bysecond) || includes(bysecond, this.second))) {
2281
+ break;
2282
+ }
2283
+ }
2284
+ };
2285
+ DateTime2.prototype.fixDay = function() {
2286
+ if (this.day <= 28) {
2287
+ return;
2288
+ }
2289
+ var daysinmonth = monthRange(this.year, this.month - 1)[1];
2290
+ if (this.day <= daysinmonth) {
2291
+ return;
2292
+ }
2293
+ while (this.day > daysinmonth) {
2294
+ this.day -= daysinmonth;
2295
+ ++this.month;
2296
+ if (this.month === 13) {
2297
+ this.month = 1;
2298
+ ++this.year;
2299
+ if (this.year > MAXYEAR) {
2300
+ return;
2301
+ }
2302
+ }
2303
+ daysinmonth = monthRange(this.year, this.month - 1)[1];
2304
+ }
2305
+ };
2306
+ DateTime2.prototype.add = function(options, filtered) {
2307
+ var freq = options.freq, interval = options.interval, wkst = options.wkst, byhour = options.byhour, byminute = options.byminute, bysecond = options.bysecond;
2308
+ switch (freq) {
2309
+ case Frequency.YEARLY:
2310
+ return this.addYears(interval);
2311
+ case Frequency.MONTHLY:
2312
+ return this.addMonths(interval);
2313
+ case Frequency.WEEKLY:
2314
+ return this.addWeekly(interval, wkst);
2315
+ case Frequency.DAILY:
2316
+ return this.addDaily(interval);
2317
+ case Frequency.HOURLY:
2318
+ return this.addHours(interval, filtered, byhour);
2319
+ case Frequency.MINUTELY:
2320
+ return this.addMinutes(interval, filtered, byhour, byminute);
2321
+ case Frequency.SECONDLY:
2322
+ return this.addSeconds(interval, filtered, byhour, byminute, bysecond);
2323
+ }
2324
+ };
2325
+ return DateTime2;
2326
+ })(Time)
2327
+ );
2328
+ ;
2329
+ function initializeOptions(options) {
2330
+ var invalid = [];
2331
+ var keys = Object.keys(options);
2332
+ for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
2333
+ var key = keys_1[_i];
2334
+ if (!includes(defaultKeys, key))
2335
+ invalid.push(key);
2336
+ if (isDate(options[key]) && !isValidDate(options[key])) {
2337
+ invalid.push(key);
2338
+ }
2339
+ }
2340
+ if (invalid.length) {
2341
+ throw new Error("Invalid options: " + invalid.join(", "));
2342
+ }
2343
+ return __assign({}, options);
2344
+ }
2345
+ function parseOptions(options) {
2346
+ var opts = __assign(__assign({}, DEFAULT_OPTIONS), initializeOptions(options));
2347
+ if (isPresent(opts.byeaster))
2348
+ opts.freq = RRule2.YEARLY;
2349
+ if (!(isPresent(opts.freq) && RRule2.FREQUENCIES[opts.freq])) {
2350
+ throw new Error("Invalid frequency: ".concat(opts.freq, " ").concat(options.freq));
2351
+ }
2352
+ if (!opts.dtstart)
2353
+ opts.dtstart = new Date((/* @__PURE__ */ new Date()).setMilliseconds(0));
2354
+ if (!isPresent(opts.wkst)) {
2355
+ opts.wkst = RRule2.MO.weekday;
2356
+ } else if (isNumber(opts.wkst)) {
2357
+ } else {
2358
+ opts.wkst = opts.wkst.weekday;
2359
+ }
2360
+ if (isPresent(opts.bysetpos)) {
2361
+ if (isNumber(opts.bysetpos))
2362
+ opts.bysetpos = [opts.bysetpos];
2363
+ for (var i = 0; i < opts.bysetpos.length; i++) {
2364
+ var v = opts.bysetpos[i];
2365
+ if (v === 0 || !(v >= -366 && v <= 366)) {
2366
+ throw new Error("bysetpos must be between 1 and 366, or between -366 and -1");
2367
+ }
2368
+ }
2369
+ }
2370
+ if (!(Boolean(opts.byweekno) || notEmpty(opts.byweekno) || notEmpty(opts.byyearday) || Boolean(opts.bymonthday) || notEmpty(opts.bymonthday) || isPresent(opts.byweekday) || isPresent(opts.byeaster))) {
2371
+ switch (opts.freq) {
2372
+ case RRule2.YEARLY:
2373
+ if (!opts.bymonth)
2374
+ opts.bymonth = opts.dtstart.getUTCMonth() + 1;
2375
+ opts.bymonthday = opts.dtstart.getUTCDate();
2376
+ break;
2377
+ case RRule2.MONTHLY:
2378
+ opts.bymonthday = opts.dtstart.getUTCDate();
2379
+ break;
2380
+ case RRule2.WEEKLY:
2381
+ opts.byweekday = [getWeekday(opts.dtstart)];
2382
+ break;
2383
+ }
2384
+ }
2385
+ if (isPresent(opts.bymonth) && !isArray(opts.bymonth)) {
2386
+ opts.bymonth = [opts.bymonth];
2387
+ }
2388
+ if (isPresent(opts.byyearday) && !isArray(opts.byyearday) && isNumber(opts.byyearday)) {
2389
+ opts.byyearday = [opts.byyearday];
2390
+ }
2391
+ if (!isPresent(opts.bymonthday)) {
2392
+ opts.bymonthday = [];
2393
+ opts.bynmonthday = [];
2394
+ } else if (isArray(opts.bymonthday)) {
2395
+ var bymonthday = [];
2396
+ var bynmonthday = [];
2397
+ for (var i = 0; i < opts.bymonthday.length; i++) {
2398
+ var v = opts.bymonthday[i];
2399
+ if (v > 0) {
2400
+ bymonthday.push(v);
2401
+ } else if (v < 0) {
2402
+ bynmonthday.push(v);
2403
+ }
2404
+ }
2405
+ opts.bymonthday = bymonthday;
2406
+ opts.bynmonthday = bynmonthday;
2407
+ } else if (opts.bymonthday < 0) {
2408
+ opts.bynmonthday = [opts.bymonthday];
2409
+ opts.bymonthday = [];
2410
+ } else {
2411
+ opts.bynmonthday = [];
2412
+ opts.bymonthday = [opts.bymonthday];
2413
+ }
2414
+ if (isPresent(opts.byweekno) && !isArray(opts.byweekno)) {
2415
+ opts.byweekno = [opts.byweekno];
2416
+ }
2417
+ if (!isPresent(opts.byweekday)) {
2418
+ opts.bynweekday = null;
2419
+ } else if (isNumber(opts.byweekday)) {
2420
+ opts.byweekday = [opts.byweekday];
2421
+ opts.bynweekday = null;
2422
+ } else if (isWeekdayStr(opts.byweekday)) {
2423
+ opts.byweekday = [Weekday.fromStr(opts.byweekday).weekday];
2424
+ opts.bynweekday = null;
2425
+ } else if (opts.byweekday instanceof Weekday) {
2426
+ if (!opts.byweekday.n || opts.freq > RRule2.MONTHLY) {
2427
+ opts.byweekday = [opts.byweekday.weekday];
2428
+ opts.bynweekday = null;
2429
+ } else {
2430
+ opts.bynweekday = [[opts.byweekday.weekday, opts.byweekday.n]];
2431
+ opts.byweekday = null;
2432
+ }
2433
+ } else {
2434
+ var byweekday = [];
2435
+ var bynweekday = [];
2436
+ for (var i = 0; i < opts.byweekday.length; i++) {
2437
+ var wday = opts.byweekday[i];
2438
+ if (isNumber(wday)) {
2439
+ byweekday.push(wday);
2440
+ continue;
2441
+ } else if (isWeekdayStr(wday)) {
2442
+ byweekday.push(Weekday.fromStr(wday).weekday);
2443
+ continue;
2444
+ }
2445
+ if (!wday.n || opts.freq > RRule2.MONTHLY) {
2446
+ byweekday.push(wday.weekday);
2447
+ } else {
2448
+ bynweekday.push([wday.weekday, wday.n]);
2449
+ }
2450
+ }
2451
+ opts.byweekday = notEmpty(byweekday) ? byweekday : null;
2452
+ opts.bynweekday = notEmpty(bynweekday) ? bynweekday : null;
2453
+ }
2454
+ if (!isPresent(opts.byhour)) {
2455
+ opts.byhour = opts.freq < RRule2.HOURLY ? [opts.dtstart.getUTCHours()] : null;
2456
+ } else if (isNumber(opts.byhour)) {
2457
+ opts.byhour = [opts.byhour];
2458
+ }
2459
+ if (!isPresent(opts.byminute)) {
2460
+ opts.byminute = opts.freq < RRule2.MINUTELY ? [opts.dtstart.getUTCMinutes()] : null;
2461
+ } else if (isNumber(opts.byminute)) {
2462
+ opts.byminute = [opts.byminute];
2463
+ }
2464
+ if (!isPresent(opts.bysecond)) {
2465
+ opts.bysecond = opts.freq < RRule2.SECONDLY ? [opts.dtstart.getUTCSeconds()] : null;
2466
+ } else if (isNumber(opts.bysecond)) {
2467
+ opts.bysecond = [opts.bysecond];
2468
+ }
2469
+ return { parsedOptions: opts };
2470
+ }
2471
+ function buildTimeset(opts) {
2472
+ var millisecondModulo = opts.dtstart.getTime() % 1e3;
2473
+ if (!freqIsDailyOrGreater(opts.freq)) {
2474
+ return [];
2475
+ }
2476
+ var timeset = [];
2477
+ opts.byhour.forEach(function(hour) {
2478
+ opts.byminute.forEach(function(minute) {
2479
+ opts.bysecond.forEach(function(second) {
2480
+ timeset.push(new Time(hour, minute, second, millisecondModulo));
2481
+ });
2482
+ });
2483
+ });
2484
+ return timeset;
2485
+ }
2486
+ ;
2487
+ function parseString(rfcString) {
2488
+ var options = rfcString.split("\n").map(parseLine).filter(function(x) {
2489
+ return x !== null;
2490
+ });
2491
+ return __assign(__assign({}, options[0]), options[1]);
2492
+ }
2493
+ function parseDtstart(line) {
2494
+ var options = {};
2495
+ var dtstartWithZone = /DTSTART(?:;TZID=([^:=]+?))?(?::|=)([^;\s]+)/i.exec(line);
2496
+ if (!dtstartWithZone) {
2497
+ return options;
2498
+ }
2499
+ var tzid = dtstartWithZone[1], dtstart = dtstartWithZone[2];
2500
+ if (tzid) {
2501
+ options.tzid = tzid;
2502
+ }
2503
+ options.dtstart = untilStringToDate(dtstart);
2504
+ return options;
2505
+ }
2506
+ function parseLine(rfcString) {
2507
+ rfcString = rfcString.replace(/^\s+|\s+$/, "");
2508
+ if (!rfcString.length)
2509
+ return null;
2510
+ var header = /^([A-Z]+?)[:;]/.exec(rfcString.toUpperCase());
2511
+ if (!header) {
2512
+ return parseRrule(rfcString);
2513
+ }
2514
+ var key = header[1];
2515
+ switch (key.toUpperCase()) {
2516
+ case "RRULE":
2517
+ case "EXRULE":
2518
+ return parseRrule(rfcString);
2519
+ case "DTSTART":
2520
+ return parseDtstart(rfcString);
2521
+ default:
2522
+ throw new Error("Unsupported RFC prop ".concat(key, " in ").concat(rfcString));
2523
+ }
2524
+ }
2525
+ function parseRrule(line) {
2526
+ var strippedLine = line.replace(/^RRULE:/i, "");
2527
+ var options = parseDtstart(strippedLine);
2528
+ var attrs = line.replace(/^(?:RRULE|EXRULE):/i, "").split(";");
2529
+ attrs.forEach(function(attr) {
2530
+ var _a = attr.split("="), key = _a[0], value = _a[1];
2531
+ switch (key.toUpperCase()) {
2532
+ case "FREQ":
2533
+ options.freq = Frequency[value.toUpperCase()];
2534
+ break;
2535
+ case "WKST":
2536
+ options.wkst = Days[value.toUpperCase()];
2537
+ break;
2538
+ case "COUNT":
2539
+ case "INTERVAL":
2540
+ case "BYSETPOS":
2541
+ case "BYMONTH":
2542
+ case "BYMONTHDAY":
2543
+ case "BYYEARDAY":
2544
+ case "BYWEEKNO":
2545
+ case "BYHOUR":
2546
+ case "BYMINUTE":
2547
+ case "BYSECOND":
2548
+ var num = parseNumber(value);
2549
+ var optionKey = key.toLowerCase();
2550
+ options[optionKey] = num;
2551
+ break;
2552
+ case "BYWEEKDAY":
2553
+ case "BYDAY":
2554
+ options.byweekday = parseWeekday(value);
2555
+ break;
2556
+ case "DTSTART":
2557
+ case "TZID":
2558
+ var dtstart = parseDtstart(line);
2559
+ options.tzid = dtstart.tzid;
2560
+ options.dtstart = dtstart.dtstart;
2561
+ break;
2562
+ case "UNTIL":
2563
+ options.until = untilStringToDate(value);
2564
+ break;
2565
+ case "BYEASTER":
2566
+ options.byeaster = Number(value);
2567
+ break;
2568
+ default:
2569
+ throw new Error("Unknown RRULE property '" + key + "'");
2570
+ }
2571
+ });
2572
+ return options;
2573
+ }
2574
+ function parseNumber(value) {
2575
+ if (value.indexOf(",") !== -1) {
2576
+ var values = value.split(",");
2577
+ return values.map(parseIndividualNumber);
2578
+ }
2579
+ return parseIndividualNumber(value);
2580
+ }
2581
+ function parseIndividualNumber(value) {
2582
+ if (/^[+-]?\d+$/.test(value)) {
2583
+ return Number(value);
2584
+ }
2585
+ return value;
2586
+ }
2587
+ function parseWeekday(value) {
2588
+ var days = value.split(",");
2589
+ return days.map(function(day) {
2590
+ if (day.length === 2) {
2591
+ return Days[day];
2592
+ }
2593
+ var parts = day.match(/^([+-]?\d{1,2})([A-Z]{2})$/);
2594
+ if (!parts || parts.length < 3) {
2595
+ throw new SyntaxError("Invalid weekday string: ".concat(day));
2596
+ }
2597
+ var n = Number(parts[1]);
2598
+ var wdaypart = parts[2];
2599
+ var wday = Days[wdaypart].weekday;
2600
+ return new Weekday(wday, n);
2601
+ });
2602
+ }
2603
+ ;
2604
+ var DateWithZone = (
2605
+ /** @class */
2606
+ (function() {
2607
+ function DateWithZone2(date, tzid) {
2608
+ if (isNaN(date.getTime())) {
2609
+ throw new RangeError("Invalid date passed to DateWithZone");
2610
+ }
2611
+ this.date = date;
2612
+ this.tzid = tzid;
2613
+ }
2614
+ Object.defineProperty(DateWithZone2.prototype, "isUTC", {
2615
+ get: function() {
2616
+ return !this.tzid || this.tzid.toUpperCase() === "UTC";
2617
+ },
2618
+ enumerable: false,
2619
+ configurable: true
2620
+ });
2621
+ DateWithZone2.prototype.toString = function() {
2622
+ var datestr = timeToUntilString(this.date.getTime(), this.isUTC);
2623
+ if (!this.isUTC) {
2624
+ return ";TZID=".concat(this.tzid, ":").concat(datestr);
2625
+ }
2626
+ return ":".concat(datestr);
2627
+ };
2628
+ DateWithZone2.prototype.getTime = function() {
2629
+ return this.date.getTime();
2630
+ };
2631
+ DateWithZone2.prototype.rezonedDate = function() {
2632
+ if (this.isUTC) {
2633
+ return this.date;
2634
+ }
2635
+ return dateInTimeZone(this.date, this.tzid);
2636
+ };
2637
+ return DateWithZone2;
2638
+ })()
2639
+ );
2640
+ ;
2641
+ function optionsToString(options) {
2642
+ var rrule = [];
2643
+ var dtstart = "";
2644
+ var keys = Object.keys(options);
2645
+ var defaultKeys2 = Object.keys(DEFAULT_OPTIONS);
2646
+ for (var i = 0; i < keys.length; i++) {
2647
+ if (keys[i] === "tzid")
2648
+ continue;
2649
+ if (!includes(defaultKeys2, keys[i]))
2650
+ continue;
2651
+ var key = keys[i].toUpperCase();
2652
+ var value = options[keys[i]];
2653
+ var outValue = "";
2654
+ if (!isPresent(value) || isArray(value) && !value.length)
2655
+ continue;
2656
+ switch (key) {
2657
+ case "FREQ":
2658
+ outValue = RRule2.FREQUENCIES[options.freq];
2659
+ break;
2660
+ case "WKST":
2661
+ if (isNumber(value)) {
2662
+ outValue = new Weekday(value).toString();
2663
+ } else {
2664
+ outValue = value.toString();
2665
+ }
2666
+ break;
2667
+ case "BYWEEKDAY":
2668
+ key = "BYDAY";
2669
+ outValue = toArray(value).map(function(wday) {
2670
+ if (wday instanceof Weekday) {
2671
+ return wday;
2672
+ }
2673
+ if (isArray(wday)) {
2674
+ return new Weekday(wday[0], wday[1]);
2675
+ }
2676
+ return new Weekday(wday);
2677
+ }).toString();
2678
+ break;
2679
+ case "DTSTART":
2680
+ dtstart = buildDtstart(value, options.tzid);
2681
+ break;
2682
+ case "UNTIL":
2683
+ outValue = timeToUntilString(value, !options.tzid);
2684
+ break;
2685
+ default:
2686
+ if (isArray(value)) {
2687
+ var strValues = [];
2688
+ for (var j = 0; j < value.length; j++) {
2689
+ strValues[j] = String(value[j]);
2690
+ }
2691
+ outValue = strValues.toString();
2692
+ } else {
2693
+ outValue = String(value);
2694
+ }
2695
+ }
2696
+ if (outValue) {
2697
+ rrule.push([key, outValue]);
2698
+ }
2699
+ }
2700
+ var rules = rrule.map(function(_a) {
2701
+ var key2 = _a[0], value2 = _a[1];
2702
+ return "".concat(key2, "=").concat(value2.toString());
2703
+ }).join(";");
2704
+ var ruleString = "";
2705
+ if (rules !== "") {
2706
+ ruleString = "RRULE:".concat(rules);
2707
+ }
2708
+ return [dtstart, ruleString].filter(function(x) {
2709
+ return !!x;
2710
+ }).join("\n");
2711
+ }
2712
+ function buildDtstart(dtstart, tzid) {
2713
+ if (!dtstart) {
2714
+ return "";
2715
+ }
2716
+ return "DTSTART" + new DateWithZone(new Date(dtstart), tzid).toString();
2717
+ }
2718
+ ;
2719
+ function argsMatch(left, right) {
2720
+ if (Array.isArray(left)) {
2721
+ if (!Array.isArray(right))
2722
+ return false;
2723
+ if (left.length !== right.length)
2724
+ return false;
2725
+ return left.every(function(date, i) {
2726
+ return date.getTime() === right[i].getTime();
2727
+ });
2728
+ }
2729
+ if (left instanceof Date) {
2730
+ return right instanceof Date && left.getTime() === right.getTime();
2731
+ }
2732
+ return left === right;
2733
+ }
2734
+ var Cache = (
2735
+ /** @class */
2736
+ (function() {
2737
+ function Cache2() {
2738
+ this.all = false;
2739
+ this.before = [];
2740
+ this.after = [];
2741
+ this.between = [];
2742
+ }
2743
+ Cache2.prototype._cacheAdd = function(what, value, args2) {
2744
+ if (value) {
2745
+ value = value instanceof Date ? dateutil_clone(value) : cloneDates(value);
2746
+ }
2747
+ if (what === "all") {
2748
+ this.all = value;
2749
+ } else {
2750
+ args2._value = value;
2751
+ this[what].push(args2);
2752
+ }
2753
+ };
2754
+ Cache2.prototype._cacheGet = function(what, args2) {
2755
+ var cached = false;
2756
+ var argsKeys = args2 ? Object.keys(args2) : [];
2757
+ var findCacheDiff = function(item2) {
2758
+ for (var i2 = 0; i2 < argsKeys.length; i2++) {
2759
+ var key = argsKeys[i2];
2760
+ if (!argsMatch(args2[key], item2[key])) {
2761
+ return true;
2762
+ }
2763
+ }
2764
+ return false;
2765
+ };
2766
+ var cachedObject = this[what];
2767
+ if (what === "all") {
2768
+ cached = this.all;
2769
+ } else if (isArray(cachedObject)) {
2770
+ for (var i = 0; i < cachedObject.length; i++) {
2771
+ var item = cachedObject[i];
2772
+ if (argsKeys.length && findCacheDiff(item))
2773
+ continue;
2774
+ cached = item._value;
2775
+ break;
2776
+ }
2777
+ }
2778
+ if (!cached && this.all) {
2779
+ var iterResult = new iterresult(what, args2);
2780
+ for (var i = 0; i < this.all.length; i++) {
2781
+ if (!iterResult.accept(this.all[i]))
2782
+ break;
2783
+ }
2784
+ cached = iterResult.getValue();
2785
+ this._cacheAdd(what, cached, args2);
2786
+ }
2787
+ return isArray(cached) ? cloneDates(cached) : cached instanceof Date ? dateutil_clone(cached) : cached;
2788
+ };
2789
+ return Cache2;
2790
+ })()
2791
+ );
2792
+ ;
2793
+ var M365MASK = __spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], repeat(1, 31), true), repeat(2, 28), true), repeat(3, 31), true), repeat(4, 30), true), repeat(5, 31), true), repeat(6, 30), true), repeat(7, 31), true), repeat(8, 31), true), repeat(9, 30), true), repeat(10, 31), true), repeat(11, 30), true), repeat(12, 31), true), repeat(1, 7), true);
2794
+ var M366MASK = __spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], repeat(1, 31), true), repeat(2, 29), true), repeat(3, 31), true), repeat(4, 30), true), repeat(5, 31), true), repeat(6, 30), true), repeat(7, 31), true), repeat(8, 31), true), repeat(9, 30), true), repeat(10, 31), true), repeat(11, 30), true), repeat(12, 31), true), repeat(1, 7), true);
2795
+ var M28 = range(1, 29);
2796
+ var M29 = range(1, 30);
2797
+ var M30 = range(1, 31);
2798
+ var M31 = range(1, 32);
2799
+ var MDAY366MASK = __spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], M31, true), M29, true), M31, true), M30, true), M31, true), M30, true), M31, true), M31, true), M30, true), M31, true), M30, true), M31, true), M31.slice(0, 7), true);
2800
+ var MDAY365MASK = __spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], M31, true), M28, true), M31, true), M30, true), M31, true), M30, true), M31, true), M31, true), M30, true), M31, true), M30, true), M31, true), M31.slice(0, 7), true);
2801
+ var NM28 = range(-28, 0);
2802
+ var NM29 = range(-29, 0);
2803
+ var NM30 = range(-30, 0);
2804
+ var NM31 = range(-31, 0);
2805
+ var NMDAY366MASK = __spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], NM31, true), NM29, true), NM31, true), NM30, true), NM31, true), NM30, true), NM31, true), NM31, true), NM30, true), NM31, true), NM30, true), NM31, true), NM31.slice(0, 7), true);
2806
+ var NMDAY365MASK = __spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], NM31, true), NM28, true), NM31, true), NM30, true), NM31, true), NM30, true), NM31, true), NM31, true), NM30, true), NM31, true), NM30, true), NM31, true), NM31.slice(0, 7), true);
2807
+ var M366RANGE = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366];
2808
+ var M365RANGE = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365];
2809
+ var WDAYMASK = (function() {
2810
+ var wdaymask = [];
2811
+ for (var i = 0; i < 55; i++)
2812
+ wdaymask = wdaymask.concat(range(7));
2813
+ return wdaymask;
2814
+ })();
2815
+ ;
2816
+ function rebuildYear(year, options) {
2817
+ var firstyday = datetime(year, 1, 1);
2818
+ var yearlen = isLeapYear(year) ? 366 : 365;
2819
+ var nextyearlen = isLeapYear(year + 1) ? 366 : 365;
2820
+ var yearordinal = toOrdinal(firstyday);
2821
+ var yearweekday = getWeekday(firstyday);
2822
+ var result = __assign(__assign({ yearlen, nextyearlen, yearordinal, yearweekday }, baseYearMasks(year)), { wnomask: null });
2823
+ if (empty(options.byweekno)) {
2824
+ return result;
2825
+ }
2826
+ result.wnomask = repeat(0, yearlen + 7);
2827
+ var firstwkst;
2828
+ var wyearlen;
2829
+ var no1wkst = firstwkst = pymod(7 - yearweekday + options.wkst, 7);
2830
+ if (no1wkst >= 4) {
2831
+ no1wkst = 0;
2832
+ wyearlen = result.yearlen + pymod(yearweekday - options.wkst, 7);
2833
+ } else {
2834
+ wyearlen = yearlen - no1wkst;
2835
+ }
2836
+ var div = Math.floor(wyearlen / 7);
2837
+ var mod = pymod(wyearlen, 7);
2838
+ var numweeks = Math.floor(div + mod / 4);
2839
+ for (var j = 0; j < options.byweekno.length; j++) {
2840
+ var n = options.byweekno[j];
2841
+ if (n < 0) {
2842
+ n += numweeks + 1;
2843
+ }
2844
+ if (!(n > 0 && n <= numweeks)) {
2845
+ continue;
2846
+ }
2847
+ var i = void 0;
2848
+ if (n > 1) {
2849
+ i = no1wkst + (n - 1) * 7;
2850
+ if (no1wkst !== firstwkst) {
2851
+ i -= 7 - firstwkst;
2852
+ }
2853
+ } else {
2854
+ i = no1wkst;
2855
+ }
2856
+ for (var k = 0; k < 7; k++) {
2857
+ result.wnomask[i] = 1;
2858
+ i++;
2859
+ if (result.wdaymask[i] === options.wkst)
2860
+ break;
2861
+ }
2862
+ }
2863
+ if (includes(options.byweekno, 1)) {
2864
+ var i = no1wkst + numweeks * 7;
2865
+ if (no1wkst !== firstwkst)
2866
+ i -= 7 - firstwkst;
2867
+ if (i < yearlen) {
2868
+ for (var j = 0; j < 7; j++) {
2869
+ result.wnomask[i] = 1;
2870
+ i += 1;
2871
+ if (result.wdaymask[i] === options.wkst)
2872
+ break;
2873
+ }
2874
+ }
2875
+ }
2876
+ if (no1wkst) {
2877
+ var lnumweeks = void 0;
2878
+ if (!includes(options.byweekno, -1)) {
2879
+ var lyearweekday = getWeekday(datetime(year - 1, 1, 1));
2880
+ var lno1wkst = pymod(7 - lyearweekday.valueOf() + options.wkst, 7);
2881
+ var lyearlen = isLeapYear(year - 1) ? 366 : 365;
2882
+ var weekst = void 0;
2883
+ if (lno1wkst >= 4) {
2884
+ lno1wkst = 0;
2885
+ weekst = lyearlen + pymod(lyearweekday - options.wkst, 7);
2886
+ } else {
2887
+ weekst = yearlen - no1wkst;
2888
+ }
2889
+ lnumweeks = Math.floor(52 + pymod(weekst, 7) / 4);
2890
+ } else {
2891
+ lnumweeks = -1;
2892
+ }
2893
+ if (includes(options.byweekno, lnumweeks)) {
2894
+ for (var i = 0; i < no1wkst; i++)
2895
+ result.wnomask[i] = 1;
2896
+ }
2897
+ }
2898
+ return result;
2899
+ }
2900
+ function baseYearMasks(year) {
2901
+ var yearlen = isLeapYear(year) ? 366 : 365;
2902
+ var firstyday = datetime(year, 1, 1);
2903
+ var wday = getWeekday(firstyday);
2904
+ if (yearlen === 365) {
2905
+ return {
2906
+ mmask: M365MASK,
2907
+ mdaymask: MDAY365MASK,
2908
+ nmdaymask: NMDAY365MASK,
2909
+ wdaymask: WDAYMASK.slice(wday),
2910
+ mrange: M365RANGE
2911
+ };
2912
+ }
2913
+ return {
2914
+ mmask: M366MASK,
2915
+ mdaymask: MDAY366MASK,
2916
+ nmdaymask: NMDAY366MASK,
2917
+ wdaymask: WDAYMASK.slice(wday),
2918
+ mrange: M366RANGE
2919
+ };
2920
+ }
2921
+ ;
2922
+ function rebuildMonth(year, month, yearlen, mrange, wdaymask, options) {
2923
+ var result = {
2924
+ lastyear: year,
2925
+ lastmonth: month,
2926
+ nwdaymask: []
2927
+ };
2928
+ var ranges = [];
2929
+ if (options.freq === RRule2.YEARLY) {
2930
+ if (empty(options.bymonth)) {
2931
+ ranges = [[0, yearlen]];
2932
+ } else {
2933
+ for (var j = 0; j < options.bymonth.length; j++) {
2934
+ month = options.bymonth[j];
2935
+ ranges.push(mrange.slice(month - 1, month + 1));
2936
+ }
2937
+ }
2938
+ } else if (options.freq === RRule2.MONTHLY) {
2939
+ ranges = [mrange.slice(month - 1, month + 1)];
2940
+ }
2941
+ if (empty(ranges)) {
2942
+ return result;
2943
+ }
2944
+ result.nwdaymask = repeat(0, yearlen);
2945
+ for (var j = 0; j < ranges.length; j++) {
2946
+ var rang = ranges[j];
2947
+ var first = rang[0];
2948
+ var last = rang[1] - 1;
2949
+ for (var k = 0; k < options.bynweekday.length; k++) {
2950
+ var i = void 0;
2951
+ var _a = options.bynweekday[k], wday = _a[0], n = _a[1];
2952
+ if (n < 0) {
2953
+ i = last + (n + 1) * 7;
2954
+ i -= pymod(wdaymask[i] - wday, 7);
2955
+ } else {
2956
+ i = first + (n - 1) * 7;
2957
+ i += pymod(7 - wdaymask[i] + wday, 7);
2958
+ }
2959
+ if (first <= i && i <= last)
2960
+ result.nwdaymask[i] = 1;
2961
+ }
2962
+ }
2963
+ return result;
2964
+ }
2965
+ ;
2966
+ function easter(y, offset) {
2967
+ if (offset === void 0) {
2968
+ offset = 0;
2969
+ }
2970
+ var a = y % 19;
2971
+ var b = Math.floor(y / 100);
2972
+ var c = y % 100;
2973
+ var d = Math.floor(b / 4);
2974
+ var e = b % 4;
2975
+ var f = Math.floor((b + 8) / 25);
2976
+ var g = Math.floor((b - f + 1) / 3);
2977
+ var h = Math.floor(19 * a + b - d - g + 15) % 30;
2978
+ var i = Math.floor(c / 4);
2979
+ var k = c % 4;
2980
+ var l = Math.floor(32 + 2 * e + 2 * i - h - k) % 7;
2981
+ var m = Math.floor((a + 11 * h + 22 * l) / 451);
2982
+ var month = Math.floor((h + l - 7 * m + 114) / 31);
2983
+ var day = (h + l - 7 * m + 114) % 31 + 1;
2984
+ var date = Date.UTC(y, month - 1, day + offset);
2985
+ var yearStart = Date.UTC(y, 0, 1);
2986
+ return [Math.ceil((date - yearStart) / (1e3 * 60 * 60 * 24))];
2987
+ }
2988
+ ;
2989
+ var Iterinfo = (
2990
+ /** @class */
2991
+ (function() {
2992
+ function Iterinfo2(options) {
2993
+ this.options = options;
2994
+ }
2995
+ Iterinfo2.prototype.rebuild = function(year, month) {
2996
+ var options = this.options;
2997
+ if (year !== this.lastyear) {
2998
+ this.yearinfo = rebuildYear(year, options);
2999
+ }
3000
+ if (notEmpty(options.bynweekday) && (month !== this.lastmonth || year !== this.lastyear)) {
3001
+ var _a = this.yearinfo, yearlen = _a.yearlen, mrange = _a.mrange, wdaymask = _a.wdaymask;
3002
+ this.monthinfo = rebuildMonth(year, month, yearlen, mrange, wdaymask, options);
3003
+ }
3004
+ if (isPresent(options.byeaster)) {
3005
+ this.eastermask = easter(year, options.byeaster);
3006
+ }
3007
+ };
3008
+ Object.defineProperty(Iterinfo2.prototype, "lastyear", {
3009
+ get: function() {
3010
+ return this.monthinfo ? this.monthinfo.lastyear : null;
3011
+ },
3012
+ enumerable: false,
3013
+ configurable: true
3014
+ });
3015
+ Object.defineProperty(Iterinfo2.prototype, "lastmonth", {
3016
+ get: function() {
3017
+ return this.monthinfo ? this.monthinfo.lastmonth : null;
3018
+ },
3019
+ enumerable: false,
3020
+ configurable: true
3021
+ });
3022
+ Object.defineProperty(Iterinfo2.prototype, "yearlen", {
3023
+ get: function() {
3024
+ return this.yearinfo.yearlen;
3025
+ },
3026
+ enumerable: false,
3027
+ configurable: true
3028
+ });
3029
+ Object.defineProperty(Iterinfo2.prototype, "yearordinal", {
3030
+ get: function() {
3031
+ return this.yearinfo.yearordinal;
3032
+ },
3033
+ enumerable: false,
3034
+ configurable: true
3035
+ });
3036
+ Object.defineProperty(Iterinfo2.prototype, "mrange", {
3037
+ get: function() {
3038
+ return this.yearinfo.mrange;
3039
+ },
3040
+ enumerable: false,
3041
+ configurable: true
3042
+ });
3043
+ Object.defineProperty(Iterinfo2.prototype, "wdaymask", {
3044
+ get: function() {
3045
+ return this.yearinfo.wdaymask;
3046
+ },
3047
+ enumerable: false,
3048
+ configurable: true
3049
+ });
3050
+ Object.defineProperty(Iterinfo2.prototype, "mmask", {
3051
+ get: function() {
3052
+ return this.yearinfo.mmask;
3053
+ },
3054
+ enumerable: false,
3055
+ configurable: true
3056
+ });
3057
+ Object.defineProperty(Iterinfo2.prototype, "wnomask", {
3058
+ get: function() {
3059
+ return this.yearinfo.wnomask;
3060
+ },
3061
+ enumerable: false,
3062
+ configurable: true
3063
+ });
3064
+ Object.defineProperty(Iterinfo2.prototype, "nwdaymask", {
3065
+ get: function() {
3066
+ return this.monthinfo ? this.monthinfo.nwdaymask : [];
3067
+ },
3068
+ enumerable: false,
3069
+ configurable: true
3070
+ });
3071
+ Object.defineProperty(Iterinfo2.prototype, "nextyearlen", {
3072
+ get: function() {
3073
+ return this.yearinfo.nextyearlen;
3074
+ },
3075
+ enumerable: false,
3076
+ configurable: true
3077
+ });
3078
+ Object.defineProperty(Iterinfo2.prototype, "mdaymask", {
3079
+ get: function() {
3080
+ return this.yearinfo.mdaymask;
3081
+ },
3082
+ enumerable: false,
3083
+ configurable: true
3084
+ });
3085
+ Object.defineProperty(Iterinfo2.prototype, "nmdaymask", {
3086
+ get: function() {
3087
+ return this.yearinfo.nmdaymask;
3088
+ },
3089
+ enumerable: false,
3090
+ configurable: true
3091
+ });
3092
+ Iterinfo2.prototype.ydayset = function() {
3093
+ return [range(this.yearlen), 0, this.yearlen];
3094
+ };
3095
+ Iterinfo2.prototype.mdayset = function(_, month) {
3096
+ var start = this.mrange[month - 1];
3097
+ var end = this.mrange[month];
3098
+ var set = repeat(null, this.yearlen);
3099
+ for (var i = start; i < end; i++)
3100
+ set[i] = i;
3101
+ return [set, start, end];
3102
+ };
3103
+ Iterinfo2.prototype.wdayset = function(year, month, day) {
3104
+ var set = repeat(null, this.yearlen + 7);
3105
+ var i = toOrdinal(datetime(year, month, day)) - this.yearordinal;
3106
+ var start = i;
3107
+ for (var j = 0; j < 7; j++) {
3108
+ set[i] = i;
3109
+ ++i;
3110
+ if (this.wdaymask[i] === this.options.wkst)
3111
+ break;
3112
+ }
3113
+ return [set, start, i];
3114
+ };
3115
+ Iterinfo2.prototype.ddayset = function(year, month, day) {
3116
+ var set = repeat(null, this.yearlen);
3117
+ var i = toOrdinal(datetime(year, month, day)) - this.yearordinal;
3118
+ set[i] = i;
3119
+ return [set, i, i + 1];
3120
+ };
3121
+ Iterinfo2.prototype.htimeset = function(hour, _, second, millisecond) {
3122
+ var _this = this;
3123
+ var set = [];
3124
+ this.options.byminute.forEach(function(minute) {
3125
+ set = set.concat(_this.mtimeset(hour, minute, second, millisecond));
3126
+ });
3127
+ sort(set);
3128
+ return set;
3129
+ };
3130
+ Iterinfo2.prototype.mtimeset = function(hour, minute, _, millisecond) {
3131
+ var set = this.options.bysecond.map(function(second) {
3132
+ return new Time(hour, minute, second, millisecond);
3133
+ });
3134
+ sort(set);
3135
+ return set;
3136
+ };
3137
+ Iterinfo2.prototype.stimeset = function(hour, minute, second, millisecond) {
3138
+ return [new Time(hour, minute, second, millisecond)];
3139
+ };
3140
+ Iterinfo2.prototype.getdayset = function(freq) {
3141
+ switch (freq) {
3142
+ case Frequency.YEARLY:
3143
+ return this.ydayset.bind(this);
3144
+ case Frequency.MONTHLY:
3145
+ return this.mdayset.bind(this);
3146
+ case Frequency.WEEKLY:
3147
+ return this.wdayset.bind(this);
3148
+ case Frequency.DAILY:
3149
+ return this.ddayset.bind(this);
3150
+ default:
3151
+ return this.ddayset.bind(this);
3152
+ }
3153
+ };
3154
+ Iterinfo2.prototype.gettimeset = function(freq) {
3155
+ switch (freq) {
3156
+ case Frequency.HOURLY:
3157
+ return this.htimeset.bind(this);
3158
+ case Frequency.MINUTELY:
3159
+ return this.mtimeset.bind(this);
3160
+ case Frequency.SECONDLY:
3161
+ return this.stimeset.bind(this);
3162
+ }
3163
+ };
3164
+ return Iterinfo2;
3165
+ })()
3166
+ );
3167
+ const iterinfo = Iterinfo;
3168
+ ;
3169
+ function buildPoslist(bysetpos, timeset, start, end, ii, dayset) {
3170
+ var poslist = [];
3171
+ for (var j = 0; j < bysetpos.length; j++) {
3172
+ var daypos = void 0;
3173
+ var timepos = void 0;
3174
+ var pos = bysetpos[j];
3175
+ if (pos < 0) {
3176
+ daypos = Math.floor(pos / timeset.length);
3177
+ timepos = pymod(pos, timeset.length);
3178
+ } else {
3179
+ daypos = Math.floor((pos - 1) / timeset.length);
3180
+ timepos = pymod(pos - 1, timeset.length);
3181
+ }
3182
+ var tmp = [];
3183
+ for (var k = start; k < end; k++) {
3184
+ var val = dayset[k];
3185
+ if (!isPresent(val))
3186
+ continue;
3187
+ tmp.push(val);
3188
+ }
3189
+ var i = void 0;
3190
+ if (daypos < 0) {
3191
+ i = tmp.slice(daypos)[0];
3192
+ } else {
3193
+ i = tmp[daypos];
3194
+ }
3195
+ var time = timeset[timepos];
3196
+ var date = fromOrdinal(ii.yearordinal + i);
3197
+ var res = combine(date, time);
3198
+ if (!includes(poslist, res))
3199
+ poslist.push(res);
3200
+ }
3201
+ sort(poslist);
3202
+ return poslist;
3203
+ }
3204
+ ;
3205
+ function iter(iterResult, options) {
3206
+ var dtstart = options.dtstart, freq = options.freq, interval = options.interval, until = options.until, bysetpos = options.bysetpos;
3207
+ var count = options.count;
3208
+ if (count === 0 || interval === 0) {
3209
+ return emitResult(iterResult);
3210
+ }
3211
+ var counterDate = DateTime.fromDate(dtstart);
3212
+ var ii = new iterinfo(options);
3213
+ ii.rebuild(counterDate.year, counterDate.month);
3214
+ var timeset = makeTimeset(ii, counterDate, options);
3215
+ for (; ; ) {
3216
+ var _a = ii.getdayset(freq)(counterDate.year, counterDate.month, counterDate.day), dayset = _a[0], start = _a[1], end = _a[2];
3217
+ var filtered = removeFilteredDays(dayset, start, end, ii, options);
3218
+ if (notEmpty(bysetpos)) {
3219
+ var poslist = buildPoslist(bysetpos, timeset, start, end, ii, dayset);
3220
+ for (var j = 0; j < poslist.length; j++) {
3221
+ var res = poslist[j];
3222
+ if (until && res > until) {
3223
+ return emitResult(iterResult);
3224
+ }
3225
+ if (res >= dtstart) {
3226
+ var rezonedDate = rezoneIfNeeded(res, options);
3227
+ if (!iterResult.accept(rezonedDate)) {
3228
+ return emitResult(iterResult);
3229
+ }
3230
+ if (count) {
3231
+ --count;
3232
+ if (!count) {
3233
+ return emitResult(iterResult);
3234
+ }
3235
+ }
3236
+ }
3237
+ }
3238
+ } else {
3239
+ for (var j = start; j < end; j++) {
3240
+ var currentDay = dayset[j];
3241
+ if (!isPresent(currentDay)) {
3242
+ continue;
3243
+ }
3244
+ var date = fromOrdinal(ii.yearordinal + currentDay);
3245
+ for (var k = 0; k < timeset.length; k++) {
3246
+ var time = timeset[k];
3247
+ var res = combine(date, time);
3248
+ if (until && res > until) {
3249
+ return emitResult(iterResult);
3250
+ }
3251
+ if (res >= dtstart) {
3252
+ var rezonedDate = rezoneIfNeeded(res, options);
3253
+ if (!iterResult.accept(rezonedDate)) {
3254
+ return emitResult(iterResult);
3255
+ }
3256
+ if (count) {
3257
+ --count;
3258
+ if (!count) {
3259
+ return emitResult(iterResult);
3260
+ }
3261
+ }
3262
+ }
3263
+ }
3264
+ }
3265
+ }
3266
+ if (options.interval === 0) {
3267
+ return emitResult(iterResult);
3268
+ }
3269
+ counterDate.add(options, filtered);
3270
+ if (counterDate.year > MAXYEAR) {
3271
+ return emitResult(iterResult);
3272
+ }
3273
+ if (!freqIsDailyOrGreater(freq)) {
3274
+ timeset = ii.gettimeset(freq)(counterDate.hour, counterDate.minute, counterDate.second, 0);
3275
+ }
3276
+ ii.rebuild(counterDate.year, counterDate.month);
3277
+ }
3278
+ }
3279
+ function isFiltered(ii, currentDay, options) {
3280
+ var bymonth = options.bymonth, byweekno = options.byweekno, byweekday = options.byweekday, byeaster = options.byeaster, bymonthday = options.bymonthday, bynmonthday = options.bynmonthday, byyearday = options.byyearday;
3281
+ return notEmpty(bymonth) && !includes(bymonth, ii.mmask[currentDay]) || notEmpty(byweekno) && !ii.wnomask[currentDay] || notEmpty(byweekday) && !includes(byweekday, ii.wdaymask[currentDay]) || notEmpty(ii.nwdaymask) && !ii.nwdaymask[currentDay] || byeaster !== null && !includes(ii.eastermask, currentDay) || (notEmpty(bymonthday) || notEmpty(bynmonthday)) && !includes(bymonthday, ii.mdaymask[currentDay]) && !includes(bynmonthday, ii.nmdaymask[currentDay]) || notEmpty(byyearday) && (currentDay < ii.yearlen && !includes(byyearday, currentDay + 1) && !includes(byyearday, -ii.yearlen + currentDay) || currentDay >= ii.yearlen && !includes(byyearday, currentDay + 1 - ii.yearlen) && !includes(byyearday, -ii.nextyearlen + currentDay - ii.yearlen));
3282
+ }
3283
+ function rezoneIfNeeded(date, options) {
3284
+ return new DateWithZone(date, options.tzid).rezonedDate();
3285
+ }
3286
+ function emitResult(iterResult) {
3287
+ return iterResult.getValue();
3288
+ }
3289
+ function removeFilteredDays(dayset, start, end, ii, options) {
3290
+ var filtered = false;
3291
+ for (var dayCounter = start; dayCounter < end; dayCounter++) {
3292
+ var currentDay = dayset[dayCounter];
3293
+ filtered = isFiltered(ii, currentDay, options);
3294
+ if (filtered)
3295
+ dayset[currentDay] = null;
3296
+ }
3297
+ return filtered;
3298
+ }
3299
+ function makeTimeset(ii, counterDate, options) {
3300
+ var freq = options.freq, byhour = options.byhour, byminute = options.byminute, bysecond = options.bysecond;
3301
+ if (freqIsDailyOrGreater(freq)) {
3302
+ return buildTimeset(options);
3303
+ }
3304
+ if (freq >= RRule2.HOURLY && notEmpty(byhour) && !includes(byhour, counterDate.hour) || freq >= RRule2.MINUTELY && notEmpty(byminute) && !includes(byminute, counterDate.minute) || freq >= RRule2.SECONDLY && notEmpty(bysecond) && !includes(bysecond, counterDate.second)) {
3305
+ return [];
3306
+ }
3307
+ return ii.gettimeset(freq)(counterDate.hour, counterDate.minute, counterDate.second, counterDate.millisecond);
3308
+ }
3309
+ ;
3310
+ var Days = {
3311
+ MO: new Weekday(0),
3312
+ TU: new Weekday(1),
3313
+ WE: new Weekday(2),
3314
+ TH: new Weekday(3),
3315
+ FR: new Weekday(4),
3316
+ SA: new Weekday(5),
3317
+ SU: new Weekday(6)
3318
+ };
3319
+ var DEFAULT_OPTIONS = {
3320
+ freq: Frequency.YEARLY,
3321
+ dtstart: null,
3322
+ interval: 1,
3323
+ wkst: Days.MO,
3324
+ count: null,
3325
+ until: null,
3326
+ tzid: null,
3327
+ bysetpos: null,
3328
+ bymonth: null,
3329
+ bymonthday: null,
3330
+ bynmonthday: null,
3331
+ byyearday: null,
3332
+ byweekno: null,
3333
+ byweekday: null,
3334
+ bynweekday: null,
3335
+ byhour: null,
3336
+ byminute: null,
3337
+ bysecond: null,
3338
+ byeaster: null
3339
+ };
3340
+ var defaultKeys = Object.keys(DEFAULT_OPTIONS);
3341
+ var RRule2 = (
3342
+ /** @class */
3343
+ (function() {
3344
+ function RRule3(options, noCache) {
3345
+ if (options === void 0) {
3346
+ options = {};
3347
+ }
3348
+ if (noCache === void 0) {
3349
+ noCache = false;
3350
+ }
3351
+ this._cache = noCache ? null : new Cache();
3352
+ this.origOptions = initializeOptions(options);
3353
+ var parsedOptions = parseOptions(options).parsedOptions;
3354
+ this.options = parsedOptions;
3355
+ }
3356
+ RRule3.parseText = function(text, language) {
3357
+ return parseText(text, language);
3358
+ };
3359
+ RRule3.fromText = function(text, language) {
3360
+ return fromText(text, language);
3361
+ };
3362
+ RRule3.fromString = function(str) {
3363
+ return new RRule3(RRule3.parseString(str) || void 0);
3364
+ };
3365
+ RRule3.prototype._iter = function(iterResult) {
3366
+ return iter(iterResult, this.options);
3367
+ };
3368
+ RRule3.prototype._cacheGet = function(what, args2) {
3369
+ if (!this._cache)
3370
+ return false;
3371
+ return this._cache._cacheGet(what, args2);
3372
+ };
3373
+ RRule3.prototype._cacheAdd = function(what, value, args2) {
3374
+ if (!this._cache)
3375
+ return;
3376
+ return this._cache._cacheAdd(what, value, args2);
3377
+ };
3378
+ RRule3.prototype.all = function(iterator) {
3379
+ if (iterator) {
3380
+ return this._iter(new callbackiterresult("all", {}, iterator));
3381
+ }
3382
+ var result = this._cacheGet("all");
3383
+ if (result === false) {
3384
+ result = this._iter(new iterresult("all", {}));
3385
+ this._cacheAdd("all", result);
3386
+ }
3387
+ return result;
3388
+ };
3389
+ RRule3.prototype.between = function(after, before, inc, iterator) {
3390
+ if (inc === void 0) {
3391
+ inc = false;
3392
+ }
3393
+ if (!isValidDate(after) || !isValidDate(before)) {
3394
+ throw new Error("Invalid date passed in to RRule.between");
3395
+ }
3396
+ var args2 = {
3397
+ before,
3398
+ after,
3399
+ inc
3400
+ };
3401
+ if (iterator) {
3402
+ return this._iter(new callbackiterresult("between", args2, iterator));
3403
+ }
3404
+ var result = this._cacheGet("between", args2);
3405
+ if (result === false) {
3406
+ result = this._iter(new iterresult("between", args2));
3407
+ this._cacheAdd("between", result, args2);
3408
+ }
3409
+ return result;
3410
+ };
3411
+ RRule3.prototype.before = function(dt, inc) {
3412
+ if (inc === void 0) {
3413
+ inc = false;
3414
+ }
3415
+ if (!isValidDate(dt)) {
3416
+ throw new Error("Invalid date passed in to RRule.before");
3417
+ }
3418
+ var args2 = { dt, inc };
3419
+ var result = this._cacheGet("before", args2);
3420
+ if (result === false) {
3421
+ result = this._iter(new iterresult("before", args2));
3422
+ this._cacheAdd("before", result, args2);
3423
+ }
3424
+ return result;
3425
+ };
3426
+ RRule3.prototype.after = function(dt, inc) {
3427
+ if (inc === void 0) {
3428
+ inc = false;
3429
+ }
3430
+ if (!isValidDate(dt)) {
3431
+ throw new Error("Invalid date passed in to RRule.after");
3432
+ }
3433
+ var args2 = { dt, inc };
3434
+ var result = this._cacheGet("after", args2);
3435
+ if (result === false) {
3436
+ result = this._iter(new iterresult("after", args2));
3437
+ this._cacheAdd("after", result, args2);
3438
+ }
3439
+ return result;
3440
+ };
3441
+ RRule3.prototype.count = function() {
3442
+ return this.all().length;
3443
+ };
3444
+ RRule3.prototype.toString = function() {
3445
+ return optionsToString(this.origOptions);
3446
+ };
3447
+ RRule3.prototype.toText = function(gettext, language, dateFormatter) {
3448
+ return toText(this, gettext, language, dateFormatter);
3449
+ };
3450
+ RRule3.prototype.isFullyConvertibleToText = function() {
3451
+ return isFullyConvertible(this);
3452
+ };
3453
+ RRule3.prototype.clone = function() {
3454
+ return new RRule3(this.origOptions);
3455
+ };
3456
+ RRule3.FREQUENCIES = [
3457
+ "YEARLY",
3458
+ "MONTHLY",
3459
+ "WEEKLY",
3460
+ "DAILY",
3461
+ "HOURLY",
3462
+ "MINUTELY",
3463
+ "SECONDLY"
3464
+ ];
3465
+ RRule3.YEARLY = Frequency.YEARLY;
3466
+ RRule3.MONTHLY = Frequency.MONTHLY;
3467
+ RRule3.WEEKLY = Frequency.WEEKLY;
3468
+ RRule3.DAILY = Frequency.DAILY;
3469
+ RRule3.HOURLY = Frequency.HOURLY;
3470
+ RRule3.MINUTELY = Frequency.MINUTELY;
3471
+ RRule3.SECONDLY = Frequency.SECONDLY;
3472
+ RRule3.MO = Days.MO;
3473
+ RRule3.TU = Days.TU;
3474
+ RRule3.WE = Days.WE;
3475
+ RRule3.TH = Days.TH;
3476
+ RRule3.FR = Days.FR;
3477
+ RRule3.SA = Days.SA;
3478
+ RRule3.SU = Days.SU;
3479
+ RRule3.parseString = parseString;
3480
+ RRule3.optionsToString = optionsToString;
3481
+ return RRule3;
3482
+ })()
3483
+ );
3484
+ ;
3485
+ function iterSet(iterResult, _rrule, _exrule, _rdate, _exdate, tzid) {
3486
+ var _exdateHash = {};
3487
+ var _accept = iterResult.accept;
3488
+ function evalExdate(after, before) {
3489
+ _exrule.forEach(function(rrule) {
3490
+ rrule.between(after, before, true).forEach(function(date) {
3491
+ _exdateHash[Number(date)] = true;
3492
+ });
3493
+ });
3494
+ }
3495
+ _exdate.forEach(function(date) {
3496
+ var zonedDate2 = new DateWithZone(date, tzid).rezonedDate();
3497
+ _exdateHash[Number(zonedDate2)] = true;
3498
+ });
3499
+ iterResult.accept = function(date) {
3500
+ var dt = Number(date);
3501
+ if (isNaN(dt))
3502
+ return _accept.call(this, date);
3503
+ if (!_exdateHash[dt]) {
3504
+ evalExdate(new Date(dt - 1), new Date(dt + 1));
3505
+ if (!_exdateHash[dt]) {
3506
+ _exdateHash[dt] = true;
3507
+ return _accept.call(this, date);
3508
+ }
3509
+ }
3510
+ return true;
3511
+ };
3512
+ if (iterResult.method === "between") {
3513
+ evalExdate(iterResult.args.after, iterResult.args.before);
3514
+ iterResult.accept = function(date) {
3515
+ var dt = Number(date);
3516
+ if (!_exdateHash[dt]) {
3517
+ _exdateHash[dt] = true;
3518
+ return _accept.call(this, date);
3519
+ }
3520
+ return true;
3521
+ };
3522
+ }
3523
+ for (var i = 0; i < _rdate.length; i++) {
3524
+ var zonedDate = new DateWithZone(_rdate[i], tzid).rezonedDate();
3525
+ if (!iterResult.accept(new Date(zonedDate.getTime())))
3526
+ break;
3527
+ }
3528
+ _rrule.forEach(function(rrule) {
3529
+ iter(iterResult, rrule.options);
3530
+ });
3531
+ var res = iterResult._result;
3532
+ sort(res);
3533
+ switch (iterResult.method) {
3534
+ case "all":
3535
+ case "between":
3536
+ return res;
3537
+ case "before":
3538
+ return res.length && res[res.length - 1] || null;
3539
+ case "after":
3540
+ default:
3541
+ return res.length && res[0] || null;
3542
+ }
3543
+ }
3544
+ ;
3545
+ var rrulestr_DEFAULT_OPTIONS = {
3546
+ dtstart: null,
3547
+ cache: false,
3548
+ unfold: false,
3549
+ forceset: false,
3550
+ compatible: false,
3551
+ tzid: null
3552
+ };
3553
+ function parseInput(s, options) {
3554
+ var rrulevals = [];
3555
+ var rdatevals = [];
3556
+ var exrulevals = [];
3557
+ var exdatevals = [];
3558
+ var parsedDtstart = parseDtstart(s);
3559
+ var dtstart = parsedDtstart.dtstart;
3560
+ var tzid = parsedDtstart.tzid;
3561
+ var lines = splitIntoLines(s, options.unfold);
3562
+ lines.forEach(function(line) {
3563
+ var _a;
3564
+ if (!line)
3565
+ return;
3566
+ var _b = breakDownLine(line), name = _b.name, parms = _b.parms, value = _b.value;
3567
+ switch (name.toUpperCase()) {
3568
+ case "RRULE":
3569
+ if (parms.length) {
3570
+ throw new Error("unsupported RRULE parm: ".concat(parms.join(",")));
3571
+ }
3572
+ rrulevals.push(parseString(line));
3573
+ break;
3574
+ case "RDATE":
3575
+ var _c = (_a = /RDATE(?:;TZID=([^:=]+))?/i.exec(line)) !== null && _a !== void 0 ? _a : [], rdateTzid = _c[1];
3576
+ if (rdateTzid && !tzid) {
3577
+ tzid = rdateTzid;
3578
+ }
3579
+ rdatevals = rdatevals.concat(parseRDate(value, parms));
3580
+ break;
3581
+ case "EXRULE":
3582
+ if (parms.length) {
3583
+ throw new Error("unsupported EXRULE parm: ".concat(parms.join(",")));
3584
+ }
3585
+ exrulevals.push(parseString(value));
3586
+ break;
3587
+ case "EXDATE":
3588
+ exdatevals = exdatevals.concat(parseRDate(value, parms));
3589
+ break;
3590
+ case "DTSTART":
3591
+ break;
3592
+ default:
3593
+ throw new Error("unsupported property: " + name);
3594
+ }
3595
+ });
3596
+ return {
3597
+ dtstart,
3598
+ tzid,
3599
+ rrulevals,
3600
+ rdatevals,
3601
+ exrulevals,
3602
+ exdatevals
3603
+ };
3604
+ }
3605
+ function buildRule(s, options) {
3606
+ var _a = parseInput(s, options), rrulevals = _a.rrulevals, rdatevals = _a.rdatevals, exrulevals = _a.exrulevals, exdatevals = _a.exdatevals, dtstart = _a.dtstart, tzid = _a.tzid;
3607
+ var noCache = options.cache === false;
3608
+ if (options.compatible) {
3609
+ options.forceset = true;
3610
+ options.unfold = true;
3611
+ }
3612
+ if (options.forceset || rrulevals.length > 1 || rdatevals.length || exrulevals.length || exdatevals.length) {
3613
+ var rset_1 = new RRuleSet(noCache);
3614
+ rset_1.dtstart(dtstart);
3615
+ rset_1.tzid(tzid || void 0);
3616
+ rrulevals.forEach(function(val2) {
3617
+ rset_1.rrule(new RRule2(groomRruleOptions(val2, dtstart, tzid), noCache));
3618
+ });
3619
+ rdatevals.forEach(function(date) {
3620
+ rset_1.rdate(date);
3621
+ });
3622
+ exrulevals.forEach(function(val2) {
3623
+ rset_1.exrule(new RRule2(groomRruleOptions(val2, dtstart, tzid), noCache));
3624
+ });
3625
+ exdatevals.forEach(function(date) {
3626
+ rset_1.exdate(date);
3627
+ });
3628
+ if (options.compatible && options.dtstart)
3629
+ rset_1.rdate(dtstart);
3630
+ return rset_1;
3631
+ }
3632
+ var val = rrulevals[0] || {};
3633
+ return new RRule2(groomRruleOptions(val, val.dtstart || options.dtstart || dtstart, val.tzid || options.tzid || tzid), noCache);
3634
+ }
3635
+ function rrulestr(s, options) {
3636
+ if (options === void 0) {
3637
+ options = {};
3638
+ }
3639
+ return buildRule(s, rrulestr_initializeOptions(options));
3640
+ }
3641
+ function groomRruleOptions(val, dtstart, tzid) {
3642
+ return __assign(__assign({}, val), { dtstart, tzid });
3643
+ }
3644
+ function rrulestr_initializeOptions(options) {
3645
+ var invalid = [];
3646
+ var keys = Object.keys(options);
3647
+ var defaultKeys2 = Object.keys(rrulestr_DEFAULT_OPTIONS);
3648
+ keys.forEach(function(key) {
3649
+ if (!includes(defaultKeys2, key))
3650
+ invalid.push(key);
3651
+ });
3652
+ if (invalid.length) {
3653
+ throw new Error("Invalid options: " + invalid.join(", "));
3654
+ }
3655
+ return __assign(__assign({}, rrulestr_DEFAULT_OPTIONS), options);
3656
+ }
3657
+ function extractName(line) {
3658
+ if (line.indexOf(":") === -1) {
3659
+ return {
3660
+ name: "RRULE",
3661
+ value: line
3662
+ };
3663
+ }
3664
+ var _a = split(line, ":", 1), name = _a[0], value = _a[1];
3665
+ return {
3666
+ name,
3667
+ value
3668
+ };
3669
+ }
3670
+ function breakDownLine(line) {
3671
+ var _a = extractName(line), name = _a.name, value = _a.value;
3672
+ var parms = name.split(";");
3673
+ if (!parms)
3674
+ throw new Error("empty property name");
3675
+ return {
3676
+ name: parms[0].toUpperCase(),
3677
+ parms: parms.slice(1),
3678
+ value
3679
+ };
3680
+ }
3681
+ function splitIntoLines(s, unfold) {
3682
+ if (unfold === void 0) {
3683
+ unfold = false;
3684
+ }
3685
+ s = s && s.trim();
3686
+ if (!s)
3687
+ throw new Error("Invalid empty string");
3688
+ if (!unfold) {
3689
+ return s.split(/\s/);
3690
+ }
3691
+ var lines = s.split("\n");
3692
+ var i = 0;
3693
+ while (i < lines.length) {
3694
+ var line = lines[i] = lines[i].replace(/\s+$/g, "");
3695
+ if (!line) {
3696
+ lines.splice(i, 1);
3697
+ } else if (i > 0 && line[0] === " ") {
3698
+ lines[i - 1] += line.slice(1);
3699
+ lines.splice(i, 1);
3700
+ } else {
3701
+ i += 1;
3702
+ }
3703
+ }
3704
+ return lines;
3705
+ }
3706
+ function validateDateParm(parms) {
3707
+ parms.forEach(function(parm) {
3708
+ if (!/(VALUE=DATE(-TIME)?)|(TZID=)/.test(parm)) {
3709
+ throw new Error("unsupported RDATE/EXDATE parm: " + parm);
3710
+ }
3711
+ });
3712
+ }
3713
+ function parseRDate(rdateval, parms) {
3714
+ validateDateParm(parms);
3715
+ return rdateval.split(",").map(function(datestr) {
3716
+ return untilStringToDate(datestr);
3717
+ });
3718
+ }
3719
+ ;
3720
+ function createGetterSetter(fieldName) {
3721
+ var _this = this;
3722
+ return function(field) {
3723
+ if (field !== void 0) {
3724
+ _this["_".concat(fieldName)] = field;
3725
+ }
3726
+ if (_this["_".concat(fieldName)] !== void 0) {
3727
+ return _this["_".concat(fieldName)];
3728
+ }
3729
+ for (var i = 0; i < _this._rrule.length; i++) {
3730
+ var field_1 = _this._rrule[i].origOptions[fieldName];
3731
+ if (field_1) {
3732
+ return field_1;
3733
+ }
3734
+ }
3735
+ };
3736
+ }
3737
+ var RRuleSet = (
3738
+ /** @class */
3739
+ (function(_super) {
3740
+ __extends(RRuleSet2, _super);
3741
+ function RRuleSet2(noCache) {
3742
+ if (noCache === void 0) {
3743
+ noCache = false;
3744
+ }
3745
+ var _this = _super.call(this, {}, noCache) || this;
3746
+ _this.dtstart = createGetterSetter.apply(_this, ["dtstart"]);
3747
+ _this.tzid = createGetterSetter.apply(_this, ["tzid"]);
3748
+ _this._rrule = [];
3749
+ _this._rdate = [];
3750
+ _this._exrule = [];
3751
+ _this._exdate = [];
3752
+ return _this;
3753
+ }
3754
+ RRuleSet2.prototype._iter = function(iterResult) {
3755
+ return iterSet(iterResult, this._rrule, this._exrule, this._rdate, this._exdate, this.tzid());
3756
+ };
3757
+ RRuleSet2.prototype.rrule = function(rrule) {
3758
+ _addRule(rrule, this._rrule);
3759
+ };
3760
+ RRuleSet2.prototype.exrule = function(rrule) {
3761
+ _addRule(rrule, this._exrule);
3762
+ };
3763
+ RRuleSet2.prototype.rdate = function(date) {
3764
+ _addDate(date, this._rdate);
3765
+ };
3766
+ RRuleSet2.prototype.exdate = function(date) {
3767
+ _addDate(date, this._exdate);
3768
+ };
3769
+ RRuleSet2.prototype.rrules = function() {
3770
+ return this._rrule.map(function(e) {
3771
+ return rrulestr(e.toString());
3772
+ });
3773
+ };
3774
+ RRuleSet2.prototype.exrules = function() {
3775
+ return this._exrule.map(function(e) {
3776
+ return rrulestr(e.toString());
3777
+ });
3778
+ };
3779
+ RRuleSet2.prototype.rdates = function() {
3780
+ return this._rdate.map(function(e) {
3781
+ return new Date(e.getTime());
3782
+ });
3783
+ };
3784
+ RRuleSet2.prototype.exdates = function() {
3785
+ return this._exdate.map(function(e) {
3786
+ return new Date(e.getTime());
3787
+ });
3788
+ };
3789
+ RRuleSet2.prototype.valueOf = function() {
3790
+ var result = [];
3791
+ if (!this._rrule.length && this._dtstart) {
3792
+ result = result.concat(optionsToString({ dtstart: this._dtstart }));
3793
+ }
3794
+ this._rrule.forEach(function(rrule) {
3795
+ result = result.concat(rrule.toString().split("\n"));
3796
+ });
3797
+ this._exrule.forEach(function(exrule) {
3798
+ result = result.concat(exrule.toString().split("\n").map(function(line) {
3799
+ return line.replace(/^RRULE:/, "EXRULE:");
3800
+ }).filter(function(line) {
3801
+ return !/^DTSTART/.test(line);
3802
+ }));
3803
+ });
3804
+ if (this._rdate.length) {
3805
+ result.push(rdatesToString("RDATE", this._rdate, this.tzid()));
3806
+ }
3807
+ if (this._exdate.length) {
3808
+ result.push(rdatesToString("EXDATE", this._exdate, this.tzid()));
3809
+ }
3810
+ return result;
3811
+ };
3812
+ RRuleSet2.prototype.toString = function() {
3813
+ return this.valueOf().join("\n");
3814
+ };
3815
+ RRuleSet2.prototype.clone = function() {
3816
+ var rrs = new RRuleSet2(!!this._cache);
3817
+ this._rrule.forEach(function(rule) {
3818
+ return rrs.rrule(rule.clone());
3819
+ });
3820
+ this._exrule.forEach(function(rule) {
3821
+ return rrs.exrule(rule.clone());
3822
+ });
3823
+ this._rdate.forEach(function(date) {
3824
+ return rrs.rdate(new Date(date.getTime()));
3825
+ });
3826
+ this._exdate.forEach(function(date) {
3827
+ return rrs.exdate(new Date(date.getTime()));
3828
+ });
3829
+ return rrs;
3830
+ };
3831
+ return RRuleSet2;
3832
+ })(RRule2)
3833
+ );
3834
+ function _addRule(rrule, collection) {
3835
+ if (!(rrule instanceof RRule2)) {
3836
+ throw new TypeError(String(rrule) + " is not RRule instance");
3837
+ }
3838
+ if (!includes(collection.map(String), String(rrule))) {
3839
+ collection.push(rrule);
3840
+ }
3841
+ }
3842
+ function _addDate(date, collection) {
3843
+ if (!(date instanceof Date)) {
3844
+ throw new TypeError(String(date) + " is not Date instance");
3845
+ }
3846
+ if (!includes(collection.map(Number), Number(date))) {
3847
+ collection.push(date);
3848
+ sort(collection);
3849
+ }
3850
+ }
3851
+ function rdatesToString(param, rdates, tzid) {
3852
+ var isUTC = !tzid || tzid.toUpperCase() === "UTC";
3853
+ var header = isUTC ? "".concat(param, ":") : "".concat(param, ";TZID=").concat(tzid, ":");
3854
+ var dateString = rdates.map(function(rdate) {
3855
+ return timeToUntilString(rdate.valueOf(), isUTC);
3856
+ }).join(",");
3857
+ return "".concat(header).concat(dateString);
3858
+ }
3859
+ ;
3860
+ return __webpack_exports__;
3861
+ })()
3862
+ );
3863
+ });
3864
+ }
3865
+ });
3866
+
3867
+ // ../../packages/shared/src/time.ts
3868
+ var init_time = __esm({
3869
+ "../../packages/shared/src/time.ts"() {
3870
+ "use strict";
3871
+ }
3872
+ });
3873
+
3874
+ // ../../packages/shared/src/recurrence.ts
3875
+ function intList(value, min, max, signed = false) {
3876
+ return value.split(",").every((s) => {
3877
+ if (!(signed ? /^[+-]?\d{1,3}$/ : /^\d{1,3}$/).test(s)) return false;
3878
+ const n = Math.abs(Number(s));
3879
+ return n >= min && n <= max;
3880
+ });
3881
+ }
3882
+ function parseUntil(value) {
3883
+ const m = /^(\d{4})(\d{2})(\d{2})(?:T(\d{2})(\d{2})(\d{2})Z)?$/.exec(value);
3884
+ if (!m) return null;
3885
+ const [y, mo, d, h, mi, s] = m.slice(1).map((v) => Number(v ?? 0));
3886
+ const date = new Date(Date.UTC(y, mo - 1, d, h, mi, s));
3887
+ if (date.getUTCMonth() !== mo - 1 || date.getUTCDate() !== d || h > 23 || mi > 59 || s > 59) {
3888
+ return null;
3889
+ }
3890
+ return { date, dateOnly: m[4] === void 0 };
3891
+ }
3892
+ function normalizeRRule(input) {
3893
+ const body = input.trim().toUpperCase().replace(/^RRULE:/, "");
3894
+ const seen = /* @__PURE__ */ new Set();
3895
+ for (const part of body.split(";")) {
3896
+ const [key, value, ...rest] = part.split("=");
3897
+ if (!key || value === void 0 || rest.length > 0) {
3898
+ throw new RRuleError(`"${part}" kh\xF4ng \u0111\xFAng d\u1EA1ng KEY=VALUE`);
3899
+ }
3900
+ const rule = RULES[key];
3901
+ if (!rule) throw new RRuleError(`Kh\xF4ng h\u1ED7 tr\u1EE3 ${key}`);
3902
+ if (seen.has(key)) throw new RRuleError(`${key} xu\u1EA5t hi\u1EC7n nhi\u1EC1u l\u1EA7n`);
3903
+ if (!rule.test(value)) throw new RRuleError(`${key}=${value} kh\xF4ng h\u1EE3p l\u1EC7, c\u1EA7n ${rule.hint}`);
3904
+ seen.add(key);
3905
+ }
3906
+ if (!seen.has("FREQ")) throw new RRuleError("Thi\u1EBFu FREQ");
3907
+ if (seen.has("COUNT") && seen.has("UNTIL")) {
3908
+ throw new RRuleError("Kh\xF4ng d\xF9ng COUNT v\xE0 UNTIL c\xF9ng l\xFAc");
3909
+ }
3910
+ return body;
3911
+ }
3912
+ var import_rrule, RRuleError, WEEKDAY, BYDAY_ITEM, RULES;
3913
+ var init_recurrence = __esm({
3914
+ "../../packages/shared/src/recurrence.ts"() {
3915
+ "use strict";
3916
+ import_rrule = __toESM(require_rrule(), 1);
3917
+ init_time();
3918
+ RRuleError = class extends Error {
3919
+ };
3920
+ WEEKDAY = "(?:MO|TU|WE|TH|FR|SA|SU)";
3921
+ BYDAY_ITEM = new RegExp(`^(?:[+-]?(?:[1-9]|[1-4]\\d|5[0-3]))?${WEEKDAY}$`);
3922
+ RULES = {
3923
+ FREQ: {
3924
+ test: (v) => /^(?:YEARLY|MONTHLY|WEEKLY|DAILY|HOURLY)$/.test(v),
3925
+ hint: "HOURLY, DAILY, WEEKLY, MONTHLY ho\u1EB7c YEARLY"
3926
+ },
3927
+ INTERVAL: { test: (v) => intList(v, 1, 999) && !v.includes(","), hint: "s\u1ED1 t\u1EEB 1 \u0111\u1EBFn 999" },
3928
+ COUNT: { test: (v) => intList(v, 1, 999) && !v.includes(","), hint: "s\u1ED1 t\u1EEB 1 \u0111\u1EBFn 999" },
3929
+ UNTIL: { test: (v) => parseUntil(v) !== null, hint: "YYYYMMDD ho\u1EB7c YYYYMMDDTHHMMSSZ" },
3930
+ BYDAY: {
3931
+ test: (v) => v.split(",").every((s) => BYDAY_ITEM.test(s)),
3932
+ hint: "vd MO,WE ho\u1EB7c 1MO, -1FR"
3933
+ },
3934
+ BYMONTHDAY: { test: (v) => intList(v, 1, 31, true), hint: "1..31 ho\u1EB7c -31..-1" },
3935
+ BYMONTH: { test: (v) => intList(v, 1, 12), hint: "1..12" },
3936
+ BYHOUR: { test: (v) => intList(v, 0, 23), hint: "0..23" },
3937
+ BYMINUTE: { test: (v) => intList(v, 0, 59), hint: "0..59" },
3938
+ BYSETPOS: { test: (v) => intList(v, 1, 366, true), hint: "1..366 ho\u1EB7c -366..-1" },
3939
+ WKST: { test: (v) => new RegExp(`^${WEEKDAY}$`).test(v), hint: "MO..SU" }
3940
+ };
3941
+ }
3942
+ });
3943
+
3944
+ // ../../packages/shared/src/schemas/reminders.ts
3945
+ import { z as z6 } from "zod";
3946
+ var MAX_SNOOZE_MIN, RRuleString, Reminder, ReminderFields, targetConsistent, CreateReminder, UpdateReminder, SnoozeReminder, ListRemindersQuery;
3947
+ var init_reminders = __esm({
3948
+ "../../packages/shared/src/schemas/reminders.ts"() {
3949
+ "use strict";
3950
+ init_enums();
3951
+ init_recurrence();
3952
+ init_common();
3953
+ MAX_SNOOZE_MIN = 24 * 60;
3954
+ RRuleString = z6.string().max(500).overwrite(
3955
+ (s) => s.trim().toUpperCase().replace(/^RRULE:/, "")
3956
+ ).superRefine((s, ctx) => {
3957
+ try {
3958
+ normalizeRRule(s);
3959
+ } catch (e) {
3960
+ if (!(e instanceof RRuleError)) throw e;
3961
+ ctx.addIssue({ code: "custom", message: e.message });
3962
+ }
3963
+ });
3964
+ Reminder = z6.object({
3965
+ id: z6.string(),
3966
+ title: z6.string(),
3967
+ body: z6.string().nullable(),
3968
+ targetType: TargetType,
3969
+ targetId: z6.string().nullable(),
3970
+ fireAt: z6.string(),
3971
+ // lần nhắc kế tiếp
3972
+ rrule: z6.string().nullable(),
3973
+ status: ReminderStatus,
3974
+ source: Source,
3975
+ createdAt: z6.string(),
3976
+ updatedAt: z6.string()
3977
+ });
3978
+ ReminderFields = z6.object({
3979
+ title: z6.string().trim().min(1).max(200),
3980
+ body: z6.string().max(2e3).nullable(),
3981
+ targetType: TargetType,
3982
+ targetId: Id.nullable(),
3983
+ fireAt: IsoDateTime,
3984
+ rrule: RRuleString.nullable()
3985
+ });
3986
+ targetConsistent = (v) => (v.targetType ?? "none") === "none" ? v.targetId == null : v.targetId != null;
3987
+ CreateReminder = ReminderFields.extend({
3988
+ body: ReminderFields.shape.body.optional(),
3989
+ targetType: TargetType.default("none"),
3990
+ targetId: ReminderFields.shape.targetId.optional(),
3991
+ rrule: ReminderFields.shape.rrule.optional()
3992
+ }).strict().refine(targetConsistent, {
3993
+ message: "targetId b\u1EAFt bu\u1ED9c khi c\xF3 targetType, v\xE0 ph\u1EA3i b\u1ECF tr\u1ED1ng khi targetType l\xE0 none",
3994
+ path: ["targetId"]
3995
+ });
3996
+ UpdateReminder = ReminderFields.extend({
3997
+ // fired / snoozed do hệ thống đặt, người dùng chỉ bật lại, đánh dấu xong hoặc huỷ
3998
+ status: z6.enum(["scheduled", "done", "cancelled"])
3999
+ }).partial().strict();
4000
+ SnoozeReminder = z6.object({ minutes: z6.number().int().min(1).max(MAX_SNOOZE_MIN) }).strict();
4001
+ ListRemindersQuery = PageQuery.extend({
4002
+ from: IsoDateTime.optional(),
4003
+ // fireAt >= from
4004
+ to: IsoDateTime.optional(),
4005
+ // fireAt < to
4006
+ status: queryList(ReminderStatus).optional(),
4007
+ targetType: TargetType.optional(),
4008
+ targetId: Id.optional()
4009
+ });
4010
+ }
4011
+ });
4012
+
581
4013
  // ../../packages/shared/src/push.ts
582
4014
  var AGENT_PERMISSION_CATEGORY;
583
4015
  var init_push = __esm({
584
4016
  "../../packages/shared/src/push.ts"() {
585
4017
  "use strict";
4018
+ init_reminders();
586
4019
  AGENT_PERMISSION_CATEGORY = "agent_permission";
587
4020
  }
588
4021
  });
@@ -595,19 +4028,20 @@ function createPusher(state2, accessToken, fetchFn = fetch) {
595
4028
  const body = notice.body.replace(/\s+/g, " ").trim();
596
4029
  const messages = tokens.map((to) => ({
597
4030
  to,
598
- title: notice.title,
599
- body: body.length > MAX_BODY ? `${body.slice(0, MAX_BODY)}\u2026` : body,
4031
+ priority: "high",
600
4032
  data: {
601
4033
  type: "agent_bridge",
602
4034
  event: notice.event,
603
4035
  sessionId: notice.sessionId,
604
- ...notice.requestId ? { requestId: notice.requestId } : {}
605
- },
606
- channelId: "alerts",
607
- // kênh app đã tạo, xem docs/05-notifications.md
608
- ...notice.event === "permission_request" ? { categoryId: AGENT_PERMISSION_CATEGORY } : {},
609
- sound: "default",
610
- priority: "high"
4036
+ ...notice.requestId ? { requestId: notice.requestId } : {},
4037
+ push: {
4038
+ title: notice.title,
4039
+ body: body.length > MAX_BODY ? `${body.slice(0, MAX_BODY)}\u2026` : body,
4040
+ category: notice.event === "permission_request" ? AGENT_PERMISSION_CATEGORY : "notice",
4041
+ channelId: "alerts"
4042
+ // kênh app đã tạo, xem docs/05-notifications.md
4043
+ }
4044
+ }
611
4045
  }));
612
4046
  try {
613
4047
  const res = await fetchFn(EXPO_PUSH_URL, {
@@ -740,13 +4174,78 @@ var init_transcript = __esm({
740
4174
  }
741
4175
  });
742
4176
 
4177
+ // src/uploads.ts
4178
+ import { mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
4179
+ import os2 from "node:os";
4180
+ import path2 from "node:path";
4181
+ function safeFileName(name) {
4182
+ const base = path2.basename(name.replace(/\\/g, "/"));
4183
+ const clean = base.replace(/[<>:"/\\|?*\x00-\x1f]/g, "_").replace(/^\.+/, "").trim().slice(0, 120);
4184
+ return clean || "tep";
4185
+ }
4186
+ function saveAttachments(files, root = UPLOAD_DIR) {
4187
+ if (!files.length) return [];
4188
+ cleanOld(root);
4189
+ const dir = path2.join(root, `${Date.now().toString(36)}-${crypto.randomUUID().slice(0, 8)}`);
4190
+ mkdirSync(dir, { recursive: true });
4191
+ const used = /* @__PURE__ */ new Set();
4192
+ return files.map((f) => {
4193
+ let name = safeFileName(f.name);
4194
+ for (let i = 2; used.has(name.toLowerCase()); i++) {
4195
+ const ext = path2.extname(name);
4196
+ name = `${path2.basename(safeFileName(f.name), ext)} (${i})${ext}`;
4197
+ }
4198
+ used.add(name.toLowerCase());
4199
+ const file = path2.join(dir, name);
4200
+ writeFileSync(file, Buffer.from(f.data, "base64"));
4201
+ return file;
4202
+ });
4203
+ }
4204
+ function promptWithFiles(text, paths) {
4205
+ if (!paths.length) return text;
4206
+ const list = paths.map((p) => `- ${p}`).join("\n");
4207
+ const head = "T\u1EC7p ng\u01B0\u1EDDi d\xF9ng g\u1EEDi k\xE8m (\u0111\u1ECDc b\u1EB1ng tool Read):";
4208
+ return text ? `${text}
4209
+
4210
+ ${head}
4211
+ ${list}` : `${head}
4212
+ ${list}`;
4213
+ }
4214
+ function cleanOld(root) {
4215
+ let names;
4216
+ try {
4217
+ names = readdirSync(root);
4218
+ } catch {
4219
+ return;
4220
+ }
4221
+ const cutoff = Date.now() - KEEP_MS;
4222
+ for (const name of names) {
4223
+ const p = path2.join(root, name);
4224
+ try {
4225
+ if (statSync(p).mtimeMs < cutoff) rmSync(p, { recursive: true, force: true });
4226
+ } catch {
4227
+ }
4228
+ }
4229
+ }
4230
+ var UPLOAD_DIR, KEEP_MS;
4231
+ var init_uploads = __esm({
4232
+ "src/uploads.ts"() {
4233
+ "use strict";
4234
+ UPLOAD_DIR = path2.join(os2.tmpdir(), "manualofme-bridge-uploads");
4235
+ KEEP_MS = 3 * 24 * 60 * 60 * 1e3;
4236
+ }
4237
+ });
4238
+
743
4239
  // src/session.ts
744
4240
  import * as sdk from "@anthropic-ai/claude-agent-sdk";
745
- var BridgeError, APPEND_PROMPT, errorText, AgentSession;
4241
+ var EDIT_TOOLS, autoAllows, BridgeError, APPEND_PROMPT, errorText, AgentSession;
746
4242
  var init_session = __esm({
747
4243
  "src/session.ts"() {
748
4244
  "use strict";
749
4245
  init_transcript();
4246
+ init_uploads();
4247
+ EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
4248
+ autoAllows = (mode, toolName) => mode === "bypassPermissions" || mode === "acceptEdits" && EDIT_TOOLS.has(toolName);
750
4249
  BridgeError = class extends Error {
751
4250
  };
752
4251
  APPEND_PROMPT = "Ng\u01B0\u1EDDi d\xF9ng \u0111ang nh\u1EAFn t\u1EEB app \u0111i\u1EC7n tho\u1EA1i qua agent bridge, kh\xF4ng nh\xECn th\u1EA5y editor. Tr\u1EA3 l\u1EDDi g\u1ECDn, n\xF3i r\xF5 \u0111\xE3 s\u1EEDa file n\xE0o. C\u1EA7n h\u1ECFi th\xEC h\u1ECFi b\u1EB1ng c\xE2u tr\u1EA3 l\u1EDDi th\u01B0\u1EDDng.";
@@ -758,6 +4257,11 @@ var init_session = __esm({
758
4257
  }
759
4258
  sdk;
760
4259
  abort = null;
4260
+ /**
4261
+ * Query của lượt đã xong nhưng chưa đóng: Claude bật tác vụ nền (server, tunnel...) thì SDK
4262
+ * còn chạy tiếp tới khi tác vụ đó tắt. Gửi tin mới / đổi session thì đóng nó trước.
4263
+ */
4264
+ tail = null;
761
4265
  pending = /* @__PURE__ */ new Map();
762
4266
  get sessionId() {
763
4267
  return this.deps.state.sessionId;
@@ -765,14 +4269,35 @@ var init_session = __esm({
765
4269
  get busy() {
766
4270
  return this.abort !== null;
767
4271
  }
4272
+ /** Chế độ duyệt đang dùng: chọn từ app, chưa chọn thì theo .env. */
4273
+ get permissionMode() {
4274
+ return this.deps.state.permissionMode ?? this.deps.config.permissionMode;
4275
+ }
768
4276
  stateMessage() {
769
4277
  return {
770
4278
  type: "state",
771
4279
  sessionId: this.sessionId,
772
4280
  busy: this.busy,
773
- pendingPermissions: [...this.pending.values()].map((p) => p.request)
4281
+ pendingPermissions: [...this.pending.values()].map((p) => p.request),
4282
+ permissionMode: this.permissionMode,
4283
+ model: this.deps.state.model
774
4284
  };
775
4285
  }
4286
+ /**
4287
+ * Đổi chế độ duyệt / model. Lượt đang chạy vẫn giữ chế độ lúc bắt đầu, nhưng yêu cầu duyệt
4288
+ * (đang chờ hoặc tới sau) mà chế độ mới tự cho phép thì được duyệt luôn, khỏi bị kẹt.
4289
+ */
4290
+ setOptions(opts) {
4291
+ const { state: state2 } = this.deps;
4292
+ if (opts.permissionMode !== void 0) {
4293
+ state2.permissionMode = opts.permissionMode === this.deps.config.permissionMode ? null : opts.permissionMode;
4294
+ }
4295
+ if (opts.model !== void 0) state2.model = opts.model;
4296
+ for (const p of [...this.pending.values()]) {
4297
+ if (autoAllows(this.permissionMode, p.request.toolName)) p.finish({ behavior: "allow" });
4298
+ }
4299
+ this.deps.broadcast(this.stateMessage());
4300
+ }
776
4301
  /** `null` khi session đã đổi trong lúc đọc file: bản lịch sử này cũ rồi, không gửi. */
777
4302
  async historyMessage() {
778
4303
  const sessionId = this.sessionId;
@@ -791,13 +4316,24 @@ var init_session = __esm({
791
4316
  }
792
4317
  async open(sessionId) {
793
4318
  if (this.busy) throw new BridgeError("Claude \u0111ang ch\u1EA1y, d\u1EEBng l\u01B0\u1EE3t n\xE0y tr\u01B0\u1EDBc khi \u0111\u1ED5i session");
4319
+ this.closeTail();
794
4320
  this.deps.state.sessionId = sessionId;
795
4321
  this.deps.broadcast(this.stateMessage());
796
4322
  const history = await this.historyMessage();
797
4323
  if (history) this.deps.broadcast(history);
798
4324
  }
799
- send(text, clientId) {
4325
+ send(input, clientId, attachments = []) {
800
4326
  if (this.busy) throw new BridgeError("Claude \u0111ang ch\u1EA1y, \u0111\u1EE3i xong ho\u1EB7c b\u1EA5m d\u1EEBng");
4327
+ if (!input && !attachments.length) throw new BridgeError("Tin nh\u1EAFn tr\u1ED1ng");
4328
+ let paths;
4329
+ try {
4330
+ paths = saveAttachments(attachments);
4331
+ } catch (e) {
4332
+ console.error("[bridge] l\u01B0u t\u1EC7p \u0111\xEDnh k\xE8m", e);
4333
+ throw new BridgeError("Kh\xF4ng l\u01B0u \u0111\u01B0\u1EE3c t\u1EC7p \u0111\xEDnh k\xE8m tr\xEAn PC");
4334
+ }
4335
+ const text = promptWithFiles(input, paths);
4336
+ this.closeTail();
801
4337
  const abort = new AbortController();
802
4338
  this.abort = abort;
803
4339
  this.deps.broadcast(this.stateMessage());
@@ -817,6 +4353,14 @@ var init_session = __esm({
817
4353
  p.finish(
818
4354
  allow ? { behavior: "allow" } : { behavior: "deny", message: message?.trim() || "Ng\u01B0\u1EDDi d\xF9ng t\u1EEB ch\u1ED1i" }
819
4355
  );
4356
+ if (allow && p.request.toolName === "ExitPlanMode" && this.permissionMode === "plan") {
4357
+ this.setOptions({ permissionMode: "default" });
4358
+ }
4359
+ }
4360
+ closeTail() {
4361
+ const tail = this.tail;
4362
+ this.tail = null;
4363
+ tail?.close();
820
4364
  }
821
4365
  async run(text, abort) {
822
4366
  const { config: config2, broadcast, push } = this.deps;
@@ -825,21 +4369,48 @@ var init_session = __esm({
825
4369
  let resultText = "";
826
4370
  let costUsd = 0;
827
4371
  let durationMs = 0;
4372
+ let ended = false;
4373
+ const mode = this.permissionMode;
4374
+ const endTurn = () => {
4375
+ if (ended) return;
4376
+ ended = true;
4377
+ if (this.abort === abort) this.abort = null;
4378
+ for (const p of this.pending.values())
4379
+ p.finish({ behavior: "deny", message: "L\u01B0\u1EE3t \u0111\xE3 k\u1EBFt th\xFAc" });
4380
+ if (!durationMs) durationMs = Date.now() - started;
4381
+ if (!ok && !resultText) resultText = abort.signal.aborted ? "\u0110\xE3 d\u1EEBng" : "L\u1ED7i kh\xF4ng r\xF5";
4382
+ const sessionId = this.sessionId;
4383
+ broadcast({ type: "turn_end", sessionId, ok, text: resultText, costUsd, durationMs });
4384
+ broadcast(this.stateMessage());
4385
+ if (!abort.signal.aborted) {
4386
+ void push({
4387
+ event: "turn_end",
4388
+ title: ok ? "Claude xong vi\u1EC7c" : "Claude g\u1EB7p l\u1ED7i",
4389
+ body: resultText || "(kh\xF4ng c\xF3 n\u1ED9i dung)",
4390
+ sessionId
4391
+ });
4392
+ }
4393
+ };
4394
+ let q = null;
828
4395
  try {
829
- const q = this.sdk.query({
4396
+ q = this.sdk.query({
830
4397
  prompt: text,
831
4398
  options: {
832
4399
  cwd: config2.cwd,
833
4400
  resume: this.sessionId ?? void 0,
834
4401
  abortController: abort,
835
4402
  canUseTool: this.canUseTool,
836
- permissionMode: config2.permissionMode,
837
- model: config2.model,
4403
+ permissionMode: mode,
4404
+ ...mode === "bypassPermissions" ? { allowDangerouslySkipPermissions: true } : {},
4405
+ model: this.deps.state.model ?? config2.model,
4406
+ // Thư mục tệp đính kèm, để Claude đọc không cần hỏi
4407
+ additionalDirectories: [UPLOAD_DIR],
838
4408
  // app không hiện được hộp chọn của tool này, để Claude hỏi bằng lời
839
4409
  disallowedTools: ["AskUserQuestion"],
840
4410
  systemPrompt: { type: "preset", preset: "claude_code", append: APPEND_PROMPT }
841
4411
  }
842
4412
  });
4413
+ this.tail = q;
843
4414
  for await (const msg of q) {
844
4415
  if (msg.type === "system" && msg.subtype === "init") {
845
4416
  if (msg.session_id !== this.sessionId) {
@@ -849,36 +4420,32 @@ var init_session = __esm({
849
4420
  } else if (msg.type === "assistant") {
850
4421
  for (const item of toChatItems(msg))
851
4422
  broadcast({ type: "item", sessionId: this.sessionId, item });
852
- } else if (msg.type === "result") {
4423
+ } else if (msg.type === "result" && !ended) {
853
4424
  ok = msg.subtype === "success" && !msg.is_error;
854
4425
  resultText = msg.subtype === "success" ? msg.result : msg.errors.join("\n") || msg.subtype;
855
4426
  costUsd = msg.total_cost_usd;
856
4427
  durationMs = msg.duration_ms;
4428
+ endTurn();
857
4429
  }
858
4430
  }
859
4431
  } catch (e) {
860
- ok = false;
861
- resultText = abort.signal.aborted ? "\u0110\xE3 d\u1EEBng" : errorText(e);
4432
+ if (!ended) {
4433
+ ok = false;
4434
+ resultText = abort.signal.aborted ? "\u0110\xE3 d\u1EEBng" : errorText(e);
4435
+ }
862
4436
  } finally {
863
- this.abort = null;
864
- for (const p of this.pending.values())
865
- p.finish({ behavior: "deny", message: "L\u01B0\u1EE3t \u0111\xE3 k\u1EBFt th\xFAc" });
866
- }
867
- if (!durationMs) durationMs = Date.now() - started;
868
- if (!ok && !resultText) resultText = abort.signal.aborted ? "\u0110\xE3 d\u1EEBng" : "L\u1ED7i kh\xF4ng r\xF5";
869
- const sessionId = this.sessionId;
870
- broadcast({ type: "turn_end", sessionId, ok, text: resultText, costUsd, durationMs });
871
- broadcast(this.stateMessage());
872
- if (!abort.signal.aborted) {
873
- void push({
874
- event: "turn_end",
875
- title: ok ? "Claude xong vi\u1EC7c" : "Claude g\u1EB7p l\u1ED7i",
876
- body: resultText || "(kh\xF4ng c\xF3 n\u1ED9i dung)",
877
- sessionId
878
- });
4437
+ if (q && this.tail === q) this.tail = null;
4438
+ endTurn();
4439
+ if (!this.busy)
4440
+ for (const p of this.pending.values())
4441
+ p.finish({ behavior: "deny", message: "L\u01B0\u1EE3t \u0111\xE3 k\u1EBFt th\xFAc" });
879
4442
  }
880
4443
  }
881
4444
  canUseTool = (toolName, input, opts) => new Promise((resolve) => {
4445
+ if (autoAllows(this.permissionMode, toolName)) {
4446
+ resolve({ behavior: "allow" });
4447
+ return;
4448
+ }
882
4449
  const requestId = opts.toolUseID || crypto.randomUUID();
883
4450
  const request = {
884
4451
  requestId,
@@ -936,8 +4503,8 @@ function createBridgeServer({ token, hub: hub2, session: session2, state: state2
936
4503
  handleProtocols: (protocols) => protocols.has(BRIDGE_SUBPROTOCOL) ? BRIDGE_SUBPROTOCOL : false
937
4504
  });
938
4505
  http.on("upgrade", (req, socket, head) => {
939
- const path5 = new URL(req.url ?? "/", "http://localhost").pathname;
940
- if (path5 !== WS_PATH) {
4506
+ const path6 = new URL(req.url ?? "/", "http://localhost").pathname;
4507
+ if (path6 !== WS_PATH) {
941
4508
  socket.end("HTTP/1.1 404 Not Found\r\n\r\n");
942
4509
  return;
943
4510
  }
@@ -960,7 +4527,10 @@ function createBridgeServer({ token, hub: hub2, session: session2, state: state2
960
4527
  await session2.open(msg.sessionId);
961
4528
  return;
962
4529
  case "send":
963
- session2.send(msg.text, msg.clientId);
4530
+ session2.send(msg.text, msg.clientId, msg.attachments);
4531
+ return;
4532
+ case "set_options":
4533
+ session2.setOptions(msg);
964
4534
  return;
965
4535
  case "interrupt":
966
4536
  session2.interrupt();
@@ -1039,7 +4609,7 @@ var init_server = __esm({
1039
4609
  init_session();
1040
4610
  WS_PATH = "/ws";
1041
4611
  PING_MS = 3e4;
1042
- MAX_PAYLOAD = 1024 * 1024;
4612
+ MAX_PAYLOAD = 2 * 1024 * 1024;
1043
4613
  Hub = class {
1044
4614
  clients = /* @__PURE__ */ new Set();
1045
4615
  broadcast(msg) {
@@ -1054,22 +4624,26 @@ var init_server = __esm({
1054
4624
  });
1055
4625
 
1056
4626
  // src/state.ts
1057
- import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
1058
- import path2 from "node:path";
1059
- import { z as z6 } from "zod";
4627
+ import { mkdirSync as mkdirSync2, readFileSync, renameSync, writeFileSync as writeFileSync2 } from "node:fs";
4628
+ import path3 from "node:path";
4629
+ import { z as z7 } from "zod";
1060
4630
  var MAX_PUSH_TOKENS, Saved, StateStore;
1061
4631
  var init_state = __esm({
1062
4632
  "src/state.ts"() {
1063
4633
  "use strict";
4634
+ init_bridge();
1064
4635
  MAX_PUSH_TOKENS = 10;
1065
- Saved = z6.object({
1066
- sessionId: z6.string().nullable().catch(null),
1067
- pushTokens: z6.array(z6.string()).catch([])
4636
+ Saved = z7.object({
4637
+ sessionId: z7.string().nullable().catch(null),
4638
+ pushTokens: z7.array(z7.string()).catch([]),
4639
+ /** Chọn từ app. `null` = theo .env. */
4640
+ permissionMode: BridgePermissionMode.nullable().catch(null),
4641
+ model: BridgeModel.catch(null)
1068
4642
  });
1069
4643
  StateStore = class {
1070
4644
  constructor(file) {
1071
4645
  this.file = file;
1072
- this.data = { sessionId: null, pushTokens: [] };
4646
+ this.data = { sessionId: null, pushTokens: [], permissionMode: null, model: null };
1073
4647
  try {
1074
4648
  const r = Saved.safeParse(JSON.parse(readFileSync(file, "utf8")));
1075
4649
  if (r.success) this.data = r.data;
@@ -1085,6 +4659,22 @@ var init_state = __esm({
1085
4659
  this.data.sessionId = id;
1086
4660
  this.save();
1087
4661
  }
4662
+ get permissionMode() {
4663
+ return this.data.permissionMode;
4664
+ }
4665
+ set permissionMode(mode) {
4666
+ if (mode === this.data.permissionMode) return;
4667
+ this.data.permissionMode = mode;
4668
+ this.save();
4669
+ }
4670
+ get model() {
4671
+ return this.data.model;
4672
+ }
4673
+ set model(model) {
4674
+ if (model === this.data.model) return;
4675
+ this.data.model = model;
4676
+ this.save();
4677
+ }
1088
4678
  get pushTokens() {
1089
4679
  return this.data.pushTokens;
1090
4680
  }
@@ -1100,9 +4690,9 @@ var init_state = __esm({
1100
4690
  this.save();
1101
4691
  }
1102
4692
  save() {
1103
- mkdirSync(path2.dirname(this.file), { recursive: true });
4693
+ mkdirSync2(path3.dirname(this.file), { recursive: true });
1104
4694
  const tmp = `${this.file}.tmp`;
1105
- writeFileSync(tmp, JSON.stringify(this.data, null, 2));
4695
+ writeFileSync2(tmp, JSON.stringify(this.data, null, 2));
1106
4696
  renameSync(tmp, this.file);
1107
4697
  }
1108
4698
  };
@@ -1112,14 +4702,14 @@ var init_state = __esm({
1112
4702
  // src/tunnel.ts
1113
4703
  import { spawn } from "node:child_process";
1114
4704
  import { existsSync } from "node:fs";
1115
- import path3 from "node:path";
4705
+ import path4 from "node:path";
1116
4706
  import { createInterface } from "node:readline";
1117
4707
  function findCloudflared(configured, env = process.env, exists = existsSync, platform = process.platform) {
1118
4708
  if (configured) return configured;
1119
4709
  if (platform === "win32") {
1120
4710
  for (const base of [env["ProgramFiles(x86)"], env.ProgramFiles]) {
1121
4711
  if (!base) continue;
1122
- const p = path3.win32.join(base, "cloudflared", "cloudflared.exe");
4712
+ const p = path4.win32.join(base, "cloudflared", "cloudflared.exe");
1123
4713
  if (exists(p)) return p;
1124
4714
  }
1125
4715
  }
@@ -1293,8 +4883,8 @@ var init_index = __esm({
1293
4883
  // src/cli.ts
1294
4884
  init_config();
1295
4885
  import { randomBytes } from "node:crypto";
1296
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, statSync, writeFileSync as writeFileSync2 } from "node:fs";
1297
- import path4 from "node:path";
4886
+ import { existsSync as existsSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync2, statSync as statSync2, writeFileSync as writeFileSync3 } from "node:fs";
4887
+ import path5 from "node:path";
1298
4888
  var HELP = `C\xE1ch d\xF9ng: manualofme-bridge [th\u01B0 m\u1EE5c]
1299
4889
 
1300
4890
  M\u1EDF Claude Code tr\xEAn m\xE1y n\xE0y cho web/app ManualOfMe \u0111i\u1EC1u khi\u1EC3n. Claude l\xE0m vi\u1EC7c trong
@@ -1314,8 +4904,8 @@ if (args.includes("-h") || args.includes("--help")) {
1314
4904
  var resetToken = args.includes("--token");
1315
4905
  var dirArg = args.find((a) => !a.startsWith("-"));
1316
4906
  if (dirArg) {
1317
- const dir = path4.resolve(dirArg);
1318
- if (!existsSync2(dir) || !statSync(dir).isDirectory()) {
4907
+ const dir = path5.resolve(dirArg);
4908
+ if (!existsSync2(dir) || !statSync2(dir).isDirectory()) {
1319
4909
  console.error(`Kh\xF4ng c\xF3 th\u01B0 m\u1EE5c ${dir}`);
1320
4910
  process.exit(1);
1321
4911
  }
@@ -1359,10 +4949,10 @@ async function askToken(reset) {
1359
4949
  }
1360
4950
  }
1361
4951
  function saveToken(token) {
1362
- mkdirSync2(CONFIG_DIR, { recursive: true });
4952
+ mkdirSync3(CONFIG_DIR, { recursive: true });
1363
4953
  const old = existsSync2(USER_ENV_FILE) ? readFileSync2(USER_ENV_FILE, "utf8") : "";
1364
4954
  const lines = old.split(/\r?\n/).filter((l) => l && !/^\s*BRIDGE_TOKEN\s*=/.test(l));
1365
- writeFileSync2(USER_ENV_FILE, [`BRIDGE_TOKEN=${token}`, ...lines, ""].join("\n"), { mode: 384 });
4955
+ writeFileSync3(USER_ENV_FILE, [`BRIDGE_TOKEN=${token}`, ...lines, ""].join("\n"), { mode: 384 });
1366
4956
  }
1367
4957
  function readHidden(prompt) {
1368
4958
  return new Promise((resolve) => {