diff --git a/weather@mockturtl/CHANGELOG.md b/weather@mockturtl/CHANGELOG.md index 2ec6b515542..d25fdd1ea7d 100644 --- a/weather@mockturtl/CHANGELOG.md +++ b/weather@mockturtl/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## 3.4.0 + +* Fix [#5212](https://github.com/linuxmint/cinnamon-spices-applets/issues/5212) +* Fix [#5392](https://github.com/linuxmint/cinnamon-spices-applets/issues/5392) +* Fix [#5355](https://github.com/linuxmint/cinnamon-spices-applets/issues/5355) +* Add description to Manual location entry +* Fix Saving Logs button not included the redacted config +* Update library typings for applet +* Use fedora geoip project for autolocation via the internet + ## 3.3.1 Fix nominatim not getting location data due to API changes. Related issues: diff --git a/weather@mockturtl/files/weather@mockturtl/3.8/settings-schema.json b/weather@mockturtl/files/weather@mockturtl/3.8/settings-schema.json index 0389f8927c1..a459c5f3da5 100644 --- a/weather@mockturtl/files/weather@mockturtl/3.8/settings-schema.json +++ b/weather@mockturtl/files/weather@mockturtl/3.8/settings-schema.json @@ -56,7 +56,8 @@ "title": "Location settings", "keys": [ "manualLocation", - "location" + "location", + "locationDescription" ] }, "location-store": { @@ -218,6 +219,11 @@ "description": "Location", "tooltip": "You can enter coordinates 'Latitude,Longitude' (e.g. 51.5085,-0.1257) or use 'City,Country-code' (e.g. London,UK) or try to enter {House number} {Street} {City/Town} {Postcode} {Country}. The search algorithm is very flexible with the format. After 3 seconds without typing the address you entered is replaced automatically for validating your choice." }, + "locationDescription": { + "type": "label", + "dependency": "manualLocation", + "description": "If the location field matches a saved location's 'Search Entry' field, the saved location will be used instead." + }, "saveLocation": { "type": "button", "indent": true, diff --git a/weather@mockturtl/files/weather@mockturtl/3.8/weather-applet.js b/weather@mockturtl/files/weather@mockturtl/3.8/weather-applet.js index edd4e7bd3e2..2537076c38d 100644 --- a/weather@mockturtl/files/weather@mockturtl/3.8/weather-applet.js +++ b/weather@mockturtl/files/weather@mockturtl/3.8/weather-applet.js @@ -10,163 +10,165 @@ var weatherApplet; SunCalc is a JavaScript library for calculating sun/moon position and light phases. https://github.com/mourner/suncalc */ - (function () { - 'use strict'; + 'use strict'; // shortcuts for easier to read formulas - // shortcuts for easier to read formulas var PI = Math.PI, - sin = Math.sin, - cos = Math.cos, - tan = Math.tan, - asin = Math.asin, - atan = Math.atan2, - acos = Math.acos, - rad = PI / 180; - - // sun calculations are based on http://aa.quae.nl/en/reken/zonpositie.html formulas - + sin = Math.sin, + cos = Math.cos, + tan = Math.tan, + asin = Math.asin, + atan = Math.atan2, + acos = Math.acos, + rad = PI / 180; // sun calculations are based on http://aa.quae.nl/en/reken/zonpositie.html formulas // date/time constants and conversions var dayMs = 1000 * 60 * 60 * 24, - J1970 = 2440588, - J2000 = 2451545; + J1970 = 2440588, + J2000 = 2451545; + function toJulian(date) { return date.valueOf() / dayMs - 0.5 + J1970; } + function fromJulian(j) { return new Date((j + 0.5 - J1970) * dayMs); } + function toDays(date) { return toJulian(date) - J2000; - } + } // general calculations for position - // general calculations for position var e = rad * 23.4397; // obliquity of the Earth function rightAscension(l, b) { return atan(sin(l) * cos(e) - tan(b) * sin(e), cos(l)); } + function declination(l, b) { return asin(sin(b) * cos(e) + cos(b) * sin(e) * sin(l)); } + function azimuth(H, phi, dec) { return atan(sin(H), cos(H) * sin(phi) - tan(dec) * cos(phi)); } + function altitude(H, phi, dec) { return asin(sin(phi) * sin(dec) + cos(phi) * cos(dec) * cos(H)); } + function siderealTime(d, lw) { return rad * (280.16 + 360.9856235 * d) - lw; } + function astroRefraction(h) { - if (h < 0) - // the following formula works for positive altitudes only. + if (h < 0) // the following formula works for positive altitudes only. h = 0; // if h = -0.08901179 a div/0 would occur. - // formula 16.4 of "Astronomical Algorithms" 2nd edition by Jean Meeus (Willmann-Bell, Richmond) 1998. // 1.02 / tan(h + 10.26 / (h + 5.10)) h in degrees, result in arc minutes -> converted to rad: + return 0.0002967 / Math.tan(h + 0.00312536 / (h + 0.08901179)); - } + } // general sun calculations - // general sun calculations function solarMeanAnomaly(d) { return rad * (357.5291 + 0.98560028 * d); } + function eclipticLongitude(M) { var C = rad * (1.9148 * sin(M) + 0.02 * sin(2 * M) + 0.0003 * sin(3 * M)), - // equation of center - P = rad * 102.9372; // perihelion of the Earth + // equation of center + P = rad * 102.9372; // perihelion of the Earth return M + C + P + PI; } + function sunCoords(d) { var M = solarMeanAnomaly(d), - L = eclipticLongitude(M); + L = eclipticLongitude(M); return { dec: declination(L, 0), ra: rightAscension(L, 0) }; } - var SunCalc = {}; - // calculates sun position for a given date and latitude/longitude + var SunCalc = {}; // calculates sun position for a given date and latitude/longitude SunCalc.getPosition = function (date, lat, lng) { var lw = rad * -lng, - phi = rad * lat, - d = toDays(date), - c = sunCoords(d), - H = siderealTime(d, lw) - c.ra; + phi = rad * lat, + d = toDays(date), + c = sunCoords(d), + H = siderealTime(d, lw) - c.ra; return { azimuth: azimuth(H, phi, c.dec), altitude: altitude(H, phi, c.dec) }; - }; + }; // sun times configuration (angle, morning name, evening name) - // sun times configuration (angle, morning name, evening name) - var times = SunCalc.times = [[-0.833, 'sunrise', 'sunset'], [-0.3, 'sunriseEnd', 'sunsetStart'], [-6, 'dawn', 'dusk'], [-12, 'nauticalDawn', 'nauticalDusk'], [-18, 'nightEnd', 'night'], [6, 'goldenHourEnd', 'goldenHour']]; - - // adds a custom time to the times config + var times = SunCalc.times = [[-0.833, 'sunrise', 'sunset'], [-0.3, 'sunriseEnd', 'sunsetStart'], [-6, 'dawn', 'dusk'], [-12, 'nauticalDawn', 'nauticalDusk'], [-18, 'nightEnd', 'night'], [6, 'goldenHourEnd', 'goldenHour']]; // adds a custom time to the times config SunCalc.addTime = function (angle, riseName, setName) { times.push([angle, riseName, setName]); - }; + }; // calculations for sun times - // calculations for sun times var J0 = 0.0009; + function julianCycle(d, lw) { return Math.round(d - J0 - lw / (2 * PI)); } + function approxTransit(Ht, lw, n) { return J0 + (Ht + lw) / (2 * PI) + n; } + function solarTransitJ(ds, M, L) { return J2000 + ds + 0.0053 * sin(M) - 0.0069 * sin(2 * L); } + function hourAngle(h, phi, d) { return acos((sin(h) - sin(phi) * sin(d)) / (cos(phi) * cos(d))); } + function observerAngle(height) { return -2.076 * Math.sqrt(height) / 60; - } + } // returns set time for the given sun altitude + - // returns set time for the given sun altitude function getSetJ(h, lw, phi, dec, n, M, L) { var w = hourAngle(h, phi, dec), - a = approxTransit(w, lw, n); + a = approxTransit(w, lw, n); return solarTransitJ(a, M, L); - } - - // calculates sun times for a given date, latitude/longitude, and, optionally, + } // calculates sun times for a given date, latitude/longitude, and, optionally, // the observer height (in meters) relative to the horizon + SunCalc.getTimes = function (date, lat, lng, height) { height = height || 0; var lw = rad * -lng, - phi = rad * lat, - dh = observerAngle(height), - d = toDays(date), - n = julianCycle(d, lw), - ds = approxTransit(0, lw, n), - M = solarMeanAnomaly(ds), - L = eclipticLongitude(M), - dec = declination(L, 0), - Jnoon = solarTransitJ(ds, M, L), - i, - len, - time, - h0, - Jset, - Jrise; + phi = rad * lat, + dh = observerAngle(height), + d = toDays(date), + n = julianCycle(d, lw), + ds = approxTransit(0, lw, n), + M = solarMeanAnomaly(ds), + L = eclipticLongitude(M), + dec = declination(L, 0), + Jnoon = solarTransitJ(ds, M, L), + i, + len, + time, + h0, + Jset, + Jrise; var result = { solarNoon: fromJulian(Jnoon), nadir: fromJulian(Jnoon - 0.5) }; + for (i = 0, len = times.length; i < len; i += 1) { time = times[i]; h0 = (time[0] + dh) * rad; @@ -175,26 +177,24 @@ var weatherApplet; result[time[1]] = fromJulian(Jrise); result[time[2]] = fromJulian(Jset); } + return result; - }; + }; // moon calculations, based on http://aa.quae.nl/en/reken/hemelpositie.html formulas - // moon calculations, based on http://aa.quae.nl/en/reken/hemelpositie.html formulas function moonCoords(d) { // geocentric ecliptic coordinates of the moon - var L = rad * (218.316 + 13.176396 * d), - // ecliptic longitude - M = rad * (134.963 + 13.064993 * d), - // mean anomaly - F = rad * (93.272 + 13.229350 * d), - // mean distance - - l = L + rad * 6.289 * sin(M), - // longitude - b = rad * 5.128 * sin(F), - // latitude - dt = 385001 - 20905 * cos(M); // distance to the moon in km + // ecliptic longitude + M = rad * (134.963 + 13.064993 * d), + // mean anomaly + F = rad * (93.272 + 13.229350 * d), + // mean distance + l = L + rad * 6.289 * sin(M), + // longitude + b = rad * 5.128 * sin(F), + // latitude + dt = 385001 - 20905 * cos(M); // distance to the moon in km return { ra: rightAscension(l, b), @@ -202,15 +202,16 @@ var weatherApplet; dist: dt }; } + SunCalc.getMoonPosition = function (date, lat, lng) { var lw = rad * -lng, - phi = rad * lat, - d = toDays(date), - c = moonCoords(d), - H = siderealTime(d, lw) - c.ra, - h = altitude(H, phi, c.dec), - // formula 14.1 of "Astronomical Algorithms" 2nd edition by Jean Meeus (Willmann-Bell, Richmond) 1998. - pa = atan(sin(H), tan(phi) * cos(c.dec) - sin(c.dec) * cos(H)); + phi = rad * lat, + d = toDays(date), + c = moonCoords(d), + H = siderealTime(d, lw) - c.ra, + h = altitude(H, phi, c.dec), + // formula 14.1 of "Astronomical Algorithms" 2nd edition by Jean Meeus (Willmann-Bell, Richmond) 1998. + pa = atan(sin(H), tan(phi) * cos(c.dec) - sin(c.dec) * cos(H)); h = h + astroRefraction(h); // altitude correction for refraction return { @@ -219,54 +220,51 @@ var weatherApplet; distance: c.dist, parallacticAngle: pa }; - }; - - // calculations for illumination parameters of the moon, + }; // calculations for illumination parameters of the moon, // based on http://idlastro.gsfc.nasa.gov/ftp/pro/astro/mphase.pro formulas and // Chapter 48 of "Astronomical Algorithms" 2nd edition by Jean Meeus (Willmann-Bell, Richmond) 1998. + SunCalc.getMoonIllumination = function (date) { var d = toDays(date || new Date()), - s = sunCoords(d), - m = moonCoords(d), - sdist = 149598000, - // distance from Earth to Sun in km - - phi = acos(sin(s.dec) * sin(m.dec) + cos(s.dec) * cos(m.dec) * cos(s.ra - m.ra)), - inc = atan(sdist * sin(phi), m.dist - sdist * cos(phi)), - angle = atan(cos(s.dec) * sin(s.ra - m.ra), sin(s.dec) * cos(m.dec) - cos(s.dec) * sin(m.dec) * cos(s.ra - m.ra)); + s = sunCoords(d), + m = moonCoords(d), + sdist = 149598000, + // distance from Earth to Sun in km + phi = acos(sin(s.dec) * sin(m.dec) + cos(s.dec) * cos(m.dec) * cos(s.ra - m.ra)), + inc = atan(sdist * sin(phi), m.dist - sdist * cos(phi)), + angle = atan(cos(s.dec) * sin(s.ra - m.ra), sin(s.dec) * cos(m.dec) - cos(s.dec) * sin(m.dec) * cos(s.ra - m.ra)); return { fraction: (1 + cos(inc)) / 2, phase: 0.5 + 0.5 * inc * (angle < 0 ? -1 : 1) / Math.PI, angle: angle }; }; + function hoursLater(date, h) { return new Date(date.valueOf() + h * dayMs / 24); - } + } // calculations for moon rise/set times are based on http://www.stargazing.net/kepler/moonrise.html article - // calculations for moon rise/set times are based on http://www.stargazing.net/kepler/moonrise.html article SunCalc.getMoonTimes = function (date, lat, lng, inUTC) { var t = new Date(date); if (inUTC) t.setUTCHours(0, 0, 0, 0);else t.setHours(0, 0, 0, 0); var hc = 0.133 * rad, - h0 = SunCalc.getMoonPosition(t, lat, lng).altitude - hc, - h1, - h2, - rise, - set, - a, - b, - xe, - ye, - d, - roots, - x1, - x2, - dx; - - // go in 2-hour chunks, each time seeing if a 3-point quadratic curve crosses zero (which means rise or set) + h0 = SunCalc.getMoonPosition(t, lat, lng).altitude - hc, + h1, + h2, + rise, + set, + a, + b, + xe, + ye, + d, + roots, + x1, + x2, + dx; // go in 2-hour chunks, each time seeing if a 3-point quadratic curve crosses zero (which means rise or set) + for (var i = 1; i <= 24; i += 2) { h1 = SunCalc.getMoonPosition(hoursLater(t, i), lat, lng).altitude - hc; h2 = SunCalc.getMoonPosition(hoursLater(t, i + 1), lat, lng).altitude - hc; @@ -276,6 +274,7 @@ var weatherApplet; ye = (a * xe + b) * xe + h1; d = b * b - 4 * a * h1; roots = 0; + if (d >= 0) { dx = Math.sqrt(d) / (Math.abs(a) * 2); x1 = xe - dx; @@ -284,23 +283,26 @@ var weatherApplet; if (Math.abs(x2) <= 1) roots++; if (x1 < -1) x1 = x2; } + if (roots === 1) { if (h0 < 0) rise = i + x1;else set = i + x1; } else if (roots === 2) { rise = i + (ye < 0 ? x2 : x1); set = i + (ye < 0 ? x1 : x2); } + if (rise && set) break; h0 = h2; } + var result = {}; if (rise) result.rise = hoursLater(t, rise); if (set) result.set = hoursLater(t, set); if (!rise && !set) result[ye > 0 ? 'alwaysUp' : 'alwaysDown'] = true; return result; - }; + }; // export as Node module / AMD module / browser variable + - // export as Node module / AMD module / browser variable if (true) module.exports = SunCalc;else {} })(); @@ -508,69 +510,74 @@ const distanceUnitLocales = { * @private */ class LuxonError extends Error {} - /** * @private */ + + class InvalidDateTimeError extends LuxonError { constructor(reason) { super(`Invalid DateTime: ${reason.toMessage()}`); } -} +} /** * @private */ + class InvalidIntervalError extends LuxonError { constructor(reason) { super(`Invalid Interval: ${reason.toMessage()}`); } -} +} /** * @private */ + class InvalidDurationError extends LuxonError { constructor(reason) { super(`Invalid Duration: ${reason.toMessage()}`); } -} +} /** * @private */ -class ConflictingSpecificationError extends LuxonError {} +class ConflictingSpecificationError extends LuxonError {} /** * @private */ + class InvalidUnitError extends LuxonError { constructor(unit) { super(`Invalid unit ${unit}`); } -} +} /** * @private */ -class InvalidArgumentError extends LuxonError {} +class InvalidArgumentError extends LuxonError {} /** * @private */ + class ZoneIsAbstractError extends LuxonError { constructor() { super("Zone is an abstract class"); } + } ;// CONCATENATED MODULE: ./node_modules/luxon/src/impl/formats.js /** * @private */ - const n = "numeric", - s = "short", - l = "long"; + s = "short", + l = "long"; const DATE_SHORT = { year: n, month: n, @@ -720,10 +727,10 @@ const DATETIME_HUGE_WITH_SECONDS = { }; ;// CONCATENATED MODULE: ./node_modules/luxon/src/zone.js - /** * @interface */ + class Zone { /** * The type of zone @@ -733,28 +740,30 @@ class Zone { 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 @@ -764,10 +773,11 @@ class Zone { * @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 @@ -776,48 +786,54 @@ class Zone { * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively * @return {string} */ + + formatOffset(ts, format) { 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(); } + } ;// CONCATENATED MODULE: ./node_modules/luxon/src/zones/systemZone.js let singleton = null; - /** * Represents the local zone for this JavaScript environment. * @implements {Zone} */ + class SystemZone extends Zone { /** * Get a singleton instance of the local zone @@ -827,61 +843,78 @@ class SystemZone extends Zone { if (singleton === null) { singleton = new SystemZone(); } + return singleton; } - /** @override **/ + + get type() { return "system"; } - /** @override **/ + + get name() { return new Intl.DateTimeFormat().resolvedOptions().timeZone; } - /** @override **/ + + get isUniversal() { return false; } - /** @override **/ + + offsetName(ts, _ref) { let format = _ref.format, - locale = _ref.locale; + locale = _ref.locale; return parseZoneInfo(ts, format, locale); } - /** @override **/ + + formatOffset(ts, format) { return formatOffset(this.offset(ts), format); } - /** @override **/ + + offset(ts) { return -new Date(ts).getTimezoneOffset(); } - /** @override **/ + + equals(otherZone) { return otherZone.type === "system"; } - /** @override **/ + + get isValid() { return true; } + } ;// CONCATENATED MODULE: ./node_modules/luxon/src/zones/IANAZone.js function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } + function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } -function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } } + +function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + let dtfCache = {}; + function makeDTF(zone) { if (!dtfCache[zone]) { dtfCache[zone] = new Intl.DateTimeFormat("en-US", { @@ -896,8 +929,10 @@ function makeDTF(zone) { era: "short" }); } + return dtfCache[zone]; } + const typeToPos = { year: 0, month: 1, @@ -907,40 +942,48 @@ const typeToPos = { 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), - _parsed = _slicedToArray(parsed, 8), - fMonth = _parsed[1], - fDay = _parsed[2], - fYear = _parsed[3], - fadOrBc = _parsed[4], - fHour = _parsed[5], - fMinute = _parsed[6], - fSecond = _parsed[7]; + parsed = /(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(formatted), + _parsed = _slicedToArray(parsed, 8), + fMonth = _parsed[1], + fDay = _parsed[2], + fYear = _parsed[3], + fadOrBc = _parsed[4], + fHour = _parsed[5], + fMinute = _parsed[6], + fSecond = _parsed[7]; + 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 _formatted$i = formatted[i], - type = _formatted$i.type, - value = _formatted$i.value; + type = _formatted$i.type, + value = _formatted$i.value; const pos = typeToPos[type]; + if (type === "era") { filled[pos] = value; } else if (!isUndefined(pos)) { filled[pos] = parseInt(value, 10); } } + return filled; } + let ianaZoneCache = {}; /** * A zone identified by an IANA identifier, like America/New_York * @implements {Zone} */ + class IANAZone extends Zone { /** * @param {string} name - Zone name @@ -950,18 +993,19 @@ class IANAZone extends Zone { 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 @@ -970,10 +1014,11 @@ class IANAZone extends Zone { * @deprecated This method returns false for some valid IANA names. Use isValidZone instead. * @return {boolean} */ + + static isValidSpecifier(s) { return this.isValidZone(s); } - /** * Returns whether the provided string identifies a real zone * @param {string} zone - The string to check @@ -982,10 +1027,13 @@ class IANAZone extends Zone { * @example IANAZone.isValidZone("Sport~~blorp") //=> false * @return {boolean} */ + + static isValidZone(zone) { if (!zone) { return false; } + try { new Intl.DateTimeFormat("en-US", { timeZone: zone @@ -995,60 +1043,71 @@ class IANAZone extends Zone { return false; } } + constructor(name) { super(); /** @private **/ + this.zoneName = name; /** @private **/ + this.valid = IANAZone.isValidZone(name); } - /** @override **/ + + get type() { return "iana"; } - /** @override **/ + + get name() { return this.zoneName; } - /** @override **/ + + get isUniversal() { return false; } - /** @override **/ + + offsetName(ts, _ref) { let format = _ref.format, - locale = _ref.locale; + locale = _ref.locale; return parseZoneInfo(ts, format, locale, this.name); } - /** @override **/ + + formatOffset(ts, format) { return formatOffset(this.offset(ts), format); } - /** @override **/ + + offset(ts) { const date = new Date(ts); if (isNaN(date)) return NaN; const dtf = makeDTF(this.name); + let _ref2 = dtf.formatToParts ? partsOffset(dtf, date) : hackyOffset(dtf, date), - _ref3 = _slicedToArray(_ref2, 7), - year = _ref3[0], - month = _ref3[1], - day = _ref3[2], - adOrBc = _ref3[3], - hour = _ref3[4], - minute = _ref3[5], - second = _ref3[6]; + _ref3 = _slicedToArray(_ref2, 7), + year = _ref3[0], + month = _ref3[1], + day = _ref3[2], + adOrBc = _ref3[3], + hour = _ref3[4], + minute = _ref3[5], + second = _ref3[6]; + if (adOrBc === "BC") { year = -Math.abs(year) + 1; - } + } // because we're using hour12 and https://bugs.chromium.org/p/chromium/issues/detail?id=1025564&can=2&q=%2224%3A00%22%20datetimeformat + - // because we're using hour12 and https://bugs.chromium.org/p/chromium/issues/detail?id=1025564&can=2&q=%2224%3A00%22%20datetimeformat const adjustedHour = hour === 24 ? 0 : hour; const asUTC = objToLocalTS({ year, @@ -1064,88 +1123,119 @@ class IANAZone extends Zone { asTS -= over >= 0 ? over : 1000 + over; return (asUTC - asTS) / (60 * 1000); } - /** @override **/ + + equals(otherZone) { return otherZone.type === "iana" && otherZone.name === this.name; } - /** @override **/ + + get isValid() { return this.valid; } + } ;// CONCATENATED MODULE: ./node_modules/luxon/src/impl/locale.js const _excluded = ["base"], - _excluded2 = ["padTo", "floor"]; + _excluded2 = ["padTo", "floor"]; + function locale_slicedToArray(arr, i) { return locale_arrayWithHoles(arr) || locale_iterableToArrayLimit(arr, i) || locale_unsupportedIterableToArray(arr, i) || locale_nonIterableRest(); } + function locale_nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + function locale_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return locale_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return locale_arrayLikeToArray(o, minLen); } + function locale_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } -function locale_iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } } + +function locale_iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + function locale_arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } + function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } -function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } -function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } +function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } -// todo - remap caching + // todo - remap caching let intlLFCache = {}; + function getCachedLF(locString) { let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; const key = JSON.stringify([locString, opts]); let dtf = intlLFCache[key]; + if (!dtf) { dtf = new Intl.ListFormat(locString, opts); intlLFCache[key] = dtf; } + return dtf; } + let intlDTCache = {}; + function getCachedDTF(locString) { let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; const key = JSON.stringify([locString, opts]); let dtf = intlDTCache[key]; + if (!dtf) { dtf = new Intl.DateTimeFormat(locString, opts); intlDTCache[key] = dtf; } + return dtf; } + let intlNumCache = {}; + function getCachedINF(locString) { let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; const key = JSON.stringify([locString, opts]); let inf = intlNumCache[key]; + if (!inf) { inf = new Intl.NumberFormat(locString, opts); intlNumCache[key] = inf; } + return inf; } + let intlRelCache = {}; + function getCachedRTF(locString) { let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + const base = opts.base, - cacheKeyOpts = _objectWithoutProperties(opts, _excluded); // exclude `base` from the options + cacheKeyOpts = _objectWithoutProperties(opts, _excluded); // exclude `base` from the options + + const key = JSON.stringify([locString, cacheKeyOpts]); let inf = intlRelCache[key]; + if (!inf) { inf = new Intl.RelativeTimeFormat(locString, opts); intlRelCache[key] = inf; } + return inf; } + let sysLocaleCache = null; + function systemLocale() { if (sysLocaleCache) { return sysLocaleCache; @@ -1154,65 +1244,79 @@ function systemLocale() { return sysLocaleCache; } } + function parseLocaleString(localeStr) { // I really want to avoid writing a BCP 47 parser // see, e.g. https://github.com/wooorm/bcp-47 // Instead, we'll do this: - // a) if the string has no -u extensions, just leave it alone // b) if it does, use Intl to resolve everything // c) if Intl fails, try again without the -u - const uIndex = localeStr.indexOf("-u-"); + if (uIndex === -1) { return [localeStr]; } else { let options; const smaller = localeStr.substring(0, uIndex); + try { options = getCachedDTF(localeStr).resolvedOptions(); } catch (e) { options = getCachedDTF(smaller).resolvedOptions(); } + const _options = options, - numberingSystem = _options.numberingSystem, - calendar = _options.calendar; - // return the smaller one so that we can append the calendar and numbering overrides to it + numberingSystem = _options.numberingSystem, + calendar = _options.calendar; // return the smaller one so that we can append the calendar and numbering overrides to it + return [smaller, numberingSystem, calendar]; } } + function intlConfigString(localeStr, numberingSystem, outputCalendar) { if (outputCalendar || numberingSystem) { 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") { @@ -1221,6 +1325,7 @@ function listStuff(loc, length, defaultOK, englishFn, intlFn) { return intlFn(length); } } + function supportsFastNumbers(loc) { if (loc.numberingSystem && loc.numberingSystem !== "latn") { return false; @@ -1228,26 +1333,30 @@ function supportsFastNumbers(loc) { return loc.numberingSystem === "latn" || !loc.locale || loc.locale.startsWith("en") || new Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem === "latn"; } } - /** * @private */ + class PolyNumberFormatter { constructor(intl, forceSimple, opts) { this.padTo = opts.padTo || 0; this.floor = opts.floor || false; + const padTo = opts.padTo, - floor = opts.floor, - otherOpts = _objectWithoutProperties(opts, _excluded2); + floor = opts.floor, + otherOpts = _objectWithoutProperties(opts, _excluded2); + if (!forceSimple || Object.keys(otherOpts).length > 0) { const intlOpts = _objectSpread({ 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; @@ -1258,16 +1367,18 @@ class PolyNumberFormatter { return padStart(fixed, this.padTo); } } -} +} /** * @private */ + class PolyDateFormatter { constructor(dt, intl, opts) { this.opts = opts; let z = undefined; + if (dt.zone.isUniversal) { // UTC-8 or Etc/UTC-8 are not part of tzdata, only Etc/GMT+8 and the like. // That is why fixed-offset TZ is set to that unless it is: @@ -1277,6 +1388,7 @@ class PolyDateFormatter { // - < Etc/GMT-14, > Etc/GMT+12, and 30-minute or 45-minute offsets are not part of tzdata 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; @@ -1289,6 +1401,7 @@ class PolyDateFormatter { // the time and tell the formatter to show it to us in UTC, so that the time is right // and the bad zone doesn't show up. z = "UTC"; + if (opts.timeZoneName) { this.dt = dt; } else { @@ -1301,33 +1414,42 @@ class PolyDateFormatter { this.dt = dt; z = dt.zone.name; } + const intlOpts = _objectSpread({}, this.opts); + intlOpts.timeZone = intlOpts.timeZone || z; this.dtf = getCachedDTF(intl, intlOpts); } + format() { return this.dtf.format(this.dt.toJSDate()); } + formatToParts() { return this.dtf.formatToParts(this.dt.toJSDate()); } + resolvedOptions() { return this.dtf.resolvedOptions(); } -} +} /** * @private */ + + class PolyRelFormatter { constructor(intl, isEnglish, opts) { this.opts = _objectSpread({ style: "long" }, opts); + if (!isEnglish && hasRelative()) { this.rtf = getCachedRTF(intl, opts); } } + format(count, unit) { if (this.rtf) { return this.rtf.format(count, unit); @@ -1335,6 +1457,7 @@ class PolyRelFormatter { return formatRelativeTime(unit, count, this.opts.numeric, this.opts.style !== "long"); } } + formatToParts(count, unit) { if (this.rtf) { return this.rtf.formatToParts(count, unit); @@ -1342,44 +1465,51 @@ class PolyRelFormatter { return []; } } -} +} /** * @private */ + class Locale { static fromOpts(opts) { return Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.defaultToEN); } + static create(locale, numberingSystem, outputCalendar) { let defaultToEN = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; - const specifiedLocale = locale || Settings.defaultLocale; - // the system locale is useful for human readable strings but annoying for parsing/formatting known formats + const specifiedLocale = locale || Settings.defaultLocale; // the system locale is useful for human readable strings but annoying for parsing/formatting known formats + 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() { let _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - locale = _ref.locale, - numberingSystem = _ref.numberingSystem, - outputCalendar = _ref.outputCalendar; + locale = _ref.locale, + numberingSystem = _ref.numberingSystem, + outputCalendar = _ref.outputCalendar; + return Locale.create(locale, numberingSystem, outputCalendar); } + constructor(locale, numbering, outputCalendar, specifiedLocale) { const _parseLocaleString = parseLocaleString(locale), - _parseLocaleString2 = locale_slicedToArray(_parseLocaleString, 3), - parsedLocale = _parseLocaleString2[0], - parsedNumberingSystem = _parseLocaleString2[1], - parsedOutputCalendar = _parseLocaleString2[2]; + _parseLocaleString2 = locale_slicedToArray(_parseLocaleString, 3), + parsedLocale = _parseLocaleString2[0], + parsedNumberingSystem = _parseLocaleString2[1], + parsedOutputCalendar = _parseLocaleString2[2]; + this.locale = parsedLocale; this.numberingSystem = numbering || parsedNumberingSystem || null; this.outputCalendar = outputCalendar || parsedOutputCalendar || null; @@ -1397,17 +1527,21 @@ class Locale { 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; @@ -1415,54 +1549,63 @@ class Locale { return Locale.create(alts.locale || this.specifiedLocale, alts.numberingSystem || this.numberingSystem, alts.outputCalendar || this.outputCalendar, alts.defaultToEN || false); } } + redefaultToEN() { let alts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return this.clone(_objectSpread(_objectSpread({}, alts), {}, { defaultToEN: true })); } + redefaultToSystem() { let alts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return this.clone(_objectSpread(_objectSpread({}, alts), {}, { defaultToEN: false })); } + months(length) { let format = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; let defaultOK = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; return listStuff(this, length, defaultOK, months, () => { const intl = format ? { - month: length, - day: "numeric" - } : { - month: length - }, - formatStr = format ? "format" : "standalone"; + month: length, + day: "numeric" + } : { + month: length + }, + formatStr = format ? "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) { let format = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; let defaultOK = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; return listStuff(this, length, defaultOK, weekdays, () => { const intl = format ? { - weekday: length, - year: "numeric", - month: "long", - day: "numeric" - } : { - weekday: length - }, - formatStr = format ? "format" : "standalone"; + weekday: length, + year: "numeric", + month: "long", + day: "numeric" + } : { + weekday: length + }, + formatStr = format ? "format" : "standalone"; + if (!this.weekdaysCache[formatStr][length]) { this.weekdaysCache[formatStr][length] = mapWeekdays(dt => this.extract(dt, intl, "weekday")); } + return this.weekdaysCache[formatStr][length]; }); } + meridiems() { let defaultOK = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; return listStuff(this, undefined, defaultOK, () => meridiems, () => { @@ -1475,64 +1618,74 @@ class Locale { }; 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) { let defaultOK = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; return listStuff(this, length, defaultOK, eras, () => { const intl = { era: length - }; - - // This is problematic. Different calendars are going to define eras totally differently. What I need is the minimum set of dates + }; // This is problematic. Different calendars are going to define eras totally differently. What I need is the minimum set of dates // to definitely enumerate them. + 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); + results = df.formatToParts(), + matching = results.find(m => m.type.toLowerCase() === field); return matching ? matching.value : null; } + numberFormatter() { let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; // this forcesimple option is never used (the only caller short-circuits on it, but it seems safer to leave) // (in contrast, the rest of the condition is used heavily) return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts); } + dtFormatter(dt) { let intlOpts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return new PolyDateFormatter(dt, this.intl, intlOpts); } + relFormatter() { let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return new PolyRelFormatter(this.intl, this.isEnglish(), opts); } + listFormatter() { let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; 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; } + } ;// CONCATENATED MODULE: ./node_modules/luxon/src/zones/fixedOffsetZone.js let fixedOffsetZone_singleton = null; - /** * A zone with a fixed offset (meaning no DST) * @implements {Zone} */ + class FixedOffsetZone extends Zone { /** * Get a singleton instance of UTC @@ -1542,18 +1695,19 @@ class FixedOffsetZone extends Zone { if (fixedOffsetZone_singleton === null) { fixedOffsetZone_singleton = new FixedOffsetZone(0); } + return fixedOffsetZone_singleton; } - /** * Get an instance with a specified offset * @param {number} offset - The offset in minutes * @return {FixedOffsetZone} */ + + static instance(offset) { return offset === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset); } - /** * Get an instance of FixedOffsetZone from a UTC offset string, like "UTC+6" * @param {string} s - The offset string to parse @@ -1562,30 +1716,39 @@ class FixedOffsetZone extends Zone { * @example FixedOffsetZone.parseSpecifier("UTC-6:00") * @return {FixedOffsetZone} */ + + static parseSpecifier(s) { if (s) { const r = s.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i); + if (r) { return new FixedOffsetZone(signedOffset(r[1], r[2])); } } + return null; } + constructor(offset) { super(); /** @private **/ + this.fixed = offset; } - /** @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"; @@ -1593,90 +1756,107 @@ class FixedOffsetZone extends Zone { return `Etc/GMT${formatOffset(-this.fixed, "narrow")}`; } } - /** @override **/ + + offsetName() { return this.name; } - /** @override **/ + + formatOffset(ts, format) { return formatOffset(this.fixed, format); } - /** @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; } + } ;// CONCATENATED MODULE: ./node_modules/luxon/src/zones/invalidZone.js - /** * A zone that failed to parse. You should never need to instantiate this. * @implements {Zone} */ + class InvalidZone extends Zone { constructor(zoneName) { super(); /** @private */ + 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; } + } ;// CONCATENATED MODULE: ./node_modules/luxon/src/impl/zoneUtil.js /** @@ -1688,9 +1868,9 @@ class InvalidZone extends Zone { - function normalizeZone(input, defaultZone) { let offset; + if (isUndefined(input) || input === null) { return defaultZone; } else if (input instanceof Zone) { @@ -1713,17 +1893,19 @@ function normalizeZone(input, defaultZone) { -let now = () => Date.now(), - defaultZone = "system", - defaultLocale = null, - defaultNumberingSystem = null, - defaultOutputCalendar = null, - twoDigitCutoffYear = 60, - throwOnInvalid; +let now = () => Date.now(), + defaultZone = "system", + defaultLocale = null, + defaultNumberingSystem = null, + defaultOutputCalendar = null, + twoDigitCutoffYear = 60, + throwOnInvalid; /** * Settings contains static getters and setters that control Luxon's overall behavior. Luxon is a simple library with few options, but the ones it does have live here. */ + + class Settings { /** * Get the callback for returning the current timestamp. @@ -1732,7 +1914,6 @@ class Settings { 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 @@ -1740,84 +1921,94 @@ class Settings { * @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(n) { now = n; } - /** * 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} @@ -1826,41 +2017,48 @@ class Settings { * @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(); } + } ;// CONCATENATED MODULE: ./node_modules/luxon/src/impl/util.js function util_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } + function util_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? util_ownKeys(Object(source), !0).forEach(function (key) { util_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : util_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } -function util_defineProperty(obj, key, value) { key = util_toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function util_toPropertyKey(arg) { var key = util_toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function util_toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } + +function util_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + /* This is just a junk drawer, containing anything used across multiple classes. Because Luxon is small(ish), this should stay small and we won't worry about splitting @@ -1868,12 +2066,9 @@ function util_toPrimitive(input, hint) { if (typeof input !== "object" || input */ - - /** * @private */ - // TYPES function isUndefined(o) { @@ -1890,9 +2085,7 @@ function isString(o) { } function isDate(o) { return Object.prototype.toString.call(o) === "[object Date]"; -} - -// CAPABILITIES +} // CAPABILITIES function hasRelative() { try { @@ -1900,9 +2093,7 @@ function hasRelative() { } catch (e) { return false; } -} - -// OBJECTS AND ARRAYS +} // OBJECTS AND ARRAYS function maybeArray(thing) { return Array.isArray(thing) ? thing : [thing]; @@ -1911,8 +2102,10 @@ function bestBy(arr, by, compare) { if (arr.length === 0) { return undefined; } + return arr.reduce((best, next) => { const pair = [by(next), next]; + if (!best) { return pair; } else if (compare(best[0], pair[0]) === best[0]) { @@ -1930,15 +2123,12 @@ function util_pick(obj, keys) { } function util_hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); -} - -// NUMBERS AND STRINGS +} // NUMBERS AND STRINGS function integerBetween(thing, bottom, top) { return isInteger(thing) && thing >= bottom && thing <= top; -} +} // x % n but takes the sign of n instead of x -// x % n but takes the sign of n instead of x function floorMod(x, n) { return x - n * Math.floor(x / n); } @@ -1946,11 +2136,13 @@ function padStart(input) { let n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2; const isNeg = input < 0; let padded; + if (isNeg) { padded = "-" + ("" + -input).padStart(n, "0"); } else { padded = ("" + input).padStart(n, "0"); } + return padded; } function parseInteger(string) { @@ -1979,11 +2171,9 @@ function parseMillis(fraction) { function roundTo(number, digits) { let towardZero = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; const factor = 10 ** digits, - rounder = towardZero ? Math.trunc : Math.round; + rounder = towardZero ? Math.trunc : Math.round; return rounder(number * factor) / factor; -} - -// DATE BASICS +} // DATE BASICS function isLeapYear(year) { return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); @@ -1993,74 +2183,72 @@ function daysInYear(year) { } function daysInMonth(year, month) { const modMonth = floorMod(month - 1, 12) + 1, - modYear = year + (month - modMonth) / 12; + 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]; } -} +} // covert a calendar object to a local timestamp (epoch, but with the offset baked in) -// covert a calendar object to a local timestamp (epoch, but with the offset baked in) function objToLocalTS(obj) { - let d = Date.UTC(obj.year, obj.month - 1, obj.day, obj.hour, obj.minute, obj.second, obj.millisecond); + let d = Date.UTC(obj.year, obj.month - 1, obj.day, obj.hour, obj.minute, obj.second, obj.millisecond); // for legacy reasons, years between 0 and 99 are interpreted as 19XX; revert that - // for legacy reasons, years between 0 and 99 are interpreted as 19XX; revert that if (obj.year < 100 && obj.year >= 0) { d = new Date(d); d.setUTCFullYear(d.getUTCFullYear() - 1900); } + 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; + 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 : 2000 + year; -} - -// PARSING +} // PARSING function parseZoneInfo(ts, offsetFormat, locale) { let timeZone = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; const date = new Date(ts), - intlOpts = { - hourCycle: "h23", - year: "numeric", - month: "2-digit", - day: "2-digit", - hour: "2-digit", - minute: "2-digit" - }; + intlOpts = { + hourCycle: "h23", + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit" + }; + if (timeZone) { intlOpts.timeZone = timeZone; } + const modified = util_objectSpread({ timeZoneName: offsetFormat }, intlOpts); + const parsed = new Intl.DateTimeFormat(locale, modified).formatToParts(date).find(m => m.type.toLowerCase() === "timezonename"); return parsed ? parsed.value : null; -} +} // signedOffset('-5', '30') -> -330 -// signedOffset('-5', '30') -> -330 function signedOffset(offHourStr, offMinuteStr) { - let offHour = parseInt(offHourStr, 10); + let offHour = parseInt(offHourStr, 10); // don't || this because we want to preserve -0 - // don't || this because we want to preserve -0 if (Number.isNaN(offHour)) { offHour = 0; } + const offMin = parseInt(offMinuteStr, 10) || 0, - offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin; + offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin; return offHour * 60 + offMinSigned; -} - -// COERCION +} // COERCION function asNumber(value) { const numericValue = Number(value); @@ -2069,6 +2257,7 @@ function asNumber(value) { } function normalizeObject(obj, normalizer) { const normalized = {}; + for (const u in obj) { if (util_hasOwnProperty(obj, u)) { const v = obj[u]; @@ -2076,19 +2265,24 @@ function normalizeObject(obj, normalizer) { normalized[normalizer(u)] = asNumber(v); } } + return normalized; } function formatOffset(offset, format) { const hours = Math.trunc(Math.abs(offset / 60)), - minutes = Math.trunc(Math.abs(offset % 60)), - sign = offset >= 0 ? "+" : "-"; + minutes = Math.trunc(Math.abs(offset % 60)), + sign = offset >= 0 ? "+" : "-"; + switch (format) { 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 ${format} is out of range for property format`); } @@ -2099,14 +2293,15 @@ function timeObject(obj) { ;// CONCATENATED MODULE: ./node_modules/luxon/src/impl/english.js + function stringify(obj) { return JSON.stringify(obj, Object.keys(obj).sort()); } - /** * @private */ + const monthsLong = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; const monthsShort = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; const monthsNarrow = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]; @@ -2114,14 +2309,19 @@ 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; } @@ -2133,12 +2333,16 @@ 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; } @@ -2151,10 +2355,13 @@ function eras(length) { switch (length) { case "narrow": return [...erasNarrow]; + case "short": return [...erasShort]; + case "long": return [...erasLong]; + default: return null; } @@ -2185,100 +2392,137 @@ function formatRelativeTime(unit, count) { 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]}`; + default: // fall through + } } 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; + 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 formatString(knownFormat) { // these all have the offsets removed because we don't have access to them // without all the intl stuff this is backfilling const filtered = pick(knownFormat, ["weekday", "era", "year", "month", "day", "hour", "minute", "second", "timeZoneName", "hourCycle"]), - key = stringify(filtered), - dateTimeHuge = "EEEE, LLLL d, yyyy, h:mm a"; + key = stringify(filtered), + dateTimeHuge = "EEEE, LLLL d, yyyy, h:mm a"; + switch (key) { case stringify(Formats.DATE_SHORT): return "M/d/yyyy"; + case stringify(Formats.DATE_MED): return "LLL d, yyyy"; + case stringify(Formats.DATE_MED_WITH_WEEKDAY): return "EEE, LLL d, yyyy"; + case stringify(Formats.DATE_FULL): return "LLLL d, yyyy"; + case stringify(Formats.DATE_HUGE): return "EEEE, LLLL d, yyyy"; + case stringify(Formats.TIME_SIMPLE): return "h:mm a"; + case stringify(Formats.TIME_WITH_SECONDS): return "h:mm:ss a"; + case stringify(Formats.TIME_WITH_SHORT_OFFSET): return "h:mm a"; + case stringify(Formats.TIME_WITH_LONG_OFFSET): return "h:mm a"; + case stringify(Formats.TIME_24_SIMPLE): return "HH:mm"; + case stringify(Formats.TIME_24_WITH_SECONDS): return "HH:mm:ss"; + case stringify(Formats.TIME_24_WITH_SHORT_OFFSET): return "HH:mm"; + case stringify(Formats.TIME_24_WITH_LONG_OFFSET): return "HH:mm"; + case stringify(Formats.DATETIME_SHORT): return "M/d/yyyy, h:mm a"; + case stringify(Formats.DATETIME_MED): return "LLL d, yyyy, h:mm a"; + case stringify(Formats.DATETIME_FULL): return "LLLL d, yyyy, h:mm a"; + case stringify(Formats.DATETIME_HUGE): return dateTimeHuge; + case stringify(Formats.DATETIME_SHORT_WITH_SECONDS): return "M/d/yyyy, h:mm:ss a"; + case stringify(Formats.DATETIME_MED_WITH_SECONDS): return "LLL d, yyyy, h:mm:ss a"; + case stringify(Formats.DATETIME_MED_WITH_WEEKDAY): return "EEE, d LLL yyyy, h:mm a"; + case stringify(Formats.DATETIME_FULL_WITH_SECONDS): return "LLLL d, yyyy, h:mm:ss a"; + case stringify(Formats.DATETIME_HUGE_WITH_SECONDS): return "EEEE, LLLL d, yyyy, h:mm:ss a"; + default: return dateTimeHuge; } } ;// CONCATENATED MODULE: ./node_modules/luxon/src/impl/formatter.js function formatter_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } + function formatter_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? formatter_ownKeys(Object(source), !0).forEach(function (key) { formatter_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : formatter_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } -function formatter_defineProperty(obj, key, value) { key = formatter_toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function formatter_toPropertyKey(arg) { var key = formatter_toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function formatter_toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } + +function formatter_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = formatter_unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } + function formatter_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return formatter_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return formatter_arrayLikeToArray(o, minLen); } + function formatter_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } + + function stringifyTokens(splits, tokenToString) { let s = ""; + var _iterator = _createForOfIteratorHelper(splits), - _step; + _step; + try { for (_iterator.s(); !(_step = _iterator.n()).done;) { const token = _step.value; + if (token.literal) { s += token.val; } else { @@ -2290,8 +2534,10 @@ function stringifyTokens(splits, tokenToString) { } finally { _iterator.f(); } + return s; } + const macroTokenToFormatOpts = { D: DATE_SHORT, DD: DATE_MED, @@ -2314,7 +2560,6 @@ const macroTokenToFormatOpts = { FFF: DATETIME_FULL_WITH_SECONDS, FFFF: DATETIME_HUGE_WITH_SECONDS }; - /** * @private */ @@ -2324,13 +2569,16 @@ class Formatter { let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return new Formatter(locale, opts); } + static parseFormat(fmt) { let current = null, - currentFull = "", - bracketed = false; + 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({ @@ -2338,6 +2586,7 @@ class Formatter { val: currentFull }); } + current = null; currentFull = ""; bracketed = !bracketed; @@ -2352,350 +2601,438 @@ class Formatter { val: currentFull }); } + currentFull = c; current = c; } } + if (currentFull.length > 0) { splits.push({ literal: bracketed, 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, formatter_objectSpread(formatter_objectSpread({}, this.opts), opts)); return df.format(); } + formatDateTime(dt) { let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; const df = this.loc.dtFormatter(dt, formatter_objectSpread(formatter_objectSpread({}, this.opts), opts)); return df.format(); } + formatDateTimeParts(dt) { let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; const df = this.loc.dtFormatter(dt, formatter_objectSpread(formatter_objectSpread({}, this.opts), opts)); return df.formatToParts(); } + formatInterval(interval) { let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; const df = this.loc.dtFormatter(interval.start, formatter_objectSpread(formatter_objectSpread({}, this.opts), opts)); return df.dtf.formatRange(interval.start.toJSDate(), interval.end.toJSDate()); } + resolvedOptions(dt) { let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; const df = this.loc.dtFormatter(dt, formatter_objectSpread(formatter_objectSpread({}, this.opts), opts)); return df.resolvedOptions(); } + num(n) { let p = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + // we get some perf out of doing this here, annoyingly if (this.opts.forceSimple) { return padStart(n, p); } + const opts = formatter_objectSpread({}, this.opts); + if (p > 0) { opts.padTo = p; } + return this.loc.numberFormatter(opts).format(n); } + 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), - formatOffset = 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 => { - // Where possible: http://cldr.unicode.org/translation/date-time-1/date-time#TOC-Standalone-vs.-Format-Styles - switch (token) { - // ms - case "S": - return this.num(dt.millisecond); - case "u": - // falls through - case "SSS": - return this.num(dt.millisecond, 3); - // seconds - case "s": - return this.num(dt.second); - case "ss": - return this.num(dt.second, 2); - // fractional seconds - case "uu": - return this.num(Math.floor(dt.millisecond / 10), 2); - case "uuu": - return this.num(Math.floor(dt.millisecond / 100)); - // minutes - case "m": - return this.num(dt.minute); - case "mm": - return this.num(dt.minute, 2); - // hours - 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); - // offset - case "Z": - // like +6 - return formatOffset({ - format: "narrow", - allowZ: this.opts.allowZ - }); - case "ZZ": - // like +06:00 - return formatOffset({ - format: "short", - allowZ: this.opts.allowZ - }); - case "ZZZ": - // like +0600 - return formatOffset({ - format: "techie", - allowZ: this.opts.allowZ - }); - case "ZZZZ": - // like EST - return dt.zone.offsetName(dt.ts, { - format: "short", - locale: this.loc.locale - }); - case "ZZZZZ": - // like Eastern Standard Time - return dt.zone.offsetName(dt.ts, { - format: "long", - locale: this.loc.locale - }); - // zone - case "z": - // like America/New_York - return dt.zoneName; - // meridiems - case "a": - return meridiem(); - // dates - 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); - // weekdays - standalone - case "c": - // like 1 - return this.num(dt.weekday); - case "ccc": - // like 'Tues' - return weekday("short", true); - case "cccc": - // like 'Tuesday' - return weekday("long", true); - case "ccccc": - // like 'T' - return weekday("narrow", true); - // weekdays - format - case "E": - // like 1 - return this.num(dt.weekday); - case "EEE": - // like 'Tues' - return weekday("short", false); - case "EEEE": - // like 'Tuesday' - return weekday("long", false); - case "EEEEE": - // like 'T' - return weekday("narrow", false); - // months - standalone - case "L": - // like 1 - return useDateTimeFormatter ? string({ - month: "numeric", - day: "numeric" - }, "month") : this.num(dt.month); - case "LL": - // like 01, doesn't seem to work - return useDateTimeFormatter ? string({ - month: "2-digit", - day: "numeric" - }, "month") : this.num(dt.month, 2); - case "LLL": - // like Jan - return month("short", true); - case "LLLL": - // like January - return month("long", true); - case "LLLLL": - // like J - return month("narrow", true); - // months - format - case "M": - // like 1 - return useDateTimeFormatter ? string({ - month: "numeric" - }, "month") : this.num(dt.month); - case "MM": - // like 01 - return useDateTimeFormatter ? string({ - month: "2-digit" - }, "month") : this.num(dt.month, 2); - case "MMM": - // like Jan - return month("short", false); - case "MMMM": - // like January - return month("long", false); - case "MMMMM": - // like J - return month("narrow", false); - // years - case "y": - // like 2014 - return useDateTimeFormatter ? string({ - year: "numeric" - }, "year") : this.num(dt.year); - case "yy": - // like 14 - return useDateTimeFormatter ? string({ - year: "2-digit" - }, "year") : this.num(dt.year.toString().slice(-2), 2); - case "yyyy": - // like 0012 - return useDateTimeFormatter ? string({ - year: "numeric" - }, "year") : this.num(dt.year, 4); - case "yyyyyy": - // like 000012 - return useDateTimeFormatter ? string({ - year: "numeric" - }, "year") : this.num(dt.year, 6); - // eras - case "G": - // like AD - return era("short"); - case "GG": - // like Anno Domini - 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": - // like 1 - return this.num(dt.quarter); - case "qq": - // like 01 - return this.num(dt.quarter, 2); - case "X": - return this.num(Math.floor(dt.ts / 1000)); - case "x": - return this.num(dt.ts); - default: - return maybeMacro(token); - } - }; + useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== "gregory", + string = (opts, extract) => this.loc.extract(dt, opts, extract), + formatOffset = 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 => { + // Where possible: http://cldr.unicode.org/translation/date-time-1/date-time#TOC-Standalone-vs.-Format-Styles + switch (token) { + // ms + case "S": + return this.num(dt.millisecond); + + case "u": // falls through + + case "SSS": + return this.num(dt.millisecond, 3); + // seconds + + case "s": + return this.num(dt.second); + + case "ss": + return this.num(dt.second, 2); + // fractional seconds + + case "uu": + return this.num(Math.floor(dt.millisecond / 10), 2); + + case "uuu": + return this.num(Math.floor(dt.millisecond / 100)); + // minutes + + case "m": + return this.num(dt.minute); + + case "mm": + return this.num(dt.minute, 2); + // hours + + 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); + // offset + + case "Z": + // like +6 + return formatOffset({ + format: "narrow", + allowZ: this.opts.allowZ + }); + + case "ZZ": + // like +06:00 + return formatOffset({ + format: "short", + allowZ: this.opts.allowZ + }); + + case "ZZZ": + // like +0600 + return formatOffset({ + format: "techie", + allowZ: this.opts.allowZ + }); + + case "ZZZZ": + // like EST + return dt.zone.offsetName(dt.ts, { + format: "short", + locale: this.loc.locale + }); + + case "ZZZZZ": + // like Eastern Standard Time + return dt.zone.offsetName(dt.ts, { + format: "long", + locale: this.loc.locale + }); + // zone + + case "z": + // like America/New_York + return dt.zoneName; + // meridiems + + case "a": + return meridiem(); + // dates + + 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); + // weekdays - standalone + + case "c": + // like 1 + return this.num(dt.weekday); + + case "ccc": + // like 'Tues' + return weekday("short", true); + + case "cccc": + // like 'Tuesday' + return weekday("long", true); + + case "ccccc": + // like 'T' + return weekday("narrow", true); + // weekdays - format + + case "E": + // like 1 + return this.num(dt.weekday); + + case "EEE": + // like 'Tues' + return weekday("short", false); + + case "EEEE": + // like 'Tuesday' + return weekday("long", false); + + case "EEEEE": + // like 'T' + return weekday("narrow", false); + // months - standalone + + case "L": + // like 1 + return useDateTimeFormatter ? string({ + month: "numeric", + day: "numeric" + }, "month") : this.num(dt.month); + + case "LL": + // like 01, doesn't seem to work + return useDateTimeFormatter ? string({ + month: "2-digit", + day: "numeric" + }, "month") : this.num(dt.month, 2); + + case "LLL": + // like Jan + return month("short", true); + + case "LLLL": + // like January + return month("long", true); + + case "LLLLL": + // like J + return month("narrow", true); + // months - format + + case "M": + // like 1 + return useDateTimeFormatter ? string({ + month: "numeric" + }, "month") : this.num(dt.month); + + case "MM": + // like 01 + return useDateTimeFormatter ? string({ + month: "2-digit" + }, "month") : this.num(dt.month, 2); + + case "MMM": + // like Jan + return month("short", false); + + case "MMMM": + // like January + return month("long", false); + + case "MMMMM": + // like J + return month("narrow", false); + // years + + case "y": + // like 2014 + return useDateTimeFormatter ? string({ + year: "numeric" + }, "year") : this.num(dt.year); + + case "yy": + // like 14 + return useDateTimeFormatter ? string({ + year: "2-digit" + }, "year") : this.num(dt.year.toString().slice(-2), 2); + + case "yyyy": + // like 0012 + return useDateTimeFormatter ? string({ + year: "numeric" + }, "year") : this.num(dt.year, 4); + + case "yyyyyy": + // like 000012 + return useDateTimeFormatter ? string({ + year: "numeric" + }, "year") : this.num(dt.year, 6); + // eras + + case "G": + // like AD + return era("short"); + + case "GG": + // like Anno Domini + 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": + // like 1 + return this.num(dt.quarter); + + case "qq": + // like 01 + return this.num(dt.quarter, 2); + + case "X": + return this.num(Math.floor(dt.ts / 1000)); + + 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, _ref) => { - let literal = _ref.literal, + 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, _ref) => { + let literal = _ref.literal, val = _ref.val; - return literal ? found : found.concat(val); - }, []), - collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter(t => t)); + return literal ? found : found.concat(val); + }, []), + collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter(t => t)); + return stringifyTokens(tokens, tokenToString(collapsed)); } + } ;// CONCATENATED MODULE: ./node_modules/luxon/src/impl/invalid.js class Invalid { @@ -2703,6 +3040,7 @@ class Invalid { this.reason = reason; this.explanation = explanation; } + toMessage() { if (this.explanation) { return `${this.reason}: ${this.explanation}`; @@ -2710,18 +3048,25 @@ class Invalid { return this.reason; } } + } ;// CONCATENATED MODULE: ./node_modules/luxon/src/impl/regexParser.js function regexParser_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } + function regexParser_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? regexParser_ownKeys(Object(source), !0).forEach(function (key) { regexParser_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : regexParser_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } -function regexParser_defineProperty(obj, key, value) { key = regexParser_toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function regexParser_toPropertyKey(arg) { var key = regexParser_toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function regexParser_toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } + +function regexParser_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + function regexParser_slicedToArray(arr, i) { return regexParser_arrayWithHoles(arr) || regexParser_iterableToArrayLimit(arr, i) || regexParser_unsupportedIterableToArray(arr, i) || regexParser_nonIterableRest(); } + function regexParser_nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + function regexParser_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return regexParser_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return regexParser_arrayLikeToArray(o, minLen); } + function regexParser_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } -function regexParser_iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } } + +function regexParser_iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + function regexParser_arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } @@ -2739,63 +3084,79 @@ function regexParser_arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } */ const ianaRegex = /[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/; + function combineRegexes() { for (var _len = arguments.length, regexes = new Array(_len), _key = 0; _key < _len; _key++) { regexes[_key] = arguments[_key]; } + const full = regexes.reduce((f, r) => f + r.source, ""); return RegExp(`^${full}$`); } + function combineExtractors() { for (var _len2 = arguments.length, extractors = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { extractors[_key2] = arguments[_key2]; } + return m => extractors.reduce((_ref, ex) => { let _ref2 = regexParser_slicedToArray(_ref, 3), - mergedVals = _ref2[0], - mergedZone = _ref2[1], - cursor = _ref2[2]; + mergedVals = _ref2[0], + mergedZone = _ref2[1], + cursor = _ref2[2]; + const _ex = ex(m, cursor), - _ex2 = regexParser_slicedToArray(_ex, 3), - val = _ex2[0], - zone = _ex2[1], - next = _ex2[2]; + _ex2 = regexParser_slicedToArray(_ex, 3), + val = _ex2[0], + zone = _ex2[1], + next = _ex2[2]; + return [regexParser_objectSpread(regexParser_objectSpread({}, mergedVals), val), zone || mergedZone, next]; }, [{}, null, 1]).slice(0, 2); } + function parse(s) { if (s == null) { return [null, null]; } + for (var _len3 = arguments.length, patterns = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { patterns[_key3 - 1] = arguments[_key3]; } + for (var _i2 = 0, _patterns = patterns; _i2 < _patterns.length; _i2++) { const _patterns$_i = regexParser_slicedToArray(_patterns[_i2], 2), - regex = _patterns$_i[0], - extractor = _patterns$_i[1]; + regex = _patterns$_i[0], + extractor = _patterns$_i[1]; + const m = regex.exec(s); + if (m) { return extractor(m); } } + return [null, null]; } + function simpleParse() { for (var _len4 = arguments.length, keys = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { keys[_key4] = arguments[_key4]; } + return (match, cursor) => { const ret = {}; let i; + for (i = 0; i < keys.length; i++) { ret[keys[i]] = parseInteger(match[cursor + i]); } + return [ret, null, cursor + i]; }; -} +} // ISO and SQL parsing + -// ISO and SQL parsing const offsetRegex = /(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/; const isoExtendedZone = `(?:${offsetRegex.source}?(?:\\[(${ianaRegex.source})\\])?)?`; const isoTimeBaseRegex = /(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/; @@ -2807,12 +3168,15 @@ const isoOrdinalRegex = /(\d{4})-?(\d{3})/; const extractISOWeekData = simpleParse("weekYear", "weekNumber", "weekDay"); const extractISOOrdinalData = simpleParse("year", "ordinal"); const sqlYmdRegex = /(\d{4})-(\d\d)-(\d\d)/; // dumbed-down version of the ISO one + const sqlTimeRegex = RegExp(`${isoTimeBaseRegex.source} ?(?:${offsetRegex.source}|(${ianaRegex.source}))?`); const sqlTimeExtensionRegex = RegExp(`(?: ${sqlTimeRegex.source})?`); + function regexParser_int(match, pos, fallback) { const m = match[pos]; return isUndefined(m) ? fallback : parseInteger(m); } + function extractISOYmd(match, cursor) { const item = { year: regexParser_int(match, cursor), @@ -2821,6 +3185,7 @@ function extractISOYmd(match, cursor) { }; return [item, null, cursor + 3]; } + function extractISOTime(match, cursor) { const item = { hours: regexParser_int(match, cursor, 0), @@ -2830,41 +3195,44 @@ function extractISOTime(match, cursor) { }; return [item, null, cursor + 4]; } + function extractISOOffset(match, cursor) { const local = !match[cursor] && !match[cursor + 1], - fullOffset = signedOffset(match[cursor + 1], match[cursor + 2]), - zone = local ? null : FixedOffsetZone.instance(fullOffset); + fullOffset = signedOffset(match[cursor + 1], match[cursor + 2]), + zone = local ? null : FixedOffsetZone.instance(fullOffset); return [{}, zone, cursor + 3]; } + function extractIANAZone(match, cursor) { const zone = match[cursor] ? IANAZone.create(match[cursor]) : null; return [{}, zone, cursor + 1]; -} +} // ISO time parsing -// ISO time parsing -const isoTimeOnly = RegExp(`^T?${isoTimeBaseRegex.source}$`); - -// ISO duration parsing +const isoTimeOnly = RegExp(`^T?${isoTimeBaseRegex.source}$`); // ISO duration parsing const 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(match) { const _match = regexParser_slicedToArray(match, 9), - s = _match[0], - yearStr = _match[1], - monthStr = _match[2], - weekStr = _match[3], - dayStr = _match[4], - hourStr = _match[5], - minuteStr = _match[6], - secondStr = _match[7], - millisecondsStr = _match[8]; + s = _match[0], + yearStr = _match[1], + monthStr = _match[2], + weekStr = _match[3], + dayStr = _match[4], + hourStr = _match[5], + minuteStr = _match[6], + secondStr = _match[7], + millisecondsStr = _match[8]; + const hasNegativePrefix = s[0] === "-"; const negativeSeconds = secondStr && secondStr[0] === "-"; + const maybeNegate = function maybeNegate(num) { let force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return num !== undefined && (force || num && hasNegativePrefix) ? -num : num; }; + return [{ years: maybeNegate(parseFloating(yearStr)), months: maybeNegate(parseFloating(monthStr)), @@ -2875,11 +3243,11 @@ function extractISODuration(match) { seconds: maybeNegate(parseFloating(secondStr), secondStr === "-0"), milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds) }]; -} - -// These are a little braindead. EDT *should* tell us that we're in, say, America/New_York +} // These are a little braindead. EDT *should* tell us that we're in, say, America/New_York // and not just that we're in -240 *right now*. But since I don't think these are used that often // I'm just going to ignore that + + const obsOffsets = { GMT: 0, EDT: -4 * 60, @@ -2891,6 +3259,7 @@ const obsOffsets = { 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), @@ -2900,29 +3269,34 @@ function fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, 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; -} +} // RFC 2822/5322 + -// RFC 2822/5322 const 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(match) { const _match2 = regexParser_slicedToArray(match, 12), - weekdayStr = _match2[1], - dayStr = _match2[2], - monthStr = _match2[3], - yearStr = _match2[4], - hourStr = _match2[5], - minuteStr = _match2[6], - secondStr = _match2[7], - obsOffset = _match2[8], - milOffset = _match2[9], - offHourStr = _match2[10], - offMinuteStr = _match2[11], - result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); + weekdayStr = _match2[1], + dayStr = _match2[2], + monthStr = _match2[3], + yearStr = _match2[4], + hourStr = _match2[5], + minuteStr = _match2[6], + secondStr = _match2[7], + obsOffset = _match2[8], + milOffset = _match2[9], + offHourStr = _match2[10], + offMinuteStr = _match2[11], + result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); + let offset; + if (obsOffset) { offset = obsOffsets[obsOffset]; } else if (milOffset) { @@ -2930,42 +3304,48 @@ function extractRFC2822(match) { } else { offset = signedOffset(offHourStr, offMinuteStr); } + return [result, new FixedOffsetZone(offset)]; } + function preprocessRFC2822(s) { // Remove comments and folding whitespace and replace multiple-spaces with a single space return s.replace(/\([^)]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").trim(); -} +} // http date -// http date const 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$/, - 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$/, - 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})$/; + 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$/, + 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(match) { const _match3 = regexParser_slicedToArray(match, 8), - weekdayStr = _match3[1], - dayStr = _match3[2], - monthStr = _match3[3], - yearStr = _match3[4], - hourStr = _match3[5], - minuteStr = _match3[6], - secondStr = _match3[7], - result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); + weekdayStr = _match3[1], + dayStr = _match3[2], + monthStr = _match3[3], + yearStr = _match3[4], + hourStr = _match3[5], + minuteStr = _match3[6], + secondStr = _match3[7], + result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); + return [result, FixedOffsetZone.utcInstance]; } + function extractASCII(match) { const _match4 = regexParser_slicedToArray(match, 8), - weekdayStr = _match4[1], - monthStr = _match4[2], - dayStr = _match4[3], - hourStr = _match4[4], - minuteStr = _match4[5], - secondStr = _match4[6], - yearStr = _match4[7], - result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); + weekdayStr = _match4[1], + monthStr = _match4[2], + dayStr = _match4[3], + hourStr = _match4[4], + minuteStr = _match4[5], + secondStr = _match4[6], + yearStr = _match4[7], + result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); + return [result, FixedOffsetZone.utcInstance]; } + const isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex); const isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex); const isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex); @@ -2974,7 +3354,6 @@ const extractISOYmdTimeAndOffset = combineExtractors(extractISOYmd, extractISOTi const extractISOWeekTimeAndOffset = combineExtractors(extractISOWeekData, extractISOTime, extractISOOffset, extractIANAZone); const extractISOOrdinalDateAndTime = combineExtractors(extractISOOrdinalData, extractISOTime, extractISOOffset, extractIANAZone); const extractISOTimeAndOffset = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone); - /* * @private */ @@ -3002,120 +3381,126 @@ function parseSQL(s) { return parse(s, [sqlYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone]); } ;// CONCATENATED MODULE: ./node_modules/luxon/src/duration.js +function duration_createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = duration_unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } + function duration_slicedToArray(arr, i) { return duration_arrayWithHoles(arr) || duration_iterableToArrayLimit(arr, i) || duration_unsupportedIterableToArray(arr, i) || duration_nonIterableRest(); } + function duration_nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + function duration_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return duration_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return duration_arrayLikeToArray(o, minLen); } + function duration_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } -function duration_iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } } + +function duration_iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + function duration_arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + function duration_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } + function duration_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? duration_ownKeys(Object(source), !0).forEach(function (key) { duration_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : duration_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } -function duration_defineProperty(obj, key, value) { key = duration_toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function duration_toPropertyKey(arg) { var key = duration_toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function duration_toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function duration_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -const INVALID = "Invalid Duration"; -// unit conversion constants + +const INVALID = "Invalid Duration"; // unit conversion constants + const lowOrderMatrix = { - weeks: { - days: 7, - hours: 7 * 24, - minutes: 7 * 24 * 60, - seconds: 7 * 24 * 60 * 60, - milliseconds: 7 * 24 * 60 * 60 * 1000 - }, - days: { - hours: 24, - minutes: 24 * 60, - seconds: 24 * 60 * 60, - milliseconds: 24 * 60 * 60 * 1000 - }, - hours: { - minutes: 60, - seconds: 60 * 60, - milliseconds: 60 * 60 * 1000 - }, - minutes: { - seconds: 60, - milliseconds: 60 * 1000 - }, - seconds: { - milliseconds: 1000 - } + weeks: { + days: 7, + hours: 7 * 24, + minutes: 7 * 24 * 60, + seconds: 7 * 24 * 60 * 60, + milliseconds: 7 * 24 * 60 * 60 * 1000 }, - casualMatrix = duration_objectSpread({ - 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 * 1000 - }, - quarters: { - months: 3, - weeks: 13, - days: 91, - hours: 91 * 24, - minutes: 91 * 24 * 60, - seconds: 91 * 24 * 60 * 60, - milliseconds: 91 * 24 * 60 * 60 * 1000 - }, - months: { - weeks: 4, - days: 30, - hours: 30 * 24, - minutes: 30 * 24 * 60, - seconds: 30 * 24 * 60 * 60, - milliseconds: 30 * 24 * 60 * 60 * 1000 - } - }, lowOrderMatrix), - daysInYearAccurate = 146097.0 / 400, - daysInMonthAccurate = 146097.0 / 4800, - accurateMatrix = duration_objectSpread({ - 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 * 1000 - }, - 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 * 1000 / 4 - }, - months: { - weeks: daysInMonthAccurate / 7, - days: daysInMonthAccurate, - hours: daysInMonthAccurate * 24, - minutes: daysInMonthAccurate * 24 * 60, - seconds: daysInMonthAccurate * 24 * 60 * 60, - milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1000 - } - }, lowOrderMatrix); + days: { + hours: 24, + minutes: 24 * 60, + seconds: 24 * 60 * 60, + milliseconds: 24 * 60 * 60 * 1000 + }, + hours: { + minutes: 60, + seconds: 60 * 60, + milliseconds: 60 * 60 * 1000 + }, + minutes: { + seconds: 60, + milliseconds: 60 * 1000 + }, + seconds: { + milliseconds: 1000 + } +}, + casualMatrix = duration_objectSpread({ + 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 * 1000 + }, + quarters: { + months: 3, + weeks: 13, + days: 91, + hours: 91 * 24, + minutes: 91 * 24 * 60, + seconds: 91 * 24 * 60 * 60, + milliseconds: 91 * 24 * 60 * 60 * 1000 + }, + months: { + weeks: 4, + days: 30, + hours: 30 * 24, + minutes: 30 * 24 * 60, + seconds: 30 * 24 * 60 * 60, + milliseconds: 30 * 24 * 60 * 60 * 1000 + } +}, lowOrderMatrix), + daysInYearAccurate = 146097.0 / 400, + daysInMonthAccurate = 146097.0 / 4800, + accurateMatrix = duration_objectSpread({ + 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 * 1000 + }, + 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 * 1000 / 4 + }, + months: { + weeks: daysInMonthAccurate / 7, + days: daysInMonthAccurate, + hours: daysInMonthAccurate * 24, + minutes: daysInMonthAccurate * 24 * 60, + seconds: daysInMonthAccurate * 24 * 60 * 60, + milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1000 + } +}, lowOrderMatrix); // units ordered by size -// units ordered by size const orderedUnits = ["years", "quarters", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds"]; -const reverseUnits = orderedUnits.slice(0).reverse(); +const reverseUnits = orderedUnits.slice(0).reverse(); // clone really means "create another instance just like this one, but with these changes" -// clone really means "create another instance just like this one, but with these changes" function clone(dur, alts) { let clear = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; // deep merge for vals @@ -3127,49 +3512,53 @@ function clone(dur, alts) { }; return new Duration(conf); } + function antiTrunc(n) { return n < 0 ? Math.floor(n) : Math.ceil(n); -} +} // NB: mutates parameters + -// NB: mutates parameters function convert(matrix, fromMap, fromUnit, toMap, toUnit) { const conv = matrix[toUnit][fromUnit], - raw = fromMap[fromUnit] / conv, - sameSign = Math.sign(raw) === Math.sign(toMap[toUnit]), - // ok, so this is wild, but see the matrix in the tests - added = !sameSign && toMap[toUnit] !== 0 && Math.abs(raw) <= 1 ? antiTrunc(raw) : Math.trunc(raw); + raw = fromMap[fromUnit] / conv, + sameSign = Math.sign(raw) === Math.sign(toMap[toUnit]), + // ok, so this is wild, but see the matrix in the tests + added = !sameSign && toMap[toUnit] !== 0 && Math.abs(raw) <= 1 ? antiTrunc(raw) : Math.trunc(raw); toMap[toUnit] += added; fromMap[fromUnit] -= added * conv; -} +} // NB: mutates parameters + -// NB: mutates parameters 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); -} +} // Remove all properties with a value of 0 from an object + -// Remove all properties with a value of 0 from an object function removeZeroes(vals) { const newVals = {}; + for (var _i = 0, _Object$entries = Object.entries(vals); _i < _Object$entries.length; _i++) { const _Object$entries$_i = duration_slicedToArray(_Object$entries[_i], 2), - key = _Object$entries$_i[0], - value = _Object$entries$_i[1]; + key = _Object$entries$_i[0], + value = _Object$entries$_i[1]; + if (value !== 0) { newVals[key] = value; } } + return newVals; } - /** * A Duration object represents a period of time, like "2 months" or "1 day, 1 hour". Conceptually, it's just a map of units to their quantities, accompanied by some additional configuration and methods for creating, parsing, interrogating, transforming, and formatting them. They can be used on their own or in conjunction with other Luxon types; for example, you can use {@link DateTime#plus} to add a Duration object to a DateTime, producing another DateTime. * @@ -3183,6 +3572,8 @@ function removeZeroes(vals) { * * There's are more methods documented below. In addition, for more information on subtler topics like internationalization and validity, see the external documentation. */ + + class Duration { /** * @private @@ -3190,36 +3581,42 @@ class Duration { constructor(config) { const accurate = config.conversionAccuracy === "longterm" || false; let matrix = accurate ? accurateMatrix : casualMatrix; + if (config.matrix) { matrix = config.matrix; } - /** * @access private */ + + this.values = config.values; /** * @access private */ + this.loc = config.loc || Locale.create(); /** * @access private */ + this.conversionAccuracy = accurate ? "longterm" : "casual"; /** * @access private */ + this.invalid = config.invalid || null; /** * @access private */ + this.matrix = matrix; /** * @access private */ + this.isLuxonDuration = true; } - /** * Create Duration from a number of milliseconds. * @param {number} count of milliseconds @@ -3229,12 +3626,13 @@ class Duration { * @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. @@ -3255,11 +3653,15 @@ class Duration { * @param {string} [opts.matrix=Object] - the custom conversion system to use * @return {Duration} */ + + static fromObject(obj) { let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + 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), @@ -3267,7 +3669,6 @@ class Duration { matrix: opts.matrix }); } - /** * Create a Duration from DurationLike. * @@ -3278,6 +3679,8 @@ class Duration { * - Duration instance * @return {Duration} */ + + static fromDurationLike(durationLike) { if (isNumber(durationLike)) { return Duration.fromMillis(durationLike); @@ -3289,7 +3692,6 @@ class Duration { 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 @@ -3304,17 +3706,19 @@ class Duration { * @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 } * @return {Duration} */ + + static fromISO(text, opts) { const _parseISODuration = parseISODuration(text), - _parseISODuration2 = duration_slicedToArray(_parseISODuration, 1), - parsed = _parseISODuration2[0]; + _parseISODuration2 = duration_slicedToArray(_parseISODuration, 1), + parsed = _parseISODuration2[0]; + 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 @@ -3331,29 +3735,36 @@ class Duration { * @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } * @return {Duration} */ + + static fromISOTime(text, opts) { const _parseISOTimeOnly = parseISOTimeOnly(text), - _parseISOTimeOnly2 = duration_slicedToArray(_parseISOTimeOnly, 1), - parsed = _parseISOTimeOnly2[0]; + _parseISOTimeOnly2 = duration_slicedToArray(_parseISOTimeOnly, 1), + parsed = _parseISOTimeOnly2[0]; + 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) { let explanation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 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 { @@ -3362,10 +3773,11 @@ class Duration { }); } } - /** * @private */ + + static normalizeUnit(unit) { const normalized = { year: "years", @@ -3390,33 +3802,35 @@ class Duration { 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 @@ -3439,15 +3853,18 @@ class Duration { * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("M S") //=> "12 518402000" * @return {string} */ + + toFormat(fmt) { let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + // reverse-compat since 1.2; we always round down now, never up, and we do it by default const fmtOpts = duration_objectSpread(duration_objectSpread({}, opts), {}, { floor: opts.round !== false && opts.floor !== false }); + return this.isValid ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt) : INVALID; } - /** * 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. @@ -3461,13 +3878,17 @@ class Duration { * dur.toHuman({ unitDisplay: "short" }) //=> '1 day, 5 hr, 6 min' * ``` */ + + toHuman() { let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; const l = orderedUnits.map(unit => { const val = this.values[unit]; + if (isUndefined(val)) { return null; } + return this.loc.numberFormatter(duration_objectSpread(duration_objectSpread({ style: "unit", unitDisplay: "long" @@ -3480,17 +3901,17 @@ class Duration { style: opts.listStyle || "narrow" }, opts)).format(l); } - /** * 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 duration_objectSpread({}, this.values); } - /** * Returns an ISO 8601-compliant string representation of this Duration. * @see https://en.wikipedia.org/wiki/ISO_8601#Durations @@ -3501,6 +3922,8 @@ class Duration { * @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S' * @return {string} */ + + toISO() { // we could use the formatter, but this is an easier way to get the minimum string if (!this.isValid) return null; @@ -3512,14 +3935,12 @@ class Duration { if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0) s += "T"; if (this.hours !== 0) s += this.hours + "H"; if (this.minutes !== 0) s += this.minutes + "M"; - if (this.seconds !== 0 || this.milliseconds !== 0) - // this will handle "floating point madness" by removing extra decimal places + if (this.seconds !== 0 || this.milliseconds !== 0) // this will handle "floating point madness" by removing extra decimal places // https://stackoverflow.com/questions/588004/is-floating-point-math-broken s += roundTo(this.seconds + this.milliseconds / 1000, 3) + "S"; if (s === "P") s += "T0S"; return s; } - /** * 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. @@ -3536,6 +3957,8 @@ class Duration { * @example Duration.fromObject({ hours: 11 }).toISOTime({ format: 'basic' }) //=> '110000.000' * @return {string} */ + + toISOTime() { let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (!this.isValid) return null; @@ -3549,82 +3972,104 @@ class Duration { }, 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 (var _i2 = 0, _orderedUnits = orderedUnits; _i2 < _orderedUnits.length; _i2++) { - const k = _orderedUnits[_i2]; - if (util_hasOwnProperty(dur.values, k) || util_hasOwnProperty(this.values, k)) { - result[k] = dur.get(k) + this.get(k); + result = {}; + + var _iterator = duration_createForOfIteratorHelper(orderedUnits), + _step; + + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + const k = _step.value; + + if (util_hasOwnProperty(dur.values, k) || util_hasOwnProperty(this.values, k)) { + result[k] = dur.get(k) + this.get(k); + } } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); } + return clone(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. @@ -3632,18 +4077,21 @@ class Duration { * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits((x, u) => u === "hours" ? x * 2 : x) //=> { hours: 2, minutes: 30 } * @return {Duration} */ + + mapUnits(fn) { if (!this.isValid) return this; const result = {}; - for (var _i3 = 0, _Object$keys = Object.keys(this.values); _i3 < _Object$keys.length; _i3++) { - const k = _Object$keys[_i3]; + + for (var _i2 = 0, _Object$keys = Object.keys(this.values); _i2 < _Object$keys.length; _i2++) { + const k = _Object$keys[_i2]; result[k] = asNumber(fn(this.values[k], k)); } + return clone(this, { values: result }, true); } - /** * Get the value of unit. * @param {string} unit - a unit such as 'minute' or 'day' @@ -3652,10 +4100,11 @@ class Duration { * @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 @@ -3663,25 +4112,31 @@ class Duration { * @example dur.set({ hours: 8, minutes: 30 }) * @return {Duration} */ + + set(values) { if (!this.isValid) return this; + const mixed = duration_objectSpread(duration_objectSpread({}, this.values), normalizeObject(values, Duration.normalizeUnit)); + return clone(this, { values: mixed }); } - /** * "Set" the locale and/or numberingSystem. Returns a newly-constructed Duration. * @example dur.reconfigure({ locale: 'en-GB' }) * @return {Duration} */ + + reconfigure() { let _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - locale = _ref.locale, - numberingSystem = _ref.numberingSystem, - conversionAccuracy = _ref.conversionAccuracy, - matrix = _ref.matrix; + locale = _ref.locale, + numberingSystem = _ref.numberingSystem, + conversionAccuracy = _ref.conversionAccuracy, + matrix = _ref.matrix; + const loc = this.loc.clone({ locale, numberingSystem @@ -3693,7 +4148,6 @@ class Duration { }; return clone(this, opts); } - /** * Return the length of the duration in the specified unit. * @param {string} unit - a unit such as 'minutes' or 'days' @@ -3702,16 +4156,19 @@ class Duration { * @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(); @@ -3720,12 +4177,13 @@ class Duration { 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()); @@ -3733,227 +4191,280 @@ class Duration { 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() { for (var _len = arguments.length, units = new Array(_len), _key = 0; _key < _len; _key++) { units[_key] = arguments[_key]; } + if (!this.isValid) return this; + if (units.length === 0) { return this; } + units = units.map(u => Duration.normalizeUnit(u)); const built = {}, - accumulated = {}, - vals = this.toObject(); + accumulated = {}, + vals = this.toObject(); let lastUnit; - for (var _i4 = 0, _orderedUnits2 = orderedUnits; _i4 < _orderedUnits2.length; _i4++) { - const k = _orderedUnits2[_i4]; - if (units.indexOf(k) >= 0) { - lastUnit = k; - let own = 0; - - // anything we haven't boiled down yet should get boiled to this unit - for (const ak in accumulated) { - own += this.matrix[ak][k] * accumulated[ak]; - accumulated[ak] = 0; - } - - // plus anything that's already in this unit - if (isNumber(vals[k])) { - own += vals[k]; - } - const i = Math.trunc(own); - built[k] = i; - accumulated[k] = (own * 1000 - i * 1000) / 1000; - - // plus anything further down the chain that should be rolled up in to this - for (const down in vals) { - if (orderedUnits.indexOf(down) > orderedUnits.indexOf(k)) { - convert(this.matrix, vals, down, built, k); + + var _iterator2 = duration_createForOfIteratorHelper(orderedUnits), + _step2; + + try { + for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { + const k = _step2.value; + + if (units.indexOf(k) >= 0) { + lastUnit = k; + let own = 0; // anything we haven't boiled down yet should get boiled to this unit + + for (const ak in accumulated) { + own += this.matrix[ak][k] * accumulated[ak]; + accumulated[ak] = 0; + } // plus anything that's already in this unit + + + if (isNumber(vals[k])) { + own += vals[k]; } + + const i = Math.trunc(own); + built[k] = i; + accumulated[k] = (own * 1000 - i * 1000) / 1000; // plus anything further down the chain that should be rolled up in to this + + for (const down in vals) { + if (orderedUnits.indexOf(down) > orderedUnits.indexOf(k)) { + convert(this.matrix, vals, down, built, k); + } + } // otherwise, keep it in the wings to boil it later + + } else if (isNumber(vals[k])) { + accumulated[k] = vals[k]; } - // otherwise, keep it in the wings to boil it later - } else if (isNumber(vals[k])) { - accumulated[k] = vals[k]; - } + } // anything leftover becomes the decimal for the last unit + // lastUnit must be defined since units is not empty + + } catch (err) { + _iterator2.e(err); + } finally { + _iterator2.f(); } - // anything leftover becomes the decimal for the last unit - // lastUnit must be defined since units is not empty for (const key in accumulated) { if (accumulated[key] !== 0) { built[lastUnit] += key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key]; } } + return clone(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 (var _i5 = 0, _Object$keys2 = Object.keys(this.values); _i5 < _Object$keys2.length; _i5++) { - const k = _Object$keys2[_i5]; + + for (var _i3 = 0, _Object$keys2 = Object.keys(this.values); _i3 < _Object$keys2.length; _i3++) { + const k = _Object$keys2[_i3]; negated[k] = this.values[k] === 0 ? 0 : -this.values[k]; } + return clone(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) { // Consider 0 and undefined as equal if (v1 === undefined || v1 === 0) return v2 === undefined || v2 === 0; return v1 === v2; } - for (var _i6 = 0, _orderedUnits3 = orderedUnits; _i6 < _orderedUnits3.length; _i6++) { - const u = _orderedUnits3[_i6]; - if (!eq(this.values[u], other.values[u])) { - return false; + + var _iterator3 = duration_createForOfIteratorHelper(orderedUnits), + _step3; + + try { + for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { + const u = _step3.value; + + if (!eq(this.values[u], other.values[u])) { + return false; + } } + } catch (err) { + _iterator3.e(err); + } finally { + _iterator3.f(); } + return true; } + } ;// CONCATENATED MODULE: ./node_modules/luxon/src/interval.js function interval_createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = interval_unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } + function interval_slicedToArray(arr, i) { return interval_arrayWithHoles(arr) || interval_iterableToArrayLimit(arr, i) || interval_unsupportedIterableToArray(arr, i) || interval_nonIterableRest(); } + function interval_nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + function interval_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return interval_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return interval_arrayLikeToArray(o, minLen); } + function interval_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } -function interval_iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } } + +function interval_iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + function interval_arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } @@ -3962,9 +4473,9 @@ function interval_arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } -const interval_INVALID = "Invalid Interval"; -// checks if the start is equal to or before the end +const interval_INVALID = "Invalid Interval"; // checks if the start is equal to or before the end + function validateStartEnd(start, end) { if (!start || !start.isValid) { return Interval.invalid("missing or invalid start"); @@ -3976,7 +4487,6 @@ function validateStartEnd(start, end) { return null; } } - /** * An Interval object represents a half-open interval of time, where each endpoint is a {@link DateTime}. Conceptually, it's a container for those two endpoints, accompanied by methods for creating, parsing, interrogating, comparing, transforming, and formatting them. * @@ -3989,6 +4499,8 @@ function validateStartEnd(start, end) { * * **Comparison** To compare this Interval to another one, use {@link Interval#equals}, {@link Interval#overlaps}, {@link Interval#abutsStart}, {@link Interval#abutsEnd}, {@link Interval#engulfs} * * **Output** To convert the Interval into other representations, see {@link Interval#toString}, {@link Interval#toLocaleString}, {@link Interval#toISO}, {@link Interval#toISODate}, {@link Interval#toISOTime}, {@link Interval#toFormat}, and {@link Interval#toDuration}. */ + + class Interval { /** * @private @@ -4001,29 +4513,36 @@ class Interval { /** * @access private */ + this.e = config.end; /** * @access private */ + this.invalid = config.invalid || null; /** * @access private */ + 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) { let explanation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 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 { @@ -4032,17 +4551,19 @@ class Interval { }); } } - /** * 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(start, end) { const builtStart = friendlyDateTime(start), - builtEnd = friendlyDateTime(end); + builtEnd = friendlyDateTime(end); const validateError = validateStartEnd(builtStart, builtEnd); + if (validateError == null) { return new Interval({ start: builtStart, @@ -4052,31 +4573,32 @@ class Interval { 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(start, duration) { const dur = Duration.fromDurationLike(duration), - dt = friendlyDateTime(start); + dt = friendlyDateTime(start); 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(end, duration) { const dur = Duration.fromDurationLike(duration), - dt = friendlyDateTime(end); + dt = friendlyDateTime(end); return Interval.fromDateTimes(dt.minus(dur), dt); } - /** * Create an Interval from an ISO 8601 string. * Accepts `/`, `/`, and `/` formats. @@ -4085,103 +4607,120 @@ class Interval { * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals * @return {Interval} */ + + static fromISO(text, opts) { const _split = (text || "").split("/", 2), - _split2 = interval_slicedToArray(_split, 2), - s = _split2[0], - e = _split2[1]; + _split2 = interval_slicedToArray(_split, 2), + s = _split2[0], + e = _split2[1]; + if (s && e) { let start, startIsValid; + try { start = DateTime.fromISO(s, opts); startIsValid = start.isValid; } catch (e) { startIsValid = false; } + let end, endIsValid; + try { end = DateTime.fromISO(e, opts); endIsValid = end.isValid; } catch (e) { endIsValid = false; } + if (startIsValid && endIsValid) { return Interval.fromDateTimes(start, end); } + if (startIsValid) { const dur = Duration.fromISO(e, opts); + if (dur.isValid) { return Interval.after(start, dur); } } else if (endIsValid) { const dur = Duration.fromISO(s, opts); + if (dur.isValid) { return Interval.before(end, 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() { let unit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "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' @@ -4189,61 +4728,67 @@ class Interval { * @param {string} [unit='milliseconds'] - the unit of time to count. * @return {number} */ + + count() { let unit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "milliseconds"; if (!this.isValid) return NaN; const start = this.start.startOf(unit), - end = this.end.startOf(unit); + end = this.end.startOf(unit); return Math.floor(end.diff(start, unit).get(unit)) + 1; } - /** * 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 @@ -4251,53 +4796,65 @@ class Interval { * @param {DateTime} values.end - the ending DateTime * @return {Interval} */ + + set() { let _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - start = _ref.start, - end = _ref.end; + start = _ref.start, + end = _ref.end; + if (!this.isValid) return this; return Interval.fromDateTimes(start || this.s, end || this.e); } - /** * Split this Interval at each of the specified DateTimes * @param {...DateTime} dateTimes - the unit of time to count. * @return {Array} */ + + splitAt() { if (!this.isValid) return []; + for (var _len = arguments.length, dateTimes = new Array(_len), _key = 0; _key < _len; _key++) { dateTimes[_key] = arguments[_key]; } + const sorted = dateTimes.map(friendlyDateTime).filter(d => this.contains(d)).sort(), - results = []; + results = []; let s = this.s, - i = 0; + i = 0; + while (s < this.e) { const added = sorted[i] || this.e, - next = +added > +this.e ? this.e : added; + next = +added > +this.e ? this.e : added; results.push(Interval.fromDateTimes(s, next)); s = 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 = this.s, - idx = 1, - next; + idx = 1, + next; const results = []; + while (s < this.e) { const added = this.start.plus(dur.mapUnits(x => x * idx)); next = +added > +this.e ? this.e : added; @@ -4305,70 +4862,77 @@ class Interval { s = 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. @@ -4376,88 +4940,101 @@ class Interval { * @param {Interval} other * @return {Interval} */ + + intersection(other) { if (!this.isValid) return this; const s = this.s > other.s ? this.s : other.s, - e = this.e < other.e ? this.e : other.e; + e = this.e < other.e ? this.e : other.e; + if (s >= e) { return null; } else { return Interval.fromDateTimes(s, 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 s = this.s < other.s ? this.s : other.s, - e = this.e > other.e ? this.e : other.e; + e = this.e > other.e ? this.e : other.e; return Interval.fromDateTimes(s, 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 _intervals$sort$reduc = intervals.sort((a, b) => a.s - b.s).reduce((_ref2, item) => { - let _ref3 = interval_slicedToArray(_ref2, 2), + let _ref3 = interval_slicedToArray(_ref2, 2), sofar = _ref3[0], current = _ref3[1]; - 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]), - _intervals$sort$reduc2 = interval_slicedToArray(_intervals$sort$reduc, 2), - found = _intervals$sort$reduc2[0], - final = _intervals$sort$reduc2[1]; + + 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]), + _intervals$sort$reduc2 = interval_slicedToArray(_intervals$sort$reduc, 2), + found = _intervals$sort$reduc2[0], + final = _intervals$sort$reduc2[1]; + 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 start = null, - currentCount = 0; + 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); + 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); + var _iterator = interval_createForOfIteratorHelper(arr), - _step; + _step; + try { for (_iterator.s(); !(_step = _iterator.n()).done;) { const i = _step.value; currentCount += i.type === "s" ? 1 : -1; + if (currentCount === 1) { start = i.time; } else { if (start && +start !== +i.time) { results.push(Interval.fromDateTimes(start, i.time)); } + start = null; } } @@ -4466,30 +5043,33 @@ class Interval { } finally { _iterator.f(); } + 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() { for (var _len2 = arguments.length, intervals = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { intervals[_key2] = arguments[_key2]; } + 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 interval_INVALID; return `[${this.s.toISO()} – ${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 @@ -4508,34 +5088,37 @@ class Interval { * @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() { let formatOpts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DATE_SHORT; let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return this.isValid ? Formatter.create(this.s.loc.clone(opts), formatOpts).formatInterval(this) : interval_INVALID; } - /** * 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 interval_INVALID; 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 interval_INVALID; return `${this.s.toISODate()}/${this.e.toISODate()}`; } - /** * Returns an ISO 8601-compliant string representation of time of this Interval. * The date components are ignored. @@ -4543,11 +5126,12 @@ class Interval { * @param {Object} opts - The same options as {@link DateTime#toISO} * @return {string} */ + + toISOTime(opts) { if (!this.isValid) return interval_INVALID; 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 @@ -4559,14 +5143,16 @@ class Interval { * representations. * @return {string} */ + + toFormat(dateFormat) { let _ref4 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref4$separator = _ref4.separator, - separator = _ref4$separator === void 0 ? " – " : _ref4$separator; + _ref4$separator = _ref4.separator, + separator = _ref4$separator === void 0 ? " – " : _ref4$separator; + if (!this.isValid) return interval_INVALID; 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. @@ -4579,13 +5165,15 @@ class Interval { * @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 @@ -4593,9 +5181,12 @@ class 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)); } + } ;// CONCATENATED MODULE: ./node_modules/luxon/src/info.js @@ -4604,10 +5195,10 @@ class Interval { - /** * The Info class contains static methods for retrieving general time and date related data. For example, it has methods for finding out if a time zone has a DST, for listing the months in any supported locale, and for discovering which of Luxon features are available in the current environment. */ + class Info { /** * Return whether the specified zone contains a DST. @@ -4623,16 +5214,16 @@ class Info { 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. * @@ -4647,10 +5238,11 @@ class Info { * @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 @@ -4668,20 +5260,23 @@ class Info { * @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I' * @return {Array} */ + + static months() { let length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "long"; + let _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref$locale = _ref.locale, - locale = _ref$locale === void 0 ? null : _ref$locale, - _ref$numberingSystem = _ref.numberingSystem, - numberingSystem = _ref$numberingSystem === void 0 ? null : _ref$numberingSystem, - _ref$locObj = _ref.locObj, - locObj = _ref$locObj === void 0 ? null : _ref$locObj, - _ref$outputCalendar = _ref.outputCalendar, - outputCalendar = _ref$outputCalendar === void 0 ? "gregory" : _ref$outputCalendar; + _ref$locale = _ref.locale, + locale = _ref$locale === void 0 ? null : _ref$locale, + _ref$numberingSystem = _ref.numberingSystem, + numberingSystem = _ref$numberingSystem === void 0 ? null : _ref$numberingSystem, + _ref$locObj = _ref.locObj, + locObj = _ref$locObj === void 0 ? null : _ref$locObj, + _ref$outputCalendar = _ref.outputCalendar, + outputCalendar = _ref$outputCalendar === void 0 ? "gregory" : _ref$outputCalendar; + 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 @@ -4695,20 +5290,23 @@ class Info { * @param {string} [opts.outputCalendar='gregory'] - the calendar * @return {Array} */ + + static monthsFormat() { let length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "long"; + let _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref2$locale = _ref2.locale, - locale = _ref2$locale === void 0 ? null : _ref2$locale, - _ref2$numberingSystem = _ref2.numberingSystem, - numberingSystem = _ref2$numberingSystem === void 0 ? null : _ref2$numberingSystem, - _ref2$locObj = _ref2.locObj, - locObj = _ref2$locObj === void 0 ? null : _ref2$locObj, - _ref2$outputCalendar = _ref2.outputCalendar, - outputCalendar = _ref2$outputCalendar === void 0 ? "gregory" : _ref2$outputCalendar; + _ref2$locale = _ref2.locale, + locale = _ref2$locale === void 0 ? null : _ref2$locale, + _ref2$numberingSystem = _ref2.numberingSystem, + numberingSystem = _ref2$numberingSystem === void 0 ? null : _ref2$numberingSystem, + _ref2$locObj = _ref2.locObj, + locObj = _ref2$locObj === void 0 ? null : _ref2$locObj, + _ref2$outputCalendar = _ref2.outputCalendar, + outputCalendar = _ref2$outputCalendar === void 0 ? "gregory" : _ref2$outputCalendar; + 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 @@ -4723,18 +5321,21 @@ class Info { * @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين' * @return {Array} */ + + static weekdays() { let length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "long"; + let _ref3 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref3$locale = _ref3.locale, - locale = _ref3$locale === void 0 ? null : _ref3$locale, - _ref3$numberingSystem = _ref3.numberingSystem, - numberingSystem = _ref3$numberingSystem === void 0 ? null : _ref3$numberingSystem, - _ref3$locObj = _ref3.locObj, - locObj = _ref3$locObj === void 0 ? null : _ref3$locObj; + _ref3$locale = _ref3.locale, + locale = _ref3$locale === void 0 ? null : _ref3$locale, + _ref3$numberingSystem = _ref3.numberingSystem, + numberingSystem = _ref3$numberingSystem === void 0 ? null : _ref3$numberingSystem, + _ref3$locObj = _ref3.locObj, + locObj = _ref3$locObj === void 0 ? null : _ref3$locObj; + 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 @@ -4747,18 +5348,21 @@ class Info { * @param {string} [opts.locObj=null] - an existing locale object to use * @return {Array} */ + + static weekdaysFormat() { let length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "long"; + let _ref4 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref4$locale = _ref4.locale, - locale = _ref4$locale === void 0 ? null : _ref4$locale, - _ref4$numberingSystem = _ref4.numberingSystem, - numberingSystem = _ref4$numberingSystem === void 0 ? null : _ref4$numberingSystem, - _ref4$locObj = _ref4.locObj, - locObj = _ref4$locObj === void 0 ? null : _ref4$locObj; + _ref4$locale = _ref4.locale, + locale = _ref4$locale === void 0 ? null : _ref4$locale, + _ref4$numberingSystem = _ref4.numberingSystem, + numberingSystem = _ref4$numberingSystem === void 0 ? null : _ref4$numberingSystem, + _ref4$locObj = _ref4.locObj, + locObj = _ref4$locObj === void 0 ? null : _ref4$locObj; + return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length, true); } - /** * Return an array of meridiems. * @param {Object} opts - options @@ -4767,13 +5371,15 @@ class Info { * @example Info.meridiems({ locale: 'my' }) //=> [ 'နံနက်', 'ညနေ' ] * @return {Array} */ + + static meridiems() { let _ref5 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - _ref5$locale = _ref5.locale, - locale = _ref5$locale === void 0 ? null : _ref5$locale; + _ref5$locale = _ref5.locale, + locale = _ref5$locale === void 0 ? null : _ref5$locale; + 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". @@ -4784,14 +5390,17 @@ class Info { * @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ] * @return {Array} */ + + static eras() { let length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "short"; + let _ref6 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref6$locale = _ref6.locale, - locale = _ref6$locale === void 0 ? null : _ref6$locale; + _ref6$locale = _ref6.locale, + locale = _ref6$locale === void 0 ? null : _ref6$locale; + 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. @@ -4800,27 +5409,39 @@ class Info { * @example Info.features() //=> { relative: false } * @return {Object} */ + + static features() { return { relative: hasRelative() }; } + } ;// CONCATENATED MODULE: ./node_modules/luxon/src/impl/diff.js function diff_slicedToArray(arr, i) { return diff_arrayWithHoles(arr) || diff_iterableToArrayLimit(arr, i) || diff_unsupportedIterableToArray(arr, i) || diff_nonIterableRest(); } + function diff_nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + function diff_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return diff_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return diff_arrayLikeToArray(o, minLen); } + function diff_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } -function diff_iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } } + +function diff_iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + function diff_arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + + function dayDiff(earlier, later) { const utcDayStart = dt => dt.toUTC(0, { - keepLocalTime: true - }).startOf("day").valueOf(), - ms = utcDayStart(later) - utcDayStart(earlier); + 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); @@ -4829,14 +5450,17 @@ function highOrderDiffs(cursor, later, units) { const results = {}; const earlier = cursor; let lowestOrder, highWater; + for (var _i = 0, _differs = differs; _i < _differs.length; _i++) { const _differs$_i = diff_slicedToArray(_differs[_i], 2), - unit = _differs$_i[0], - differ = _differs$_i[1]; + unit = _differs$_i[0], + differ = _differs$_i[1]; + 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); @@ -4845,28 +5469,35 @@ function highOrderDiffs(cursor, later, units) { } } } + return [cursor, results, highWater, lowestOrder]; } + /* harmony default export */ function diff(earlier, later, units, opts) { let _highOrderDiffs = highOrderDiffs(earlier, later, units), - _highOrderDiffs2 = diff_slicedToArray(_highOrderDiffs, 4), - cursor = _highOrderDiffs2[0], - results = _highOrderDiffs2[1], - highWater = _highOrderDiffs2[2], - lowestOrder = _highOrderDiffs2[3]; + _highOrderDiffs2 = diff_slicedToArray(_highOrderDiffs, 4), + cursor = _highOrderDiffs2[0], + results = _highOrderDiffs2[1], + highWater = _highOrderDiffs2[2], + lowestOrder = _highOrderDiffs2[3]; + 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 { @@ -4875,11 +5506,17 @@ function highOrderDiffs(cursor, later, units) { } ;// CONCATENATED MODULE: ./node_modules/luxon/src/impl/digits.js function digits_slicedToArray(arr, i) { return digits_arrayWithHoles(arr) || digits_iterableToArrayLimit(arr, i) || digits_unsupportedIterableToArray(arr, i) || digits_nonIterableRest(); } + function digits_nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + function digits_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return digits_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return digits_arrayLikeToArray(o, minLen); } + function digits_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } -function digits_iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } } + +function digits_iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + function digits_arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + const numberingSystems = { arab: "[\u0660-\u0669]", arabext: "[\u06F0-\u06F9]", @@ -4927,23 +5564,28 @@ const numberingSystemsUTF16 = { const 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 _numberingSystemsUTF = digits_slicedToArray(numberingSystemsUTF16[key], 2), - min = _numberingSystemsUTF[0], - max = _numberingSystemsUTF[1]; + min = _numberingSystemsUTF[0], + max = _numberingSystemsUTF[1]; + if (code >= min && code <= max) { value += code - min; } } } } + return parseInt(value, 10); } else { return value; @@ -4956,10 +5598,15 @@ function digitRegex(_ref) { } ;// CONCATENATED MODULE: ./node_modules/luxon/src/impl/tokenParser.js function tokenParser_slicedToArray(arr, i) { return tokenParser_arrayWithHoles(arr) || tokenParser_iterableToArrayLimit(arr, i) || tokenParser_unsupportedIterableToArray(arr, i) || tokenParser_nonIterableRest(); } + function tokenParser_nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + function tokenParser_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return tokenParser_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return tokenParser_arrayLikeToArray(o, minLen); } + function tokenParser_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } -function tokenParser_iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } } + +function tokenParser_iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + function tokenParser_arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } @@ -4968,31 +5615,38 @@ function tokenParser_arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + const MISSING_FTP = "missing Intl.DateTimeFormat.formatToParts support"; + function intUnit(regex) { let post = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : i => i; return { regex, deser: _ref => { let _ref2 = tokenParser_slicedToArray(_ref, 1), - s = _ref2[0]; + s = _ref2[0]; + return post(parseDigits(s)); } }; } + const NBSP = String.fromCharCode(160); const spaceOrNBSP = `[ ${NBSP}]`; const spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, "g"); + function fixListRegex(s) { // make dots optional and also make them literal // make space and non breakable space characters interchangeable return s.replace(/\./g, "\\.?").replace(spaceOrNBSPRegExp, spaceOrNBSP); } + function stripInsensitivities(s) { return s.replace(/\./g, "") // ignore dots that were made optional .replace(spaceOrNBSPRegExp, " ") // interchange space and nbsp .toLowerCase(); } + function oneOf(strings, startIndex) { if (strings === null) { return null; @@ -5001,182 +5655,240 @@ function oneOf(strings, startIndex) { regex: RegExp(strings.map(fixListRegex).join("|")), deser: _ref3 => { let _ref4 = tokenParser_slicedToArray(_ref3, 1), - s = _ref4[0]; + s = _ref4[0]; + return strings.findIndex(i => stripInsensitivities(s) === stripInsensitivities(i)) + startIndex; } }; } } + function offset(regex, groups) { return { regex, deser: _ref5 => { let _ref6 = tokenParser_slicedToArray(_ref5, 3), - h = _ref6[1], - m = _ref6[2]; + h = _ref6[1], + m = _ref6[2]; + return signedOffset(h, m); }, groups }; } + function simple(regex) { return { regex, deser: _ref7 => { let _ref8 = tokenParser_slicedToArray(_ref7, 1), - s = _ref8[0]; + s = _ref8[0]; + return s; } }; } + 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: _ref9 => { - let _ref10 = tokenParser_slicedToArray(_ref9, 1), + 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: _ref9 => { + let _ref10 = tokenParser_slicedToArray(_ref9, 1), s = _ref10[0]; - return s; - }, - literal: true - }), - unitate = t => { - if (token.literal) { + + return s; + }, + literal: true + }), + unitate = t => { + if (token.literal) { + return literal(t); + } + + switch (t.val) { + // era + case "G": + return oneOf(loc.eras("short", false), 0); + + case "GG": + return oneOf(loc.eras("long", false), 0); + // years + + 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); + // months + + 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); + // dates + + case "d": + return intUnit(oneOrTwo); + + case "dd": + return intUnit(two); + // ordinals + + case "o": + return intUnit(oneToThree); + + case "ooo": + return intUnit(three); + // time + + 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); + // meridiem + + case "a": + return oneOf(loc.meridiems(), 0); + // weekYear (k) + + case "kkkk": + return intUnit(four); + + case "kk": + return intUnit(twoToFour, untruncateYear); + // weekNumber (W) + + case "W": + return intUnit(oneOrTwo); + + case "WW": + return intUnit(two); + // weekdays + + 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); + // offset/zone + + case "Z": + case "ZZ": + return offset(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2); + + case "ZZZ": + return offset(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2); + // we don't support ZZZZ (PST) or ZZZZZ (Pacific Standard Time) in parsing + // because we don't have any way to figure out what they are + + case "z": + return simple(/[a-z_+-/]{1,256}?/i); + + default: return literal(t); - } - switch (t.val) { - // era - case "G": - return oneOf(loc.eras("short", false), 0); - case "GG": - return oneOf(loc.eras("long", false), 0); - // years - 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); - // months - 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); - // dates - case "d": - return intUnit(oneOrTwo); - case "dd": - return intUnit(two); - // ordinals - case "o": - return intUnit(oneToThree); - case "ooo": - return intUnit(three); - // time - 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); - // meridiem - case "a": - return oneOf(loc.meridiems(), 0); - // weekYear (k) - case "kkkk": - return intUnit(four); - case "kk": - return intUnit(twoToFour, untruncateYear); - // weekNumber (W) - case "W": - return intUnit(oneOrTwo); - case "WW": - return intUnit(two); - // weekdays - 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); - // offset/zone - case "Z": - case "ZZ": - return offset(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2); - case "ZZZ": - return offset(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2); - // we don't support ZZZZ (PST) or ZZZZZ (Pacific Standard Time) in parsing - // because we don't have any way to figure out what they are - case "z": - return simple(/[a-z_+-/]{1,256}?/i); - default: - return literal(t); - } - }; + } + }; + const unit = unitate(token) || { invalidReason: MISSING_FTP }; unit.token = token; return unit; } + const partTypeStyleToTokenVal = { year: { "2-digit": "yy", @@ -5215,100 +5927,132 @@ const partTypeStyleToTokenVal = { short: "ZZZ" } }; + function tokenForPart(part, formatOpts) { const type = part.type, - value = part.value; + value = part.value; + if (type === "literal") { return { literal: true, val: value }; } + const style = formatOpts[type]; let val = partTypeStyleToTokenVal[type]; + if (typeof val === "object") { val = val[style]; } + if (val) { return { literal: false, val }; } + return undefined; } + 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 (util_hasOwnProperty(handlers, i)) { const h = handlers[i], - groups = h.groups ? h.groups + 1 : 1; + 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; @@ -5316,51 +6060,64 @@ function dateTimeFromMatches(matches) { 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]; } + let 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(undefined)) { return token; } + return tokens; } + function expandMacroTokens(tokens, locale) { return Array.prototype.concat(...tokens.map(t => maybeExpandMacroToken(t, locale))); } - /** * @private */ function explainFromTokens(locale, input, format) { const tokens = expandMacroTokens(Formatter.parseFormat(format), locale), - units = tokens.map(t => unitForToken(t, locale)), - disqualifyingUnit = units.find(t => t.invalidReason); + units = tokens.map(t => unitForToken(t, locale)), + disqualifyingUnit = units.find(t => t.invalidReason); + if (disqualifyingUnit) { return { input, @@ -5369,22 +6126,24 @@ function explainFromTokens(locale, input, format) { }; } else { const _buildRegex = buildRegex(units), - _buildRegex2 = tokenParser_slicedToArray(_buildRegex, 2), - regexString = _buildRegex2[0], - handlers = _buildRegex2[1], - regex = RegExp(regexString, "i"), - _match = match(input, regex, handlers), - _match2 = tokenParser_slicedToArray(_match, 2), - rawMatches = _match2[0], - matches = _match2[1], - _ref11 = matches ? dateTimeFromMatches(matches) : [null, null, undefined], - _ref12 = tokenParser_slicedToArray(_ref11, 3), - result = _ref12[0], - zone = _ref12[1], - specificOffset = _ref12[2]; + _buildRegex2 = tokenParser_slicedToArray(_buildRegex, 2), + regexString = _buildRegex2[0], + handlers = _buildRegex2[1], + regex = RegExp(regexString, "i"), + _match = match(input, regex, handlers), + _match2 = tokenParser_slicedToArray(_match, 2), + rawMatches = _match2[0], + matches = _match2[1], + _ref11 = matches ? dateTimeFromMatches(matches) : [null, null, undefined], + _ref12 = tokenParser_slicedToArray(_ref11, 3), + result = _ref12[0], + zone = _ref12[1], + specificOffset = _ref12[2]; + if (util_hasOwnProperty(matches, "a") && util_hasOwnProperty(matches, "H")) { throw new ConflictingSpecificationError("Can't include meridiem when specifying 24-hour format"); } + return { input, tokens, @@ -5399,66 +6158,76 @@ function explainFromTokens(locale, input, format) { } function parseFromTokens(locale, input, format) { const _explainFromTokens = explainFromTokens(locale, input, format), - result = _explainFromTokens.result, - zone = _explainFromTokens.zone, - specificOffset = _explainFromTokens.specificOffset, - invalidReason = _explainFromTokens.invalidReason; + result = _explainFromTokens.result, + zone = _explainFromTokens.zone, + specificOffset = _explainFromTokens.specificOffset, + invalidReason = _explainFromTokens.invalidReason; + 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)); } ;// CONCATENATED MODULE: ./node_modules/luxon/src/impl/conversions.js function conversions_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } + function conversions_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? conversions_ownKeys(Object(source), !0).forEach(function (key) { conversions_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : conversions_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } -function conversions_defineProperty(obj, key, value) { key = conversions_toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function conversions_toPropertyKey(arg) { var key = conversions_toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function conversions_toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } + +function conversions_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + const nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334], - leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]; + 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]; + month0 = table.findIndex(i => i < ordinal), + day = ordinal - table[month0]; return { month: month0 + 1, day }; } - /** * @private */ + function gregorianToWeek(gregObj) { const year = gregObj.year, - month = gregObj.month, - day = gregObj.day, - ordinal = computeOrdinal(year, month, day), - weekday = dayOfWeek(year, month, day); + month = gregObj.month, + day = gregObj.day, + ordinal = computeOrdinal(year, month, day), + weekday = dayOfWeek(year, month, day); let weekNumber = Math.floor((ordinal - weekday + 10) / 7), - weekYear; + weekYear; + if (weekNumber < 1) { weekYear = year - 1; weekNumber = weeksInWeekYear(weekYear); @@ -5468,6 +6237,7 @@ function gregorianToWeek(gregObj) { } else { weekYear = year; } + return conversions_objectSpread({ weekYear, weekNumber, @@ -5476,12 +6246,13 @@ function gregorianToWeek(gregObj) { } function weekToGregorian(weekData) { const weekYear = weekData.weekYear, - weekNumber = weekData.weekNumber, - weekday = weekData.weekday, - weekdayOfJan4 = dayOfWeek(weekYear, 1, 4), - yearInDays = daysInYear(weekYear); + weekNumber = weekData.weekNumber, + weekday = weekData.weekday, + weekdayOfJan4 = dayOfWeek(weekYear, 1, 4), + yearInDays = daysInYear(weekYear); let ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 3, - year; + year; + if (ordinal < 1) { year = weekYear - 1; ordinal += daysInYear(year); @@ -5491,9 +6262,11 @@ function weekToGregorian(weekData) { } else { year = weekYear; } + const _uncomputeOrdinal = uncomputeOrdinal(year, ordinal), - month = _uncomputeOrdinal.month, - day = _uncomputeOrdinal.day; + month = _uncomputeOrdinal.month, + day = _uncomputeOrdinal.day; + return conversions_objectSpread({ year, month, @@ -5502,8 +6275,8 @@ function weekToGregorian(weekData) { } function gregorianToOrdinal(gregData) { const year = gregData.year, - month = gregData.month, - day = gregData.day; + month = gregData.month, + day = gregData.day; const ordinal = computeOrdinal(year, month, day); return conversions_objectSpread({ year, @@ -5512,10 +6285,12 @@ function gregorianToOrdinal(gregData) { } function ordinalToGregorian(ordinalData) { const year = ordinalData.year, - ordinal = ordinalData.ordinal; + ordinal = ordinalData.ordinal; + const _uncomputeOrdinal2 = uncomputeOrdinal(year, ordinal), - month = _uncomputeOrdinal2.month, - day = _uncomputeOrdinal2.day; + month = _uncomputeOrdinal2.month, + day = _uncomputeOrdinal2.day; + return conversions_objectSpread({ year, month, @@ -5524,8 +6299,9 @@ function ordinalToGregorian(ordinalData) { } function hasInvalidWeekData(obj) { const validYear = isInteger(obj.weekYear), - validWeek = integerBetween(obj.weekNumber, 1, weeksInWeekYear(obj.weekYear)), - validWeekday = integerBetween(obj.weekday, 1, 7); + validWeek = integerBetween(obj.weekNumber, 1, weeksInWeekYear(obj.weekYear)), + validWeekday = integerBetween(obj.weekday, 1, 7); + if (!validYear) { return unitOutOfRange("weekYear", obj.weekYear); } else if (!validWeek) { @@ -5536,7 +6312,8 @@ function hasInvalidWeekData(obj) { } function hasInvalidOrdinalData(obj) { const validYear = isInteger(obj.year), - validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year)); + validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year)); + if (!validYear) { return unitOutOfRange("year", obj.year); } else if (!validOrdinal) { @@ -5545,8 +6322,9 @@ function hasInvalidOrdinalData(obj) { } function hasInvalidGregorianData(obj) { const validYear = isInteger(obj.year), - validMonth = integerBetween(obj.month, 1, 12), - validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month)); + 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) { @@ -5557,13 +6335,14 @@ function hasInvalidGregorianData(obj) { } function hasInvalidTimeData(obj) { const hour = obj.hour, - minute = obj.minute, - second = obj.second, - millisecond = obj.millisecond; + minute = obj.minute, + second = obj.second, + millisecond = obj.millisecond; 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); + validMinute = integerBetween(minute, 0, 59), + validSecond = integerBetween(second, 0, 59), + validMillisecond = integerBetween(millisecond, 0, 999); + if (!validHour) { return unitOutOfRange("hour", hour); } else if (!validMinute) { @@ -5576,17 +6355,25 @@ function hasInvalidTimeData(obj) { } ;// CONCATENATED MODULE: ./node_modules/luxon/src/datetime.js function datetime_createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = datetime_unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } + function datetime_slicedToArray(arr, i) { return datetime_arrayWithHoles(arr) || datetime_iterableToArrayLimit(arr, i) || datetime_unsupportedIterableToArray(arr, i) || datetime_nonIterableRest(); } + function datetime_nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + function datetime_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return datetime_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return datetime_arrayLikeToArray(o, minLen); } + function datetime_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } -function datetime_iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } } + +function datetime_iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + function datetime_arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + function datetime_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } + function datetime_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? datetime_ownKeys(Object(source), !0).forEach(function (key) { datetime_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : datetime_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } -function datetime_defineProperty(obj, key, value) { key = datetime_toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function datetime_toPropertyKey(arg) { var key = datetime_toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function datetime_toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } + +function datetime_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + @@ -5605,20 +6392,22 @@ function datetime_toPrimitive(input, hint) { if (typeof input !== "object" || in const datetime_INVALID = "Invalid DateTime"; const MAX_DATE = 8.64e15; + function unsupportedZone(zone) { return new Invalid("unsupported zone", `the zone "${zone.name}" is not supported`); -} +} // we cache week data on the DT object and this intermediates the cache + -// we cache week data on the DT object and this intermediates the cache function possiblyCachedWeekData(dt) { if (dt.weekData === null) { dt.weekData = gregorianToWeek(dt.c); } - return dt.weekData; -} -// clone really means, "make a new object with these modifications". all "setters" really use this + return dt.weekData; +} // clone really means, "make a new object with these modifications". all "setters" really use this // to create a new object while only changing some of the properties + + function datetime_clone(inst, alts) { const current = { ts: inst.ts, @@ -5631,36 +6420,34 @@ function datetime_clone(inst, alts) { return new DateTime(datetime_objectSpread(datetime_objectSpread(datetime_objectSpread({}, current), alts), {}, { old: current })); -} - -// find the right offset a given local time. The o input is our guess, which determines which +} // find the right offset a given local time. The o input is our guess, which determines which // offset we'll pick in ambiguous cases (e.g. there are two 3 AMs b/c Fallback DST) + + function fixOffset(localTS, o, tz) { // Our UTC time is just a guess because our offset is just a guess - let utcGuess = localTS - o * 60 * 1000; + let utcGuess = localTS - o * 60 * 1000; // Test whether the zone matches the offset for this ts - // Test whether the zone matches the offset for this ts - const o2 = tz.offset(utcGuess); + const o2 = tz.offset(utcGuess); // If so, offset didn't change and we're done - // If so, offset didn't change and we're done if (o === o2) { return [utcGuess, o]; - } + } // If not, change the ts by the difference in the offset - // If not, change the ts by the difference in the offset - utcGuess -= (o2 - o) * 60 * 1000; - // If that gives us the local time we want, we're done + utcGuess -= (o2 - o) * 60 * 1000; // If that gives us the local time we want, we're done + const o3 = tz.offset(utcGuess); + if (o2 === o3) { return [utcGuess, o2]; - } + } // If it's different, we're in a hole time. The offset has changed, but the we don't adjust the time + - // If it's different, we're in a hole time. The offset has changed, but the we don't adjust the time return [localTS - Math.min(o2, o3) * 60 * 1000, Math.max(o2, o3)]; -} +} // convert an epoch timestamp into a calendar object with the given offset + -// convert an epoch timestamp into a calendar object with the given offset function tsToObj(ts, offset) { ts += offset * 60 * 1000; const d = new Date(ts); @@ -5673,69 +6460,73 @@ function tsToObj(ts, offset) { second: d.getUTCSeconds(), millisecond: d.getUTCMilliseconds() }; -} +} // convert a calendar object to a epoch timestamp + -// convert a calendar object to a epoch timestamp function objToTS(obj, offset, zone) { return fixOffset(objToLocalTS(obj), offset, zone); -} +} // create a new DT instance by adding a duration, adjusting for DSTs + -// create a new DT instance by adding a duration, adjusting for DSTs 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 = datetime_objectSpread(datetime_objectSpread({}, 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); + year = inst.c.year + Math.trunc(dur.years), + month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3, + c = datetime_objectSpread(datetime_objectSpread({}, 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 _fixOffset = fixOffset(localTS, oPre, inst.zone), - _fixOffset2 = datetime_slicedToArray(_fixOffset, 2), - ts = _fixOffset2[0], - o = _fixOffset2[1]; + _fixOffset2 = datetime_slicedToArray(_fixOffset, 2), + ts = _fixOffset2[0], + o = _fixOffset2[1]; + if (millisToAdd !== 0) { - ts += millisToAdd; - // that could have changed the offset by going over a DST, but we want to keep the ts the same + ts += millisToAdd; // that could have changed the offset by going over a DST, but we want to keep the ts the same + o = inst.zone.offset(ts); } + return { ts, o }; -} - -// helper useful in turning the results of parsing into real dates +} // helper useful in turning the results of parsing into real dates // by handling the zone options + + function parseDataToDateTime(parsed, parsedZone, opts, format, text, specificOffset) { const setZone = opts.setZone, - zone = opts.zone; + zone = opts.zone; + if (parsed && Object.keys(parsed).length !== 0) { const interpretationZone = parsedZone || zone, - inst = DateTime.fromObject(parsed, datetime_objectSpread(datetime_objectSpread({}, opts), {}, { - zone: interpretationZone, - specificOffset - })); + inst = DateTime.fromObject(parsed, datetime_objectSpread(datetime_objectSpread({}, 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 ${format}`)); } -} - -// if you want to output a technical format (e.g. RFC 2822), this helper +} // if you want to output a technical format (e.g. RFC 2822), this helper // helps handle the details + + function toTechFormat(dt, format) { let allowZ = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; return dt.isValid ? Formatter.create(Locale.create("en-US"), { @@ -5743,11 +6534,13 @@ function toTechFormat(dt, format) { forceSimple: true }).formatDateTimeFromString(dt, format) : 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); @@ -5757,26 +6550,33 @@ function toISODate(o, extended) { 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"; @@ -5792,43 +6592,43 @@ function toISOTime(o, extended, suppressSeconds, suppressMilliseconds, includeOf c += padStart(Math.trunc(o.o % 60)); } } + if (extendedZone) { c += "[" + o.zone.ianaName + "]"; } + return c; -} +} // defaults for unspecified units in the supported calendars + -// defaults for unspecified units in the supported calendars const defaultUnitValues = { - month: 1, - day: 1, - hour: 0, - minute: 0, - second: 0, - millisecond: 0 - }, - defaultWeekUnitValues = { - weekNumber: 1, - weekday: 1, - hour: 0, - minute: 0, - second: 0, - millisecond: 0 - }, - defaultOrdinalUnitValues = { - ordinal: 1, - hour: 0, - minute: 0, - second: 0, - millisecond: 0 - }; + month: 1, + day: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0 +}, + defaultWeekUnitValues = { + weekNumber: 1, + weekday: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0 +}, + defaultOrdinalUnitValues = { + ordinal: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0 +}; // Units in the supported calendars, sorted by bigness -// Units in the supported calendars, sorted by bigness const datetime_orderedUnits = ["year", "month", "day", "hour", "minute", "second", "millisecond"], - orderedWeekUnits = ["weekYear", "weekNumber", "weekday", "hour", "minute", "second", "millisecond"], - orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"]; + orderedWeekUnits = ["weekYear", "weekNumber", "weekday", "hour", "minute", "second", "millisecond"], + orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"]; // standardize case and plurality in units -// standardize case and plurality in units function normalizeUnit(unit) { const normalized = { year: "year", @@ -5858,37 +6658,53 @@ function normalizeUnit(unit) { }[unit.toLowerCase()]; if (!normalized) throw new InvalidUnitError(unit); return normalized; -} - -// this is a dumbed down version of fromObject() that runs about 60% faster +} // this is a dumbed down version of fromObject() that runs about 60% faster // but doesn't do any validation, makes a bunch of assumptions about what units // are present, and so on. + + function quickDT(obj, opts) { const zone = normalizeZone(opts.zone, Settings.defaultZone), - loc = Locale.fromObject(opts), - tsNow = Settings.now(); - let ts, o; + loc = Locale.fromObject(opts), + tsNow = Settings.now(); + let ts, o; // assume we have the higher-order units - // assume we have the higher-order units if (!isUndefined(obj.year)) { - for (var _i2 = 0, _orderedUnits = datetime_orderedUnits; _i2 < _orderedUnits.length; _i2++) { - const u = _orderedUnits[_i2]; - if (isUndefined(obj[u])) { - obj[u] = defaultUnitValues[u]; + var _iterator = datetime_createForOfIteratorHelper(datetime_orderedUnits), + _step; + + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + const u = _step.value; + + if (isUndefined(obj[u])) { + obj[u] = defaultUnitValues[u]; + } } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); } + const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj); + if (invalid) { return DateTime.invalid(invalid); } + const offsetProvis = zone.offset(tsNow); + var _objToTS = objToTS(obj, offsetProvis, zone); + var _objToTS2 = datetime_slicedToArray(_objToTS, 2); + ts = _objToTS2[0]; o = _objToTS2[1]; } else { ts = tsNow; } + return new DateTime({ ts, zone, @@ -5896,54 +6712,62 @@ function quickDT(obj, opts) { o }); } + function diffRelative(start, end, opts) { const round = isUndefined(opts.round) ? true : opts.round, - format = (c, unit) => { - c = roundTo(c, round || opts.calendary ? 0 : 2, true); - const formatter = end.loc.clone(opts).relFormatter(opts); - return formatter.format(c, unit); - }, - differ = unit => { - if (opts.calendary) { - if (!end.hasSame(start, unit)) { - return end.startOf(unit).diff(start.startOf(unit), unit).get(unit); - } else return 0; - } else { - return end.diff(start, unit).get(unit); - } - }; + format = (c, unit) => { + c = roundTo(c, round || opts.calendary ? 0 : 2, true); + const formatter = end.loc.clone(opts).relFormatter(opts); + return formatter.format(c, unit); + }, + differ = unit => { + if (opts.calendary) { + if (!end.hasSame(start, unit)) { + return end.startOf(unit).diff(start.startOf(unit), unit).get(unit); + } else return 0; + } else { + return end.diff(start, unit).get(unit); + } + }; + if (opts.unit) { return format(differ(opts.unit), opts.unit); } - var _iterator = datetime_createForOfIteratorHelper(opts.units), - _step; + + var _iterator2 = datetime_createForOfIteratorHelper(opts.units), + _step2; + try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - const unit = _step.value; + for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { + const unit = _step2.value; const count = differ(unit); + if (Math.abs(count) >= 1) { return format(count, unit); } } } catch (err) { - _iterator.e(err); + _iterator2.e(err); } finally { - _iterator.f(); + _iterator2.f(); } + return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]); } + function lastOpts(argList) { let opts = {}, - args; + 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]; } - /** * A DateTime is an immutable data structure representing a specific date and time and accompanying methods. It contains class and instance methods for creating, parsing, interrogating, transforming, and formatting them. * @@ -5964,6 +6788,8 @@ function lastOpts(argList) { * * There's plenty others documented below. In addition, for more information on subtler topics like internationalization, time zones, alternative calendars, validity, and so on, see the external documentation. */ + + class DateTime { /** * @access private @@ -5974,11 +6800,14 @@ class DateTime { /** * @access private */ + this.ts = isUndefined(config.ts) ? Settings.now() : config.ts; let c = null, - o = null; + o = null; + if (!invalid) { const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone); + if (unchanged) { var _ref = [config.old.c, config.old.o]; c = _ref[0]; @@ -5991,38 +6820,43 @@ class DateTime { o = invalid ? null : ot; } } - /** * @access private */ + + this._zone = zone; /** * @access private */ + this.loc = config.loc || Locale.create(); /** * @access private */ + this.invalid = invalid; /** * @access private */ + this.weekData = null; /** * @access private */ + this.c = c; /** * @access private */ + this.o = o; /** * @access private */ - this.isLuxonDateTime = true; - } - // CONSTRUCT + this.isLuxonDateTime = true; + } // CONSTRUCT /** * Create a DateTime for the current instant, in the system's time zone. @@ -6031,10 +6865,11 @@ class DateTime { * @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 @@ -6056,19 +6891,22 @@ class DateTime { * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765 * @return {DateTime} */ + + static local() { const _lastOpts = lastOpts(arguments), - _lastOpts2 = datetime_slicedToArray(_lastOpts, 2), - opts = _lastOpts2[0], - args = _lastOpts2[1], - _args = datetime_slicedToArray(args, 7), - year = _args[0], - month = _args[1], - day = _args[2], - hour = _args[3], - minute = _args[4], - second = _args[5], - millisecond = _args[6]; + _lastOpts2 = datetime_slicedToArray(_lastOpts, 2), + opts = _lastOpts2[0], + args = _lastOpts2[1], + _args = datetime_slicedToArray(args, 7), + year = _args[0], + month = _args[1], + day = _args[2], + hour = _args[3], + minute = _args[4], + second = _args[5], + millisecond = _args[6]; + return quickDT({ year, month, @@ -6079,7 +6917,6 @@ class DateTime { 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 @@ -6104,19 +6941,22 @@ class DateTime { * @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 _lastOpts3 = lastOpts(arguments), - _lastOpts4 = datetime_slicedToArray(_lastOpts3, 2), - opts = _lastOpts4[0], - args = _lastOpts4[1], - _args2 = datetime_slicedToArray(args, 7), - year = _args2[0], - month = _args2[1], - day = _args2[2], - hour = _args2[3], - minute = _args2[4], - second = _args2[5], - millisecond = _args2[6]; + _lastOpts4 = datetime_slicedToArray(_lastOpts3, 2), + opts = _lastOpts4[0], + args = _lastOpts4[1], + _args2 = datetime_slicedToArray(args, 7), + year = _args2[0], + month = _args2[1], + day = _args2[2], + hour = _args2[3], + minute = _args2[4], + second = _args2[5], + millisecond = _args2[6]; + opts.zone = FixedOffsetZone.utcInstance; return quickDT({ year, @@ -6128,7 +6968,6 @@ class DateTime { millisecond }, opts); } - /** * Create a DateTime from a JavaScript Date object. Uses the default zone. * @param {Date} date - a JavaScript Date object @@ -6136,23 +6975,28 @@ class DateTime { * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into * @return {DateTime} */ + + static fromJSDate(date) { let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 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: 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 @@ -6163,8 +7007,11 @@ class DateTime { * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance * @return {DateTime} */ + + static fromMillis(milliseconds) { let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + 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) { @@ -6178,7 +7025,6 @@ class DateTime { }); } } - /** * 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 @@ -6189,8 +7035,11 @@ class DateTime { * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance * @return {DateTime} */ + + static fromSeconds(seconds) { let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if (!isNumber(seconds)) { throw new InvalidArgumentError("fromSeconds requires a numerical input"); } else { @@ -6201,7 +7050,6 @@ class DateTime { }); } } - /** * 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 @@ -6230,24 +7078,26 @@ class DateTime { * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13' * @return {DateTime} */ + + static fromObject(obj) { let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 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); - - // cases: + 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); // cases: // just a weekday -> this week's instance of that weekday, no worries // (gregorian data or ordinal) + (weekYear or weekNumber) -> error // (gregorian month or day) + ordinal -> error @@ -6256,15 +7106,17 @@ class DateTime { 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; - // configure ourselves to deal with gregorian dates or week stuff + const useWeekData = definiteWeekDef || normalized.weekday && !containsGregor; // configure ourselves to deal with gregorian dates or week stuff + let units, - defaultValues, - objNow = tsToObj(tsNow, offsetProvis); + defaultValues, + objNow = tsToObj(tsNow, offsetProvis); + if (useWeekData) { units = orderedWeekUnits; defaultValues = defaultWeekUnitValues; @@ -6276,16 +7128,19 @@ class DateTime { } else { units = datetime_orderedUnits; defaultValues = defaultUnitValues; - } + } // set default values for missing stuff + - // set default values for missing stuff let foundFirst = false; - var _iterator2 = datetime_createForOfIteratorHelper(units), - _step2; + + var _iterator3 = datetime_createForOfIteratorHelper(units), + _step3; + try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - const u = _step2.value; + for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { + const u = _step3.value; const v = normalized[u]; + if (!isUndefined(v)) { foundFirst = true; } else if (foundFirst) { @@ -6293,40 +7148,41 @@ class DateTime { } else { normalized[u] = objNow[u]; } - } + } // make sure the values we have are in range - // make sure the values we have are in range } catch (err) { - _iterator2.e(err); + _iterator3.e(err); } finally { - _iterator2.f(); + _iterator3.f(); } + const higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized), - invalid = higherOrderInvalid || hasInvalidTimeData(normalized); + invalid = higherOrderInvalid || hasInvalidTimeData(normalized); + if (invalid) { return DateTime.invalid(invalid); - } + } // compute the actual time + - // compute the actual time const gregorian = useWeekData ? weekToGregorian(normalized) : containsOrdinal ? ordinalToGregorian(normalized) : normalized, - _objToTS3 = objToTS(gregorian, offsetProvis, zoneToUse), - _objToTS4 = datetime_slicedToArray(_objToTS3, 2), - tsFinal = _objToTS4[0], - offsetFinal = _objToTS4[1], - inst = new DateTime({ - ts: tsFinal, - zone: zoneToUse, - o: offsetFinal, - loc - }); + _objToTS3 = objToTS(gregorian, offsetProvis, zoneToUse), + _objToTS4 = datetime_slicedToArray(_objToTS3, 2), + tsFinal = _objToTS4[0], + offsetFinal = _objToTS4[1], + inst = new DateTime({ + ts: tsFinal, + zone: zoneToUse, + o: offsetFinal, + loc + }); // gregorian data + weekday serves only to validate + - // gregorian data + weekday serves only to validate 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 @@ -6343,15 +7199,18 @@ class DateTime { * @example DateTime.fromISO('2016-W05-4') * @return {DateTime} */ + + static fromISO(text) { let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + const _parseISODate = parseISODate(text), - _parseISODate2 = datetime_slicedToArray(_parseISODate, 2), - vals = _parseISODate2[0], - parsedZone = _parseISODate2[1]; + _parseISODate2 = datetime_slicedToArray(_parseISODate, 2), + vals = _parseISODate2[0], + parsedZone = _parseISODate2[1]; + return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text); } - /** * Create a DateTime from an RFC 2822 string * @param {string} text - the RFC 2822 string @@ -6366,15 +7225,18 @@ class DateTime { * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z') * @return {DateTime} */ + + static fromRFC2822(text) { let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + const _parseRFC2822Date = parseRFC2822Date(text), - _parseRFC2822Date2 = datetime_slicedToArray(_parseRFC2822Date, 2), - vals = _parseRFC2822Date2[0], - parsedZone = _parseRFC2822Date2[1]; + _parseRFC2822Date2 = datetime_slicedToArray(_parseRFC2822Date, 2), + vals = _parseRFC2822Date2[0], + parsedZone = _parseRFC2822Date2[1]; + 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 @@ -6390,15 +7252,18 @@ class DateTime { * @example DateTime.fromHTTP('Sun Nov 6 08:49:37 1994') * @return {DateTime} */ + + static fromHTTP(text) { let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + const _parseHTTPDate = parseHTTPDate(text), - _parseHTTPDate2 = datetime_slicedToArray(_parseHTTPDate, 2), - vals = _parseHTTPDate2[0], - parsedZone = _parseHTTPDate2[1]; + _parseHTTPDate2 = datetime_slicedToArray(_parseHTTPDate, 2), + vals = _parseHTTPDate2[0], + parsedZone = _parseHTTPDate2[1]; + 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). @@ -6412,41 +7277,46 @@ class DateTime { * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance * @return {DateTime} */ + + static fromFormat(text, fmt) { let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + if (isUndefined(text) || isUndefined(fmt)) { throw new InvalidArgumentError("fromFormat requires an input string and a format"); } + const _opts$locale = opts.locale, - locale = _opts$locale === void 0 ? null : _opts$locale, - _opts$numberingSystem = opts.numberingSystem, - numberingSystem = _opts$numberingSystem === void 0 ? null : _opts$numberingSystem, - localeToUse = Locale.fromOpts({ - locale, - numberingSystem, - defaultToEN: true - }), - _parseFromTokens = parseFromTokens(localeToUse, text, fmt), - _parseFromTokens2 = datetime_slicedToArray(_parseFromTokens, 4), - vals = _parseFromTokens2[0], - parsedZone = _parseFromTokens2[1], - specificOffset = _parseFromTokens2[2], - invalid = _parseFromTokens2[3]; + locale = _opts$locale === void 0 ? null : _opts$locale, + _opts$numberingSystem = opts.numberingSystem, + numberingSystem = _opts$numberingSystem === void 0 ? null : _opts$numberingSystem, + localeToUse = Locale.fromOpts({ + locale, + numberingSystem, + defaultToEN: true + }), + _parseFromTokens = parseFromTokens(localeToUse, text, fmt), + _parseFromTokens2 = datetime_slicedToArray(_parseFromTokens, 4), + vals = _parseFromTokens2[0], + parsedZone = _parseFromTokens2[1], + specificOffset = _parseFromTokens2[2], + invalid = _parseFromTokens2[3]; + if (invalid) { return DateTime.invalid(invalid); } else { return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text, specificOffset); } } - /** * @deprecated use fromFormat instead */ + + static fromString(text, fmt) { let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; 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 @@ -6467,27 +7337,35 @@ class DateTime { * @example DateTime.fromSQL('09:12:34.342') * @return {DateTime} */ + + static fromSQL(text) { let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + const _parseSQL = parseSQL(text), - _parseSQL2 = datetime_slicedToArray(_parseSQL, 2), - vals = _parseSQL2[0], - parsedZone = _parseSQL2[1]; + _parseSQL2 = datetime_slicedToArray(_parseSQL, 2), + vals = _parseSQL2[0], + parsedZone = _parseSQL2[1]; + 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) { let explanation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 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 { @@ -6496,28 +7374,29 @@ class DateTime { }); } } - /** * 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) { let localeOpts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 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 @@ -6525,13 +7404,13 @@ class DateTime { * @param localeOpts * @returns {string} */ + + static expandFormat(fmt) { let localeOpts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; const expanded = expandMacroTokens(Formatter.parseFormat(fmt), Locale.fromObject(localeOpts)); return expanded.map(t => t.val).join(""); - } - - // INFO + } // INFO /** * Get the value of unit. @@ -6540,171 +7419,190 @@ class DateTime { * @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 @@ -6712,82 +7610,91 @@ class DateTime { * @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, { @@ -6798,12 +7705,13 @@ class DateTime { 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, { @@ -6814,19 +7722,21 @@ class DateTime { 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; @@ -6839,37 +7749,39 @@ class DateTime { }).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 @@ -6877,30 +7789,33 @@ class DateTime { * @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() { let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + const _Formatter$create$res = Formatter.create(this.loc.clone(opts), opts).resolvedOptions(this), - locale = _Formatter$create$res.locale, - numberingSystem = _Formatter$create$res.numberingSystem, - calendar = _Formatter$create$res.calendar; + locale = _Formatter$create$res.locale, + numberingSystem = _Formatter$create$res.numberingSystem, + calendar = _Formatter$create$res.calendar; + return { locale, numberingSystem, outputCalendar: calendar }; - } - - // TRANSFORM + } // TRANSFORM /** * "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime. @@ -6910,22 +7825,24 @@ class DateTime { * @param {Object} [opts={}] - options to pass to `setZone()` * @return {DateTime} */ + + toUTC() { let offset = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return this.setZone(FixedOffsetZone.instance(offset), 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. * @@ -6935,44 +7852,55 @@ class DateTime { * @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) { let _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref2$keepLocalTime = _ref2.keepLocalTime, - keepLocalTime = _ref2$keepLocalTime === void 0 ? false : _ref2$keepLocalTime, - _ref2$keepCalendarTim = _ref2.keepCalendarTime, - keepCalendarTime = _ref2$keepCalendarTim === void 0 ? false : _ref2$keepCalendarTim; + _ref2$keepLocalTime = _ref2.keepLocalTime, + keepLocalTime = _ref2$keepLocalTime === void 0 ? false : _ref2$keepLocalTime, + _ref2$keepCalendarTim = _ref2.keepCalendarTime, + keepCalendarTime = _ref2$keepCalendarTim === void 0 ? false : _ref2$keepCalendarTim; + 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(); + var _objToTS5 = objToTS(asObj, offsetGuess, zone); + var _objToTS6 = datetime_slicedToArray(_objToTS5, 1); + newTS = _objToTS6[0]; } + return datetime_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() { let _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - locale = _ref3.locale, - numberingSystem = _ref3.numberingSystem, - outputCalendar = _ref3.outputCalendar; + locale = _ref3.locale, + numberingSystem = _ref3.numberingSystem, + outputCalendar = _ref3.outputCalendar; + const loc = this.loc.clone({ locale, numberingSystem, @@ -6982,19 +7910,19 @@ class DateTime { 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}. @@ -7005,45 +7933,51 @@ class DateTime { * @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; + 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(datetime_objectSpread(datetime_objectSpread({}, gregorianToWeek(this.c)), normalized)); } else if (!isUndefined(normalized.ordinal)) { mixed = ordinalToGregorian(datetime_objectSpread(datetime_objectSpread({}, gregorianToOrdinal(this.c)), normalized)); } else { - mixed = datetime_objectSpread(datetime_objectSpread({}, this.toObject()), normalized); - - // if we didn't set the day but we ended up on an overflow date, + mixed = datetime_objectSpread(datetime_objectSpread({}, this.toObject()), normalized); // if we didn't set the day but we ended up on an overflow date, // use the last day of the right month + if (isUndefined(normalized.day)) { mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day); } } + const _objToTS7 = objToTS(mixed, this.o, this.zone), - _objToTS8 = datetime_slicedToArray(_objToTS7, 2), - ts = _objToTS8[0], - o = _objToTS8[1]; + _objToTS8 = datetime_slicedToArray(_objToTS7, 2), + ts = _objToTS8[0], + o = _objToTS8[1]; + return datetime_clone(this, { ts, o }); } - /** * Add a period of time to this DateTime and return the resulting DateTime * @@ -7057,24 +7991,26 @@ class DateTime { * @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 datetime_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 datetime_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'. @@ -7085,31 +8021,40 @@ class DateTime { * @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); + normalizedUnit = Duration.normalizeUnit(unit); + switch (normalizedUnit) { case "years": o.month = 1; // falls through + case "quarters": case "months": o.day = 1; // falls through + case "weeks": case "days": o.hour = 0; // falls through + case "hours": o.minute = 0; // falls through + case "minutes": o.second = 0; // falls through + case "seconds": o.millisecond = 0; break; + case "milliseconds": break; // no default, invalid units throw in normalizeUnit() @@ -7118,13 +8063,14 @@ class DateTime { 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'. @@ -7135,13 +8081,13 @@ class DateTime { * @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 + } // OUTPUT /** * Returns a string representation of this DateTime formatted according to the specified format string. @@ -7155,11 +8101,12 @@ class DateTime { * @example DateTime.now().toFormat("HH 'hours and' mm 'minutes'") //=> '20 hours and 55 minutes' * @return {string} */ + + toFormat(fmt) { let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return this.isValid ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) : datetime_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 @@ -7179,12 +8126,13 @@ class DateTime { * @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); //=> '11:32' * @return {string} */ + + toLocaleString() { let formatOpts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DATE_SHORT; let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return this.isValid ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this) : datetime_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 @@ -7198,11 +8146,12 @@ class DateTime { * //=> { type: 'year', value: '1982' } * //=> ] */ + + toLocaleParts() { let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; 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 @@ -7217,28 +8166,31 @@ class DateTime { * @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400' * @return {string} */ + + toISO() { let _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - _ref4$format = _ref4.format, - format = _ref4$format === void 0 ? "extended" : _ref4$format, - _ref4$suppressSeconds = _ref4.suppressSeconds, - suppressSeconds = _ref4$suppressSeconds === void 0 ? false : _ref4$suppressSeconds, - _ref4$suppressMillise = _ref4.suppressMilliseconds, - suppressMilliseconds = _ref4$suppressMillise === void 0 ? false : _ref4$suppressMillise, - _ref4$includeOffset = _ref4.includeOffset, - includeOffset = _ref4$includeOffset === void 0 ? true : _ref4$includeOffset, - _ref4$extendedZone = _ref4.extendedZone, - extendedZone = _ref4$extendedZone === void 0 ? false : _ref4$extendedZone; + _ref4$format = _ref4.format, + format = _ref4$format === void 0 ? "extended" : _ref4$format, + _ref4$suppressSeconds = _ref4.suppressSeconds, + suppressSeconds = _ref4$suppressSeconds === void 0 ? false : _ref4$suppressSeconds, + _ref4$suppressMillise = _ref4.suppressMilliseconds, + suppressMilliseconds = _ref4$suppressMillise === void 0 ? false : _ref4$suppressMillise, + _ref4$includeOffset = _ref4.includeOffset, + includeOffset = _ref4$includeOffset === void 0 ? true : _ref4$includeOffset, + _ref4$extendedZone = _ref4.extendedZone, + extendedZone = _ref4$extendedZone === void 0 ? false : _ref4$extendedZone; + if (!this.isValid) { return null; } + const ext = format === "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 @@ -7247,25 +8199,29 @@ class DateTime { * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525' * @return {string} */ + + toISODate() { let _ref5 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - _ref5$format = _ref5.format, - format = _ref5$format === void 0 ? "extended" : _ref5$format; + _ref5$format = _ref5.format, + format = _ref5$format === void 0 ? "extended" : _ref5$format; + if (!this.isValid) { return null; } + return toISODate(this, format === "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 @@ -7281,37 +8237,41 @@ class DateTime { * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z' * @return {string} */ + + toISOTime() { let _ref6 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - _ref6$suppressMillise = _ref6.suppressMilliseconds, - suppressMilliseconds = _ref6$suppressMillise === void 0 ? false : _ref6$suppressMillise, - _ref6$suppressSeconds = _ref6.suppressSeconds, - suppressSeconds = _ref6$suppressSeconds === void 0 ? false : _ref6$suppressSeconds, - _ref6$includeOffset = _ref6.includeOffset, - includeOffset = _ref6$includeOffset === void 0 ? true : _ref6$includeOffset, - _ref6$includePrefix = _ref6.includePrefix, - includePrefix = _ref6$includePrefix === void 0 ? false : _ref6$includePrefix, - _ref6$extendedZone = _ref6.extendedZone, - extendedZone = _ref6$extendedZone === void 0 ? false : _ref6$extendedZone, - _ref6$format = _ref6.format, - format = _ref6$format === void 0 ? "extended" : _ref6$format; + _ref6$suppressMillise = _ref6.suppressMilliseconds, + suppressMilliseconds = _ref6$suppressMillise === void 0 ? false : _ref6$suppressMillise, + _ref6$suppressSeconds = _ref6.suppressSeconds, + suppressSeconds = _ref6$suppressSeconds === void 0 ? false : _ref6$suppressSeconds, + _ref6$includeOffset = _ref6.includeOffset, + includeOffset = _ref6$includeOffset === void 0 ? true : _ref6$includeOffset, + _ref6$includePrefix = _ref6.includePrefix, + includePrefix = _ref6$includePrefix === void 0 ? false : _ref6$includePrefix, + _ref6$extendedZone = _ref6.extendedZone, + extendedZone = _ref6$extendedZone === void 0 ? false : _ref6$extendedZone, + _ref6$format = _ref6.format, + format = _ref6$format === void 0 ? "extended" : _ref6$format; + if (!this.isValid) { return null; } + let c = includePrefix ? "T" : ""; return c + toISOTime(this, format === "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. @@ -7320,22 +8280,25 @@ class DateTime { * @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 @@ -7348,28 +8311,33 @@ class DateTime { * @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York' * @return {string} */ + + toSQLTime() { let _ref7 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - _ref7$includeOffset = _ref7.includeOffset, - includeOffset = _ref7$includeOffset === void 0 ? true : _ref7$includeOffset, - _ref7$includeZone = _ref7.includeZone, - includeZone = _ref7$includeZone === void 0 ? false : _ref7$includeZone, - _ref7$includeOffsetSp = _ref7.includeOffsetSpace, - includeOffsetSpace = _ref7$includeOffsetSp === void 0 ? true : _ref7$includeOffsetSp; + _ref7$includeOffset = _ref7.includeOffset, + includeOffset = _ref7$includeOffset === void 0 ? true : _ref7$includeOffset, + _ref7$includeZone = _ref7.includeZone, + includeZone = _ref7$includeZone === void 0 ? false : _ref7$includeZone, + _ref7$includeOffsetSp = _ref7.includeOffsetSpace, + includeOffsetSpace = _ref7$includeOffsetSp === void 0 ? true : _ref7$includeOffsetSp; + 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 @@ -7382,70 +8350,80 @@ class DateTime { * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York' * @return {string} */ + + toSQL() { let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + 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() : datetime_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 / 1000 : NaN; } - /** * Returns the epoch seconds (as a whole number) of this DateTime. * @return {number} */ + + toUnixInteger() { return this.isValid ? Math.floor(this.ts / 1000) : 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 @@ -7453,27 +8431,31 @@ class DateTime { * @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 } * @return {Object} */ + + toObject() { let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (!this.isValid) return {}; + const base = datetime_objectSpread({}, 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 + } // COMPARE /** * Return the difference between two DateTimes as a Duration. @@ -7490,24 +8472,28 @@ class DateTime { * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 } * @return {Duration} */ + + diff(otherDateTime) { let unit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "milliseconds"; let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + if (!this.isValid || !otherDateTime.isValid) { return Duration.invalid("created by diffing an invalid DateTime"); } + const durOpts = datetime_objectSpread({ 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); + 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} @@ -7516,21 +8502,23 @@ class DateTime { * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use * @return {Duration} */ + + diffNow() { let unit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "milliseconds"; let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 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`. @@ -7540,6 +8528,8 @@ class DateTime { * @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(); @@ -7548,7 +8538,6 @@ class DateTime { }); 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. @@ -7556,10 +8545,11 @@ class DateTime { * @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. @@ -7578,26 +8568,29 @@ class DateTime { * @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() { let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (!this.isValid) return null; const base = options.base || DateTime.fromObject({}, { - zone: this.zone - }), - padding = options.padding ? this < base ? -options.padding : options.padding : 0; + 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 = undefined; } + return diffRelative(base, this.plus(padding), datetime_objectSpread(datetime_objectSpread({}, 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. @@ -7611,6 +8604,8 @@ class DateTime { * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: "fr" }) //=> "demain" * @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> "2 days ago" */ + + toRelativeCalendar() { let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (!this.isValid) return null; @@ -7622,38 +8617,42 @@ class DateTime { 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() { for (var _len = arguments.length, dateTimes = new Array(_len), _key = 0; _key < _len; _key++) { dateTimes[_key] = arguments[_key]; } + 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() { for (var _len2 = arguments.length, dateTimes = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { dateTimes[_key2] = arguments[_key2]; } + if (!dateTimes.every(DateTime.isDateTime)) { throw new InvalidArgumentError("max requires all arguments be DateTimes"); } - return bestBy(dateTimes, i => i.valueOf(), Math.max); - } - // MISC + return bestBy(dateTimes, i => i.valueOf(), Math.max); + } // MISC /** * Explain how a string would be parsed by fromFormat() @@ -7662,210 +8661,235 @@ class DateTime { * @param {Object} options - options taken by fromFormat() * @return {Object} */ + + static fromFormatExplain(text, fmt) { let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; const _options$locale = options.locale, - locale = _options$locale === void 0 ? null : _options$locale, - _options$numberingSys = options.numberingSystem, - numberingSystem = _options$numberingSys === void 0 ? null : _options$numberingSys, - localeToUse = Locale.fromOpts({ - locale, - numberingSystem, - defaultToEN: true - }); + locale = _options$locale === void 0 ? null : _options$locale, + _options$numberingSys = options.numberingSystem, + numberingSystem = _options$numberingSys === void 0 ? null : _options$numberingSys, + localeToUse = Locale.fromOpts({ + locale, + numberingSystem, + defaultToEN: true + }); return explainFromTokens(localeToUse, text, fmt); } - /** * @deprecated use fromFormatExplain instead */ + + static fromStringExplain(text, fmt) { let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; return DateTime.fromFormatExplain(text, fmt, options); - } - - // FORMAT PRESETS + } // 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; } -} +} /** * @private */ + function friendlyDateTime(dateTimeish) { if (DateTime.isDateTime(dateTimeish)) { return dateTimeish; @@ -13814,55 +14838,6 @@ class WeatherUnderground extends BaseProvider { } } -;// CONCATENATED MODULE: ./src/3_8/location_services/geoip_services/geojs.io.ts - - -class GeoJS { - constructor(_app) { - this.query = "https://get.geojs.io/v1/ip/geo.json"; - this.app = _app; - } - async GetLocation() { - const json = await this.app.LoadJsonAsync(this.query); - if (!json) { - return null; - } - return this.ParseInformation(json); - } - ; - ParseInformation(json) { - try { - const lat = parseFloat(json.latitude); - const lon = parseFloat(json.longitude); - if (Number.isNaN(lat) || Number.isNaN(lon)) { - this.HandleErrorResponse(json); - return null; - } - const result = { - lat: lat, - lon: lon, - city: json.city, - country: json.country, - timeZone: json.timezone, - entryText: lat + "," + lon, - }; - logger_Logger.Debug("Location obtained:" + lat + "," + lon); - return result; - } - catch (e) { - logger_Logger.Error("ip-api parsing error: " + e); - this.app.ShowError({ type: "hard", detail: "no location", service: "ipapi", message: _("Could not obtain location") }); - return null; - } - } - ; - HandleErrorResponse(json) { - this.app.ShowError({ type: "hard", detail: "bad api response", message: _("Location Service responded with errors, please see the logs in Looking Glass"), service: "ipapi" }); - logger_Logger.Error("ip-api responds with Error: " + json.reason); - } - ; -} - ;// CONCATENATED MODULE: ./src/3_8/providers/pirate_weather/pirateWeather.ts @@ -14104,6 +15079,137 @@ class PirateWeather extends BaseProvider { } ; +;// CONCATENATED MODULE: ./src/3_8/location_services/geoip_services/geoclue.ts + +let GeoClueLib = undefined; +let GeocodeGlib = undefined; +class GeoClue { + constructor(_app) { + this.app = _app; + try { + GeoClueLib = imports.gi.Geoclue; + GeocodeGlib = imports.gi.GeocodeGlib; + } + catch (e) { + logger_Logger.Info("GeoClue2 not available, disabling it's use."); + } + } + async GetLocation() { + if (GeoClueLib == null || GeocodeGlib == null) { + return null; + } + const { AccuracyLevel, Simple: GeoClue } = GeoClueLib; + const res = await new Promise((resolve, reject) => { + GeoClue.new_with_thresholds("weather_mockturtl", AccuracyLevel.EXACT, 0, 0, null, (client, res) => { + const simple = GeoClue.new_finish(res); + const clientObj = simple.get_client(); + if (clientObj == null || !clientObj.active) { + logger_Logger.Debug("GeoGlue2 Geolocation disabled, skipping"); + resolve(null); + return; + } + const loc = simple.get_location(); + if (loc == null) { + resolve(null); + return; + } + const result = { + lat: loc.latitude, + lon: loc.longitude, + city: undefined, + country: undefined, + timeZone: "", + entryText: loc.latitude + "," + loc.longitude, + altitude: loc.altitude, + accuracy: loc.accuracy, + }; + resolve(result); + }); + }); + if (res == null) { + return null; + } + const geoCodeRes = await this.GetGeoCodeData(res.lat, res.lon, res.accuracy); + if (geoCodeRes == null) { + return res; + } + return Object.assign(Object.assign({}, res), geoCodeRes); + } + ; + async GetGeoCodeData(lat, lon, accuracy) { + if (GeocodeGlib == null) { + return null; + } + const geoCodeLoc = GeocodeGlib.Location.new(lat, lon, accuracy); + const geoCodeRes = GeocodeGlib.Reverse.new_for_location(geoCodeLoc); + return new Promise((resolve, reject) => { + geoCodeRes.resolve_async(null, (obj, res) => { + const result = geoCodeRes.resolve_finish(res); + if (result == null) { + resolve(null); + return; + } + resolve({ + city: result.town, + country: result.country, + }); + }); + }); + } +} + +;// CONCATENATED MODULE: ./src/3_8/location_services/geoip_services/geoip.fedora.ts + + +class GeoIPFedora { + constructor(app) { + this.query = "https://geoip.fedoraproject.org/city"; + this.app = app; + } + async GetLocation() { + const json = await this.app.LoadJsonAsync(this.query); + if (!json) { + logger_Logger.Info("geoip.fedoraproject didn't return any data"); + return null; + } + return this.ParseInformation(json); + } + ParseInformation(json) { + var _a, _b, _c; + if (json.latitude === null || json.longitude === null) { + this.HandleErrorResponse(json); + return null; + } + try { + const result = { + lat: json.latitude, + lon: json.longitude, + city: (_a = json.city) !== null && _a !== void 0 ? _a : undefined, + country: (_b = json.country_name) !== null && _b !== void 0 ? _b : undefined, + timeZone: (_c = json.time_zone) !== null && _c !== void 0 ? _c : this.app.config.UserTimezone, + entryText: json.latitude + "," + json.longitude, + }; + logger_Logger.Debug("Location obtained: " + json.latitude + "," + json.longitude); + return result; + } + catch (e) { + logger_Logger.Error("geoip.fedoraproject parsing error: " + e); + this.app.ShowError({ type: "hard", detail: "no location", service: "ipapi", message: _("Could not obtain location") }); + return null; + } + } + ; + HandleErrorResponse(json) { + this.app.ShowError({ + type: "hard", + detail: "bad api response", + message: _("Location Service couldn't find your location, please see the logs in Looking Glass"), + service: "geoip.fedoreproject" + }); + } + ; +} + ;// CONCATENATED MODULE: ./src/3_8/config.ts @@ -14126,7 +15232,8 @@ class PirateWeather extends BaseProvider { -const { get_home_dir: config_get_home_dir, get_user_data_dir } = imports.gi.GLib; + +const { get_home_dir: config_get_home_dir, get_user_data_dir, get_user_config_dir } = imports.gi.GLib; const { File: config_File } = imports.gi.Gio; const { AppletSettings, BindingDirection } = imports.ui.settings; const Lang = imports.lang; @@ -14232,7 +15339,8 @@ class Config { this.currentLocale = ConstructJsLocale(get_language_names()[0]); logger_Logger.Debug(`System locale is ${this.currentLocale}, original is ${get_language_names()[0]}`); this.countryCode = this.GetCountryCode(this.currentLocale); - this.autoLocProvider = new GeoJS(app); + this.autoLocProvider = new GeoIPFedora(app); + this.geoClue = new GeoClue(app); this.geoLocationService = new GeoLocation(app); this.InterfaceSettings = new config_Settings({ schema: "org.cinnamon.desktop.interface" }); this.InterfaceSettings.connect('changed::font-name', () => this.OnFontChanged()); @@ -14304,9 +15412,16 @@ class Config { async EnsureLocation() { this.currentLocation = null; if (!this._manualLocation) { + const geoClue = await this.geoClue.GetLocation(); + if (geoClue != null) { + logger_Logger.Debug("Auto location obtained via GeoClue2."); + this.InjectLocationToConfig(geoClue); + return geoClue; + } const location = await this.autoLocProvider.GetLocation(); if (!location) return null; + logger_Logger.Debug("Auto location obtained via IP lookup."); this.InjectLocationToConfig(location); return location; } @@ -14316,13 +15431,13 @@ class Config { type: "hard", detail: "no location", userError: true, - message: _("Make sure you entered a location or use Automatic location instead") + message: _("Make sure you entered a location or use Automatic location instead.") }); return null; } let location = this.LocStore.FindLocation(this._location); if (location != null) { - logger_Logger.Debug("location exist in locationstore, retrieve"); + logger_Logger.Debug("Manual Location exist in Saved Locations, retrieve."); this.LocStore.SwitchToLocation(location); this.InjectLocationToConfig(location, true); return location; @@ -14336,6 +15451,7 @@ class Config { timeZone: DateTime.now().zoneName, entryText: loc, }; + logger_Logger.Debug("Manual Location is a coordinate, using it directly."); this.InjectLocationToConfig(location); return location; } @@ -14344,11 +15460,11 @@ class Config { if (locationData == null) return null; if (!!(locationData === null || locationData === void 0 ? void 0 : locationData.entryText)) { - logger_Logger.Debug("Address found via address search"); + logger_Logger.Debug("Coordinates are found via Reverse address search"); } location = this.LocStore.FindLocation(locationData.entryText); if (location != null) { - logger_Logger.Debug("Found location was found in locationStore, return that instead"); + logger_Logger.Debug("Entered location was found in Saved Location, switch to it instead."); this.InjectLocationToConfig(location); this.LocStore.SwitchToLocation(location); return location; @@ -14446,16 +15562,16 @@ class Config { async GetAppletConfigJson() { var _a, _b, _c, _d, _e; const home = (_a = config_get_home_dir()) !== null && _a !== void 0 ? _a : "~"; - let configFilePath = `${get_user_data_dir()}/cinnamon/spices/weather@mockturtl/${this.app.instance_id}.json`; + let configFilePath = `${get_user_config_dir()}/cinnamon/spices/weather@mockturtl/${this.app.instance_id}.json`; const oldConfigFilePath = `${home}/.cinnamon/configs/weather@mockturtl/${this.app.instance_id}.json`; let configFile = config_File.new_for_path(configFilePath); const oldConfigFile = config_File.new_for_path(oldConfigFilePath); if (!await FileExists(configFile)) { - configFile = oldConfigFile; - configFilePath = oldConfigFilePath; - if (!await FileExists(configFile)) { + if (!await FileExists(oldConfigFile)) { throw new Error(_("Could not retrieve config, file was not found under paths\n {configFilePath}", { configFilePath: `${configFilePath}\n${oldConfigFilePath}` })); } + configFile = oldConfigFile; + configFilePath = oldConfigFilePath; } const confString = await LoadContents(configFile); if (confString == null) { @@ -16188,7 +17304,7 @@ class UI { ;// CONCATENATED MODULE: ./src/3_8/lib/soupLib.ts -const { Message, Session, SessionAsync } = imports.gi.Soup; +const { Message, Session } = imports.gi.Soup; const { PRIORITY_DEFAULT } = imports.gi.GLib; const soupLib_ByteArray = imports.byteArray; function AddParamsToURI(url, params) { @@ -16248,8 +17364,8 @@ class Soup3 { } class Soup2 { constructor() { + const { ProxyResolverDefault, SessionAsync } = imports.gi.Soup; this._httpSession = new SessionAsync(); - const { ProxyResolverDefault } = imports.gi.Soup; this._httpSession.user_agent = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:37.0) Gecko/20100101 Firefox/37.0"; this._httpSession.timeout = 10; this._httpSession.idle_timeout = 10; @@ -16318,7 +17434,7 @@ class HttpLib { } } async LoadAsync(url, params, headers, method = "GET") { - var _a, _b, _c, _d, _e; + var _a, _b, _c, _d, _e, _f; const message = await soupLib.Send(url, params, headers, method); let error = undefined; if (!message) { @@ -16358,10 +17474,10 @@ class HttpLib { } logger_Logger.Verbose("API full response: " + ((_c = message === null || message === void 0 ? void 0 : message.response_body) === null || _c === void 0 ? void 0 : _c.toString())); if (error != null) - logger_Logger.Info("Error calling URL: " + error.reason_phrase + ", " + ((_d = error === null || error === void 0 ? void 0 : error.response) === null || _d === void 0 ? void 0 : _d.response_body)); + logger_Logger.Info(`Error calling URL: ${error.code}, ${error.reason_phrase}, ${(_e = (_d = error === null || error === void 0 ? void 0 : error.response) === null || _d === void 0 ? void 0 : _d.response_body) !== null && _e !== void 0 ? _e : "None"}`); return { Success: (error == null), - Data: ((_e = message === null || message === void 0 ? void 0 : message.response_body) !== null && _e !== void 0 ? _e : null), + Data: ((_f = message === null || message === void 0 ? void 0 : message.response_body) !== null && _f !== void 0 ? _f : null), ResponseHeaders: message === null || message === void 0 ? void 0 : message.response_headers, ErrorData: error, Response: message @@ -16418,6 +17534,8 @@ class WeatherApplet extends TextIconApplet { if (this.online === true) break; logger_Logger.Info("Internet access now available, resuming operations."); + this.encounteredError = false; + this.loop.ResetErrorCount(); this.loop.Resume(); this.online = true; break; diff --git a/weather@mockturtl/files/weather@mockturtl/metadata.json b/weather@mockturtl/files/weather@mockturtl/metadata.json index e899d55dc3d..eebc7fb75b0 100644 --- a/weather@mockturtl/files/weather@mockturtl/metadata.json +++ b/weather@mockturtl/files/weather@mockturtl/metadata.json @@ -3,7 +3,7 @@ "name": "Weather", "description": "View your local weather forecast", "max-instances": 3, - "version": "3.3.1", + "version": "3.4.0", "multiversion": true, "cinnamon-version": ["2.2", "2.4", "2.6", "2.8", "3.0", "3.2", "3.4", "3.6", "3.8", "4.0", "4.2", "4.4", "4.6", "4.8"] } diff --git a/weather@mockturtl/files/weather@mockturtl/po/weather@mockturtl.pot b/weather@mockturtl/files/weather@mockturtl/po/weather@mockturtl.pot index 641520540b6..17c4d789cb1 100644 --- a/weather@mockturtl/files/weather@mockturtl/po/weather@mockturtl.pot +++ b/weather@mockturtl/files/weather@mockturtl/po/weather@mockturtl.pot @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2023-07-21 09:37+0100\n" +"POT-Creation-Date: 2024-01-30 08:55+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -18,48 +18,48 @@ msgstr "" "Content-Transfer-Encoding: 8bit\n" #: 3.0/applet.js:166 3.0/applet.js:426 3.0/applet.js:2131 -#: 3.8/weather-applet.js:17519 +#: 3.8/weather-applet.js:17607 msgid "Error" msgstr "" #: 3.0/applet.js:167 3.0/applet.js:169 3.0/applet.js:171 3.0/applet.js:174 #: 3.0/applet.js:177 3.0/applet.js:178 3.0/applet.js:179 3.0/applet.js:180 -#: 3.8/weather-applet.js:17520 3.8/weather-applet.js:17522 -#: 3.8/weather-applet.js:17524 3.8/weather-applet.js:17527 -#: 3.8/weather-applet.js:17530 3.8/weather-applet.js:17531 -#: 3.8/weather-applet.js:17532 3.8/weather-applet.js:17533 +#: 3.8/weather-applet.js:17608 3.8/weather-applet.js:17610 +#: 3.8/weather-applet.js:17612 3.8/weather-applet.js:17615 +#: 3.8/weather-applet.js:17618 3.8/weather-applet.js:17619 +#: 3.8/weather-applet.js:17620 3.8/weather-applet.js:17621 msgid "Service Error" msgstr "" -#: 3.0/applet.js:168 3.8/weather-applet.js:17521 +#: 3.0/applet.js:168 3.8/weather-applet.js:17609 msgid "Incorrect API Key" msgstr "" -#: 3.0/applet.js:170 3.8/weather-applet.js:17523 +#: 3.0/applet.js:170 3.8/weather-applet.js:17611 msgid "Incorrect Location Format" msgstr "" -#: 3.0/applet.js:172 3.8/weather-applet.js:17525 +#: 3.0/applet.js:172 3.8/weather-applet.js:17613 msgid "Key Blocked" msgstr "" -#: 3.0/applet.js:173 3.8/weather-applet.js:17526 +#: 3.0/applet.js:173 3.8/weather-applet.js:17614 msgid "Can't find location" msgstr "" -#: 3.0/applet.js:175 3.8/weather-applet.js:17528 +#: 3.0/applet.js:175 3.8/weather-applet.js:17616 msgid "No Api Key" msgstr "" -#: 3.0/applet.js:176 3.8/weather-applet.js:17529 +#: 3.0/applet.js:176 3.8/weather-applet.js:17617 msgid "No Location" msgstr "" -#: 3.0/applet.js:181 3.8/weather-applet.js:17534 +#: 3.0/applet.js:181 3.8/weather-applet.js:17622 msgid "Missing Packages" msgstr "" -#: 3.0/applet.js:182 3.8/weather-applet.js:17535 +#: 3.0/applet.js:182 3.8/weather-applet.js:17623 msgid "Location not covered" msgstr "" @@ -67,16 +67,16 @@ msgstr "" msgid "Weather Applet" msgstr "" -#: 3.0/applet.js:217 3.8/weather-applet.js:17833 +#: 3.0/applet.js:217 3.8/weather-applet.js:17921 msgid "..." msgstr "" -#: 3.0/applet.js:218 3.8/weather-applet.js:17834 +#: 3.0/applet.js:218 3.8/weather-applet.js:17922 msgid "Click to open" msgstr "" -#: 3.0/applet.js:232 3.0/applet.js:1244 3.8/weather-applet.js:16129 -#: 3.8/weather-applet.js:17837 +#: 3.0/applet.js:232 3.0/applet.js:1244 3.8/weather-applet.js:16215 +#: 3.8/weather-applet.js:17925 msgid "Refresh" msgstr "" @@ -99,12 +99,12 @@ msgstr "" msgid "Could not get weather information" msgstr "" -#: 3.0/applet.js:624 3.8/weather-applet.js:17672 +#: 3.0/applet.js:624 3.8/weather-applet.js:17760 msgid "" "Unexpected Error While Refreshing Weather, please see log in Looking Glass" msgstr "" -#: 3.0/applet.js:670 3.8/weather-applet.js:17915 +#: 3.0/applet.js:670 3.8/weather-applet.js:18003 msgid "" "Could not update weather for a while...\n" "are you connected to the internet?" @@ -118,7 +118,7 @@ msgstr "" msgid "As of" msgstr "" -#: 3.0/applet.js:1108 3.8/weather-applet.js:16920 +#: 3.0/applet.js:1108 3.8/weather-applet.js:17006 msgid "Powered by" msgstr "" @@ -126,56 +126,56 @@ msgstr "" msgid "from you" msgstr "" -#: 3.0/applet.js:1132 3.8/weather-applet.js:16833 +#: 3.0/applet.js:1132 3.8/weather-applet.js:16919 msgid "mm" msgstr "" -#: 3.0/applet.js:1132 3.0/darkSky.js:71 3.8/weather-applet.js:16833 +#: 3.0/applet.js:1132 3.0/darkSky.js:71 3.8/weather-applet.js:16919 msgid "in" msgstr "" #: 3.0/applet.js:1205 3.0/met_uk.js:421 3.8/weather-applet.js:10312 -#: 3.8/weather-applet.js:16998 +#: 3.8/weather-applet.js:17084 msgid "mi" msgstr "" #: 3.0/applet.js:1206 3.0/met_uk.js:422 3.8/weather-applet.js:10313 -#: 3.8/weather-applet.js:16999 +#: 3.8/weather-applet.js:17085 msgid "km" msgstr "" -#: 3.0/applet.js:1227 3.8/weather-applet.js:17176 +#: 3.0/applet.js:1227 3.8/weather-applet.js:17262 msgid "Loading current weather ..." msgstr "" -#: 3.0/applet.js:1230 3.8/weather-applet.js:17179 +#: 3.0/applet.js:1230 3.8/weather-applet.js:17265 msgid "Loading future weather ..." msgstr "" -#: 3.0/applet.js:1280 3.8/weather-applet.js:16082 +#: 3.0/applet.js:1280 3.8/weather-applet.js:16168 msgid "Loading ..." msgstr "" -#: 3.0/applet.js:1329 3.8/weather-applet.js:16103 +#: 3.0/applet.js:1329 3.8/weather-applet.js:16189 msgid "Temperature" msgstr "" -#: 3.0/applet.js:1330 3.8/weather-applet.js:16104 +#: 3.0/applet.js:1330 3.8/weather-applet.js:16190 msgid "Humidity" msgstr "" -#: 3.0/applet.js:1331 3.8/weather-applet.js:16105 +#: 3.0/applet.js:1331 3.8/weather-applet.js:16191 msgid "Pressure" msgstr "" #: 3.0/applet.js:1332 3.8/weather-applet.js:12249 3.8/weather-applet.js:12256 #: 3.8/weather-applet.js:12257 3.8/weather-applet.js:12263 #: 3.8/weather-applet.js:14217 3.8/weather-applet.js:14218 -#: 3.8/weather-applet.js:15951 +#: 3.8/weather-applet.js:16037 msgid "Wind" msgstr "" -#: 3.0/applet.js:1639 3.8/weather-applet.js:15343 +#: 3.0/applet.js:1639 msgid "Make sure you entered a location or use Automatic location instead" msgstr "" @@ -245,12 +245,12 @@ msgstr "" #: 3.8/weather-applet.js:10740 3.8/weather-applet.js:11711 #: 3.8/weather-applet.js:12150 3.8/weather-applet.js:12659 #: 3.8/weather-applet.js:13021 3.8/weather-applet.js:14388 -#: 3.8/weather-applet.js:14978 +#: 3.8/weather-applet.js:14929 msgid "Feels Like" msgstr "" #: 3.0/climacell.js:174 3.0/darkSky.js:189 3.0/yahoo.js:166 -#: 3.8/weather-applet.js:15040 +#: 3.8/weather-applet.js:14991 msgid "Failed to Process Weather Info" msgstr "" @@ -261,7 +261,7 @@ msgid "" msgstr "" #: 3.0/climacell.js:239 3.0/darkSky.js:229 3.0/weatherbit.js:331 -#: 3.8/weather-applet.js:11877 3.8/weather-applet.js:14920 +#: 3.8/weather-applet.js:11877 3.8/weather-applet.js:14871 msgid "" "Please Make sure you\n" "entered the API key correctly and your account is not locked" @@ -532,17 +532,17 @@ msgid "" "or get one first on https://darksky.net/dev/register" msgstr "" -#: 3.0/darkSky.js:238 3.8/weather-applet.js:14930 +#: 3.0/darkSky.js:238 3.8/weather-applet.js:14881 msgid "" "Please Make sure you\n" "entered the API key that you have from DarkSky" msgstr "" -#: 3.0/ipApi.js:89 3.8/weather-applet.js:14878 +#: 3.0/ipApi.js:89 3.8/weather-applet.js:15197 msgid "Could not obtain location" msgstr "" -#: 3.0/ipApi.js:95 3.8/weather-applet.js:14884 +#: 3.0/ipApi.js:95 msgid "" "Location Service responded with errors, please see the logs in Looking Glass" msgstr "" @@ -1685,71 +1685,81 @@ msgstr "" msgid "Mostly Clear" msgstr "" -#: 3.8/weather-applet.js:14902 +#: 3.8/weather-applet.js:14853 msgid "Pirate Weather" msgstr "" -#: 3.8/weather-applet.js:15481 +#: 3.8/weather-applet.js:15206 +msgid "" +"Location Service couldn't find your location, please see the logs in Looking" +" Glass" +msgstr "" + +#: 3.8/weather-applet.js:15428 +msgid "Make sure you entered a location or use Automatic location instead." +msgstr "" + +#: 3.8/weather-applet.js:15565 msgid "" "Could not retrieve config, file was not found under paths\n" " {configFilePath}" msgstr "" -#: 3.8/weather-applet.js:15486 +#: 3.8/weather-applet.js:15572 msgid "" "Could not get contents of config file under path\n" " {configFilePath}" msgstr "" -#: 3.8/weather-applet.js:16106 +#: 3.8/weather-applet.js:16192 msgid "Dew Point" msgstr "" -#: 3.8/weather-applet.js:16178 +#: 3.8/weather-applet.js:16264 msgid "Precipitation will end in {precipEnd} minutes" msgstr "" -#: 3.8/weather-applet.js:16180 +#: 3.8/weather-applet.js:16266 msgid "Precipitation won't end in within an hour" msgstr "" -#: 3.8/weather-applet.js:16183 +#: 3.8/weather-applet.js:16269 msgid "Precipitation will start within {precipStart} minutes" msgstr "" -#: 3.8/weather-applet.js:16395 +#: 3.8/weather-applet.js:16481 msgid "Forecast parsing failed, see logs for more details." msgstr "" -#: 3.8/weather-applet.js:16927 3.8/weather-applet.js:17714 +#: 3.8/weather-applet.js:17013 3.8/weather-applet.js:17802 msgid "As of {lastUpdatedTime}" msgstr "" -#: 3.8/weather-applet.js:16933 +#: 3.8/weather-applet.js:17019 msgid "{distance} {distanceUnit} from you" msgstr "" -#: 3.8/weather-applet.js:16937 +#: 3.8/weather-applet.js:17023 msgid "Station Name: {stationName}" msgstr "" -#: 3.8/weather-applet.js:16940 +#: 3.8/weather-applet.js:17026 msgid "Area: {stationArea}" msgstr "" -#: 3.8/weather-applet.js:17485 3.8/weather-applet.js:17495 +#: 3.8/weather-applet.js:17573 3.8/weather-applet.js:17583 msgid "Error Saving Debug Information" msgstr "" -#: 3.8/weather-applet.js:17507 +#: 3.8/weather-applet.js:17595 msgid "Debug Information saved successfully" msgstr "" -#: 3.8/weather-applet.js:17507 +#: 3.8/weather-applet.js:17595 msgid "Saved to {filePath}" msgstr "" -#: 3.8/weather-applet.js:17638 +#: 3.8/weather-applet.js:17726 msgid "This provider requires an API key to operate" msgstr "" @@ -2261,6 +2271,12 @@ msgid "" "entered is replaced automatically for validating your choice." msgstr "" +#. 3.8->settings-schema.json->locationDescription->description +msgid "" +"If the location field matches a saved location's 'Search Entry' field, the " +"saved location will be used instead." +msgstr "" + #. 3.8->settings-schema.json->saveLocation->description msgid "Save current location to storage" msgstr "" diff --git a/weather@mockturtl/package.json b/weather@mockturtl/package.json index 66eea30e486..9f930a2f556 100644 --- a/weather@mockturtl/package.json +++ b/weather@mockturtl/package.json @@ -15,16 +15,17 @@ "suncalc": "1.9.0" }, "devDependencies": { - "babel-loader": "8.2.2", - "@babel/preset-env": "7.16.4", "@babel/core": "7.16.0", + "@babel/preset-env": "7.16.4", + "@ci-types/cjs": "^6.0.2-5", "@types/luxon": "3.2.0", "@types/suncalc": "1.9.0", + "babel-loader": "8.2.2", + "terser-webpack-plugin": "5.3.6", "ts-loader": "9.4.2", "typescript": "5.0.2", "webpack": "5.75.0", "webpack-bundle-analyzer": "4.4.2", - "webpack-cli": "4.7.2", - "terser-webpack-plugin": "5.3.6" + "webpack-cli": "4.7.2" } } diff --git a/weather@mockturtl/src/3_8/config.ts b/weather@mockturtl/src/3_8/config.ts index 656e990d392..29b4fb6a52a 100644 --- a/weather@mockturtl/src/3_8/config.ts +++ b/weather@mockturtl/src/3_8/config.ts @@ -21,10 +21,11 @@ import { DeutscherWetterdienst } from "./providers/deutscherWetterdienst"; import { WeatherUnderground } from "./providers/weatherUnderground"; import { Event } from "./lib/events"; import { GeoIP } from "./location_services/geoip_services/base"; -import { GeoJS } from "./location_services/geoip_services/geojs.io"; import { PirateWeather } from "./providers/pirate_weather/pirateWeather"; +import { GeoClue } from "./location_services/geoip_services/geoclue"; +import { GeoIPFedora } from "./location_services/geoip_services/geoip.fedora"; -const { get_home_dir, get_user_data_dir } = imports.gi.GLib; +const { get_home_dir, get_user_data_dir, get_user_config_dir } = imports.gi.GLib; const { File } = imports.gi.Gio; const { AppletSettings, BindingDirection } = imports.ui.settings; const Lang: typeof imports.lang = imports.lang; @@ -190,6 +191,7 @@ export class Config { } private readonly autoLocProvider: GeoIP; + private readonly geoClue: GeoClue; private readonly geoLocationService: GeoLocation; /** Stores and retrieves manual locations */ @@ -208,7 +210,8 @@ export class Config { this.currentLocale = ConstructJsLocale(get_language_names()[0]); Logger.Debug(`System locale is ${this.currentLocale}, original is ${get_language_names()[0]}`); this.countryCode = this.GetCountryCode(this.currentLocale); - this.autoLocProvider = new GeoJS(app); // IP location lookup + this.autoLocProvider = new GeoIPFedora(app); // IP location lookup + this.geoClue = new GeoClue(app); this.geoLocationService = new GeoLocation(app); this.InterfaceSettings = new Settings({ schema: "org.cinnamon.desktop.interface" }); this.InterfaceSettings.connect('changed::font-name', () => this.OnFontChanged()); @@ -312,10 +315,19 @@ export class Config { // Automatic location if (!this._manualLocation) { + const geoClue = await this.geoClue.GetLocation(); + if (geoClue != null) { + Logger.Debug("Auto location obtained via GeoClue2."); + this.InjectLocationToConfig(geoClue); + return geoClue; + } + const location = await this.autoLocProvider.GetLocation(); // User facing errors handled by provider - if (!location) return null; + if (!location) + return null; + Logger.Debug("Auto location obtained via IP lookup."); this.InjectLocationToConfig(location); return location; } @@ -328,7 +340,7 @@ export class Config { type: "hard", detail: "no location", userError: true, - message: _("Make sure you entered a location or use Automatic location instead") + message: _("Make sure you entered a location or use Automatic location instead.") }); return null; } @@ -336,7 +348,7 @@ export class Config { // Find location in storage let location = this.LocStore.FindLocation(this._location); if (location != null) { - Logger.Debug("location exist in locationstore, retrieve"); + Logger.Debug("Manual Location exist in Saved Locations, retrieve."); this.LocStore.SwitchToLocation(location); this.InjectLocationToConfig(location, true); return location; @@ -352,6 +364,7 @@ export class Config { timeZone: DateTime.now().zoneName, entryText: loc, } + Logger.Debug("Manual Location is a coordinate, using it directly."); this.InjectLocationToConfig(location); return location; } @@ -361,13 +374,13 @@ export class Config { // User facing errors are handled by service if (locationData == null) return null; if (!!locationData?.entryText) { - Logger.Debug("Address found via address search"); + Logger.Debug("Coordinates are found via Reverse address search"); } // Maybe location is in locationStore, first search location = this.LocStore.FindLocation(locationData.entryText); if (location != null) { - Logger.Debug("Found location was found in locationStore, return that instead"); + Logger.Debug("Entered location was found in Saved Location, switch to it instead."); this.InjectLocationToConfig(location); this.LocStore.SwitchToLocation(location); return location; @@ -531,20 +544,21 @@ export class Config { public async GetAppletConfigJson(): Promise> { const home = get_home_dir() ?? "~"; - let configFilePath = `${get_user_data_dir()}/cinnamon/spices/weather@mockturtl/${this.app.instance_id}.json`; + let configFilePath = `${get_user_config_dir()}/cinnamon/spices/weather@mockturtl/${this.app.instance_id}.json`; const oldConfigFilePath = `${home}/.cinnamon/configs/weather@mockturtl/${this.app.instance_id}.json`; let configFile = File.new_for_path(configFilePath); const oldConfigFile = File.new_for_path(oldConfigFilePath); // Check if file exists if (!await FileExists(configFile)) { - configFile = oldConfigFile; - configFilePath = oldConfigFilePath; - if (!await FileExists(configFile)) { + if (!await FileExists(oldConfigFile)) { throw new Error( _("Could not retrieve config, file was not found under paths\n {configFilePath}", { configFilePath: `${configFilePath}\n${oldConfigFilePath}` }) ); } + + configFile = oldConfigFile; + configFilePath = oldConfigFilePath; } // Load file contents diff --git a/weather@mockturtl/src/3_8/lib/httpLib.ts b/weather@mockturtl/src/3_8/lib/httpLib.ts index d9c41ab3b99..264f0abfb9a 100644 --- a/weather@mockturtl/src/3_8/lib/httpLib.ts +++ b/weather@mockturtl/src/3_8/lib/httpLib.ts @@ -89,7 +89,7 @@ export class HttpLib { Logger.Verbose("API full response: " + message?.response_body?.toString()); if (error != null) - Logger.Info("Error calling URL: " + error.reason_phrase + ", " + error?.response?.response_body); + Logger.Info(`Error calling URL: ${error.code}, ${error.reason_phrase}, ${error?.response?.response_body ?? "None"}`); return { Success: (error == null), Data: (message?.response_body ?? null), diff --git a/weather@mockturtl/src/3_8/lib/soupLib.ts b/weather@mockturtl/src/3_8/lib/soupLib.ts index 93f209d8cdf..04f9f5b8fce 100644 --- a/weather@mockturtl/src/3_8/lib/soupLib.ts +++ b/weather@mockturtl/src/3_8/lib/soupLib.ts @@ -1,6 +1,6 @@ import { HTTPHeaders, HTTPParams, Method } from "./httpLib"; import { Logger } from "./logger"; -const { Message, Session, SessionAsync } = imports.gi.Soup; +const { Message, Session } = imports.gi.Soup; const { PRIORITY_DEFAULT } = imports.gi.GLib; const ByteArray = imports.byteArray; @@ -59,16 +59,16 @@ class Soup3 implements SoupLib { } else { AddHeadersToMessage(message, headers); - (this._httpSession as any).send_and_read_async(message, PRIORITY_DEFAULT, null, (session: any, result: any) => { - const res: imports.gi.GLib.Bytes | null = (this._httpSession as any).send_and_read_finish(result); + this._httpSession.send_and_read_async(message, PRIORITY_DEFAULT, null, (session: any, result: any) => { + const res: imports.gi.GLib.Bytes | null = this._httpSession.send_and_read_finish(result); const headers: Record = {}; - (message as any).get_response_headers().foreach((name: string, value: string) => { + message.get_response_headers().foreach((name: string, value: string) => { headers[name] = value; }) resolve({ - reason_phrase: (message as any).get_reason_phrase() ?? "", - status_code: (message as any).get_status(), + reason_phrase: message.get_reason_phrase() ?? "", + status_code: message.get_status(), response_body: res != null ? ByteArray.toString(ByteArray.fromGBytes(res)) : null, response_headers: headers }); @@ -83,10 +83,11 @@ class Soup3 implements SoupLib { class Soup2 implements SoupLib { /** Soup session (see https://bugzilla.gnome.org/show_bug.cgi?id=661323#c64) */ - private readonly _httpSession = new SessionAsync(); + private readonly _httpSession: any; constructor() { - const {ProxyResolverDefault} = imports.gi.Soup; + const { ProxyResolverDefault, SessionAsync } = (imports.gi.Soup as any); + this._httpSession = new SessionAsync(); this._httpSession.user_agent = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:37.0) Gecko/20100101 Firefox/37.0"; // ipapi blocks non-browsers agents, imitating browser this._httpSession.timeout = 10; this._httpSession.idle_timeout = 10; @@ -112,9 +113,9 @@ class Soup2 implements SoupLib { } else { AddHeadersToMessage(message, headers); - this._httpSession.queue_message(message, (session, message) => { + this._httpSession.queue_message(message, (session: any, message: any) => { const headers: Record = {}; - message.response_headers.foreach((name, value) => { + message.response_headers.foreach((name: any, value: any) => { headers[name] = value; }) diff --git a/weather@mockturtl/src/3_8/location_services/geoip_services/geoclue.ts b/weather@mockturtl/src/3_8/location_services/geoip_services/geoclue.ts new file mode 100644 index 00000000000..4154cc98f9c --- /dev/null +++ b/weather@mockturtl/src/3_8/location_services/geoip_services/geoclue.ts @@ -0,0 +1,108 @@ +import { Logger } from "../../lib/logger"; +import { WeatherApplet } from "../../main"; +import { LocationData } from "../../types"; +import { _ } from "../../utils"; +import { GeoIP } from "./base"; + +let GeoClueLib: typeof imports.gi.Geoclue | undefined = undefined; +let GeocodeGlib: typeof imports.gi.GeocodeGlib | undefined = undefined; + +interface ExtendedLocationData extends LocationData { + accuracy: imports.gi.Geoclue.AccuracyLevel; + altitude: number; +} + +export class GeoClue implements GeoIP { + private app: WeatherApplet; + + constructor(_app: WeatherApplet) { + this.app = _app; + try { + GeoClueLib = imports.gi.Geoclue; + GeocodeGlib = imports.gi.GeocodeGlib; + } + catch (e) { + Logger.Info("GeoClue2 not available, disabling it's use."); + } + } + + public async GetLocation(): Promise { + if (GeoClueLib == null || GeocodeGlib == null) { + return null; + } + + const { AccuracyLevel, Simple: GeoClue } = GeoClueLib; + const res = await new Promise((resolve, reject) => { + GeoClue.new_with_thresholds("weather_mockturtl", AccuracyLevel.EXACT, 0, 0, null, (client, res) => { + const simple = GeoClue.new_finish(res); + const clientObj = simple.get_client(); + if (clientObj == null || !clientObj.active) { + Logger.Debug("GeoGlue2 Geolocation disabled, skipping"); + resolve(null); + return; + } + + const loc = simple.get_location(); + if (loc == null) { + resolve(null); + return; + } + + const result: ExtendedLocationData = { + lat: loc.latitude, + lon: loc.longitude, + city: undefined, + country: undefined, + timeZone: "", + entryText: loc.latitude + "," + loc.longitude, + altitude: loc.altitude, + accuracy: loc.accuracy, + } + + resolve(result); + }) + }); + + if (res == null) { + return null; + } + + const geoCodeRes = await this.GetGeoCodeData(res.lat, res.lon, res.accuracy); + if (geoCodeRes == null) { + return res; + } + + return { + ...res, + ...geoCodeRes, + }; + }; + + private async GetGeoCodeData(lat: number, lon: number, accuracy: imports.gi.Geoclue.AccuracyLevel): Promise | null> { + if (GeocodeGlib == null) { + return null; + } + + const geoCodeLoc = GeocodeGlib.Location.new( + lat, + lon, + accuracy + ) + + const geoCodeRes = GeocodeGlib.Reverse.new_for_location(geoCodeLoc); + return new Promise | null>((resolve, reject) => { + geoCodeRes.resolve_async(null, (obj, res) => { + const result = geoCodeRes.resolve_finish(res); + if (result == null) { + resolve(null); + return; + } + + resolve({ + city: result.town, + country: result.country, + }) + }); + }) + } +} \ No newline at end of file diff --git a/weather@mockturtl/src/3_8/location_services/geoip_services/geoip.fedora.ts b/weather@mockturtl/src/3_8/location_services/geoip_services/geoip.fedora.ts new file mode 100644 index 00000000000..dc689f1093a --- /dev/null +++ b/weather@mockturtl/src/3_8/location_services/geoip_services/geoip.fedora.ts @@ -0,0 +1,83 @@ +import { Logger } from "../../lib/logger"; +import { WeatherApplet } from "../../main"; +import { LocationData } from "../../types"; +import { _ } from "../../utils"; +import { GeoIP } from "./base"; + + +/** + * https://docs.fedoraproject.org/en-US/infra/sysadmin_guide/geoip-city-wsgi/ + */ +export class GeoIPFedora implements GeoIP { + private readonly query = "https://geoip.fedoraproject.org/city"; + + private app: WeatherApplet; + + constructor(app: WeatherApplet) { + this.app = app; + } + + public async GetLocation(): Promise { + const json = await this.app.LoadJsonAsync(this.query); + + if (!json) { + Logger.Info("geoip.fedoraproject didn't return any data"); + return null; + } + + return this.ParseInformation(json); + } + + private ParseInformation(json: GeoIPFedoraPayload): LocationData | null { + if (json.latitude === null || json.longitude === null) { + this.HandleErrorResponse(json); + return null; + } + + try { + const result: LocationData = { + lat: json.latitude, + lon: json.longitude, + city: json.city ?? undefined, + country: json.country_name ?? undefined, + timeZone: json.time_zone ?? this.app.config.UserTimezone, + entryText: json.latitude + "," + json.longitude, + } + Logger.Debug("Location obtained: " + json.latitude + "," + json.longitude); + return result; + } + catch (e) { + Logger.Error("geoip.fedoraproject parsing error: " + e); + this.app.ShowError({ type: "hard", detail: "no location", service: "ipapi", message: _("Could not obtain location") }); + return null; + } + }; + + private HandleErrorResponse(json: any): void { + this.app.ShowError({ + type: "hard", + detail: "bad api response", + message: _("Location Service couldn't find your location, please see the logs in Looking Glass"), + service: "geoip.fedoreproject" + }) + }; +} + +/** + * Literally everything can be null here + */ +interface GeoIPFedoraPayload { + ip: string; + city: string | null; + region: string | null; + region_name: string | null; + time_zone: string | null; + latitude: number | null; + longitude: number | null; + metro_code: number | null; + country_code: string | null; + country_name: string | null; + country_code3: string | null; + postal_code: string | null; + dma_code: number | null; +} \ No newline at end of file diff --git a/weather@mockturtl/src/3_8/main.ts b/weather@mockturtl/src/3_8/main.ts index f360ede4e81..fab692c030e 100644 --- a/weather@mockturtl/src/3_8/main.ts +++ b/weather@mockturtl/src/3_8/main.ts @@ -161,7 +161,10 @@ export class WeatherApplet extends TextIconApplet { case NetworkConnectivity.PORTAL: if (this.online === true) break; + Logger.Info("Internet access now available, resuming operations."); + this.encounteredError = false; + this.loop.ResetErrorCount(); this.loop.Resume(); this.online = true; break; diff --git a/weather@mockturtl/src/3_8/tsconfig.json b/weather@mockturtl/src/3_8/tsconfig.json index 020034e0850..efdaebdbae0 100644 --- a/weather@mockturtl/src/3_8/tsconfig.json +++ b/weather@mockturtl/src/3_8/tsconfig.json @@ -13,9 +13,11 @@ "noImplicitReturns": true, "noImplicitAny": true, "experimentalDecorators": true, + "types": [ + "@ci-types/cjs" + ] }, "include": [ "./**/*", - "../../../.typescript-declarations/**/*", ], } \ No newline at end of file diff --git a/weather@mockturtl/src/3_8/types.ts b/weather@mockturtl/src/3_8/types.ts index e84a56bdec9..0c24146559e 100644 --- a/weather@mockturtl/src/3_8/types.ts +++ b/weather@mockturtl/src/3_8/types.ts @@ -159,7 +159,7 @@ export interface AppletError { * soft will show a subtle hint that the refresh failed (NOT IMPLEMENTED) */ export type ErrorSeverity = "hard" | "soft" | "silent"; -export type ApiService = "ipapi" | "openweathermap" | "met-norway" | "weatherbit" | "yahoo" | "climacell" | "met-uk" | "us-weather" | "pirate_weather"; +export type ApiService = "ipapi" | "openweathermap" | "met-norway" | "weatherbit" | "yahoo" | "climacell" | "met-uk" | "us-weather" | "pirate_weather" | "geoip.fedoreproject"; export type ErrorDetail = "no key" | "bad key" | "no location" | "bad location format" | "location not found" | "no network response" | "no api response" | "location not covered" | "bad api response - non json" | "bad api response" | "no response body" |