@coast/rrule
Version:
JavaScript library for working with recurrence rules for calendar dates.
1,288 lines (1,217 loc) • 141 kB
JavaScript
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("luxon"));
else if(typeof define === 'function' && define.amd)
define(["luxon"], factory);
else if(typeof exports === 'object')
exports["rrule"] = factory(require("luxon"));
else
root["rrule"] = factory(root["luxon"]);
})(typeof self !== 'undefined' ? self : this, function(__WEBPACK_EXTERNAL_MODULE__3__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 1);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return isPresent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return isNumber; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return isWeekdayStr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return isArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return range; });
/* unused harmony export clone */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return repeat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return toArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return padStart; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return split; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return pymod; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return divmod; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return empty; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return notEmpty; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return includes; });
/* harmony import */ var _weekday__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
// =============================================================================
// Helper functions
// =============================================================================
var isPresent = function (value) {
return value !== null && value !== undefined;
};
var isNumber = function (value) {
return typeof value === 'number';
};
var isWeekdayStr = function (value) {
return _weekday__WEBPACK_IMPORTED_MODULE_0__[/* ALL_WEEKDAYS */ "a"].indexOf(value) >= 0;
};
var isArray = Array.isArray;
/**
* Simplified version of python's range()
*/
var range = function (start, end) {
if (end === void 0) { end = start; }
if (arguments.length === 1) {
end = start;
start = 0;
}
var rang = [];
for (var i = start; i < end; i++)
rang.push(i);
return rang;
};
var clone = function (array) {
return [].concat(array);
};
var repeat = function (value, times) {
var i = 0;
var array = [];
if (isArray(value)) {
for (; i < times; i++)
array[i] = [].concat(value);
}
else {
for (; i < times; i++)
array[i] = value;
}
return array;
};
var toArray = function (item) {
if (isArray(item)) {
return item;
}
return [item];
};
function padStart(item, targetLength, padString) {
if (padString === void 0) { padString = ' '; }
var str = String(item);
targetLength = targetLength >> 0;
if (str.length > targetLength) {
return String(str);
}
targetLength = targetLength - str.length;
if (targetLength > padString.length) {
padString += repeat(padString, targetLength / padString.length);
}
return padString.slice(0, targetLength) + String(str);
}
/**
* Python like split
*/
var split = function (str, sep, num) {
var splits = str.split(sep);
return num
? splits.slice(0, num).concat([splits.slice(num).join(sep)])
: splits;
};
/**
* closure/goog/math/math.js:modulo
* Copyright 2006 The Closure Library Authors.
* The % operator in JavaScript returns the remainder of a / b, but differs from
* some other languages in that the result will have the same sign as the
* dividend. For example, -1 % 8 == -1, whereas in some other languages
* (such as Python) the result would be 7. This function emulates the more
* correct modulo behavior, which is useful for certain applications such as
* calculating an offset index in a circular list.
*
* @param {number} a The dividend.
* @param {number} b The divisor.
* @return {number} a % b where the result is between 0 and b (either 0 <= x < b
* or b < x <= 0, depending on the sign of b).
*/
var pymod = function (a, b) {
var r = a % b;
// If r and b differ in sign, add b to wrap the result to the correct sign.
return r * b < 0 ? r + b : r;
};
/**
* @see: <http://docs.python.org/library/functions.html#divmod>
*/
var divmod = function (a, b) {
return { div: Math.floor(a / b), mod: pymod(a, b) };
};
var empty = function (obj) {
return !isPresent(obj) || obj.length === 0;
};
/**
* Python-like boolean
* @return {Boolean} value of an object/primitive, taking into account
* the fact that in Python an empty list's/tuple's
* boolean value is False, whereas in JS it's true
*/
var notEmpty = function (obj) {
return !empty(obj);
};
/**
* Return true if a value is in an array
*/
var includes = function (arr, val) {
return notEmpty(arr) && arr.indexOf(val) !== -1;
};
/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
// EXTERNAL MODULE: ./src/helpers.ts
var helpers = __webpack_require__(0);
// CONCATENATED MODULE: ./src/dateutil.ts
/**
* General date-related utilities.
* Also handles several incompatibilities between JavaScript and Python
*
*/
var dateutil_dateutil;
(function (dateutil) {
dateutil.MONTH_DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
/**
* Number of milliseconds of one day
*/
dateutil.ONE_DAY = 1000 * 60 * 60 * 24;
/**
* @see: <http://docs.python.org/library/datetime.html#datetime.MAXYEAR>
*/
dateutil.MAXYEAR = 9999;
/**
* Python uses 1-Jan-1 as the base for calculating ordinals but we don't
* want to confuse the JS engine with milliseconds > Number.MAX_NUMBER,
* therefore we use 1-Jan-1970 instead
*/
dateutil.ORDINAL_BASE = new Date(Date.UTC(1970, 0, 1));
/**
* Python: MO-SU: 0 - 6
* JS: SU-SAT 0 - 6
*/
dateutil.PY_WEEKDAYS = [6, 0, 1, 2, 3, 4, 5];
/**
* py_date.timetuple()[7]
*/
dateutil.getYearDay = function (date) {
var dateNoTime = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
return (Math.ceil((dateNoTime.valueOf() -
new Date(date.getUTCFullYear(), 0, 1).valueOf()) /
dateutil.ONE_DAY) + 1);
};
dateutil.isLeapYear = function (year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
};
dateutil.isDate = function (value) {
return value instanceof Date;
};
dateutil.isValidDate = function (value) {
return dateutil.isDate(value) && !isNaN(value.getTime());
};
/**
* @return {Number} the date's timezone offset in ms
*/
dateutil.tzOffset = function (date) {
return date.getTimezoneOffset() * 60 * 1000;
};
/**
* @see: <http://www.mcfedries.com/JavaScript/DaysBetween.asp>
*/
dateutil.daysBetween = function (date1, date2) {
// The number of milliseconds in one day
// Convert both dates to milliseconds
var date1ms = date1.getTime() - dateutil.tzOffset(date1);
var date2ms = date2.getTime() - dateutil.tzOffset(date2);
// Calculate the difference in milliseconds
var differencems = date1ms - date2ms;
// Convert back to days and return
return Math.round(differencems / dateutil.ONE_DAY);
};
/**
* @see: <http://docs.python.org/library/datetime.html#datetime.date.toordinal>
*/
dateutil.toOrdinal = function (date) {
return dateutil.daysBetween(date, dateutil.ORDINAL_BASE);
};
/**
* @see - <http://docs.python.org/library/datetime.html#datetime.date.fromordinal>
*/
dateutil.fromOrdinal = function (ordinal) {
return new Date(dateutil.ORDINAL_BASE.getTime() + ordinal * dateutil.ONE_DAY);
};
dateutil.getMonthDays = function (date) {
var month = date.getUTCMonth();
return month === 1 && dateutil.isLeapYear(date.getUTCFullYear())
? 29
: dateutil.MONTH_DAYS[month];
};
/**
* @return {Number} python-like weekday
*/
dateutil.getWeekday = function (date) {
return dateutil.PY_WEEKDAYS[date.getUTCDay()];
};
/**
* @see: <http://docs.python.org/library/calendar.html#calendar.monthrange>
*/
dateutil.monthRange = function (year, month) {
var date = new Date(Date.UTC(year, month, 1));
return [dateutil.getWeekday(date), dateutil.getMonthDays(date)];
};
/**
* @see: <http://docs.python.org/library/datetime.html#datetime.datetime.combine>
*/
dateutil.combine = function (date, time) {
time = time || date;
return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), time.getHours(), time.getMinutes(), time.getSeconds(), time.getMilliseconds()));
};
dateutil.clone = function (date) {
var dolly = new Date(date.getTime());
return dolly;
};
dateutil.cloneDates = function (dates) {
var clones = [];
for (var i = 0; i < dates.length; i++) {
clones.push(dateutil.clone(dates[i]));
}
return clones;
};
/**
* Sorts an array of Date or dateutil.Time objects
*/
dateutil.sort = function (dates) {
dates.sort(function (a, b) {
return a.getTime() - b.getTime();
});
};
dateutil.timeToUntilString = function (time, utc) {
if (utc === void 0) { utc = true; }
var date = new Date(time);
return [
Object(helpers["i" /* padStart */])(date.getUTCFullYear().toString(), 4, '0'),
Object(helpers["i" /* padStart */])(date.getUTCMonth() + 1, 2, '0'),
Object(helpers["i" /* padStart */])(date.getUTCDate(), 2, '0'),
'T',
Object(helpers["i" /* padStart */])(date.getUTCHours(), 2, '0'),
Object(helpers["i" /* padStart */])(date.getUTCMinutes(), 2, '0'),
Object(helpers["i" /* padStart */])(date.getUTCSeconds(), 2, '0'),
utc ? 'Z' : ''
].join('');
};
dateutil.untilStringToDate = function (until) {
var re = /^(\d{4})(\d{2})(\d{2})(T(\d{2})(\d{2})(\d{2})Z?)?$/;
var bits = re.exec(until);
if (!bits)
throw new Error("Invalid UNTIL value: " + until);
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));
};
})(dateutil_dateutil || (dateutil_dateutil = {}));
/* harmony default export */ var src_dateutil = (dateutil_dateutil);
// CONCATENATED MODULE: ./src/iterresult.ts
/**
* This class helps us to emulate python's generators, sorta.
*/
var IterResult = /** @class */ (function () {
function IterResult(method, args) {
this.minDate = null;
this.maxDate = null;
this._result = [];
this.total = 0;
this.method = method;
this.args = args;
if (method === 'between') {
this.maxDate = args.inc
? args.before
: new Date(args.before.getTime() - 1);
this.minDate = args.inc ? args.after : new Date(args.after.getTime() + 1);
}
else if (method === 'before') {
this.maxDate = args.inc ? args.dt : new Date(args.dt.getTime() - 1);
}
else if (method === 'after') {
this.minDate = args.inc ? args.dt : new Date(args.dt.getTime() + 1);
}
}
/**
* Possibly adds a date into the result.
*
* @param {Date} date - the date isn't necessarly added to the result
* list (if it is too late/too early)
* @return {Boolean} true if it makes sense to continue the iteration
* false if we're done.
*/
IterResult.prototype.accept = function (date) {
++this.total;
var tooEarly = this.minDate && date < this.minDate;
var tooLate = this.maxDate && date > this.maxDate;
if (this.method === 'between') {
if (tooEarly)
return true;
if (tooLate)
return false;
}
else if (this.method === 'before') {
if (tooLate)
return false;
}
else if (this.method === 'after') {
if (tooEarly)
return true;
this.add(date);
return false;
}
return this.add(date);
};
/**
*
* @param {Date} date that is part of the result.
* @return {Boolean} whether we are interested in more values.
*/
IterResult.prototype.add = function (date) {
this._result.push(date);
return true;
};
/**
* 'before' and 'after' return only one date, whereas 'all'
* and 'between' an array.
* @return {Date,Array?}
*/
IterResult.prototype.getValue = function () {
var res = this._result;
switch (this.method) {
case 'all':
case 'between':
return res;
case 'before':
case 'after':
default:
return (res.length ? res[res.length - 1] : null);
}
};
IterResult.prototype.clone = function () {
return new IterResult(this.method, this.args);
};
return IterResult;
}());
/* harmony default export */ var iterresult = (IterResult);
// CONCATENATED MODULE: ./node_modules/tslib/tslib.es6.js
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
}
return __assign.apply(this, arguments);
}
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
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;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
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;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __exportStar(m, exports) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
function __values(o) {
var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
if (m) return m.call(o);
return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
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 () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result.default = mod;
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
// CONCATENATED MODULE: ./src/callbackiterresult.ts
/**
* IterResult subclass that calls a callback function on each add,
* and stops iterating when the callback returns false.
*/
var callbackiterresult_CallbackIterResult = /** @class */ (function (_super) {
__extends(CallbackIterResult, _super);
function CallbackIterResult(method, args, iterator) {
var _this = _super.call(this, method, args) || this;
_this.iterator = iterator;
return _this;
}
CallbackIterResult.prototype.add = function (date) {
if (this.iterator(date, this._result.length)) {
this._result.push(date);
return true;
}
return false;
};
return CallbackIterResult;
}(iterresult));
/* harmony default export */ var callbackiterresult = (callbackiterresult_CallbackIterResult);
// CONCATENATED MODULE: ./src/types.ts
var Frequency;
(function (Frequency) {
Frequency[Frequency["YEARLY"] = 0] = "YEARLY";
Frequency[Frequency["MONTHLY"] = 1] = "MONTHLY";
Frequency[Frequency["WEEKLY"] = 2] = "WEEKLY";
Frequency[Frequency["DAILY"] = 3] = "DAILY";
Frequency[Frequency["HOURLY"] = 4] = "HOURLY";
Frequency[Frequency["MINUTELY"] = 5] = "MINUTELY";
Frequency[Frequency["SECONDLY"] = 6] = "SECONDLY";
})(Frequency || (Frequency = {}));
function freqIsDailyOrGreater(freq) {
return freq < Frequency.HOURLY;
}
// EXTERNAL MODULE: ./src/weekday.ts
var weekday = __webpack_require__(2);
// CONCATENATED MODULE: ./src/datetime.ts
var Time = /** @class */ (function () {
function Time(hour, minute, second, millisecond) {
this.hour = hour;
this.minute = minute;
this.second = second;
this.millisecond = millisecond || 0;
}
Time.prototype.getHours = function () {
return this.hour;
};
Time.prototype.getMinutes = function () {
return this.minute;
};
Time.prototype.getSeconds = function () {
return this.second;
};
Time.prototype.getMilliseconds = function () {
return this.millisecond;
};
Time.prototype.getTime = function () {
return ((this.hour * 60 * 60 + this.minute * 60 + this.second) * 1000 +
this.millisecond);
};
return Time;
}());
var datetime_DateTime = /** @class */ (function (_super) {
__extends(DateTime, _super);
function DateTime(year, month, day, hour, minute, second, millisecond) {
var _this = _super.call(this, hour, minute, second, millisecond) || this;
_this.year = year;
_this.month = month;
_this.day = day;
return _this;
}
DateTime.fromDate = function (date) {
return new this(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.valueOf() % 1000);
};
DateTime.prototype.getWeekday = function () {
return dateutil_dateutil.getWeekday(new Date(this.getTime()));
};
DateTime.prototype.getTime = function () {
return new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, this.millisecond)).getTime();
};
DateTime.prototype.getDay = function () {
return this.day;
};
DateTime.prototype.getMonth = function () {
return this.month;
};
DateTime.prototype.getYear = function () {
return this.year;
};
DateTime.prototype.addYears = function (years) {
this.year += years;
};
DateTime.prototype.addMonths = function (months) {
this.month += months;
if (this.month > 12) {
var yearDiv = Math.floor(this.month / 12);
var monthMod = Object(helpers["j" /* pymod */])(this.month, 12);
this.month = monthMod;
this.year += yearDiv;
if (this.month === 0) {
this.month = 12;
--this.year;
}
}
};
DateTime.prototype.addWeekly = function (days, wkst) {
if (wkst > this.getWeekday()) {
this.day += -(this.getWeekday() + 1 + (6 - wkst)) + days * 7;
}
else {
this.day += -(this.getWeekday() - wkst) + days * 7;
}
this.fixDay();
};
DateTime.prototype.addDaily = function (days) {
this.day += days;
this.fixDay();
};
DateTime.prototype.addHours = function (hours, filtered, byhour) {
if (filtered) {
// Jump to one iteration before next day
this.hour += Math.floor((23 - this.hour) / hours) * hours;
}
while (true) {
this.hour += hours;
var _a = Object(helpers["a" /* divmod */])(this.hour, 24), dayDiv = _a.div, hourMod = _a.mod;
if (dayDiv) {
this.hour = hourMod;
this.addDaily(dayDiv);
}
if (Object(helpers["b" /* empty */])(byhour) || Object(helpers["c" /* includes */])(byhour, this.hour))
break;
}
};
DateTime.prototype.addMinutes = function (minutes, filtered, byhour, byminute) {
if (filtered) {
// Jump to one iteration before next day
this.minute +=
Math.floor((1439 - (this.hour * 60 + this.minute)) / minutes) * minutes;
}
while (true) {
this.minute += minutes;
var _a = Object(helpers["a" /* divmod */])(this.minute, 60), hourDiv = _a.div, minuteMod = _a.mod;
if (hourDiv) {
this.minute = minuteMod;
this.addHours(hourDiv, false, byhour);
}
if ((Object(helpers["b" /* empty */])(byhour) || Object(helpers["c" /* includes */])(byhour, this.hour)) &&
(Object(helpers["b" /* empty */])(byminute) || Object(helpers["c" /* includes */])(byminute, this.minute))) {
break;
}
}
};
DateTime.prototype.addSeconds = function (seconds, filtered, byhour, byminute, bysecond) {
if (filtered) {
// Jump to one iteration before next day
this.second +=
Math.floor((86399 - (this.hour * 3600 + this.minute * 60 + this.second)) / seconds) * seconds;
}
while (true) {
this.second += seconds;
var _a = Object(helpers["a" /* divmod */])(this.second, 60), minuteDiv = _a.div, secondMod = _a.mod;
if (minuteDiv) {
this.second = secondMod;
this.addMinutes(minuteDiv, false, byhour, byminute);
}
if ((Object(helpers["b" /* empty */])(byhour) || Object(helpers["c" /* includes */])(byhour, this.hour)) &&
(Object(helpers["b" /* empty */])(byminute) || Object(helpers["c" /* includes */])(byminute, this.minute)) &&
(Object(helpers["b" /* empty */])(bysecond) || Object(helpers["c" /* includes */])(bysecond, this.second))) {
break;
}
}
};
DateTime.prototype.fixDay = function () {
if (this.day <= 28) {
return;
}
var daysinmonth = dateutil_dateutil.monthRange(this.year, this.month - 1)[1];
if (this.day <= daysinmonth) {
return;
}
while (this.day > daysinmonth) {
this.day -= daysinmonth;
++this.month;
if (this.month === 13) {
this.month = 1;
++this.year;
if (this.year > dateutil_dateutil.MAXYEAR) {
return;
}
}
daysinmonth = dateutil_dateutil.monthRange(this.year, this.month - 1)[1];
}
};
DateTime.prototype.add = function (options, filtered) {
var freq = options.freq, interval = options.interval, wkst = options.wkst, byhour = options.byhour, byminute = options.byminute, bysecond = options.bysecond;
switch (freq) {
case Frequency.YEARLY: return this.addYears(interval);
case Frequency.MONTHLY: return this.addMonths(interval);
case Frequency.WEEKLY: return this.addWeekly(interval, wkst);
case Frequency.DAILY: return this.addDaily(interval);
case Frequency.HOURLY: return this.addHours(interval, filtered, byhour);
case Frequency.MINUTELY: return this.addMinutes(interval, filtered, byhour, byminute);
case Frequency.SECONDLY: return this.addSeconds(interval, filtered, byhour, byminute, bysecond);
}
};
return DateTime;
}(Time));
// CONCATENATED MODULE: ./src/parseoptions.ts
function initializeOptions(options) {
var invalid = [];
var keys = Object.keys(options);
// Shallow copy for options and origOptions and check for invalid
for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
var key = keys_1[_i];
if (!Object(helpers["c" /* includes */])(rrule_defaultKeys, key))
invalid.push(key);
if (src_dateutil.isDate(options[key]) && !src_dateutil.isValidDate(options[key]))
invalid.push(key);
}
if (invalid.length) {
throw new Error('Invalid options: ' + invalid.join(', '));
}
return __assign({}, options);
}
function parseOptions(options) {
var opts = __assign(__assign({}, DEFAULT_OPTIONS), initializeOptions(options));
if (Object(helpers["f" /* isPresent */])(opts.byeaster))
opts.freq = src_rrule.YEARLY;
if (!(Object(helpers["f" /* isPresent */])(opts.freq) && src_rrule.FREQUENCIES[opts.freq])) {
throw new Error("Invalid frequency: " + opts.freq + " " + options.freq);
}
if (!opts.dtstart)
opts.dtstart = new Date(new Date().setMilliseconds(0));
if (!Object(helpers["f" /* isPresent */])(opts.wkst)) {
opts.wkst = src_rrule.MO.weekday;
}
else if (Object(helpers["e" /* isNumber */])(opts.wkst)) {
// cool, just keep it like that
}
else {
opts.wkst = opts.wkst.weekday;
}
if (Object(helpers["f" /* isPresent */])(opts.bysetpos)) {
if (Object(helpers["e" /* isNumber */])(opts.bysetpos))
opts.bysetpos = [opts.bysetpos];
for (var i = 0; i < opts.bysetpos.length; i++) {
var v = opts.bysetpos[i];
if (v === 0 || !(v >= -366 && v <= 366)) {
throw new Error('bysetpos must be between 1 and 366,' + ' or between -366 and -1');
}
}
}
if (!(Boolean(opts.byweekno) ||
Object(helpers["h" /* notEmpty */])(opts.byweekno) ||
Object(helpers["h" /* notEmpty */])(opts.byyearday) ||
Boolean(opts.bymonthday) ||
Object(helpers["h" /* notEmpty */])(opts.bymonthday) ||
Object(helpers["f" /* isPresent */])(opts.byweekday) ||
Object(helpers["f" /* isPresent */])(opts.byeaster))) {
switch (opts.freq) {
case src_rrule.YEARLY:
if (!opts.bymonth)
opts.bymonth = opts.dtstart.getUTCMonth() + 1;
opts.bymonthday = opts.dtstart.getUTCDate();
break;
case src_rrule.MONTHLY:
opts.bymonthday = opts.dtstart.getUTCDate();
break;
case src_rrule.WEEKLY:
opts.byweekday = [src_dateutil.getWeekday(opts.dtstart)];
break;
}
}
// bymonth
if (Object(helpers["f" /* isPresent */])(opts.bymonth) && !Object(helpers["d" /* isArray */])(opts.bymonth)) {
opts.bymonth = [opts.bymonth];
}
// byyearday
if (Object(helpers["f" /* isPresent */])(opts.byyearday) &&
!Object(helpers["d" /* isArray */])(opts.byyearday) &&
Object(helpers["e" /* isNumber */])(opts.byyearday)) {
opts.byyearday = [opts.byyearday];
}
// bymonthday
if (!Object(helpers["f" /* isPresent */])(opts.bymonthday)) {
opts.bymonthday = [];
opts.bynmonthday = [];
}
else if (Object(helpers["d" /* isArray */])(opts.bymonthday)) {
var bymonthday = [];
var bynmonthday = [];
for (var i = 0; i < opts.bymonthday.length; i++) {
var v = opts.bymonthday[i];
if (v > 0) {
bymonthday.push(v);
}
else if (v < 0) {
bynmonthday.push(v);
}
}
opts.bymonthday = bymonthday;
opts.bynmonthday = bynmonthday;
}
else if (opts.bymonthday < 0) {
opts.bynmonthday = [opts.bymonthday];
opts.bymonthday = [];
}
else {
opts.bynmonthday = [];
opts.bymonthday = [opts.bymonthday];
}
// byweekno
if (Object(helpers["f" /* isPresent */])(opts.byweekno) && !Object(helpers["d" /* isArray */])(opts.byweekno)) {
opts.byweekno = [opts.byweekno];
}
// byweekday / bynweekday
if (!Object(helpers["f" /* isPresent */])(opts.byweekday)) {
opts.bynweekday = null;
}
else if (Object(helpers["e" /* isNumber */])(opts.byweekday)) {
opts.byweekday = [opts.byweekday];
opts.bynweekday = null;
}
else if (Object(helpers["g" /* isWeekdayStr */])(opts.byweekday)) {
opts.byweekday = [weekday["b" /* Weekday */].fromStr(opts.byweekday).weekday];
opts.bynweekday = null;
}
else if (opts.byweekday instanceof weekday["b" /* Weekday */]) {
if (!opts.byweekday.n || opts.freq > src_rrule.MONTHLY) {
opts.byweekday = [opts.byweekday.weekday];
opts.bynweekday = null;
}
else {
opts.bynweekday = [[opts.byweekday.weekday, opts.byweekday.n]];
opts.byweekday = null;
}
}
else {
var byweekday = [];
var bynweekday = [];
for (var i = 0; i < opts.byweekday.length; i++) {
var wday = opts.byweekday[i];
if (Object(helpers["e" /* isNumber */])(wday)) {
byweekday.push(wday);
continue;
}
else if (Object(helpers["g" /* isWeekdayStr */])(wday)) {
byweekday.push(weekday["b" /* Weekday */].fromStr(wday).weekday);
continue;
}
if (!wday.n || opts.freq > src_rrule.MONTHLY) {
byweekday.push(wday.weekday);
}
else {
bynweekday.push([wday.weekday, wday.n]);
}
}
opts.byweekday = Object(helpers["h" /* notEmpty */])(byweekday) ? byweekday : null;
opts.bynweekday = Object(helpers["h" /* notEmpty */])(bynweekday) ? bynweekday : null;
}
// byhour
if (!Object(helpers["f" /* isPresent */])(opts.byhour)) {
opts.byhour =
opts.freq < src_rrule.HOURLY ? [opts.dtstart.getUTCHours()] : null;
}
else if (Object(helpers["e" /* isNumber */])(opts.byhour)) {
opts.byhour = [opts.byhour];
}
// byminute
if (!Object(helpers["f" /* isPresent */])(opts.byminute)) {
opts.byminute =
opts.freq < src_rrule.MINUTELY ? [opts.dtstart.getUTCMinutes()] : null;
}
else if (Object(helpers["e" /* isNumber */])(opts.byminute)) {
opts.byminute = [opts.byminute];
}
// bysecond
if (!Object(helpers["f" /* isPresent */])(opts.bysecond)) {
opts.bysecond =
opts.freq < src_rrule.SECONDLY ? [opts.dtstart.getUTCSeconds()] : null;
}
else if (Object(helpers["e" /* isNumber */])(opts.bysecond)) {
opts.bysecond = [opts.bysecond];
}
return { parsedOptions: opts };
}
function buildTimeset(opts) {
var millisecondModulo = opts.dtstart.getTime() % 1000;
if (!freqIsDailyOrGreater(opts.freq)) {
return [];
}
var timeset = [];
opts.byhour.forEach(function (hour) {
opts.byminute.forEach(function (minute) {
opts.bysecond.forEach(function (second) {
timeset.push(new Time(hour, minute, second, millisecondModulo));
});
});
});
return timeset;
}
// CONCATENATED MODULE: ./src/parsestring.ts
function parseString(rfcString) {
var options = rfcString.split('\n').map(parseLine).filter(function (x) { return x !== null; });
return __assign(__assign({}, options[0]), options[1]);
}
function parseDtstart(line) {
var options = {};
var dtstartWithZone = /DTSTART(?:;TZID=([^:=]+?))?(?::|=)([^;\s]+)/i.exec(line);
if (!dtstartWithZone) {
return options;
}
var _ = dtstartWithZone[0], tzid = dtstartWithZone[1], dtstart = dtstartWithZone[2];
if (tzid) {
options.tzid = tzid;
}
options.dtstart = src_dateutil.untilStringToDate(dtstart);
return options;
}
function parseLine(rfcString) {
rfcString = rfcString.replace(/^\s+|\s+$/, '');
if (!rfcString.length)
return null;
var header = /^([A-Z]+?)[:;]/.exec(rfcString.toUpperCase());
if (!header) {
return parseRrule(rfcString);
}
var _ = header[0], key = header[1];
switch (key.toUpperCase()) {
case 'RRULE':
case 'EXRULE':
return parseRrule(rfcString);
case 'DTSTART':
return parseDtstart(rfcString);
default:
throw new Error("Unsupported RFC prop " + key + " in " + rfcString);
}
}
function parseRrule(line) {
var strippedLine = line.replace(/^RRULE:/i, '');
var options = parseDtstart(strippedLine);
var attrs = line.replace(/^(?:RRULE|EXRULE):/i, '').split(';');
attrs.forEach(function (attr) {
var _a = attr.split('='), key = _a[0], value = _a[1];
switch (key.toUpperCase()) {
case 'FREQ':
options.freq = Frequency[value.toUpperCase()];
break;
case 'WKST':
options.wkst = Days[value.toUpperCase()];
break;
case 'COUNT':
case 'INTERVAL':
case 'BYSETPOS':
case 'BYMONTH':
case 'BYMONTHDAY':
case 'BYYEARDAY':
case 'BYWEEKNO':
case 'BYHOUR':
case 'BYMINUTE':
case 'BYSECOND':
var num = parseNumber(value);
var optionKey = key.toLowerCase();
// @ts-ignore
options[optionKey] = num;
break;
case 'BYWEEKDAY':
case 'BYDAY':
options.byweekday = parseWeekday(value);
break;
case 'DTSTART':
case 'TZID':
// for backwards compatibility
var dtstart = parseDtstart(line);
options.tzid = dtstart.tzid;
options.dtstart = dtstart.dtstart;
break;
case 'UNTIL':
options.until = src_dateutil.untilStringToDate(value);
break;
case 'BYEASTER':
options.byeaster = Number(value);
break;
default:
throw new Error("Unknown RRULE property '" + key + "'");
}
});
return options;
}
function parseNumber(value) {
if (value.indexOf(',') !== -1) {
var values = value.split(',');
return values.map(parseIndividualNumber);
}
return parseIndividualNumber(value);
}
function parseIndividualNumber(value) {
if (/^[+-]?\d+$/.test(value)) {
return Number(value);
}
return value;
}
function parseWeekday(value) {
var days = value.split(',');
return days.map(function (day) {
if (day.length === 2) {
// MO, TU, ...
return Days[day]; // wday instanceof Weekday
}
// -1MO, +3FR, 1SO, 13TU ...
var parts = day.match(/^([+-]?\d{1,2})([A-Z]{2})$/);
var n = Number(parts[1]);
var wdaypart = parts[2];
var wday = Days[wdaypart].weekday;
return new weekday["b" /* Weekday */](wday, n);
});
}
// EXTERNAL MODULE: external "luxon"
var external_luxon_ = __webpack_require__(3);
// CONCATENATED MODULE: ./src/datewithzone.ts
var datewithzone_DateWithZone = /** @class */ (function () {
function DateWithZone(date, tzid) {
this.date = date;
this.tzid = tzid;
}
Object.defineProperty(DateWithZone.prototype, "isUTC", {
get: function () {
return !this.tzid || this.tzid.toUpperCase() === 'UTC';
},
enumerable: true,
configurable: true
});
DateWithZone.prototype.toString = function () {
var datestr = src_dateutil.timeToUntilString(this.date.getTime(), this.isUTC);
if (!this.isUTC) {
return ";TZID=" + this.tzid + ":" + datestr;
}
return ":" + datestr;
};
DateWithZone.prototype.getTime = function () {
return this.date.getTime();
};
DateWithZone.prototype.rezonedDate = function () {
if (this.isUTC) {
return this.date;
}
try {
var datetime = external_luxon_["DateTime"]
.fromJSDate(this.date);
var rezoned = datetime.setZone(this.tzid, { keepLocalTime: true });
return rezoned.toJSDate();
}
catch (e) {
if (e instanceof TypeError) {
console.error('Using TZID without Luxon available is unsupported. Returned times are in UTC, not the requested time zone');
}
return this.date;
}
};
return DateWithZone;
}());
// CONCATENATED MODULE: ./src/optionstostring.ts
function optionsToString(options) {
var rrule = [];
var dtstart = '';
var keys = Object.keys(options);
var defaultKeys = Object.keys(DEFAULT_OPTIONS);
for (var i = 0; i < keys.length; i++) {
if (keys[i] === 'tzid')
continue;