You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

9345 lines
343 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// node_modules/luxon/build/node/luxon.js
var require_luxon = __commonJS({
"node_modules/luxon/build/node/luxon.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var LuxonError = class extends Error {
};
var InvalidDateTimeError = class extends LuxonError {
constructor(reason) {
super(`Invalid DateTime: ${reason.toMessage()}`);
}
};
var InvalidIntervalError = class extends LuxonError {
constructor(reason) {
super(`Invalid Interval: ${reason.toMessage()}`);
}
};
var InvalidDurationError = class extends LuxonError {
constructor(reason) {
super(`Invalid Duration: ${reason.toMessage()}`);
}
};
var ConflictingSpecificationError = class extends LuxonError {
};
var InvalidUnitError = class extends LuxonError {
constructor(unit) {
super(`Invalid unit ${unit}`);
}
};
var InvalidArgumentError = class extends LuxonError {
};
var ZoneIsAbstractError = class extends LuxonError {
constructor() {
super("Zone is an abstract class");
}
};
var n = "numeric";
var s = "short";
var l = "long";
var DATE_SHORT = {
year: n,
month: n,
day: n
};
var DATE_MED = {
year: n,
month: s,
day: n
};
var DATE_MED_WITH_WEEKDAY = {
year: n,
month: s,
day: n,
weekday: s
};
var DATE_FULL = {
year: n,
month: l,
day: n
};
var DATE_HUGE = {
year: n,
month: l,
day: n,
weekday: l
};
var TIME_SIMPLE = {
hour: n,
minute: n
};
var TIME_WITH_SECONDS = {
hour: n,
minute: n,
second: n
};
var TIME_WITH_SHORT_OFFSET = {
hour: n,
minute: n,
second: n,
timeZoneName: s
};
var TIME_WITH_LONG_OFFSET = {
hour: n,
minute: n,
second: n,
timeZoneName: l
};
var TIME_24_SIMPLE = {
hour: n,
minute: n,
hourCycle: "h23"
};
var TIME_24_WITH_SECONDS = {
hour: n,
minute: n,
second: n,
hourCycle: "h23"
};
var TIME_24_WITH_SHORT_OFFSET = {
hour: n,
minute: n,
second: n,
hourCycle: "h23",
timeZoneName: s
};
var TIME_24_WITH_LONG_OFFSET = {
hour: n,
minute: n,
second: n,
hourCycle: "h23",
timeZoneName: l
};
var DATETIME_SHORT = {
year: n,
month: n,
day: n,
hour: n,
minute: n
};
var DATETIME_SHORT_WITH_SECONDS = {
year: n,
month: n,
day: n,
hour: n,
minute: n,
second: n
};
var DATETIME_MED = {
year: n,
month: s,
day: n,
hour: n,
minute: n
};
var DATETIME_MED_WITH_SECONDS = {
year: n,
month: s,
day: n,
hour: n,
minute: n,
second: n
};
var DATETIME_MED_WITH_WEEKDAY = {
year: n,
month: s,
day: n,
weekday: s,
hour: n,
minute: n
};
var DATETIME_FULL = {
year: n,
month: l,
day: n,
hour: n,
minute: n,
timeZoneName: s
};
var DATETIME_FULL_WITH_SECONDS = {
year: n,
month: l,
day: n,
hour: n,
minute: n,
second: n,
timeZoneName: s
};
var DATETIME_HUGE = {
year: n,
month: l,
day: n,
weekday: l,
hour: n,
minute: n,
timeZoneName: l
};
var DATETIME_HUGE_WITH_SECONDS = {
year: n,
month: l,
day: n,
weekday: l,
hour: n,
minute: n,
second: n,
timeZoneName: l
};
var Zone = class {
/**
* The type of zone
* @abstract
* @type {string}
*/
get type() {
throw new ZoneIsAbstractError();
}
/**
* The name of this zone.
* @abstract
* @type {string}
*/
get name() {
throw new ZoneIsAbstractError();
}
get ianaName() {
return this.name;
}
/**
* Returns whether the offset is known to be fixed for the whole year.
* @abstract
* @type {boolean}
*/
get isUniversal() {
throw new ZoneIsAbstractError();
}
/**
* Returns the offset's common name (such as EST) at the specified timestamp
* @abstract
* @param {number} ts - Epoch milliseconds for which to get the name
* @param {Object} opts - Options to affect the format
* @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'.
* @param {string} opts.locale - What locale to return the offset name in.
* @return {string}
*/
offsetName(ts, opts) {
throw new ZoneIsAbstractError();
}
/**
* Returns the offset's value as a string
* @abstract
* @param {number} ts - Epoch milliseconds for which to get the offset
* @param {string} format - What style of offset to return.
* Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively
* @return {string}
*/
formatOffset(ts, format2) {
throw new ZoneIsAbstractError();
}
/**
* Return the offset in minutes for this zone at the specified timestamp.
* @abstract
* @param {number} ts - Epoch milliseconds for which to compute the offset
* @return {number}
*/
offset(ts) {
throw new ZoneIsAbstractError();
}
/**
* Return whether this Zone is equal to another zone
* @abstract
* @param {Zone} otherZone - the zone to compare
* @return {boolean}
*/
equals(otherZone) {
throw new ZoneIsAbstractError();
}
/**
* Return whether this Zone is valid.
* @abstract
* @type {boolean}
*/
get isValid() {
throw new ZoneIsAbstractError();
}
};
var singleton$1 = null;
var SystemZone = class extends Zone {
/**
* Get a singleton instance of the local zone
* @return {SystemZone}
*/
static get instance() {
if (singleton$1 === null) {
singleton$1 = new SystemZone();
}
return singleton$1;
}
/** @override **/
get type() {
return "system";
}
/** @override **/
get name() {
return new Intl.DateTimeFormat().resolvedOptions().timeZone;
}
/** @override **/
get isUniversal() {
return false;
}
/** @override **/
offsetName(ts, {
format: format2,
locale
}) {
return parseZoneInfo(ts, format2, locale);
}
/** @override **/
formatOffset(ts, format2) {
return formatOffset(this.offset(ts), format2);
}
/** @override **/
offset(ts) {
return -new Date(ts).getTimezoneOffset();
}
/** @override **/
equals(otherZone) {
return otherZone.type === "system";
}
/** @override **/
get isValid() {
return true;
}
};
var dtfCache = {};
function makeDTF(zone) {
if (!dtfCache[zone]) {
dtfCache[zone] = new Intl.DateTimeFormat("en-US", {
hour12: false,
timeZone: zone,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
era: "short"
});
}
return dtfCache[zone];
}
var typeToPos = {
year: 0,
month: 1,
day: 2,
era: 3,
hour: 4,
minute: 5,
second: 6
};
function hackyOffset(dtf, date) {
const formatted = dtf.format(date).replace(/\u200E/g, ""), parsed = /(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(formatted), [, fMonth, fDay, fYear, fadOrBc, fHour, fMinute, fSecond] = parsed;
return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond];
}
function partsOffset(dtf, date) {
const formatted = dtf.formatToParts(date);
const filled = [];
for (let i = 0; i < formatted.length; i++) {
const {
type,
value
} = formatted[i];
const pos = typeToPos[type];
if (type === "era") {
filled[pos] = value;
} else if (!isUndefined(pos)) {
filled[pos] = parseInt(value, 10);
}
}
return filled;
}
var ianaZoneCache = {};
var IANAZone = class extends Zone {
/**
* @param {string} name - Zone name
* @return {IANAZone}
*/
static create(name) {
if (!ianaZoneCache[name]) {
ianaZoneCache[name] = new IANAZone(name);
}
return ianaZoneCache[name];
}
/**
* Reset local caches. Should only be necessary in testing scenarios.
* @return {void}
*/
static resetCache() {
ianaZoneCache = {};
dtfCache = {};
}
/**
* Returns whether the provided string is a valid specifier. This only checks the string's format, not that the specifier identifies a known zone; see isValidZone for that.
* @param {string} s - The string to check validity on
* @example IANAZone.isValidSpecifier("America/New_York") //=> true
* @example IANAZone.isValidSpecifier("Sport~~blorp") //=> false
* @deprecated This method returns false for some valid IANA names. Use isValidZone instead.
* @return {boolean}
*/
static isValidSpecifier(s2) {
return this.isValidZone(s2);
}
/**
* Returns whether the provided string identifies a real zone
* @param {string} zone - The string to check
* @example IANAZone.isValidZone("America/New_York") //=> true
* @example IANAZone.isValidZone("Fantasia/Castle") //=> false
* @example IANAZone.isValidZone("Sport~~blorp") //=> false
* @return {boolean}
*/
static isValidZone(zone) {
if (!zone) {
return false;
}
try {
new Intl.DateTimeFormat("en-US", {
timeZone: zone
}).format();
return true;
} catch (e) {
return false;
}
}
constructor(name) {
super();
this.zoneName = name;
this.valid = IANAZone.isValidZone(name);
}
/** @override **/
get type() {
return "iana";
}
/** @override **/
get name() {
return this.zoneName;
}
/** @override **/
get isUniversal() {
return false;
}
/** @override **/
offsetName(ts, {
format: format2,
locale
}) {
return parseZoneInfo(ts, format2, locale, this.name);
}
/** @override **/
formatOffset(ts, format2) {
return formatOffset(this.offset(ts), format2);
}
/** @override **/
offset(ts) {
const date = new Date(ts);
if (isNaN(date))
return NaN;
const dtf = makeDTF(this.name);
let [year, month, day, adOrBc, hour, minute, second] = dtf.formatToParts ? partsOffset(dtf, date) : hackyOffset(dtf, date);
if (adOrBc === "BC") {
year = -Math.abs(year) + 1;
}
const adjustedHour = hour === 24 ? 0 : hour;
const asUTC = objToLocalTS({
year,
month,
day,
hour: adjustedHour,
minute,
second,
millisecond: 0
});
let asTS = +date;
const over = asTS % 1e3;
asTS -= over >= 0 ? over : 1e3 + over;
return (asUTC - asTS) / (60 * 1e3);
}
/** @override **/
equals(otherZone) {
return otherZone.type === "iana" && otherZone.name === this.name;
}
/** @override **/
get isValid() {
return this.valid;
}
};
var intlLFCache = {};
function getCachedLF(locString, opts = {}) {
const key = JSON.stringify([locString, opts]);
let dtf = intlLFCache[key];
if (!dtf) {
dtf = new Intl.ListFormat(locString, opts);
intlLFCache[key] = dtf;
}
return dtf;
}
var intlDTCache = {};
function getCachedDTF(locString, opts = {}) {
const key = JSON.stringify([locString, opts]);
let dtf = intlDTCache[key];
if (!dtf) {
dtf = new Intl.DateTimeFormat(locString, opts);
intlDTCache[key] = dtf;
}
return dtf;
}
var intlNumCache = {};
function getCachedINF(locString, opts = {}) {
const key = JSON.stringify([locString, opts]);
let inf = intlNumCache[key];
if (!inf) {
inf = new Intl.NumberFormat(locString, opts);
intlNumCache[key] = inf;
}
return inf;
}
var intlRelCache = {};
function getCachedRTF(locString, opts = {}) {
const {
base,
...cacheKeyOpts
} = opts;
const key = JSON.stringify([locString, cacheKeyOpts]);
let inf = intlRelCache[key];
if (!inf) {
inf = new Intl.RelativeTimeFormat(locString, opts);
intlRelCache[key] = inf;
}
return inf;
}
var sysLocaleCache = null;
function systemLocale() {
if (sysLocaleCache) {
return sysLocaleCache;
} else {
sysLocaleCache = new Intl.DateTimeFormat().resolvedOptions().locale;
return sysLocaleCache;
}
}
function parseLocaleString(localeStr) {
const xIndex = localeStr.indexOf("-x-");
if (xIndex !== -1) {
localeStr = localeStr.substring(0, xIndex);
}
const uIndex = localeStr.indexOf("-u-");
if (uIndex === -1) {
return [localeStr];
} else {
let options;
let selectedStr;
try {
options = getCachedDTF(localeStr).resolvedOptions();
selectedStr = localeStr;
} catch (e) {
const smaller = localeStr.substring(0, uIndex);
options = getCachedDTF(smaller).resolvedOptions();
selectedStr = smaller;
}
const {
numberingSystem,
calendar
} = options;
return [selectedStr, numberingSystem, calendar];
}
}
function intlConfigString(localeStr, numberingSystem, outputCalendar) {
if (outputCalendar || numberingSystem) {
if (!localeStr.includes("-u-")) {
localeStr += "-u";
}
if (outputCalendar) {
localeStr += `-ca-${outputCalendar}`;
}
if (numberingSystem) {
localeStr += `-nu-${numberingSystem}`;
}
return localeStr;
} else {
return localeStr;
}
}
function mapMonths(f) {
const ms = [];
for (let i = 1; i <= 12; i++) {
const dt = DateTime.utc(2016, i, 1);
ms.push(f(dt));
}
return ms;
}
function mapWeekdays(f) {
const ms = [];
for (let i = 1; i <= 7; i++) {
const dt = DateTime.utc(2016, 11, 13 + i);
ms.push(f(dt));
}
return ms;
}
function listStuff(loc, length, defaultOK, englishFn, intlFn) {
const mode = loc.listingMode(defaultOK);
if (mode === "error") {
return null;
} else if (mode === "en") {
return englishFn(length);
} else {
return intlFn(length);
}
}
function supportsFastNumbers(loc) {
if (loc.numberingSystem && loc.numberingSystem !== "latn") {
return false;
} else {
return loc.numberingSystem === "latn" || !loc.locale || loc.locale.startsWith("en") || new Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem === "latn";
}
}
var PolyNumberFormatter = class {
constructor(intl, forceSimple, opts) {
this.padTo = opts.padTo || 0;
this.floor = opts.floor || false;
const {
padTo,
floor,
...otherOpts
} = opts;
if (!forceSimple || Object.keys(otherOpts).length > 0) {
const intlOpts = {
useGrouping: false,
...opts
};
if (opts.padTo > 0)
intlOpts.minimumIntegerDigits = opts.padTo;
this.inf = getCachedINF(intl, intlOpts);
}
}
format(i) {
if (this.inf) {
const fixed = this.floor ? Math.floor(i) : i;
return this.inf.format(fixed);
} else {
const fixed = this.floor ? Math.floor(i) : roundTo(i, 3);
return padStart(fixed, this.padTo);
}
}
};
var PolyDateFormatter = class {
constructor(dt, intl, opts) {
this.opts = opts;
this.originalZone = void 0;
let z = void 0;
if (this.opts.timeZone) {
this.dt = dt;
} else if (dt.zone.type === "fixed") {
const gmtOffset = -1 * (dt.offset / 60);
const offsetZ = gmtOffset >= 0 ? `Etc/GMT+${gmtOffset}` : `Etc/GMT${gmtOffset}`;
if (dt.offset !== 0 && IANAZone.create(offsetZ).valid) {
z = offsetZ;
this.dt = dt;
} else {
z = "UTC";
this.dt = dt.offset === 0 ? dt : dt.setZone("UTC").plus({
minutes: dt.offset
});
this.originalZone = dt.zone;
}
} else if (dt.zone.type === "system") {
this.dt = dt;
} else if (dt.zone.type === "iana") {
this.dt = dt;
z = dt.zone.name;
} else {
z = "UTC";
this.dt = dt.setZone("UTC").plus({
minutes: dt.offset
});
this.originalZone = dt.zone;
}
const intlOpts = {
...this.opts
};
intlOpts.timeZone = intlOpts.timeZone || z;
this.dtf = getCachedDTF(intl, intlOpts);
}
format() {
if (this.originalZone) {
return this.formatToParts().map(({
value
}) => value).join("");
}
return this.dtf.format(this.dt.toJSDate());
}
formatToParts() {
const parts = this.dtf.formatToParts(this.dt.toJSDate());
if (this.originalZone) {
return parts.map((part) => {
if (part.type === "timeZoneName") {
const offsetName = this.originalZone.offsetName(this.dt.ts, {
locale: this.dt.locale,
format: this.opts.timeZoneName
});
return {
...part,
value: offsetName
};
} else {
return part;
}
});
}
return parts;
}
resolvedOptions() {
return this.dtf.resolvedOptions();
}
};
var PolyRelFormatter = class {
constructor(intl, isEnglish, opts) {
this.opts = {
style: "long",
...opts
};
if (!isEnglish && hasRelative()) {
this.rtf = getCachedRTF(intl, opts);
}
}
format(count, unit) {
if (this.rtf) {
return this.rtf.format(count, unit);
} else {
return formatRelativeTime(unit, count, this.opts.numeric, this.opts.style !== "long");
}
}
formatToParts(count, unit) {
if (this.rtf) {
return this.rtf.formatToParts(count, unit);
} else {
return [];
}
}
};
var Locale = class {
static fromOpts(opts) {
return Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.defaultToEN);
}
static create(locale, numberingSystem, outputCalendar, defaultToEN = false) {
const specifiedLocale = locale || Settings.defaultLocale;
const localeR = specifiedLocale || (defaultToEN ? "en-US" : systemLocale());
const numberingSystemR = numberingSystem || Settings.defaultNumberingSystem;
const outputCalendarR = outputCalendar || Settings.defaultOutputCalendar;
return new Locale(localeR, numberingSystemR, outputCalendarR, specifiedLocale);
}
static resetCache() {
sysLocaleCache = null;
intlDTCache = {};
intlNumCache = {};
intlRelCache = {};
}
static fromObject({
locale,
numberingSystem,
outputCalendar
} = {}) {
return Locale.create(locale, numberingSystem, outputCalendar);
}
constructor(locale, numbering, outputCalendar, specifiedLocale) {
const [parsedLocale, parsedNumberingSystem, parsedOutputCalendar] = parseLocaleString(locale);
this.locale = parsedLocale;
this.numberingSystem = numbering || parsedNumberingSystem || null;
this.outputCalendar = outputCalendar || parsedOutputCalendar || null;
this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar);
this.weekdaysCache = {
format: {},
standalone: {}
};
this.monthsCache = {
format: {},
standalone: {}
};
this.meridiemCache = null;
this.eraCache = {};
this.specifiedLocale = specifiedLocale;
this.fastNumbersCached = null;
}
get fastNumbers() {
if (this.fastNumbersCached == null) {
this.fastNumbersCached = supportsFastNumbers(this);
}
return this.fastNumbersCached;
}
listingMode() {
const isActuallyEn = this.isEnglish();
const hasNoWeirdness = (this.numberingSystem === null || this.numberingSystem === "latn") && (this.outputCalendar === null || this.outputCalendar === "gregory");
return isActuallyEn && hasNoWeirdness ? "en" : "intl";
}
clone(alts) {
if (!alts || Object.getOwnPropertyNames(alts).length === 0) {
return this;
} else {
return Locale.create(alts.locale || this.specifiedLocale, alts.numberingSystem || this.numberingSystem, alts.outputCalendar || this.outputCalendar, alts.defaultToEN || false);
}
}
redefaultToEN(alts = {}) {
return this.clone({
...alts,
defaultToEN: true
});
}
redefaultToSystem(alts = {}) {
return this.clone({
...alts,
defaultToEN: false
});
}
months(length, format2 = false, defaultOK = true) {
return listStuff(this, length, defaultOK, months, () => {
const intl = format2 ? {
month: length,
day: "numeric"
} : {
month: length
}, formatStr = format2 ? "format" : "standalone";
if (!this.monthsCache[formatStr][length]) {
this.monthsCache[formatStr][length] = mapMonths((dt) => this.extract(dt, intl, "month"));
}
return this.monthsCache[formatStr][length];
});
}
weekdays(length, format2 = false, defaultOK = true) {
return listStuff(this, length, defaultOK, weekdays, () => {
const intl = format2 ? {
weekday: length,
year: "numeric",
month: "long",
day: "numeric"
} : {
weekday: length
}, formatStr = format2 ? "format" : "standalone";
if (!this.weekdaysCache[formatStr][length]) {
this.weekdaysCache[formatStr][length] = mapWeekdays((dt) => this.extract(dt, intl, "weekday"));
}
return this.weekdaysCache[formatStr][length];
});
}
meridiems(defaultOK = true) {
return listStuff(this, void 0, defaultOK, () => meridiems, () => {
if (!this.meridiemCache) {
const intl = {
hour: "numeric",
hourCycle: "h12"
};
this.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map((dt) => this.extract(dt, intl, "dayperiod"));
}
return this.meridiemCache;
});
}
eras(length, defaultOK = true) {
return listStuff(this, length, defaultOK, eras, () => {
const intl = {
era: length
};
if (!this.eraCache[length]) {
this.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map((dt) => this.extract(dt, intl, "era"));
}
return this.eraCache[length];
});
}
extract(dt, intlOpts, field) {
const df = this.dtFormatter(dt, intlOpts), results = df.formatToParts(), matching = results.find((m) => m.type.toLowerCase() === field);
return matching ? matching.value : null;
}
numberFormatter(opts = {}) {
return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts);
}
dtFormatter(dt, intlOpts = {}) {
return new PolyDateFormatter(dt, this.intl, intlOpts);
}
relFormatter(opts = {}) {
return new PolyRelFormatter(this.intl, this.isEnglish(), opts);
}
listFormatter(opts = {}) {
return getCachedLF(this.intl, opts);
}
isEnglish() {
return this.locale === "en" || this.locale.toLowerCase() === "en-us" || new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us");
}
equals(other) {
return this.locale === other.locale && this.numberingSystem === other.numberingSystem && this.outputCalendar === other.outputCalendar;
}
};
var singleton = null;
var FixedOffsetZone = class extends Zone {
/**
* Get a singleton instance of UTC
* @return {FixedOffsetZone}
*/
static get utcInstance() {
if (singleton === null) {
singleton = new FixedOffsetZone(0);
}
return singleton;
}
/**
* Get an instance with a specified offset
* @param {number} offset - The offset in minutes
* @return {FixedOffsetZone}
*/
static instance(offset3) {
return offset3 === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset3);
}
/**
* Get an instance of FixedOffsetZone from a UTC offset string, like "UTC+6"
* @param {string} s - The offset string to parse
* @example FixedOffsetZone.parseSpecifier("UTC+6")
* @example FixedOffsetZone.parseSpecifier("UTC+06")
* @example FixedOffsetZone.parseSpecifier("UTC-6:00")
* @return {FixedOffsetZone}
*/
static parseSpecifier(s2) {
if (s2) {
const r = s2.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);
if (r) {
return new FixedOffsetZone(signedOffset(r[1], r[2]));
}
}
return null;
}
constructor(offset3) {
super();
this.fixed = offset3;
}
/** @override **/
get type() {
return "fixed";
}
/** @override **/
get name() {
return this.fixed === 0 ? "UTC" : `UTC${formatOffset(this.fixed, "narrow")}`;
}
get ianaName() {
if (this.fixed === 0) {
return "Etc/UTC";
} else {
return `Etc/GMT${formatOffset(-this.fixed, "narrow")}`;
}
}
/** @override **/
offsetName() {
return this.name;
}
/** @override **/
formatOffset(ts, format2) {
return formatOffset(this.fixed, format2);
}
/** @override **/
get isUniversal() {
return true;
}
/** @override **/
offset() {
return this.fixed;
}
/** @override **/
equals(otherZone) {
return otherZone.type === "fixed" && otherZone.fixed === this.fixed;
}
/** @override **/
get isValid() {
return true;
}
};
var InvalidZone = class extends Zone {
constructor(zoneName) {
super();
this.zoneName = zoneName;
}
/** @override **/
get type() {
return "invalid";
}
/** @override **/
get name() {
return this.zoneName;
}
/** @override **/
get isUniversal() {
return false;
}
/** @override **/
offsetName() {
return null;
}
/** @override **/
formatOffset() {
return "";
}
/** @override **/
offset() {
return NaN;
}
/** @override **/
equals() {
return false;
}
/** @override **/
get isValid() {
return false;
}
};
function normalizeZone(input, defaultZone2) {
if (isUndefined(input) || input === null) {
return defaultZone2;
} else if (input instanceof Zone) {
return input;
} else if (isString(input)) {
const lowered = input.toLowerCase();
if (lowered === "default")
return defaultZone2;
else if (lowered === "local" || lowered === "system")
return SystemZone.instance;
else if (lowered === "utc" || lowered === "gmt")
return FixedOffsetZone.utcInstance;
else
return FixedOffsetZone.parseSpecifier(lowered) || IANAZone.create(input);
} else if (isNumber(input)) {
return FixedOffsetZone.instance(input);
} else if (typeof input === "object" && input.offset && typeof input.offset === "number") {
return input;
} else {
return new InvalidZone(input);
}
}
var now = () => Date.now();
var defaultZone = "system";
var defaultLocale = null;
var defaultNumberingSystem = null;
var defaultOutputCalendar = null;
var twoDigitCutoffYear = 60;
var throwOnInvalid;
var Settings = class {
/**
* Get the callback for returning the current timestamp.
* @type {function}
*/
static get now() {
return now;
}
/**
* Set the callback for returning the current timestamp.
* The function should return a number, which will be interpreted as an Epoch millisecond count
* @type {function}
* @example Settings.now = () => Date.now() + 3000 // pretend it is 3 seconds in the future
* @example Settings.now = () => 0 // always pretend it's Jan 1, 1970 at midnight in UTC time
*/
static set now(n2) {
now = n2;
}
/**
* Set the default time zone to create DateTimes in. Does not affect existing instances.
* Use the value "system" to reset this value to the system's time zone.
* @type {string}
*/
static set defaultZone(zone) {
defaultZone = zone;
}
/**
* Get the default time zone object currently used to create DateTimes. Does not affect existing instances.
* The default value is the system's time zone (the one set on the machine that runs this code).
* @type {Zone}
*/
static get defaultZone() {
return normalizeZone(defaultZone, SystemZone.instance);
}
/**
* Get the default locale to create DateTimes with. Does not affect existing instances.
* @type {string}
*/
static get defaultLocale() {
return defaultLocale;
}
/**
* Set the default locale to create DateTimes with. Does not affect existing instances.
* @type {string}
*/
static set defaultLocale(locale) {
defaultLocale = locale;
}
/**
* Get the default numbering system to create DateTimes with. Does not affect existing instances.
* @type {string}
*/
static get defaultNumberingSystem() {
return defaultNumberingSystem;
}
/**
* Set the default numbering system to create DateTimes with. Does not affect existing instances.
* @type {string}
*/
static set defaultNumberingSystem(numberingSystem) {
defaultNumberingSystem = numberingSystem;
}
/**
* Get the default output calendar to create DateTimes with. Does not affect existing instances.
* @type {string}
*/
static get defaultOutputCalendar() {
return defaultOutputCalendar;
}
/**
* Set the default output calendar to create DateTimes with. Does not affect existing instances.
* @type {string}
*/
static set defaultOutputCalendar(outputCalendar) {
defaultOutputCalendar = outputCalendar;
}
/**
* Get the cutoff year after which a string encoding a year as two digits is interpreted to occur in the current century.
* @type {number}
*/
static get twoDigitCutoffYear() {
return twoDigitCutoffYear;
}
/**
* Set the cutoff year after which a string encoding a year as two digits is interpreted to occur in the current century.
* @type {number}
* @example Settings.twoDigitCutoffYear = 0 // cut-off year is 0, so all 'yy' are interpretted as current century
* @example Settings.twoDigitCutoffYear = 50 // '49' -> 1949; '50' -> 2050
* @example Settings.twoDigitCutoffYear = 1950 // interpretted as 50
* @example Settings.twoDigitCutoffYear = 2050 // ALSO interpretted as 50
*/
static set twoDigitCutoffYear(cutoffYear) {
twoDigitCutoffYear = cutoffYear % 100;
}
/**
* Get whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals
* @type {boolean}
*/
static get throwOnInvalid() {
return throwOnInvalid;
}
/**
* Set whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals
* @type {boolean}
*/
static set throwOnInvalid(t) {
throwOnInvalid = t;
}
/**
* Reset Luxon's global caches. Should only be necessary in testing scenarios.
* @return {void}
*/
static resetCaches() {
Locale.resetCache();
IANAZone.resetCache();
}
};
function isUndefined(o) {
return typeof o === "undefined";
}
function isNumber(o) {
return typeof o === "number";
}
function isInteger(o) {
return typeof o === "number" && o % 1 === 0;
}
function isString(o) {
return typeof o === "string";
}
function isDate(o) {
return Object.prototype.toString.call(o) === "[object Date]";
}
function hasRelative() {
try {
return typeof Intl !== "undefined" && !!Intl.RelativeTimeFormat;
} catch (e) {
return false;
}
}
function maybeArray(thing) {
return Array.isArray(thing) ? thing : [thing];
}
function bestBy(arr, by, compare) {
if (arr.length === 0) {
return void 0;
}
return arr.reduce((best, next) => {
const pair = [by(next), next];
if (!best) {
return pair;
} else if (compare(best[0], pair[0]) === best[0]) {
return best;
} else {
return pair;
}
}, null)[1];
}
function pick(obj, keys) {
return keys.reduce((a, k) => {
a[k] = obj[k];
return a;
}, {});
}
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
function integerBetween(thing, bottom2, top2) {
return isInteger(thing) && thing >= bottom2 && thing <= top2;
}
function floorMod(x, n2) {
return x - n2 * Math.floor(x / n2);
}
function padStart(input, n2 = 2) {
const isNeg = input < 0;
let padded;
if (isNeg) {
padded = "-" + ("" + -input).padStart(n2, "0");
} else {
padded = ("" + input).padStart(n2, "0");
}
return padded;
}
function parseInteger(string) {
if (isUndefined(string) || string === null || string === "") {
return void 0;
} else {
return parseInt(string, 10);
}
}
function parseFloating(string) {
if (isUndefined(string) || string === null || string === "") {
return void 0;
} else {
return parseFloat(string);
}
}
function parseMillis(fraction) {
if (isUndefined(fraction) || fraction === null || fraction === "") {
return void 0;
} else {
const f = parseFloat("0." + fraction) * 1e3;
return Math.floor(f);
}
}
function roundTo(number, digits, towardZero = false) {
const factor = 10 ** digits, rounder = towardZero ? Math.trunc : Math.round;
return rounder(number * factor) / factor;
}
function isLeapYear(year) {
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
function daysInYear(year) {
return isLeapYear(year) ? 366 : 365;
}
function daysInMonth(year, month) {
const modMonth = floorMod(month - 1, 12) + 1, modYear = year + (month - modMonth) / 12;
if (modMonth === 2) {
return isLeapYear(modYear) ? 29 : 28;
} else {
return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1];
}
}
function objToLocalTS(obj) {
let d = Date.UTC(obj.year, obj.month - 1, obj.day, obj.hour, obj.minute, obj.second, obj.millisecond);
if (obj.year < 100 && obj.year >= 0) {
d = new Date(d);
d.setUTCFullYear(obj.year, obj.month - 1, obj.day);
}
return +d;
}
function weeksInWeekYear(weekYear) {
const p1 = (weekYear + Math.floor(weekYear / 4) - Math.floor(weekYear / 100) + Math.floor(weekYear / 400)) % 7, last = weekYear - 1, p2 = (last + Math.floor(last / 4) - Math.floor(last / 100) + Math.floor(last / 400)) % 7;
return p1 === 4 || p2 === 3 ? 53 : 52;
}
function untruncateYear(year) {
if (year > 99) {
return year;
} else
return year > Settings.twoDigitCutoffYear ? 1900 + year : 2e3 + year;
}
function parseZoneInfo(ts, offsetFormat, locale, timeZone = null) {
const date = new Date(ts), intlOpts = {
hourCycle: "h23",
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit"
};
if (timeZone) {
intlOpts.timeZone = timeZone;
}
const modified = {
timeZoneName: offsetFormat,
...intlOpts
};
const parsed = new Intl.DateTimeFormat(locale, modified).formatToParts(date).find((m) => m.type.toLowerCase() === "timezonename");
return parsed ? parsed.value : null;
}
function signedOffset(offHourStr, offMinuteStr) {
let offHour = parseInt(offHourStr, 10);
if (Number.isNaN(offHour)) {
offHour = 0;
}
const offMin = parseInt(offMinuteStr, 10) || 0, offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin;
return offHour * 60 + offMinSigned;
}
function asNumber(value) {
const numericValue = Number(value);
if (typeof value === "boolean" || value === "" || Number.isNaN(numericValue))
throw new InvalidArgumentError(`Invalid unit value ${value}`);
return numericValue;
}
function normalizeObject(obj, normalizer) {
const normalized = {};
for (const u in obj) {
if (hasOwnProperty(obj, u)) {
const v = obj[u];
if (v === void 0 || v === null)
continue;
normalized[normalizer(u)] = asNumber(v);
}
}
return normalized;
}
function formatOffset(offset3, format2) {
const hours = Math.trunc(Math.abs(offset3 / 60)), minutes = Math.trunc(Math.abs(offset3 % 60)), sign = offset3 >= 0 ? "+" : "-";
switch (format2) {
case "short":
return `${sign}${padStart(hours, 2)}:${padStart(minutes, 2)}`;
case "narrow":
return `${sign}${hours}${minutes > 0 ? `:${minutes}` : ""}`;
case "techie":
return `${sign}${padStart(hours, 2)}${padStart(minutes, 2)}`;
default:
throw new RangeError(`Value format ${format2} is out of range for property format`);
}
}
function timeObject(obj) {
return pick(obj, ["hour", "minute", "second", "millisecond"]);
}
var monthsLong = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthsShort = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var monthsNarrow = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"];
function months(length) {
switch (length) {
case "narrow":
return [...monthsNarrow];
case "short":
return [...monthsShort];
case "long":
return [...monthsLong];
case "numeric":
return ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"];
case "2-digit":
return ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
default:
return null;
}
}
var weekdaysLong = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
var weekdaysShort = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
var weekdaysNarrow = ["M", "T", "W", "T", "F", "S", "S"];
function weekdays(length) {
switch (length) {
case "narrow":
return [...weekdaysNarrow];
case "short":
return [...weekdaysShort];
case "long":
return [...weekdaysLong];
case "numeric":
return ["1", "2", "3", "4", "5", "6", "7"];
default:
return null;
}
}
var meridiems = ["AM", "PM"];
var erasLong = ["Before Christ", "Anno Domini"];
var erasShort = ["BC", "AD"];
var erasNarrow = ["B", "A"];
function eras(length) {
switch (length) {
case "narrow":
return [...erasNarrow];
case "short":
return [...erasShort];
case "long":
return [...erasLong];
default:
return null;
}
}
function meridiemForDateTime(dt) {
return meridiems[dt.hour < 12 ? 0 : 1];
}
function weekdayForDateTime(dt, length) {
return weekdays(length)[dt.weekday - 1];
}
function monthForDateTime(dt, length) {
return months(length)[dt.month - 1];
}
function eraForDateTime(dt, length) {
return eras(length)[dt.year < 0 ? 0 : 1];
}
function formatRelativeTime(unit, count, numeric = "always", narrow = false) {
const units = {
years: ["year", "yr."],
quarters: ["quarter", "qtr."],
months: ["month", "mo."],
weeks: ["week", "wk."],
days: ["day", "day", "days"],
hours: ["hour", "hr."],
minutes: ["minute", "min."],
seconds: ["second", "sec."]
};
const lastable = ["hours", "minutes", "seconds"].indexOf(unit) === -1;
if (numeric === "auto" && lastable) {
const isDay = unit === "days";
switch (count) {
case 1:
return isDay ? "tomorrow" : `next ${units[unit][0]}`;
case -1:
return isDay ? "yesterday" : `last ${units[unit][0]}`;
case 0:
return isDay ? "today" : `this ${units[unit][0]}`;
}
}
const isInPast = Object.is(count, -0) || count < 0, fmtValue = Math.abs(count), singular = fmtValue === 1, lilUnits = units[unit], fmtUnit = narrow ? singular ? lilUnits[1] : lilUnits[2] || lilUnits[1] : singular ? units[unit][0] : unit;
return isInPast ? `${fmtValue} ${fmtUnit} ago` : `in ${fmtValue} ${fmtUnit}`;
}
function stringifyTokens(splits, tokenToString) {
let s2 = "";
for (const token of splits) {
if (token.literal) {
s2 += token.val;
} else {
s2 += tokenToString(token.val);
}
}
return s2;
}
var macroTokenToFormatOpts = {
D: DATE_SHORT,
DD: DATE_MED,
DDD: DATE_FULL,
DDDD: DATE_HUGE,
t: TIME_SIMPLE,
tt: TIME_WITH_SECONDS,
ttt: TIME_WITH_SHORT_OFFSET,
tttt: TIME_WITH_LONG_OFFSET,
T: TIME_24_SIMPLE,
TT: TIME_24_WITH_SECONDS,
TTT: TIME_24_WITH_SHORT_OFFSET,
TTTT: TIME_24_WITH_LONG_OFFSET,
f: DATETIME_SHORT,
ff: DATETIME_MED,
fff: DATETIME_FULL,
ffff: DATETIME_HUGE,
F: DATETIME_SHORT_WITH_SECONDS,
FF: DATETIME_MED_WITH_SECONDS,
FFF: DATETIME_FULL_WITH_SECONDS,
FFFF: DATETIME_HUGE_WITH_SECONDS
};
var Formatter = class {
static create(locale, opts = {}) {
return new Formatter(locale, opts);
}
static parseFormat(fmt) {
let current = null, currentFull = "", bracketed = false;
const splits = [];
for (let i = 0; i < fmt.length; i++) {
const c = fmt.charAt(i);
if (c === "'") {
if (currentFull.length > 0) {
splits.push({
literal: bracketed || /^\s+$/.test(currentFull),
val: currentFull
});
}
current = null;
currentFull = "";
bracketed = !bracketed;
} else if (bracketed) {
currentFull += c;
} else if (c === current) {
currentFull += c;
} else {
if (currentFull.length > 0) {
splits.push({
literal: /^\s+$/.test(currentFull),
val: currentFull
});
}
currentFull = c;
current = c;
}
}
if (currentFull.length > 0) {
splits.push({
literal: bracketed || /^\s+$/.test(currentFull),
val: currentFull
});
}
return splits;
}
static macroTokenToFormatOpts(token) {
return macroTokenToFormatOpts[token];
}
constructor(locale, formatOpts) {
this.opts = formatOpts;
this.loc = locale;
this.systemLoc = null;
}
formatWithSystemDefault(dt, opts) {
if (this.systemLoc === null) {
this.systemLoc = this.loc.redefaultToSystem();
}
const df = this.systemLoc.dtFormatter(dt, {
...this.opts,
...opts
});
return df.format();
}
formatDateTime(dt, opts = {}) {
const df = this.loc.dtFormatter(dt, {
...this.opts,
...opts
});
return df.format();
}
formatDateTimeParts(dt, opts = {}) {
const df = this.loc.dtFormatter(dt, {
...this.opts,
...opts
});
return df.formatToParts();
}
formatInterval(interval, opts = {}) {
const df = this.loc.dtFormatter(interval.start, {
...this.opts,
...opts
});
return df.dtf.formatRange(interval.start.toJSDate(), interval.end.toJSDate());
}
resolvedOptions(dt, opts = {}) {
const df = this.loc.dtFormatter(dt, {
...this.opts,
...opts
});
return df.resolvedOptions();
}
num(n2, p = 0) {
if (this.opts.forceSimple) {
return padStart(n2, p);
}
const opts = {
...this.opts
};
if (p > 0) {
opts.padTo = p;
}
return this.loc.numberFormatter(opts).format(n2);
}
formatDateTimeFromString(dt, fmt) {
const knownEnglish = this.loc.listingMode() === "en", useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== "gregory", string = (opts, extract) => this.loc.extract(dt, opts, extract), formatOffset2 = (opts) => {
if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) {
return "Z";
}
return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : "";
}, meridiem = () => knownEnglish ? meridiemForDateTime(dt) : string({
hour: "numeric",
hourCycle: "h12"
}, "dayperiod"), month = (length, standalone) => knownEnglish ? monthForDateTime(dt, length) : string(standalone ? {
month: length
} : {
month: length,
day: "numeric"
}, "month"), weekday = (length, standalone) => knownEnglish ? weekdayForDateTime(dt, length) : string(standalone ? {
weekday: length
} : {
weekday: length,
month: "long",
day: "numeric"
}, "weekday"), maybeMacro = (token) => {
const formatOpts = Formatter.macroTokenToFormatOpts(token);
if (formatOpts) {
return this.formatWithSystemDefault(dt, formatOpts);
} else {
return token;
}
}, era = (length) => knownEnglish ? eraForDateTime(dt, length) : string({
era: length
}, "era"), tokenToString = (token) => {
switch (token) {
case "S":
return this.num(dt.millisecond);
case "u":
case "SSS":
return this.num(dt.millisecond, 3);
case "s":
return this.num(dt.second);
case "ss":
return this.num(dt.second, 2);
case "uu":
return this.num(Math.floor(dt.millisecond / 10), 2);
case "uuu":
return this.num(Math.floor(dt.millisecond / 100));
case "m":
return this.num(dt.minute);
case "mm":
return this.num(dt.minute, 2);
case "h":
return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12);
case "hh":
return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2);
case "H":
return this.num(dt.hour);
case "HH":
return this.num(dt.hour, 2);
case "Z":
return formatOffset2({
format: "narrow",
allowZ: this.opts.allowZ
});
case "ZZ":
return formatOffset2({
format: "short",
allowZ: this.opts.allowZ
});
case "ZZZ":
return formatOffset2({
format: "techie",
allowZ: this.opts.allowZ
});
case "ZZZZ":
return dt.zone.offsetName(dt.ts, {
format: "short",
locale: this.loc.locale
});
case "ZZZZZ":
return dt.zone.offsetName(dt.ts, {
format: "long",
locale: this.loc.locale
});
case "z":
return dt.zoneName;
case "a":
return meridiem();
case "d":
return useDateTimeFormatter ? string({
day: "numeric"
}, "day") : this.num(dt.day);
case "dd":
return useDateTimeFormatter ? string({
day: "2-digit"
}, "day") : this.num(dt.day, 2);
case "c":
return this.num(dt.weekday);
case "ccc":
return weekday("short", true);
case "cccc":
return weekday("long", true);
case "ccccc":
return weekday("narrow", true);
case "E":
return this.num(dt.weekday);
case "EEE":
return weekday("short", false);
case "EEEE":
return weekday("long", false);
case "EEEEE":
return weekday("narrow", false);
case "L":
return useDateTimeFormatter ? string({
month: "numeric",
day: "numeric"
}, "month") : this.num(dt.month);
case "LL":
return useDateTimeFormatter ? string({
month: "2-digit",
day: "numeric"
}, "month") : this.num(dt.month, 2);
case "LLL":
return month("short", true);
case "LLLL":
return month("long", true);
case "LLLLL":
return month("narrow", true);
case "M":
return useDateTimeFormatter ? string({
month: "numeric"
}, "month") : this.num(dt.month);
case "MM":
return useDateTimeFormatter ? string({
month: "2-digit"
}, "month") : this.num(dt.month, 2);
case "MMM":
return month("short", false);
case "MMMM":
return month("long", false);
case "MMMMM":
return month("narrow", false);
case "y":
return useDateTimeFormatter ? string({
year: "numeric"
}, "year") : this.num(dt.year);
case "yy":
return useDateTimeFormatter ? string({
year: "2-digit"
}, "year") : this.num(dt.year.toString().slice(-2), 2);
case "yyyy":
return useDateTimeFormatter ? string({
year: "numeric"
}, "year") : this.num(dt.year, 4);
case "yyyyyy":
return useDateTimeFormatter ? string({
year: "numeric"
}, "year") : this.num(dt.year, 6);
case "G":
return era("short");
case "GG":
return era("long");
case "GGGGG":
return era("narrow");
case "kk":
return this.num(dt.weekYear.toString().slice(-2), 2);
case "kkkk":
return this.num(dt.weekYear, 4);
case "W":
return this.num(dt.weekNumber);
case "WW":
return this.num(dt.weekNumber, 2);
case "o":
return this.num(dt.ordinal);
case "ooo":
return this.num(dt.ordinal, 3);
case "q":
return this.num(dt.quarter);
case "qq":
return this.num(dt.quarter, 2);
case "X":
return this.num(Math.floor(dt.ts / 1e3));
case "x":
return this.num(dt.ts);
default:
return maybeMacro(token);
}
};
return stringifyTokens(Formatter.parseFormat(fmt), tokenToString);
}
formatDurationFromString(dur, fmt) {
const tokenToField = (token) => {
switch (token[0]) {
case "S":
return "millisecond";
case "s":
return "second";
case "m":
return "minute";
case "h":
return "hour";
case "d":
return "day";
case "w":
return "week";
case "M":
return "month";
case "y":
return "year";
default:
return null;
}
}, tokenToString = (lildur) => (token) => {
const mapped = tokenToField(token);
if (mapped) {
return this.num(lildur.get(mapped), token.length);
} else {
return token;
}
}, tokens = Formatter.parseFormat(fmt), realTokens = tokens.reduce((found, {
literal,
val
}) => literal ? found : found.concat(val), []), collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter((t) => t));
return stringifyTokens(tokens, tokenToString(collapsed));
}
};
var Invalid = class {
constructor(reason, explanation) {
this.reason = reason;
this.explanation = explanation;
}
toMessage() {
if (this.explanation) {
return `${this.reason}: ${this.explanation}`;
} else {
return this.reason;
}
}
};
var ianaRegex = /[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;
function combineRegexes(...regexes) {
const full = regexes.reduce((f, r) => f + r.source, "");
return RegExp(`^${full}$`);
}
function combineExtractors(...extractors) {
return (m) => extractors.reduce(([mergedVals, mergedZone, cursor], ex) => {
const [val, zone, next] = ex(m, cursor);
return [{
...mergedVals,
...val
}, zone || mergedZone, next];
}, [{}, null, 1]).slice(0, 2);
}
function parse(s2, ...patterns) {
if (s2 == null) {
return [null, null];
}
for (const [regex, extractor] of patterns) {
const m = regex.exec(s2);
if (m) {
return extractor(m);
}
}
return [null, null];
}
function simpleParse(...keys) {
return (match2, cursor) => {
const ret = {};
let i;
for (i = 0; i < keys.length; i++) {
ret[keys[i]] = parseInteger(match2[cursor + i]);
}
return [ret, null, cursor + i];
};
}
var offsetRegex = /(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/;
var isoExtendedZone = `(?:${offsetRegex.source}?(?:\\[(${ianaRegex.source})\\])?)?`;
var isoTimeBaseRegex = /(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/;
var isoTimeRegex = RegExp(`${isoTimeBaseRegex.source}${isoExtendedZone}`);
var isoTimeExtensionRegex = RegExp(`(?:T${isoTimeRegex.source})?`);
var isoYmdRegex = /([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/;
var isoWeekRegex = /(\d{4})-?W(\d\d)(?:-?(\d))?/;
var isoOrdinalRegex = /(\d{4})-?(\d{3})/;
var extractISOWeekData = simpleParse("weekYear", "weekNumber", "weekDay");
var extractISOOrdinalData = simpleParse("year", "ordinal");
var sqlYmdRegex = /(\d{4})-(\d\d)-(\d\d)/;
var sqlTimeRegex = RegExp(`${isoTimeBaseRegex.source} ?(?:${offsetRegex.source}|(${ianaRegex.source}))?`);
var sqlTimeExtensionRegex = RegExp(`(?: ${sqlTimeRegex.source})?`);
function int(match2, pos, fallback) {
const m = match2[pos];
return isUndefined(m) ? fallback : parseInteger(m);
}
function extractISOYmd(match2, cursor) {
const item = {
year: int(match2, cursor),
month: int(match2, cursor + 1, 1),
day: int(match2, cursor + 2, 1)
};
return [item, null, cursor + 3];
}
function extractISOTime(match2, cursor) {
const item = {
hours: int(match2, cursor, 0),
minutes: int(match2, cursor + 1, 0),
seconds: int(match2, cursor + 2, 0),
milliseconds: parseMillis(match2[cursor + 3])
};
return [item, null, cursor + 4];
}
function extractISOOffset(match2, cursor) {
const local = !match2[cursor] && !match2[cursor + 1], fullOffset = signedOffset(match2[cursor + 1], match2[cursor + 2]), zone = local ? null : FixedOffsetZone.instance(fullOffset);
return [{}, zone, cursor + 3];
}
function extractIANAZone(match2, cursor) {
const zone = match2[cursor] ? IANAZone.create(match2[cursor]) : null;
return [{}, zone, cursor + 1];
}
var isoTimeOnly = RegExp(`^T?${isoTimeBaseRegex.source}$`);
var isoDuration = /^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;
function extractISODuration(match2) {
const [s2, yearStr, monthStr, weekStr, dayStr, hourStr, minuteStr, secondStr, millisecondsStr] = match2;
const hasNegativePrefix = s2[0] === "-";
const negativeSeconds = secondStr && secondStr[0] === "-";
const maybeNegate = (num, force = false) => num !== void 0 && (force || num && hasNegativePrefix) ? -num : num;
return [{
years: maybeNegate(parseFloating(yearStr)),
months: maybeNegate(parseFloating(monthStr)),
weeks: maybeNegate(parseFloating(weekStr)),
days: maybeNegate(parseFloating(dayStr)),
hours: maybeNegate(parseFloating(hourStr)),
minutes: maybeNegate(parseFloating(minuteStr)),
seconds: maybeNegate(parseFloating(secondStr), secondStr === "-0"),
milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds)
}];
}
var obsOffsets = {
GMT: 0,
EDT: -4 * 60,
EST: -5 * 60,
CDT: -5 * 60,
CST: -6 * 60,
MDT: -6 * 60,
MST: -7 * 60,
PDT: -7 * 60,
PST: -8 * 60
};
function fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
const result = {
year: yearStr.length === 2 ? untruncateYear(parseInteger(yearStr)) : parseInteger(yearStr),
month: monthsShort.indexOf(monthStr) + 1,
day: parseInteger(dayStr),
hour: parseInteger(hourStr),
minute: parseInteger(minuteStr)
};
if (secondStr)
result.second = parseInteger(secondStr);
if (weekdayStr) {
result.weekday = weekdayStr.length > 3 ? weekdaysLong.indexOf(weekdayStr) + 1 : weekdaysShort.indexOf(weekdayStr) + 1;
}
return result;
}
var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;
function extractRFC2822(match2) {
const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr, obsOffset, milOffset, offHourStr, offMinuteStr] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
let offset3;
if (obsOffset) {
offset3 = obsOffsets[obsOffset];
} else if (milOffset) {
offset3 = 0;
} else {
offset3 = signedOffset(offHourStr, offMinuteStr);
}
return [result, new FixedOffsetZone(offset3)];
}
function preprocessRFC2822(s2) {
return s2.replace(/\([^()]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").trim();
}
var rfc1123 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/;
var rfc850 = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/;
var ascii = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;
function extractRFC1123Or850(match2) {
const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
return [result, FixedOffsetZone.utcInstance];
}
function extractASCII(match2) {
const [, weekdayStr, monthStr, dayStr, hourStr, minuteStr, secondStr, yearStr] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);
return [result, FixedOffsetZone.utcInstance];
}
var isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex);
var isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex);
var isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex);
var isoTimeCombinedRegex = combineRegexes(isoTimeRegex);
var extractISOYmdTimeAndOffset = combineExtractors(extractISOYmd, extractISOTime, extractISOOffset, extractIANAZone);
var extractISOWeekTimeAndOffset = combineExtractors(extractISOWeekData, extractISOTime, extractISOOffset, extractIANAZone);
var extractISOOrdinalDateAndTime = combineExtractors(extractISOOrdinalData, extractISOTime, extractISOOffset, extractIANAZone);
var extractISOTimeAndOffset = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone);
function parseISODate(s2) {
return parse(s2, [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset], [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime], [isoTimeCombinedRegex, extractISOTimeAndOffset]);
}
function parseRFC2822Date(s2) {
return parse(preprocessRFC2822(s2), [rfc2822, extractRFC2822]);
}
function parseHTTPDate(s2) {
return parse(s2, [rfc1123, extractRFC1123Or850], [rfc850, extractRFC1123Or850], [ascii, extractASCII]);
}
function parseISODuration(s2) {
return parse(s2, [isoDuration, extractISODuration]);
}
var extractISOTimeOnly = combineExtractors(extractISOTime);
function parseISOTimeOnly(s2) {
return parse(s2, [isoTimeOnly, extractISOTimeOnly]);
}
var sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex);
var sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex);
var extractISOTimeOffsetAndIANAZone = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone);
function parseSQL(s2) {
return parse(s2, [sqlYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone]);
}
var INVALID$2 = "Invalid Duration";
var lowOrderMatrix = {
weeks: {
days: 7,
hours: 7 * 24,
minutes: 7 * 24 * 60,
seconds: 7 * 24 * 60 * 60,
milliseconds: 7 * 24 * 60 * 60 * 1e3
},
days: {
hours: 24,
minutes: 24 * 60,
seconds: 24 * 60 * 60,
milliseconds: 24 * 60 * 60 * 1e3
},
hours: {
minutes: 60,
seconds: 60 * 60,
milliseconds: 60 * 60 * 1e3
},
minutes: {
seconds: 60,
milliseconds: 60 * 1e3
},
seconds: {
milliseconds: 1e3
}
};
var casualMatrix = {
years: {
quarters: 4,
months: 12,
weeks: 52,
days: 365,
hours: 365 * 24,
minutes: 365 * 24 * 60,
seconds: 365 * 24 * 60 * 60,
milliseconds: 365 * 24 * 60 * 60 * 1e3
},
quarters: {
months: 3,
weeks: 13,
days: 91,
hours: 91 * 24,
minutes: 91 * 24 * 60,
seconds: 91 * 24 * 60 * 60,
milliseconds: 91 * 24 * 60 * 60 * 1e3
},
months: {
weeks: 4,
days: 30,
hours: 30 * 24,
minutes: 30 * 24 * 60,
seconds: 30 * 24 * 60 * 60,
milliseconds: 30 * 24 * 60 * 60 * 1e3
},
...lowOrderMatrix
};
var daysInYearAccurate = 146097 / 400;
var daysInMonthAccurate = 146097 / 4800;
var accurateMatrix = {
years: {
quarters: 4,
months: 12,
weeks: daysInYearAccurate / 7,
days: daysInYearAccurate,
hours: daysInYearAccurate * 24,
minutes: daysInYearAccurate * 24 * 60,
seconds: daysInYearAccurate * 24 * 60 * 60,
milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1e3
},
quarters: {
months: 3,
weeks: daysInYearAccurate / 28,
days: daysInYearAccurate / 4,
hours: daysInYearAccurate * 24 / 4,
minutes: daysInYearAccurate * 24 * 60 / 4,
seconds: daysInYearAccurate * 24 * 60 * 60 / 4,
milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1e3 / 4
},
months: {
weeks: daysInMonthAccurate / 7,
days: daysInMonthAccurate,
hours: daysInMonthAccurate * 24,
minutes: daysInMonthAccurate * 24 * 60,
seconds: daysInMonthAccurate * 24 * 60 * 60,
milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1e3
},
...lowOrderMatrix
};
var orderedUnits$1 = ["years", "quarters", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds"];
var reverseUnits = orderedUnits$1.slice(0).reverse();
function clone$1(dur, alts, clear = false) {
const conf = {
values: clear ? alts.values : {
...dur.values,
...alts.values || {}
},
loc: dur.loc.clone(alts.loc),
conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy,
matrix: alts.matrix || dur.matrix
};
return new Duration(conf);
}
function antiTrunc(n2) {
return n2 < 0 ? Math.floor(n2) : Math.ceil(n2);
}
function convert(matrix, fromMap, fromUnit, toMap, toUnit) {
const conv = matrix[toUnit][fromUnit], raw = fromMap[fromUnit] / conv, sameSign = Math.sign(raw) === Math.sign(toMap[toUnit]), added = !sameSign && toMap[toUnit] !== 0 && Math.abs(raw) <= 1 ? antiTrunc(raw) : Math.trunc(raw);
toMap[toUnit] += added;
fromMap[fromUnit] -= added * conv;
}
function normalizeValues(matrix, vals) {
reverseUnits.reduce((previous, current) => {
if (!isUndefined(vals[current])) {
if (previous) {
convert(matrix, vals, previous, vals, current);
}
return current;
} else {
return previous;
}
}, null);
}
function removeZeroes(vals) {
const newVals = {};
for (const [key, value] of Object.entries(vals)) {
if (value !== 0) {
newVals[key] = value;
}
}
return newVals;
}
var Duration = class {
/**
* @private
*/
constructor(config) {
const accurate = config.conversionAccuracy === "longterm" || false;
let matrix = accurate ? accurateMatrix : casualMatrix;
if (config.matrix) {
matrix = config.matrix;
}
this.values = config.values;
this.loc = config.loc || Locale.create();
this.conversionAccuracy = accurate ? "longterm" : "casual";
this.invalid = config.invalid || null;
this.matrix = matrix;
this.isLuxonDuration = true;
}
/**
* Create Duration from a number of milliseconds.
* @param {number} count of milliseconds
* @param {Object} opts - options for parsing
* @param {string} [opts.locale='en-US'] - the locale to use
* @param {string} opts.numberingSystem - the numbering system to use
* @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
* @return {Duration}
*/
static fromMillis(count, opts) {
return Duration.fromObject({
milliseconds: count
}, opts);
}
/**
* Create a Duration from a JavaScript object with keys like 'years' and 'hours'.
* If this object is empty then a zero milliseconds duration is returned.
* @param {Object} obj - the object to create the DateTime from
* @param {number} obj.years
* @param {number} obj.quarters
* @param {number} obj.months
* @param {number} obj.weeks
* @param {number} obj.days
* @param {number} obj.hours
* @param {number} obj.minutes
* @param {number} obj.seconds
* @param {number} obj.milliseconds
* @param {Object} [opts=[]] - options for creating this Duration
* @param {string} [opts.locale='en-US'] - the locale to use
* @param {string} opts.numberingSystem - the numbering system to use
* @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use
* @param {string} [opts.matrix=Object] - the custom conversion system to use
* @return {Duration}
*/
static fromObject(obj, opts = {}) {
if (obj == null || typeof obj !== "object") {
throw new InvalidArgumentError(`Duration.fromObject: argument expected to be an object, got ${obj === null ? "null" : typeof obj}`);
}
return new Duration({
values: normalizeObject(obj, Duration.normalizeUnit),
loc: Locale.fromObject(opts),
conversionAccuracy: opts.conversionAccuracy,
matrix: opts.matrix
});
}
/**
* Create a Duration from DurationLike.
*
* @param {Object | number | Duration} durationLike
* One of:
* - object with keys like 'years' and 'hours'.
* - number representing milliseconds
* - Duration instance
* @return {Duration}
*/
static fromDurationLike(durationLike) {
if (isNumber(durationLike)) {
return Duration.fromMillis(durationLike);
} else if (Duration.isDuration(durationLike)) {
return durationLike;
} else if (typeof durationLike === "object") {
return Duration.fromObject(durationLike);
} else {
throw new InvalidArgumentError(`Unknown duration argument ${durationLike} of type ${typeof durationLike}`);
}
}
/**
* Create a Duration from an ISO 8601 duration string.
* @param {string} text - text to parse
* @param {Object} opts - options for parsing
* @param {string} [opts.locale='en-US'] - the locale to use
* @param {string} opts.numberingSystem - the numbering system to use
* @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use
* @param {string} [opts.matrix=Object] - the preset conversion system to use
* @see https://en.wikipedia.org/wiki/ISO_8601#Durations
* @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 }
* @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 }
* @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 }
* @return {Duration}
*/
static fromISO(text, opts) {
const [parsed] = parseISODuration(text);
if (parsed) {
return Duration.fromObject(parsed, opts);
} else {
return Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`);
}
}
/**
* Create a Duration from an ISO 8601 time string.
* @param {string} text - text to parse
* @param {Object} opts - options for parsing
* @param {string} [opts.locale='en-US'] - the locale to use
* @param {string} opts.numberingSystem - the numbering system to use
* @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use
* @param {string} [opts.matrix=Object] - the conversion system to use
* @see https://en.wikipedia.org/wiki/ISO_8601#Times
* @example Duration.fromISOTime('11:22:33.444').toObject() //=> { hours: 11, minutes: 22, seconds: 33, milliseconds: 444 }
* @example Duration.fromISOTime('11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
* @example Duration.fromISOTime('T11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
* @example Duration.fromISOTime('1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
* @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
* @return {Duration}
*/
static fromISOTime(text, opts) {
const [parsed] = parseISOTimeOnly(text);
if (parsed) {
return Duration.fromObject(parsed, opts);
} else {
return Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`);
}
}
/**
* Create an invalid Duration.
* @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent
* @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
* @return {Duration}
*/
static invalid(reason, explanation = null) {
if (!reason) {
throw new InvalidArgumentError("need to specify a reason the Duration is invalid");
}
const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
if (Settings.throwOnInvalid) {
throw new InvalidDurationError(invalid);
} else {
return new Duration({
invalid
});
}
}
/**
* @private
*/
static normalizeUnit(unit) {
const normalized = {
year: "years",
years: "years",
quarter: "quarters",
quarters: "quarters",
month: "months",
months: "months",
week: "weeks",
weeks: "weeks",
day: "days",
days: "days",
hour: "hours",
hours: "hours",
minute: "minutes",
minutes: "minutes",
second: "seconds",
seconds: "seconds",
millisecond: "milliseconds",
milliseconds: "milliseconds"
}[unit ? unit.toLowerCase() : unit];
if (!normalized)
throw new InvalidUnitError(unit);
return normalized;
}
/**
* Check if an object is a Duration. Works across context boundaries
* @param {object} o
* @return {boolean}
*/
static isDuration(o) {
return o && o.isLuxonDuration || false;
}
/**
* Get the locale of a Duration, such 'en-GB'
* @type {string}
*/
get locale() {
return this.isValid ? this.loc.locale : null;
}
/**
* Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration
*
* @type {string}
*/
get numberingSystem() {
return this.isValid ? this.loc.numberingSystem : null;
}
/**
* Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens:
* * `S` for milliseconds
* * `s` for seconds
* * `m` for minutes
* * `h` for hours
* * `d` for days
* * `w` for weeks
* * `M` for months
* * `y` for years
* Notes:
* * Add padding by repeating the token, e.g. "yy" pads the years to two digits, "hhhh" pads the hours out to four digits
* * Tokens can be escaped by wrapping with single quotes.
* * The duration will be converted to the set of units in the format string using {@link Duration#shiftTo} and the Durations's conversion accuracy setting.
* @param {string} fmt - the format string
* @param {Object} opts - options
* @param {boolean} [opts.floor=true] - floor numerical values
* @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("y d s") //=> "1 6 2"
* @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("yy dd sss") //=> "01 06 002"
* @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("M S") //=> "12 518402000"
* @return {string}
*/
toFormat(fmt, opts = {}) {
const fmtOpts = {
...opts,
floor: opts.round !== false && opts.floor !== false
};
return this.isValid ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt) : INVALID$2;
}
/**
* Returns a string representation of a Duration with all units included.
* To modify its behavior use the `listStyle` and any Intl.NumberFormat option, though `unitDisplay` is especially relevant.
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat
* @param opts - On option object to override the formatting. Accepts the same keys as the options parameter of the native `Int.NumberFormat` constructor, as well as `listStyle`.
* @example
* ```js
* var dur = Duration.fromObject({ days: 1, hours: 5, minutes: 6 })
* dur.toHuman() //=> '1 day, 5 hours, 6 minutes'
* dur.toHuman({ listStyle: "long" }) //=> '1 day, 5 hours, and 6 minutes'
* dur.toHuman({ unitDisplay: "short" }) //=> '1 day, 5 hr, 6 min'
* ```
*/
toHuman(opts = {}) {
const l2 = orderedUnits$1.map((unit) => {
const val = this.values[unit];
if (isUndefined(val)) {
return null;
}
return this.loc.numberFormatter({
style: "unit",
unitDisplay: "long",
...opts,
unit: unit.slice(0, -1)
}).format(val);
}).filter((n2) => n2);
return this.loc.listFormatter({
type: "conjunction",
style: opts.listStyle || "narrow",
...opts
}).format(l2);
}
/**
* Returns a JavaScript object with this Duration's values.
* @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 }
* @return {Object}
*/
toObject() {
if (!this.isValid)
return {};
return {
...this.values
};
}
/**
* Returns an ISO 8601-compliant string representation of this Duration.
* @see https://en.wikipedia.org/wiki/ISO_8601#Durations
* @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S'
* @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S'
* @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M'
* @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M'
* @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S'
* @return {string}
*/
toISO() {
if (!this.isValid)
return null;
let s2 = "P";
if (this.years !== 0)
s2 += this.years + "Y";
if (this.months !== 0 || this.quarters !== 0)
s2 += this.months + this.quarters * 3 + "M";
if (this.weeks !== 0)
s2 += this.weeks + "W";
if (this.days !== 0)
s2 += this.days + "D";
if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0)
s2 += "T";
if (this.hours !== 0)
s2 += this.hours + "H";
if (this.minutes !== 0)
s2 += this.minutes + "M";
if (this.seconds !== 0 || this.milliseconds !== 0)
s2 += roundTo(this.seconds + this.milliseconds / 1e3, 3) + "S";
if (s2 === "P")
s2 += "T0S";
return s2;
}
/**
* Returns an ISO 8601-compliant string representation of this Duration, formatted as a time of day.
* Note that this will return null if the duration is invalid, negative, or equal to or greater than 24 hours.
* @see https://en.wikipedia.org/wiki/ISO_8601#Times
* @param {Object} opts - options
* @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
* @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
* @param {boolean} [opts.includePrefix=false] - include the `T` prefix
* @param {string} [opts.format='extended'] - choose between the basic and extended format
* @example Duration.fromObject({ hours: 11 }).toISOTime() //=> '11:00:00.000'
* @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressMilliseconds: true }) //=> '11:00:00'
* @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressSeconds: true }) //=> '11:00'
* @example Duration.fromObject({ hours: 11 }).toISOTime({ includePrefix: true }) //=> 'T11:00:00.000'
* @example Duration.fromObject({ hours: 11 }).toISOTime({ format: 'basic' }) //=> '110000.000'
* @return {string}
*/
toISOTime(opts = {}) {
if (!this.isValid)
return null;
const millis = this.toMillis();
if (millis < 0 || millis >= 864e5)
return null;
opts = {
suppressMilliseconds: false,
suppressSeconds: false,
includePrefix: false,
format: "extended",
...opts
};
const value = this.shiftTo("hours", "minutes", "seconds", "milliseconds");
let fmt = opts.format === "basic" ? "hhmm" : "hh:mm";
if (!opts.suppressSeconds || value.seconds !== 0 || value.milliseconds !== 0) {
fmt += opts.format === "basic" ? "ss" : ":ss";
if (!opts.suppressMilliseconds || value.milliseconds !== 0) {
fmt += ".SSS";
}
}
let str = value.toFormat(fmt);
if (opts.includePrefix) {
str = "T" + str;
}
return str;
}
/**
* Returns an ISO 8601 representation of this Duration appropriate for use in JSON.
* @return {string}
*/
toJSON() {
return this.toISO();
}
/**
* Returns an ISO 8601 representation of this Duration appropriate for use in debugging.
* @return {string}
*/
toString() {
return this.toISO();
}
/**
* Returns an milliseconds value of this Duration.
* @return {number}
*/
toMillis() {
return this.as("milliseconds");
}
/**
* Returns an milliseconds value of this Duration. Alias of {@link toMillis}
* @return {number}
*/
valueOf() {
return this.toMillis();
}
/**
* Make this Duration longer by the specified amount. Return a newly-constructed Duration.
* @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
* @return {Duration}
*/
plus(duration) {
if (!this.isValid)
return this;
const dur = Duration.fromDurationLike(duration), result = {};
for (const k of orderedUnits$1) {
if (hasOwnProperty(dur.values, k) || hasOwnProperty(this.values, k)) {
result[k] = dur.get(k) + this.get(k);
}
}
return clone$1(this, {
values: result
}, true);
}
/**
* Make this Duration shorter by the specified amount. Return a newly-constructed Duration.
* @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
* @return {Duration}
*/
minus(duration) {
if (!this.isValid)
return this;
const dur = Duration.fromDurationLike(duration);
return this.plus(dur.negate());
}
/**
* Scale this Duration by the specified amount. Return a newly-constructed Duration.
* @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number.
* @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits(x => x * 2) //=> { hours: 2, minutes: 60 }
* @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits((x, u) => u === "hours" ? x * 2 : x) //=> { hours: 2, minutes: 30 }
* @return {Duration}
*/
mapUnits(fn2) {
if (!this.isValid)
return this;
const result = {};
for (const k of Object.keys(this.values)) {
result[k] = asNumber(fn2(this.values[k], k));
}
return clone$1(this, {
values: result
}, true);
}
/**
* Get the value of unit.
* @param {string} unit - a unit such as 'minute' or 'day'
* @example Duration.fromObject({years: 2, days: 3}).get('years') //=> 2
* @example Duration.fromObject({years: 2, days: 3}).get('months') //=> 0
* @example Duration.fromObject({years: 2, days: 3}).get('days') //=> 3
* @return {number}
*/
get(unit) {
return this[Duration.normalizeUnit(unit)];
}
/**
* "Set" the values of specified units. Return a newly-constructed Duration.
* @param {Object} values - a mapping of units to numbers
* @example dur.set({ years: 2017 })
* @example dur.set({ hours: 8, minutes: 30 })
* @return {Duration}
*/
set(values) {
if (!this.isValid)
return this;
const mixed = {
...this.values,
...normalizeObject(values, Duration.normalizeUnit)
};
return clone$1(this, {
values: mixed
});
}
/**
* "Set" the locale and/or numberingSystem. Returns a newly-constructed Duration.
* @example dur.reconfigure({ locale: 'en-GB' })
* @return {Duration}
*/
reconfigure({
locale,
numberingSystem,
conversionAccuracy,
matrix
} = {}) {
const loc = this.loc.clone({
locale,
numberingSystem
});
const opts = {
loc,
matrix,
conversionAccuracy
};
return clone$1(this, opts);
}
/**
* Return the length of the duration in the specified unit.
* @param {string} unit - a unit such as 'minutes' or 'days'
* @example Duration.fromObject({years: 1}).as('days') //=> 365
* @example Duration.fromObject({years: 1}).as('months') //=> 12
* @example Duration.fromObject({hours: 60}).as('days') //=> 2.5
* @return {number}
*/
as(unit) {
return this.isValid ? this.shiftTo(unit).get(unit) : NaN;
}
/**
* Reduce this Duration to its canonical representation in its current units.
* @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 }
* @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 }
* @return {Duration}
*/
normalize() {
if (!this.isValid)
return this;
const vals = this.toObject();
normalizeValues(this.matrix, vals);
return clone$1(this, {
values: vals
}, true);
}
/**
* Rescale units to its largest representation
* @example Duration.fromObject({ milliseconds: 90000 }).rescale().toObject() //=> { minutes: 1, seconds: 30 }
* @return {Duration}
*/
rescale() {
if (!this.isValid)
return this;
const vals = removeZeroes(this.normalize().shiftToAll().toObject());
return clone$1(this, {
values: vals
}, true);
}
/**
* Convert this Duration into its representation in a different set of units.
* @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 }
* @return {Duration}
*/
shiftTo(...units) {
if (!this.isValid)
return this;
if (units.length === 0) {
return this;
}
units = units.map((u) => Duration.normalizeUnit(u));
const built = {}, accumulated = {}, vals = this.toObject();
let lastUnit;
for (const k of orderedUnits$1) {
if (units.indexOf(k) >= 0) {
lastUnit = k;
let own = 0;
for (const ak in accumulated) {
own += this.matrix[ak][k] * accumulated[ak];
accumulated[ak] = 0;
}
if (isNumber(vals[k])) {
own += vals[k];
}
const i = Math.trunc(own);
built[k] = i;
accumulated[k] = (own * 1e3 - i * 1e3) / 1e3;
for (const down in vals) {
if (orderedUnits$1.indexOf(down) > orderedUnits$1.indexOf(k)) {
convert(this.matrix, vals, down, built, k);
}
}
} else if (isNumber(vals[k])) {
accumulated[k] = vals[k];
}
}
for (const key in accumulated) {
if (accumulated[key] !== 0) {
built[lastUnit] += key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key];
}
}
return clone$1(this, {
values: built
}, true).normalize();
}
/**
* Shift this Duration to all available units.
* Same as shiftTo("years", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds")
* @return {Duration}
*/
shiftToAll() {
if (!this.isValid)
return this;
return this.shiftTo("years", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds");
}
/**
* Return the negative of this Duration.
* @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 }
* @return {Duration}
*/
negate() {
if (!this.isValid)
return this;
const negated = {};
for (const k of Object.keys(this.values)) {
negated[k] = this.values[k] === 0 ? 0 : -this.values[k];
}
return clone$1(this, {
values: negated
}, true);
}
/**
* Get the years.
* @type {number}
*/
get years() {
return this.isValid ? this.values.years || 0 : NaN;
}
/**
* Get the quarters.
* @type {number}
*/
get quarters() {
return this.isValid ? this.values.quarters || 0 : NaN;
}
/**
* Get the months.
* @type {number}
*/
get months() {
return this.isValid ? this.values.months || 0 : NaN;
}
/**
* Get the weeks
* @type {number}
*/
get weeks() {
return this.isValid ? this.values.weeks || 0 : NaN;
}
/**
* Get the days.
* @type {number}
*/
get days() {
return this.isValid ? this.values.days || 0 : NaN;
}
/**
* Get the hours.
* @type {number}
*/
get hours() {
return this.isValid ? this.values.hours || 0 : NaN;
}
/**
* Get the minutes.
* @type {number}
*/
get minutes() {
return this.isValid ? this.values.minutes || 0 : NaN;
}
/**
* Get the seconds.
* @return {number}
*/
get seconds() {
return this.isValid ? this.values.seconds || 0 : NaN;
}
/**
* Get the milliseconds.
* @return {number}
*/
get milliseconds() {
return this.isValid ? this.values.milliseconds || 0 : NaN;
}
/**
* Returns whether the Duration is invalid. Invalid durations are returned by diff operations
* on invalid DateTimes or Intervals.
* @return {boolean}
*/
get isValid() {
return this.invalid === null;
}
/**
* Returns an error code if this Duration became invalid, or null if the Duration is valid
* @return {string}
*/
get invalidReason() {
return this.invalid ? this.invalid.reason : null;
}
/**
* Returns an explanation of why this Duration became invalid, or null if the Duration is valid
* @type {string}
*/
get invalidExplanation() {
return this.invalid ? this.invalid.explanation : null;
}
/**
* Equality check
* Two Durations are equal iff they have the same units and the same values for each unit.
* @param {Duration} other
* @return {boolean}
*/
equals(other) {
if (!this.isValid || !other.isValid) {
return false;
}
if (!this.loc.equals(other.loc)) {
return false;
}
function eq(v1, v2) {
if (v1 === void 0 || v1 === 0)
return v2 === void 0 || v2 === 0;
return v1 === v2;
}
for (const u of orderedUnits$1) {
if (!eq(this.values[u], other.values[u])) {
return false;
}
}
return true;
}
};
var INVALID$1 = "Invalid Interval";
function validateStartEnd(start2, end2) {
if (!start2 || !start2.isValid) {
return Interval.invalid("missing or invalid start");
} else if (!end2 || !end2.isValid) {
return Interval.invalid("missing or invalid end");
} else if (end2 < start2) {
return Interval.invalid("end before start", `The end of an interval must be after its start, but you had start=${start2.toISO()} and end=${end2.toISO()}`);
} else {
return null;
}
}
var Interval = class {
/**
* @private
*/
constructor(config) {
this.s = config.start;
this.e = config.end;
this.invalid = config.invalid || null;
this.isLuxonInterval = true;
}
/**
* Create an invalid Interval.
* @param {string} reason - simple string of why this Interval is invalid. Should not contain parameters or anything else data-dependent
* @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
* @return {Interval}
*/
static invalid(reason, explanation = null) {
if (!reason) {
throw new InvalidArgumentError("need to specify a reason the Interval is invalid");
}
const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
if (Settings.throwOnInvalid) {
throw new InvalidIntervalError(invalid);
} else {
return new Interval({
invalid
});
}
}
/**
* Create an Interval from a start DateTime and an end DateTime. Inclusive of the start but not the end.
* @param {DateTime|Date|Object} start
* @param {DateTime|Date|Object} end
* @return {Interval}
*/
static fromDateTimes(start2, end2) {
const builtStart = friendlyDateTime(start2), builtEnd = friendlyDateTime(end2);
const validateError = validateStartEnd(builtStart, builtEnd);
if (validateError == null) {
return new Interval({
start: builtStart,
end: builtEnd
});
} else {
return validateError;
}
}
/**
* Create an Interval from a start DateTime and a Duration to extend to.
* @param {DateTime|Date|Object} start
* @param {Duration|Object|number} duration - the length of the Interval.
* @return {Interval}
*/
static after(start2, duration) {
const dur = Duration.fromDurationLike(duration), dt = friendlyDateTime(start2);
return Interval.fromDateTimes(dt, dt.plus(dur));
}
/**
* Create an Interval from an end DateTime and a Duration to extend backwards to.
* @param {DateTime|Date|Object} end
* @param {Duration|Object|number} duration - the length of the Interval.
* @return {Interval}
*/
static before(end2, duration) {
const dur = Duration.fromDurationLike(duration), dt = friendlyDateTime(end2);
return Interval.fromDateTimes(dt.minus(dur), dt);
}
/**
* Create an Interval from an ISO 8601 string.
* Accepts `<start>/<end>`, `<start>/<duration>`, and `<duration>/<end>` formats.
* @param {string} text - the ISO string to parse
* @param {Object} [opts] - options to pass {@link DateTime#fromISO} and optionally {@link Duration#fromISO}
* @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
* @return {Interval}
*/
static fromISO(text, opts) {
const [s2, e] = (text || "").split("/", 2);
if (s2 && e) {
let start2, startIsValid;
try {
start2 = DateTime.fromISO(s2, opts);
startIsValid = start2.isValid;
} catch (e2) {
startIsValid = false;
}
let end2, endIsValid;
try {
end2 = DateTime.fromISO(e, opts);
endIsValid = end2.isValid;
} catch (e2) {
endIsValid = false;
}
if (startIsValid && endIsValid) {
return Interval.fromDateTimes(start2, end2);
}
if (startIsValid) {
const dur = Duration.fromISO(e, opts);
if (dur.isValid) {
return Interval.after(start2, dur);
}
} else if (endIsValid) {
const dur = Duration.fromISO(s2, opts);
if (dur.isValid) {
return Interval.before(end2, dur);
}
}
}
return Interval.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`);
}
/**
* Check if an object is an Interval. Works across context boundaries
* @param {object} o
* @return {boolean}
*/
static isInterval(o) {
return o && o.isLuxonInterval || false;
}
/**
* Returns the start of the Interval
* @type {DateTime}
*/
get start() {
return this.isValid ? this.s : null;
}
/**
* Returns the end of the Interval
* @type {DateTime}
*/
get end() {
return this.isValid ? this.e : null;
}
/**
* Returns whether this Interval's end is at least its start, meaning that the Interval isn't 'backwards'.
* @type {boolean}
*/
get isValid() {
return this.invalidReason === null;
}
/**
* Returns an error code if this Interval is invalid, or null if the Interval is valid
* @type {string}
*/
get invalidReason() {
return this.invalid ? this.invalid.reason : null;
}
/**
* Returns an explanation of why this Interval became invalid, or null if the Interval is valid
* @type {string}
*/
get invalidExplanation() {
return this.invalid ? this.invalid.explanation : null;
}
/**
* Returns the length of the Interval in the specified unit.
* @param {string} unit - the unit (such as 'hours' or 'days') to return the length in.
* @return {number}
*/
length(unit = "milliseconds") {
return this.isValid ? this.toDuration(...[unit]).get(unit) : NaN;
}
/**
* Returns the count of minutes, hours, days, months, or years included in the Interval, even in part.
* Unlike {@link Interval#length} this counts sections of the calendar, not periods of time, e.g. specifying 'day'
* asks 'what dates are included in this interval?', not 'how many days long is this interval?'
* @param {string} [unit='milliseconds'] - the unit of time to count.
* @return {number}
*/
count(unit = "milliseconds") {
if (!this.isValid)
return NaN;
const start2 = this.start.startOf(unit), end2 = this.end.startOf(unit);
return Math.floor(end2.diff(start2, unit).get(unit)) + (end2.valueOf() !== this.end.valueOf());
}
/**
* Returns whether this Interval's start and end are both in the same unit of time
* @param {string} unit - the unit of time to check sameness on
* @return {boolean}
*/
hasSame(unit) {
return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false;
}
/**
* Return whether this Interval has the same start and end DateTimes.
* @return {boolean}
*/
isEmpty() {
return this.s.valueOf() === this.e.valueOf();
}
/**
* Return whether this Interval's start is after the specified DateTime.
* @param {DateTime} dateTime
* @return {boolean}
*/
isAfter(dateTime) {
if (!this.isValid)
return false;
return this.s > dateTime;
}
/**
* Return whether this Interval's end is before the specified DateTime.
* @param {DateTime} dateTime
* @return {boolean}
*/
isBefore(dateTime) {
if (!this.isValid)
return false;
return this.e <= dateTime;
}
/**
* Return whether this Interval contains the specified DateTime.
* @param {DateTime} dateTime
* @return {boolean}
*/
contains(dateTime) {
if (!this.isValid)
return false;
return this.s <= dateTime && this.e > dateTime;
}
/**
* "Sets" the start and/or end dates. Returns a newly-constructed Interval.
* @param {Object} values - the values to set
* @param {DateTime} values.start - the starting DateTime
* @param {DateTime} values.end - the ending DateTime
* @return {Interval}
*/
set({
start: start2,
end: end2
} = {}) {
if (!this.isValid)
return this;
return Interval.fromDateTimes(start2 || this.s, end2 || this.e);
}
/**
* Split this Interval at each of the specified DateTimes
* @param {...DateTime} dateTimes - the unit of time to count.
* @return {Array}
*/
splitAt(...dateTimes) {
if (!this.isValid)
return [];
const sorted = dateTimes.map(friendlyDateTime).filter((d) => this.contains(d)).sort(), results = [];
let {
s: s2
} = this, i = 0;
while (s2 < this.e) {
const added = sorted[i] || this.e, next = +added > +this.e ? this.e : added;
results.push(Interval.fromDateTimes(s2, next));
s2 = next;
i += 1;
}
return results;
}
/**
* Split this Interval into smaller Intervals, each of the specified length.
* Left over time is grouped into a smaller interval
* @param {Duration|Object|number} duration - The length of each resulting interval.
* @return {Array}
*/
splitBy(duration) {
const dur = Duration.fromDurationLike(duration);
if (!this.isValid || !dur.isValid || dur.as("milliseconds") === 0) {
return [];
}
let {
s: s2
} = this, idx = 1, next;
const results = [];
while (s2 < this.e) {
const added = this.start.plus(dur.mapUnits((x) => x * idx));
next = +added > +this.e ? this.e : added;
results.push(Interval.fromDateTimes(s2, next));
s2 = next;
idx += 1;
}
return results;
}
/**
* Split this Interval into the specified number of smaller intervals.
* @param {number} numberOfParts - The number of Intervals to divide the Interval into.
* @return {Array}
*/
divideEqually(numberOfParts) {
if (!this.isValid)
return [];
return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts);
}
/**
* Return whether this Interval overlaps with the specified Interval
* @param {Interval} other
* @return {boolean}
*/
overlaps(other) {
return this.e > other.s && this.s < other.e;
}
/**
* Return whether this Interval's end is adjacent to the specified Interval's start.
* @param {Interval} other
* @return {boolean}
*/
abutsStart(other) {
if (!this.isValid)
return false;
return +this.e === +other.s;
}
/**
* Return whether this Interval's start is adjacent to the specified Interval's end.
* @param {Interval} other
* @return {boolean}
*/
abutsEnd(other) {
if (!this.isValid)
return false;
return +other.e === +this.s;
}
/**
* Return whether this Interval engulfs the start and end of the specified Interval.
* @param {Interval} other
* @return {boolean}
*/
engulfs(other) {
if (!this.isValid)
return false;
return this.s <= other.s && this.e >= other.e;
}
/**
* Return whether this Interval has the same start and end as the specified Interval.
* @param {Interval} other
* @return {boolean}
*/
equals(other) {
if (!this.isValid || !other.isValid) {
return false;
}
return this.s.equals(other.s) && this.e.equals(other.e);
}
/**
* Return an Interval representing the intersection of this Interval and the specified Interval.
* Specifically, the resulting Interval has the maximum start time and the minimum end time of the two Intervals.
* Returns null if the intersection is empty, meaning, the intervals don't intersect.
* @param {Interval} other
* @return {Interval}
*/
intersection(other) {
if (!this.isValid)
return this;
const s2 = this.s > other.s ? this.s : other.s, e = this.e < other.e ? this.e : other.e;
if (s2 >= e) {
return null;
} else {
return Interval.fromDateTimes(s2, e);
}
}
/**
* Return an Interval representing the union of this Interval and the specified Interval.
* Specifically, the resulting Interval has the minimum start time and the maximum end time of the two Intervals.
* @param {Interval} other
* @return {Interval}
*/
union(other) {
if (!this.isValid)
return this;
const s2 = this.s < other.s ? this.s : other.s, e = this.e > other.e ? this.e : other.e;
return Interval.fromDateTimes(s2, e);
}
/**
* Merge an array of Intervals into a equivalent minimal set of Intervals.
* Combines overlapping and adjacent Intervals.
* @param {Array} intervals
* @return {Array}
*/
static merge(intervals) {
const [found, final] = intervals.sort((a, b) => a.s - b.s).reduce(([sofar, current], item) => {
if (!current) {
return [sofar, item];
} else if (current.overlaps(item) || current.abutsStart(item)) {
return [sofar, current.union(item)];
} else {
return [sofar.concat([current]), item];
}
}, [[], null]);
if (final) {
found.push(final);
}
return found;
}
/**
* Return an array of Intervals representing the spans of time that only appear in one of the specified Intervals.
* @param {Array} intervals
* @return {Array}
*/
static xor(intervals) {
let start2 = null, currentCount = 0;
const results = [], ends = intervals.map((i) => [{
time: i.s,
type: "s"
}, {
time: i.e,
type: "e"
}]), flattened = Array.prototype.concat(...ends), arr = flattened.sort((a, b) => a.time - b.time);
for (const i of arr) {
currentCount += i.type === "s" ? 1 : -1;
if (currentCount === 1) {
start2 = i.time;
} else {
if (start2 && +start2 !== +i.time) {
results.push(Interval.fromDateTimes(start2, i.time));
}
start2 = null;
}
}
return Interval.merge(results);
}
/**
* Return an Interval representing the span of time in this Interval that doesn't overlap with any of the specified Intervals.
* @param {...Interval} intervals
* @return {Array}
*/
difference(...intervals) {
return Interval.xor([this].concat(intervals)).map((i) => this.intersection(i)).filter((i) => i && !i.isEmpty());
}
/**
* Returns a string representation of this Interval appropriate for debugging.
* @return {string}
*/
toString() {
if (!this.isValid)
return INVALID$1;
return `[${this.s.toISO()} \u2013 ${this.e.toISO()})`;
}
/**
* Returns a localized string representing this Interval. Accepts the same options as the
* Intl.DateTimeFormat constructor and any presets defined by Luxon, such as
* {@link DateTime.DATE_FULL} or {@link DateTime.TIME_SIMPLE}. The exact behavior of this method
* is browser-specific, but in general it will return an appropriate representation of the
* Interval in the assigned locale. Defaults to the system's locale if no locale has been
* specified.
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
* @param {Object} [formatOpts=DateTime.DATE_SHORT] - Either a DateTime preset or
* Intl.DateTimeFormat constructor options.
* @param {Object} opts - Options to override the configuration of the start DateTime.
* @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(); //=> 11/7/2022 11/8/2022
* @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL); //=> November 7 8, 2022
* @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL, { locale: 'fr-FR' }); //=> 78 novembre 2022
* @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString(DateTime.TIME_SIMPLE); //=> 6:00 8:00 PM
* @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> Mon, Nov 07, 6:00 8:00 p
* @return {string}
*/
toLocaleString(formatOpts = DATE_SHORT, opts = {}) {
return this.isValid ? Formatter.create(this.s.loc.clone(opts), formatOpts).formatInterval(this) : INVALID$1;
}
/**
* Returns an ISO 8601-compliant string representation of this Interval.
* @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
* @param {Object} opts - The same options as {@link DateTime#toISO}
* @return {string}
*/
toISO(opts) {
if (!this.isValid)
return INVALID$1;
return `${this.s.toISO(opts)}/${this.e.toISO(opts)}`;
}
/**
* Returns an ISO 8601-compliant string representation of date of this Interval.
* The time components are ignored.
* @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
* @return {string}
*/
toISODate() {
if (!this.isValid)
return INVALID$1;
return `${this.s.toISODate()}/${this.e.toISODate()}`;
}
/**
* Returns an ISO 8601-compliant string representation of time of this Interval.
* The date components are ignored.
* @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals
* @param {Object} opts - The same options as {@link DateTime#toISO}
* @return {string}
*/
toISOTime(opts) {
if (!this.isValid)
return INVALID$1;
return `${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`;
}
/**
* Returns a string representation of this Interval formatted according to the specified format
* string. **You may not want this.** See {@link Interval#toLocaleString} for a more flexible
* formatting tool.
* @param {string} dateFormat - The format string. This string formats the start and end time.
* See {@link DateTime#toFormat} for details.
* @param {Object} opts - Options.
* @param {string} [opts.separator = ' '] - A separator to place between the start and end
* representations.
* @return {string}
*/
toFormat(dateFormat, {
separator = " \u2013 "
} = {}) {
if (!this.isValid)
return INVALID$1;
return `${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`;
}
/**
* Return a Duration representing the time spanned by this interval.
* @param {string|string[]} [unit=['milliseconds']] - the unit or units (such as 'hours' or 'days') to include in the duration.
* @param {Object} opts - options that affect the creation of the Duration
* @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
* @example Interval.fromDateTimes(dt1, dt2).toDuration().toObject() //=> { milliseconds: 88489257 }
* @example Interval.fromDateTimes(dt1, dt2).toDuration('days').toObject() //=> { days: 1.0241812152777778 }
* @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes']).toObject() //=> { hours: 24, minutes: 34.82095 }
* @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes', 'seconds']).toObject() //=> { hours: 24, minutes: 34, seconds: 49.257 }
* @example Interval.fromDateTimes(dt1, dt2).toDuration('seconds').toObject() //=> { seconds: 88489.257 }
* @return {Duration}
*/
toDuration(unit, opts) {
if (!this.isValid) {
return Duration.invalid(this.invalidReason);
}
return this.e.diff(this.s, unit, opts);
}
/**
* Run mapFn on the interval start and end, returning a new Interval from the resulting DateTimes
* @param {function} mapFn
* @return {Interval}
* @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.toUTC())
* @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.plus({ hours: 2 }))
*/
mapEndpoints(mapFn) {
return Interval.fromDateTimes(mapFn(this.s), mapFn(this.e));
}
};
var Info = class {
/**
* Return whether the specified zone contains a DST.
* @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone.
* @return {boolean}
*/
static hasDST(zone = Settings.defaultZone) {
const proto = DateTime.now().setZone(zone).set({
month: 12
});
return !zone.isUniversal && proto.offset !== proto.set({
month: 6
}).offset;
}
/**
* Return whether the specified zone is a valid IANA specifier.
* @param {string} zone - Zone to check
* @return {boolean}
*/
static isValidIANAZone(zone) {
return IANAZone.isValidZone(zone);
}
/**
* Converts the input into a {@link Zone} instance.
*
* * If `input` is already a Zone instance, it is returned unchanged.
* * If `input` is a string containing a valid time zone name, a Zone instance
* with that name is returned.
* * If `input` is a string that doesn't refer to a known time zone, a Zone
* instance with {@link Zone#isValid} == false is returned.
* * If `input is a number, a Zone instance with the specified fixed offset
* in minutes is returned.
* * If `input` is `null` or `undefined`, the default zone is returned.
* @param {string|Zone|number} [input] - the value to be converted
* @return {Zone}
*/
static normalizeZone(input) {
return normalizeZone(input, Settings.defaultZone);
}
/**
* Return an array of standalone month names.
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
* @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long"
* @param {Object} opts - options
* @param {string} [opts.locale] - the locale code
* @param {string} [opts.numberingSystem=null] - the numbering system
* @param {string} [opts.locObj=null] - an existing locale object to use
* @param {string} [opts.outputCalendar='gregory'] - the calendar
* @example Info.months()[0] //=> 'January'
* @example Info.months('short')[0] //=> 'Jan'
* @example Info.months('numeric')[0] //=> '1'
* @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.'
* @example Info.months('numeric', { locale: 'ar' })[0] //=> '١'
* @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I'
* @return {Array}
*/
static months(length = "long", {
locale = null,
numberingSystem = null,
locObj = null,
outputCalendar = "gregory"
} = {}) {
return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length);
}
/**
* Return an array of format month names.
* Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that
* changes the string.
* See {@link Info#months}
* @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long"
* @param {Object} opts - options
* @param {string} [opts.locale] - the locale code
* @param {string} [opts.numberingSystem=null] - the numbering system
* @param {string} [opts.locObj=null] - an existing locale object to use
* @param {string} [opts.outputCalendar='gregory'] - the calendar
* @return {Array}
*/
static monthsFormat(length = "long", {
locale = null,
numberingSystem = null,
locObj = null,
outputCalendar = "gregory"
} = {}) {
return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length, true);
}
/**
* Return an array of standalone week names.
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
* @param {string} [length='long'] - the length of the weekday representation, such as "narrow", "short", "long".
* @param {Object} opts - options
* @param {string} [opts.locale] - the locale code
* @param {string} [opts.numberingSystem=null] - the numbering system
* @param {string} [opts.locObj=null] - an existing locale object to use
* @example Info.weekdays()[0] //=> 'Monday'
* @example Info.weekdays('short')[0] //=> 'Mon'
* @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.'
* @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين'
* @return {Array}
*/
static weekdays(length = "long", {
locale = null,
numberingSystem = null,
locObj = null
} = {}) {
return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length);
}
/**
* Return an array of format week names.
* Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that
* changes the string.
* See {@link Info#weekdays}
* @param {string} [length='long'] - the length of the month representation, such as "narrow", "short", "long".
* @param {Object} opts - options
* @param {string} [opts.locale=null] - the locale code
* @param {string} [opts.numberingSystem=null] - the numbering system
* @param {string} [opts.locObj=null] - an existing locale object to use
* @return {Array}
*/
static weekdaysFormat(length = "long", {
locale = null,
numberingSystem = null,
locObj = null
} = {}) {
return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length, true);
}
/**
* Return an array of meridiems.
* @param {Object} opts - options
* @param {string} [opts.locale] - the locale code
* @example Info.meridiems() //=> [ 'AM', 'PM' ]
* @example Info.meridiems({ locale: 'my' }) //=> [ 'နံနက်', 'ညနေ' ]
* @return {Array}
*/
static meridiems({
locale = null
} = {}) {
return Locale.create(locale).meridiems();
}
/**
* Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian.
* @param {string} [length='short'] - the length of the era representation, such as "short" or "long".
* @param {Object} opts - options
* @param {string} [opts.locale] - the locale code
* @example Info.eras() //=> [ 'BC', 'AD' ]
* @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ]
* @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ]
* @return {Array}
*/
static eras(length = "short", {
locale = null
} = {}) {
return Locale.create(locale, null, "gregory").eras(length);
}
/**
* Return the set of available features in this environment.
* Some features of Luxon are not available in all environments. For example, on older browsers, relative time formatting support is not available. Use this function to figure out if that's the case.
* Keys:
* * `relative`: whether this environment supports relative time formatting
* @example Info.features() //=> { relative: false }
* @return {Object}
*/
static features() {
return {
relative: hasRelative()
};
}
};
function dayDiff(earlier, later) {
const utcDayStart = (dt) => dt.toUTC(0, {
keepLocalTime: true
}).startOf("day").valueOf(), ms = utcDayStart(later) - utcDayStart(earlier);
return Math.floor(Duration.fromMillis(ms).as("days"));
}
function highOrderDiffs(cursor, later, units) {
const differs = [["years", (a, b) => b.year - a.year], ["quarters", (a, b) => b.quarter - a.quarter + (b.year - a.year) * 4], ["months", (a, b) => b.month - a.month + (b.year - a.year) * 12], ["weeks", (a, b) => {
const days = dayDiff(a, b);
return (days - days % 7) / 7;
}], ["days", dayDiff]];
const results = {};
const earlier = cursor;
let lowestOrder, highWater;
for (const [unit, differ] of differs) {
if (units.indexOf(unit) >= 0) {
lowestOrder = unit;
results[unit] = differ(cursor, later);
highWater = earlier.plus(results);
if (highWater > later) {
results[unit]--;
cursor = earlier.plus(results);
} else {
cursor = highWater;
}
}
}
return [cursor, results, highWater, lowestOrder];
}
function diff(earlier, later, units, opts) {
let [cursor, results, highWater, lowestOrder] = highOrderDiffs(earlier, later, units);
const remainingMillis = later - cursor;
const lowerOrderUnits = units.filter((u) => ["hours", "minutes", "seconds", "milliseconds"].indexOf(u) >= 0);
if (lowerOrderUnits.length === 0) {
if (highWater < later) {
highWater = cursor.plus({
[lowestOrder]: 1
});
}
if (highWater !== cursor) {
results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor);
}
}
const duration = Duration.fromObject(results, opts);
if (lowerOrderUnits.length > 0) {
return Duration.fromMillis(remainingMillis, opts).shiftTo(...lowerOrderUnits).plus(duration);
} else {
return duration;
}
}
var numberingSystems = {
arab: "[\u0660-\u0669]",
arabext: "[\u06F0-\u06F9]",
bali: "[\u1B50-\u1B59]",
beng: "[\u09E6-\u09EF]",
deva: "[\u0966-\u096F]",
fullwide: "[\uFF10-\uFF19]",
gujr: "[\u0AE6-\u0AEF]",
hanidec: "[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",
khmr: "[\u17E0-\u17E9]",
knda: "[\u0CE6-\u0CEF]",
laoo: "[\u0ED0-\u0ED9]",
limb: "[\u1946-\u194F]",
mlym: "[\u0D66-\u0D6F]",
mong: "[\u1810-\u1819]",
mymr: "[\u1040-\u1049]",
orya: "[\u0B66-\u0B6F]",
tamldec: "[\u0BE6-\u0BEF]",
telu: "[\u0C66-\u0C6F]",
thai: "[\u0E50-\u0E59]",
tibt: "[\u0F20-\u0F29]",
latn: "\\d"
};
var numberingSystemsUTF16 = {
arab: [1632, 1641],
arabext: [1776, 1785],
bali: [6992, 7001],
beng: [2534, 2543],
deva: [2406, 2415],
fullwide: [65296, 65303],
gujr: [2790, 2799],
khmr: [6112, 6121],
knda: [3302, 3311],
laoo: [3792, 3801],
limb: [6470, 6479],
mlym: [3430, 3439],
mong: [6160, 6169],
mymr: [4160, 4169],
orya: [2918, 2927],
tamldec: [3046, 3055],
telu: [3174, 3183],
thai: [3664, 3673],
tibt: [3872, 3881]
};
var hanidecChars = numberingSystems.hanidec.replace(/[\[|\]]/g, "").split("");
function parseDigits(str) {
let value = parseInt(str, 10);
if (isNaN(value)) {
value = "";
for (let i = 0; i < str.length; i++) {
const code = str.charCodeAt(i);
if (str[i].search(numberingSystems.hanidec) !== -1) {
value += hanidecChars.indexOf(str[i]);
} else {
for (const key in numberingSystemsUTF16) {
const [min2, max2] = numberingSystemsUTF16[key];
if (code >= min2 && code <= max2) {
value += code - min2;
}
}
}
}
return parseInt(value, 10);
} else {
return value;
}
}
function digitRegex({
numberingSystem
}, append = "") {
return new RegExp(`${numberingSystems[numberingSystem || "latn"]}${append}`);
}
var MISSING_FTP = "missing Intl.DateTimeFormat.formatToParts support";
function intUnit(regex, post = (i) => i) {
return {
regex,
deser: ([s2]) => post(parseDigits(s2))
};
}
var NBSP = String.fromCharCode(160);
var spaceOrNBSP = `[ ${NBSP}]`;
var spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, "g");
function fixListRegex(s2) {
return s2.replace(/\./g, "\\.?").replace(spaceOrNBSPRegExp, spaceOrNBSP);
}
function stripInsensitivities(s2) {
return s2.replace(/\./g, "").replace(spaceOrNBSPRegExp, " ").toLowerCase();
}
function oneOf(strings, startIndex) {
if (strings === null) {
return null;
} else {
return {
regex: RegExp(strings.map(fixListRegex).join("|")),
deser: ([s2]) => strings.findIndex((i) => stripInsensitivities(s2) === stripInsensitivities(i)) + startIndex
};
}
}
function offset2(regex, groups) {
return {
regex,
deser: ([, h, m]) => signedOffset(h, m),
groups
};
}
function simple(regex) {
return {
regex,
deser: ([s2]) => s2
};
}
function escapeToken(value) {
return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
}
function unitForToken(token, loc) {
const one = digitRegex(loc), two = digitRegex(loc, "{2}"), three = digitRegex(loc, "{3}"), four = digitRegex(loc, "{4}"), six = digitRegex(loc, "{6}"), oneOrTwo = digitRegex(loc, "{1,2}"), oneToThree = digitRegex(loc, "{1,3}"), oneToSix = digitRegex(loc, "{1,6}"), oneToNine = digitRegex(loc, "{1,9}"), twoToFour = digitRegex(loc, "{2,4}"), fourToSix = digitRegex(loc, "{4,6}"), literal = (t) => ({
regex: RegExp(escapeToken(t.val)),
deser: ([s2]) => s2,
literal: true
}), unitate = (t) => {
if (token.literal) {
return literal(t);
}
switch (t.val) {
case "G":
return oneOf(loc.eras("short", false), 0);
case "GG":
return oneOf(loc.eras("long", false), 0);
case "y":
return intUnit(oneToSix);
case "yy":
return intUnit(twoToFour, untruncateYear);
case "yyyy":
return intUnit(four);
case "yyyyy":
return intUnit(fourToSix);
case "yyyyyy":
return intUnit(six);
case "M":
return intUnit(oneOrTwo);
case "MM":
return intUnit(two);
case "MMM":
return oneOf(loc.months("short", true, false), 1);
case "MMMM":
return oneOf(loc.months("long", true, false), 1);
case "L":
return intUnit(oneOrTwo);
case "LL":
return intUnit(two);
case "LLL":
return oneOf(loc.months("short", false, false), 1);
case "LLLL":
return oneOf(loc.months("long", false, false), 1);
case "d":
return intUnit(oneOrTwo);
case "dd":
return intUnit(two);
case "o":
return intUnit(oneToThree);
case "ooo":
return intUnit(three);
case "HH":
return intUnit(two);
case "H":
return intUnit(oneOrTwo);
case "hh":
return intUnit(two);
case "h":
return intUnit(oneOrTwo);
case "mm":
return intUnit(two);
case "m":
return intUnit(oneOrTwo);
case "q":
return intUnit(oneOrTwo);
case "qq":
return intUnit(two);
case "s":
return intUnit(oneOrTwo);
case "ss":
return intUnit(two);
case "S":
return intUnit(oneToThree);
case "SSS":
return intUnit(three);
case "u":
return simple(oneToNine);
case "uu":
return simple(oneOrTwo);
case "uuu":
return intUnit(one);
case "a":
return oneOf(loc.meridiems(), 0);
case "kkkk":
return intUnit(four);
case "kk":
return intUnit(twoToFour, untruncateYear);
case "W":
return intUnit(oneOrTwo);
case "WW":
return intUnit(two);
case "E":
case "c":
return intUnit(one);
case "EEE":
return oneOf(loc.weekdays("short", false, false), 1);
case "EEEE":
return oneOf(loc.weekdays("long", false, false), 1);
case "ccc":
return oneOf(loc.weekdays("short", true, false), 1);
case "cccc":
return oneOf(loc.weekdays("long", true, false), 1);
case "Z":
case "ZZ":
return offset2(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2);
case "ZZZ":
return offset2(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2);
case "z":
return simple(/[a-z_+-/]{1,256}?/i);
case " ":
return simple(/[^\S\n\r]/);
default:
return literal(t);
}
};
const unit = unitate(token) || {
invalidReason: MISSING_FTP
};
unit.token = token;
return unit;
}
var partTypeStyleToTokenVal = {
year: {
"2-digit": "yy",
numeric: "yyyyy"
},
month: {
numeric: "M",
"2-digit": "MM",
short: "MMM",
long: "MMMM"
},
day: {
numeric: "d",
"2-digit": "dd"
},
weekday: {
short: "EEE",
long: "EEEE"
},
dayperiod: "a",
dayPeriod: "a",
hour: {
numeric: "h",
"2-digit": "hh"
},
minute: {
numeric: "m",
"2-digit": "mm"
},
second: {
numeric: "s",
"2-digit": "ss"
},
timeZoneName: {
long: "ZZZZZ",
short: "ZZZ"
}
};
function tokenForPart(part, formatOpts) {
const {
type,
value
} = part;
if (type === "literal") {
const isSpace = /^\s+$/.test(value);
return {
literal: !isSpace,
val: isSpace ? " " : value
};
}
const style = formatOpts[type];
let val = partTypeStyleToTokenVal[type];
if (typeof val === "object") {
val = val[style];
}
if (val) {
return {
literal: false,
val
};
}
return void 0;
}
function buildRegex(units) {
const re = units.map((u) => u.regex).reduce((f, r) => `${f}(${r.source})`, "");
return [`^${re}$`, units];
}
function match(input, regex, handlers) {
const matches = input.match(regex);
if (matches) {
const all = {};
let matchIndex = 1;
for (const i in handlers) {
if (hasOwnProperty(handlers, i)) {
const h = handlers[i], groups = h.groups ? h.groups + 1 : 1;
if (!h.literal && h.token) {
all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups));
}
matchIndex += groups;
}
}
return [matches, all];
} else {
return [matches, {}];
}
}
function dateTimeFromMatches(matches) {
const toField = (token) => {
switch (token) {
case "S":
return "millisecond";
case "s":
return "second";
case "m":
return "minute";
case "h":
case "H":
return "hour";
case "d":
return "day";
case "o":
return "ordinal";
case "L":
case "M":
return "month";
case "y":
return "year";
case "E":
case "c":
return "weekday";
case "W":
return "weekNumber";
case "k":
return "weekYear";
case "q":
return "quarter";
default:
return null;
}
};
let zone = null;
let specificOffset;
if (!isUndefined(matches.z)) {
zone = IANAZone.create(matches.z);
}
if (!isUndefined(matches.Z)) {
if (!zone) {
zone = new FixedOffsetZone(matches.Z);
}
specificOffset = matches.Z;
}
if (!isUndefined(matches.q)) {
matches.M = (matches.q - 1) * 3 + 1;
}
if (!isUndefined(matches.h)) {
if (matches.h < 12 && matches.a === 1) {
matches.h += 12;
} else if (matches.h === 12 && matches.a === 0) {
matches.h = 0;
}
}
if (matches.G === 0 && matches.y) {
matches.y = -matches.y;
}
if (!isUndefined(matches.u)) {
matches.S = parseMillis(matches.u);
}
const vals = Object.keys(matches).reduce((r, k) => {
const f = toField(k);
if (f) {
r[f] = matches[k];
}
return r;
}, {});
return [vals, zone, specificOffset];
}
var dummyDateTimeCache = null;
function getDummyDateTime() {
if (!dummyDateTimeCache) {
dummyDateTimeCache = DateTime.fromMillis(1555555555555);
}
return dummyDateTimeCache;
}
function maybeExpandMacroToken(token, locale) {
if (token.literal) {
return token;
}
const formatOpts = Formatter.macroTokenToFormatOpts(token.val);
const tokens = formatOptsToTokens(formatOpts, locale);
if (tokens == null || tokens.includes(void 0)) {
return token;
}
return tokens;
}
function expandMacroTokens(tokens, locale) {
return Array.prototype.concat(...tokens.map((t) => maybeExpandMacroToken(t, locale)));
}
function explainFromTokens(locale, input, format2) {
const tokens = expandMacroTokens(Formatter.parseFormat(format2), locale), units = tokens.map((t) => unitForToken(t, locale)), disqualifyingUnit = units.find((t) => t.invalidReason);
if (disqualifyingUnit) {
return {
input,
tokens,
invalidReason: disqualifyingUnit.invalidReason
};
} else {
const [regexString, handlers] = buildRegex(units), regex = RegExp(regexString, "i"), [rawMatches, matches] = match(input, regex, handlers), [result, zone, specificOffset] = matches ? dateTimeFromMatches(matches) : [null, null, void 0];
if (hasOwnProperty(matches, "a") && hasOwnProperty(matches, "H")) {
throw new ConflictingSpecificationError("Can't include meridiem when specifying 24-hour format");
}
return {
input,
tokens,
regex,
rawMatches,
matches,
result,
zone,
specificOffset
};
}
}
function parseFromTokens(locale, input, format2) {
const {
result,
zone,
specificOffset,
invalidReason
} = explainFromTokens(locale, input, format2);
return [result, zone, specificOffset, invalidReason];
}
function formatOptsToTokens(formatOpts, locale) {
if (!formatOpts) {
return null;
}
const formatter = Formatter.create(locale, formatOpts);
const parts = formatter.formatDateTimeParts(getDummyDateTime());
return parts.map((p) => tokenForPart(p, formatOpts));
}
var nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
var leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];
function unitOutOfRange(unit, value) {
return new Invalid("unit out of range", `you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid`);
}
function dayOfWeek(year, month, day) {
const d = new Date(Date.UTC(year, month - 1, day));
if (year < 100 && year >= 0) {
d.setUTCFullYear(d.getUTCFullYear() - 1900);
}
const js = d.getUTCDay();
return js === 0 ? 7 : js;
}
function computeOrdinal(year, month, day) {
return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1];
}
function uncomputeOrdinal(year, ordinal) {
const table = isLeapYear(year) ? leapLadder : nonLeapLadder, month0 = table.findIndex((i) => i < ordinal), day = ordinal - table[month0];
return {
month: month0 + 1,
day
};
}
function gregorianToWeek(gregObj) {
const {
year,
month,
day
} = gregObj, ordinal = computeOrdinal(year, month, day), weekday = dayOfWeek(year, month, day);
let weekNumber = Math.floor((ordinal - weekday + 10) / 7), weekYear;
if (weekNumber < 1) {
weekYear = year - 1;
weekNumber = weeksInWeekYear(weekYear);
} else if (weekNumber > weeksInWeekYear(year)) {
weekYear = year + 1;
weekNumber = 1;
} else {
weekYear = year;
}
return {
weekYear,
weekNumber,
weekday,
...timeObject(gregObj)
};
}
function weekToGregorian(weekData) {
const {
weekYear,
weekNumber,
weekday
} = weekData, weekdayOfJan4 = dayOfWeek(weekYear, 1, 4), yearInDays = daysInYear(weekYear);
let ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 3, year;
if (ordinal < 1) {
year = weekYear - 1;
ordinal += daysInYear(year);
} else if (ordinal > yearInDays) {
year = weekYear + 1;
ordinal -= daysInYear(weekYear);
} else {
year = weekYear;
}
const {
month,
day
} = uncomputeOrdinal(year, ordinal);
return {
year,
month,
day,
...timeObject(weekData)
};
}
function gregorianToOrdinal(gregData) {
const {
year,
month,
day
} = gregData;
const ordinal = computeOrdinal(year, month, day);
return {
year,
ordinal,
...timeObject(gregData)
};
}
function ordinalToGregorian(ordinalData) {
const {
year,
ordinal
} = ordinalData;
const {
month,
day
} = uncomputeOrdinal(year, ordinal);
return {
year,
month,
day,
...timeObject(ordinalData)
};
}
function hasInvalidWeekData(obj) {
const validYear = isInteger(obj.weekYear), validWeek = integerBetween(obj.weekNumber, 1, weeksInWeekYear(obj.weekYear)), validWeekday = integerBetween(obj.weekday, 1, 7);
if (!validYear) {
return unitOutOfRange("weekYear", obj.weekYear);
} else if (!validWeek) {
return unitOutOfRange("week", obj.week);
} else if (!validWeekday) {
return unitOutOfRange("weekday", obj.weekday);
} else
return false;
}
function hasInvalidOrdinalData(obj) {
const validYear = isInteger(obj.year), validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year));
if (!validYear) {
return unitOutOfRange("year", obj.year);
} else if (!validOrdinal) {
return unitOutOfRange("ordinal", obj.ordinal);
} else
return false;
}
function hasInvalidGregorianData(obj) {
const validYear = isInteger(obj.year), validMonth = integerBetween(obj.month, 1, 12), validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month));
if (!validYear) {
return unitOutOfRange("year", obj.year);
} else if (!validMonth) {
return unitOutOfRange("month", obj.month);
} else if (!validDay) {
return unitOutOfRange("day", obj.day);
} else
return false;
}
function hasInvalidTimeData(obj) {
const {
hour,
minute,
second,
millisecond
} = obj;
const validHour = integerBetween(hour, 0, 23) || hour === 24 && minute === 0 && second === 0 && millisecond === 0, validMinute = integerBetween(minute, 0, 59), validSecond = integerBetween(second, 0, 59), validMillisecond = integerBetween(millisecond, 0, 999);
if (!validHour) {
return unitOutOfRange("hour", hour);
} else if (!validMinute) {
return unitOutOfRange("minute", minute);
} else if (!validSecond) {
return unitOutOfRange("second", second);
} else if (!validMillisecond) {
return unitOutOfRange("millisecond", millisecond);
} else
return false;
}
var INVALID = "Invalid DateTime";
var MAX_DATE = 864e13;
function unsupportedZone(zone) {
return new Invalid("unsupported zone", `the zone "${zone.name}" is not supported`);
}
function possiblyCachedWeekData(dt) {
if (dt.weekData === null) {
dt.weekData = gregorianToWeek(dt.c);
}
return dt.weekData;
}
function clone(inst, alts) {
const current = {
ts: inst.ts,
zone: inst.zone,
c: inst.c,
o: inst.o,
loc: inst.loc,
invalid: inst.invalid
};
return new DateTime({
...current,
...alts,
old: current
});
}
function fixOffset(localTS, o, tz) {
let utcGuess = localTS - o * 60 * 1e3;
const o2 = tz.offset(utcGuess);
if (o === o2) {
return [utcGuess, o];
}
utcGuess -= (o2 - o) * 60 * 1e3;
const o3 = tz.offset(utcGuess);
if (o2 === o3) {
return [utcGuess, o2];
}
return [localTS - Math.min(o2, o3) * 60 * 1e3, Math.max(o2, o3)];
}
function tsToObj(ts, offset3) {
ts += offset3 * 60 * 1e3;
const d = new Date(ts);
return {
year: d.getUTCFullYear(),
month: d.getUTCMonth() + 1,
day: d.getUTCDate(),
hour: d.getUTCHours(),
minute: d.getUTCMinutes(),
second: d.getUTCSeconds(),
millisecond: d.getUTCMilliseconds()
};
}
function objToTS(obj, offset3, zone) {
return fixOffset(objToLocalTS(obj), offset3, zone);
}
function adjustTime(inst, dur) {
const oPre = inst.o, year = inst.c.year + Math.trunc(dur.years), month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3, c = {
...inst.c,
year,
month,
day: Math.min(inst.c.day, daysInMonth(year, month)) + Math.trunc(dur.days) + Math.trunc(dur.weeks) * 7
}, millisToAdd = Duration.fromObject({
years: dur.years - Math.trunc(dur.years),
quarters: dur.quarters - Math.trunc(dur.quarters),
months: dur.months - Math.trunc(dur.months),
weeks: dur.weeks - Math.trunc(dur.weeks),
days: dur.days - Math.trunc(dur.days),
hours: dur.hours,
minutes: dur.minutes,
seconds: dur.seconds,
milliseconds: dur.milliseconds
}).as("milliseconds"), localTS = objToLocalTS(c);
let [ts, o] = fixOffset(localTS, oPre, inst.zone);
if (millisToAdd !== 0) {
ts += millisToAdd;
o = inst.zone.offset(ts);
}
return {
ts,
o
};
}
function parseDataToDateTime(parsed, parsedZone, opts, format2, text, specificOffset) {
const {
setZone,
zone
} = opts;
if (parsed && Object.keys(parsed).length !== 0 || parsedZone) {
const interpretationZone = parsedZone || zone, inst = DateTime.fromObject(parsed, {
...opts,
zone: interpretationZone,
specificOffset
});
return setZone ? inst : inst.setZone(zone);
} else {
return DateTime.invalid(new Invalid("unparsable", `the input "${text}" can't be parsed as ${format2}`));
}
}
function toTechFormat(dt, format2, allowZ = true) {
return dt.isValid ? Formatter.create(Locale.create("en-US"), {
allowZ,
forceSimple: true
}).formatDateTimeFromString(dt, format2) : null;
}
function toISODate(o, extended) {
const longFormat = o.c.year > 9999 || o.c.year < 0;
let c = "";
if (longFormat && o.c.year >= 0)
c += "+";
c += padStart(o.c.year, longFormat ? 6 : 4);
if (extended) {
c += "-";
c += padStart(o.c.month);
c += "-";
c += padStart(o.c.day);
} else {
c += padStart(o.c.month);
c += padStart(o.c.day);
}
return c;
}
function toISOTime(o, extended, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone) {
let c = padStart(o.c.hour);
if (extended) {
c += ":";
c += padStart(o.c.minute);
if (o.c.second !== 0 || !suppressSeconds) {
c += ":";
}
} else {
c += padStart(o.c.minute);
}
if (o.c.second !== 0 || !suppressSeconds) {
c += padStart(o.c.second);
if (o.c.millisecond !== 0 || !suppressMilliseconds) {
c += ".";
c += padStart(o.c.millisecond, 3);
}
}
if (includeOffset) {
if (o.isOffsetFixed && o.offset === 0 && !extendedZone) {
c += "Z";
} else if (o.o < 0) {
c += "-";
c += padStart(Math.trunc(-o.o / 60));
c += ":";
c += padStart(Math.trunc(-o.o % 60));
} else {
c += "+";
c += padStart(Math.trunc(o.o / 60));
c += ":";
c += padStart(Math.trunc(o.o % 60));
}
}
if (extendedZone) {
c += "[" + o.zone.ianaName + "]";
}
return c;
}
var defaultUnitValues = {
month: 1,
day: 1,
hour: 0,
minute: 0,
second: 0,
millisecond: 0
};
var defaultWeekUnitValues = {
weekNumber: 1,
weekday: 1,
hour: 0,
minute: 0,
second: 0,
millisecond: 0
};
var defaultOrdinalUnitValues = {
ordinal: 1,
hour: 0,
minute: 0,
second: 0,
millisecond: 0
};
var orderedUnits = ["year", "month", "day", "hour", "minute", "second", "millisecond"];
var orderedWeekUnits = ["weekYear", "weekNumber", "weekday", "hour", "minute", "second", "millisecond"];
var orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"];
function normalizeUnit(unit) {
const normalized = {
year: "year",
years: "year",
month: "month",
months: "month",
day: "day",
days: "day",
hour: "hour",
hours: "hour",
minute: "minute",
minutes: "minute",
quarter: "quarter",
quarters: "quarter",
second: "second",
seconds: "second",
millisecond: "millisecond",
milliseconds: "millisecond",
weekday: "weekday",
weekdays: "weekday",
weeknumber: "weekNumber",
weeksnumber: "weekNumber",
weeknumbers: "weekNumber",
weekyear: "weekYear",
weekyears: "weekYear",
ordinal: "ordinal"
}[unit.toLowerCase()];
if (!normalized)
throw new InvalidUnitError(unit);
return normalized;
}
function quickDT(obj, opts) {
const zone = normalizeZone(opts.zone, Settings.defaultZone), loc = Locale.fromObject(opts), tsNow = Settings.now();
let ts, o;
if (!isUndefined(obj.year)) {
for (const u of orderedUnits) {
if (isUndefined(obj[u])) {
obj[u] = defaultUnitValues[u];
}
}
const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);
if (invalid) {
return DateTime.invalid(invalid);
}
const offsetProvis = zone.offset(tsNow);
[ts, o] = objToTS(obj, offsetProvis, zone);
} else {
ts = tsNow;
}
return new DateTime({
ts,
zone,
loc,
o
});
}
function diffRelative(start2, end2, opts) {
const round2 = isUndefined(opts.round) ? true : opts.round, format2 = (c, unit) => {
c = roundTo(c, round2 || opts.calendary ? 0 : 2, true);
const formatter = end2.loc.clone(opts).relFormatter(opts);
return formatter.format(c, unit);
}, differ = (unit) => {
if (opts.calendary) {
if (!end2.hasSame(start2, unit)) {
return end2.startOf(unit).diff(start2.startOf(unit), unit).get(unit);
} else
return 0;
} else {
return end2.diff(start2, unit).get(unit);
}
};
if (opts.unit) {
return format2(differ(opts.unit), opts.unit);
}
for (const unit of opts.units) {
const count = differ(unit);
if (Math.abs(count) >= 1) {
return format2(count, unit);
}
}
return format2(start2 > end2 ? -0 : 0, opts.units[opts.units.length - 1]);
}
function lastOpts(argList) {
let opts = {}, args;
if (argList.length > 0 && typeof argList[argList.length - 1] === "object") {
opts = argList[argList.length - 1];
args = Array.from(argList).slice(0, argList.length - 1);
} else {
args = Array.from(argList);
}
return [opts, args];
}
var DateTime = class {
/**
* @access private
*/
constructor(config) {
const zone = config.zone || Settings.defaultZone;
let invalid = config.invalid || (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || (!zone.isValid ? unsupportedZone(zone) : null);
this.ts = isUndefined(config.ts) ? Settings.now() : config.ts;
let c = null, o = null;
if (!invalid) {
const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone);
if (unchanged) {
[c, o] = [config.old.c, config.old.o];
} else {
const ot = zone.offset(this.ts);
c = tsToObj(this.ts, ot);
invalid = Number.isNaN(c.year) ? new Invalid("invalid input") : null;
c = invalid ? null : c;
o = invalid ? null : ot;
}
}
this._zone = zone;
this.loc = config.loc || Locale.create();
this.invalid = invalid;
this.weekData = null;
this.c = c;
this.o = o;
this.isLuxonDateTime = true;
}
// CONSTRUCT
/**
* Create a DateTime for the current instant, in the system's time zone.
*
* Use Settings to override these default values if needed.
* @example DateTime.now().toISO() //~> now in the ISO format
* @return {DateTime}
*/
static now() {
return new DateTime({});
}
/**
* Create a local DateTime
* @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used
* @param {number} [month=1] - The month, 1-indexed
* @param {number} [day=1] - The day of the month, 1-indexed
* @param {number} [hour=0] - The hour of the day, in 24-hour time
* @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59
* @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59
* @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999
* @example DateTime.local() //~> now
* @example DateTime.local({ zone: "America/New_York" }) //~> now, in US east coast time
* @example DateTime.local(2017) //~> 2017-01-01T00:00:00
* @example DateTime.local(2017, 3) //~> 2017-03-01T00:00:00
* @example DateTime.local(2017, 3, 12, { locale: "fr" }) //~> 2017-03-12T00:00:00, with a French locale
* @example DateTime.local(2017, 3, 12, 5) //~> 2017-03-12T05:00:00
* @example DateTime.local(2017, 3, 12, 5, { zone: "utc" }) //~> 2017-03-12T05:00:00, in UTC
* @example DateTime.local(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00
* @example DateTime.local(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10
* @example DateTime.local(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765
* @return {DateTime}
*/
static local() {
const [opts, args] = lastOpts(arguments), [year, month, day, hour, minute, second, millisecond] = args;
return quickDT({
year,
month,
day,
hour,
minute,
second,
millisecond
}, opts);
}
/**
* Create a DateTime in UTC
* @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used
* @param {number} [month=1] - The month, 1-indexed
* @param {number} [day=1] - The day of the month
* @param {number} [hour=0] - The hour of the day, in 24-hour time
* @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59
* @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59
* @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999
* @param {Object} options - configuration options for the DateTime
* @param {string} [options.locale] - a locale to set on the resulting DateTime instance
* @param {string} [options.outputCalendar] - the output calendar to set on the resulting DateTime instance
* @param {string} [options.numberingSystem] - the numbering system to set on the resulting DateTime instance
* @example DateTime.utc() //~> now
* @example DateTime.utc(2017) //~> 2017-01-01T00:00:00Z
* @example DateTime.utc(2017, 3) //~> 2017-03-01T00:00:00Z
* @example DateTime.utc(2017, 3, 12) //~> 2017-03-12T00:00:00Z
* @example DateTime.utc(2017, 3, 12, 5) //~> 2017-03-12T05:00:00Z
* @example DateTime.utc(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00Z
* @example DateTime.utc(2017, 3, 12, 5, 45, { locale: "fr" }) //~> 2017-03-12T05:45:00Z with a French locale
* @example DateTime.utc(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10Z
* @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765, { locale: "fr" }) //~> 2017-03-12T05:45:10.765Z with a French locale
* @return {DateTime}
*/
static utc() {
const [opts, args] = lastOpts(arguments), [year, month, day, hour, minute, second, millisecond] = args;
opts.zone = FixedOffsetZone.utcInstance;
return quickDT({
year,
month,
day,
hour,
minute,
second,
millisecond
}, opts);
}
/**
* Create a DateTime from a JavaScript Date object. Uses the default zone.
* @param {Date} date - a JavaScript Date object
* @param {Object} options - configuration options for the DateTime
* @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
* @return {DateTime}
*/
static fromJSDate(date, options = {}) {
const ts = isDate(date) ? date.valueOf() : NaN;
if (Number.isNaN(ts)) {
return DateTime.invalid("invalid input");
}
const zoneToUse = normalizeZone(options.zone, Settings.defaultZone);
if (!zoneToUse.isValid) {
return DateTime.invalid(unsupportedZone(zoneToUse));
}
return new DateTime({
ts,
zone: zoneToUse,
loc: Locale.fromObject(options)
});
}
/**
* Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.
* @param {number} milliseconds - a number of milliseconds since 1970 UTC
* @param {Object} options - configuration options for the DateTime
* @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
* @param {string} [options.locale] - a locale to set on the resulting DateTime instance
* @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
* @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance
* @return {DateTime}
*/
static fromMillis(milliseconds, options = {}) {
if (!isNumber(milliseconds)) {
throw new InvalidArgumentError(`fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}`);
} else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) {
return DateTime.invalid("Timestamp out of range");
} else {
return new DateTime({
ts: milliseconds,
zone: normalizeZone(options.zone, Settings.defaultZone),
loc: Locale.fromObject(options)
});
}
}
/**
* Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.
* @param {number} seconds - a number of seconds since 1970 UTC
* @param {Object} options - configuration options for the DateTime
* @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
* @param {string} [options.locale] - a locale to set on the resulting DateTime instance
* @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
* @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance
* @return {DateTime}
*/
static fromSeconds(seconds, options = {}) {
if (!isNumber(seconds)) {
throw new InvalidArgumentError("fromSeconds requires a numerical input");
} else {
return new DateTime({
ts: seconds * 1e3,
zone: normalizeZone(options.zone, Settings.defaultZone),
loc: Locale.fromObject(options)
});
}
}
/**
* Create a DateTime from a JavaScript object with keys like 'year' and 'hour' with reasonable defaults.
* @param {Object} obj - the object to create the DateTime from
* @param {number} obj.year - a year, such as 1987
* @param {number} obj.month - a month, 1-12
* @param {number} obj.day - a day of the month, 1-31, depending on the month
* @param {number} obj.ordinal - day of the year, 1-365 or 366
* @param {number} obj.weekYear - an ISO week year
* @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year
* @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday
* @param {number} obj.hour - hour of the day, 0-23
* @param {number} obj.minute - minute of the hour, 0-59
* @param {number} obj.second - second of the minute, 0-59
* @param {number} obj.millisecond - millisecond of the second, 0-999
* @param {Object} opts - options for creating this DateTime
* @param {string|Zone} [opts.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone()
* @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
* @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
* @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
* @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25'
* @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01'
* @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06
* @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'utc' }),
* @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'local' })
* @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'America/New_York' })
* @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13'
* @return {DateTime}
*/
static fromObject(obj, opts = {}) {
obj = obj || {};
const zoneToUse = normalizeZone(opts.zone, Settings.defaultZone);
if (!zoneToUse.isValid) {
return DateTime.invalid(unsupportedZone(zoneToUse));
}
const tsNow = Settings.now(), offsetProvis = !isUndefined(opts.specificOffset) ? opts.specificOffset : zoneToUse.offset(tsNow), normalized = normalizeObject(obj, normalizeUnit), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber, loc = Locale.fromObject(opts);
if ((containsGregor || containsOrdinal) && definiteWeekDef) {
throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals");
}
if (containsGregorMD && containsOrdinal) {
throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");
}
const useWeekData = definiteWeekDef || normalized.weekday && !containsGregor;
let units, defaultValues, objNow = tsToObj(tsNow, offsetProvis);
if (useWeekData) {
units = orderedWeekUnits;
defaultValues = defaultWeekUnitValues;
objNow = gregorianToWeek(objNow);
} else if (containsOrdinal) {
units = orderedOrdinalUnits;
defaultValues = defaultOrdinalUnitValues;
objNow = gregorianToOrdinal(objNow);
} else {
units = orderedUnits;
defaultValues = defaultUnitValues;
}
let foundFirst = false;
for (const u of units) {
const v = normalized[u];
if (!isUndefined(v)) {
foundFirst = true;
} else if (foundFirst) {
normalized[u] = defaultValues[u];
} else {
normalized[u] = objNow[u];
}
}
const higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized), invalid = higherOrderInvalid || hasInvalidTimeData(normalized);
if (invalid) {
return DateTime.invalid(invalid);
}
const gregorian = useWeekData ? weekToGregorian(normalized) : containsOrdinal ? ordinalToGregorian(normalized) : normalized, [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse), inst = new DateTime({
ts: tsFinal,
zone: zoneToUse,
o: offsetFinal,
loc
});
if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) {
return DateTime.invalid("mismatched weekday", `you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}`);
}
return inst;
}
/**
* Create a DateTime from an ISO 8601 string
* @param {string} text - the ISO string
* @param {Object} opts - options to affect the creation
* @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone
* @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
* @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
* @param {string} [opts.outputCalendar] - the output calendar to set on the resulting DateTime instance
* @param {string} [opts.numberingSystem] - the numbering system to set on the resulting DateTime instance
* @example DateTime.fromISO('2016-05-25T09:08:34.123')
* @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00')
* @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true})
* @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'})
* @example DateTime.fromISO('2016-W05-4')
* @return {DateTime}
*/
static fromISO(text, opts = {}) {
const [vals, parsedZone] = parseISODate(text);
return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text);
}
/**
* Create a DateTime from an RFC 2822 string
* @param {string} text - the RFC 2822 string
* @param {Object} opts - options to affect the creation
* @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.
* @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
* @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
* @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
* @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
* @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT')
* @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600')
* @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z')
* @return {DateTime}
*/
static fromRFC2822(text, opts = {}) {
const [vals, parsedZone] = parseRFC2822Date(text);
return parseDataToDateTime(vals, parsedZone, opts, "RFC 2822", text);
}
/**
* Create a DateTime from an HTTP header date
* @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
* @param {string} text - the HTTP header date
* @param {Object} opts - options to affect the creation
* @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.
* @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods.
* @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
* @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
* @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
* @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT')
* @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT')
* @example DateTime.fromHTTP('Sun Nov 6 08:49:37 1994')
* @return {DateTime}
*/
static fromHTTP(text, opts = {}) {
const [vals, parsedZone] = parseHTTPDate(text);
return parseDataToDateTime(vals, parsedZone, opts, "HTTP", opts);
}
/**
* Create a DateTime from an input string and format string.
* Defaults to en-US if no locale has been specified, regardless of the system's locale. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/parsing?id=table-of-tokens).
* @param {string} text - the string to parse
* @param {string} fmt - the format the string is expected to be in (see the link below for the formats)
* @param {Object} opts - options to affect the creation
* @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone
* @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one
* @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale
* @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system
* @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
* @return {DateTime}
*/
static fromFormat(text, fmt, opts = {}) {
if (isUndefined(text) || isUndefined(fmt)) {
throw new InvalidArgumentError("fromFormat requires an input string and a format");
}
const {
locale = null,
numberingSystem = null
} = opts, localeToUse = Locale.fromOpts({
locale,
numberingSystem,
defaultToEN: true
}), [vals, parsedZone, specificOffset, invalid] = parseFromTokens(localeToUse, text, fmt);
if (invalid) {
return DateTime.invalid(invalid);
} else {
return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text, specificOffset);
}
}
/**
* @deprecated use fromFormat instead
*/
static fromString(text, fmt, opts = {}) {
return DateTime.fromFormat(text, fmt, opts);
}
/**
* Create a DateTime from a SQL date, time, or datetime
* Defaults to en-US if no locale has been specified, regardless of the system's locale
* @param {string} text - the string to parse
* @param {Object} opts - options to affect the creation
* @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone
* @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one
* @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale
* @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system
* @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
* @example DateTime.fromSQL('2017-05-15')
* @example DateTime.fromSQL('2017-05-15 09:12:34')
* @example DateTime.fromSQL('2017-05-15 09:12:34.342')
* @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00')
* @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles')
* @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true })
* @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' })
* @example DateTime.fromSQL('09:12:34.342')
* @return {DateTime}
*/
static fromSQL(text, opts = {}) {
const [vals, parsedZone] = parseSQL(text);
return parseDataToDateTime(vals, parsedZone, opts, "SQL", text);
}
/**
* Create an invalid DateTime.
* @param {DateTime} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent
* @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
* @return {DateTime}
*/
static invalid(reason, explanation = null) {
if (!reason) {
throw new InvalidArgumentError("need to specify a reason the DateTime is invalid");
}
const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
if (Settings.throwOnInvalid) {
throw new InvalidDateTimeError(invalid);
} else {
return new DateTime({
invalid
});
}
}
/**
* Check if an object is an instance of DateTime. Works across context boundaries
* @param {object} o
* @return {boolean}
*/
static isDateTime(o) {
return o && o.isLuxonDateTime || false;
}
/**
* Produce the format string for a set of options
* @param formatOpts
* @param localeOpts
* @returns {string}
*/
static parseFormatForOpts(formatOpts, localeOpts = {}) {
const tokenList = formatOptsToTokens(formatOpts, Locale.fromObject(localeOpts));
return !tokenList ? null : tokenList.map((t) => t ? t.val : null).join("");
}
/**
* Produce the the fully expanded format token for the locale
* Does NOT quote characters, so quoted tokens will not round trip correctly
* @param fmt
* @param localeOpts
* @returns {string}
*/
static expandFormat(fmt, localeOpts = {}) {
const expanded = expandMacroTokens(Formatter.parseFormat(fmt), Locale.fromObject(localeOpts));
return expanded.map((t) => t.val).join("");
}
// INFO
/**
* Get the value of unit.
* @param {string} unit - a unit such as 'minute' or 'day'
* @example DateTime.local(2017, 7, 4).get('month'); //=> 7
* @example DateTime.local(2017, 7, 4).get('day'); //=> 4
* @return {number}
*/
get(unit) {
return this[unit];
}
/**
* Returns whether the DateTime is valid. Invalid DateTimes occur when:
* * The DateTime was created from invalid calendar information, such as the 13th month or February 30
* * The DateTime was created by an operation on another invalid date
* @type {boolean}
*/
get isValid() {
return this.invalid === null;
}
/**
* Returns an error code if this DateTime is invalid, or null if the DateTime is valid
* @type {string}
*/
get invalidReason() {
return this.invalid ? this.invalid.reason : null;
}
/**
* Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid
* @type {string}
*/
get invalidExplanation() {
return this.invalid ? this.invalid.explanation : null;
}
/**
* Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime
*
* @type {string}
*/
get locale() {
return this.isValid ? this.loc.locale : null;
}
/**
* Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime
*
* @type {string}
*/
get numberingSystem() {
return this.isValid ? this.loc.numberingSystem : null;
}
/**
* Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime
*
* @type {string}
*/
get outputCalendar() {
return this.isValid ? this.loc.outputCalendar : null;
}
/**
* Get the time zone associated with this DateTime.
* @type {Zone}
*/
get zone() {
return this._zone;
}
/**
* Get the name of the time zone.
* @type {string}
*/
get zoneName() {
return this.isValid ? this.zone.name : null;
}
/**
* Get the year
* @example DateTime.local(2017, 5, 25).year //=> 2017
* @type {number}
*/
get year() {
return this.isValid ? this.c.year : NaN;
}
/**
* Get the quarter
* @example DateTime.local(2017, 5, 25).quarter //=> 2
* @type {number}
*/
get quarter() {
return this.isValid ? Math.ceil(this.c.month / 3) : NaN;
}
/**
* Get the month (1-12).
* @example DateTime.local(2017, 5, 25).month //=> 5
* @type {number}
*/
get month() {
return this.isValid ? this.c.month : NaN;
}
/**
* Get the day of the month (1-30ish).
* @example DateTime.local(2017, 5, 25).day //=> 25
* @type {number}
*/
get day() {
return this.isValid ? this.c.day : NaN;
}
/**
* Get the hour of the day (0-23).
* @example DateTime.local(2017, 5, 25, 9).hour //=> 9
* @type {number}
*/
get hour() {
return this.isValid ? this.c.hour : NaN;
}
/**
* Get the minute of the hour (0-59).
* @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30
* @type {number}
*/
get minute() {
return this.isValid ? this.c.minute : NaN;
}
/**
* Get the second of the minute (0-59).
* @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52
* @type {number}
*/
get second() {
return this.isValid ? this.c.second : NaN;
}
/**
* Get the millisecond of the second (0-999).
* @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654
* @type {number}
*/
get millisecond() {
return this.isValid ? this.c.millisecond : NaN;
}
/**
* Get the week year
* @see https://en.wikipedia.org/wiki/ISO_week_date
* @example DateTime.local(2014, 12, 31).weekYear //=> 2015
* @type {number}
*/
get weekYear() {
return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN;
}
/**
* Get the week number of the week year (1-52ish).
* @see https://en.wikipedia.org/wiki/ISO_week_date
* @example DateTime.local(2017, 5, 25).weekNumber //=> 21
* @type {number}
*/
get weekNumber() {
return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN;
}
/**
* Get the day of the week.
* 1 is Monday and 7 is Sunday
* @see https://en.wikipedia.org/wiki/ISO_week_date
* @example DateTime.local(2014, 11, 31).weekday //=> 4
* @type {number}
*/
get weekday() {
return this.isValid ? possiblyCachedWeekData(this).weekday : NaN;
}
/**
* Get the ordinal (meaning the day of the year)
* @example DateTime.local(2017, 5, 25).ordinal //=> 145
* @type {number|DateTime}
*/
get ordinal() {
return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN;
}
/**
* Get the human readable short month name, such as 'Oct'.
* Defaults to the system's locale if no locale has been specified
* @example DateTime.local(2017, 10, 30).monthShort //=> Oct
* @type {string}
*/
get monthShort() {
return this.isValid ? Info.months("short", {
locObj: this.loc
})[this.month - 1] : null;
}
/**
* Get the human readable long month name, such as 'October'.
* Defaults to the system's locale if no locale has been specified
* @example DateTime.local(2017, 10, 30).monthLong //=> October
* @type {string}
*/
get monthLong() {
return this.isValid ? Info.months("long", {
locObj: this.loc
})[this.month - 1] : null;
}
/**
* Get the human readable short weekday, such as 'Mon'.
* Defaults to the system's locale if no locale has been specified
* @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon
* @type {string}
*/
get weekdayShort() {
return this.isValid ? Info.weekdays("short", {
locObj: this.loc
})[this.weekday - 1] : null;
}
/**
* Get the human readable long weekday, such as 'Monday'.
* Defaults to the system's locale if no locale has been specified
* @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday
* @type {string}
*/
get weekdayLong() {
return this.isValid ? Info.weekdays("long", {
locObj: this.loc
})[this.weekday - 1] : null;
}
/**
* Get the UTC offset of this DateTime in minutes
* @example DateTime.now().offset //=> -240
* @example DateTime.utc().offset //=> 0
* @type {number}
*/
get offset() {
return this.isValid ? +this.o : NaN;
}
/**
* Get the short human name for the zone's current offset, for example "EST" or "EDT".
* Defaults to the system's locale if no locale has been specified
* @type {string}
*/
get offsetNameShort() {
if (this.isValid) {
return this.zone.offsetName(this.ts, {
format: "short",
locale: this.locale
});
} else {
return null;
}
}
/**
* Get the long human name for the zone's current offset, for example "Eastern Standard Time" or "Eastern Daylight Time".
* Defaults to the system's locale if no locale has been specified
* @type {string}
*/
get offsetNameLong() {
if (this.isValid) {
return this.zone.offsetName(this.ts, {
format: "long",
locale: this.locale
});
} else {
return null;
}
}
/**
* Get whether this zone's offset ever changes, as in a DST.
* @type {boolean}
*/
get isOffsetFixed() {
return this.isValid ? this.zone.isUniversal : null;
}
/**
* Get whether the DateTime is in a DST.
* @type {boolean}
*/
get isInDST() {
if (this.isOffsetFixed) {
return false;
} else {
return this.offset > this.set({
month: 1,
day: 1
}).offset || this.offset > this.set({
month: 5
}).offset;
}
}
/**
* Returns true if this DateTime is in a leap year, false otherwise
* @example DateTime.local(2016).isInLeapYear //=> true
* @example DateTime.local(2013).isInLeapYear //=> false
* @type {boolean}
*/
get isInLeapYear() {
return isLeapYear(this.year);
}
/**
* Returns the number of days in this DateTime's month
* @example DateTime.local(2016, 2).daysInMonth //=> 29
* @example DateTime.local(2016, 3).daysInMonth //=> 31
* @type {number}
*/
get daysInMonth() {
return daysInMonth(this.year, this.month);
}
/**
* Returns the number of days in this DateTime's year
* @example DateTime.local(2016).daysInYear //=> 366
* @example DateTime.local(2013).daysInYear //=> 365
* @type {number}
*/
get daysInYear() {
return this.isValid ? daysInYear(this.year) : NaN;
}
/**
* Returns the number of weeks in this DateTime's year
* @see https://en.wikipedia.org/wiki/ISO_week_date
* @example DateTime.local(2004).weeksInWeekYear //=> 53
* @example DateTime.local(2013).weeksInWeekYear //=> 52
* @type {number}
*/
get weeksInWeekYear() {
return this.isValid ? weeksInWeekYear(this.weekYear) : NaN;
}
/**
* Returns the resolved Intl options for this DateTime.
* This is useful in understanding the behavior of formatting methods
* @param {Object} opts - the same options as toLocaleString
* @return {Object}
*/
resolvedLocaleOptions(opts = {}) {
const {
locale,
numberingSystem,
calendar
} = Formatter.create(this.loc.clone(opts), opts).resolvedOptions(this);
return {
locale,
numberingSystem,
outputCalendar: calendar
};
}
// TRANSFORM
/**
* "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime.
*
* Equivalent to {@link DateTime#setZone}('utc')
* @param {number} [offset=0] - optionally, an offset from UTC in minutes
* @param {Object} [opts={}] - options to pass to `setZone()`
* @return {DateTime}
*/
toUTC(offset3 = 0, opts = {}) {
return this.setZone(FixedOffsetZone.instance(offset3), opts);
}
/**
* "Set" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime.
*
* Equivalent to `setZone('local')`
* @return {DateTime}
*/
toLocal() {
return this.setZone(Settings.defaultZone);
}
/**
* "Set" the DateTime's zone to specified zone. Returns a newly-constructed DateTime.
*
* By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link DateTime#plus}. You may wish to use {@link DateTime#toLocal} and {@link DateTime#toUTC} which provide simple convenience wrappers for commonly used zones.
* @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link DateTime#Zone} class.
* @param {Object} opts - options
* @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this.
* @return {DateTime}
*/
setZone(zone, {
keepLocalTime = false,
keepCalendarTime = false
} = {}) {
zone = normalizeZone(zone, Settings.defaultZone);
if (zone.equals(this.zone)) {
return this;
} else if (!zone.isValid) {
return DateTime.invalid(unsupportedZone(zone));
} else {
let newTS = this.ts;
if (keepLocalTime || keepCalendarTime) {
const offsetGuess = zone.offset(this.ts);
const asObj = this.toObject();
[newTS] = objToTS(asObj, offsetGuess, zone);
}
return clone(this, {
ts: newTS,
zone
});
}
}
/**
* "Set" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime.
* @param {Object} properties - the properties to set
* @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' })
* @return {DateTime}
*/
reconfigure({
locale,
numberingSystem,
outputCalendar
} = {}) {
const loc = this.loc.clone({
locale,
numberingSystem,
outputCalendar
});
return clone(this, {
loc
});
}
/**
* "Set" the locale. Returns a newly-constructed DateTime.
* Just a convenient alias for reconfigure({ locale })
* @example DateTime.local(2017, 5, 25).setLocale('en-GB')
* @return {DateTime}
*/
setLocale(locale) {
return this.reconfigure({
locale
});
}
/**
* "Set" the values of specified units. Returns a newly-constructed DateTime.
* You can only set units with this method; for "setting" metadata, see {@link DateTime#reconfigure} and {@link DateTime#setZone}.
* @param {Object} values - a mapping of units to numbers
* @example dt.set({ year: 2017 })
* @example dt.set({ hour: 8, minute: 30 })
* @example dt.set({ weekday: 5 })
* @example dt.set({ year: 2005, ordinal: 234 })
* @return {DateTime}
*/
set(values) {
if (!this.isValid)
return this;
const normalized = normalizeObject(values, normalizeUnit), settingWeekStuff = !isUndefined(normalized.weekYear) || !isUndefined(normalized.weekNumber) || !isUndefined(normalized.weekday), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber;
if ((containsGregor || containsOrdinal) && definiteWeekDef) {
throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals");
}
if (containsGregorMD && containsOrdinal) {
throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");
}
let mixed;
if (settingWeekStuff) {
mixed = weekToGregorian({
...gregorianToWeek(this.c),
...normalized
});
} else if (!isUndefined(normalized.ordinal)) {
mixed = ordinalToGregorian({
...gregorianToOrdinal(this.c),
...normalized
});
} else {
mixed = {
...this.toObject(),
...normalized
};
if (isUndefined(normalized.day)) {
mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day);
}
}
const [ts, o] = objToTS(mixed, this.o, this.zone);
return clone(this, {
ts,
o
});
}
/**
* Add a period of time to this DateTime and return the resulting DateTime
*
* Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between.
* @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
* @example DateTime.now().plus(123) //~> in 123 milliseconds
* @example DateTime.now().plus({ minutes: 15 }) //~> in 15 minutes
* @example DateTime.now().plus({ days: 1 }) //~> this time tomorrow
* @example DateTime.now().plus({ days: -1 }) //~> this time yesterday
* @example DateTime.now().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min
* @example DateTime.now().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min
* @return {DateTime}
*/
plus(duration) {
if (!this.isValid)
return this;
const dur = Duration.fromDurationLike(duration);
return clone(this, adjustTime(this, dur));
}
/**
* Subtract a period of time to this DateTime and return the resulting DateTime
* See {@link DateTime#plus}
* @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
@return {DateTime}
*/
minus(duration) {
if (!this.isValid)
return this;
const dur = Duration.fromDurationLike(duration).negate();
return clone(this, adjustTime(this, dur));
}
/**
* "Set" this DateTime to the beginning of a unit of time.
* @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.
* @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01'
* @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01'
* @example DateTime.local(2014, 3, 3).startOf('week').toISODate(); //=> '2014-03-03', weeks always start on Mondays
* @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00'
* @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00'
* @return {DateTime}
*/
startOf(unit) {
if (!this.isValid)
return this;
const o = {}, normalizedUnit = Duration.normalizeUnit(unit);
switch (normalizedUnit) {
case "years":
o.month = 1;
case "quarters":
case "months":
o.day = 1;
case "weeks":
case "days":
o.hour = 0;
case "hours":
o.minute = 0;
case "minutes":
o.second = 0;
case "seconds":
o.millisecond = 0;
break;
}
if (normalizedUnit === "weeks") {
o.weekday = 1;
}
if (normalizedUnit === "quarters") {
const q = Math.ceil(this.month / 3);
o.month = (q - 1) * 3 + 1;
}
return this.set(o);
}
/**
* "Set" this DateTime to the end (meaning the last millisecond) of a unit of time
* @param {string} unit - The unit to go to the end of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.
* @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00'
* @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00'
* @example DateTime.local(2014, 3, 3).endOf('week').toISO(); // => '2014-03-09T23:59:59.999-05:00', weeks start on Mondays
* @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00'
* @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00'
* @return {DateTime}
*/
endOf(unit) {
return this.isValid ? this.plus({
[unit]: 1
}).startOf(unit).minus(1) : this;
}
// OUTPUT
/**
* Returns a string representation of this DateTime formatted according to the specified format string.
* **You may not want this.** See {@link DateTime#toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/formatting?id=table-of-tokens).
* Defaults to en-US if no locale has been specified, regardless of the system's locale.
* @param {string} fmt - the format string
* @param {Object} opts - opts to override the configuration options on this DateTime
* @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22'
* @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22'
* @example DateTime.now().toFormat('yyyy LLL dd', { locale: "fr" }) //=> '2017 avr. 22'
* @example DateTime.now().toFormat("HH 'hours and' mm 'minutes'") //=> '20 hours and 55 minutes'
* @return {string}
*/
toFormat(fmt, opts = {}) {
return this.isValid ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) : INVALID;
}
/**
* Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`.
* The exact behavior of this method is browser-specific, but in general it will return an appropriate representation
* of the DateTime in the assigned locale.
* Defaults to the system's locale if no locale has been specified
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
* @param formatOpts {Object} - Intl.DateTimeFormat constructor options and configuration options
* @param {Object} opts - opts to override the configuration options on this DateTime
* @example DateTime.now().toLocaleString(); //=> 4/20/2017
* @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017'
* @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017'
* @example DateTime.now().toLocaleString(DateTime.DATE_FULL, { locale: 'fr' }); //=> '28 août 2022'
* @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM'
* @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM'
* @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20'
* @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM'
* @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); //=> '11:32'
* @return {string}
*/
toLocaleString(formatOpts = DATE_SHORT, opts = {}) {
return this.isValid ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this) : INVALID;
}
/**
* Returns an array of format "parts", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output.
* Defaults to the system's locale if no locale has been specified
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts
* @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`.
* @example DateTime.now().toLocaleParts(); //=> [
* //=> { type: 'day', value: '25' },
* //=> { type: 'literal', value: '/' },
* //=> { type: 'month', value: '05' },
* //=> { type: 'literal', value: '/' },
* //=> { type: 'year', value: '1982' }
* //=> ]
*/
toLocaleParts(opts = {}) {
return this.isValid ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this) : [];
}
/**
* Returns an ISO 8601-compliant string representation of this DateTime
* @param {Object} opts - options
* @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
* @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
* @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
* @param {boolean} [opts.extendedZone=false] - add the time zone format extension
* @param {string} [opts.format='extended'] - choose between the basic and extended format
* @example DateTime.utc(1983, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z'
* @example DateTime.now().toISO() //=> '2017-04-22T20:47:05.335-04:00'
* @example DateTime.now().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335'
* @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400'
* @return {string}
*/
toISO({
format: format2 = "extended",
suppressSeconds = false,
suppressMilliseconds = false,
includeOffset = true,
extendedZone = false
} = {}) {
if (!this.isValid) {
return null;
}
const ext = format2 === "extended";
let c = toISODate(this, ext);
c += "T";
c += toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone);
return c;
}
/**
* Returns an ISO 8601-compliant string representation of this DateTime's date component
* @param {Object} opts - options
* @param {string} [opts.format='extended'] - choose between the basic and extended format
* @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25'
* @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525'
* @return {string}
*/
toISODate({
format: format2 = "extended"
} = {}) {
if (!this.isValid) {
return null;
}
return toISODate(this, format2 === "extended");
}
/**
* Returns an ISO 8601-compliant string representation of this DateTime's week date
* @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2'
* @return {string}
*/
toISOWeekDate() {
return toTechFormat(this, "kkkk-'W'WW-c");
}
/**
* Returns an ISO 8601-compliant string representation of this DateTime's time component
* @param {Object} opts - options
* @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
* @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
* @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
* @param {boolean} [opts.extendedZone=true] - add the time zone format extension
* @param {boolean} [opts.includePrefix=false] - include the `T` prefix
* @param {string} [opts.format='extended'] - choose between the basic and extended format
* @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z'
* @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z'
* @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z'
* @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z'
* @return {string}
*/
toISOTime({
suppressMilliseconds = false,
suppressSeconds = false,
includeOffset = true,
includePrefix = false,
extendedZone = false,
format: format2 = "extended"
} = {}) {
if (!this.isValid) {
return null;
}
let c = includePrefix ? "T" : "";
return c + toISOTime(this, format2 === "extended", suppressSeconds, suppressMilliseconds, includeOffset, extendedZone);
}
/**
* Returns an RFC 2822-compatible string representation of this DateTime
* @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000'
* @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400'
* @return {string}
*/
toRFC2822() {
return toTechFormat(this, "EEE, dd LLL yyyy HH:mm:ss ZZZ", false);
}
/**
* Returns a string representation of this DateTime appropriate for use in HTTP headers. The output is always expressed in GMT.
* Specifically, the string conforms to RFC 1123.
* @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
* @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT'
* @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT'
* @return {string}
*/
toHTTP() {
return toTechFormat(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'");
}
/**
* Returns a string representation of this DateTime appropriate for use in SQL Date
* @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13'
* @return {string}
*/
toSQLDate() {
if (!this.isValid) {
return null;
}
return toISODate(this, true);
}
/**
* Returns a string representation of this DateTime appropriate for use in SQL Time
* @param {Object} opts - options
* @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.
* @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
* @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'
* @example DateTime.utc().toSQL() //=> '05:15:16.345'
* @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00'
* @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345'
* @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York'
* @return {string}
*/
toSQLTime({
includeOffset = true,
includeZone = false,
includeOffsetSpace = true
} = {}) {
let fmt = "HH:mm:ss.SSS";
if (includeZone || includeOffset) {
if (includeOffsetSpace) {
fmt += " ";
}
if (includeZone) {
fmt += "z";
} else if (includeOffset) {
fmt += "ZZ";
}
}
return toTechFormat(this, fmt, true);
}
/**
* Returns a string representation of this DateTime appropriate for use in SQL DateTime
* @param {Object} opts - options
* @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.
* @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
* @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'
* @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z'
* @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00'
* @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000'
* @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York'
* @return {string}
*/
toSQL(opts = {}) {
if (!this.isValid) {
return null;
}
return `${this.toSQLDate()} ${this.toSQLTime(opts)}`;
}
/**
* Returns a string representation of this DateTime appropriate for debugging
* @return {string}
*/
toString() {
return this.isValid ? this.toISO() : INVALID;
}
/**
* Returns the epoch milliseconds of this DateTime. Alias of {@link DateTime#toMillis}
* @return {number}
*/
valueOf() {
return this.toMillis();
}
/**
* Returns the epoch milliseconds of this DateTime.
* @return {number}
*/
toMillis() {
return this.isValid ? this.ts : NaN;
}
/**
* Returns the epoch seconds of this DateTime.
* @return {number}
*/
toSeconds() {
return this.isValid ? this.ts / 1e3 : NaN;
}
/**
* Returns the epoch seconds (as a whole number) of this DateTime.
* @return {number}
*/
toUnixInteger() {
return this.isValid ? Math.floor(this.ts / 1e3) : NaN;
}
/**
* Returns an ISO 8601 representation of this DateTime appropriate for use in JSON.
* @return {string}
*/
toJSON() {
return this.toISO();
}
/**
* Returns a BSON serializable equivalent to this DateTime.
* @return {Date}
*/
toBSON() {
return this.toJSDate();
}
/**
* Returns a JavaScript object with this DateTime's year, month, day, and so on.
* @param opts - options for generating the object
* @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output
* @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 }
* @return {Object}
*/
toObject(opts = {}) {
if (!this.isValid)
return {};
const base = {
...this.c
};
if (opts.includeConfig) {
base.outputCalendar = this.outputCalendar;
base.numberingSystem = this.loc.numberingSystem;
base.locale = this.loc.locale;
}
return base;
}
/**
* Returns a JavaScript Date equivalent to this DateTime.
* @return {Date}
*/
toJSDate() {
return new Date(this.isValid ? this.ts : NaN);
}
// COMPARE
/**
* Return the difference between two DateTimes as a Duration.
* @param {DateTime} otherDateTime - the DateTime to compare this one to
* @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration.
* @param {Object} opts - options that affect the creation of the Duration
* @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
* @example
* var i1 = DateTime.fromISO('1982-05-25T09:45'),
* i2 = DateTime.fromISO('1983-10-14T10:30');
* i2.diff(i1).toObject() //=> { milliseconds: 43807500000 }
* i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 }
* i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 }
* i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 }
* @return {Duration}
*/
diff(otherDateTime, unit = "milliseconds", opts = {}) {
if (!this.isValid || !otherDateTime.isValid) {
return Duration.invalid("created by diffing an invalid DateTime");
}
const durOpts = {
locale: this.locale,
numberingSystem: this.numberingSystem,
...opts
};
const units = maybeArray(unit).map(Duration.normalizeUnit), otherIsLater = otherDateTime.valueOf() > this.valueOf(), earlier = otherIsLater ? this : otherDateTime, later = otherIsLater ? otherDateTime : this, diffed = diff(earlier, later, units, durOpts);
return otherIsLater ? diffed.negate() : diffed;
}
/**
* Return the difference between this DateTime and right now.
* See {@link DateTime#diff}
* @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration
* @param {Object} opts - options that affect the creation of the Duration
* @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
* @return {Duration}
*/
diffNow(unit = "milliseconds", opts = {}) {
return this.diff(DateTime.now(), unit, opts);
}
/**
* Return an Interval spanning between this DateTime and another DateTime
* @param {DateTime} otherDateTime - the other end point of the Interval
* @return {Interval}
*/
until(otherDateTime) {
return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this;
}
/**
* Return whether this DateTime is in the same unit of time as another DateTime.
* Higher-order units must also be identical for this function to return `true`.
* Note that time zones are **ignored** in this comparison, which compares the **local** calendar time. Use {@link DateTime#setZone} to convert one of the dates if needed.
* @param {DateTime} otherDateTime - the other DateTime
* @param {string} unit - the unit of time to check sameness on
* @example DateTime.now().hasSame(otherDT, 'day'); //~> true if otherDT is in the same current calendar day
* @return {boolean}
*/
hasSame(otherDateTime, unit) {
if (!this.isValid)
return false;
const inputMs = otherDateTime.valueOf();
const adjustedToZone = this.setZone(otherDateTime.zone, {
keepLocalTime: true
});
return adjustedToZone.startOf(unit) <= inputMs && inputMs <= adjustedToZone.endOf(unit);
}
/**
* Equality check
* Two DateTimes are equal if and only if they represent the same millisecond, have the same zone and location, and are both valid.
* To compare just the millisecond values, use `+dt1 === +dt2`.
* @param {DateTime} other - the other DateTime
* @return {boolean}
*/
equals(other) {
return this.isValid && other.isValid && this.valueOf() === other.valueOf() && this.zone.equals(other.zone) && this.loc.equals(other.loc);
}
/**
* Returns a string representation of a this time relative to now, such as "in two days". Can only internationalize if your
* platform supports Intl.RelativeTimeFormat. Rounds down by default.
* @param {Object} options - options that affect the output
* @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.
* @param {string} [options.style="long"] - the style of units, must be "long", "short", or "narrow"
* @param {string|string[]} options.unit - use a specific unit or array of units; if omitted, or an array, the method will pick the best unit. Use an array or one of "years", "quarters", "months", "weeks", "days", "hours", "minutes", or "seconds"
* @param {boolean} [options.round=true] - whether to round the numbers in the output.
* @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding.
* @param {string} options.locale - override the locale of this DateTime
* @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this
* @example DateTime.now().plus({ days: 1 }).toRelative() //=> "in 1 day"
* @example DateTime.now().setLocale("es").toRelative({ days: 1 }) //=> "dentro de 1 día"
* @example DateTime.now().plus({ days: 1 }).toRelative({ locale: "fr" }) //=> "dans 23 heures"
* @example DateTime.now().minus({ days: 2 }).toRelative() //=> "2 days ago"
* @example DateTime.now().minus({ days: 2 }).toRelative({ unit: "hours" }) //=> "48 hours ago"
* @example DateTime.now().minus({ hours: 36 }).toRelative({ round: false }) //=> "1.5 days ago"
*/
toRelative(options = {}) {
if (!this.isValid)
return null;
const base = options.base || DateTime.fromObject({}, {
zone: this.zone
}), padding = options.padding ? this < base ? -options.padding : options.padding : 0;
let units = ["years", "months", "days", "hours", "minutes", "seconds"];
let unit = options.unit;
if (Array.isArray(options.unit)) {
units = options.unit;
unit = void 0;
}
return diffRelative(base, this.plus(padding), {
...options,
numeric: "always",
units,
unit
});
}
/**
* Returns a string representation of this date relative to today, such as "yesterday" or "next month".
* Only internationalizes on platforms that supports Intl.RelativeTimeFormat.
* @param {Object} options - options that affect the output
* @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.
* @param {string} options.locale - override the locale of this DateTime
* @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of "years", "quarters", "months", "weeks", or "days"
* @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this
* @example DateTime.now().plus({ days: 1 }).toRelativeCalendar() //=> "tomorrow"
* @example DateTime.now().setLocale("es").plus({ days: 1 }).toRelative() //=> ""mañana"
* @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: "fr" }) //=> "demain"
* @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> "2 days ago"
*/
toRelativeCalendar(options = {}) {
if (!this.isValid)
return null;
return diffRelative(options.base || DateTime.fromObject({}, {
zone: this.zone
}), this, {
...options,
numeric: "auto",
units: ["years", "months", "days"],
calendary: true
});
}
/**
* Return the min of several date times
* @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum
* @return {DateTime} the min DateTime, or undefined if called with no argument
*/
static min(...dateTimes) {
if (!dateTimes.every(DateTime.isDateTime)) {
throw new InvalidArgumentError("min requires all arguments be DateTimes");
}
return bestBy(dateTimes, (i) => i.valueOf(), Math.min);
}
/**
* Return the max of several date times
* @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum
* @return {DateTime} the max DateTime, or undefined if called with no argument
*/
static max(...dateTimes) {
if (!dateTimes.every(DateTime.isDateTime)) {
throw new InvalidArgumentError("max requires all arguments be DateTimes");
}
return bestBy(dateTimes, (i) => i.valueOf(), Math.max);
}
// MISC
/**
* Explain how a string would be parsed by fromFormat()
* @param {string} text - the string to parse
* @param {string} fmt - the format the string is expected to be in (see description)
* @param {Object} options - options taken by fromFormat()
* @return {Object}
*/
static fromFormatExplain(text, fmt, options = {}) {
const {
locale = null,
numberingSystem = null
} = options, localeToUse = Locale.fromOpts({
locale,
numberingSystem,
defaultToEN: true
});
return explainFromTokens(localeToUse, text, fmt);
}
/**
* @deprecated use fromFormatExplain instead
*/
static fromStringExplain(text, fmt, options = {}) {
return DateTime.fromFormatExplain(text, fmt, options);
}
// FORMAT PRESETS
/**
* {@link DateTime#toLocaleString} format like 10/14/1983
* @type {Object}
*/
static get DATE_SHORT() {
return DATE_SHORT;
}
/**
* {@link DateTime#toLocaleString} format like 'Oct 14, 1983'
* @type {Object}
*/
static get DATE_MED() {
return DATE_MED;
}
/**
* {@link DateTime#toLocaleString} format like 'Fri, Oct 14, 1983'
* @type {Object}
*/
static get DATE_MED_WITH_WEEKDAY() {
return DATE_MED_WITH_WEEKDAY;
}
/**
* {@link DateTime#toLocaleString} format like 'October 14, 1983'
* @type {Object}
*/
static get DATE_FULL() {
return DATE_FULL;
}
/**
* {@link DateTime#toLocaleString} format like 'Tuesday, October 14, 1983'
* @type {Object}
*/
static get DATE_HUGE() {
return DATE_HUGE;
}
/**
* {@link DateTime#toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is.
* @type {Object}
*/
static get TIME_SIMPLE() {
return TIME_SIMPLE;
}
/**
* {@link DateTime#toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is.
* @type {Object}
*/
static get TIME_WITH_SECONDS() {
return TIME_WITH_SECONDS;
}
/**
* {@link DateTime#toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is.
* @type {Object}
*/
static get TIME_WITH_SHORT_OFFSET() {
return TIME_WITH_SHORT_OFFSET;
}
/**
* {@link DateTime#toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is.
* @type {Object}
*/
static get TIME_WITH_LONG_OFFSET() {
return TIME_WITH_LONG_OFFSET;
}
/**
* {@link DateTime#toLocaleString} format like '09:30', always 24-hour.
* @type {Object}
*/
static get TIME_24_SIMPLE() {
return TIME_24_SIMPLE;
}
/**
* {@link DateTime#toLocaleString} format like '09:30:23', always 24-hour.
* @type {Object}
*/
static get TIME_24_WITH_SECONDS() {
return TIME_24_WITH_SECONDS;
}
/**
* {@link DateTime#toLocaleString} format like '09:30:23 EDT', always 24-hour.
* @type {Object}
*/
static get TIME_24_WITH_SHORT_OFFSET() {
return TIME_24_WITH_SHORT_OFFSET;
}
/**
* {@link DateTime#toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour.
* @type {Object}
*/
static get TIME_24_WITH_LONG_OFFSET() {
return TIME_24_WITH_LONG_OFFSET;
}
/**
* {@link DateTime#toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is.
* @type {Object}
*/
static get DATETIME_SHORT() {
return DATETIME_SHORT;
}
/**
* {@link DateTime#toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is.
* @type {Object}
*/
static get DATETIME_SHORT_WITH_SECONDS() {
return DATETIME_SHORT_WITH_SECONDS;
}
/**
* {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is.
* @type {Object}
*/
static get DATETIME_MED() {
return DATETIME_MED;
}
/**
* {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is.
* @type {Object}
*/
static get DATETIME_MED_WITH_SECONDS() {
return DATETIME_MED_WITH_SECONDS;
}
/**
* {@link DateTime#toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is.
* @type {Object}
*/
static get DATETIME_MED_WITH_WEEKDAY() {
return DATETIME_MED_WITH_WEEKDAY;
}
/**
* {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is.
* @type {Object}
*/
static get DATETIME_FULL() {
return DATETIME_FULL;
}
/**
* {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is.
* @type {Object}
*/
static get DATETIME_FULL_WITH_SECONDS() {
return DATETIME_FULL_WITH_SECONDS;
}
/**
* {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is.
* @type {Object}
*/
static get DATETIME_HUGE() {
return DATETIME_HUGE;
}
/**
* {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is.
* @type {Object}
*/
static get DATETIME_HUGE_WITH_SECONDS() {
return DATETIME_HUGE_WITH_SECONDS;
}
};
function friendlyDateTime(dateTimeish) {
if (DateTime.isDateTime(dateTimeish)) {
return dateTimeish;
} else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) {
return DateTime.fromJSDate(dateTimeish);
} else if (dateTimeish && typeof dateTimeish === "object") {
return DateTime.fromObject(dateTimeish);
} else {
throw new InvalidArgumentError(`Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`);
}
}
var VERSION = "3.3.0";
exports.DateTime = DateTime;
exports.Duration = Duration;
exports.FixedOffsetZone = FixedOffsetZone;
exports.IANAZone = IANAZone;
exports.Info = Info;
exports.Interval = Interval;
exports.InvalidZone = InvalidZone;
exports.Settings = Settings;
exports.SystemZone = SystemZone;
exports.VERSION = VERSION;
exports.Zone = Zone;
}
});
// node_modules/cron-parser/lib/date.js
var require_date = __commonJS({
"node_modules/cron-parser/lib/date.js"(exports, module2) {
"use strict";
var luxon = require_luxon();
CronDate.prototype.addYear = function() {
this._date = this._date.plus({ years: 1 });
};
CronDate.prototype.addMonth = function() {
this._date = this._date.plus({ months: 1 }).startOf("month");
};
CronDate.prototype.addDay = function() {
this._date = this._date.plus({ days: 1 }).startOf("day");
};
CronDate.prototype.addHour = function() {
var prev = this._date;
this._date = this._date.plus({ hours: 1 }).startOf("hour");
if (this._date <= prev) {
this._date = this._date.plus({ hours: 1 });
}
};
CronDate.prototype.addMinute = function() {
var prev = this._date;
this._date = this._date.plus({ minutes: 1 }).startOf("minute");
if (this._date < prev) {
this._date = this._date.plus({ hours: 1 });
}
};
CronDate.prototype.addSecond = function() {
var prev = this._date;
this._date = this._date.plus({ seconds: 1 }).startOf("second");
if (this._date < prev) {
this._date = this._date.plus({ hours: 1 });
}
};
CronDate.prototype.subtractYear = function() {
this._date = this._date.minus({ years: 1 });
};
CronDate.prototype.subtractMonth = function() {
this._date = this._date.minus({ months: 1 }).endOf("month").startOf("second");
};
CronDate.prototype.subtractDay = function() {
this._date = this._date.minus({ days: 1 }).endOf("day").startOf("second");
};
CronDate.prototype.subtractHour = function() {
var prev = this._date;
this._date = this._date.minus({ hours: 1 }).endOf("hour").startOf("second");
if (this._date >= prev) {
this._date = this._date.minus({ hours: 1 });
}
};
CronDate.prototype.subtractMinute = function() {
var prev = this._date;
this._date = this._date.minus({ minutes: 1 }).endOf("minute").startOf("second");
if (this._date > prev) {
this._date = this._date.minus({ hours: 1 });
}
};
CronDate.prototype.subtractSecond = function() {
var prev = this._date;
this._date = this._date.minus({ seconds: 1 }).startOf("second");
if (this._date > prev) {
this._date = this._date.minus({ hours: 1 });
}
};
CronDate.prototype.getDate = function() {
return this._date.day;
};
CronDate.prototype.getFullYear = function() {
return this._date.year;
};
CronDate.prototype.getDay = function() {
var weekday = this._date.weekday;
return weekday == 7 ? 0 : weekday;
};
CronDate.prototype.getMonth = function() {
return this._date.month - 1;
};
CronDate.prototype.getHours = function() {
return this._date.hour;
};
CronDate.prototype.getMinutes = function() {
return this._date.minute;
};
CronDate.prototype.getSeconds = function() {
return this._date.second;
};
CronDate.prototype.getMilliseconds = function() {
return this._date.millisecond;
};
CronDate.prototype.getTime = function() {
return this._date.valueOf();
};
CronDate.prototype.getUTCDate = function() {
return this._getUTC().day;
};
CronDate.prototype.getUTCFullYear = function() {
return this._getUTC().year;
};
CronDate.prototype.getUTCDay = function() {
var weekday = this._getUTC().weekday;
return weekday == 7 ? 0 : weekday;
};
CronDate.prototype.getUTCMonth = function() {
return this._getUTC().month - 1;
};
CronDate.prototype.getUTCHours = function() {
return this._getUTC().hour;
};
CronDate.prototype.getUTCMinutes = function() {
return this._getUTC().minute;
};
CronDate.prototype.getUTCSeconds = function() {
return this._getUTC().second;
};
CronDate.prototype.toISOString = function() {
return this._date.toUTC().toISO();
};
CronDate.prototype.toJSON = function() {
return this._date.toJSON();
};
CronDate.prototype.setDate = function(d) {
this._date = this._date.set({ day: d });
};
CronDate.prototype.setFullYear = function(y) {
this._date = this._date.set({ year: y });
};
CronDate.prototype.setDay = function(d) {
this._date = this._date.set({ weekday: d });
};
CronDate.prototype.setMonth = function(m) {
this._date = this._date.set({ month: m + 1 });
};
CronDate.prototype.setHours = function(h) {
this._date = this._date.set({ hour: h });
};
CronDate.prototype.setMinutes = function(m) {
this._date = this._date.set({ minute: m });
};
CronDate.prototype.setSeconds = function(s) {
this._date = this._date.set({ second: s });
};
CronDate.prototype.setMilliseconds = function(s) {
this._date = this._date.set({ millisecond: s });
};
CronDate.prototype._getUTC = function() {
return this._date.toUTC();
};
CronDate.prototype.toString = function() {
return this.toDate().toString();
};
CronDate.prototype.toDate = function() {
return this._date.toJSDate();
};
CronDate.prototype.isLastDayOfMonth = function() {
var newDate = this._date.plus({ days: 1 }).startOf("day");
return this._date.month !== newDate.month;
};
CronDate.prototype.isLastWeekdayOfMonth = function() {
var newDate = this._date.plus({ days: 7 }).startOf("day");
return this._date.month !== newDate.month;
};
function CronDate(timestamp, tz) {
var dateOpts = { zone: tz };
if (!timestamp) {
this._date = luxon.DateTime.local();
} else if (timestamp instanceof CronDate) {
this._date = timestamp._date;
} else if (timestamp instanceof Date) {
this._date = luxon.DateTime.fromJSDate(timestamp, dateOpts);
} else if (typeof timestamp === "number") {
this._date = luxon.DateTime.fromMillis(timestamp, dateOpts);
} else if (typeof timestamp === "string") {
this._date = luxon.DateTime.fromISO(timestamp, dateOpts);
this._date.isValid || (this._date = luxon.DateTime.fromRFC2822(timestamp, dateOpts));
this._date.isValid || (this._date = luxon.DateTime.fromSQL(timestamp, dateOpts));
this._date.isValid || (this._date = luxon.DateTime.fromFormat(timestamp, "EEE, d MMM yyyy HH:mm:ss", dateOpts));
}
if (!this._date || !this._date.isValid) {
throw new Error("CronDate: unhandled timestamp: " + JSON.stringify(timestamp));
}
if (tz && tz !== this._date.zoneName) {
this._date = this._date.setZone(tz);
}
}
module2.exports = CronDate;
}
});
// node_modules/cron-parser/lib/field_compactor.js
var require_field_compactor = __commonJS({
"node_modules/cron-parser/lib/field_compactor.js"(exports, module2) {
"use strict";
function buildRange(item) {
return {
start: item,
count: 1
};
}
function completeRangeWithItem(range, item) {
range.end = item;
range.step = item - range.start;
range.count = 2;
}
function finalizeCurrentRange(results, currentRange, currentItemRange) {
if (currentRange) {
if (currentRange.count === 2) {
results.push(buildRange(currentRange.start));
results.push(buildRange(currentRange.end));
} else {
results.push(currentRange);
}
}
if (currentItemRange) {
results.push(currentItemRange);
}
}
function compactField(arr) {
var results = [];
var currentRange = void 0;
for (var i = 0; i < arr.length; i++) {
var currentItem = arr[i];
if (typeof currentItem !== "number") {
finalizeCurrentRange(results, currentRange, buildRange(currentItem));
currentRange = void 0;
} else if (!currentRange) {
currentRange = buildRange(currentItem);
} else if (currentRange.count === 1) {
completeRangeWithItem(currentRange, currentItem);
} else {
if (currentRange.step === currentItem - currentRange.end) {
currentRange.count++;
currentRange.end = currentItem;
} else if (currentRange.count === 2) {
results.push(buildRange(currentRange.start));
currentRange = buildRange(currentRange.end);
completeRangeWithItem(currentRange, currentItem);
} else {
finalizeCurrentRange(results, currentRange);
currentRange = buildRange(currentItem);
}
}
}
finalizeCurrentRange(results, currentRange);
return results;
}
module2.exports = compactField;
}
});
// node_modules/cron-parser/lib/field_stringify.js
var require_field_stringify = __commonJS({
"node_modules/cron-parser/lib/field_stringify.js"(exports, module2) {
"use strict";
var compactField = require_field_compactor();
function stringifyField(arr, min2, max2) {
var ranges = compactField(arr);
if (ranges.length === 1) {
var singleRange = ranges[0];
var step = singleRange.step;
if (step === 1 && singleRange.start === min2 && singleRange.end === max2) {
return "*";
}
if (step !== 1 && singleRange.start === min2 && singleRange.end === max2 - step + 1) {
return "*/" + step;
}
}
var result = [];
for (var i = 0, l = ranges.length; i < l; ++i) {
var range = ranges[i];
if (range.count === 1) {
result.push(range.start);
continue;
}
var step = range.step;
if (range.step === 1) {
result.push(range.start + "-" + range.end);
continue;
}
var multiplier = range.start == 0 ? range.count - 1 : range.count;
if (range.step * multiplier > range.end) {
result = result.concat(
Array.from({ length: range.end - range.start + 1 }).map(function(_, index) {
var value = range.start + index;
if ((value - range.start) % range.step === 0) {
return value;
}
return null;
}).filter(function(value) {
return value != null;
})
);
} else if (range.end === max2 - range.step + 1) {
result.push(range.start + "/" + range.step);
} else {
result.push(range.start + "-" + range.end + "/" + range.step);
}
}
return result.join(",");
}
module2.exports = stringifyField;
}
});
// node_modules/cron-parser/lib/expression.js
var require_expression = __commonJS({
"node_modules/cron-parser/lib/expression.js"(exports, module2) {
"use strict";
var CronDate = require_date();
var stringifyField = require_field_stringify();
var LOOP_LIMIT = 1e4;
function CronExpression(fields, options) {
this._options = options;
this._utc = options.utc || false;
this._tz = this._utc ? "UTC" : options.tz;
this._currentDate = new CronDate(options.currentDate, this._tz);
this._startDate = options.startDate ? new CronDate(options.startDate, this._tz) : null;
this._endDate = options.endDate ? new CronDate(options.endDate, this._tz) : null;
this._isIterator = options.iterator || false;
this._hasIterated = false;
this._nthDayOfWeek = options.nthDayOfWeek || 0;
this.fields = CronExpression._freezeFields(fields);
}
CronExpression.map = ["second", "minute", "hour", "dayOfMonth", "month", "dayOfWeek"];
CronExpression.predefined = {
"@yearly": "0 0 1 1 *",
"@monthly": "0 0 1 * *",
"@weekly": "0 0 * * 0",
"@daily": "0 0 * * *",
"@hourly": "0 * * * *"
};
CronExpression.constraints = [
{ min: 0, max: 59, chars: [] },
// Second
{ min: 0, max: 59, chars: [] },
// Minute
{ min: 0, max: 23, chars: [] },
// Hour
{ min: 1, max: 31, chars: ["L"] },
// Day of month
{ min: 1, max: 12, chars: [] },
// Month
{ min: 0, max: 7, chars: ["L"] }
// Day of week
];
CronExpression.daysInMonth = [
31,
29,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
];
CronExpression.aliases = {
month: {
jan: 1,
feb: 2,
mar: 3,
apr: 4,
may: 5,
jun: 6,
jul: 7,
aug: 8,
sep: 9,
oct: 10,
nov: 11,
dec: 12
},
dayOfWeek: {
sun: 0,
mon: 1,
tue: 2,
wed: 3,
thu: 4,
fri: 5,
sat: 6
}
};
CronExpression.parseDefaults = ["0", "*", "*", "*", "*", "*"];
CronExpression.standardValidCharacters = /^[,*\d/-]+$/;
CronExpression.dayOfWeekValidCharacters = /^[?,*\dL#/-]+$/;
CronExpression.dayOfMonthValidCharacters = /^[?,*\dL/-]+$/;
CronExpression.validCharacters = {
second: CronExpression.standardValidCharacters,
minute: CronExpression.standardValidCharacters,
hour: CronExpression.standardValidCharacters,
dayOfMonth: CronExpression.dayOfMonthValidCharacters,
month: CronExpression.standardValidCharacters,
dayOfWeek: CronExpression.dayOfWeekValidCharacters
};
CronExpression._isValidConstraintChar = function _isValidConstraintChar(constraints, value) {
if (typeof value !== "string") {
return false;
}
return constraints.chars.some(function(char) {
return value.indexOf(char) > -1;
});
};
CronExpression._parseField = function _parseField(field, value, constraints) {
switch (field) {
case "month":
case "dayOfWeek":
var aliases = CronExpression.aliases[field];
value = value.replace(/[a-z]{3}/gi, function(match) {
match = match.toLowerCase();
if (typeof aliases[match] !== "undefined") {
return aliases[match];
} else {
throw new Error('Validation error, cannot resolve alias "' + match + '"');
}
});
break;
}
if (!CronExpression.validCharacters[field].test(value)) {
throw new Error("Invalid characters, got value: " + value);
}
if (value.indexOf("*") !== -1) {
value = value.replace(/\*/g, constraints.min + "-" + constraints.max);
} else if (value.indexOf("?") !== -1) {
value = value.replace(/\?/g, constraints.min + "-" + constraints.max);
}
function parseSequence(val) {
var stack = [];
function handleResult(result) {
if (result instanceof Array) {
for (var i2 = 0, c2 = result.length; i2 < c2; i2++) {
var value2 = result[i2];
if (CronExpression._isValidConstraintChar(constraints, value2)) {
stack.push(value2);
continue;
}
if (typeof value2 !== "number" || Number.isNaN(value2) || value2 < constraints.min || value2 > constraints.max) {
throw new Error(
"Constraint error, got value " + value2 + " expected range " + constraints.min + "-" + constraints.max
);
}
stack.push(value2);
}
} else {
if (CronExpression._isValidConstraintChar(constraints, result)) {
stack.push(result);
return;
}
var numResult = +result;
if (Number.isNaN(numResult) || numResult < constraints.min || numResult > constraints.max) {
throw new Error(
"Constraint error, got value " + result + " expected range " + constraints.min + "-" + constraints.max
);
}
if (field === "dayOfWeek") {
numResult = numResult % 7;
}
stack.push(numResult);
}
}
var atoms = val.split(",");
if (!atoms.every(function(atom) {
return atom.length > 0;
})) {
throw new Error("Invalid list value format");
}
if (atoms.length > 1) {
for (var i = 0, c = atoms.length; i < c; i++) {
handleResult(parseRepeat(atoms[i]));
}
} else {
handleResult(parseRepeat(val));
}
stack.sort(CronExpression._sortCompareFn);
return stack;
}
function parseRepeat(val) {
var repeatInterval = 1;
var atoms = val.split("/");
if (atoms.length > 2) {
throw new Error("Invalid repeat: " + val);
}
if (atoms.length > 1) {
if (atoms[0] == +atoms[0]) {
atoms = [atoms[0] + "-" + constraints.max, atoms[1]];
}
return parseRange(atoms[0], atoms[atoms.length - 1]);
}
return parseRange(val, repeatInterval);
}
function parseRange(val, repeatInterval) {
var stack = [];
var atoms = val.split("-");
if (atoms.length > 1) {
if (atoms.length < 2) {
return +val;
}
if (!atoms[0].length) {
if (!atoms[1].length) {
throw new Error("Invalid range: " + val);
}
return +val;
}
var min2 = +atoms[0];
var max2 = +atoms[1];
if (Number.isNaN(min2) || Number.isNaN(max2) || min2 < constraints.min || max2 > constraints.max) {
throw new Error(
"Constraint error, got range " + min2 + "-" + max2 + " expected range " + constraints.min + "-" + constraints.max
);
} else if (min2 > max2) {
throw new Error("Invalid range: " + val);
}
var repeatIndex = +repeatInterval;
if (Number.isNaN(repeatIndex) || repeatIndex <= 0) {
throw new Error("Constraint error, cannot repeat at every " + repeatIndex + " time.");
}
if (field === "dayOfWeek" && max2 % 7 === 0) {
stack.push(0);
}
for (var index = min2, count = max2; index <= count; index++) {
var exists = stack.indexOf(index) !== -1;
if (!exists && repeatIndex > 0 && repeatIndex % repeatInterval === 0) {
repeatIndex = 1;
stack.push(index);
} else {
repeatIndex++;
}
}
return stack;
}
return Number.isNaN(+val) ? val : +val;
}
return parseSequence(value);
};
CronExpression._sortCompareFn = function(a, b) {
var aIsNumber = typeof a === "number";
var bIsNumber = typeof b === "number";
if (aIsNumber && bIsNumber) {
return a - b;
}
if (!aIsNumber && bIsNumber) {
return 1;
}
if (aIsNumber && !bIsNumber) {
return -1;
}
return a.localeCompare(b);
};
CronExpression._handleMaxDaysInMonth = function(mappedFields) {
if (mappedFields.month.length === 1) {
var daysInMonth = CronExpression.daysInMonth[mappedFields.month[0] - 1];
if (mappedFields.dayOfMonth[0] > daysInMonth) {
throw new Error("Invalid explicit day of month definition");
}
return mappedFields.dayOfMonth.filter(function(dayOfMonth) {
return dayOfMonth === "L" ? true : dayOfMonth <= daysInMonth;
}).sort(CronExpression._sortCompareFn);
}
};
CronExpression._freezeFields = function(fields) {
for (var i = 0, c = CronExpression.map.length; i < c; ++i) {
var field = CronExpression.map[i];
var value = fields[field];
fields[field] = Object.freeze(value);
}
return Object.freeze(fields);
};
CronExpression.prototype._applyTimezoneShift = function(currentDate, dateMathVerb, method) {
if (method === "Month" || method === "Day") {
var prevTime = currentDate.getTime();
currentDate[dateMathVerb + method]();
var currTime = currentDate.getTime();
if (prevTime === currTime) {
if (currentDate.getMinutes() === 0 && currentDate.getSeconds() === 0) {
currentDate.addHour();
} else if (currentDate.getMinutes() === 59 && currentDate.getSeconds() === 59) {
currentDate.subtractHour();
}
}
} else {
var previousHour = currentDate.getHours();
currentDate[dateMathVerb + method]();
var currentHour = currentDate.getHours();
var diff = currentHour - previousHour;
if (diff === 2) {
if (this.fields.hour.length !== 24) {
this._dstStart = currentHour;
}
} else if (diff === 0 && currentDate.getMinutes() === 0 && currentDate.getSeconds() === 0) {
if (this.fields.hour.length !== 24) {
this._dstEnd = currentHour;
}
}
}
};
CronExpression.prototype._findSchedule = function _findSchedule(reverse) {
function matchSchedule(value, sequence) {
for (var i = 0, c = sequence.length; i < c; i++) {
if (sequence[i] >= value) {
return sequence[i] === value;
}
}
return sequence[0] === value;
}
function isNthDayMatch(date, nthDayOfWeek) {
if (nthDayOfWeek < 6) {
if (date.getDate() < 8 && nthDayOfWeek === 1) {
return true;
}
var offset2 = date.getDate() % 7 ? 1 : 0;
var adjustedDate = date.getDate() - date.getDate() % 7;
var occurrence = Math.floor(adjustedDate / 7) + offset2;
return occurrence === nthDayOfWeek;
}
return false;
}
function isLInExpressions(expressions) {
return expressions.length > 0 && expressions.some(function(expression) {
return typeof expression === "string" && expression.indexOf("L") >= 0;
});
}
reverse = reverse || false;
var dateMathVerb = reverse ? "subtract" : "add";
var currentDate = new CronDate(this._currentDate, this._tz);
var startDate = this._startDate;
var endDate = this._endDate;
var startTimestamp = currentDate.getTime();
var stepCount = 0;
function isLastWeekdayOfMonthMatch(expressions) {
return expressions.some(function(expression) {
if (!isLInExpressions([expression])) {
return false;
}
var weekday = Number.parseInt(expression[0]) % 7;
if (Number.isNaN(weekday)) {
throw new Error("Invalid last weekday of the month expression: " + expression);
}
return currentDate.getDay() === weekday && currentDate.isLastWeekdayOfMonth();
});
}
while (stepCount < LOOP_LIMIT) {
stepCount++;
if (reverse) {
if (startDate && currentDate.getTime() - startDate.getTime() < 0) {
throw new Error("Out of the timespan range");
}
} else {
if (endDate && endDate.getTime() - currentDate.getTime() < 0) {
throw new Error("Out of the timespan range");
}
}
var dayOfMonthMatch = matchSchedule(currentDate.getDate(), this.fields.dayOfMonth);
if (isLInExpressions(this.fields.dayOfMonth)) {
dayOfMonthMatch = dayOfMonthMatch || currentDate.isLastDayOfMonth();
}
var dayOfWeekMatch = matchSchedule(currentDate.getDay(), this.fields.dayOfWeek);
if (isLInExpressions(this.fields.dayOfWeek)) {
dayOfWeekMatch = dayOfWeekMatch || isLastWeekdayOfMonthMatch(this.fields.dayOfWeek);
}
var isDayOfMonthWildcardMatch = this.fields.dayOfMonth.length >= CronExpression.daysInMonth[currentDate.getMonth()];
var isDayOfWeekWildcardMatch = this.fields.dayOfWeek.length === CronExpression.constraints[5].max - CronExpression.constraints[5].min + 1;
var currentHour = currentDate.getHours();
if (!dayOfMonthMatch && (!dayOfWeekMatch || isDayOfWeekWildcardMatch)) {
this._applyTimezoneShift(currentDate, dateMathVerb, "Day");
continue;
}
if (!isDayOfMonthWildcardMatch && isDayOfWeekWildcardMatch && !dayOfMonthMatch) {
this._applyTimezoneShift(currentDate, dateMathVerb, "Day");
continue;
}
if (isDayOfMonthWildcardMatch && !isDayOfWeekWildcardMatch && !dayOfWeekMatch) {
this._applyTimezoneShift(currentDate, dateMathVerb, "Day");
continue;
}
if (this._nthDayOfWeek > 0 && !isNthDayMatch(currentDate, this._nthDayOfWeek)) {
this._applyTimezoneShift(currentDate, dateMathVerb, "Day");
continue;
}
if (!matchSchedule(currentDate.getMonth() + 1, this.fields.month)) {
this._applyTimezoneShift(currentDate, dateMathVerb, "Month");
continue;
}
if (!matchSchedule(currentHour, this.fields.hour)) {
if (this._dstStart !== currentHour) {
this._dstStart = null;
this._applyTimezoneShift(currentDate, dateMathVerb, "Hour");
continue;
} else if (!matchSchedule(currentHour - 1, this.fields.hour)) {
currentDate[dateMathVerb + "Hour"]();
continue;
}
} else if (this._dstEnd === currentHour) {
if (!reverse) {
this._dstEnd = null;
this._applyTimezoneShift(currentDate, "add", "Hour");
continue;
}
}
if (!matchSchedule(currentDate.getMinutes(), this.fields.minute)) {
this._applyTimezoneShift(currentDate, dateMathVerb, "Minute");
continue;
}
if (!matchSchedule(currentDate.getSeconds(), this.fields.second)) {
this._applyTimezoneShift(currentDate, dateMathVerb, "Second");
continue;
}
if (startTimestamp === currentDate.getTime()) {
if (dateMathVerb === "add" || currentDate.getMilliseconds() === 0) {
this._applyTimezoneShift(currentDate, dateMathVerb, "Second");
} else {
currentDate.setMilliseconds(0);
}
continue;
}
break;
}
if (stepCount >= LOOP_LIMIT) {
throw new Error("Invalid expression, loop limit exceeded");
}
this._currentDate = new CronDate(currentDate, this._tz);
this._hasIterated = true;
return currentDate;
};
CronExpression.prototype.next = function next() {
var schedule = this._findSchedule();
if (this._isIterator) {
return {
value: schedule,
done: !this.hasNext()
};
}
return schedule;
};
CronExpression.prototype.prev = function prev() {
var schedule = this._findSchedule(true);
if (this._isIterator) {
return {
value: schedule,
done: !this.hasPrev()
};
}
return schedule;
};
CronExpression.prototype.hasNext = function() {
var current = this._currentDate;
var hasIterated = this._hasIterated;
try {
this._findSchedule();
return true;
} catch (err) {
return false;
} finally {
this._currentDate = current;
this._hasIterated = hasIterated;
}
};
CronExpression.prototype.hasPrev = function() {
var current = this._currentDate;
var hasIterated = this._hasIterated;
try {
this._findSchedule(true);
return true;
} catch (err) {
return false;
} finally {
this._currentDate = current;
this._hasIterated = hasIterated;
}
};
CronExpression.prototype.iterate = function iterate(steps, callback) {
var dates = [];
if (steps >= 0) {
for (var i = 0, c = steps; i < c; i++) {
try {
var item = this.next();
dates.push(item);
if (callback) {
callback(item, i);
}
} catch (err) {
break;
}
}
} else {
for (var i = 0, c = steps; i > c; i--) {
try {
var item = this.prev();
dates.push(item);
if (callback) {
callback(item, i);
}
} catch (err) {
break;
}
}
}
return dates;
};
CronExpression.prototype.reset = function reset(newDate) {
this._currentDate = new CronDate(newDate || this._options.currentDate);
};
CronExpression.prototype.stringify = function stringify(includeSeconds) {
var resultArr = [];
for (var i = includeSeconds ? 0 : 1, c = CronExpression.map.length; i < c; ++i) {
var field = CronExpression.map[i];
var value = this.fields[field];
var constraint = CronExpression.constraints[i];
if (field === "dayOfMonth" && this.fields.month.length === 1) {
constraint = { min: 1, max: CronExpression.daysInMonth[this.fields.month[0] - 1] };
} else if (field === "dayOfWeek") {
constraint = { min: 0, max: 6 };
value = value[value.length - 1] === 7 ? value.slice(0, -1) : value;
}
resultArr.push(stringifyField(value, constraint.min, constraint.max));
}
return resultArr.join(" ");
};
CronExpression.parse = function parse(expression, options) {
var self = this;
if (typeof options === "function") {
options = {};
}
function parse2(expression2, options2) {
if (!options2) {
options2 = {};
}
if (typeof options2.currentDate === "undefined") {
options2.currentDate = new CronDate(void 0, self._tz);
}
if (CronExpression.predefined[expression2]) {
expression2 = CronExpression.predefined[expression2];
}
var fields = [];
var atoms = (expression2 + "").trim().split(/\s+/);
if (atoms.length > 6) {
throw new Error("Invalid cron expression");
}
var start2 = CronExpression.map.length - atoms.length;
for (var i = 0, c = CronExpression.map.length; i < c; ++i) {
var field = CronExpression.map[i];
var value = atoms[atoms.length > c ? i : i - start2];
if (i < start2 || !value) {
fields.push(
CronExpression._parseField(
field,
CronExpression.parseDefaults[i],
CronExpression.constraints[i]
)
);
} else {
var val = field === "dayOfWeek" ? parseNthDay(value) : value;
fields.push(
CronExpression._parseField(
field,
val,
CronExpression.constraints[i]
)
);
}
}
var mappedFields = {};
for (var i = 0, c = CronExpression.map.length; i < c; i++) {
var key = CronExpression.map[i];
mappedFields[key] = fields[i];
}
var dayOfMonth = CronExpression._handleMaxDaysInMonth(mappedFields);
mappedFields.dayOfMonth = dayOfMonth || mappedFields.dayOfMonth;
return new CronExpression(mappedFields, options2);
function parseNthDay(val2) {
var atoms2 = val2.split("#");
if (atoms2.length > 1) {
var nthValue = +atoms2[atoms2.length - 1];
if (/,/.test(val2)) {
throw new Error("Constraint error, invalid dayOfWeek `#` and `,` special characters are incompatible");
}
if (/\//.test(val2)) {
throw new Error("Constraint error, invalid dayOfWeek `#` and `/` special characters are incompatible");
}
if (/-/.test(val2)) {
throw new Error("Constraint error, invalid dayOfWeek `#` and `-` special characters are incompatible");
}
if (atoms2.length > 2 || Number.isNaN(nthValue) || (nthValue < 1 || nthValue > 5)) {
throw new Error("Constraint error, invalid dayOfWeek occurrence number (#)");
}
options2.nthDayOfWeek = nthValue;
return atoms2[0];
}
return val2;
}
}
return parse2(expression, options);
};
CronExpression.fieldsToExpression = function fieldsToExpression(fields, options) {
function validateConstraints(field2, values2, constraints) {
if (!values2) {
throw new Error("Validation error, Field " + field2 + " is missing");
}
if (values2.length === 0) {
throw new Error("Validation error, Field " + field2 + " contains no values");
}
for (var i2 = 0, c2 = values2.length; i2 < c2; i2++) {
var value = values2[i2];
if (CronExpression._isValidConstraintChar(constraints, value)) {
continue;
}
if (typeof value !== "number" || Number.isNaN(value) || value < constraints.min || value > constraints.max) {
throw new Error(
"Constraint error, got value " + value + " expected range " + constraints.min + "-" + constraints.max
);
}
}
}
var mappedFields = {};
for (var i = 0, c = CronExpression.map.length; i < c; ++i) {
var field = CronExpression.map[i];
var values = fields[field];
validateConstraints(
field,
values,
CronExpression.constraints[i]
);
var copy = [];
var j = -1;
while (++j < values.length) {
copy[j] = values[j];
}
values = copy.sort(CronExpression._sortCompareFn).filter(function(item, pos, ary) {
return !pos || item !== ary[pos - 1];
});
if (values.length !== copy.length) {
throw new Error("Validation error, Field " + field + " contains duplicate values");
}
mappedFields[field] = values;
}
var dayOfMonth = CronExpression._handleMaxDaysInMonth(mappedFields);
mappedFields.dayOfMonth = dayOfMonth || mappedFields.dayOfMonth;
return new CronExpression(mappedFields, options || {});
};
module2.exports = CronExpression;
}
});
// node_modules/cron-parser/lib/parser.js
var require_parser = __commonJS({
"node_modules/cron-parser/lib/parser.js"(exports, module2) {
"use strict";
var CronExpression = require_expression();
function CronParser() {
}
CronParser._parseEntry = function _parseEntry(entry) {
var atoms = entry.split(" ");
if (atoms.length === 6) {
return {
interval: CronExpression.parse(entry)
};
} else if (atoms.length > 6) {
return {
interval: CronExpression.parse(
atoms.slice(0, 6).join(" ")
),
command: atoms.slice(6, atoms.length)
};
} else {
throw new Error("Invalid entry: " + entry);
}
};
CronParser.parseExpression = function parseExpression2(expression, options) {
return CronExpression.parse(expression, options);
};
CronParser.fieldsToExpression = function fieldsToExpression(fields, options) {
return CronExpression.fieldsToExpression(fields, options);
};
CronParser.parseString = function parseString(data) {
var blocks = data.split("\n");
var response = {
variables: {},
expressions: [],
errors: {}
};
for (var i = 0, c = blocks.length; i < c; i++) {
var block = blocks[i];
var matches = null;
var entry = block.trim();
if (entry.length > 0) {
if (entry.match(/^#/)) {
continue;
} else if (matches = entry.match(/^(.*)=(.*)$/)) {
response.variables[matches[1]] = matches[2];
} else {
var result = null;
try {
result = CronParser._parseEntry("0 " + entry);
response.expressions.push(result.interval);
} catch (err) {
response.errors[entry] = err;
}
}
}
}
return response;
};
CronParser.parseFile = function parseFile(filePath, callback) {
require("fs").readFile(filePath, function(err, data) {
if (err) {
callback(err);
return;
}
return callback(null, CronParser.parseString(data.toString()));
});
};
module2.exports = CronParser;
}
});
// src/main.ts
var main_exports = {};
__export(main_exports, {
default: () => Cron
});
module.exports = __toCommonJS(main_exports);
var import_obsidian3 = require("obsidian");
// src/lockManager.ts
var CronLockManager = class {
constructor(job, jobSettings, plugin, syncChecker) {
this.syncChecker = syncChecker;
this.job = job;
this.settings = jobSettings;
this.plugin = plugin;
if (!this.plugin.settings.locks[this.job]) {
this.plugin.settings.locks[this.job] = {};
}
this.plugin.saveSettings();
}
updateLastrun() {
this.plugin.settings.locks[this.job].lastRun = window.moment().format();
return this.plugin.saveSettings();
}
async updateLockJob(status) {
this.plugin.settings.locks[this.job].locked = status;
this.plugin.settings.locks[this.job].lockedDeviceName = this.syncChecker.deviceName();
await this.plugin.saveSettings();
return this.syncChecker.waitForSync(this.settings);
}
lockJob() {
return this.updateLockJob(true);
}
unlockJob() {
return this.updateLockJob(false);
}
clearLock() {
this.plugin.settings.locks[this.job].locked = false;
}
lastRun() {
return this.plugin.settings.locks[this.job].lastRun;
}
resetLastRun() {
this.plugin.settings.locks[this.job].lastRun = void 0;
}
jobLocked() {
return this.plugin.settings.locks[this.job].locked || false;
}
};
// src/job.ts
var import_cron_parser = __toESM(require_parser());
var Job = class {
constructor(id, name, job, frequency, settings, app2, plugin, syncChecker) {
this.syncChecker = syncChecker;
this.plugin = plugin;
this.app = app2;
this.lockManager = new CronLockManager(id, settings, plugin, syncChecker);
this.name = name;
this.id = id;
this.job = job;
this.frequency = frequency;
this.settings = settings;
}
async runJob() {
console.log(`Running ${this.name}`);
await this.lockManager.lockJob();
typeof this.job == "string" ? await this.runJobCommand() : await this.runJobFunction();
await this.lockManager.updateLastrun();
await this.lockManager.unlockJob();
}
canRunJob() {
if (this.lockManager.jobLocked() && !this.settings.disableJobLock) {
this.noRunReason = "job locked";
return false;
}
if (this.app.isMobile && !this.settings.enableMobile) {
this.noRunReason = "disabled on mobile";
return false;
}
if (!this.jobIntervalPassed()) {
this.noRunReason = "job interval hasnt passed";
return false;
}
return true;
}
clearJobLock() {
this.lockManager.clearLock();
}
jobIntervalPassed() {
const lastRun = this.lockManager.lastRun();
if (!lastRun)
return true;
const prevRun = window.moment((0, import_cron_parser.parseExpression)(this.frequency).prev().toDate());
return prevRun.isAfter(lastRun);
}
async runJobFunction() {
if (typeof this.job !== "function") {
return;
}
try {
await this.job(this.app);
console.log(`${this.name} completed`);
} catch (error) {
console.log(`${this.name} failed to run`);
console.log(error);
}
}
async runJobCommand() {
if (typeof this.job !== "string") {
return;
}
const jobCommand = this.app.commands.commands[this.job];
if (!jobCommand) {
console.log(`${this.name} failed to run: Command unknown`);
}
await this.app.commands.executeCommand(jobCommand);
}
};
// src/settings.ts
var import_obsidian2 = require("obsidian");
// node_modules/uuid/dist/esm-browser/rng.js
var getRandomValues;
var rnds8 = new Uint8Array(16);
function rng() {
if (!getRandomValues) {
getRandomValues = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
if (!getRandomValues) {
throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
}
}
return getRandomValues(rnds8);
}
// node_modules/uuid/dist/esm-browser/stringify.js
var byteToHex = [];
for (let i = 0; i < 256; ++i) {
byteToHex.push((i + 256).toString(16).slice(1));
}
function unsafeStringify(arr, offset2 = 0) {
return (byteToHex[arr[offset2 + 0]] + byteToHex[arr[offset2 + 1]] + byteToHex[arr[offset2 + 2]] + byteToHex[arr[offset2 + 3]] + "-" + byteToHex[arr[offset2 + 4]] + byteToHex[arr[offset2 + 5]] + "-" + byteToHex[arr[offset2 + 6]] + byteToHex[arr[offset2 + 7]] + "-" + byteToHex[arr[offset2 + 8]] + byteToHex[arr[offset2 + 9]] + "-" + byteToHex[arr[offset2 + 10]] + byteToHex[arr[offset2 + 11]] + byteToHex[arr[offset2 + 12]] + byteToHex[arr[offset2 + 13]] + byteToHex[arr[offset2 + 14]] + byteToHex[arr[offset2 + 15]]).toLowerCase();
}
// node_modules/uuid/dist/esm-browser/native.js
var randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
var native_default = {
randomUUID
};
// node_modules/uuid/dist/esm-browser/v4.js
function v4(options, buf, offset2) {
if (native_default.randomUUID && !buf && !options) {
return native_default.randomUUID();
}
options = options || {};
const rnds = options.random || (options.rng || rng)();
rnds[6] = rnds[6] & 15 | 64;
rnds[8] = rnds[8] & 63 | 128;
if (buf) {
offset2 = offset2 || 0;
for (let i = 0; i < 16; ++i) {
buf[offset2 + i] = rnds[i];
}
return buf;
}
return unsafeStringify(rnds);
}
var v4_default = v4;
// src/suggest.ts
var import_obsidian = require("obsidian");
// node_modules/@popperjs/core/lib/enums.js
var top = "top";
var bottom = "bottom";
var right = "right";
var left = "left";
var auto = "auto";
var basePlacements = [top, bottom, right, left];
var start = "start";
var end = "end";
var clippingParents = "clippingParents";
var viewport = "viewport";
var popper = "popper";
var reference = "reference";
var variationPlacements = /* @__PURE__ */ basePlacements.reduce(function(acc, placement) {
return acc.concat([placement + "-" + start, placement + "-" + end]);
}, []);
var placements = /* @__PURE__ */ [].concat(basePlacements, [auto]).reduce(function(acc, placement) {
return acc.concat([placement, placement + "-" + start, placement + "-" + end]);
}, []);
var beforeRead = "beforeRead";
var read = "read";
var afterRead = "afterRead";
var beforeMain = "beforeMain";
var main = "main";
var afterMain = "afterMain";
var beforeWrite = "beforeWrite";
var write = "write";
var afterWrite = "afterWrite";
var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite];
// node_modules/@popperjs/core/lib/dom-utils/getNodeName.js
function getNodeName(element) {
return element ? (element.nodeName || "").toLowerCase() : null;
}
// node_modules/@popperjs/core/lib/dom-utils/getWindow.js
function getWindow(node) {
if (node == null) {
return window;
}
if (node.toString() !== "[object Window]") {
var ownerDocument = node.ownerDocument;
return ownerDocument ? ownerDocument.defaultView || window : window;
}
return node;
}
// node_modules/@popperjs/core/lib/dom-utils/instanceOf.js
function isElement(node) {
var OwnElement = getWindow(node).Element;
return node instanceof OwnElement || node instanceof Element;
}
function isHTMLElement(node) {
var OwnElement = getWindow(node).HTMLElement;
return node instanceof OwnElement || node instanceof HTMLElement;
}
function isShadowRoot(node) {
if (typeof ShadowRoot === "undefined") {
return false;
}
var OwnElement = getWindow(node).ShadowRoot;
return node instanceof OwnElement || node instanceof ShadowRoot;
}
// node_modules/@popperjs/core/lib/modifiers/applyStyles.js
function applyStyles(_ref) {
var state = _ref.state;
Object.keys(state.elements).forEach(function(name) {
var style = state.styles[name] || {};
var attributes = state.attributes[name] || {};
var element = state.elements[name];
if (!isHTMLElement(element) || !getNodeName(element)) {
return;
}
Object.assign(element.style, style);
Object.keys(attributes).forEach(function(name2) {
var value = attributes[name2];
if (value === false) {
element.removeAttribute(name2);
} else {
element.setAttribute(name2, value === true ? "" : value);
}
});
});
}
function effect(_ref2) {
var state = _ref2.state;
var initialStyles = {
popper: {
position: state.options.strategy,
left: "0",
top: "0",
margin: "0"
},
arrow: {
position: "absolute"
},
reference: {}
};
Object.assign(state.elements.popper.style, initialStyles.popper);
state.styles = initialStyles;
if (state.elements.arrow) {
Object.assign(state.elements.arrow.style, initialStyles.arrow);
}
return function() {
Object.keys(state.elements).forEach(function(name) {
var element = state.elements[name];
var attributes = state.attributes[name] || {};
var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]);
var style = styleProperties.reduce(function(style2, property) {
style2[property] = "";
return style2;
}, {});
if (!isHTMLElement(element) || !getNodeName(element)) {
return;
}
Object.assign(element.style, style);
Object.keys(attributes).forEach(function(attribute) {
element.removeAttribute(attribute);
});
});
};
}
var applyStyles_default = {
name: "applyStyles",
enabled: true,
phase: "write",
fn: applyStyles,
effect,
requires: ["computeStyles"]
};
// node_modules/@popperjs/core/lib/utils/getBasePlacement.js
function getBasePlacement(placement) {
return placement.split("-")[0];
}
// node_modules/@popperjs/core/lib/utils/math.js
var max = Math.max;
var min = Math.min;
var round = Math.round;
// node_modules/@popperjs/core/lib/utils/userAgent.js
function getUAString() {
var uaData = navigator.userAgentData;
if (uaData != null && uaData.brands) {
return uaData.brands.map(function(item) {
return item.brand + "/" + item.version;
}).join(" ");
}
return navigator.userAgent;
}
// node_modules/@popperjs/core/lib/dom-utils/isLayoutViewport.js
function isLayoutViewport() {
return !/^((?!chrome|android).)*safari/i.test(getUAString());
}
// node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js
function getBoundingClientRect(element, includeScale, isFixedStrategy) {
if (includeScale === void 0) {
includeScale = false;
}
if (isFixedStrategy === void 0) {
isFixedStrategy = false;
}
var clientRect = element.getBoundingClientRect();
var scaleX = 1;
var scaleY = 1;
if (includeScale && isHTMLElement(element)) {
scaleX = element.offsetWidth > 0 ? round(clientRect.width) / element.offsetWidth || 1 : 1;
scaleY = element.offsetHeight > 0 ? round(clientRect.height) / element.offsetHeight || 1 : 1;
}
var _ref = isElement(element) ? getWindow(element) : window, visualViewport = _ref.visualViewport;
var addVisualOffsets = !isLayoutViewport() && isFixedStrategy;
var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX;
var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY;
var width = clientRect.width / scaleX;
var height = clientRect.height / scaleY;
return {
width,
height,
top: y,
right: x + width,
bottom: y + height,
left: x,
x,
y
};
}
// node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js
function getLayoutRect(element) {
var clientRect = getBoundingClientRect(element);
var width = element.offsetWidth;
var height = element.offsetHeight;
if (Math.abs(clientRect.width - width) <= 1) {
width = clientRect.width;
}
if (Math.abs(clientRect.height - height) <= 1) {
height = clientRect.height;
}
return {
x: element.offsetLeft,
y: element.offsetTop,
width,
height
};
}
// node_modules/@popperjs/core/lib/dom-utils/contains.js
function contains(parent, child) {
var rootNode = child.getRootNode && child.getRootNode();
if (parent.contains(child)) {
return true;
} else if (rootNode && isShadowRoot(rootNode)) {
var next = child;
do {
if (next && parent.isSameNode(next)) {
return true;
}
next = next.parentNode || next.host;
} while (next);
}
return false;
}
// node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js
function getComputedStyle(element) {
return getWindow(element).getComputedStyle(element);
}
// node_modules/@popperjs/core/lib/dom-utils/isTableElement.js
function isTableElement(element) {
return ["table", "td", "th"].indexOf(getNodeName(element)) >= 0;
}
// node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js
function getDocumentElement(element) {
return ((isElement(element) ? element.ownerDocument : (
// $FlowFixMe[prop-missing]
element.document
)) || window.document).documentElement;
}
// node_modules/@popperjs/core/lib/dom-utils/getParentNode.js
function getParentNode(element) {
if (getNodeName(element) === "html") {
return element;
}
return (
// this is a quicker (but less type safe) way to save quite some bytes from the bundle
// $FlowFixMe[incompatible-return]
// $FlowFixMe[prop-missing]
element.assignedSlot || // step into the shadow DOM of the parent of a slotted node
element.parentNode || // DOM Element detected
(isShadowRoot(element) ? element.host : null) || // ShadowRoot detected
// $FlowFixMe[incompatible-call]: HTMLElement is a Node
getDocumentElement(element)
);
}
// node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js
function getTrueOffsetParent(element) {
if (!isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837
getComputedStyle(element).position === "fixed") {
return null;
}
return element.offsetParent;
}
function getContainingBlock(element) {
var isFirefox = /firefox/i.test(getUAString());
var isIE = /Trident/i.test(getUAString());
if (isIE && isHTMLElement(element)) {
var elementCss = getComputedStyle(element);
if (elementCss.position === "fixed") {
return null;
}
}
var currentNode = getParentNode(element);
if (isShadowRoot(currentNode)) {
currentNode = currentNode.host;
}
while (isHTMLElement(currentNode) && ["html", "body"].indexOf(getNodeName(currentNode)) < 0) {
var css = getComputedStyle(currentNode);
if (css.transform !== "none" || css.perspective !== "none" || css.contain === "paint" || ["transform", "perspective"].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === "filter" || isFirefox && css.filter && css.filter !== "none") {
return currentNode;
} else {
currentNode = currentNode.parentNode;
}
}
return null;
}
function getOffsetParent(element) {
var window2 = getWindow(element);
var offsetParent = getTrueOffsetParent(element);
while (offsetParent && isTableElement(offsetParent) && getComputedStyle(offsetParent).position === "static") {
offsetParent = getTrueOffsetParent(offsetParent);
}
if (offsetParent && (getNodeName(offsetParent) === "html" || getNodeName(offsetParent) === "body" && getComputedStyle(offsetParent).position === "static")) {
return window2;
}
return offsetParent || getContainingBlock(element) || window2;
}
// node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js
function getMainAxisFromPlacement(placement) {
return ["top", "bottom"].indexOf(placement) >= 0 ? "x" : "y";
}
// node_modules/@popperjs/core/lib/utils/within.js
function within(min2, value, max2) {
return max(min2, min(value, max2));
}
function withinMaxClamp(min2, value, max2) {
var v = within(min2, value, max2);
return v > max2 ? max2 : v;
}
// node_modules/@popperjs/core/lib/utils/getFreshSideObject.js
function getFreshSideObject() {
return {
top: 0,
right: 0,
bottom: 0,
left: 0
};
}
// node_modules/@popperjs/core/lib/utils/mergePaddingObject.js
function mergePaddingObject(paddingObject) {
return Object.assign({}, getFreshSideObject(), paddingObject);
}
// node_modules/@popperjs/core/lib/utils/expandToHashMap.js
function expandToHashMap(value, keys) {
return keys.reduce(function(hashMap, key) {
hashMap[key] = value;
return hashMap;
}, {});
}
// node_modules/@popperjs/core/lib/modifiers/arrow.js
var toPaddingObject = function toPaddingObject2(padding, state) {
padding = typeof padding === "function" ? padding(Object.assign({}, state.rects, {
placement: state.placement
})) : padding;
return mergePaddingObject(typeof padding !== "number" ? padding : expandToHashMap(padding, basePlacements));
};
function arrow(_ref) {
var _state$modifiersData$;
var state = _ref.state, name = _ref.name, options = _ref.options;
var arrowElement = state.elements.arrow;
var popperOffsets2 = state.modifiersData.popperOffsets;
var basePlacement = getBasePlacement(state.placement);
var axis = getMainAxisFromPlacement(basePlacement);
var isVertical = [left, right].indexOf(basePlacement) >= 0;
var len = isVertical ? "height" : "width";
if (!arrowElement || !popperOffsets2) {
return;
}
var paddingObject = toPaddingObject(options.padding, state);
var arrowRect = getLayoutRect(arrowElement);
var minProp = axis === "y" ? top : left;
var maxProp = axis === "y" ? bottom : right;
var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets2[axis] - state.rects.popper[len];
var startDiff = popperOffsets2[axis] - state.rects.reference[axis];
var arrowOffsetParent = getOffsetParent(arrowElement);
var clientSize = arrowOffsetParent ? axis === "y" ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;
var centerToReference = endDiff / 2 - startDiff / 2;
var min2 = paddingObject[minProp];
var max2 = clientSize - arrowRect[len] - paddingObject[maxProp];
var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference;
var offset2 = within(min2, center, max2);
var axisProp = axis;
state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset2, _state$modifiersData$.centerOffset = offset2 - center, _state$modifiersData$);
}
function effect2(_ref2) {
var state = _ref2.state, options = _ref2.options;
var _options$element = options.element, arrowElement = _options$element === void 0 ? "[data-popper-arrow]" : _options$element;
if (arrowElement == null) {
return;
}
if (typeof arrowElement === "string") {
arrowElement = state.elements.popper.querySelector(arrowElement);
if (!arrowElement) {
return;
}
}
if (true) {
if (!isHTMLElement(arrowElement)) {
console.error(['Popper: "arrow" element must be an HTMLElement (not an SVGElement).', "To use an SVG arrow, wrap it in an HTMLElement that will be used as", "the arrow."].join(" "));
}
}
if (!contains(state.elements.popper, arrowElement)) {
if (true) {
console.error(['Popper: "arrow" modifier\'s `element` must be a child of the popper', "element."].join(" "));
}
return;
}
state.elements.arrow = arrowElement;
}
var arrow_default = {
name: "arrow",
enabled: true,
phase: "main",
fn: arrow,
effect: effect2,
requires: ["popperOffsets"],
requiresIfExists: ["preventOverflow"]
};
// node_modules/@popperjs/core/lib/utils/getVariation.js
function getVariation(placement) {
return placement.split("-")[1];
}
// node_modules/@popperjs/core/lib/modifiers/computeStyles.js
var unsetSides = {
top: "auto",
right: "auto",
bottom: "auto",
left: "auto"
};
function roundOffsetsByDPR(_ref) {
var x = _ref.x, y = _ref.y;
var win = window;
var dpr = win.devicePixelRatio || 1;
return {
x: round(x * dpr) / dpr || 0,
y: round(y * dpr) / dpr || 0
};
}
function mapToStyles(_ref2) {
var _Object$assign2;
var popper2 = _ref2.popper, popperRect = _ref2.popperRect, placement = _ref2.placement, variation = _ref2.variation, offsets = _ref2.offsets, position = _ref2.position, gpuAcceleration = _ref2.gpuAcceleration, adaptive = _ref2.adaptive, roundOffsets = _ref2.roundOffsets, isFixed = _ref2.isFixed;
var _offsets$x = offsets.x, x = _offsets$x === void 0 ? 0 : _offsets$x, _offsets$y = offsets.y, y = _offsets$y === void 0 ? 0 : _offsets$y;
var _ref3 = typeof roundOffsets === "function" ? roundOffsets({
x,
y
}) : {
x,
y
};
x = _ref3.x;
y = _ref3.y;
var hasX = offsets.hasOwnProperty("x");
var hasY = offsets.hasOwnProperty("y");
var sideX = left;
var sideY = top;
var win = window;
if (adaptive) {
var offsetParent = getOffsetParent(popper2);
var heightProp = "clientHeight";
var widthProp = "clientWidth";
if (offsetParent === getWindow(popper2)) {
offsetParent = getDocumentElement(popper2);
if (getComputedStyle(offsetParent).position !== "static" && position === "absolute") {
heightProp = "scrollHeight";
widthProp = "scrollWidth";
}
}
offsetParent = offsetParent;
if (placement === top || (placement === left || placement === right) && variation === end) {
sideY = bottom;
var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : (
// $FlowFixMe[prop-missing]
offsetParent[heightProp]
);
y -= offsetY - popperRect.height;
y *= gpuAcceleration ? 1 : -1;
}
if (placement === left || (placement === top || placement === bottom) && variation === end) {
sideX = right;
var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : (
// $FlowFixMe[prop-missing]
offsetParent[widthProp]
);
x -= offsetX - popperRect.width;
x *= gpuAcceleration ? 1 : -1;
}
}
var commonStyles = Object.assign({
position
}, adaptive && unsetSides);
var _ref4 = roundOffsets === true ? roundOffsetsByDPR({
x,
y
}) : {
x,
y
};
x = _ref4.x;
y = _ref4.y;
if (gpuAcceleration) {
var _Object$assign;
return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? "0" : "", _Object$assign[sideX] = hasX ? "0" : "", _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign));
}
return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : "", _Object$assign2[sideX] = hasX ? x + "px" : "", _Object$assign2.transform = "", _Object$assign2));
}
function computeStyles(_ref5) {
var state = _ref5.state, options = _ref5.options;
var _options$gpuAccelerat = options.gpuAcceleration, gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat, _options$adaptive = options.adaptive, adaptive = _options$adaptive === void 0 ? true : _options$adaptive, _options$roundOffsets = options.roundOffsets, roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets;
if (true) {
var transitionProperty = getComputedStyle(state.elements.popper).transitionProperty || "";
if (adaptive && ["transform", "top", "right", "bottom", "left"].some(function(property) {
return transitionProperty.indexOf(property) >= 0;
})) {
console.warn(["Popper: Detected CSS transitions on at least one of the following", 'CSS properties: "transform", "top", "right", "bottom", "left".', "\n\n", 'Disable the "computeStyles" modifier\'s `adaptive` option to allow', "for smooth transitions, or remove these properties from the CSS", "transition declaration on the popper element if only transitioning", "opacity or background-color for example.", "\n\n", "We recommend using the popper element as a wrapper around an inner", "element that can have any CSS property transitioned for animations."].join(" "));
}
}
var commonStyles = {
placement: getBasePlacement(state.placement),
variation: getVariation(state.placement),
popper: state.elements.popper,
popperRect: state.rects.popper,
gpuAcceleration,
isFixed: state.options.strategy === "fixed"
};
if (state.modifiersData.popperOffsets != null) {
state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, {
offsets: state.modifiersData.popperOffsets,
position: state.options.strategy,
adaptive,
roundOffsets
})));
}
if (state.modifiersData.arrow != null) {
state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, {
offsets: state.modifiersData.arrow,
position: "absolute",
adaptive: false,
roundOffsets
})));
}
state.attributes.popper = Object.assign({}, state.attributes.popper, {
"data-popper-placement": state.placement
});
}
var computeStyles_default = {
name: "computeStyles",
enabled: true,
phase: "beforeWrite",
fn: computeStyles,
data: {}
};
// node_modules/@popperjs/core/lib/modifiers/eventListeners.js
var passive = {
passive: true
};
function effect3(_ref) {
var state = _ref.state, instance = _ref.instance, options = _ref.options;
var _options$scroll = options.scroll, scroll = _options$scroll === void 0 ? true : _options$scroll, _options$resize = options.resize, resize = _options$resize === void 0 ? true : _options$resize;
var window2 = getWindow(state.elements.popper);
var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);
if (scroll) {
scrollParents.forEach(function(scrollParent) {
scrollParent.addEventListener("scroll", instance.update, passive);
});
}
if (resize) {
window2.addEventListener("resize", instance.update, passive);
}
return function() {
if (scroll) {
scrollParents.forEach(function(scrollParent) {
scrollParent.removeEventListener("scroll", instance.update, passive);
});
}
if (resize) {
window2.removeEventListener("resize", instance.update, passive);
}
};
}
var eventListeners_default = {
name: "eventListeners",
enabled: true,
phase: "write",
fn: function fn() {
},
effect: effect3,
data: {}
};
// node_modules/@popperjs/core/lib/utils/getOppositePlacement.js
var hash = {
left: "right",
right: "left",
bottom: "top",
top: "bottom"
};
function getOppositePlacement(placement) {
return placement.replace(/left|right|bottom|top/g, function(matched) {
return hash[matched];
});
}
// node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js
var hash2 = {
start: "end",
end: "start"
};
function getOppositeVariationPlacement(placement) {
return placement.replace(/start|end/g, function(matched) {
return hash2[matched];
});
}
// node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js
function getWindowScroll(node) {
var win = getWindow(node);
var scrollLeft = win.pageXOffset;
var scrollTop = win.pageYOffset;
return {
scrollLeft,
scrollTop
};
}
// node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js
function getWindowScrollBarX(element) {
return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;
}
// node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js
function getViewportRect(element, strategy) {
var win = getWindow(element);
var html = getDocumentElement(element);
var visualViewport = win.visualViewport;
var width = html.clientWidth;
var height = html.clientHeight;
var x = 0;
var y = 0;
if (visualViewport) {
width = visualViewport.width;
height = visualViewport.height;
var layoutViewport = isLayoutViewport();
if (layoutViewport || !layoutViewport && strategy === "fixed") {
x = visualViewport.offsetLeft;
y = visualViewport.offsetTop;
}
}
return {
width,
height,
x: x + getWindowScrollBarX(element),
y
};
}
// node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js
function getDocumentRect(element) {
var _element$ownerDocumen;
var html = getDocumentElement(element);
var winScroll = getWindowScroll(element);
var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body;
var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);
var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);
var x = -winScroll.scrollLeft + getWindowScrollBarX(element);
var y = -winScroll.scrollTop;
if (getComputedStyle(body || html).direction === "rtl") {
x += max(html.clientWidth, body ? body.clientWidth : 0) - width;
}
return {
width,
height,
x,
y
};
}
// node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js
function isScrollParent(element) {
var _getComputedStyle = getComputedStyle(element), overflow = _getComputedStyle.overflow, overflowX = _getComputedStyle.overflowX, overflowY = _getComputedStyle.overflowY;
return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);
}
// node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js
function getScrollParent(node) {
if (["html", "body", "#document"].indexOf(getNodeName(node)) >= 0) {
return node.ownerDocument.body;
}
if (isHTMLElement(node) && isScrollParent(node)) {
return node;
}
return getScrollParent(getParentNode(node));
}
// node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js
function listScrollParents(element, list) {
var _element$ownerDocumen;
if (list === void 0) {
list = [];
}
var scrollParent = getScrollParent(element);
var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body);
var win = getWindow(scrollParent);
var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;
var updatedList = list.concat(target);
return isBody ? updatedList : (
// $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here
updatedList.concat(listScrollParents(getParentNode(target)))
);
}
// node_modules/@popperjs/core/lib/utils/rectToClientRect.js
function rectToClientRect(rect) {
return Object.assign({}, rect, {
left: rect.x,
top: rect.y,
right: rect.x + rect.width,
bottom: rect.y + rect.height
});
}
// node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js
function getInnerBoundingClientRect(element, strategy) {
var rect = getBoundingClientRect(element, false, strategy === "fixed");
rect.top = rect.top + element.clientTop;
rect.left = rect.left + element.clientLeft;
rect.bottom = rect.top + element.clientHeight;
rect.right = rect.left + element.clientWidth;
rect.width = element.clientWidth;
rect.height = element.clientHeight;
rect.x = rect.left;
rect.y = rect.top;
return rect;
}
function getClientRectFromMixedType(element, clippingParent, strategy) {
return clippingParent === viewport ? rectToClientRect(getViewportRect(element, strategy)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect(getDocumentRect(getDocumentElement(element)));
}
function getClippingParents(element) {
var clippingParents2 = listScrollParents(getParentNode(element));
var canEscapeClipping = ["absolute", "fixed"].indexOf(getComputedStyle(element).position) >= 0;
var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element;
if (!isElement(clipperElement)) {
return [];
}
return clippingParents2.filter(function(clippingParent) {
return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== "body";
});
}
function getClippingRect(element, boundary, rootBoundary, strategy) {
var mainClippingParents = boundary === "clippingParents" ? getClippingParents(element) : [].concat(boundary);
var clippingParents2 = [].concat(mainClippingParents, [rootBoundary]);
var firstClippingParent = clippingParents2[0];
var clippingRect = clippingParents2.reduce(function(accRect, clippingParent) {
var rect = getClientRectFromMixedType(element, clippingParent, strategy);
accRect.top = max(rect.top, accRect.top);
accRect.right = min(rect.right, accRect.right);
accRect.bottom = min(rect.bottom, accRect.bottom);
accRect.left = max(rect.left, accRect.left);
return accRect;
}, getClientRectFromMixedType(element, firstClippingParent, strategy));
clippingRect.width = clippingRect.right - clippingRect.left;
clippingRect.height = clippingRect.bottom - clippingRect.top;
clippingRect.x = clippingRect.left;
clippingRect.y = clippingRect.top;
return clippingRect;
}
// node_modules/@popperjs/core/lib/utils/computeOffsets.js
function computeOffsets(_ref) {
var reference2 = _ref.reference, element = _ref.element, placement = _ref.placement;
var basePlacement = placement ? getBasePlacement(placement) : null;
var variation = placement ? getVariation(placement) : null;
var commonX = reference2.x + reference2.width / 2 - element.width / 2;
var commonY = reference2.y + reference2.height / 2 - element.height / 2;
var offsets;
switch (basePlacement) {
case top:
offsets = {
x: commonX,
y: reference2.y - element.height
};
break;
case bottom:
offsets = {
x: commonX,
y: reference2.y + reference2.height
};
break;
case right:
offsets = {
x: reference2.x + reference2.width,
y: commonY
};
break;
case left:
offsets = {
x: reference2.x - element.width,
y: commonY
};
break;
default:
offsets = {
x: reference2.x,
y: reference2.y
};
}
var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null;
if (mainAxis != null) {
var len = mainAxis === "y" ? "height" : "width";
switch (variation) {
case start:
offsets[mainAxis] = offsets[mainAxis] - (reference2[len] / 2 - element[len] / 2);
break;
case end:
offsets[mainAxis] = offsets[mainAxis] + (reference2[len] / 2 - element[len] / 2);
break;
default:
}
}
return offsets;
}
// node_modules/@popperjs/core/lib/utils/detectOverflow.js
function detectOverflow(state, options) {
if (options === void 0) {
options = {};
}
var _options = options, _options$placement = _options.placement, placement = _options$placement === void 0 ? state.placement : _options$placement, _options$strategy = _options.strategy, strategy = _options$strategy === void 0 ? state.strategy : _options$strategy, _options$boundary = _options.boundary, boundary = _options$boundary === void 0 ? clippingParents : _options$boundary, _options$rootBoundary = _options.rootBoundary, rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary, _options$elementConte = _options.elementContext, elementContext = _options$elementConte === void 0 ? popper : _options$elementConte, _options$altBoundary = _options.altBoundary, altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary, _options$padding = _options.padding, padding = _options$padding === void 0 ? 0 : _options$padding;
var paddingObject = mergePaddingObject(typeof padding !== "number" ? padding : expandToHashMap(padding, basePlacements));
var altContext = elementContext === popper ? reference : popper;
var popperRect = state.rects.popper;
var element = state.elements[altBoundary ? altContext : elementContext];
var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary, strategy);
var referenceClientRect = getBoundingClientRect(state.elements.reference);
var popperOffsets2 = computeOffsets({
reference: referenceClientRect,
element: popperRect,
strategy: "absolute",
placement
});
var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets2));
var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect;
var overflowOffsets = {
top: clippingClientRect.top - elementClientRect.top + paddingObject.top,
bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom,
left: clippingClientRect.left - elementClientRect.left + paddingObject.left,
right: elementClientRect.right - clippingClientRect.right + paddingObject.right
};
var offsetData = state.modifiersData.offset;
if (elementContext === popper && offsetData) {
var offset2 = offsetData[placement];
Object.keys(overflowOffsets).forEach(function(key) {
var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1;
var axis = [top, bottom].indexOf(key) >= 0 ? "y" : "x";
overflowOffsets[key] += offset2[axis] * multiply;
});
}
return overflowOffsets;
}
// node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js
function computeAutoPlacement(state, options) {
if (options === void 0) {
options = {};
}
var _options = options, placement = _options.placement, boundary = _options.boundary, rootBoundary = _options.rootBoundary, padding = _options.padding, flipVariations = _options.flipVariations, _options$allowedAutoP = _options.allowedAutoPlacements, allowedAutoPlacements = _options$allowedAutoP === void 0 ? placements : _options$allowedAutoP;
var variation = getVariation(placement);
var placements2 = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function(placement2) {
return getVariation(placement2) === variation;
}) : basePlacements;
var allowedPlacements = placements2.filter(function(placement2) {
return allowedAutoPlacements.indexOf(placement2) >= 0;
});
if (allowedPlacements.length === 0) {
allowedPlacements = placements2;
if (true) {
console.error(["Popper: The `allowedAutoPlacements` option did not allow any", "placements. Ensure the `placement` option matches the variation", "of the allowed placements.", 'For example, "auto" cannot be used to allow "bottom-start".', 'Use "auto-start" instead.'].join(" "));
}
}
var overflows = allowedPlacements.reduce(function(acc, placement2) {
acc[placement2] = detectOverflow(state, {
placement: placement2,
boundary,
rootBoundary,
padding
})[getBasePlacement(placement2)];
return acc;
}, {});
return Object.keys(overflows).sort(function(a, b) {
return overflows[a] - overflows[b];
});
}
// node_modules/@popperjs/core/lib/modifiers/flip.js
function getExpandedFallbackPlacements(placement) {
if (getBasePlacement(placement) === auto) {
return [];
}
var oppositePlacement = getOppositePlacement(placement);
return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)];
}
function flip(_ref) {
var state = _ref.state, options = _ref.options, name = _ref.name;
if (state.modifiersData[name]._skip) {
return;
}
var _options$mainAxis = options.mainAxis, checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, _options$altAxis = options.altAxis, checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis, specifiedFallbackPlacements = options.fallbackPlacements, padding = options.padding, boundary = options.boundary, rootBoundary = options.rootBoundary, altBoundary = options.altBoundary, _options$flipVariatio = options.flipVariations, flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio, allowedAutoPlacements = options.allowedAutoPlacements;
var preferredPlacement = state.options.placement;
var basePlacement = getBasePlacement(preferredPlacement);
var isBasePlacement = basePlacement === preferredPlacement;
var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));
var placements2 = [preferredPlacement].concat(fallbackPlacements).reduce(function(acc, placement2) {
return acc.concat(getBasePlacement(placement2) === auto ? computeAutoPlacement(state, {
placement: placement2,
boundary,
rootBoundary,
padding,
flipVariations,
allowedAutoPlacements
}) : placement2);
}, []);
var referenceRect = state.rects.reference;
var popperRect = state.rects.popper;
var checksMap = /* @__PURE__ */ new Map();
var makeFallbackChecks = true;
var firstFittingPlacement = placements2[0];
for (var i = 0; i < placements2.length; i++) {
var placement = placements2[i];
var _basePlacement = getBasePlacement(placement);
var isStartVariation = getVariation(placement) === start;
var isVertical = [top, bottom].indexOf(_basePlacement) >= 0;
var len = isVertical ? "width" : "height";
var overflow = detectOverflow(state, {
placement,
boundary,
rootBoundary,
altBoundary,
padding
});
var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top;
if (referenceRect[len] > popperRect[len]) {
mainVariationSide = getOppositePlacement(mainVariationSide);
}
var altVariationSide = getOppositePlacement(mainVariationSide);
var checks = [];
if (checkMainAxis) {
checks.push(overflow[_basePlacement] <= 0);
}
if (checkAltAxis) {
checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);
}
if (checks.every(function(check) {
return check;
})) {
firstFittingPlacement = placement;
makeFallbackChecks = false;
break;
}
checksMap.set(placement, checks);
}
if (makeFallbackChecks) {
var numberOfChecks = flipVariations ? 3 : 1;
var _loop = function _loop2(_i2) {
var fittingPlacement = placements2.find(function(placement2) {
var checks2 = checksMap.get(placement2);
if (checks2) {
return checks2.slice(0, _i2).every(function(check) {
return check;
});
}
});
if (fittingPlacement) {
firstFittingPlacement = fittingPlacement;
return "break";
}
};
for (var _i = numberOfChecks; _i > 0; _i--) {
var _ret = _loop(_i);
if (_ret === "break")
break;
}
}
if (state.placement !== firstFittingPlacement) {
state.modifiersData[name]._skip = true;
state.placement = firstFittingPlacement;
state.reset = true;
}
}
var flip_default = {
name: "flip",
enabled: true,
phase: "main",
fn: flip,
requiresIfExists: ["offset"],
data: {
_skip: false
}
};
// node_modules/@popperjs/core/lib/modifiers/hide.js
function getSideOffsets(overflow, rect, preventedOffsets) {
if (preventedOffsets === void 0) {
preventedOffsets = {
x: 0,
y: 0
};
}
return {
top: overflow.top - rect.height - preventedOffsets.y,
right: overflow.right - rect.width + preventedOffsets.x,
bottom: overflow.bottom - rect.height + preventedOffsets.y,
left: overflow.left - rect.width - preventedOffsets.x
};
}
function isAnySideFullyClipped(overflow) {
return [top, right, bottom, left].some(function(side) {
return overflow[side] >= 0;
});
}
function hide(_ref) {
var state = _ref.state, name = _ref.name;
var referenceRect = state.rects.reference;
var popperRect = state.rects.popper;
var preventedOffsets = state.modifiersData.preventOverflow;
var referenceOverflow = detectOverflow(state, {
elementContext: "reference"
});
var popperAltOverflow = detectOverflow(state, {
altBoundary: true
});
var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect);
var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);
var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);
var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);
state.modifiersData[name] = {
referenceClippingOffsets,
popperEscapeOffsets,
isReferenceHidden,
hasPopperEscaped
};
state.attributes.popper = Object.assign({}, state.attributes.popper, {
"data-popper-reference-hidden": isReferenceHidden,
"data-popper-escaped": hasPopperEscaped
});
}
var hide_default = {
name: "hide",
enabled: true,
phase: "main",
requiresIfExists: ["preventOverflow"],
fn: hide
};
// node_modules/@popperjs/core/lib/modifiers/offset.js
function distanceAndSkiddingToXY(placement, rects, offset2) {
var basePlacement = getBasePlacement(placement);
var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1;
var _ref = typeof offset2 === "function" ? offset2(Object.assign({}, rects, {
placement
})) : offset2, skidding = _ref[0], distance = _ref[1];
skidding = skidding || 0;
distance = (distance || 0) * invertDistance;
return [left, right].indexOf(basePlacement) >= 0 ? {
x: distance,
y: skidding
} : {
x: skidding,
y: distance
};
}
function offset(_ref2) {
var state = _ref2.state, options = _ref2.options, name = _ref2.name;
var _options$offset = options.offset, offset2 = _options$offset === void 0 ? [0, 0] : _options$offset;
var data = placements.reduce(function(acc, placement) {
acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset2);
return acc;
}, {});
var _data$state$placement = data[state.placement], x = _data$state$placement.x, y = _data$state$placement.y;
if (state.modifiersData.popperOffsets != null) {
state.modifiersData.popperOffsets.x += x;
state.modifiersData.popperOffsets.y += y;
}
state.modifiersData[name] = data;
}
var offset_default = {
name: "offset",
enabled: true,
phase: "main",
requires: ["popperOffsets"],
fn: offset
};
// node_modules/@popperjs/core/lib/modifiers/popperOffsets.js
function popperOffsets(_ref) {
var state = _ref.state, name = _ref.name;
state.modifiersData[name] = computeOffsets({
reference: state.rects.reference,
element: state.rects.popper,
strategy: "absolute",
placement: state.placement
});
}
var popperOffsets_default = {
name: "popperOffsets",
enabled: true,
phase: "read",
fn: popperOffsets,
data: {}
};
// node_modules/@popperjs/core/lib/utils/getAltAxis.js
function getAltAxis(axis) {
return axis === "x" ? "y" : "x";
}
// node_modules/@popperjs/core/lib/modifiers/preventOverflow.js
function preventOverflow(_ref) {
var state = _ref.state, options = _ref.options, name = _ref.name;
var _options$mainAxis = options.mainAxis, checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, _options$altAxis = options.altAxis, checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis, boundary = options.boundary, rootBoundary = options.rootBoundary, altBoundary = options.altBoundary, padding = options.padding, _options$tether = options.tether, tether = _options$tether === void 0 ? true : _options$tether, _options$tetherOffset = options.tetherOffset, tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset;
var overflow = detectOverflow(state, {
boundary,
rootBoundary,
padding,
altBoundary
});
var basePlacement = getBasePlacement(state.placement);
var variation = getVariation(state.placement);
var isBasePlacement = !variation;
var mainAxis = getMainAxisFromPlacement(basePlacement);
var altAxis = getAltAxis(mainAxis);
var popperOffsets2 = state.modifiersData.popperOffsets;
var referenceRect = state.rects.reference;
var popperRect = state.rects.popper;
var tetherOffsetValue = typeof tetherOffset === "function" ? tetherOffset(Object.assign({}, state.rects, {
placement: state.placement
})) : tetherOffset;
var normalizedTetherOffsetValue = typeof tetherOffsetValue === "number" ? {
mainAxis: tetherOffsetValue,
altAxis: tetherOffsetValue
} : Object.assign({
mainAxis: 0,
altAxis: 0
}, tetherOffsetValue);
var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null;
var data = {
x: 0,
y: 0
};
if (!popperOffsets2) {
return;
}
if (checkMainAxis) {
var _offsetModifierState$;
var mainSide = mainAxis === "y" ? top : left;
var altSide = mainAxis === "y" ? bottom : right;
var len = mainAxis === "y" ? "height" : "width";
var offset2 = popperOffsets2[mainAxis];
var min2 = offset2 + overflow[mainSide];
var max2 = offset2 - overflow[altSide];
var additive = tether ? -popperRect[len] / 2 : 0;
var minLen = variation === start ? referenceRect[len] : popperRect[len];
var maxLen = variation === start ? -popperRect[len] : -referenceRect[len];
var arrowElement = state.elements.arrow;
var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : {
width: 0,
height: 0
};
var arrowPaddingObject = state.modifiersData["arrow#persistent"] ? state.modifiersData["arrow#persistent"].padding : getFreshSideObject();
var arrowPaddingMin = arrowPaddingObject[mainSide];
var arrowPaddingMax = arrowPaddingObject[altSide];
var arrowLen = within(0, referenceRect[len], arrowRect[len]);
var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis;
var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis;
var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow);
var clientOffset = arrowOffsetParent ? mainAxis === "y" ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0;
var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0;
var tetherMin = offset2 + minOffset - offsetModifierValue - clientOffset;
var tetherMax = offset2 + maxOffset - offsetModifierValue;
var preventedOffset = within(tether ? min(min2, tetherMin) : min2, offset2, tether ? max(max2, tetherMax) : max2);
popperOffsets2[mainAxis] = preventedOffset;
data[mainAxis] = preventedOffset - offset2;
}
if (checkAltAxis) {
var _offsetModifierState$2;
var _mainSide = mainAxis === "x" ? top : left;
var _altSide = mainAxis === "x" ? bottom : right;
var _offset = popperOffsets2[altAxis];
var _len = altAxis === "y" ? "height" : "width";
var _min = _offset + overflow[_mainSide];
var _max = _offset - overflow[_altSide];
var isOriginSide = [top, left].indexOf(basePlacement) !== -1;
var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0;
var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis;
var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max;
var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max);
popperOffsets2[altAxis] = _preventedOffset;
data[altAxis] = _preventedOffset - _offset;
}
state.modifiersData[name] = data;
}
var preventOverflow_default = {
name: "preventOverflow",
enabled: true,
phase: "main",
fn: preventOverflow,
requiresIfExists: ["offset"]
};
// node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js
function getHTMLElementScroll(element) {
return {
scrollLeft: element.scrollLeft,
scrollTop: element.scrollTop
};
}
// node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js
function getNodeScroll(node) {
if (node === getWindow(node) || !isHTMLElement(node)) {
return getWindowScroll(node);
} else {
return getHTMLElementScroll(node);
}
}
// node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js
function isElementScaled(element) {
var rect = element.getBoundingClientRect();
var scaleX = round(rect.width) / element.offsetWidth || 1;
var scaleY = round(rect.height) / element.offsetHeight || 1;
return scaleX !== 1 || scaleY !== 1;
}
function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) {
if (isFixed === void 0) {
isFixed = false;
}
var isOffsetParentAnElement = isHTMLElement(offsetParent);
var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent);
var documentElement = getDocumentElement(offsetParent);
var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled, isFixed);
var scroll = {
scrollLeft: 0,
scrollTop: 0
};
var offsets = {
x: 0,
y: 0
};
if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
if (getNodeName(offsetParent) !== "body" || // https://github.com/popperjs/popper-core/issues/1078
isScrollParent(documentElement)) {
scroll = getNodeScroll(offsetParent);
}
if (isHTMLElement(offsetParent)) {
offsets = getBoundingClientRect(offsetParent, true);
offsets.x += offsetParent.clientLeft;
offsets.y += offsetParent.clientTop;
} else if (documentElement) {
offsets.x = getWindowScrollBarX(documentElement);
}
}
return {
x: rect.left + scroll.scrollLeft - offsets.x,
y: rect.top + scroll.scrollTop - offsets.y,
width: rect.width,
height: rect.height
};
}
// node_modules/@popperjs/core/lib/utils/orderModifiers.js
function order(modifiers) {
var map = /* @__PURE__ */ new Map();
var visited = /* @__PURE__ */ new Set();
var result = [];
modifiers.forEach(function(modifier) {
map.set(modifier.name, modifier);
});
function sort(modifier) {
visited.add(modifier.name);
var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []);
requires.forEach(function(dep) {
if (!visited.has(dep)) {
var depModifier = map.get(dep);
if (depModifier) {
sort(depModifier);
}
}
});
result.push(modifier);
}
modifiers.forEach(function(modifier) {
if (!visited.has(modifier.name)) {
sort(modifier);
}
});
return result;
}
function orderModifiers(modifiers) {
var orderedModifiers = order(modifiers);
return modifierPhases.reduce(function(acc, phase) {
return acc.concat(orderedModifiers.filter(function(modifier) {
return modifier.phase === phase;
}));
}, []);
}
// node_modules/@popperjs/core/lib/utils/debounce.js
function debounce(fn2) {
var pending;
return function() {
if (!pending) {
pending = new Promise(function(resolve) {
Promise.resolve().then(function() {
pending = void 0;
resolve(fn2());
});
});
}
return pending;
};
}
// node_modules/@popperjs/core/lib/utils/format.js
function format(str) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return [].concat(args).reduce(function(p, c) {
return p.replace(/%s/, c);
}, str);
}
// node_modules/@popperjs/core/lib/utils/validateModifiers.js
var INVALID_MODIFIER_ERROR = 'Popper: modifier "%s" provided an invalid %s property, expected %s but got %s';
var MISSING_DEPENDENCY_ERROR = 'Popper: modifier "%s" requires "%s", but "%s" modifier is not available';
var VALID_PROPERTIES = ["name", "enabled", "phase", "fn", "effect", "requires", "options"];
function validateModifiers(modifiers) {
modifiers.forEach(function(modifier) {
[].concat(Object.keys(modifier), VALID_PROPERTIES).filter(function(value, index, self) {
return self.indexOf(value) === index;
}).forEach(function(key) {
switch (key) {
case "name":
if (typeof modifier.name !== "string") {
console.error(format(INVALID_MODIFIER_ERROR, String(modifier.name), '"name"', '"string"', '"' + String(modifier.name) + '"'));
}
break;
case "enabled":
if (typeof modifier.enabled !== "boolean") {
console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"enabled"', '"boolean"', '"' + String(modifier.enabled) + '"'));
}
break;
case "phase":
if (modifierPhases.indexOf(modifier.phase) < 0) {
console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"phase"', "either " + modifierPhases.join(", "), '"' + String(modifier.phase) + '"'));
}
break;
case "fn":
if (typeof modifier.fn !== "function") {
console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"fn"', '"function"', '"' + String(modifier.fn) + '"'));
}
break;
case "effect":
if (modifier.effect != null && typeof modifier.effect !== "function") {
console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"effect"', '"function"', '"' + String(modifier.fn) + '"'));
}
break;
case "requires":
if (modifier.requires != null && !Array.isArray(modifier.requires)) {
console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"requires"', '"array"', '"' + String(modifier.requires) + '"'));
}
break;
case "requiresIfExists":
if (!Array.isArray(modifier.requiresIfExists)) {
console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"requiresIfExists"', '"array"', '"' + String(modifier.requiresIfExists) + '"'));
}
break;
case "options":
case "data":
break;
default:
console.error('PopperJS: an invalid property has been provided to the "' + modifier.name + '" modifier, valid properties are ' + VALID_PROPERTIES.map(function(s) {
return '"' + s + '"';
}).join(", ") + '; but "' + key + '" was provided.');
}
modifier.requires && modifier.requires.forEach(function(requirement) {
if (modifiers.find(function(mod) {
return mod.name === requirement;
}) == null) {
console.error(format(MISSING_DEPENDENCY_ERROR, String(modifier.name), requirement, requirement));
}
});
});
});
}
// node_modules/@popperjs/core/lib/utils/uniqueBy.js
function uniqueBy(arr, fn2) {
var identifiers = /* @__PURE__ */ new Set();
return arr.filter(function(item) {
var identifier = fn2(item);
if (!identifiers.has(identifier)) {
identifiers.add(identifier);
return true;
}
});
}
// node_modules/@popperjs/core/lib/utils/mergeByName.js
function mergeByName(modifiers) {
var merged = modifiers.reduce(function(merged2, current) {
var existing = merged2[current.name];
merged2[current.name] = existing ? Object.assign({}, existing, current, {
options: Object.assign({}, existing.options, current.options),
data: Object.assign({}, existing.data, current.data)
}) : current;
return merged2;
}, {});
return Object.keys(merged).map(function(key) {
return merged[key];
});
}
// node_modules/@popperjs/core/lib/createPopper.js
var INVALID_ELEMENT_ERROR = "Popper: Invalid reference or popper argument provided. They must be either a DOM element or virtual element.";
var INFINITE_LOOP_ERROR = "Popper: An infinite loop in the modifiers cycle has been detected! The cycle has been interrupted to prevent a browser crash.";
var DEFAULT_OPTIONS = {
placement: "bottom",
modifiers: [],
strategy: "absolute"
};
function areValidElements() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return !args.some(function(element) {
return !(element && typeof element.getBoundingClientRect === "function");
});
}
function popperGenerator(generatorOptions) {
if (generatorOptions === void 0) {
generatorOptions = {};
}
var _generatorOptions = generatorOptions, _generatorOptions$def = _generatorOptions.defaultModifiers, defaultModifiers2 = _generatorOptions$def === void 0 ? [] : _generatorOptions$def, _generatorOptions$def2 = _generatorOptions.defaultOptions, defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;
return function createPopper2(reference2, popper2, options) {
if (options === void 0) {
options = defaultOptions;
}
var state = {
placement: "bottom",
orderedModifiers: [],
options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions),
modifiersData: {},
elements: {
reference: reference2,
popper: popper2
},
attributes: {},
styles: {}
};
var effectCleanupFns = [];
var isDestroyed = false;
var instance = {
state,
setOptions: function setOptions(setOptionsAction) {
var options2 = typeof setOptionsAction === "function" ? setOptionsAction(state.options) : setOptionsAction;
cleanupModifierEffects();
state.options = Object.assign({}, defaultOptions, state.options, options2);
state.scrollParents = {
reference: isElement(reference2) ? listScrollParents(reference2) : reference2.contextElement ? listScrollParents(reference2.contextElement) : [],
popper: listScrollParents(popper2)
};
var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers2, state.options.modifiers)));
state.orderedModifiers = orderedModifiers.filter(function(m) {
return m.enabled;
});
if (true) {
var modifiers = uniqueBy([].concat(orderedModifiers, state.options.modifiers), function(_ref) {
var name = _ref.name;
return name;
});
validateModifiers(modifiers);
if (getBasePlacement(state.options.placement) === auto) {
var flipModifier = state.orderedModifiers.find(function(_ref2) {
var name = _ref2.name;
return name === "flip";
});
if (!flipModifier) {
console.error(['Popper: "auto" placements require the "flip" modifier be', "present and enabled to work."].join(" "));
}
}
var _getComputedStyle = getComputedStyle(popper2), marginTop = _getComputedStyle.marginTop, marginRight = _getComputedStyle.marginRight, marginBottom = _getComputedStyle.marginBottom, marginLeft = _getComputedStyle.marginLeft;
if ([marginTop, marginRight, marginBottom, marginLeft].some(function(margin) {
return parseFloat(margin);
})) {
console.warn(['Popper: CSS "margin" styles cannot be used to apply padding', "between the popper and its reference element or boundary.", "To replicate margin, use the `offset` modifier, as well as", "the `padding` option in the `preventOverflow` and `flip`", "modifiers."].join(" "));
}
}
runModifierEffects();
return instance.update();
},
// Sync update it will always be executed, even if not necessary. This
// is useful for low frequency updates where sync behavior simplifies the
// logic.
// For high frequency updates (e.g. `resize` and `scroll` events), always
// prefer the async Popper#update method
forceUpdate: function forceUpdate() {
if (isDestroyed) {
return;
}
var _state$elements = state.elements, reference3 = _state$elements.reference, popper3 = _state$elements.popper;
if (!areValidElements(reference3, popper3)) {
if (true) {
console.error(INVALID_ELEMENT_ERROR);
}
return;
}
state.rects = {
reference: getCompositeRect(reference3, getOffsetParent(popper3), state.options.strategy === "fixed"),
popper: getLayoutRect(popper3)
};
state.reset = false;
state.placement = state.options.placement;
state.orderedModifiers.forEach(function(modifier) {
return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);
});
var __debug_loops__ = 0;
for (var index = 0; index < state.orderedModifiers.length; index++) {
if (true) {
__debug_loops__ += 1;
if (__debug_loops__ > 100) {
console.error(INFINITE_LOOP_ERROR);
break;
}
}
if (state.reset === true) {
state.reset = false;
index = -1;
continue;
}
var _state$orderedModifie = state.orderedModifiers[index], fn2 = _state$orderedModifie.fn, _state$orderedModifie2 = _state$orderedModifie.options, _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2, name = _state$orderedModifie.name;
if (typeof fn2 === "function") {
state = fn2({
state,
options: _options,
name,
instance
}) || state;
}
}
},
// Async and optimistically optimized update it will not be executed if
// not necessary (debounced to run at most once-per-tick)
update: debounce(function() {
return new Promise(function(resolve) {
instance.forceUpdate();
resolve(state);
});
}),
destroy: function destroy() {
cleanupModifierEffects();
isDestroyed = true;
}
};
if (!areValidElements(reference2, popper2)) {
if (true) {
console.error(INVALID_ELEMENT_ERROR);
}
return instance;
}
instance.setOptions(options).then(function(state2) {
if (!isDestroyed && options.onFirstUpdate) {
options.onFirstUpdate(state2);
}
});
function runModifierEffects() {
state.orderedModifiers.forEach(function(_ref3) {
var name = _ref3.name, _ref3$options = _ref3.options, options2 = _ref3$options === void 0 ? {} : _ref3$options, effect4 = _ref3.effect;
if (typeof effect4 === "function") {
var cleanupFn = effect4({
state,
name,
instance,
options: options2
});
var noopFn = function noopFn2() {
};
effectCleanupFns.push(cleanupFn || noopFn);
}
});
}
function cleanupModifierEffects() {
effectCleanupFns.forEach(function(fn2) {
return fn2();
});
effectCleanupFns = [];
}
return instance;
};
}
// node_modules/@popperjs/core/lib/popper.js
var defaultModifiers = [eventListeners_default, popperOffsets_default, computeStyles_default, applyStyles_default, offset_default, flip_default, preventOverflow_default, arrow_default, hide_default];
var createPopper = /* @__PURE__ */ popperGenerator({
defaultModifiers
});
// src/suggest.ts
var wrapAround = (value, size) => {
return (value % size + size) % size;
};
var Suggest = class {
constructor(owner, containerEl, scope) {
this.owner = owner;
this.containerEl = containerEl;
containerEl.on(
"click",
".suggestion-item",
this.onSuggestionClick.bind(this)
);
containerEl.on(
"mousemove",
".suggestion-item",
this.onSuggestionMouseover.bind(this)
);
scope.register([], "ArrowUp", (event) => {
if (!event.isComposing) {
this.setSelectedItem(this.selectedItem - 1, true);
return false;
}
});
scope.register([], "ArrowDown", (event) => {
if (!event.isComposing) {
this.setSelectedItem(this.selectedItem + 1, true);
return false;
}
});
scope.register([], "Enter", (event) => {
if (!event.isComposing) {
this.useSelectedItem(event);
return false;
}
});
}
onSuggestionClick(event, el) {
event.preventDefault();
const item = this.suggestions.indexOf(el);
this.setSelectedItem(item, false);
this.useSelectedItem(event);
}
onSuggestionMouseover(_event, el) {
const item = this.suggestions.indexOf(el);
this.setSelectedItem(item, false);
}
setSuggestions(values) {
this.containerEl.empty();
const suggestionEls = [];
values.forEach((value) => {
const suggestionEl = this.containerEl.createDiv("suggestion-item");
this.owner.renderSuggestion(value, suggestionEl);
suggestionEls.push(suggestionEl);
});
this.values = values;
this.suggestions = suggestionEls;
this.setSelectedItem(0, false);
}
useSelectedItem(event) {
const currentValue = this.values[this.selectedItem];
if (currentValue) {
this.owner.selectSuggestion(currentValue, event);
}
}
setSelectedItem(selectedIndex, scrollIntoView) {
const normalizedIndex = wrapAround(
selectedIndex,
this.suggestions.length
);
const prevSelectedSuggestion = this.suggestions[this.selectedItem];
const selectedSuggestion = this.suggestions[normalizedIndex];
prevSelectedSuggestion == null ? void 0 : prevSelectedSuggestion.removeClass("is-selected");
selectedSuggestion == null ? void 0 : selectedSuggestion.addClass("is-selected");
this.selectedItem = normalizedIndex;
if (scrollIntoView) {
selectedSuggestion.scrollIntoView(false);
}
}
};
var TextInputSuggest = class {
constructor(inputEl) {
this.inputEl = inputEl;
this.scope = new import_obsidian.Scope();
this.suggestEl = createDiv("suggestion-container");
const suggestion = this.suggestEl.createDiv("suggestion");
this.suggest = new Suggest(this, suggestion, this.scope);
this.scope.register([], "Escape", this.close.bind(this));
this.inputEl.addEventListener("input", this.onInputChanged.bind(this));
this.inputEl.addEventListener("focus", this.onInputChanged.bind(this));
this.inputEl.addEventListener("blur", this.close.bind(this));
this.suggestEl.on(
"mousedown",
".suggestion-container",
(event) => {
event.preventDefault();
}
);
}
onInputChanged() {
const inputStr = this.inputEl.value;
const suggestions = this.getSuggestions(inputStr);
if (!suggestions) {
this.close();
return;
}
if (suggestions.length > 0) {
this.suggest.setSuggestions(suggestions);
this.open(app.dom.appContainerEl, this.inputEl);
} else {
this.close();
}
}
open(container, inputEl) {
app.keymap.pushScope(this.scope);
container.appendChild(this.suggestEl);
this.popper = createPopper(inputEl, this.suggestEl, {
placement: "bottom-start",
modifiers: [
{
name: "sameWidth",
enabled: true,
fn: ({ state, instance }) => {
const targetWidth = "20000px";
if (state.styles.popper.width === targetWidth) {
return;
}
state.styles.popper.width = targetWidth;
instance.update();
},
phase: "beforeWrite",
requires: ["computeStyles"]
}
]
});
}
close() {
app.keymap.popScope(this.scope);
this.suggest.setSuggestions([]);
if (this.popper)
this.popper.destroy();
this.suggestEl.detach();
}
};
// src/commandSuggest.ts
var CommandSuggest = class extends TextInputSuggest {
getSuggestions(inputStr) {
const abstractCommands = app.commands.commands;
const commands = [];
const lowerCaseInputStr = inputStr.toLowerCase();
for (const [, command] of Object.entries(abstractCommands)) {
if (command.name.toLowerCase().contains(lowerCaseInputStr)) {
commands.push(command);
}
}
return commands;
}
renderSuggestion(command, el) {
el.setText(command.name);
}
selectSuggestion(command) {
this.inputEl.value = command.id;
this.inputEl.trigger("input");
this.close();
}
};
// src/settings.ts
var CronSettingTab = class extends import_obsidian2.PluginSettingTab {
constructor(app2, plugin) {
super(app2, plugin);
this.plugin = plugin;
}
display() {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl("h2", { text: "Settings for Cron." });
new import_obsidian2.Setting(containerEl).setName("Cron Interval").setDesc("The interval the cron will run in minutes").addText(
(text) => text.setValue(this.plugin.settings.cronInterval.toString()).onChange(async (value) => {
if (value == "") {
return;
}
this.plugin.settings.cronInterval = parseInt(value);
await this.plugin.saveSettings();
this.plugin.loadInterval();
})
);
new import_obsidian2.Setting(containerEl).setName("Run cron on startup").setDesc("Do a cron run on startup instead of waiting for the first interval to pass").addToggle(
(toggle) => toggle.setValue(this.plugin.settings.runOnStartup).onChange(async (value) => {
this.plugin.settings.runOnStartup = value;
await this.plugin.saveSettings();
})
);
new import_obsidian2.Setting(containerEl).setName("Enable Obsidian Sync Checker").setDesc("Whether or not to wait for Obsidian sync before running any CRONs globally.").addToggle(
(toggle) => toggle.setValue(this.plugin.settings.watchObsidianSync).onChange(async (value) => {
this.plugin.settings.watchObsidianSync = value;
await this.plugin.saveSettings();
})
);
new import_obsidian2.Setting(containerEl).setName("Enable Obsidian on Mobile").setDesc("Whether or not to load jobs at all on Mobile devices. If disabled even jobs with mobile enabled will not run.").addToggle(
(toggle) => toggle.setValue(this.plugin.settings.enableMobile).onChange(async (value) => {
this.plugin.settings.enableMobile = value;
await this.plugin.saveSettings();
})
);
const desc = document.createDocumentFragment();
desc.append(
"List of CRON Jobs to run. Jobs will not be ran until all 3 fields have been filled",
desc.createEl("br"),
"Cron Frequency is a cron schedule expression. Use ",
desc.createEl("a", {
href: "https://crontab.guru/",
text: "crontab guru"
}),
" for help with creating cron schedule expressions."
);
new import_obsidian2.Setting(containerEl).setName("Cron Jobs").setDesc(desc);
this.addCommandSearch();
}
addCommandSearch() {
this.plugin.settings.crons.forEach((cronjob, index) => {
const jobSetting = new import_obsidian2.Setting(this.containerEl).addText(
(text) => text.setValue(cronjob.name).setPlaceholder("Job name").onChange(async (value) => {
this.plugin.settings.crons[index].name = value;
await this.plugin.saveSettings();
this.plugin.loadCrons();
}).inputEl.addClass("cron-plugin-text-input")
).addSearch((cb) => {
new CommandSuggest(cb.inputEl);
cb.setPlaceholder("Command").setValue(cronjob.job).onChange(async (command) => {
if (!command) {
return;
}
this.plugin.settings.crons[index].job = command;
await this.plugin.saveSettings();
this.plugin.loadCrons();
}).inputEl.addClass("cron-plugin-text-input");
}).addText(
(text) => text.setPlaceholder("CronJob frequency").setValue(cronjob.frequency).onChange(async (value) => {
this.plugin.settings.crons[index].frequency = value;
await this.plugin.saveSettings();
this.plugin.loadCrons();
}).inputEl.addClass("cron-plugin-text-input")
).addExtraButton((button) => {
button.setIcon(cronjob.settings.enableMobile ? "lucide-phone" : "lucide-phone-off").setTooltip("Toggle job on mobile").onClick(async () => {
this.plugin.settings.crons[index].settings.enableMobile = !cronjob.settings.enableMobile;
await this.plugin.saveSettings();
this.display();
});
});
const jobLocked = this.plugin.settings.locks[cronjob.name] && this.plugin.settings.locks[cronjob.name].locked;
jobSetting.addExtraButton((button) => {
button.setIcon(jobLocked ? "lucide-lock" : "lucide-unlock").setTooltip("Toggle job lock (clear lock if accidentally left locked)").onClick(() => {
this.plugin.settings.locks[cronjob.id].locked = !jobLocked;
this.plugin.saveSettings();
this.display();
});
});
jobSetting.addExtraButton((button) => {
button.setIcon(cronjob.settings.disableSyncCheck ? "paused" : "lucide-check-circle-2").setTooltip("Toggle Sync check for this job. Presently: " + (cronjob.settings.disableSyncCheck ? "disabled" : "enabled")).onClick(() => {
this.plugin.settings.crons[index].settings.disableSyncCheck = !cronjob.settings.disableSyncCheck;
this.plugin.saveSettings();
this.display();
});
}).addExtraButton((button) => {
button.setIcon("cross").setTooltip("Delete Job").onClick(() => {
this.plugin.settings.crons.splice(index, 1);
delete this.plugin.settings.locks[cronjob.id];
this.plugin.saveSettings();
this.display();
});
});
jobSetting.controlEl.addClass("cron-plugin-job");
});
new import_obsidian2.Setting(this.containerEl).addButton((cb) => {
cb.setButtonText("Add cron job").setCta().onClick(() => {
this.plugin.settings.crons.push({
id: v4_default(),
name: "",
job: "",
frequency: "",
settings: {
enableMobile: false
}
});
this.plugin.saveSettings();
this.display();
});
});
}
};
// src/syncChecker.ts
var syncEmitterName = "status-change";
var syncCompletedStatus = "synced";
var syncWaiterCtxID = "syncWaiter";
var SyncChecker = class {
constructor(app2, plugin) {
this.syncInstance = app2.internalPlugins.plugins["sync"].instance;
this.plugin = plugin;
this.syncWaiters = [];
this.syncInstance.on(syncEmitterName, this.handleSyncStatusChange.bind(this), syncWaiterCtxID);
}
deviceName() {
return this.syncInstance.deviceName ? this.syncInstance.deviceName : this.syncInstance.getDefaultDeviceName();
}
handleSyncStatusChange() {
if (this.syncInstance.getStatus() === syncCompletedStatus) {
this.clearSyncWaiters();
}
}
clearSyncWaiters() {
this.syncWaiters.forEach((waiter) => {
waiter.resolve();
});
}
handleUnload() {
this.syncWaiters.forEach((waiter) => {
waiter.reject("Unloading plugin");
});
this.syncInstance._[syncEmitterName] = this.syncInstance._[syncEmitterName].filter((listener) => {
if (listener.ctx === syncWaiterCtxID)
return false;
return true;
});
}
waitForSync(settings) {
return new Promise((resolve, reject) => {
if (settings.disableSyncCheck)
resolve();
if (!this.plugin.settings.watchObsidianSync)
resolve();
if (this.syncInstance.getStatus() === syncCompletedStatus) {
resolve();
}
this.syncWaiters.push({ resolve, reject });
});
}
};
// src/api.ts
var CronAPI = class {
static get(plugin) {
return {
addCronJob(name, frequency, settings, job) {
return plugin.addCronJob(name, frequency, settings, job);
},
runJob(name) {
return plugin.runJob(name);
},
clearJobLock(name) {
return plugin.clearJobLock(name);
},
getJob(name) {
return plugin.getJob(name);
}
};
}
};
// src/main.ts
var DEFAULT_SETTINGS = {
cronInterval: 15,
runOnStartup: true,
enableMobile: true,
watchObsidianSync: true,
crons: [],
locks: {}
};
var Cron = class extends import_obsidian3.Plugin {
async onload() {
console.log("Loading Obsidian CRON!");
Cron.instance = this;
await this.loadSettings();
this.addSettingTab(new CronSettingTab(this.app, this));
this.syncChecker = new SyncChecker(this.app, this);
this.jobs = {};
this.loadCrons();
this.loadInterval();
this.api = CronAPI.get(this);
this.app.workspace.onLayoutReady(() => {
if (this.settings.runOnStartup) {
if (this.app.isMobile && !this.settings.enableMobile) {
return;
}
this.runCron();
}
});
}
async runCron() {
for (const [, job] of Object.entries(this.jobs)) {
await this.syncChecker.waitForSync(job.settings);
await this.loadSettings();
if (!job.canRunJob()) {
continue;
}
await job.runJob();
}
}
addCronJob(name, frequency, settings, job) {
const existingJob = this.getJob(name);
if (existingJob)
throw new Error("CRON Job already exists");
this.jobs[name] = new Job(name, name, job, frequency, settings, this.app, this, this.syncChecker);
}
async runJob(name) {
const job = this.getJob(name);
if (!job)
throw new Error("CRON Job doesn't exist");
await job.runJob();
}
clearJobLock(name) {
const job = this.getJob(name);
if (!job)
throw new Error("CRON Job doesn't exist");
job.clearJobLock();
}
getJob(name) {
for (const [, job] of Object.entries(this.jobs)) {
if (job.name == name)
return job;
}
return null;
}
onunload() {
if (this.settings.watchObsidianSync)
this.syncChecker.handleUnload();
console.log("Cron unloaded");
}
loadCrons() {
this.settings.crons.forEach((cronjob) => {
if (cronjob.frequency === "" || cronjob.job === "") {
return;
}
this.jobs[cronjob.id] = new Job(cronjob.id, cronjob.name, cronjob.job, cronjob.frequency, cronjob.settings, this.app, this, this.syncChecker);
});
}
loadInterval() {
clearInterval(this.interval);
if (this.app.isMobile && !this.settings.enableMobile) {
return;
}
this.interval = window.setInterval(async () => {
await this.runCron();
}, this.settings.cronInterval * 60 * 1e3);
this.registerInterval(this.interval);
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
};