Created
April 2, 2023 09:41
-
-
Save Mara-Li/dac37c8d842111d64fb7396b317b1783 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD | |
if you want to view the source, please visit the github repository of this plugin | |
*/ | |
var __create = Object.create; | |
var __defProp = Object.defineProperty; | |
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | |
var __getOwnPropNames = Object.getOwnPropertyNames; | |
var __getProtoOf = Object.getPrototypeOf; | |
var __hasOwnProp = Object.prototype.hasOwnProperty; | |
var __commonJS = (cb, mod) => function __require() { | |
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; | |
}; | |
var __export = (target, all) => { | |
for (var name in all) | |
__defProp(target, name, { get: all[name], enumerable: true }); | |
}; | |
var __copyProps = (to, from, except, desc) => { | |
if (from && typeof from === "object" || typeof from === "function") { | |
for (let key of __getOwnPropNames(from)) | |
if (!__hasOwnProp.call(to, key) && key !== except) | |
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | |
} | |
return to; | |
}; | |
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( | |
// If the importer is in node compatibility mode or this is not an ESM | |
// file that has been converted to a CommonJS file using a Babel- | |
// compatible transform (i.e. "__esModule" has not been set), then set | |
// "default" to the CommonJS "module.exports" for node compatibility. | |
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, | |
mod | |
)); | |
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | |
var __async = (__this, __arguments, generator) => { | |
return new Promise((resolve, reject) => { | |
var fulfilled = (value) => { | |
try { | |
step(generator.next(value)); | |
} catch (e) { | |
reject(e); | |
} | |
}; | |
var rejected = (value) => { | |
try { | |
step(generator.throw(value)); | |
} catch (e) { | |
reject(e); | |
} | |
}; | |
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); | |
step((generator = generator.apply(__this, __arguments)).next()); | |
}); | |
}; | |
// node_modules/obsidian-dataview/lib/index.js | |
var require_lib = __commonJS({ | |
"node_modules/obsidian-dataview/lib/index.js"(exports) { | |
"use strict"; | |
Object.defineProperty(exports, "__esModule", { value: true }); | |
require("obsidian"); | |
var LuxonError = class extends Error { | |
}; | |
var InvalidDateTimeError = class extends LuxonError { | |
constructor(reason) { | |
super(`Invalid DateTime: ${reason.toMessage()}`); | |
} | |
}; | |
var InvalidIntervalError = class extends LuxonError { | |
constructor(reason) { | |
super(`Invalid Interval: ${reason.toMessage()}`); | |
} | |
}; | |
var InvalidDurationError = class extends LuxonError { | |
constructor(reason) { | |
super(`Invalid Duration: ${reason.toMessage()}`); | |
} | |
}; | |
var ConflictingSpecificationError = class extends LuxonError { | |
}; | |
var InvalidUnitError = class extends LuxonError { | |
constructor(unit) { | |
super(`Invalid unit ${unit}`); | |
} | |
}; | |
var InvalidArgumentError = class extends LuxonError { | |
}; | |
var ZoneIsAbstractError = class extends LuxonError { | |
constructor() { | |
super("Zone is an abstract class"); | |
} | |
}; | |
var n = "numeric"; | |
var s = "short"; | |
var l = "long"; | |
var DATE_SHORT = { | |
year: n, | |
month: n, | |
day: n | |
}; | |
var DATE_MED = { | |
year: n, | |
month: s, | |
day: n | |
}; | |
var DATE_MED_WITH_WEEKDAY = { | |
year: n, | |
month: s, | |
day: n, | |
weekday: s | |
}; | |
var DATE_FULL = { | |
year: n, | |
month: l, | |
day: n | |
}; | |
var DATE_HUGE = { | |
year: n, | |
month: l, | |
day: n, | |
weekday: l | |
}; | |
var TIME_SIMPLE = { | |
hour: n, | |
minute: n | |
}; | |
var TIME_WITH_SECONDS = { | |
hour: n, | |
minute: n, | |
second: n | |
}; | |
var TIME_WITH_SHORT_OFFSET = { | |
hour: n, | |
minute: n, | |
second: n, | |
timeZoneName: s | |
}; | |
var TIME_WITH_LONG_OFFSET = { | |
hour: n, | |
minute: n, | |
second: n, | |
timeZoneName: l | |
}; | |
var TIME_24_SIMPLE = { | |
hour: n, | |
minute: n, | |
hourCycle: "h23" | |
}; | |
var TIME_24_WITH_SECONDS = { | |
hour: n, | |
minute: n, | |
second: n, | |
hourCycle: "h23" | |
}; | |
var TIME_24_WITH_SHORT_OFFSET = { | |
hour: n, | |
minute: n, | |
second: n, | |
hourCycle: "h23", | |
timeZoneName: s | |
}; | |
var TIME_24_WITH_LONG_OFFSET = { | |
hour: n, | |
minute: n, | |
second: n, | |
hourCycle: "h23", | |
timeZoneName: l | |
}; | |
var DATETIME_SHORT = { | |
year: n, | |
month: n, | |
day: n, | |
hour: n, | |
minute: n | |
}; | |
var DATETIME_SHORT_WITH_SECONDS = { | |
year: n, | |
month: n, | |
day: n, | |
hour: n, | |
minute: n, | |
second: n | |
}; | |
var DATETIME_MED = { | |
year: n, | |
month: s, | |
day: n, | |
hour: n, | |
minute: n | |
}; | |
var DATETIME_MED_WITH_SECONDS = { | |
year: n, | |
month: s, | |
day: n, | |
hour: n, | |
minute: n, | |
second: n | |
}; | |
var DATETIME_MED_WITH_WEEKDAY = { | |
year: n, | |
month: s, | |
day: n, | |
weekday: s, | |
hour: n, | |
minute: n | |
}; | |
var DATETIME_FULL = { | |
year: n, | |
month: l, | |
day: n, | |
hour: n, | |
minute: n, | |
timeZoneName: s | |
}; | |
var DATETIME_FULL_WITH_SECONDS = { | |
year: n, | |
month: l, | |
day: n, | |
hour: n, | |
minute: n, | |
second: n, | |
timeZoneName: s | |
}; | |
var DATETIME_HUGE = { | |
year: n, | |
month: l, | |
day: n, | |
weekday: l, | |
hour: n, | |
minute: n, | |
timeZoneName: l | |
}; | |
var DATETIME_HUGE_WITH_SECONDS = { | |
year: n, | |
month: l, | |
day: n, | |
weekday: l, | |
hour: n, | |
minute: n, | |
second: n, | |
timeZoneName: l | |
}; | |
var Zone = class { | |
/** | |
* The type of zone | |
* @abstract | |
* @type {string} | |
*/ | |
get type() { | |
throw new ZoneIsAbstractError(); | |
} | |
/** | |
* The name of this zone. | |
* @abstract | |
* @type {string} | |
*/ | |
get name() { | |
throw new ZoneIsAbstractError(); | |
} | |
get ianaName() { | |
return this.name; | |
} | |
/** | |
* Returns whether the offset is known to be fixed for the whole year. | |
* @abstract | |
* @type {boolean} | |
*/ | |
get isUniversal() { | |
throw new ZoneIsAbstractError(); | |
} | |
/** | |
* Returns the offset's common name (such as EST) at the specified timestamp | |
* @abstract | |
* @param {number} ts - Epoch milliseconds for which to get the name | |
* @param {Object} opts - Options to affect the format | |
* @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'. | |
* @param {string} opts.locale - What locale to return the offset name in. | |
* @return {string} | |
*/ | |
offsetName(ts, opts) { | |
throw new ZoneIsAbstractError(); | |
} | |
/** | |
* Returns the offset's value as a string | |
* @abstract | |
* @param {number} ts - Epoch milliseconds for which to get the offset | |
* @param {string} format - What style of offset to return. | |
* Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively | |
* @return {string} | |
*/ | |
formatOffset(ts, 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(); | |
} | |
}; | |
var singleton$1 = null; | |
var SystemZone = class extends Zone { | |
/** | |
* Get a singleton instance of the local zone | |
* @return {SystemZone} | |
*/ | |
static get instance() { | |
if (singleton$1 === null) { | |
singleton$1 = new SystemZone(); | |
} | |
return singleton$1; | |
} | |
/** @override **/ | |
get type() { | |
return "system"; | |
} | |
/** @override **/ | |
get name() { | |
return new Intl.DateTimeFormat().resolvedOptions().timeZone; | |
} | |
/** @override **/ | |
get isUniversal() { | |
return false; | |
} | |
/** @override **/ | |
offsetName(ts, { format, 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; | |
} | |
}; | |
var dtfCache = {}; | |
function makeDTF(zone) { | |
if (!dtfCache[zone]) { | |
dtfCache[zone] = new Intl.DateTimeFormat("en-US", { | |
hour12: false, | |
timeZone: zone, | |
year: "numeric", | |
month: "2-digit", | |
day: "2-digit", | |
hour: "2-digit", | |
minute: "2-digit", | |
second: "2-digit", | |
era: "short" | |
}); | |
} | |
return dtfCache[zone]; | |
} | |
var typeToPos = { | |
year: 0, | |
month: 1, | |
day: 2, | |
era: 3, | |
hour: 4, | |
minute: 5, | |
second: 6 | |
}; | |
function hackyOffset(dtf, date) { | |
const formatted = dtf.format(date).replace(/\u200E/g, ""), parsed = /(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(formatted), [, fMonth, fDay, fYear, fadOrBc, fHour, fMinute, fSecond] = parsed; | |
return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond]; | |
} | |
function partsOffset(dtf, date) { | |
const formatted = dtf.formatToParts(date); | |
const filled = []; | |
for (let i = 0; i < formatted.length; i++) { | |
const { type, value } = formatted[i]; | |
const pos = typeToPos[type]; | |
if (type === "era") { | |
filled[pos] = value; | |
} else if (!isUndefined(pos)) { | |
filled[pos] = parseInt(value, 10); | |
} | |
} | |
return filled; | |
} | |
var ianaZoneCache = {}; | |
var IANAZone = class extends Zone { | |
/** | |
* @param {string} name - Zone name | |
* @return {IANAZone} | |
*/ | |
static create(name) { | |
if (!ianaZoneCache[name]) { | |
ianaZoneCache[name] = new IANAZone(name); | |
} | |
return ianaZoneCache[name]; | |
} | |
/** | |
* Reset local caches. Should only be necessary in testing scenarios. | |
* @return {void} | |
*/ | |
static resetCache() { | |
ianaZoneCache = {}; | |
dtfCache = {}; | |
} | |
/** | |
* Returns whether the provided string is a valid specifier. This only checks the string's format, not that the specifier identifies a known zone; see isValidZone for that. | |
* @param {string} s - The string to check validity on | |
* @example IANAZone.isValidSpecifier("America/New_York") //=> true | |
* @example IANAZone.isValidSpecifier("Sport~~blorp") //=> false | |
* @deprecated This method returns false for some valid IANA names. Use isValidZone instead. | |
* @return {boolean} | |
*/ | |
static isValidSpecifier(s2) { | |
return this.isValidZone(s2); | |
} | |
/** | |
* Returns whether the provided string identifies a real zone | |
* @param {string} zone - The string to check | |
* @example IANAZone.isValidZone("America/New_York") //=> true | |
* @example IANAZone.isValidZone("Fantasia/Castle") //=> false | |
* @example IANAZone.isValidZone("Sport~~blorp") //=> false | |
* @return {boolean} | |
*/ | |
static isValidZone(zone) { | |
if (!zone) { | |
return false; | |
} | |
try { | |
new Intl.DateTimeFormat("en-US", { timeZone: zone }).format(); | |
return true; | |
} catch (e) { | |
return false; | |
} | |
} | |
constructor(name) { | |
super(); | |
this.zoneName = name; | |
this.valid = IANAZone.isValidZone(name); | |
} | |
/** @override **/ | |
get type() { | |
return "iana"; | |
} | |
/** @override **/ | |
get name() { | |
return this.zoneName; | |
} | |
/** @override **/ | |
get isUniversal() { | |
return false; | |
} | |
/** @override **/ | |
offsetName(ts, { format, 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 [year, month, day, adOrBc, hour, minute, second] = dtf.formatToParts ? partsOffset(dtf, date) : hackyOffset(dtf, date); | |
if (adOrBc === "BC") { | |
year = -Math.abs(year) + 1; | |
} | |
const adjustedHour = hour === 24 ? 0 : hour; | |
const asUTC = objToLocalTS({ | |
year, | |
month, | |
day, | |
hour: adjustedHour, | |
minute, | |
second, | |
millisecond: 0 | |
}); | |
let asTS = +date; | |
const over = asTS % 1e3; | |
asTS -= over >= 0 ? over : 1e3 + over; | |
return (asUTC - asTS) / (60 * 1e3); | |
} | |
/** @override **/ | |
equals(otherZone) { | |
return otherZone.type === "iana" && otherZone.name === this.name; | |
} | |
/** @override **/ | |
get isValid() { | |
return this.valid; | |
} | |
}; | |
var intlLFCache = {}; | |
function getCachedLF(locString, opts = {}) { | |
const key = JSON.stringify([locString, opts]); | |
let dtf = intlLFCache[key]; | |
if (!dtf) { | |
dtf = new Intl.ListFormat(locString, opts); | |
intlLFCache[key] = dtf; | |
} | |
return dtf; | |
} | |
var intlDTCache = {}; | |
function getCachedDTF(locString, opts = {}) { | |
const key = JSON.stringify([locString, opts]); | |
let dtf = intlDTCache[key]; | |
if (!dtf) { | |
dtf = new Intl.DateTimeFormat(locString, opts); | |
intlDTCache[key] = dtf; | |
} | |
return dtf; | |
} | |
var intlNumCache = {}; | |
function getCachedINF(locString, opts = {}) { | |
const key = JSON.stringify([locString, opts]); | |
let inf = intlNumCache[key]; | |
if (!inf) { | |
inf = new Intl.NumberFormat(locString, opts); | |
intlNumCache[key] = inf; | |
} | |
return inf; | |
} | |
var intlRelCache = {}; | |
function getCachedRTF(locString, opts = {}) { | |
const { base, ...cacheKeyOpts } = opts; | |
const key = JSON.stringify([locString, cacheKeyOpts]); | |
let inf = intlRelCache[key]; | |
if (!inf) { | |
inf = new Intl.RelativeTimeFormat(locString, opts); | |
intlRelCache[key] = inf; | |
} | |
return inf; | |
} | |
var sysLocaleCache = null; | |
function systemLocale() { | |
if (sysLocaleCache) { | |
return sysLocaleCache; | |
} else { | |
sysLocaleCache = new Intl.DateTimeFormat().resolvedOptions().locale; | |
return sysLocaleCache; | |
} | |
} | |
function parseLocaleString(localeStr) { | |
const xIndex = localeStr.indexOf("-x-"); | |
if (xIndex !== -1) { | |
localeStr = localeStr.substring(0, xIndex); | |
} | |
const uIndex = localeStr.indexOf("-u-"); | |
if (uIndex === -1) { | |
return [localeStr]; | |
} else { | |
let options; | |
let selectedStr; | |
try { | |
options = getCachedDTF(localeStr).resolvedOptions(); | |
selectedStr = localeStr; | |
} catch (e) { | |
const smaller = localeStr.substring(0, uIndex); | |
options = getCachedDTF(smaller).resolvedOptions(); | |
selectedStr = smaller; | |
} | |
const { numberingSystem, calendar } = options; | |
return [selectedStr, numberingSystem, calendar]; | |
} | |
} | |
function intlConfigString(localeStr, numberingSystem, outputCalendar) { | |
if (outputCalendar || numberingSystem) { | |
if (!localeStr.includes("-u-")) { | |
localeStr += "-u"; | |
} | |
if (outputCalendar) { | |
localeStr += `-ca-${outputCalendar}`; | |
} | |
if (numberingSystem) { | |
localeStr += `-nu-${numberingSystem}`; | |
} | |
return localeStr; | |
} else { | |
return localeStr; | |
} | |
} | |
function mapMonths(f) { | |
const ms = []; | |
for (let i = 1; i <= 12; i++) { | |
const dt = DateTime.utc(2016, i, 1); | |
ms.push(f(dt)); | |
} | |
return ms; | |
} | |
function mapWeekdays(f) { | |
const ms = []; | |
for (let i = 1; i <= 7; i++) { | |
const dt = DateTime.utc(2016, 11, 13 + i); | |
ms.push(f(dt)); | |
} | |
return ms; | |
} | |
function listStuff(loc, length, defaultOK, englishFn, intlFn) { | |
const mode = loc.listingMode(defaultOK); | |
if (mode === "error") { | |
return null; | |
} else if (mode === "en") { | |
return englishFn(length); | |
} else { | |
return intlFn(length); | |
} | |
} | |
function supportsFastNumbers(loc) { | |
if (loc.numberingSystem && loc.numberingSystem !== "latn") { | |
return false; | |
} else { | |
return loc.numberingSystem === "latn" || !loc.locale || loc.locale.startsWith("en") || new Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem === "latn"; | |
} | |
} | |
var PolyNumberFormatter = class { | |
constructor(intl, forceSimple, opts) { | |
this.padTo = opts.padTo || 0; | |
this.floor = opts.floor || false; | |
const { padTo, floor, ...otherOpts } = opts; | |
if (!forceSimple || Object.keys(otherOpts).length > 0) { | |
const intlOpts = { useGrouping: false, ...opts }; | |
if (opts.padTo > 0) | |
intlOpts.minimumIntegerDigits = opts.padTo; | |
this.inf = getCachedINF(intl, intlOpts); | |
} | |
} | |
format(i) { | |
if (this.inf) { | |
const fixed = this.floor ? Math.floor(i) : i; | |
return this.inf.format(fixed); | |
} else { | |
const fixed = this.floor ? Math.floor(i) : roundTo(i, 3); | |
return padStart(fixed, this.padTo); | |
} | |
} | |
}; | |
var PolyDateFormatter = class { | |
constructor(dt, intl, opts) { | |
this.opts = opts; | |
let z = void 0; | |
if (dt.zone.isUniversal) { | |
const gmtOffset = -1 * (dt.offset / 60); | |
const offsetZ = gmtOffset >= 0 ? `Etc/GMT+${gmtOffset}` : `Etc/GMT${gmtOffset}`; | |
if (dt.offset !== 0 && IANAZone.create(offsetZ).valid) { | |
z = offsetZ; | |
this.dt = dt; | |
} else { | |
z = "UTC"; | |
if (opts.timeZoneName) { | |
this.dt = dt; | |
} else { | |
this.dt = dt.offset === 0 ? dt : DateTime.fromMillis(dt.ts + dt.offset * 60 * 1e3); | |
} | |
} | |
} else if (dt.zone.type === "system") { | |
this.dt = dt; | |
} else { | |
this.dt = dt; | |
z = dt.zone.name; | |
} | |
const intlOpts = { ...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(); | |
} | |
}; | |
var PolyRelFormatter = class { | |
constructor(intl, isEnglish, opts) { | |
this.opts = { style: "long", ...opts }; | |
if (!isEnglish && hasRelative()) { | |
this.rtf = getCachedRTF(intl, opts); | |
} | |
} | |
format(count, unit) { | |
if (this.rtf) { | |
return this.rtf.format(count, unit); | |
} else { | |
return formatRelativeTime(unit, count, this.opts.numeric, this.opts.style !== "long"); | |
} | |
} | |
formatToParts(count, unit) { | |
if (this.rtf) { | |
return this.rtf.formatToParts(count, unit); | |
} else { | |
return []; | |
} | |
} | |
}; | |
var Locale = class { | |
static fromOpts(opts) { | |
return Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.defaultToEN); | |
} | |
static create(locale, numberingSystem, outputCalendar, defaultToEN = false) { | |
const specifiedLocale = locale || Settings.defaultLocale; | |
const localeR = specifiedLocale || (defaultToEN ? "en-US" : systemLocale()); | |
const numberingSystemR = numberingSystem || Settings.defaultNumberingSystem; | |
const outputCalendarR = outputCalendar || Settings.defaultOutputCalendar; | |
return new Locale(localeR, numberingSystemR, outputCalendarR, specifiedLocale); | |
} | |
static resetCache() { | |
sysLocaleCache = null; | |
intlDTCache = {}; | |
intlNumCache = {}; | |
intlRelCache = {}; | |
} | |
static fromObject({ locale, numberingSystem, outputCalendar } = {}) { | |
return Locale.create(locale, numberingSystem, outputCalendar); | |
} | |
constructor(locale, numbering, outputCalendar, specifiedLocale) { | |
const [parsedLocale, parsedNumberingSystem, parsedOutputCalendar] = parseLocaleString(locale); | |
this.locale = parsedLocale; | |
this.numberingSystem = numbering || parsedNumberingSystem || null; | |
this.outputCalendar = outputCalendar || parsedOutputCalendar || null; | |
this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar); | |
this.weekdaysCache = { format: {}, standalone: {} }; | |
this.monthsCache = { format: {}, standalone: {} }; | |
this.meridiemCache = null; | |
this.eraCache = {}; | |
this.specifiedLocale = specifiedLocale; | |
this.fastNumbersCached = null; | |
} | |
get fastNumbers() { | |
if (this.fastNumbersCached == null) { | |
this.fastNumbersCached = supportsFastNumbers(this); | |
} | |
return this.fastNumbersCached; | |
} | |
listingMode() { | |
const isActuallyEn = this.isEnglish(); | |
const hasNoWeirdness = (this.numberingSystem === null || this.numberingSystem === "latn") && (this.outputCalendar === null || this.outputCalendar === "gregory"); | |
return isActuallyEn && hasNoWeirdness ? "en" : "intl"; | |
} | |
clone(alts) { | |
if (!alts || Object.getOwnPropertyNames(alts).length === 0) { | |
return this; | |
} else { | |
return Locale.create( | |
alts.locale || this.specifiedLocale, | |
alts.numberingSystem || this.numberingSystem, | |
alts.outputCalendar || this.outputCalendar, | |
alts.defaultToEN || false | |
); | |
} | |
} | |
redefaultToEN(alts = {}) { | |
return this.clone({ ...alts, defaultToEN: true }); | |
} | |
redefaultToSystem(alts = {}) { | |
return this.clone({ ...alts, defaultToEN: false }); | |
} | |
months(length, format = false, defaultOK = true) { | |
return listStuff(this, length, defaultOK, months, () => { | |
const intl = format ? { 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, format = false, defaultOK = true) { | |
return listStuff(this, length, defaultOK, weekdays, () => { | |
const intl = format ? { 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(defaultOK = true) { | |
return listStuff( | |
this, | |
void 0, | |
defaultOK, | |
() => meridiems, | |
() => { | |
if (!this.meridiemCache) { | |
const intl = { hour: "numeric", hourCycle: "h12" }; | |
this.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map( | |
(dt) => this.extract(dt, intl, "dayperiod") | |
); | |
} | |
return this.meridiemCache; | |
} | |
); | |
} | |
eras(length, defaultOK = true) { | |
return listStuff(this, length, defaultOK, eras, () => { | |
const intl = { era: length }; | |
if (!this.eraCache[length]) { | |
this.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map( | |
(dt) => this.extract(dt, intl, "era") | |
); | |
} | |
return this.eraCache[length]; | |
}); | |
} | |
extract(dt, intlOpts, field) { | |
const df = this.dtFormatter(dt, intlOpts), results = df.formatToParts(), matching = results.find((m) => m.type.toLowerCase() === field); | |
return matching ? matching.value : null; | |
} | |
numberFormatter(opts = {}) { | |
return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts); | |
} | |
dtFormatter(dt, intlOpts = {}) { | |
return new PolyDateFormatter(dt, this.intl, intlOpts); | |
} | |
relFormatter(opts = {}) { | |
return new PolyRelFormatter(this.intl, this.isEnglish(), opts); | |
} | |
listFormatter(opts = {}) { | |
return getCachedLF(this.intl, opts); | |
} | |
isEnglish() { | |
return this.locale === "en" || this.locale.toLowerCase() === "en-us" || new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us"); | |
} | |
equals(other) { | |
return this.locale === other.locale && this.numberingSystem === other.numberingSystem && this.outputCalendar === other.outputCalendar; | |
} | |
}; | |
var singleton = null; | |
var FixedOffsetZone = class extends Zone { | |
/** | |
* Get a singleton instance of UTC | |
* @return {FixedOffsetZone} | |
*/ | |
static get utcInstance() { | |
if (singleton === null) { | |
singleton = new FixedOffsetZone(0); | |
} | |
return singleton; | |
} | |
/** | |
* Get an instance with a specified offset | |
* @param {number} offset - The offset in minutes | |
* @return {FixedOffsetZone} | |
*/ | |
static instance(offset2) { | |
return offset2 === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset2); | |
} | |
/** | |
* Get an instance of FixedOffsetZone from a UTC offset string, like "UTC+6" | |
* @param {string} s - The offset string to parse | |
* @example FixedOffsetZone.parseSpecifier("UTC+6") | |
* @example FixedOffsetZone.parseSpecifier("UTC+06") | |
* @example FixedOffsetZone.parseSpecifier("UTC-6:00") | |
* @return {FixedOffsetZone} | |
*/ | |
static parseSpecifier(s2) { | |
if (s2) { | |
const r = s2.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i); | |
if (r) { | |
return new FixedOffsetZone(signedOffset(r[1], r[2])); | |
} | |
} | |
return null; | |
} | |
constructor(offset2) { | |
super(); | |
this.fixed = offset2; | |
} | |
/** @override **/ | |
get type() { | |
return "fixed"; | |
} | |
/** @override **/ | |
get name() { | |
return this.fixed === 0 ? "UTC" : `UTC${formatOffset(this.fixed, "narrow")}`; | |
} | |
get ianaName() { | |
if (this.fixed === 0) { | |
return "Etc/UTC"; | |
} else { | |
return `Etc/GMT${formatOffset(-this.fixed, "narrow")}`; | |
} | |
} | |
/** @override **/ | |
offsetName() { | |
return this.name; | |
} | |
/** @override **/ | |
formatOffset(ts, 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; | |
} | |
}; | |
var InvalidZone = class extends Zone { | |
constructor(zoneName) { | |
super(); | |
this.zoneName = zoneName; | |
} | |
/** @override **/ | |
get type() { | |
return "invalid"; | |
} | |
/** @override **/ | |
get name() { | |
return this.zoneName; | |
} | |
/** @override **/ | |
get isUniversal() { | |
return false; | |
} | |
/** @override **/ | |
offsetName() { | |
return null; | |
} | |
/** @override **/ | |
formatOffset() { | |
return ""; | |
} | |
/** @override **/ | |
offset() { | |
return NaN; | |
} | |
/** @override **/ | |
equals() { | |
return false; | |
} | |
/** @override **/ | |
get isValid() { | |
return false; | |
} | |
}; | |
function normalizeZone(input, defaultZone2) { | |
if (isUndefined(input) || input === null) { | |
return defaultZone2; | |
} else if (input instanceof Zone) { | |
return input; | |
} else if (isString(input)) { | |
const lowered = input.toLowerCase(); | |
if (lowered === "default") | |
return defaultZone2; | |
else if (lowered === "local" || lowered === "system") | |
return SystemZone.instance; | |
else if (lowered === "utc" || lowered === "gmt") | |
return FixedOffsetZone.utcInstance; | |
else | |
return FixedOffsetZone.parseSpecifier(lowered) || IANAZone.create(input); | |
} else if (isNumber(input)) { | |
return FixedOffsetZone.instance(input); | |
} else if (typeof input === "object" && input.offset && typeof input.offset === "number") { | |
return input; | |
} else { | |
return new InvalidZone(input); | |
} | |
} | |
var now = () => Date.now(); | |
var defaultZone = "system"; | |
var defaultLocale = null; | |
var defaultNumberingSystem = null; | |
var defaultOutputCalendar = null; | |
var twoDigitCutoffYear = 60; | |
var throwOnInvalid; | |
var Settings = class { | |
/** | |
* Get the callback for returning the current timestamp. | |
* @type {function} | |
*/ | |
static get now() { | |
return now; | |
} | |
/** | |
* Set the callback for returning the current timestamp. | |
* The function should return a number, which will be interpreted as an Epoch millisecond count | |
* @type {function} | |
* @example Settings.now = () => Date.now() + 3000 // pretend it is 3 seconds in the future | |
* @example Settings.now = () => 0 // always pretend it's Jan 1, 1970 at midnight in UTC time | |
*/ | |
static set now(n2) { | |
now = n2; | |
} | |
/** | |
* Set the default time zone to create DateTimes in. Does not affect existing instances. | |
* Use the value "system" to reset this value to the system's time zone. | |
* @type {string} | |
*/ | |
static set defaultZone(zone) { | |
defaultZone = zone; | |
} | |
/** | |
* Get the default time zone object currently used to create DateTimes. Does not affect existing instances. | |
* The default value is the system's time zone (the one set on the machine that runs this code). | |
* @type {Zone} | |
*/ | |
static get defaultZone() { | |
return normalizeZone(defaultZone, SystemZone.instance); | |
} | |
/** | |
* Get the default locale to create DateTimes with. Does not affect existing instances. | |
* @type {string} | |
*/ | |
static get defaultLocale() { | |
return defaultLocale; | |
} | |
/** | |
* Set the default locale to create DateTimes with. Does not affect existing instances. | |
* @type {string} | |
*/ | |
static set defaultLocale(locale) { | |
defaultLocale = locale; | |
} | |
/** | |
* Get the default numbering system to create DateTimes with. Does not affect existing instances. | |
* @type {string} | |
*/ | |
static get defaultNumberingSystem() { | |
return defaultNumberingSystem; | |
} | |
/** | |
* Set the default numbering system to create DateTimes with. Does not affect existing instances. | |
* @type {string} | |
*/ | |
static set defaultNumberingSystem(numberingSystem) { | |
defaultNumberingSystem = numberingSystem; | |
} | |
/** | |
* Get the default output calendar to create DateTimes with. Does not affect existing instances. | |
* @type {string} | |
*/ | |
static get defaultOutputCalendar() { | |
return defaultOutputCalendar; | |
} | |
/** | |
* Set the default output calendar to create DateTimes with. Does not affect existing instances. | |
* @type {string} | |
*/ | |
static set defaultOutputCalendar(outputCalendar) { | |
defaultOutputCalendar = outputCalendar; | |
} | |
/** | |
* Get the cutoff year after which a string encoding a year as two digits is interpreted to occur in the current century. | |
* @type {number} | |
*/ | |
static get twoDigitCutoffYear() { | |
return twoDigitCutoffYear; | |
} | |
/** | |
* Set the cutoff year after which a string encoding a year as two digits is interpreted to occur in the current century. | |
* @type {number} | |
* @example Settings.twoDigitCutoffYear = 0 // cut-off year is 0, so all 'yy' are interpretted as current century | |
* @example Settings.twoDigitCutoffYear = 50 // '49' -> 1949; '50' -> 2050 | |
* @example Settings.twoDigitCutoffYear = 1950 // interpretted as 50 | |
* @example Settings.twoDigitCutoffYear = 2050 // ALSO interpretted as 50 | |
*/ | |
static set twoDigitCutoffYear(cutoffYear) { | |
twoDigitCutoffYear = cutoffYear % 100; | |
} | |
/** | |
* Get whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals | |
* @type {boolean} | |
*/ | |
static get throwOnInvalid() { | |
return throwOnInvalid; | |
} | |
/** | |
* Set whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals | |
* @type {boolean} | |
*/ | |
static set throwOnInvalid(t2) { | |
throwOnInvalid = t2; | |
} | |
/** | |
* Reset Luxon's global caches. Should only be necessary in testing scenarios. | |
* @return {void} | |
*/ | |
static resetCaches() { | |
Locale.resetCache(); | |
IANAZone.resetCache(); | |
} | |
}; | |
function isUndefined(o) { | |
return typeof o === "undefined"; | |
} | |
function isNumber(o) { | |
return typeof o === "number"; | |
} | |
function isInteger(o) { | |
return typeof o === "number" && o % 1 === 0; | |
} | |
function isString(o) { | |
return typeof o === "string"; | |
} | |
function isDate(o) { | |
return Object.prototype.toString.call(o) === "[object Date]"; | |
} | |
function hasRelative() { | |
try { | |
return typeof Intl !== "undefined" && !!Intl.RelativeTimeFormat; | |
} catch (e) { | |
return false; | |
} | |
} | |
function maybeArray(thing) { | |
return Array.isArray(thing) ? thing : [thing]; | |
} | |
function bestBy(arr, by, compare) { | |
if (arr.length === 0) { | |
return void 0; | |
} | |
return arr.reduce((best, next) => { | |
const pair = [by(next), next]; | |
if (!best) { | |
return pair; | |
} else if (compare(best[0], pair[0]) === best[0]) { | |
return best; | |
} else { | |
return pair; | |
} | |
}, null)[1]; | |
} | |
function pick(obj, keys) { | |
return keys.reduce((a, k) => { | |
a[k] = obj[k]; | |
return a; | |
}, {}); | |
} | |
function hasOwnProperty(obj, prop) { | |
return Object.prototype.hasOwnProperty.call(obj, prop); | |
} | |
function integerBetween(thing, bottom, top) { | |
return isInteger(thing) && thing >= bottom && thing <= top; | |
} | |
function floorMod(x, n2) { | |
return x - n2 * Math.floor(x / n2); | |
} | |
function padStart(input, n2 = 2) { | |
const isNeg = input < 0; | |
let padded; | |
if (isNeg) { | |
padded = "-" + ("" + -input).padStart(n2, "0"); | |
} else { | |
padded = ("" + input).padStart(n2, "0"); | |
} | |
return padded; | |
} | |
function parseInteger(string) { | |
if (isUndefined(string) || string === null || string === "") { | |
return void 0; | |
} else { | |
return parseInt(string, 10); | |
} | |
} | |
function parseFloating(string) { | |
if (isUndefined(string) || string === null || string === "") { | |
return void 0; | |
} else { | |
return parseFloat(string); | |
} | |
} | |
function parseMillis(fraction) { | |
if (isUndefined(fraction) || fraction === null || fraction === "") { | |
return void 0; | |
} else { | |
const f = parseFloat("0." + fraction) * 1e3; | |
return Math.floor(f); | |
} | |
} | |
function roundTo(number, digits, towardZero = false) { | |
const factor = 10 ** digits, rounder = towardZero ? Math.trunc : Math.round; | |
return rounder(number * factor) / factor; | |
} | |
function isLeapYear(year) { | |
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); | |
} | |
function daysInYear(year) { | |
return isLeapYear(year) ? 366 : 365; | |
} | |
function daysInMonth(year, month) { | |
const modMonth = floorMod(month - 1, 12) + 1, modYear = year + (month - modMonth) / 12; | |
if (modMonth === 2) { | |
return isLeapYear(modYear) ? 29 : 28; | |
} else { | |
return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1]; | |
} | |
} | |
function objToLocalTS(obj) { | |
let d = Date.UTC( | |
obj.year, | |
obj.month - 1, | |
obj.day, | |
obj.hour, | |
obj.minute, | |
obj.second, | |
obj.millisecond | |
); | |
if (obj.year < 100 && obj.year >= 0) { | |
d = new Date(d); | |
d.setUTCFullYear(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; | |
return p1 === 4 || p2 === 3 ? 53 : 52; | |
} | |
function untruncateYear(year) { | |
if (year > 99) { | |
return year; | |
} else | |
return year > Settings.twoDigitCutoffYear ? 1900 + year : 2e3 + year; | |
} | |
function parseZoneInfo(ts, offsetFormat, locale, timeZone = null) { | |
const date = new Date(ts), intlOpts = { | |
hourCycle: "h23", | |
year: "numeric", | |
month: "2-digit", | |
day: "2-digit", | |
hour: "2-digit", | |
minute: "2-digit" | |
}; | |
if (timeZone) { | |
intlOpts.timeZone = timeZone; | |
} | |
const modified = { timeZoneName: offsetFormat, ...intlOpts }; | |
const parsed = new Intl.DateTimeFormat(locale, modified).formatToParts(date).find((m) => m.type.toLowerCase() === "timezonename"); | |
return parsed ? parsed.value : null; | |
} | |
function signedOffset(offHourStr, offMinuteStr) { | |
let offHour = parseInt(offHourStr, 10); | |
if (Number.isNaN(offHour)) { | |
offHour = 0; | |
} | |
const offMin = parseInt(offMinuteStr, 10) || 0, offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin; | |
return offHour * 60 + offMinSigned; | |
} | |
function asNumber(value) { | |
const numericValue = Number(value); | |
if (typeof value === "boolean" || value === "" || Number.isNaN(numericValue)) | |
throw new InvalidArgumentError(`Invalid unit value ${value}`); | |
return numericValue; | |
} | |
function normalizeObject(obj, normalizer) { | |
const normalized = {}; | |
for (const u in obj) { | |
if (hasOwnProperty(obj, u)) { | |
const v = obj[u]; | |
if (v === void 0 || v === null) | |
continue; | |
normalized[normalizer(u)] = asNumber(v); | |
} | |
} | |
return normalized; | |
} | |
function formatOffset(offset2, format) { | |
const hours = Math.trunc(Math.abs(offset2 / 60)), minutes = Math.trunc(Math.abs(offset2 % 60)), sign = offset2 >= 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`); | |
} | |
} | |
function timeObject(obj) { | |
return pick(obj, ["hour", "minute", "second", "millisecond"]); | |
} | |
var monthsLong = [ | |
"January", | |
"February", | |
"March", | |
"April", | |
"May", | |
"June", | |
"July", | |
"August", | |
"September", | |
"October", | |
"November", | |
"December" | |
]; | |
var monthsShort = [ | |
"Jan", | |
"Feb", | |
"Mar", | |
"Apr", | |
"May", | |
"Jun", | |
"Jul", | |
"Aug", | |
"Sep", | |
"Oct", | |
"Nov", | |
"Dec" | |
]; | |
var monthsNarrow = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]; | |
function months(length) { | |
switch (length) { | |
case "narrow": | |
return [...monthsNarrow]; | |
case "short": | |
return [...monthsShort]; | |
case "long": | |
return [...monthsLong]; | |
case "numeric": | |
return ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]; | |
case "2-digit": | |
return ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]; | |
default: | |
return null; | |
} | |
} | |
var weekdaysLong = [ | |
"Monday", | |
"Tuesday", | |
"Wednesday", | |
"Thursday", | |
"Friday", | |
"Saturday", | |
"Sunday" | |
]; | |
var weekdaysShort = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; | |
var weekdaysNarrow = ["M", "T", "W", "T", "F", "S", "S"]; | |
function weekdays(length) { | |
switch (length) { | |
case "narrow": | |
return [...weekdaysNarrow]; | |
case "short": | |
return [...weekdaysShort]; | |
case "long": | |
return [...weekdaysLong]; | |
case "numeric": | |
return ["1", "2", "3", "4", "5", "6", "7"]; | |
default: | |
return null; | |
} | |
} | |
var meridiems = ["AM", "PM"]; | |
var erasLong = ["Before Christ", "Anno Domini"]; | |
var erasShort = ["BC", "AD"]; | |
var erasNarrow = ["B", "A"]; | |
function eras(length) { | |
switch (length) { | |
case "narrow": | |
return [...erasNarrow]; | |
case "short": | |
return [...erasShort]; | |
case "long": | |
return [...erasLong]; | |
default: | |
return null; | |
} | |
} | |
function meridiemForDateTime(dt) { | |
return meridiems[dt.hour < 12 ? 0 : 1]; | |
} | |
function weekdayForDateTime(dt, length) { | |
return weekdays(length)[dt.weekday - 1]; | |
} | |
function monthForDateTime(dt, length) { | |
return months(length)[dt.month - 1]; | |
} | |
function eraForDateTime(dt, length) { | |
return eras(length)[dt.year < 0 ? 0 : 1]; | |
} | |
function formatRelativeTime(unit, count, numeric = "always", narrow = false) { | |
const units = { | |
years: ["year", "yr."], | |
quarters: ["quarter", "qtr."], | |
months: ["month", "mo."], | |
weeks: ["week", "wk."], | |
days: ["day", "day", "days"], | |
hours: ["hour", "hr."], | |
minutes: ["minute", "min."], | |
seconds: ["second", "sec."] | |
}; | |
const lastable = ["hours", "minutes", "seconds"].indexOf(unit) === -1; | |
if (numeric === "auto" && lastable) { | |
const isDay = unit === "days"; | |
switch (count) { | |
case 1: | |
return isDay ? "tomorrow" : `next ${units[unit][0]}`; | |
case -1: | |
return isDay ? "yesterday" : `last ${units[unit][0]}`; | |
case 0: | |
return isDay ? "today" : `this ${units[unit][0]}`; | |
} | |
} | |
const isInPast = Object.is(count, -0) || count < 0, fmtValue = Math.abs(count), singular = fmtValue === 1, lilUnits = units[unit], fmtUnit = narrow ? singular ? lilUnits[1] : lilUnits[2] || lilUnits[1] : singular ? units[unit][0] : unit; | |
return isInPast ? `${fmtValue} ${fmtUnit} ago` : `in ${fmtValue} ${fmtUnit}`; | |
} | |
function stringifyTokens(splits, tokenToString) { | |
let s2 = ""; | |
for (const token of splits) { | |
if (token.literal) { | |
s2 += token.val; | |
} else { | |
s2 += tokenToString(token.val); | |
} | |
} | |
return s2; | |
} | |
var macroTokenToFormatOpts = { | |
D: DATE_SHORT, | |
DD: DATE_MED, | |
DDD: DATE_FULL, | |
DDDD: DATE_HUGE, | |
t: TIME_SIMPLE, | |
tt: TIME_WITH_SECONDS, | |
ttt: TIME_WITH_SHORT_OFFSET, | |
tttt: TIME_WITH_LONG_OFFSET, | |
T: TIME_24_SIMPLE, | |
TT: TIME_24_WITH_SECONDS, | |
TTT: TIME_24_WITH_SHORT_OFFSET, | |
TTTT: TIME_24_WITH_LONG_OFFSET, | |
f: DATETIME_SHORT, | |
ff: DATETIME_MED, | |
fff: DATETIME_FULL, | |
ffff: DATETIME_HUGE, | |
F: DATETIME_SHORT_WITH_SECONDS, | |
FF: DATETIME_MED_WITH_SECONDS, | |
FFF: DATETIME_FULL_WITH_SECONDS, | |
FFFF: DATETIME_HUGE_WITH_SECONDS | |
}; | |
var Formatter2 = class { | |
static create(locale, opts = {}) { | |
return new Formatter2(locale, opts); | |
} | |
static parseFormat(fmt) { | |
let current = null, currentFull = "", bracketed = false; | |
const splits = []; | |
for (let i = 0; i < fmt.length; i++) { | |
const c = fmt.charAt(i); | |
if (c === "'") { | |
if (currentFull.length > 0) { | |
splits.push({ literal: bracketed, val: currentFull }); | |
} | |
current = null; | |
currentFull = ""; | |
bracketed = !bracketed; | |
} else if (bracketed) { | |
currentFull += c; | |
} else if (c === current) { | |
currentFull += c; | |
} else { | |
if (currentFull.length > 0) { | |
splits.push({ literal: false, 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, { ...this.opts, ...opts }); | |
return df.format(); | |
} | |
formatDateTime(dt, opts = {}) { | |
const df = this.loc.dtFormatter(dt, { ...this.opts, ...opts }); | |
return df.format(); | |
} | |
formatDateTimeParts(dt, opts = {}) { | |
const df = this.loc.dtFormatter(dt, { ...this.opts, ...opts }); | |
return df.formatToParts(); | |
} | |
formatInterval(interval, opts = {}) { | |
const df = this.loc.dtFormatter(interval.start, { ...this.opts, ...opts }); | |
return df.dtf.formatRange(interval.start.toJSDate(), interval.end.toJSDate()); | |
} | |
resolvedOptions(dt, opts = {}) { | |
const df = this.loc.dtFormatter(dt, { ...this.opts, ...opts }); | |
return df.resolvedOptions(); | |
} | |
num(n2, p = 0) { | |
if (this.opts.forceSimple) { | |
return padStart(n2, p); | |
} | |
const opts = { ...this.opts }; | |
if (p > 0) { | |
opts.padTo = p; | |
} | |
return this.loc.numberFormatter(opts).format(n2); | |
} | |
formatDateTimeFromString(dt, fmt) { | |
const knownEnglish = this.loc.listingMode() === "en", useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== "gregory", string = (opts, extract) => this.loc.extract(dt, opts, extract), formatOffset2 = (opts) => { | |
if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) { | |
return "Z"; | |
} | |
return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : ""; | |
}, meridiem = () => knownEnglish ? meridiemForDateTime(dt) : string({ hour: "numeric", hourCycle: "h12" }, "dayperiod"), month = (length, standalone) => knownEnglish ? monthForDateTime(dt, length) : string(standalone ? { month: length } : { month: length, day: "numeric" }, "month"), weekday = (length, standalone) => knownEnglish ? weekdayForDateTime(dt, length) : string( | |
standalone ? { weekday: length } : { weekday: length, month: "long", day: "numeric" }, | |
"weekday" | |
), maybeMacro = (token) => { | |
const formatOpts = Formatter2.macroTokenToFormatOpts(token); | |
if (formatOpts) { | |
return this.formatWithSystemDefault(dt, formatOpts); | |
} else { | |
return token; | |
} | |
}, era = (length) => knownEnglish ? eraForDateTime(dt, length) : string({ era: length }, "era"), tokenToString = (token) => { | |
switch (token) { | |
case "S": | |
return this.num(dt.millisecond); | |
case "u": | |
case "SSS": | |
return this.num(dt.millisecond, 3); | |
case "s": | |
return this.num(dt.second); | |
case "ss": | |
return this.num(dt.second, 2); | |
case "uu": | |
return this.num(Math.floor(dt.millisecond / 10), 2); | |
case "uuu": | |
return this.num(Math.floor(dt.millisecond / 100)); | |
case "m": | |
return this.num(dt.minute); | |
case "mm": | |
return this.num(dt.minute, 2); | |
case "h": | |
return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12); | |
case "hh": | |
return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2); | |
case "H": | |
return this.num(dt.hour); | |
case "HH": | |
return this.num(dt.hour, 2); | |
case "Z": | |
return formatOffset2({ format: "narrow", allowZ: this.opts.allowZ }); | |
case "ZZ": | |
return formatOffset2({ format: "short", allowZ: this.opts.allowZ }); | |
case "ZZZ": | |
return formatOffset2({ format: "techie", allowZ: this.opts.allowZ }); | |
case "ZZZZ": | |
return dt.zone.offsetName(dt.ts, { format: "short", locale: this.loc.locale }); | |
case "ZZZZZ": | |
return dt.zone.offsetName(dt.ts, { format: "long", locale: this.loc.locale }); | |
case "z": | |
return dt.zoneName; | |
case "a": | |
return meridiem(); | |
case "d": | |
return useDateTimeFormatter ? string({ day: "numeric" }, "day") : this.num(dt.day); | |
case "dd": | |
return useDateTimeFormatter ? string({ day: "2-digit" }, "day") : this.num(dt.day, 2); | |
case "c": | |
return this.num(dt.weekday); | |
case "ccc": | |
return weekday("short", true); | |
case "cccc": | |
return weekday("long", true); | |
case "ccccc": | |
return weekday("narrow", true); | |
case "E": | |
return this.num(dt.weekday); | |
case "EEE": | |
return weekday("short", false); | |
case "EEEE": | |
return weekday("long", false); | |
case "EEEEE": | |
return weekday("narrow", false); | |
case "L": | |
return useDateTimeFormatter ? string({ month: "numeric", day: "numeric" }, "month") : this.num(dt.month); | |
case "LL": | |
return useDateTimeFormatter ? string({ month: "2-digit", day: "numeric" }, "month") : this.num(dt.month, 2); | |
case "LLL": | |
return month("short", true); | |
case "LLLL": | |
return month("long", true); | |
case "LLLLL": | |
return month("narrow", true); | |
case "M": | |
return useDateTimeFormatter ? string({ month: "numeric" }, "month") : this.num(dt.month); | |
case "MM": | |
return useDateTimeFormatter ? string({ month: "2-digit" }, "month") : this.num(dt.month, 2); | |
case "MMM": | |
return month("short", false); | |
case "MMMM": | |
return month("long", false); | |
case "MMMMM": | |
return month("narrow", false); | |
case "y": | |
return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year); | |
case "yy": | |
return useDateTimeFormatter ? string({ year: "2-digit" }, "year") : this.num(dt.year.toString().slice(-2), 2); | |
case "yyyy": | |
return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year, 4); | |
case "yyyyyy": | |
return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year, 6); | |
case "G": | |
return era("short"); | |
case "GG": | |
return era("long"); | |
case "GGGGG": | |
return era("narrow"); | |
case "kk": | |
return this.num(dt.weekYear.toString().slice(-2), 2); | |
case "kkkk": | |
return this.num(dt.weekYear, 4); | |
case "W": | |
return this.num(dt.weekNumber); | |
case "WW": | |
return this.num(dt.weekNumber, 2); | |
case "o": | |
return this.num(dt.ordinal); | |
case "ooo": | |
return this.num(dt.ordinal, 3); | |
case "q": | |
return this.num(dt.quarter); | |
case "qq": | |
return this.num(dt.quarter, 2); | |
case "X": | |
return this.num(Math.floor(dt.ts / 1e3)); | |
case "x": | |
return this.num(dt.ts); | |
default: | |
return maybeMacro(token); | |
} | |
}; | |
return stringifyTokens(Formatter2.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 = Formatter2.parseFormat(fmt), realTokens = tokens.reduce( | |
(found, { literal, val }) => literal ? found : found.concat(val), | |
[] | |
), collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter((t2) => t2)); | |
return stringifyTokens(tokens, tokenToString(collapsed)); | |
} | |
}; | |
var Invalid = class { | |
constructor(reason, explanation) { | |
this.reason = reason; | |
this.explanation = explanation; | |
} | |
toMessage() { | |
if (this.explanation) { | |
return `${this.reason}: ${this.explanation}`; | |
} else { | |
return this.reason; | |
} | |
} | |
}; | |
var ianaRegex = /[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/; | |
function combineRegexes(...regexes) { | |
const full = regexes.reduce((f, r) => f + r.source, ""); | |
return RegExp(`^${full}$`); | |
} | |
function combineExtractors(...extractors) { | |
return (m) => extractors.reduce( | |
([mergedVals, mergedZone, cursor], ex) => { | |
const [val, zone, next] = ex(m, cursor); | |
return [{ ...mergedVals, ...val }, zone || mergedZone, next]; | |
}, | |
[{}, null, 1] | |
).slice(0, 2); | |
} | |
function parse2(s2, ...patterns) { | |
if (s2 == null) { | |
return [null, null]; | |
} | |
for (const [regex3, extractor] of patterns) { | |
const m = regex3.exec(s2); | |
if (m) { | |
return extractor(m); | |
} | |
} | |
return [null, null]; | |
} | |
function simpleParse(...keys) { | |
return (match2, cursor) => { | |
const ret = {}; | |
let i; | |
for (i = 0; i < keys.length; i++) { | |
ret[keys[i]] = parseInteger(match2[cursor + i]); | |
} | |
return [ret, null, cursor + i]; | |
}; | |
} | |
var offsetRegex = /(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/; | |
var isoExtendedZone = `(?:${offsetRegex.source}?(?:\\[(${ianaRegex.source})\\])?)?`; | |
var isoTimeBaseRegex = /(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/; | |
var isoTimeRegex = RegExp(`${isoTimeBaseRegex.source}${isoExtendedZone}`); | |
var isoTimeExtensionRegex = RegExp(`(?:T${isoTimeRegex.source})?`); | |
var isoYmdRegex = /([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/; | |
var isoWeekRegex = /(\d{4})-?W(\d\d)(?:-?(\d))?/; | |
var isoOrdinalRegex = /(\d{4})-?(\d{3})/; | |
var extractISOWeekData = simpleParse("weekYear", "weekNumber", "weekDay"); | |
var extractISOOrdinalData = simpleParse("year", "ordinal"); | |
var sqlYmdRegex = /(\d{4})-(\d\d)-(\d\d)/; | |
var sqlTimeRegex = RegExp( | |
`${isoTimeBaseRegex.source} ?(?:${offsetRegex.source}|(${ianaRegex.source}))?` | |
); | |
var sqlTimeExtensionRegex = RegExp(`(?: ${sqlTimeRegex.source})?`); | |
function int(match2, pos, fallback) { | |
const m = match2[pos]; | |
return isUndefined(m) ? fallback : parseInteger(m); | |
} | |
function extractISOYmd(match2, cursor) { | |
const item = { | |
year: int(match2, cursor), | |
month: int(match2, cursor + 1, 1), | |
day: int(match2, cursor + 2, 1) | |
}; | |
return [item, null, cursor + 3]; | |
} | |
function extractISOTime(match2, cursor) { | |
const item = { | |
hours: int(match2, cursor, 0), | |
minutes: int(match2, cursor + 1, 0), | |
seconds: int(match2, cursor + 2, 0), | |
milliseconds: parseMillis(match2[cursor + 3]) | |
}; | |
return [item, null, cursor + 4]; | |
} | |
function extractISOOffset(match2, cursor) { | |
const local = !match2[cursor] && !match2[cursor + 1], fullOffset = signedOffset(match2[cursor + 1], match2[cursor + 2]), zone = local ? null : FixedOffsetZone.instance(fullOffset); | |
return [{}, zone, cursor + 3]; | |
} | |
function extractIANAZone(match2, cursor) { | |
const zone = match2[cursor] ? IANAZone.create(match2[cursor]) : null; | |
return [{}, zone, cursor + 1]; | |
} | |
var isoTimeOnly = RegExp(`^T?${isoTimeBaseRegex.source}$`); | |
var isoDuration = /^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/; | |
function extractISODuration(match2) { | |
const [s2, yearStr, monthStr, weekStr, dayStr, hourStr, minuteStr, secondStr, millisecondsStr] = match2; | |
const hasNegativePrefix = s2[0] === "-"; | |
const negativeSeconds = secondStr && secondStr[0] === "-"; | |
const maybeNegate = (num, force = false) => num !== void 0 && (force || num && hasNegativePrefix) ? -num : num; | |
return [ | |
{ | |
years: maybeNegate(parseFloating(yearStr)), | |
months: maybeNegate(parseFloating(monthStr)), | |
weeks: maybeNegate(parseFloating(weekStr)), | |
days: maybeNegate(parseFloating(dayStr)), | |
hours: maybeNegate(parseFloating(hourStr)), | |
minutes: maybeNegate(parseFloating(minuteStr)), | |
seconds: maybeNegate(parseFloating(secondStr), secondStr === "-0"), | |
milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds) | |
} | |
]; | |
} | |
var obsOffsets = { | |
GMT: 0, | |
EDT: -4 * 60, | |
EST: -5 * 60, | |
CDT: -5 * 60, | |
CST: -6 * 60, | |
MDT: -6 * 60, | |
MST: -7 * 60, | |
PDT: -7 * 60, | |
PST: -8 * 60 | |
}; | |
function fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) { | |
const result = { | |
year: yearStr.length === 2 ? untruncateYear(parseInteger(yearStr)) : parseInteger(yearStr), | |
month: monthsShort.indexOf(monthStr) + 1, | |
day: parseInteger(dayStr), | |
hour: parseInteger(hourStr), | |
minute: parseInteger(minuteStr) | |
}; | |
if (secondStr) | |
result.second = parseInteger(secondStr); | |
if (weekdayStr) { | |
result.weekday = weekdayStr.length > 3 ? weekdaysLong.indexOf(weekdayStr) + 1 : weekdaysShort.indexOf(weekdayStr) + 1; | |
} | |
return result; | |
} | |
var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/; | |
function extractRFC2822(match2) { | |
const [ | |
, | |
weekdayStr, | |
dayStr, | |
monthStr, | |
yearStr, | |
hourStr, | |
minuteStr, | |
secondStr, | |
obsOffset, | |
milOffset, | |
offHourStr, | |
offMinuteStr | |
] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); | |
let offset2; | |
if (obsOffset) { | |
offset2 = obsOffsets[obsOffset]; | |
} else if (milOffset) { | |
offset2 = 0; | |
} else { | |
offset2 = signedOffset(offHourStr, offMinuteStr); | |
} | |
return [result, new FixedOffsetZone(offset2)]; | |
} | |
function preprocessRFC2822(s2) { | |
return s2.replace(/\([^()]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").trim(); | |
} | |
var rfc1123 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/; | |
var rfc850 = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/; | |
var ascii = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/; | |
function extractRFC1123Or850(match2) { | |
const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); | |
return [result, FixedOffsetZone.utcInstance]; | |
} | |
function extractASCII(match2) { | |
const [, weekdayStr, monthStr, dayStr, hourStr, minuteStr, secondStr, yearStr] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); | |
return [result, FixedOffsetZone.utcInstance]; | |
} | |
var isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex); | |
var isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex); | |
var isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex); | |
var isoTimeCombinedRegex = combineRegexes(isoTimeRegex); | |
var extractISOYmdTimeAndOffset = combineExtractors( | |
extractISOYmd, | |
extractISOTime, | |
extractISOOffset, | |
extractIANAZone | |
); | |
var extractISOWeekTimeAndOffset = combineExtractors( | |
extractISOWeekData, | |
extractISOTime, | |
extractISOOffset, | |
extractIANAZone | |
); | |
var extractISOOrdinalDateAndTime = combineExtractors( | |
extractISOOrdinalData, | |
extractISOTime, | |
extractISOOffset, | |
extractIANAZone | |
); | |
var extractISOTimeAndOffset = combineExtractors( | |
extractISOTime, | |
extractISOOffset, | |
extractIANAZone | |
); | |
function parseISODate(s2) { | |
return parse2( | |
s2, | |
[isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], | |
[isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset], | |
[isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime], | |
[isoTimeCombinedRegex, extractISOTimeAndOffset] | |
); | |
} | |
function parseRFC2822Date(s2) { | |
return parse2(preprocessRFC2822(s2), [rfc2822, extractRFC2822]); | |
} | |
function parseHTTPDate(s2) { | |
return parse2( | |
s2, | |
[rfc1123, extractRFC1123Or850], | |
[rfc850, extractRFC1123Or850], | |
[ascii, extractASCII] | |
); | |
} | |
function parseISODuration(s2) { | |
return parse2(s2, [isoDuration, extractISODuration]); | |
} | |
var extractISOTimeOnly = combineExtractors(extractISOTime); | |
function parseISOTimeOnly(s2) { | |
return parse2(s2, [isoTimeOnly, extractISOTimeOnly]); | |
} | |
var sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex); | |
var sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex); | |
var extractISOTimeOffsetAndIANAZone = combineExtractors( | |
extractISOTime, | |
extractISOOffset, | |
extractIANAZone | |
); | |
function parseSQL(s2) { | |
return parse2( | |
s2, | |
[sqlYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], | |
[sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone] | |
); | |
} | |
var INVALID$2 = "Invalid Duration"; | |
var lowOrderMatrix = { | |
weeks: { | |
days: 7, | |
hours: 7 * 24, | |
minutes: 7 * 24 * 60, | |
seconds: 7 * 24 * 60 * 60, | |
milliseconds: 7 * 24 * 60 * 60 * 1e3 | |
}, | |
days: { | |
hours: 24, | |
minutes: 24 * 60, | |
seconds: 24 * 60 * 60, | |
milliseconds: 24 * 60 * 60 * 1e3 | |
}, | |
hours: { minutes: 60, seconds: 60 * 60, milliseconds: 60 * 60 * 1e3 }, | |
minutes: { seconds: 60, milliseconds: 60 * 1e3 }, | |
seconds: { milliseconds: 1e3 } | |
}; | |
var casualMatrix = { | |
years: { | |
quarters: 4, | |
months: 12, | |
weeks: 52, | |
days: 365, | |
hours: 365 * 24, | |
minutes: 365 * 24 * 60, | |
seconds: 365 * 24 * 60 * 60, | |
milliseconds: 365 * 24 * 60 * 60 * 1e3 | |
}, | |
quarters: { | |
months: 3, | |
weeks: 13, | |
days: 91, | |
hours: 91 * 24, | |
minutes: 91 * 24 * 60, | |
seconds: 91 * 24 * 60 * 60, | |
milliseconds: 91 * 24 * 60 * 60 * 1e3 | |
}, | |
months: { | |
weeks: 4, | |
days: 30, | |
hours: 30 * 24, | |
minutes: 30 * 24 * 60, | |
seconds: 30 * 24 * 60 * 60, | |
milliseconds: 30 * 24 * 60 * 60 * 1e3 | |
}, | |
...lowOrderMatrix | |
}; | |
var daysInYearAccurate = 146097 / 400; | |
var daysInMonthAccurate = 146097 / 4800; | |
var accurateMatrix = { | |
years: { | |
quarters: 4, | |
months: 12, | |
weeks: daysInYearAccurate / 7, | |
days: daysInYearAccurate, | |
hours: daysInYearAccurate * 24, | |
minutes: daysInYearAccurate * 24 * 60, | |
seconds: daysInYearAccurate * 24 * 60 * 60, | |
milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1e3 | |
}, | |
quarters: { | |
months: 3, | |
weeks: daysInYearAccurate / 28, | |
days: daysInYearAccurate / 4, | |
hours: daysInYearAccurate * 24 / 4, | |
minutes: daysInYearAccurate * 24 * 60 / 4, | |
seconds: daysInYearAccurate * 24 * 60 * 60 / 4, | |
milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1e3 / 4 | |
}, | |
months: { | |
weeks: daysInMonthAccurate / 7, | |
days: daysInMonthAccurate, | |
hours: daysInMonthAccurate * 24, | |
minutes: daysInMonthAccurate * 24 * 60, | |
seconds: daysInMonthAccurate * 24 * 60 * 60, | |
milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1e3 | |
}, | |
...lowOrderMatrix | |
}; | |
var orderedUnits$1 = [ | |
"years", | |
"quarters", | |
"months", | |
"weeks", | |
"days", | |
"hours", | |
"minutes", | |
"seconds", | |
"milliseconds" | |
]; | |
var reverseUnits = orderedUnits$1.slice(0).reverse(); | |
function clone$1(dur, alts, clear = false) { | |
const conf = { | |
values: clear ? alts.values : { ...dur.values, ...alts.values || {} }, | |
loc: dur.loc.clone(alts.loc), | |
conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy, | |
matrix: alts.matrix || dur.matrix | |
}; | |
return new Duration(conf); | |
} | |
function antiTrunc(n2) { | |
return n2 < 0 ? Math.floor(n2) : Math.ceil(n2); | |
} | |
function convert(matrix, fromMap, fromUnit, toMap, toUnit) { | |
const conv = matrix[toUnit][fromUnit], raw = fromMap[fromUnit] / conv, sameSign = Math.sign(raw) === Math.sign(toMap[toUnit]), added = !sameSign && toMap[toUnit] !== 0 && Math.abs(raw) <= 1 ? antiTrunc(raw) : Math.trunc(raw); | |
toMap[toUnit] += added; | |
fromMap[fromUnit] -= added * conv; | |
} | |
function normalizeValues(matrix, vals) { | |
reverseUnits.reduce((previous, current) => { | |
if (!isUndefined(vals[current])) { | |
if (previous) { | |
convert(matrix, vals, previous, vals, current); | |
} | |
return current; | |
} else { | |
return previous; | |
} | |
}, null); | |
} | |
function removeZeroes(vals) { | |
const newVals = {}; | |
for (const [key, value] of Object.entries(vals)) { | |
if (value !== 0) { | |
newVals[key] = value; | |
} | |
} | |
return newVals; | |
} | |
var Duration = class { | |
/** | |
* @private | |
*/ | |
constructor(config) { | |
const accurate = config.conversionAccuracy === "longterm" || false; | |
let matrix = accurate ? accurateMatrix : casualMatrix; | |
if (config.matrix) { | |
matrix = config.matrix; | |
} | |
this.values = config.values; | |
this.loc = config.loc || Locale.create(); | |
this.conversionAccuracy = accurate ? "longterm" : "casual"; | |
this.invalid = config.invalid || null; | |
this.matrix = matrix; | |
this.isLuxonDuration = true; | |
} | |
/** | |
* Create Duration from a number of milliseconds. | |
* @param {number} count of milliseconds | |
* @param {Object} opts - options for parsing | |
* @param {string} [opts.locale='en-US'] - the locale to use | |
* @param {string} opts.numberingSystem - the numbering system to use | |
* @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use | |
* @return {Duration} | |
*/ | |
static fromMillis(count, opts) { | |
return Duration.fromObject({ milliseconds: count }, opts); | |
} | |
/** | |
* Create a Duration from a JavaScript object with keys like 'years' and 'hours'. | |
* If this object is empty then a zero milliseconds duration is returned. | |
* @param {Object} obj - the object to create the DateTime from | |
* @param {number} obj.years | |
* @param {number} obj.quarters | |
* @param {number} obj.months | |
* @param {number} obj.weeks | |
* @param {number} obj.days | |
* @param {number} obj.hours | |
* @param {number} obj.minutes | |
* @param {number} obj.seconds | |
* @param {number} obj.milliseconds | |
* @param {Object} [opts=[]] - options for creating this Duration | |
* @param {string} [opts.locale='en-US'] - the locale to use | |
* @param {string} opts.numberingSystem - the numbering system to use | |
* @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use | |
* @param {string} [opts.matrix=Object] - the custom conversion system to use | |
* @return {Duration} | |
*/ | |
static fromObject(obj, opts = {}) { | |
if (obj == null || typeof obj !== "object") { | |
throw new InvalidArgumentError( | |
`Duration.fromObject: argument expected to be an object, got ${obj === null ? "null" : typeof obj}` | |
); | |
} | |
return new Duration({ | |
values: normalizeObject(obj, Duration.normalizeUnit), | |
loc: Locale.fromObject(opts), | |
conversionAccuracy: opts.conversionAccuracy, | |
matrix: opts.matrix | |
}); | |
} | |
/** | |
* Create a Duration from DurationLike. | |
* | |
* @param {Object | number | Duration} durationLike | |
* One of: | |
* - object with keys like 'years' and 'hours'. | |
* - number representing milliseconds | |
* - Duration instance | |
* @return {Duration} | |
*/ | |
static fromDurationLike(durationLike) { | |
if (isNumber(durationLike)) { | |
return Duration.fromMillis(durationLike); | |
} else if (Duration.isDuration(durationLike)) { | |
return durationLike; | |
} else if (typeof durationLike === "object") { | |
return Duration.fromObject(durationLike); | |
} else { | |
throw new InvalidArgumentError( | |
`Unknown duration argument ${durationLike} of type ${typeof durationLike}` | |
); | |
} | |
} | |
/** | |
* Create a Duration from an ISO 8601 duration string. | |
* @param {string} text - text to parse | |
* @param {Object} opts - options for parsing | |
* @param {string} [opts.locale='en-US'] - the locale to use | |
* @param {string} opts.numberingSystem - the numbering system to use | |
* @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use | |
* @param {string} [opts.matrix=Object] - the preset conversion system to use | |
* @see https://en.wikipedia.org/wiki/ISO_8601#Durations | |
* @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 } | |
* @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 } | |
* @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 } | |
* @return {Duration} | |
*/ | |
static fromISO(text, opts) { | |
const [parsed] = parseISODuration(text); | |
if (parsed) { | |
return Duration.fromObject(parsed, opts); | |
} else { | |
return Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`); | |
} | |
} | |
/** | |
* Create a Duration from an ISO 8601 time string. | |
* @param {string} text - text to parse | |
* @param {Object} opts - options for parsing | |
* @param {string} [opts.locale='en-US'] - the locale to use | |
* @param {string} opts.numberingSystem - the numbering system to use | |
* @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use | |
* @param {string} [opts.matrix=Object] - the conversion system to use | |
* @see https://en.wikipedia.org/wiki/ISO_8601#Times | |
* @example Duration.fromISOTime('11:22:33.444').toObject() //=> { hours: 11, minutes: 22, seconds: 33, milliseconds: 444 } | |
* @example Duration.fromISOTime('11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } | |
* @example Duration.fromISOTime('T11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } | |
* @example Duration.fromISOTime('1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } | |
* @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } | |
* @return {Duration} | |
*/ | |
static fromISOTime(text, opts) { | |
const [parsed] = parseISOTimeOnly(text); | |
if (parsed) { | |
return Duration.fromObject(parsed, opts); | |
} else { | |
return Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`); | |
} | |
} | |
/** | |
* Create an invalid Duration. | |
* @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent | |
* @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information | |
* @return {Duration} | |
*/ | |
static invalid(reason, explanation = null) { | |
if (!reason) { | |
throw new InvalidArgumentError("need to specify a reason the Duration is invalid"); | |
} | |
const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); | |
if (Settings.throwOnInvalid) { | |
throw new InvalidDurationError(invalid); | |
} else { | |
return new Duration({ invalid }); | |
} | |
} | |
/** | |
* @private | |
*/ | |
static normalizeUnit(unit) { | |
const normalized = { | |
year: "years", | |
years: "years", | |
quarter: "quarters", | |
quarters: "quarters", | |
month: "months", | |
months: "months", | |
week: "weeks", | |
weeks: "weeks", | |
day: "days", | |
days: "days", | |
hour: "hours", | |
hours: "hours", | |
minute: "minutes", | |
minutes: "minutes", | |
second: "seconds", | |
seconds: "seconds", | |
millisecond: "milliseconds", | |
milliseconds: "milliseconds" | |
}[unit ? unit.toLowerCase() : unit]; | |
if (!normalized) | |
throw new InvalidUnitError(unit); | |
return normalized; | |
} | |
/** | |
* Check if an object is a Duration. Works across context boundaries | |
* @param {object} o | |
* @return {boolean} | |
*/ | |
static isDuration(o) { | |
return o && o.isLuxonDuration || false; | |
} | |
/** | |
* Get the locale of a Duration, such 'en-GB' | |
* @type {string} | |
*/ | |
get locale() { | |
return this.isValid ? this.loc.locale : null; | |
} | |
/** | |
* Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration | |
* | |
* @type {string} | |
*/ | |
get numberingSystem() { | |
return this.isValid ? this.loc.numberingSystem : null; | |
} | |
/** | |
* Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens: | |
* * `S` for milliseconds | |
* * `s` for seconds | |
* * `m` for minutes | |
* * `h` for hours | |
* * `d` for days | |
* * `w` for weeks | |
* * `M` for months | |
* * `y` for years | |
* Notes: | |
* * Add padding by repeating the token, e.g. "yy" pads the years to two digits, "hhhh" pads the hours out to four digits | |
* * Tokens can be escaped by wrapping with single quotes. | |
* * The duration will be converted to the set of units in the format string using {@link Duration#shiftTo} and the Durations's conversion accuracy setting. | |
* @param {string} fmt - the format string | |
* @param {Object} opts - options | |
* @param {boolean} [opts.floor=true] - floor numerical values | |
* @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("y d s") //=> "1 6 2" | |
* @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("yy dd sss") //=> "01 06 002" | |
* @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("M S") //=> "12 518402000" | |
* @return {string} | |
*/ | |
toFormat(fmt, opts = {}) { | |
const fmtOpts = { | |
...opts, | |
floor: opts.round !== false && opts.floor !== false | |
}; | |
return this.isValid ? Formatter2.create(this.loc, fmtOpts).formatDurationFromString(this, fmt) : INVALID$2; | |
} | |
/** | |
* Returns a string representation of a Duration with all units included. | |
* To modify its behavior use the `listStyle` and any Intl.NumberFormat option, though `unitDisplay` is especially relevant. | |
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat | |
* @param opts - On option object to override the formatting. Accepts the same keys as the options parameter of the native `Int.NumberFormat` constructor, as well as `listStyle`. | |
* @example | |
* ```js | |
* var dur = Duration.fromObject({ days: 1, hours: 5, minutes: 6 }) | |
* dur.toHuman() //=> '1 day, 5 hours, 6 minutes' | |
* dur.toHuman({ listStyle: "long" }) //=> '1 day, 5 hours, and 6 minutes' | |
* dur.toHuman({ unitDisplay: "short" }) //=> '1 day, 5 hr, 6 min' | |
* ``` | |
*/ | |
toHuman(opts = {}) { | |
const l2 = orderedUnits$1.map((unit) => { | |
const val = this.values[unit]; | |
if (isUndefined(val)) { | |
return null; | |
} | |
return this.loc.numberFormatter({ style: "unit", unitDisplay: "long", ...opts, unit: unit.slice(0, -1) }).format(val); | |
}).filter((n2) => n2); | |
return this.loc.listFormatter({ type: "conjunction", style: opts.listStyle || "narrow", ...opts }).format(l2); | |
} | |
/** | |
* Returns a JavaScript object with this Duration's values. | |
* @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 } | |
* @return {Object} | |
*/ | |
toObject() { | |
if (!this.isValid) | |
return {}; | |
return { ...this.values }; | |
} | |
/** | |
* Returns an ISO 8601-compliant string representation of this Duration. | |
* @see https://en.wikipedia.org/wiki/ISO_8601#Durations | |
* @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S' | |
* @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S' | |
* @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M' | |
* @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M' | |
* @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S' | |
* @return {string} | |
*/ | |
toISO() { | |
if (!this.isValid) | |
return null; | |
let s2 = "P"; | |
if (this.years !== 0) | |
s2 += this.years + "Y"; | |
if (this.months !== 0 || this.quarters !== 0) | |
s2 += this.months + this.quarters * 3 + "M"; | |
if (this.weeks !== 0) | |
s2 += this.weeks + "W"; | |
if (this.days !== 0) | |
s2 += this.days + "D"; | |
if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0) | |
s2 += "T"; | |
if (this.hours !== 0) | |
s2 += this.hours + "H"; | |
if (this.minutes !== 0) | |
s2 += this.minutes + "M"; | |
if (this.seconds !== 0 || this.milliseconds !== 0) | |
s2 += roundTo(this.seconds + this.milliseconds / 1e3, 3) + "S"; | |
if (s2 === "P") | |
s2 += "T0S"; | |
return s2; | |
} | |
/** | |
* Returns an ISO 8601-compliant string representation of this Duration, formatted as a time of day. | |
* Note that this will return null if the duration is invalid, negative, or equal to or greater than 24 hours. | |
* @see https://en.wikipedia.org/wiki/ISO_8601#Times | |
* @param {Object} opts - options | |
* @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 | |
* @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 | |
* @param {boolean} [opts.includePrefix=false] - include the `T` prefix | |
* @param {string} [opts.format='extended'] - choose between the basic and extended format | |
* @example Duration.fromObject({ hours: 11 }).toISOTime() //=> '11:00:00.000' | |
* @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressMilliseconds: true }) //=> '11:00:00' | |
* @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressSeconds: true }) //=> '11:00' | |
* @example Duration.fromObject({ hours: 11 }).toISOTime({ includePrefix: true }) //=> 'T11:00:00.000' | |
* @example Duration.fromObject({ hours: 11 }).toISOTime({ format: 'basic' }) //=> '110000.000' | |
* @return {string} | |
*/ | |
toISOTime(opts = {}) { | |
if (!this.isValid) | |
return null; | |
const millis = this.toMillis(); | |
if (millis < 0 || millis >= 864e5) | |
return null; | |
opts = { | |
suppressMilliseconds: false, | |
suppressSeconds: false, | |
includePrefix: false, | |
format: "extended", | |
...opts | |
}; | |
const value = this.shiftTo("hours", "minutes", "seconds", "milliseconds"); | |
let fmt = opts.format === "basic" ? "hhmm" : "hh:mm"; | |
if (!opts.suppressSeconds || value.seconds !== 0 || value.milliseconds !== 0) { | |
fmt += opts.format === "basic" ? "ss" : ":ss"; | |
if (!opts.suppressMilliseconds || value.milliseconds !== 0) { | |
fmt += ".SSS"; | |
} | |
} | |
let str = value.toFormat(fmt); | |
if (opts.includePrefix) { | |
str = "T" + str; | |
} | |
return str; | |
} | |
/** | |
* Returns an ISO 8601 representation of this Duration appropriate for use in JSON. | |
* @return {string} | |
*/ | |
toJSON() { | |
return this.toISO(); | |
} | |
/** | |
* Returns an ISO 8601 representation of this Duration appropriate for use in debugging. | |
* @return {string} | |
*/ | |
toString() { | |
return this.toISO(); | |
} | |
/** | |
* Returns an milliseconds value of this Duration. | |
* @return {number} | |
*/ | |
toMillis() { | |
return this.as("milliseconds"); | |
} | |
/** | |
* Returns an milliseconds value of this Duration. Alias of {@link toMillis} | |
* @return {number} | |
*/ | |
valueOf() { | |
return this.toMillis(); | |
} | |
/** | |
* Make this Duration longer by the specified amount. Return a newly-constructed Duration. | |
* @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() | |
* @return {Duration} | |
*/ | |
plus(duration) { | |
if (!this.isValid) | |
return this; | |
const dur = Duration.fromDurationLike(duration), result = {}; | |
for (const k of orderedUnits$1) { | |
if (hasOwnProperty(dur.values, k) || hasOwnProperty(this.values, k)) { | |
result[k] = dur.get(k) + this.get(k); | |
} | |
} | |
return clone$1(this, { values: result }, true); | |
} | |
/** | |
* Make this Duration shorter by the specified amount. Return a newly-constructed Duration. | |
* @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() | |
* @return {Duration} | |
*/ | |
minus(duration) { | |
if (!this.isValid) | |
return this; | |
const dur = Duration.fromDurationLike(duration); | |
return this.plus(dur.negate()); | |
} | |
/** | |
* Scale this Duration by the specified amount. Return a newly-constructed Duration. | |
* @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number. | |
* @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits(x => x * 2) //=> { hours: 2, minutes: 60 } | |
* @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits((x, u) => u === "hours" ? x * 2 : x) //=> { hours: 2, minutes: 30 } | |
* @return {Duration} | |
*/ | |
mapUnits(fn) { | |
if (!this.isValid) | |
return this; | |
const result = {}; | |
for (const k of Object.keys(this.values)) { | |
result[k] = asNumber(fn(this.values[k], k)); | |
} | |
return clone$1(this, { values: result }, true); | |
} | |
/** | |
* Get the value of unit. | |
* @param {string} unit - a unit such as 'minute' or 'day' | |
* @example Duration.fromObject({years: 2, days: 3}).get('years') //=> 2 | |
* @example Duration.fromObject({years: 2, days: 3}).get('months') //=> 0 | |
* @example Duration.fromObject({years: 2, days: 3}).get('days') //=> 3 | |
* @return {number} | |
*/ | |
get(unit) { | |
return this[Duration.normalizeUnit(unit)]; | |
} | |
/** | |
* "Set" the values of specified units. Return a newly-constructed Duration. | |
* @param {Object} values - a mapping of units to numbers | |
* @example dur.set({ years: 2017 }) | |
* @example dur.set({ hours: 8, minutes: 30 }) | |
* @return {Duration} | |
*/ | |
set(values) { | |
if (!this.isValid) | |
return this; | |
const mixed = { ...this.values, ...normalizeObject(values, Duration.normalizeUnit) }; | |
return clone$1(this, { values: mixed }); | |
} | |
/** | |
* "Set" the locale and/or numberingSystem. Returns a newly-constructed Duration. | |
* @example dur.reconfigure({ locale: 'en-GB' }) | |
* @return {Duration} | |
*/ | |
reconfigure({ locale, numberingSystem, conversionAccuracy, matrix } = {}) { | |
const loc = this.loc.clone({ locale, numberingSystem }); | |
const opts = { loc, matrix, conversionAccuracy }; | |
return clone$1(this, opts); | |
} | |
/** | |
* Return the length of the duration in the specified unit. | |
* @param {string} unit - a unit such as 'minutes' or 'days' | |
* @example Duration.fromObject({years: 1}).as('days') //=> 365 | |
* @example Duration.fromObject({years: 1}).as('months') //=> 12 | |
* @example Duration.fromObject({hours: 60}).as('days') //=> 2.5 | |
* @return {number} | |
*/ | |
as(unit) { | |
return this.isValid ? this.shiftTo(unit).get(unit) : NaN; | |
} | |
/** | |
* Reduce this Duration to its canonical representation in its current units. | |
* @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 } | |
* @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 } | |
* @return {Duration} | |
*/ | |
normalize() { | |
if (!this.isValid) | |
return this; | |
const vals = this.toObject(); | |
normalizeValues(this.matrix, vals); | |
return clone$1(this, { values: vals }, true); | |
} | |
/** | |
* Rescale units to its largest representation | |
* @example Duration.fromObject({ milliseconds: 90000 }).rescale().toObject() //=> { minutes: 1, seconds: 30 } | |
* @return {Duration} | |
*/ | |
rescale() { | |
if (!this.isValid) | |
return this; | |
const vals = removeZeroes(this.normalize().shiftToAll().toObject()); | |
return clone$1(this, { values: vals }, true); | |
} | |
/** | |
* Convert this Duration into its representation in a different set of units. | |
* @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 } | |
* @return {Duration} | |
*/ | |
shiftTo(...units) { | |
if (!this.isValid) | |
return this; | |
if (units.length === 0) { | |
return this; | |
} | |
units = units.map((u) => Duration.normalizeUnit(u)); | |
const built = {}, accumulated = {}, vals = this.toObject(); | |
let lastUnit; | |
for (const k of orderedUnits$1) { | |
if (units.indexOf(k) >= 0) { | |
lastUnit = k; | |
let own = 0; | |
for (const ak in accumulated) { | |
own += this.matrix[ak][k] * accumulated[ak]; | |
accumulated[ak] = 0; | |
} | |
if (isNumber(vals[k])) { | |
own += vals[k]; | |
} | |
const i = Math.trunc(own); | |
built[k] = i; | |
accumulated[k] = (own * 1e3 - i * 1e3) / 1e3; | |
for (const down in vals) { | |
if (orderedUnits$1.indexOf(down) > orderedUnits$1.indexOf(k)) { | |
convert(this.matrix, vals, down, built, k); | |
} | |
} | |
} else if (isNumber(vals[k])) { | |
accumulated[k] = vals[k]; | |
} | |
} | |
for (const key in accumulated) { | |
if (accumulated[key] !== 0) { | |
built[lastUnit] += key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key]; | |
} | |
} | |
return clone$1(this, { values: built }, true).normalize(); | |
} | |
/** | |
* Shift this Duration to all available units. | |
* Same as shiftTo("years", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds") | |
* @return {Duration} | |
*/ | |
shiftToAll() { | |
if (!this.isValid) | |
return this; | |
return this.shiftTo( | |
"years", | |
"months", | |
"weeks", | |
"days", | |
"hours", | |
"minutes", | |
"seconds", | |
"milliseconds" | |
); | |
} | |
/** | |
* Return the negative of this Duration. | |
* @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 } | |
* @return {Duration} | |
*/ | |
negate() { | |
if (!this.isValid) | |
return this; | |
const negated = {}; | |
for (const k of Object.keys(this.values)) { | |
negated[k] = this.values[k] === 0 ? 0 : -this.values[k]; | |
} | |
return clone$1(this, { values: negated }, true); | |
} | |
/** | |
* Get the years. | |
* @type {number} | |
*/ | |
get years() { | |
return this.isValid ? this.values.years || 0 : NaN; | |
} | |
/** | |
* Get the quarters. | |
* @type {number} | |
*/ | |
get quarters() { | |
return this.isValid ? this.values.quarters || 0 : NaN; | |
} | |
/** | |
* Get the months. | |
* @type {number} | |
*/ | |
get months() { | |
return this.isValid ? this.values.months || 0 : NaN; | |
} | |
/** | |
* Get the weeks | |
* @type {number} | |
*/ | |
get weeks() { | |
return this.isValid ? this.values.weeks || 0 : NaN; | |
} | |
/** | |
* Get the days. | |
* @type {number} | |
*/ | |
get days() { | |
return this.isValid ? this.values.days || 0 : NaN; | |
} | |
/** | |
* Get the hours. | |
* @type {number} | |
*/ | |
get hours() { | |
return this.isValid ? this.values.hours || 0 : NaN; | |
} | |
/** | |
* Get the minutes. | |
* @type {number} | |
*/ | |
get minutes() { | |
return this.isValid ? this.values.minutes || 0 : NaN; | |
} | |
/** | |
* Get the seconds. | |
* @return {number} | |
*/ | |
get seconds() { | |
return this.isValid ? this.values.seconds || 0 : NaN; | |
} | |
/** | |
* Get the milliseconds. | |
* @return {number} | |
*/ | |
get milliseconds() { | |
return this.isValid ? this.values.milliseconds || 0 : NaN; | |
} | |
/** | |
* Returns whether the Duration is invalid. Invalid durations are returned by diff operations | |
* on invalid DateTimes or Intervals. | |
* @return {boolean} | |
*/ | |
get isValid() { | |
return this.invalid === null; | |
} | |
/** | |
* Returns an error code if this Duration became invalid, or null if the Duration is valid | |
* @return {string} | |
*/ | |
get invalidReason() { | |
return this.invalid ? this.invalid.reason : null; | |
} | |
/** | |
* Returns an explanation of why this Duration became invalid, or null if the Duration is valid | |
* @type {string} | |
*/ | |
get invalidExplanation() { | |
return this.invalid ? this.invalid.explanation : null; | |
} | |
/** | |
* Equality check | |
* Two Durations are equal iff they have the same units and the same values for each unit. | |
* @param {Duration} other | |
* @return {boolean} | |
*/ | |
equals(other) { | |
if (!this.isValid || !other.isValid) { | |
return false; | |
} | |
if (!this.loc.equals(other.loc)) { | |
return false; | |
} | |
function eq(v1, v2) { | |
if (v1 === void 0 || v1 === 0) | |
return v2 === void 0 || v2 === 0; | |
return v1 === v2; | |
} | |
for (const u of orderedUnits$1) { | |
if (!eq(this.values[u], other.values[u])) { | |
return false; | |
} | |
} | |
return true; | |
} | |
}; | |
var INVALID$1 = "Invalid Interval"; | |
function validateStartEnd(start, end) { | |
if (!start || !start.isValid) { | |
return Interval.invalid("missing or invalid start"); | |
} else if (!end || !end.isValid) { | |
return Interval.invalid("missing or invalid end"); | |
} else if (end < start) { | |
return Interval.invalid( | |
"end before start", | |
`The end of an interval must be after its start, but you had start=${start.toISO()} and end=${end.toISO()}` | |
); | |
} else { | |
return null; | |
} | |
} | |
var Interval = class { | |
/** | |
* @private | |
*/ | |
constructor(config) { | |
this.s = config.start; | |
this.e = config.end; | |
this.invalid = config.invalid || null; | |
this.isLuxonInterval = true; | |
} | |
/** | |
* Create an invalid Interval. | |
* @param {string} reason - simple string of why this Interval is invalid. Should not contain parameters or anything else data-dependent | |
* @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information | |
* @return {Interval} | |
*/ | |
static invalid(reason, explanation = null) { | |
if (!reason) { | |
throw new InvalidArgumentError("need to specify a reason the Interval is invalid"); | |
} | |
const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); | |
if (Settings.throwOnInvalid) { | |
throw new InvalidIntervalError(invalid); | |
} else { | |
return new Interval({ invalid }); | |
} | |
} | |
/** | |
* Create an Interval from a start DateTime and an end DateTime. Inclusive of the start but not the end. | |
* @param {DateTime|Date|Object} start | |
* @param {DateTime|Date|Object} end | |
* @return {Interval} | |
*/ | |
static fromDateTimes(start, end) { | |
const builtStart = friendlyDateTime(start), builtEnd = friendlyDateTime(end); | |
const validateError = validateStartEnd(builtStart, builtEnd); | |
if (validateError == null) { | |
return new Interval({ | |
start: builtStart, | |
end: builtEnd | |
}); | |
} else { | |
return validateError; | |
} | |
} | |
/** | |
* Create an Interval from a start DateTime and a Duration to extend to. | |
* @param {DateTime|Date|Object} start | |
* @param {Duration|Object|number} duration - the length of the Interval. | |
* @return {Interval} | |
*/ | |
static after(start, duration) { | |
const dur = Duration.fromDurationLike(duration), 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); | |
return Interval.fromDateTimes(dt.minus(dur), dt); | |
} | |
/** | |
* Create an Interval from an ISO 8601 string. | |
* Accepts `<start>/<end>`, `<start>/<duration>`, and `<duration>/<end>` formats. | |
* @param {string} text - the ISO string to parse | |
* @param {Object} [opts] - options to pass {@link DateTime#fromISO} and optionally {@link Duration#fromISO} | |
* @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals | |
* @return {Interval} | |
*/ | |
static fromISO(text, opts) { | |
const [s2, e] = (text || "").split("/", 2); | |
if (s2 && e) { | |
let start, startIsValid; | |
try { | |
start = DateTime.fromISO(s2, opts); | |
startIsValid = start.isValid; | |
} catch (e2) { | |
startIsValid = false; | |
} | |
let end, endIsValid; | |
try { | |
end = DateTime.fromISO(e, opts); | |
endIsValid = end.isValid; | |
} catch (e2) { | |
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(s2, 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(unit = "milliseconds") { | |
return this.isValid ? this.toDuration(...[unit]).get(unit) : NaN; | |
} | |
/** | |
* Returns the count of minutes, hours, days, months, or years included in the Interval, even in part. | |
* Unlike {@link Interval#length} this counts sections of the calendar, not periods of time, e.g. specifying 'day' | |
* asks 'what dates are included in this interval?', not 'how many days long is this interval?' | |
* @param {string} [unit='milliseconds'] - the unit of time to count. | |
* @return {number} | |
*/ | |
count(unit = "milliseconds") { | |
if (!this.isValid) | |
return NaN; | |
const start = this.start.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 | |
* @param {DateTime} values.start - the starting DateTime | |
* @param {DateTime} values.end - the ending DateTime | |
* @return {Interval} | |
*/ | |
set({ start, 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(...dateTimes) { | |
if (!this.isValid) | |
return []; | |
const sorted = dateTimes.map(friendlyDateTime).filter((d) => this.contains(d)).sort(), results = []; | |
let { s: s2 } = this, i = 0; | |
while (s2 < this.e) { | |
const added = sorted[i] || this.e, next = +added > +this.e ? this.e : added; | |
results.push(Interval.fromDateTimes(s2, next)); | |
s2 = next; | |
i += 1; | |
} | |
return results; | |
} | |
/** | |
* Split this Interval into smaller Intervals, each of the specified length. | |
* Left over time is grouped into a smaller interval | |
* @param {Duration|Object|number} duration - The length of each resulting interval. | |
* @return {Array} | |
*/ | |
splitBy(duration) { | |
const dur = Duration.fromDurationLike(duration); | |
if (!this.isValid || !dur.isValid || dur.as("milliseconds") === 0) { | |
return []; | |
} | |
let { s: s2 } = this, idx = 1, next; | |
const results = []; | |
while (s2 < this.e) { | |
const added = this.start.plus(dur.mapUnits((x) => x * idx)); | |
next = +added > +this.e ? this.e : added; | |
results.push(Interval.fromDateTimes(s2, next)); | |
s2 = next; | |
idx += 1; | |
} | |
return results; | |
} | |
/** | |
* Split this Interval into the specified number of smaller intervals. | |
* @param {number} numberOfParts - The number of Intervals to divide the Interval into. | |
* @return {Array} | |
*/ | |
divideEqually(numberOfParts) { | |
if (!this.isValid) | |
return []; | |
return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts); | |
} | |
/** | |
* Return whether this Interval overlaps with the specified Interval | |
* @param {Interval} other | |
* @return {boolean} | |
*/ | |
overlaps(other) { | |
return this.e > other.s && this.s < other.e; | |
} | |
/** | |
* Return whether this Interval's end is adjacent to the specified Interval's start. | |
* @param {Interval} other | |
* @return {boolean} | |
*/ | |
abutsStart(other) { | |
if (!this.isValid) | |
return false; | |
return +this.e === +other.s; | |
} | |
/** | |
* Return whether this Interval's start is adjacent to the specified Interval's end. | |
* @param {Interval} other | |
* @return {boolean} | |
*/ | |
abutsEnd(other) { | |
if (!this.isValid) | |
return false; | |
return +other.e === +this.s; | |
} | |
/** | |
* Return whether this Interval engulfs the start and end of the specified Interval. | |
* @param {Interval} other | |
* @return {boolean} | |
*/ | |
engulfs(other) { | |
if (!this.isValid) | |
return false; | |
return this.s <= other.s && this.e >= other.e; | |
} | |
/** | |
* Return whether this Interval has the same start and end as the specified Interval. | |
* @param {Interval} other | |
* @return {boolean} | |
*/ | |
equals(other) { | |
if (!this.isValid || !other.isValid) { | |
return false; | |
} | |
return this.s.equals(other.s) && this.e.equals(other.e); | |
} | |
/** | |
* Return an Interval representing the intersection of this Interval and the specified Interval. | |
* Specifically, the resulting Interval has the maximum start time and the minimum end time of the two Intervals. | |
* Returns null if the intersection is empty, meaning, the intervals don't intersect. | |
* @param {Interval} other | |
* @return {Interval} | |
*/ | |
intersection(other) { | |
if (!this.isValid) | |
return this; | |
const s2 = this.s > other.s ? this.s : other.s, e = this.e < other.e ? this.e : other.e; | |
if (s2 >= e) { | |
return null; | |
} else { | |
return Interval.fromDateTimes(s2, e); | |
} | |
} | |
/** | |
* Return an Interval representing the union of this Interval and the specified Interval. | |
* Specifically, the resulting Interval has the minimum start time and the maximum end time of the two Intervals. | |
* @param {Interval} other | |
* @return {Interval} | |
*/ | |
union(other) { | |
if (!this.isValid) | |
return this; | |
const s2 = this.s < other.s ? this.s : other.s, e = this.e > other.e ? this.e : other.e; | |
return Interval.fromDateTimes(s2, e); | |
} | |
/** | |
* Merge an array of Intervals into a equivalent minimal set of Intervals. | |
* Combines overlapping and adjacent Intervals. | |
* @param {Array} intervals | |
* @return {Array} | |
*/ | |
static merge(intervals) { | |
const [found, final] = intervals.sort((a, b) => a.s - b.s).reduce( | |
([sofar, current], item) => { | |
if (!current) { | |
return [sofar, item]; | |
} else if (current.overlaps(item) || current.abutsStart(item)) { | |
return [sofar, current.union(item)]; | |
} else { | |
return [sofar.concat([current]), item]; | |
} | |
}, | |
[[], null] | |
); | |
if (final) { | |
found.push(final); | |
} | |
return found; | |
} | |
/** | |
* Return an array of Intervals representing the spans of time that only appear in one of the specified Intervals. | |
* @param {Array} intervals | |
* @return {Array} | |
*/ | |
static xor(intervals) { | |
let start = null, currentCount = 0; | |
const results = [], ends = intervals.map((i) => [ | |
{ time: i.s, type: "s" }, | |
{ time: i.e, type: "e" } | |
]), flattened = Array.prototype.concat(...ends), arr = flattened.sort((a, b) => a.time - b.time); | |
for (const i of arr) { | |
currentCount += i.type === "s" ? 1 : -1; | |
if (currentCount === 1) { | |
start = i.time; | |
} else { | |
if (start && +start !== +i.time) { | |
results.push(Interval.fromDateTimes(start, i.time)); | |
} | |
start = null; | |
} | |
} | |
return Interval.merge(results); | |
} | |
/** | |
* Return an Interval representing the span of time in this Interval that doesn't overlap with any of the specified Intervals. | |
* @param {...Interval} intervals | |
* @return {Array} | |
*/ | |
difference(...intervals) { | |
return Interval.xor([this].concat(intervals)).map((i) => this.intersection(i)).filter((i) => i && !i.isEmpty()); | |
} | |
/** | |
* Returns a string representation of this Interval appropriate for debugging. | |
* @return {string} | |
*/ | |
toString() { | |
if (!this.isValid) | |
return INVALID$1; | |
return `[${this.s.toISO()} \u2013 ${this.e.toISO()})`; | |
} | |
/** | |
* Returns a localized string representing this Interval. Accepts the same options as the | |
* Intl.DateTimeFormat constructor and any presets defined by Luxon, such as | |
* {@link DateTime.DATE_FULL} or {@link DateTime.TIME_SIMPLE}. The exact behavior of this method | |
* is browser-specific, but in general it will return an appropriate representation of the | |
* Interval in the assigned locale. Defaults to the system's locale if no locale has been | |
* specified. | |
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat | |
* @param {Object} [formatOpts=DateTime.DATE_SHORT] - Either a DateTime preset or | |
* Intl.DateTimeFormat constructor options. | |
* @param {Object} opts - Options to override the configuration of the start DateTime. | |
* @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(); //=> 11/7/2022 – 11/8/2022 | |
* @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL); //=> November 7 – 8, 2022 | |
* @example Interval.fromISO('2022-11-07T09:00Z/2022-11-08T09:00Z').toLocaleString(DateTime.DATE_FULL, { locale: 'fr-FR' }); //=> 7–8 novembre 2022 | |
* @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString(DateTime.TIME_SIMPLE); //=> 6:00 – 8:00 PM | |
* @example Interval.fromISO('2022-11-07T17:00Z/2022-11-07T19:00Z').toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> Mon, Nov 07, 6:00 – 8:00 p | |
* @return {string} | |
*/ | |
toLocaleString(formatOpts = DATE_SHORT, opts = {}) { | |
return this.isValid ? Formatter2.create(this.s.loc.clone(opts), formatOpts).formatInterval(this) : INVALID$1; | |
} | |
/** | |
* Returns an ISO 8601-compliant string representation of this Interval. | |
* @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals | |
* @param {Object} opts - The same options as {@link DateTime#toISO} | |
* @return {string} | |
*/ | |
toISO(opts) { | |
if (!this.isValid) | |
return INVALID$1; | |
return `${this.s.toISO(opts)}/${this.e.toISO(opts)}`; | |
} | |
/** | |
* Returns an ISO 8601-compliant string representation of date of this Interval. | |
* The time components are ignored. | |
* @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals | |
* @return {string} | |
*/ | |
toISODate() { | |
if (!this.isValid) | |
return INVALID$1; | |
return `${this.s.toISODate()}/${this.e.toISODate()}`; | |
} | |
/** | |
* Returns an ISO 8601-compliant string representation of time of this Interval. | |
* The date components are ignored. | |
* @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals | |
* @param {Object} opts - The same options as {@link DateTime#toISO} | |
* @return {string} | |
*/ | |
toISOTime(opts) { | |
if (!this.isValid) | |
return INVALID$1; | |
return `${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`; | |
} | |
/** | |
* Returns a string representation of this Interval formatted according to the specified format | |
* string. **You may not want this.** See {@link Interval#toLocaleString} for a more flexible | |
* formatting tool. | |
* @param {string} dateFormat - The format string. This string formats the start and end time. | |
* See {@link DateTime#toFormat} for details. | |
* @param {Object} opts - Options. | |
* @param {string} [opts.separator = ' – '] - A separator to place between the start and end | |
* representations. | |
* @return {string} | |
*/ | |
toFormat(dateFormat, { separator = " \u2013 " } = {}) { | |
if (!this.isValid) | |
return INVALID$1; | |
return `${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`; | |
} | |
/** | |
* Return a Duration representing the time spanned by this interval. | |
* @param {string|string[]} [unit=['milliseconds']] - the unit or units (such as 'hours' or 'days') to include in the duration. | |
* @param {Object} opts - options that affect the creation of the Duration | |
* @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use | |
* @example Interval.fromDateTimes(dt1, dt2).toDuration().toObject() //=> { milliseconds: 88489257 } | |
* @example Interval.fromDateTimes(dt1, dt2).toDuration('days').toObject() //=> { days: 1.0241812152777778 } | |
* @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes']).toObject() //=> { hours: 24, minutes: 34.82095 } | |
* @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes', 'seconds']).toObject() //=> { hours: 24, minutes: 34, seconds: 49.257 } | |
* @example Interval.fromDateTimes(dt1, dt2).toDuration('seconds').toObject() //=> { seconds: 88489.257 } | |
* @return {Duration} | |
*/ | |
toDuration(unit, opts) { | |
if (!this.isValid) { | |
return Duration.invalid(this.invalidReason); | |
} | |
return this.e.diff(this.s, unit, opts); | |
} | |
/** | |
* Run mapFn on the interval start and end, returning a new Interval from the resulting DateTimes | |
* @param {function} mapFn | |
* @return {Interval} | |
* @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.toUTC()) | |
* @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.plus({ hours: 2 })) | |
*/ | |
mapEndpoints(mapFn) { | |
return Interval.fromDateTimes(mapFn(this.s), mapFn(this.e)); | |
} | |
}; | |
var Info = class { | |
/** | |
* Return whether the specified zone contains a DST. | |
* @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone. | |
* @return {boolean} | |
*/ | |
static hasDST(zone = Settings.defaultZone) { | |
const proto = DateTime.now().setZone(zone).set({ month: 12 }); | |
return !zone.isUniversal && proto.offset !== proto.set({ month: 6 }).offset; | |
} | |
/** | |
* Return whether the specified zone is a valid IANA specifier. | |
* @param {string} zone - Zone to check | |
* @return {boolean} | |
*/ | |
static isValidIANAZone(zone) { | |
return IANAZone.isValidZone(zone); | |
} | |
/** | |
* Converts the input into a {@link Zone} instance. | |
* | |
* * If `input` is already a Zone instance, it is returned unchanged. | |
* * If `input` is a string containing a valid time zone name, a Zone instance | |
* with that name is returned. | |
* * If `input` is a string that doesn't refer to a known time zone, a Zone | |
* instance with {@link Zone#isValid} == false is returned. | |
* * If `input is a number, a Zone instance with the specified fixed offset | |
* in minutes is returned. | |
* * If `input` is `null` or `undefined`, the default zone is returned. | |
* @param {string|Zone|number} [input] - the value to be converted | |
* @return {Zone} | |
*/ | |
static normalizeZone(input) { | |
return normalizeZone(input, Settings.defaultZone); | |
} | |
/** | |
* Return an array of standalone month names. | |
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat | |
* @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long" | |
* @param {Object} opts - options | |
* @param {string} [opts.locale] - the locale code | |
* @param {string} [opts.numberingSystem=null] - the numbering system | |
* @param {string} [opts.locObj=null] - an existing locale object to use | |
* @param {string} [opts.outputCalendar='gregory'] - the calendar | |
* @example Info.months()[0] //=> 'January' | |
* @example Info.months('short')[0] //=> 'Jan' | |
* @example Info.months('numeric')[0] //=> '1' | |
* @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.' | |
* @example Info.months('numeric', { locale: 'ar' })[0] //=> '١' | |
* @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I' | |
* @return {Array} | |
*/ | |
static months(length = "long", { locale = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {}) { | |
return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length); | |
} | |
/** | |
* Return an array of format month names. | |
* Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that | |
* changes the string. | |
* See {@link Info#months} | |
* @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long" | |
* @param {Object} opts - options | |
* @param {string} [opts.locale] - the locale code | |
* @param {string} [opts.numberingSystem=null] - the numbering system | |
* @param {string} [opts.locObj=null] - an existing locale object to use | |
* @param {string} [opts.outputCalendar='gregory'] - the calendar | |
* @return {Array} | |
*/ | |
static monthsFormat(length = "long", { locale = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {}) { | |
return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length, true); | |
} | |
/** | |
* Return an array of standalone week names. | |
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat | |
* @param {string} [length='long'] - the length of the weekday representation, such as "narrow", "short", "long". | |
* @param {Object} opts - options | |
* @param {string} [opts.locale] - the locale code | |
* @param {string} [opts.numberingSystem=null] - the numbering system | |
* @param {string} [opts.locObj=null] - an existing locale object to use | |
* @example Info.weekdays()[0] //=> 'Monday' | |
* @example Info.weekdays('short')[0] //=> 'Mon' | |
* @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.' | |
* @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين' | |
* @return {Array} | |
*/ | |
static weekdays(length = "long", { locale = null, numberingSystem = null, locObj = null } = {}) { | |
return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length); | |
} | |
/** | |
* Return an array of format week names. | |
* Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that | |
* changes the string. | |
* See {@link Info#weekdays} | |
* @param {string} [length='long'] - the length of the month representation, such as "narrow", "short", "long". | |
* @param {Object} opts - options | |
* @param {string} [opts.locale=null] - the locale code | |
* @param {string} [opts.numberingSystem=null] - the numbering system | |
* @param {string} [opts.locObj=null] - an existing locale object to use | |
* @return {Array} | |
*/ | |
static weekdaysFormat(length = "long", { locale = null, numberingSystem = null, locObj = null } = {}) { | |
return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length, true); | |
} | |
/** | |
* Return an array of meridiems. | |
* @param {Object} opts - options | |
* @param {string} [opts.locale] - the locale code | |
* @example Info.meridiems() //=> [ 'AM', 'PM' ] | |
* @example Info.meridiems({ locale: 'my' }) //=> [ 'နံနက်', 'ညနေ' ] | |
* @return {Array} | |
*/ | |
static meridiems({ locale = null } = {}) { | |
return Locale.create(locale).meridiems(); | |
} | |
/** | |
* Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian. | |
* @param {string} [length='short'] - the length of the era representation, such as "short" or "long". | |
* @param {Object} opts - options | |
* @param {string} [opts.locale] - the locale code | |
* @example Info.eras() //=> [ 'BC', 'AD' ] | |
* @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ] | |
* @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ] | |
* @return {Array} | |
*/ | |
static eras(length = "short", { locale = null } = {}) { | |
return Locale.create(locale, null, "gregory").eras(length); | |
} | |
/** | |
* Return the set of available features in this environment. | |
* Some features of Luxon are not available in all environments. For example, on older browsers, relative time formatting support is not available. Use this function to figure out if that's the case. | |
* Keys: | |
* * `relative`: whether this environment supports relative time formatting | |
* @example Info.features() //=> { relative: false } | |
* @return {Object} | |
*/ | |
static features() { | |
return { relative: hasRelative() }; | |
} | |
}; | |
function dayDiff(earlier, later) { | |
const utcDayStart = (dt) => dt.toUTC(0, { keepLocalTime: true }).startOf("day").valueOf(), ms = utcDayStart(later) - utcDayStart(earlier); | |
return Math.floor(Duration.fromMillis(ms).as("days")); | |
} | |
function highOrderDiffs(cursor, later, units) { | |
const differs = [ | |
["years", (a, b) => b.year - a.year], | |
["quarters", (a, b) => b.quarter - a.quarter + (b.year - a.year) * 4], | |
["months", (a, b) => b.month - a.month + (b.year - a.year) * 12], | |
[ | |
"weeks", | |
(a, b) => { | |
const days = dayDiff(a, b); | |
return (days - days % 7) / 7; | |
} | |
], | |
["days", dayDiff] | |
]; | |
const results = {}; | |
const earlier = cursor; | |
let lowestOrder, highWater; | |
for (const [unit, differ] of differs) { | |
if (units.indexOf(unit) >= 0) { | |
lowestOrder = unit; | |
results[unit] = differ(cursor, later); | |
highWater = earlier.plus(results); | |
if (highWater > later) { | |
results[unit]--; | |
cursor = earlier.plus(results); | |
} else { | |
cursor = highWater; | |
} | |
} | |
} | |
return [cursor, results, highWater, lowestOrder]; | |
} | |
function diff(earlier, later, units, opts) { | |
let [cursor, results, highWater, lowestOrder] = highOrderDiffs(earlier, later, units); | |
const remainingMillis = later - cursor; | |
const lowerOrderUnits = units.filter( | |
(u) => ["hours", "minutes", "seconds", "milliseconds"].indexOf(u) >= 0 | |
); | |
if (lowerOrderUnits.length === 0) { | |
if (highWater < later) { | |
highWater = cursor.plus({ [lowestOrder]: 1 }); | |
} | |
if (highWater !== cursor) { | |
results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor); | |
} | |
} | |
const duration = Duration.fromObject(results, opts); | |
if (lowerOrderUnits.length > 0) { | |
return Duration.fromMillis(remainingMillis, opts).shiftTo(...lowerOrderUnits).plus(duration); | |
} else { | |
return duration; | |
} | |
} | |
var numberingSystems = { | |
arab: "[\u0660-\u0669]", | |
arabext: "[\u06F0-\u06F9]", | |
bali: "[\u1B50-\u1B59]", | |
beng: "[\u09E6-\u09EF]", | |
deva: "[\u0966-\u096F]", | |
fullwide: "[\uFF10-\uFF19]", | |
gujr: "[\u0AE6-\u0AEF]", | |
hanidec: "[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]", | |
khmr: "[\u17E0-\u17E9]", | |
knda: "[\u0CE6-\u0CEF]", | |
laoo: "[\u0ED0-\u0ED9]", | |
limb: "[\u1946-\u194F]", | |
mlym: "[\u0D66-\u0D6F]", | |
mong: "[\u1810-\u1819]", | |
mymr: "[\u1040-\u1049]", | |
orya: "[\u0B66-\u0B6F]", | |
tamldec: "[\u0BE6-\u0BEF]", | |
telu: "[\u0C66-\u0C6F]", | |
thai: "[\u0E50-\u0E59]", | |
tibt: "[\u0F20-\u0F29]", | |
latn: "\\d" | |
}; | |
var numberingSystemsUTF16 = { | |
arab: [1632, 1641], | |
arabext: [1776, 1785], | |
bali: [6992, 7001], | |
beng: [2534, 2543], | |
deva: [2406, 2415], | |
fullwide: [65296, 65303], | |
gujr: [2790, 2799], | |
khmr: [6112, 6121], | |
knda: [3302, 3311], | |
laoo: [3792, 3801], | |
limb: [6470, 6479], | |
mlym: [3430, 3439], | |
mong: [6160, 6169], | |
mymr: [4160, 4169], | |
orya: [2918, 2927], | |
tamldec: [3046, 3055], | |
telu: [3174, 3183], | |
thai: [3664, 3673], | |
tibt: [3872, 3881] | |
}; | |
var hanidecChars = numberingSystems.hanidec.replace(/[\[|\]]/g, "").split(""); | |
function parseDigits(str) { | |
let value = parseInt(str, 10); | |
if (isNaN(value)) { | |
value = ""; | |
for (let i = 0; i < str.length; i++) { | |
const code = str.charCodeAt(i); | |
if (str[i].search(numberingSystems.hanidec) !== -1) { | |
value += hanidecChars.indexOf(str[i]); | |
} else { | |
for (const key in numberingSystemsUTF16) { | |
const [min, max] = numberingSystemsUTF16[key]; | |
if (code >= min && code <= max) { | |
value += code - min; | |
} | |
} | |
} | |
} | |
return parseInt(value, 10); | |
} else { | |
return value; | |
} | |
} | |
function digitRegex({ numberingSystem }, append = "") { | |
return new RegExp(`${numberingSystems[numberingSystem || "latn"]}${append}`); | |
} | |
var MISSING_FTP = "missing Intl.DateTimeFormat.formatToParts support"; | |
function intUnit(regex3, post = (i) => i) { | |
return { regex: regex3, deser: ([s2]) => post(parseDigits(s2)) }; | |
} | |
var NBSP = String.fromCharCode(160); | |
var spaceOrNBSP = `[ ${NBSP}]`; | |
var spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, "g"); | |
function fixListRegex(s2) { | |
return s2.replace(/\./g, "\\.?").replace(spaceOrNBSPRegExp, spaceOrNBSP); | |
} | |
function stripInsensitivities(s2) { | |
return s2.replace(/\./g, "").replace(spaceOrNBSPRegExp, " ").toLowerCase(); | |
} | |
function oneOf(strings, startIndex) { | |
if (strings === null) { | |
return null; | |
} else { | |
return { | |
regex: RegExp(strings.map(fixListRegex).join("|")), | |
deser: ([s2]) => strings.findIndex((i) => stripInsensitivities(s2) === stripInsensitivities(i)) + startIndex | |
}; | |
} | |
} | |
function offset(regex3, groups) { | |
return { regex: regex3, deser: ([, h, m]) => signedOffset(h, m), groups }; | |
} | |
function simple(regex3) { | |
return { regex: regex3, deser: ([s2]) => s2 }; | |
} | |
function escapeToken(value) { | |
return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); | |
} | |
function unitForToken(token, loc) { | |
const one = digitRegex(loc), two = digitRegex(loc, "{2}"), three = digitRegex(loc, "{3}"), four = digitRegex(loc, "{4}"), six = digitRegex(loc, "{6}"), oneOrTwo = digitRegex(loc, "{1,2}"), oneToThree = digitRegex(loc, "{1,3}"), oneToSix = digitRegex(loc, "{1,6}"), oneToNine = digitRegex(loc, "{1,9}"), twoToFour = digitRegex(loc, "{2,4}"), fourToSix = digitRegex(loc, "{4,6}"), literal = (t2) => ({ regex: RegExp(escapeToken(t2.val)), deser: ([s2]) => s2, literal: true }), unitate = (t2) => { | |
if (token.literal) { | |
return literal(t2); | |
} | |
switch (t2.val) { | |
case "G": | |
return oneOf(loc.eras("short", false), 0); | |
case "GG": | |
return oneOf(loc.eras("long", false), 0); | |
case "y": | |
return intUnit(oneToSix); | |
case "yy": | |
return intUnit(twoToFour, untruncateYear); | |
case "yyyy": | |
return intUnit(four); | |
case "yyyyy": | |
return intUnit(fourToSix); | |
case "yyyyyy": | |
return intUnit(six); | |
case "M": | |
return intUnit(oneOrTwo); | |
case "MM": | |
return intUnit(two); | |
case "MMM": | |
return oneOf(loc.months("short", true, false), 1); | |
case "MMMM": | |
return oneOf(loc.months("long", true, false), 1); | |
case "L": | |
return intUnit(oneOrTwo); | |
case "LL": | |
return intUnit(two); | |
case "LLL": | |
return oneOf(loc.months("short", false, false), 1); | |
case "LLLL": | |
return oneOf(loc.months("long", false, false), 1); | |
case "d": | |
return intUnit(oneOrTwo); | |
case "dd": | |
return intUnit(two); | |
case "o": | |
return intUnit(oneToThree); | |
case "ooo": | |
return intUnit(three); | |
case "HH": | |
return intUnit(two); | |
case "H": | |
return intUnit(oneOrTwo); | |
case "hh": | |
return intUnit(two); | |
case "h": | |
return intUnit(oneOrTwo); | |
case "mm": | |
return intUnit(two); | |
case "m": | |
return intUnit(oneOrTwo); | |
case "q": | |
return intUnit(oneOrTwo); | |
case "qq": | |
return intUnit(two); | |
case "s": | |
return intUnit(oneOrTwo); | |
case "ss": | |
return intUnit(two); | |
case "S": | |
return intUnit(oneToThree); | |
case "SSS": | |
return intUnit(three); | |
case "u": | |
return simple(oneToNine); | |
case "uu": | |
return simple(oneOrTwo); | |
case "uuu": | |
return intUnit(one); | |
case "a": | |
return oneOf(loc.meridiems(), 0); | |
case "kkkk": | |
return intUnit(four); | |
case "kk": | |
return intUnit(twoToFour, untruncateYear); | |
case "W": | |
return intUnit(oneOrTwo); | |
case "WW": | |
return intUnit(two); | |
case "E": | |
case "c": | |
return intUnit(one); | |
case "EEE": | |
return oneOf(loc.weekdays("short", false, false), 1); | |
case "EEEE": | |
return oneOf(loc.weekdays("long", false, false), 1); | |
case "ccc": | |
return oneOf(loc.weekdays("short", true, false), 1); | |
case "cccc": | |
return oneOf(loc.weekdays("long", true, false), 1); | |
case "Z": | |
case "ZZ": | |
return offset(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2); | |
case "ZZZ": | |
return offset(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2); | |
case "z": | |
return simple(/[a-z_+-/]{1,256}?/i); | |
default: | |
return literal(t2); | |
} | |
}; | |
const unit = unitate(token) || { | |
invalidReason: MISSING_FTP | |
}; | |
unit.token = token; | |
return unit; | |
} | |
var partTypeStyleToTokenVal = { | |
year: { | |
"2-digit": "yy", | |
numeric: "yyyyy" | |
}, | |
month: { | |
numeric: "M", | |
"2-digit": "MM", | |
short: "MMM", | |
long: "MMMM" | |
}, | |
day: { | |
numeric: "d", | |
"2-digit": "dd" | |
}, | |
weekday: { | |
short: "EEE", | |
long: "EEEE" | |
}, | |
dayperiod: "a", | |
dayPeriod: "a", | |
hour: { | |
numeric: "h", | |
"2-digit": "hh" | |
}, | |
minute: { | |
numeric: "m", | |
"2-digit": "mm" | |
}, | |
second: { | |
numeric: "s", | |
"2-digit": "ss" | |
}, | |
timeZoneName: { | |
long: "ZZZZZ", | |
short: "ZZZ" | |
} | |
}; | |
function tokenForPart(part, formatOpts) { | |
const { type, value } = part; | |
if (type === "literal") { | |
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 void 0; | |
} | |
function buildRegex(units) { | |
const re = units.map((u) => u.regex).reduce((f, r) => `${f}(${r.source})`, ""); | |
return [`^${re}$`, units]; | |
} | |
function match(input, regex3, handlers) { | |
const matches = input.match(regex3); | |
if (matches) { | |
const all = {}; | |
let matchIndex = 1; | |
for (const i in handlers) { | |
if (hasOwnProperty(handlers, i)) { | |
const h = handlers[i], groups = h.groups ? h.groups + 1 : 1; | |
if (!h.literal && h.token) { | |
all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups)); | |
} | |
matchIndex += groups; | |
} | |
} | |
return [matches, all]; | |
} else { | |
return [matches, {}]; | |
} | |
} | |
function dateTimeFromMatches(matches) { | |
const toField = (token) => { | |
switch (token) { | |
case "S": | |
return "millisecond"; | |
case "s": | |
return "second"; | |
case "m": | |
return "minute"; | |
case "h": | |
case "H": | |
return "hour"; | |
case "d": | |
return "day"; | |
case "o": | |
return "ordinal"; | |
case "L": | |
case "M": | |
return "month"; | |
case "y": | |
return "year"; | |
case "E": | |
case "c": | |
return "weekday"; | |
case "W": | |
return "weekNumber"; | |
case "k": | |
return "weekYear"; | |
case "q": | |
return "quarter"; | |
default: | |
return null; | |
} | |
}; | |
let zone = null; | |
let specificOffset; | |
if (!isUndefined(matches.z)) { | |
zone = IANAZone.create(matches.z); | |
} | |
if (!isUndefined(matches.Z)) { | |
if (!zone) { | |
zone = new FixedOffsetZone(matches.Z); | |
} | |
specificOffset = matches.Z; | |
} | |
if (!isUndefined(matches.q)) { | |
matches.M = (matches.q - 1) * 3 + 1; | |
} | |
if (!isUndefined(matches.h)) { | |
if (matches.h < 12 && matches.a === 1) { | |
matches.h += 12; | |
} else if (matches.h === 12 && matches.a === 0) { | |
matches.h = 0; | |
} | |
} | |
if (matches.G === 0 && matches.y) { | |
matches.y = -matches.y; | |
} | |
if (!isUndefined(matches.u)) { | |
matches.S = parseMillis(matches.u); | |
} | |
const vals = Object.keys(matches).reduce((r, k) => { | |
const f = toField(k); | |
if (f) { | |
r[f] = matches[k]; | |
} | |
return r; | |
}, {}); | |
return [vals, zone, specificOffset]; | |
} | |
var dummyDateTimeCache = null; | |
function getDummyDateTime() { | |
if (!dummyDateTimeCache) { | |
dummyDateTimeCache = DateTime.fromMillis(1555555555555); | |
} | |
return dummyDateTimeCache; | |
} | |
function maybeExpandMacroToken(token, locale) { | |
if (token.literal) { | |
return token; | |
} | |
const formatOpts = Formatter2.macroTokenToFormatOpts(token.val); | |
const tokens = formatOptsToTokens(formatOpts, locale); | |
if (tokens == null || tokens.includes(void 0)) { | |
return token; | |
} | |
return tokens; | |
} | |
function expandMacroTokens(tokens, locale) { | |
return Array.prototype.concat(...tokens.map((t2) => maybeExpandMacroToken(t2, locale))); | |
} | |
function explainFromTokens(locale, input, format) { | |
const tokens = expandMacroTokens(Formatter2.parseFormat(format), locale), units = tokens.map((t2) => unitForToken(t2, locale)), disqualifyingUnit = units.find((t2) => t2.invalidReason); | |
if (disqualifyingUnit) { | |
return { input, tokens, invalidReason: disqualifyingUnit.invalidReason }; | |
} else { | |
const [regexString, handlers] = buildRegex(units), regex3 = RegExp(regexString, "i"), [rawMatches, matches] = match(input, regex3, handlers), [result, zone, specificOffset] = matches ? dateTimeFromMatches(matches) : [null, null, void 0]; | |
if (hasOwnProperty(matches, "a") && hasOwnProperty(matches, "H")) { | |
throw new ConflictingSpecificationError( | |
"Can't include meridiem when specifying 24-hour format" | |
); | |
} | |
return { input, tokens, regex: regex3, rawMatches, matches, result, zone, specificOffset }; | |
} | |
} | |
function parseFromTokens(locale, input, format) { | |
const { result, zone, specificOffset, invalidReason } = explainFromTokens(locale, input, format); | |
return [result, zone, specificOffset, invalidReason]; | |
} | |
function formatOptsToTokens(formatOpts, locale) { | |
if (!formatOpts) { | |
return null; | |
} | |
const formatter = Formatter2.create(locale, formatOpts); | |
const parts = formatter.formatDateTimeParts(getDummyDateTime()); | |
return parts.map((p) => tokenForPart(p, formatOpts)); | |
} | |
var nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; | |
var leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]; | |
function unitOutOfRange(unit, value) { | |
return new Invalid( | |
"unit out of range", | |
`you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid` | |
); | |
} | |
function dayOfWeek(year, month, day) { | |
const d = new Date(Date.UTC(year, month - 1, day)); | |
if (year < 100 && year >= 0) { | |
d.setUTCFullYear(d.getUTCFullYear() - 1900); | |
} | |
const js = d.getUTCDay(); | |
return js === 0 ? 7 : js; | |
} | |
function computeOrdinal(year, month, day) { | |
return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1]; | |
} | |
function uncomputeOrdinal(year, ordinal) { | |
const table = isLeapYear(year) ? leapLadder : nonLeapLadder, month0 = table.findIndex((i) => i < ordinal), day = ordinal - table[month0]; | |
return { month: month0 + 1, day }; | |
} | |
function gregorianToWeek(gregObj) { | |
const { year, month, day } = gregObj, ordinal = computeOrdinal(year, month, day), weekday = dayOfWeek(year, month, day); | |
let weekNumber = Math.floor((ordinal - weekday + 10) / 7), weekYear; | |
if (weekNumber < 1) { | |
weekYear = year - 1; | |
weekNumber = weeksInWeekYear(weekYear); | |
} else if (weekNumber > weeksInWeekYear(year)) { | |
weekYear = year + 1; | |
weekNumber = 1; | |
} else { | |
weekYear = year; | |
} | |
return { weekYear, weekNumber, weekday, ...timeObject(gregObj) }; | |
} | |
function weekToGregorian(weekData) { | |
const { weekYear, weekNumber, weekday } = weekData, weekdayOfJan4 = dayOfWeek(weekYear, 1, 4), yearInDays = daysInYear(weekYear); | |
let ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 3, year; | |
if (ordinal < 1) { | |
year = weekYear - 1; | |
ordinal += daysInYear(year); | |
} else if (ordinal > yearInDays) { | |
year = weekYear + 1; | |
ordinal -= daysInYear(weekYear); | |
} else { | |
year = weekYear; | |
} | |
const { month, day } = uncomputeOrdinal(year, ordinal); | |
return { year, month, day, ...timeObject(weekData) }; | |
} | |
function gregorianToOrdinal(gregData) { | |
const { year, month, day } = gregData; | |
const ordinal = computeOrdinal(year, month, day); | |
return { year, ordinal, ...timeObject(gregData) }; | |
} | |
function ordinalToGregorian(ordinalData) { | |
const { year, ordinal } = ordinalData; | |
const { month, day } = uncomputeOrdinal(year, ordinal); | |
return { year, month, day, ...timeObject(ordinalData) }; | |
} | |
function hasInvalidWeekData(obj) { | |
const validYear = isInteger(obj.weekYear), validWeek = integerBetween(obj.weekNumber, 1, weeksInWeekYear(obj.weekYear)), validWeekday = integerBetween(obj.weekday, 1, 7); | |
if (!validYear) { | |
return unitOutOfRange("weekYear", obj.weekYear); | |
} else if (!validWeek) { | |
return unitOutOfRange("week", obj.week); | |
} else if (!validWeekday) { | |
return unitOutOfRange("weekday", obj.weekday); | |
} else | |
return false; | |
} | |
function hasInvalidOrdinalData(obj) { | |
const validYear = isInteger(obj.year), validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year)); | |
if (!validYear) { | |
return unitOutOfRange("year", obj.year); | |
} else if (!validOrdinal) { | |
return unitOutOfRange("ordinal", obj.ordinal); | |
} else | |
return false; | |
} | |
function hasInvalidGregorianData(obj) { | |
const validYear = isInteger(obj.year), validMonth = integerBetween(obj.month, 1, 12), validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month)); | |
if (!validYear) { | |
return unitOutOfRange("year", obj.year); | |
} else if (!validMonth) { | |
return unitOutOfRange("month", obj.month); | |
} else if (!validDay) { | |
return unitOutOfRange("day", obj.day); | |
} else | |
return false; | |
} | |
function hasInvalidTimeData(obj) { | |
const { hour, minute, second, millisecond } = obj; | |
const validHour = integerBetween(hour, 0, 23) || hour === 24 && minute === 0 && second === 0 && millisecond === 0, validMinute = integerBetween(minute, 0, 59), validSecond = integerBetween(second, 0, 59), validMillisecond = integerBetween(millisecond, 0, 999); | |
if (!validHour) { | |
return unitOutOfRange("hour", hour); | |
} else if (!validMinute) { | |
return unitOutOfRange("minute", minute); | |
} else if (!validSecond) { | |
return unitOutOfRange("second", second); | |
} else if (!validMillisecond) { | |
return unitOutOfRange("millisecond", millisecond); | |
} else | |
return false; | |
} | |
var INVALID = "Invalid DateTime"; | |
var MAX_DATE = 864e13; | |
function unsupportedZone(zone) { | |
return new Invalid("unsupported zone", `the zone "${zone.name}" is not supported`); | |
} | |
function possiblyCachedWeekData(dt) { | |
if (dt.weekData === null) { | |
dt.weekData = gregorianToWeek(dt.c); | |
} | |
return dt.weekData; | |
} | |
function clone2(inst, alts) { | |
const current = { | |
ts: inst.ts, | |
zone: inst.zone, | |
c: inst.c, | |
o: inst.o, | |
loc: inst.loc, | |
invalid: inst.invalid | |
}; | |
return new DateTime({ ...current, ...alts, old: current }); | |
} | |
function fixOffset(localTS, o, tz) { | |
let utcGuess = localTS - o * 60 * 1e3; | |
const o2 = tz.offset(utcGuess); | |
if (o === o2) { | |
return [utcGuess, o]; | |
} | |
utcGuess -= (o2 - o) * 60 * 1e3; | |
const o3 = tz.offset(utcGuess); | |
if (o2 === o3) { | |
return [utcGuess, o2]; | |
} | |
return [localTS - Math.min(o2, o3) * 60 * 1e3, Math.max(o2, o3)]; | |
} | |
function tsToObj(ts, offset2) { | |
ts += offset2 * 60 * 1e3; | |
const d = new Date(ts); | |
return { | |
year: d.getUTCFullYear(), | |
month: d.getUTCMonth() + 1, | |
day: d.getUTCDate(), | |
hour: d.getUTCHours(), | |
minute: d.getUTCMinutes(), | |
second: d.getUTCSeconds(), | |
millisecond: d.getUTCMilliseconds() | |
}; | |
} | |
function objToTS(obj, offset2, zone) { | |
return fixOffset(objToLocalTS(obj), offset2, zone); | |
} | |
function adjustTime(inst, dur) { | |
const oPre = inst.o, year = inst.c.year + Math.trunc(dur.years), month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3, c = { | |
...inst.c, | |
year, | |
month, | |
day: Math.min(inst.c.day, daysInMonth(year, month)) + Math.trunc(dur.days) + Math.trunc(dur.weeks) * 7 | |
}, millisToAdd = Duration.fromObject({ | |
years: dur.years - Math.trunc(dur.years), | |
quarters: dur.quarters - Math.trunc(dur.quarters), | |
months: dur.months - Math.trunc(dur.months), | |
weeks: dur.weeks - Math.trunc(dur.weeks), | |
days: dur.days - Math.trunc(dur.days), | |
hours: dur.hours, | |
minutes: dur.minutes, | |
seconds: dur.seconds, | |
milliseconds: dur.milliseconds | |
}).as("milliseconds"), localTS = objToLocalTS(c); | |
let [ts, o] = fixOffset(localTS, oPre, inst.zone); | |
if (millisToAdd !== 0) { | |
ts += millisToAdd; | |
o = inst.zone.offset(ts); | |
} | |
return { ts, o }; | |
} | |
function parseDataToDateTime(parsed, parsedZone, opts, format, text, specificOffset) { | |
const { setZone, zone } = opts; | |
if (parsed && Object.keys(parsed).length !== 0) { | |
const interpretationZone = parsedZone || zone, inst = DateTime.fromObject(parsed, { | |
...opts, | |
zone: interpretationZone, | |
specificOffset | |
}); | |
return setZone ? inst : inst.setZone(zone); | |
} else { | |
return DateTime.invalid( | |
new Invalid("unparsable", `the input "${text}" can't be parsed as ${format}`) | |
); | |
} | |
} | |
function toTechFormat(dt, format, allowZ = true) { | |
return dt.isValid ? Formatter2.create(Locale.create("en-US"), { | |
allowZ, | |
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); | |
c += "-"; | |
c += padStart(o.c.day); | |
} else { | |
c += padStart(o.c.month); | |
c += padStart(o.c.day); | |
} | |
return c; | |
} | |
function toISOTime(o, extended, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone) { | |
let c = padStart(o.c.hour); | |
if (extended) { | |
c += ":"; | |
c += padStart(o.c.minute); | |
if (o.c.second !== 0 || !suppressSeconds) { | |
c += ":"; | |
} | |
} else { | |
c += padStart(o.c.minute); | |
} | |
if (o.c.second !== 0 || !suppressSeconds) { | |
c += padStart(o.c.second); | |
if (o.c.millisecond !== 0 || !suppressMilliseconds) { | |
c += "."; | |
c += padStart(o.c.millisecond, 3); | |
} | |
} | |
if (includeOffset) { | |
if (o.isOffsetFixed && o.offset === 0 && !extendedZone) { | |
c += "Z"; | |
} else if (o.o < 0) { | |
c += "-"; | |
c += padStart(Math.trunc(-o.o / 60)); | |
c += ":"; | |
c += padStart(Math.trunc(-o.o % 60)); | |
} else { | |
c += "+"; | |
c += padStart(Math.trunc(o.o / 60)); | |
c += ":"; | |
c += padStart(Math.trunc(o.o % 60)); | |
} | |
} | |
if (extendedZone) { | |
c += "[" + o.zone.ianaName + "]"; | |
} | |
return c; | |
} | |
var defaultUnitValues = { | |
month: 1, | |
day: 1, | |
hour: 0, | |
minute: 0, | |
second: 0, | |
millisecond: 0 | |
}; | |
var defaultWeekUnitValues = { | |
weekNumber: 1, | |
weekday: 1, | |
hour: 0, | |
minute: 0, | |
second: 0, | |
millisecond: 0 | |
}; | |
var defaultOrdinalUnitValues = { | |
ordinal: 1, | |
hour: 0, | |
minute: 0, | |
second: 0, | |
millisecond: 0 | |
}; | |
var orderedUnits = ["year", "month", "day", "hour", "minute", "second", "millisecond"]; | |
var orderedWeekUnits = [ | |
"weekYear", | |
"weekNumber", | |
"weekday", | |
"hour", | |
"minute", | |
"second", | |
"millisecond" | |
]; | |
var orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"]; | |
function normalizeUnit(unit) { | |
const normalized = { | |
year: "year", | |
years: "year", | |
month: "month", | |
months: "month", | |
day: "day", | |
days: "day", | |
hour: "hour", | |
hours: "hour", | |
minute: "minute", | |
minutes: "minute", | |
quarter: "quarter", | |
quarters: "quarter", | |
second: "second", | |
seconds: "second", | |
millisecond: "millisecond", | |
milliseconds: "millisecond", | |
weekday: "weekday", | |
weekdays: "weekday", | |
weeknumber: "weekNumber", | |
weeksnumber: "weekNumber", | |
weeknumbers: "weekNumber", | |
weekyear: "weekYear", | |
weekyears: "weekYear", | |
ordinal: "ordinal" | |
}[unit.toLowerCase()]; | |
if (!normalized) | |
throw new InvalidUnitError(unit); | |
return normalized; | |
} | |
function quickDT(obj, opts) { | |
const zone = normalizeZone(opts.zone, Settings.defaultZone), loc = Locale.fromObject(opts), tsNow = Settings.now(); | |
let ts, o; | |
if (!isUndefined(obj.year)) { | |
for (const u of orderedUnits) { | |
if (isUndefined(obj[u])) { | |
obj[u] = defaultUnitValues[u]; | |
} | |
} | |
const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj); | |
if (invalid) { | |
return DateTime.invalid(invalid); | |
} | |
const offsetProvis = zone.offset(tsNow); | |
[ts, o] = objToTS(obj, offsetProvis, zone); | |
} else { | |
ts = tsNow; | |
} | |
return new DateTime({ ts, zone, loc, o }); | |
} | |
function diffRelative(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); | |
} | |
}; | |
if (opts.unit) { | |
return format(differ(opts.unit), opts.unit); | |
} | |
for (const unit of opts.units) { | |
const count = differ(unit); | |
if (Math.abs(count) >= 1) { | |
return format(count, unit); | |
} | |
} | |
return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]); | |
} | |
function lastOpts(argList) { | |
let opts = {}, args; | |
if (argList.length > 0 && typeof argList[argList.length - 1] === "object") { | |
opts = argList[argList.length - 1]; | |
args = Array.from(argList).slice(0, argList.length - 1); | |
} else { | |
args = Array.from(argList); | |
} | |
return [opts, args]; | |
} | |
var DateTime = class { | |
/** | |
* @access private | |
*/ | |
constructor(config) { | |
const zone = config.zone || Settings.defaultZone; | |
let invalid = config.invalid || (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || (!zone.isValid ? unsupportedZone(zone) : null); | |
this.ts = isUndefined(config.ts) ? Settings.now() : config.ts; | |
let c = null, o = null; | |
if (!invalid) { | |
const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone); | |
if (unchanged) { | |
[c, o] = [config.old.c, config.old.o]; | |
} else { | |
const ot = zone.offset(this.ts); | |
c = tsToObj(this.ts, ot); | |
invalid = Number.isNaN(c.year) ? new Invalid("invalid input") : null; | |
c = invalid ? null : c; | |
o = invalid ? null : ot; | |
} | |
} | |
this._zone = zone; | |
this.loc = config.loc || Locale.create(); | |
this.invalid = invalid; | |
this.weekData = null; | |
this.c = c; | |
this.o = o; | |
this.isLuxonDateTime = true; | |
} | |
// CONSTRUCT | |
/** | |
* Create a DateTime for the current instant, in the system's time zone. | |
* | |
* Use Settings to override these default values if needed. | |
* @example DateTime.now().toISO() //~> now in the ISO format | |
* @return {DateTime} | |
*/ | |
static now() { | |
return new DateTime({}); | |
} | |
/** | |
* Create a local DateTime | |
* @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used | |
* @param {number} [month=1] - The month, 1-indexed | |
* @param {number} [day=1] - The day of the month, 1-indexed | |
* @param {number} [hour=0] - The hour of the day, in 24-hour time | |
* @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59 | |
* @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59 | |
* @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999 | |
* @example DateTime.local() //~> now | |
* @example DateTime.local({ zone: "America/New_York" }) //~> now, in US east coast time | |
* @example DateTime.local(2017) //~> 2017-01-01T00:00:00 | |
* @example DateTime.local(2017, 3) //~> 2017-03-01T00:00:00 | |
* @example DateTime.local(2017, 3, 12, { locale: "fr" }) //~> 2017-03-12T00:00:00, with a French locale | |
* @example DateTime.local(2017, 3, 12, 5) //~> 2017-03-12T05:00:00 | |
* @example DateTime.local(2017, 3, 12, 5, { zone: "utc" }) //~> 2017-03-12T05:00:00, in UTC | |
* @example DateTime.local(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00 | |
* @example DateTime.local(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10 | |
* @example DateTime.local(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765 | |
* @return {DateTime} | |
*/ | |
static local() { | |
const [opts, args] = lastOpts(arguments), [year, month, day, hour, minute, second, millisecond] = args; | |
return quickDT({ year, month, day, hour, minute, second, millisecond }, opts); | |
} | |
/** | |
* Create a DateTime in UTC | |
* @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used | |
* @param {number} [month=1] - The month, 1-indexed | |
* @param {number} [day=1] - The day of the month | |
* @param {number} [hour=0] - The hour of the day, in 24-hour time | |
* @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59 | |
* @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59 | |
* @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999 | |
* @param {Object} options - configuration options for the DateTime | |
* @param {string} [options.locale] - a locale to set on the resulting DateTime instance | |
* @param {string} [options.outputCalendar] - the output calendar to set on the resulting DateTime instance | |
* @param {string} [options.numberingSystem] - the numbering system to set on the resulting DateTime instance | |
* @example DateTime.utc() //~> now | |
* @example DateTime.utc(2017) //~> 2017-01-01T00:00:00Z | |
* @example DateTime.utc(2017, 3) //~> 2017-03-01T00:00:00Z | |
* @example DateTime.utc(2017, 3, 12) //~> 2017-03-12T00:00:00Z | |
* @example DateTime.utc(2017, 3, 12, 5) //~> 2017-03-12T05:00:00Z | |
* @example DateTime.utc(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00Z | |
* @example DateTime.utc(2017, 3, 12, 5, 45, { locale: "fr" }) //~> 2017-03-12T05:45:00Z with a French locale | |
* @example DateTime.utc(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10Z | |
* @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765, { locale: "fr" }) //~> 2017-03-12T05:45:10.765Z with a French locale | |
* @return {DateTime} | |
*/ | |
static utc() { | |
const [opts, args] = lastOpts(arguments), [year, month, day, hour, minute, second, millisecond] = args; | |
opts.zone = FixedOffsetZone.utcInstance; | |
return quickDT({ year, month, day, hour, minute, second, millisecond }, opts); | |
} | |
/** | |
* Create a DateTime from a JavaScript Date object. Uses the default zone. | |
* @param {Date} date - a JavaScript Date object | |
* @param {Object} options - configuration options for the DateTime | |
* @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into | |
* @return {DateTime} | |
*/ | |
static fromJSDate(date, options = {}) { | |
const ts = isDate(date) ? date.valueOf() : NaN; | |
if (Number.isNaN(ts)) { | |
return DateTime.invalid("invalid input"); | |
} | |
const zoneToUse = normalizeZone(options.zone, Settings.defaultZone); | |
if (!zoneToUse.isValid) { | |
return DateTime.invalid(unsupportedZone(zoneToUse)); | |
} | |
return new DateTime({ | |
ts, | |
zone: zoneToUse, | |
loc: Locale.fromObject(options) | |
}); | |
} | |
/** | |
* Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone. | |
* @param {number} milliseconds - a number of milliseconds since 1970 UTC | |
* @param {Object} options - configuration options for the DateTime | |
* @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into | |
* @param {string} [options.locale] - a locale to set on the resulting DateTime instance | |
* @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance | |
* @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance | |
* @return {DateTime} | |
*/ | |
static fromMillis(milliseconds, options = {}) { | |
if (!isNumber(milliseconds)) { | |
throw new InvalidArgumentError( | |
`fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}` | |
); | |
} else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) { | |
return DateTime.invalid("Timestamp out of range"); | |
} else { | |
return new DateTime({ | |
ts: milliseconds, | |
zone: normalizeZone(options.zone, Settings.defaultZone), | |
loc: Locale.fromObject(options) | |
}); | |
} | |
} | |
/** | |
* Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone. | |
* @param {number} seconds - a number of seconds since 1970 UTC | |
* @param {Object} options - configuration options for the DateTime | |
* @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into | |
* @param {string} [options.locale] - a locale to set on the resulting DateTime instance | |
* @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance | |
* @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance | |
* @return {DateTime} | |
*/ | |
static fromSeconds(seconds, options = {}) { | |
if (!isNumber(seconds)) { | |
throw new InvalidArgumentError("fromSeconds requires a numerical input"); | |
} else { | |
return new DateTime({ | |
ts: seconds * 1e3, | |
zone: normalizeZone(options.zone, Settings.defaultZone), | |
loc: Locale.fromObject(options) | |
}); | |
} | |
} | |
/** | |
* Create a DateTime from a JavaScript object with keys like 'year' and 'hour' with reasonable defaults. | |
* @param {Object} obj - the object to create the DateTime from | |
* @param {number} obj.year - a year, such as 1987 | |
* @param {number} obj.month - a month, 1-12 | |
* @param {number} obj.day - a day of the month, 1-31, depending on the month | |
* @param {number} obj.ordinal - day of the year, 1-365 or 366 | |
* @param {number} obj.weekYear - an ISO week year | |
* @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year | |
* @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday | |
* @param {number} obj.hour - hour of the day, 0-23 | |
* @param {number} obj.minute - minute of the hour, 0-59 | |
* @param {number} obj.second - second of the minute, 0-59 | |
* @param {number} obj.millisecond - millisecond of the second, 0-999 | |
* @param {Object} opts - options for creating this DateTime | |
* @param {string|Zone} [opts.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone() | |
* @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance | |
* @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance | |
* @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance | |
* @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25' | |
* @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01' | |
* @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06 | |
* @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'utc' }), | |
* @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'local' }) | |
* @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'America/New_York' }) | |
* @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13' | |
* @return {DateTime} | |
*/ | |
static fromObject(obj, opts = {}) { | |
obj = obj || {}; | |
const zoneToUse = normalizeZone(opts.zone, Settings.defaultZone); | |
if (!zoneToUse.isValid) { | |
return DateTime.invalid(unsupportedZone(zoneToUse)); | |
} | |
const tsNow = Settings.now(), offsetProvis = !isUndefined(opts.specificOffset) ? opts.specificOffset : zoneToUse.offset(tsNow), normalized = normalizeObject(obj, normalizeUnit), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber, loc = Locale.fromObject(opts); | |
if ((containsGregor || containsOrdinal) && definiteWeekDef) { | |
throw new ConflictingSpecificationError( | |
"Can't mix weekYear/weekNumber units with year/month/day or ordinals" | |
); | |
} | |
if (containsGregorMD && containsOrdinal) { | |
throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day"); | |
} | |
const useWeekData = definiteWeekDef || normalized.weekday && !containsGregor; | |
let units, defaultValues, objNow = tsToObj(tsNow, offsetProvis); | |
if (useWeekData) { | |
units = orderedWeekUnits; | |
defaultValues = defaultWeekUnitValues; | |
objNow = gregorianToWeek(objNow); | |
} else if (containsOrdinal) { | |
units = orderedOrdinalUnits; | |
defaultValues = defaultOrdinalUnitValues; | |
objNow = gregorianToOrdinal(objNow); | |
} else { | |
units = orderedUnits; | |
defaultValues = defaultUnitValues; | |
} | |
let foundFirst = false; | |
for (const u of units) { | |
const v = normalized[u]; | |
if (!isUndefined(v)) { | |
foundFirst = true; | |
} else if (foundFirst) { | |
normalized[u] = defaultValues[u]; | |
} else { | |
normalized[u] = objNow[u]; | |
} | |
} | |
const higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized), invalid = higherOrderInvalid || hasInvalidTimeData(normalized); | |
if (invalid) { | |
return DateTime.invalid(invalid); | |
} | |
const gregorian = useWeekData ? weekToGregorian(normalized) : containsOrdinal ? ordinalToGregorian(normalized) : normalized, [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse), inst = new DateTime({ | |
ts: tsFinal, | |
zone: zoneToUse, | |
o: offsetFinal, | |
loc | |
}); | |
if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) { | |
return DateTime.invalid( | |
"mismatched weekday", | |
`you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}` | |
); | |
} | |
return inst; | |
} | |
/** | |
* Create a DateTime from an ISO 8601 string | |
* @param {string} text - the ISO string | |
* @param {Object} opts - options to affect the creation | |
* @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone | |
* @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one | |
* @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance | |
* @param {string} [opts.outputCalendar] - the output calendar to set on the resulting DateTime instance | |
* @param {string} [opts.numberingSystem] - the numbering system to set on the resulting DateTime instance | |
* @example DateTime.fromISO('2016-05-25T09:08:34.123') | |
* @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00') | |
* @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true}) | |
* @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'}) | |
* @example DateTime.fromISO('2016-W05-4') | |
* @return {DateTime} | |
*/ | |
static fromISO(text, opts = {}) { | |
const [vals, parsedZone] = parseISODate(text); | |
return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text); | |
} | |
/** | |
* Create a DateTime from an RFC 2822 string | |
* @param {string} text - the RFC 2822 string | |
* @param {Object} opts - options to affect the creation | |
* @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in. | |
* @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one | |
* @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance | |
* @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance | |
* @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance | |
* @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT') | |
* @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600') | |
* @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z') | |
* @return {DateTime} | |
*/ | |
static fromRFC2822(text, opts = {}) { | |
const [vals, parsedZone] = parseRFC2822Date(text); | |
return parseDataToDateTime(vals, parsedZone, opts, "RFC 2822", text); | |
} | |
/** | |
* Create a DateTime from an HTTP header date | |
* @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 | |
* @param {string} text - the HTTP header date | |
* @param {Object} opts - options to affect the creation | |
* @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in. | |
* @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods. | |
* @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance | |
* @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance | |
* @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance | |
* @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT') | |
* @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT') | |
* @example DateTime.fromHTTP('Sun Nov 6 08:49:37 1994') | |
* @return {DateTime} | |
*/ | |
static fromHTTP(text, opts = {}) { | |
const [vals, parsedZone] = parseHTTPDate(text); | |
return parseDataToDateTime(vals, parsedZone, opts, "HTTP", opts); | |
} | |
/** | |
* Create a DateTime from an input string and format string. | |
* Defaults to en-US if no locale has been specified, regardless of the system's locale. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/parsing?id=table-of-tokens). | |
* @param {string} text - the string to parse | |
* @param {string} fmt - the format the string is expected to be in (see the link below for the formats) | |
* @param {Object} opts - options to affect the creation | |
* @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone | |
* @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one | |
* @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale | |
* @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system | |
* @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance | |
* @return {DateTime} | |
*/ | |
static fromFormat(text, fmt, opts = {}) { | |
if (isUndefined(text) || isUndefined(fmt)) { | |
throw new InvalidArgumentError("fromFormat requires an input string and a format"); | |
} | |
const { locale = null, numberingSystem = null } = opts, localeToUse = Locale.fromOpts({ | |
locale, | |
numberingSystem, | |
defaultToEN: true | |
}), [vals, parsedZone, specificOffset, invalid] = parseFromTokens(localeToUse, text, fmt); | |
if (invalid) { | |
return DateTime.invalid(invalid); | |
} else { | |
return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text, specificOffset); | |
} | |
} | |
/** | |
* @deprecated use fromFormat instead | |
*/ | |
static fromString(text, fmt, opts = {}) { | |
return DateTime.fromFormat(text, fmt, opts); | |
} | |
/** | |
* Create a DateTime from a SQL date, time, or datetime | |
* Defaults to en-US if no locale has been specified, regardless of the system's locale | |
* @param {string} text - the string to parse | |
* @param {Object} opts - options to affect the creation | |
* @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone | |
* @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one | |
* @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale | |
* @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system | |
* @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance | |
* @example DateTime.fromSQL('2017-05-15') | |
* @example DateTime.fromSQL('2017-05-15 09:12:34') | |
* @example DateTime.fromSQL('2017-05-15 09:12:34.342') | |
* @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00') | |
* @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles') | |
* @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true }) | |
* @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' }) | |
* @example DateTime.fromSQL('09:12:34.342') | |
* @return {DateTime} | |
*/ | |
static fromSQL(text, opts = {}) { | |
const [vals, parsedZone] = parseSQL(text); | |
return parseDataToDateTime(vals, parsedZone, opts, "SQL", text); | |
} | |
/** | |
* Create an invalid DateTime. | |
* @param {DateTime} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent | |
* @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information | |
* @return {DateTime} | |
*/ | |
static invalid(reason, explanation = null) { | |
if (!reason) { | |
throw new InvalidArgumentError("need to specify a reason the DateTime is invalid"); | |
} | |
const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); | |
if (Settings.throwOnInvalid) { | |
throw new InvalidDateTimeError(invalid); | |
} else { | |
return new DateTime({ invalid }); | |
} | |
} | |
/** | |
* Check if an object is an instance of DateTime. Works across context boundaries | |
* @param {object} o | |
* @return {boolean} | |
*/ | |
static isDateTime(o) { | |
return o && o.isLuxonDateTime || false; | |
} | |
/** | |
* Produce the format string for a set of options | |
* @param formatOpts | |
* @param localeOpts | |
* @returns {string} | |
*/ | |
static parseFormatForOpts(formatOpts, localeOpts = {}) { | |
const tokenList = formatOptsToTokens(formatOpts, Locale.fromObject(localeOpts)); | |
return !tokenList ? null : tokenList.map((t2) => t2 ? t2.val : null).join(""); | |
} | |
/** | |
* Produce the the fully expanded format token for the locale | |
* Does NOT quote characters, so quoted tokens will not round trip correctly | |
* @param fmt | |
* @param localeOpts | |
* @returns {string} | |
*/ | |
static expandFormat(fmt, localeOpts = {}) { | |
const expanded = expandMacroTokens(Formatter2.parseFormat(fmt), Locale.fromObject(localeOpts)); | |
return expanded.map((t2) => t2.val).join(""); | |
} | |
// INFO | |
/** | |
* Get the value of unit. | |
* @param {string} unit - a unit such as 'minute' or 'day' | |
* @example DateTime.local(2017, 7, 4).get('month'); //=> 7 | |
* @example DateTime.local(2017, 7, 4).get('day'); //=> 4 | |
* @return {number} | |
*/ | |
get(unit) { | |
return this[unit]; | |
} | |
/** | |
* Returns whether the DateTime is valid. Invalid DateTimes occur when: | |
* * The DateTime was created from invalid calendar information, such as the 13th month or February 30 | |
* * The DateTime was created by an operation on another invalid date | |
* @type {boolean} | |
*/ | |
get isValid() { | |
return this.invalid === null; | |
} | |
/** | |
* Returns an error code if this DateTime is invalid, or null if the DateTime is valid | |
* @type {string} | |
*/ | |
get invalidReason() { | |
return this.invalid ? this.invalid.reason : null; | |
} | |
/** | |
* Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid | |
* @type {string} | |
*/ | |
get invalidExplanation() { | |
return this.invalid ? this.invalid.explanation : null; | |
} | |
/** | |
* Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime | |
* | |
* @type {string} | |
*/ | |
get locale() { | |
return this.isValid ? this.loc.locale : null; | |
} | |
/** | |
* Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime | |
* | |
* @type {string} | |
*/ | |
get numberingSystem() { | |
return this.isValid ? this.loc.numberingSystem : null; | |
} | |
/** | |
* Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime | |
* | |
* @type {string} | |
*/ | |
get outputCalendar() { | |
return this.isValid ? this.loc.outputCalendar : null; | |
} | |
/** | |
* Get the time zone associated with this DateTime. | |
* @type {Zone} | |
*/ | |
get zone() { | |
return this._zone; | |
} | |
/** | |
* Get the name of the time zone. | |
* @type {string} | |
*/ | |
get zoneName() { | |
return this.isValid ? this.zone.name : null; | |
} | |
/** | |
* Get the year | |
* @example DateTime.local(2017, 5, 25).year //=> 2017 | |
* @type {number} | |
*/ | |
get year() { | |
return this.isValid ? this.c.year : NaN; | |
} | |
/** | |
* Get the quarter | |
* @example DateTime.local(2017, 5, 25).quarter //=> 2 | |
* @type {number} | |
*/ | |
get quarter() { | |
return this.isValid ? Math.ceil(this.c.month / 3) : NaN; | |
} | |
/** | |
* Get the month (1-12). | |
* @example DateTime.local(2017, 5, 25).month //=> 5 | |
* @type {number} | |
*/ | |
get month() { | |
return this.isValid ? this.c.month : NaN; | |
} | |
/** | |
* Get the day of the month (1-30ish). | |
* @example DateTime.local(2017, 5, 25).day //=> 25 | |
* @type {number} | |
*/ | |
get day() { | |
return this.isValid ? this.c.day : NaN; | |
} | |
/** | |
* Get the hour of the day (0-23). | |
* @example DateTime.local(2017, 5, 25, 9).hour //=> 9 | |
* @type {number} | |
*/ | |
get hour() { | |
return this.isValid ? this.c.hour : NaN; | |
} | |
/** | |
* Get the minute of the hour (0-59). | |
* @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30 | |
* @type {number} | |
*/ | |
get minute() { | |
return this.isValid ? this.c.minute : NaN; | |
} | |
/** | |
* Get the second of the minute (0-59). | |
* @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52 | |
* @type {number} | |
*/ | |
get second() { | |
return this.isValid ? this.c.second : NaN; | |
} | |
/** | |
* Get the millisecond of the second (0-999). | |
* @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654 | |
* @type {number} | |
*/ | |
get millisecond() { | |
return this.isValid ? this.c.millisecond : NaN; | |
} | |
/** | |
* Get the week year | |
* @see https://en.wikipedia.org/wiki/ISO_week_date | |
* @example DateTime.local(2014, 12, 31).weekYear //=> 2015 | |
* @type {number} | |
*/ | |
get weekYear() { | |
return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN; | |
} | |
/** | |
* Get the week number of the week year (1-52ish). | |
* @see https://en.wikipedia.org/wiki/ISO_week_date | |
* @example DateTime.local(2017, 5, 25).weekNumber //=> 21 | |
* @type {number} | |
*/ | |
get weekNumber() { | |
return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN; | |
} | |
/** | |
* Get the day of the week. | |
* 1 is Monday and 7 is Sunday | |
* @see https://en.wikipedia.org/wiki/ISO_week_date | |
* @example DateTime.local(2014, 11, 31).weekday //=> 4 | |
* @type {number} | |
*/ | |
get weekday() { | |
return this.isValid ? possiblyCachedWeekData(this).weekday : NaN; | |
} | |
/** | |
* Get the ordinal (meaning the day of the year) | |
* @example DateTime.local(2017, 5, 25).ordinal //=> 145 | |
* @type {number|DateTime} | |
*/ | |
get ordinal() { | |
return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN; | |
} | |
/** | |
* Get the human readable short month name, such as 'Oct'. | |
* Defaults to the system's locale if no locale has been specified | |
* @example DateTime.local(2017, 10, 30).monthShort //=> Oct | |
* @type {string} | |
*/ | |
get monthShort() { | |
return this.isValid ? Info.months("short", { locObj: this.loc })[this.month - 1] : null; | |
} | |
/** | |
* Get the human readable long month name, such as 'October'. | |
* Defaults to the system's locale if no locale has been specified | |
* @example DateTime.local(2017, 10, 30).monthLong //=> October | |
* @type {string} | |
*/ | |
get monthLong() { | |
return this.isValid ? Info.months("long", { locObj: this.loc })[this.month - 1] : null; | |
} | |
/** | |
* Get the human readable short weekday, such as 'Mon'. | |
* Defaults to the system's locale if no locale has been specified | |
* @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon | |
* @type {string} | |
*/ | |
get weekdayShort() { | |
return this.isValid ? Info.weekdays("short", { locObj: this.loc })[this.weekday - 1] : null; | |
} | |
/** | |
* Get the human readable long weekday, such as 'Monday'. | |
* Defaults to the system's locale if no locale has been specified | |
* @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday | |
* @type {string} | |
*/ | |
get weekdayLong() { | |
return this.isValid ? Info.weekdays("long", { locObj: this.loc })[this.weekday - 1] : null; | |
} | |
/** | |
* Get the UTC offset of this DateTime in minutes | |
* @example DateTime.now().offset //=> -240 | |
* @example DateTime.utc().offset //=> 0 | |
* @type {number} | |
*/ | |
get offset() { | |
return this.isValid ? +this.o : NaN; | |
} | |
/** | |
* Get the short human name for the zone's current offset, for example "EST" or "EDT". | |
* Defaults to the system's locale if no locale has been specified | |
* @type {string} | |
*/ | |
get offsetNameShort() { | |
if (this.isValid) { | |
return this.zone.offsetName(this.ts, { | |
format: "short", | |
locale: this.locale | |
}); | |
} else { | |
return null; | |
} | |
} | |
/** | |
* Get the long human name for the zone's current offset, for example "Eastern Standard Time" or "Eastern Daylight Time". | |
* Defaults to the system's locale if no locale has been specified | |
* @type {string} | |
*/ | |
get offsetNameLong() { | |
if (this.isValid) { | |
return this.zone.offsetName(this.ts, { | |
format: "long", | |
locale: this.locale | |
}); | |
} else { | |
return null; | |
} | |
} | |
/** | |
* Get whether this zone's offset ever changes, as in a DST. | |
* @type {boolean} | |
*/ | |
get isOffsetFixed() { | |
return this.isValid ? this.zone.isUniversal : null; | |
} | |
/** | |
* Get whether the DateTime is in a DST. | |
* @type {boolean} | |
*/ | |
get isInDST() { | |
if (this.isOffsetFixed) { | |
return false; | |
} else { | |
return this.offset > this.set({ month: 1, day: 1 }).offset || this.offset > this.set({ month: 5 }).offset; | |
} | |
} | |
/** | |
* Returns true if this DateTime is in a leap year, false otherwise | |
* @example DateTime.local(2016).isInLeapYear //=> true | |
* @example DateTime.local(2013).isInLeapYear //=> false | |
* @type {boolean} | |
*/ | |
get isInLeapYear() { | |
return isLeapYear(this.year); | |
} | |
/** | |
* Returns the number of days in this DateTime's month | |
* @example DateTime.local(2016, 2).daysInMonth //=> 29 | |
* @example DateTime.local(2016, 3).daysInMonth //=> 31 | |
* @type {number} | |
*/ | |
get daysInMonth() { | |
return daysInMonth(this.year, this.month); | |
} | |
/** | |
* Returns the number of days in this DateTime's year | |
* @example DateTime.local(2016).daysInYear //=> 366 | |
* @example DateTime.local(2013).daysInYear //=> 365 | |
* @type {number} | |
*/ | |
get daysInYear() { | |
return this.isValid ? daysInYear(this.year) : NaN; | |
} | |
/** | |
* Returns the number of weeks in this DateTime's year | |
* @see https://en.wikipedia.org/wiki/ISO_week_date | |
* @example DateTime.local(2004).weeksInWeekYear //=> 53 | |
* @example DateTime.local(2013).weeksInWeekYear //=> 52 | |
* @type {number} | |
*/ | |
get weeksInWeekYear() { | |
return this.isValid ? weeksInWeekYear(this.weekYear) : NaN; | |
} | |
/** | |
* Returns the resolved Intl options for this DateTime. | |
* This is useful in understanding the behavior of formatting methods | |
* @param {Object} opts - the same options as toLocaleString | |
* @return {Object} | |
*/ | |
resolvedLocaleOptions(opts = {}) { | |
const { locale, numberingSystem, calendar } = Formatter2.create( | |
this.loc.clone(opts), | |
opts | |
).resolvedOptions(this); | |
return { locale, numberingSystem, outputCalendar: calendar }; | |
} | |
// TRANSFORM | |
/** | |
* "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime. | |
* | |
* Equivalent to {@link DateTime#setZone}('utc') | |
* @param {number} [offset=0] - optionally, an offset from UTC in minutes | |
* @param {Object} [opts={}] - options to pass to `setZone()` | |
* @return {DateTime} | |
*/ | |
toUTC(offset2 = 0, opts = {}) { | |
return this.setZone(FixedOffsetZone.instance(offset2), opts); | |
} | |
/** | |
* "Set" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime. | |
* | |
* Equivalent to `setZone('local')` | |
* @return {DateTime} | |
*/ | |
toLocal() { | |
return this.setZone(Settings.defaultZone); | |
} | |
/** | |
* "Set" the DateTime's zone to specified zone. Returns a newly-constructed DateTime. | |
* | |
* By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link DateTime#plus}. You may wish to use {@link DateTime#toLocal} and {@link DateTime#toUTC} which provide simple convenience wrappers for commonly used zones. | |
* @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link DateTime#Zone} class. | |
* @param {Object} opts - options | |
* @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this. | |
* @return {DateTime} | |
*/ | |
setZone(zone, { keepLocalTime = false, keepCalendarTime = false } = {}) { | |
zone = normalizeZone(zone, Settings.defaultZone); | |
if (zone.equals(this.zone)) { | |
return this; | |
} else if (!zone.isValid) { | |
return DateTime.invalid(unsupportedZone(zone)); | |
} else { | |
let newTS = this.ts; | |
if (keepLocalTime || keepCalendarTime) { | |
const offsetGuess = zone.offset(this.ts); | |
const asObj = this.toObject(); | |
[newTS] = objToTS(asObj, offsetGuess, zone); | |
} | |
return clone2(this, { ts: newTS, zone }); | |
} | |
} | |
/** | |
* "Set" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime. | |
* @param {Object} properties - the properties to set | |
* @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' }) | |
* @return {DateTime} | |
*/ | |
reconfigure({ locale, numberingSystem, outputCalendar } = {}) { | |
const loc = this.loc.clone({ locale, numberingSystem, outputCalendar }); | |
return clone2(this, { loc }); | |
} | |
/** | |
* "Set" the locale. Returns a newly-constructed DateTime. | |
* Just a convenient alias for reconfigure({ locale }) | |
* @example DateTime.local(2017, 5, 25).setLocale('en-GB') | |
* @return {DateTime} | |
*/ | |
setLocale(locale) { | |
return this.reconfigure({ locale }); | |
} | |
/** | |
* "Set" the values of specified units. Returns a newly-constructed DateTime. | |
* You can only set units with this method; for "setting" metadata, see {@link DateTime#reconfigure} and {@link DateTime#setZone}. | |
* @param {Object} values - a mapping of units to numbers | |
* @example dt.set({ year: 2017 }) | |
* @example dt.set({ hour: 8, minute: 30 }) | |
* @example dt.set({ weekday: 5 }) | |
* @example dt.set({ year: 2005, ordinal: 234 }) | |
* @return {DateTime} | |
*/ | |
set(values) { | |
if (!this.isValid) | |
return this; | |
const normalized = normalizeObject(values, normalizeUnit), settingWeekStuff = !isUndefined(normalized.weekYear) || !isUndefined(normalized.weekNumber) || !isUndefined(normalized.weekday), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber; | |
if ((containsGregor || containsOrdinal) && definiteWeekDef) { | |
throw new ConflictingSpecificationError( | |
"Can't mix weekYear/weekNumber units with year/month/day or ordinals" | |
); | |
} | |
if (containsGregorMD && containsOrdinal) { | |
throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day"); | |
} | |
let mixed; | |
if (settingWeekStuff) { | |
mixed = weekToGregorian({ ...gregorianToWeek(this.c), ...normalized }); | |
} else if (!isUndefined(normalized.ordinal)) { | |
mixed = ordinalToGregorian({ ...gregorianToOrdinal(this.c), ...normalized }); | |
} else { | |
mixed = { ...this.toObject(), ...normalized }; | |
if (isUndefined(normalized.day)) { | |
mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day); | |
} | |
} | |
const [ts, o] = objToTS(mixed, this.o, this.zone); | |
return clone2(this, { ts, o }); | |
} | |
/** | |
* Add a period of time to this DateTime and return the resulting DateTime | |
* | |
* Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between. | |
* @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() | |
* @example DateTime.now().plus(123) //~> in 123 milliseconds | |
* @example DateTime.now().plus({ minutes: 15 }) //~> in 15 minutes | |
* @example DateTime.now().plus({ days: 1 }) //~> this time tomorrow | |
* @example DateTime.now().plus({ days: -1 }) //~> this time yesterday | |
* @example DateTime.now().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min | |
* @example DateTime.now().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min | |
* @return {DateTime} | |
*/ | |
plus(duration) { | |
if (!this.isValid) | |
return this; | |
const dur = Duration.fromDurationLike(duration); | |
return clone2(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 clone2(this, adjustTime(this, dur)); | |
} | |
/** | |
* "Set" this DateTime to the beginning of a unit of time. | |
* @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'. | |
* @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01' | |
* @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01' | |
* @example DateTime.local(2014, 3, 3).startOf('week').toISODate(); //=> '2014-03-03', weeks always start on Mondays | |
* @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00' | |
* @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00' | |
* @return {DateTime} | |
*/ | |
startOf(unit) { | |
if (!this.isValid) | |
return this; | |
const o = {}, normalizedUnit = Duration.normalizeUnit(unit); | |
switch (normalizedUnit) { | |
case "years": | |
o.month = 1; | |
case "quarters": | |
case "months": | |
o.day = 1; | |
case "weeks": | |
case "days": | |
o.hour = 0; | |
case "hours": | |
o.minute = 0; | |
case "minutes": | |
o.second = 0; | |
case "seconds": | |
o.millisecond = 0; | |
break; | |
} | |
if (normalizedUnit === "weeks") { | |
o.weekday = 1; | |
} | |
if (normalizedUnit === "quarters") { | |
const q = Math.ceil(this.month / 3); | |
o.month = (q - 1) * 3 + 1; | |
} | |
return this.set(o); | |
} | |
/** | |
* "Set" this DateTime to the end (meaning the last millisecond) of a unit of time | |
* @param {string} unit - The unit to go to the end of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'. | |
* @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00' | |
* @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00' | |
* @example DateTime.local(2014, 3, 3).endOf('week').toISO(); // => '2014-03-09T23:59:59.999-05:00', weeks start on Mondays | |
* @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00' | |
* @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00' | |
* @return {DateTime} | |
*/ | |
endOf(unit) { | |
return this.isValid ? this.plus({ [unit]: 1 }).startOf(unit).minus(1) : this; | |
} | |
// OUTPUT | |
/** | |
* Returns a string representation of this DateTime formatted according to the specified format string. | |
* **You may not want this.** See {@link DateTime#toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/formatting?id=table-of-tokens). | |
* Defaults to en-US if no locale has been specified, regardless of the system's locale. | |
* @param {string} fmt - the format string | |
* @param {Object} opts - opts to override the configuration options on this DateTime | |
* @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22' | |
* @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22' | |
* @example DateTime.now().toFormat('yyyy LLL dd', { locale: "fr" }) //=> '2017 avr. 22' | |
* @example DateTime.now().toFormat("HH 'hours and' mm 'minutes'") //=> '20 hours and 55 minutes' | |
* @return {string} | |
*/ | |
toFormat(fmt, opts = {}) { | |
return this.isValid ? Formatter2.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) : INVALID; | |
} | |
/** | |
* Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`. | |
* The exact behavior of this method is browser-specific, but in general it will return an appropriate representation | |
* of the DateTime in the assigned locale. | |
* Defaults to the system's locale if no locale has been specified | |
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat | |
* @param formatOpts {Object} - Intl.DateTimeFormat constructor options and configuration options | |
* @param {Object} opts - opts to override the configuration options on this DateTime | |
* @example DateTime.now().toLocaleString(); //=> 4/20/2017 | |
* @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017' | |
* @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017' | |
* @example DateTime.now().toLocaleString(DateTime.DATE_FULL, { locale: 'fr' }); //=> '28 août 2022' | |
* @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM' | |
* @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM' | |
* @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20' | |
* @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM' | |
* @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); //=> '11:32' | |
* @return {string} | |
*/ | |
toLocaleString(formatOpts = DATE_SHORT, opts = {}) { | |
return this.isValid ? Formatter2.create(this.loc.clone(opts), formatOpts).formatDateTime(this) : INVALID; | |
} | |
/** | |
* Returns an array of format "parts", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output. | |
* Defaults to the system's locale if no locale has been specified | |
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts | |
* @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`. | |
* @example DateTime.now().toLocaleParts(); //=> [ | |
* //=> { type: 'day', value: '25' }, | |
* //=> { type: 'literal', value: '/' }, | |
* //=> { type: 'month', value: '05' }, | |
* //=> { type: 'literal', value: '/' }, | |
* //=> { type: 'year', value: '1982' } | |
* //=> ] | |
*/ | |
toLocaleParts(opts = {}) { | |
return this.isValid ? Formatter2.create(this.loc.clone(opts), opts).formatDateTimeParts(this) : []; | |
} | |
/** | |
* Returns an ISO 8601-compliant string representation of this DateTime | |
* @param {Object} opts - options | |
* @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 | |
* @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 | |
* @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' | |
* @param {boolean} [opts.extendedZone=false] - add the time zone format extension | |
* @param {string} [opts.format='extended'] - choose between the basic and extended format | |
* @example DateTime.utc(1983, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z' | |
* @example DateTime.now().toISO() //=> '2017-04-22T20:47:05.335-04:00' | |
* @example DateTime.now().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335' | |
* @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400' | |
* @return {string} | |
*/ | |
toISO({ | |
format = "extended", | |
suppressSeconds = false, | |
suppressMilliseconds = false, | |
includeOffset = true, | |
extendedZone = false | |
} = {}) { | |
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 | |
* @param {string} [opts.format='extended'] - choose between the basic and extended format | |
* @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25' | |
* @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525' | |
* @return {string} | |
*/ | |
toISODate({ format = "extended" } = {}) { | |
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 | |
* @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 | |
* @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 | |
* @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' | |
* @param {boolean} [opts.extendedZone=true] - add the time zone format extension | |
* @param {boolean} [opts.includePrefix=false] - include the `T` prefix | |
* @param {string} [opts.format='extended'] - choose between the basic and extended format | |
* @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z' | |
* @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z' | |
* @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z' | |
* @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z' | |
* @return {string} | |
*/ | |
toISOTime({ | |
suppressMilliseconds = false, | |
suppressSeconds = false, | |
includeOffset = true, | |
includePrefix = false, | |
extendedZone = false, | |
format = "extended" | |
} = {}) { | |
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. | |
* @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 | |
* @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT' | |
* @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT' | |
* @return {string} | |
*/ | |
toHTTP() { | |
return toTechFormat(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'"); | |
} | |
/** | |
* Returns a string representation of this DateTime appropriate for use in SQL Date | |
* @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13' | |
* @return {string} | |
*/ | |
toSQLDate() { | |
if (!this.isValid) { | |
return null; | |
} | |
return toISODate(this, true); | |
} | |
/** | |
* Returns a string representation of this DateTime appropriate for use in SQL Time | |
* @param {Object} opts - options | |
* @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset. | |
* @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' | |
* @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00' | |
* @example DateTime.utc().toSQL() //=> '05:15:16.345' | |
* @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00' | |
* @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345' | |
* @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York' | |
* @return {string} | |
*/ | |
toSQLTime({ includeOffset = true, includeZone = false, includeOffsetSpace = true } = {}) { | |
let fmt = "HH:mm:ss.SSS"; | |
if (includeZone || includeOffset) { | |
if (includeOffsetSpace) { | |
fmt += " "; | |
} | |
if (includeZone) { | |
fmt += "z"; | |
} else if (includeOffset) { | |
fmt += "ZZ"; | |
} | |
} | |
return toTechFormat(this, fmt, true); | |
} | |
/** | |
* Returns a string representation of this DateTime appropriate for use in SQL DateTime | |
* @param {Object} opts - options | |
* @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset. | |
* @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' | |
* @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00' | |
* @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z' | |
* @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00' | |
* @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000' | |
* @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York' | |
* @return {string} | |
*/ | |
toSQL(opts = {}) { | |
if (!this.isValid) { | |
return null; | |
} | |
return `${this.toSQLDate()} ${this.toSQLTime(opts)}`; | |
} | |
/** | |
* Returns a string representation of this DateTime appropriate for debugging | |
* @return {string} | |
*/ | |
toString() { | |
return this.isValid ? this.toISO() : INVALID; | |
} | |
/** | |
* Returns the epoch milliseconds of this DateTime. Alias of {@link DateTime#toMillis} | |
* @return {number} | |
*/ | |
valueOf() { | |
return this.toMillis(); | |
} | |
/** | |
* Returns the epoch milliseconds of this DateTime. | |
* @return {number} | |
*/ | |
toMillis() { | |
return this.isValid ? this.ts : NaN; | |
} | |
/** | |
* Returns the epoch seconds of this DateTime. | |
* @return {number} | |
*/ | |
toSeconds() { | |
return this.isValid ? this.ts / 1e3 : NaN; | |
} | |
/** | |
* Returns the epoch seconds (as a whole number) of this DateTime. | |
* @return {number} | |
*/ | |
toUnixInteger() { | |
return this.isValid ? Math.floor(this.ts / 1e3) : NaN; | |
} | |
/** | |
* Returns an ISO 8601 representation of this DateTime appropriate for use in JSON. | |
* @return {string} | |
*/ | |
toJSON() { | |
return this.toISO(); | |
} | |
/** | |
* Returns a BSON serializable equivalent to this DateTime. | |
* @return {Date} | |
*/ | |
toBSON() { | |
return this.toJSDate(); | |
} | |
/** | |
* Returns a JavaScript object with this DateTime's year, month, day, and so on. | |
* @param opts - options for generating the object | |
* @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output | |
* @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 } | |
* @return {Object} | |
*/ | |
toObject(opts = {}) { | |
if (!this.isValid) | |
return {}; | |
const base = { ...this.c }; | |
if (opts.includeConfig) { | |
base.outputCalendar = this.outputCalendar; | |
base.numberingSystem = this.loc.numberingSystem; | |
base.locale = this.loc.locale; | |
} | |
return base; | |
} | |
/** | |
* Returns a JavaScript Date equivalent to this DateTime. | |
* @return {Date} | |
*/ | |
toJSDate() { | |
return new Date(this.isValid ? this.ts : NaN); | |
} | |
// COMPARE | |
/** | |
* Return the difference between two DateTimes as a Duration. | |
* @param {DateTime} otherDateTime - the DateTime to compare this one to | |
* @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration. | |
* @param {Object} opts - options that affect the creation of the Duration | |
* @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use | |
* @example | |
* var i1 = DateTime.fromISO('1982-05-25T09:45'), | |
* i2 = DateTime.fromISO('1983-10-14T10:30'); | |
* i2.diff(i1).toObject() //=> { milliseconds: 43807500000 } | |
* i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 } | |
* i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 } | |
* i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 } | |
* @return {Duration} | |
*/ | |
diff(otherDateTime, unit = "milliseconds", opts = {}) { | |
if (!this.isValid || !otherDateTime.isValid) { | |
return Duration.invalid("created by diffing an invalid DateTime"); | |
} | |
const durOpts = { locale: this.locale, numberingSystem: this.numberingSystem, ...opts }; | |
const units = maybeArray(unit).map(Duration.normalizeUnit), otherIsLater = otherDateTime.valueOf() > this.valueOf(), earlier = otherIsLater ? this : otherDateTime, later = otherIsLater ? otherDateTime : this, diffed = diff(earlier, later, units, durOpts); | |
return otherIsLater ? diffed.negate() : diffed; | |
} | |
/** | |
* Return the difference between this DateTime and right now. | |
* See {@link DateTime#diff} | |
* @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration | |
* @param {Object} opts - options that affect the creation of the Duration | |
* @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use | |
* @return {Duration} | |
*/ | |
diffNow(unit = "milliseconds", opts = {}) { | |
return this.diff(DateTime.now(), unit, opts); | |
} | |
/** | |
* Return an Interval spanning between this DateTime and another DateTime | |
* @param {DateTime} otherDateTime - the other end point of the Interval | |
* @return {Interval} | |
*/ | |
until(otherDateTime) { | |
return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this; | |
} | |
/** | |
* Return whether this DateTime is in the same unit of time as another DateTime. | |
* Higher-order units must also be identical for this function to return `true`. | |
* Note that time zones are **ignored** in this comparison, which compares the **local** calendar time. Use {@link DateTime#setZone} to convert one of the dates if needed. | |
* @param {DateTime} otherDateTime - the other DateTime | |
* @param {string} unit - the unit of time to check sameness on | |
* @example DateTime.now().hasSame(otherDT, 'day'); //~> true if otherDT is in the same current calendar day | |
* @return {boolean} | |
*/ | |
hasSame(otherDateTime, unit) { | |
if (!this.isValid) | |
return false; | |
const inputMs = otherDateTime.valueOf(); | |
const adjustedToZone = this.setZone(otherDateTime.zone, { keepLocalTime: true }); | |
return adjustedToZone.startOf(unit) <= inputMs && inputMs <= adjustedToZone.endOf(unit); | |
} | |
/** | |
* Equality check | |
* Two DateTimes are equal if and only if they represent the same millisecond, have the same zone and location, and are both valid. | |
* To compare just the millisecond values, use `+dt1 === +dt2`. | |
* @param {DateTime} other - the other DateTime | |
* @return {boolean} | |
*/ | |
equals(other) { | |
return this.isValid && other.isValid && this.valueOf() === other.valueOf() && this.zone.equals(other.zone) && this.loc.equals(other.loc); | |
} | |
/** | |
* Returns a string representation of a this time relative to now, such as "in two days". Can only internationalize if your | |
* platform supports Intl.RelativeTimeFormat. Rounds down by default. | |
* @param {Object} options - options that affect the output | |
* @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now. | |
* @param {string} [options.style="long"] - the style of units, must be "long", "short", or "narrow" | |
* @param {string|string[]} options.unit - use a specific unit or array of units; if omitted, or an array, the method will pick the best unit. Use an array or one of "years", "quarters", "months", "weeks", "days", "hours", "minutes", or "seconds" | |
* @param {boolean} [options.round=true] - whether to round the numbers in the output. | |
* @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding. | |
* @param {string} options.locale - override the locale of this DateTime | |
* @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this | |
* @example DateTime.now().plus({ days: 1 }).toRelative() //=> "in 1 day" | |
* @example DateTime.now().setLocale("es").toRelative({ days: 1 }) //=> "dentro de 1 día" | |
* @example DateTime.now().plus({ days: 1 }).toRelative({ locale: "fr" }) //=> "dans 23 heures" | |
* @example DateTime.now().minus({ days: 2 }).toRelative() //=> "2 days ago" | |
* @example DateTime.now().minus({ days: 2 }).toRelative({ unit: "hours" }) //=> "48 hours ago" | |
* @example DateTime.now().minus({ hours: 36 }).toRelative({ round: false }) //=> "1.5 days ago" | |
*/ | |
toRelative(options = {}) { | |
if (!this.isValid) | |
return null; | |
const base = options.base || DateTime.fromObject({}, { zone: this.zone }), padding = options.padding ? this < base ? -options.padding : options.padding : 0; | |
let units = ["years", "months", "days", "hours", "minutes", "seconds"]; | |
let unit = options.unit; | |
if (Array.isArray(options.unit)) { | |
units = options.unit; | |
unit = void 0; | |
} | |
return diffRelative(base, this.plus(padding), { | |
...options, | |
numeric: "always", | |
units, | |
unit | |
}); | |
} | |
/** | |
* Returns a string representation of this date relative to today, such as "yesterday" or "next month". | |
* Only internationalizes on platforms that supports Intl.RelativeTimeFormat. | |
* @param {Object} options - options that affect the output | |
* @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now. | |
* @param {string} options.locale - override the locale of this DateTime | |
* @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of "years", "quarters", "months", "weeks", or "days" | |
* @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this | |
* @example DateTime.now().plus({ days: 1 }).toRelativeCalendar() //=> "tomorrow" | |
* @example DateTime.now().setLocale("es").plus({ days: 1 }).toRelative() //=> ""mañana" | |
* @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: "fr" }) //=> "demain" | |
* @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> "2 days ago" | |
*/ | |
toRelativeCalendar(options = {}) { | |
if (!this.isValid) | |
return null; | |
return diffRelative(options.base || DateTime.fromObject({}, { zone: this.zone }), this, { | |
...options, | |
numeric: "auto", | |
units: ["years", "months", "days"], | |
calendary: true | |
}); | |
} | |
/** | |
* Return the min of several date times | |
* @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum | |
* @return {DateTime} the min DateTime, or undefined if called with no argument | |
*/ | |
static min(...dateTimes) { | |
if (!dateTimes.every(DateTime.isDateTime)) { | |
throw new InvalidArgumentError("min requires all arguments be DateTimes"); | |
} | |
return bestBy(dateTimes, (i) => i.valueOf(), Math.min); | |
} | |
/** | |
* Return the max of several date times | |
* @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum | |
* @return {DateTime} the max DateTime, or undefined if called with no argument | |
*/ | |
static max(...dateTimes) { | |
if (!dateTimes.every(DateTime.isDateTime)) { | |
throw new InvalidArgumentError("max requires all arguments be DateTimes"); | |
} | |
return bestBy(dateTimes, (i) => i.valueOf(), Math.max); | |
} | |
// MISC | |
/** | |
* Explain how a string would be parsed by fromFormat() | |
* @param {string} text - the string to parse | |
* @param {string} fmt - the format the string is expected to be in (see description) | |
* @param {Object} options - options taken by fromFormat() | |
* @return {Object} | |
*/ | |
static fromFormatExplain(text, fmt, options = {}) { | |
const { locale = null, numberingSystem = null } = options, localeToUse = Locale.fromOpts({ | |
locale, | |
numberingSystem, | |
defaultToEN: true | |
}); | |
return explainFromTokens(localeToUse, text, fmt); | |
} | |
/** | |
* @deprecated use fromFormatExplain instead | |
*/ | |
static fromStringExplain(text, fmt, options = {}) { | |
return DateTime.fromFormatExplain(text, fmt, options); | |
} | |
// FORMAT PRESETS | |
/** | |
* {@link DateTime#toLocaleString} format like 10/14/1983 | |
* @type {Object} | |
*/ | |
static get DATE_SHORT() { | |
return DATE_SHORT; | |
} | |
/** | |
* {@link DateTime#toLocaleString} format like 'Oct 14, 1983' | |
* @type {Object} | |
*/ | |
static get DATE_MED() { | |
return DATE_MED; | |
} | |
/** | |
* {@link DateTime#toLocaleString} format like 'Fri, Oct 14, 1983' | |
* @type {Object} | |
*/ | |
static get DATE_MED_WITH_WEEKDAY() { | |
return DATE_MED_WITH_WEEKDAY; | |
} | |
/** | |
* {@link DateTime#toLocaleString} format like 'October 14, 1983' | |
* @type {Object} | |
*/ | |
static get DATE_FULL() { | |
return DATE_FULL; | |
} | |
/** | |
* {@link DateTime#toLocaleString} format like 'Tuesday, October 14, 1983' | |
* @type {Object} | |
*/ | |
static get DATE_HUGE() { | |
return DATE_HUGE; | |
} | |
/** | |
* {@link DateTime#toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is. | |
* @type {Object} | |
*/ | |
static get TIME_SIMPLE() { | |
return TIME_SIMPLE; | |
} | |
/** | |
* {@link DateTime#toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is. | |
* @type {Object} | |
*/ | |
static get TIME_WITH_SECONDS() { | |
return TIME_WITH_SECONDS; | |
} | |
/** | |
* {@link DateTime#toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is. | |
* @type {Object} | |
*/ | |
static get TIME_WITH_SHORT_OFFSET() { | |
return TIME_WITH_SHORT_OFFSET; | |
} | |
/** | |
* {@link DateTime#toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is. | |
* @type {Object} | |
*/ | |
static get TIME_WITH_LONG_OFFSET() { | |
return TIME_WITH_LONG_OFFSET; | |
} | |
/** | |
* {@link DateTime#toLocaleString} format like '09:30', always 24-hour. | |
* @type {Object} | |
*/ | |
static get TIME_24_SIMPLE() { | |
return TIME_24_SIMPLE; | |
} | |
/** | |
* {@link DateTime#toLocaleString} format like '09:30:23', always 24-hour. | |
* @type {Object} | |
*/ | |
static get TIME_24_WITH_SECONDS() { | |
return TIME_24_WITH_SECONDS; | |
} | |
/** | |
* {@link DateTime#toLocaleString} format like '09:30:23 EDT', always 24-hour. | |
* @type {Object} | |
*/ | |
static get TIME_24_WITH_SHORT_OFFSET() { | |
return TIME_24_WITH_SHORT_OFFSET; | |
} | |
/** | |
* {@link DateTime#toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour. | |
* @type {Object} | |
*/ | |
static get TIME_24_WITH_LONG_OFFSET() { | |
return TIME_24_WITH_LONG_OFFSET; | |
} | |
/** | |
* {@link DateTime#toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is. | |
* @type {Object} | |
*/ | |
static get DATETIME_SHORT() { | |
return DATETIME_SHORT; | |
} | |
/** | |
* {@link DateTime#toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is. | |
* @type {Object} | |
*/ | |
static get DATETIME_SHORT_WITH_SECONDS() { | |
return DATETIME_SHORT_WITH_SECONDS; | |
} | |
/** | |
* {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is. | |
* @type {Object} | |
*/ | |
static get DATETIME_MED() { | |
return DATETIME_MED; | |
} | |
/** | |
* {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is. | |
* @type {Object} | |
*/ | |
static get DATETIME_MED_WITH_SECONDS() { | |
return DATETIME_MED_WITH_SECONDS; | |
} | |
/** | |
* {@link DateTime#toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is. | |
* @type {Object} | |
*/ | |
static get DATETIME_MED_WITH_WEEKDAY() { | |
return DATETIME_MED_WITH_WEEKDAY; | |
} | |
/** | |
* {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is. | |
* @type {Object} | |
*/ | |
static get DATETIME_FULL() { | |
return DATETIME_FULL; | |
} | |
/** | |
* {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is. | |
* @type {Object} | |
*/ | |
static get DATETIME_FULL_WITH_SECONDS() { | |
return DATETIME_FULL_WITH_SECONDS; | |
} | |
/** | |
* {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is. | |
* @type {Object} | |
*/ | |
static get DATETIME_HUGE() { | |
return DATETIME_HUGE; | |
} | |
/** | |
* {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is. | |
* @type {Object} | |
*/ | |
static get DATETIME_HUGE_WITH_SECONDS() { | |
return DATETIME_HUGE_WITH_SECONDS; | |
} | |
}; | |
function friendlyDateTime(dateTimeish) { | |
if (DateTime.isDateTime(dateTimeish)) { | |
return dateTimeish; | |
} else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) { | |
return DateTime.fromJSDate(dateTimeish); | |
} else if (dateTimeish && typeof dateTimeish === "object") { | |
return DateTime.fromObject(dateTimeish); | |
} else { | |
throw new InvalidArgumentError( | |
`Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}` | |
); | |
} | |
} | |
var DEFAULT_QUERY_SETTINGS = { | |
renderNullAs: "\\-", | |
taskCompletionTracking: false, | |
taskCompletionUseEmojiShorthand: false, | |
taskCompletionText: "completion", | |
taskCompletionDateFormat: "yyyy-MM-dd", | |
recursiveSubTaskCompletion: false, | |
warnOnEmptyResult: true, | |
refreshEnabled: true, | |
refreshInterval: 2500, | |
defaultDateFormat: "MMMM dd, yyyy", | |
defaultDateTimeFormat: "h:mm a - MMMM dd, yyyy", | |
maxRecursiveRenderDepth: 4, | |
tableIdColumnName: "File", | |
tableGroupColumnName: "Group", | |
showResultCount: true | |
}; | |
var DEFAULT_EXPORT_SETTINGS = { | |
allowHtml: true | |
}; | |
({ | |
...DEFAULT_QUERY_SETTINGS, | |
...DEFAULT_EXPORT_SETTINGS, | |
...{ | |
inlineQueryPrefix: "=", | |
inlineJsQueryPrefix: "$=", | |
inlineQueriesInCodeblocks: true, | |
enableInlineDataview: true, | |
enableDataviewJs: false, | |
enableInlineDataviewJs: false, | |
prettyRenderInlineFields: true, | |
dataviewJsKeyword: "dataviewjs" | |
} | |
}); | |
var Success = class { | |
constructor(value) { | |
this.value = value; | |
this.successful = true; | |
} | |
map(f) { | |
return new Success(f(this.value)); | |
} | |
flatMap(f) { | |
return f(this.value); | |
} | |
mapErr(f) { | |
return this; | |
} | |
bimap(succ, _fail) { | |
return this.map(succ); | |
} | |
orElse(_value) { | |
return this.value; | |
} | |
cast() { | |
return this; | |
} | |
orElseThrow(_message) { | |
return this.value; | |
} | |
}; | |
var Failure = class { | |
constructor(error4) { | |
this.error = error4; | |
this.successful = false; | |
} | |
map(_f) { | |
return this; | |
} | |
flatMap(_f) { | |
return this; | |
} | |
mapErr(f) { | |
return new Failure(f(this.error)); | |
} | |
bimap(_succ, fail) { | |
return this.mapErr(fail); | |
} | |
orElse(value) { | |
return value; | |
} | |
cast() { | |
return this; | |
} | |
orElseThrow(message) { | |
if (message) | |
throw new Error(message(this.error)); | |
else | |
throw new Error("" + this.error); | |
} | |
}; | |
var Result; | |
(function(Result2) { | |
function success(value) { | |
return new Success(value); | |
} | |
Result2.success = success; | |
function failure(error4) { | |
return new Failure(error4); | |
} | |
Result2.failure = failure; | |
function flatMap2(first, second, f) { | |
if (first.successful) { | |
if (second.successful) | |
return f(first.value, second.value); | |
else | |
return failure(second.error); | |
} else { | |
return failure(first.error); | |
} | |
} | |
Result2.flatMap2 = flatMap2; | |
function map2(first, second, f) { | |
return flatMap2(first, second, (a, b) => success(f(a, b))); | |
} | |
Result2.map2 = map2; | |
})(Result || (Result = {})); | |
var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; | |
var parsimmon_umd_min = { exports: {} }; | |
(function(module3, exports2) { | |
!function(n2, t2) { | |
module3.exports = t2(); | |
}("undefined" != typeof self ? self : commonjsGlobal, function() { | |
return function(n2) { | |
var t2 = {}; | |
function r(e) { | |
if (t2[e]) | |
return t2[e].exports; | |
var u = t2[e] = { i: e, l: false, exports: {} }; | |
return n2[e].call(u.exports, u, u.exports, r), u.l = true, u.exports; | |
} | |
return r.m = n2, r.c = t2, r.d = function(n3, t3, e) { | |
r.o(n3, t3) || Object.defineProperty(n3, t3, { configurable: false, enumerable: true, get: e }); | |
}, r.r = function(n3) { | |
Object.defineProperty(n3, "__esModule", { value: true }); | |
}, r.n = function(n3) { | |
var t3 = n3 && n3.__esModule ? function() { | |
return n3.default; | |
} : function() { | |
return n3; | |
}; | |
return r.d(t3, "a", t3), t3; | |
}, r.o = function(n3, t3) { | |
return Object.prototype.hasOwnProperty.call(n3, t3); | |
}, r.p = "", r(r.s = 0); | |
}([function(n2, t2, r) { | |
function e(n3) { | |
if (!(this instanceof e)) | |
return new e(n3); | |
this._ = n3; | |
} | |
var u = e.prototype; | |
function o(n3, t3) { | |
for (var r2 = 0; r2 < n3; r2++) | |
t3(r2); | |
} | |
function i(n3, t3, r2) { | |
return function(n4, t4) { | |
o(t4.length, function(r3) { | |
n4(t4[r3], r3, t4); | |
}); | |
}(function(r3, e2, u2) { | |
t3 = n3(t3, r3, e2, u2); | |
}, r2), t3; | |
} | |
function a(n3, t3) { | |
return i(function(t4, r2, e2, u2) { | |
return t4.concat([n3(r2, e2, u2)]); | |
}, [], t3); | |
} | |
function f(n3, t3) { | |
var r2 = { v: 0, buf: t3 }; | |
return o(n3, function() { | |
var n4; | |
r2 = { v: r2.v << 1 | (n4 = r2.buf, n4[0] >> 7), buf: function(n5) { | |
var t4 = i(function(n6, t5, r3, e2) { | |
return n6.concat(r3 === e2.length - 1 ? Buffer.from([t5, 0]).readUInt16BE(0) : e2.readUInt16BE(r3)); | |
}, [], n5); | |
return Buffer.from(a(function(n6) { | |
return (n6 << 1 & 65535) >> 8; | |
}, t4)); | |
}(r2.buf) }; | |
}), r2; | |
} | |
function c() { | |
return "undefined" != typeof Buffer; | |
} | |
function s2() { | |
if (!c()) | |
throw new Error("Buffer global does not exist; please use webpack if you need to parse Buffers in the browser."); | |
} | |
function l2(n3) { | |
s2(); | |
var t3 = i(function(n4, t4) { | |
return n4 + t4; | |
}, 0, n3); | |
if (t3 % 8 != 0) | |
throw new Error("The bits [" + n3.join(", ") + "] add up to " + t3 + " which is not an even number of bytes; the total should be divisible by 8"); | |
var r2, u2 = t3 / 8, o2 = (r2 = function(n4) { | |
return n4 > 48; | |
}, i(function(n4, t4) { | |
return n4 || (r2(t4) ? t4 : n4); | |
}, null, n3)); | |
if (o2) | |
throw new Error(o2 + " bit range requested exceeds 48 bit (6 byte) Number max."); | |
return new e(function(t4, r3) { | |
var e2 = u2 + r3; | |
return e2 > t4.length ? x(r3, u2.toString() + " bytes") : b(e2, i(function(n4, t5) { | |
var r4 = f(t5, n4.buf); | |
return { coll: n4.coll.concat(r4.v), buf: r4.buf }; | |
}, { coll: [], buf: t4.slice(r3, e2) }, n3).coll); | |
}); | |
} | |
function h(n3, t3) { | |
return new e(function(r2, e2) { | |
return s2(), e2 + t3 > r2.length ? x(e2, t3 + " bytes for " + n3) : b(e2 + t3, r2.slice(e2, e2 + t3)); | |
}); | |
} | |
function p(n3, t3) { | |
if ("number" != typeof (r2 = t3) || Math.floor(r2) !== r2 || t3 < 0 || t3 > 6) | |
throw new Error(n3 + " requires integer length in range [0, 6]."); | |
var r2; | |
} | |
function d(n3) { | |
return p("uintBE", n3), h("uintBE(" + n3 + ")", n3).map(function(t3) { | |
return t3.readUIntBE(0, n3); | |
}); | |
} | |
function v(n3) { | |
return p("uintLE", n3), h("uintLE(" + n3 + ")", n3).map(function(t3) { | |
return t3.readUIntLE(0, n3); | |
}); | |
} | |
function g(n3) { | |
return p("intBE", n3), h("intBE(" + n3 + ")", n3).map(function(t3) { | |
return t3.readIntBE(0, n3); | |
}); | |
} | |
function m(n3) { | |
return p("intLE", n3), h("intLE(" + n3 + ")", n3).map(function(t3) { | |
return t3.readIntLE(0, n3); | |
}); | |
} | |
function y(n3) { | |
return n3 instanceof e; | |
} | |
function E(n3) { | |
return "[object Array]" === {}.toString.call(n3); | |
} | |
function w(n3) { | |
return c() && Buffer.isBuffer(n3); | |
} | |
function b(n3, t3) { | |
return { status: true, index: n3, value: t3, furthest: -1, expected: [] }; | |
} | |
function x(n3, t3) { | |
return E(t3) || (t3 = [t3]), { status: false, index: -1, value: null, furthest: n3, expected: t3 }; | |
} | |
function B(n3, t3) { | |
if (!t3) | |
return n3; | |
if (n3.furthest > t3.furthest) | |
return n3; | |
var r2 = n3.furthest === t3.furthest ? function(n4, t4) { | |
if (function() { | |
if (void 0 !== e._supportsSet) | |
return e._supportsSet; | |
var n5 = "undefined" != typeof Set; | |
return e._supportsSet = n5, n5; | |
}() && Array.from) { | |
for (var r3 = new Set(n4), u2 = 0; u2 < t4.length; u2++) | |
r3.add(t4[u2]); | |
var o2 = Array.from(r3); | |
return o2.sort(), o2; | |
} | |
for (var i2 = {}, a2 = 0; a2 < n4.length; a2++) | |
i2[n4[a2]] = true; | |
for (var f2 = 0; f2 < t4.length; f2++) | |
i2[t4[f2]] = true; | |
var c2 = []; | |
for (var s3 in i2) | |
({}).hasOwnProperty.call(i2, s3) && c2.push(s3); | |
return c2.sort(), c2; | |
}(n3.expected, t3.expected) : t3.expected; | |
return { status: n3.status, index: n3.index, value: n3.value, furthest: t3.furthest, expected: r2 }; | |
} | |
var j = {}; | |
function S(n3, t3) { | |
if (w(n3)) | |
return { offset: t3, line: -1, column: -1 }; | |
n3 in j || (j[n3] = {}); | |
for (var r2 = j[n3], e2 = 0, u2 = 0, o2 = 0, i2 = t3; i2 >= 0; ) { | |
if (i2 in r2) { | |
e2 = r2[i2].line, 0 === o2 && (o2 = r2[i2].lineStart); | |
break; | |
} | |
("\n" === n3.charAt(i2) || "\r" === n3.charAt(i2) && "\n" !== n3.charAt(i2 + 1)) && (u2++, 0 === o2 && (o2 = i2 + 1)), i2--; | |
} | |
var a2 = e2 + u2, f2 = t3 - o2; | |
return r2[t3] = { line: a2, lineStart: o2 }, { offset: t3, line: a2 + 1, column: f2 + 1 }; | |
} | |
function _23(n3) { | |
if (!y(n3)) | |
throw new Error("not a parser: " + n3); | |
} | |
function L(n3, t3) { | |
return "string" == typeof n3 ? n3.charAt(t3) : n3[t3]; | |
} | |
function O(n3) { | |
if ("number" != typeof n3) | |
throw new Error("not a number: " + n3); | |
} | |
function k(n3) { | |
if ("function" != typeof n3) | |
throw new Error("not a function: " + n3); | |
} | |
function P(n3) { | |
if ("string" != typeof n3) | |
throw new Error("not a string: " + n3); | |
} | |
var q = 2, A = 3, I = 8, F = 5 * I, M = 4 * I, z = " "; | |
function R(n3, t3) { | |
return new Array(t3 + 1).join(n3); | |
} | |
function U(n3, t3, r2) { | |
var e2 = t3 - n3.length; | |
return e2 <= 0 ? n3 : R(r2, e2) + n3; | |
} | |
function W(n3, t3, r2, e2) { | |
return { from: n3 - t3 > 0 ? n3 - t3 : 0, to: n3 + r2 > e2 ? e2 : n3 + r2 }; | |
} | |
function D(n3, t3) { | |
var r2, e2, u2, o2, f2, c2 = t3.index, s3 = c2.offset, l3 = 1; | |
if (s3 === n3.length) | |
return "Got the end of the input"; | |
if (w(n3)) { | |
var h2 = s3 - s3 % I, p2 = s3 - h2, d2 = W(h2, F, M + I, n3.length), v2 = a(function(n4) { | |
return a(function(n5) { | |
return U(n5.toString(16), 2, "0"); | |
}, n4); | |
}, function(n4, t4) { | |
var r3 = n4.length, e3 = [], u3 = 0; | |
if (r3 <= t4) | |
return [n4.slice()]; | |
for (var o3 = 0; o3 < r3; o3++) | |
e3[u3] || e3.push([]), e3[u3].push(n4[o3]), (o3 + 1) % t4 == 0 && u3++; | |
return e3; | |
}(n3.slice(d2.from, d2.to).toJSON().data, I)); | |
o2 = function(n4) { | |
return 0 === n4.from && 1 === n4.to ? { from: n4.from, to: n4.to } : { from: n4.from / I, to: Math.floor(n4.to / I) }; | |
}(d2), e2 = h2 / I, r2 = 3 * p2, p2 >= 4 && (r2 += 1), l3 = 2, u2 = a(function(n4) { | |
return n4.length <= 4 ? n4.join(" ") : n4.slice(0, 4).join(" ") + " " + n4.slice(4).join(" "); | |
}, v2), (f2 = (8 * (o2.to > 0 ? o2.to - 1 : o2.to)).toString(16).length) < 2 && (f2 = 2); | |
} else { | |
var g2 = n3.split(/\r\n|[\n\r\u2028\u2029]/); | |
r2 = c2.column - 1, e2 = c2.line - 1, o2 = W(e2, q, A, g2.length), u2 = g2.slice(o2.from, o2.to), f2 = o2.to.toString().length; | |
} | |
var m2 = e2 - o2.from; | |
return w(n3) && (f2 = (8 * (o2.to > 0 ? o2.to - 1 : o2.to)).toString(16).length) < 2 && (f2 = 2), i(function(t4, e3, u3) { | |
var i2, a2 = u3 === m2, c3 = a2 ? "> " : z; | |
return i2 = w(n3) ? U((8 * (o2.from + u3)).toString(16), f2, "0") : U((o2.from + u3 + 1).toString(), f2, " "), [].concat(t4, [c3 + i2 + " | " + e3], a2 ? [z + R(" ", f2) + " | " + U("", r2, " ") + R("^", l3)] : []); | |
}, [], u2).join("\n"); | |
} | |
function N(n3, t3) { | |
return ["\n", "-- PARSING FAILED " + R("-", 50), "\n\n", D(n3, t3), "\n\n", (r2 = t3.expected, 1 === r2.length ? "Expected:\n\n" + r2[0] : "Expected one of the following: \n\n" + r2.join(", ")), "\n"].join(""); | |
var r2; | |
} | |
function G(n3) { | |
return void 0 !== n3.flags ? n3.flags : [n3.global ? "g" : "", n3.ignoreCase ? "i" : "", n3.multiline ? "m" : "", n3.unicode ? "u" : "", n3.sticky ? "y" : ""].join(""); | |
} | |
function C() { | |
for (var n3 = [].slice.call(arguments), t3 = n3.length, r2 = 0; r2 < t3; r2 += 1) | |
_23(n3[r2]); | |
return e(function(r3, e2) { | |
for (var u2, o2 = new Array(t3), i2 = 0; i2 < t3; i2 += 1) { | |
if (!(u2 = B(n3[i2]._(r3, e2), u2)).status) | |
return u2; | |
o2[i2] = u2.value, e2 = u2.index; | |
} | |
return B(b(e2, o2), u2); | |
}); | |
} | |
function J() { | |
var n3 = [].slice.call(arguments); | |
if (0 === n3.length) | |
throw new Error("seqMap needs at least one argument"); | |
var t3 = n3.pop(); | |
return k(t3), C.apply(null, n3).map(function(n4) { | |
return t3.apply(null, n4); | |
}); | |
} | |
function T() { | |
var n3 = [].slice.call(arguments), t3 = n3.length; | |
if (0 === t3) | |
return Y("zero alternates"); | |
for (var r2 = 0; r2 < t3; r2 += 1) | |
_23(n3[r2]); | |
return e(function(t4, r3) { | |
for (var e2, u2 = 0; u2 < n3.length; u2 += 1) | |
if ((e2 = B(n3[u2]._(t4, r3), e2)).status) | |
return e2; | |
return e2; | |
}); | |
} | |
function V(n3, t3) { | |
return H(n3, t3).or(X([])); | |
} | |
function H(n3, t3) { | |
return _23(n3), _23(t3), J(n3, t3.then(n3).many(), function(n4, t4) { | |
return [n4].concat(t4); | |
}); | |
} | |
function K(n3) { | |
P(n3); | |
var t3 = "'" + n3 + "'"; | |
return e(function(r2, e2) { | |
var u2 = e2 + n3.length, o2 = r2.slice(e2, u2); | |
return o2 === n3 ? b(u2, o2) : x(e2, t3); | |
}); | |
} | |
function Q(n3, t3) { | |
!function(n4) { | |
if (!(n4 instanceof RegExp)) | |
throw new Error("not a regexp: " + n4); | |
for (var t4 = G(n4), r3 = 0; r3 < t4.length; r3++) { | |
var e2 = t4.charAt(r3); | |
if ("i" !== e2 && "m" !== e2 && "u" !== e2 && "s" !== e2) | |
throw new Error('unsupported regexp flag "' + e2 + '": ' + n4); | |
} | |
}(n3), arguments.length >= 2 ? O(t3) : t3 = 0; | |
var r2 = function(n4) { | |
return RegExp("^(?:" + n4.source + ")", G(n4)); | |
}(n3), u2 = "" + n3; | |
return e(function(n4, e2) { | |
var o2 = r2.exec(n4.slice(e2)); | |
if (o2) { | |
if (0 <= t3 && t3 <= o2.length) { | |
var i2 = o2[0], a2 = o2[t3]; | |
return b(e2 + i2.length, a2); | |
} | |
return x(e2, "valid match group (0 to " + o2.length + ") in " + u2); | |
} | |
return x(e2, u2); | |
}); | |
} | |
function X(n3) { | |
return e(function(t3, r2) { | |
return b(r2, n3); | |
}); | |
} | |
function Y(n3) { | |
return e(function(t3, r2) { | |
return x(r2, n3); | |
}); | |
} | |
function Z(n3) { | |
if (y(n3)) | |
return e(function(t3, r2) { | |
var e2 = n3._(t3, r2); | |
return e2.index = r2, e2.value = "", e2; | |
}); | |
if ("string" == typeof n3) | |
return Z(K(n3)); | |
if (n3 instanceof RegExp) | |
return Z(Q(n3)); | |
throw new Error("not a string, regexp, or parser: " + n3); | |
} | |
function $(n3) { | |
return _23(n3), e(function(t3, r2) { | |
var e2 = n3._(t3, r2), u2 = t3.slice(r2, e2.index); | |
return e2.status ? x(r2, 'not "' + u2 + '"') : b(r2, null); | |
}); | |
} | |
function nn(n3) { | |
return k(n3), e(function(t3, r2) { | |
var e2 = L(t3, r2); | |
return r2 < t3.length && n3(e2) ? b(r2 + 1, e2) : x(r2, "a character/byte matching " + n3); | |
}); | |
} | |
function tn(n3, t3) { | |
arguments.length < 2 && (t3 = n3, n3 = void 0); | |
var r2 = e(function(n4, e2) { | |
return r2._ = t3()._, r2._(n4, e2); | |
}); | |
return n3 ? r2.desc(n3) : r2; | |
} | |
function rn() { | |
return Y("fantasy-land/empty"); | |
} | |
u.parse = function(n3) { | |
if ("string" != typeof n3 && !w(n3)) | |
throw new Error(".parse must be called with a string or Buffer as its argument"); | |
var t3, r2 = this.skip(an)._(n3, 0); | |
return t3 = r2.status ? { status: true, value: r2.value } : { status: false, index: S(n3, r2.furthest), expected: r2.expected }, delete j[n3], t3; | |
}, u.tryParse = function(n3) { | |
var t3 = this.parse(n3); | |
if (t3.status) | |
return t3.value; | |
var r2 = N(n3, t3), e2 = new Error(r2); | |
throw e2.type = "ParsimmonError", e2.result = t3, e2; | |
}, u.assert = function(n3, t3) { | |
return this.chain(function(r2) { | |
return n3(r2) ? X(r2) : Y(t3); | |
}); | |
}, u.or = function(n3) { | |
return T(this, n3); | |
}, u.trim = function(n3) { | |
return this.wrap(n3, n3); | |
}, u.wrap = function(n3, t3) { | |
return J(n3, this, t3, function(n4, t4) { | |
return t4; | |
}); | |
}, u.thru = function(n3) { | |
return n3(this); | |
}, u.then = function(n3) { | |
return _23(n3), C(this, n3).map(function(n4) { | |
return n4[1]; | |
}); | |
}, u.many = function() { | |
var n3 = this; | |
return e(function(t3, r2) { | |
for (var e2 = [], u2 = void 0; ; ) { | |
if (!(u2 = B(n3._(t3, r2), u2)).status) | |
return B(b(r2, e2), u2); | |
if (r2 === u2.index) | |
throw new Error("infinite loop detected in .many() parser --- calling .many() on a parser which can accept zero characters is usually the cause"); | |
r2 = u2.index, e2.push(u2.value); | |
} | |
}); | |
}, u.tieWith = function(n3) { | |
return P(n3), this.map(function(t3) { | |
if (function(n4) { | |
if (!E(n4)) | |
throw new Error("not an array: " + n4); | |
}(t3), t3.length) { | |
P(t3[0]); | |
for (var r2 = t3[0], e2 = 1; e2 < t3.length; e2++) | |
P(t3[e2]), r2 += n3 + t3[e2]; | |
return r2; | |
} | |
return ""; | |
}); | |
}, u.tie = function() { | |
return this.tieWith(""); | |
}, u.times = function(n3, t3) { | |
var r2 = this; | |
return arguments.length < 2 && (t3 = n3), O(n3), O(t3), e(function(e2, u2) { | |
for (var o2 = [], i2 = void 0, a2 = void 0, f2 = 0; f2 < n3; f2 += 1) { | |
if (a2 = B(i2 = r2._(e2, u2), a2), !i2.status) | |
return a2; | |
u2 = i2.index, o2.push(i2.value); | |
} | |
for (; f2 < t3 && (a2 = B(i2 = r2._(e2, u2), a2), i2.status); f2 += 1) | |
u2 = i2.index, o2.push(i2.value); | |
return B(b(u2, o2), a2); | |
}); | |
}, u.result = function(n3) { | |
return this.map(function() { | |
return n3; | |
}); | |
}, u.atMost = function(n3) { | |
return this.times(0, n3); | |
}, u.atLeast = function(n3) { | |
return J(this.times(n3), this.many(), function(n4, t3) { | |
return n4.concat(t3); | |
}); | |
}, u.map = function(n3) { | |
k(n3); | |
var t3 = this; | |
return e(function(r2, e2) { | |
var u2 = t3._(r2, e2); | |
return u2.status ? B(b(u2.index, n3(u2.value)), u2) : u2; | |
}); | |
}, u.contramap = function(n3) { | |
k(n3); | |
var t3 = this; | |
return e(function(r2, e2) { | |
var u2 = t3.parse(n3(r2.slice(e2))); | |
return u2.status ? b(e2 + r2.length, u2.value) : u2; | |
}); | |
}, u.promap = function(n3, t3) { | |
return k(n3), k(t3), this.contramap(n3).map(t3); | |
}, u.skip = function(n3) { | |
return C(this, n3).map(function(n4) { | |
return n4[0]; | |
}); | |
}, u.mark = function() { | |
return J(en, this, en, function(n3, t3, r2) { | |
return { start: n3, value: t3, end: r2 }; | |
}); | |
}, u.node = function(n3) { | |
return J(en, this, en, function(t3, r2, e2) { | |
return { name: n3, value: r2, start: t3, end: e2 }; | |
}); | |
}, u.sepBy = function(n3) { | |
return V(this, n3); | |
}, u.sepBy1 = function(n3) { | |
return H(this, n3); | |
}, u.lookahead = function(n3) { | |
return this.skip(Z(n3)); | |
}, u.notFollowedBy = function(n3) { | |
return this.skip($(n3)); | |
}, u.desc = function(n3) { | |
E(n3) || (n3 = [n3]); | |
var t3 = this; | |
return e(function(r2, e2) { | |
var u2 = t3._(r2, e2); | |
return u2.status || (u2.expected = n3), u2; | |
}); | |
}, u.fallback = function(n3) { | |
return this.or(X(n3)); | |
}, u.ap = function(n3) { | |
return J(n3, this, function(n4, t3) { | |
return n4(t3); | |
}); | |
}, u.chain = function(n3) { | |
var t3 = this; | |
return e(function(r2, e2) { | |
var u2 = t3._(r2, e2); | |
return u2.status ? B(n3(u2.value)._(r2, u2.index), u2) : u2; | |
}); | |
}, u.concat = u.or, u.empty = rn, u.of = X, u["fantasy-land/ap"] = u.ap, u["fantasy-land/chain"] = u.chain, u["fantasy-land/concat"] = u.concat, u["fantasy-land/empty"] = u.empty, u["fantasy-land/of"] = u.of, u["fantasy-land/map"] = u.map; | |
var en = e(function(n3, t3) { | |
return b(t3, S(n3, t3)); | |
}), un = e(function(n3, t3) { | |
return t3 >= n3.length ? x(t3, "any character/byte") : b(t3 + 1, L(n3, t3)); | |
}), on = e(function(n3, t3) { | |
return b(n3.length, n3.slice(t3)); | |
}), an = e(function(n3, t3) { | |
return t3 < n3.length ? x(t3, "EOF") : b(t3, null); | |
}), fn = Q(/[0-9]/).desc("a digit"), cn = Q(/[0-9]*/).desc("optional digits"), sn = Q(/[a-z]/i).desc("a letter"), ln = Q(/[a-z]*/i).desc("optional letters"), hn = Q(/\s*/).desc("optional whitespace"), pn = Q(/\s+/).desc("whitespace"), dn = K("\r"), vn = K("\n"), gn = K("\r\n"), mn = T(gn, vn, dn).desc("newline"), yn = T(mn, an); | |
e.all = on, e.alt = T, e.any = un, e.cr = dn, e.createLanguage = function(n3) { | |
var t3 = {}; | |
for (var r2 in n3) | |
({}).hasOwnProperty.call(n3, r2) && function(r3) { | |
t3[r3] = tn(function() { | |
return n3[r3](t3); | |
}); | |
}(r2); | |
return t3; | |
}, e.crlf = gn, e.custom = function(n3) { | |
return e(n3(b, x)); | |
}, e.digit = fn, e.digits = cn, e.empty = rn, e.end = yn, e.eof = an, e.fail = Y, e.formatError = N, e.index = en, e.isParser = y, e.lazy = tn, e.letter = sn, e.letters = ln, e.lf = vn, e.lookahead = Z, e.makeFailure = x, e.makeSuccess = b, e.newline = mn, e.noneOf = function(n3) { | |
return nn(function(t3) { | |
return n3.indexOf(t3) < 0; | |
}).desc("none of '" + n3 + "'"); | |
}, e.notFollowedBy = $, e.of = X, e.oneOf = function(n3) { | |
for (var t3 = n3.split(""), r2 = 0; r2 < t3.length; r2++) | |
t3[r2] = "'" + t3[r2] + "'"; | |
return nn(function(t4) { | |
return n3.indexOf(t4) >= 0; | |
}).desc(t3); | |
}, e.optWhitespace = hn, e.Parser = e, e.range = function(n3, t3) { | |
return nn(function(r2) { | |
return n3 <= r2 && r2 <= t3; | |
}).desc(n3 + "-" + t3); | |
}, e.regex = Q, e.regexp = Q, e.sepBy = V, e.sepBy1 = H, e.seq = C, e.seqMap = J, e.seqObj = function() { | |
for (var n3, t3 = {}, r2 = 0, u2 = (n3 = arguments, Array.prototype.slice.call(n3)), o2 = u2.length, i2 = 0; i2 < o2; i2 += 1) { | |
var a2 = u2[i2]; | |
if (!y(a2)) { | |
if (E(a2) && 2 === a2.length && "string" == typeof a2[0] && y(a2[1])) { | |
var f2 = a2[0]; | |
if (Object.prototype.hasOwnProperty.call(t3, f2)) | |
throw new Error("seqObj: duplicate key " + f2); | |
t3[f2] = true, r2++; | |
continue; | |
} | |
throw new Error("seqObj arguments must be parsers or [string, parser] array pairs."); | |
} | |
} | |
if (0 === r2) | |
throw new Error("seqObj expects at least one named parser, found zero"); | |
return e(function(n4, t4) { | |
for (var r3, e2 = {}, i3 = 0; i3 < o2; i3 += 1) { | |
var a3, f3; | |
if (E(u2[i3]) ? (a3 = u2[i3][0], f3 = u2[i3][1]) : (a3 = null, f3 = u2[i3]), !(r3 = B(f3._(n4, t4), r3)).status) | |
return r3; | |
a3 && (e2[a3] = r3.value), t4 = r3.index; | |
} | |
return B(b(t4, e2), r3); | |
}); | |
}, e.string = K, e.succeed = X, e.takeWhile = function(n3) { | |
return k(n3), e(function(t3, r2) { | |
for (var e2 = r2; e2 < t3.length && n3(L(t3, e2)); ) | |
e2++; | |
return b(e2, t3.slice(r2, e2)); | |
}); | |
}, e.test = nn, e.whitespace = pn, e["fantasy-land/empty"] = rn, e["fantasy-land/of"] = X, e.Binary = { bitSeq: l2, bitSeqObj: function(n3) { | |
s2(); | |
var t3 = {}, r2 = 0, e2 = a(function(n4) { | |
if (E(n4)) { | |
var e3 = n4; | |
if (2 !== e3.length) | |
throw new Error("[" + e3.join(", ") + "] should be length 2, got length " + e3.length); | |
if (P(e3[0]), O(e3[1]), Object.prototype.hasOwnProperty.call(t3, e3[0])) | |
throw new Error("duplicate key in bitSeqObj: " + e3[0]); | |
return t3[e3[0]] = true, r2++, e3; | |
} | |
return O(n4), [null, n4]; | |
}, n3); | |
if (r2 < 1) | |
throw new Error("bitSeqObj expects at least one named pair, got [" + n3.join(", ") + "]"); | |
var u2 = a(function(n4) { | |
return n4[0]; | |
}, e2); | |
return l2(a(function(n4) { | |
return n4[1]; | |
}, e2)).map(function(n4) { | |
return i(function(n5, t4) { | |
return null !== t4[0] && (n5[t4[0]] = t4[1]), n5; | |
}, {}, a(function(t4, r3) { | |
return [t4, n4[r3]]; | |
}, u2)); | |
}); | |
}, byte: function(n3) { | |
if (s2(), O(n3), n3 > 255) | |
throw new Error("Value specified to byte constructor (" + n3 + "=0x" + n3.toString(16) + ") is larger in value than a single byte."); | |
var t3 = (n3 > 15 ? "0x" : "0x0") + n3.toString(16); | |
return e(function(r2, e2) { | |
var u2 = L(r2, e2); | |
return u2 === n3 ? b(e2 + 1, u2) : x(e2, t3); | |
}); | |
}, buffer: function(n3) { | |
return h("buffer", n3).map(function(n4) { | |
return Buffer.from(n4); | |
}); | |
}, encodedString: function(n3, t3) { | |
return h("string", t3).map(function(t4) { | |
return t4.toString(n3); | |
}); | |
}, uintBE: d, uint8BE: d(1), uint16BE: d(2), uint32BE: d(4), uintLE: v, uint8LE: v(1), uint16LE: v(2), uint32LE: v(4), intBE: g, int8BE: g(1), int16BE: g(2), int32BE: g(4), intLE: m, int8LE: m(1), int16LE: m(2), int32LE: m(4), floatBE: h("floatBE", 4).map(function(n3) { | |
return n3.readFloatBE(0); | |
}), floatLE: h("floatLE", 4).map(function(n3) { | |
return n3.readFloatLE(0); | |
}), doubleBE: h("doubleBE", 8).map(function(n3) { | |
return n3.readDoubleBE(0); | |
}), doubleLE: h("doubleLE", 8).map(function(n3) { | |
return n3.readDoubleLE(0); | |
}) }, n2.exports = e; | |
}]); | |
}); | |
})(parsimmon_umd_min); | |
var emojiRegex = () => { | |
return /(?:[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26F9(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC3\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDD-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF6](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7C\uDE80-\uDE86\uDE90-\uDEAC\uDEB0-\uDEBA\uDEC0-\uDEC2\uDED0-\uDED9\uDEE0-\uDEE7]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?))/g; | |
}; | |
function normalizeDuration(dur) { | |
if (dur === void 0 || dur === null) | |
return dur; | |
return dur.shiftToAll().normalize(); | |
} | |
function getFileTitle(path) { | |
if (path.includes("/")) | |
path = path.substring(path.lastIndexOf("/") + 1); | |
if (path.endsWith(".md")) | |
path = path.substring(0, path.length - 3); | |
return path; | |
} | |
parsimmon_umd_min.exports.alt(parsimmon_umd_min.exports.regex(new RegExp(emojiRegex(), "")), parsimmon_umd_min.exports.regex(/[0-9\p{Letter}_-]+/u).map((str) => str.toLocaleLowerCase()), parsimmon_umd_min.exports.whitespace.map((_23) => "-"), parsimmon_umd_min.exports.any.map((_23) => "")).many().map((result) => result.join("")); | |
var HEADER_CANONICALIZER = parsimmon_umd_min.exports.alt(parsimmon_umd_min.exports.regex(new RegExp(emojiRegex(), "")), parsimmon_umd_min.exports.regex(/[0-9\p{Letter}_-]+/u), parsimmon_umd_min.exports.whitespace.map((_23) => " "), parsimmon_umd_min.exports.any.map((_23) => " ")).many().map((result) => { | |
return result.join("").split(/\s+/).join(" ").trim(); | |
}); | |
function normalizeHeaderForLink(header) { | |
return HEADER_CANONICALIZER.tryParse(header); | |
} | |
function renderMinimalDuration(dur) { | |
dur = normalizeDuration(dur); | |
dur = Duration.fromObject(Object.fromEntries(Object.entries(dur.toObject()).filter(([, quantity]) => quantity > 0))); | |
return dur.toHuman(); | |
} | |
var Values; | |
(function(Values2) { | |
function toString(field, setting = DEFAULT_QUERY_SETTINGS, recursive = false) { | |
let wrapped = wrapValue(field); | |
if (!wrapped) | |
return setting.renderNullAs; | |
switch (wrapped.type) { | |
case "null": | |
return setting.renderNullAs; | |
case "string": | |
return wrapped.value; | |
case "number": | |
case "boolean": | |
return "" + wrapped.value; | |
case "html": | |
return wrapped.value.outerHTML; | |
case "widget": | |
return wrapped.value.markdown(); | |
case "link": | |
return wrapped.value.markdown(); | |
case "function": | |
return "<function>"; | |
case "array": | |
let result = ""; | |
if (recursive) | |
result += "["; | |
result += wrapped.value.map((f) => toString(f, setting, true)).join(", "); | |
if (recursive) | |
result += "]"; | |
return result; | |
case "object": | |
return "{ " + Object.entries(wrapped.value).map((e) => e[0] + ": " + toString(e[1], setting, true)).join(", ") + " }"; | |
case "date": | |
if (wrapped.value.second == 0 && wrapped.value.hour == 0 && wrapped.value.minute == 0) { | |
return wrapped.value.toFormat(setting.defaultDateFormat); | |
} | |
return wrapped.value.toFormat(setting.defaultDateTimeFormat); | |
case "duration": | |
return renderMinimalDuration(wrapped.value); | |
} | |
} | |
Values2.toString = toString; | |
function wrapValue(val) { | |
if (isNull(val)) | |
return { type: "null", value: val }; | |
else if (isNumber2(val)) | |
return { type: "number", value: val }; | |
else if (isString2(val)) | |
return { type: "string", value: val }; | |
else if (isBoolean(val)) | |
return { type: "boolean", value: val }; | |
else if (isDuration(val)) | |
return { type: "duration", value: val }; | |
else if (isDate2(val)) | |
return { type: "date", value: val }; | |
else if (isWidget(val)) | |
return { type: "widget", value: val }; | |
else if (isArray(val)) | |
return { type: "array", value: val }; | |
else if (isLink(val)) | |
return { type: "link", value: val }; | |
else if (isFunction(val)) | |
return { type: "function", value: val }; | |
else if (isHtml(val)) | |
return { type: "html", value: val }; | |
else if (isObject2(val)) | |
return { type: "object", value: val }; | |
else | |
return void 0; | |
} | |
Values2.wrapValue = wrapValue; | |
function mapLeaves(val, func) { | |
if (isObject2(val)) { | |
let result = {}; | |
for (let [key, value] of Object.entries(val)) | |
result[key] = mapLeaves(value, func); | |
return result; | |
} else if (isArray(val)) { | |
let result = []; | |
for (let value of val) | |
result.push(mapLeaves(value, func)); | |
return result; | |
} else { | |
return func(val); | |
} | |
} | |
Values2.mapLeaves = mapLeaves; | |
function compareValue(val1, val2, linkNormalizer) { | |
var _a, _b; | |
if (val1 === void 0) | |
val1 = null; | |
if (val2 === void 0) | |
val2 = null; | |
if (val1 === null && val2 === null) | |
return 0; | |
else if (val1 === null) | |
return -1; | |
else if (val2 === null) | |
return 1; | |
let wrap1 = wrapValue(val1); | |
let wrap2 = wrapValue(val2); | |
if (wrap1 === void 0 && wrap2 === void 0) | |
return 0; | |
else if (wrap1 === void 0) | |
return -1; | |
else if (wrap2 === void 0) | |
return 1; | |
if (wrap1.type != wrap2.type) | |
return wrap1.type.localeCompare(wrap2.type); | |
if (wrap1.value === wrap2.value) | |
return 0; | |
switch (wrap1.type) { | |
case "string": | |
return wrap1.value.localeCompare(wrap2.value); | |
case "number": | |
if (wrap1.value < wrap2.value) | |
return -1; | |
else if (wrap1.value == wrap2.value) | |
return 0; | |
return 1; | |
case "null": | |
return 0; | |
case "boolean": | |
if (wrap1.value == wrap2.value) | |
return 0; | |
else | |
return wrap1.value ? 1 : -1; | |
case "link": | |
let link1 = wrap1.value; | |
let link2 = wrap2.value; | |
let normalize = linkNormalizer !== null && linkNormalizer !== void 0 ? linkNormalizer : (x) => x; | |
let pathCompare = normalize(link1.path).localeCompare(normalize(link2.path)); | |
if (pathCompare != 0) | |
return pathCompare; | |
let typeCompare = link1.type.localeCompare(link2.type); | |
if (typeCompare != 0) | |
return typeCompare; | |
if (link1.subpath && !link2.subpath) | |
return 1; | |
if (!link1.subpath && link2.subpath) | |
return -1; | |
if (!link1.subpath && !link2.subpath) | |
return 0; | |
return ((_a = link1.subpath) !== null && _a !== void 0 ? _a : "").localeCompare((_b = link2.subpath) !== null && _b !== void 0 ? _b : ""); | |
case "date": | |
return wrap1.value < wrap2.value ? -1 : wrap1.value.equals(wrap2.value) ? 0 : 1; | |
case "duration": | |
return wrap1.value < wrap2.value ? -1 : wrap1.value.equals(wrap2.value) ? 0 : 1; | |
case "array": | |
let f1 = wrap1.value; | |
let f2 = wrap2.value; | |
for (let index = 0; index < Math.min(f1.length, f2.length); index++) { | |
let comp = compareValue(f1[index], f2[index]); | |
if (comp != 0) | |
return comp; | |
} | |
return f1.length - f2.length; | |
case "object": | |
let o1 = wrap1.value; | |
let o2 = wrap2.value; | |
let k1 = Array.from(Object.keys(o1)); | |
let k2 = Array.from(Object.keys(o2)); | |
k1.sort(); | |
k2.sort(); | |
let keyCompare = compareValue(k1, k2); | |
if (keyCompare != 0) | |
return keyCompare; | |
for (let key of k1) { | |
let comp = compareValue(o1[key], o2[key]); | |
if (comp != 0) | |
return comp; | |
} | |
return 0; | |
case "widget": | |
case "html": | |
case "function": | |
return 0; | |
} | |
} | |
Values2.compareValue = compareValue; | |
function typeOf(val) { | |
var _a; | |
return (_a = wrapValue(val)) === null || _a === void 0 ? void 0 : _a.type; | |
} | |
Values2.typeOf = typeOf; | |
function isTruthy(field) { | |
let wrapped = wrapValue(field); | |
if (!wrapped) | |
return false; | |
switch (wrapped.type) { | |
case "number": | |
return wrapped.value != 0; | |
case "string": | |
return wrapped.value.length > 0; | |
case "boolean": | |
return wrapped.value; | |
case "link": | |
return !!wrapped.value.path; | |
case "date": | |
return wrapped.value.toMillis() != 0; | |
case "duration": | |
return wrapped.value.as("seconds") != 0; | |
case "object": | |
return Object.keys(wrapped.value).length > 0; | |
case "array": | |
return wrapped.value.length > 0; | |
case "null": | |
return false; | |
case "html": | |
case "widget": | |
case "function": | |
return true; | |
} | |
} | |
Values2.isTruthy = isTruthy; | |
function deepCopy(field) { | |
if (field === null || field === void 0) | |
return field; | |
if (Values2.isArray(field)) { | |
return [].concat(field.map((v) => deepCopy(v))); | |
} else if (Values2.isObject(field)) { | |
let result = {}; | |
for (let [key, value] of Object.entries(field)) | |
result[key] = deepCopy(value); | |
return result; | |
} else { | |
return field; | |
} | |
} | |
Values2.deepCopy = deepCopy; | |
function isString2(val) { | |
return typeof val == "string"; | |
} | |
Values2.isString = isString2; | |
function isNumber2(val) { | |
return typeof val == "number"; | |
} | |
Values2.isNumber = isNumber2; | |
function isDate2(val) { | |
return val instanceof DateTime; | |
} | |
Values2.isDate = isDate2; | |
function isDuration(val) { | |
return val instanceof Duration; | |
} | |
Values2.isDuration = isDuration; | |
function isNull(val) { | |
return val === null || val === void 0; | |
} | |
Values2.isNull = isNull; | |
function isArray(val) { | |
return Array.isArray(val); | |
} | |
Values2.isArray = isArray; | |
function isBoolean(val) { | |
return typeof val === "boolean"; | |
} | |
Values2.isBoolean = isBoolean; | |
function isLink(val) { | |
return val instanceof Link3; | |
} | |
Values2.isLink = isLink; | |
function isWidget(val) { | |
return val instanceof Widget; | |
} | |
Values2.isWidget = isWidget; | |
function isHtml(val) { | |
if (typeof HTMLElement !== "undefined") { | |
return val instanceof HTMLElement; | |
} else { | |
return false; | |
} | |
} | |
Values2.isHtml = isHtml; | |
function isObject2(val) { | |
return typeof val == "object" && !isHtml(val) && !isWidget(val) && !isArray(val) && !isDuration(val) && !isDate2(val) && !isLink(val) && val !== void 0 && !isNull(val); | |
} | |
Values2.isObject = isObject2; | |
function isFunction(val) { | |
return typeof val == "function"; | |
} | |
Values2.isFunction = isFunction; | |
})(Values || (Values = {})); | |
var Groupings; | |
(function(Groupings2) { | |
function isElementGroup(entry) { | |
return Values.isObject(entry) && Object.keys(entry).length == 2 && "key" in entry && "rows" in entry; | |
} | |
Groupings2.isElementGroup = isElementGroup; | |
function isGrouping(entry) { | |
for (let element of entry) | |
if (!isElementGroup(element)) | |
return false; | |
return true; | |
} | |
Groupings2.isGrouping = isGrouping; | |
function count(elements) { | |
if (isGrouping(elements)) { | |
let result = 0; | |
for (let subgroup of elements) | |
result += count(subgroup.rows); | |
return result; | |
} else { | |
return elements.length; | |
} | |
} | |
Groupings2.count = count; | |
})(Groupings || (Groupings = {})); | |
var Link3 = class { | |
constructor(fields) { | |
Object.assign(this, fields); | |
} | |
/** Create a link to a specific file. */ | |
static file(path, embed = false, display) { | |
return new Link3({ | |
path, | |
embed, | |
display, | |
subpath: void 0, | |
type: "file" | |
}); | |
} | |
static infer(linkpath, embed = false, display) { | |
if (linkpath.includes("#^")) { | |
let split = linkpath.split("#^"); | |
return Link3.block(split[0], split[1], embed, display); | |
} else if (linkpath.includes("#")) { | |
let split = linkpath.split("#"); | |
return Link3.header(split[0], split[1], embed, display); | |
} else | |
return Link3.file(linkpath, embed, display); | |
} | |
/** Create a link to a specific file and header in that file. */ | |
static header(path, header, embed, display) { | |
return new Link3({ | |
path, | |
embed, | |
display, | |
subpath: normalizeHeaderForLink(header), | |
type: "header" | |
}); | |
} | |
/** Create a link to a specific file and block in that file. */ | |
static block(path, blockId, embed, display) { | |
return new Link3({ | |
path, | |
embed, | |
display, | |
subpath: blockId, | |
type: "block" | |
}); | |
} | |
static fromObject(object) { | |
return new Link3(object); | |
} | |
/** Checks for link equality (i.e., that the links are pointing to the same exact location). */ | |
equals(other) { | |
if (other == void 0 || other == null) | |
return false; | |
return this.path == other.path && this.type == other.type && this.subpath == other.subpath; | |
} | |
/** Convert this link to it's markdown representation. */ | |
toString() { | |
return this.markdown(); | |
} | |
/** Convert this link to a raw object which is serialization-friendly. */ | |
toObject() { | |
return { path: this.path, type: this.type, subpath: this.subpath, display: this.display, embed: this.embed }; | |
} | |
/** Update this link with a new path. */ | |
//@ts-ignore; error appeared after updating Obsidian to 0.15.4; it also updated other packages but didn't say which | |
withPath(path) { | |
return new Link3(Object.assign({}, this, { path })); | |
} | |
/** Return a new link which points to the same location but with a new display value. */ | |
withDisplay(display) { | |
return new Link3(Object.assign({}, this, { display })); | |
} | |
/** Convert a file link into a link to a specific header. */ | |
withHeader(header) { | |
return Link3.header(this.path, header, this.embed, this.display); | |
} | |
/** Convert any link into a link to its file. */ | |
toFile() { | |
return Link3.file(this.path, this.embed, this.display); | |
} | |
/** Convert this link into an embedded link. */ | |
toEmbed() { | |
if (this.embed) { | |
return this; | |
} else { | |
let link = new Link3(this); | |
link.embed = true; | |
return link; | |
} | |
} | |
/** Convert this link into a non-embedded link. */ | |
fromEmbed() { | |
if (!this.embed) { | |
return this; | |
} else { | |
let link = new Link3(this); | |
link.embed = false; | |
return link; | |
} | |
} | |
/** Convert this link to markdown so it can be rendered. */ | |
markdown() { | |
let result = (this.embed ? "!" : "") + "[[" + this.obsidianLink(); | |
if (this.display) { | |
result += "|" + this.display; | |
} else { | |
result += "|" + getFileTitle(this.path); | |
if (this.type == "header" || this.type == "block") | |
result += " > " + this.subpath; | |
} | |
result += "]]"; | |
return result; | |
} | |
/** Convert the inner part of the link to something that Obsidian can open / understand. */ | |
obsidianLink() { | |
var _a, _b; | |
const escaped = this.path.replace("|", "\\|"); | |
if (this.type == "header") | |
return escaped + "#" + ((_a = this.subpath) === null || _a === void 0 ? void 0 : _a.replace("|", "\\|")); | |
if (this.type == "block") | |
return escaped + "#^" + ((_b = this.subpath) === null || _b === void 0 ? void 0 : _b.replace("|", "\\|")); | |
else | |
return escaped; | |
} | |
/** The stripped name of the file this link points to. */ | |
fileName() { | |
return getFileTitle(this.path).replace(".md", ""); | |
} | |
}; | |
var Widget = class { | |
constructor($widget) { | |
this.$widget = $widget; | |
} | |
}; | |
var ListPairWidget = class extends Widget { | |
constructor(key, value) { | |
super("dataview:list-pair"); | |
this.key = key; | |
this.value = value; | |
} | |
markdown() { | |
return `${Values.toString(this.key)}: ${Values.toString(this.value)}`; | |
} | |
}; | |
var ExternalLinkWidget = class extends Widget { | |
constructor(url, display) { | |
super("dataview:external-link"); | |
this.url = url; | |
this.display = display; | |
} | |
markdown() { | |
var _a; | |
return `[${(_a = this.display) !== null && _a !== void 0 ? _a : this.url}](${this.url})`; | |
} | |
}; | |
var Widgets; | |
(function(Widgets2) { | |
function listPair(key, value) { | |
return new ListPairWidget(key, value); | |
} | |
Widgets2.listPair = listPair; | |
function externalLink(url, display) { | |
return new ExternalLinkWidget(url, display); | |
} | |
Widgets2.externalLink = externalLink; | |
function isListPair(widget) { | |
return widget.$widget === "dataview:list-pair"; | |
} | |
Widgets2.isListPair = isListPair; | |
function isExternalLink(widget) { | |
return widget.$widget === "dataview:external-link"; | |
} | |
Widgets2.isExternalLink = isExternalLink; | |
function isBuiltin(widget) { | |
return isListPair(widget) || isExternalLink(widget); | |
} | |
Widgets2.isBuiltin = isBuiltin; | |
})(Widgets || (Widgets = {})); | |
var Fields; | |
(function(Fields2) { | |
function variable(name) { | |
return { type: "variable", name }; | |
} | |
Fields2.variable = variable; | |
function literal(value) { | |
return { type: "literal", value }; | |
} | |
Fields2.literal = literal; | |
function binaryOp(left, op, right) { | |
return { type: "binaryop", left, op, right }; | |
} | |
Fields2.binaryOp = binaryOp; | |
function index(obj, index2) { | |
return { type: "index", object: obj, index: index2 }; | |
} | |
Fields2.index = index; | |
function indexVariable(name) { | |
let parts = name.split("."); | |
let result = Fields2.variable(parts[0]); | |
for (let index2 = 1; index2 < parts.length; index2++) { | |
result = Fields2.index(result, Fields2.literal(parts[index2])); | |
} | |
return result; | |
} | |
Fields2.indexVariable = indexVariable; | |
function lambda(args, value) { | |
return { type: "lambda", arguments: args, value }; | |
} | |
Fields2.lambda = lambda; | |
function func(func2, args) { | |
return { type: "function", func: func2, arguments: args }; | |
} | |
Fields2.func = func; | |
function list(values) { | |
return { type: "list", values }; | |
} | |
Fields2.list = list; | |
function object(values) { | |
return { type: "object", values }; | |
} | |
Fields2.object = object; | |
function negate(child) { | |
return { type: "negated", child }; | |
} | |
Fields2.negate = negate; | |
function isCompareOp(op) { | |
return op == "<=" || op == "<" || op == ">" || op == ">=" || op == "!=" || op == "="; | |
} | |
Fields2.isCompareOp = isCompareOp; | |
Fields2.NULL = Fields2.literal(null); | |
})(Fields || (Fields = {})); | |
var Sources; | |
(function(Sources2) { | |
function tag(tag2) { | |
return { type: "tag", tag: tag2 }; | |
} | |
Sources2.tag = tag; | |
function csv(path) { | |
return { type: "csv", path }; | |
} | |
Sources2.csv = csv; | |
function folder(prefix) { | |
return { type: "folder", folder: prefix }; | |
} | |
Sources2.folder = folder; | |
function link(file, incoming) { | |
return { type: "link", file, direction: incoming ? "incoming" : "outgoing" }; | |
} | |
Sources2.link = link; | |
function binaryOp(left, op, right) { | |
return { type: "binaryop", left, op, right }; | |
} | |
Sources2.binaryOp = binaryOp; | |
function and(left, right) { | |
return { type: "binaryop", left, op: "&", right }; | |
} | |
Sources2.and = and; | |
function or(left, right) { | |
return { type: "binaryop", left, op: "|", right }; | |
} | |
Sources2.or = or; | |
function negate(child) { | |
return { type: "negate", child }; | |
} | |
Sources2.negate = negate; | |
function empty() { | |
return { type: "empty" }; | |
} | |
Sources2.empty = empty; | |
})(Sources || (Sources = {})); | |
var EMOJI_REGEX = new RegExp(emojiRegex(), ""); | |
var DURATION_TYPES = { | |
year: Duration.fromObject({ years: 1 }), | |
years: Duration.fromObject({ years: 1 }), | |
yr: Duration.fromObject({ years: 1 }), | |
yrs: Duration.fromObject({ years: 1 }), | |
month: Duration.fromObject({ months: 1 }), | |
months: Duration.fromObject({ months: 1 }), | |
mo: Duration.fromObject({ months: 1 }), | |
mos: Duration.fromObject({ months: 1 }), | |
week: Duration.fromObject({ weeks: 1 }), | |
weeks: Duration.fromObject({ weeks: 1 }), | |
wk: Duration.fromObject({ weeks: 1 }), | |
wks: Duration.fromObject({ weeks: 1 }), | |
w: Duration.fromObject({ weeks: 1 }), | |
day: Duration.fromObject({ days: 1 }), | |
days: Duration.fromObject({ days: 1 }), | |
d: Duration.fromObject({ days: 1 }), | |
hour: Duration.fromObject({ hours: 1 }), | |
hours: Duration.fromObject({ hours: 1 }), | |
hr: Duration.fromObject({ hours: 1 }), | |
hrs: Duration.fromObject({ hours: 1 }), | |
h: Duration.fromObject({ hours: 1 }), | |
minute: Duration.fromObject({ minutes: 1 }), | |
minutes: Duration.fromObject({ minutes: 1 }), | |
min: Duration.fromObject({ minutes: 1 }), | |
mins: Duration.fromObject({ minutes: 1 }), | |
m: Duration.fromObject({ minutes: 1 }), | |
second: Duration.fromObject({ seconds: 1 }), | |
seconds: Duration.fromObject({ seconds: 1 }), | |
sec: Duration.fromObject({ seconds: 1 }), | |
secs: Duration.fromObject({ seconds: 1 }), | |
s: Duration.fromObject({ seconds: 1 }) | |
}; | |
var DATE_SHORTHANDS = { | |
now: () => DateTime.local(), | |
today: () => DateTime.local().startOf("day"), | |
yesterday: () => DateTime.local().startOf("day").minus(Duration.fromObject({ days: 1 })), | |
tomorrow: () => DateTime.local().startOf("day").plus(Duration.fromObject({ days: 1 })), | |
sow: () => DateTime.local().startOf("week"), | |
"start-of-week": () => DateTime.local().startOf("week"), | |
eow: () => DateTime.local().endOf("week"), | |
"end-of-week": () => DateTime.local().endOf("week"), | |
soy: () => DateTime.local().startOf("year"), | |
"start-of-year": () => DateTime.local().startOf("year"), | |
eoy: () => DateTime.local().endOf("year"), | |
"end-of-year": () => DateTime.local().endOf("year"), | |
som: () => DateTime.local().startOf("month"), | |
"start-of-month": () => DateTime.local().startOf("month"), | |
eom: () => DateTime.local().endOf("month"), | |
"end-of-month": () => DateTime.local().endOf("month") | |
}; | |
var KEYWORDS = ["FROM", "WHERE", "LIMIT", "GROUP", "FLATTEN"]; | |
function splitOnUnescapedPipe(link) { | |
let pipe = -1; | |
while ((pipe = link.indexOf("|", pipe + 1)) >= 0) { | |
if (pipe > 0 && link[pipe - 1] == "\\") | |
continue; | |
return [link.substring(0, pipe).replace(/\\\|/g, "|"), link.substring(pipe + 1)]; | |
} | |
return [link.replace(/\\\|/g, "|"), void 0]; | |
} | |
function parseInnerLink(rawlink) { | |
let [link, display] = splitOnUnescapedPipe(rawlink); | |
return Link3.infer(link, false, display); | |
} | |
function createBinaryParser(child, sep, combine) { | |
return parsimmon_umd_min.exports.seqMap(child, parsimmon_umd_min.exports.seq(parsimmon_umd_min.exports.optWhitespace, sep, parsimmon_umd_min.exports.optWhitespace, child).many(), (first, rest) => { | |
if (rest.length == 0) | |
return first; | |
let node = combine(first, rest[0][1], rest[0][3]); | |
for (let index = 1; index < rest.length; index++) { | |
node = combine(node, rest[index][1], rest[index][3]); | |
} | |
return node; | |
}); | |
} | |
function chainOpt(base, ...funcs) { | |
return parsimmon_umd_min.exports.custom((success, failure) => { | |
return (input, i) => { | |
let result = base._(input, i); | |
if (!result.status) | |
return result; | |
for (let func of funcs) { | |
let next = func(result.value)._(input, result.index); | |
if (!next.status) | |
return result; | |
result = next; | |
} | |
return result; | |
}; | |
}); | |
} | |
var EXPRESSION = parsimmon_umd_min.exports.createLanguage({ | |
// A floating point number; the decimal point is optional. | |
number: (q) => parsimmon_umd_min.exports.regexp(/-?[0-9]+(\.[0-9]+)?/).map((str) => Number.parseFloat(str)).desc("number"), | |
// A quote-surrounded string which supports escape characters ('\'). | |
string: (q) => parsimmon_umd_min.exports.string('"').then(parsimmon_umd_min.exports.alt(q.escapeCharacter, parsimmon_umd_min.exports.noneOf('"\\')).atLeast(0).map((chars2) => chars2.join(""))).skip(parsimmon_umd_min.exports.string('"')).desc("string"), | |
escapeCharacter: (_23) => parsimmon_umd_min.exports.string("\\").then(parsimmon_umd_min.exports.any).map((escaped) => { | |
if (escaped === '"') | |
return '"'; | |
if (escaped === "\\") | |
return "\\"; | |
else | |
return "\\" + escaped; | |
}), | |
// A boolean true/false value. | |
bool: (_23) => parsimmon_umd_min.exports.regexp(/true|false|True|False/).map((str) => str.toLowerCase() == "true").desc("boolean ('true' or 'false')"), | |
// A tag of the form '#stuff/hello-there'. | |
tag: (_23) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.string("#"), parsimmon_umd_min.exports.alt(parsimmon_umd_min.exports.regexp(/[^\u2000-\u206F\u2E00-\u2E7F'!"#$%&()*+,.:;<=>?@^`{|}~\[\]\\\s]/).desc("text")).many(), (start, rest) => start + rest.join("")).desc("tag ('#hello/stuff')"), | |
// A variable identifier, which is alphanumeric and must start with a letter or... emoji. | |
identifier: (_23) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.alt(parsimmon_umd_min.exports.regexp(/\p{Letter}/u), parsimmon_umd_min.exports.regexp(EMOJI_REGEX).desc("text")), parsimmon_umd_min.exports.alt(parsimmon_umd_min.exports.regexp(/[0-9\p{Letter}_-]/u), parsimmon_umd_min.exports.regexp(EMOJI_REGEX).desc("text")).many(), (first, rest) => first + rest.join("")).desc("variable identifier"), | |
// An Obsidian link of the form [[<link>]]. | |
link: (_23) => parsimmon_umd_min.exports.regexp(/\[\[([^\[\]]*?)\]\]/u, 1).map((linkInner) => parseInnerLink(linkInner)).desc("file link"), | |
// An embeddable link which can start with '!'. This overlaps with the normal negation operator, so it is only | |
// provided for metadata parsing. | |
embedLink: (q) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.string("!").atMost(1), q.link, (p, l2) => { | |
if (p.length > 0) | |
l2.embed = true; | |
return l2; | |
}).desc("file link"), | |
// Binary plus or minus operator. | |
binaryPlusMinus: (_23) => parsimmon_umd_min.exports.regexp(/\+|-/).map((str) => str).desc("'+' or '-'"), | |
// Binary times or divide operator. | |
binaryMulDiv: (_23) => parsimmon_umd_min.exports.regexp(/\*|\/|%/).map((str) => str).desc("'*' or '/' or '%'"), | |
// Binary comparison operator. | |
binaryCompareOp: (_23) => parsimmon_umd_min.exports.regexp(/>=|<=|!=|>|<|=/).map((str) => str).desc("'>=' or '<=' or '!=' or '=' or '>' or '<'"), | |
// Binary boolean combination operator. | |
binaryBooleanOp: (_23) => parsimmon_umd_min.exports.regexp(/and|or|&|\|/i).map((str) => { | |
if (str.toLowerCase() == "and") | |
return "&"; | |
else if (str.toLowerCase() == "or") | |
return "|"; | |
else | |
return str; | |
}).desc("'and' or 'or'"), | |
// A date which can be YYYY-MM[-DDTHH:mm:ss]. | |
rootDate: (_23) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.regexp(/\d{4}/), parsimmon_umd_min.exports.string("-"), parsimmon_umd_min.exports.regexp(/\d{2}/), (year, _24, month) => { | |
return DateTime.fromObject({ year: Number.parseInt(year), month: Number.parseInt(month) }); | |
}).desc("date in format YYYY-MM[-DDTHH-MM-SS.MS]"), | |
dateShorthand: (_23) => parsimmon_umd_min.exports.alt(...Object.keys(DATE_SHORTHANDS).sort((a, b) => b.length - a.length).map(parsimmon_umd_min.exports.string)), | |
date: (q) => chainOpt(q.rootDate, (ym) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.string("-"), parsimmon_umd_min.exports.regexp(/\d{2}/), (_23, day) => ym.set({ day: Number.parseInt(day) })), (ymd) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.string("T"), parsimmon_umd_min.exports.regexp(/\d{2}/), (_23, hour) => ymd.set({ hour: Number.parseInt(hour) })), (ymdh) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.string(":"), parsimmon_umd_min.exports.regexp(/\d{2}/), (_23, minute) => ymdh.set({ minute: Number.parseInt(minute) })), (ymdhm) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.string(":"), parsimmon_umd_min.exports.regexp(/\d{2}/), (_23, second) => ymdhm.set({ second: Number.parseInt(second) })), (ymdhms) => parsimmon_umd_min.exports.alt( | |
parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.string("."), parsimmon_umd_min.exports.regexp(/\d{3}/), (_23, millisecond) => ymdhms.set({ millisecond: Number.parseInt(millisecond) })), | |
parsimmon_umd_min.exports.succeed(ymdhms) | |
// pass | |
), (dt) => parsimmon_umd_min.exports.alt(parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.string("+").or(parsimmon_umd_min.exports.string("-")), parsimmon_umd_min.exports.regexp(/\d{1,2}(:\d{2})?/), (pm, hr) => dt.setZone("UTC" + pm + hr, { keepLocalTime: true })), parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.string("Z"), () => dt.setZone("utc", { keepLocalTime: true })), parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.string("["), parsimmon_umd_min.exports.regexp(/[0-9A-Za-z+-\/]+/u), parsimmon_umd_min.exports.string("]"), (_a, zone, _b) => dt.setZone(zone, { keepLocalTime: true })))).assert((dt) => dt.isValid, "valid date").desc("date in format YYYY-MM[-DDTHH-MM-SS.MS]"), | |
// A date, plus various shorthand times of day it could be. | |
datePlus: (q) => parsimmon_umd_min.exports.alt(q.dateShorthand.map((d) => DATE_SHORTHANDS[d]()), q.date).desc("date in format YYYY-MM[-DDTHH-MM-SS.MS] or in shorthand"), | |
// A duration of time. | |
durationType: (_23) => parsimmon_umd_min.exports.alt(...Object.keys(DURATION_TYPES).sort((a, b) => b.length - a.length).map(parsimmon_umd_min.exports.string)), | |
duration: (q) => parsimmon_umd_min.exports.seqMap(q.number, parsimmon_umd_min.exports.optWhitespace, q.durationType, (count, _23, t2) => DURATION_TYPES[t2].mapUnits((x) => x * count)).sepBy1(parsimmon_umd_min.exports.string(",").trim(parsimmon_umd_min.exports.optWhitespace).or(parsimmon_umd_min.exports.optWhitespace)).map((durations) => durations.reduce((p, c) => p.plus(c))).desc("duration like 4hr2min"), | |
// A raw null value. | |
rawNull: (_23) => parsimmon_umd_min.exports.string("null"), | |
// Source parsing. | |
tagSource: (q) => q.tag.map((tag) => Sources.tag(tag)), | |
csvSource: (q) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.string("csv(").skip(parsimmon_umd_min.exports.optWhitespace), q.string, parsimmon_umd_min.exports.string(")"), (_1, path, _23) => Sources.csv(path)), | |
linkIncomingSource: (q) => q.link.map((link) => Sources.link(link.path, true)), | |
linkOutgoingSource: (q) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.string("outgoing(").skip(parsimmon_umd_min.exports.optWhitespace), q.link, parsimmon_umd_min.exports.string(")"), (_1, link, _23) => Sources.link(link.path, false)), | |
folderSource: (q) => q.string.map((str) => Sources.folder(str)), | |
parensSource: (q) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.string("("), parsimmon_umd_min.exports.optWhitespace, q.source, parsimmon_umd_min.exports.optWhitespace, parsimmon_umd_min.exports.string(")"), (_1, _23, field, _32, _42) => field), | |
negateSource: (q) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.alt(parsimmon_umd_min.exports.string("-"), parsimmon_umd_min.exports.string("!")), q.atomSource, (_23, source) => Sources.negate(source)), | |
atomSource: (q) => parsimmon_umd_min.exports.alt(q.parensSource, q.negateSource, q.linkOutgoingSource, q.linkIncomingSource, q.folderSource, q.tagSource, q.csvSource), | |
binaryOpSource: (q) => createBinaryParser(q.atomSource, q.binaryBooleanOp.map((s2) => s2), Sources.binaryOp), | |
source: (q) => q.binaryOpSource, | |
// Field parsing. | |
variableField: (q) => q.identifier.chain((r) => { | |
if (KEYWORDS.includes(r.toUpperCase())) { | |
return parsimmon_umd_min.exports.fail("Variable fields cannot be a keyword (" + KEYWORDS.join(" or ") + ")"); | |
} else { | |
return parsimmon_umd_min.exports.succeed(Fields.variable(r)); | |
} | |
}).desc("variable"), | |
numberField: (q) => q.number.map((val) => Fields.literal(val)).desc("number"), | |
stringField: (q) => q.string.map((val) => Fields.literal(val)).desc("string"), | |
boolField: (q) => q.bool.map((val) => Fields.literal(val)).desc("boolean"), | |
dateField: (q) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.string("date("), parsimmon_umd_min.exports.optWhitespace, q.datePlus, parsimmon_umd_min.exports.optWhitespace, parsimmon_umd_min.exports.string(")"), (prefix, _1, date, _23, postfix) => Fields.literal(date)).desc("date"), | |
durationField: (q) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.string("dur("), parsimmon_umd_min.exports.optWhitespace, q.duration, parsimmon_umd_min.exports.optWhitespace, parsimmon_umd_min.exports.string(")"), (prefix, _1, dur, _23, postfix) => Fields.literal(dur)).desc("duration"), | |
nullField: (q) => q.rawNull.map((_23) => Fields.NULL), | |
linkField: (q) => q.link.map((f) => Fields.literal(f)), | |
listField: (q) => q.field.sepBy(parsimmon_umd_min.exports.string(",").trim(parsimmon_umd_min.exports.optWhitespace)).wrap(parsimmon_umd_min.exports.string("[").skip(parsimmon_umd_min.exports.optWhitespace), parsimmon_umd_min.exports.optWhitespace.then(parsimmon_umd_min.exports.string("]"))).map((l2) => Fields.list(l2)).desc("list ('[1, 2, 3]')"), | |
objectField: (q) => parsimmon_umd_min.exports.seqMap(q.identifier.or(q.string), parsimmon_umd_min.exports.string(":").trim(parsimmon_umd_min.exports.optWhitespace), q.field, (name, _sep, value) => { | |
return { name, value }; | |
}).sepBy(parsimmon_umd_min.exports.string(",").trim(parsimmon_umd_min.exports.optWhitespace)).wrap(parsimmon_umd_min.exports.string("{").skip(parsimmon_umd_min.exports.optWhitespace), parsimmon_umd_min.exports.optWhitespace.then(parsimmon_umd_min.exports.string("}"))).map((vals) => { | |
let res = {}; | |
for (let entry of vals) | |
res[entry.name] = entry.value; | |
return Fields.object(res); | |
}).desc("object ('{ a: 1, b: 2 }')"), | |
atomInlineField: (q) => parsimmon_umd_min.exports.alt(q.date, q.duration.map((d) => normalizeDuration(d)), q.string, q.tag, q.embedLink, q.bool, q.number, q.rawNull), | |
inlineFieldList: (q) => q.atomInlineField.sepBy(parsimmon_umd_min.exports.string(",").trim(parsimmon_umd_min.exports.optWhitespace).lookahead(q.atomInlineField)), | |
inlineField: (q) => parsimmon_umd_min.exports.alt(parsimmon_umd_min.exports.seqMap(q.atomInlineField, parsimmon_umd_min.exports.string(",").trim(parsimmon_umd_min.exports.optWhitespace), q.inlineFieldList, (f, _s, l2) => [f].concat(l2)), q.atomInlineField), | |
atomField: (q) => parsimmon_umd_min.exports.alt( | |
// Place embed links above negated fields as they are the special parser case '![[thing]]' and are generally unambigious. | |
q.embedLink.map((l2) => Fields.literal(l2)), | |
q.negatedField, | |
q.linkField, | |
q.listField, | |
q.objectField, | |
q.lambdaField, | |
q.parensField, | |
q.boolField, | |
q.numberField, | |
q.stringField, | |
q.dateField, | |
q.durationField, | |
q.nullField, | |
q.variableField | |
), | |
indexField: (q) => parsimmon_umd_min.exports.seqMap(q.atomField, parsimmon_umd_min.exports.alt(q.dotPostfix, q.indexPostfix, q.functionPostfix).many(), (obj, postfixes) => { | |
let result = obj; | |
for (let post of postfixes) { | |
switch (post.type) { | |
case "dot": | |
result = Fields.index(result, Fields.literal(post.field)); | |
break; | |
case "index": | |
result = Fields.index(result, post.field); | |
break; | |
case "function": | |
result = Fields.func(result, post.fields); | |
break; | |
} | |
} | |
return result; | |
}), | |
negatedField: (q) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.string("!"), q.indexField, (_23, field) => Fields.negate(field)).desc("negated field"), | |
parensField: (q) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.string("("), parsimmon_umd_min.exports.optWhitespace, q.field, parsimmon_umd_min.exports.optWhitespace, parsimmon_umd_min.exports.string(")"), (_1, _23, field, _32, _42) => field), | |
lambdaField: (q) => parsimmon_umd_min.exports.seqMap(q.identifier.sepBy(parsimmon_umd_min.exports.string(",").trim(parsimmon_umd_min.exports.optWhitespace)).wrap(parsimmon_umd_min.exports.string("(").trim(parsimmon_umd_min.exports.optWhitespace), parsimmon_umd_min.exports.string(")").trim(parsimmon_umd_min.exports.optWhitespace)), parsimmon_umd_min.exports.string("=>").trim(parsimmon_umd_min.exports.optWhitespace), q.field, (ident, _ignore, value) => { | |
return { type: "lambda", arguments: ident, value }; | |
}), | |
dotPostfix: (q) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.string("."), q.identifier, (_23, field) => { | |
return { type: "dot", field }; | |
}), | |
indexPostfix: (q) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.string("["), parsimmon_umd_min.exports.optWhitespace, q.field, parsimmon_umd_min.exports.optWhitespace, parsimmon_umd_min.exports.string("]"), (_23, _24, field, _32, _42) => { | |
return { type: "index", field }; | |
}), | |
functionPostfix: (q) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.string("("), parsimmon_umd_min.exports.optWhitespace, q.field.sepBy(parsimmon_umd_min.exports.string(",").trim(parsimmon_umd_min.exports.optWhitespace)), parsimmon_umd_min.exports.optWhitespace, parsimmon_umd_min.exports.string(")"), (_23, _1, fields, _24, _32) => { | |
return { type: "function", fields }; | |
}), | |
// The precedence hierarchy of operators - multiply/divide, add/subtract, compare, and then boolean operations. | |
binaryMulDivField: (q) => createBinaryParser(q.indexField, q.binaryMulDiv, Fields.binaryOp), | |
binaryPlusMinusField: (q) => createBinaryParser(q.binaryMulDivField, q.binaryPlusMinus, Fields.binaryOp), | |
binaryCompareField: (q) => createBinaryParser(q.binaryPlusMinusField, q.binaryCompareOp, Fields.binaryOp), | |
binaryBooleanField: (q) => createBinaryParser(q.binaryCompareField, q.binaryBooleanOp, Fields.binaryOp), | |
binaryOpField: (q) => q.binaryBooleanField, | |
field: (q) => q.binaryOpField | |
}); | |
function parseField(text) { | |
try { | |
return Result.success(EXPRESSION.field.tryParse(text)); | |
} catch (error4) { | |
return Result.failure("" + error4); | |
} | |
} | |
var QueryFields; | |
(function(QueryFields2) { | |
function named(name, field) { | |
return { name, field }; | |
} | |
QueryFields2.named = named; | |
function sortBy(field, dir2) { | |
return { field, direction: dir2 }; | |
} | |
QueryFields2.sortBy = sortBy; | |
})(QueryFields || (QueryFields = {})); | |
function captureRaw(base) { | |
return parsimmon_umd_min.exports.custom((success, failure) => { | |
return (input, i) => { | |
let result = base._(input, i); | |
if (!result.status) | |
return result; | |
return Object.assign({}, result, { value: [result.value, input.substring(i, result.index)] }); | |
}; | |
}); | |
} | |
function stripNewlines(text) { | |
return text.split(/[\r\n]+/).map((t2) => t2.trim()).join(""); | |
} | |
var QUERY_LANGUAGE = parsimmon_umd_min.exports.createLanguage({ | |
// Simple atom parsing, like words, identifiers, numbers. | |
queryType: (q) => parsimmon_umd_min.exports.alt(parsimmon_umd_min.exports.regexp(/TABLE|LIST|TASK|CALENDAR/i)).map((str) => str.toLowerCase()).desc("query type ('TABLE', 'LIST', 'TASK', or 'CALENDAR')"), | |
explicitNamedField: (q) => parsimmon_umd_min.exports.seqMap(EXPRESSION.field.skip(parsimmon_umd_min.exports.whitespace), parsimmon_umd_min.exports.regexp(/AS/i).skip(parsimmon_umd_min.exports.whitespace), EXPRESSION.identifier.or(EXPRESSION.string), (field, _as, ident) => QueryFields.named(ident, field)), | |
namedField: (q) => parsimmon_umd_min.exports.alt(q.explicitNamedField, captureRaw(EXPRESSION.field).map(([value, text]) => QueryFields.named(stripNewlines(text), value))), | |
sortField: (q) => parsimmon_umd_min.exports.seqMap(EXPRESSION.field.skip(parsimmon_umd_min.exports.optWhitespace), parsimmon_umd_min.exports.regexp(/ASCENDING|DESCENDING|ASC|DESC/i).atMost(1), (field, dir2) => { | |
let direction = dir2.length == 0 ? "ascending" : dir2[0].toLowerCase(); | |
if (direction == "desc") | |
direction = "descending"; | |
if (direction == "asc") | |
direction = "ascending"; | |
return { | |
field, | |
direction | |
}; | |
}), | |
headerClause: (q) => q.queryType.skip(parsimmon_umd_min.exports.whitespace).chain((qtype) => { | |
switch (qtype) { | |
case "table": | |
return parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.regexp(/WITHOUT\s+ID/i).skip(parsimmon_umd_min.exports.optWhitespace).atMost(1), parsimmon_umd_min.exports.sepBy(q.namedField, parsimmon_umd_min.exports.string(",").trim(parsimmon_umd_min.exports.optWhitespace)), (withoutId, fields) => { | |
return { type: "table", fields, showId: withoutId.length == 0 }; | |
}); | |
case "list": | |
return parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.regexp(/WITHOUT\s+ID/i).skip(parsimmon_umd_min.exports.optWhitespace).atMost(1), EXPRESSION.field.atMost(1), (withoutId, format) => { | |
return { | |
type: "list", | |
format: format.length == 1 ? format[0] : void 0, | |
showId: withoutId.length == 0 | |
}; | |
}); | |
case "task": | |
return parsimmon_umd_min.exports.succeed({ type: "task" }); | |
case "calendar": | |
return parsimmon_umd_min.exports.seqMap(q.namedField, (field) => { | |
return { | |
type: "calendar", | |
showId: true, | |
field | |
}; | |
}); | |
default: | |
return parsimmon_umd_min.exports.fail(`Unrecognized query type '${qtype}'`); | |
} | |
}).desc("TABLE or LIST or TASK or CALENDAR"), | |
fromClause: (q) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.regexp(/FROM/i), parsimmon_umd_min.exports.whitespace, EXPRESSION.source, (_1, _23, source) => source), | |
whereClause: (q) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.regexp(/WHERE/i), parsimmon_umd_min.exports.whitespace, EXPRESSION.field, (where, _23, field) => { | |
return { type: "where", clause: field }; | |
}).desc("WHERE <expression>"), | |
sortByClause: (q) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.regexp(/SORT/i), parsimmon_umd_min.exports.whitespace, q.sortField.sepBy1(parsimmon_umd_min.exports.string(",").trim(parsimmon_umd_min.exports.optWhitespace)), (sort, _1, fields) => { | |
return { type: "sort", fields }; | |
}).desc("SORT field [ASC/DESC]"), | |
limitClause: (q) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.regexp(/LIMIT/i), parsimmon_umd_min.exports.whitespace, EXPRESSION.field, (limit, _1, field) => { | |
return { type: "limit", amount: field }; | |
}).desc("LIMIT <value>"), | |
flattenClause: (q) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.regexp(/FLATTEN/i).skip(parsimmon_umd_min.exports.whitespace), q.namedField, (_23, field) => { | |
return { type: "flatten", field }; | |
}).desc("FLATTEN <value> [AS <name>]"), | |
groupByClause: (q) => parsimmon_umd_min.exports.seqMap(parsimmon_umd_min.exports.regexp(/GROUP BY/i).skip(parsimmon_umd_min.exports.whitespace), q.namedField, (_23, field) => { | |
return { type: "group", field }; | |
}).desc("GROUP BY <value> [AS <name>]"), | |
// Full query parsing. | |
clause: (q) => parsimmon_umd_min.exports.alt(q.fromClause, q.whereClause, q.sortByClause, q.limitClause, q.groupByClause, q.flattenClause), | |
query: (q) => parsimmon_umd_min.exports.seqMap(q.headerClause.trim(parsimmon_umd_min.exports.optWhitespace), q.fromClause.trim(parsimmon_umd_min.exports.optWhitespace).atMost(1), q.clause.trim(parsimmon_umd_min.exports.optWhitespace).many(), (header, from, clauses) => { | |
return { | |
header, | |
source: from.length == 0 ? Sources.folder("") : from[0], | |
operations: clauses, | |
settings: DEFAULT_QUERY_SETTINGS | |
}; | |
}) | |
}); | |
var getAPI3 = (app2) => { | |
var _a; | |
if (app2) | |
return (_a = app2.plugins.plugins.dataview) === null || _a === void 0 ? void 0 : _a.api; | |
else | |
return window.DataviewAPI; | |
}; | |
var isPluginEnabled = (app2) => app2.plugins.enabledPlugins.has("dataview"); | |
exports.DATE_SHORTHANDS = DATE_SHORTHANDS; | |
exports.DURATION_TYPES = DURATION_TYPES; | |
exports.EXPRESSION = EXPRESSION; | |
exports.KEYWORDS = KEYWORDS; | |
exports.QUERY_LANGUAGE = QUERY_LANGUAGE; | |
exports.getAPI = getAPI3; | |
exports.isPluginEnabled = isPluginEnabled; | |
exports.parseField = parseField; | |
} | |
}); | |
// node_modules/slugify/slugify.js | |
var require_slugify = __commonJS({ | |
"node_modules/slugify/slugify.js"(exports, module2) { | |
(function(name, root, factory) { | |
if (typeof exports === "object") { | |
module2.exports = factory(); | |
module2.exports["default"] = factory(); | |
} else if (typeof define === "function" && define.amd) { | |
define(factory); | |
} else { | |
root[name] = factory(); | |
} | |
})("slugify", exports, function() { | |
var charMap = JSON.parse(`{"$":"dollar","%":"percent","&":"and","<":"less",">":"greater","|":"or","\xA2":"cent","\xA3":"pound","\xA4":"currency","\xA5":"yen","\xA9":"(c)","\xAA":"a","\xAE":"(r)","\xBA":"o","\xC0":"A","\xC1":"A","\xC2":"A","\xC3":"A","\xC4":"A","\xC5":"A","\xC6":"AE","\xC7":"C","\xC8":"E","\xC9":"E","\xCA":"E","\xCB":"E","\xCC":"I","\xCD":"I","\xCE":"I","\xCF":"I","\xD0":"D","\xD1":"N","\xD2":"O","\xD3":"O","\xD4":"O","\xD5":"O","\xD6":"O","\xD8":"O","\xD9":"U","\xDA":"U","\xDB":"U","\xDC":"U","\xDD":"Y","\xDE":"TH","\xDF":"ss","\xE0":"a","\xE1":"a","\xE2":"a","\xE3":"a","\xE4":"a","\xE5":"a","\xE6":"ae","\xE7":"c","\xE8":"e","\xE9":"e","\xEA":"e","\xEB":"e","\xEC":"i","\xED":"i","\xEE":"i","\xEF":"i","\xF0":"d","\xF1":"n","\xF2":"o","\xF3":"o","\xF4":"o","\xF5":"o","\xF6":"o","\xF8":"o","\xF9":"u","\xFA":"u","\xFB":"u","\xFC":"u","\xFD":"y","\xFE":"th","\xFF":"y","\u0100":"A","\u0101":"a","\u0102":"A","\u0103":"a","\u0104":"A","\u0105":"a","\u0106":"C","\u0107":"c","\u010C":"C","\u010D":"c","\u010E":"D","\u010F":"d","\u0110":"DJ","\u0111":"dj","\u0112":"E","\u0113":"e","\u0116":"E","\u0117":"e","\u0118":"e","\u0119":"e","\u011A":"E","\u011B":"e","\u011E":"G","\u011F":"g","\u0122":"G","\u0123":"g","\u0128":"I","\u0129":"i","\u012A":"i","\u012B":"i","\u012E":"I","\u012F":"i","\u0130":"I","\u0131":"i","\u0136":"k","\u0137":"k","\u013B":"L","\u013C":"l","\u013D":"L","\u013E":"l","\u0141":"L","\u0142":"l","\u0143":"N","\u0144":"n","\u0145":"N","\u0146":"n","\u0147":"N","\u0148":"n","\u014C":"O","\u014D":"o","\u0150":"O","\u0151":"o","\u0152":"OE","\u0153":"oe","\u0154":"R","\u0155":"r","\u0158":"R","\u0159":"r","\u015A":"S","\u015B":"s","\u015E":"S","\u015F":"s","\u0160":"S","\u0161":"s","\u0162":"T","\u0163":"t","\u0164":"T","\u0165":"t","\u0168":"U","\u0169":"u","\u016A":"u","\u016B":"u","\u016E":"U","\u016F":"u","\u0170":"U","\u0171":"u","\u0172":"U","\u0173":"u","\u0174":"W","\u0175":"w","\u0176":"Y","\u0177":"y","\u0178":"Y","\u0179":"Z","\u017A":"z","\u017B":"Z","\u017C":"z","\u017D":"Z","\u017E":"z","\u018F":"E","\u0192":"f","\u01A0":"O","\u01A1":"o","\u01AF":"U","\u01B0":"u","\u01C8":"LJ","\u01C9":"lj","\u01CB":"NJ","\u01CC":"nj","\u0218":"S","\u0219":"s","\u021A":"T","\u021B":"t","\u0259":"e","\u02DA":"o","\u0386":"A","\u0388":"E","\u0389":"H","\u038A":"I","\u038C":"O","\u038E":"Y","\u038F":"W","\u0390":"i","\u0391":"A","\u0392":"B","\u0393":"G","\u0394":"D","\u0395":"E","\u0396":"Z","\u0397":"H","\u0398":"8","\u0399":"I","\u039A":"K","\u039B":"L","\u039C":"M","\u039D":"N","\u039E":"3","\u039F":"O","\u03A0":"P","\u03A1":"R","\u03A3":"S","\u03A4":"T","\u03A5":"Y","\u03A6":"F","\u03A7":"X","\u03A8":"PS","\u03A9":"W","\u03AA":"I","\u03AB":"Y","\u03AC":"a","\u03AD":"e","\u03AE":"h","\u03AF":"i","\u03B0":"y","\u03B1":"a","\u03B2":"b","\u03B3":"g","\u03B4":"d","\u03B5":"e","\u03B6":"z","\u03B7":"h","\u03B8":"8","\u03B9":"i","\u03BA":"k","\u03BB":"l","\u03BC":"m","\u03BD":"n","\u03BE":"3","\u03BF":"o","\u03C0":"p","\u03C1":"r","\u03C2":"s","\u03C3":"s","\u03C4":"t","\u03C5":"y","\u03C6":"f","\u03C7":"x","\u03C8":"ps","\u03C9":"w","\u03CA":"i","\u03CB":"y","\u03CC":"o","\u03CD":"y","\u03CE":"w","\u0401":"Yo","\u0402":"DJ","\u0404":"Ye","\u0406":"I","\u0407":"Yi","\u0408":"J","\u0409":"LJ","\u040A":"NJ","\u040B":"C","\u040F":"DZ","\u0410":"A","\u0411":"B","\u0412":"V","\u0413":"G","\u0414":"D","\u0415":"E","\u0416":"Zh","\u0417":"Z","\u0418":"I","\u0419":"J","\u041A":"K","\u041B":"L","\u041C":"M","\u041D":"N","\u041E":"O","\u041F":"P","\u0420":"R","\u0421":"S","\u0422":"T","\u0423":"U","\u0424":"F","\u0425":"H","\u0426":"C","\u0427":"Ch","\u0428":"Sh","\u0429":"Sh","\u042A":"U","\u042B":"Y","\u042C":"","\u042D":"E","\u042E":"Yu","\u042F":"Ya","\u0430":"a","\u0431":"b","\u0432":"v","\u0433":"g","\u0434":"d","\u0435":"e","\u0436":"zh","\u0437":"z","\u0438":"i","\u0439":"j","\u043A":"k","\u043B":"l","\u043C":"m","\u043D":"n","\u043E":"o","\u043F":"p","\u0440":"r","\u0441":"s","\u0442":"t","\u0443":"u","\u0444":"f","\u0445":"h","\u0446":"c","\u0447":"ch","\u0448":"sh","\u0449":"sh","\u044A":"u","\u044B":"y","\u044C":"","\u044D":"e","\u044E":"yu","\u044F":"ya","\u0451":"yo","\u0452":"dj","\u0454":"ye","\u0456":"i","\u0457":"yi","\u0458":"j","\u0459":"lj","\u045A":"nj","\u045B":"c","\u045D":"u","\u045F":"dz","\u0490":"G","\u0491":"g","\u0492":"GH","\u0493":"gh","\u049A":"KH","\u049B":"kh","\u04A2":"NG","\u04A3":"ng","\u04AE":"UE","\u04AF":"ue","\u04B0":"U","\u04B1":"u","\u04BA":"H","\u04BB":"h","\u04D8":"AE","\u04D9":"ae","\u04E8":"OE","\u04E9":"oe","\u0531":"A","\u0532":"B","\u0533":"G","\u0534":"D","\u0535":"E","\u0536":"Z","\u0537":"E'","\u0538":"Y'","\u0539":"T'","\u053A":"JH","\u053B":"I","\u053C":"L","\u053D":"X","\u053E":"C'","\u053F":"K","\u0540":"H","\u0541":"D'","\u0542":"GH","\u0543":"TW","\u0544":"M","\u0545":"Y","\u0546":"N","\u0547":"SH","\u0549":"CH","\u054A":"P","\u054B":"J","\u054C":"R'","\u054D":"S","\u054E":"V","\u054F":"T","\u0550":"R","\u0551":"C","\u0553":"P'","\u0554":"Q'","\u0555":"O''","\u0556":"F","\u0587":"EV","\u0621":"a","\u0622":"aa","\u0623":"a","\u0624":"u","\u0625":"i","\u0626":"e","\u0627":"a","\u0628":"b","\u0629":"h","\u062A":"t","\u062B":"th","\u062C":"j","\u062D":"h","\u062E":"kh","\u062F":"d","\u0630":"th","\u0631":"r","\u0632":"z","\u0633":"s","\u0634":"sh","\u0635":"s","\u0636":"dh","\u0637":"t","\u0638":"z","\u0639":"a","\u063A":"gh","\u0641":"f","\u0642":"q","\u0643":"k","\u0644":"l","\u0645":"m","\u0646":"n","\u0647":"h","\u0648":"w","\u0649":"a","\u064A":"y","\u064B":"an","\u064C":"on","\u064D":"en","\u064E":"a","\u064F":"u","\u0650":"e","\u0652":"","\u0660":"0","\u0661":"1","\u0662":"2","\u0663":"3","\u0664":"4","\u0665":"5","\u0666":"6","\u0667":"7","\u0668":"8","\u0669":"9","\u067E":"p","\u0686":"ch","\u0698":"zh","\u06A9":"k","\u06AF":"g","\u06CC":"y","\u06F0":"0","\u06F1":"1","\u06F2":"2","\u06F3":"3","\u06F4":"4","\u06F5":"5","\u06F6":"6","\u06F7":"7","\u06F8":"8","\u06F9":"9","\u0E3F":"baht","\u10D0":"a","\u10D1":"b","\u10D2":"g","\u10D3":"d","\u10D4":"e","\u10D5":"v","\u10D6":"z","\u10D7":"t","\u10D8":"i","\u10D9":"k","\u10DA":"l","\u10DB":"m","\u10DC":"n","\u10DD":"o","\u10DE":"p","\u10DF":"zh","\u10E0":"r","\u10E1":"s","\u10E2":"t","\u10E3":"u","\u10E4":"f","\u10E5":"k","\u10E6":"gh","\u10E7":"q","\u10E8":"sh","\u10E9":"ch","\u10EA":"ts","\u10EB":"dz","\u10EC":"ts","\u10ED":"ch","\u10EE":"kh","\u10EF":"j","\u10F0":"h","\u1E62":"S","\u1E63":"s","\u1E80":"W","\u1E81":"w","\u1E82":"W","\u1E83":"w","\u1E84":"W","\u1E85":"w","\u1E9E":"SS","\u1EA0":"A","\u1EA1":"a","\u1EA2":"A","\u1EA3":"a","\u1EA4":"A","\u1EA5":"a","\u1EA6":"A","\u1EA7":"a","\u1EA8":"A","\u1EA9":"a","\u1EAA":"A","\u1EAB":"a","\u1EAC":"A","\u1EAD":"a","\u1EAE":"A","\u1EAF":"a","\u1EB0":"A","\u1EB1":"a","\u1EB2":"A","\u1EB3":"a","\u1EB4":"A","\u1EB5":"a","\u1EB6":"A","\u1EB7":"a","\u1EB8":"E","\u1EB9":"e","\u1EBA":"E","\u1EBB":"e","\u1EBC":"E","\u1EBD":"e","\u1EBE":"E","\u1EBF":"e","\u1EC0":"E","\u1EC1":"e","\u1EC2":"E","\u1EC3":"e","\u1EC4":"E","\u1EC5":"e","\u1EC6":"E","\u1EC7":"e","\u1EC8":"I","\u1EC9":"i","\u1ECA":"I","\u1ECB":"i","\u1ECC":"O","\u1ECD":"o","\u1ECE":"O","\u1ECF":"o","\u1ED0":"O","\u1ED1":"o","\u1ED2":"O","\u1ED3":"o","\u1ED4":"O","\u1ED5":"o","\u1ED6":"O","\u1ED7":"o","\u1ED8":"O","\u1ED9":"o","\u1EDA":"O","\u1EDB":"o","\u1EDC":"O","\u1EDD":"o","\u1EDE":"O","\u1EDF":"o","\u1EE0":"O","\u1EE1":"o","\u1EE2":"O","\u1EE3":"o","\u1EE4":"U","\u1EE5":"u","\u1EE6":"U","\u1EE7":"u","\u1EE8":"U","\u1EE9":"u","\u1EEA":"U","\u1EEB":"u","\u1EEC":"U","\u1EED":"u","\u1EEE":"U","\u1EEF":"u","\u1EF0":"U","\u1EF1":"u","\u1EF2":"Y","\u1EF3":"y","\u1EF4":"Y","\u1EF5":"y","\u1EF6":"Y","\u1EF7":"y","\u1EF8":"Y","\u1EF9":"y","\u2013":"-","\u2018":"'","\u2019":"'","\u201C":"\\"","\u201D":"\\"","\u201E":"\\"","\u2020":"+","\u2022":"*","\u2026":"...","\u20A0":"ecu","\u20A2":"cruzeiro","\u20A3":"french franc","\u20A4":"lira","\u20A5":"mill","\u20A6":"naira","\u20A7":"peseta","\u20A8":"rupee","\u20A9":"won","\u20AA":"new shequel","\u20AB":"dong","\u20AC":"euro","\u20AD":"kip","\u20AE":"tugrik","\u20AF":"drachma","\u20B0":"penny","\u20B1":"peso","\u20B2":"guarani","\u20B3":"austral","\u20B4":"hryvnia","\u20B5":"cedi","\u20B8":"kazakhstani tenge","\u20B9":"indian rupee","\u20BA":"turkish lira","\u20BD":"russian ruble","\u20BF":"bitcoin","\u2120":"sm","\u2122":"tm","\u2202":"d","\u2206":"delta","\u2211":"sum","\u221E":"infinity","\u2665":"love","\u5143":"yuan","\u5186":"yen","\uFDFC":"rial","\uFEF5":"laa","\uFEF7":"laa","\uFEF9":"lai","\uFEFB":"la"}`); | |
var locales = JSON.parse('{"bg":{"\u0419":"Y","\u0426":"Ts","\u0429":"Sht","\u042A":"A","\u042C":"Y","\u0439":"y","\u0446":"ts","\u0449":"sht","\u044A":"a","\u044C":"y"},"de":{"\xC4":"AE","\xE4":"ae","\xD6":"OE","\xF6":"oe","\xDC":"UE","\xFC":"ue","\xDF":"ss","%":"prozent","&":"und","|":"oder","\u2211":"summe","\u221E":"unendlich","\u2665":"liebe"},"es":{"%":"por ciento","&":"y","<":"menor que",">":"mayor que","|":"o","\xA2":"centavos","\xA3":"libras","\xA4":"moneda","\u20A3":"francos","\u2211":"suma","\u221E":"infinito","\u2665":"amor"},"fr":{"%":"pourcent","&":"et","<":"plus petit",">":"plus grand","|":"ou","\xA2":"centime","\xA3":"livre","\xA4":"devise","\u20A3":"franc","\u2211":"somme","\u221E":"infini","\u2665":"amour"},"pt":{"%":"porcento","&":"e","<":"menor",">":"maior","|":"ou","\xA2":"centavo","\u2211":"soma","\xA3":"libra","\u221E":"infinito","\u2665":"amor"},"uk":{"\u0418":"Y","\u0438":"y","\u0419":"Y","\u0439":"y","\u0426":"Ts","\u0446":"ts","\u0425":"Kh","\u0445":"kh","\u0429":"Shch","\u0449":"shch","\u0413":"H","\u0433":"h"},"vi":{"\u0110":"D","\u0111":"d"},"da":{"\xD8":"OE","\xF8":"oe","\xC5":"AA","\xE5":"aa","%":"procent","&":"og","|":"eller","$":"dollar","<":"mindre end",">":"st\xF8rre end"},"nb":{"&":"og","\xC5":"AA","\xC6":"AE","\xD8":"OE","\xE5":"aa","\xE6":"ae","\xF8":"oe"},"it":{"&":"e"},"nl":{"&":"en"},"sv":{"&":"och","\xC5":"AA","\xC4":"AE","\xD6":"OE","\xE5":"aa","\xE4":"ae","\xF6":"oe"}}'); | |
function replace(string, options) { | |
if (typeof string !== "string") { | |
throw new Error("slugify: string argument expected"); | |
} | |
options = typeof options === "string" ? { replacement: options } : options || {}; | |
var locale = locales[options.locale] || {}; | |
var replacement = options.replacement === void 0 ? "-" : options.replacement; | |
var trim = options.trim === void 0 ? true : options.trim; | |
var slug = string.normalize().split("").reduce(function(result, ch) { | |
var appendChar = locale[ch]; | |
if (appendChar === void 0) | |
appendChar = charMap[ch]; | |
if (appendChar === void 0) | |
appendChar = ch; | |
if (appendChar === replacement) | |
appendChar = " "; | |
return result + appendChar.replace(options.remove || /[^\w\s$*_+~.()'"!\-:@]+/g, ""); | |
}, ""); | |
if (options.strict) { | |
slug = slug.replace(/[^A-Za-z0-9\s]/g, ""); | |
} | |
if (trim) { | |
slug = slug.trim(); | |
} | |
slug = slug.replace(/\s+/g, replacement); | |
if (options.lower) { | |
slug = slug.toLowerCase(); | |
} | |
return slug; | |
} | |
replace.extend = function(customMap) { | |
Object.assign(charMap, customMap); | |
}; | |
return replace; | |
}); | |
} | |
}); | |
// node_modules/before-after-hook/lib/register.js | |
var require_register = __commonJS({ | |
"node_modules/before-after-hook/lib/register.js"(exports, module2) { | |
module2.exports = register; | |
function register(state, name, method, options) { | |
if (typeof method !== "function") { | |
throw new Error("method for before hook must be a function"); | |
} | |
if (!options) { | |
options = {}; | |
} | |
if (Array.isArray(name)) { | |
return name.reverse().reduce(function(callback, name2) { | |
return register.bind(null, state, name2, callback, options); | |
}, method)(); | |
} | |
return Promise.resolve().then(function() { | |
if (!state.registry[name]) { | |
return method(options); | |
} | |
return state.registry[name].reduce(function(method2, registered) { | |
return registered.hook.bind(null, method2, options); | |
}, method)(); | |
}); | |
} | |
} | |
}); | |
// node_modules/before-after-hook/lib/add.js | |
var require_add = __commonJS({ | |
"node_modules/before-after-hook/lib/add.js"(exports, module2) { | |
module2.exports = addHook; | |
function addHook(state, kind, name, hook2) { | |
var orig = hook2; | |
if (!state.registry[name]) { | |
state.registry[name] = []; | |
} | |
if (kind === "before") { | |
hook2 = function(method, options) { | |
return Promise.resolve().then(orig.bind(null, options)).then(method.bind(null, options)); | |
}; | |
} | |
if (kind === "after") { | |
hook2 = function(method, options) { | |
var result; | |
return Promise.resolve().then(method.bind(null, options)).then(function(result_) { | |
result = result_; | |
return orig(result, options); | |
}).then(function() { | |
return result; | |
}); | |
}; | |
} | |
if (kind === "error") { | |
hook2 = function(method, options) { | |
return Promise.resolve().then(method.bind(null, options)).catch(function(error4) { | |
return orig(error4, options); | |
}); | |
}; | |
} | |
state.registry[name].push({ | |
hook: hook2, | |
orig | |
}); | |
} | |
} | |
}); | |
// node_modules/before-after-hook/lib/remove.js | |
var require_remove = __commonJS({ | |
"node_modules/before-after-hook/lib/remove.js"(exports, module2) { | |
module2.exports = removeHook; | |
function removeHook(state, name, method) { | |
if (!state.registry[name]) { | |
return; | |
} | |
var index = state.registry[name].map(function(registered) { | |
return registered.orig; | |
}).indexOf(method); | |
if (index === -1) { | |
return; | |
} | |
state.registry[name].splice(index, 1); | |
} | |
} | |
}); | |
// node_modules/before-after-hook/index.js | |
var require_before_after_hook = __commonJS({ | |
"node_modules/before-after-hook/index.js"(exports, module2) { | |
var register = require_register(); | |
var addHook = require_add(); | |
var removeHook = require_remove(); | |
var bind = Function.bind; | |
var bindable = bind.bind(bind); | |
function bindApi(hook2, state, name) { | |
var removeHookRef = bindable(removeHook, null).apply( | |
null, | |
name ? [state, name] : [state] | |
); | |
hook2.api = { remove: removeHookRef }; | |
hook2.remove = removeHookRef; | |
["before", "error", "after", "wrap"].forEach(function(kind) { | |
var args = name ? [state, kind, name] : [state, kind]; | |
hook2[kind] = hook2.api[kind] = bindable(addHook, null).apply(null, args); | |
}); | |
} | |
function HookSingular() { | |
var singularHookName = "h"; | |
var singularHookState = { | |
registry: {} | |
}; | |
var singularHook = register.bind(null, singularHookState, singularHookName); | |
bindApi(singularHook, singularHookState, singularHookName); | |
return singularHook; | |
} | |
function HookCollection() { | |
var state = { | |
registry: {} | |
}; | |
var hook2 = register.bind(null, state); | |
bindApi(hook2, state); | |
return hook2; | |
} | |
var collectionHookDeprecationMessageDisplayed = false; | |
function Hook() { | |
if (!collectionHookDeprecationMessageDisplayed) { | |
console.warn( | |
'[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' | |
); | |
collectionHookDeprecationMessageDisplayed = true; | |
} | |
return HookCollection(); | |
} | |
Hook.Singular = HookSingular.bind(); | |
Hook.Collection = HookCollection.bind(); | |
module2.exports = Hook; | |
module2.exports.Hook = Hook; | |
module2.exports.Singular = Hook.Singular; | |
module2.exports.Collection = Hook.Collection; | |
} | |
}); | |
// node_modules/node-fetch/browser.js | |
var require_browser = __commonJS({ | |
"node_modules/node-fetch/browser.js"(exports, module2) { | |
"use strict"; | |
var getGlobal = function() { | |
if (typeof self !== "undefined") { | |
return self; | |
} | |
if (typeof window !== "undefined") { | |
return window; | |
} | |
if (typeof global !== "undefined") { | |
return global; | |
} | |
throw new Error("unable to locate global object"); | |
}; | |
var globalObject = getGlobal(); | |
module2.exports = exports = globalObject.fetch; | |
if (globalObject.fetch) { | |
exports.default = globalObject.fetch.bind(globalObject); | |
} | |
exports.Headers = globalObject.Headers; | |
exports.Request = globalObject.Request; | |
exports.Response = globalObject.Response; | |
} | |
}); | |
// node_modules/wrappy/wrappy.js | |
var require_wrappy = __commonJS({ | |
"node_modules/wrappy/wrappy.js"(exports, module2) { | |
module2.exports = wrappy; | |
function wrappy(fn, cb) { | |
if (fn && cb) | |
return wrappy(fn)(cb); | |
if (typeof fn !== "function") | |
throw new TypeError("need wrapper function"); | |
Object.keys(fn).forEach(function(k) { | |
wrapper[k] = fn[k]; | |
}); | |
return wrapper; | |
function wrapper() { | |
var args = new Array(arguments.length); | |
for (var i = 0; i < args.length; i++) { | |
args[i] = arguments[i]; | |
} | |
var ret = fn.apply(this, args); | |
var cb2 = args[args.length - 1]; | |
if (typeof ret === "function" && ret !== cb2) { | |
Object.keys(cb2).forEach(function(k) { | |
ret[k] = cb2[k]; | |
}); | |
} | |
return ret; | |
} | |
} | |
} | |
}); | |
// node_modules/once/once.js | |
var require_once = __commonJS({ | |
"node_modules/once/once.js"(exports, module2) { | |
var wrappy = require_wrappy(); | |
module2.exports = wrappy(once2); | |
module2.exports.strict = wrappy(onceStrict); | |
once2.proto = once2(function() { | |
Object.defineProperty(Function.prototype, "once", { | |
value: function() { | |
return once2(this); | |
}, | |
configurable: true | |
}); | |
Object.defineProperty(Function.prototype, "onceStrict", { | |
value: function() { | |
return onceStrict(this); | |
}, | |
configurable: true | |
}); | |
}); | |
function once2(fn) { | |
var f = function() { | |
if (f.called) | |
return f.value; | |
f.called = true; | |
return f.value = fn.apply(this, arguments); | |
}; | |
f.called = false; | |
return f; | |
} | |
function onceStrict(fn) { | |
var f = function() { | |
if (f.called) | |
throw new Error(f.onceError); | |
f.called = true; | |
return f.value = fn.apply(this, arguments); | |
}; | |
var name = fn.name || "Function wrapped with `once`"; | |
f.onceError = name + " shouldn't be called more than once"; | |
f.called = false; | |
return f; | |
} | |
} | |
}); | |
// plugin/main.ts | |
var main_exports = {}; | |
__export(main_exports, { | |
default: () => GithubPublisher | |
}); | |
module.exports = __toCommonJS(main_exports); | |
var import_obsidian15 = require("obsidian"); | |
// plugin/settings.ts | |
var import_obsidian6 = require("obsidian"); | |
// plugin/settings/modals/regex_edition.ts | |
var import_obsidian = require("obsidian"); | |
// plugin/settings/interface.ts | |
var DEFAULT_SETTINGS = { | |
github: { | |
user: "", | |
repo: "", | |
branch: "main", | |
token: "", | |
automaticallyMergePR: true, | |
api: { | |
tiersForApi: "Github Free/Pro/Team (default)" /* free */, | |
hostname: "" | |
}, | |
worflow: { | |
customCommitMsg: "[PUBLISHER] Merge", | |
workflowName: "" | |
} | |
}, | |
upload: { | |
behavior: "fixed" /* fixed */, | |
defaultName: "", | |
rootFolder: "", | |
yamlFolderKey: "", | |
frontmatterTitle: { | |
enable: false, | |
key: "title" | |
}, | |
replaceTitle: [], | |
replacePath: [], | |
autoclean: { | |
enable: false, | |
excluded: [] | |
}, | |
folderNote: { | |
enable: false, | |
rename: "index.md" | |
}, | |
metadataExtractorPath: "" | |
}, | |
conversion: { | |
hardbreak: false, | |
dataview: true, | |
censorText: [], | |
tags: { | |
inline: false, | |
exclude: [], | |
fields: [] | |
}, | |
links: { | |
internal: false, | |
unshared: false, | |
wiki: false, | |
slugify: false | |
} | |
}, | |
embed: { | |
attachments: true, | |
keySendFile: [], | |
notes: false, | |
folder: "" | |
}, | |
plugin: { | |
shareKey: "share", | |
fileMenu: false, | |
editorMenu: false, | |
excludedFolder: [], | |
copyLink: { | |
enable: false, | |
links: "", | |
removePart: [], | |
addCmd: false | |
}, | |
noticeError: false, | |
displayModalRepoEditing: false | |
} | |
}; | |
// node_modules/@babel/runtime/helpers/esm/typeof.js | |
function _typeof(obj) { | |
"@babel/helpers - typeof"; | |
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj2) { | |
return typeof obj2; | |
} : function(obj2) { | |
return obj2 && "function" == typeof Symbol && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; | |
}, _typeof(obj); | |
} | |
// node_modules/@babel/runtime/helpers/esm/classCallCheck.js | |
function _classCallCheck(instance2, Constructor) { | |
if (!(instance2 instanceof Constructor)) { | |
throw new TypeError("Cannot call a class as a function"); | |
} | |
} | |
// node_modules/@babel/runtime/helpers/esm/toPrimitive.js | |
function _toPrimitive(input, hint) { | |
if (_typeof(input) !== "object" || input === null) | |
return input; | |
var prim = input[Symbol.toPrimitive]; | |
if (prim !== void 0) { | |
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); | |
} | |
// node_modules/@babel/runtime/helpers/esm/toPropertyKey.js | |
function _toPropertyKey(arg) { | |
var key = _toPrimitive(arg, "string"); | |
return _typeof(key) === "symbol" ? key : String(key); | |
} | |
// node_modules/@babel/runtime/helpers/esm/createClass.js | |
function _defineProperties(target, props) { | |
for (var i = 0; i < props.length; i++) { | |
var descriptor = props[i]; | |
descriptor.enumerable = descriptor.enumerable || false; | |
descriptor.configurable = true; | |
if ("value" in descriptor) | |
descriptor.writable = true; | |
Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); | |
} | |
} | |
function _createClass(Constructor, protoProps, staticProps) { | |
if (protoProps) | |
_defineProperties(Constructor.prototype, protoProps); | |
if (staticProps) | |
_defineProperties(Constructor, staticProps); | |
Object.defineProperty(Constructor, "prototype", { | |
writable: false | |
}); | |
return Constructor; | |
} | |
// node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js | |
function _assertThisInitialized(self2) { | |
if (self2 === void 0) { | |
throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); | |
} | |
return self2; | |
} | |
// node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js | |
function _setPrototypeOf(o, p) { | |
_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) { | |
o2.__proto__ = p2; | |
return o2; | |
}; | |
return _setPrototypeOf(o, p); | |
} | |
// node_modules/@babel/runtime/helpers/esm/inherits.js | |
function _inherits(subClass, superClass) { | |
if (typeof superClass !== "function" && superClass !== null) { | |
throw new TypeError("Super expression must either be null or a function"); | |
} | |
subClass.prototype = Object.create(superClass && superClass.prototype, { | |
constructor: { | |
value: subClass, | |
writable: true, | |
configurable: true | |
} | |
}); | |
Object.defineProperty(subClass, "prototype", { | |
writable: false | |
}); | |
if (superClass) | |
_setPrototypeOf(subClass, superClass); | |
} | |
// node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js | |
function _possibleConstructorReturn(self2, call) { | |
if (call && (_typeof(call) === "object" || typeof call === "function")) { | |
return call; | |
} else if (call !== void 0) { | |
throw new TypeError("Derived constructors may only return object or undefined"); | |
} | |
return _assertThisInitialized(self2); | |
} | |
// node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js | |
function _getPrototypeOf(o) { | |
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) { | |
return o2.__proto__ || Object.getPrototypeOf(o2); | |
}; | |
return _getPrototypeOf(o); | |
} | |
// node_modules/@babel/runtime/helpers/esm/defineProperty.js | |
function _defineProperty(obj, key, value) { | |
key = _toPropertyKey(key); | |
if (key in obj) { | |
Object.defineProperty(obj, key, { | |
value, | |
enumerable: true, | |
configurable: true, | |
writable: true | |
}); | |
} else { | |
obj[key] = value; | |
} | |
return obj; | |
} | |
// node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js | |
function _arrayWithHoles(arr) { | |
if (Array.isArray(arr)) | |
return arr; | |
} | |
// node_modules/@babel/runtime/helpers/esm/iterableToArray.js | |
function _iterableToArray(iter) { | |
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) | |
return Array.from(iter); | |
} | |
// node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js | |
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; | |
} | |
// node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js | |
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); | |
} | |
// node_modules/@babel/runtime/helpers/esm/nonIterableRest.js | |
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."); | |
} | |
// node_modules/@babel/runtime/helpers/esm/toArray.js | |
function _toArray(arr) { | |
return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest(); | |
} | |
// node_modules/i18next/dist/esm/i18next.js | |
function ownKeys$6(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$6(target) { | |
for (var i = 1; i < arguments.length; i++) { | |
var source = null != arguments[i] ? arguments[i] : {}; | |
i % 2 ? ownKeys$6(Object(source), true).forEach(function(key) { | |
_defineProperty(target, key, source[key]); | |
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$6(Object(source)).forEach(function(key) { | |
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); | |
}); | |
} | |
return target; | |
} | |
var consoleLogger = { | |
type: "logger", | |
log: function log(args) { | |
this.output("log", args); | |
}, | |
warn: function warn(args) { | |
this.output("warn", args); | |
}, | |
error: function error(args) { | |
this.output("error", args); | |
}, | |
output: function output(type, args) { | |
if (console && console[type]) | |
console[type].apply(console, args); | |
} | |
}; | |
var Logger = function() { | |
function Logger2(concreteLogger) { | |
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; | |
_classCallCheck(this, Logger2); | |
this.init(concreteLogger, options); | |
} | |
_createClass(Logger2, [{ | |
key: "init", | |
value: function init2(concreteLogger) { | |
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; | |
this.prefix = options.prefix || "i18next:"; | |
this.logger = concreteLogger || consoleLogger; | |
this.options = options; | |
this.debug = options.debug; | |
} | |
}, { | |
key: "setDebug", | |
value: function setDebug(bool) { | |
this.debug = bool; | |
} | |
}, { | |
key: "log", | |
value: function log2() { | |
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | |
args[_key] = arguments[_key]; | |
} | |
return this.forward(args, "log", "", true); | |
} | |
}, { | |
key: "warn", | |
value: function warn2() { | |
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { | |
args[_key2] = arguments[_key2]; | |
} | |
return this.forward(args, "warn", "", true); | |
} | |
}, { | |
key: "error", | |
value: function error4() { | |
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { | |
args[_key3] = arguments[_key3]; | |
} | |
return this.forward(args, "error", ""); | |
} | |
}, { | |
key: "deprecate", | |
value: function deprecate() { | |
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { | |
args[_key4] = arguments[_key4]; | |
} | |
return this.forward(args, "warn", "WARNING DEPRECATED: ", true); | |
} | |
}, { | |
key: "forward", | |
value: function forward(args, lvl, prefix, debugOnly) { | |
if (debugOnly && !this.debug) | |
return null; | |
if (typeof args[0] === "string") | |
args[0] = "".concat(prefix).concat(this.prefix, " ").concat(args[0]); | |
return this.logger[lvl](args); | |
} | |
}, { | |
key: "create", | |
value: function create(moduleName) { | |
return new Logger2(this.logger, _objectSpread$6(_objectSpread$6({}, { | |
prefix: "".concat(this.prefix, ":").concat(moduleName, ":") | |
}), this.options)); | |
} | |
}, { | |
key: "clone", | |
value: function clone2(options) { | |
options = options || this.options; | |
options.prefix = options.prefix || this.prefix; | |
return new Logger2(this.logger, options); | |
} | |
}]); | |
return Logger2; | |
}(); | |
var baseLogger = new Logger(); | |
var EventEmitter = function() { | |
function EventEmitter2() { | |
_classCallCheck(this, EventEmitter2); | |
this.observers = {}; | |
} | |
_createClass(EventEmitter2, [{ | |
key: "on", | |
value: function on(events, listener) { | |
var _this = this; | |
events.split(" ").forEach(function(event) { | |
_this.observers[event] = _this.observers[event] || []; | |
_this.observers[event].push(listener); | |
}); | |
return this; | |
} | |
}, { | |
key: "off", | |
value: function off(event, listener) { | |
if (!this.observers[event]) | |
return; | |
if (!listener) { | |
delete this.observers[event]; | |
return; | |
} | |
this.observers[event] = this.observers[event].filter(function(l) { | |
return l !== listener; | |
}); | |
} | |
}, { | |
key: "emit", | |
value: function emit(event) { | |
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { | |
args[_key - 1] = arguments[_key]; | |
} | |
if (this.observers[event]) { | |
var cloned = [].concat(this.observers[event]); | |
cloned.forEach(function(observer) { | |
observer.apply(void 0, args); | |
}); | |
} | |
if (this.observers["*"]) { | |
var _cloned = [].concat(this.observers["*"]); | |
_cloned.forEach(function(observer) { | |
observer.apply(observer, [event].concat(args)); | |
}); | |
} | |
} | |
}]); | |
return EventEmitter2; | |
}(); | |
function defer() { | |
var res; | |
var rej; | |
var promise = new Promise(function(resolve, reject) { | |
res = resolve; | |
rej = reject; | |
}); | |
promise.resolve = res; | |
promise.reject = rej; | |
return promise; | |
} | |
function makeString(object) { | |
if (object == null) | |
return ""; | |
return "" + object; | |
} | |
function copy(a, s, t2) { | |
a.forEach(function(m) { | |
if (s[m]) | |
t2[m] = s[m]; | |
}); | |
} | |
function getLastOfPath(object, path, Empty) { | |
function cleanKey(key2) { | |
return key2 && key2.indexOf("###") > -1 ? key2.replace(/###/g, ".") : key2; | |
} | |
function canNotTraverseDeeper() { | |
return !object || typeof object === "string"; | |
} | |
var stack = typeof path !== "string" ? [].concat(path) : path.split("."); | |
while (stack.length > 1) { | |
if (canNotTraverseDeeper()) | |
return {}; | |
var key = cleanKey(stack.shift()); | |
if (!object[key] && Empty) | |
object[key] = new Empty(); | |
if (Object.prototype.hasOwnProperty.call(object, key)) { | |
object = object[key]; | |
} else { | |
object = {}; | |
} | |
} | |
if (canNotTraverseDeeper()) | |
return {}; | |
return { | |
obj: object, | |
k: cleanKey(stack.shift()) | |
}; | |
} | |
function setPath(object, path, newValue) { | |
var _getLastOfPath = getLastOfPath(object, path, Object), obj = _getLastOfPath.obj, k = _getLastOfPath.k; | |
obj[k] = newValue; | |
} | |
function pushPath(object, path, newValue, concat) { | |
var _getLastOfPath2 = getLastOfPath(object, path, Object), obj = _getLastOfPath2.obj, k = _getLastOfPath2.k; | |
obj[k] = obj[k] || []; | |
if (concat) | |
obj[k] = obj[k].concat(newValue); | |
if (!concat) | |
obj[k].push(newValue); | |
} | |
function getPath(object, path) { | |
var _getLastOfPath3 = getLastOfPath(object, path), obj = _getLastOfPath3.obj, k = _getLastOfPath3.k; | |
if (!obj) | |
return void 0; | |
return obj[k]; | |
} | |
function getPathWithDefaults(data, defaultData, key) { | |
var value = getPath(data, key); | |
if (value !== void 0) { | |
return value; | |
} | |
return getPath(defaultData, key); | |
} | |
function deepExtend(target, source, overwrite) { | |
for (var prop in source) { | |
if (prop !== "__proto__" && prop !== "constructor") { | |
if (prop in target) { | |
if (typeof target[prop] === "string" || target[prop] instanceof String || typeof source[prop] === "string" || source[prop] instanceof String) { | |
if (overwrite) | |
target[prop] = source[prop]; | |
} else { | |
deepExtend(target[prop], source[prop], overwrite); | |
} | |
} else { | |
target[prop] = source[prop]; | |
} | |
} | |
} | |
return target; | |
} | |
function regexEscape(str) { | |
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); | |
} | |
var _entityMap = { | |
"&": "&", | |
"<": "<", | |
">": ">", | |
'"': """, | |
"'": "'", | |
"/": "/" | |
}; | |
function escape(data) { | |
if (typeof data === "string") { | |
return data.replace(/[&<>"'\/]/g, function(s) { | |
return _entityMap[s]; | |
}); | |
} | |
return data; | |
} | |
var isIE10 = typeof window !== "undefined" && window.navigator && typeof window.navigator.userAgentData === "undefined" && window.navigator.userAgent && window.navigator.userAgent.indexOf("MSIE") > -1; | |
var chars = [" ", ",", "?", "!", ";"]; | |
function looksLikeObjectPath(key, nsSeparator, keySeparator) { | |
nsSeparator = nsSeparator || ""; | |
keySeparator = keySeparator || ""; | |
var possibleChars = chars.filter(function(c) { | |
return nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0; | |
}); | |
if (possibleChars.length === 0) | |
return true; | |
var r = new RegExp("(".concat(possibleChars.map(function(c) { | |
return c === "?" ? "\\?" : c; | |
}).join("|"), ")")); | |
var matched = !r.test(key); | |
if (!matched) { | |
var ki = key.indexOf(keySeparator); | |
if (ki > 0 && !r.test(key.substring(0, ki))) { | |
matched = true; | |
} | |
} | |
return matched; | |
} | |
function ownKeys$5(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$5(target) { | |
for (var i = 1; i < arguments.length; i++) { | |
var source = null != arguments[i] ? arguments[i] : {}; | |
i % 2 ? ownKeys$5(Object(source), true).forEach(function(key) { | |
_defineProperty(target, key, source[key]); | |
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$5(Object(source)).forEach(function(key) { | |
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); | |
}); | |
} | |
return target; | |
} | |
function _createSuper$3(Derived) { | |
var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); | |
return function _createSuperInternal() { | |
var Super = _getPrototypeOf(Derived), result; | |
if (hasNativeReflectConstruct) { | |
var NewTarget = _getPrototypeOf(this).constructor; | |
result = Reflect.construct(Super, arguments, NewTarget); | |
} else { | |
result = Super.apply(this, arguments); | |
} | |
return _possibleConstructorReturn(this, result); | |
}; | |
} | |
function _isNativeReflectConstruct$3() { | |
if (typeof Reflect === "undefined" || !Reflect.construct) | |
return false; | |
if (Reflect.construct.sham) | |
return false; | |
if (typeof Proxy === "function") | |
return true; | |
try { | |
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() { | |
})); | |
return true; | |
} catch (e) { | |
return false; | |
} | |
} | |
function deepFind(obj, path) { | |
var keySeparator = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "."; | |
if (!obj) | |
return void 0; | |
if (obj[path]) | |
return obj[path]; | |
var paths = path.split(keySeparator); | |
var current = obj; | |
for (var i = 0; i < paths.length; ++i) { | |
if (!current) | |
return void 0; | |
if (typeof current[paths[i]] === "string" && i + 1 < paths.length) { | |
return void 0; | |
} | |
if (current[paths[i]] === void 0) { | |
var j = 2; | |
var p = paths.slice(i, i + j).join(keySeparator); | |
var mix = current[p]; | |
while (mix === void 0 && paths.length > i + j) { | |
j++; | |
p = paths.slice(i, i + j).join(keySeparator); | |
mix = current[p]; | |
} | |
if (mix === void 0) | |
return void 0; | |
if (mix === null) | |
return null; | |
if (path.endsWith(p)) { | |
if (typeof mix === "string") | |
return mix; | |
if (p && typeof mix[p] === "string") | |
return mix[p]; | |
} | |
var joinedPath = paths.slice(i + j).join(keySeparator); | |
if (joinedPath) | |
return deepFind(mix, joinedPath, keySeparator); | |
return void 0; | |
} | |
current = current[paths[i]]; | |
} | |
return current; | |
} | |
var ResourceStore = function(_EventEmitter) { | |
_inherits(ResourceStore2, _EventEmitter); | |
var _super = _createSuper$3(ResourceStore2); | |
function ResourceStore2(data) { | |
var _this; | |
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : { | |
ns: ["translation"], | |
defaultNS: "translation" | |
}; | |
_classCallCheck(this, ResourceStore2); | |
_this = _super.call(this); | |
if (isIE10) { | |
EventEmitter.call(_assertThisInitialized(_this)); | |
} | |
_this.data = data || {}; | |
_this.options = options; | |
if (_this.options.keySeparator === void 0) { | |
_this.options.keySeparator = "."; | |
} | |
if (_this.options.ignoreJSONStructure === void 0) { | |
_this.options.ignoreJSONStructure = true; | |
} | |
return _this; | |
} | |
_createClass(ResourceStore2, [{ | |
key: "addNamespaces", | |
value: function addNamespaces(ns) { | |
if (this.options.ns.indexOf(ns) < 0) { | |
this.options.ns.push(ns); | |
} | |
} | |
}, { | |
key: "removeNamespaces", | |
value: function removeNamespaces(ns) { | |
var index = this.options.ns.indexOf(ns); | |
if (index > -1) { | |
this.options.ns.splice(index, 1); | |
} | |
} | |
}, { | |
key: "getResource", | |
value: function getResource(lng, ns, key) { | |
var options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {}; | |
var keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator; | |
var ignoreJSONStructure = options.ignoreJSONStructure !== void 0 ? options.ignoreJSONStructure : this.options.ignoreJSONStructure; | |
var path = [lng, ns]; | |
if (key && typeof key !== "string") | |
path = path.concat(key); | |
if (key && typeof key === "string") | |
path = path.concat(keySeparator ? key.split(keySeparator) : key); | |
if (lng.indexOf(".") > -1) { | |
path = lng.split("."); | |
} | |
var result = getPath(this.data, path); | |
if (result || !ignoreJSONStructure || typeof key !== "string") | |
return result; | |
return deepFind(this.data && this.data[lng] && this.data[lng][ns], key, keySeparator); | |
} | |
}, { | |
key: "addResource", | |
value: function addResource(lng, ns, key, value) { | |
var options = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : { | |
silent: false | |
}; | |
var keySeparator = this.options.keySeparator; | |
if (keySeparator === void 0) | |
keySeparator = "."; | |
var path = [lng, ns]; | |
if (key) | |
path = path.concat(keySeparator ? key.split(keySeparator) : key); | |
if (lng.indexOf(".") > -1) { | |
path = lng.split("."); | |
value = ns; | |
ns = path[1]; | |
} | |
this.addNamespaces(ns); | |
setPath(this.data, path, value); | |
if (!options.silent) | |
this.emit("added", lng, ns, key, value); | |
} | |
}, { | |
key: "addResources", | |
value: function addResources(lng, ns, resources) { | |
var options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : { | |
silent: false | |
}; | |
for (var m in resources) { | |
if (typeof resources[m] === "string" || Object.prototype.toString.apply(resources[m]) === "[object Array]") | |
this.addResource(lng, ns, m, resources[m], { | |
silent: true | |
}); | |
} | |
if (!options.silent) | |
this.emit("added", lng, ns, resources); | |
} | |
}, { | |
key: "addResourceBundle", | |
value: function addResourceBundle(lng, ns, resources, deep, overwrite) { | |
var options = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : { | |
silent: false | |
}; | |
var path = [lng, ns]; | |
if (lng.indexOf(".") > -1) { | |
path = lng.split("."); | |
deep = resources; | |
resources = ns; | |
ns = path[1]; | |
} | |
this.addNamespaces(ns); | |
var pack = getPath(this.data, path) || {}; | |
if (deep) { | |
deepExtend(pack, resources, overwrite); | |
} else { | |
pack = _objectSpread$5(_objectSpread$5({}, pack), resources); | |
} | |
setPath(this.data, path, pack); | |
if (!options.silent) | |
this.emit("added", lng, ns, resources); | |
} | |
}, { | |
key: "removeResourceBundle", | |
value: function removeResourceBundle(lng, ns) { | |
if (this.hasResourceBundle(lng, ns)) { | |
delete this.data[lng][ns]; | |
} | |
this.removeNamespaces(ns); | |
this.emit("removed", lng, ns); | |
} | |
}, { | |
key: "hasResourceBundle", | |
value: function hasResourceBundle(lng, ns) { | |
return this.getResource(lng, ns) !== void 0; | |
} | |
}, { | |
key: "getResourceBundle", | |
value: function getResourceBundle(lng, ns) { | |
if (!ns) | |
ns = this.options.defaultNS; | |
if (this.options.compatibilityAPI === "v1") | |
return _objectSpread$5(_objectSpread$5({}, {}), this.getResource(lng, ns)); | |
return this.getResource(lng, ns); | |
} | |
}, { | |
key: "getDataByLanguage", | |
value: function getDataByLanguage(lng) { | |
return this.data[lng]; | |
} | |
}, { | |
key: "hasLanguageSomeTranslations", | |
value: function hasLanguageSomeTranslations(lng) { | |
var data = this.getDataByLanguage(lng); | |
var n = data && Object.keys(data) || []; | |
return !!n.find(function(v) { | |
return data[v] && Object.keys(data[v]).length > 0; | |
}); | |
} | |
}, { | |
key: "toJSON", | |
value: function toJSON() { | |
return this.data; | |
} | |
}]); | |
return ResourceStore2; | |
}(EventEmitter); | |
var postProcessor = { | |
processors: {}, | |
addPostProcessor: function addPostProcessor(module2) { | |
this.processors[module2.name] = module2; | |
}, | |
handle: function handle(processors, value, key, options, translator) { | |
var _this = this; | |
processors.forEach(function(processor) { | |
if (_this.processors[processor]) | |
value = _this.processors[processor].process(value, key, options, translator); | |
}); | |
return value; | |
} | |
}; | |
function ownKeys$4(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$4(target) { | |
for (var i = 1; i < arguments.length; i++) { | |
var source = null != arguments[i] ? arguments[i] : {}; | |
i % 2 ? ownKeys$4(Object(source), true).forEach(function(key) { | |
_defineProperty(target, key, source[key]); | |
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$4(Object(source)).forEach(function(key) { | |
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); | |
}); | |
} | |
return target; | |
} | |
function _createSuper$2(Derived) { | |
var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); | |
return function _createSuperInternal() { | |
var Super = _getPrototypeOf(Derived), result; | |
if (hasNativeReflectConstruct) { | |
var NewTarget = _getPrototypeOf(this).constructor; | |
result = Reflect.construct(Super, arguments, NewTarget); | |
} else { | |
result = Super.apply(this, arguments); | |
} | |
return _possibleConstructorReturn(this, result); | |
}; | |
} | |
function _isNativeReflectConstruct$2() { | |
if (typeof Reflect === "undefined" || !Reflect.construct) | |
return false; | |
if (Reflect.construct.sham) | |
return false; | |
if (typeof Proxy === "function") | |
return true; | |
try { | |
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() { | |
})); | |
return true; | |
} catch (e) { | |
return false; | |
} | |
} | |
var checkedLoadedFor = {}; | |
var Translator = function(_EventEmitter) { | |
_inherits(Translator2, _EventEmitter); | |
var _super = _createSuper$2(Translator2); | |
function Translator2(services) { | |
var _this; | |
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; | |
_classCallCheck(this, Translator2); | |
_this = _super.call(this); | |
if (isIE10) { | |
EventEmitter.call(_assertThisInitialized(_this)); | |
} | |
copy(["resourceStore", "languageUtils", "pluralResolver", "interpolator", "backendConnector", "i18nFormat", "utils"], services, _assertThisInitialized(_this)); | |
_this.options = options; | |
if (_this.options.keySeparator === void 0) { | |
_this.options.keySeparator = "."; | |
} | |
_this.logger = baseLogger.create("translator"); | |
return _this; | |
} | |
_createClass(Translator2, [{ | |
key: "changeLanguage", | |
value: function changeLanguage2(lng) { | |
if (lng) | |
this.language = lng; | |
} | |
}, { | |
key: "exists", | |
value: function exists2(key) { | |
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : { | |
interpolation: {} | |
}; | |
if (key === void 0 || key === null) { | |
return false; | |
} | |
var resolved = this.resolve(key, options); | |
return resolved && resolved.res !== void 0; | |
} | |
}, { | |
key: "extractFromKey", | |
value: function extractFromKey(key, options) { | |
var nsSeparator = options.nsSeparator !== void 0 ? options.nsSeparator : this.options.nsSeparator; | |
if (nsSeparator === void 0) | |
nsSeparator = ":"; | |
var keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator; | |
var namespaces = options.ns || this.options.defaultNS || []; | |
var wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1; | |
var seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !options.keySeparator && !this.options.userDefinedNsSeparator && !options.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator); | |
if (wouldCheckForNsInKey && !seemsNaturalLanguage) { | |
var m = key.match(this.interpolator.nestingRegexp); | |
if (m && m.length > 0) { | |
return { | |
key, | |
namespaces | |
}; | |
} | |
var parts = key.split(nsSeparator); | |
if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) | |
namespaces = parts.shift(); | |
key = parts.join(keySeparator); | |
} | |
if (typeof namespaces === "string") | |
namespaces = [namespaces]; | |
return { | |
key, | |
namespaces | |
}; | |
} | |
}, { | |
key: "translate", | |
value: function translate(keys, options, lastKey) { | |
var _this2 = this; | |
if (_typeof(options) !== "object" && this.options.overloadTranslationOptionHandler) { | |
options = this.options.overloadTranslationOptionHandler(arguments); | |
} | |
if (!options) | |
options = {}; | |
if (keys === void 0 || keys === null) | |
return ""; | |
if (!Array.isArray(keys)) | |
keys = [String(keys)]; | |
var returnDetails = options.returnDetails !== void 0 ? options.returnDetails : this.options.returnDetails; | |
var keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator; | |
var _this$extractFromKey = this.extractFromKey(keys[keys.length - 1], options), key = _this$extractFromKey.key, namespaces = _this$extractFromKey.namespaces; | |
var namespace = namespaces[namespaces.length - 1]; | |
var lng = options.lng || this.language; | |
var appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode; | |
if (lng && lng.toLowerCase() === "cimode") { | |
if (appendNamespaceToCIMode) { | |
var nsSeparator = options.nsSeparator || this.options.nsSeparator; | |
if (returnDetails) { | |
return { | |
res: "".concat(namespace).concat(nsSeparator).concat(key), | |
usedKey: key, | |
exactUsedKey: key, | |
usedLng: lng, | |
usedNS: namespace | |
}; | |
} | |
return "".concat(namespace).concat(nsSeparator).concat(key); | |
} | |
if (returnDetails) { | |
return { | |
res: key, | |
usedKey: key, | |
exactUsedKey: key, | |
usedLng: lng, | |
usedNS: namespace | |
}; | |
} | |
return key; | |
} | |
var resolved = this.resolve(keys, options); | |
var res = resolved && resolved.res; | |
var resUsedKey = resolved && resolved.usedKey || key; | |
var resExactUsedKey = resolved && resolved.exactUsedKey || key; | |
var resType = Object.prototype.toString.apply(res); | |
var noObject = ["[object Number]", "[object Function]", "[object RegExp]"]; | |
var joinArrays = options.joinArrays !== void 0 ? options.joinArrays : this.options.joinArrays; | |
var handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject; | |
var handleAsObject = typeof res !== "string" && typeof res !== "boolean" && typeof res !== "number"; | |
if (handleAsObjectInI18nFormat && res && handleAsObject && noObject.indexOf(resType) < 0 && !(typeof joinArrays === "string" && resType === "[object Array]")) { | |
if (!options.returnObjects && !this.options.returnObjects) { | |
if (!this.options.returnedObjectHandler) { | |
this.logger.warn("accessing an object - but returnObjects options is not enabled!"); | |
} | |
var r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, res, _objectSpread$4(_objectSpread$4({}, options), {}, { | |
ns: namespaces | |
})) : "key '".concat(key, " (").concat(this.language, ")' returned an object instead of string."); | |
if (returnDetails) { | |
resolved.res = r; | |
return resolved; | |
} | |
return r; | |
} | |
if (keySeparator) { | |
var resTypeIsArray = resType === "[object Array]"; | |
var copy2 = resTypeIsArray ? [] : {}; | |
var newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey; | |
for (var m in res) { | |
if (Object.prototype.hasOwnProperty.call(res, m)) { | |
var deepKey = "".concat(newKeyToUse).concat(keySeparator).concat(m); | |
copy2[m] = this.translate(deepKey, _objectSpread$4(_objectSpread$4({}, options), { | |
joinArrays: false, | |
ns: namespaces | |
})); | |
if (copy2[m] === deepKey) | |
copy2[m] = res[m]; | |
} | |
} | |
res = copy2; | |
} | |
} else if (handleAsObjectInI18nFormat && typeof joinArrays === "string" && resType === "[object Array]") { | |
res = res.join(joinArrays); | |
if (res) | |
res = this.extendTranslation(res, keys, options, lastKey); | |
} else { | |
var usedDefault = false; | |
var usedKey = false; | |
var needsPluralHandling = options.count !== void 0 && typeof options.count !== "string"; | |
var hasDefaultValue = Translator2.hasDefaultValue(options); | |
var defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, options) : ""; | |
var defaultValue = options["defaultValue".concat(defaultValueSuffix)] || options.defaultValue; | |
if (!this.isValidLookup(res) && hasDefaultValue) { | |
usedDefault = true; | |
res = defaultValue; | |
} | |
if (!this.isValidLookup(res)) { | |
usedKey = true; | |
res = key; | |
} | |
var missingKeyNoValueFallbackToKey = options.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey; | |
var resForMissing = missingKeyNoValueFallbackToKey && usedKey ? void 0 : res; | |
var updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing; | |
if (usedKey || usedDefault || updateMissing) { | |
this.logger.log(updateMissing ? "updateKey" : "missingKey", lng, namespace, key, updateMissing ? defaultValue : res); | |
if (keySeparator) { | |
var fk = this.resolve(key, _objectSpread$4(_objectSpread$4({}, options), {}, { | |
keySeparator: false | |
})); | |
if (fk && fk.res) | |
this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format."); | |
} | |
var lngs = []; | |
var fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language); | |
if (this.options.saveMissingTo === "fallback" && fallbackLngs && fallbackLngs[0]) { | |
for (var i = 0; i < fallbackLngs.length; i++) { | |
lngs.push(fallbackLngs[i]); | |
} | |
} else if (this.options.saveMissingTo === "all") { | |
lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language); | |
} else { | |
lngs.push(options.lng || this.language); | |
} | |
var send = function send2(l, k, specificDefaultValue) { | |
var defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing; | |
if (_this2.options.missingKeyHandler) { | |
_this2.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, options); | |
} else if (_this2.backendConnector && _this2.backendConnector.saveMissing) { | |
_this2.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, options); | |
} | |
_this2.emit("missingKey", l, namespace, k, res); | |
}; | |
if (this.options.saveMissing) { | |
if (this.options.saveMissingPlurals && needsPluralHandling) { | |
lngs.forEach(function(language) { | |
_this2.pluralResolver.getSuffixes(language, options).forEach(function(suffix) { | |
send([language], key + suffix, options["defaultValue".concat(suffix)] || defaultValue); | |
}); | |
}); | |
} else { | |
send(lngs, key, defaultValue); | |
} | |
} | |
} | |
res = this.extendTranslation(res, keys, options, resolved, lastKey); | |
if (usedKey && res === key && this.options.appendNamespaceToMissingKey) | |
res = "".concat(namespace, ":").concat(key); | |
if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) { | |
if (this.options.compatibilityAPI !== "v1") { | |
res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? "".concat(namespace, ":").concat(key) : key, usedDefault ? res : void 0); | |
} else { | |
res = this.options.parseMissingKeyHandler(res); | |
} | |
} | |
} | |
if (returnDetails) { | |
resolved.res = res; | |
return resolved; | |
} | |
return res; | |
} | |
}, { | |
key: "extendTranslation", | |
value: function extendTranslation(res, key, options, resolved, lastKey) { | |
var _this3 = this; | |
if (this.i18nFormat && this.i18nFormat.parse) { | |
res = this.i18nFormat.parse(res, _objectSpread$4(_objectSpread$4({}, this.options.interpolation.defaultVariables), options), resolved.usedLng, resolved.usedNS, resolved.usedKey, { | |
resolved | |
}); | |
} else if (!options.skipInterpolation) { | |
if (options.interpolation) | |
this.interpolator.init(_objectSpread$4(_objectSpread$4({}, options), { | |
interpolation: _objectSpread$4(_objectSpread$4({}, this.options.interpolation), options.interpolation) | |
})); | |
var skipOnVariables = typeof res === "string" && (options && options.interpolation && options.interpolation.skipOnVariables !== void 0 ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables); | |
var nestBef; | |
if (skipOnVariables) { | |
var nb = res.match(this.interpolator.nestingRegexp); | |
nestBef = nb && nb.length; | |
} | |
var data = options.replace && typeof options.replace !== "string" ? options.replace : options; | |
if (this.options.interpolation.defaultVariables) | |
data = _objectSpread$4(_objectSpread$4({}, this.options.interpolation.defaultVariables), data); | |
res = this.interpolator.interpolate(res, data, options.lng || this.language, options); | |
if (skipOnVariables) { | |
var na = res.match(this.interpolator.nestingRegexp); | |
var nestAft = na && na.length; | |
if (nestBef < nestAft) | |
options.nest = false; | |
} | |
if (options.nest !== false) | |
res = this.interpolator.nest(res, function() { | |
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | |
args[_key] = arguments[_key]; | |
} | |
if (lastKey && lastKey[0] === args[0] && !options.context) { | |
_this3.logger.warn("It seems you are nesting recursively key: ".concat(args[0], " in key: ").concat(key[0])); | |
return null; | |
} | |
return _this3.translate.apply(_this3, args.concat([key])); | |
}, options); | |
if (options.interpolation) | |
this.interpolator.reset(); | |
} | |
var postProcess = options.postProcess || this.options.postProcess; | |
var postProcessorNames = typeof postProcess === "string" ? [postProcess] : postProcess; | |
if (res !== void 0 && res !== null && postProcessorNames && postProcessorNames.length && options.applyPostProcessor !== false) { | |
res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? _objectSpread$4({ | |
i18nResolved: resolved | |
}, options) : options, this); | |
} | |
return res; | |
} | |
}, { | |
key: "resolve", | |
value: function resolve(keys) { | |
var _this4 = this; | |
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; | |
var found; | |
var usedKey; | |
var exactUsedKey; | |
var usedLng; | |
var usedNS; | |
if (typeof keys === "string") | |
keys = [keys]; | |
keys.forEach(function(k) { | |
if (_this4.isValidLookup(found)) | |
return; | |
var extracted = _this4.extractFromKey(k, options); | |
var key = extracted.key; | |
usedKey = key; | |
var namespaces = extracted.namespaces; | |
if (_this4.options.fallbackNS) | |
namespaces = namespaces.concat(_this4.options.fallbackNS); | |
var needsPluralHandling = options.count !== void 0 && typeof options.count !== "string"; | |
var needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0 && _this4.pluralResolver.shouldUseIntlApi(); | |
var needsContextHandling = options.context !== void 0 && (typeof options.context === "string" || typeof options.context === "number") && options.context !== ""; | |
var codes = options.lngs ? options.lngs : _this4.languageUtils.toResolveHierarchy(options.lng || _this4.language, options.fallbackLng); | |
namespaces.forEach(function(ns) { | |
if (_this4.isValidLookup(found)) | |
return; | |
usedNS = ns; | |
if (!checkedLoadedFor["".concat(codes[0], "-").concat(ns)] && _this4.utils && _this4.utils.hasLoadedNamespace && !_this4.utils.hasLoadedNamespace(usedNS)) { | |
checkedLoadedFor["".concat(codes[0], "-").concat(ns)] = true; | |
_this4.logger.warn('key "'.concat(usedKey, '" for languages "').concat(codes.join(", "), `" won't get resolved as namespace "`).concat(usedNS, '" was not yet loaded'), "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!"); | |
} | |
codes.forEach(function(code) { | |
if (_this4.isValidLookup(found)) | |
return; | |
usedLng = code; | |
var finalKeys = [key]; | |
if (_this4.i18nFormat && _this4.i18nFormat.addLookupKeys) { | |
_this4.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options); | |
} else { | |
var pluralSuffix; | |
if (needsPluralHandling) | |
pluralSuffix = _this4.pluralResolver.getSuffix(code, options.count, options); | |
var zeroSuffix = "".concat(_this4.options.pluralSeparator, "zero"); | |
if (needsPluralHandling) { | |
finalKeys.push(key + pluralSuffix); | |
if (needsZeroSuffixLookup) { | |
finalKeys.push(key + zeroSuffix); | |
} | |
} | |
if (needsContextHandling) { | |
var contextKey = "".concat(key).concat(_this4.options.contextSeparator).concat(options.context); | |
finalKeys.push(contextKey); | |
if (needsPluralHandling) { | |
finalKeys.push(contextKey + pluralSuffix); | |
if (needsZeroSuffixLookup) { | |
finalKeys.push(contextKey + zeroSuffix); | |
} | |
} | |
} | |
} | |
var possibleKey; | |
while (possibleKey = finalKeys.pop()) { | |
if (!_this4.isValidLookup(found)) { | |
exactUsedKey = possibleKey; | |
found = _this4.getResource(code, ns, possibleKey, options); | |
} | |
} | |
}); | |
}); | |
}); | |
return { | |
res: found, | |
usedKey, | |
exactUsedKey, | |
usedLng, | |
usedNS | |
}; | |
} | |
}, { | |
key: "isValidLookup", | |
value: function isValidLookup(res) { | |
return res !== void 0 && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === ""); | |
} | |
}, { | |
key: "getResource", | |
value: function getResource(code, ns, key) { | |
var options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {}; | |
if (this.i18nFormat && this.i18nFormat.getResource) | |
return this.i18nFormat.getResource(code, ns, key, options); | |
return this.resourceStore.getResource(code, ns, key, options); | |
} | |
}], [{ | |
key: "hasDefaultValue", | |
value: function hasDefaultValue(options) { | |
var prefix = "defaultValue"; | |
for (var option in options) { | |
if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && void 0 !== options[option]) { | |
return true; | |
} | |
} | |
return false; | |
} | |
}]); | |
return Translator2; | |
}(EventEmitter); | |
function capitalize(string) { | |
return string.charAt(0).toUpperCase() + string.slice(1); | |
} | |
var LanguageUtil = function() { | |
function LanguageUtil2(options) { | |
_classCallCheck(this, LanguageUtil2); | |
this.options = options; | |
this.supportedLngs = this.options.supportedLngs || false; | |
this.logger = baseLogger.create("languageUtils"); | |
} | |
_createClass(LanguageUtil2, [{ | |
key: "getScriptPartFromCode", | |
value: function getScriptPartFromCode(code) { | |
if (!code || code.indexOf("-") < 0) | |
return null; | |
var p = code.split("-"); | |
if (p.length === 2) | |
return null; | |
p.pop(); | |
if (p[p.length - 1].toLowerCase() === "x") | |
return null; | |
return this.formatLanguageCode(p.join("-")); | |
} | |
}, { | |
key: "getLanguagePartFromCode", | |
value: function getLanguagePartFromCode(code) { | |
if (!code || code.indexOf("-") < 0) | |
return code; | |
var p = code.split("-"); | |
return this.formatLanguageCode(p[0]); | |
} | |
}, { | |
key: "formatLanguageCode", | |
value: function formatLanguageCode(code) { | |
if (typeof code === "string" && code.indexOf("-") > -1) { | |
var specialCases = ["hans", "hant", "latn", "cyrl", "cans", "mong", "arab"]; | |
var p = code.split("-"); | |
if (this.options.lowerCaseLng) { | |
p = p.map(function(part) { | |
return part.toLowerCase(); | |
}); | |
} else if (p.length === 2) { | |
p[0] = p[0].toLowerCase(); | |
p[1] = p[1].toUpperCase(); | |
if (specialCases.indexOf(p[1].toLowerCase()) > -1) | |
p[1] = capitalize(p[1].toLowerCase()); | |
} else if (p.length === 3) { | |
p[0] = p[0].toLowerCase(); | |
if (p[1].length === 2) | |
p[1] = p[1].toUpperCase(); | |
if (p[0] !== "sgn" && p[2].length === 2) | |
p[2] = p[2].toUpperCase(); | |
if (specialCases.indexOf(p[1].toLowerCase()) > -1) | |
p[1] = capitalize(p[1].toLowerCase()); | |
if (specialCases.indexOf(p[2].toLowerCase()) > -1) | |
p[2] = capitalize(p[2].toLowerCase()); | |
} | |
return p.join("-"); | |
} | |
return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code; | |
} | |
}, { | |
key: "isSupportedCode", | |
value: function isSupportedCode(code) { | |
if (this.options.load === "languageOnly" || this.options.nonExplicitSupportedLngs) { | |
code = this.getLanguagePartFromCode(code); | |
} | |
return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1; | |
} | |
}, { | |
key: "getBestMatchFromCodes", | |
value: function getBestMatchFromCodes(codes) { | |
var _this = this; | |
if (!codes) | |
return null; | |
var found; | |
codes.forEach(function(code) { | |
if (found) | |
return; | |
var cleanedLng = _this.formatLanguageCode(code); | |
if (!_this.options.supportedLngs || _this.isSupportedCode(cleanedLng)) | |
found = cleanedLng; | |
}); | |
if (!found && this.options.supportedLngs) { | |
codes.forEach(function(code) { | |
if (found) | |
return; | |
var lngOnly = _this.getLanguagePartFromCode(code); | |
if (_this.isSupportedCode(lngOnly)) | |
return found = lngOnly; | |
found = _this.options.supportedLngs.find(function(supportedLng) { | |
if (supportedLng.indexOf(lngOnly) === 0) | |
return supportedLng; | |
}); | |
}); | |
} | |
if (!found) | |
found = this.getFallbackCodes(this.options.fallbackLng)[0]; | |
return found; | |
} | |
}, { | |
key: "getFallbackCodes", | |
value: function getFallbackCodes(fallbacks, code) { | |
if (!fallbacks) | |
return []; | |
if (typeof fallbacks === "function") | |
fallbacks = fallbacks(code); | |
if (typeof fallbacks === "string") | |
fallbacks = [fallbacks]; | |
if (Object.prototype.toString.apply(fallbacks) === "[object Array]") | |
return fallbacks; | |
if (!code) | |
return fallbacks["default"] || []; | |
var found = fallbacks[code]; | |
if (!found) | |
found = fallbacks[this.getScriptPartFromCode(code)]; | |
if (!found) | |
found = fallbacks[this.formatLanguageCode(code)]; | |
if (!found) | |
found = fallbacks[this.getLanguagePartFromCode(code)]; | |
if (!found) | |
found = fallbacks["default"]; | |
return found || []; | |
} | |
}, { | |
key: "toResolveHierarchy", | |
value: function toResolveHierarchy(code, fallbackCode) { | |
var _this2 = this; | |
var fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code); | |
var codes = []; | |
var addCode = function addCode2(c) { | |
if (!c) | |
return; | |
if (_this2.isSupportedCode(c)) { | |
codes.push(c); | |
} else { | |
_this2.logger.warn("rejecting language code not found in supportedLngs: ".concat(c)); | |
} | |
}; | |
if (typeof code === "string" && code.indexOf("-") > -1) { | |
if (this.options.load !== "languageOnly") | |
addCode(this.formatLanguageCode(code)); | |
if (this.options.load !== "languageOnly" && this.options.load !== "currentOnly") | |
addCode(this.getScriptPartFromCode(code)); | |
if (this.options.load !== "currentOnly") | |
addCode(this.getLanguagePartFromCode(code)); | |
} else if (typeof code === "string") { | |
addCode(this.formatLanguageCode(code)); | |
} | |
fallbackCodes.forEach(function(fc) { | |
if (codes.indexOf(fc) < 0) | |
addCode(_this2.formatLanguageCode(fc)); | |
}); | |
return codes; | |
} | |
}]); | |
return LanguageUtil2; | |
}(); | |
var sets = [{ | |
lngs: ["ach", "ak", "am", "arn", "br", "fil", "gun", "ln", "mfe", "mg", "mi", "oc", "pt", "pt-BR", "tg", "tl", "ti", "tr", "uz", "wa"], | |
nr: [1, 2], | |
fc: 1 | |
}, { | |
lngs: ["af", "an", "ast", "az", "bg", "bn", "ca", "da", "de", "dev", "el", "en", "eo", "es", "et", "eu", "fi", "fo", "fur", "fy", "gl", "gu", "ha", "hi", "hu", "hy", "ia", "it", "kk", "kn", "ku", "lb", "mai", "ml", "mn", "mr", "nah", "nap", "nb", "ne", "nl", "nn", "no", "nso", "pa", "pap", "pms", "ps", "pt-PT", "rm", "sco", "se", "si", "so", "son", "sq", "sv", "sw", "ta", "te", "tk", "ur", "yo"], | |
nr: [1, 2], | |
fc: 2 | |
}, { | |
lngs: ["ay", "bo", "cgg", "fa", "ht", "id", "ja", "jbo", "ka", "km", "ko", "ky", "lo", "ms", "sah", "su", "th", "tt", "ug", "vi", "wo", "zh"], | |
nr: [1], | |
fc: 3 | |
}, { | |
lngs: ["be", "bs", "cnr", "dz", "hr", "ru", "sr", "uk"], | |
nr: [1, 2, 5], | |
fc: 4 | |
}, { | |
lngs: ["ar"], | |
nr: [0, 1, 2, 3, 11, 100], | |
fc: 5 | |
}, { | |
lngs: ["cs", "sk"], | |
nr: [1, 2, 5], | |
fc: 6 | |
}, { | |
lngs: ["csb", "pl"], | |
nr: [1, 2, 5], | |
fc: 7 | |
}, { | |
lngs: ["cy"], | |
nr: [1, 2, 3, 8], | |
fc: 8 | |
}, { | |
lngs: ["fr"], | |
nr: [1, 2], | |
fc: 9 | |
}, { | |
lngs: ["ga"], | |
nr: [1, 2, 3, 7, 11], | |
fc: 10 | |
}, { | |
lngs: ["gd"], | |
nr: [1, 2, 3, 20], | |
fc: 11 | |
}, { | |
lngs: ["is"], | |
nr: [1, 2], | |
fc: 12 | |
}, { | |
lngs: ["jv"], | |
nr: [0, 1], | |
fc: 13 | |
}, { | |
lngs: ["kw"], | |
nr: [1, 2, 3, 4], | |
fc: 14 | |
}, { | |
lngs: ["lt"], | |
nr: [1, 2, 10], | |
fc: 15 | |
}, { | |
lngs: ["lv"], | |
nr: [1, 2, 0], | |
fc: 16 | |
}, { | |
lngs: ["mk"], | |
nr: [1, 2], | |
fc: 17 | |
}, { | |
lngs: ["mnk"], | |
nr: [0, 1, 2], | |
fc: 18 | |
}, { | |
lngs: ["mt"], | |
nr: [1, 2, 11, 20], | |
fc: 19 | |
}, { | |
lngs: ["or"], | |
nr: [2, 1], | |
fc: 2 | |
}, { | |
lngs: ["ro"], | |
nr: [1, 2, 20], | |
fc: 20 | |
}, { | |
lngs: ["sl"], | |
nr: [5, 1, 2, 3], | |
fc: 21 | |
}, { | |
lngs: ["he", "iw"], | |
nr: [1, 2, 20, 21], | |
fc: 22 | |
}]; | |
var _rulesPluralsTypes = { | |
1: function _(n) { | |
return Number(n > 1); | |
}, | |
2: function _2(n) { | |
return Number(n != 1); | |
}, | |
3: function _3(n) { | |
return 0; | |
}, | |
4: function _4(n) { | |
return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2); | |
}, | |
5: function _5(n) { | |
return Number(n == 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5); | |
}, | |
6: function _6(n) { | |
return Number(n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2); | |
}, | |
7: function _7(n) { | |
return Number(n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2); | |
}, | |
8: function _8(n) { | |
return Number(n == 1 ? 0 : n == 2 ? 1 : n != 8 && n != 11 ? 2 : 3); | |
}, | |
9: function _9(n) { | |
return Number(n >= 2); | |
}, | |
10: function _10(n) { | |
return Number(n == 1 ? 0 : n == 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4); | |
}, | |
11: function _11(n) { | |
return Number(n == 1 || n == 11 ? 0 : n == 2 || n == 12 ? 1 : n > 2 && n < 20 ? 2 : 3); | |
}, | |
12: function _12(n) { | |
return Number(n % 10 != 1 || n % 100 == 11); | |
}, | |
13: function _13(n) { | |
return Number(n !== 0); | |
}, | |
14: function _14(n) { | |
return Number(n == 1 ? 0 : n == 2 ? 1 : n == 3 ? 2 : 3); | |
}, | |
15: function _15(n) { | |
return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2); | |
}, | |
16: function _16(n) { | |
return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n !== 0 ? 1 : 2); | |
}, | |
17: function _17(n) { | |
return Number(n == 1 || n % 10 == 1 && n % 100 != 11 ? 0 : 1); | |
}, | |
18: function _18(n) { | |
return Number(n == 0 ? 0 : n == 1 ? 1 : 2); | |
}, | |
19: function _19(n) { | |
return Number(n == 1 ? 0 : n == 0 || n % 100 > 1 && n % 100 < 11 ? 1 : n % 100 > 10 && n % 100 < 20 ? 2 : 3); | |
}, | |
20: function _20(n) { | |
return Number(n == 1 ? 0 : n == 0 || n % 100 > 0 && n % 100 < 20 ? 1 : 2); | |
}, | |
21: function _21(n) { | |
return Number(n % 100 == 1 ? 1 : n % 100 == 2 ? 2 : n % 100 == 3 || n % 100 == 4 ? 3 : 0); | |
}, | |
22: function _22(n) { | |
return Number(n == 1 ? 0 : n == 2 ? 1 : (n < 0 || n > 10) && n % 10 == 0 ? 2 : 3); | |
} | |
}; | |
var deprecatedJsonVersions = ["v1", "v2", "v3"]; | |
var suffixesOrder = { | |
zero: 0, | |
one: 1, | |
two: 2, | |
few: 3, | |
many: 4, | |
other: 5 | |
}; | |
function createRules() { | |
var rules = {}; | |
sets.forEach(function(set) { | |
set.lngs.forEach(function(l) { | |
rules[l] = { | |
numbers: set.nr, | |
plurals: _rulesPluralsTypes[set.fc] | |
}; | |
}); | |
}); | |
return rules; | |
} | |
var PluralResolver = function() { | |
function PluralResolver2(languageUtils) { | |
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; | |
_classCallCheck(this, PluralResolver2); | |
this.languageUtils = languageUtils; | |
this.options = options; | |
this.logger = baseLogger.create("pluralResolver"); | |
if ((!this.options.compatibilityJSON || this.options.compatibilityJSON === "v4") && (typeof Intl === "undefined" || !Intl.PluralRules)) { | |
this.options.compatibilityJSON = "v3"; | |
this.logger.error("Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling."); | |
} | |
this.rules = createRules(); | |
} | |
_createClass(PluralResolver2, [{ | |
key: "addRule", | |
value: function addRule(lng, obj) { | |
this.rules[lng] = obj; | |
} | |
}, { | |
key: "getRule", | |
value: function getRule(code) { | |
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; | |
if (this.shouldUseIntlApi()) { | |
try { | |
return new Intl.PluralRules(code, { | |
type: options.ordinal ? "ordinal" : "cardinal" | |
}); | |
} catch (_unused) { | |
return; | |
} | |
} | |
return this.rules[code] || this.rules[this.languageUtils.getLanguagePartFromCode(code)]; | |
} | |
}, { | |
key: "needsPlural", | |
value: function needsPlural(code) { | |
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; | |
var rule = this.getRule(code, options); | |
if (this.shouldUseIntlApi()) { | |
return rule && rule.resolvedOptions().pluralCategories.length > 1; | |
} | |
return rule && rule.numbers.length > 1; | |
} | |
}, { | |
key: "getPluralFormsOfKey", | |
value: function getPluralFormsOfKey(code, key) { | |
var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}; | |
return this.getSuffixes(code, options).map(function(suffix) { | |
return "".concat(key).concat(suffix); | |
}); | |
} | |
}, { | |
key: "getSuffixes", | |
value: function getSuffixes(code) { | |
var _this = this; | |
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; | |
var rule = this.getRule(code, options); | |
if (!rule) { | |
return []; | |
} | |
if (this.shouldUseIntlApi()) { | |
return rule.resolvedOptions().pluralCategories.sort(function(pluralCategory1, pluralCategory2) { | |
return suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]; | |
}).map(function(pluralCategory) { | |
return "".concat(_this.options.prepend).concat(pluralCategory); | |
}); | |
} | |
return rule.numbers.map(function(number) { | |
return _this.getSuffix(code, number, options); | |
}); | |
} | |
}, { | |
key: "getSuffix", | |
value: function getSuffix(code, count) { | |
var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}; | |
var rule = this.getRule(code, options); | |
if (rule) { | |
if (this.shouldUseIntlApi()) { | |
return "".concat(this.options.prepend).concat(rule.select(count)); | |
} | |
return this.getSuffixRetroCompatible(rule, count); | |
} | |
this.logger.warn("no plural rule found for: ".concat(code)); | |
return ""; | |
} | |
}, { | |
key: "getSuffixRetroCompatible", | |
value: function getSuffixRetroCompatible(rule, count) { | |
var _this2 = this; | |
var idx = rule.noAbs ? rule.plurals(count) : rule.plurals(Math.abs(count)); | |
var suffix = rule.numbers[idx]; | |
if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) { | |
if (suffix === 2) { | |
suffix = "plural"; | |
} else if (suffix === 1) { | |
suffix = ""; | |
} | |
} | |
var returnSuffix = function returnSuffix2() { | |
return _this2.options.prepend && suffix.toString() ? _this2.options.prepend + suffix.toString() : suffix.toString(); | |
}; | |
if (this.options.compatibilityJSON === "v1") { | |
if (suffix === 1) | |
return ""; | |
if (typeof suffix === "number") | |
return "_plural_".concat(suffix.toString()); | |
return returnSuffix(); | |
} else if (this.options.compatibilityJSON === "v2") { | |
return returnSuffix(); | |
} else if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) { | |
return returnSuffix(); | |
} | |
return this.options.prepend && idx.toString() ? this.options.prepend + idx.toString() : idx.toString(); | |
} | |
}, { | |
key: "shouldUseIntlApi", | |
value: function shouldUseIntlApi() { | |
return !deprecatedJsonVersions.includes(this.options.compatibilityJSON); | |
} | |
}]); | |
return PluralResolver2; | |
}(); | |
function ownKeys$3(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$3(target) { | |
for (var i = 1; i < arguments.length; i++) { | |
var source = null != arguments[i] ? arguments[i] : {}; | |
i % 2 ? ownKeys$3(Object(source), true).forEach(function(key) { | |
_defineProperty(target, key, source[key]); | |
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$3(Object(source)).forEach(function(key) { | |
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); | |
}); | |
} | |
return target; | |
} | |
var Interpolator = function() { | |
function Interpolator2() { | |
var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; | |
_classCallCheck(this, Interpolator2); | |
this.logger = baseLogger.create("interpolator"); | |
this.options = options; | |
this.format = options.interpolation && options.interpolation.format || function(value) { | |
return value; | |
}; | |
this.init(options); | |
} | |
_createClass(Interpolator2, [{ | |
key: "init", | |
value: function init2() { | |
var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; | |
if (!options.interpolation) | |
options.interpolation = { | |
escapeValue: true | |
}; | |
var iOpts = options.interpolation; | |
this.escape = iOpts.escape !== void 0 ? iOpts.escape : escape; | |
this.escapeValue = iOpts.escapeValue !== void 0 ? iOpts.escapeValue : true; | |
this.useRawValueToEscape = iOpts.useRawValueToEscape !== void 0 ? iOpts.useRawValueToEscape : false; | |
this.prefix = iOpts.prefix ? regexEscape(iOpts.prefix) : iOpts.prefixEscaped || "{{"; | |
this.suffix = iOpts.suffix ? regexEscape(iOpts.suffix) : iOpts.suffixEscaped || "}}"; | |
this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ","; | |
this.unescapePrefix = iOpts.unescapeSuffix ? "" : iOpts.unescapePrefix || "-"; | |
this.unescapeSuffix = this.unescapePrefix ? "" : iOpts.unescapeSuffix || ""; | |
this.nestingPrefix = iOpts.nestingPrefix ? regexEscape(iOpts.nestingPrefix) : iOpts.nestingPrefixEscaped || regexEscape("$t("); | |
this.nestingSuffix = iOpts.nestingSuffix ? regexEscape(iOpts.nestingSuffix) : iOpts.nestingSuffixEscaped || regexEscape(")"); | |
this.nestingOptionsSeparator = iOpts.nestingOptionsSeparator ? iOpts.nestingOptionsSeparator : iOpts.nestingOptionsSeparator || ","; | |
this.maxReplaces = iOpts.maxReplaces ? iOpts.maxReplaces : 1e3; | |
this.alwaysFormat = iOpts.alwaysFormat !== void 0 ? iOpts.alwaysFormat : false; | |
this.resetRegExp(); | |
} | |
}, { | |
key: "reset", | |
value: function reset() { | |
if (this.options) | |
this.init(this.options); | |
} | |
}, { | |
key: "resetRegExp", | |
value: function resetRegExp() { | |
var regexpStr = "".concat(this.prefix, "(.+?)").concat(this.suffix); | |
this.regexp = new RegExp(regexpStr, "g"); | |
var regexpUnescapeStr = "".concat(this.prefix).concat(this.unescapePrefix, "(.+?)").concat(this.unescapeSuffix).concat(this.suffix); | |
this.regexpUnescape = new RegExp(regexpUnescapeStr, "g"); | |
var nestingRegexpStr = "".concat(this.nestingPrefix, "(.+?)").concat(this.nestingSuffix); | |
this.nestingRegexp = new RegExp(nestingRegexpStr, "g"); | |
} | |
}, { | |
key: "interpolate", | |
value: function interpolate(str, data, lng, options) { | |
var _this = this; | |
var match; | |
var value; | |
var replaces; | |
var defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {}; | |
function regexSafe(val) { | |
return val.replace(/\$/g, "$$$$"); | |
} | |
var handleFormat = function handleFormat2(key) { | |
if (key.indexOf(_this.formatSeparator) < 0) { | |
var path = getPathWithDefaults(data, defaultData, key); | |
return _this.alwaysFormat ? _this.format(path, void 0, lng, _objectSpread$3(_objectSpread$3(_objectSpread$3({}, options), data), {}, { | |
interpolationkey: key | |
})) : path; | |
} | |
var p = key.split(_this.formatSeparator); | |
var k = p.shift().trim(); | |
var f = p.join(_this.formatSeparator).trim(); | |
return _this.format(getPathWithDefaults(data, defaultData, k), f, lng, _objectSpread$3(_objectSpread$3(_objectSpread$3({}, options), data), {}, { | |
interpolationkey: k | |
})); | |
}; | |
this.resetRegExp(); | |
var missingInterpolationHandler = options && options.missingInterpolationHandler || this.options.missingInterpolationHandler; | |
var skipOnVariables = options && options.interpolation && options.interpolation.skipOnVariables !== void 0 ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables; | |
var todos = [{ | |
regex: this.regexpUnescape, | |
safeValue: function safeValue(val) { | |
return regexSafe(val); | |
} | |
}, { | |
regex: this.regexp, | |
safeValue: function safeValue(val) { | |
return _this.escapeValue ? regexSafe(_this.escape(val)) : regexSafe(val); | |
} | |
}]; | |
todos.forEach(function(todo) { | |
replaces = 0; | |
while (match = todo.regex.exec(str)) { | |
var matchedVar = match[1].trim(); | |
value = handleFormat(matchedVar); | |
if (value === void 0) { | |
if (typeof missingInterpolationHandler === "function") { | |
var temp = missingInterpolationHandler(str, match, options); | |
value = typeof temp === "string" ? temp : ""; | |
} else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) { | |
value = ""; | |
} else if (skipOnVariables) { | |
value = match[0]; | |
continue; | |
} else { | |
_this.logger.warn("missed to pass in variable ".concat(matchedVar, " for interpolating ").concat(str)); | |
value = ""; | |
} | |
} else if (typeof value !== "string" && !_this.useRawValueToEscape) { | |
value = makeString(value); | |
} | |
var safeValue = todo.safeValue(value); | |
str = str.replace(match[0], safeValue); | |
if (skipOnVariables) { | |
todo.regex.lastIndex += value.length; | |
todo.regex.lastIndex -= match[0].length; | |
} else { | |
todo.regex.lastIndex = 0; | |
} | |
replaces++; | |
if (replaces >= _this.maxReplaces) { | |
break; | |
} | |
} | |
}); | |
return str; | |
} | |
}, { | |
key: "nest", | |
value: function nest(str, fc) { | |
var _this2 = this; | |
var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}; | |
var match; | |
var value; | |
var clonedOptions; | |
function handleHasOptions(key, inheritedOptions) { | |
var sep = this.nestingOptionsSeparator; | |
if (key.indexOf(sep) < 0) | |
return key; | |
var c = key.split(new RegExp("".concat(sep, "[ ]*{"))); | |
var optionsString = "{".concat(c[1]); | |
key = c[0]; | |
optionsString = this.interpolate(optionsString, clonedOptions); | |
var matchedSingleQuotes = optionsString.match(/'/g); | |
var matchedDoubleQuotes = optionsString.match(/"/g); | |
if (matchedSingleQuotes && matchedSingleQuotes.length % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) { | |
optionsString = optionsString.replace(/'/g, '"'); | |
} | |
try { | |
clonedOptions = JSON.parse(optionsString); | |
if (inheritedOptions) | |
clonedOptions = _objectSpread$3(_objectSpread$3({}, inheritedOptions), clonedOptions); | |
} catch (e) { | |
this.logger.warn("failed parsing options string in nesting for key ".concat(key), e); | |
return "".concat(key).concat(sep).concat(optionsString); | |
} | |
delete clonedOptions.defaultValue; | |
return key; | |
} | |
while (match = this.nestingRegexp.exec(str)) { | |
var formatters = []; | |
clonedOptions = _objectSpread$3({}, options); | |
clonedOptions = clonedOptions.replace && typeof clonedOptions.replace !== "string" ? clonedOptions.replace : clonedOptions; | |
clonedOptions.applyPostProcessor = false; | |
delete clonedOptions.defaultValue; | |
var doReduce = false; | |
if (match[0].indexOf(this.formatSeparator) !== -1 && !/{.*}/.test(match[1])) { | |
var r = match[1].split(this.formatSeparator).map(function(elem) { | |
return elem.trim(); | |
}); | |
match[1] = r.shift(); | |
formatters = r; | |
doReduce = true; | |
} | |
value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions); | |
if (value && match[0] === str && typeof value !== "string") | |
return value; | |
if (typeof value !== "string") | |
value = makeString(value); | |
if (!value) { | |
this.logger.warn("missed to resolve ".concat(match[1], " for nesting ").concat(str)); | |
value = ""; | |
} | |
if (doReduce) { | |
value = formatters.reduce(function(v, f) { | |
return _this2.format(v, f, options.lng, _objectSpread$3(_objectSpread$3({}, options), {}, { | |
interpolationkey: match[1].trim() | |
})); | |
}, value.trim()); | |
} | |
str = str.replace(match[0], value); | |
this.regexp.lastIndex = 0; | |
} | |
return str; | |
} | |
}]); | |
return Interpolator2; | |
}(); | |
function ownKeys$2(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$2(target) { | |
for (var i = 1; i < arguments.length; i++) { | |
var source = null != arguments[i] ? arguments[i] : {}; | |
i % 2 ? ownKeys$2(Object(source), true).forEach(function(key) { | |
_defineProperty(target, key, source[key]); | |
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$2(Object(source)).forEach(function(key) { | |
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); | |
}); | |
} | |
return target; | |
} | |
function parseFormatStr(formatStr) { | |
var formatName = formatStr.toLowerCase().trim(); | |
var formatOptions = {}; | |
if (formatStr.indexOf("(") > -1) { | |
var p = formatStr.split("("); | |
formatName = p[0].toLowerCase().trim(); | |
var optStr = p[1].substring(0, p[1].length - 1); | |
if (formatName === "currency" && optStr.indexOf(":") < 0) { | |
if (!formatOptions.currency) | |
formatOptions.currency = optStr.trim(); | |
} else if (formatName === "relativetime" && optStr.indexOf(":") < 0) { | |
if (!formatOptions.range) | |
formatOptions.range = optStr.trim(); | |
} else { | |
var opts = optStr.split(";"); | |
opts.forEach(function(opt) { | |
if (!opt) | |
return; | |
var _opt$split = opt.split(":"), _opt$split2 = _toArray(_opt$split), key = _opt$split2[0], rest = _opt$split2.slice(1); | |
var val = rest.join(":").trim().replace(/^'+|'+$/g, ""); | |
if (!formatOptions[key.trim()]) | |
formatOptions[key.trim()] = val; | |
if (val === "false") | |
formatOptions[key.trim()] = false; | |
if (val === "true") | |
formatOptions[key.trim()] = true; | |
if (!isNaN(val)) | |
formatOptions[key.trim()] = parseInt(val, 10); | |
}); | |
} | |
} | |
return { | |
formatName, | |
formatOptions | |
}; | |
} | |
function createCachedFormatter(fn) { | |
var cache = {}; | |
return function invokeFormatter(val, lng, options) { | |
var key = lng + JSON.stringify(options); | |
var formatter = cache[key]; | |
if (!formatter) { | |
formatter = fn(lng, options); | |
cache[key] = formatter; | |
} | |
return formatter(val); | |
}; | |
} | |
var Formatter = function() { | |
function Formatter2() { | |
var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; | |
_classCallCheck(this, Formatter2); | |
this.logger = baseLogger.create("formatter"); | |
this.options = options; | |
this.formats = { | |
number: createCachedFormatter(function(lng, opt) { | |
var formatter = new Intl.NumberFormat(lng, _objectSpread$2({}, opt)); | |
return function(val) { | |
return formatter.format(val); | |
}; | |
}), | |
currency: createCachedFormatter(function(lng, opt) { | |
var formatter = new Intl.NumberFormat(lng, _objectSpread$2(_objectSpread$2({}, opt), {}, { | |
style: "currency" | |
})); | |
return function(val) { | |
return formatter.format(val); | |
}; | |
}), | |
datetime: createCachedFormatter(function(lng, opt) { | |
var formatter = new Intl.DateTimeFormat(lng, _objectSpread$2({}, opt)); | |
return function(val) { | |
return formatter.format(val); | |
}; | |
}), | |
relativetime: createCachedFormatter(function(lng, opt) { | |
var formatter = new Intl.RelativeTimeFormat(lng, _objectSpread$2({}, opt)); | |
return function(val) { | |
return formatter.format(val, opt.range || "day"); | |
}; | |
}), | |
list: createCachedFormatter(function(lng, opt) { | |
var formatter = new Intl.ListFormat(lng, _objectSpread$2({}, opt)); | |
return function(val) { | |
return formatter.format(val); | |
}; | |
}) | |
}; | |
this.init(options); | |
} | |
_createClass(Formatter2, [{ | |
key: "init", | |
value: function init2(services) { | |
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : { | |
interpolation: {} | |
}; | |
var iOpts = options.interpolation; | |
this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ","; | |
} | |
}, { | |
key: "add", | |
value: function add(name, fc) { | |
this.formats[name.toLowerCase().trim()] = fc; | |
} | |
}, { | |
key: "addCached", | |
value: function addCached(name, fc) { | |
this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc); | |
} | |
}, { | |
key: "format", | |
value: function format(value, _format, lng) { | |
var _this = this; | |
var options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {}; | |
var formats = _format.split(this.formatSeparator); | |
var result = formats.reduce(function(mem, f) { | |
var _parseFormatStr = parseFormatStr(f), formatName = _parseFormatStr.formatName, formatOptions = _parseFormatStr.formatOptions; | |
if (_this.formats[formatName]) { | |
var formatted = mem; | |
try { | |
var valOptions = options && options.formatParams && options.formatParams[options.interpolationkey] || {}; | |
var l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng; | |
formatted = _this.formats[formatName](mem, l, _objectSpread$2(_objectSpread$2(_objectSpread$2({}, formatOptions), options), valOptions)); | |
} catch (error4) { | |
_this.logger.warn(error4); | |
} | |
return formatted; | |
} else { | |
_this.logger.warn("there was no format function for ".concat(formatName)); | |
} | |
return mem; | |
}, value); | |
return result; | |
} | |
}]); | |
return Formatter2; | |
}(); | |
function ownKeys$1(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$1(target) { | |
for (var i = 1; i < arguments.length; i++) { | |
var source = null != arguments[i] ? arguments[i] : {}; | |
i % 2 ? ownKeys$1(Object(source), true).forEach(function(key) { | |
_defineProperty(target, key, source[key]); | |
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1(Object(source)).forEach(function(key) { | |
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); | |
}); | |
} | |
return target; | |
} | |
function _createSuper$1(Derived) { | |
var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); | |
return function _createSuperInternal() { | |
var Super = _getPrototypeOf(Derived), result; | |
if (hasNativeReflectConstruct) { | |
var NewTarget = _getPrototypeOf(this).constructor; | |
result = Reflect.construct(Super, arguments, NewTarget); | |
} else { | |
result = Super.apply(this, arguments); | |
} | |
return _possibleConstructorReturn(this, result); | |
}; | |
} | |
function _isNativeReflectConstruct$1() { | |
if (typeof Reflect === "undefined" || !Reflect.construct) | |
return false; | |
if (Reflect.construct.sham) | |
return false; | |
if (typeof Proxy === "function") | |
return true; | |
try { | |
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() { | |
})); | |
return true; | |
} catch (e) { | |
return false; | |
} | |
} | |
function removePending(q, name) { | |
if (q.pending[name] !== void 0) { | |
delete q.pending[name]; | |
q.pendingCount--; | |
} | |
} | |
var Connector = function(_EventEmitter) { | |
_inherits(Connector2, _EventEmitter); | |
var _super = _createSuper$1(Connector2); | |
function Connector2(backend, store, services) { | |
var _this; | |
var options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {}; | |
_classCallCheck(this, Connector2); | |
_this = _super.call(this); | |
if (isIE10) { | |
EventEmitter.call(_assertThisInitialized(_this)); | |
} | |
_this.backend = backend; | |
_this.store = store; | |
_this.services = services; | |
_this.languageUtils = services.languageUtils; | |
_this.options = options; | |
_this.logger = baseLogger.create("backendConnector"); | |
_this.waitingReads = []; | |
_this.maxParallelReads = options.maxParallelReads || 10; | |
_this.readingCalls = 0; | |
_this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5; | |
_this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350; | |
_this.state = {}; | |
_this.queue = []; | |
if (_this.backend && _this.backend.init) { | |
_this.backend.init(services, options.backend, options); | |
} | |
return _this; | |
} | |
_createClass(Connector2, [{ | |
key: "queueLoad", | |
value: function queueLoad(languages, namespaces, options, callback) { | |
var _this2 = this; | |
var toLoad = {}; | |
var pending = {}; | |
var toLoadLanguages = {}; | |
var toLoadNamespaces = {}; | |
languages.forEach(function(lng) { | |
var hasAllNamespaces = true; | |
namespaces.forEach(function(ns) { | |
var name = "".concat(lng, "|").concat(ns); | |
if (!options.reload && _this2.store.hasResourceBundle(lng, ns)) { | |
_this2.state[name] = 2; | |
} else if (_this2.state[name] < 0) | |
; | |
else if (_this2.state[name] === 1) { | |
if (pending[name] === void 0) | |
pending[name] = true; | |
} else { | |
_this2.state[name] = 1; | |
hasAllNamespaces = false; | |
if (pending[name] === void 0) | |
pending[name] = true; | |
if (toLoad[name] === void 0) | |
toLoad[name] = true; | |
if (toLoadNamespaces[ns] === void 0) | |
toLoadNamespaces[ns] = true; | |
} | |
}); | |
if (!hasAllNamespaces) | |
toLoadLanguages[lng] = true; | |
}); | |
if (Object.keys(toLoad).length || Object.keys(pending).length) { | |
this.queue.push({ | |
pending, | |
pendingCount: Object.keys(pending).length, | |
loaded: {}, | |
errors: [], | |
callback | |
}); | |
} | |
return { | |
toLoad: Object.keys(toLoad), | |
pending: Object.keys(pending), | |
toLoadLanguages: Object.keys(toLoadLanguages), | |
toLoadNamespaces: Object.keys(toLoadNamespaces) | |
}; | |
} | |
}, { | |
key: "loaded", | |
value: function loaded(name, err, data) { | |
var s = name.split("|"); | |
var lng = s[0]; | |
var ns = s[1]; | |
if (err) | |
this.emit("failedLoading", lng, ns, err); | |
if (data) { | |
this.store.addResourceBundle(lng, ns, data); | |
} | |
this.state[name] = err ? -1 : 2; | |
var loaded2 = {}; | |
this.queue.forEach(function(q) { | |
pushPath(q.loaded, [lng], ns); | |
removePending(q, name); | |
if (err) | |
q.errors.push(err); | |
if (q.pendingCount === 0 && !q.done) { | |
Object.keys(q.loaded).forEach(function(l) { | |
if (!loaded2[l]) | |
loaded2[l] = {}; | |
var loadedKeys = q.loaded[l]; | |
if (loadedKeys.length) { | |
loadedKeys.forEach(function(n) { | |
if (loaded2[l][n] === void 0) | |
loaded2[l][n] = true; | |
}); | |
} | |
}); | |
q.done = true; | |
if (q.errors.length) { | |
q.callback(q.errors); | |
} else { | |
q.callback(); | |
} | |
} | |
}); | |
this.emit("loaded", loaded2); | |
this.queue = this.queue.filter(function(q) { | |
return !q.done; | |
}); | |
} | |
}, { | |
key: "read", | |
value: function read(lng, ns, fcName) { | |
var _this3 = this; | |
var tried = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 0; | |
var wait = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : this.retryTimeout; | |
var callback = arguments.length > 5 ? arguments[5] : void 0; | |
if (!lng.length) | |
return callback(null, {}); | |
if (this.readingCalls >= this.maxParallelReads) { | |
this.waitingReads.push({ | |
lng, | |
ns, | |
fcName, | |
tried, | |
wait, | |
callback | |
}); | |
return; | |
} | |
this.readingCalls++; | |
var resolver = function resolver2(err, data) { | |
_this3.readingCalls--; | |
if (_this3.waitingReads.length > 0) { | |
var next = _this3.waitingReads.shift(); | |
_this3.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback); | |
} | |
if (err && data && tried < _this3.maxRetries) { | |
setTimeout(function() { | |
_this3.read.call(_this3, lng, ns, fcName, tried + 1, wait * 2, callback); | |
}, wait); | |
return; | |
} | |
callback(err, data); | |
}; | |
var fc = this.backend[fcName].bind(this.backend); | |
if (fc.length === 2) { | |
try { | |
var r = fc(lng, ns); | |
if (r && typeof r.then === "function") { | |
r.then(function(data) { | |
return resolver(null, data); | |
})["catch"](resolver); | |
} else { | |
resolver(null, r); | |
} | |
} catch (err) { | |
resolver(err); | |
} | |
return; | |
} | |
return fc(lng, ns, resolver); | |
} | |
}, { | |
key: "prepareLoading", | |
value: function prepareLoading(languages, namespaces) { | |
var _this4 = this; | |
var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}; | |
var callback = arguments.length > 3 ? arguments[3] : void 0; | |
if (!this.backend) { | |
this.logger.warn("No backend was added via i18next.use. Will not load resources."); | |
return callback && callback(); | |
} | |
if (typeof languages === "string") | |
languages = this.languageUtils.toResolveHierarchy(languages); | |
if (typeof namespaces === "string") | |
namespaces = [namespaces]; | |
var toLoad = this.queueLoad(languages, namespaces, options, callback); | |
if (!toLoad.toLoad.length) { | |
if (!toLoad.pending.length) | |
callback(); | |
return null; | |
} | |
toLoad.toLoad.forEach(function(name) { | |
_this4.loadOne(name); | |
}); | |
} | |
}, { | |
key: "load", | |
value: function load(languages, namespaces, callback) { | |
this.prepareLoading(languages, namespaces, {}, callback); | |
} | |
}, { | |
key: "reload", | |
value: function reload(languages, namespaces, callback) { | |
this.prepareLoading(languages, namespaces, { | |
reload: true | |
}, callback); | |
} | |
}, { | |
key: "loadOne", | |
value: function loadOne(name) { | |
var _this5 = this; | |
var prefix = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : ""; | |
var s = name.split("|"); | |
var lng = s[0]; | |
var ns = s[1]; | |
this.read(lng, ns, "read", void 0, void 0, function(err, data) { | |
if (err) | |
_this5.logger.warn("".concat(prefix, "loading namespace ").concat(ns, " for language ").concat(lng, " failed"), err); | |
if (!err && data) | |
_this5.logger.log("".concat(prefix, "loaded namespace ").concat(ns, " for language ").concat(lng), data); | |
_this5.loaded(name, err, data); | |
}); | |
} | |
}, { | |
key: "saveMissing", | |
value: function saveMissing(languages, namespace, key, fallbackValue, isUpdate) { | |
var options = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : {}; | |
var clb = arguments.length > 6 && arguments[6] !== void 0 ? arguments[6] : function() { | |
}; | |
if (this.services.utils && this.services.utils.hasLoadedNamespace && !this.services.utils.hasLoadedNamespace(namespace)) { | |
this.logger.warn('did not save key "'.concat(key, '" as the namespace "').concat(namespace, '" was not yet loaded'), "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!"); | |
return; | |
} | |
if (key === void 0 || key === null || key === "") | |
return; | |
if (this.backend && this.backend.create) { | |
var opts = _objectSpread$1(_objectSpread$1({}, options), {}, { | |
isUpdate | |
}); | |
var fc = this.backend.create.bind(this.backend); | |
if (fc.length < 6) { | |
try { | |
var r; | |
if (fc.length === 5) { | |
r = fc(languages, namespace, key, fallbackValue, opts); | |
} else { | |
r = fc(languages, namespace, key, fallbackValue); | |
} | |
if (r && typeof r.then === "function") { | |
r.then(function(data) { | |
return clb(null, data); | |
})["catch"](clb); | |
} else { | |
clb(null, r); | |
} | |
} catch (err) { | |
clb(err); | |
} | |
} else { | |
fc(languages, namespace, key, fallbackValue, clb, opts); | |
} | |
} | |
if (!languages || !languages[0]) | |
return; | |
this.store.addResource(languages[0], namespace, key, fallbackValue); | |
} | |
}]); | |
return Connector2; | |
}(EventEmitter); | |
function get() { | |
return { | |
debug: false, | |
initImmediate: true, | |
ns: ["translation"], | |
defaultNS: ["translation"], | |
fallbackLng: ["dev"], | |
fallbackNS: false, | |
supportedLngs: false, | |
nonExplicitSupportedLngs: false, | |
load: "all", | |
preload: false, | |
simplifyPluralSuffix: true, | |
keySeparator: ".", | |
nsSeparator: ":", | |
pluralSeparator: "_", | |
contextSeparator: "_", | |
partialBundledLanguages: false, | |
saveMissing: false, | |
updateMissing: false, | |
saveMissingTo: "fallback", | |
saveMissingPlurals: true, | |
missingKeyHandler: false, | |
missingInterpolationHandler: false, | |
postProcess: false, | |
postProcessPassResolved: false, | |
returnNull: true, | |
returnEmptyString: true, | |
returnObjects: false, | |
joinArrays: false, | |
returnedObjectHandler: false, | |
parseMissingKeyHandler: false, | |
appendNamespaceToMissingKey: false, | |
appendNamespaceToCIMode: false, | |
overloadTranslationOptionHandler: function handle2(args) { | |
var ret = {}; | |
if (_typeof(args[1]) === "object") | |
ret = args[1]; | |
if (typeof args[1] === "string") | |
ret.defaultValue = args[1]; | |
if (typeof args[2] === "string") | |
ret.tDescription = args[2]; | |
if (_typeof(args[2]) === "object" || _typeof(args[3]) === "object") { | |
var options = args[3] || args[2]; | |
Object.keys(options).forEach(function(key) { | |
ret[key] = options[key]; | |
}); | |
} | |
return ret; | |
}, | |
interpolation: { | |
escapeValue: true, | |
format: function format(value, _format, lng, options) { | |
return value; | |
}, | |
prefix: "{{", | |
suffix: "}}", | |
formatSeparator: ",", | |
unescapePrefix: "-", | |
nestingPrefix: "$t(", | |
nestingSuffix: ")", | |
nestingOptionsSeparator: ",", | |
maxReplaces: 1e3, | |
skipOnVariables: true | |
} | |
}; | |
} | |
function transformOptions(options) { | |
if (typeof options.ns === "string") | |
options.ns = [options.ns]; | |
if (typeof options.fallbackLng === "string") | |
options.fallbackLng = [options.fallbackLng]; | |
if (typeof options.fallbackNS === "string") | |
options.fallbackNS = [options.fallbackNS]; | |
if (options.supportedLngs && options.supportedLngs.indexOf("cimode") < 0) { | |
options.supportedLngs = options.supportedLngs.concat(["cimode"]); | |
} | |
return options; | |
} | |
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), true).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 _createSuper(Derived) { | |
var hasNativeReflectConstruct = _isNativeReflectConstruct(); | |
return function _createSuperInternal() { | |
var Super = _getPrototypeOf(Derived), result; | |
if (hasNativeReflectConstruct) { | |
var NewTarget = _getPrototypeOf(this).constructor; | |
result = Reflect.construct(Super, arguments, NewTarget); | |
} else { | |
result = Super.apply(this, arguments); | |
} | |
return _possibleConstructorReturn(this, result); | |
}; | |
} | |
function _isNativeReflectConstruct() { | |
if (typeof Reflect === "undefined" || !Reflect.construct) | |
return false; | |
if (Reflect.construct.sham) | |
return false; | |
if (typeof Proxy === "function") | |
return true; | |
try { | |
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() { | |
})); | |
return true; | |
} catch (e) { | |
return false; | |
} | |
} | |
function noop() { | |
} | |
function bindMemberFunctions(inst) { | |
var mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst)); | |
mems.forEach(function(mem) { | |
if (typeof inst[mem] === "function") { | |
inst[mem] = inst[mem].bind(inst); | |
} | |
}); | |
} | |
var I18n = function(_EventEmitter) { | |
_inherits(I18n2, _EventEmitter); | |
var _super = _createSuper(I18n2); | |
function I18n2() { | |
var _this; | |
var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; | |
var callback = arguments.length > 1 ? arguments[1] : void 0; | |
_classCallCheck(this, I18n2); | |
_this = _super.call(this); | |
if (isIE10) { | |
EventEmitter.call(_assertThisInitialized(_this)); | |
} | |
_this.options = transformOptions(options); | |
_this.services = {}; | |
_this.logger = baseLogger; | |
_this.modules = { | |
external: [] | |
}; | |
bindMemberFunctions(_assertThisInitialized(_this)); | |
if (callback && !_this.isInitialized && !options.isClone) { | |
if (!_this.options.initImmediate) { | |
_this.init(options, callback); | |
return _possibleConstructorReturn(_this, _assertThisInitialized(_this)); | |
} | |
setTimeout(function() { | |
_this.init(options, callback); | |
}, 0); | |
} | |
return _this; | |
} | |
_createClass(I18n2, [{ | |
key: "init", | |
value: function init2() { | |
var _this2 = this; | |
var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; | |
var callback = arguments.length > 1 ? arguments[1] : void 0; | |
if (typeof options === "function") { | |
callback = options; | |
options = {}; | |
} | |
if (!options.defaultNS && options.defaultNS !== false && options.ns) { | |
if (typeof options.ns === "string") { | |
options.defaultNS = options.ns; | |
} else if (options.ns.indexOf("translation") < 0) { | |
options.defaultNS = options.ns[0]; | |
} | |
} | |
var defOpts = get(); | |
this.options = _objectSpread(_objectSpread(_objectSpread({}, defOpts), this.options), transformOptions(options)); | |
if (this.options.compatibilityAPI !== "v1") { | |
this.options.interpolation = _objectSpread(_objectSpread({}, defOpts.interpolation), this.options.interpolation); | |
} | |
if (options.keySeparator !== void 0) { | |
this.options.userDefinedKeySeparator = options.keySeparator; | |
} | |
if (options.nsSeparator !== void 0) { | |
this.options.userDefinedNsSeparator = options.nsSeparator; | |
} | |
function createClassOnDemand(ClassOrObject) { | |
if (!ClassOrObject) | |
return null; | |
if (typeof ClassOrObject === "function") | |
return new ClassOrObject(); | |
return ClassOrObject; | |
} | |
if (!this.options.isClone) { | |
if (this.modules.logger) { | |
baseLogger.init(createClassOnDemand(this.modules.logger), this.options); | |
} else { | |
baseLogger.init(null, this.options); | |
} | |
var formatter; | |
if (this.modules.formatter) { | |
formatter = this.modules.formatter; | |
} else if (typeof Intl !== "undefined") { | |
formatter = Formatter; | |
} | |
var lu = new LanguageUtil(this.options); | |
this.store = new ResourceStore(this.options.resources, this.options); | |
var s = this.services; | |
s.logger = baseLogger; | |
s.resourceStore = this.store; | |
s.languageUtils = lu; | |
s.pluralResolver = new PluralResolver(lu, { | |
prepend: this.options.pluralSeparator, | |
compatibilityJSON: this.options.compatibilityJSON, | |
simplifyPluralSuffix: this.options.simplifyPluralSuffix | |
}); | |
if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) { | |
s.formatter = createClassOnDemand(formatter); | |
s.formatter.init(s, this.options); | |
this.options.interpolation.format = s.formatter.format.bind(s.formatter); | |
} | |
s.interpolator = new Interpolator(this.options); | |
s.utils = { | |
hasLoadedNamespace: this.hasLoadedNamespace.bind(this) | |
}; | |
s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options); | |
s.backendConnector.on("*", function(event) { | |
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { | |
args[_key - 1] = arguments[_key]; | |
} | |
_this2.emit.apply(_this2, [event].concat(args)); | |
}); | |
if (this.modules.languageDetector) { | |
s.languageDetector = createClassOnDemand(this.modules.languageDetector); | |
if (s.languageDetector.init) | |
s.languageDetector.init(s, this.options.detection, this.options); | |
} | |
if (this.modules.i18nFormat) { | |
s.i18nFormat = createClassOnDemand(this.modules.i18nFormat); | |
if (s.i18nFormat.init) | |
s.i18nFormat.init(this); | |
} | |
this.translator = new Translator(this.services, this.options); | |
this.translator.on("*", function(event) { | |
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { | |
args[_key2 - 1] = arguments[_key2]; | |
} | |
_this2.emit.apply(_this2, [event].concat(args)); | |
}); | |
this.modules.external.forEach(function(m) { | |
if (m.init) | |
m.init(_this2); | |
}); | |
} | |
this.format = this.options.interpolation.format; | |
if (!callback) | |
callback = noop; | |
if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) { | |
var codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng); | |
if (codes.length > 0 && codes[0] !== "dev") | |
this.options.lng = codes[0]; | |
} | |
if (!this.services.languageDetector && !this.options.lng) { | |
this.logger.warn("init: no languageDetector is used and no lng is defined"); | |
} | |
var storeApi = ["getResource", "hasResourceBundle", "getResourceBundle", "getDataByLanguage"]; | |
storeApi.forEach(function(fcName) { | |
_this2[fcName] = function() { | |
var _this2$store; | |
return (_this2$store = _this2.store)[fcName].apply(_this2$store, arguments); | |
}; | |
}); | |
var storeApiChained = ["addResource", "addResources", "addResourceBundle", "removeResourceBundle"]; | |
storeApiChained.forEach(function(fcName) { | |
_this2[fcName] = function() { | |
var _this2$store2; | |
(_this2$store2 = _this2.store)[fcName].apply(_this2$store2, arguments); | |
return _this2; | |
}; | |
}); | |
var deferred = defer(); | |
var load = function load2() { | |
var finish = function finish2(err, t2) { | |
if (_this2.isInitialized && !_this2.initializedStoreOnce) | |
_this2.logger.warn("init: i18next is already initialized. You should call init just once!"); | |
_this2.isInitialized = true; | |
if (!_this2.options.isClone) | |
_this2.logger.log("initialized", _this2.options); | |
_this2.emit("initialized", _this2.options); | |
deferred.resolve(t2); | |
callback(err, t2); | |
}; | |
if (_this2.languages && _this2.options.compatibilityAPI !== "v1" && !_this2.isInitialized) | |
return finish(null, _this2.t.bind(_this2)); | |
_this2.changeLanguage(_this2.options.lng, finish); | |
}; | |
if (this.options.resources || !this.options.initImmediate) { | |
load(); | |
} else { | |
setTimeout(load, 0); | |
} | |
return deferred; | |
} | |
}, { | |
key: "loadResources", | |
value: function loadResources2(language) { | |
var _this3 = this; | |
var callback = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : noop; | |
var usedCallback = callback; | |
var usedLng = typeof language === "string" ? language : this.language; | |
if (typeof language === "function") | |
usedCallback = language; | |
if (!this.options.resources || this.options.partialBundledLanguages) { | |
if (usedLng && usedLng.toLowerCase() === "cimode") | |
return usedCallback(); | |
var toLoad = []; | |
var append = function append2(lng) { | |
if (!lng) | |
return; | |
var lngs = _this3.services.languageUtils.toResolveHierarchy(lng); | |
lngs.forEach(function(l) { | |
if (toLoad.indexOf(l) < 0) | |
toLoad.push(l); | |
}); | |
}; | |
if (!usedLng) { | |
var fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng); | |
fallbacks.forEach(function(l) { | |
return append(l); | |
}); | |
} else { | |
append(usedLng); | |
} | |
if (this.options.preload) { | |
this.options.preload.forEach(function(l) { | |
return append(l); | |
}); | |
} | |
this.services.backendConnector.load(toLoad, this.options.ns, function(e) { | |
if (!e && !_this3.resolvedLanguage && _this3.language) | |
_this3.setResolvedLanguage(_this3.language); | |
usedCallback(e); | |
}); | |
} else { | |
usedCallback(null); | |
} | |
} | |
}, { | |
key: "reloadResources", | |
value: function reloadResources2(lngs, ns, callback) { | |
var deferred = defer(); | |
if (!lngs) | |
lngs = this.languages; | |
if (!ns) | |
ns = this.options.ns; | |
if (!callback) | |
callback = noop; | |
this.services.backendConnector.reload(lngs, ns, function(err) { | |
deferred.resolve(); | |
callback(err); | |
}); | |
return deferred; | |
} | |
}, { | |
key: "use", | |
value: function use2(module2) { | |
if (!module2) | |
throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()"); | |
if (!module2.type) | |
throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()"); | |
if (module2.type === "backend") { | |
this.modules.backend = module2; | |
} | |
if (module2.type === "logger" || module2.log && module2.warn && module2.error) { | |
this.modules.logger = module2; | |
} | |
if (module2.type === "languageDetector") { | |
this.modules.languageDetector = module2; | |
} | |
if (module2.type === "i18nFormat") { | |
this.modules.i18nFormat = module2; | |
} | |
if (module2.type === "postProcessor") { | |
postProcessor.addPostProcessor(module2); | |
} | |
if (module2.type === "formatter") { | |
this.modules.formatter = module2; | |
} | |
if (module2.type === "3rdParty") { | |
this.modules.external.push(module2); | |
} | |
return this; | |
} | |
}, { | |
key: "setResolvedLanguage", | |
value: function setResolvedLanguage(l) { | |
if (!l || !this.languages) | |
return; | |
if (["cimode", "dev"].indexOf(l) > -1) | |
return; | |
for (var li = 0; li < this.languages.length; li++) { | |
var lngInLngs = this.languages[li]; | |
if (["cimode", "dev"].indexOf(lngInLngs) > -1) | |
continue; | |
if (this.store.hasLanguageSomeTranslations(lngInLngs)) { | |
this.resolvedLanguage = lngInLngs; | |
break; | |
} | |
} | |
} | |
}, { | |
key: "changeLanguage", | |
value: function changeLanguage2(lng, callback) { | |
var _this4 = this; | |
this.isLanguageChangingTo = lng; | |
var deferred = defer(); | |
this.emit("languageChanging", lng); | |
var setLngProps = function setLngProps2(l) { | |
_this4.language = l; | |
_this4.languages = _this4.services.languageUtils.toResolveHierarchy(l); | |
_this4.resolvedLanguage = void 0; | |
_this4.setResolvedLanguage(l); | |
}; | |
var done = function done2(err, l) { | |
if (l) { | |
setLngProps(l); | |
_this4.translator.changeLanguage(l); | |
_this4.isLanguageChangingTo = void 0; | |
_this4.emit("languageChanged", l); | |
_this4.logger.log("languageChanged", l); | |
} else { | |
_this4.isLanguageChangingTo = void 0; | |
} | |
deferred.resolve(function() { | |
return _this4.t.apply(_this4, arguments); | |
}); | |
if (callback) | |
callback(err, function() { | |
return _this4.t.apply(_this4, arguments); | |
}); | |
}; | |
var setLng = function setLng2(lngs) { | |
if (!lng && !lngs && _this4.services.languageDetector) | |
lngs = []; | |
var l = typeof lngs === "string" ? lngs : _this4.services.languageUtils.getBestMatchFromCodes(lngs); | |
if (l) { | |
if (!_this4.language) { | |
setLngProps(l); | |
} | |
if (!_this4.translator.language) | |
_this4.translator.changeLanguage(l); | |
if (_this4.services.languageDetector && _this4.services.languageDetector.cacheUserLanguage) | |
_this4.services.languageDetector.cacheUserLanguage(l); | |
} | |
_this4.loadResources(l, function(err) { | |
done(err, l); | |
}); | |
}; | |
if (!lng && this.services.languageDetector && !this.services.languageDetector.async) { | |
setLng(this.services.languageDetector.detect()); | |
} else if (!lng && this.services.languageDetector && this.services.languageDetector.async) { | |
if (this.services.languageDetector.detect.length === 0) { | |
this.services.languageDetector.detect().then(setLng); | |
} else { | |
this.services.languageDetector.detect(setLng); | |
} | |
} else { | |
setLng(lng); | |
} | |
return deferred; | |
} | |
}, { | |
key: "getFixedT", | |
value: function getFixedT2(lng, ns, keyPrefix) { | |
var _this5 = this; | |
var fixedT = function fixedT2(key, opts) { | |
var options; | |
if (_typeof(opts) !== "object") { | |
for (var _len3 = arguments.length, rest = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) { | |
rest[_key3 - 2] = arguments[_key3]; | |
} | |
options = _this5.options.overloadTranslationOptionHandler([key, opts].concat(rest)); | |
} else { | |
options = _objectSpread({}, opts); | |
} | |
options.lng = options.lng || fixedT2.lng; | |
options.lngs = options.lngs || fixedT2.lngs; | |
options.ns = options.ns || fixedT2.ns; | |
options.keyPrefix = options.keyPrefix || keyPrefix || fixedT2.keyPrefix; | |
var keySeparator = _this5.options.keySeparator || "."; | |
var resultKey; | |
if (options.keyPrefix && Array.isArray(key)) { | |
resultKey = key.map(function(k) { | |
return "".concat(options.keyPrefix).concat(keySeparator).concat(k); | |
}); | |
} else { | |
resultKey = options.keyPrefix ? "".concat(options.keyPrefix).concat(keySeparator).concat(key) : key; | |
} | |
return _this5.t(resultKey, options); | |
}; | |
if (typeof lng === "string") { | |
fixedT.lng = lng; | |
} else { | |
fixedT.lngs = lng; | |
} | |
fixedT.ns = ns; | |
fixedT.keyPrefix = keyPrefix; | |
return fixedT; | |
} | |
}, { | |
key: "t", | |
value: function t2() { | |
var _this$translator; | |
return this.translator && (_this$translator = this.translator).translate.apply(_this$translator, arguments); | |
} | |
}, { | |
key: "exists", | |
value: function exists2() { | |
var _this$translator2; | |
return this.translator && (_this$translator2 = this.translator).exists.apply(_this$translator2, arguments); | |
} | |
}, { | |
key: "setDefaultNamespace", | |
value: function setDefaultNamespace2(ns) { | |
this.options.defaultNS = ns; | |
} | |
}, { | |
key: "hasLoadedNamespace", | |
value: function hasLoadedNamespace2(ns) { | |
var _this6 = this; | |
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; | |
if (!this.isInitialized) { | |
this.logger.warn("hasLoadedNamespace: i18next was not initialized", this.languages); | |
return false; | |
} | |
if (!this.languages || !this.languages.length) { | |
this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty", this.languages); | |
return false; | |
} | |
var lng = this.resolvedLanguage || this.languages[0]; | |
var fallbackLng = this.options ? this.options.fallbackLng : false; | |
var lastLng = this.languages[this.languages.length - 1]; | |
if (lng.toLowerCase() === "cimode") | |
return true; | |
var loadNotPending = function loadNotPending2(l, n) { | |
var loadState = _this6.services.backendConnector.state["".concat(l, "|").concat(n)]; | |
return loadState === -1 || loadState === 2; | |
}; | |
if (options.precheck) { | |
var preResult = options.precheck(this, loadNotPending); | |
if (preResult !== void 0) | |
return preResult; | |
} | |
if (this.hasResourceBundle(lng, ns)) | |
return true; | |
if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) | |
return true; | |
if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) | |
return true; | |
return false; | |
} | |
}, { | |
key: "loadNamespaces", | |
value: function loadNamespaces2(ns, callback) { | |
var _this7 = this; | |
var deferred = defer(); | |
if (!this.options.ns) { | |
if (callback) | |
callback(); | |
return Promise.resolve(); | |
} | |
if (typeof ns === "string") | |
ns = [ns]; | |
ns.forEach(function(n) { | |
if (_this7.options.ns.indexOf(n) < 0) | |
_this7.options.ns.push(n); | |
}); | |
this.loadResources(function(err) { | |
deferred.resolve(); | |
if (callback) | |
callback(err); | |
}); | |
return deferred; | |
} | |
}, { | |
key: "loadLanguages", | |
value: function loadLanguages2(lngs, callback) { | |
var deferred = defer(); | |
if (typeof lngs === "string") | |
lngs = [lngs]; | |
var preloaded = this.options.preload || []; | |
var newLngs = lngs.filter(function(lng) { | |
return preloaded.indexOf(lng) < 0; | |
}); | |
if (!newLngs.length) { | |
if (callback) | |
callback(); | |
return Promise.resolve(); | |
} | |
this.options.preload = preloaded.concat(newLngs); | |
this.loadResources(function(err) { | |
deferred.resolve(); | |
if (callback) | |
callback(err); | |
}); | |
return deferred; | |
} | |
}, { | |
key: "dir", | |
value: function dir2(lng) { | |
if (!lng) | |
lng = this.resolvedLanguage || (this.languages && this.languages.length > 0 ? this.languages[0] : this.language); | |
if (!lng) | |
return "rtl"; | |
var rtlLngs = ["ar", "shu", "sqr", "ssh", "xaa", "yhd", "yud", "aao", "abh", "abv", "acm", "acq", "acw", "acx", "acy", "adf", "ads", "aeb", "aec", "afb", "ajp", "apc", "apd", "arb", "arq", "ars", "ary", "arz", "auz", "avl", "ayh", "ayl", "ayn", "ayp", "bbz", "pga", "he", "iw", "ps", "pbt", "pbu", "pst", "prp", "prd", "ug", "ur", "ydd", "yds", "yih", "ji", "yi", "hbo", "men", "xmn", "fa", "jpr", "peo", "pes", "prs", "dv", "sam", "ckb"]; | |
var languageUtils = this.services && this.services.languageUtils || new LanguageUtil(get()); | |
return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf("-arab") > 1 ? "rtl" : "ltr"; | |
} | |
}, { | |
key: "cloneInstance", | |
value: function cloneInstance() { | |
var _this8 = this; | |
var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; | |
var callback = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : noop; | |
var mergedOptions = _objectSpread(_objectSpread(_objectSpread({}, this.options), options), { | |
isClone: true | |
}); | |
var clone2 = new I18n2(mergedOptions); | |
if (options.debug !== void 0 || options.prefix !== void 0) { | |
clone2.logger = clone2.logger.clone(options); | |
} | |
var membersToCopy = ["store", "services", "language"]; | |
membersToCopy.forEach(function(m) { | |
clone2[m] = _this8[m]; | |
}); | |
clone2.services = _objectSpread({}, this.services); | |
clone2.services.utils = { | |
hasLoadedNamespace: clone2.hasLoadedNamespace.bind(clone2) | |
}; | |
clone2.translator = new Translator(clone2.services, clone2.options); | |
clone2.translator.on("*", function(event) { | |
for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { | |
args[_key4 - 1] = arguments[_key4]; | |
} | |
clone2.emit.apply(clone2, [event].concat(args)); | |
}); | |
clone2.init(mergedOptions, callback); | |
clone2.translator.options = clone2.options; | |
clone2.translator.backendConnector.services.utils = { | |
hasLoadedNamespace: clone2.hasLoadedNamespace.bind(clone2) | |
}; | |
return clone2; | |
} | |
}, { | |
key: "toJSON", | |
value: function toJSON() { | |
return { | |
options: this.options, | |
store: this.store, | |
language: this.language, | |
languages: this.languages, | |
resolvedLanguage: this.resolvedLanguage | |
}; | |
} | |
}]); | |
return I18n2; | |
}(EventEmitter); | |
_defineProperty(I18n, "createInstance", function() { | |
var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; | |
var callback = arguments.length > 1 ? arguments[1] : void 0; | |
return new I18n(options, callback); | |
}); | |
var instance = I18n.createInstance(); | |
instance.createInstance = I18n.createInstance; | |
var createInstance = instance.createInstance; | |
var dir = instance.dir; | |
var init = instance.init; | |
var loadResources = instance.loadResources; | |
var reloadResources = instance.reloadResources; | |
var use = instance.use; | |
var changeLanguage = instance.changeLanguage; | |
var getFixedT = instance.getFixedT; | |
var t = instance.t; | |
var exists = instance.exists; | |
var setDefaultNamespace = instance.setDefaultNamespace; | |
var hasLoadedNamespace = instance.hasLoadedNamespace; | |
var loadNamespaces = instance.loadNamespaces; | |
var loadLanguages = instance.loadLanguages; | |
// plugin/settings/modals/regex_edition.ts | |
var ModalRegexFilePathName = class extends import_obsidian.Modal { | |
constructor(app2, settings3, allRegex, onSubmit) { | |
super(app2); | |
this.allRegex = allRegex; | |
this.settings = settings3; | |
this.onSubmit = onSubmit; | |
} | |
classValue(allRegex) { | |
this.settings.upload.replacePath = allRegex.filter((regex3) => { | |
return regex3.type === "path" /* path */; | |
}); | |
this.settings.upload.replaceTitle = allRegex.filter( | |
(regex3) => { | |
return regex3.type === "title" /* title */; | |
} | |
); | |
} | |
forbiddenValue(value, type) { | |
let onWhat = type === "path" /* path */ ? instance.t("common.path.folder") : instance.t("common.path.file"); | |
onWhat = onWhat.toLowerCase(); | |
let isForbidden = false; | |
if (value == "/") { | |
new import_obsidian.Notice(instance.t("settings.regexReplacing.forbiddenValue", { what: onWhat, forbiddenChar: value })); | |
value = ""; | |
isForbidden = true; | |
} else if (value.match(/[><:"|?*]|(\\\/)|(^\w+\/\w+)|(\\)/) && type === "title" /* title */) { | |
new import_obsidian.Notice(instance.t("settings.regexReplacing.forbiddenValue", { what: onWhat, forbiddenChar: value.match(/[><:"|?*]|(\\\/)|(^\w+\/\w+)|(\\)/)[0] })); | |
value = ""; | |
isForbidden = true; | |
} else if (type === "path" /* path */) { | |
if (value.match(/[\\><:"|?*]/)) { | |
new import_obsidian.Notice(instance.t("settings.regexReplacing.forbiddenValue", { what: onWhat, forbiddenChar: value.match(/[\\><:"|?*]/)[0] })); | |
value = ""; | |
isForbidden = true; | |
} else if (value.match(/(^\w+\/\w+)|(\\\/)/)) { | |
new import_obsidian.Notice(instance.t("settings.regexReplacing.warningPath")); | |
} | |
} | |
return [value, isForbidden]; | |
} | |
onOpen() { | |
const { contentEl } = this; | |
contentEl.empty(); | |
if (this.settings.upload.behavior === "fixed" /* fixed */) { | |
contentEl.createEl("h2", { text: instance.t("settings.regexReplacing.modal.title.only") }); | |
} else { | |
contentEl.createEl("h2", { text: instance.t("settings.regexReplacing.modal.title.all") }); | |
} | |
if (!this.settings.upload.replacePath) { | |
this.settings.upload.replacePath = []; | |
} else if (!this.settings.upload.replaceTitle) { | |
this.settings.upload.replaceTitle = []; | |
} | |
this.settings.upload.replacePath.forEach((title) => { | |
if (!title.type) { | |
title.type = "path" /* path */; | |
} | |
}); | |
this.settings.upload.replaceTitle.forEach((title) => { | |
if (!title.type) { | |
title.type = "title" /* title */; | |
} | |
}); | |
for (const title of this.allRegex) { | |
const sett = new import_obsidian.Setting(contentEl).setClass("github-publisher-censor-entry").addText((text) => { | |
text.inputEl.style.width = "100%"; | |
text.setPlaceholder(instance.t("regex.entry")).setValue(title.regex).onChange((value) => { | |
title.regex = value; | |
}); | |
}).addText((text) => { | |
text.inputEl.style.width = "100%"; | |
text.setPlaceholder(instance.t("regex.replace")).setValue(title.replacement).onChange((value) => { | |
title.replacement = value; | |
}); | |
}); | |
if (this.settings.upload.behavior !== "fixed" /* fixed */) { | |
sett.addDropdown((dropdown) => { | |
dropdown.addOption("path", instance.t("common.path.folder")).addOption("title", instance.t("common.path.file")).setValue(title.type).onChange((value) => { | |
title.type = value; | |
}); | |
}); | |
} else { | |
sett.addButton((button) => { | |
button.buttonEl.classList.add("github-publisher-disabled-button"); | |
button.setButtonText(instance.t("common.path.file")); | |
}); | |
} | |
sett.addExtraButton((button) => { | |
button.setIcon("trash").onClick(() => { | |
this.allRegex.splice(this.allRegex.indexOf(title), 1); | |
this.onOpen(); | |
}); | |
}); | |
} | |
new import_obsidian.Setting(contentEl).setClass("github-publisher-modals").addButton((button) => { | |
button.setIcon("plus").onClick(() => { | |
this.allRegex.push({ | |
regex: "", | |
replacement: "", | |
type: "title" /* title */ | |
}); | |
this.onOpen(); | |
}); | |
}).addButton((button) => { | |
button.setButtonText(instance.t("common.save")).onClick(() => { | |
const canBeValidated = []; | |
this.allRegex.forEach((title) => { | |
const isForbiddenEntry = this.forbiddenValue(title.regex, title.type); | |
const isForbiddenReplace = this.forbiddenValue(title.replacement, title.type); | |
canBeValidated.push(isForbiddenEntry[1]); | |
canBeValidated.push(isForbiddenReplace[1]); | |
if (isForbiddenEntry[1] || isForbiddenReplace[1]) { | |
title.regex = isForbiddenEntry[0]; | |
title.replacement = isForbiddenReplace[0]; | |
} | |
}); | |
if (!canBeValidated.includes(true)) { | |
this.onSubmit(this.allRegex); | |
this.close(); | |
} | |
}); | |
}); | |
} | |
onClose() { | |
const { contentEl } = this; | |
contentEl.empty(); | |
} | |
}; | |
var ModalRegexOnContents = class extends import_obsidian.Modal { | |
constructor(app2, settings3, onSubmit) { | |
super(app2); | |
this.settings = settings3; | |
this.onSubmit = onSubmit; | |
} | |
onOpen() { | |
const { contentEl } = this; | |
contentEl.empty(); | |
contentEl.createEl("p", { | |
text: instance.t("settings.regexReplacing.modal.title.text") | |
}).createEl("p", { | |
text: instance.t("settings.regexReplacing.modal.desc") | |
}).createEl("p", { | |
text: instance.t("settings.regexReplacing.empty") | |
}); | |
for (const censorText of this.settings.conversion.censorText) { | |
const afterIcon = censorText.after ? "arrow-down" : "arrow-up"; | |
const moment2 = censorText.after ? instance.t("common.after").toLowerCase() : instance.t("common.before").toLowerCase(); | |
const desc = instance.t("settings.regexReplacing.momentReplaceRegex", { moment: moment2 }); | |
new import_obsidian.Setting(contentEl).setClass("github-publisher-censor-entry").addText((text) => { | |
text.inputEl.style.width = "100%"; | |
text.setPlaceholder( | |
instance.t( | |
"regex.entry" | |
) | |
).setValue(censorText.entry).onChange((value) => __async(this, null, function* () { | |
censorText.entry = value; | |
})); | |
}).addText((text) => { | |
text.inputEl.style.width = "100%"; | |
text.setPlaceholder(instance.t("regex.replace")).setValue(censorText.replace).onChange((value) => __async(this, null, function* () { | |
censorText.replace = value; | |
})); | |
}).addExtraButton((btn) => { | |
btn.setIcon("trash").setTooltip(instance.t("common.delete", { things: "Regex" })).onClick(() => __async(this, null, function* () { | |
this.settings.conversion.censorText.splice( | |
this.settings.conversion.censorText.indexOf( | |
censorText | |
), | |
1 | |
); | |
this.onOpen(); | |
})); | |
}).addExtraButton((btn) => { | |
btn.setTooltip(desc).setIcon(afterIcon).onClick(() => __async(this, null, function* () { | |
censorText.after = !censorText.after; | |
this.onOpen(); | |
})); | |
}); | |
} | |
new import_obsidian.Setting(contentEl).addButton((btn) => { | |
btn.setIcon("plus").setTooltip(instance.t("common.add", { things: "Regex" })).onClick(() => __async(this, null, function* () { | |
const censorText = { | |
entry: "", | |
replace: "", | |
after: false | |
}; | |
this.settings.conversion.censorText.push(censorText); | |
this.onOpen(); | |
})); | |
}).addButton((button) => { | |
button.setButtonText(instance.t("common.save")).onClick(() => { | |
this.onSubmit(this.settings); | |
this.close(); | |
}); | |
}); | |
} | |
onClose() { | |
const { contentEl } = this; | |
contentEl.empty(); | |
} | |
}; | |
// plugin/settings/style.ts | |
function showSettings(containerEl) { | |
for (const [type, elem] of Object.entries(containerEl)) { | |
if (type != "components") { | |
elem.show(); | |
} | |
} | |
} | |
function hideSettings(containerEl) { | |
for (const [type, elem] of Object.entries(containerEl)) { | |
if (type != "components") { | |
elem.hide(); | |
} | |
} | |
} | |
function showHideBasedOnFolder(settings3, frontmatterKeySettings, rootFolderSettings, folderNoteSettings) { | |
const upload = settings3.upload; | |
if (upload.behavior === "yaml" /* yaml */) { | |
showSettings(frontmatterKeySettings); | |
showSettings(rootFolderSettings); | |
showSettings(folderNoteSettings); | |
} else { | |
hideSettings(frontmatterKeySettings); | |
hideSettings(rootFolderSettings); | |
if (upload.behavior === "obsidian" /* obsidian */) { | |
showSettings(folderNoteSettings); | |
} else { | |
hideSettings(folderNoteSettings); | |
} | |
} | |
} | |
function autoCleanCondition(value, autoCleanSetting, plugin) { | |
return __async(this, null, function* () { | |
const settings3 = plugin.settings.upload; | |
if (value.length === 0 && settings3.defaultName) { | |
settings3.autoclean.enable = false; | |
yield plugin.saveSettings(); | |
autoCleanSetting.setDisabled(true); | |
autoCleanSetting.components[0].toggleEl.classList.remove("is-enabled"); | |
} else if (value.length === 0 && settings3.behavior !== "yaml" /* yaml */) { | |
settings3.autoclean.enable = false; | |
autoCleanSetting.setDisabled(true); | |
autoCleanSetting.components[0].toggleEl.classList.remove("is-enabled"); | |
} else { | |
autoCleanSetting.setDisabled(false); | |
if (settings3.autoclean.enable) { | |
autoCleanSetting.components[0].toggleEl.classList.add("is-enabled"); | |
} | |
} | |
}); | |
} | |
function folderHideShowSettings(frontmatterKeySettings, rootFolderSettings, autoCleanSetting, value, plugin) { | |
return __async(this, null, function* () { | |
const settings3 = plugin.settings.upload; | |
if (value === "yaml" /* yaml */) { | |
showSettings(frontmatterKeySettings); | |
showSettings(rootFolderSettings); | |
autoCleanCondition( | |
settings3.rootFolder, | |
autoCleanSetting, | |
plugin | |
).then(); | |
} else { | |
if (settings3.defaultName.length > 0) { | |
autoCleanSetting.setDisabled(false); | |
if (settings3.autoclean.enable) { | |
autoCleanSetting.components[0].toggleEl.classList.add( | |
"is-enabled" | |
); | |
} | |
} | |
hideSettings(frontmatterKeySettings); | |
hideSettings(rootFolderSettings); | |
} | |
}); | |
} | |
function autoCleanUpSettingsOnCondition(condition, autoCleanSetting, plugin) { | |
const settings3 = plugin.settings.upload; | |
if (condition) { | |
autoCleanSetting.setDisabled(true); | |
autoCleanSetting.components[0].toggleEl.classList.remove("is-enabled"); | |
settings3.autoclean.enable = false; | |
plugin.saveSettings().then(); | |
} else { | |
autoCleanSetting.setDisabled(false); | |
if (settings3.autoclean.enable) { | |
autoCleanSetting.components[0].toggleEl.classList.add("is-enabled"); | |
} | |
} | |
} | |
function shortcutsHideShow(condition, toDisplay) { | |
condition ? showSettings(toDisplay) : hideSettings(toDisplay); | |
} | |
// plugin/settings/help.ts | |
function KeyBasedOnSettings(settings3) { | |
let category = ""; | |
if (settings3.upload.behavior === "yaml" /* yaml */) { | |
category = `${settings3.upload.yamlFolderKey}: ${settings3.upload.defaultName} | |
`; | |
} | |
return `${settings3.plugin.shareKey}: true | |
` + category + `links: | |
mdlinks: ${settings3.conversion.links.wiki} | |
convert: true | |
internals: ${settings3.conversion.links.internal} | |
nonShared: ${settings3.conversion.links.unshared} | |
embed: | |
send: ${settings3.embed.notes} | |
remove: false | |
attachment: | |
send: ${settings3.embed.attachments} | |
folder: ${settings3.embed.folder} | |
dataview: ${settings3.conversion.dataview} | |
hardBreak: ${settings3.conversion.hardbreak} | |
repo: | |
owner: ${settings3.github.user} | |
repo: ${settings3.github.repo} | |
branch: ${settings3.github.branch} | |
autoclean: ${settings3.upload.autoclean.enable} | |
copylink: | |
base: ${settings3.plugin.copyLink.links} | |
remove: [${settings3.plugin.copyLink.removePart.map((val) => `"${val}"`).join(", ")}] | |
`; | |
} | |
function help(settings3) { | |
const explanation = document.createDocumentFragment(); | |
explanation.createEl("ul", null, (span) => { | |
span.createEl("li", null, (span2) => { | |
span2.createEl("code", { | |
text: `${settings3.plugin.shareKey}:`, | |
cls: "code-title" | |
}); | |
span2.createEl("span", { | |
text: ` ${instance.t("settings.help.frontmatter.share")}` | |
}); | |
}); | |
span.createEl("li", null, (span2) => { | |
span2.createEl("code", { | |
text: "path:", | |
cls: "code-title" | |
}); | |
span2.createEl("span", { | |
text: ` ${instance.t("settings.help.frontmatter.path")}` | |
}); | |
}); | |
span.createEl("li", null, (span2) => { | |
span2.createEl("code", { text: "links:", cls: "code-title" }); | |
}); | |
span.createEl("ul", null, (l) => { | |
l.createEl("li", null, (p) => { | |
p.createEl("code", { text: "mdlinks" }); | |
p.createEl("span", { | |
text: `: ${instance.t("settings.help.frontmatter.mdlinks")}` | |
}); | |
}); | |
l.createEl("li", null, (p) => { | |
p.createEl("code", { text: "convert" }); | |
p.createEl("span", null, (span2) => { | |
span2.createEl("span", { | |
text: `: ${instance.t( | |
"settings.help.frontmatter.convert.enableOrDisable" | |
)} ` | |
}); | |
span2.createEl("code", { text: " [[link]] " }); | |
span2.createEl("span", { | |
text: instance.t("common.or") | |
}); | |
span2.createEl("code", { text: " [](link) " }); | |
span2.createEl("span", { | |
text: instance.t("settings.help.frontmatter.convert.syntax") | |
}); | |
}); | |
}); | |
l.createEl("li", null, (p) => { | |
p.createEl("code", { text: "internals" }); | |
p.createEl("span", { | |
text: `: ${instance.t("settings.help.frontmatter.internals")}` | |
}); | |
}); | |
l.createEl("li", null, (p) => { | |
p.createEl("code", { text: "nonShared" }); | |
p.createEl("span", { text: `: ${instance.t("settings.help.frontmatter.nonShared")}` }); | |
}); | |
}); | |
span.createEl("li", { text: "embed:", cls: "code code-title" }); | |
span.createEl("ul", null, (l) => { | |
l.createEl("li", null, (p) => { | |
p.createEl("code", { text: "send" }); | |
p.createEl("span", { | |
text: `: ${instance.t("settings.help.frontmatter.embed.send")}` | |
}); | |
}); | |
l.createEl("li", null, (p) => { | |
p.createEl("code", { text: "remove" }); | |
p.createEl("span", { | |
text: `: ${instance.t("settings.help.frontmatter.embed.remove")}` | |
}); | |
}); | |
}); | |
span.createEl("li", { text: "attachment:", cls: "code code-title" }); | |
span.createEl("ul", null, (l) => { | |
l.createEl("li", null, (span2) => { | |
span2.createEl("code", { text: "send" }); | |
span2.createEl("span", { | |
text: `: ${instance.t( | |
"settings.help.frontmatter.attachment.send" | |
)}` | |
}); | |
}); | |
l.createEl("li", null, (p) => { | |
p.createEl("code", { text: "folder" }); | |
p.createEl("span", { | |
text: `: ${instance.t( | |
"settings.help.frontmatter.attachment.folder" | |
)}` | |
}); | |
}); | |
}); | |
span.createEl("li", null, (span2) => { | |
span2.createEl("code", { text: "dataview", cls: "code-title" }); | |
span2.createEl("span", { | |
text: `: ${instance.t("settings.help.frontmatter.dataview")}` | |
}); | |
}); | |
span.createEl("li", null, (span2) => { | |
span2.createEl("code", { text: "hardbreak", cls: "code-title" }); | |
span2.createEl("span", { | |
text: `: ${instance.t("settings.help.frontmatter.hardBreak")}` | |
}); | |
}); | |
span.createEl("li", null, (span2) => { | |
span2.createEl("code", { text: "repo", cls: "code-title" }); | |
span2.createEl("span", { | |
text: `: ${instance.t("settings.help.frontmatter.repo.desc")}` | |
}); | |
span2.createEl("ul", null, (ul) => { | |
ul.createEl("li", null, (li) => { | |
li.createEl("code", { text: "owner" }); | |
li.createEl("span", { | |
text: `: ${instance.t("settings.help.frontmatter.repo.owner")}` | |
}); | |
}); | |
ul.createEl("li", null, (li) => { | |
li.createEl("code", { text: "repo" }); | |
li.createEl("span", { | |
text: `: ${instance.t("settings.help.frontmatter.repo.repo")}` | |
}); | |
}); | |
ul.createEl("li", null, (li) => { | |
li.createEl("code", { text: "branch" }); | |
li.createEl("span", { | |
text: `: ${instance.t( | |
"settings.help.frontmatter.repo.branch" | |
)}` | |
}); | |
}); | |
ul.createEl("li", null, (li) => { | |
li.createEl("code", { text: "autoclean" }); | |
li.createEl("span", { | |
text: `: ${instance.t("settings.help.frontmatter.autoclean")}` | |
}); | |
}); | |
}); | |
}); | |
span.createEl("li", null, (span2) => { | |
span2.createEl("code", { | |
text: `${settings3.upload.frontmatterTitle.key}`, | |
cls: "code-title" | |
}); | |
span2.createEl("span", { | |
text: `: ${instance.t("settings.help.frontmatter.titleKey")}` | |
}); | |
}); | |
span.createEl("li", null, (span2) => { | |
span2.createEl("code", { text: "baseLink", cls: "code-title" }); | |
span2.createEl("span", { | |
text: `: ${instance.t("settings.help.frontmatter.baselink.desc")}` | |
}); | |
span2.createEl("code", { text: "copylink:", cls: "code-title" }); | |
span2.createEl("ul", null, (ul) => { | |
ul.createEl("li", null, (li) => { | |
li.createEl("code", { text: "base" }); | |
li.createEl("span", { | |
text: `: ${instance.t("settings.help.frontmatter.baselink.base")}` | |
}); | |
}); | |
ul.createEl("li", null, (li) => { | |
li.createEl("code", { text: "remove" }); | |
li.createEl("span", { | |
text: `: ${instance.t("settings.help.frontmatter.baselink.remove")}` | |
}); | |
}); | |
}); | |
}); | |
}); | |
return explanation; | |
} | |
function usefullLinks() { | |
const usefullLinks2 = document.createDocumentFragment(); | |
usefullLinks2.createEl("ul", null, (el) => { | |
el.createEl("li", null, (el2) => { | |
el2.createEl("a", { | |
text: instance.t("settings.help.usefulLinks.documentation"), | |
href: instance.t("settings.help.usefulLinks.links") | |
}); | |
}); | |
el.createEl("li", null, (el2) => { | |
el2.createEl("a", { | |
text: instance.t("settings.help.usefulLinks.repository"), | |
href: "https://github.com/ObsidianPublisher/obsidian-github-publisher" | |
}); | |
}); | |
el.createEl("li", null, (el2) => { | |
el2.createEl("a", { | |
text: instance.t("settings.help.usefulLinks.issue"), | |
href: "https://github.com/ObsidianPublisher/obsidian-github-publisher/issues" | |
}); | |
}); | |
el.createEl("li", null, (el2) => { | |
el2.createEl("a", { | |
text: instance.t("settings.help.usefulLinks.discussion"), | |
href: "https://github.com/ObsidianPublisher/obsidian-github-publisher/discussions" | |
}); | |
}); | |
}); | |
return usefullLinks2; | |
} | |
function multipleRepoExplained(settings3) { | |
const multipleRepoExplained2 = document.createDocumentFragment(); | |
multipleRepoExplained2.createEl("p", null, (el) => { | |
el.createEl("span", { | |
text: instance.t("settings.help.multiRepoHelp.desc") | |
}); | |
el.createEl("code", { text: "multipleRepo" }); | |
el.createEl("span", { | |
text: ` ${instance.t("settings.help.multiRepoHelp.desc2")}:` | |
}); | |
el.createEl("ul", null, (el2) => { | |
el2.createEl("li", { text: "owner" }).addClass("code"); | |
el2.createEl("li", { text: "repo" }).addClass("code"); | |
el2.createEl("li", { text: "branch" }).addClass("code"); | |
el2.createEl("li", { text: "autoclean" }).addClass("code"); | |
}); | |
el.createEl("span", { | |
text: instance.t("settings.help.multiRepoHelp.exampleDesc") | |
}); | |
}); | |
multipleRepoExplained2.createEl("pre", { cls: "language-yaml" }).createEl("code", { | |
text: `multipleRepo: | |
- owner: ${settings3.github.user} | |
repo: ${settings3.github.repo} | |
branch: ${settings3.github.branch} | |
autoclean: false | |
- owner: ${settings3.github.user} | |
repo: my_second_brain | |
branch: master | |
autoclean: false`, | |
cls: "language-yaml" | |
}); | |
return multipleRepoExplained2; | |
} | |
function supportMe() { | |
const supportMe2 = document.createDocumentFragment(); | |
supportMe2.createEl("p", null, (el) => { | |
el.createEl("a", null, (el2) => { | |
el2.createEl("img", null, (img) => { | |
img.setAttr( | |
"src", | |
"https://storage.ko-fi.com/cdn/kofi2.png?v=3" | |
); | |
img.setAttr("alt", "Buy Me A Coffee"); | |
img.setAttr( | |
"style", | |
"height: 60px !important;width: 217px !important;" | |
); | |
}); | |
el2.setAttr("href", "https://ko-fi.com/lisandra_dev"); | |
}); | |
el.setAttr("style", "text-align: center;"); | |
}); | |
return supportMe2; | |
} | |
// plugin/src/data_validation_test.ts | |
var import_obsidian4 = require("obsidian"); | |
// plugin/src/utils.ts | |
var import_obsidian3 = require("obsidian"); | |
// plugin/conversion/filePathConvertor.ts | |
var import_obsidian2 = require("obsidian"); | |
// plugin/conversion/findAndReplaceText.ts | |
function createRegexFromText(toReplace, withflag) { | |
let flags = withflag; | |
if (!withflag) { | |
const flagsRegex = toReplace.match(/\/([gimy]+)$/); | |
flags = flagsRegex ? Array.from(new Set(flagsRegex[1].split(""))).join("") : ""; | |
} | |
return new RegExp(toReplace.replace(/\/(.+)\/.*/, "$1"), flags); | |
} | |
function findAndReplaceText(text, settings3, after) { | |
if (!settings3.conversion.censorText) { | |
return text; | |
} | |
let censoring = settings3.conversion.censorText.filter((censor) => !censor.after); | |
if (after) { | |
censoring = settings3.conversion.censorText.filter((censor) => censor.after); | |
} | |
for (const censor of censoring) { | |
if (censor.entry.trim().length > 0) { | |
const toReplace = censor.entry; | |
const replaceWith = censor.replace; | |
if (toReplace.match(/^\/.+\/$/)) { | |
const regex3 = createRegexFromText(toReplace, censor.flags); | |
text = text.replace(regex3, replaceWith); | |
} else { | |
text = text.replaceAll(toReplace, replaceWith); | |
} | |
} | |
} | |
return text; | |
} | |
// plugin/conversion/filePathConvertor.ts | |
function getDataviewPath(markdown, settings3, vault) { | |
if (!settings3.conversion.dataview) { | |
return []; | |
} | |
const wikiRegex = /\[\[(.*?)\]\]/gim; | |
const wikiMatches = markdown.matchAll(wikiRegex); | |
const linkedFiles = []; | |
if (!wikiMatches) | |
return []; | |
if (wikiMatches) { | |
for (const wikiMatch of wikiMatches) { | |
const altText = wikiMatch[1].replace(/(.*)\\?\|/i, ""); | |
const linkFrom = wikiMatch[1].replace(/\\?\|(.*)/, ""); | |
const linked = vault.getAbstractFileByPath(linkFrom) instanceof import_obsidian2.TFile ? vault.getAbstractFileByPath(linkFrom) : null; | |
if (linked) { | |
linkedFiles.push({ | |
linked, | |
linkFrom, | |
altText | |
}); | |
} | |
} | |
} | |
return linkedFiles; | |
} | |
function createRelativePath(sourceFile, targetFile, metadata, settings3, vault, frontmatter, sourceRepo, frontmatterSettings) { | |
return __async(this, null, function* () { | |
const sourcePath = getReceiptFolder(sourceFile, settings3, metadata, vault); | |
const frontmatterTarget = yield metadata.getFileCache(targetFile.linked).frontmatter; | |
const targetRepo = yield getRepoFrontmatter(settings3, frontmatterTarget); | |
const isFromAnotherRepo = checkIfRepoIsInAnother(sourceRepo, targetRepo); | |
const shared = isInternalShared( | |
settings3.plugin.shareKey, | |
frontmatterTarget, | |
frontmatterSettings | |
); | |
if (targetFile.linked.extension === "md" && (isFromAnotherRepo === false || shared === false)) { | |
return targetFile.destinationFilePath ? targetFile.destinationFilePath : targetFile.linked.basename; | |
} | |
if (targetFile.linked.path === sourceFile.path) { | |
return getReceiptFolder(targetFile.linked, settings3, metadata, vault).split("/").at(-1); | |
} | |
const targetPath = targetFile.linked.extension === "md" ? getReceiptFolder(targetFile.linked, settings3, metadata, vault) : getImageLinkOptions( | |
targetFile.linked, | |
settings3, | |
getFrontmatterCondition(frontmatter, settings3) | |
); | |
const sourceList = sourcePath.split("/"); | |
const targetList = targetPath.split("/"); | |
const excludeUtilDiff = (sourceList2, targetList2) => { | |
let i = 0; | |
while (sourceList2[i] === targetList2[i]) { | |
i++; | |
} | |
return sourceList2.slice(i); | |
}; | |
const diffSourcePath = excludeUtilDiff(sourceList, targetList); | |
const diffTargetPath = excludeUtilDiff(targetList, sourceList); | |
const diffTarget = function(folderPath) { | |
const relativePath2 = []; | |
for (const folder of folderPath) { | |
if (folder != folderPath.at(-1)) { | |
relativePath2.push(".."); | |
} | |
} | |
return relativePath2; | |
}; | |
const relativePath = diffTarget(diffSourcePath); | |
if (relativePath.length === 0) { | |
relativePath.push("."); | |
} | |
let relative = relativePath.concat(diffTargetPath).join("/"); | |
if (relative.trim() === "." || relative.trim() === "") { | |
relative = getReceiptFolder( | |
targetFile.linked, | |
settings3, | |
metadata, | |
vault | |
).split("/").at(-1); | |
} | |
return relative; | |
}); | |
} | |
function folderNoteIndexOBS(file, vault, settings3, fileName) { | |
const index = settings3.upload.folderNote.rename; | |
const folderParent = file.parent.path !== "/" ? `/${file.parent.path}/` : "/"; | |
const defaultPath = `${folderParent}${regexOnFileName(fileName, settings3)}`; | |
if (!settings3.upload.folderNote.enable) | |
return defaultPath; | |
const parentFolderName = file.parent.name; | |
if (fileName.replace(".md", "") === parentFolderName) | |
return `/${file.parent.path}/${index}`; | |
const outsideFolder = vault.getAbstractFileByPath( | |
file.path.replace(".md", "") | |
); | |
if (outsideFolder && outsideFolder instanceof import_obsidian2.TFolder) | |
return `/${outsideFolder.path}/${index}`; | |
return defaultPath; | |
} | |
function createObsidianPath(file, settings3, vault, fileName) { | |
fileName = folderNoteIndexOBS(file, vault, settings3, fileName); | |
const rootFolder = settings3.upload.defaultName.length > 0 ? settings3.upload.defaultName : ""; | |
const path = rootFolder + fileName; | |
let pathWithoutEnd = path.split("/").slice(0, -1).join("/"); | |
const fileNameOnly = path.split("/").at(-1); | |
pathWithoutEnd = regexOnPath(pathWithoutEnd, settings3); | |
if (pathWithoutEnd.trim().length === 0) | |
return fileNameOnly; | |
return (pathWithoutEnd + "/" + fileNameOnly).replace(/^\//, ""); | |
} | |
function folderNoteIndexYAML(fileName, frontmatter, settings3) { | |
const category = getCategory(frontmatter, settings3); | |
const parentCatFolder = !category.endsWith("/") ? category.split("/").at(-1) : category.split("/").at(-2); | |
if (!settings3.upload.folderNote.enable) | |
return regexOnFileName(fileName, settings3); | |
if (fileName.replace(".md", "").toLowerCase() === parentCatFolder.toLowerCase()) | |
return settings3.upload.folderNote.rename; | |
return regexOnFileName(fileName, settings3); | |
} | |
function createFrontmatterPath(settings3, frontmatter, fileName) { | |
const uploadSettings = settings3.upload; | |
const folderCategory = getCategory(frontmatter, settings3); | |
const folderNote = folderNoteIndexYAML(fileName, frontmatter, settings3); | |
let folderRoot = ""; | |
if (uploadSettings.rootFolder.length > 0 && !folderCategory.includes(uploadSettings.rootFolder)) { | |
folderRoot = uploadSettings.rootFolder + "/"; | |
} | |
if (folderCategory.trim().length === 0) | |
return folderNote; | |
const folderRegex = regexOnPath(folderRoot + folderCategory, settings3); | |
if (folderRegex.trim().length === 0) | |
return folderNote; | |
return (folderRegex + "/" + folderNote).replace(/^\//, ""); | |
} | |
function regexOnFileName(fileName, settings3) { | |
const uploadSettings = settings3.upload; | |
if (fileName === uploadSettings.folderNote.rename && uploadSettings.folderNote.enable || uploadSettings.replaceTitle.length === 0) | |
return fileName; | |
fileName = fileName.replace(".md", ""); | |
for (const regexTitle of uploadSettings.replaceTitle) { | |
if (regexTitle.regex.trim().length > 0) { | |
const toReplace = regexTitle.regex; | |
const replaceWith = regexTitle.replacement; | |
if (toReplace.match(/\/.+\//)) { | |
const regex3 = createRegexFromText(toReplace); | |
fileName = fileName.replace( | |
regex3, | |
replaceWith | |
); | |
} else { | |
fileName = fileName.replaceAll( | |
toReplace, | |
replaceWith | |
); | |
} | |
} | |
} | |
return fileName + ".md"; | |
} | |
function regexOnPath(path, settings3) { | |
const uploadSettings = settings3.upload; | |
if (uploadSettings.behavior === "fixed" /* fixed */ || uploadSettings.replacePath.length === 0) | |
return path; | |
for (const regexTitle of uploadSettings.replacePath) { | |
if (regexTitle.regex.trim().length > 0) { | |
const toReplace = regexTitle.regex; | |
const replaceWith = regexTitle.replacement; | |
if (toReplace.match(/\/.+\//)) { | |
const flagsRegex = toReplace.match(/\/([gimy]+)$/); | |
const flags = flagsRegex ? Array.from(new Set(flagsRegex[1].split(""))).join("") : ""; | |
const regex3 = new RegExp(toReplace.replace(/\/(.+)\/.*/, "$1"), flags); | |
path = path.replace( | |
regex3, | |
replaceWith | |
); | |
} else { | |
path = path.replaceAll( | |
toReplace, | |
replaceWith | |
); | |
} | |
} | |
} | |
return path; | |
} | |
function getTitleField(frontmatter, file, settings3) { | |
let fileName = file.name; | |
if (frontmatter && settings3.upload.frontmatterTitle.enable && frontmatter[settings3.upload.frontmatterTitle.key] && frontmatter[settings3.upload.frontmatterTitle.key] !== file.name) { | |
fileName = frontmatter[settings3.upload.frontmatterTitle.key] + ".md"; | |
} | |
return fileName; | |
} | |
function getReceiptFolder(file, settings3, metadataCache, vault) { | |
var _a; | |
if (file.extension === "md") { | |
const frontmatter = (_a = metadataCache.getCache(file.path)) == null ? void 0 : _a.frontmatter; | |
const fileName = getTitleField(frontmatter, file, settings3); | |
const editedFileName = regexOnFileName(fileName, settings3); | |
if (!isShared(frontmatter, settings3, file)) { | |
return fileName; | |
} | |
if (frontmatter.path) { | |
const frontmatterPath = frontmatter["path"] instanceof Array ? frontmatter["path"].join("/") : frontmatter["path"]; | |
if (frontmatterPath == "" || frontmatterPath == "/") { | |
return editedFileName; | |
} | |
return frontmatterPath + "/" + editedFileName; | |
} else if (settings3.upload.behavior === "yaml" /* yaml */) { | |
return createFrontmatterPath(settings3, frontmatter, fileName); | |
} else if (settings3.upload.behavior === "obsidian" /* obsidian */) { | |
return createObsidianPath(file, settings3, vault, fileName); | |
} else { | |
return settings3.upload.defaultName.length > 0 ? settings3.upload.defaultName + "/" + editedFileName : editedFileName; | |
} | |
} | |
} | |
function getImageLinkOptions(file, settings3, sourceFrontmatter) { | |
if (!sourceFrontmatter || !sourceFrontmatter.attachmentLinks) { | |
const defaultImageFolder = settings3.embed.folder; | |
if (defaultImageFolder.length > 0) { | |
return defaultImageFolder + "/" + file.name; | |
} else if (settings3.upload.defaultName.length > 0) { | |
return settings3.upload.defaultName + "/" + file.name; | |
} else { | |
return file.path; | |
} | |
} else if (sourceFrontmatter && sourceFrontmatter.attachmentLinks) { | |
return sourceFrontmatter.attachmentLinks + "/" + file.name; | |
} | |
return file.path; | |
} | |
// plugin/src/utils.ts | |
function noticeLog(message, settings3) { | |
if (settings3.plugin.noticeError) { | |
new import_obsidian3.Notice(message); | |
} else { | |
console.log(message); | |
} | |
} | |
function createListEdited(listUploaded, deleted, fileError) { | |
const listEdited = { | |
added: [], | |
edited: [], | |
deleted: [], | |
unpublished: [], | |
notDeleted: [] | |
}; | |
listUploaded.forEach((file) => { | |
if (file.isUpdated) { | |
listEdited.added.push(file.file); | |
} else { | |
listEdited.edited.push(file.file); | |
} | |
}); | |
listEdited.unpublished = fileError; | |
if (deleted) { | |
listEdited.deleted = deleted.deleted; | |
listEdited.notDeleted = deleted.undeleted; | |
} | |
return listEdited; | |
} | |
function getSettingsOfMetadataExtractor(app2, settings3) { | |
return __async(this, null, function* () { | |
if (import_obsidian3.Platform.isMobile || //@ts-ignore | |
!app2.plugins.enabledPlugins.has("metadata-extractor") || settings3.upload.metadataExtractorPath.length === 0) | |
return null; | |
const metadataExtractor = { | |
allExceptMdFile: null, | |
metadataFile: null, | |
tagsFile: null | |
}; | |
const path = `${app2.vault.configDir}/plugins/metadata-extractor`; | |
const plugin = app2.plugins.plugins["metadata-extractor"]; | |
if (plugin && plugin.settings) { | |
if (plugin.settings["allExceptMdFile"].length > 0) { | |
metadataExtractor.allExceptMdFile = path + "/" + plugin.settings["allExceptMdFile"]; | |
} | |
if (plugin.settings["metadataFile"].length > 0) { | |
metadataExtractor.metadataFile = path + "/" + plugin.settings["metadataFile"]; | |
} | |
if (plugin.settings["tagFile"].length > 0) { | |
metadataExtractor.tagsFile = path + "/" + plugin.settings["tagFile"]; | |
} | |
return metadataExtractor; | |
} | |
return null; | |
}); | |
} | |
function checkSlash(link) { | |
const slash = link.match(/\/*$/); | |
if (slash[0].length != 1) { | |
link = link.replace(/\/*$/, "") + "/"; | |
} | |
return link; | |
} | |
function createLink(file, repo, metadataCache, vault, settings3) { | |
return __async(this, null, function* () { | |
var _a, _b; | |
const copyLink = settings3.plugin.copyLink; | |
const github = settings3.github; | |
if (!copyLink.enable) { | |
return; | |
} | |
let filepath = getReceiptFolder(file, settings3, metadataCache, vault); | |
let baseLink = copyLink.links; | |
if (baseLink.length === 0) { | |
if (repo instanceof Array) { | |
baseLink = `https://${github.user}.github.io/${settings3.github.repo}/`; | |
} else { | |
baseLink = `https://${repo.owner}.github.io/${repo.repo}/`; | |
} | |
} | |
const frontmatter = (_a = metadataCache.getFileCache(file)) == null ? void 0 : _a.frontmatter; | |
const keyRepo = frontmatter["baselink"]; | |
let removePart = copyLink.removePart; | |
if (frontmatter["baselink"] !== void 0) { | |
baseLink = keyRepo; | |
removePart = []; | |
} else if (frontmatter["copylink"] && typeof frontmatter["copylink"] === "object") { | |
baseLink = frontmatter["copylink"].base; | |
removePart = (_b = frontmatter["copylink"].remove) != null ? _b : []; | |
} | |
baseLink = checkSlash(baseLink); | |
if (removePart.length > 0) { | |
for (const part of removePart) { | |
if (part.length > 0) { | |
filepath = filepath.replace(part.trim(), ""); | |
} | |
} | |
} | |
filepath = checkSlash(filepath); | |
const url = checkSlash(encodeURI(baseLink + filepath)); | |
yield navigator.clipboard.writeText(url); | |
return; | |
}); | |
} | |
function noticeMessage(PublisherManager, file, settings3, repo) { | |
return __async(this, null, function* () { | |
repo = Array.isArray(repo) ? repo : [repo]; | |
for (const repository of repo) { | |
yield noticeMessageOneRepo( | |
PublisherManager, | |
file, | |
settings3, | |
repository | |
); | |
} | |
}); | |
} | |
function noticeMessageOneRepo(PublisherManager, file, settings3, repo) { | |
return __async(this, null, function* () { | |
const noticeValue = file instanceof import_obsidian3.TFile ? '"' + file.basename + '"' : file; | |
let successMsg = ""; | |
if (file instanceof String) { | |
successMsg = instance.t("informations.successfullPublish", { nbNotes: noticeValue, repo }); | |
} else { | |
successMsg = instance.t("informations.successPublishOneNote", { file: noticeValue, repo }); | |
} | |
if (settings3.github.worflow.workflowName.length > 0) { | |
const msg = instance.t("informations.sendMessage", { nbNotes: noticeValue, repo }) + ".\n" + instance.t("informations.waitingWorkflow"); | |
new import_obsidian3.Notice(msg); | |
const successWorkflow = yield PublisherManager.workflowGestion(repo); | |
if (successWorkflow) { | |
new import_obsidian3.Notice(successMsg); | |
} | |
} else { | |
new import_obsidian3.Notice(successMsg); | |
} | |
}); | |
} | |
function trimObject(obj) { | |
const trimmed = JSON.stringify(obj, (key, value) => { | |
if (typeof value === "string") { | |
return value.trim().toLowerCase(); | |
} | |
return value; | |
}); | |
return JSON.parse(trimmed); | |
} | |
function getFrontmatterCondition(frontmatter, settings3) { | |
let imageDefaultFolder = null; | |
if (settings3.embed.folder.length > 0) { | |
imageDefaultFolder = settings3.embed.folder; | |
} else if (settings3.upload.defaultName.length > 0) { | |
imageDefaultFolder = settings3.upload.defaultName; | |
} | |
const settingsConversion = { | |
convertWiki: settings3.conversion.links.wiki, | |
attachment: settings3.embed.attachments, | |
embed: settings3.embed.notes, | |
attachmentLinks: imageDefaultFolder, | |
links: true, | |
removeEmbed: false, | |
dataview: settings3.conversion.dataview, | |
hardbreak: settings3.conversion.hardbreak, | |
convertInternalNonShared: settings3.conversion.links.unshared, | |
convertInternalLinks: settings3.conversion.links.internal | |
}; | |
if (frontmatter.links !== void 0) { | |
if (typeof frontmatter.links === "object") { | |
if (frontmatter.links.convert !== void 0) { | |
settingsConversion.links = frontmatter.links.convert; | |
} | |
if (frontmatter.links.internals !== void 0) { | |
settingsConversion.convertInternalLinks = frontmatter.links.internals; | |
} | |
if (frontmatter.links.mdlinks !== void 0) { | |
settingsConversion.convertWiki = frontmatter.links.mdlinks; | |
} | |
if (frontmatter.links.nonShared !== void 0) { | |
settingsConversion.convertInternalNonShared = frontmatter.links.nonShared; | |
} | |
} else { | |
settingsConversion.links = frontmatter.links; | |
} | |
} | |
if (frontmatter.embed !== void 0) { | |
if (typeof frontmatter.embed === "object") { | |
if (frontmatter.embed.send !== void 0) { | |
settingsConversion.embed = frontmatter.embed.send; | |
} | |
if (frontmatter.embed.remove !== void 0) { | |
settingsConversion.removeEmbed = frontmatter.embed.remove; | |
} | |
} else { | |
settingsConversion.embed = frontmatter.embed; | |
} | |
} | |
if (frontmatter.attachment !== void 0) { | |
if (typeof frontmatter.attachment === "object") { | |
if (frontmatter.attachment.send !== void 0) { | |
settingsConversion.attachment = frontmatter.attachment.send; | |
} | |
if (frontmatter.attachment.folder !== void 0) { | |
settingsConversion.attachmentLinks = frontmatter.attachment.folder; | |
} | |
} else { | |
settingsConversion.attachment = frontmatter.attachment; | |
} | |
} | |
if (frontmatter.attachmentLinks !== void 0) { | |
settingsConversion.attachmentLinks = frontmatter.attachmentLinks.toString().replace(/\/$/, ""); | |
} | |
if (frontmatter.mdlinks !== void 0) { | |
settingsConversion.convertWiki = frontmatter.mdlinks; | |
} | |
if (frontmatter.removeEmbed !== void 0) { | |
settingsConversion.removeEmbed = frontmatter.removeEmbed; | |
} | |
if (frontmatter.dataview !== void 0) { | |
settingsConversion.dataview = frontmatter.dataview; | |
} | |
if (frontmatter.hardbreak !== void 0) { | |
settingsConversion.hardbreak = frontmatter.hardbreak; | |
} | |
if (frontmatter.internals !== void 0) { | |
settingsConversion.convertInternalLinks = frontmatter.internals; | |
} | |
if (frontmatter.nonShared !== void 0) { | |
settingsConversion.convertInternalNonShared = frontmatter.nonShared; | |
} | |
return settingsConversion; | |
} | |
function getRepoFrontmatter(settings3, frontmatter) { | |
const github = settings3.github; | |
let repoFrontmatter = { | |
branch: github.branch, | |
repo: github.repo, | |
owner: github.user, | |
autoclean: settings3.upload.autoclean.enable | |
}; | |
if (settings3.upload.behavior === "fixed" /* fixed */) { | |
repoFrontmatter.autoclean = false; | |
} | |
if (!frontmatter || frontmatter.multipleRepo === void 0 && frontmatter.repo === void 0) { | |
return repoFrontmatter; | |
} | |
let isFrontmatterAutoClean = null; | |
if (frontmatter.multipleRepo) { | |
const multipleRepo = parseMultipleRepo(frontmatter, repoFrontmatter); | |
if (multipleRepo.length === 1) { | |
return multipleRepo[0]; | |
} | |
return multipleRepo; | |
} else if (frontmatter.repo) { | |
if (typeof frontmatter.repo === "object") { | |
if (frontmatter.repo.branch !== void 0) { | |
repoFrontmatter.branch = frontmatter.repo.branch; | |
} | |
if (frontmatter.repo.repo !== void 0) { | |
repoFrontmatter.repo = frontmatter.repo.repo; | |
} | |
if (frontmatter.repo.owner !== void 0) { | |
repoFrontmatter.owner = frontmatter.repo.owner; | |
} | |
if (frontmatter.repo.autoclean !== void 0) { | |
repoFrontmatter.autoclean = frontmatter.repo.autoclean; | |
isFrontmatterAutoClean = true; | |
} | |
} else { | |
const repo = frontmatter.repo.split("/"); | |
isFrontmatterAutoClean = repo.length > 4 ? true : null; | |
repoFrontmatter = repositoryStringSlice(repo, repoFrontmatter); | |
} | |
} | |
if (frontmatter.autoclean !== void 0 && isFrontmatterAutoClean === null) { | |
repoFrontmatter.autoclean = frontmatter.autoclean; | |
} | |
return repoFrontmatter; | |
} | |
function parseMultipleRepo(frontmatter, repoFrontmatter) { | |
const multipleRepo = []; | |
if (frontmatter.multipleRepo instanceof Array && frontmatter.multipleRepo.length > 0) { | |
for (const repo of frontmatter.multipleRepo) { | |
if (typeof repo === "object") { | |
const repository = { | |
branch: repoFrontmatter.branch, | |
repo: repoFrontmatter.repo, | |
owner: repoFrontmatter.owner, | |
autoclean: false | |
}; | |
if (repo.branch !== void 0) { | |
repository.branch = repo.branch; | |
} | |
if (repo.repo !== void 0) { | |
repository.repo = repo.repo; | |
} | |
if (repo.owner !== void 0) { | |
repository.owner = repo.owner; | |
} | |
if (repo.autoclean !== void 0) { | |
repository.autoclean = repo.autoclean; | |
} | |
multipleRepo.push(repository); | |
} else { | |
const repoString = repo.split("/"); | |
const repository = { | |
branch: repoFrontmatter.branch, | |
repo: repoFrontmatter.repo, | |
owner: repoFrontmatter.owner, | |
autoclean: false | |
}; | |
multipleRepo.push( | |
repositoryStringSlice(repoString, repository) | |
); | |
} | |
} | |
} | |
return multipleRepo.filter( | |
(v, i, a) => a.findIndex( | |
(t2) => t2.repo === v.repo && t2.owner === v.owner && t2.branch === v.branch && t2.autoclean === v.autoclean | |
) === i | |
); | |
} | |
function repositoryStringSlice(repo, repoFrontmatter) { | |
const newRepo = { | |
branch: repoFrontmatter.branch, | |
repo: repoFrontmatter.repo, | |
owner: repoFrontmatter.owner, | |
autoclean: false | |
}; | |
if (repo.length >= 4) { | |
newRepo.branch = repo[2]; | |
newRepo.repo = repo[1]; | |
newRepo.owner = repo[0]; | |
newRepo.autoclean = repo[3] === "true"; | |
} | |
if (repo.length === 3) { | |
newRepo.branch = repo[2]; | |
newRepo.repo = repo[1]; | |
newRepo.owner = repo[0]; | |
} else if (repo.length === 2) { | |
newRepo.repo = repo[1]; | |
newRepo.owner = repo[0]; | |
} else if (repo.length === 1) { | |
newRepo.repo = repo[0]; | |
} | |
return newRepo; | |
} | |
function getCategory(frontmatter, settings3) { | |
const key = settings3.upload.yamlFolderKey; | |
let category = frontmatter[key] !== void 0 ? frontmatter[key] : settings3.upload.defaultName; | |
if (category instanceof Array) { | |
category = category.join("/"); | |
} | |
return category; | |
} | |
// plugin/src/data_validation_test.ts | |
function isInternalShared(sharekey, frontmatter, frontmatterSettings) { | |
const shared = frontmatter && frontmatter[sharekey] ? frontmatter[sharekey] : false; | |
if (shared) | |
return true; | |
return !shared && frontmatterSettings.convertInternalNonShared === true; | |
} | |
function isShared(meta, settings3, file) { | |
if (!file || file.extension !== "md" || meta === null) { | |
return false; | |
} | |
const folderList = settings3.plugin.excludedFolder; | |
if (meta === void 0 || meta[settings3.plugin.shareKey] === void 0) { | |
return false; | |
} else if (folderList.length > 0) { | |
for (let i = 0; i < folderList.length; i++) { | |
const isRegex = folderList[i].match(/^\/(.*)\/[igmsuy]*$/); | |
const regex3 = isRegex ? new RegExp(isRegex[1], isRegex[2]) : null; | |
if (regex3 && regex3.test(file.path) || file.path.contains(folderList[i].trim())) { | |
return false; | |
} | |
} | |
} | |
return meta[settings3.plugin.shareKey]; | |
} | |
function isAttachment(filename) { | |
return filename.match( | |
/(png|jpe?g|gif|bmp|svg|mp[34]|web[mp]|wav|m4a|ogg|3gp|flac|ogv|mov|mkv|pdf)$/i | |
); | |
} | |
function checkIfRepoIsInAnother(source, target) { | |
source = source instanceof Array ? source : [source]; | |
target = target instanceof Array ? target : [target]; | |
const isSame = (source2, target2) => { | |
return source2.owner === target2.owner && source2.repo === target2.repo && source2.branch === target2.branch; | |
}; | |
for (const repoTarget of target) { | |
for (const repoSource of source) { | |
if (isSame(repoTarget, repoSource)) { | |
return true; | |
} | |
} | |
} | |
for (const sourceRepo of source) { | |
for (const targetRepo of target) { | |
if (isSame(sourceRepo, targetRepo)) { | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
function checkEmptyConfiguration(repoFrontmatter, settings3) { | |
repoFrontmatter = Array.isArray(repoFrontmatter) ? repoFrontmatter : [repoFrontmatter]; | |
const isEmpty = []; | |
if (settings3.github.token.length === 0) { | |
isEmpty.push(true); | |
const whatIsEmpty = instance.t("error.whatEmpty.ghToken"); | |
new import_obsidian4.Notice(instance.t("error.isEmpty", { what: whatIsEmpty })); | |
} | |
if (settings3.github.token.length != 0) { | |
for (const repo of repoFrontmatter) { | |
if (repo.repo.length === 0) { | |
isEmpty.push(true); | |
const whatIsEmpty = instance.t("error.whatEmpty.repo"); | |
new import_obsidian4.Notice(instance.t("error.isEmpty", { what: whatIsEmpty })); | |
} else if (repo.owner.length === 0) { | |
isEmpty.push(true); | |
const whatIsEmpty = instance.t("error.whatEmpty.owner"); | |
new import_obsidian4.Notice(instance.t("error.isEmpty", { what: whatIsEmpty })); | |
} else if (repo.branch.length === 0) { | |
isEmpty.push(true); | |
const whatIsEmpty = instance.t("error.whatEmpty.branch"); | |
new import_obsidian4.Notice(instance.t("error.isEmpty", { what: whatIsEmpty })); | |
} else { | |
isEmpty.push(false); | |
} | |
} | |
} | |
const allInvalid = isEmpty.every((value) => value === true); | |
return !allInvalid; | |
} | |
function noTextConversion(conditionConvert) { | |
const convertWikilink = conditionConvert.convertWiki; | |
const imageSettings = conditionConvert.attachment; | |
const embedSettings = conditionConvert.embed; | |
const convertLinks = conditionConvert.links; | |
return !convertWikilink && convertLinks && imageSettings && embedSettings && !conditionConvert.removeEmbed; | |
} | |
function checkRepositoryValidity(branchName, PublisherManager, settings3, file, metadataCache) { | |
return __async(this, null, function* () { | |
var _a; | |
try { | |
const frontmatter = file ? (_a = metadataCache.getFileCache(file)) == null ? void 0 : _a.frontmatter : null; | |
const repoFrontmatter = getRepoFrontmatter(settings3, frontmatter); | |
const isNotEmpty = checkEmptyConfiguration(repoFrontmatter, settings3); | |
if (isNotEmpty) { | |
yield PublisherManager.checkRepository(repoFrontmatter, false); | |
} | |
} catch (e) { | |
noticeLog(e, settings3); | |
} | |
}); | |
} | |
function checkRepositoryValidityWithRepoFrontmatter(PublisherManager, settings3, repoFrontmatter) { | |
return __async(this, null, function* () { | |
try { | |
const isNotEmpty = checkEmptyConfiguration(repoFrontmatter, settings3); | |
if (isNotEmpty) { | |
yield PublisherManager.checkRepository(repoFrontmatter, true); | |
return true; | |
} | |
} catch (e) { | |
noticeLog(e, settings3); | |
return false; | |
} | |
}); | |
} | |
// plugin/settings/modals/import_export.ts | |
var import_obsidian5 = require("obsidian"); | |
// plugin/settings/migrate.ts | |
function migrateSettings(old, plugin) { | |
return __async(this, null, function* () { | |
var _a, _b; | |
if (Object.keys(old).includes("editorMenu")) { | |
noticeLog(instance.t("informations.migrating.oldSettings"), plugin.settings); | |
plugin.settings = { | |
github: { | |
user: old.githubName ? old.githubName : plugin.settings.github.user ? plugin.settings.github.user : "", | |
repo: old.githubRepo ? old.githubRepo : plugin.settings.github.repo ? plugin.settings.github.repo : "", | |
token: old.GhToken ? old.GhToken : plugin.settings.github.token ? plugin.settings.github.token : "", | |
branch: old.githubBranch, | |
automaticallyMergePR: old.automaticallyMergePR, | |
api: { | |
tiersForApi: old.tiersForApi, | |
hostname: old.hostname | |
}, | |
worflow: { | |
workflowName: old.workflowName, | |
customCommitMsg: (_b = (_a = old.customCommitMsg) != null ? _a : plugin.settings.github.worflow.customCommitMsg) != null ? _b : "[PUBLISHER] MERGE" | |
} | |
}, | |
upload: { | |
behavior: old.downloadedFolder, | |
defaultName: old.folderDefaultName, | |
rootFolder: old.rootFolder, | |
yamlFolderKey: old.yamlFolderKey, | |
frontmatterTitle: { | |
enable: old.useFrontmatterTitle, | |
key: old.frontmatterTitleKey | |
}, | |
replaceTitle: [{ | |
regex: old.frontmatterTitleRegex, | |
replacement: old.frontmatterTitleReplacement, | |
type: "title" /* title */ | |
}], | |
replacePath: [ | |
{ | |
regex: old.subFolder, | |
replacement: "", | |
type: "path" /* path */ | |
} | |
], | |
autoclean: { | |
enable: old.autoCleanUp, | |
excluded: old.autoCleanUpExcluded | |
}, | |
folderNote: { | |
enable: old.folderNote, | |
rename: old.folderNoteRename | |
}, | |
metadataExtractorPath: old.metadataExtractorPath | |
}, | |
conversion: { | |
hardbreak: old.hardBreak, | |
dataview: old.convertDataview, | |
censorText: old.censorText, | |
tags: { | |
inline: old.inlineTags, | |
exclude: old.excludeDataviewValue, | |
fields: old.dataviewFields | |
}, | |
links: { | |
internal: old.convertForGithub, | |
unshared: old.convertInternalNonShared, | |
wiki: old.convertWikiLinks, | |
slugify: false | |
} | |
}, | |
embed: { | |
attachments: old.embedImage, | |
keySendFile: old.metadataFileFields, | |
notes: old.embedNotes, | |
folder: old.defaultImageFolder | |
}, | |
plugin: { | |
shareKey: old.shareKey, | |
fileMenu: old.fileMenu, | |
editorMenu: old.editorMenu, | |
excludedFolder: old.excludedFolder, | |
copyLink: { | |
enable: old.copyLink, | |
links: old.mainLink, | |
removePart: old.linkRemover.split(/[,\n]\W*/).map((s) => s.trim()), | |
addCmd: false | |
}, | |
noticeError: old.logNotice, | |
displayModalRepoEditing: false | |
} | |
}; | |
yield plugin.saveSettings(); | |
} | |
if (!(plugin.settings.upload.replaceTitle instanceof Array)) { | |
noticeLog(instance.t("informations.migrating.fileReplace"), plugin.settings); | |
plugin.settings.upload.replaceTitle = [plugin.settings.upload.replaceTitle]; | |
yield plugin.saveSettings(); | |
} | |
if (plugin.settings.upload.subFolder && !plugin.settings.upload.replacePath.find((e) => e.regex === "/" + plugin.settings.upload.subFolder)) { | |
noticeLog(instance.t("informations.migrating.subFolder"), plugin.settings); | |
if (plugin.settings.upload.subFolder.length > 0) { | |
plugin.settings.upload.replacePath.push({ | |
//@ts-ignore | |
regex: "/" + plugin.settings.upload.subFolder, | |
replacement: "", | |
type: "path" /* path */ | |
}); | |
} | |
delete plugin.settings.upload.subFolder; | |
yield plugin.saveSettings(); | |
} | |
for (const censor of plugin.settings.conversion.censorText) { | |
if (censor.flags) { | |
censor.entry = "/" + censor.entry + "/" + censor.flags; | |
delete censor.flags; | |
yield plugin.saveSettings(); | |
} | |
} | |
}); | |
} | |
// plugin/settings/modals/import_export.ts | |
function clone(obj) { | |
return JSON.parse(JSON.stringify(obj)); | |
} | |
var ImportModal = class extends import_obsidian5.Modal { | |
constructor(app2, plugin, settingsPage, settingsTab) { | |
super(app2); | |
this.plugin = plugin; | |
this.settingsPage = settingsPage; | |
this.settingsTab = settingsTab; | |
} | |
onOpen() { | |
const { contentEl } = this; | |
new import_obsidian5.Setting(contentEl).setName(instance.t("modals.import.title")).setDesc(instance.t("modals.import.desc")); | |
new import_obsidian5.Setting(contentEl).then((setting) => { | |
const errorSpan = createSpan({ | |
cls: "github-publisher-import-error", | |
text: instance.t("modals.import.error.span") | |
}); | |
setting.nameEl.appendChild(errorSpan); | |
const importAndClose = (str) => __async(this, null, function* () { | |
if (str) { | |
try { | |
let importedSettings = JSON.parse(str); | |
if (Object.keys(importedSettings).includes("editorMenu")) { | |
const oldSettings = importedSettings; | |
yield migrateSettings(oldSettings, this.plugin); | |
noticeLog(instance.t("informations.migrating.oldSettings"), this.plugin.settings); | |
} else { | |
noticeLog(instance.t("informations.migrating.normalFormat"), this.plugin.settings); | |
importedSettings = importedSettings; | |
const actualSettings = clone(this.plugin.settings); | |
if (!(importedSettings.upload.replaceTitle instanceof Array)) { | |
importedSettings.upload.replaceTitle = [importedSettings.upload.replaceTitle]; | |
} | |
for (const [key, value] of Object.entries(importedSettings)) { | |
this.plugin.settings[key] = value; | |
} | |
this.plugin.settings.plugin = actualSettings.plugin; | |
this.plugin.settings.github.repo = actualSettings.github.repo; | |
this.plugin.settings.github.token = actualSettings.github.token; | |
this.plugin.settings.github.user = actualSettings.github.user; | |
yield this.plugin.saveSettings(); | |
} | |
this.close(); | |
} catch (e) { | |
errorSpan.addClass("active"); | |
errorSpan.setText(`${instance.t("modals.import.error.span")}${e}`); | |
} | |
} else { | |
errorSpan.addClass("active"); | |
errorSpan.setText(`${instance.t("modals.import.error.span")}: ${instance.t("modals.import.error.isEmpty")}`); | |
} | |
}); | |
setting.controlEl.createEl( | |
"input", | |
{ | |
cls: "github-publisher-import-input", | |
attr: { | |
id: "github-publisher-import-input", | |
name: "github-publisher-import-input", | |
type: "file", | |
accept: ".json" | |
} | |
}, | |
(importInput) => { | |
importInput.addEventListener("change", (e) => { | |
const reader = new FileReader(); | |
reader.onload = (e2) => __async(this, null, function* () { | |
yield importAndClose(e2.target.result.toString().trim()); | |
}); | |
reader.readAsText(e.target.files[0]); | |
}); | |
} | |
); | |
setting.controlEl.createEl("label", { | |
cls: "github-publisher-import-label", | |
text: instance.t("modals.import.importFromFile"), | |
attr: { | |
for: "github-publisher-import-input" | |
} | |
}); | |
const textArea = new import_obsidian5.TextAreaComponent(contentEl).setPlaceholder(instance.t("modals.import.paste")).then((ta) => { | |
const saveButton = new import_obsidian5.ButtonComponent(contentEl).setButtonText(instance.t("common.save")).onClick(() => __async(this, null, function* () { | |
yield importAndClose(ta.getValue().trim()); | |
})); | |
saveButton.buttonEl.addClass("github-publisher-import-save-button"); | |
}); | |
textArea.inputEl.addClass("github-publisher-import-textarea"); | |
}); | |
} | |
onClose() { | |
const { contentEl } = this; | |
contentEl.empty(); | |
this.settingsPage.empty(); | |
let openedTab = document.querySelector(".settings-tab-active.github-publisher") ? document.querySelector(".settings-tab-active.github-publisher").innerText : instance.t("settings.github.title"); | |
openedTab = openedTab.trim(); | |
switch (openedTab) { | |
case instance.t("settings.github.title"): | |
this.settingsTab.renderGithubConfiguration(); | |
break; | |
case instance.t("settings.upload.title"): | |
this.settingsTab.renderUploadConfiguration(); | |
break; | |
case instance.t("settings.conversion.title"): | |
this.settingsTab.renderTextConversion(); | |
break; | |
case instance.t("settings.embed.title"): | |
this.settingsTab.renderEmbedConfiguration(); | |
break; | |
case instance.t("settings.plugin.title"): | |
this.settingsTab.renderPluginSettings(); | |
break; | |
case instance.t("settings.help.title"): | |
this.settingsTab.renderHelp(); | |
break; | |
} | |
} | |
}; | |
var ExportModal = class extends import_obsidian5.Modal { | |
constructor(app2, plugin) { | |
super(app2); | |
this.plugin = plugin; | |
} | |
onOpen() { | |
const { contentEl, modalEl } = this; | |
modalEl.addClass("modal-github-publisher"); | |
new import_obsidian5.Setting(contentEl).setName(instance.t("modals.export.title")).setDesc(instance.t("modals.export.desc")).then((setting) => { | |
const censuredSettings = clone(this.plugin.settings); | |
delete censuredSettings.github.repo; | |
delete censuredSettings.github.token; | |
delete censuredSettings.github.user; | |
delete censuredSettings.plugin; | |
const output2 = JSON.stringify(censuredSettings, null, 2); | |
setting.controlEl.createEl( | |
"a", | |
{ | |
cls: "github-publisher-copy", | |
text: instance.t("modals.export.copy"), | |
href: "#" | |
}, | |
(copyButton) => { | |
const textArea = new import_obsidian5.TextAreaComponent(contentEl).setValue(output2).then((textarea) => { | |
copyButton.addEventListener("click", (e) => { | |
e.preventDefault(); | |
textarea.inputEl.select(); | |
textarea.inputEl.setSelectionRange(0, 99999); | |
document.execCommand("copy"); | |
copyButton.addClass("success"); | |
setTimeout(() => { | |
if (copyButton.parentNode) { | |
copyButton.removeClass("success"); | |
} | |
}, 2e3); | |
}); | |
}); | |
textArea.inputEl.addClass("github-publisher-export-textarea"); | |
} | |
); | |
if (import_obsidian5.Platform.isDesktop) { | |
setting.controlEl.createEl("a", { | |
cls: "github-publisher-download", | |
text: instance.t("modals.export.download"), | |
attr: { | |
download: "github-publisher.json", | |
href: `data:application/json;charset=utf-8,${encodeURIComponent(output2)}` | |
} | |
}); | |
} else if (import_obsidian5.Platform.isMobile) { | |
setting.addButton((b) => b.setButtonText(instance.t("modals.export.download")).onClick(() => { | |
this.app.vault.adapter.write(`${app.vault.configDir}/plugins/obsidian-mkdocs-publisher/._tempSettings.json`, output2); | |
this.app.openWithDefaultApp(`${app.vault.configDir}/plugins/obsidian-mkdocs-publisher/._tempSettings.json`); | |
})); | |
} | |
}); | |
} | |
onClose() { | |
try { | |
this.app.vault.adapter.trashSystem(`${app.vault.configDir}/plugins/obsidian-mkdocs-publisher/._tempSettings.json`); | |
} catch (e) { | |
} | |
const { contentEl } = this; | |
contentEl.empty(); | |
} | |
}; | |
// plugin/settings.ts | |
var GithubPublisherSettingsTab = class extends import_obsidian6.PluginSettingTab { | |
constructor(app2, plugin, branchName) { | |
super(app2, plugin); | |
this.plugin = plugin; | |
this.branchName = branchName; | |
} | |
display() { | |
const { containerEl } = this; | |
containerEl.empty(); | |
const PUBLISHER_TABS = { | |
"github-configuration": { | |
name: instance.t("settings.github.title"), | |
icon: "cloud" | |
}, | |
"upload-configuration": { | |
name: instance.t("settings.upload.title"), | |
icon: "upload" | |
}, | |
"text-conversion": { | |
name: instance.t("settings.conversion.title"), | |
icon: "file-text" | |
}, | |
"embed-configuration": { | |
name: instance.t("settings.embed.title"), | |
icon: "link" | |
}, | |
"plugin-settings": { | |
name: instance.t("settings.plugin.title"), | |
icon: "gear" | |
}, | |
"help": { | |
name: instance.t("settings.help.title"), | |
icon: "info" | |
} | |
}; | |
new import_obsidian6.Setting(containerEl).setClass("github-publisher-export-import").addButton( | |
(button) => { | |
button.setButtonText(instance.t("modals.export.title")).setClass("github-publisher-export").onClick(() => { | |
new ExportModal(this.app, this.plugin).open(); | |
}); | |
} | |
).addButton((button) => { | |
button.setButtonText(instance.t("modals.import.title")).setClass("github-publisher-import").onClick(() => { | |
new ImportModal(this.app, this.plugin, this.settingsPage, this).open(); | |
}); | |
}); | |
const tabBar = containerEl.createEl("nav", { | |
cls: "settings-tab-bar github-publisher" | |
}); | |
for (const [tabID, tabInfo] of Object.entries(PUBLISHER_TABS)) { | |
const tabEl = tabBar.createEl("div", { | |
cls: "settings-tab github-publisher" | |
}); | |
const tabIcon = tabEl.createEl("div", { | |
cls: "settings-tab-icon github-publisher" | |
}); | |
(0, import_obsidian6.setIcon)(tabIcon, tabInfo.icon); | |
tabEl.createEl("div", { | |
cls: "settings-tab-name github-publisher", | |
text: tabInfo.name | |
}); | |
if (tabID === "github-configuration") | |
tabEl.addClass("settings-tab-active"); | |
tabEl.addEventListener("click", () => { | |
for (const tabEl2 of tabBar.children) | |
tabEl2.removeClass("settings-tab-active"); | |
tabEl.addClass("settings-tab-active"); | |
this.renderSettingsPage(tabID); | |
}); | |
} | |
this.settingsPage = containerEl.createEl("div", { | |
cls: "settings-tab-page github-publisher" | |
}); | |
this.renderSettingsPage("github-configuration"); | |
} | |
renderSettingsPage(tabId) { | |
this.settingsPage.empty(); | |
switch (tabId) { | |
case "github-configuration": | |
this.renderGithubConfiguration(); | |
break; | |
case "upload-configuration": | |
this.renderUploadConfiguration(); | |
break; | |
case "text-conversion": | |
this.renderTextConversion(); | |
break; | |
case "embed-configuration": | |
this.renderEmbedConfiguration(); | |
break; | |
case "plugin-settings": | |
this.renderPluginSettings(); | |
break; | |
case "help": | |
this.renderHelp(); | |
break; | |
} | |
} | |
renderGithubConfiguration() { | |
const githubSettings = this.plugin.settings.github; | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.github.apiType.title")).setDesc(instance.t("settings.github.apiType.desc")).addDropdown((dropdown) => { | |
dropdown.addOption("Github Free/Pro/Team (default)" /* free */, instance.t("settings.github.apiType.dropdown.free")).addOption("Enterprise" /* entreprise */, instance.t("settings.github.apiType.dropdown.enterprise")).setValue(githubSettings.api.tiersForApi).onChange((value) => __async(this, null, function* () { | |
githubSettings.api.tiersForApi = value; | |
yield this.plugin.saveSettings(); | |
this.renderSettingsPage("github-configuration" /* github */); | |
})); | |
}); | |
if (githubSettings.api.tiersForApi === "Enterprise" /* entreprise */) { | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.github.apiType.hostname.title")).setDesc(instance.t("settings.github.apiType.hostname.desc")).addText( | |
(text) => text.setPlaceholder("https://github.mycompany.com").setValue(githubSettings.api.hostname).onChange((value) => __async(this, null, function* () { | |
githubSettings.api.hostname = value.trim(); | |
yield this.plugin.saveSettings(); | |
})) | |
); | |
} | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.github.repoName.title")).setDesc(instance.t("settings.github.repoName.desc")).addText( | |
(text) => text.setPlaceholder(instance.t("settings.github.repoName.placeholder")).setValue(githubSettings.repo).onChange((value) => __async(this, null, function* () { | |
githubSettings.repo = value.trim(); | |
yield this.plugin.saveSettings(); | |
})) | |
); | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.github.username.title")).setDesc(instance.t("settings.github.username.desc")).addText( | |
(text) => text.setPlaceholder( | |
instance.t("settings.github.username.title") | |
).setValue(githubSettings.user).onChange((value) => __async(this, null, function* () { | |
githubSettings.user = value.trim(); | |
yield this.plugin.saveSettings(); | |
})) | |
); | |
const desc_ghToken = document.createDocumentFragment(); | |
desc_ghToken.createEl("span", null, (span) => { | |
span.innerText = instance.t("settings.github.ghToken.desc"); | |
span.createEl("a", null, (link) => { | |
link.innerText = instance.t("common.here"); | |
link.href = "https://github.com/settings/tokens/new?scopes=repo,workflow"; | |
}); | |
}); | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.github.ghToken.title")).setDesc(desc_ghToken).addText( | |
(text) => text.setPlaceholder("ghb-15457498545647987987112184").setValue(githubSettings.token).onChange((value) => __async(this, null, function* () { | |
githubSettings.token = value.trim(); | |
yield this.plugin.saveSettings(); | |
})) | |
); | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.github.branch.title")).setDesc(instance.t("settings.github.branch.desc")).addText( | |
(text) => text.setPlaceholder("main").setValue(githubSettings.branch).onChange((value) => __async(this, null, function* () { | |
githubSettings.branch = value.trim(); | |
yield this.plugin.saveSettings(); | |
})) | |
); | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.github.automaticallyMergePR")).addToggle( | |
(toggle) => toggle.setValue(githubSettings.automaticallyMergePR).onChange((value) => __async(this, null, function* () { | |
githubSettings.automaticallyMergePR = value; | |
yield this.plugin.saveSettings(); | |
})) | |
); | |
new import_obsidian6.Setting(this.settingsPage).setClass("github-publisher-no-display").addButton( | |
(button) => button.setButtonText(instance.t("settings.github.testConnection")).setClass("github-publisher-connect-button").onClick(() => __async(this, null, function* () { | |
yield checkRepositoryValidity(this.branchName, this.plugin.reloadOctokit(), this.plugin.settings, null, this.app.metadataCache); | |
})) | |
); | |
this.settingsPage.createEl("h3", { text: "Github Workflow" }); | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.githubWorkflow.prRequest.title")).setDesc(instance.t("settings.githubWorkflow.prRequest.desc")).addText( | |
(text) => text.setPlaceholder("[PUBLISHER] MERGE").setValue(githubSettings.worflow.customCommitMsg).onChange((value) => __async(this, null, function* () { | |
if (value.trim().length === 0) { | |
value = "[PUBLISHER] MERGE"; | |
new import_obsidian6.Notice(instance.t("settings.githubWorkflow.prRequest.error")); | |
} | |
githubSettings.worflow.customCommitMsg = value; | |
yield this.plugin.saveSettings(); | |
})) | |
); | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.githubWorkflow.githubAction.title")).setDesc( | |
instance.t("settings.githubWorkflow.githubAction.desc") | |
).addText((text) => { | |
text.setPlaceholder("ci").setValue(githubSettings.worflow.workflowName).onChange((value) => __async(this, null, function* () { | |
if (value.length > 0) { | |
value = value.trim(); | |
const yamlEndings = [".yml", ".yaml"]; | |
if (!yamlEndings.some((ending) => value.endsWith(ending))) { | |
value += yamlEndings[0]; | |
} | |
} | |
githubSettings.worflow.workflowName = value; | |
yield this.plugin.saveSettings(); | |
})); | |
}); | |
} | |
renderUploadConfiguration() { | |
const uploadSettings = this.plugin.settings.upload; | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.upload.folderBehavior.title")).setDesc(instance.t("settings.upload.folderBehavior.desc")).addDropdown((dropDown) => { | |
dropDown.addOptions({ | |
fixed: instance.t( | |
"settings.upload.folderBehavior.fixedFolder" | |
), | |
yaml: instance.t("settings.upload.folderBehavior.yaml"), | |
obsidian: instance.t( | |
"settings.upload.folderBehavior.obsidianPath" | |
) | |
}).setValue(uploadSettings.behavior).onChange((value) => __async(this, null, function* () { | |
uploadSettings.behavior = value; | |
yield folderHideShowSettings( | |
frontmatterKeySettings, | |
rootFolderSettings, | |
autoCleanSetting, | |
value, | |
this.plugin | |
); | |
yield this.plugin.saveSettings(); | |
this.renderSettingsPage("upload-configuration" /* upload */); | |
})); | |
}); | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.upload.defaultFolder.title")).setDesc(instance.t("settings.upload.defaultFolder.desc")).addText((text) => { | |
text.setPlaceholder(instance.t("settings.upload.defaultFolder.placeholder")).setValue(uploadSettings.defaultName).onChange((value) => __async(this, null, function* () { | |
uploadSettings.defaultName = value.replace( | |
/\/$/, | |
"" | |
); | |
yield autoCleanCondition( | |
value, | |
autoCleanSetting, | |
this.plugin | |
); | |
yield this.plugin.saveSettings(); | |
})); | |
}); | |
const frontmatterKeySettings = new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.upload.frontmatterKey.title")).setClass("github-publisher").setDesc(instance.t("settings.upload.frontmatterKey.desc")).addText((text) => { | |
text.setPlaceholder(instance.t("settings.upload.frontmatterKey.placeholder")).setValue(uploadSettings.yamlFolderKey).onChange((value) => __async(this, null, function* () { | |
uploadSettings.yamlFolderKey = value.trim(); | |
yield this.plugin.saveSettings(); | |
})); | |
}); | |
const rootFolderSettings = new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.upload.rootFolder.title")).setClass("github-publisher").setDesc(instance.t("settings.upload.rootFolder.desc")).addText((text) => { | |
text.setPlaceholder("docs").setValue(uploadSettings.rootFolder).onChange((value) => __async(this, null, function* () { | |
uploadSettings.rootFolder = value.replace( | |
/\/$/, | |
"" | |
); | |
yield autoCleanCondition( | |
value, | |
autoCleanSetting, | |
this.plugin | |
); | |
yield this.plugin.saveSettings(); | |
})); | |
}); | |
const frontmatterTitleSet = new import_obsidian6.Setting(this.settingsPage).setName( | |
instance.t("settings.upload.useFrontmatterTitle.title") | |
).setDesc( | |
instance.t("settings.upload.useFrontmatterTitle.desc") | |
).setClass("github-publisher-title").addToggle((toggle) => { | |
toggle.setValue(uploadSettings.frontmatterTitle.enable).onChange((value) => __async(this, null, function* () { | |
uploadSettings.frontmatterTitle.enable = value; | |
yield this.plugin.saveSettings(); | |
this.renderSettingsPage("upload-configuration" /* upload */); | |
})); | |
}); | |
if (uploadSettings.frontmatterTitle.enable) { | |
frontmatterTitleSet.addText((text) => { | |
text.setPlaceholder("title").setValue(uploadSettings.frontmatterTitle.key).onChange((value) => __async(this, null, function* () { | |
uploadSettings.frontmatterTitle.key = value.trim(); | |
yield this.plugin.saveSettings(); | |
})); | |
}); | |
} | |
let desc = instance.t("settings.upload.regexFilePathTitle.title.FolderPathTitle"); | |
if (uploadSettings.behavior === "fixed" /* fixed */) { | |
desc = instance.t("settings.upload.regexFilePathTitle.title.titleOnly"); | |
} | |
new import_obsidian6.Setting(this.settingsPage).setName(desc).setDesc( | |
instance.t("settings.upload.regexFilePathTitle.desc") | |
).addButton((button) => { | |
button.setIcon("pencil").onClick(() => __async(this, null, function* () { | |
let allRegex = uploadSettings.replaceTitle; | |
if (uploadSettings.behavior !== "fixed" /* fixed */) { | |
allRegex = allRegex.concat(uploadSettings.replacePath); | |
} | |
new ModalRegexFilePathName(this.app, this.plugin.settings, allRegex, (result) => { | |
uploadSettings.replacePath = result.filter((title) => { | |
return title.type === "path"; | |
}); | |
uploadSettings.replaceTitle = result.filter((title) => { | |
return title.type === "title"; | |
}); | |
this.plugin.saveSettings(); | |
}).open(); | |
})); | |
}); | |
const folderNoteSettings = new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.conversion.links.folderNote.title")).setClass("github-publisher-folderNote").setDesc( | |
instance.t("settings.conversion.links.folderNote.desc") | |
).addToggle((toggle) => { | |
toggle.setValue(uploadSettings.folderNote.enable).onChange((value) => __async(this, null, function* () { | |
uploadSettings.folderNote.enable = value; | |
yield this.plugin.saveSettings(); | |
this.renderSettingsPage("upload-configuration"); | |
})); | |
}); | |
if (uploadSettings.folderNote.enable) { | |
folderNoteSettings.addText((text) => { | |
text.setPlaceholder("folderNote").setValue(uploadSettings.folderNote.rename).onChange((value) => __async(this, null, function* () { | |
uploadSettings.folderNote.rename = value; | |
yield this.plugin.saveSettings(); | |
})); | |
}); | |
} | |
showHideBasedOnFolder(this.plugin.settings, frontmatterKeySettings, rootFolderSettings, folderNoteSettings); | |
if (app.plugins.enabledPlugins.has("metadata-extractor")) { | |
new import_obsidian6.Setting(this.settingsPage).setName( | |
instance.t("settings.githubWorkflow.useMetadataExtractor.title") | |
).setDesc( | |
instance.t("settings.githubWorkflow.useMetadataExtractor.desc") | |
).addText((text) => { | |
text.setPlaceholder("docs/_assets/metadata").setValue(uploadSettings.metadataExtractorPath).onChange((value) => __async(this, null, function* () { | |
uploadSettings.metadataExtractorPath = value.trim(); | |
yield this.plugin.saveSettings(); | |
})); | |
}); | |
} | |
const condition = uploadSettings.behavior === "yaml" /* yaml */ && uploadSettings.rootFolder.length === 0 || uploadSettings.defaultName.length === 0; | |
const autoCleanSetting = new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.githubWorkflow.autoCleanUp.title")).setDesc(instance.t("settings.githubWorkflow.autoCleanUp.desc")).setDisabled(condition).addToggle((toggle) => { | |
toggle.setValue(uploadSettings.autoclean.enable).onChange((value) => __async(this, null, function* () { | |
uploadSettings.autoclean.enable = value; | |
yield this.plugin.saveSettings(); | |
this.renderSettingsPage("upload-configuration" /* upload */); | |
})); | |
}); | |
if (uploadSettings.autoclean.enable) { | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.githubWorkflow.excludedFiles.title")).setDesc(instance.t("settings.githubWorkflow.excludedFiles.desc")).setClass("github-publisher-textarea").addTextArea((textArea) => { | |
textArea.setPlaceholder( | |
"docs/assets/js, docs/assets/logo, /\\.js$/" | |
).setValue( | |
uploadSettings.autoclean.excluded.join(", ") | |
).onChange((value) => __async(this, null, function* () { | |
uploadSettings.autoclean.excluded = value.split(/[,\n]\W*/).map((item) => item.trim()).filter((item) => item.length > 0); | |
yield this.plugin.saveSettings(); | |
})); | |
}); | |
} | |
autoCleanUpSettingsOnCondition( | |
condition, | |
autoCleanSetting, | |
this.plugin | |
); | |
folderHideShowSettings( | |
frontmatterKeySettings, | |
rootFolderSettings, | |
autoCleanSetting, | |
uploadSettings.behavior, | |
this.plugin | |
); | |
} | |
renderTextConversion() { | |
const textSettings = this.plugin.settings.conversion; | |
this.settingsPage.createEl("p", { | |
text: instance.t("settings.conversion.desc") | |
}); | |
this.settingsPage.createEl("h5", { | |
text: instance.t("settings.conversion.sectionTitle") | |
}); | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.conversion.hardBreak.title")).setDesc(instance.t("settings.conversion.hardBreak.desc")).addToggle((toggle) => { | |
toggle.setValue(textSettings.hardbreak).onChange((value) => __async(this, null, function* () { | |
textSettings.hardbreak = value; | |
yield this.plugin.saveSettings(); | |
})); | |
}); | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.conversion.dataview.title")).setDesc(instance.t("settings.conversion.dataview.desc")).addToggle((toggle) => { | |
toggle.setValue(textSettings.dataview).onChange((value) => __async(this, null, function* () { | |
textSettings.dataview = value; | |
yield this.plugin.saveSettings(); | |
})); | |
}); | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.regexReplacing.modal.title.text")).setDesc(instance.t("settings.regexReplacing.modal.desc")).addButton((button) => { | |
button.setIcon("pencil").onClick(() => __async(this, null, function* () { | |
new ModalRegexOnContents(this.app, this.plugin.settings, (result) => { | |
this.plugin.settings.conversion.censorText = result.conversion.censorText; | |
this.plugin.saveSettings(); | |
}).open(); | |
})); | |
}); | |
this.settingsPage.createEl("h5", { text: "Tags" }); | |
new import_obsidian6.Setting(this.settingsPage).setName( | |
instance.t("settings.conversion.tags.inlineTags.title") | |
).setDesc( | |
instance.t("settings.conversion.tags.inlineTags.desc") | |
).addToggle((toggle) => { | |
toggle.setValue(textSettings.tags.inline).onChange((value) => __async(this, null, function* () { | |
textSettings.tags.inline = value; | |
yield this.plugin.saveSettings(); | |
})); | |
}); | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.conversion.tags.title")).setDesc(instance.t("settings.conversion.tags.desc")).setClass("github-publisher-textarea").addTextArea((text) => { | |
text.inputEl.style.width = "50%"; | |
text.setPlaceholder("field_name").setValue(textSettings.tags.fields.join(",")).onChange((value) => __async(this, null, function* () { | |
textSettings.tags.fields = value.split(/[,\n]\W*/).map((item) => item.trim()).filter((item) => item.length > 0); | |
yield this.plugin.saveSettings(); | |
})); | |
}); | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.conversion.tags.exclude.title")).setDesc(instance.t("settings.conversion.tags.exclude.desc")).setClass("github-publisher-textarea").addTextArea((text) => { | |
text.setPlaceholder("field value").setValue( | |
textSettings.tags.exclude.join(",") | |
).onChange((value) => __async(this, null, function* () { | |
textSettings.tags.exclude = value.split(/[,\n]\W*/).map((item) => item.trim()).filter((item) => item.length > 0); | |
yield this.plugin.saveSettings(); | |
})); | |
}); | |
this.settingsPage.createEl("h5", { | |
text: instance.t("settings.conversion.links.title") | |
}); | |
this.settingsPage.createEl("p", { | |
text: instance.t("settings.conversion.links.desc") | |
}); | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.conversion.links.internals.title")).setDesc( | |
instance.t("settings.conversion.links.internals.desc") | |
).addToggle((toggle) => { | |
toggle.setValue(textSettings.links.internal).onChange((value) => __async(this, null, function* () { | |
textSettings.links.internal = value; | |
yield this.plugin.saveSettings(); | |
this.renderSettingsPage("text-conversion"); | |
})); | |
}); | |
if (textSettings.links.internal) { | |
new import_obsidian6.Setting(this.settingsPage).setName( | |
instance.t("settings.conversion.links.nonShared.title") | |
).setDesc( | |
instance.t("settings.conversion.links.nonShared.desc") | |
).addToggle((toggle) => { | |
toggle.setValue(textSettings.links.unshared).onChange((value) => __async(this, null, function* () { | |
textSettings.links.unshared = value; | |
yield this.plugin.saveSettings(); | |
})); | |
}); | |
} | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.conversion.links.wikilinks.title")).setDesc( | |
instance.t("settings.conversion.links.wikilinks.desc") | |
).addToggle((toggle) => { | |
toggle.setValue(textSettings.links.wiki).onChange((value) => __async(this, null, function* () { | |
textSettings.links.wiki = value; | |
yield this.plugin.saveSettings(); | |
this.renderSettingsPage("text-conversion"); | |
})); | |
}); | |
if (textSettings.links.wiki || textSettings.links.internal) { | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.conversion.links.slugify.title")).setDesc(instance.t("settings.conversion.links.slugify.desc")).addToggle((toggle) => { | |
toggle.setValue(textSettings.links.slugify).onChange((value) => __async(this, null, function* () { | |
textSettings.links.slugify = value; | |
yield this.plugin.saveSettings(); | |
})); | |
}); | |
} | |
} | |
renderEmbedConfiguration() { | |
const embedSettings = this.plugin.settings.embed; | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.embed.transferImage.title")).setDesc(instance.t("settings.embed.transferImage.desc")).addToggle((toggle) => { | |
toggle.setValue(embedSettings.attachments).onChange((value) => __async(this, null, function* () { | |
embedSettings.attachments = value; | |
shortcutsHideShow(value, settingsDefaultImage); | |
yield this.plugin.saveSettings(); | |
})); | |
}); | |
const settingsDefaultImage = new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.embed.defaultImageFolder.title")).setDesc(instance.t("settings.embed.defaultImageFolder.desc")).addText((text) => { | |
text.setPlaceholder("docs/images").setValue(embedSettings.folder).onChange((value) => __async(this, null, function* () { | |
embedSettings.folder = value.replace( | |
/\/$/, | |
"" | |
); | |
yield this.plugin.saveSettings(); | |
})); | |
}); | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.embed.transferMetaFile.title")).setDesc(instance.t("settings.embed.transferMetaFile.desc")).setClass("github-publisher-textarea").addTextArea((text) => { | |
text.setPlaceholder("banner").setValue( | |
embedSettings.keySendFile.join(", ") | |
).onChange((value) => __async(this, null, function* () { | |
embedSettings.keySendFile = value.split(/[,\n]\W*/).map((item) => item.trim()).filter((item) => item.length > 0); | |
yield this.plugin.saveSettings(); | |
})); | |
}); | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.embed.transferNotes.title")).setDesc(instance.t("settings.embed.transferNotes.desc")).addToggle((toggle) => { | |
toggle.setValue(embedSettings.notes).onChange((value) => __async(this, null, function* () { | |
embedSettings.notes = value; | |
yield this.plugin.saveSettings(); | |
})); | |
}); | |
} | |
renderPluginSettings() { | |
const pluginSettings = this.plugin.settings.plugin; | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.plugin.shareKey.title")).setDesc(instance.t("settings.plugin.shareKey.desc")).addText( | |
(text) => text.setPlaceholder("share").setValue(pluginSettings.shareKey).onChange((value) => __async(this, null, function* () { | |
pluginSettings.shareKey = value.trim(); | |
yield this.plugin.saveSettings(); | |
})) | |
); | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.plugin.excludedFolder.title")).setDesc(instance.t("settings.plugin.excludedFolder.desc")).setClass("github-publisher-textarea").addTextArea( | |
(textArea) => textArea.setPlaceholder("_assets, Archive, /^_(.*)/gi").setValue(pluginSettings.excludedFolder.join(", ")).onChange((value) => __async(this, null, function* () { | |
pluginSettings.excludedFolder = value.split(/[,\n]\W*/).map((item) => item.trim()).filter((item) => item.length > 0); | |
yield this.plugin.saveSettings(); | |
})) | |
); | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.plugin.fileMenu.title")).setDesc(instance.t("settings.plugin.fileMenu.desc")).addToggle( | |
(toggle) => toggle.setValue(pluginSettings.fileMenu).onChange((value) => __async(this, null, function* () { | |
pluginSettings.fileMenu = value; | |
yield this.plugin.saveSettings(); | |
})) | |
); | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.plugin.editorMenu.title")).setDesc(instance.t("settings.plugin.editorMenu.desc")).addToggle( | |
(toggle) => toggle.setValue(pluginSettings.editorMenu).onChange((value) => __async(this, null, function* () { | |
pluginSettings.editorMenu = value; | |
yield this.plugin.saveSettings(); | |
})) | |
); | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.plugin.copyLink.title")).setDesc(instance.t("settings.plugin.copyLink.desc")).addToggle( | |
(toggle) => toggle.setValue(pluginSettings.copyLink.enable).onChange((value) => __async(this, null, function* () { | |
pluginSettings.copyLink.enable = value; | |
yield this.plugin.saveSettings(); | |
this.renderSettingsPage("plugin-settings" /* plugin */); | |
})) | |
); | |
if (pluginSettings.copyLink.enable) { | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.plugin.copyLink.baselink.title")).setDesc(instance.t("settings.plugin.copyLink.baselink.desc")).setClass("github-publisher").addText((text) => { | |
text.setPlaceholder("my_blog.com").setValue(pluginSettings.copyLink.links).onChange((value) => __async(this, null, function* () { | |
pluginSettings.copyLink.links = value; | |
yield this.plugin.saveSettings(); | |
})); | |
}); | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.plugin.copyLink.linkpathremover.title")).setDesc( | |
instance.t("settings.plugin.copyLink.linkpathremover.desc") | |
).setClass("github-publisher").addText((text) => { | |
text.setPlaceholder("docs").setValue(pluginSettings.copyLink.removePart.join(", ")).onChange((value) => __async(this, null, function* () { | |
pluginSettings.copyLink.removePart = value.split(/[,\n]\s*/).map((item) => item.trim()).filter((item) => item.length > 0); | |
yield this.plugin.saveSettings(); | |
})); | |
}); | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.plugin.copyLink.command.desc")).addToggle( | |
(toggle) => toggle.setValue(pluginSettings.copyLink.addCmd).onChange((value) => __async(this, null, function* () { | |
pluginSettings.copyLink.addCmd = value; | |
yield this.plugin.saveSettings(); | |
})) | |
); | |
} | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.plugin.logNoticeHeader.title")).setDesc(instance.t("settings.plugin.logNoticeHeader.desc")).addToggle( | |
(toggle) => toggle.setValue(pluginSettings.noticeError).onChange((value) => __async(this, null, function* () { | |
pluginSettings.noticeError = value; | |
yield this.plugin.saveSettings(); | |
})) | |
); | |
new import_obsidian6.Setting(this.settingsPage).setName(instance.t("settings.plugin.embedEditRepo.title")).setDesc(instance.t("settings.plugin.embedEditRepo.desc")).addToggle( | |
(toggle) => toggle.setValue(pluginSettings.displayModalRepoEditing).onChange((value) => __async(this, null, function* () { | |
pluginSettings.displayModalRepoEditing = value; | |
yield this.plugin.saveSettings(); | |
})) | |
); | |
} | |
renderHelp() { | |
this.settingsPage.createEl("h2", { | |
text: instance.t("settings.help.usefulLinks.title") | |
}); | |
this.settingsPage.appendChild(usefullLinks()); | |
this.settingsPage.createEl("hr"); | |
this.settingsPage.createEl("h2", { | |
text: instance.t("settings.help.frontmatter.title") | |
}); | |
this.settingsPage.createEl("p", { | |
text: instance.t("settings.help.frontmatter.desc") | |
}); | |
this.settingsPage.createEl("pre", { cls: "language-yaml" }).createEl("code", { | |
text: KeyBasedOnSettings(this.plugin.settings), | |
cls: "language-yaml" | |
}); | |
this.settingsPage.appendChild(help(this.plugin.settings)); | |
this.settingsPage.createEl("h2", { | |
text: instance.t("settings.help.multiRepoHelp.title") | |
}); | |
this.settingsPage.appendChild( | |
multipleRepoExplained(this.plugin.settings) | |
); | |
this.settingsPage.appendChild(supportMe()); | |
} | |
}; | |
// plugin/publish/files.ts | |
var import_obsidian10 = require("obsidian"); | |
// plugin/publish/upload.ts | |
var import_obsidian9 = require("obsidian"); | |
// node_modules/js-base64/base64.mjs | |
var version = "3.7.5"; | |
var VERSION = version; | |
var _hasatob = typeof atob === "function"; | |
var _hasbtoa = typeof btoa === "function"; | |
var _hasBuffer = typeof Buffer === "function"; | |
var _TD = typeof TextDecoder === "function" ? new TextDecoder() : void 0; | |
var _TE = typeof TextEncoder === "function" ? new TextEncoder() : void 0; | |
var b64ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; | |
var b64chs = Array.prototype.slice.call(b64ch); | |
var b64tab = ((a) => { | |
let tab = {}; | |
a.forEach((c, i) => tab[c] = i); | |
return tab; | |
})(b64chs); | |
var b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/; | |
var _fromCC = String.fromCharCode.bind(String); | |
var _U8Afrom = typeof Uint8Array.from === "function" ? Uint8Array.from.bind(Uint8Array) : (it) => new Uint8Array(Array.prototype.slice.call(it, 0)); | |
var _mkUriSafe = (src) => src.replace(/=/g, "").replace(/[+\/]/g, (m0) => m0 == "+" ? "-" : "_"); | |
var _tidyB64 = (s) => s.replace(/[^A-Za-z0-9\+\/]/g, ""); | |
var btoaPolyfill = (bin) => { | |
let u32, c0, c1, c2, asc = ""; | |
const pad = bin.length % 3; | |
for (let i = 0; i < bin.length; ) { | |
if ((c0 = bin.charCodeAt(i++)) > 255 || (c1 = bin.charCodeAt(i++)) > 255 || (c2 = bin.charCodeAt(i++)) > 255) | |
throw new TypeError("invalid character found"); | |
u32 = c0 << 16 | c1 << 8 | c2; | |
asc += b64chs[u32 >> 18 & 63] + b64chs[u32 >> 12 & 63] + b64chs[u32 >> 6 & 63] + b64chs[u32 & 63]; | |
} | |
return pad ? asc.slice(0, pad - 3) + "===".substring(pad) : asc; | |
}; | |
var _btoa = _hasbtoa ? (bin) => btoa(bin) : _hasBuffer ? (bin) => Buffer.from(bin, "binary").toString("base64") : btoaPolyfill; | |
var _fromUint8Array = _hasBuffer ? (u8a) => Buffer.from(u8a).toString("base64") : (u8a) => { | |
const maxargs = 4096; | |
let strs = []; | |
for (let i = 0, l = u8a.length; i < l; i += maxargs) { | |
strs.push(_fromCC.apply(null, u8a.subarray(i, i + maxargs))); | |
} | |
return _btoa(strs.join("")); | |
}; | |
var fromUint8Array = (u8a, urlsafe = false) => urlsafe ? _mkUriSafe(_fromUint8Array(u8a)) : _fromUint8Array(u8a); | |
var cb_utob = (c) => { | |
if (c.length < 2) { | |
var cc = c.charCodeAt(0); | |
return cc < 128 ? c : cc < 2048 ? _fromCC(192 | cc >>> 6) + _fromCC(128 | cc & 63) : _fromCC(224 | cc >>> 12 & 15) + _fromCC(128 | cc >>> 6 & 63) + _fromCC(128 | cc & 63); | |
} else { | |
var cc = 65536 + (c.charCodeAt(0) - 55296) * 1024 + (c.charCodeAt(1) - 56320); | |
return _fromCC(240 | cc >>> 18 & 7) + _fromCC(128 | cc >>> 12 & 63) + _fromCC(128 | cc >>> 6 & 63) + _fromCC(128 | cc & 63); | |
} | |
}; | |
var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g; | |
var utob = (u) => u.replace(re_utob, cb_utob); | |
var _encode = _hasBuffer ? (s) => Buffer.from(s, "utf8").toString("base64") : _TE ? (s) => _fromUint8Array(_TE.encode(s)) : (s) => _btoa(utob(s)); | |
var encode = (src, urlsafe = false) => urlsafe ? _mkUriSafe(_encode(src)) : _encode(src); | |
var encodeURI2 = (src) => encode(src, true); | |
var re_btou = /[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g; | |
var cb_btou = (cccc) => { | |
switch (cccc.length) { | |
case 4: | |
var cp = (7 & cccc.charCodeAt(0)) << 18 | (63 & cccc.charCodeAt(1)) << 12 | (63 & cccc.charCodeAt(2)) << 6 | 63 & cccc.charCodeAt(3), offset = cp - 65536; | |
return _fromCC((offset >>> 10) + 55296) + _fromCC((offset & 1023) + 56320); | |
case 3: | |
return _fromCC((15 & cccc.charCodeAt(0)) << 12 | (63 & cccc.charCodeAt(1)) << 6 | 63 & cccc.charCodeAt(2)); | |
default: | |
return _fromCC((31 & cccc.charCodeAt(0)) << 6 | 63 & cccc.charCodeAt(1)); | |
} | |
}; | |
var btou = (b) => b.replace(re_btou, cb_btou); | |
var atobPolyfill = (asc) => { | |
asc = asc.replace(/\s+/g, ""); | |
if (!b64re.test(asc)) | |
throw new TypeError("malformed base64."); | |
asc += "==".slice(2 - (asc.length & 3)); | |
let u24, bin = "", r1, r2; | |
for (let i = 0; i < asc.length; ) { | |
u24 = b64tab[asc.charAt(i++)] << 18 | b64tab[asc.charAt(i++)] << 12 | (r1 = b64tab[asc.charAt(i++)]) << 6 | (r2 = b64tab[asc.charAt(i++)]); | |
bin += r1 === 64 ? _fromCC(u24 >> 16 & 255) : r2 === 64 ? _fromCC(u24 >> 16 & 255, u24 >> 8 & 255) : _fromCC(u24 >> 16 & 255, u24 >> 8 & 255, u24 & 255); | |
} | |
return bin; | |
}; | |
var _atob = _hasatob ? (asc) => atob(_tidyB64(asc)) : _hasBuffer ? (asc) => Buffer.from(asc, "base64").toString("binary") : atobPolyfill; | |
var _toUint8Array = _hasBuffer ? (a) => _U8Afrom(Buffer.from(a, "base64")) : (a) => _U8Afrom(_atob(a).split("").map((c) => c.charCodeAt(0))); | |
var toUint8Array = (a) => _toUint8Array(_unURI(a)); | |
var _decode = _hasBuffer ? (a) => Buffer.from(a, "base64").toString("utf8") : _TD ? (a) => _TD.decode(_toUint8Array(a)) : (a) => btou(_atob(a)); | |
var _unURI = (a) => _tidyB64(a.replace(/[-_]/g, (m0) => m0 == "-" ? "+" : "/")); | |
var decode = (src) => _decode(_unURI(src)); | |
var isValid = (src) => { | |
if (typeof src !== "string") | |
return false; | |
const s = src.replace(/\s+/g, "").replace(/={0,2}$/, ""); | |
return !/[^\s0-9a-zA-Z\+/]/.test(s) || !/[^\s0-9a-zA-Z\-_]/.test(s); | |
}; | |
var _noEnum = (v) => { | |
return { | |
value: v, | |
enumerable: false, | |
writable: true, | |
configurable: true | |
}; | |
}; | |
var extendString = function() { | |
const _add = (name, body) => Object.defineProperty(String.prototype, name, _noEnum(body)); | |
_add("fromBase64", function() { | |
return decode(this); | |
}); | |
_add("toBase64", function(urlsafe) { | |
return encode(this, urlsafe); | |
}); | |
_add("toBase64URI", function() { | |
return encode(this, true); | |
}); | |
_add("toBase64URL", function() { | |
return encode(this, true); | |
}); | |
_add("toUint8Array", function() { | |
return toUint8Array(this); | |
}); | |
}; | |
var extendUint8Array = function() { | |
const _add = (name, body) => Object.defineProperty(Uint8Array.prototype, name, _noEnum(body)); | |
_add("toBase64", function(urlsafe) { | |
return fromUint8Array(this, urlsafe); | |
}); | |
_add("toBase64URI", function() { | |
return fromUint8Array(this, true); | |
}); | |
_add("toBase64URL", function() { | |
return fromUint8Array(this, true); | |
}); | |
}; | |
var extendBuiltins = () => { | |
extendString(); | |
extendUint8Array(); | |
}; | |
var gBase64 = { | |
version, | |
VERSION, | |
atob: _atob, | |
atobPolyfill, | |
btoa: _btoa, | |
btoaPolyfill, | |
fromBase64: decode, | |
toBase64: encode, | |
encode, | |
encodeURI: encodeURI2, | |
encodeURL: encodeURI2, | |
utob, | |
btou, | |
decode, | |
isValid, | |
fromUint8Array, | |
toUint8Array, | |
extendString, | |
extendUint8Array, | |
extendBuiltins | |
}; | |
// plugin/publish/delete.ts | |
var import_obsidian7 = require("obsidian"); | |
function deleteFromGithub(silent = false, settings3, octokit, branchName, filesManagement, repoFrontmatter) { | |
return __async(this, null, function* () { | |
repoFrontmatter = Array.isArray(repoFrontmatter) ? repoFrontmatter : [repoFrontmatter]; | |
const deleted = []; | |
for (const repo of repoFrontmatter) { | |
deleted.push(yield deleteFromGithubOneRepo( | |
silent, | |
settings3, | |
octokit, | |
branchName, | |
filesManagement, | |
repo | |
)); | |
} | |
return deleted[0]; | |
}); | |
} | |
function deleteFromGithubOneRepo(silent = false, settings3, octokit, branchName, filesManagement, repo) { | |
return __async(this, null, function* () { | |
if (!repo.autoclean) | |
return; | |
const getAllFile = yield filesManagement.getAllFileFromRepo( | |
branchName, | |
octokit, | |
settings3, | |
repo | |
); | |
const filesInRepo = yield filterGithubFile(getAllFile, settings3); | |
if (!filesInRepo) { | |
let errorMsg = ""; | |
if (settings3.upload.defaultName.length > 0) { | |
if (settings3.upload.defaultName.length > 0) { | |
errorMsg = instance.t("deletion.defaultFolder"); | |
} else if (settings3.upload.behavior === "yaml" /* yaml */ && settings3.upload.rootFolder.length === 0) { | |
errorMsg = instance.t("deletion.rootFolder"); | |
} | |
} | |
if (!silent) { | |
new import_obsidian7.Notice("Error : " + errorMsg); | |
} | |
return { success: false, deleted: [], undeleted: [] }; | |
} | |
const allSharedFiles = filesManagement.getAllFileWithPath(); | |
const allSharedConverted = allSharedFiles.map((file) => { | |
return { converted: file.converted, repo: file.repoFrontmatter }; | |
}); | |
let deletedSuccess = 0; | |
let deletedFailed = 0; | |
const result = { | |
deleted: [], | |
undeleted: [], | |
success: false | |
}; | |
for (const file of filesInRepo) { | |
const isInObsidian = allSharedConverted.some( | |
(f) => f.converted === file.file | |
); | |
const isMarkdownForAnotherRepo = file.file.trim().endsWith(".md") ? !allSharedConverted.some( | |
(f) => f.converted === file.file && JSON.stringify(f.repo) == JSON.stringify(repo) | |
) : false; | |
const isNeedToBeDeleted = isInObsidian ? isMarkdownForAnotherRepo : true; | |
if (isNeedToBeDeleted) { | |
const checkingIndex = file.file.contains(settings3.upload.folderNote.rename) ? yield checkIndexFiles(octokit, settings3, file.file, repo) : false; | |
try { | |
if (!checkingIndex) { | |
noticeLog( | |
`trying to delete file : ${file.file} from ${repo.owner}/${repo.repo}`, | |
settings3 | |
); | |
const reponse = yield octokit.request( | |
"DELETE /repos/{owner}/{repo}/contents/{path}", | |
{ | |
owner: repo.owner, | |
repo: repo.repo, | |
path: file.file, | |
message: `DELETE FILE : ${file.file}`, | |
sha: file.sha, | |
branch: branchName | |
} | |
); | |
if (reponse.status === 200) { | |
deletedSuccess++; | |
result.deleted.push(file.file); | |
} else { | |
deletedFailed++; | |
result.undeleted.push(file.file); | |
} | |
} | |
} catch (e) { | |
if (!(e instanceof DOMException)) | |
noticeLog(e, settings3); | |
} | |
} | |
} | |
let successMsg = instance.t("deletion.noFile"); | |
let failedMsg = ""; | |
if (deletedSuccess > 0) { | |
successMsg = instance.t("deletion.success", { nb: deletedSuccess.toString() }); | |
} | |
if (deletedFailed > 0) { | |
failedMsg = instance.t("deletion.failed", { nb: deletedFailed.toString() }); | |
} | |
if (!silent) { | |
new import_obsidian7.Notice(successMsg + failedMsg); | |
} | |
result.success = deletedFailed === 0; | |
return result; | |
}); | |
} | |
function excludedFileFromDelete(file, settings3) { | |
const autoCleanExcluded = settings3.upload.autoclean.excluded; | |
if (autoCleanExcluded.length > 0) { | |
for (const excludedFile of autoCleanExcluded) { | |
const isRegex = excludedFile.match(/^\/(.*)\/[igmsuy]*$/); | |
const regex3 = isRegex ? new RegExp(isRegex[1], isRegex[2]) : null; | |
if (regex3 && regex3.test(file)) { | |
return true; | |
} else if (file.trim().includes(excludedFile.trim()) && excludedFile.length > 0) { | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
function filterGithubFile(fileInRepo, settings3) { | |
return __async(this, null, function* () { | |
const sharedFilesInRepo = []; | |
for (const file of fileInRepo) { | |
const behavior = settings3.upload.behavior; | |
const root = settings3.upload.rootFolder; | |
const defaultName = settings3.upload.defaultName; | |
const attachmentFolder = settings3.embed.folder; | |
if (behavior === "yaml" /* yaml */ && root.length === 0 || defaultName.length === 0 || behavior === "fixed" /* fixed */) { | |
return null; | |
} | |
if ((file.file.includes(defaultName) || behavior === "yaml" /* yaml */ && file.file.includes(root) || attachmentFolder.length > 0 && file.file.includes(attachmentFolder)) && !excludedFileFromDelete(file.file, settings3) && (isAttachment(file.file) || file.file.match("md$"))) { | |
sharedFilesInRepo.push(file); | |
} | |
} | |
return sharedFilesInRepo; | |
}); | |
} | |
function parseYamlFrontmatter(contents) { | |
const yamlFrontmatter = contents.split("---")[1]; | |
const yamlFrontmatterParsed = (0, import_obsidian7.parseYaml)(yamlFrontmatter); | |
return trimObject(yamlFrontmatterParsed); | |
} | |
function checkIndexFiles(octokit, settings3, path, repoFrontmatter) { | |
return __async(this, null, function* () { | |
try { | |
const fileRequest = yield octokit.request( | |
"GET /repos/{owner}/{repo}/contents/{path}", | |
{ | |
owner: repoFrontmatter.owner, | |
repo: repoFrontmatter.repo, | |
path | |
} | |
); | |
if (fileRequest.status === 200) { | |
const fileContent = gBase64.decode(fileRequest.data.content); | |
const fileFrontmatter = parseYamlFrontmatter(fileContent); | |
return fileFrontmatter.index === "true" || fileFrontmatter.delete === "false" || !fileFrontmatter.share; | |
} | |
} catch (e) { | |
if (!(e instanceof DOMException)) { | |
noticeLog(e, settings3); | |
return false; | |
} | |
} | |
}); | |
} | |
// plugin/src/status_bar.ts | |
var ShareStatusBar = class { | |
/** | |
* @param {HTMLElement} statusBarItem | |
* @param {number} numberOfNotesToPublish | |
* @param {boolean} attachment true if there are attachment to the note | |
*/ | |
constructor(statusBarItem, numberOfNotesToPublish, attachment = false) { | |
this.attachment = false; | |
this.statusBarItem = statusBarItem; | |
this.counter = 0; | |
this.numberOfNotesToPublish = numberOfNotesToPublish; | |
this.attachment = attachment; | |
this.statusBarItem.createEl("span", { text: "" }); | |
let typeAttachment = instance.t("common.files"); | |
if (this.attachment) { | |
typeAttachment = instance.t("common.attachments"); | |
} | |
const msg = instance.t("statusBar.markedForSharing", { nb: this.numberOfNotesToPublish, type: typeAttachment }); | |
this.status = this.statusBarItem.createEl("span", { text: `${msg}` }); | |
} | |
/** | |
* increment the counter | |
*/ | |
increment() { | |
let typeAttachment = instance.t("common.files"); | |
if (this.attachment) { | |
typeAttachment = instance.t("common.attachments"); | |
} | |
const msg = instance.t("statusBar.sharing", { type: typeAttachment }); | |
this.status.setText( | |
instance.t("statusBar.counter", { msg, counter: ++this.counter, nb: this.numberOfNotesToPublish }) | |
); | |
} | |
/** | |
* finish the status bar | |
* @param {number} displayDurationMillisec | |
*/ | |
finish(displayDurationMillisec) { | |
let msg = instance.t("statusBar.success", { action: instance.t("common.published"), type: instance.t("common.files") }); | |
if (this.attachment) { | |
msg = instance.t("statusBar.success", { action: instance.t("common.shared"), type: instance.t("common.attachments") }); | |
} | |
this.status.setText( | |
instance.t("statusBar.counter", { msg, counter: this.counter, nb: this.numberOfNotesToPublish }) | |
); | |
setTimeout(() => { | |
this.statusBarItem.remove(); | |
}, displayDurationMillisec); | |
} | |
/** | |
* Remove the status bar if error occurs | |
*/ | |
error() { | |
this.statusBarItem.remove(); | |
} | |
}; | |
// plugin/conversion/convertText.ts | |
var import_obsidian8 = require("obsidian"); | |
var import_obsidian_dataview = __toESM(require_lib()); | |
// plugin/conversion/convertLinks.ts | |
var import_slugify = __toESM(require_slugify()); | |
function convertWikilinks(fileContent, conditionConvert, linkedFiles, settings3) { | |
const convertWikilink = conditionConvert.convertWiki; | |
const imageSettings = conditionConvert.attachment; | |
const convertLinks = conditionConvert.links; | |
if (noTextConversion(conditionConvert)) { | |
return fileContent; | |
} | |
const wikiRegex = /!?\[\[.*?\]\]/g; | |
const wikiMatches = fileContent.match(wikiRegex); | |
if (wikiMatches) { | |
const fileRegex = /(\[\[).*?([\]|])/; | |
for (const wikiMatch of wikiMatches) { | |
const fileMatch = wikiMatch.match(fileRegex); | |
const isEmbed = wikiMatch.startsWith("!") ? "!" : ""; | |
const isEmbedBool = wikiMatch.startsWith("!"); | |
if (fileMatch) { | |
let linkCreator = wikiMatch; | |
const fileName = fileMatch[0].replaceAll("[", "").replaceAll("|", "").replaceAll("]", "").replaceAll("\\", ""); | |
const StrictFileName = fileMatch[0].replaceAll("[", "").replaceAll("|", "").replaceAll("]", "").replaceAll("\\", "").replaceAll("../", "").replaceAll("./", "").replace(/#.*/, ""); | |
const linkedFile = linkedFiles.find( | |
(item) => item.linkFrom.replace(/#.*/, "") === StrictFileName | |
); | |
if (linkedFile) { | |
let altText; | |
if (linkedFile.linked.extension !== "md") { | |
altText = linkedFile.altText.length > 0 ? linkedFile.altText : ""; | |
} else { | |
altText = linkedFile.altText.length > 0 ? linkedFile.altText : linkedFile.linked.basename; | |
} | |
const removeEmbed = conditionConvert.removeEmbed && isEmbedBool && linkedFile.linked.extension === "md"; | |
if (convertWikilink) { | |
const altMatch = wikiMatch.match(/(\|).*(]])/); | |
const altCreator = fileName.split("/"); | |
const altLink = creatorAltLink( | |
altMatch, | |
altCreator, | |
fileName.split(".").at(-1), | |
fileName | |
); | |
linkCreator = createMarkdownLinks(fileName, isEmbed, altLink, settings3); | |
} | |
if (linkedFile.linked.extension === "md" && !convertLinks && !isEmbedBool) { | |
linkCreator = altText; | |
} | |
if (!imageSettings && isAttachment(linkedFile.linked.extension) || removeEmbed) { | |
linkCreator = ""; | |
} | |
fileContent = fileContent.replace(wikiMatch, linkCreator); | |
} else if (!fileName.startsWith("http")) { | |
const altMatch = wikiMatch.match(/(\|).*(]])/); | |
const altCreator = fileName.split("/"); | |
const altLink = creatorAltLink( | |
altMatch, | |
altCreator, | |
fileName.split(".").at(-1), | |
fileName | |
); | |
const removeEmbed = !isAttachment(fileName.trim()) && conditionConvert.removeEmbed && isEmbedBool; | |
if (convertWikilink) { | |
linkCreator = createMarkdownLinks(fileName, isEmbed, altLink, settings3); | |
} | |
if (!isAttachment(fileName.trim()) && !convertLinks && !isEmbedBool) { | |
linkCreator = altLink; | |
} | |
if (!imageSettings && isAttachment(fileName.trim()) || removeEmbed) { | |
linkCreator = ""; | |
} | |
fileContent = fileContent.replace(wikiMatch, linkCreator); | |
} | |
} | |
} | |
} | |
return fileContent; | |
} | |
function createMarkdownLinks(fileName, isEmbed, altLink, settings3) { | |
const markdownName = !isAttachment(fileName.trim()) ? fileName.replace(/#.*/, "").trim() + ".md" : fileName.trim(); | |
let anchor = fileName.match(/(#.*)/) ? fileName.match(/(#.*)/)[0].replaceAll(" ", "%20") : ""; | |
const encodedURI = encodeURI(markdownName); | |
if (settings3.conversion.links.slugify) { | |
anchor = fileName.match(/(#.*)/) ? (0, import_slugify.default)(fileName.match(/(#.*)/)[0], { lower: true, strict: true }) : ""; | |
anchor = `#${anchor}`; | |
} | |
return `${isEmbed}[${altLink}](${encodedURI}${anchor})`; | |
} | |
function addAltText(link, linkedFile) { | |
if (link.match(/\[{2}.*\]{2}/) && !link.match(/(\|).*(]])/)) { | |
return link.replace("|", "").replace("]]", `|${linkedFile.altText}]]`); | |
} | |
return link; | |
} | |
function escapeRegex(filepath) { | |
return filepath.replace(/[/\-\\^$*+?.()|[\]{}]/g, "\\$&"); | |
} | |
function convertLinkCitation(fileContent, settings3, linkedFiles, metadataCache, sourceFile, vault, frontmatter, sourceRepoFrontmatter, frontmatterSettings) { | |
return __async(this, null, function* () { | |
if (!frontmatterSettings.convertInternalLinks) { | |
return fileContent; | |
} | |
for (const linkedFile of linkedFiles) { | |
let pathInGithub = yield createRelativePath( | |
sourceFile, | |
linkedFile, | |
metadataCache, | |
settings3, | |
vault, | |
frontmatter, | |
sourceRepoFrontmatter, | |
frontmatterSettings | |
); | |
pathInGithub = pathInGithub.replace(".md", ""); | |
let anchor = linkedFile.anchor ? linkedFile.anchor : ""; | |
let linkInMarkdown = escapeRegex(linkedFile.linkFrom.replace(linkedFile.anchor, "")).replaceAll(" ", "%20") + anchor.replace("^", "\\^"); | |
linkInMarkdown = linkInMarkdown.replaceAll(" ", "%20"); | |
const escapedLinkedFile = escapeRegex(linkedFile.linkFrom); | |
const regexToReplace = new RegExp( | |
`(\\[{2}${escapedLinkedFile}(\\\\?\\|.*)?\\]{2})|(\\[.*\\]\\((${escapedLinkedFile}|${linkInMarkdown})\\))`, | |
"g" | |
); | |
const matchedLink = fileContent.match(regexToReplace); | |
if (matchedLink) { | |
for (const link of matchedLink) { | |
const regToReplace = new RegExp(`((${escapedLinkedFile})|(${linkInMarkdown}))`); | |
let pathInGithubWithAnchor = pathInGithub; | |
if (linkedFile.anchor) { | |
pathInGithub = pathInGithub.replace(/#.*/, ""); | |
pathInGithubWithAnchor += linkedFile.anchor; | |
} | |
let newLink = link.replace(regToReplace, pathInGithubWithAnchor); | |
if (link.match(/\[.*\]\(.*\)/)) { | |
if (linkedFile.linked.extension === "md") { | |
anchor = settings3.conversion.links.slugify ? (0, import_slugify.default)(anchor, { lower: true, strict: true }) : anchor; | |
pathInGithub = pathInGithub.replaceAll(" ", "%20") + ".md#" + anchor; | |
pathInGithub = !pathInGithub.match(/(#.*)/) && !pathInGithub.endsWith(".md") ? pathInGithub + ".md" : pathInGithub; | |
} | |
const altText = link.match(/\[(.*)\]/)[1]; | |
newLink = `[${altText}](${pathInGithub})`; | |
} | |
newLink = addAltText(newLink, linkedFile); | |
fileContent = fileContent.replace(link, newLink); | |
} | |
} | |
} | |
return fileContent; | |
}); | |
} | |
function creatorAltLink(altMatch, altCreator, fileExtension, match) { | |
if (altMatch) { | |
return altMatch[0].replace("]]", "").replace("|", ""); | |
} | |
if (fileExtension === "md") { | |
return altCreator.length > 1 ? altCreator[altCreator.length - 1] : altCreator[0]; | |
} | |
return match.split("/").at(-1); | |
} | |
// plugin/conversion/convertText.ts | |
function addHardLineBreak(text, settings3, frontmatter) { | |
try { | |
text = text.replace(/^\s*\\\s*$/gim, "<br/>"); | |
if (frontmatter.hardbreak) { | |
text = text.replace(/\n/gm, " \n"); | |
} | |
return text; | |
} catch (e) { | |
noticeLog(e, settings3); | |
return text; | |
} | |
} | |
function addTagsToYAML(text, toAdd) { | |
return __async(this, null, function* () { | |
const yaml = text.split("---")[1]; | |
const yamlObject = (0, import_obsidian8.parseYaml)(yaml); | |
if (yamlObject.tag) { | |
toAdd = [ | |
.../* @__PURE__ */ new Set([ | |
...toAdd, | |
...yamlObject.tag.map( | |
(tag) => tag.replaceAll("/", "_") | |
) | |
]) | |
]; | |
delete yamlObject.tag; | |
} | |
if (yamlObject.tags) { | |
yamlObject.tags = [ | |
.../* @__PURE__ */ new Set([ | |
...yamlObject.tags.map( | |
(tag) => tag.replaceAll("/", "_") | |
), | |
...toAdd | |
]) | |
]; | |
} else { | |
yamlObject.tags = toAdd; | |
} | |
const returnToYaml = (0, import_obsidian8.stringifyYaml)(yamlObject); | |
const fileContentsOnly = text.split("---").slice(2).join("---"); | |
return `--- | |
${returnToYaml}--- | |
${fileContentsOnly}`; | |
}); | |
} | |
function addInlineTags(settings3, file, metadataCache, app2, frontmatter, text) { | |
return __async(this, null, function* () { | |
var _a; | |
if (!settings3.conversion.tags.inline) { | |
return text; | |
} | |
const inlineTags = (_a = metadataCache.getFileCache(file)) == null ? void 0 : _a.tags; | |
const inlineTagsInText = inlineTags ? inlineTags.map((t2) => t2.tag.replace("#", "").replaceAll("/", "_")) : []; | |
const frontmatterTags = (0, import_obsidian8.parseFrontMatterTags)(frontmatter); | |
const yamlTags = frontmatterTags ? frontmatterTags.map((t2) => t2.replace("#", "").replaceAll("/", "_")) : []; | |
const toAdd = [.../* @__PURE__ */ new Set([...inlineTagsInText, ...yamlTags])]; | |
if (toAdd.length > 0) { | |
return yield addTagsToYAML(text, toAdd); | |
} | |
return text; | |
}); | |
} | |
function dataviewExtract(fieldValue, settings3) { | |
const basename = (name) => /([^/\\.]*)(\..*)?$/.exec(name)[1]; | |
const filename = basename(fieldValue.path).toString(); | |
const display = fieldValue.display ? fieldValue.display.toString() : filename; | |
if (!settings3.conversion.tags.exclude.includes(display) && !settings3.conversion.tags.fields.includes(filename)) { | |
return display; | |
} | |
return null; | |
} | |
function convertInlineDataview(text, settings3, sourceFile, app2) { | |
return __async(this, null, function* () { | |
if (settings3.conversion.tags.fields.length === 0 || // @ts-ignore | |
!app2.plugins.enabledPlugins.has("dataview")) { | |
return text; | |
} | |
const dvApi = (0, import_obsidian_dataview.getAPI)(); | |
const dataviewLinks = yield dvApi.page(sourceFile.path); | |
const valueToAdd = []; | |
for (const field of settings3.conversion.tags.fields) { | |
const fieldValue = dataviewLinks[field]; | |
if (fieldValue) { | |
if (fieldValue.constructor.name === "Link") { | |
const stringifyField = dataviewExtract(fieldValue, settings3); | |
valueToAdd.push(stringifyField); | |
} else if (fieldValue.constructor.name === "Array") { | |
for (const item of fieldValue) { | |
let stringifyField = item; | |
if (item.constructor.name === "Link") { | |
stringifyField = dataviewExtract(item, settings3); | |
valueToAdd.push(stringifyField); | |
} else if (!settings3.conversion.tags.exclude.includes( | |
stringifyField.toString() | |
)) { | |
valueToAdd.push(stringifyField.toString()); | |
} | |
} | |
} else if (!settings3.conversion.tags.exclude.includes(fieldValue.toString())) { | |
valueToAdd.push(fieldValue.toString()); | |
} | |
} | |
} | |
if (valueToAdd.length > 0) { | |
return yield addTagsToYAML(text, valueToAdd.filter(Boolean)); | |
} | |
return text; | |
}); | |
} | |
function convertDataviewQueries(text, path, settings3, app2, metadataCache, frontmatterSettings, frontmatter, sourceFile, sourceFrontmatter) { | |
return __async(this, null, function* () { | |
if (!app2.plugins.enabledPlugins.has("dataview")) { | |
return text; | |
} | |
const vault = app2.vault; | |
let replacedText = text; | |
const dataviewRegex = new RegExp("```dataview(.+?)```", "gms"); | |
const dvApi = (0, import_obsidian_dataview.getAPI)(); | |
const matches = text.matchAll(dataviewRegex); | |
if (!matches) | |
return; | |
const settingsDataview = frontmatterSettings.dataview; | |
for (const queryBlock of matches) { | |
try { | |
const block = queryBlock[0]; | |
const query = queryBlock[1]; | |
let md = settingsDataview ? yield dvApi.tryQueryMarkdown(query, path) : ""; | |
const dataviewPath = getDataviewPath(md, settings3, vault); | |
md = yield convertLinkCitation( | |
md, | |
settings3, | |
dataviewPath, | |
metadataCache, | |
sourceFile, | |
vault, | |
frontmatter, | |
sourceFrontmatter, | |
frontmatterSettings | |
); | |
md = convertWikilinks( | |
md, | |
frontmatterSettings, | |
dataviewPath, | |
settings3 | |
); | |
replacedText = replacedText.replace(block, md); | |
} catch (e) { | |
noticeLog(e, settings3); | |
if (!queryBlock[1].match("js")) | |
new import_obsidian8.Notice(instance.t("error.dataview")); | |
return text; | |
} | |
} | |
return replacedText; | |
}); | |
} | |
function mainConverting(text, settings3, frontmatterSettings, file, app2, metadataCache, frontmatter, linkedFiles, plugin, vault, sourceRepo) { | |
return __async(this, null, function* () { | |
text = findAndReplaceText(text, settings3, false); | |
text = yield addInlineTags( | |
settings3, | |
file, | |
metadataCache, | |
plugin.app, | |
frontmatter, | |
text | |
); | |
text = yield convertDataviewQueries( | |
text, | |
file.path, | |
settings3, | |
plugin.app, | |
metadataCache, | |
frontmatterSettings, | |
frontmatter, | |
file, | |
sourceRepo | |
); | |
text = yield convertInlineDataview(text, settings3, file, plugin.app); | |
text = addHardLineBreak(text, settings3, frontmatterSettings); | |
text = yield convertLinkCitation( | |
text, | |
settings3, | |
linkedFiles, | |
metadataCache, | |
file, | |
vault, | |
frontmatter, | |
sourceRepo, | |
frontmatterSettings | |
); | |
text = convertWikilinks(text, frontmatterSettings, linkedFiles, settings3); | |
text = findAndReplaceText(text, settings3, true); | |
return text; | |
}); | |
} | |
// plugin/publish/upload.ts | |
var Publisher = class { | |
/** | |
* Class to manage the branch | |
* @param {Vault} vault Obsidian vault | |
* @param {MetadataCache} metadataCache Obsidian metadataCache | |
* @param {GitHubPublisherSettings} settings Settings of the plugin | |
* @param {Octokit} octokit Octokit instance | |
* @param {GithubPublisher} plugin GithubPublisher instance | |
*/ | |
constructor(vault, metadataCache, settings3, octokit, plugin) { | |
this.vault = vault; | |
this.metadataCache = metadataCache; | |
this.settings = settings3; | |
this.octokit = octokit; | |
this.plugin = plugin; | |
} | |
/** | |
* Add a status bar + send embed to GitHub. Deep-scanning files. | |
* @param {TFile[]} linkedFiles File embedded | |
* @param {TFile[]} fileHistory already sent files | |
* @param {string} branchName The name of the branch created by the plugin | |
* @param {boolean} deepScan starts the conversion+push of md file. If false, just sharing image | |
* @param {FrontmatterConvert} sourceFrontmatter frontmatter settings | |
* @param {RepoFrontmatter} repoFrontmatter frontmatter settings | |
* @returns {Promise<TFile[]>} | |
*/ | |
statusBarForEmbed(linkedFiles, fileHistory, branchName, deepScan, sourceFrontmatter, repoFrontmatter) { | |
return __async(this, null, function* () { | |
const uploadedFile = []; | |
const fileError = []; | |
if (linkedFiles.length > 0) { | |
if (linkedFiles.length > 1) { | |
const statusBarItems = this.plugin.addStatusBarItem(); | |
const statusBar3 = new ShareStatusBar( | |
statusBarItems, | |
linkedFiles.length, | |
true | |
); | |
try { | |
for (const file of linkedFiles) { | |
try { | |
if (!fileHistory.includes(file)) { | |
if (file.extension === "md" && deepScan) { | |
const published = yield this.publish( | |
file, | |
false, | |
branchName, | |
repoFrontmatter, | |
fileHistory, | |
true | |
); | |
if (published) { | |
uploadedFile.push(...published.uploaded); | |
} | |
} else if (isAttachment(file.extension) && sourceFrontmatter.attachment) { | |
const published = yield this.uploadImage( | |
file, | |
branchName, | |
sourceFrontmatter, | |
repoFrontmatter | |
); | |
fileHistory.push(file); | |
if (published) { | |
uploadedFile.push(published); | |
} | |
} | |
} | |
statusBar3.increment(); | |
} catch (e) { | |
new import_obsidian9.Notice( | |
instance.t("error.unablePublishNote", { file: file.name }) | |
); | |
fileError.push(file.name); | |
console.error(e); | |
} | |
} | |
statusBar3.finish(8e3); | |
} catch (e) { | |
noticeLog(e, this.settings); | |
new import_obsidian9.Notice( | |
instance.t("error.errorPublish", { repo: repoFrontmatter }) | |
); | |
statusBar3.error(); | |
} | |
} else { | |
const embed = linkedFiles[0]; | |
if (!fileHistory.includes(embed)) { | |
if (embed.extension === "md" && deepScan) { | |
const published = yield this.publish( | |
embed, | |
false, | |
branchName, | |
repoFrontmatter, | |
fileHistory, | |
true | |
); | |
if (published) { | |
uploadedFile.push(...published.uploaded); | |
} | |
} else if (isAttachment(embed.extension) && sourceFrontmatter.attachment) { | |
const published = yield this.uploadImage( | |
embed, | |
branchName, | |
sourceFrontmatter, | |
repoFrontmatter | |
); | |
fileHistory.push(embed); | |
if (published) { | |
uploadedFile.push(published); | |
} | |
} | |
} | |
} | |
} | |
return { | |
fileHistory, | |
uploaded: uploadedFile, | |
error: fileError | |
}; | |
}); | |
} | |
/** | |
* Main prog to scan notes, their embed files and send it to GitHub. | |
* @param {TFile} file Origin file | |
* @param {boolean} autoclean If the autoclean must be done right after the file | |
* @param {string} branchName The name of the branch created | |
* @param {TFile[]} fileHistory File already sent during DeepScan | |
* @param {boolean} deepScan if the plugin must check the embed notes too. | |
* @param {RepoFrontmatter} repoFrontmatter frontmatter settings | |
*/ | |
publish(_0) { | |
return __async(this, arguments, function* (file, autoclean = false, branchName, repoFrontmatter, fileHistory = [], deepScan = false) { | |
const shareFiles = new FilesManagement( | |
this.vault, | |
this.metadataCache, | |
this.settings, | |
this.octokit, | |
this.plugin | |
); | |
const frontmatter = this.metadataCache.getFileCache(file).frontmatter; | |
const isNotEmpty = checkEmptyConfiguration(getRepoFrontmatter(this.settings, frontmatter), this.settings); | |
if (!isShared(frontmatter, this.settings, file) || fileHistory.includes(file) || !checkIfRepoIsInAnother( | |
getRepoFrontmatter(this.settings, frontmatter), | |
repoFrontmatter | |
) || !isNotEmpty) { | |
return false; | |
} | |
try { | |
noticeLog("Publishing file: " + file.path, this.settings); | |
fileHistory.push(file); | |
const frontmatterSettings = getFrontmatterCondition( | |
frontmatter, | |
this.settings | |
); | |
let embedFiles = shareFiles.getSharedEmbed( | |
file, | |
frontmatterSettings | |
); | |
embedFiles = yield shareFiles.getMetadataLinks( | |
file, | |
embedFiles, | |
frontmatter, | |
frontmatterSettings | |
); | |
const linkedFiles = shareFiles.getLinkedByEmbedding(file); | |
let text = yield app.vault.cachedRead(file); | |
text = yield mainConverting( | |
text, | |
this.settings, | |
frontmatterSettings, | |
file, | |
app, | |
this.metadataCache, | |
frontmatter, | |
linkedFiles, | |
this.plugin, | |
this.vault, | |
repoFrontmatter | |
); | |
const path = getReceiptFolder( | |
file, | |
this.settings, | |
this.metadataCache, | |
this.vault | |
); | |
repoFrontmatter = Array.isArray(repoFrontmatter) ? repoFrontmatter : [repoFrontmatter]; | |
let multiRepMsg = ""; | |
for (const repo of repoFrontmatter) { | |
multiRepMsg += `[${repo.owner}/${repo.repo}/${repo.branch}] `; | |
} | |
const msg = `Publishing ${file.name} to ${multiRepMsg}`; | |
noticeLog(msg, this.settings); | |
const fileDeleted = []; | |
const updated = []; | |
const fileError = []; | |
for (const repo of repoFrontmatter) { | |
const deleted = yield this.uploadOnMultipleRepo( | |
file, | |
text, | |
branchName, | |
frontmatterSettings, | |
path, | |
repo, | |
embedFiles, | |
fileHistory, | |
deepScan, | |
shareFiles, | |
autoclean | |
); | |
fileDeleted.push(deleted.deleted); | |
updated.push(deleted.uploaded); | |
fileError.push(...deleted.error); | |
} | |
return { deleted: fileDeleted[0], uploaded: updated[0], error: fileError }; | |
} catch (e) { | |
noticeLog(e, this.settings); | |
return false; | |
} | |
}); | |
} | |
/** | |
* Upload the file to GitHub | |
* @param {TFile} file sourceFile | |
* @param {string} text text to send | |
* @param {string} branchName the branch name created by the plugin | |
* @param {FrontmatterConvert} frontmatterSettings frontmatter settings | |
* @param {string} path path to the file in the github repo | |
* @param {RepoFrontmatter} repo frontmatter settings | |
* @param {TFile[]} embedFiles File embedded in the note | |
* @param {TFile[]} fileHistory File already sent during DeepScan | |
* @param {boolean} deepScan if the plugin must check the embed notes too. | |
* @param {FilesManagement} shareFiles FilesManagement class | |
* @param {boolean} autoclean If the autoclean must be done right after the file upload | |
*/ | |
uploadOnMultipleRepo(file, text, branchName, frontmatterSettings, path, repo, embedFiles, fileHistory, deepScan, shareFiles, autoclean) { | |
return __async(this, null, function* () { | |
noticeLog( | |
`Upload ${file.name}:${path} on ${repo.owner}/${repo.repo}:${branchName}`, | |
this.settings | |
); | |
const uploaded = yield this.uploadText(text, path, file.name, branchName, repo); | |
let deleted; | |
const embeded = yield this.statusBarForEmbed( | |
embedFiles, | |
fileHistory, | |
branchName, | |
deepScan, | |
frontmatterSettings, | |
repo | |
); | |
const embeddedUploaded = embeded.uploaded; | |
embeddedUploaded.push(uploaded); | |
if (autoclean && repo.autoclean) { | |
deleted = yield deleteFromGithub( | |
true, | |
this.settings, | |
this.octokit, | |
branchName, | |
shareFiles, | |
repo | |
); | |
} | |
return { | |
deleted, | |
uploaded: embeddedUploaded, | |
error: embeded.error | |
}; | |
}); | |
} | |
/** | |
* Upload file to GitHub | |
* @param {string} content Contents of the file sent | |
* @param {string} title for commit message, name of the file | |
* @param {string} branchName the branch name created by the plugin | |
* @param {string} path path in GitHub | |
* @param {RepoFrontmatter} repoFrontmatter frontmatter settings | |
*/ | |
upload(content, path, title = "", branchName, repoFrontmatter) { | |
return __async(this, null, function* () { | |
if (!repoFrontmatter.repo) { | |
new import_obsidian9.Notice( | |
"Config error : You need to define a github repo in the plugin settings" | |
); | |
throw {}; | |
} | |
if (!repoFrontmatter.owner) { | |
new import_obsidian9.Notice( | |
"Config error : You need to define your github username in the plugin settings" | |
); | |
throw {}; | |
} | |
const octokit = this.octokit; | |
let msg = `PUSH NOTE : ${title}`; | |
if (isAttachment(path)) { | |
title = path.split("/")[path.split("/").length - 1]; | |
msg = `PUSH ATTACHMENT : ${title}`; | |
} | |
const payload = { | |
owner: repoFrontmatter.owner, | |
repo: repoFrontmatter.repo, | |
path, | |
message: `Adding ${title}`, | |
content, | |
sha: "", | |
branch: branchName | |
}; | |
const result = { | |
isUpdated: false, | |
file: title | |
}; | |
try { | |
const response = yield octokit.request( | |
"GET /repos/{owner}/{repo}/contents/{path}", | |
{ | |
owner: repoFrontmatter.owner, | |
repo: repoFrontmatter.repo, | |
path, | |
ref: branchName | |
} | |
); | |
if (response.status === 200 && response.data.type === "file") { | |
payload.sha = response.data.sha; | |
result.isUpdated = true; | |
} | |
} catch (e) { | |
noticeLog( | |
"The 404 error is normal ! It means that the file does not exist yet. Don't worry \u2764\uFE0F.", | |
this.settings | |
); | |
} | |
payload.message = msg; | |
yield octokit.request( | |
"PUT /repos/{owner}/{repo}/contents/{path}", | |
payload | |
); | |
return result; | |
}); | |
} | |
/** | |
* Convert image in base64 and upload it to GitHub | |
* @param {TFile} imageFile the image | |
* @param {string} branchName branch name | |
* @param {RepoFrontmatter} repoFrontmatter frontmatter settings | |
* @param {FrontmatterConvert} sourceFrontmatter frontmatter settings | |
*/ | |
uploadImage(imageFile, branchName, sourceFrontmatter, repoFrontmatter) { | |
return __async(this, null, function* () { | |
const imageBin = yield this.vault.readBinary(imageFile); | |
const image64 = (0, import_obsidian9.arrayBufferToBase64)(imageBin); | |
const path = getImageLinkOptions( | |
imageFile, | |
this.settings, | |
sourceFrontmatter | |
); | |
return yield this.upload(image64, path, "", branchName, repoFrontmatter); | |
}); | |
} | |
/** | |
* Convert text contents to base64 | |
* @param {string} text contents of the note | |
* @param {string} path new Path in GitHub | |
* @param {string} title name note for message commit | |
* @param {string} branchName The branch created by the plugin | |
* @param {RepoFrontmatter} repoFrontmatter frontmatter settings | |
* @return {Promise<void>} | |
*/ | |
uploadText(text, path, title = "", branchName, repoFrontmatter) { | |
return __async(this, null, function* () { | |
try { | |
const contentBase64 = gBase64.encode(text).toString(); | |
return yield this.upload( | |
contentBase64, | |
path, | |
title, | |
branchName, | |
repoFrontmatter | |
); | |
} catch (e) { | |
console.error(e); | |
return void 0; | |
} | |
}); | |
} | |
/** | |
* Upload the metadataExtractor json file | |
* @param {MetadataExtractor} metadataExtractor metadataExtractor | |
* @param {string} branchName The branch name created by the plugin | |
* @param {RepoFrontmatter | RepoFrontmatter[]} repoFrontmatter frontmatter settings | |
* @return {Promise<void>} | |
*/ | |
uploadMetadataExtractorFiles(metadataExtractor, branchName, repoFrontmatter) { | |
return __async(this, null, function* () { | |
if (metadataExtractor) { | |
for (const file of Object.values(metadataExtractor)) { | |
if (file) { | |
const contents = yield app.vault.adapter.read(file); | |
const path = this.settings.upload.metadataExtractorPath + "/" + file.split("/").pop(); | |
repoFrontmatter = Array.isArray(repoFrontmatter) ? repoFrontmatter : [repoFrontmatter]; | |
for (const repo of repoFrontmatter) { | |
yield this.uploadText( | |
contents, | |
path, | |
file.split("/").pop(), | |
branchName, | |
repo | |
); | |
} | |
} | |
} | |
} | |
}); | |
} | |
/** | |
* Allow to activate a workflow dispatch github actions | |
* @param {RepoFrontmatter} repoFrontmatter frontmatter settings | |
* @return {Promise<boolean>} | |
*/ | |
workflowGestion(repoFrontmatter) { | |
return __async(this, null, function* () { | |
let finished = false; | |
if (this.settings.github.worflow.workflowName.length === 0) { | |
return false; | |
} else { | |
const octokit = this.octokit; | |
yield octokit.request( | |
"POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches", | |
{ | |
owner: repoFrontmatter.owner, | |
repo: repoFrontmatter.repo, | |
workflow_id: this.settings.github.worflow.workflowName, | |
ref: repoFrontmatter.branch | |
} | |
); | |
while (!finished) { | |
yield sleep(1e4); | |
const workflowGet = yield octokit.request( | |
"GET /repos/{owner}/{repo}/actions/runs", | |
{ | |
owner: repoFrontmatter.owner, | |
repo: repoFrontmatter.repo | |
} | |
); | |
if (workflowGet.data.workflow_runs.length > 0) { | |
const build = workflowGet.data.workflow_runs.find( | |
(run) => run.name === this.settings.github.worflow.workflowName.replace(".yml", "") | |
); | |
if (build.status === "completed") { | |
finished = true; | |
return true; | |
} | |
} | |
} | |
} | |
}); | |
} | |
}; | |
// plugin/publish/files.ts | |
var import_obsidian_dataview2 = __toESM(require_lib()); | |
var FilesManagement = class extends Publisher { | |
/** | |
* | |
* @param {Vault} vault Obsidian Vault API | |
* @param {MetadataCache} metadataCache Obsidian MetadataCache API | |
* @param {GitHubPublisherSettings} settings The settings | |
* @param {Octokit} octokit The octokit instance | |
* @param {GitHubPublisherSettings} plugin The plugin | |
*/ | |
constructor(vault, metadataCache, settings3, octokit, plugin) { | |
super(vault, metadataCache, settings3, octokit, plugin); | |
this.vault = vault; | |
this.metadataCache = metadataCache; | |
this.settings = settings3; | |
this.octokit = octokit; | |
this.plugin = plugin; | |
} | |
/** | |
* Get all shared files in the vault, by scanning the frontmatter and the state of the shareKey | |
* @return {TFile[]} The shared files | |
*/ | |
getSharedFiles() { | |
const files = this.vault.getMarkdownFiles(); | |
const shared_File = []; | |
const sharedkey = this.settings.plugin.shareKey; | |
for (const file of files) { | |
try { | |
const frontMatter = this.metadataCache.getCache( | |
file.path | |
).frontmatter; | |
if (frontMatter && frontMatter[sharedkey] === true) { | |
shared_File.push(file); | |
} | |
} catch (e) { | |
} | |
} | |
return shared_File; | |
} | |
/** | |
* Get all shared file in the vault, but create an ConvertedLink object with the real path and the converted path | |
* @return {ConvertedLink[]} The shared files | |
*/ | |
getAllFileWithPath() { | |
const files = this.vault.getFiles(); | |
const allFileWithPath = []; | |
const shareKey = this.settings.plugin.shareKey; | |
for (const file of files) { | |
if (isAttachment(file.extension)) { | |
const filepath = getImageLinkOptions(file, this.settings, null); | |
allFileWithPath.push({ | |
converted: filepath, | |
real: file.path | |
}); | |
} else if (file.extension == "md") { | |
const frontMatter = this.metadataCache.getCache( | |
file.path | |
).frontmatter; | |
if (frontMatter && frontMatter[shareKey] === true) { | |
const filepath = getReceiptFolder( | |
file, | |
this.settings, | |
this.metadataCache, | |
this.vault | |
); | |
allFileWithPath.push({ | |
converted: filepath, | |
real: file.path, | |
repoFrontmatter: getRepoFrontmatter( | |
this.settings, | |
frontMatter | |
) | |
}); | |
} | |
} | |
} | |
return allFileWithPath; | |
} | |
/** | |
* Create a database with every internal links and embedded image and files | |
* Used for the links conversion (for markdown links and receipt folder) | |
* @param {TFile} file source file | |
* @return {LinkedNotes[]} array of linked files | |
*/ | |
getLinkedByEmbedding(file) { | |
const linkedFiles = this.getLinkedFiles(file); | |
const imageEmbedded = this.metadataCache.getFileCache(file).embeds; | |
if (imageEmbedded != void 0) { | |
for (const image of imageEmbedded) { | |
try { | |
const imageLink = this.metadataCache.getFirstLinkpathDest( | |
image.link.replace(/#.*/, ""), | |
file.path | |
); | |
if (imageLink !== null) { | |
let altText = image.displayText !== imageLink.path.replace(".md", "") ? image.displayText : imageLink.basename; | |
let frontmatterDestinationFilePath; | |
if (this.settings.upload.frontmatterTitle.enable) { | |
const frontmatter = this.metadataCache.getCache( | |
imageLink.path | |
).frontmatter; | |
if (frontmatter && frontmatter[this.settings.upload.frontmatterTitle.key]) { | |
frontmatterDestinationFilePath = frontmatter[this.settings.upload.frontmatterTitle.key]; | |
if (altText === imageLink.basename) { | |
altText = frontmatterDestinationFilePath; | |
} | |
} | |
} | |
const thisLinkedFile = { | |
linked: imageLink, | |
//TFile found | |
linkFrom: image.link, | |
//path of the founded file | |
altText, | |
//alt text if exists, filename otherwise | |
destinationFilePath: frontmatterDestinationFilePath | |
}; | |
if (image.link.includes("#")) { | |
thisLinkedFile.anchor = "#" + image.link.split("#")[1]; | |
} | |
linkedFiles.push(thisLinkedFile); | |
} | |
} catch (e) { | |
} | |
} | |
} | |
return [...new Set(linkedFiles)]; | |
} | |
/** | |
* Create an objet of all files linked (not embed!) in the shared files | |
* Used during links conversion (for markdown links and receipt folder) | |
* @param {TFile} file The file shared | |
* @return {LinkedNotes[]} the file linked (TFile), the path to it, and the alt text if exists | |
*/ | |
getLinkedFiles(file) { | |
const embedCaches = this.metadataCache.getCache(file.path).links; | |
const embedList = []; | |
if (embedCaches != void 0) { | |
for (const embedCache of embedCaches) { | |
try { | |
const linkedFile = this.metadataCache.getFirstLinkpathDest( | |
embedCache.link.replace(/#.*/, ""), | |
file.path | |
); | |
if (linkedFile) { | |
let altText = embedCache.displayText !== linkedFile.path.replace(".md", "") ? embedCache.displayText : linkedFile.basename; | |
if (embedCache.original.match(/\[.*\]\(.*\)/)) { | |
altText = embedCache.original.match(/\[(.*)\]/)[1]; | |
} | |
let frontmatterDestinationFilePath; | |
if (this.settings.upload.frontmatterTitle.enable) { | |
const frontmatter = this.metadataCache.getCache( | |
linkedFile.path | |
).frontmatter; | |
if (frontmatter && frontmatter[this.settings.upload.frontmatterTitle.key]) { | |
frontmatterDestinationFilePath = frontmatter[this.settings.upload.frontmatterTitle.key]; | |
if (altText === linkedFile.basename) { | |
altText = frontmatterDestinationFilePath; | |
} | |
} | |
} | |
const thisEmbed = { | |
linked: linkedFile, | |
linkFrom: embedCache.link, | |
altText, | |
destinationFilePath: frontmatterDestinationFilePath | |
}; | |
if (embedCache.link.includes("#")) { | |
thisEmbed.anchor = "#" + embedCache.link.split("#")[1]; | |
} | |
embedList.push(thisEmbed); | |
} | |
} catch (e) { | |
noticeLog(e, this.settings); | |
noticeLog( | |
"Error with this links : " + embedCache.link, | |
this.settings | |
); | |
} | |
} | |
return [...new Set(embedList)]; | |
} | |
return []; | |
} | |
/** | |
* Get all files embedded in the shared file | |
* If the settings are true, allowing to publish the files (for attachments) | |
* Markdown files attachments are always verified using the main publish function | |
* @param {TFile} file The file shared | |
* @param {FrontmatterConvert} frontmatterSourceFile frontmatter of the file | |
* @return {TFile[]} the file embedded & shared in form of an array of TFile | |
*/ | |
getSharedEmbed(file, frontmatterSourceFile) { | |
const embedCaches = this.metadataCache.getCache(file.path).embeds; | |
const imageList = []; | |
if (embedCaches != void 0) { | |
for (const embed of embedCaches) { | |
try { | |
const imageLink = this.metadataCache.getFirstLinkpathDest( | |
embed.link.replace(/#(.*)/, ""), | |
file.path | |
); | |
imageList.push( | |
this.imageSharedOrNote(imageLink, frontmatterSourceFile) | |
); | |
} catch (e) { | |
noticeLog(e, this.settings); | |
noticeLog( | |
"Error with this file : " + embed.displayText, | |
this.settings | |
); | |
} | |
} | |
return [...new Set(imageList)].filter((x) => x !== null); | |
} | |
return []; | |
} | |
/** | |
* Check if the file is in the excluded folder by checking the settings | |
* @param {TFile} file The file shared | |
* @return {boolean} true if the file is in the excluded folder | |
*/ | |
checkExcludedFolder(file) { | |
const excludedFolder = this.settings.plugin.excludedFolder; | |
if (excludedFolder.length > 0) { | |
for (let i = 0; i < excludedFolder.length; i++) { | |
const isRegex = excludedFolder[i].match(/^\/(.*)\/[igmsuy]*$/); | |
const regex3 = isRegex ? new RegExp(isRegex[1], isRegex[2]) : null; | |
if (regex3 && regex3.test(file.path)) { | |
return true; | |
} else if (file.path.contains(excludedFolder[i].trim())) { | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
/** | |
* Get the last time the file from the github Repo was edited | |
* @param {Octokit} octokit | |
* @param {GithubRepo} githubRepo | |
* @param {GitHubPublisherSettings} settings | |
* @return {Promise<Date>} | |
*/ | |
getLastEditedTimeRepo(octokit, githubRepo, settings3) { | |
return __async(this, null, function* () { | |
const commits = yield octokit.request( | |
"GET /repos/{owner}/{repo}/commits", | |
{ | |
owner: settings3.github.user, | |
repo: settings3.github.repo, | |
path: githubRepo.file | |
} | |
); | |
const lastCommittedFile = commits.data[0]; | |
return new Date(lastCommittedFile.commit.committer.date); | |
}); | |
} | |
/** | |
* Get all file from the github Repo | |
* @param {string} branchToScan the branch name to scan the files | |
* @param {Octokit} octokit the octokit instance | |
* @param {GitHubPublisherSettings} settings the settings | |
* @param {RepoFrontmatter} repo | |
* @return {Promise<GithubRepo[]>} | |
*/ | |
getAllFileFromRepo(branchToScan, octokit, settings3, repo) { | |
return __async(this, null, function* () { | |
const filesInRepo = []; | |
try { | |
const repoContents = yield octokit.request( | |
"GET /repos/{owner}/{repo}/git/trees/{tree_sha}", | |
{ | |
owner: repo.owner, | |
repo: repo.repo, | |
tree_sha: branchToScan, | |
recursive: "true" | |
} | |
); | |
if (repoContents.status === 200) { | |
const files = repoContents.data.tree; | |
for (const file of files) { | |
const basename = (name) => /([^/\\.]*)(\..*)?$/.exec(name)[1]; | |
if (file.type === "blob" && basename(file.path).length > 0) { | |
filesInRepo.push({ | |
file: file.path, | |
sha: file.sha | |
}); | |
} | |
} | |
} | |
} catch (e) { | |
noticeLog(e, settings3); | |
} | |
return filesInRepo; | |
}); | |
} | |
/** | |
* Compare the last edited time of the file in the github repo and the file in the vault | |
* Always push in the list if the file doesn't exist in the github repo | |
* @param {ConvertedLink[]} allFileWithPath | |
* @param {GithubRepo[]} githubSharedFiles | |
* @param {Vault} vault | |
* @return {TFile[]} | |
*/ | |
getNewFiles(allFileWithPath, githubSharedFiles, vault) { | |
const newFiles = []; | |
for (const file of allFileWithPath) { | |
if (!githubSharedFiles.some((x) => x.file === file.converted.trim())) { | |
const fileInVault = vault.getAbstractFileByPath( | |
file.real.trim() | |
); | |
if (fileInVault && fileInVault instanceof import_obsidian10.TFile && fileInVault.extension === "md") { | |
newFiles.push(fileInVault); | |
} | |
} | |
} | |
return newFiles; | |
} | |
/** | |
* Get the filepath of a file shared in a dataview field and return the file if it exists in the vault | |
* @param {Link | string} path | |
* @param {Link | string} field | |
* @param {FrontmatterConvert} frontmatterSourceFile | |
* @return {TFile} | |
*/ | |
getImageByPath(path, field, frontmatterSourceFile) { | |
if (field.constructor.name === "Link") { | |
field = field.path; | |
} | |
if (path.constructor.name === "Link") { | |
path = path.path; | |
} | |
const imageLink = this.metadataCache.getFirstLinkpathDest(field, path); | |
if (imageLink !== null) { | |
return this.imageSharedOrNote(imageLink, frontmatterSourceFile); | |
} | |
return null; | |
} | |
/** | |
* Check if the file is a image or a note based on the extension | |
* Check if the sharing is allowing based on the frontmatter | |
* @param {TFile} file | |
* @param {FrontmatterConvert} settingsConversion | |
* @return {null | TFile} | |
* @private | |
*/ | |
imageSharedOrNote(file, settingsConversion) { | |
const transferImage = settingsConversion.attachment; | |
const transferEmbeds = settingsConversion.embed; | |
if (isAttachment(file.extension) && transferImage || transferEmbeds && file.extension === "md") { | |
return file; | |
} | |
return null; | |
} | |
/** | |
* Get all files linked to a metadata field, based on the frontmatter or dataview | |
* if frontmatter, get the path of the file and check if it exists in the vault | |
* @param {TFile} file | |
* @param {TFile[]} embedFiles | |
* @param {FrontMatterCache} frontmatterSourceFile | |
* @param {FrontmatterConvert} frontmatterSettings | |
* @return {Promise<TFile[]>} | |
*/ | |
getMetadataLinks(file, embedFiles, frontmatterSourceFile, frontmatterSettings) { | |
return __async(this, null, function* () { | |
for (const field of this.settings.embed.keySendFile) { | |
if (frontmatterSourceFile[field] != void 0) { | |
const imageLink = this.metadataCache.getFirstLinkpathDest( | |
frontmatterSourceFile[field], | |
file.path | |
); | |
if (imageLink !== null) { | |
embedFiles.push( | |
this.imageSharedOrNote(file, frontmatterSettings) | |
); | |
} | |
} | |
} | |
if (this.plugin.app.plugins.enabledPlugins.has("dataview")) { | |
const dvApi = (0, import_obsidian_dataview2.getAPI)(); | |
const dataviewMetadata = yield dvApi.page(file.path); | |
for (const field of this.settings.embed.keySendFile) { | |
const fieldValue = dataviewMetadata[field]; | |
if (fieldValue != void 0) { | |
if (fieldValue.constructor.name === "Array") { | |
for (const value of fieldValue) { | |
embedFiles.push( | |
this.getImageByPath( | |
value, | |
fieldValue, | |
frontmatterSettings | |
) | |
); | |
} | |
} else { | |
embedFiles.push( | |
this.getImageByPath( | |
fieldValue, | |
fieldValue, | |
frontmatterSettings | |
) | |
); | |
} | |
} | |
} | |
} | |
return [...new Set(embedFiles)].filter((x) => x != null); | |
}); | |
} | |
/** | |
* Get all edited file since the last sync, compared to the github repo | |
* @param {ConvertedLink[]} allFileWithPath - all shared file with their path | |
* @param {GithubRepo[]} githubSharedFiles - all file in the github repo | |
* @param {Vault} vault - vault | |
* @param {TFile[]} newFiles - new file to add to the repo | |
* @return {Promise<TFile[]>} newFiles - File to add in the repo | |
*/ | |
getEditedFiles(allFileWithPath, githubSharedFiles, vault, newFiles) { | |
return __async(this, null, function* () { | |
for (const file of allFileWithPath) { | |
if (githubSharedFiles.some((x) => x.file === file.converted.trim())) { | |
const githubSharedFile = githubSharedFiles.find( | |
(x) => x.file === file.converted.trim() | |
); | |
const repoEditedTime = yield this.getLastEditedTimeRepo( | |
this.octokit, | |
githubSharedFile, | |
this.settings | |
); | |
const fileInVault = vault.getAbstractFileByPath( | |
file.real.trim() | |
); | |
if (fileInVault && fileInVault instanceof import_obsidian10.TFile && fileInVault.extension === "md") { | |
const vaultEditedTime = new Date(fileInVault.stat.mtime); | |
if (vaultEditedTime > repoEditedTime) { | |
noticeLog( | |
`edited file : ${fileInVault.path} / ${vaultEditedTime} vs ${repoEditedTime}`, | |
this.settings | |
); | |
newFiles.push(fileInVault); | |
} | |
} | |
} | |
} | |
return newFiles; | |
}); | |
} | |
}; | |
// plugin/publish/branch.ts | |
var import_obsidian11 = require("obsidian"); | |
var GithubBranch = class extends FilesManagement { | |
/** | |
* Manage the branch | |
* @param {GitHubPublisherSettings} settings The name of the branch to create | |
* @param {Octokit} octokit The octokit instance | |
* @param {Vault} vault The vault | |
* @param {MetadataCache} metadataCache The metadataCache | |
* @param {GithubPublisherPlugin} plugin The plugin | |
* | |
**/ | |
constructor(settings3, octokit, vault, metadataCache, plugin) { | |
super(vault, metadataCache, settings3, octokit, plugin); | |
this.settings = settings3; | |
this.octokit = octokit; | |
this.plugin = plugin; | |
} | |
/** | |
* Check if RepoFrontmatter is an array or not and run the newBranchOnRepo function on each repo | |
* @param {string} branchName The name of the branch to create | |
* @param {RepoFrontmatter[] | RepoFrontmatter} repoFrontmatter The repo to use | |
*/ | |
newBranch(branchName, repoFrontmatter) { | |
return __async(this, null, function* () { | |
repoFrontmatter = Array.isArray(repoFrontmatter) ? repoFrontmatter : [repoFrontmatter]; | |
for (const repo of repoFrontmatter) { | |
yield this.newBranchOnRepo(branchName, repo); | |
} | |
}); | |
} | |
/** | |
* Create a new branch on the repo named "Vault-date" | |
* Pass if the branch already exists | |
* Run in a loop in the newBranch function if RepoFrontmatter[] is passed | |
* @param {string} branchName The name of the branch to create | |
* @param {RepoFrontmatter} repoFrontmatter The repo to use | |
* @return {Promise<boolean>} True if the branch is created | |
*/ | |
newBranchOnRepo(branchName, repoFrontmatter) { | |
return __async(this, null, function* () { | |
const allBranch = yield this.octokit.request( | |
"GET /repos/{owner}/{repo}/branches", | |
{ | |
owner: repoFrontmatter.owner, | |
repo: repoFrontmatter.repo | |
} | |
); | |
const mainBranch = allBranch.data.find( | |
(branch) => branch.name === repoFrontmatter.branch | |
); | |
try { | |
const shaMainBranch = mainBranch.commit.sha; | |
const branch = yield this.octokit.request( | |
"POST /repos/{owner}/{repo}/git/refs", | |
{ | |
owner: repoFrontmatter.owner, | |
repo: repoFrontmatter.repo, | |
ref: "refs/heads/" + branchName, | |
sha: shaMainBranch | |
} | |
); | |
noticeLog( | |
instance.t("publish.branch.success", { branchStatus: branch.status, repo: repoFrontmatter }), | |
this.settings | |
); | |
return branch.status === 201; | |
} catch (e) { | |
try { | |
noticeLog(e, this.settings); | |
const allBranch2 = yield this.octokit.request( | |
"GET /repos/{owner}/{repo}/branches", | |
{ | |
owner: repoFrontmatter.owner, | |
repo: repoFrontmatter.repo | |
} | |
); | |
const mainBranch2 = allBranch2.data.find( | |
(branch) => branch.name === branchName | |
); | |
noticeLog(instance.t("publish.branch.alreadyExists", { branchName: mainBranch2.name, repo: repoFrontmatter }), this.settings); | |
return !!mainBranch2; | |
} catch (e2) { | |
noticeLog(e2, this.settings); | |
return false; | |
} | |
} | |
}); | |
} | |
/** | |
* Create a pull request on repoFrontmatter.branch with the branchName | |
* Run in a loop in the pullRequest function if RepoFrontmatter[] is passed | |
* @param {string} branchName The name of the branch to create | |
* @param {RepoFrontmatter} repoFrontmatter The repo to use | |
* @return {Promise<number>} False in case of error, the pull request number otherwise | |
*/ | |
pullRequestOnRepo(branchName, repoFrontmatter) { | |
return __async(this, null, function* () { | |
try { | |
const PR = yield this.octokit.request( | |
"POST /repos/{owner}/{repo}/pulls", | |
{ | |
owner: repoFrontmatter.owner, | |
repo: repoFrontmatter.repo, | |
title: instance.t("publish.branch.prMessage", { branchName }), | |
body: "", | |
head: branchName, | |
base: repoFrontmatter.branch | |
} | |
); | |
return PR.data.number; | |
} catch (e) { | |
noticeLog(e, this.settings); | |
try { | |
const PR = yield this.octokit.request( | |
"GET /repos/{owner}/{repo}/pulls", | |
{ | |
owner: repoFrontmatter.owner, | |
repo: repoFrontmatter.repo, | |
state: "open" | |
} | |
); | |
return PR.data[0].number; | |
} catch (e2) { | |
noticeLog( | |
instance.t("publish.branch.error", { error: e2, repo: repoFrontmatter }), | |
this.settings | |
); | |
return 0; | |
} | |
} | |
}); | |
} | |
/** | |
* After the merge, delete the new branch on the repo | |
* Run in a loop in the updateRepository function if RepoFrontmatter[] is passed | |
* @param {settings} branchName The name of the branch to create | |
* @param {RepoFrontmatter} repoFrontmatter The repo to use | |
* @return {Promise<boolean>} true if the branch is deleted | |
*/ | |
deleteBranchOnRepo(branchName, repoFrontmatter) { | |
return __async(this, null, function* () { | |
try { | |
const branch = yield this.octokit.request( | |
"DELETE /repos/{owner}/{repo}/git/refs/heads/" + branchName, | |
{ | |
owner: repoFrontmatter.owner, | |
repo: repoFrontmatter.repo | |
} | |
); | |
return branch.status === 200; | |
} catch (e) { | |
return false; | |
} | |
}); | |
} | |
/** | |
* Automatically merge pull request from the plugin (only if the settings allow it) | |
* Run in a loop in the updateRepository function if RepoFrontmatter[] is passed | |
* @param {string} branchName The name of the branch to create | |
* @param {number} pullRequestNumber number of the new pullrequest | |
* @param {RepoFrontmatter} repoFrontmatter The repo to use | |
*/ | |
mergePullRequestOnRepo(branchName, pullRequestNumber, repoFrontmatter) { | |
return __async(this, null, function* () { | |
const commitMsg = this.plugin.settings.github.worflow.customCommitMsg || this.plugin.settings.github.worflow.customCommitMsg.trim().length > 0 ? `${this.plugin.settings.github.worflow.customCommitMsg} #${pullRequestNumber}` : `[PUBLISHER] Merge #${pullRequestNumber}`; | |
try { | |
const branch = yield this.octokit.request( | |
"PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge", | |
{ | |
owner: repoFrontmatter.owner, | |
repo: repoFrontmatter.repo, | |
pull_number: pullRequestNumber, | |
commit_title: commitMsg, | |
merge_method: "squash" | |
} | |
); | |
return branch.status === 200; | |
} catch (e) { | |
noticeLog(e, this.settings); | |
new import_obsidian11.Notice(instance.t("error.mergeconflic")); | |
return false; | |
} | |
}); | |
} | |
/** | |
* Update the repository with the new branch : PR, merging and deleting the branch if allowed by the global settings | |
* @param {string} branchName The name of the branch to merge | |
* @param {RepoFrontmatter | RepoFrontmatter[]} repoFrontmatter The repo to use | |
* @returns {Promise<boolean>} True if the update is successful | |
*/ | |
updateRepository(branchName, repoFrontmatter) { | |
return __async(this, null, function* () { | |
repoFrontmatter = Array.isArray(repoFrontmatter) ? repoFrontmatter : [repoFrontmatter]; | |
const success = []; | |
for (const repo of repoFrontmatter) { | |
success.push(yield this.updateRepositoryOnOne(branchName, repo)); | |
} | |
return !success.every((value) => value === false); | |
}); | |
} | |
/** | |
* Run merging + deleting branch in once, for one repo | |
* Run in a loop in the updateRepository function if RepoFrontmatter[] is passed | |
* @param {string} branchName The name of the branch to merge | |
* @param {RepoFrontmatter} repoFrontmatter The repo to use | |
* @returns {Promise<boolean>} true if the update is successful | |
*/ | |
updateRepositoryOnOne(branchName, repoFrontmatter) { | |
return __async(this, null, function* () { | |
try { | |
const pullRequest = yield this.pullRequestOnRepo( | |
branchName, | |
repoFrontmatter | |
); | |
if (this.plugin.settings.github.automaticallyMergePR && pullRequest !== 0) { | |
const PRSuccess = yield this.mergePullRequestOnRepo( | |
branchName, | |
pullRequest, | |
repoFrontmatter | |
); | |
if (PRSuccess) { | |
yield this.deleteBranchOnRepo(branchName, repoFrontmatter); | |
return true; | |
} | |
return false; | |
} | |
return true; | |
} catch (e) { | |
noticeLog(e, this.settings); | |
new import_obsidian11.Notice( | |
instance.t("error.errorConfig", { repo: repoFrontmatter }) | |
); | |
return false; | |
} | |
}); | |
} | |
/** | |
* Use octokit to check if: | |
* - the repo exists | |
* - the main branch exists | |
* Send a notice if the repo doesn't exist or if the main branch doesn't exist | |
* Note: If one of the repo defined in the list doesn't exist, the rest of the list will not be checked because the octokit request throws an error | |
* @param {RepoFrontmatter | RepoFrontmatter[]} repoFrontmatter | |
* @param silent Send a notice if the repo is valid | |
* @return {Promise<void>} | |
*/ | |
checkRepository(repoFrontmatter, silent = true) { | |
return __async(this, null, function* () { | |
repoFrontmatter = Array.isArray(repoFrontmatter) ? repoFrontmatter : [repoFrontmatter]; | |
for (const repo of repoFrontmatter) { | |
try { | |
const repoExist = yield this.octokit.request("GET /repos/{owner}/{repo}", { | |
owner: repo.owner, | |
repo: repo.repo | |
}).catch((e) => { | |
if (e.status === 404) { | |
new import_obsidian11.Notice( | |
instance.t("commands.checkValidity.inRepo.error404", { repo }) | |
); | |
} else if (e.status === 403) { | |
new import_obsidian11.Notice( | |
instance.t("commands.checkValidity.inRepo.error403", { repo }) | |
); | |
} else if (e.status === 301) { | |
new import_obsidian11.Notice( | |
instance.t("commands.checkValidity.inRepo.error301", { repo }) | |
); | |
} | |
}); | |
if (repoExist.status === 200) { | |
noticeLog(instance.t("commands.checkValidity.repoExistsTestBranch", { repo }), this.settings); | |
const branchExist = yield this.octokit.request("GET /repos/{owner}/{repo}/branches/{branch}", { | |
owner: repo.owner, | |
repo: repo.repo, | |
branch: repo.branch | |
}).catch((e) => { | |
if (e.status === 404) { | |
new import_obsidian11.Notice( | |
instance.t("commands.checkValidity.inBranch.error404", { repo }) | |
); | |
} else if (e.status === 403) { | |
new import_obsidian11.Notice( | |
instance.t("commands.checkValidity.inBranch.error403", { repo }) | |
); | |
} | |
}); | |
if (branchExist.status === 200 && !silent) { | |
new import_obsidian11.Notice( | |
instance.t("commands.checkValidity.success", { repo }) | |
); | |
} | |
} | |
} catch (e) { | |
break; | |
} | |
} | |
}); | |
} | |
}; | |
// node_modules/universal-user-agent/dist-web/index.js | |
function getUserAgent() { | |
if (typeof navigator === "object" && "userAgent" in navigator) { | |
return navigator.userAgent; | |
} | |
if (typeof process === "object" && "version" in process) { | |
return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; | |
} | |
return "<environment undetectable>"; | |
} | |
// node_modules/@octokit/core/dist-web/index.js | |
var import_before_after_hook = __toESM(require_before_after_hook()); | |
// node_modules/is-plain-object/dist/is-plain-object.mjs | |
function isObject(o) { | |
return Object.prototype.toString.call(o) === "[object Object]"; | |
} | |
function isPlainObject(o) { | |
var ctor, prot; | |
if (isObject(o) === false) | |
return false; | |
ctor = o.constructor; | |
if (ctor === void 0) | |
return true; | |
prot = ctor.prototype; | |
if (isObject(prot) === false) | |
return false; | |
if (prot.hasOwnProperty("isPrototypeOf") === false) { | |
return false; | |
} | |
return true; | |
} | |
// node_modules/@octokit/endpoint/dist-web/index.js | |
function lowercaseKeys(object) { | |
if (!object) { | |
return {}; | |
} | |
return Object.keys(object).reduce((newObj, key) => { | |
newObj[key.toLowerCase()] = object[key]; | |
return newObj; | |
}, {}); | |
} | |
function mergeDeep(defaults, options) { | |
const result = Object.assign({}, defaults); | |
Object.keys(options).forEach((key) => { | |
if (isPlainObject(options[key])) { | |
if (!(key in defaults)) | |
Object.assign(result, { [key]: options[key] }); | |
else | |
result[key] = mergeDeep(defaults[key], options[key]); | |
} else { | |
Object.assign(result, { [key]: options[key] }); | |
} | |
}); | |
return result; | |
} | |
function removeUndefinedProperties(obj) { | |
for (const key in obj) { | |
if (obj[key] === void 0) { | |
delete obj[key]; | |
} | |
} | |
return obj; | |
} | |
function merge(defaults, route, options) { | |
if (typeof route === "string") { | |
let [method, url] = route.split(" "); | |
options = Object.assign(url ? { method, url } : { url: method }, options); | |
} else { | |
options = Object.assign({}, route); | |
} | |
options.headers = lowercaseKeys(options.headers); | |
removeUndefinedProperties(options); | |
removeUndefinedProperties(options.headers); | |
const mergedOptions = mergeDeep(defaults || {}, options); | |
if (defaults && defaults.mediaType.previews.length) { | |
mergedOptions.mediaType.previews = defaults.mediaType.previews.filter((preview) => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews); | |
} | |
mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map((preview) => preview.replace(/-preview/, "")); | |
return mergedOptions; | |
} | |
function addQueryParameters(url, parameters) { | |
const separator = /\?/.test(url) ? "&" : "?"; | |
const names = Object.keys(parameters); | |
if (names.length === 0) { | |
return url; | |
} | |
return url + separator + names.map((name) => { | |
if (name === "q") { | |
return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); | |
} | |
return `${name}=${encodeURIComponent(parameters[name])}`; | |
}).join("&"); | |
} | |
var urlVariableRegex = /\{[^}]+\}/g; | |
function removeNonChars(variableName) { | |
return variableName.replace(/^\W+|\W+$/g, "").split(/,/); | |
} | |
function extractUrlVariableNames(url) { | |
const matches = url.match(urlVariableRegex); | |
if (!matches) { | |
return []; | |
} | |
return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); | |
} | |
function omit(object, keysToOmit) { | |
return Object.keys(object).filter((option) => !keysToOmit.includes(option)).reduce((obj, key) => { | |
obj[key] = object[key]; | |
return obj; | |
}, {}); | |
} | |
function encodeReserved(str) { | |
return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { | |
if (!/%[0-9A-Fa-f]/.test(part)) { | |
part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); | |
} | |
return part; | |
}).join(""); | |
} | |
function encodeUnreserved(str) { | |
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { | |
return "%" + c.charCodeAt(0).toString(16).toUpperCase(); | |
}); | |
} | |
function encodeValue(operator, value, key) { | |
value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); | |
if (key) { | |
return encodeUnreserved(key) + "=" + value; | |
} else { | |
return value; | |
} | |
} | |
function isDefined(value) { | |
return value !== void 0 && value !== null; | |
} | |
function isKeyOperator(operator) { | |
return operator === ";" || operator === "&" || operator === "?"; | |
} | |
function getValues(context, operator, key, modifier) { | |
var value = context[key], result = []; | |
if (isDefined(value) && value !== "") { | |
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { | |
value = value.toString(); | |
if (modifier && modifier !== "*") { | |
value = value.substring(0, parseInt(modifier, 10)); | |
} | |
result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); | |
} else { | |
if (modifier === "*") { | |
if (Array.isArray(value)) { | |
value.filter(isDefined).forEach(function(value2) { | |
result.push(encodeValue(operator, value2, isKeyOperator(operator) ? key : "")); | |
}); | |
} else { | |
Object.keys(value).forEach(function(k) { | |
if (isDefined(value[k])) { | |
result.push(encodeValue(operator, value[k], k)); | |
} | |
}); | |
} | |
} else { | |
const tmp = []; | |
if (Array.isArray(value)) { | |
value.filter(isDefined).forEach(function(value2) { | |
tmp.push(encodeValue(operator, value2)); | |
}); | |
} else { | |
Object.keys(value).forEach(function(k) { | |
if (isDefined(value[k])) { | |
tmp.push(encodeUnreserved(k)); | |
tmp.push(encodeValue(operator, value[k].toString())); | |
} | |
}); | |
} | |
if (isKeyOperator(operator)) { | |
result.push(encodeUnreserved(key) + "=" + tmp.join(",")); | |
} else if (tmp.length !== 0) { | |
result.push(tmp.join(",")); | |
} | |
} | |
} | |
} else { | |
if (operator === ";") { | |
if (isDefined(value)) { | |
result.push(encodeUnreserved(key)); | |
} | |
} else if (value === "" && (operator === "&" || operator === "?")) { | |
result.push(encodeUnreserved(key) + "="); | |
} else if (value === "") { | |
result.push(""); | |
} | |
} | |
return result; | |
} | |
function parseUrl(template) { | |
return { | |
expand: expand.bind(null, template) | |
}; | |
} | |
function expand(template, context) { | |
var operators = ["+", "#", ".", "/", ";", "?", "&"]; | |
return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function(_23, expression, literal) { | |
if (expression) { | |
let operator = ""; | |
const values = []; | |
if (operators.indexOf(expression.charAt(0)) !== -1) { | |
operator = expression.charAt(0); | |
expression = expression.substr(1); | |
} | |
expression.split(/,/g).forEach(function(variable) { | |
var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); | |
values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); | |
}); | |
if (operator && operator !== "+") { | |
var separator = ","; | |
if (operator === "?") { | |
separator = "&"; | |
} else if (operator !== "#") { | |
separator = operator; | |
} | |
return (values.length !== 0 ? operator : "") + values.join(separator); | |
} else { | |
return values.join(","); | |
} | |
} else { | |
return encodeReserved(literal); | |
} | |
}); | |
} | |
function parse(options) { | |
let method = options.method.toUpperCase(); | |
let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); | |
let headers = Object.assign({}, options.headers); | |
let body; | |
let parameters = omit(options, [ | |
"method", | |
"baseUrl", | |
"url", | |
"headers", | |
"request", | |
"mediaType" | |
]); | |
const urlVariableNames = extractUrlVariableNames(url); | |
url = parseUrl(url).expand(parameters); | |
if (!/^http/.test(url)) { | |
url = options.baseUrl + url; | |
} | |
const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); | |
const remainingParameters = omit(parameters, omittedParameters); | |
const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); | |
if (!isBinaryRequest) { | |
if (options.mediaType.format) { | |
headers.accept = headers.accept.split(/,/).map((preview) => preview.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(","); | |
} | |
if (options.mediaType.previews.length) { | |
const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || []; | |
headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map((preview) => { | |
const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; | |
return `application/vnd.github.${preview}-preview${format}`; | |
}).join(","); | |
} | |
} | |
if (["GET", "HEAD"].includes(method)) { | |
url = addQueryParameters(url, remainingParameters); | |
} else { | |
if ("data" in remainingParameters) { | |
body = remainingParameters.data; | |
} else { | |
if (Object.keys(remainingParameters).length) { | |
body = remainingParameters; | |
} | |
} | |
} | |
if (!headers["content-type"] && typeof body !== "undefined") { | |
headers["content-type"] = "application/json; charset=utf-8"; | |
} | |
if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { | |
body = ""; | |
} | |
return Object.assign({ method, url, headers }, typeof body !== "undefined" ? { body } : null, options.request ? { request: options.request } : null); | |
} | |
function endpointWithDefaults(defaults, route, options) { | |
return parse(merge(defaults, route, options)); | |
} | |
function withDefaults(oldDefaults, newDefaults) { | |
const DEFAULTS2 = merge(oldDefaults, newDefaults); | |
const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2); | |
return Object.assign(endpoint2, { | |
DEFAULTS: DEFAULTS2, | |
defaults: withDefaults.bind(null, DEFAULTS2), | |
merge: merge.bind(null, DEFAULTS2), | |
parse | |
}); | |
} | |
var VERSION2 = "7.0.5"; | |
var userAgent = `octokit-endpoint.js/${VERSION2} ${getUserAgent()}`; | |
var DEFAULTS = { | |
method: "GET", | |
baseUrl: "https://api.github.com", | |
headers: { | |
accept: "application/vnd.github.v3+json", | |
"user-agent": userAgent | |
}, | |
mediaType: { | |
format: "", | |
previews: [] | |
} | |
}; | |
var endpoint = withDefaults(null, DEFAULTS); | |
// node_modules/@octokit/request/dist-web/index.js | |
var import_node_fetch = __toESM(require_browser()); | |
// node_modules/deprecation/dist-web/index.js | |
var Deprecation = class extends Error { | |
constructor(message) { | |
super(message); | |
if (Error.captureStackTrace) { | |
Error.captureStackTrace(this, this.constructor); | |
} | |
this.name = "Deprecation"; | |
} | |
}; | |
// node_modules/@octokit/request-error/dist-web/index.js | |
var import_once = __toESM(require_once()); | |
var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); | |
var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); | |
var RequestError = class extends Error { | |
constructor(message, statusCode, options) { | |
super(message); | |
if (Error.captureStackTrace) { | |
Error.captureStackTrace(this, this.constructor); | |
} | |
this.name = "HttpError"; | |
this.status = statusCode; | |
let headers; | |
if ("headers" in options && typeof options.headers !== "undefined") { | |
headers = options.headers; | |
} | |
if ("response" in options) { | |
this.response = options.response; | |
headers = options.response.headers; | |
} | |
const requestCopy = Object.assign({}, options.request); | |
if (options.request.headers.authorization) { | |
requestCopy.headers = Object.assign({}, options.request.headers, { | |
authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]") | |
}); | |
} | |
requestCopy.url = requestCopy.url.replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]").replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); | |
this.request = requestCopy; | |
Object.defineProperty(this, "code", { | |
get() { | |
logOnceCode(new Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); | |
return statusCode; | |
} | |
}); | |
Object.defineProperty(this, "headers", { | |
get() { | |
logOnceHeaders(new Deprecation("[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`.")); | |
return headers || {}; | |
} | |
}); | |
} | |
}; | |
// node_modules/@octokit/request/dist-web/index.js | |
var VERSION3 = "6.2.3"; | |
function getBufferResponse(response) { | |
return response.arrayBuffer(); | |
} | |
function fetchWrapper(requestOptions) { | |
const log2 = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; | |
if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { | |
requestOptions.body = JSON.stringify(requestOptions.body); | |
} | |
let headers = {}; | |
let status; | |
let url; | |
const fetch = requestOptions.request && requestOptions.request.fetch || globalThis.fetch || /* istanbul ignore next */ | |
import_node_fetch.default; | |
return fetch(requestOptions.url, Object.assign( | |
{ | |
method: requestOptions.method, | |
body: requestOptions.body, | |
headers: requestOptions.headers, | |
redirect: requestOptions.redirect | |
}, | |
// `requestOptions.request.agent` type is incompatible | |
// see https://github.com/octokit/types.ts/pull/264 | |
requestOptions.request | |
)).then(async (response) => { | |
url = response.url; | |
status = response.status; | |
for (const keyAndValue of response.headers) { | |
headers[keyAndValue[0]] = keyAndValue[1]; | |
} | |
if ("deprecation" in headers) { | |
const matches = headers.link && headers.link.match(/<([^>]+)>; rel="deprecation"/); | |
const deprecationLink = matches && matches.pop(); | |
log2.warn(`[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}`); | |
} | |
if (status === 204 || status === 205) { | |
return; | |
} | |
if (requestOptions.method === "HEAD") { | |
if (status < 400) { | |
return; | |
} | |
throw new RequestError(response.statusText, status, { | |
response: { | |
url, | |
status, | |
headers, | |
data: void 0 | |
}, | |
request: requestOptions | |
}); | |
} | |
if (status === 304) { | |
throw new RequestError("Not modified", status, { | |
response: { | |
url, | |
status, | |
headers, | |
data: await getResponseData(response) | |
}, | |
request: requestOptions | |
}); | |
} | |
if (status >= 400) { | |
const data = await getResponseData(response); | |
const error4 = new RequestError(toErrorMessage(data), status, { | |
response: { | |
url, | |
status, | |
headers, | |
data | |
}, | |
request: requestOptions | |
}); | |
throw error4; | |
} | |
return getResponseData(response); | |
}).then((data) => { | |
return { | |
status, | |
url, | |
headers, | |
data | |
}; | |
}).catch((error4) => { | |
if (error4 instanceof RequestError) | |
throw error4; | |
else if (error4.name === "AbortError") | |
throw error4; | |
throw new RequestError(error4.message, 500, { | |
request: requestOptions | |
}); | |
}); | |
} | |
async function getResponseData(response) { | |
const contentType = response.headers.get("content-type"); | |
if (/application\/json/.test(contentType)) { | |
return response.json(); | |
} | |
if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { | |
return response.text(); | |
} | |
return getBufferResponse(response); | |
} | |
function toErrorMessage(data) { | |
if (typeof data === "string") | |
return data; | |
if ("message" in data) { | |
if (Array.isArray(data.errors)) { | |
return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}`; | |
} | |
return data.message; | |
} | |
return `Unknown error: ${JSON.stringify(data)}`; | |
} | |
function withDefaults2(oldEndpoint, newDefaults) { | |
const endpoint2 = oldEndpoint.defaults(newDefaults); | |
const newApi = function(route, parameters) { | |
const endpointOptions = endpoint2.merge(route, parameters); | |
if (!endpointOptions.request || !endpointOptions.request.hook) { | |
return fetchWrapper(endpoint2.parse(endpointOptions)); | |
} | |
const request2 = (route2, parameters2) => { | |
return fetchWrapper(endpoint2.parse(endpoint2.merge(route2, parameters2))); | |
}; | |
Object.assign(request2, { | |
endpoint: endpoint2, | |
defaults: withDefaults2.bind(null, endpoint2) | |
}); | |
return endpointOptions.request.hook(request2, endpointOptions); | |
}; | |
return Object.assign(newApi, { | |
endpoint: endpoint2, | |
defaults: withDefaults2.bind(null, endpoint2) | |
}); | |
} | |
var request = withDefaults2(endpoint, { | |
headers: { | |
"user-agent": `octokit-request.js/${VERSION3} ${getUserAgent()}` | |
} | |
}); | |
// node_modules/@octokit/graphql/dist-web/index.js | |
var VERSION4 = "5.0.5"; | |
function _buildMessageForResponseErrors(data) { | |
return `Request failed due to following response errors: | |
` + data.errors.map((e) => ` - ${e.message}`).join("\n"); | |
} | |
var GraphqlResponseError = class extends Error { | |
constructor(request2, headers, response) { | |
super(_buildMessageForResponseErrors(response)); | |
this.request = request2; | |
this.headers = headers; | |
this.response = response; | |
this.name = "GraphqlResponseError"; | |
this.errors = response.errors; | |
this.data = response.data; | |
if (Error.captureStackTrace) { | |
Error.captureStackTrace(this, this.constructor); | |
} | |
} | |
}; | |
var NON_VARIABLE_OPTIONS = [ | |
"method", | |
"baseUrl", | |
"url", | |
"headers", | |
"request", | |
"query", | |
"mediaType" | |
]; | |
var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; | |
var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; | |
function graphql(request2, query, options) { | |
if (options) { | |
if (typeof query === "string" && "query" in options) { | |
return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`)); | |
} | |
for (const key in options) { | |
if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) | |
continue; | |
return Promise.reject(new Error(`[@octokit/graphql] "${key}" cannot be used as variable name`)); | |
} | |
} | |
const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query; | |
const requestOptions = Object.keys(parsedOptions).reduce((result, key) => { | |
if (NON_VARIABLE_OPTIONS.includes(key)) { | |
result[key] = parsedOptions[key]; | |
return result; | |
} | |
if (!result.variables) { | |
result.variables = {}; | |
} | |
result.variables[key] = parsedOptions[key]; | |
return result; | |
}, {}); | |
const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl; | |
if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { | |
requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); | |
} | |
return request2(requestOptions).then((response) => { | |
if (response.data.errors) { | |
const headers = {}; | |
for (const key of Object.keys(response.headers)) { | |
headers[key] = response.headers[key]; | |
} | |
throw new GraphqlResponseError(requestOptions, headers, response.data); | |
} | |
return response.data.data; | |
}); | |
} | |
function withDefaults3(request2, newDefaults) { | |
const newRequest = request2.defaults(newDefaults); | |
const newApi = (query, options) => { | |
return graphql(newRequest, query, options); | |
}; | |
return Object.assign(newApi, { | |
defaults: withDefaults3.bind(null, newRequest), | |
endpoint: newRequest.endpoint | |
}); | |
} | |
var graphql$1 = withDefaults3(request, { | |
headers: { | |
"user-agent": `octokit-graphql.js/${VERSION4} ${getUserAgent()}` | |
}, | |
method: "POST", | |
url: "/graphql" | |
}); | |
function withCustomRequest(customRequest) { | |
return withDefaults3(customRequest, { | |
method: "POST", | |
url: "/graphql" | |
}); | |
} | |
// node_modules/@octokit/auth-token/dist-web/index.js | |
var REGEX_IS_INSTALLATION_LEGACY = /^v1\./; | |
var REGEX_IS_INSTALLATION = /^ghs_/; | |
var REGEX_IS_USER_TO_SERVER = /^ghu_/; | |
async function auth(token) { | |
const isApp = token.split(/\./).length === 3; | |
const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token); | |
const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token); | |
const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; | |
return { | |
type: "token", | |
token, | |
tokenType | |
}; | |
} | |
function withAuthorizationPrefix(token) { | |
if (token.split(/\./).length === 3) { | |
return `bearer ${token}`; | |
} | |
return `token ${token}`; | |
} | |
async function hook(token, request2, route, parameters) { | |
const endpoint2 = request2.endpoint.merge(route, parameters); | |
endpoint2.headers.authorization = withAuthorizationPrefix(token); | |
return request2(endpoint2); | |
} | |
var createTokenAuth = function createTokenAuth2(token) { | |
if (!token) { | |
throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); | |
} | |
if (typeof token !== "string") { | |
throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string"); | |
} | |
token = token.replace(/^(token|bearer) +/i, ""); | |
return Object.assign(auth.bind(null, token), { | |
hook: hook.bind(null, token) | |
}); | |
}; | |
// node_modules/@octokit/core/dist-web/index.js | |
var VERSION5 = "4.2.0"; | |
var Octokit = class { | |
constructor(options = {}) { | |
const hook2 = new import_before_after_hook.Collection(); | |
const requestDefaults = { | |
baseUrl: request.endpoint.DEFAULTS.baseUrl, | |
headers: {}, | |
request: Object.assign({}, options.request, { | |
// @ts-ignore internal usage only, no need to type | |
hook: hook2.bind(null, "request") | |
}), | |
mediaType: { | |
previews: [], | |
format: "" | |
} | |
}; | |
requestDefaults.headers["user-agent"] = [ | |
options.userAgent, | |
`octokit-core.js/${VERSION5} ${getUserAgent()}` | |
].filter(Boolean).join(" "); | |
if (options.baseUrl) { | |
requestDefaults.baseUrl = options.baseUrl; | |
} | |
if (options.previews) { | |
requestDefaults.mediaType.previews = options.previews; | |
} | |
if (options.timeZone) { | |
requestDefaults.headers["time-zone"] = options.timeZone; | |
} | |
this.request = request.defaults(requestDefaults); | |
this.graphql = withCustomRequest(this.request).defaults(requestDefaults); | |
this.log = Object.assign({ | |
debug: () => { | |
}, | |
info: () => { | |
}, | |
warn: console.warn.bind(console), | |
error: console.error.bind(console) | |
}, options.log); | |
this.hook = hook2; | |
if (!options.authStrategy) { | |
if (!options.auth) { | |
this.auth = async () => ({ | |
type: "unauthenticated" | |
}); | |
} else { | |
const auth2 = createTokenAuth(options.auth); | |
hook2.wrap("request", auth2.hook); | |
this.auth = auth2; | |
} | |
} else { | |
const { authStrategy, ...otherOptions } = options; | |
const auth2 = authStrategy(Object.assign({ | |
request: this.request, | |
log: this.log, | |
// we pass the current octokit instance as well as its constructor options | |
// to allow for authentication strategies that return a new octokit instance | |
// that shares the same internal state as the current one. The original | |
// requirement for this was the "event-octokit" authentication strategy | |
// of https://github.com/probot/octokit-auth-probot. | |
octokit: this, | |
octokitOptions: otherOptions | |
}, options.auth)); | |
hook2.wrap("request", auth2.hook); | |
this.auth = auth2; | |
} | |
const classConstructor = this.constructor; | |
classConstructor.plugins.forEach((plugin) => { | |
Object.assign(this, plugin(this, options)); | |
}); | |
} | |
static defaults(defaults) { | |
const OctokitWithDefaults = class extends this { | |
constructor(...args) { | |
const options = args[0] || {}; | |
if (typeof defaults === "function") { | |
super(defaults(options)); | |
return; | |
} | |
super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent ? { | |
userAgent: `${options.userAgent} ${defaults.userAgent}` | |
} : null)); | |
} | |
}; | |
return OctokitWithDefaults; | |
} | |
/** | |
* Attach a plugin (or many) to your Octokit instance. | |
* | |
* @example | |
* const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) | |
*/ | |
static plugin(...newPlugins) { | |
var _a; | |
const currentPlugins = this.plugins; | |
const NewOctokit = (_a = class extends this { | |
}, _a.plugins = currentPlugins.concat(newPlugins.filter((plugin) => !currentPlugins.includes(plugin))), _a); | |
return NewOctokit; | |
} | |
}; | |
Octokit.VERSION = VERSION5; | |
Octokit.plugins = []; | |
// plugin/commands.ts | |
var import_obsidian13 = require("obsidian"); | |
// plugin/settings/modals/list_changed.ts | |
var import_obsidian12 = require("obsidian"); | |
var ListChangedFiles = class extends import_obsidian12.Modal { | |
constructor(app2, listChanged) { | |
super(app2); | |
this.listChanged = listChanged; | |
} | |
displayListOfFile(toDisplay, contentEl) { | |
if (!toDisplay.length) | |
return; | |
const ul = contentEl.createEl("ul"); | |
toDisplay.forEach((file) => { | |
let emoji = "\u2753"; | |
const ext = file.split(".").pop(); | |
if (["md"].includes(ext)) { | |
emoji = "\u{1F5D2}\uFE0F"; | |
} else if ([".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp"].includes(`.${ext}`)) { | |
emoji = "\u{1F5BC}\uFE0F"; | |
} else if ([".mp3", ".wav", ".ogg", ".flac", ".aac"].includes(`.${ext}`)) { | |
emoji = "\u{1F3B5}"; | |
} else if ([".mp4", ".avi", ".mov", ".mkv", ".webm"].includes(`.${ext}`)) { | |
emoji = "\u{1F3A5}"; | |
} else if ([".pdf"].includes(`.${ext}`)) { | |
emoji = "\u{1F4C4}"; | |
} | |
const li = ul.createEl("li"); | |
li.createEl("span", { text: emoji, cls: "github-publisher emoji" }); | |
li.createEl("code", { text: file, cls: "code-title github-publisher list-changed" }); | |
}); | |
} | |
onOpen() { | |
const { contentEl } = this; | |
contentEl.empty(); | |
contentEl.createEl("h2", { text: instance.t("modals.listChangedFiles.title"), cls: "github-publisher title" }); | |
if (Object.keys(this.listChanged).contains("edited")) { | |
this.listChanged = this.listChanged; | |
contentEl.createEl("h3", { text: `\u{1F4E4} ${instance.t("modals.listChangedFiles.added")}` }); | |
this.displayListOfFile(this.listChanged.added, contentEl); | |
contentEl.createEl("h3", { text: `\u2712\uFE0F ${instance.t("modals.listChangedFiles.edited")}` }); | |
this.displayListOfFile(this.listChanged.edited, contentEl); | |
contentEl.createEl("h3", { text: `\u{1F5D1}\uFE0F ${instance.t("modals.listChangedFiles.deleted")}` }); | |
this.displayListOfFile(this.listChanged.deleted, contentEl); | |
contentEl.createEl("h2", { text: `\u274C ${instance.t("modals.listChangedFiles.error")}`, cls: "github-publisher title error" }); | |
contentEl.createEl("h3", { text: `\u{1F4E4} ${instance.t("modals.listChangedFiles.unpublished")}` }); | |
this.displayListOfFile(this.listChanged.unpublished, contentEl); | |
contentEl.createEl("h3", { text: `\u267B\uFE0F ${instance.t("modals.listChangedFiles.notDeleted")}` }); | |
this.displayListOfFile(this.listChanged.notDeleted, contentEl); | |
} else { | |
this.listChanged = this.listChanged; | |
contentEl.createEl("h3", { text: `\u{1F5D1}\uFE0F ${instance.t("modals.listChangedFiles.deleted")}` }); | |
this.displayListOfFile(this.listChanged.deleted, contentEl); | |
contentEl.createEl("h3", { text: `\u274C ${instance.t("modals.listChangedFiles.error")}`, cls: "github-publisher error" }); | |
contentEl.createEl("h3", { text: `\u267B\uFE0F ${instance.t("modals.listChangedFiles.notDeleted")}` }); | |
this.displayListOfFile(this.listChanged.undeleted, contentEl); | |
} | |
} | |
onClose() { | |
const { contentEl } = this; | |
contentEl.empty(); | |
} | |
}; | |
// plugin/commands.ts | |
function shareAllMarkedNotes(PublisherManager, settings3, octokit, statusBarItems, branchName, repoFrontmatter, sharedFiles, createGithubBranch = true, plugin) { | |
return __async(this, null, function* () { | |
const statusBar3 = new ShareStatusBar(statusBarItems, sharedFiles.length); | |
try { | |
let errorCount = 0; | |
const fileError = []; | |
const listStateUploaded = []; | |
if (sharedFiles.length > 0) { | |
const publishedFiles = sharedFiles.map((file) => file.name); | |
if (createGithubBranch) { | |
const isValid2 = checkRepositoryValidityWithRepoFrontmatter(PublisherManager, settings3, repoFrontmatter); | |
if (!isValid2) | |
return false; | |
yield PublisherManager.newBranch(branchName, repoFrontmatter); | |
} | |
for (let files = 0; files < sharedFiles.length; files++) { | |
try { | |
const file = sharedFiles[files]; | |
statusBar3.increment(); | |
const uploaded = yield PublisherManager.publish( | |
file, | |
false, | |
branchName, | |
repoFrontmatter | |
); | |
if (uploaded) { | |
listStateUploaded.push(...uploaded.uploaded); | |
} | |
} catch (e) { | |
errorCount++; | |
fileError.push(sharedFiles[files].name); | |
new import_obsidian13.Notice( | |
instance.t("error.unablePublishNote", { file: sharedFiles[files].name }) | |
); | |
} | |
} | |
statusBar3.finish(8e3); | |
const noticeValue = `${publishedFiles.length - errorCount} notes`; | |
const deleted = yield deleteFromGithub( | |
true, | |
settings3, | |
octokit, | |
branchName, | |
PublisherManager, | |
repoFrontmatter | |
); | |
if (settings3.upload.metadataExtractorPath.length > 0 && import_obsidian13.Platform.isDesktop) { | |
const metadataExtractor = yield getSettingsOfMetadataExtractor( | |
app, | |
settings3 | |
); | |
if (metadataExtractor) { | |
yield PublisherManager.uploadMetadataExtractorFiles( | |
metadataExtractor, | |
branchName, | |
repoFrontmatter | |
); | |
} | |
} | |
const update = yield PublisherManager.updateRepository( | |
branchName, | |
repoFrontmatter | |
); | |
if (update) { | |
yield noticeMessage( | |
PublisherManager, | |
noticeValue, | |
settings3, | |
repoFrontmatter | |
); | |
if (settings3.plugin.displayModalRepoEditing) { | |
const listEdited = createListEdited(listStateUploaded, deleted, fileError); | |
new ListChangedFiles(plugin.app, listEdited).open(); | |
} | |
} else { | |
new import_obsidian13.Notice( | |
instance.t("error.errorPublish", { repo: repoFrontmatter }) | |
); | |
} | |
} | |
} catch (error4) { | |
console.error(error4); | |
new import_obsidian13.Notice(instance.t("error.unablePublishMultiNotes")); | |
statusBar3.error(); | |
} | |
}); | |
} | |
function deleteUnsharedDeletedNotes(PublisherManager, settings3, octokit, branchName, repoFrontmatter) { | |
return __async(this, null, function* () { | |
try { | |
new import_obsidian13.Notice( | |
instance.t("informations.startingClean", { repo: repoFrontmatter }) | |
); | |
const isValid2 = checkRepositoryValidityWithRepoFrontmatter(PublisherManager, settings3, repoFrontmatter); | |
if (!isValid2) | |
return false; | |
yield PublisherManager.newBranch(branchName, repoFrontmatter); | |
const deleted = yield deleteFromGithub( | |
false, | |
settings3, | |
octokit, | |
branchName, | |
PublisherManager, | |
repoFrontmatter | |
); | |
yield PublisherManager.updateRepository(branchName, repoFrontmatter); | |
if (settings3.plugin.displayModalRepoEditing) | |
new ListChangedFiles(app, deleted).open(); | |
} catch (e) { | |
console.error(e); | |
} | |
}); | |
} | |
function shareOneNote(branchName, PublisherManager, settings3, file, metadataCache, vault) { | |
return __async(this, null, function* () { | |
try { | |
const frontmatter = metadataCache.getFileCache(file).frontmatter; | |
const repoFrontmatter = getRepoFrontmatter(settings3, frontmatter); | |
const isValid2 = checkRepositoryValidityWithRepoFrontmatter(PublisherManager, settings3, repoFrontmatter); | |
if (!isValid2) | |
return false; | |
yield PublisherManager.newBranch(branchName, repoFrontmatter); | |
const publishSuccess = yield PublisherManager.publish( | |
file, | |
true, | |
branchName, | |
repoFrontmatter, | |
[], | |
true | |
); | |
if (publishSuccess) { | |
if (settings3.upload.metadataExtractorPath.length > 0 && import_obsidian13.Platform.isDesktop) { | |
const metadataExtractor = yield getSettingsOfMetadataExtractor( | |
app, | |
settings3 | |
); | |
if (metadataExtractor) { | |
yield PublisherManager.uploadMetadataExtractorFiles( | |
metadataExtractor, | |
branchName, | |
repoFrontmatter | |
); | |
} | |
} | |
const update = yield PublisherManager.updateRepository( | |
branchName, | |
repoFrontmatter | |
); | |
if (update) { | |
yield noticeMessage( | |
PublisherManager, | |
file, | |
settings3, | |
repoFrontmatter | |
); | |
yield createLink( | |
file, | |
repoFrontmatter, | |
metadataCache, | |
vault, | |
settings3 | |
); | |
if (settings3.plugin.displayModalRepoEditing) { | |
const listEdited = createListEdited(publishSuccess.uploaded, publishSuccess.deleted, publishSuccess.error); | |
new ListChangedFiles(app, listEdited).open(); | |
} | |
} else { | |
new import_obsidian13.Notice( | |
instance.t("error.errorPublish", { repo: repoFrontmatter }) | |
); | |
} | |
} | |
} catch (error4) { | |
if (!(error4 instanceof DOMException)) { | |
noticeLog(error4, settings3); | |
new import_obsidian13.Notice( | |
instance.t("error.errorPublish", { repo: getRepoFrontmatter(settings3, metadataCache.getFileCache(file).frontmatter) }) | |
); | |
} | |
} | |
}); | |
} | |
function shareNewNote(PublisherManager, octokit, branchName, vault, plugin, repoFrontmatter) { | |
return __async(this, null, function* () { | |
const settings3 = plugin.settings; | |
new import_obsidian13.Notice(instance.t("informations.scanningRepo")); | |
const sharedFilesWithPaths = PublisherManager.getAllFileWithPath(); | |
const githubSharedNotes = yield PublisherManager.getAllFileFromRepo( | |
repoFrontmatter.branch, | |
// we need to take the master branch because the branch to create doesn't exist yet | |
octokit, | |
settings3, | |
repoFrontmatter | |
); | |
const newlySharedNotes = PublisherManager.getNewFiles( | |
sharedFilesWithPaths, | |
githubSharedNotes, | |
vault | |
); | |
if (newlySharedNotes.length > 0) { | |
new import_obsidian13.Notice( | |
instance.t("informations.foundNoteToSend", { nbNotes: newlySharedNotes.length }) | |
); | |
const statusBarElement = plugin.addStatusBarItem(); | |
const isValid2 = checkRepositoryValidityWithRepoFrontmatter(PublisherManager, settings3, repoFrontmatter); | |
if (!isValid2) | |
return false; | |
yield PublisherManager.newBranch(branchName, repoFrontmatter); | |
yield shareAllMarkedNotes( | |
PublisherManager, | |
plugin.settings, | |
octokit, | |
statusBarElement, | |
branchName, | |
repoFrontmatter, | |
newlySharedNotes, | |
false, | |
plugin | |
); | |
} else { | |
new import_obsidian13.Notice(instance.t("informations.noNewNote")); | |
} | |
}); | |
} | |
function shareAllEditedNotes(PublisherManager, octokit, branchName, vault, plugin, repoFrontmatter) { | |
return __async(this, null, function* () { | |
const settings3 = plugin.settings; | |
new import_obsidian13.Notice(instance.t("informations.scanningRepo")); | |
const sharedFilesWithPaths = PublisherManager.getAllFileWithPath(); | |
const githubSharedNotes = yield PublisherManager.getAllFileFromRepo( | |
repoFrontmatter.branch, | |
octokit, | |
settings3, | |
repoFrontmatter | |
); | |
const newSharedFiles = PublisherManager.getNewFiles( | |
sharedFilesWithPaths, | |
githubSharedNotes, | |
vault | |
); | |
const newlySharedNotes = yield PublisherManager.getEditedFiles( | |
sharedFilesWithPaths, | |
githubSharedNotes, | |
vault, | |
newSharedFiles | |
); | |
if (newlySharedNotes.length > 0) { | |
new import_obsidian13.Notice( | |
instance.t("informations.foundNoteToSend", { nbNotes: newlySharedNotes.length }) | |
); | |
const statusBarElement = plugin.addStatusBarItem(); | |
const isValid2 = checkRepositoryValidityWithRepoFrontmatter(PublisherManager, settings3, repoFrontmatter); | |
if (!isValid2) | |
return false; | |
yield PublisherManager.newBranch(branchName, repoFrontmatter); | |
yield shareAllMarkedNotes( | |
PublisherManager, | |
settings3, | |
octokit, | |
statusBarElement, | |
branchName, | |
repoFrontmatter, | |
newlySharedNotes, | |
false, | |
plugin | |
); | |
} else { | |
new import_obsidian13.Notice(instance.t("informations.noNewNote")); | |
} | |
}); | |
} | |
function shareOnlyEdited(PublisherManager, octokit, branchName, vault, plugin, repoFrontmatter) { | |
return __async(this, null, function* () { | |
const settings3 = plugin.settings; | |
new import_obsidian13.Notice(instance.t("informations.scanningRepo")); | |
const sharedFilesWithPaths = PublisherManager.getAllFileWithPath(); | |
const githubSharedNotes = yield PublisherManager.getAllFileFromRepo( | |
repoFrontmatter.branch, | |
octokit, | |
settings3, | |
repoFrontmatter | |
); | |
const newSharedFiles = []; | |
const newlySharedNotes = yield PublisherManager.getEditedFiles( | |
sharedFilesWithPaths, | |
githubSharedNotes, | |
vault, | |
newSharedFiles | |
); | |
if (newlySharedNotes.length > 0) { | |
new import_obsidian13.Notice( | |
instance.t("informations.foundNoteToSend", { nbNotes: newlySharedNotes.length }) | |
); | |
const statusBarElement = plugin.addStatusBarItem(); | |
const isValid2 = checkRepositoryValidityWithRepoFrontmatter(PublisherManager, settings3, repoFrontmatter); | |
if (!isValid2) | |
return false; | |
yield PublisherManager.newBranch(branchName, repoFrontmatter); | |
yield shareAllMarkedNotes( | |
PublisherManager, | |
settings3, | |
octokit, | |
statusBarElement, | |
branchName, | |
repoFrontmatter, | |
newlySharedNotes, | |
false, | |
plugin | |
); | |
} else { | |
new import_obsidian13.Notice(instance.t("informations.noNewNote")); | |
} | |
}); | |
} | |
// plugin/i18n/i18next.ts | |
var import_obsidian14 = require("obsidian"); | |
// plugin/i18n/locales/en.json | |
var en_exports = {}; | |
__export(en_exports, { | |
commands: () => commands, | |
common: () => common, | |
default: () => en_default, | |
deletion: () => deletion, | |
error: () => error2, | |
informations: () => informations, | |
modals: () => modals, | |
publish: () => publish, | |
regex: () => regex, | |
settings: () => settings, | |
statusBar: () => statusBar | |
}); | |
var commands = { | |
checkValidity: { | |
inBranch: { | |
error403: "Error 403: {{- repo.owner}}/{{- repo.repo}} was moved permanently (from {{- branchInfo}}).", | |
error404: "Error 404: The branch {{- branchInfo}} was not found in {{- repo.owner}}/{{- repo.repo}}." | |
}, | |
inRepo: { | |
error301: "Error 301: {{- repo.owner}}/{{- repo.repo}} was moved permanently.", | |
error403: "Error 403: this action is forbidden for {{- repo.owner}}/{{- repo.repo}}.", | |
error404: "Error 404: {{- repo.owner}}/{{- repo.repo}}: is not found." | |
}, | |
repoExistsTestBranch: "Repository {{- repo.owner}}/{{- repo.repo}} exists. Now testing the {{- main}} branch.", | |
success: "{{- repo.owner}}/{{- repo.repo}} seems to be valid!", | |
title: "Test the connection to the configured repository" | |
}, | |
copyLink: "Create a link to this note", | |
publisherDeleteClean: "Purge depublished and deleted files", | |
shareActiveFile: "Upload single current active note", | |
shareViewFiles: "Upload {{- viewFile}} with Github Publisher", | |
uploadAllEditedNote: "Refresh all published notes", | |
uploadAllNewEditedNote: "Refresh published and upload new notes", | |
uploadAllNotes: "Upload all shared notes", | |
uploadNewNotes: "Upload unpublished notes" | |
}; | |
var common = { | |
add: "Add {{- things}}", | |
after: "After", | |
attachments: "attachments", | |
before: "Before", | |
cancel: "Cancel", | |
close: "Close", | |
delete: "Delete {{- things}}", | |
edit: "Edit {{- things}}", | |
error: "Error", | |
files: "files", | |
here: "here", | |
or: "or", | |
path: { | |
file: "File name", | |
folder: "Folder path", | |
full: "Filepath" | |
}, | |
published: "Published", | |
regex: "regex", | |
save: "Save", | |
shared: "Shared", | |
text: "text", | |
warning: "Warning" | |
}; | |
var deletion = { | |
defaultFolder: "You need a default folder name in the settings to use this command.", | |
failed: "Failed to delete {{- nb}} files.", | |
noFile: "No files have been deleted.", | |
rootFolder: "You need to configure a root folder in the settings to use this command.", | |
success: "Successfully deleted {{- nb}} files." | |
}; | |
var error2 = { | |
dataview: "Unable to render dataview query. Please update the dataview plugin to the last version.", | |
errorConfig: "Error configuring {{- repo.owner}}/{{- repo.repo}}. Please check your settings.", | |
errorPublish: "Error during upload to {{- repo.owner}}/{{- repo.repo}}", | |
isEmpty: "{{- what}} is empty.", | |
mergeconflic: "Pull-request is not mergeable, you need to do it manually.", | |
unablePublishMultiNotes: "Unable to upload multiple notes, something went wrong.", | |
unablePublishNote: "Unable to upload note {{- file}}, skipping it", | |
whatEmpty: { | |
branch: "Branch", | |
ghToken: "GitHub Token", | |
owner: "Owner", | |
repo: "Repository" | |
} | |
}; | |
var informations = { | |
foundNoteToSend: "Found {{- nbNotes}} new notes to send", | |
migrating: { | |
fileReplace: "Migration of filename replace to the new format...", | |
oldSettings: "Migration of old settings to new settings format...", | |
subFolder: "Adding replacing subfolder to the folderpath replacement...", | |
normalFormat: "Migrating settings..." | |
}, | |
noNewNote: "No new notes to upload.", | |
scanningRepo: "Scanning the repository, may take a while...", | |
sendMessage: "Upload {{- nbNotes}} notes to {{- repo.owner}}/{{- repo.repo}}", | |
startingClean: "Starting cleaning {{- repo.owner}}/{{- repo.repo}}", | |
successPublishOneNote: "Successfully uploaded {{- file}} to {{- repo.owner}}/{{- repo.repo}}", | |
successfullPublish: "Successfully uploaded {{- nbNotes}} to {{- repo.owner}}/{{- repo.repo}}", | |
waitingWorkflow: "Now, waiting for the workflow to be completed..." | |
}; | |
var modals = { | |
export: { | |
copy: "Copy to clipboard", | |
desc: "Export settings to clipboard or a file.", | |
download: "Download", | |
title: "Export settings" | |
}, | |
import: { | |
desc: "Import settings from text or a file. Note : this will overwrite your current settings (except for username, repo name and token).", | |
error: { | |
isEmpty: "the configuration is empty.", | |
span: "Error importing configuration: " | |
}, | |
importFromFile: "Import from file", | |
paste: "Paste configuration here...", | |
title: "Import settings" | |
}, | |
listChangedFiles: { | |
added: "Added", | |
deleted: "Deleted", | |
edited: "Edited", | |
error: "Errors", | |
notDeleted: "Cannot be deleted", | |
title: "List of files edited in the repository", | |
unpublished: "Cannot be published" | |
} | |
}; | |
var publish = { | |
branch: { | |
alreadyExists: "Branch already exists ({{- branchName}} on {{- repo.owner}}/{{- repo.repo}} - Using it.", | |
error: "Error with {{- repo.owner}}/{{- repo.repo}}: {{- error}}", | |
prMessage: "Pull-Request [{{- branchName}}] from Obsidian", | |
success: "Branch successfully created (status: {{- branchStatus}}) on {{- repo.owner}}/{{- repo.repo}}" | |
} | |
}; | |
var regex = { | |
entry: "Value to replace", | |
replace: "Replacement" | |
}; | |
var settings = { | |
conversion: { | |
dataview: { | |
desc: "Convert dataview to markdown.", | |
title: "Dataview" | |
}, | |
desc: "Theses option won't change the content of the file in your Obsidian Vault, but will change the content of the file in Github.", | |
hardBreak: { | |
desc: "Add a markdown hard line break (double whitespace) after each line.", | |
title: "Markdown hard line break" | |
}, | |
links: { | |
desc: 'You can prevent links to be converted and keep the alt text (or filename) by using the frontmatter key "links" with the value "false".', | |
folderNote: { | |
desc: "Rename files to a specified name (default: index.md) if it has the same name as their parent folder/category (also works if the note is outside of the folder).", | |
title: "Folder note" | |
}, | |
internals: { | |
desc: "Convert internal links to their counterpart in the repository, with relative path.", | |
title: "Internals Links" | |
}, | |
nonShared: { | |
desc: "Same option as internals, but for notes that are not yet published. Disabled, only the filename will be conserved.", | |
title: "Convert internal links pointing to unpublished notes" | |
}, | |
slugify: { | |
title: "Sluglify anchor in markdown links", | |
desc: "Anchors (pointing to titles) will be slugified by transforming the text to lower case and replacing spaces with dashes. Only works for markdown links (including transformation from wikilinks)." | |
}, | |
title: "Links", | |
wikilinks: { | |
desc: "Convert Wikilinks to MDlinks, without changing the contents.", | |
title: "[[Wikilinks]] to [MDlinks](links)" | |
} | |
}, | |
sectionTitle: "Main text", | |
tags: { | |
desc: "This will convert any frontmatter or dataview inline field into frontmatter tags. Separate fields with a comma.", | |
exclude: { | |
desc: "This will exclude value from being converted. Separate fields with a comma.", | |
title: "Exclude value from conversion" | |
}, | |
inlineTags: { | |
desc: 'Add your inline tags in your frontmatter tags field and converting nested tags with replacing "/" with "_"', | |
title: "Inline tags" | |
}, | |
title: "Convert frontmatter/dataview field into tags" | |
}, | |
title: "Content's conversion" | |
}, | |
embed: { | |
defaultImageFolder: { | |
desc: "To use a folder different from default", | |
title: "Default attachment folder" | |
}, | |
title: "Embed", | |
transferImage: { | |
desc: "Send attachments embedded in a file to GitHub.", | |
title: "Transfer attachments" | |
}, | |
transferMetaFile: { | |
desc: "Set the names of the metadata field you want to use to send files. Separate fields with a comma. Dataview inline field are supported.", | |
title: "Send files using a metadata field" | |
}, | |
transferNotes: { | |
desc: "Send embedded notes in a shared file to GitHub. Only shared files will be send!", | |
title: "Transfer embedded notes" | |
} | |
}, | |
github: { | |
apiType: { | |
desc: "Choose between the Github API or the Github Enterprise API (only Github Enterprise users \u2014 Advanced user!).", | |
dropdown: { | |
enterprise: "Enterprise", | |
free: "Free/Pro/Team (default)" | |
}, | |
hostname: { | |
desc: "The hostname of your Github Enterprise instance.", | |
title: "Github Enterprise Hostname" | |
}, | |
title: "API Type" | |
}, | |
automaticallyMergePR: "Automatically merge pull requests", | |
branch: { | |
desc: 'If you use a different branch than "main"', | |
title: "Main branch" | |
}, | |
ghToken: { | |
desc: "A GitHub token with repository permission. You can generate it ", | |
title: "Github Token" | |
}, | |
repoName: { | |
desc: "The name of the repository where you store your blog.", | |
placeholder: "mkdocs-template", | |
title: "Repository Name" | |
}, | |
testConnection: "Test connection", | |
title: "GitHub Configuration", | |
username: { | |
desc: "Your GitHub username.", | |
title: "Github Username" | |
} | |
}, | |
githubWorkflow: { | |
autoCleanUp: { | |
desc: "If the plugin must remove from GitHub the depublished files (stop share or deleted)", | |
title: "Auto clean up" | |
}, | |
excludedFiles: { | |
desc: 'If you want to exclude some folder or file from the autoclean, add them here. You can use regex by surrounding the string with "/". Separate files with a comma.', | |
title: "Excluded files and folder" | |
}, | |
githubAction: { | |
desc: 'If you want to activate a GitHub action when the plugin push the file, set the name of the file (in your .github/worfklows folder). Only workflow with the "workflow_dispatch" event will be triggered.', | |
title: "Github action name" | |
}, | |
prRequest: { | |
desc: "The message send when the pull-request is merged. Will always followed by the pull-request number.", | |
error: "You can't use an empty string here!", | |
title: "Commit message" | |
}, | |
useMetadataExtractor: { | |
desc: "Send the files generated by the metadata-extractor plugin in this folder.", | |
title: "Metadata-extractor files" | |
} | |
}, | |
help: { | |
frontmatter: { | |
attachment: { | |
folder: "Change the default folder for the attachments", | |
send: "Send all attachments to GitHub" | |
}, | |
autoclean: "Disable or enable autocleaning", | |
baselink: { | |
base: "Base link", | |
desc: "Change the base link for the copy link command. Also disable the link replacer part. Can be used as an YAML object with the name ", | |
remove: "Remove part of the link. It must be a list!" | |
}, | |
convert: { | |
enableOrDisable: "Enable or disable the conversion of links. Disabling this will remove the", | |
syntax: "syntax, while keeping the file name or the alternative text." | |
}, | |
dataview: "Convert dataview queries to markdown.", | |
desc: "Moreover, there are some frontmatter YAML keys that can be usefull for your workflow. The YAML code below show the default settings, but feel free to change it to your needs in each notes!", | |
embed: { | |
remove: "Remove the embed from the note, leaving empty line.", | |
send: "Send embedded note to GitHub" | |
}, | |
hardBreak: "Convert all linebreaks to markdown \xABhard break\xBB.", | |
internals: "Convert internals links to their counterpart in the website, with relative path. Disabled, the plugin will keep the internal link as is.", | |
mdlinks: "Convert all [[wikilinks]] to [markdown](links)", | |
nonShared: "Convert internal links pointing to a unshared file to their counterpart in the website, with relative path. Disabled, the plugin will keep the filename.", | |
path: "You can override all path settings using this key. The path will be relative to the root of your repository.", | |
repo: { | |
branch: "Branch of the repo", | |
desc: "Change the default repo for the note.", | |
owner: "Owner of the repo", | |
repo: "Name of the repo" | |
}, | |
share: "This key is used to share a note with the plugin.", | |
title: "Frontmatter keys cheatsheet", | |
titleKey: "Change the title of the note." | |
}, | |
multiRepoHelp: { | |
desc: "If you want to send your notes to multiple repository, you can use the ", | |
desc2: "key in your frontmatter. The value of this key must be a list of repository. Each repository must have the following keys ", | |
exampleDesc: "The YAML code below show an example based on your settings.", | |
title: "Send to multiple repository" | |
}, | |
title: "Help", | |
usefulLinks: { | |
discussion: "Discussion", | |
documentation: "Documentation", | |
issue: "Issue", | |
links: "https://obsidian-publisher.netlify.app/", | |
repository: "Repository", | |
title: "Useful links" | |
} | |
}, | |
plugin: { | |
copyLink: { | |
baselink: { | |
desc: "The base link of your website. By default : https://username.github.io/repo/", | |
title: "Base link" | |
}, | |
command: { | |
desc: "Add a command to copy the link of the note (need reloading the plugin to take effect)", | |
onActivation: "Link copied to your clipboard" | |
}, | |
desc: "Send a link to your note in your clipboard", | |
linkpathremover: { | |
desc: "Remove this part from the created links. Separate by comma if multiple value must be removed.", | |
title: "Remove link part" | |
}, | |
title: "Copy link" | |
}, | |
editorMenu: { | |
desc: "Add a sharing commands in the right-click menu", | |
title: "Editor Menu" | |
}, | |
embedEditRepo: { | |
desc: "Display the editions on the repository", | |
title: "Allows to display the list of edited, added, deleted files... From the main repository (in a modal)." | |
}, | |
excludedFolder: { | |
desc: "Never publish file in these folder, regardless of the share key. Separate folder name by comma.", | |
title: "Excluded Folder" | |
}, | |
fileMenu: { | |
desc: "Add an sharing commands in the file menu", | |
title: "File Menu" | |
}, | |
logNoticeHeader: { | |
desc: "On mobile, it can be hard to debug the plugin. Enable this option to log every error in a Notice.", | |
title: "Notice every error" | |
}, | |
shareExternalModified: {}, | |
shareKey: { | |
desc: "The frontmatter key to publish your file on the website.", | |
title: "Share Key" | |
}, | |
title: "Plugin Settings" | |
}, | |
regexReplacing: { | |
empty: "Replacement can be empty to remove the whole string.", | |
forbiddenValue: "The {{- what}} cannont contain the character: {{- forbiddenChar}}", | |
modal: { | |
desc: 'Replace text in the file with the given value. Enclose the text with "//" to use regex.', | |
title: { | |
all: "Folder path & filename replacer", | |
only: "Replace filename", | |
text: "Text replacer" | |
} | |
}, | |
momentReplaceRegex: "Run replacement {{- moment}} the other plugin conversion (dataview, internals links...)", | |
warningPath: 'Warning! Using the character "/" will edit the path, be careful with this option.' | |
}, | |
upload: { | |
defaultFolder: { | |
desc: "Set the default reception folder. Let it empty to use the root of the repository.", | |
placeholder: "docs", | |
title: "Default Folder" | |
}, | |
filepathRegex: {}, | |
folderBehavior: { | |
desc: "Choose the file tree in the repository, with using a frontmatter key, a fixed folder or your Obsidian file tree.", | |
fixedFolder: "Fixed Folder", | |
obsidianPath: "Obsidian Path", | |
title: "File tree in repository", | |
yaml: "YAML frontmatter" | |
}, | |
frontmatterKey: { | |
desc: "Set the key where to get the folder's value.", | |
placeholder: "category", | |
title: "Frontmatter key" | |
}, | |
regexFilePathTitle: { | |
desc: 'If the text is between "//", it will be used as a regex. Otherwise, it will be used as a string.', | |
title: { | |
FolderPathTitle: "Apply edit on the folder path or the filename (automatically)", | |
titleOnly: "Apply edit on the filename (automatically)" | |
} | |
}, | |
rootFolder: { | |
desc: "Append this path to the folder set by the frontmatter key", | |
title: "Root folder" | |
}, | |
title: "Upload configuration", | |
useFrontmatterTitle: { | |
desc: 'Use a frontmatter value to generate the filename. By default, "title" is used. ', | |
title: "Set the key where to get the value of the filename" | |
} | |
} | |
}; | |
var statusBar = { | |
counter: "{{- msg}}: {{- counter}}/{{- nb}}", | |
markedForSharing: "{{- nb}} {{- type}} marked for sharing", | |
sharing: "\u231BSharing {{- type}}", | |
success: "\u2705 {{- action}} {{- type}}" | |
}; | |
var en_default = { | |
commands, | |
common, | |
deletion, | |
error: error2, | |
informations, | |
modals, | |
publish, | |
regex, | |
settings, | |
statusBar | |
}; | |
// plugin/i18n/locales/fr.json | |
var fr_exports = {}; | |
__export(fr_exports, { | |
commands: () => commands2, | |
common: () => common2, | |
default: () => fr_default, | |
deletion: () => deletion2, | |
error: () => error3, | |
informations: () => informations2, | |
modals: () => modals2, | |
publish: () => publish2, | |
regex: () => regex2, | |
settings: () => settings2, | |
statusBar: () => statusBar2 | |
}); | |
var commands2 = { | |
checkValidity: { | |
inBranch: { | |
error403: "Erreur 403: {{- repo.owner}}/{{- repo.repo}} a \xE9t\xE9 d\xE9plac\xE9 de mani\xE8re permanente (depuis {{- branchInfo}}", | |
error404: "Erreur 404 : La branche {{- repo.branch}} est introuvable depuis {{- repo.owner}}/{{- repo.repo}}" | |
}, | |
inRepo: { | |
error301: "Erreur 301 : {{- repo.owner}}/{{- repo.repo}} a \xE9t\xE9 d\xE9plac\xE9 de mani\xE8re permanente", | |
error403: "Erreur 403 : Cette action est interdite pour {{- repo.owner}}/{{- repo.repo}}", | |
error404: "Erreur 404 : {{- repo.owner}}/{{- repo.repo}} est introuvable" | |
}, | |
repoExistsTestBranch: "Le d\xE9p\xF4t {{- repo.owner}}/{{- repo.repo}} existe. Maintenant, nous allons tester la branche {{- repo.branch}}", | |
success: "{{- repo.owner}}/{{- repo.repo}} semble valide !", | |
title: "Tester la connexion au d\xE9p\xF4t configur\xE9" | |
}, | |
copyLink: "Cr\xE9er un lien vers cette note", | |
publisherDeleteClean: "Purger les fichiers d\xE9publi\xE9s et supprim\xE9s", | |
shareActiveFile: "Transf\xE9rer la note active", | |
shareViewFiles: "Transf\xE9rer {{- viewFile}} avec Github Publisher", | |
uploadAllEditedNote: "Rafra\xEEchir toutes les notes publi\xE9es", | |
uploadAllNewEditedNote: "Rafra\xEEchir les notes publi\xE9es et transf\xE9rer les nouvelles notes", | |
uploadAllNotes: "Transf\xE9rer toutes les notes", | |
uploadNewNotes: "Transf\xE9rer les nouvelles notes" | |
}; | |
var common2 = { | |
add: "Ajouter {{- things}}", | |
after: "Apr\xE8s", | |
attachments: "pi\xE8ces-jointes", | |
before: "Avant", | |
cancel: "Annuler", | |
close: "Fermer", | |
delete: "Supprimer {{- things}}", | |
edit: "\xC9diter {{- things}}", | |
error: "Erreur", | |
files: "fichiers", | |
here: "ici", | |
or: "ou", | |
path: { | |
file: "Nom du fichier", | |
folder: "Chemin du dossier", | |
full: "Chemin du fichier" | |
}, | |
published: "publi\xE9s", | |
regex: "regex", | |
save: "Sauvegarder", | |
shared: "partag\xE9s", | |
text: "texte", | |
warning: "Attention" | |
}; | |
var deletion2 = { | |
defaultFolder: "Vous avez besoin d'un dossier par d\xE9faut dans les param\xE8tres pour utiliser cette commande.", | |
failed: "\xC9chec de la suppression de {{- nb}} notes.", | |
noFile: "Aucun fichier n'a \xE9t\xE9 supprim\xE9.", | |
rootFolder: "Vous devez configurer un dossier racine dans les param\xE8tres pour utiliser cette commande.", | |
success: "Suppression r\xE9ussie de {{- nb}} fichiers." | |
}; | |
var error3 = { | |
dataview: "Impossible de convertir la requ\xEAte Dataview. Veuillez mettre \xE0 jour le module Dataview \xE0 la derni\xE8re version;", | |
errorConfig: "Erreur de configuration pour {{- repo.owner}}/{{- repo.repo}}:{{- repo.branch}}. Merci de v\xE9rifier vos param\xE8tres.", | |
errorPublish: "Erreur lors de la publication sur {{- repo.owner}}/{{- repo.repo}}:{{- repo.branch}}", | |
isEmpty: "{{- what}} est vide.", | |
mergeconflic: "La Pull-Request n'est pas fusionnale, vous avez besoin de le faire manuellement.", | |
unablePublishMultiNotes: "Impossible de transf\xE9rer plusieurs notes, quelque chose s'est mal pass\xE9.", | |
unablePublishNote: "Impossible de transf\xE9rer {{- file}}, le fichier a \xE9t\xE9 ignor\xE9.", | |
whatEmpty: { | |
branch: "Branch", | |
ghToken: "Github Token", | |
owner: "Propri\xE9taire", | |
repo: "D\xE9p\xF4t" | |
} | |
}; | |
var informations2 = { | |
foundNoteToSend: "Trouv\xE9 {{- nbNotes}} nouvelles notes \xE0 transf\xE9rer.", | |
migrating: { | |
fileReplace: "Migration du remplacement du nom du fichier au nouveau format...", | |
oldSettings: "Migration des anciens param\xE8tres au nouveau format...", | |
subFolder: "Ajout du remplacement du sous-dossier au remplacement de chemin de fichier...", | |
normalFormat: "Migration des param\xE8tres..." | |
}, | |
noNewNote: "Aucune note \xE0 transf\xE9rer.", | |
scanningRepo: "Scan du d\xE9p\xF4t, veuillez patienter...", | |
sendMessage: "Transfert de {{- nbNotes}} notes vers {{- repo.owner}}/{{- repo.repo}}", | |
startingClean: "D\xE9but du nettoyage de {{- repo.owner}}/{{- repo.repo}}", | |
successPublishOneNote: "Transfert r\xE9ussi de {{- file}} vers {{- repo.owner}}/{{- repo.repo}}", | |
successfullPublish: "Transfert r\xE9ussi de {{- nbNotes}} notes vers {{- repo.owner}}/{{- repo.repo}}", | |
waitingWorkflow: "Maintenant, attente de la fin du workflow..." | |
}; | |
var modals2 = { | |
export: { | |
copy: "Copier vers le presse-papier", | |
desc: "Exporter les param\xE8tres vers un fichier ou dans le presse-papier.", | |
download: "T\xE9l\xE9charger", | |
title: "Exporter les param\xE8tres" | |
}, | |
import: { | |
desc: "Importer des param\xE8tres depuis un fichier ou un texte. Cela \xE9crasera vos param\xE8tres actuels (sauf le nom du d\xE9p\xF4t, le nom d'utilisateur et votre token)", | |
error: { | |
isEmpty: "la configuration est vide", | |
span: "Erreur lors de l'importation de la configuration :" | |
}, | |
importFromFile: "Import depuis le fichier", | |
paste: "Coller la configuration ici...", | |
title: "Importer des param\xE8tres" | |
}, | |
listChangedFiles: { | |
added: "Ajout\xE9", | |
deleted: "Supprim\xE9", | |
edited: "Modifi\xE9", | |
error: "Erreurs", | |
notDeleted: "Impossible \xE0 supprimer", | |
title: "Liste des fichiers \xE9dit\xE9s sur le d\xE9p\xF4t", | |
unpublished: "Impossible \xE0 publier" | |
} | |
}; | |
var publish2 = { | |
branch: { | |
alreadyExists: "La branche {{- branchName}} sur {{- repo.owner}}/{{- repo.repo}} existe d\xE9j\xE0 - Utilisation de celle-ci.", | |
error: "Erreur avec {{- repo.owner}}/{{- repo.repo}} : {{- error}}", | |
prMessage: "Pull-Request [{{- branchName}}] depuis Obsidian", | |
success: "La branche a \xE9t\xE9 cr\xE9e avec succ\xE8s (status: {{- branchStatus}} sur {{- repo.owner}}/{{- repo.repo}})" | |
} | |
}; | |
var regex2 = { | |
entry: "Valeur \xE0 remplacer", | |
replace: "Remplacement" | |
}; | |
var settings2 = { | |
conversion: { | |
dataview: { | |
desc: "Convertir les requ\xEAtes Dataview en markdown.", | |
title: "Dataview" | |
}, | |
desc: "Ces options ne changent pas le contenu du fichier dans votre coffre Obsidian, mais changeront le contenu du fichier publi\xE9 sur GitHub.", | |
hardBreak: { | |
desc: "Ajoutez un retour \xE0 la ligne Markdown (double espace) apr\xE8s chaque ligne.", | |
title: "Saut de ligne strict" | |
}, | |
links: { | |
desc: 'Vous pouvez emp\xEAcher la conversion des liens et conserver le texte alt (ou le nom du fichier) en utilisant la cl\xE9 frontmatter "links" avec la valeur "false".', | |
folderNote: { | |
desc: `Renommer les fichiers en un nom sp\xE9cifique (d\xE9faut : "index.md") s'il porte le m\xEAme nom que leur dossier/cat\xE9gorie parent (fonctionne aussi si la note est \xE0 l'ext\xE9rieur du dossier).`, | |
title: "Folder Note" | |
}, | |
internals: { | |
desc: "Convertir les liens internes pointant vers les notes publi\xE9es vers leur homologue dans le d\xE9p\xF4t, sous forme de chemin relatif.", | |
title: "Liens internes" | |
}, | |
nonShared: { | |
desc: "L'option pr\xE9c\xE9dente, mais appliqu\xE9es aux liens internes pointant vers des notes non-publi\xE9es. D\xE9sactiv\xE9, seul le nom du fichier sera conserv\xE9.", | |
title: "Conversion des liens internes pointant vers des notes non-publi\xE9es" | |
}, | |
slugify: { | |
title: "Slugifier l'ancre des liens markdown", | |
desc: "Les ancres (pointant vers les titres) seront slugifi\xE9s en transformant le texte en minuscule et rempla\xE7ant les espace par des tirets. Ne fonctionne uniquement pour des liens markdown (incluant la transformation depuis les wikilinks)." | |
}, | |
title: "Liens", | |
wikilinks: { | |
desc: "Conversion des liens wikilinks en liens Markdown, sans en modifier le contenu.", | |
title: "Convertir [[WikiLinks]] en [liens](Markdown)" | |
} | |
}, | |
sectionTitle: "Texte principal", | |
tags: { | |
desc: "Ceci convertira tous les champs du frontmatter/dataview en tags. S\xE9parez les champs par une virgule.", | |
exclude: { | |
desc: "Exclusion de champs de la conversion. S\xE9parer les valeurs par une virgule.", | |
title: "Exclusion de tags" | |
}, | |
inlineTags: { | |
desc: 'Ajoute vos inlines tags dans votre bloc frontmatter et converti les tags imbriqu\xE9s en rempla\xE7ant "/" par "_".', | |
title: "Inlines tags" | |
}, | |
title: "Convertir des champs dataview ou frontmatter en tags" | |
}, | |
title: "Conversion du contenu" | |
}, | |
embed: { | |
defaultImageFolder: { | |
desc: "Pour utiliser un dossier diff\xE9rent de celui par d\xE9faut pour les pi\xE8ces-jointes.", | |
title: "Dossier de pi\xE8ces-jointes par d\xE9faut" | |
}, | |
title: "Embed", | |
transferImage: { | |
desc: "Transf\xE9rer les pi\xE8ces-jointes", | |
title: "Envoyer les pi\xE8ces-jointes int\xE9gr\xE9es dans un fichier dans le d\xE9p\xF4t." | |
}, | |
transferMetaFile: { | |
desc: "Permet d'envoyer des fichiers en utilisant une cl\xE9 frontmatter/dataview. S\xE9parer les champs par une virgule.", | |
title: "Envoyer des fichiers en utilisant une cl\xE9 frontmatter/dataview" | |
}, | |
transferNotes: { | |
desc: "Envoyer les notes int\xE9gr\xE9es dans un fichier publi\xE9 dans le d\xE9p\xF4t. Seul les fichiers publi\xE9s seront envoy\xE9s !", | |
title: "Transf\xE9rer les notes int\xE9gr\xE9es" | |
} | |
}, | |
github: { | |
apiType: { | |
desc: "Choisir entre l'API GitHub ou l'API pour GitHub Entreprise (uniquement pour les utilisateurs de GitHub Enterprise \u2014 Utilisateur avanc\xE9 !).", | |
dropdown: { | |
enterprise: "Entreprise", | |
free: "Free/Pro/Team (d\xE9faut)" | |
}, | |
hostname: { | |
desc: "Le nom de l'instance Github de votre entreprise.", | |
title: "Instance Github Entreprise" | |
}, | |
title: "Type d'API" | |
}, | |
automaticallyMergePR: "Fusionner automatiquement les pull-request", | |
branch: { | |
desc: 'Dans le cas o\xF9 vous souhaitez utiliser une branche diff\xE9rente de "main".', | |
title: "Branche principale" | |
}, | |
ghToken: { | |
desc: "Un token GitHub avec autorisation de d\xE9p\xF4t. Vous pouvez le g\xE9n\xE9rer ", | |
title: "Token Github" | |
}, | |
repoName: { | |
desc: "Le nom du d\xE9p\xF4t dans lequel vos fichiers seront transf\xE9r\xE9s.", | |
placeholder: "mkdocs-template", | |
title: "Nom du d\xE9p\xF4t" | |
}, | |
testConnection: "Tester la connexion", | |
title: "Configuration GitHub", | |
username: { | |
desc: "Votre username sur GitHub.", | |
title: "Nom d'utilisateur GitHub" | |
} | |
}, | |
githubWorkflow: { | |
autoCleanUp: { | |
desc: "Si le plugin doit supprimer de votre d\xE9p\xF4t les fichiers d\xE9publi\xE9s (arr\xEAt du partage ou suppression).", | |
title: "Auto-nettoyage" | |
}, | |
excludedFiles: { | |
desc: "Si vous voulez exclure certains dossier ou fichier du nettoyage automatique, d\xE9finissez leur chemin. Les regex sont accept\xE9es en les encadrant par des slashs. S\xE9parer les valeurs par une virgule.", | |
title: "fichiers et dossier exclus" | |
}, | |
githubAction: { | |
desc: "Si vous souhaitez activer une action GitHub lorsque le plugin push les fichiers dans le d\xE9p\xF4t, il vous faut indiquer le nom du fichier issus du dossier .github/workflows/. Seules les actions activ\xE9es par un workflow_dispatch sont activ\xE9es.", | |
title: "Nom de l'action GitHub" | |
}, | |
prRequest: { | |
desc: "Le message envoy\xE9 lorsque la pull-request est fusionn\xE9e. Sera toujours suivi par le num\xE9ro de la pull-request.", | |
error: "Vous ne pouvez pas utiliser une valeur vide pour le message de commit.", | |
title: "Message de commit" | |
}, | |
useMetadataExtractor: { | |
desc: "Envoyer les fichiers g\xE9n\xE9r\xE9s par metadata-extractor dans ce dossier.", | |
title: "Fichier de metadata-extractor" | |
} | |
}, | |
help: { | |
frontmatter: { | |
attachment: { | |
folder: "Change le dossier par d\xE9faut pour les pi\xE8ces-jointes.", | |
send: "Envoie toutes les pi\xE8ces-jointes dans le d\xE9p\xF4t GitHub." | |
}, | |
autoclean: "D\xE9sactive ou active le nettoyage automatique du d\xE9p\xF4t GitHub.", | |
baselink: { | |
base: "Lien de base", | |
desc: "Change le lien de base pour la commande de copie de lien. D\xE9sactive aussi la suppression de partie de lien. Peut \xEAtre utilis\xE9e en tant qu'objet sous le nom de ", | |
remove: "Supprime les parties de lien. \xC0 mettre sous forme de liste !" | |
}, | |
convert: { | |
enableOrDisable: "Active ou d\xE9sactive la conversion des liens. En d\xE9sactivant cette option, vous supprimez les", | |
syntax: "syntaxes, tout en gardant le nom du fichier ou son text alternatif." | |
}, | |
dataview: "Convertit les requ\xEAtes dataview en markdown.", | |
desc: "Il existe quelques cl\xE9s YAML qui peuvent vous \xEAtes utile. Le code ci-dessous montre les param\xE8tres par d\xE9faut, mais n'h\xE9sitez pas \xE0 le modifier selon vos besoins pour chaque note !", | |
embed: { | |
remove: "Supprime les notes int\xE9gr\xE9es du fichier partag\xE9s en ne laissant qu'une ligne vide.", | |
send: "Envoie les notes int\xE9gr\xE9es de la note publi\xE9es dans le d\xE9p\xF4t. Seules les notes partag\xE9es seront envoy\xE9es !" | |
}, | |
hardBreak: 'Convertit tous les sauts de lignes en "hard break" markdown.', | |
internals: "Convertit les liens internes vers leur homologue du d\xE9p\xF4t, sous forme de liens relatifs. D\xE9sactiv\xE9s, les liens seront conserv\xE9s tels quels.", | |
mdlinks: "Convertir tous les liens [[wikilinks]] en [liens](Markdown)", | |
nonShared: "Convertit les liens internes pointat vers une notes non publi\xE9es vers son futur homologue. D\xE9sactiv\xE9, le plugin conservera le nom du fichier ou son texte alternatif.", | |
path: "Vous pouvez \xE9craser tous les param\xE8tres de chemins en utilisant cette cl\xE9. Le chemin sera cr\xE9\xE9e \xE0 partir de la racine du d\xE9p\xF4t.", | |
repo: { | |
branch: "Nom de la branche", | |
desc: "Changer le d\xE9p\xF4t GitHub pour cette note", | |
owner: "Pseudo GitHub du propri\xE9taire du d\xE9p\xF4t", | |
repo: "Nom du d\xE9p\xF4t" | |
}, | |
share: "La cl\xE9 utilis\xE9e pour partager une note", | |
title: "Aide-m\xE9moire frontmatter", | |
titleKey: "Change le titre de la note" | |
}, | |
multiRepoHelp: { | |
desc: "Si vous souhaitez envoyer vos notes dans plusieurs d\xE9p\xF4t en m\xEAme temps, vous pouvez utiliser la cl\xE9 ", | |
desc2: "dans votre frontmatter. La valeur de cette cl\xE9 doit \xEAtre une liste. Chaque d\xE9p\xF4t doit avoir les cl\xE9s suivantes :", | |
exampleDesc: "Le code YAML ci-dessous montre un exemple bas\xE9 sur vos param\xE8tres.", | |
title: "Envoie dans plusieurs d\xE9p\xF4t" | |
}, | |
title: "Aide", | |
usefulLinks: { | |
discussion: "Discussion", | |
documentation: "Documentation (en anglais)", | |
issue: "Issue", | |
links: "https://obsidian-publisher.netlify.app", | |
repository: "D\xE9p\xF4t", | |
title: "Liens utiles" | |
} | |
}, | |
plugin: { | |
copyLink: { | |
baselink: { | |
desc: 'Permet de cr\xE9er un lien dans le presse-papier avec cette base. Par d\xE9faut : "https://username.github.io/repo/"', | |
title: "Lien du d\xE9p\xF4t/blog" | |
}, | |
command: { | |
desc: "Ajouter une commande permettant de copier le lien de la note publi\xE9e dans le presse-papier (n\xE9cessite de recharger le plugin pour prendre effet)", | |
onActivation: "Lien copi\xE9 dans le presse-papier !" | |
}, | |
desc: "Envoie d'un lien vers la note publi\xE9es dans votre presse-papier.", | |
linkpathremover: { | |
desc: "Supprimer cette partie des liens cr\xE9\xE9s. S\xE9parer par une virgule si plusieurs valeurs doivent \xEAtre supprim\xE9es.", | |
title: "Suppression d'une partie du lien" | |
}, | |
title: "Copie de lien" | |
}, | |
editorMenu: { | |
desc: "Ajouter une commande de partage dans le menu du clic droit.", | |
title: 'Menu "Edition"' | |
}, | |
embedEditRepo: { | |
desc: "Permet d'afficher la liste des fichiers \xE9diter, ajout\xE9, supprim\xE9... Du d\xE9p\xF4t principal (dans un modal).", | |
title: "Afficher les \xE9ditions sur le d\xE9p\xF4t" | |
}, | |
excludedFolder: { | |
desc: "Les fichiers dans ses dossiers ne seront jamais publi\xE9s, quelle que soit l'\xE9tat de la cl\xE9 de partage. S\xE9parez les noms de dossier par une virgule.", | |
title: "Dossiers exclus" | |
}, | |
fileMenu: { | |
desc: 'Ajouter une commande de partage dans le menu "Fichier"', | |
title: 'Menu "Fichier"' | |
}, | |
logNoticeHeader: { | |
desc: "Sur mobile, il peut \xEAtre difficile de debug le module. Activer cette option pour notifier toutes les erreurs via une notification Obsidian.", | |
title: "Notifier toutes les erreurs" | |
}, | |
shareExternalModified: {}, | |
shareKey: { | |
desc: "Cl\xE9 de partage", | |
title: "La cl\xE9 frontmatter pour publier la note sur le d\xE9p\xF4t." | |
}, | |
title: "Param\xE8tres du plugin" | |
}, | |
regexReplacing: { | |
empty: "Le remplacement peut \xEAtre vide pour supprimer l'ensemble de la cha\xEEne de caract\xE8re.", | |
forbiddenValue: "Le {{- what}} ne peut contenir le caract\xE8re : {{- forbiddenChar}}.", | |
modal: { | |
desc: 'Replace des textes dans le fichier par la valeur donn\xE9e. Vous pouvez encadrer le texte \xE0 remplacer avec "//" pour utiliser un regex.', | |
title: { | |
all: "Remplacement du nom ou du chemin du fichier", | |
only: "Remplacement du titre uniquement", | |
text: "Remplacement de texte" | |
} | |
}, | |
momentReplaceRegex: "\xC9x\xE9cuter le remplacement {{- moment}} les autres conversions (dataview, liens internes...)", | |
warningPath: 'Attention ! Utiliser le caract\xE8re "/" modifiera le chemin du fichier. Veuillez faire attention avec cette option.' | |
}, | |
upload: { | |
defaultFolder: { | |
desc: "D\xE9finir le dossier de r\xE9ception par d\xE9faut. Laisser vide pour utiliser la racine du d\xE9p\xF4t.", | |
placeholder: "docs", | |
title: "Dossier par d\xE9faut" | |
}, | |
filepathRegex: {}, | |
folderBehavior: { | |
desc: "Choisir la hierarchie des dossiers dans le d\xE9p\xF4t, en se basant sur une cl\xE9 frontmatter, un dossier fixe ou la hierarchie des dossiers dans Obsidian.", | |
fixedFolder: "Dossier fix\xE9", | |
obsidianPath: "Chemin Obsidian", | |
title: "Hierarchie des dossiers", | |
yaml: "Valeur d'une cl\xE9 frontmatter" | |
}, | |
frontmatterKey: { | |
desc: "D\xE9finir le nom de la cl\xE9 o\xF9 obtenir le dossier", | |
placeholder: "category", | |
title: "Cl\xE9 frontmatter" | |
}, | |
regexFilePathTitle: { | |
desc: 'Si le texte est entre "//", il sera interpr\xE9t\xE9 comme une expression r\xE9guli\xE8re. Sinon, il sera interpr\xE9t\xE9 comme du texte brut.', | |
title: { | |
FolderPathTitle: "\xC9diter le titre et le chemin du dossier (automatiquement)", | |
titleOnly: "\xC9diter le titre (automatiquement)" | |
} | |
}, | |
rootFolder: { | |
desc: "Ajouter ce chemin au dossier d\xE9finit par la cl\xE9 frontmatter.", | |
title: "Dossier racine" | |
}, | |
title: "Configuration du transfert", | |
useFrontmatterTitle: { | |
desc: 'Utiliser un champ du frontmatter pour g\xE9n\xE9rer le nom du fichier. Par d\xE9faut, "title" est utilis\xE9.', | |
title: "Utiliser une cl\xE9 frontmatter pour d\xE9finir le titre" | |
} | |
} | |
}; | |
var statusBar2 = { | |
counter: "{{- msg}} : {{- counter}}/{{- nb}}", | |
markedForSharing: "{{- nb}} {{- type}} \xE0 partager", | |
sharing: "\u231BPartage de {{- type}}", | |
success: "\u2705{{- action}} {{- type}}" | |
}; | |
var fr_default = { | |
commands: commands2, | |
common: common2, | |
deletion: deletion2, | |
error: error3, | |
informations: informations2, | |
modals: modals2, | |
publish: publish2, | |
regex: regex2, | |
settings: settings2, | |
statusBar: statusBar2 | |
}; | |
// plugin/i18n/i18next.ts | |
var ressources = { | |
en: { translation: en_exports }, | |
fr: { translation: fr_exports } | |
}; | |
var translationLanguage = Object.keys(ressources).find((i) => i == import_obsidian14.moment.locale()) ? import_obsidian14.moment.locale() : "en"; | |
// plugin/main.ts | |
var GithubPublisher = class extends import_obsidian15.Plugin { | |
/** | |
* Get the title field of a file | |
* @param {TFile} file - The file to get the title field from | |
* @param {FrontMatterCache} frontmatter - The frontmatter of the file | |
* @return {string} - The title field of the file | |
*/ | |
getTitleFieldForCommand(file, frontmatter) { | |
return regexOnFileName(getTitleField(frontmatter, file, this.settings), this.settings); | |
} | |
/** | |
* Create a new instance of Octokit to load a new instance of GithubBranch | |
*/ | |
reloadOctokit() { | |
let octokit; | |
const apiSettings = this.settings.github.api; | |
const githubSettings = this.settings.github; | |
if (apiSettings.tiersForApi === "Enterprise" /* entreprise */ && apiSettings.hostname.length > 0) { | |
octokit = new Octokit( | |
{ | |
baseUrl: `${apiSettings.hostname}/api/v3`, | |
auth: githubSettings.token | |
} | |
); | |
} else { | |
octokit = new Octokit({ auth: githubSettings.token }); | |
} | |
return new GithubBranch( | |
this.settings, | |
octokit, | |
this.app.vault, | |
this.app.metadataCache, | |
this | |
); | |
} | |
/** | |
* Function called when the plugin is loaded | |
* @return {Promise<void>} | |
*/ | |
onload() { | |
return __async(this, null, function* () { | |
console.log( | |
`Github Publisher v.${this.manifest.version} (lang: ${translationLanguage}) loaded` | |
); | |
instance.init({ | |
lng: translationLanguage, | |
fallbackLng: "en", | |
resources: ressources, | |
returnNull: false | |
}); | |
yield this.loadSettings(); | |
const oldSettings = this.settings; | |
yield migrateSettings(oldSettings, this); | |
const branchName = app.vault.getName().replaceAll(" ", "-").replaceAll(".", "-") + "-" + (/* @__PURE__ */ new Date()).toLocaleDateString("en-US").replace(/\//g, "-"); | |
this.addSettingTab(new GithubPublisherSettingsTab(this.app, this, branchName)); | |
this.registerEvent( | |
this.app.workspace.on("file-menu", (menu, file) => { | |
const frontmatter = file instanceof import_obsidian15.TFile ? this.app.metadataCache.getFileCache(file).frontmatter : null; | |
if (isShared(frontmatter, this.settings, file) && this.settings.plugin.fileMenu) { | |
const fileName = this.getTitleFieldForCommand(file, this.app.metadataCache.getFileCache(file).frontmatter).replace(".md", ""); | |
menu.addItem((item) => { | |
item.setSection("action"); | |
item.setTitle( | |
instance.t("commands.shareViewFiles", { viewFile: fileName }) | |
).setIcon("share").onClick(() => __async(this, null, function* () { | |
yield shareOneNote( | |
branchName, | |
this.reloadOctokit(), | |
this.settings, | |
file, | |
this.app.metadataCache, | |
this.app.vault | |
); | |
})); | |
}); | |
menu.addSeparator(); | |
} | |
}) | |
); | |
this.registerEvent( | |
this.app.workspace.on("editor-menu", (menu, editor, view) => { | |
const frontmatter = this.app.metadataCache.getFileCache(view.file).frontmatter; | |
if (isShared(frontmatter, this.settings, view.file) && this.settings.plugin.editorMenu) { | |
const fileName = this.getTitleFieldForCommand(view.file, this.app.metadataCache.getFileCache(view.file).frontmatter).replace(".md", ""); | |
menu.addSeparator(); | |
menu.addItem((item) => { | |
item.setSection("mkdocs-publisher"); | |
item.setTitle( | |
instance.t("commands.shareViewFiles", { viewFile: fileName }) | |
).setIcon("share").onClick(() => __async(this, null, function* () { | |
yield shareOneNote( | |
branchName, | |
this.reloadOctokit(), | |
this.settings, | |
view.file, | |
this.app.metadataCache, | |
this.app.vault | |
); | |
})); | |
}); | |
} | |
}) | |
); | |
if (this.settings.plugin.copyLink.addCmd) { | |
this.addCommand({ | |
id: "publisher-copy-link", | |
name: instance.t("commands.copyLink"), | |
hotkeys: [], | |
checkCallback: (checking) => { | |
const file = this.app.workspace.getActiveFile(); | |
const frontmatter = file ? this.app.metadataCache.getFileCache(file).frontmatter : null; | |
if (file && frontmatter && isShared(frontmatter, this.settings, file)) { | |
if (!checking) { | |
createLink( | |
file, | |
getRepoFrontmatter(this.settings, frontmatter), | |
this.app.metadataCache, | |
this.app.vault, | |
this.settings | |
); | |
new import_obsidian15.Notice(instance.t("settings.plugin.copyLink.command.onActivation")); | |
} | |
return true; | |
} | |
return false; | |
} | |
}); | |
} | |
this.addCommand({ | |
id: "publisher-one", | |
name: instance.t("commands.shareActiveFile"), | |
hotkeys: [], | |
checkCallback: (checking) => { | |
const file = this.app.workspace.getActiveFile(); | |
const frontmatter = file ? this.app.metadataCache.getFileCache(file).frontmatter : null; | |
if (file && frontmatter && isShared(frontmatter, this.settings, file)) { | |
if (!checking) { | |
shareOneNote( | |
branchName, | |
this.reloadOctokit(), | |
this.settings, | |
file, | |
this.app.metadataCache, | |
this.app.vault | |
); | |
} | |
return true; | |
} | |
return false; | |
} | |
}); | |
this.addCommand({ | |
id: "publisher-delete-clean", | |
name: instance.t("commands.publisherDeleteClean"), | |
hotkeys: [], | |
checkCallback: (checking) => { | |
if (this.settings.upload.autoclean.enable && this.settings.upload.behavior !== "fixed" /* fixed */) { | |
if (!checking) { | |
const publisher = this.reloadOctokit(); | |
deleteUnsharedDeletedNotes( | |
publisher, | |
this.settings, | |
publisher.octokit, | |
branchName, | |
getRepoFrontmatter(this.settings) | |
); | |
} | |
return true; | |
} | |
return false; | |
} | |
}); | |
this.addCommand({ | |
id: "publisher-publish-all", | |
name: instance.t("commands.uploadAllNotes"), | |
callback: () => __async(this, null, function* () { | |
const sharedFiles = this.reloadOctokit().getSharedFiles(); | |
const statusBarItems = this.addStatusBarItem(); | |
const publisher = this.reloadOctokit(); | |
yield shareAllMarkedNotes( | |
publisher, | |
this.settings, | |
publisher.octokit, | |
statusBarItems, | |
branchName, | |
getRepoFrontmatter(this.settings), | |
sharedFiles, | |
true, | |
this | |
); | |
}) | |
}); | |
this.addCommand({ | |
id: "publisher-upload-new", | |
name: instance.t("commands.uploadNewNotes"), | |
callback: () => __async(this, null, function* () { | |
const publisher = this.reloadOctokit(); | |
yield shareNewNote( | |
publisher, | |
publisher.octokit, | |
branchName, | |
this.app.vault, | |
this, | |
getRepoFrontmatter(this.settings) | |
); | |
}) | |
}); | |
this.addCommand({ | |
id: "publisher-upload-all-edited-new", | |
name: instance.t("commands.uploadAllNewEditedNote"), | |
callback: () => __async(this, null, function* () { | |
const publisher = this.reloadOctokit(); | |
yield shareAllEditedNotes( | |
publisher, | |
publisher.octokit, | |
branchName, | |
this.app.vault, | |
this, | |
getRepoFrontmatter(this.settings) | |
); | |
}) | |
}); | |
this.addCommand({ | |
id: "publisher-upload-edited", | |
name: instance.t("commands.uploadAllEditedNote"), | |
callback: () => __async(this, null, function* () { | |
const publisher = this.reloadOctokit(); | |
yield shareOnlyEdited( | |
publisher, | |
publisher.octokit, | |
branchName, | |
this.app.vault, | |
this, | |
getRepoFrontmatter(this.settings) | |
); | |
}) | |
}); | |
this.addCommand({ | |
id: "check-this-repo-validy", | |
name: instance.t("commands.checkValidity.title"), | |
checkCallback: (checking) => { | |
if (this.app.workspace.getActiveFile()) { | |
if (!checking) { | |
checkRepositoryValidity( | |
branchName, | |
this.reloadOctokit(), | |
this.settings, | |
this.app.workspace.getActiveFile(), | |
this.app.metadataCache | |
); | |
} | |
return true; | |
} | |
return false; | |
} | |
}); | |
}); | |
} | |
/** | |
* Called when the plugin is disabled | |
*/ | |
onunload() { | |
console.log("Github Publisher unloaded"); | |
} | |
/** | |
* Get the settings of the plugin | |
* @return {Promise<void>} | |
*/ | |
loadSettings() { | |
return __async(this, null, function* () { | |
this.settings = Object.assign( | |
{}, | |
DEFAULT_SETTINGS, | |
yield this.loadData() | |
); | |
}); | |
} | |
/** | |
* Save the settings of the plugin | |
* @return {Promise<void>} | |
*/ | |
saveSettings() { | |
return __async(this, null, function* () { | |
yield this.saveData(this.settings); | |
}); | |
} | |
}; | |
/*! Bundled license information: | |
is-plain-object/dist/is-plain-object.mjs: | |
(*! | |
* is-plain-object <https://github.com/jonschlinkert/is-plain-object> | |
* | |
* Copyright (c) 2014-2017, Jon Schlinkert. | |
* Released under the MIT License. | |
*) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment